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

fix(form): modify mobile form problem #2643

Merged
merged 4 commits into from
Dec 16, 2024
Merged

fix(form): modify mobile form problem #2643

merged 4 commits into from
Dec 16, 2024

Conversation

James-9696
Copy link
Collaborator

@James-9696 James-9696 commented Dec 12, 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

Release Notes

  • New Features
    • Introduced a new title property for input components, enhancing configuration options.
  • Bug Fixes
    • Improved error handling and rendering logic for mobile form items.
  • Style
    • Updated styling rules for form items, including fixed line-height values and new color variables for labels and error messages.
    • Simplified margin settings for inline form items by removing variable dependencies.
  • Documentation
    • Enhanced API documentation for input component methods to reflect new return types.

@github-actions github-actions bot added the bug Something isn't working label Dec 12, 2024
Copy link

[e2e-test-warn]
The component to be tested is missing.

The title of the Pull request should look like "fix(vue-renderless): [action-menu, alert] fix xxx bug".

Please make sure you've read our contributing guide

Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The changes in this pull request focus on enhancing the handling of the form state and rendering logic within mobile components. Key modifications include the transition from state.form to formInstance across various components, which streamlines state management. The rendering logic has been simplified, particularly for mobile scenarios, by removing unnecessary conditionals and ensuring consistent rendering of labels and error messages. Additionally, CSS updates have been made to improve styling and reduce reliance on CSS variables. These changes aim to improve maintainability and clarity in the codebase.

Changes

File Path Change Summary
packages/mobile/components/form-item/src/mobile.vue Replaced state.form with formInstance for properties; hardcoded isMobile to true; simplified getFormItemContent function; adjusted error message rendering logic; refined rendering of LabelContent.
packages/mobile/components/form-item/src/renderless/index.ts Replaced state.form with state.formInstance in computed properties and methods; removed computedForm method; standardized error handling and validation logic to use formInstance.
packages/mobile/components/form-item/src/renderless/vue.ts Removed computedForm from initState and initApi, updated access to hideRequiredAsterisk and tooltipType using optional chaining.
packages/mobile/components/form/src/renderless/vue.ts Changed the argument in the provide function for the 'form' key from parent to vm.
packages/mobile/components/input/src/input.ts Added title property to inputProps; retained textareaTitle; updated IInputApi to include return types for utility functions.
packages/theme-mobile/src/form-item/index.less Removed CSS variable references for line-height; updated line-height values to fixed pixels; modified color properties for labels and error messages to new variable names.
packages/theme-mobile/src/form-item/vars.less Removed several CSS custom properties related to form item styling; added new properties for label and error colors.
packages/theme-mobile/src/form/index.less Adjusted margin-right in &--inline class from a variable to a fixed value of 10px.

Possibly related PRs

  • fix(form): [form] fix form tooltip class name #2154: This PR addresses issues related to tooltip class names within form components, which is relevant to the changes made in the main PR regarding error message rendering and visibility logic using formInstance.
  • fix(modal): [modal] modify design style #2389: This PR modifies design styles for modal components, which may indirectly relate to the overall UI consistency and rendering logic improvements seen in the main PR's changes to the mobile.vue component.

Suggested reviewers

  • zzcr

🐰 In the meadow where bunnies play,
A form's new look is here today!
With labels bright and messages clear,
Our mobile forms now bring good cheer!
So hop along, let’s celebrate,
For change is good, let’s elevate! 🌼


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. (Experiment)
  • @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

🧹 Outside diff range and nitpick comments (9)
packages/mobile/components/input/src/input.ts (1)

128-131: Add unit tests for the new title property

The new title property adds functionality that should be tested to ensure it behaves as expected.

Would you like assistance in creating unit tests for the title property?

packages/mobile/components/form-item/src/renderless/index.ts (4)

124-137: Consider adding type guards for better type safety.

While the refactoring to formInstance is correct, consider adding type guards to handle potential undefined values more explicitly.

