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

chore: Added Cookie banner to Marketing website #2826

Open
wants to merge 15 commits into
base: main
Choose a base branch
from

Conversation

BurnedChris
Copy link
Contributor

@BurnedChris BurnedChris commented Jan 17, 2025

What does this PR do?

Fixes # (issue)

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Open the marketing website, see the cookie banner, check that its working properly.
  • Check that all buttons are still working since we added onClick event.
  • We also had to change around the footer array to add the onClick function for allowing the users to change there consent in the footers.

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

Release Notes

  • New Features

    • Added comprehensive cookie consent management system.
    • Introduced new cookie banner for user consent preferences.
  • Improvements

    • Enhanced footer with ability to modify consent settings.
    • Updated page view tracking to respect user consent preferences.
  • Dependencies

    • Added @koroflow/elements package (v0.0.1-beta.8).

The release focuses on improving user privacy controls and consent management across the application.

… look squashed, using object-cover should fix that
- Updated pnpm-lock.yaml to version 9.0 and adjusted package versions for dependencies.
- Added @koroflow/core-react for consent management.
- Implemented ConsentManagerProvider in layout.tsx to manage user consent.
- Created CookieBanner and ConsentCustomizationDialog components for user consent interactions.
- Enhanced button components to support onKeyDown and onKeyUp events.
- Updated footer to include a link for changing consent preferences.
- Integrated consent checks in PostHogPageView for analytics tracking based on user consent.
Copy link

changeset-bot bot commented Jan 17, 2025

⚠️ No Changeset found

Latest commit: 81612b3

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

📝 Walkthrough

Walkthrough

The pull request introduces a comprehensive consent management system across the application. The changes involve integrating a new ConsentManagerProvider in the root layout, adding a CookieBanner component, and modifying existing components to support consent-related functionality. The implementation includes new imports from @koroflow/elements, updates to the footer navigation, and modifications to page view tracking to respect user consent settings.

Changes

File Change Summary
apps/www/app/layout.tsx - Added ConsentManagerProvider with initialGdprTypes
- Integrated CookieBanner component
- Nested PHProvider within new consent management structure
apps/www/components/footer/footer.tsx - Updated NavLink type to support flexible link handling
- Added "Change my consent" link
- Imported useConsentManager hook
apps/www/package.json - Added new dependency @koroflow/[email protected]
apps/www/providers/posthog/PostHogPageView.tsx - Imported useConsentManager hook
- Added consent check for page view tracking
apps/www/components/cookie-banner.tsx - Created new CookieBannerComponent
- Integrated CookieBanner and ConsentManagerDialog from @koroflow/elements

Sequence Diagram

sequenceDiagram
    participant User
    participant App
    participant ConsentManager
    participant CookieBanner
    participant PostHog

    User->>App: Loads Application
    App->>ConsentManager: Initialize with default consents
    ConsentManager-->>App: Consent State
    App->>CookieBanner: Render Consent Options
    User->>CookieBanner: Interact with Consent Preferences
    CookieBanner->>ConsentManager: Update Consent Settings
    ConsentManager-->>PostHog: Check Measurement Consent
    alt Measurement Consent Granted
        PostHog->>PostHog: Track Page View
    else Measurement Consent Denied
        PostHog->>PostHog: Skip Tracking
    end
Loading

📜 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 1e3aee5 and 81612b3.

📒 Files selected for processing (1)
  • apps/www/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/www/package.json

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

vercel bot commented Jan 17, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
engineering ❌ Failed (Inspect) Jan 26, 2025 7:55pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 26, 2025 7:55pm

Copy link
Contributor

github-actions bot commented Jan 17, 2025

Thank you for following the naming conventions for pull request titles! 🙏

Copy link

vercel bot commented Jan 17, 2025

@BurnedChris is attempting to deploy a commit to the Unkey Team on Vercel.

A member of the Team first needs to authorize it.

@perkinsjr perkinsjr changed the title Cookie banner chore: Cookie banner Jan 17, 2025
@BurnedChris BurnedChris changed the title chore: Cookie banner chore: Added Cookie banner to Marketing website Jan 17, 2025
@BurnedChris
Copy link
Contributor Author

I don't know why the pnpm.lock has changed so much maybe it was formatting problem?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🔭 Outside diff range comments (2)
apps/www/providers/posthog/PostHogPageView.tsx (1)

Line range hint 15-24: Add error handling for PostHog tracking calls.

The PostHog capture calls should be wrapped in try-catch blocks to handle potential failures gracefully.

 if (pathname && posthog && consents.measurement) {
+  try {
     posthog.capture("$pageleave");
     let url = window.origin + pathname;
     if (searchParams.toString()) {
       url = `${url}?${searchParams.toString()}`;
     }
     posthog.capture("$pageview", {
       $current_url: url,
     });
+  } catch (error) {
+    console.error("Failed to capture analytics:", error);
+  }
 }
apps/www/components/button.tsx (1)

Line range hint 16-27: Convert PrimaryButton to use button element for accessibility.

Using a div for a button is not accessible. Convert to a proper button element and remove the TODO comment.

-// TODO: use <button> not <div>
 export const PrimaryButton: React.FC<Props> = ({
   className,
   IconLeft,
   label,
   IconRight,
   shiny = false,
   ...props
 }) => {
   return (
-    //@ts-expect-error added props spread to add onClick, onKeyDown, onKeyUp
-    <div className="relative group/button" {...props}>
+    <button type="button" className="relative group/button" {...props}>
🧹 Nitpick comments (4)
apps/www/components/button.tsx (1)

11-12: Consider using ButtonHTMLAttributes type.

Instead of manually defining keyboard event handlers, extend from React.ButtonHTMLAttributes for better type safety.

-type Props = {
+type Props = React.ButtonHTMLAttributes<HTMLButtonElement> & {
   className?: string;
   IconLeft?: LucideIcon;
   label: string;
   IconRight?: LucideIcon;
-  onClick?: React.MouseEventHandler<HTMLButtonElement>;
-  onKeyDown?: React.KeyboardEventHandler<HTMLButtonElement>;
-  onKeyUp?: React.KeyboardEventHandler<HTMLButtonElement>;
   shiny?: boolean;
 };
apps/www/app/layout.tsx (1)

76-77: Consider lazy loading consent components.

The CookieBanner and ConsentCustomizationDialog could be lazy loaded to improve initial page load performance.

-import { ConsentCustomizationDialog } from "@/components/consent/consent-customization-dialog";
-import CookieBanner from "@/components/consent/cookie-banner";
+const CookieBanner = dynamic(() => import("@/components/consent/cookie-banner"), {
+  ssr: false,
+});
+const ConsentCustomizationDialog = dynamic(
+  () => import("@/components/consent/consent-customization-dialog"),
+  { ssr: false }
+);
apps/www/components/consent/consent-customization-dialog.tsx (1)

20-38: Optimize animation performance.

Move animation variants outside the component to prevent recreation on each render.

+const ANIMATION_VARIANTS = {
+  dialog: {
+    hidden: { opacity: 0 },
+    visible: { opacity: 1 },
+    exit: { opacity: 0 },
+  },
+  content: {
+    hidden: { opacity: 0, scale: 0.95 },
+    visible: {
+      opacity: 1,
+      scale: 1,
+      transition: { type: "spring", stiffness: 300, damping: 30 },
+    },
+    exit: {
+      opacity: 0,
+      scale: 0.95,
+      transition: { duration: 0.2 },
+    },
+  },
+};

-const dialogVariants = {
-  hidden: { opacity: 0 },
-  visible: { opacity: 1 },
-  exit: { opacity: 0 },
-};

-const contentVariants = {
-  hidden: { opacity: 0, scale: 0.95 },
-  visible: {
-    opacity: 1,
-    scale: 1,
-    transition: { type: "spring", stiffness: 300, damping: 30 },
-  },
-  exit: {
-    opacity: 0,
-    scale: 0.95,
-    transition: { duration: 0.2 },
-  },
-};
apps/www/components/consent/cookie-banner.tsx (1)

147-154: Improve conditional rendering performance.

Move the GDPR check outside the render tree to prevent unnecessary DOM updates.

+                  {complianceSettings.gdpr.enabled ? (
                   <div className="flex flex-col sm:flex-row justify-between gap-2 w-full sm:w-auto">
-                    {complianceSettings.gdpr.enabled && (
                       <SecondaryButton
                         onClick={rejectAll}
                         label="Reject All"
                         className="w-full cursor-pointer text-sm sm:w-auto"
                       />
-                    )}
                     <SecondaryButton
                       onClick={handleCustomize}
                       label="Customize Consent"
                       className="w-full cursor-pointer text-sm sm:w-auto"
                     />
                   </div>
+                  ) : (
+                   <SecondaryButton
+                     onClick={handleCustomize}
+                     label="Customize Consent"
+                     className="w-full cursor-pointer text-sm sm:w-auto"
+                   />
+                  )}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f8fa80a and f99adec.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (10)
  • apps/www/app/layout.tsx (2 hunks)
  • apps/www/components/button.tsx (3 hunks)
  • apps/www/components/consent/consent-customization-dialog.tsx (1 hunks)
  • apps/www/components/consent/consent-customization-widget.tsx (1 hunks)
  • apps/www/components/consent/cookie-banner.tsx (1 hunks)
  • apps/www/components/consent/overlay.tsx (1 hunks)
  • apps/www/components/footer/footer.tsx (2 hunks)
  • apps/www/components/ui/switch.tsx (1 hunks)
  • apps/www/package.json (2 hunks)
  • apps/www/providers/posthog/PostHogPageView.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test Agent Local / test_agent_local
🔇 Additional comments (11)
apps/www/components/ui/switch.tsx (2)

8-27: LGTM! Well-implemented accessible switch component.

The implementation includes:

  • Proper keyboard navigation support
  • Focus management
  • Transition animations
  • ARIA states through Radix UI

14-14: Verify color scheme alignment with design system.

The switch uses custom colors (bg-[#3CEEAE]/70 for checked state) that might not be part of the design system. Consider using design tokens for consistency.

#!/bin/bash
# Search for other occurrences of this color in the codebase
rg -i '#3CEEAE' --type css --type tsx
apps/www/package.json (3)

28-28: LGTM! Radix UI switch dependency.

The @radix-ui/react-switch is a stable, well-maintained package that provides accessible switch components.


15-15: Verify stability of beta dependency.

The @koroflow/[email protected] package is in beta. Before proceeding:

  1. Confirm if this package is actively maintained
  2. Verify if there are any known issues or limitations
  3. Consider waiting for a stable release
#!/bin/bash
# Check package details and recent activity
curl -s "https://registry.npmjs.org/@koroflow%2Fcore-react" | jq '{
  "latest_version": .["dist-tags"].latest,
  "modified": .time.modified,
  "maintainers": .maintainers[].name
}'

# Check for existing issues in the codebase
rg -l '@koroflow/core-react'

Line range hint 1-1: Architectural Considerations for Cookie Banner Implementation

  1. The PR introduces UI components but the cookie consent management logic isn't visible in the provided files. Please ensure:
    • Proper persistence of user consent
    • Integration with your analytics and tracking systems
    • Compliance with privacy regulations (GDPR, CCPA)
  2. Consider documenting the purpose of @koroflow/core-react and its role in consent management.
#!/bin/bash
# Check for consent management implementation
echo "Searching for consent management implementation..."
rg -l 'consent|gdpr|ccpa|cookie' --type tsx --type ts

# Check for analytics integration
echo "Checking analytics integration..."
rg -l 'analytics|tracking|posthog' --type tsx --type ts
apps/www/components/consent/overlay.tsx (1)

13-13: Verify z-index coordination with other components.

The z-index of 40 needs to be verified against other modal/overlay components to ensure proper stacking order.

#!/bin/bash
# Search for z-index values across the codebase
rg -n "z-\d+" --type css --type tsx
apps/www/providers/posthog/PostHogPageView.tsx (1)

11-11: Verify PostHog initialization timing.

The consent check might run before PostHog is fully initialized. Consider adding a ready check.

#!/bin/bash
# Search for PostHog initialization code
rg -A 5 "posthog\.(init|setup)" --type tsx
apps/www/app/layout.tsx (1)

55-55: Verify consent persistence mechanism.

Ensure that consent preferences are properly persisted across sessions.

#!/bin/bash
# Search for storage-related code in consent management
rg -n "localStorage|sessionStorage" --type tsx
rg -n "setCookie|cookie" --type tsx
apps/www/components/consent/consent-customization-widget.tsx (2)

75-80: 🛠️ Refactor suggestion

Enhance keyboard accessibility.

The close button should have a more descriptive aria-label and keyboard focus styles.

           <Button
             variant="ghost"
             size="icon"
-            className="absolute right-2 top-2"
+            className="absolute right-2 top-2 focus:ring-2 focus:ring-white/20 focus:outline-none"
             onClick={onCloseWrapper}
-            aria-label="Close privacy settings"
+            aria-label="Close privacy settings dialog"

Likely invalid or redundant comment.


51-51: ⚠️ Potential issue

Remove debug console.log statement.

Debug statements should not be present in production code.

-  console.log("Card rendered with props:", { showCloseButton, onClose, handleSave }); // Debug render

Likely invalid or redundant comment.

apps/www/components/consent/cookie-banner.tsx (1)

58-67: ⚠️ Potential issue

Fix potential memory leak in useEffect.

The bannerShownRef is not reset in the cleanup function, which could cause issues if the component is unmounted and remounted.

   React.useEffect(() => {
     if (!isMounted) {
       return;
     }

     if (showPopup && !bannerShownRef.current && !hasConsented()) {
       callbacks.onBannerShown?.();
       bannerShownRef.current = true;
     }
+    return () => {
+      bannerShownRef.current = false;
+    };
   }, [showPopup, callbacks, hasConsented, isMounted]);

Likely invalid or redundant comment.

apps/www/components/consent/overlay.tsx Outdated Show resolved Hide resolved
apps/www/components/footer/footer.tsx Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (4)
apps/www/components/consent/cookie-banner.tsx (3)

3-13: Consider reorganizing imports for better maintainability.

Group imports into these categories:

  1. External dependencies
  2. Internal UI components
  3. Utils and hooks
- import { useConsentManager } from "@koroflow/core-react";
- import { AnimatePresence, motion } from "framer-motion";
- import { X } from "lucide-react";
- import * as React from "react";
- import { createPortal } from "react-dom";
-
- import { Button } from "@/components/ui/button";
- import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
- import { cn } from "@/lib/utils";
- import { PrimaryButton, SecondaryButton } from "../button";
- import { usePostHog } from "posthog-js/react";

+ import * as React from "react";
+ import { createPortal } from "react-dom";
+ import { useConsentManager } from "@koroflow/core-react";
+ import { AnimatePresence, motion } from "framer-motion";
+ import { X } from "lucide-react";
+ import { usePostHog } from "posthog-js/react";
+
+ import { Button } from "@/components/ui/button";
+ import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
+ import { PrimaryButton, SecondaryButton } from "../button";
+
+ import { cn } from "@/lib/utils";

18-24: Add JSDoc documentation for the interface.

Adding documentation will improve code maintainability and help other developers understand the purpose of each prop.

+ /**
+  * Props for the CookieBanner component
+  * @interface PrivacyPopupProps
+  * @extends {React.HTMLAttributes<HTMLDivElement>}
+  */
 interface PrivacyPopupProps extends React.HTMLAttributes<HTMLDivElement> {
+   /** Description text for the cookie banner */
    bannerDescription?: string;
+   /** Title text for the cookie banner */
    bannerTitle?: string;
+   /** Horizontal positioning of the banner */
    horizontalPosition?: HorizontalPosition;
+   /** Vertical positioning of the banner */
    verticalPosition?: VerticalPosition;
+   /** Whether to show the close button */
    showCloseButton?: boolean;
 }

52-58: Add cleanup for bannerShownRef to prevent memory leaks.

The bannerShownRef should be reset when the component unmounts.

 React.useEffect(() => {
   setIsMounted(true);
-  return () => setIsMounted(false);
+  return () => {
+    setIsMounted(false);
+    bannerShownRef.current = false;
+  };
 }, []);
apps/www/components/consent/consent-customization-widget.tsx (1)

92-93: Simplify keyboard event handling

Having both onKeyUp and onKeyDown handlers for the same key can lead to duplicate actions. Consider using only one, preferably onKeyDown, for a consistent and immediate response to key presses.

Apply this diff to remove the redundant handler:

                 onClick={() => toggleAccordion(consent.name)}
-                onKeyUp={(e) => e.key === "Enter" && toggleAccordion(consent.name)}
                 onKeyDown={(e) => e.key === "Enter" && toggleAccordion(consent.name)}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f99adec and ae500c6.

📒 Files selected for processing (4)
  • apps/www/components/consent/consent-customization-dialog.tsx (1 hunks)
  • apps/www/components/consent/consent-customization-widget.tsx (1 hunks)
  • apps/www/components/consent/cookie-banner.tsx (1 hunks)
  • apps/www/components/consent/overlay.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/www/components/consent/overlay.tsx
🔇 Additional comments (1)
apps/www/components/consent/cookie-banner.tsx (1)

26-49: 🛠️ Refactor suggestion

Enhance error handling and accessibility.

Consider these improvements:

  1. Wrap the component in an error boundary
  2. Add ARIA live region for screen readers
  3. Add keyboard navigation support

Let me check if error boundaries are implemented elsewhere:

apps/www/components/consent/cookie-banner.tsx Outdated Show resolved Hide resolved
Comment on lines 71 to 87
const acceptAll = React.useCallback(() => {
const allConsents = Object.keys(consents) as (keyof typeof consents)[];
for (const consentName of allConsents) {
setConsent(consentName, true);
}
saveConsents("all");
posthog.capture("consent", {
consent: "necessary",
});
}, [consents, setConsent, saveConsents, posthog]);

const rejectAll = React.useCallback(() => {
saveConsents("necessary");
posthog.capture("consent", {
consent: "necessary",
});
}, [saveConsents, posthog]);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix duplicate PostHog event payload and add error handling.

The PostHog event payload is duplicated between acceptAll and rejectAll. Also, consider adding error handling for PostHog events.

+ const captureConsent = (type: 'all' | 'necessary') => {
+   try {
+     posthog.capture("consent", { consent: "necessary" });
+   } catch (error) {
+     console.error('Failed to capture consent event:', error);
+   }
+ };

 const acceptAll = React.useCallback(() => {
   const allConsents = Object.keys(consents) as (keyof typeof consents)[];
   for (const consentName of allConsents) {
     setConsent(consentName, true);
   }
   saveConsents("all");
-  posthog.capture("consent", {
-    consent: "necessary",
-  });
+  captureConsent('all');
 }, [consents, setConsent, saveConsents, posthog]);

 const rejectAll = React.useCallback(() => {
   saveConsents("necessary");
-  posthog.capture("consent", {
-    consent: "necessary",
-  });
+  captureConsent('necessary');
 }, [saveConsents, posthog]);
📝 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
const acceptAll = React.useCallback(() => {
const allConsents = Object.keys(consents) as (keyof typeof consents)[];
for (const consentName of allConsents) {
setConsent(consentName, true);
}
saveConsents("all");
posthog.capture("consent", {
consent: "necessary",
});
}, [consents, setConsent, saveConsents, posthog]);
const rejectAll = React.useCallback(() => {
saveConsents("necessary");
posthog.capture("consent", {
consent: "necessary",
});
}, [saveConsents, posthog]);
const captureConsent = (type: 'all' | 'necessary') => {
try {
posthog.capture("consent", { consent: "necessary" });
} catch (error) {
console.error('Failed to capture consent event:', error);
}
};
const acceptAll = React.useCallback(() => {
const allConsents = Object.keys(consents) as (keyof typeof consents)[];
for (const consentName of allConsents) {
setConsent(consentName, true);
}
saveConsents("all");
captureConsent('all');
}, [consents, setConsent, saveConsents, posthog]);
const rejectAll = React.useCallback(() => {
saveConsents("necessary");
captureConsent('necessary');
}, [saveConsents, posthog]);

apps/www/components/consent/cookie-banner.tsx Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
apps/www/components/consent/consent-customization-widget.tsx (1)

89-96: 🛠️ Refactor suggestion

Convert div to button element for better accessibility.

Using a div with role="button" is less semantic than using a native button element.

Apply this diff:

-              <div
-                className="flex-grow"
-                role="button"
-                tabIndex={0}
-                onClick={() => toggleAccordion(consent.name)}
-                onKeyUp={(e) => e.key === "Enter" && toggleAccordion(consent.name)}
-                onKeyDown={(e) => e.key === "Enter" && toggleAccordion(consent.name)}
-              >
+              <button
+                type="button"
+                className="flex-grow text-left"
+                onClick={() => toggleAccordion(consent.name)}
+              >
🧰 Tools
🪛 Biome (1.9.4)

[error] 90-91: The elements with the following roles can be changed to the following elements:

For examples and more information, see WAI-ARIA Roles

(lint/a11y/useSemanticElements)

🧹 Nitpick comments (2)
apps/www/components/consent/consent-customization-widget.tsx (2)

31-41: Add error handling for analytics tracking.

The PostHog analytics tracking calls could fail silently. Consider adding try-catch blocks to handle potential failures gracefully.

Example implementation:

 const handleSaveConsents = React.useCallback(() => {
   saveConsents("custom");
-  posthog.capture("consent", {
-    consent: "custom",
-    consents,
-  });
+  try {
+    posthog.capture("consent", {
+      consent: "custom",
+      consents,
+    });
+  } catch (error) {
+    console.error("Failed to track consent analytics:", error);
+  }

   if (onSave) {
     onSave();
   }
 }, [saveConsents, posthog, consents, onSave]);

Apply similar error handling to other analytics tracking calls in acceptAll and rejectAll functions.

Also applies to: 50-62, 64-72


106-111: Enhance switch component accessibility.

The switch component could benefit from additional accessibility improvements.

Add ARIA labels and descriptions:

 <Switch
   checked={consents[consent.name]}
   onCheckedChange={(checked) => handleConsentChange(consent.name, checked)}
   disabled={consent.disabled}
-  className="ml-4"
+  className="ml-4"
+  aria-label={`Toggle ${consent.name.replace("_", " ")}`}
+  aria-describedby={`${consent.name}-description`}
 />

Also, consider adding an invisible span with ID matching the aria-describedby for screen readers:

 <AccordionContent>
-  <p className="text-sm text-muted-foreground pb-4">{consent.description}</p>
+  <p className="text-sm text-muted-foreground pb-4" id={`${consent.name}-description`}>
+    {consent.description}
+  </p>
 </AccordionContent>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ae500c6 and 5eb3a8f.

📒 Files selected for processing (1)
  • apps/www/components/consent/consent-customization-widget.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
apps/www/components/consent/consent-customization-widget.tsx

[error] 90-91: The elements with the following roles can be changed to the following elements:

For examples and more information, see WAI-ARIA Roles

(lint/a11y/useSemanticElements)

🔇 Additional comments (2)
apps/www/components/consent/consent-customization-widget.tsx (2)

1-14: LGTM! Clean imports and well-typed props interface.

The imports are well-organized, and the props interface is properly typed with TypeScript.


16-24: LGTM! Well-structured component initialization.

Good use of forwardRef and proper hook initialization. The state management is clean and follows React best practices.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@perkinsjr perkinsjr self-assigned this Jan 17, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (6)
apps/www/components/cookie-banner.tsx (3)

8-11: Extract button styles to a separate constants file.

The button styles are reused across components and should be moved to a dedicated styles/constants file for better maintainability and reusability.

Create a new file styles/button-styles.ts:

export const buttonStyles = {
  secondary: "items-center gap-2 px-4 duration-500 border border-white/40 rounded-lg text-white/70 hover:text-white h-10 flex",
  primary: "relative flex items-center px-4 gap-2 text-sm font-semibold text-black group-hover:bg-white/90 duration-1000 rounded-lg bg-gradient-to-r from-white/80 to-white h-10"
};

16-32: Extract cookie banner theme to a separate configuration file.

The theme object is large and could be reused. Consider moving it to a dedicated theme configuration file.

Create a new file themes/cookie-banner-theme.ts:

export const cookieBannerTheme = {
  "cookie-banner.overlay": "bg-black/50 inset-0 fixed z-40",
  // ... rest of the theme
};

34-75: Extract consent manager theme to a separate configuration file.

Similar to the cookie banner theme, the consent manager theme should be moved to a dedicated file to improve maintainability.

Create a new file themes/consent-manager-theme.ts:

export const consentManagerTheme = {
  "consent-manager-widget.root": "space-y-6",
  // ... rest of the theme
};
apps/www/app/layout.tsx (2)

77-77: Remove commented code.

Remove the commented ConsentCustomizationDialog line. If it's needed later, it can be retrieved from version control.

-            {/* <ConsentCustomizationDialog /> */}

55-55: Move GDPR configuration to a separate file.

The initialGdprTypes should be moved to a configuration file for better maintainability and reusability.

Create a new file config/consent-manager.ts:

export const consentManagerConfig = {
  initialGdprTypes: ["necessary", "measurement"] as const
};
apps/www/components/footer/footer.tsx (1)

8-20: Improve NavLink type definition.

The NavLink type could be improved using discriminated union with a 'type' field for better type safety.

type BaseNavLink = {
  title: string;
  external?: boolean;
};

type NavLink =
  | (BaseNavLink & {
      type: 'link';
      href: string;
    })
  | (BaseNavLink & {
      type: 'button';
      onClick: () => void;
    });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5eb3a8f and c3cccd2.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • apps/www/app/layout.tsx (2 hunks)
  • apps/www/components/cookie-banner.tsx (1 hunks)
  • apps/www/components/footer/footer.tsx (2 hunks)
  • apps/www/package.json (1 hunks)
  • apps/www/providers/posthog/PostHogPageView.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/www/package.json
  • apps/www/providers/posthog/PostHogPageView.tsx
🔇 Additional comments (3)
apps/www/app/layout.tsx (1)

55-80: Verify PostHogPageView respects consent settings.

Ensure that PostHogPageView component respects the user's consent preferences set through the ConsentManagerProvider.

✅ Verification successful

PostHogPageView correctly implements consent management

The component properly respects user consent preferences by checking consents.measurement before capturing any analytics events.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if PostHogPageView uses consent manager hook
ast-grep --pattern 'import { useConsentManager } from "@koroflow/elements/headless"' providers/posthog/PostHogPageView.tsx

# Check if page view tracking is conditional based on consent
ast-grep --pattern 'if ($consent) {
  $$$
  posthog.capture($$$)
  $$$
}' providers/posthog/PostHogPageView.tsx

Length of output: 408


Script:

#!/bin/bash
# Find PostHogPageView component file
fd PostHogPageView

# Search for any file containing PostHogPageView class or function definition
ast-grep --pattern 'function PostHogPageView() {
  $$$
}'

ast-grep --pattern 'const PostHogPageView = () => {
  $$$
}'

Length of output: 190


Script:

#!/bin/bash
# Read the PostHogPageView component implementation
cat apps/www/providers/posthog/PostHogPageView.tsx

# Also search for any consent-related imports or usage in the file
rg -i "consent" apps/www/providers/posthog/PostHogPageView.tsx

Length of output: 1183

apps/www/components/footer/footer.tsx (2)

46-52: Enhance button accessibility.

The button element needs proper ARIA attributes and keyboard focus styles.


62-62: Verify consent manager integration.

Ensure that the consent manager hook is properly integrated and the dialog opens correctly.

Also applies to: 123-123

✅ Verification successful

Consent manager integration verified successfully

The consent manager is properly integrated with all required components in place:

  • ConsentManagerProvider at the application root
  • Hook usage in components
  • Dialog control implementation
  • Correct GDPR configuration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if setIsPrivacyDialogOpen is used consistently
ast-grep --pattern 'setIsPrivacyDialogOpen($$$)' 

# Check if useConsentManager hook is used correctly
ast-grep --pattern 'const { $$ } = useConsentManager()'

Length of output: 8480


Script:

#!/bin/bash
# Find useConsentManager hook definition
ast-grep --pattern 'export function useConsentManager() {
  $$$
}'

