Skip to content

Conversation

@robertherber
Copy link

@robertherber robertherber commented Dec 16, 2024

…and streamline structure

And testing out pkg.pkg config :)

Summary by CodeRabbit

Release Notes

  • New Features

    • Updated family activity selection management to utilize identifiers instead of names.
    • Introduced streamlined methods for configuring shields based on family activity selections.
  • Bug Fixes

    • Disabled the "Start monitoring" button functionality for better user experience.
  • Documentation

    • Updated method signatures and parameter names for clarity on family activity selection handling.
  • Chores

    • Cleaned up console log statements to reduce debugging output.

@coderabbitai
Copy link

coderabbitai bot commented Dec 16, 2024

Warning

Rate limit exceeded

@robertherber has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 4 minutes and 15 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 5339d44 and edc5716.

📒 Files selected for processing (1)
  • package.json (1 hunks)

Walkthrough

The pull request introduces modifications to the device activity management system, focusing on replacing references to activity names with unique identifiers across multiple files. Key changes include renaming methods, updating type signatures, and adjusting how family activity selections are stored and retrieved. The updates are reflected in React Native components, Swift files, and TypeScript type definitions, emphasizing a streamlined approach to managing family activity selections through identifiers.

Changes

File Change Summary
example/components/CreateActivity.tsx Replaced updateFamilyActivitySelectionToActivityNameMap with setFamilyActivitySelectionId and updated event handling logic.
example/screens/AllTheThings.tsx Updated updateShieldConfiguration to updateShield, simplified event handler, and commented out console logs.
example/screens/ShieldTab.tsx Replaced updateShieldConfiguration with updateShield in onSubmitEditing callback.
ios/Shared.swift Renamed methods and structures to use family activity selection IDs and improved error handling.
src/ReactNativeDeviceActivity.types.ts Renamed familyActivitySelection to familyActivitySelectionId in the Action type.
src/index.ts Introduced setFamilyActivitySelectionId function, replacing updateFamilyActivitySelectionToActivityNameMap.
targets/ShieldConfiguration/ShieldConfigurationExtension.swift Updated configuration methods to use familyActivitySelectionId instead of activityName.

Sequence Diagram

sequenceDiagram
    participant App
    participant DeviceActivity
    participant ShieldConfiguration
    
    App->>DeviceActivity: setFamilyActivitySelectionId(id)
    DeviceActivity-->>App: Store selection ID
    App->>ShieldConfiguration: updateShield(configuration)
    ShieldConfiguration->>DeviceActivity: Apply shield with selection ID
Loading

Poem

🐰 A Rabbit's Ode to Identifiers

From names to IDs, we hop and leap,
Tracking activities, no more to keep
Confusing strings that twist and turn
Now clean and crisp, new methods we learn! 🏃‍♂️

Hop, hop, hooray for cleaner code! 🎉


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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 16, 2024

Open in Stackblitz

npm i https://pkg.pr.new/Intentional-Digital/react-native-device-activity@1

commit: edc5716

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 comments (1)
example/screens/ShieldTab.tsx (1)

Missing Required Parameter in updateShield Call

The current implementation is missing the required shieldActions parameter. Based on the type definitions, updateShield requires two parameters:

  1. shieldConfiguration: Your current configuration appears valid with the correct properties (title, colors, etc.)
  2. shieldActions: This mandatory parameter is missing and must include at least a primary action

You need to add the missing shieldActions parameter with at least:

shieldActions: {
  primary: ShieldAction
}
🔗 Analysis chain

Line range hint 70-92: Ensure Correct Usage of Updated Method

The function ReactNativeDeviceActivity.updateShield replaces the deprecated updateShieldConfiguration. Ensure that all parameters and their structures align with the new method's expectations.

Please confirm that updateShield accepts the same parameters or adjust them accordingly. Run the following script to check the method definition:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for the definition of updateShield

rg -A 5 "function updateShield\(" src/

Length of output: 342


Script:

#!/bin/bash
# Let's check the ShieldConfiguration type definition
ast-grep --pattern 'type ShieldConfiguration = {
  $$$
}'

# Also search for any usage examples
rg -B 5 -A 10 "updateShield\(" --type typescript

Length of output: 4738


Script:

