Skip to content

types: add types to useProperties, useProperty and useSaveLocal#1265

Merged
hexqi merged 2 commits into
opentiny:developfrom
gene9831:types/use-property
Apr 21, 2025
Merged

types: add types to useProperties, useProperty and useSaveLocal#1265
hexqi merged 2 commits into
opentiny:developfrom
gene9831:types/use-property

Conversation

@gene9831
Copy link
Copy Markdown
Collaborator

@gene9831 gene9831 commented Mar 29, 2025

English | 简体中文

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)
  • Built its own designer, fully self-validated

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:

Background and solution

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

  • Refactor

    • Improved type safety and specificity across various modules, including enhanced typings for page and schema state, property management functions, and composables.
    • Updated function signatures and parameters for better static analysis and clarity.
    • Added safer property access to prevent potential runtime errors.
  • Chores

    • Extended public APIs by re-exporting additional types for easier integration and usage.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 29, 2025

Walkthrough

This update enhances type safety and public API clarity across several packages. Type annotations are added or refined in multiple TypeScript files, notably in composables and type definition files, ensuring stricter and more explicit type usage. Two package index files now re-export internal types, making them accessible from the package root. Additionally, optional chaining is introduced in one composable to prevent runtime errors when accessing potentially undefined properties. No business logic or control flow is changed; all modifications focus on type declarations, exports, and null-safety.

Changes

File(s) Change Summary
packages/canvas/DesignCanvas/src/api/types.ts Refined PageState interface: currentSchema and currentPage now have more specific object types; added currentPageId? and currentPageName? optional properties.
packages/canvas/index.ts, packages/plugins/materials/index.ts Added export statements to re-export all exports from internal type modules, extending the public API surface of each package.
packages/settings/props/src/composable/useProperties.ts Added and refined TypeScript typings for parameters, return values, and state; improved null-safety with optional chaining and default fallbacks.
packages/settings/props/src/composable/useProperty.ts Introduced interfaces and explicit type annotations for function parameters and signatures; updated function signatures for improved type safety.
packages/toolbars/generate-code/src/composable/useSaveLocal.ts Added optional chaining when accessing id and name of currentPage to prevent runtime errors if currentPage is null or undefined.

Poem

In fields of code where types now bloom,
The rabbits hop and sweep the room.
With exports clear and typings tight,
Our burrow glows with pure delight.
Optional chains guard every nest—
Type-safe carrots are the best!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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.

@gene9831 gene9831 marked this pull request as ready for review April 18, 2025 09:19
@gene9831 gene9831 added this to the v2.5.0 milestone Apr 18, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/settings/props/src/composable/useProperty.ts (1)

29-29: Good use of parameter destructuring with types.

Nice work using the underscore notation for the unused defaultValue parameter. Consider adding a comment explaining why this parameter is accepted but not used.

