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

feat: added saveStateOfMindSample #136

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

nickmcmillan
Copy link

@nickmcmillan nickmcmillan commented Feb 14, 2025

This adds the ability to save a State of Mind sample. Ref: #134

Example usage:

const res = await saveStateOfMindSample({
  date: new Date(),
  kind: HKStateOfMindKind.dailyMood,
  valence: -0.5,
  labels: [HKStateOfMindLabel.stressed, HKStateOfMindLabel.worried],
  associations: [HKStateOfMindAssociation.currentEvents],
  metadata: {
    key: 'value',
  },
})

One challenge I ran into was that on the React Native side the labels and associations are arrays of enums, which is great. But the value of those enums is lost when passing it over the bridge: Swift just receives an array of Int's.
So those Int's need to be converted back into enums on the Swift side.

I've solved this by writing extensions for Label and Association (see Helpers.swift). It feels a bit like extra work having to re-declare everything. I'm new to Swift so wondering if there's a more efficient way to do this?

Summary by CodeRabbit

  • New Features

    • Introduced enhanced support for tracking mental health data by enabling users to save and query state of mind samples on iOS 18 and later.
    • Added human-friendly representations for mood statuses and integrated the functionality into our React Native module, ensuring smooth asynchronous operations.
  • Tests

    • Updated testing utilities to simulate state of mind sample operations, improving overall reliability.

Copy link

coderabbitai bot commented Feb 14, 2025

Warning

Rate limit exceeded

@nickmcmillan has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 16 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 8c29a61 and f7de665.

📒 Files selected for processing (1)
  • src/utils/saveStateOfMindSample.ts (1 hunks)

Walkthrough

The changes expand HealthKit functionality for iOS 18+ by introducing new extensions on the HKStateOfMind types to support human-readable descriptions and safe integer-to-enum conversions. New methods for saving and querying state of mind samples are added to the React Native HealthKit modules in both Objective-C and Swift, with proper checks for iOS version compatibility. Additionally, the corresponding TypeScript interfaces, exports, and test mocks are updated, along with a new utility function to invoke the native functionality.

Changes

Files Change Summary
ios/Helpers.swift Added extensions for HKStateOfMind.Kind, HKStateOfMind.Label, and HKStateOfMind.Association implementing CaseIterable and CustomStringConvertible, plus static methods for safe integer-to-state conversions under iOS 18+ conditions.
ios/ReactNativeHealthkit.m
ios/ReactNativeHealthkit.swift
Introduced new methods (saveStateOfMindSample and queryStateOfMindSamples) to save and query state of mind samples, incorporating HealthKit availability and iOS version checks.
src/index.ios.tsx
src/index.native.tsx
Added saveStateOfMindSample to module exports: on iOS invoking the proper function and on native returning a resolved false promise via the UnavailableFn utility.
src/native-types.ts
src/test-setup.ts
Updated the ReactNativeHealthkitTypeNative interface to add saveStateOfMindSample and modified the metadata property in HKStateOfMindSampleRaw; also added a mock implementation for saveStateOfMindSample in the test setup.
src/utils/saveStateOfMindSample.ts Created a new asynchronous utility function that accepts a modified sample options object, converts the provided date to an ISO string, and calls Native.saveStateOfMindSample with default values for optional properties.

Sequence Diagram(s)

sequenceDiagram
  participant JS as JavaScript Client
  participant Util as SaveStateOfMind Utility
  participant RNHK as ReactNativeHealthkit (iOS)
  participant HK as HKHealthStore

  JS->>Util: Call saveStateOfMindSample(options)
  Util->>RNHK: Invoke saveStateOfMindSample(date, kind, ... )
  RNHK->>RNHK: Check iOS version & HealthKit availability
  RNHK->>HK: Create and Save HKStateOfMind Sample
  HK-->>RNHK: Success/Error Callback
  RNHK-->>Util: Return result (resolve/reject)
  Util-->>JS: Complete promise resolution
Loading

Poem

I’m just a rabbit in this digital glen,
Hopping through code changes time and again.
New state-of-mind functions now in sight,
With HealthKit’s magic shining bright.
I celebrate with hops and a joyful grin—
CodeRabbit’s changes make my day begin! 🐇✨


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.

Copy link