#!/bin/bash
# Let's check the ShieldActions type and search for usage examples with proper file type
ast-grep --pattern 'type ShieldActions = {
  $$$
}'

rg -B 5 -A 10 'updateShield\(' --type ts --type tsx

Length of output: 393

🧹 Nitpick comments (4)
ios/Shared.swift (2)

261-263: Add Documentation to FamilyActivitySelectionWithId Struct

Consider adding documentation comments to the FamilyActivitySelectionWithId struct to clarify its purpose and usage within the codebase. This improves maintainability and helps other developers understand its role.

Apply this diff to add documentation:

+ /// A struct that pairs a `FamilyActivitySelection` with its unique identifier.
struct FamilyActivitySelectionWithId {
  var selection: FamilyActivitySelection
  var id: String
}

Line range hint 378-409: Simplify Optional Unwrapping in getPossibleFamilyActivitySelectionId

The return statement return foundIt??.id uses double optional chaining, which can be confusing. Adjust the unwrapping to improve readability and ensure safe optional handling.

Apply this diff to simplify the return statement:

- return foundIt??.id
+ if let mapping = foundIt, let id = mapping?.id {
+   return id
+ }
+ return nil
targets/ShieldConfiguration/ShieldConfigurationExtension.swift (1)

Line range hint 107-113: Avoid Code Duplication in Placeholder Dictionaries

The placeholders dictionary is constructed similarly in multiple methods. Consider extracting it into a shared function to reduce code duplication and improve maintainability.

Apply this diff to create a shared function:

func createPlaceholders(token: Token?, tokenType: String, activityToken: ActivityCategoryToken?) -> [String: String?] {
  return [
    "applicationOrDomainDisplayName": token?.localizedDisplayName,
    "token": "\(token?.hashValue ?? 0)",
    "tokenType": tokenType,
    "familyActivitySelectionId": getPossibleFamilyActivitySelectionId(
      applicationToken: token as? ApplicationToken,
      webDomainToken: token as? WebDomainToken,
      categoryToken: activityToken
    )
  ]
}

Then update the methods to use this function:

override func configuration(shielding application: Application) -> ShieldConfiguration {
  let placeholders = createPlaceholders(token: application.token, tokenType: "application", activityToken: nil)
  // Rest of the method remains the same
}
example/components/CreateActivity.tsx (1)

21-23: Remove Unnecessary Commented Code

The commented-out code for ReactNativeDeviceActivity.setFamilyActivitySelectionId may cause confusion. If it's no longer needed, consider removing it to keep the code clean.

Apply this diff to remove the commented code:

- // ReactNativeDeviceActivity.setFamilyActivitySelectionId({
- //   activityName,
- //   familyActivitySelection: activitySelection,
- // });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f4bd3ca and 4994c12.

📒 Files selected for processing (7)
  • example/components/CreateActivity.tsx (1 hunks)
  • example/screens/AllTheThings.tsx (4 hunks)
  • example/screens/ShieldTab.tsx (1 hunks)
  • ios/Shared.swift (6 hunks)
  • src/ReactNativeDeviceActivity.types.ts (1 hunks)
  • src/index.ts (1 hunks)
  • targets/ShieldConfiguration/ShieldConfigurationExtension.swift (4 hunks)
🔇 Additional comments (7)
targets/ShieldConfiguration/ShieldConfigurationExtension.swift (3)

Line range hint 130-136: See Previous Comment Regarding Code Duplication

As with the previous method, consider using the shared function for placeholder creation to avoid duplication.


Line range hint 151-157: See Previous Comment Regarding Code Duplication

Again, consider refactoring to use the shared function for placeholder creation.


Line range hint 175-181: See Previous Comment Regarding Code Duplication

Refactor to use the shared placeholder creation function to enhance code maintainability.

src/index.ts (1)

161-176: Implementation looks good and aligns with PR objectives.

The function properly maintains existing mappings while adding new ones. The approach of using a single userDefaults key for all mappings helps reduce the load on userDefaults storage.

Let's verify the usage of this new function across the codebase:

✅ Verification successful

Implementation verified and properly integrated across the codebase

The verification shows:

  • The new function is properly integrated with a commented example usage in example/components/CreateActivity.tsx
  • The familyActivitySelectionIds key is consistently used across both TypeScript and Swift code
  • No legacy storage patterns were found, indicating a clean migration to the new approach
  • The implementation is properly consumed by the Swift code which reads the stored mappings
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining uses of the old familyActivitySelection storage pattern
rg "familyActivitySelectionToActivityNameMap"

# Verify all calls to the new function match the expected signature
ast-grep --pattern 'setFamilyActivitySelectionId({ id: $_, familyActivitySelection: $_ })'

Length of output: 138


Script:

#!/bin/bash
# Search for any usage of the new function name
rg "setFamilyActivitySelectionId" -A 2

# Search for any usage of the familyActivitySelectionIds key in userDefaults
rg "familyActivitySelectionIds"

# Look for any other potential related storage patterns
rg "ActivitySelection.*userDefaults" -i

Length of output: 1438

src/ReactNativeDeviceActivity.types.ts (1)

153-153: ⚠️ Potential issue

Breaking change: Verify all consumers of the Action type.

The property rename from familyActivitySelection to familyActivitySelectionId is a breaking change that requires updates in all code that creates actions of type "blockSelection".

Let's verify all usages of this action type:

example/screens/AllTheThings.tsx (2)

Line range hint 37-44: LGTM: Cleanup of debug logging.

Good cleanup of development-only debug logging.


Line range hint 266-309: LGTM: Proper usage of updated shield API.

The change to use updateShield is consistent with the API updates and maintains proper typing of shield configuration.

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

♻️ Duplicate comments (1)
ios/Shared.swift (1)

71-71: 🛠️ Refactor suggestion

Consider using async/await or completion handlers instead of sleep.

Using sleep for timing control can lead to poor user experience and potential race conditions. Consider using more modern approaches:

  1. For shield config changes: Use notification observers or completion handlers
  2. For HTTP requests: Use async/await or completion handlers

Also applies to: 85-85

🧹 Nitpick comments (1)
ios/Shared.swift (1)

Line range hint 375-406: Consider simplifying the token matching logic.

The nested conditions in getPossibleFamilyActivitySelectionId could be simplified for better readability.

Consider this refactor:

func getPossibleFamilyActivitySelectionId(
  applicationToken: ApplicationToken?,
  webDomainToken: WebDomainToken?,
  categoryToken: ActivityCategoryToken?
) -> String? {
  let familyActivitySelectionIds = getFamilyActivitySelectionIds()
  
-  let foundIt = familyActivitySelectionIds.first(where: { (mapping) in
-    if let mapping = mapping {
-      if let applicationToken = applicationToken {
-        if mapping.selection.applicationTokens.contains(applicationToken) {
-          return true
-        }
-      }
-
-      if let webDomainToken = webDomainToken {
-        if mapping.selection.webDomainTokens.contains(webDomainToken) {
-          return true
-        }
-      }
-
-      if let categoryToken = categoryToken {
-        if mapping.selection.categoryTokens.contains(categoryToken) {
-          return true
-        }
-      }
-    }
-    return false
-  })
+  let foundIt = familyActivitySelectionIds.first { mapping in
+    guard let mapping = mapping else { return false }
+    return (applicationToken.map { mapping.selection.applicationTokens.contains($0) } ?? false) ||
+           (webDomainToken.map { mapping.selection.webDomainTokens.contains($0) } ?? false) ||
+           (categoryToken.map { mapping.selection.categoryTokens.contains($0) } ?? false)
+  }

  return foundIt??.id
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4994c12 and 5339d44.

📒 Files selected for processing (2)
  • example/components/CreateActivity.tsx (1 hunks)
  • ios/Shared.swift (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • example/components/CreateActivity.tsx
🔇 Additional comments (3)
ios/Shared.swift (3)

50-59: LGTM! Error handling looks good.

The changes properly handle the case where activity selection is not found and include appropriate error logging.


264-266: LGTM! Clean struct implementation.

The struct effectively combines the activity selection with its identifier, supporting the new identifier-based approach.


345-356: LGTM! Efficient implementation of activity selection retrieval.

The functions effectively implement the new identifier-based approach with proper error handling and efficient dictionary access.

Also applies to: 362-372

@robertherber robertherber merged commit e7e9a30 into main Dec 16, 2024
7 checks passed
@robertherber robertherber deleted the id-mapping-for-family-activity-selections branch December 16, 2024 23:59
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