Skip to content

feat: add device detection for (ios/android) and enable appClip default #31

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

Merged
merged 4 commits into from
May 26, 2025

Conversation

kryptocodes
Copy link
Contributor

@kryptocodes kryptocodes commented May 24, 2025

Description

This PR introduces automatic detection of the user's device platform (iOS or Android) to streamline SDK configuration. By auto-configuring optimal settings based on the detected platform, this eliminates the need for manual setup and enhances the developer experience

Type of change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Checklist:

Additional Notes:

  • This change is backward-compatible and gracefully falls back to manual settings if detection fails.

Summary by CodeRabbit

  • New Features
    • Device type (iOS or Android) is now automatically detected and set by default when initializing a proof request.
    • App clip usage is automatically enabled by default if not specified.
  • Chores
    • Updated package version to 3.0.3.

Implement smart device type detection to auto-configure SDK settings for iOS and Android platforms. This eliminates the need for manual device configuration and improves developer experience by setting optimal defaults based on the user's platform.
Copy link

coderabbitai bot commented May 24, 2025

"""

Walkthrough

A new utility module for device detection was introduced, providing environment-safe checks for Android, iOS, and mobile devices. The ReclaimProofRequest constructor and init method now automatically assign default values for device type and app clip usage based on detected platform if not explicitly set. The package version was incremented.

Changes

File(s) Change Summary
package.json Incremented package version from 3.0.1 to 3.0.3.
src/utils/device.ts Added new module exporting userAgentIsAndroid, userAgentIsIOS, userAgentIsMobile booleans and re-exporting DeviceType.
src/utils/types.ts Added new DeviceType enum with values ANDROID, IOS, and IPAD.
src/Reclaim.ts Enhanced ReclaimProofRequest constructor and init method to default device and useAppClip options based on detected platform.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ReclaimProofRequest
    participant DeviceUtils

    Caller->>ReclaimProofRequest: init(applicationId, appSecret, providerId, options?)
    alt options not provided
        ReclaimProofRequest->>ReclaimProofRequest: Initialize options as {}
    end
    alt options.device not set
        ReclaimProofRequest->>DeviceUtils: Check userAgentIsIOS / userAgentIsAndroid
        DeviceUtils-->>ReclaimProofRequest: Return device type
        ReclaimProofRequest->>ReclaimProofRequest: Set options.device to "ios" or "android"
    end
    alt options.useAppClip undefined
        ReclaimProofRequest->>ReclaimProofRequest: Set options.useAppClip = true
    end
    ReclaimProofRequest-->>Caller: Return initialized ReclaimProofRequest
Loading

Poem

In the warren of code where devices abound,
A rabbit detects—Android? iOS?—with a bound!
Options now set with a hop and a cheer,
App clips default true, device type is clear.
With version increased, we leap to the sky—
Hoppy updates, oh my! 🐇✨
"""


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9800402 and 8061cf6.

📒 Files selected for processing (1)
  • src/utils/device.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/device.ts
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@kryptocodes kryptocodes marked this pull request as ready for review May 25, 2025 17:05
@kryptocodes kryptocodes requested a review from Kushal7788 May 25, 2025 17:06
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

🧹 Nitpick comments (2)
package.json (1)

3-3: Consider using minor version increment for feature additions.

This appears to be a feature addition (device detection) rather than a bug fix. According to semantic versioning, new features should increment the minor version (3.1.0) rather than the patch version (3.0.2).

-  "version": "3.0.2",
+  "version": "3.1.0",
src/Reclaim.ts (1)

178-188: Consider logging device detection results.

For debugging purposes, consider adding a log statement when device type is auto-detected.

            if (!options.device) {
                if (userAgentIsIOS) {
                    options.device = "ios";
+                    logger.info(`Auto-detected device type: ios`);
                } else if (userAgentIsAndroid) {
                    options.device = "android";
+                    logger.info(`Auto-detected device type: android`);
                }
            }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e6b647 and 328088f.

📒 Files selected for processing (3)
  • package.json (1 hunks)
  • src/Reclaim.ts (3 hunks)
  • src/utils/device.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/Reclaim.ts (1)
src/utils/device.ts (2)
  • userAgentIsIOS (14-15)
  • userAgentIsAndroid (7-7)
🔇 Additional comments (4)
src/utils/device.ts (2)

1-5: LGTM: Safe environment checks and user agent extraction.

The environment safety checks for navigator and window properly handle SSR/Node.js environments. The user agent extraction with TypeScript assertion is appropriate here since we're already checking for navigatorDefined.


9-15: Excellent iPad and iOS detection implementation.

The iPad detection properly uses the modern userAgentData.platform API with a fallback to user agent string parsing. The iOS detection correctly combines iPhone/iPod regex matching with iPad detection. The case-insensitive regex is appropriate for user agent parsing.

src/Reclaim.ts (2)

38-38: LGTM: Clean import of device detection utilities.

The import statement correctly brings in the device detection constants from the new utility module.


202-204: LGTM: Sensible default for useAppClip.

Setting useAppClip to true by default when undefined makes sense for the SDK's intended use case and improves the developer experience by reducing required configuration.

Comment on lines 17 to 19
export const userAgentIsMobile =
/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent) ||
(windowDefined && 'orientation' in window);
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify orientation-based mobile detection reliability.

The mobile detection logic is comprehensive, but the window.orientation check may have browser compatibility issues and can be unreliable on some devices.


🌐 Web query:

Is window.orientation still a reliable way to detect mobile devices in modern browsers? Are there any deprecation warnings or better alternatives?

💡 Result:

The window.orientation property is no longer considered a reliable method for detecting mobile device orientation in modern browsers. This property has been officially deprecated and is not recommended for use in new projects or code updates.

Deprecation Status

The window.orientation property has been marked as deprecated in documentation, meaning it's no longer recommended for use[10]. Mozilla Developer Network (MDN) explicitly states: "This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes"[10]. This indicates that while the property might still function in some browsers, its long-term availability cannot be guaranteed.

Better Alternatives

Several more modern and standardized alternatives exist for detecting device orientation:

1. Screen.orientation API

The official replacement for window.orientation is the Screen.orientation property, which is available via window.screen.orientation[10]. This provides a more robust and standardized way to access orientation information.

2. matchMedia() for Orientation Detection

One of the most recommended and easiest approaches is using the window.matchMedia() method with orientation media queries:

const portrait = window.matchMedia("(orientation: portrait)").matches;
// portrait will be true or false

This method not only detects the current orientation but can also listen for orientation changes[5]:

window.matchMedia("(orientation: portrait)").addEventListener("change", e => {
  const portrait = e.matches;
  if (portrait) {
    // Handle portrait orientation
  } else {
    // Handle landscape orientation
  }
});

This approach is compatible with all major browsers, including Safari, and works reliably on mobile and tablet devices[5].

3. DeviceOrientationEvent

For more detailed orientation data, you can use the DeviceOrientationEvent, which provides precise information about device rotation along different axes:

window.addEventListener("deviceorientation", handleOrientation, true);

function handleOrientation(event) {
  const absolute = event.absolute;
  const alpha = event.alpha;    // rotation around z-axis
  const beta = event.beta;      // front to back motion (x-axis)
  const gamma = event.gamma;    // left to right motion (y-axis)
  
  // Use orientation data
}

This event provides detailed values for device rotation along different axes, including alpha (z-axis rotation), beta (x-axis rotation), and gamma (y-axis rotation)[1][3].

4. Feature Detection for Touch Capability

If your goal is specifically to detect mobile devices to optimize for touch interfaces, it's better to directly test for touch capability rather than making assumptions based on orientation:

if (navigator.maxTouchPoints > 1) {
  // Device supports multi-touch
}

This approach aligns with modern best practices of testing for specific features rather than attempting to identify device types[8].

Industry Trends