-const addPropertyLinks = ({ linked, propertyName, componentProperties, defaultValue: _ }: AddPropertyLinksOptions) => {
+const addPropertyLinks = ({ linked, propertyName, componentProperties, defaultValue: _ /* Received but not used */ }: AddPropertyLinksOptions) => {
packages/settings/props/src/composable/useProperties.ts (1)

157-159: Consider using optional chaining here.

For consistency with the rest of the codebase, change to optional chaining for the id property access.

  useCanvas().operateNode({
    type: 'changeProps',
-    id: properties.schema?.id || '',
+    id: properties.schema?.id ?? '',
    value: { props: newProps },
    option: { overwrite: true }
  })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f3ed925 and 0880e3f.

📒 Files selected for processing (6)
  • packages/canvas/DesignCanvas/src/api/types.ts (1 hunks)
  • packages/canvas/index.ts (1 hunks)
  • packages/plugins/materials/index.ts (1 hunks)
  • packages/settings/props/src/composable/useProperties.ts (6 hunks)
  • packages/settings/props/src/composable/useProperty.ts (4 hunks)
  • packages/toolbars/generate-code/src/composable/useSaveLocal.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/toolbars/generate-code/src/composable/useSaveLocal.ts (1)
packages/canvas/render/src/canvas-function/page-switcher.ts (1)
  • currentPage (9-13)
🪛 GitHub Actions: Push And Create PR Check
packages/plugins/materials/index.ts

[error] 1-1: Build failed: Could not resolve "./src/composable/types" from "index.ts".

🪛 Biome (1.9.4)
packages/settings/props/src/composable/useProperties.ts

[error] 159-160: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (25)
packages/canvas/index.ts (1)

33-33: Good addition of type exports

This export statement makes the types defined in ./DesignCanvas/src/api/types directly accessible to consumers of this package, which improves the developer experience and type-safety of the API.

packages/toolbars/generate-code/src/composable/useSaveLocal.ts (2)

22-23: Good use of optional chaining for type safety

The addition of optional chaining (?.) when accessing pageState.currentPage.id and pageState.currentPage.name aligns with the updated type definition in PageState where currentPage can be null. This prevents potential runtime errors.


55-56: Good use of optional chaining for null safety

Similar to the previous instance, adding optional chaining here protects against null reference errors when currentPage is null or undefined. This is a good defensive programming practice.

packages/canvas/DesignCanvas/src/api/types.ts (2)

7-7: Improved type specificity for currentSchema

Changing currentSchema from a generic unknown type to a more specific object type with a required id property improves type safety and makes the code more self-documenting.


9-11: Enhanced types with nullable currentPage and added optional fields

The changes to currentPage type and addition of currentPageId and currentPageName properties:

  1. Make currentPage explicitly nullable, which is aligned with the optional chaining used elsewhere
  2. Add specific optional properties to access page ID and name directly
  3. Improve overall type safety and developer experience

This aligns well with the changes in useSaveLocal.ts where these properties are accessed with optional chaining.

packages/settings/props/src/composable/useProperty.ts (7)

16-17: Good addition of type imports.

The added imports for PageState, Property, and Linked types provide the foundation for the TypeScript enhancements in this file.


21-26: Well-defined interface for addPropertyLinks options.

Good practice defining a clear interface for the options object. The defaultValue parameter is marked as unknown, which is appropriate for a value that could be of any type.


53-57: Clear interface definition for findLinked options.

The FindLinkedOptions interface clearly defines the structure for the options passed to findLinked. The blockProperties type uses a complex but precise type definition with Property['content'][number][].


60-62: Well-refactored function signature with proper typing.

Good job consolidating parameters into a single options object with proper typing. This improves readability and type safety.


78-78: Added proper type annotation to resetLink function.

The explicit typing of the properties parameter as Property[] enhances type safety.


90-90: Good type annotation for getProperty function.

The function parameter is properly typed with destructured object pattern and PageState type.


95-95: Appropriate use of type assertions.

The type assertions to Property[] are necessary here to ensure type compatibility with the functions being called.

Also applies to: 99-102

packages/settings/props/src/composable/useProperties.ts (13)

16-16: Good addition of type imports.

The added imports for Property and Schema types provide the foundation for the TypeScript enhancements in this file.


21-21: Enhanced type safety for getSlotSwitch.

The function parameters now have proper type annotations with appropriate defaults.


56-56: Improved type safety for mergeProps.

The function parameters now have proper type annotations with appropriate defaults.


75-75: Added type annotation to translateProp.

The value parameter is properly typed as an object with a type property.


88-91: Well-typed reactive state.

The shallowReactive properties object now has proper type annotations with nullable Schema types, which enables better type checking throughout the codebase.


93-94: Added type safety to isPageOrBlock.

The function parameter is now properly typed, and optional chaining is used for safe property access.


96-96: Enhanced type safety for getProps.

Both parameters are properly typed as Schema objects.


119-119: Added type annotations to setProp.

The parameters now have proper type annotations, with value as unknown to accommodate different types.


139-139: Improved null safety with fallback empty string.

Good practice to provide a fallback empty string for the id property when it might be undefined.


147-148: Enhanced null safety in getProp.

The function now uses optional chaining and nullish coalescing to safely access potentially undefined properties.


151-152: Added null safety to delProp.

Optional chaining is used to safely access the props object.


165-167: Added type safety to setProps.

The schema parameter is now properly typed as a Schema object.


169-171: Enhanced type safety for getSchema.

The parent parameter is now properly typed as a boolean.

Comment thread packages/plugins/materials/index.ts
@hexqi hexqi merged commit 53e3296 into opentiny:develop Apr 21, 2025
1 check passed
@gene9831 gene9831 deleted the types/use-property branch May 7, 2025 01:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants