Skip to content

fix: styling fixes#4279

Merged
pandeymangg merged 9 commits intomainfrom
survey-editor-fixes
Nov 13, 2024
Merged

fix: styling fixes#4279
pandeymangg merged 9 commits intomainfrom
survey-editor-fixes

Conversation

@Dhruwang
Copy link
Member

@Dhruwang Dhruwang commented Nov 11, 2024

What does this PR do?

Fixes #4265
Fixes #4272

How should this be tested?

Test issues tagged above

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read How we Code at Formbricks
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand bits
  • Ran pnpm build
  • 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
  • First PR at Formbricks? Please sign the CLA! Without it we wont be able to merge it 🙏

Appreciated

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Updated default card arrangement settings for surveys to enhance user experience.
    • Improved internationalization for the loading component, allowing dynamic translations based on user locale.
    • Enhanced card abandonment survey with new questions to gather targeted user feedback.
  • Bug Fixes

    • Simplified logic for styling defaults in the survey editor, ensuring more straightforward configuration.
  • Documentation

    • Updated localization files to include new survey questions and options in multiple languages (German, English, Portuguese).
  • Chores

    • Cleaned up unused imports and optimized function signatures for better performance.

@vercel
Copy link

vercel bot commented Nov 11, 2024

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

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
formbricks-cloud ⬜️ Ignored (Inspect) Visit Preview Nov 13, 2024 9:42am
formbricks-docs ⬜️ Ignored (Inspect) Visit Preview Nov 13, 2024 9:42am

@Dhruwang Dhruwang requested a review from pandeymangg November 11, 2024 11:00
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on updating default values for card arrangements in the survey editor and simplifying the logic for determining styling defaults. Key modifications include setting default card arrangements to "straight," removing complex logic for styling defaults, and enhancing localization for card abandonment surveys. Additionally, the Loading component has been updated for better internationalization, and various localization files have been modified to include new survey questions and options.

Changes

File Change Summary
apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/CardStylingSettings.tsx Updated default values for linkCardArrangement and appCardArrangement from "simple" to "straight".
apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/StylingView.tsx Removed complex logic for stylingDefaults; directly set defaultValues to localSurvey.styling or product.styling.
apps/web/app/(app)/environments/[environmentId]/product/look/components/ThemeStyling.tsx Updated default values for linkSurveys and appSurveys from "simple" to "straight"; modified onReset function accordingly.
apps/web/app/(app)/environments/[environmentId]/product/look/loading.tsx Localized static text strings using useTranslations for improved internationalization.
packages/lib/styling/constants.ts Removed unused import for getDefaultEndingCard; modified endings property to directly include a static object.
packages/surveys/src/lib/styles.ts Updated appendCssVariable function signature to accept undefined implicitly.
packages/lib/messages/de-DE.json Added new questions and options for card abandonment survey; removed old questions.
packages/lib/messages/en-US.json Enhanced "card_abandonment_survey" section with new questions and options, removed old questions.
packages/lib/messages/pt-BR.json Similar modifications as in en-US.json, focusing on card abandonment survey updates.
packages/lib/templates.ts Updated question headlines and labels in cartAbandonmentSurvey function for correct referencing.

Assessment against linked issues

Objective Addressed Explanation
Ensure survey preview remains stable when interacting with cards (4265) Changes do not directly address the stability issue during card interactions.
Maintain current styling as default when custom styles are toggled (4272) Default values for card arrangements have been updated to ensure expected behavior.

Possibly related PRs

Suggested labels

enhancement, 🕹️ oss.gg, 🕹️ 150 points

Suggested reviewers

  • jobenjada

Warning

Rate limit exceeded

@Dhruwang has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 41 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 75bcf34 and 84fc804.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 75bcf34 and 84fc804.

📒 Files selected for processing (1)
  • apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/StylingView.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/StylingView.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions
Copy link
Contributor

github-actions bot commented Nov 11, 2024

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

@github-actions github-actions bot added the bug Something isn't working label Nov 11, 2024
@Dhruwang Dhruwang changed the title styling fixes fix: styling fixes Nov 11, 2024
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

🧹 Outside diff range and nitpick comments (8)
packages/types/styling.ts (1)

5-5: Consider documenting the nullish value handling strategy.

The introduction of nullish values across styling schemas provides more flexibility but also increases complexity in how undefined states should be handled. Consider adding documentation about:

  1. When nullish values are expected/allowed
  2. How they should be handled in the UI
  3. Default value fallback strategy