pkg-pr-new bot commented Feb 14, 2025

Open in Stackblitz

npm i https://pkg.pr.new/kingstinct/react-native-healthkit/@kingstinct/react-native-healthkit@136

commit: f7de665

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

🔭 Outside diff range comments (1)
src/native-types.ts (1)

2300-2426: 🧹 Nitpick (assertive)

Add iOS version requirement to enum documentation.

While the enums are well-documented with links to Apple's documentation, consider adding the iOS version requirement to the JSDoc comments for each enum, similar to how it's documented for HKStateOfMindAssociation. This helps developers understand platform compatibility requirements.

Apply this documentation update to the following enums:

 /**
+ * @since iOS 17.0+
  * @see {@link https://developer.apple.com/documentation/healthkit/hkstateofmind/valenceclassification Apple Docs}
  */
 export enum HKStateOfMindValenceClassification {

 /**
+ * @since iOS 17.0+
  * @see {@link https://developer.apple.com/documentation/healthkit/hkstateofmind/label Apple Docs}
  */
 export enum HKStateOfMindLabel {

 /**
+ * @since iOS 17.0+
  * @see {@link https://developer.apple.com/documentation/healthkit/hkstateofmind/kind Apple Docs}
  */
 export enum HKStateOfMindKind {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b357c61 and 0effd7a.

📒 Files selected for processing (8)
  • ios/Helpers.swift (2 hunks)
  • ios/ReactNativeHealthkit.m (1 hunks)
  • ios/ReactNativeHealthkit.swift (1 hunks)
  • src/index.ios.tsx (3 hunks)
  • src/index.native.tsx (3 hunks)
  • src/native-types.ts (2 hunks)
  • src/test-setup.ts (1 hunks)
  • src/utils/saveStateOfMindSample.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: eas-ios / eas-build
  • GitHub Check: expo-publish-preview
🔇 Additional comments (9)
ios/Helpers.swift (3)

74-80: Looks good!
No issues found with the additional check for iOS 18 when returning HKObjectType.stateOfMindType().


258-279: Implementation appears consistent.
Using a default of .dailyMood for out-of-bounds values is a reasonable fallback, ensuring the app won't crash when an unknown kind is passed.


281-349: Description and conversion logic are well-defined.
The enumerations and the method convertToStateOfMindLabels correctly safeguard against invalid indices.

ios/ReactNativeHealthkit.swift (1)

2207-2298: Nice addition for querying state of mind samples.
The code effectively covers iOS version requirements and serializes the newly introduced fields. Consider adding test coverage to ensure returning associations and labels works as intended.

src/test-setup.ts (1)

38-38: LGTM!

The mock function is correctly added to the mockModule object using jest.fn(), following the established pattern in the file.

src/index.native.tsx (1)

100-100: LGTM!

The saveStateOfMindSample function is correctly added using the UnavailableFn utility and properly exported, following the established pattern in the file.

Also applies to: 191-191, 270-270

ios/ReactNativeHealthkit.m (1)

91-99:

✅ Verification successful

Verify iOS version compatibility.

The method signature is correct, but since this functionality is only available in iOS 18+, ensure that the Swift implementation includes proper version checks.

Run the following script to verify the version check in the Swift implementation:


🏁 Script executed:

#!/bin/bash
# Description: Verify iOS version check for saveStateOfMindSample.

# Test: Search for iOS version check in the Swift implementation.
rg -A 5 $'if #available\(iOS 18.0' ios/ReactNativeHealthkit.swift

Length of output: 804


iOS 18+ Version Check Confirmed

The Swift implementation for saveStateOfMindSample has been verified to include the proper version checks using if #available(iOS 18.0, *). No further changes are required.

src/native-types.ts (2)

2237-2244: LGTM! Well-structured method signature.

The saveStateOfMindSample method follows the established pattern of other save methods in the interface, with proper parameter types and return type.


2315-2315: LGTM! Appropriate metadata type selection.

Using HKGenericMetadata instead of HKHeartbeatSeriesSampleMetadata is the correct choice for state of mind samples, as they don't require specialized heartbeat-related metadata fields.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0effd7a and d4c9922.

📒 Files selected for processing (1)
  • ios/Helpers.swift (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: eas-ios / eas-build
🔇 Additional comments (1)
ios/Helpers.swift (1)

74-81: Looks good checking for iOS 18 availability.

This snippet properly guards for older iOS versions, so there is no concern here.

Comment on lines +259 to +279
#if compiler(>=6)
@available(iOS 18.0, *)
extension HKStateOfMind.Kind: @retroactive CaseIterable, @retroactive CustomStringConvertible {
public var description: String {
switch self {
case .dailyMood: "Daily mood"
case .momentaryEmotion: "Momentary Emotion"
@unknown default: "Unknown"
}
}

public static var allCases: [HKStateOfMind.Kind] {
[.dailyMood, .momentaryEmotion]
}

static func convertToStateOfMindKind(int: Int) -> HKStateOfMind.Kind {
// default to .dailyMood if we receive an int out of bounds
return HKStateOfMind.Kind(rawValue: int) ?? .dailyMood
}
}
#endif
Copy link

@coderabbitai coderabbitai bot Feb 14, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing return statements in switch cases.

The description property will not compile without explicit return statements for each case. Apply the following fix:

-  public var description: String {
-    switch self {
-      case .dailyMood: "Daily mood"
-      case .momentaryEmotion: "Momentary Emotion"
-      @unknown default: "Unknown"
-    }
-  }
+  public var description: String {
+    switch self {
+      case .dailyMood:
+        return "Daily mood"
+      case .momentaryEmotion:
+        return "Momentary Emotion"
+      @unknown default:
+        return "Unknown"
+    }
+  }
📝 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 compiler(>=6)
@available(iOS 18.0, *)
extension HKStateOfMind.Kind: @retroactive CaseIterable, @retroactive CustomStringConvertible {
public var description: String {
switch self {
case .dailyMood: "Daily mood"
case .momentaryEmotion: "Momentary Emotion"
@unknown default: "Unknown"
}
}
public static var allCases: [HKStateOfMind.Kind] {
[.dailyMood, .momentaryEmotion]
}
static func convertToStateOfMindKind(int: Int) -> HKStateOfMind.Kind {
// default to .dailyMood if we receive an int out of bounds
return HKStateOfMind.Kind(rawValue: int) ?? .dailyMood
}
}
#endif
#if compiler(>=6)
@available(iOS 18.0, *)
extension HKStateOfMind.Kind: @retroactive CaseIterable, @retroactive CustomStringConvertible {
public var description: String {
switch self {
case .dailyMood:
return "Daily mood"
case .momentaryEmotion:
return "Momentary Emotion"
@unknown default:
return "Unknown"
}
}
public static var allCases: [HKStateOfMind.Kind] {
[.dailyMood, .momentaryEmotion]
}
static func convertToStateOfMindKind(int: Int) -> HKStateOfMind.Kind {
// default to .dailyMood if we receive an int out of bounds
return HKStateOfMind.Kind(rawValue: int) ?? .dailyMood
}
}
#endif

Copy link
Author

Choose a reason for hiding this comment

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

@robertherber I'm pretty new to Swift - is an explicit return statement necessary? My research suggests it might be a new Swift feature.

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment on lines +281 to +349
#if compiler(>=6)
@available(iOS 18.0, *)
extension HKStateOfMind.Label: @retroactive CaseIterable, @retroactive CustomStringConvertible {
public var description: String {
switch self {
case .amazed: "Amazed"
case .amused: "Amused"
case .angry: "Angry"
case .anxious: "Anxious"
case .ashamed: "Ashamed"
case .brave: "Brave"
case .calm: "Calm"
case .content: "Content"
case .disappointed: "Disappointed"
case .discouraged: "Discouraged"
case .disgusted: "Disgusted"
case .embarrassed: "Embarrassed"
case .excited: "Excited"
case .frustrated: "Frustrated"
case .grateful: "Grateful"
case .guilty: "Guilty"
case .happy: "Happy"
case .hopeless: "Hopeless"
case .irritated: "Irritated"
case .jealous: "Jealous"
case .joyful: "Joyful"
case .lonely: "Lonely"
case .passionate: "Passionate"
case .peaceful: "Peaceful"
case .proud: "Proud"
case .relieved: "Relieved"
case .sad: "Sad"
case .scared: "Scared"
case .stressed: "Stressed"
case .surprised: "Surprised"
case .worried: "Worried"
case .annoyed: "Annoyed"
case .confident: "Confident"
case .drained: "Drained"
case .hopeful: "Hopeful"
case .indifferent: "Indifferent"
case .overwhelmed: "Overwhelmed"
case .satisfied: "Satisfied"
@unknown default: "Unknown"
}
}

public static var allCases: [HKStateOfMind.Label] {
[
.amazed, .amused, .angry, .anxious, .ashamed,
.brave, .calm, .content, .disappointed, .discouraged,
.disgusted, .embarrassed, .excited, .frustrated, .grateful,
.guilty, .happy, .hopeless, .irritated, .jealous,
.joyful, .lonely, .passionate, .peaceful, .proud,
.relieved, .sad, .scared, .stressed, .surprised,
.worried, .annoyed, .confident, .drained, .hopeful,
.indifferent, .overwhelmed, .satisfied
]
}

static func convertToStateOfMindLabels(intArray: [Int]) -> [HKStateOfMind.Label] {
return intArray.compactMap { index in
// if any int are out of bounds return nil instead of crashing
guard index >= 0 && index < HKStateOfMind.Label.allCases.count else { return nil }
return HKStateOfMind.Label(rawValue: index)
}
}
}
#endif
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing return statements in switch cases for labels.

Same issue: the enum cases need return for valid compilation. Here’s a sample fix:

-      case .amazed: "Amazed"
-      case .amused: "Amused"
-      ...
-      @unknown default: "Unknown"
+      case .amazed:
+        return "Amazed"
+      case .amused:
+        return "Amused"
+      ...
+      @unknown default:
+        return "Unknown"
📝 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 compiler(>=6)
@available(iOS 18.0, *)
extension HKStateOfMind.Label: @retroactive CaseIterable, @retroactive CustomStringConvertible {
public var description: String {
switch self {
case .amazed: "Amazed"
case .amused: "Amused"
case .angry: "Angry"
case .anxious: "Anxious"
case .ashamed: "Ashamed"
case .brave: "Brave"
case .calm: "Calm"
case .content: "Content"
case .disappointed: "Disappointed"
case .discouraged: "Discouraged"
case .disgusted: "Disgusted"
case .embarrassed: "Embarrassed"
case .excited: "Excited"
case .frustrated: "Frustrated"
case .grateful: "Grateful"
case .guilty: "Guilty"
case .happy: "Happy"
case .hopeless: "Hopeless"
case .irritated: "Irritated"
case .jealous: "Jealous"
case .joyful: "Joyful"
case .lonely: "Lonely"
case .passionate: "Passionate"
case .peaceful: "Peaceful"
case .proud: "Proud"
case .relieved: "Relieved"
case .sad: "Sad"
case .scared: "Scared"
case .stressed: "Stressed"
case .surprised: "Surprised"
case .worried: "Worried"
case .annoyed: "Annoyed"
case .confident: "Confident"
case .drained: "Drained"
case .hopeful: "Hopeful"
case .indifferent: "Indifferent"
case .overwhelmed: "Overwhelmed"
case .satisfied: "Satisfied"
@unknown default: "Unknown"
}
}
public static var allCases: [HKStateOfMind.Label] {
[
.amazed, .amused, .angry, .anxious, .ashamed,
.brave, .calm, .content, .disappointed, .discouraged,
.disgusted, .embarrassed, .excited, .frustrated, .grateful,
.guilty, .happy, .hopeless, .irritated, .jealous,
.joyful, .lonely, .passionate, .peaceful, .proud,
.relieved, .sad, .scared, .stressed, .surprised,
.worried, .annoyed, .confident, .drained, .hopeful,
.indifferent, .overwhelmed, .satisfied
]
}
static func convertToStateOfMindLabels(intArray: [Int]) -> [HKStateOfMind.Label] {
return intArray.compactMap { index in
// if any int are out of bounds return nil instead of crashing
guard index >= 0 && index < HKStateOfMind.Label.allCases.count else { return nil }
return HKStateOfMind.Label(rawValue: index)
}
}
}
#endif
#if compiler(>=6)
@available(iOS 18.0, *)
extension HKStateOfMind.Label: @retroactive CaseIterable, @retroactive CustomStringConvertible {
public var description: String {
switch self {
case .amazed:
return "Amazed"
case .amused:
return "Amused"
case .angry:
return "Angry"
case .anxious:
return "Anxious"
case .ashamed:
return "Ashamed"
case .brave:
return "Brave"
case .calm:
return "Calm"
case .content:
return "Content"
case .disappointed:
return "Disappointed"
case .discouraged:
return "Discouraged"
case .disgusted:
return "Disgusted"
case .embarrassed:
return "Embarrassed"
case .excited:
return "Excited"
case .frustrated:
return "Frustrated"
case .grateful:
return "Grateful"
case .guilty:
return "Guilty"
case .happy:
return "Happy"
case .hopeless:
return "Hopeless"
case .irritated:
return "Irritated"
case .jealous:
return "Jealous"
case .joyful:
return "Joyful"
case .lonely:
return "Lonely"
case .passionate:
return "Passionate"
case .peaceful:
return "Peaceful"
case .proud:
return "Proud"
case .relieved:
return "Relieved"
case .sad:
return "Sad"
case .scared:
return "Scared"
case .stressed:
return "Stressed"
case .surprised:
return "Surprised"
case .worried:
return "Worried"
case .annoyed:
return "Annoyed"
case .confident:
return "Confident"
case .drained:
return "Drained"
case .hopeful:
return "Hopeful"
case .indifferent:
return "Indifferent"
case .overwhelmed:
return "Overwhelmed"
case .satisfied:
return "Satisfied"
@unknown default:
return "Unknown"
}
}
public static var allCases: [HKStateOfMind.Label] {
[
.amazed, .amused, .angry, .anxious, .ashamed,
.brave, .calm, .content, .disappointed, .discouraged,
.disgusted, .embarrassed, .excited, .frustrated, .grateful,
.guilty, .happy, .hopeless, .irritated, .jealous,
.joyful, .lonely, .passionate, .peaceful, .proud,
.relieved, .sad, .scared, .stressed, .surprised,
.worried, .annoyed, .confident, .drained, .hopeful,
.indifferent, .overwhelmed, .satisfied
]
}
static func convertToStateOfMindLabels(intArray: [Int]) -> [HKStateOfMind.Label] {
return intArray.compactMap { index in
// if any int are out of bounds return nil instead of crashing
guard index >= 0 && index < HKStateOfMind.Label.allCases.count else { return nil }
return HKStateOfMind.Label(rawValue: index)
}
}
}
#endif

Comment on lines +351 to +394
#if compiler(>=6)
@available(iOS 18.0, *)
extension HKStateOfMind.Association: @retroactive CaseIterable, @retroactive CustomStringConvertible {
public var description: String {
switch self {
case .community: "Community"
case .currentEvents: "Current Events"
case .dating: "Dating"
case .education: "Education"
case .family: "Family"
case .fitness: "Fitness"
case .friends: "Friends"
case .health: "Health"
case .hobbies: "Hobbies"
case .identity: "Identity"
case .money: "Money"
case .partner: "Partner"
case .selfCare: "Self Care"
case .spirituality: "Spirituality"
case .tasks: "Tasks"
case .travel: "Travel"
case .work: "Work"
case .weather: "Weather"
@unknown default: "Unknown"
}
}

public static var allCases: [HKStateOfMind.Association] {
[
.community, .currentEvents, .dating, .education, .family,
.fitness, .friends, .health, .hobbies, .identity,
.money, .partner, .selfCare, .spirituality, .tasks,
.travel, .work, .weather
]
}

static func convertToStateOfMindAssociations(intArray: [Int]) -> [HKStateOfMind.Association] {
return intArray.compactMap { index in
guard index >= 0 && index < HKStateOfMind.Association.allCases.count else { return nil }
return HKStateOfMind.Association(rawValue: index)
}
}
}
#endif
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing return statements in switch cases for associations.

Although the index guard is properly fixed (thanks for addressing the prior bug), each case in description must explicitly return a string. For example:

-      case .community: "Community"
-      case .currentEvents: "Current Events"
-      ...
-      @unknown default: "Unknown"
+      case .community:
+        return "Community"
+      case .currentEvents:
+        return "Current Events"
+      ...
+      @unknown default:
+        return "Unknown"
📝 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 compiler(>=6)
@available(iOS 18.0, *)
extension HKStateOfMind.Association: @retroactive CaseIterable, @retroactive CustomStringConvertible {
public var description: String {
switch self {
case .community: "Community"
case .currentEvents: "Current Events"
case .dating: "Dating"
case .education: "Education"
case .family: "Family"
case .fitness: "Fitness"
case .friends: "Friends"
case .health: "Health"
case .hobbies: "Hobbies"
case .identity: "Identity"
case .money: "Money"
case .partner: "Partner"
case .selfCare: "Self Care"
case .spirituality: "Spirituality"
case .tasks: "Tasks"
case .travel: "Travel"
case .work: "Work"
case .weather: "Weather"
@unknown default: "Unknown"
}
}
public static var allCases: [HKStateOfMind.Association] {
[
.community, .currentEvents, .dating, .education, .family,
.fitness, .friends, .health, .hobbies, .identity,
.money, .partner, .selfCare, .spirituality, .tasks,
.travel, .work, .weather
]
}
static func convertToStateOfMindAssociations(intArray: [Int]) -> [HKStateOfMind.Association] {
return intArray.compactMap { index in
guard index >= 0 && index < HKStateOfMind.Association.allCases.count else { return nil }
return HKStateOfMind.Association(rawValue: index)
}
}
}
#endif
#if compiler(>=6)
@available(iOS 18.0, *)
extension HKStateOfMind.Association: @retroactive CaseIterable, @retroactive CustomStringConvertible {
public var description: String {
switch self {
case .community:
return "Community"
case .currentEvents:
return "Current Events"
case .dating:
return "Dating"
case .education:
return "Education"
case .family:
return "Family"
case .fitness:
return "Fitness"
case .friends:
return "Friends"
case .health:
return "Health"
case .hobbies:
return "Hobbies"
case .identity:
return "Identity"
case .money:
return "Money"
case .partner:
return "Partner"
case .selfCare:
return "Self Care"
case .spirituality:
return "Spirituality"
case .tasks:
return "Tasks"
case .travel:
return "Travel"
case .work:
return "Work"
case .weather:
return "Weather"
@unknown default:
return "Unknown"
}
}
public static var allCases: [HKStateOfMind.Association] {
[
.community, .currentEvents, .dating, .education, .family,
.fitness, .friends, .health, .hobbies, .identity,
.money, .partner, .selfCare, .spirituality, .tasks,
.travel, .work, .weather
]
}
static func convertToStateOfMindAssociations(intArray: [Int]) -> [HKStateOfMind.Association] {
return intArray.compactMap { index in
guard index >= 0 && index < HKStateOfMind.Association.allCases.count else { return nil }
return HKStateOfMind.Association(rawValue: index)
}
}
}
#endif

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d4c9922 and 8c29a61.

📒 Files selected for processing (1)
  • ios/ReactNativeHealthkit.swift (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: eas-ios / eas-build
🔇 Additional comments (1)
ios/ReactNativeHealthkit.swift (1)

667-668: Good job clamping the valence range.

Clamping valence between -1.0 and 1.0 addresses the earlier feedback on out-of-range inputs. This helps maintain data integrity.

Comment on lines +649 to +653
@objc(saveStateOfMindSample:kind:valence:labels:associations:metadata:resolve:reject:)
func saveStateOfMindSample(
_ date: Date,
kind: Int,
valence: Double, // non-integer number, ie 0.5
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add unit tests for saveStateOfMindSample.

This newly introduced function appears untested. Having unit tests ensures correct integration with HealthKit and guards against regressions.

Would you like me to provide an example test snippet that covers typical success and error scenarios?

Copy link

Expo preview is ready for review.

There should soon be a new native build available here

With that installed just scan this QR code:
QR Preview

@@ -2304,7 +2312,7 @@ export type HKStateOfMindSampleRaw = {
readonly device?: HKDevice;
readonly startDate: string;
readonly endDate: string;
readonly metadata?: HKHeartbeatSeriesSampleMetadata;
Copy link
Author

Choose a reason for hiding this comment

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

Note: I suspected this might have been a typo. I'm not sure why HKStateOfMindSampleRaw['metadata'] would need to be HKHeartbeatSeriesSampleMetadata? So I've changed it to HKGenericMetadata.

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.

1 participant