# Find privacy dialog component
ast-grep --pattern 'export $$ function PrivacyDialog'

# Look for ConsentManager provider
ast-grep --pattern 'export $$ function ConsentManagerProvider'

# Find any imports of useConsentManager
rg "import.*useConsentManager"

Length of output: 437


Script:

#!/bin/bash
# Check package dependencies
fd package.json --exec cat {} | jq '.dependencies."@koroflow/elements"'

# Find ConsentManagerProvider usage
rg -A 2 "ConsentManagerProvider"

# Check if the dialog component is imported and used
rg "import.*PrivacyDialog"
rg "PrivacyDialog"

Length of output: 1185

apps/www/components/cookie-banner.tsx Show resolved Hide resolved
@@ -0,0 +1,80 @@
//@ts-nocheck
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove @ts-nocheck and fix type issues.

Using @ts-nocheck bypasses TypeScript's type checking, which could lead to runtime errors. Instead, properly type the components and fix any type issues.

-//@ts-nocheck

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
apps/www/app/layout.tsx (2)

55-56: Consider making GDPR types configurable.

The initialGdprTypes are hardcoded. Consider moving these to environment variables or configuration to make them more maintainable and environment-specific.

-      <ConsentManagerProvider initialGdprTypes={["necessary", "measurement"]}>
+      <ConsentManagerProvider initialGdprTypes={parsedEnv.INITIAL_GDPR_TYPES ?? ["necessary", "measurement"]}>