The Android platform is also moving away from allowing apps to restrict orientation. Android 16 is removing the ability for apps to restrict orientation and resizability at the platform level, shifting to a model where apps should adapt seamlessly to different screen sizes and orientations[2]. This industry-wide trend emphasizes the importance of responsive, adaptive design rather than orientation detection and restriction.

Should You Still Use window.orientation?

While window.orientation might continue to work in some contexts for backward compatibility, developers are strongly encouraged to transition to newer methods. As one forum commenter noted: "My bet is that window.orientation isn't going away soon - too much software will break. You'll see warnings in the console long before they get rid of it"[6]. However, relying on deprecated features is generally not recommended for new development.

In conclusion, for modern web development, it's best to use Screen.orientation or the matchMedia() approach for orientation detection, while focusing on responsive design principles that adapt to various screen sizes and orientations rather than trying to detect specific device types.

Citations:


Replace deprecated window.orientation check with modern APIs

The window.orientation property is deprecated and may be removed from browsers at any time. To improve reliability and future-proof our mobile detection, consider swapping it out for one or more of these approaches:

• Use the Screen Orientation API

export const userAgentIsMobile =
  /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent) ||
- (windowDefined && 'orientation' in window);
+ (windowDefined && window.screen?.orientation?.type.startsWith('portrait'));

• Or use a media query via matchMedia

- (windowDefined && 'orientation' in window);
+ (windowDefined && window.matchMedia('(orientation: portrait)').matches);

• For touch-capable devices, feature-detect touch input:

- (windowDefined && 'orientation' in window);
+ (windowDefined && navigator.maxTouchPoints > 1);

You can even combine these checks for broader coverage:

 export const userAgentIsMobile =
   /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent) ||
-  (windowDefined && 'orientation' in window);
+  (windowDefined && (
+    window.screen?.orientation?.type.startsWith('portrait') ||
+    window.matchMedia('(orientation: portrait)').matches ||
+    navigator.maxTouchPoints > 1
+  ));

This ensures robust orientation detection across modern browsers.

🤖 Prompt for AI Agents
In src/utils/device.ts around lines 17 to 19, replace the deprecated
window.orientation check with a more reliable method such as using the Screen
Orientation API (window.screen.orientation) or a media query with
window.matchMedia("(orientation: portrait)").matches. Additionally, consider
incorporating a feature detection for touch capability using
navigator.maxTouchPoints to improve mobile detection accuracy. Combine these
modern approaches to ensure robust and future-proof orientation and device type
detection across browsers.

package.json Outdated
@@ -1,6 +1,6 @@
{
"name": "@reclaimprotocol/js-sdk",
"version": "3.0.1",
"version": "3.0.2",
Copy link
Collaborator

Choose a reason for hiding this comment

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

make it 3.0.3

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated to 3.0.3

const userAgent = navigatorDefined ? navigator.userAgent.toLowerCase() : '';
const userAgentData = navigatorDefined ? (navigator as Navigator & { userAgentData?: { platform: string } }).userAgentData : undefined;

export const userAgentIsAndroid = userAgent.includes("android");
Copy link
Collaborator

Choose a reason for hiding this comment

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

add enum for 'android'

const isIpad =
windowDefined &&
navigatorDefined &&
(userAgentData?.platform === 'iPad' || userAgent.includes('ipad'));
Copy link
Collaborator

Choose a reason for hiding this comment

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

add enum for 'ipad'

src/Reclaim.ts Outdated

if (!options.device) {
if (userAgentIsIOS) {
options.device = "ios";
Copy link
Collaborator

Choose a reason for hiding this comment

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

add enum for 'ios'

src/Reclaim.ts Outdated
if (userAgentIsIOS) {
options.device = "ios";
} else if (userAgentIsAndroid) {
options.device = "android";
Copy link
Collaborator

Choose a reason for hiding this comment

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

add enum for 'android'

src/Reclaim.ts Outdated
options = {};
}

if (!options.device) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Add this in constructor rather than init method. Set the default device and useAppClip fields in constructor

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done !

@kryptocodes kryptocodes merged commit 43e0307 into main May 26, 2025
1 check passed
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