Also applies to: 14-15

packages/ui/components/PreviewSurvey/components/Modal.tsx (2)

Line range hint 127-151: Consider strengthening modal visibility management.

Given the reported issue #4265 about survey preview disappearing, the visibility management logic could be improved. While the current implementation handles basic show/hide states, it might benefit from additional safeguards.

Consider these improvements:

 useEffect(() => {
+  let timeoutId: NodeJS.Timeout;
   if (!clickOutsideClose || placement !== "center") return;
   const handleClickOutside = (e: MouseEvent) => {
     const previewBase = document.getElementById("preview-survey-base");

     if (
       clickOutsideClose &&
       modalRef.current &&
       previewBase &&
       previewBase.contains(e.target as Node) &&
       !modalRef.current.contains(e.target as Node)
     ) {
       setShow(false);
-      setTimeout(() => {
+      timeoutId = setTimeout(() => {
         setShow(true);
       }, 1000);
     }
   };

   document.addEventListener("mousedown", handleClickOutside);
   return () => {
     document.removeEventListener("mousedown", handleClickOutside);
+    if (timeoutId) clearTimeout(timeoutId);
   };
 }, [clickOutsideClose, placement]);

Additionally, consider adding a state guard:

 useEffect(() => {
+  if (!isOpen) return;
   if (modalRef.current) {
     modalRef.current.scrollTop = 0;
   }
 }, [children]);

Line range hint 152-190: Enhance style handling robustness.

The style application logic could be made more robust to prevent potential rendering issues.

Consider this improvement:

 style={{
   ...scalingClasses,
-  ...(borderRadius && {
+  ...(typeof borderRadius === 'number' && {
     borderRadius: `${borderRadius}px`,
   }),
-  ...(background && {
+  ...(background !== null && background !== undefined && {
     background,
   }),
 }}
packages/surveys/src/lib/styles.ts (1)

Line range hint 36-124: Consider refactoring color manipulation logic for better maintainability.

The code contains repeated patterns for color mixing and lightness checks. Consider extracting these into helper functions to improve maintainability and reduce duplication.

Consider creating these helper functions:

const getTextColorForBackground = (bgColor: string) => 
  isLight(bgColor) ? "black" : "white";

const getMixedColor = (baseColor: string, mixWith: string, opacity: number) => 
  mixColor(baseColor, mixWith, opacity);

const getContrastColors = (baseColor: string) => ({
  signature: isLight(baseColor) 
    ? mixColor(baseColor, "#000000", 0.2)
    : mixColor(baseColor, "#ffffff", 0.2),
  branding: isLight(baseColor)
    ? mixColor(baseColor, "#000000", 0.3)
    : mixColor(baseColor, "#ffffff", 0.3)
});

This would simplify the main code and make it easier to maintain consistent color calculations throughout the application.

apps/web/app/(app)/environments/[environmentId]/product/look/loading.tsx (1)

Line range hint 1-185: Consider enhancing loading state feedback.

While the loading component provides a good skeleton UI, consider adding aria-labels or status messages for screen readers to improve accessibility. Additionally, the loading state could benefit from progressive loading indicators to better communicate the loading progress to users.

Example enhancement:

 <PageContentWrapper>
+  <div role="status" aria-live="polite" className="sr-only">
+    {t("common.loading_styling_page")}
+  </div>
   <PageHeader pageTitle={t("common.configuration")}>
apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/StylingView.tsx (3)

Line range hint 126-171: Consider refactoring the styling toggle logic for better maintainability.

The handleOverwriteToggle function handles multiple state updates and complex conditional logic. This makes it harder to track state changes and could lead to inconsistencies.

Consider breaking it down into smaller, focused functions:

const handleStylingToggleOn = () => {
  if (!styling) {
    setStyling({
      ...defaultProductStyling,
      overwriteThemeStyling: true,
    });
    return;
  }

  setStyling(localStylingChanges ?? {
    ...defaultProductStyling,
    overwriteThemeStyling: true,
  });
};

const handleStylingToggleOff = () => {
  setLocalStylingChanges(styling);
  setStyling({
    ...defaultProductStyling,
    overwriteThemeStyling: false,
  });
};

const handleOverwriteToggle = (value: boolean) => {
  setOverwriteThemeStyling(value);
  value ? handleStylingToggleOn() : handleStylingToggleOff();
};

Line range hint 87-98: Add error handling for theme reset operation.

The onResetThemeStyling function performs multiple state updates without error handling. If any of these operations fail, it could leave the styling in an inconsistent state.

Consider wrapping the operations in a try-catch block:

const onResetThemeStyling = async () => {
  try {
    const { styling: productStyling } = product;
    const { allowStyleOverwrite, ...baseStyling } = productStyling ?? {};

    await Promise.all([
      setStyling({
        ...baseStyling,
        overwriteThemeStyling: true,
      }),
      form.reset({
        ...baseStyling,
        overwriteThemeStyling: true,
      })
    ]);

    setConfirmResetStylingModalOpen(false);
    toast.success(t("environments.surveys.edit.styling_set_to_theme_styles"));
  } catch (error) {
    toast.error(t("common.error_saving_changes"));
    // Consider logging the error
  }
};

Line range hint 102-108: Add cleanup logic for form state.

The useEffect hook that handles card states doesn't clean up form state when overwriteThemeStyling is disabled. This could lead to stale form values when re-enabling styling.

Consider resetting form values:

useEffect(() => {
  if (!overwriteThemeStyling) {
    setFormStylingOpen(false);
    setCardStylingOpen(false);
    setStylingOpen(false);
    // Reset form values to prevent stale state
    form.reset(product.styling);
  }
}, [overwriteThemeStyling, product.styling, form]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d094f63 and 2adf35b.

📒 Files selected for processing (8)
  • apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/CardStylingSettings.tsx (1 hunks)
  • apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/StylingView.tsx (1 hunks)
  • apps/web/app/(app)/environments/[environmentId]/product/look/components/ThemeStyling.tsx (2 hunks)
  • apps/web/app/(app)/environments/[environmentId]/product/look/loading.tsx (1 hunks)
  • packages/lib/styling/constants.ts (2 hunks)
  • packages/surveys/src/lib/styles.ts (1 hunks)
  • packages/types/styling.ts (2 hunks)
  • packages/ui/components/PreviewSurvey/components/Modal.tsx (1 hunks)
🔇 Additional comments (14)
packages/types/styling.ts (2)

14-15: Verify the impact of nullish card arrangements.

The schema changes appropriately allow for nullable card arrangement options. However, given the AI summary's mention of default value changes from "simple" to "straight", we should verify the migration path.

Let's check the usage and default values across the codebase:

#!/bin/bash
# Search for card arrangement default value assignments
rg -A 2 "linkSurveys:|appSurveys:" --type ts

# Search for direct usage of these properties
ast-grep --pattern 'cardArrangement.$_(linkSurveys|appSurveys)'

5-5: LGTM! Verify the impact of nullable light color.

The schema change to allow nullish values for the light color property is consistent with the existing pattern for dark colors.

Let's verify how this property is used in the codebase:

✅ Verification successful

Let's search specifically for usage of the light property to understand its impact.


LGTM! The light color property is safely handled throughout the codebase.

The search results show that all usages of the .light property are properly guarded with optional chaining and fallback to default values using the nullish coalescing operator (??). This pattern is consistently applied across:

  • Email preview components
  • Survey preview components
  • Theme styling components
  • Form styling settings
  • API routes
  • Style generation utilities

The schema change aligns perfectly with the existing codebase implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct usage of the light property in styling colors
rg -l "\.light\b" --type ts

Length of output: 1239


Script:

#!/bin/bash
# Search for direct usage of the light property in styling colors
rg -A 2 "\.light\b" --type ts

Length of output: 20020

packages/lib/styling/constants.ts (2)

1-4: LGTM! Simplified import structure

The removal of the getDefaultEndingCard import in favor of direct implementation reduces complexity and provides better control over the ending card behavior.


103-112: Verify the hardcoded values in the endings configuration

The implementation looks good and should help with the survey preview stability issues. However, there are a few points to consider:

  1. The hardcoded buttonLink "https://formbricks.com" might not be appropriate for all use cases
  2. The hardcoded id "cltyqp5ng000108l9dmxw6nde" could potentially cause conflicts

Let's verify if these values should be configurable:

Consider making these values configurable through parameters:

-    endings: [
-      {
-        id: "cltyqp5ng000108l9dmxw6nde",
-        type: "endScreen",
-        headline: { default: translate("default_ending_card_headline", locale) },
-        subheader: { default: translate("default_ending_card_subheader", locale) },
-        buttonLabel: { default: translate("default_ending_card_button_label", locale) },
-        buttonLink: "https://formbricks.com",
-      },
-    ],
+    endings: [
+      {
+        id: crypto.randomUUID(),
+        type: "endScreen",
+        headline: { default: translate("default_ending_card_headline", locale) },
+        subheader: { default: translate("default_ending_card_subheader", locale) },
+        buttonLabel: { default: translate("default_ending_card_button_label", locale) },
+        buttonLink: process.env.NEXT_PUBLIC_DEFAULT_THANK_YOU_URL || "https://formbricks.com",
+      },
+    ],
packages/ui/components/PreviewSurvey/components/Modal.tsx (1)

16-16: Type change looks good but verify the impact.

The change to allow explicit null values for background is a good defensive programming practice.

Let's verify how this property is used across the codebase:

✅ Verification successful

Making background prop nullable is safe and correctly implemented

The verification shows that:

  1. The background prop is properly used in the Modal component implementation (lines 148-150)
  2. It's only used conditionally when a value is provided, with proper null checks
  3. The component is used in ThemeStylingPreviewSurvey where theme customization is expected
  4. The implementation follows React best practices for optional styling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Modal component usage with background prop
rg -A 2 '<Modal.*background=' 

Length of output: 31


Script:

#!/bin/bash
# Let's try a broader search for Modal component usage and its imports
rg -l "Modal" --type typescript --type tsx

# Then let's look for any usage of background prop in these files
rg "background.*?=" --type typescript --type tsx

# Also search for the Modal component definition
ast-grep --pattern 'interface ModalProps {
  $$$
}'

Length of output: 2596


Script:

#!/bin/bash
# Let's look at the implementation of PreviewSurvey Modal to see how background is used
ast-grep --pattern 'const Modal = ({ $$$, background, $$$ }: ModalProps) => {
  $$$
}'

# Also search for any usage of this specific Modal component
rg -B2 -A2 "from.*PreviewSurvey.*Modal"

Length of output: 13539

packages/surveys/src/lib/styles.ts (1)

36-39: Verify styling behavior in survey preview.

Given the reported issue #4265 about survey preview disappearing, please verify that this change doesn't affect the styling behavior when properties are set to null. Pay special attention to:

  1. Survey preview interactions
  2. Style application when opening/closing cards
  3. Console errors related to CSS variables

Run the following script to check for potential null value assignments in styling-related files:

✅ Verification successful

Let me gather more information about the styling system and its usage to better understand the impact.


Based on the analysis of the code, I can now generate the final response:

CSS variable handling is safe and working as intended

The change to appendCssVariable is correct and safe because:

  1. The function is used consistently throughout the styling system to set CSS variables with proper fallbacks
  2. All CSS variables have default values in global.css
  3. The undefined check prevents invalid CSS variable declarations
  4. The styling system properly handles null values by not setting the variable, allowing the default values to take effect

The survey preview disappearing issue (#4265) is unlikely to be related to this change since:

  • The styling system has a robust fallback mechanism
  • CSS variables are properly scoped with the fb- prefix
  • Default values are always available in global.css
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for potential null assignments to styling properties

# Look for direct null assignments to style properties
echo "Checking for null style assignments..."
rg -g '*.{ts,tsx}' '(?i)style.*=.*null'

# Look for potential null values in styling objects
echo "Checking styling object definitions..."
ast-grep --pattern 'styling: {
  $$$
  $_: null,
  $$$
}'

Length of output: 275


Script:

#!/bin/bash
# Search for usage of appendCssVariable function and related styling patterns
echo "Checking appendCssVariable usage..."
rg -A 3 "appendCssVariable\(" 

echo -e "\nChecking style-related files for null handling..."
fd -e ts -e tsx -H | xargs rg "null.*style|style.*null" -l

echo -e "\nChecking for CSS variable definitions and usage..."
rg "fb-" -A 2 -g "*.{ts,tsx,css,scss}"

Length of output: 106092

apps/web/app/(app)/environments/[environmentId]/product/look/loading.tsx (2)

31-31: LGTM! Translation keys properly implemented.

The hardcoded strings have been correctly replaced with translation keys using the useTranslations hook.

Also applies to: 33-33


Line range hint 1-185: Note: This component is not related to the reported survey preview bug.

The reported bug in issue #4265 about the survey preview disappearing when interacting with cards is not related to this loading component, as this only handles the initial loading state. The issue should be investigated in the main survey preview component.

Let's verify the actual component handling the survey preview:

apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/StylingView.tsx (1)

55-55: ⚠️ Potential issue

Verify the robustness of default values handling.

The simplified default values logic might not handle all edge cases, particularly when switching between styling states. This could be related to the reported issue where the survey preview disappears when opening/closing cards.

Consider adding defensive fallbacks:

-    defaultValues: localSurvey.styling ?? product.styling,
+    defaultValues: localSurvey.styling ?? product.styling ?? {
+      // Provide essential fallback values
+      overwriteThemeStyling: false,
+      // Add other necessary styling defaults
+    },

Let's verify the styling state transitions:

apps/web/app/(app)/environments/[environmentId]/product/look/components/ThemeStyling.tsx (3)

122-123: Confirm reset values match product defaults.

The reset function's default values are consistent with the form's default values, which is good. However, we should verify that these values align with the product's default styling configuration.

#!/bin/bash
# Search for other instances of default styling configuration
ast-grep --pattern 'const $_ = {
  $$$
  cardArrangement: {
    $$$
  }
  $$$
}'

75-76: Verify fix for survey preview disappearing issue.

The change to "straight" card arrangement might be related to issue #4265 where the survey preview disappears when interacting with cards. Please verify:

  1. The preview remains visible after reaching the Thank You page
  2. Opening/closing cards doesn't cause the preview to disappear
  3. The sticky positioning of the preview works correctly
#!/bin/bash
# Look for related preview visibility issues or fixes
rg -A 5 "sticky|preview|ThemeStylingPreviewSurvey" --type typescript

# Check for any z-index or positioning styles that might affect visibility
rg "z-index|absolute|relative|sticky" --type css --type typescript

Also applies to: 122-123


75-76: Verify the impact of changing default card arrangement.

The change from "simple" to "straight" for both linkSurveys and appSurveys default values could affect the display of existing surveys. Please ensure this change is intentional and backwards compatible.

✅ Verification successful

Based on the search results, I can now generate a final response:

Default card arrangement change is safe and intentional

The change from "simple" to "straight" as the default card arrangement is consistent with the codebase:

  • All survey components use "straight" as the fallback value when cardArrangement is not specified
  • The "simple" arrangement is only referenced in conditional UI styling and is not a default anywhere
  • The change aligns with the existing card arrangement options ("straight", "casual") used throughout the codebase
  • The reset functionality in ThemeStyling.tsx correctly mirrors these defaults
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any hardcoded "simple" values that might need updating
rg -i "simple.*cardArrangement|cardArrangement.*simple" --type typescript

# Look for any migration scripts that might be needed
fd -e ts -e js --full-path "migration|migrate" -x grep -l "cardArrangement"

Length of output: 303


Script:

#!/bin/bash
# Search for cardArrangement usage across the codebase
rg "cardArrangement" -A 3 -B 3

# Search for any references to "simple" or "straight" in relation to surveys or card styling
rg "(simple|straight).*(survey|card)" -A 2 -B 2

# Look for any type definitions or interfaces related to card arrangement
ast-grep --pattern 'interface $_ {
  $$$
  cardArrangement
  $$$
}'

Length of output: 20670

apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/CardStylingSettings.tsx (2)

44-45: LGTM, but verify impact on existing surveys.

The use of nullish coalescing with "straight" as the default value is a good practice. However, since this changes the default card arrangement behavior, we should verify the impact.

Let's check for any existing surveys that might be affected:

✅ Verification successful

Default card arrangement value is safe and consistent with the codebase

The code changes are verified to be correct and safe because:

  1. The "straight" default value is a valid option defined in ZCardArrangementOptions enum ("casual" | "straight" | "simple")
  2. The StackedCardsContainer component properly handles all arrangement options, including "straight"
  3. The nullish coalescing pattern matches the schema definition in ZCardArrangement where both linkSurveys and appSurveys are defined as nullish()
  4. The CardArrangementTabs component supports all three options with proper icons and translations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing card arrangement configurations
rg -A 5 'cardArrangement' --type ts --type tsx

Length of output: 74


Script:

#!/bin/bash
# Search for existing card arrangement configurations with ripgrep
# Note: Using --type typescript to include both .ts and .tsx files
rg -A 5 'cardArrangement' --type typescript

Length of output: 78


Script:

#!/bin/bash
# Find all TypeScript/TSX files that might contain card arrangement logic
fd -e ts -e tsx | xargs rg -l 'cardArrangement'

Length of output: 623


Script:

#!/bin/bash
# Search for any schema or type definitions related to card arrangement
rg -A 5 'cardArrangement|CardArrangement' --type typescript

Length of output: 96


Script:

#!/bin/bash
# Look for form schema definitions that might define card arrangement
ast-grep --pattern 'const $_ = z.object({
  $$$
  cardArrangement: $$$
  $$$
})'

Length of output: 1196


Script:

#!/bin/bash
# Let's check the definition of ZCardArrangement and its usage
rg -p 'ZCardArrangement' packages/types/styling.ts

# Also check the actual content of CardArrangementTabs component
cat packages/ui/components/CardArrangementTabs/index.tsx

# And check the StackedCardsContainer implementation
cat packages/ui/components/StackedCardsContainer/index.tsx

Length of output: 5038


44-45: Additional investigation needed for survey preview bug.

While standardizing card arrangements is a good improvement, the core issue from #4265 (survey preview disappearing when cards are opened/closed on Thank You page) might require additional investigation into card state management. Consider:

  1. Adding state logging for card open/close events
  2. Investigating component lifecycle on the Thank You page
  3. Adding error boundaries to prevent survey disappearance

Let's check for related state management code:

Comment on lines 36 to 39
const appendCssVariable = (variableName: string, value?: string | null) => {
if (value !== undefined) {
cssVariables += `--fb-${variableName}: ${value};\n`;
}
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

Consider handling null values consistently with undefined values.

The current implementation only filters out undefined values but allows null values to be set as CSS variables. This could lead to unexpected styling issues since "null" would be set as the CSS variable value.

Apply this diff to handle both null and undefined values consistently:

-  const appendCssVariable = (variableName: string, value?: string | null) => {
-    if (value !== undefined) {
+  const appendCssVariable = (variableName: string, value?: string | null) => {
+    if (value !== undefined && value !== null) {
       cssVariables += `--fb-${variableName}: ${value};\n`;
     }
   };
📝 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 appendCssVariable = (variableName: string, value?: string | null) => {
if (value !== undefined) {
cssVariables += `--fb-${variableName}: ${value};\n`;
}
const appendCssVariable = (variableName: string, value?: string | null) => {
if (value !== undefined && value !== null) {
cssVariables += `--fb-${variableName}: ${value};\n`;
}

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

🧹 Outside diff range and nitpick comments (3)
apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/StylingView.tsx (1)

97-102: Improved state management for styling updates.

Using form.getValues() instead of watchedValues provides more reliable state updates, which could help prevent the survey preview disappearance issue (#4265). However, consider adding error boundaries to handle potential state update failures gracefully.

Consider wrapping the state update in a try-catch block:

-    const newValues = form.getValues();
-    setLocalSurvey((prev) => ({
-      ...prev,
-      styling: {
-        ...prev.styling,
-        ...newValues,
-      },
-    }));
+    try {
+      const newValues = form.getValues();
+      setLocalSurvey((prev) => ({
+        ...prev,
+        styling: {
+          ...prev.styling,
+          ...newValues,
+        },
+      }));
+    } catch (error) {
+      console.error('Failed to update survey styling:', error);
+      toast.error(t('environments.surveys.edit.styling_update_failed'));
+    }
packages/lib/messages/en-US.json (2)

1938-1941: Consider making the initial prompt more specific and action-oriented.

The initial prompt is clear but could be more engaging and specific about the value proposition.

Consider this alternative wording:

-    "card_abandonment_survey_question_1_button_label": "Sure!",
-    "card_abandonment_survey_question_1_dismiss_button_label": "No, thanks.",
-    "card_abandonment_survey_question_1_headline": "Do you have 2 minutes to help us improve?",
-    "card_abandonment_survey_question_1_html": "<p class=\"fb-editor-paragraph\" dir=\"ltr\"><span>We noticed you left some items in your cart. We would love to understand why.</span></p>",
+    "card_abandonment_survey_question_1_button_label": "Help improve",
+    "card_abandonment_survey_question_1_dismiss_button_label": "Not now",
+    "card_abandonment_survey_question_1_headline": "Help us improve your shopping experience",
+    "card_abandonment_survey_question_1_html": "<p class=\"fb-editor-paragraph\" dir=\"ltr\"><span>We noticed you left items in your cart. Your quick feedback will help us make shopping easier for you.</span></p>",

1948-1965: Consider adding more context to some follow-up questions.

The follow-up questions are good but some could benefit from more context to encourage detailed responses.

Consider these improvements:

-    "card_abandonment_survey_question_3_headline": "Please elaborate on your reason for not completing the purchase:",
+    "card_abandonment_survey_question_3_headline": "Could you tell us more about what specifically prevented you from completing your purchase?",

-    "card_abandonment_survey_question_8_headline": "Any additional comments or suggestions?",
+    "card_abandonment_survey_question_8_headline": "What else could we do to improve your shopping experience?",
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2adf35b and 8072b4e.

📒 Files selected for processing (6)
  • apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/StylingView.tsx (2 hunks)
  • packages/lib/messages/de-DE.json (1 hunks)
  • packages/lib/messages/en-US.json (1 hunks)
  • packages/lib/messages/pt-BR.json (1 hunks)
  • packages/lib/templates.ts (5 hunks)
  • packages/surveys/src/lib/styles.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/surveys/src/lib/styles.ts
🔇 Additional comments (7)
apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/StylingView.tsx (2)

55-55: Simplified styling defaults address unexpected style changes.

The simplified form initialization using nullish coalescing operator should fix issue #4272 where card styling changed unexpectedly when toggling custom styles. The direct assignment ensures that either the survey's styling or product styling is used without complex intermediate calculations.

Let's verify the fix for issue #4272:

✅ Verification successful

Styling default simplification verified without remaining complex calculations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining complex styling calculations or defaults
rg -A 5 "stylingDefaults|defaultStyling" --type typescript

# Look for any other components that might affect styling initialization
ast-grep --pattern 'useForm<$_>({
  defaultValues: $_
})'

Length of output: 1307


Script:

#!/bin/bash
# Search for any remaining complex styling calculations or defaults in TypeScript files
rg -A 5 "stylingDefaults|defaultStyling" --glob "*.ts"

# Look for any other components that might affect styling initialization
ast-grep --pattern 'useForm<$_>({
  defaultValues: $_
})'

Length of output: 1268


97-102: Additional verification needed for survey preview persistence.

While the improved state management helps, issue #4265 specifically mentions survey preview disappearance after reaching the Thank You page. Consider adding specific handling for the Thank You page state.

Let's search for Thank You page related code:

Consider implementing these architectural improvements:

  1. Add a dedicated state for tracking the Thank You page visibility
  2. Implement a preview persistence mechanism that maintains the survey state across page transitions
  3. Add error boundaries around the preview component to prevent complete disappearance
packages/lib/messages/en-US.json (1)

1942-1947: LGTM! Comprehensive list of abandonment reasons.

The multiple choice options cover the most common cart abandonment reasons and are clearly worded.

packages/lib/messages/pt-BR.json (2)

1938-1965: LGTM! Card abandonment survey translations are complete and accurate.

The new translations for the card abandonment survey questions are well-structured and maintain consistency with the platform's tone and style. The translations are natural and appropriate for Brazilian Portuguese speakers.


Line range hint 1-2500: Translations are consistent with documented changes.

The changes in the file perfectly match the additions and removals listed in the AI-generated summary. All the required translations have been properly implemented.

packages/lib/messages/de-DE.json (2)

1938-1965: LGTM! The new card abandonment survey translations are well-structured and complete.

The translations:

  • Follow consistent terminology
  • Maintain proper formatting
  • Cover all required survey questions and options
  • Use natural German language that flows well

Line range hint 1-2500: Overall file structure and formatting looks good!

The JSON structure is well-organized with:

  • Clear hierarchical organization
  • Consistent indentation
  • Proper nesting of translation keys
  • No duplicate keys detected

Comment on lines +110 to +115
headline: { default: translate("card_abandonment_survey_question_1_headline", locale) },
required: false,
buttonLabel: { default: translate("card_abandonment_survey_question_2_button_label", locale) },
buttonLabel: { default: translate("card_abandonment_survey_question_1_button_label", locale) },
buttonExternal: false,
dismissButtonLabel: {
default: translate("card_abandonment_survey_question_2_dismiss_button_label", locale),
default: translate("card_abandonment_survey_question_1_dismiss_button_label", locale),
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Old translation keys still present in localization files.

The following translation keys were not removed:

  • card_abandonment_survey_question_2_headline found in:
    • packages/lib/messages/en-US.json
    • packages/lib/messages/pt-BR.json
    • packages/lib/messages/de-DE.json
🔗 Analysis chain

Translation key updates look good!

The renumbering of question identifiers in translation keys is consistent. The changes align with the standard practice of zero-based numbering.

Let's verify that the updated translation keys exist in the localization files:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the new translation keys exist in localization files
# Test: Search for the new translation keys in all locale files. Expect: All keys should be found.

echo "Checking for new translation keys..."
for key in "card_abandonment_survey_question_1_headline" \
          "card_abandonment_survey_question_1_button_label" \
          "card_abandonment_survey_question_1_dismiss_button_label"; do
  echo "Searching for $key..."
  rg "\"$key\"" --type json
done

Length of output: 2260


Script:

#!/bin/bash
# Description: Verify that old translation keys have been removed from localization files
# Test: Search for the old translation keys in all locale files. Expect: No instances should be found.

echo "Verifying removal of old translation keys..."
for key in "card_abandonment_survey_question_2_headline" \
          "card_abandonment_survey_question_2_button_label" \
          "card_abandonment_survey_question_2_dismiss_button_label"; do
  echo "Searching for $key..."
  rg "\"$key\"" --type json
done

Length of output: 1696

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

🧹 Outside diff range and nitpick comments (2)
packages/lib/messages/en-US.json (1)

1940-1967: LGTM! Well-structured cart abandonment survey translations.

The new translation keys for the cart abandonment survey are well-organized and provide a complete user journey from initial engagement through feedback collection. The tone is professional yet approachable.

Consider these minor improvements:

  1. Add placeholder text for the open-ended questions (e.g., lines 1952, 1967) to guide users on expected input
  2. Consider adding "aria-label" translations for better accessibility
 "card_abandonment_survey_question_3_headline": "Please elaborate on your reason for not completing the purchase:",
+"card_abandonment_survey_question_3_placeholder": "E.g., shipping costs were higher than expected...",
 
 "card_abandonment_survey_question_8_headline": "Any additional comments or suggestions?",
+"card_abandonment_survey_question_8_placeholder": "Share any thoughts that could help us improve..."
packages/lib/messages/pt-BR.json (1)

Line range hint 1-3000: Consider standardizing the level of formality across translations.

There are inconsistencies in the use of formal ("você") vs informal ("tu") pronouns across different sections. Consider standardizing to "você" throughout the translations as it's more commonly used in Brazilian Portuguese.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8072b4e and 75bcf34.

📒 Files selected for processing (3)
  • packages/lib/messages/de-DE.json (1 hunks)
  • packages/lib/messages/en-US.json (1 hunks)
  • packages/lib/messages/pt-BR.json (1 hunks)
🔇 Additional comments (4)
packages/lib/messages/pt-BR.json (2)

1940-1967: Card abandonment survey translations look good!

The translations for the card abandonment survey are well-formed, natural, and maintain a consistent tone appropriate for Brazilian Portuguese speakers.


Line range hint 1-3000: File structure and formatting are well-maintained.

The JSON structure is valid, properly nested, and consistently formatted throughout the file.

packages/lib/messages/de-DE.json (2)

1940-1967: Well-crafted German translations for card abandonment survey!

The new translations for the card abandonment survey are professionally done with natural German phrasing and consistent terminology. The translations maintain a good balance between being formal yet approachable, which is appropriate for customer surveys.


Line range hint 1-1967: LGTM! Complete and consistent localization file.

The German localization file is well-maintained with:

  • Consistent translation style and terminology
  • Complete coverage of all UI elements
  • Valid JSON structure

Copy link
Contributor

@pandeymangg pandeymangg left a comment

Choose a reason for hiding this comment

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

LGTM 🚀

@pandeymangg pandeymangg added this pull request to the merge queue Nov 13, 2024
Merged via the queue into main with commit 9fd585e Nov 13, 2024
@pandeymangg pandeymangg deleted the survey-editor-fixes branch November 13, 2024 11:11
@coderabbitai coderabbitai bot mentioned this pull request Dec 5, 2024
12 tasks
This was referenced Dec 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Card styling changes as soon as custom styles are toggled on [BUG] Survey Preview on Styling page

3 participants