55-79: Consider extracting consent management logic.

The current implementation tightly couples consent management with the root layout. Consider creating a separate ConsentManager component that encapsulates both the provider and banner:

// components/consent/ConsentManager.tsx
export function ConsentManager({ children }: { children: React.ReactNode }) {
  return (
    <ConsentManagerProvider initialGdprTypes={parsedEnv.INITIAL_GDPR_TYPES ?? ["necessary", "measurement"]}>
      {children}
      <CookieBanner />
    </ConsentManagerProvider>
  );
}

This would simplify the root layout and make the consent management logic more maintainable and testable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c3cccd2 and 3731c2e.

📒 Files selected for processing (2)
  • apps/www/app/layout.tsx (2 hunks)
  • apps/www/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/www/package.json
🔇 Additional comments (2)
apps/www/app/layout.tsx (2)

75-76: Verify mobile responsiveness with cookie banner.

The cookie banner is placed after the footer, which might affect the mobile layout. As noted in the PR objectives, responsiveness verification was not checked off.

Please ensure:

  1. The banner doesn't obstruct important content on mobile devices
  2. All buttons remain clickable
  3. The layout remains consistent across different screen sizes

57-58: Verify PostHog tracking respects user consent.

The PostHogPageView component is rendered immediately, which might lead to tracking before user consent is obtained. Ensure that PostHog respects the consent settings from ConsentManagerProvider.

Let's check the PostHog integration:

✅ Verification successful

PostHog tracking correctly respects user consent

The implementation in PostHogPageView properly gates all tracking behind the consents.measurement flag from ConsentManagerProvider. Auto-tracking is disabled during PostHog initialization, and manual tracking only occurs when consent is granted.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for PostHog initialization and consent checks
ast-grep --pattern 'posthog.$$$' -l typescript

# Check if PostHog tracking is conditional on consent
rg -A 5 'posthog\.(capture|identify)' 

Length of output: 3076


Script:

#!/bin/bash
# Check PostHogPageView implementation
cat apps/www/providers/posthog/PostHogPageView.tsx

# Look for ConsentManagerProvider and consent management
rg -l "ConsentManagerProvider"
rg -A 5 "useConsent"

# Check PostHog initialization
rg -A 10 "posthog\.init"

Length of output: 5814

apps/www/app/layout.tsx Show resolved Hide resolved
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