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: return urlState as normal type, not readonly #23

Conversation

asmyshlyaev177
Copy link
Owner

@asmyshlyaev177 asmyshlyaev177 commented Nov 9, 2024

return urlState as normal type, not readonly

fix #22

PR title

Proposed Changes

Breaking Changes

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced documentation for the state-in-url library, detailing capabilities like server-side rendering and framework flexibility.
    • Updated examples and best practices for using the useUrlState and useSharedState hooks.
  • Bug Fixes

    • Corrected handling of the urlState object to comply with TypeScript's readonly constraints in various form components.
  • Documentation

    • Improved clarity and structure of the README files for useUrlState, useSharedState, and other components, emphasizing state mutability and usage examples.
  • Chores

    • Removed unnecessary types to streamline code and improve clarity across various hooks and utilities.
    • Added a new script for managing GitHub dependencies in the project.

return `urlState` as normal type, not `readonly`
Copy link

coderabbitai bot commented Nov 9, 2024

Walkthrough

The pull request includes extensive updates to the documentation and functionality of the state-in-url library. Key changes involve enhancing the README.md files for various components, clarifying installation instructions, and providing detailed usage examples. Additionally, modifications to the Form components across multiple packages correct TypeScript errors related to readonly properties of the urlState object. The useUrlState and useSharedState hooks have been updated to remove the DeepReadonly type, allowing for mutable state management. Overall, these changes aim to improve clarity and usability while maintaining functionality.

Changes

File Path Change Summary
README.md (various packages) Enhanced documentation with detailed descriptions, installation instructions, and usage examples.
packages/example-nextjs14/src/app/Form-for-test.tsx Removed direct modifications to readonly properties of urlState, retaining state management logic.
packages/example-nextjs15/src/app/Form-for-test.tsx Similar changes as above, focusing on correcting readonly property handling in urlState.
packages/example-react-router6/src/Form-for-test.tsx Adjusted to comply with readonly constraints of urlState, maintaining overall functionality.
packages/urlstate/next/useUrlState/README.md Updated to clarify urlState mutability and refined parameters section for better understanding.
packages/urlstate/next/useUrlState/useUrlState.ts Removed DeepReadonly type, updated function signature to enhance flexibility, clarified internal logic.
packages/urlstate/react-router/useUrlState/README.md Clarified urlState mutability, expanded parameters section for consistency with useNavigate.
packages/urlstate/react-router/useUrlState/useUrlState.ts Similar updates as above, enhancing mutability and simplifying type handling.
packages/urlstate/useSharedState/README.md Updated to clarify return types and parameters, removing readonly qualifiers.
packages/urlstate/useSharedState/useSharedState.ts Simplified setState parameter type by removing DeepReadonly, maintaining core functionality.
packages/urlstate/useUrlStateBase/README.md Clarified return type description for state, removing readonly designation.
packages/urlstate/useUrlStateBase/useUrlStateBase.ts Removed DeepReadonly type, refined URL update handling, and maintained event listener management.
packages/urlstate/utils.ts Removed DeepReadonly<T> type definition, retaining other utility functions and type definitions.
package.json Added new script "pin-gh-deps" and new dependency "pin-github-action": "^1.9.1" in devDependencies.

Assessment against linked issues

Objective Addressed Explanation
Argument of type 'readonly string[]' is not assignable to parameter of type 'string[]'. (#22)

Possibly related PRs

  • docs: Update README.md #20: The changes in this PR also involve updates to the README.md file, although they focus on adding badges and minor formatting adjustments rather than content related to the state-in-url library's functionality.

🐰 In the garden, we hop and play,
With state and URLs, we find our way.
Documentation shines, clear as can be,
Type safety’s here, oh what glee!
No more readonly, mutable delight,
Hopping through code, everything feels right! 🌼


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

codacy-production bot commented Nov 9, 2024

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
+0.00% (target: -1.00%) 100.00%
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (b2f5bc3) 196 192 97.96%
Head commit (a26617e) 196 (+0) 192 (+0) 97.96% (+0.00%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#23) 1 1 100.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

Codacy stopped sending the deprecated coverage status on June 5th, 2024. Learn more

@asmyshlyaev177 asmyshlyaev177 self-assigned this Nov 9, 2024
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: 0

🧹 Outside diff range and nitpick comments (5)
packages/urlstate/useSharedState/README.md (1)

46-46: Enhance parameter type documentation.

The type definition has been simplified, but it could be more explicit about partial updates.

Consider expanding the documentation:

-value: T | ((currState: T) => T) - New state value or a function that receives the current state and returns the new state.
+value: T | Partial<T> | ((currState: T) => T) - New state value (full or partial) or a function that receives the current state and returns the new state.

This better reflects the type shown in the Returns section above (line 20: setState: T | Partial<T> | (T) => void).

packages/urlstate/next/useUrlState/README.md (1)

Line range hint 1-67: Consider enhancing the documentation with type information

While the documentation is comprehensive, it could benefit from explicitly showing the TypeScript types for the returned state and functions. This would make it clearer to users how to properly type their implementations.

Consider adding type information like this:

interface UrlStateResult<T> {
  urlState: T;
  setState: (value: T | Partial<T> | ((curr: T) => T)) => void;
  setUrl: (value: T | Partial<T> | ((curr: T) => T), options?: { replace?: boolean; scroll?: boolean }) => void;
}
🧰 Tools
🪛 Markdownlint

16-16: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)

packages/urlstate/react-router/useUrlState/README.md (1)

Line range hint 1-67: Consider adding mutation examples to clarify new behavior.

While the documentation is comprehensive, it would be helpful to add examples demonstrating direct state mutations now that urlState is no longer readonly. This would help users understand the practical implications of this change.

Consider adding an example like:

// Example of direct state mutation (now possible)
const { urlState, setUrl } = useUrlState({ count: 0 });
urlState.count++; // This is now valid
setUrl(urlState); // Update URL with modified state
🧰 Tools
🪛 Markdownlint

16-16: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)

packages/urlstate/next/useUrlState/useUrlState.ts (1)

117-117: Changes align with PR objective but warrant documentation updates.

The removal of readonly constraints from urlState and state successfully implements the PR objective. However, consider the following recommendations:

  1. Update the JSDoc comments to explicitly document that the state is now mutable
  2. Add a warning about avoiding direct mutations of the state object

Add the following JSDoc comment above the urlState property:

+    /**
+     * The current state object. While mutable, direct mutations should be avoided.
+     * Use setState/setUrl for updates to ensure proper state management.
+     */
     urlState: state,

Also applies to: 121-121

packages/urlstate/react-router/useUrlState/useUrlState.ts (1)

123-127: Consider documenting state mutability implications.

The removal of readonly constraints from urlState and state improves developer experience but introduces potential risks if state is modified directly instead of using setState/setUrl. While this aligns with React's standard patterns, it's important to ensure proper usage.

Consider adding a note in the JSDoc comments above urlState to clarify:

+    /**
+     * Current state object. While mutable, it's recommended to use setState/setUrl
+     * for updates to ensure proper URL synchronization.
+     */
     urlState: state,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b2f5bc3 and a0aa6dd.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (13)
  • README.md (0 hunks)
  • packages/example-nextjs14/src/app/Form-for-test.tsx (0 hunks)
  • packages/example-nextjs15/src/app/Form-for-test.tsx (0 hunks)
  • packages/example-react-router6/src/Form-for-test.tsx (0 hunks)
  • packages/urlstate/next/useUrlState/README.md (1 hunks)
  • packages/urlstate/next/useUrlState/useUrlState.ts (1 hunks)
  • packages/urlstate/react-router/useUrlState/README.md (1 hunks)
  • packages/urlstate/react-router/useUrlState/useUrlState.ts (1 hunks)
  • packages/urlstate/useSharedState/README.md (2 hunks)
  • packages/urlstate/useSharedState/useSharedState.ts (2 hunks)
  • packages/urlstate/useUrlStateBase/README.md (1 hunks)
  • packages/urlstate/useUrlStateBase/useUrlStateBase.ts (1 hunks)
  • packages/urlstate/utils.ts (0 hunks)
💤 Files with no reviewable changes (5)
  • README.md
  • packages/example-nextjs14/src/app/Form-for-test.tsx
  • packages/example-nextjs15/src/app/Form-for-test.tsx
  • packages/example-react-router6/src/Form-for-test.tsx
  • packages/urlstate/utils.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/urlstate/useUrlStateBase/README.md
🔇 Additional comments (8)
packages/urlstate/useSharedState/README.md (1)

17-18: Verify state property documentation completeness.

While removing "readonly" aligns with the PR objectives, consider adding a note about state mutability to help users understand the implications of this change.

Consider adding:

-state: T - The current state.
+state: T - The current state. Note: Unlike previous versions, this state object is mutable.
packages/urlstate/next/useUrlState/README.md (1)

19-20: LGTM! Documentation accurately reflects the mutable nature of urlState

The removal of readonly designation aligns with the PR objectives and correctly represents the actual behavior of the urlState object.

packages/urlstate/react-router/useUrlState/README.md (1)

19-20: Documentation accurately reflects the type change.

The removal of the "readonly" designation from the urlState documentation aligns with the PR's objective to return urlState as a normal type instead of a readonly type. The documentation now correctly represents the mutable nature of the returned state object.

Let's verify the implementation matches this documentation change:

✅ Verification successful

Based on the implementation files examined, I can now generate the final response:

Documentation correctly reflects the implementation

The documentation change is accurate as the implementation in useUrlState.ts and useUrlStateBase.ts shows that:

  1. The urlState is returned as a regular object without readonly constraints
  2. The type T extends JSONCompatible is used without any readonly modifiers
  3. The state is mutable through setState and setUrl functions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the TypeScript implementation to confirm urlState is no longer readonly
# Expected: No DeepReadonly type usage for urlState

# Search for any remaining readonly type declarations
rg -i "readonly.*urlState|DeepReadonly.*urlState" --type ts

# Search for the hook implementation
ast-grep --pattern 'export function useUrlState($_) {
  $$$
}'

Length of output: 126


Script:

#!/bin/bash
# Let's try a different approach to find the implementation and type definitions

# Search for useUrlState implementation files
fd -e ts -e tsx useUrlState

# Once we find the files, let's examine their content
rg -l "useUrlState" --type=typescript

# Look for type definitions or interfaces related to urlState
rg "interface.*UrlState|type.*UrlState" --type=typescript

Length of output: 416


Script:

#!/bin/bash
# Now that we found the relevant files, let's examine their content

# Check the specific implementation for react-router useUrlState
cat packages/urlstate/react-router/useUrlState/useUrlState.ts

# Check the base implementation which might contain type definitions
cat packages/urlstate/useUrlStateBase/useUrlStateBase.ts

# Look for type definitions with corrected ripgrep syntax
rg "interface.*UrlState|type.*UrlState"

Length of output: 8120

packages/urlstate/useSharedState/useSharedState.ts (2)

5-5: LGTM! Import changes align with removing readonly types

The removal of the DeepReadonly import and addition of JSONCompatible type maintains type safety while allowing mutable state.


49-51: Type signature change looks good, verify type safety implications

The simplified type signature aligns with the PR objective of removing readonly constraints while maintaining support for both object and function-based updates.

Let's verify the impact on type safety across the codebase:

✅ Verification successful

Based on the gathered evidence, I can now generate the final response:

Type signature change is safe and correctly used throughout the codebase

The verification shows that:

  • All setState usages follow immutable update patterns using spread operator (...curr)
  • Function-based updates are consistently used to ensure state updates are based on current values
  • No direct mutations of state objects are found in the codebase
  • The simplified type maintains type safety while reducing unnecessary complexity
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any TypeScript errors related to state mutations
# and verify usage patterns of useSharedState

# Search for useSharedState usage patterns
echo "Checking useSharedState usage patterns:"
rg -t typescript "useSharedState[<(]" -A 3

# Look for any mutation-related comments or TODOs
echo "Checking for mutation-related concerns:"
rg -t typescript "mutation|mutable|readonly" --glob "!*.test.*" --glob "!*.spec.*"

Length of output: 377


Script:

#!/bin/bash
# Let's try without typescript file type flag and use file extensions directly
echo "Checking useSharedState usage patterns:"
rg "useSharedState[<(]" --glob "*.ts" --glob "*.tsx" -A 3

echo -e "\nChecking for mutation-related concerns:"
rg "mutation|mutable|readonly" --glob "*.ts" --glob "*.tsx" --glob "!*.test.*" --glob "!*.spec.*"

# Also check for any type errors or issues in related files
echo -e "\nChecking for type-related files and interfaces:"
fd -e ts -e tsx | grep -i "type\|interface"

Length of output: 9140


Script:

#!/bin/bash
# Let's examine the implementation and usage of setState more closely
echo "Checking setState implementation:"
ast-grep --pattern 'setState = ($$$) => {
  $$$
}'

echo -e "\nChecking actual state updates in examples:"
rg "setState\(" --glob "*.ts" --glob "*.tsx" -A 1

# Let's also check the type definitions
echo -e "\nChecking type definitions:"
cat packages/example-nextjs15/src/app/types.ts

Length of output: 8034

packages/urlstate/next/useUrlState/useUrlState.ts (1)

117-121: Verify impact of removing readonly constraint.

Let's check for any code that might be affected by this type change.

packages/urlstate/react-router/useUrlState/useUrlState.ts (1)

123-127: Verify impact of type change on existing code.

The change from readonly to mutable state might affect existing code that relies on type checking.

packages/urlstate/useUrlStateBase/useUrlStateBase.ts (1)

112-112: ⚠️ Potential issue

Breaking Change: Removing readonly type constraint requires documentation

The removal of the DeepReadonly type constraint allows direct mutation of the state object. While this achieves the PR's objective, it has several implications:

  1. This is a breaking change for TypeScript users who may rely on type checking
  2. It deviates from React's immutable state pattern
  3. Could lead to bugs if state is accidentally mutated

Consider:

  1. Adding a comment in the JSDoc explaining why readonly was removed
  2. Documenting this breaking change in the changelog
  3. Adding a warning about direct mutations in the documentation

Let's check for any direct mutations in the codebase that might now be problematic:

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

🧹 Outside diff range and nitpick comments (1)
package.json (1)

106-106: Consider documenting the purpose of the pin-gh-deps script.

The script appears to be a DevOps improvement for pinning GitHub Actions dependencies. While the functionality is clear from the command, adding a brief comment about its purpose would improve maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a0aa6dd and a26617e.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (2 hunks)
  • packages/urlstate/next/useUrlState/useUrlState.ts (1 hunks)
  • packages/urlstate/react-router/useUrlState/useUrlState.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/urlstate/next/useUrlState/useUrlState.ts
  • packages/urlstate/react-router/useUrlState/useUrlState.ts
🔇 Additional comments (1)
package.json (1)

367-367: LGTM! DevOps dependency addition.

The pin-github-action dependency is correctly added with a stable version (^1.9.1) to support the new pin-gh-deps script.

Let's verify the workflow file exists:

✅ Verification successful

Perfect! The pin-github-action dependency is justified and properly used

The workflow file exists and contains multiple GitHub Actions that are already pinned to specific commit hashes, which is exactly what the pin-github-action package is designed to maintain. The presence of comments with version numbers (e.g., # v4.2.2) alongside commit hashes (e.g., @11bd71901bbe5b1630ceea73d27597364c9af683) indicates this pinning system is already in active use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the workflow file exists and contains GitHub Actions that can be pinned
# Expected: File exists and contains action references

if [ -f ".github/workflows/tests.yml" ]; then
    echo "Workflow file exists"
    # Look for action references (e.g., uses: action@version)
    rg "uses: .+@" .github/workflows/tests.yml
else
    echo "Workflow file not found"
fi

Length of output: 2574

@asmyshlyaev177 asmyshlyaev177 merged commit 87ce820 into master Nov 9, 2024
14 checks passed
@asmyshlyaev177 asmyshlyaev177 deleted the 22-argument-of-type-readonly-string-is-not-assignable-to-parameter-of-type-string branch November 9, 2024 17:59
This was referenced Nov 18, 2024
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.

Argument of type 'readonly string[]' is not assignable to parameter of type 'string[]'.
1 participant