-    if (state.formInstance.labelPosition === POSITION.Top || state.formInstance.inline) {
+    if (!state.formInstance?.labelPosition) return result
+    if (state.formInstance.labelPosition === POSITION.Top || state.formInstance.inline) {

Line range hint 214-320: Add explicit error handling for invalid model paths.

While the path handling logic is correct, consider adding explicit error handling for cases where the model path is invalid.

   const model = state.formInstance?.model

   if (!model || !props.prop) {
+    console.warn('[Form-Item] Invalid model or prop')
     return
   }

Line range hint 489-506: Add JSDoc and type safety improvements for tooltip handling.

While the tooltip functionality is correct, consider adding proper JSDoc documentation and type safety improvements.

+/**
+ * Handles mouse enter events for form items
+ * @param {MouseEvent} e - The mouse event
+ */
 export const handleMouseenter =
   ({ state }: Pick<IFormItemRenderlessParams, 'state'>) =>
   (e): void => {
-    if (!state.isDisplayOnly || !state.typeName || !state.formInstance) return
+    if (!state.isDisplayOnly || !state.typeName || !state.formInstance?.showTooltip) return
🧰 Tools
🪛 Biome (1.9.4)

[error] 487-488: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)


513-521: LGTM! Consider strengthening null checks.

The tooltip functionality for labels is properly implemented. Consider adding stronger null checks for better reliability.

-    if (!state.formInstance?.overflowTitle || !state.formInstance || slots.label) return
+    if (!state.formInstance?.overflowTitle || !state.formInstance?.showTooltip || slots.label) return
packages/theme-mobile/src/form-item/vars.less (1)

2-3: Consider adding fallback values for CSS variables

While the new mobile-specific color variables improve separation of concerns, consider adding fallback values to ensure graceful degradation:

- --ti-mobile-form-item-label-color: #333;
- --ti-mobile-form-item-error-color: #f5222d;
+ --ti-mobile-form-item-label-color: var(--ti-common-color-text-primary, #333);
+ --ti-mobile-form-item-error-color: var(--ti-common-color-error, #f5222d);
packages/theme-mobile/src/form/index.less (1)

55-55: Consider responsive margins for different screen sizes

The fixed margin-right value of 10px might not scale well across different screen sizes. Consider using relative units or media queries for better responsiveness.

- margin-right: 10px;
+ margin-right: clamp(8px, 2vw, 16px);
packages/theme-mobile/src/form-item/index.less (2)

41-41: Consider using relative units for line heights

Fixed pixel values for line heights might not scale well with different font sizes or screen densities. Consider using relative units for better accessibility and responsiveness.

- line-height: 36px;
+ line-height: 2.25; /* 36px ÷ 16px */

- line-height: 28px;
+ line-height: 1.75; /* 28px ÷ 16px */

- line-height: 24px;
+ line-height: 1.5; /* 24px ÷ 16px */

Also applies to: 46-46, 55-55


93-93: Consider using relative font size

Fixed pixel values for font sizes might affect readability across different devices and user preferences.

- font-size: 14px;
+ font-size: 0.875rem; /* 14px ÷ 16px */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 708f026 and 6212bfb.

📒 Files selected for processing (8)
  • packages/mobile/components/form-item/src/mobile.vue (7 hunks)
  • packages/mobile/components/form-item/src/renderless/index.ts (8 hunks)
  • packages/mobile/components/form-item/src/renderless/vue.ts (2 hunks)
  • packages/mobile/components/form/src/renderless/vue.ts (1 hunks)
  • packages/mobile/components/input/src/input.ts (2 hunks)
  • packages/theme-mobile/src/form-item/index.less (8 hunks)
  • packages/theme-mobile/src/form-item/vars.less (1 hunks)
  • packages/theme-mobile/src/form/index.less (1 hunks)
🔇 Additional comments (10)
packages/mobile/components/form-item/src/mobile.vue (3)

13-13: Approved change to import statement

The import statement correctly includes the necessary modules.


53-53: Confirm hardcoding isMobile to true

Hardcoding isMobile to true may prevent this component from adapting to non-mobile contexts. Ensure this change is intentional and won't affect any conditional logic based on isMobile.


167-167: Ensure label suffix handles undefined formInstance

When appending state.formInstance?.labelSuffix, confirm that labelSuffix is correctly defined or provide a default value to prevent potential issues.

packages/mobile/components/form/src/renderless/vue.ts (1)

111-111: Verify impact of changing provide('form', vm)

Changing the provided value from parent to vm may affect components that inject form. Ensure all dependent components expect vm as the form instance.

packages/mobile/components/input/src/input.ts (1)

16-30: Approved re-import of utility functions

Re-importing utility functions ensures all necessary methods are available for the input component.

packages/mobile/components/form-item/src/renderless/vue.ts (1)

111-111: Approved use of optional chaining for safer property access

Using optional chaining with state.formInstance enhances robustness by preventing runtime errors when formInstance may be undefined.

Also applies to: 121-121

packages/mobile/components/form-item/src/renderless/index.ts (3)

100-105: LGTM! Width calculation logic is preserved.

The transition to formInstance maintains the same width calculation logic while improving consistency.


354-354: LGTM! Rules access properly updated.

The transition to formInstance for rules access is consistent with the overall refactoring pattern.


82-86: LGTM! Verify formInstance references.

The refactoring from form to formInstance is consistent. The logic remains unchanged and proper optional chaining is maintained.

✅ Verification successful

Consistent usage of formInstance property confirmed

The codebase scan shows that formInstance is consistently used across the form-item component files, replacing the previous form references. The changes in the reviewed code segment align with this pattern, showing proper optional chaining and maintaining the same logical structure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify consistent usage of formInstance across the codebase
rg -g '*.{vue,ts,js}' "formInstance\." packages/mobile/components/form-item/

Length of output: 3412

packages/theme-mobile/src/form-item/index.less (1)

76-76: Verify color contrast ratios for accessibility

The new color variables are being used consistently across different states. However, ensure that the chosen colors meet WCAG contrast requirements for accessibility.

Also applies to: 121-121, 142-142, 152-152, 163-163, 169-169

@@ -294,9 +208,9 @@ export default defineComponent({
style: !isMobile && state.contentStyle
},
[
isMobile ? LabelContent : null,
LabelContent,
FormItemContnet,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in FormItemContnet variable name

The variable FormItemContnet appears to be misspelled. It should likely be FormItemContent.

-                FormItemContnet,
+                FormItemContent,
📝 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
FormItemContnet,
FormItemContent,

)
]
)
const validatePosition = this.validatePosition || state.formInstance.validatePosition || 'right'
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add optional chaining to formInstance.validatePosition

To avoid runtime errors if formInstance is undefined, use optional chaining when accessing validatePosition.

-          const validatePosition = this.validatePosition || state.formInstance.validatePosition || 'right'
+          const validatePosition = this.validatePosition || state.formInstance?.validatePosition || 'right'
📝 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 validatePosition = this.validatePosition || state.formInstance.validatePosition || 'right'
const validatePosition = this.validatePosition || state.formInstance?.validatePosition || 'right'

const classPrefix = isMobile ? 'tiny-mobile-' : 'tiny-'
const labelSlot = slots.label ? slots.label() : null
const defaultSlots = slots.default ? slots.default() : null
const errorSlot = scopedSlots.error && scopedSlots.error(state.validateMessage)
const formItemClass = `${classPrefix}form-item--${state.sizeClass ? state.sizeClass : 'default'}`
const isShowError = state.validateState === 'error' && showMessage && state.form.showMessage
const isShowError = state.validateState === 'error' && showMessage && formInstance.showMessage
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 optional chaining with formInstance.showMessage

Accessing formInstance.showMessage without checking if formInstance is defined may lead to runtime errors. Consider using optional chaining to prevent potential issues.

-    const isShowError = state.validateState === 'error' && showMessage && formInstance.showMessage
+    const isShowError = state.validateState === 'error' && showMessage && formInstance?.showMessage
📝 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 isShowError = state.validateState === 'error' && showMessage && formInstance.showMessage
const isShowError = state.validateState === 'error' && showMessage && formInstance?.showMessage

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

🧹 Outside diff range and nitpick comments (7)
packages/theme-mobile/src/form/index.less (1)

55-55: Consider maintaining customization capability

The change from var(--ti-form-item-margin-right, 10px) to a fixed 10px aligns with other CSS variable removals, but:

  1. Reduces customization flexibility
  2. May impact responsive designs where different spacings are needed

Consider keeping the variable with a default value:

-      margin-right: 10px;
+      margin-right: var(--ti-mobile-form-item-margin-right, 10px);
packages/mobile/components/form/src/renderless/vue.ts (1)

Line range hint 1-111: Consider documenting the mobile form architecture changes

The changes across these files show a coordinated effort to:

  1. Simplify mobile form styling by removing CSS variables
  2. Change form context management
  3. Fix mobile-specific form issues

However, there are some architectural considerations:

  1. Document the rationale behind removing CSS variables and impact on customization
  2. Add tests for the new form context propagation
  3. Update component documentation to reflect these changes

Consider creating an architecture decision record (ADR) to document:

  1. The motivation behind these changes
  2. The trade-offs considered
  3. The impact on customization and maintainability
packages/theme-mobile/src/form-item/index.less (2)

41-41: Consider using relative units for line heights

While the fixed pixel values (36px, 28px, 24px) work for most cases, using relative units (like rem or em) would better support accessibility and different screen densities.

-    line-height: 36px;
+    line-height: 2.25rem; /* 36px at 16px base */

-    line-height: 28px;
+    line-height: 1.75rem; /* 28px at 16px base */

-    line-height: 24px;
+    line-height: 1.5rem;  /* 24px at 16px base */

Also applies to: 46-46, 55-55


93-93: Consider using a CSS variable for font size

Hardcoding the font size to 14px reduces flexibility. Consider using a CSS variable to maintain consistency and support theming.

-    font-size: 14px;
+    font-size: var(--ti-mobile-form-item-content-font-size, 14px);
packages/mobile/components/form-item/src/mobile.vue (1)

167-167: Handle undefined labelSuffix gracefully

The optional chaining is good, but consider providing a default value for undefined cases.

-              labelSlot || label + (state.formInstance?.labelSuffix || '')
+              labelSlot || label + (state.formInstance?.labelSuffix ?? '')
packages/mobile/components/form-item/src/renderless/index.ts (2)

Line range hint 489-521: Add consistent optional chaining across tooltip-related methods.

Several formInstance accesses lack optional chaining, which could cause runtime errors. Also, the null checks could be simplified.

Apply these improvements:

-if (!state.isDisplayOnly || !state.typeName || !state.formInstance) return
+if (!state.isDisplayOnly || !state.typeName || !state.formInstance?.showTooltip) return

-state.formInstance.showTooltip(dom, state.displayedValue)
+state.formInstance?.showTooltip(dom, state.displayedValue)

-if (!state.formInstance?.overflowTitle || !state.formInstance || slots.label) return
+if (!state.formInstance?.overflowTitle || slots.label) return

-state.formInstance.showTooltip(label, props.label + state.formInstance.labelSuffix)
+state.formInstance?.showTooltip(label, props.label + state.formInstance?.labelSuffix)

-state.formInstance && state.formInstance.hideTooltip()
+state.formInstance?.hideTooltip()

Line range hint 1-549: Add unit tests for the formInstance migration.

The PR objectives indicate that tests haven't been added. Given the significant changes in form instance handling and the addition of null safety checks, it's important to add unit tests to verify the behavior, especially for edge cases where formInstance might be null.

Would you like me to help generate unit tests for these changes?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 708f026 and 6212bfb.

📒 Files selected for processing (8)
  • packages/mobile/components/form-item/src/mobile.vue (7 hunks)
  • packages/mobile/components/form-item/src/renderless/index.ts (8 hunks)
  • packages/mobile/components/form-item/src/renderless/vue.ts (2 hunks)
  • packages/mobile/components/form/src/renderless/vue.ts (1 hunks)
  • packages/mobile/components/input/src/input.ts (2 hunks)
  • packages/theme-mobile/src/form-item/index.less (8 hunks)
  • packages/theme-mobile/src/form-item/vars.less (1 hunks)
  • packages/theme-mobile/src/form/index.less (1 hunks)
🔇 Additional comments (11)
packages/mobile/components/input/src/input.ts (3)

16-29: LGTM! Well-organized type imports.

The consolidation of renderless function types into a single import block improves code organization and maintainability.


Line range hint 207-219: LGTM! Comprehensive type definitions.

The IInputApi interface properly maps all imported function types, ensuring type safety and maintainability.


128-131: Clarify the relationship between title-related props.

The component now has three title-related props:

  • title (new)
  • textareaTitle
  • showTitle

This might cause confusion for developers. Consider:

  1. Adding JSDoc comments to clarify the purpose of each title prop
  2. Updating component documentation
  3. Verifying the template implementation
packages/theme-mobile/src/form-item/vars.less (1)

2-3: Document the migration of removed CSS variables

While the new mobile-specific color variables are good additions, the removal of several CSS variables (line-height and font-size) should be documented to help other developers understand:

  1. Where the fixed values are now defined
  2. Why the variables were removed
  3. Impact on customization capabilities

Let's check for any remaining references to the removed variables:

✅ Verification successful

No references found to removed CSS variables - safe to proceed

The verification shows that there are no remaining references to the removed CSS variables in either Less files or Vue components. This indicates that the removal of these variables is safe and won't cause any broken references in the codebase. While documentation would be helpful for future reference, it's not critical since the variables are completely unused.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to removed variables
rg --type=less --type=vue \
  "ti-form-item-(small|medium|mini)-line-height|ti-form-item-label-(line-height|font-size)|ti-form-item-error-font-size"

Length of output: 174


Script:

#!/bin/bash
# Search for any remaining references to removed variables, fixing the file type issue
rg --type=less \
  "ti-form-item-(small|medium|mini)-line-height|ti-form-item-label-(line-height|font-size)|ti-form-item-error-font-size"

# Also search in .vue files separately
find . -name "*.vue" -type f -exec grep -l \
  "ti-form-item-\(small\|medium\|mini\)-line-height\|ti-form-item-label-\(line-height\|font-size\)\|ti-form-item-error-font-size" \
  {} \;

Length of output: 317

packages/mobile/components/form/src/renderless/vue.ts (1)

111-111: ⚠️ Potential issue

Verify form context propagation

The change from parent to vm as the provided form context is significant and could affect child components' behavior. This change:

  1. May fix the mobile form issue mentioned in the PR
  2. Could impact form validation and state management

Let's verify the form context usage in child components:

Please add tests to verify:

  1. Form validation still works correctly
  2. Child components can access form methods
  3. No regression in form functionality

Would you like me to help create test cases for these scenarios?

✅ Verification successful

Form context change appears safe and well-integrated

The codebase analysis shows that the form context change is consistent with the existing pattern across components:

  • Form-items correctly inject and use the form context (packages/mobile/components/form-item/src/renderless/vue.ts)
  • Multiple form-related components (input, checkbox, radio, etc.) follow a consistent pattern of injecting the form context with a null fallback
  • The form context is used similarly in both mobile and desktop components
  • Components handle form context appropriately for validation and state management
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components that inject and use the form context
ast-grep --pattern 'inject($_, "form")' 

# Search for potential form context usage
rg -A 3 'inject.*form'

Length of output: 11426

packages/theme-mobile/src/form-item/index.less (1)

76-76: LGTM! Good separation of mobile-specific styling

The consistent transition from ti-form-item to ti-mobile-form-item CSS variables improves the separation of concerns between mobile and desktop styles.

Also applies to: 121-121, 142-142, 152-152, 163-163, 169-169

packages/mobile/components/form-item/src/renderless/vue.ts (1)

111-111: LGTM! Improved null safety with optional chaining

The addition of optional chaining for accessing formInstance.state properties prevents potential runtime errors.

Also applies to: 121-121

packages/mobile/components/form-item/src/mobile.vue (1)

211-213: Consider adding error boundaries

The template renders multiple elements without error boundaries. Consider wrapping critical sections with error handling.

Also applies to: 222-222

packages/mobile/components/form-item/src/renderless/index.ts (3)

100-105: LGTM! Consistent property access pattern.

The changes maintain consistency with the formInstance migration pattern while adding null safety.


214-214: LGTM! Proper null safety added.

The optional chaining operator provides appropriate null safety for model access.


354-354: LGTM! Proper null safety added.

The optional chaining operator provides appropriate null safety for rules access.

@@ -10,7 +10,7 @@
*
-->
<script lang="tsx">
import { $prefix, setup, parseVnode, h, defineComponent, isVue2, hooks } from '../../../vue-common'
import { $prefix, setup, parseVnode, h, defineComponent, isVue2 } from '../../../vue-common'
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Tests needed for this bugfix

According to the PR objectives, this is a bugfix but no tests have been added. Please add tests to verify the form behavior on mobile devices, especially around:

  • Validation message positioning
  • Label suffix rendering
  • Error state handling

Would you like me to help generate test cases for these scenarios?

Comment on lines +107 to +114
const validatePosition = this.validatePosition || state.formInstance.validatePosition || 'right'
validateMessage = state.validateMessage ? (
validatePosition === 'right' ? (
<div class="tiny-mobile-input-form__error align-right">{state.validateMessage}</div>
) : (
<div class="tiny-mobile-input-form__error align-left">{state.validateMessage}</div>
)
) : null
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for position value

The validation position logic should handle invalid position values gracefully.

-      const validatePosition = this.validatePosition || state.formInstance.validatePosition || 'right'
+      const validPositions = ['right', 'left']
+      const requestedPosition = this.validatePosition || state.formInstance.validatePosition || 'right'
+      const validatePosition = validPositions.includes(requestedPosition) ? requestedPosition : 'right'
📝 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 validatePosition = this.validatePosition || state.formInstance.validatePosition || 'right'
validateMessage = state.validateMessage ? (
validatePosition === 'right' ? (
<div class="tiny-mobile-input-form__error align-right">{state.validateMessage}</div>
) : (
<div class="tiny-mobile-input-form__error align-left">{state.validateMessage}</div>
)
) : null
const validPositions = ['right', 'left']
const requestedPosition = this.validatePosition || state.formInstance.validatePosition || 'right'
const validatePosition = validPositions.includes(requestedPosition) ? requestedPosition : 'right'
validateMessage = state.validateMessage ? (
validatePosition === 'right' ? (
<div class="tiny-mobile-input-form__error align-right">{state.validateMessage}</div>
) : (
<div class="tiny-mobile-input-form__error align-left">{state.validateMessage}</div>
)
) : null

const { validateIcon, isErrorInline, isErrorBlock, tooltipType } = state
const isMobile = state.mode === 'mobile'
const { validateIcon, isErrorInline, isErrorBlock, formInstance } = state
const isMobile = true
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 making mobile mode configurable

Hardcoding isMobile = true reduces component reusability. Consider making this configurable through props or environment settings.

-    const isMobile = true
+    const isMobile = props.forceMobile ?? state.mode === 'mobile'

Committable suggestion skipped: line range outside the PR's diff.

@@ -338,7 +317,7 @@ export const resetField =
state.validateState = ''
state.validateMessage = ''

let model = state.form.model || {}
let model = state.formInstance.model || {}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add optional chaining to prevent potential runtime errors.

The formInstance access lacks optional chaining, which could cause runtime errors if formInstance is null.

Apply this diff to add null safety:

-let model = state.formInstance.model || {}
+let model = state.formInstance?.model || {}
📝 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
let model = state.formInstance.model || {}
let model = state.formInstance?.model || {}

Comment on lines +124 to +137
if (state.formInstance.labelPosition === POSITION.Top || state.formInstance.inline) {
return result
}

if (!label && !props.labelWidth && state.isNested) {
return result
}

const labelWidth = props.labelWidth || state.form.state.labelWidth
const labelWidth = props.labelWidth || state.formInstance.state.labelWidth

if (labelWidth === 'auto') {
if (props.labelWidth === 'auto') {
result.marginLeft = state.computedLabelWidth
} else if (state.form.state.labelWidth === 'auto') {
} else if (state.formInstance.state.labelWidth === 'auto') {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add optional chaining to prevent potential runtime errors.

The formInstance access on line 124 lacks optional chaining, which could cause runtime errors if formInstance is null.

Apply this diff to add null safety:

-if (state.formInstance.labelPosition === POSITION.Top || state.formInstance.inline) {
+if (state.formInstance?.labelPosition === POSITION.Top || state.formInstance?.inline) {
📝 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 (state.formInstance.labelPosition === POSITION.Top || state.formInstance.inline) {
return result
}
if (!label && !props.labelWidth && state.isNested) {
return result
}
const labelWidth = props.labelWidth || state.form.state.labelWidth
const labelWidth = props.labelWidth || state.formInstance.state.labelWidth
if (labelWidth === 'auto') {
if (props.labelWidth === 'auto') {
result.marginLeft = state.computedLabelWidth
} else if (state.form.state.labelWidth === 'auto') {
} else if (state.formInstance.state.labelWidth === 'auto') {
if (state.formInstance?.labelPosition === POSITION.Top || state.formInstance?.inline) {
return result
}
if (!label && !props.labelWidth && state.isNested) {
return result
}
const labelWidth = props.labelWidth || state.formInstance.state.labelWidth
if (labelWidth === 'auto') {
if (props.labelWidth === 'auto') {
result.marginLeft = state.computedLabelWidth
} else if (state.formInstance.state.labelWidth === 'auto') {

Comment on lines +82 to +86
if (state.formInstance?.labelPosition === POSITION.Top) {
return result
}

const labelWidth = props.labelWidth || state.form.state.labelWidth
const labelWidth = props.labelWidth || state.formInstance?.state?.labelWidth
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Migration from state.form to state.formInstance needs attention

The verification reveals inconsistency in the codebase:

  • packages/renderless/src/form-item/index.ts still uses the old state.form pattern
  • packages/mobile/components/form-item/src/renderless/index.ts has been updated to use state.formInstance

This suggests an incomplete migration where the renderless package hasn't been updated to match the mobile package's changes. The changes need to be synchronized across both packages to maintain consistency.

  • packages/renderless/src/form-item/index.ts: Needs to be updated to use state.formInstance pattern
  • packages/mobile/components/form-item/src/renderless/index.ts: Changes are correct but depend on the renderless package
🔗 Analysis chain

LGTM! Verify form instance property access.

The optional chaining operators improve null safety when accessing formInstance properties.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify formInstance property access patterns across the codebase
# Look for any remaining instances of state.form that might have been missed

rg "state\.form\." --type ts

Length of output: 1444


Script:

#!/bin/bash
# Let's check if there are any other files in the codebase that use formInstance
rg "formInstance" --type ts -A 2

Length of output: 13525

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants