Shopify / restyle

A type-enforced system for building UI components in React Native with TypeScript.
https://shopify.github.io/restyle/
MIT License
2.86k stars 128 forks source link

Fix custom themed nested components props overwrite #241

Closed mattfrances closed 1 year ago

mattfrances commented 1 year ago

Description

Note: This was a team effort with @ElviraBurchik!

The issue When using nested components with different variant values and breakpoints, the child was receiving the parent's value. For example with the following variant, if the child had mediumPadding and the parent had noPadding, the child ended up with a padding of 'none' / 0 rather than 'm' / 8:

spacingVariant: {
            defaults: {},
            noPadding: {
              phone: 'none',
              tablet: 'none',
            },
            mediumPadding: {
              phone: 'm',
              tablet: 'm',
            }
          }

Why this happened This was happening because when memoizing properties that were objects, we were converting them to Strings resulting in a memoized hash key ending with "[object Object]". So the flow for nested components with variants was as follows:

  1. Parent's props get memoized into a hash key -> "1334x750-spacing-padding-[object Object]"
  2. The memoized has key now refers to the parent's props (in this case padding of 0)
  3. Child's props get memoized into a hash key -> "1334x750-spacing-padding-[object Object]"
  4. Since it's the same hash key as above, we return padding of 0

The fix By stringifying properties that are objects, we create unique hash keys for each case. For the example above, this would result in two separate hash keys for each variant:

  1. "1334x750-spacing-padding-{"phone":"none","tablet":"none"}"
  2. "1334x750-spacing-padding-{"phone":"m","tablet":"m"}"

As a result, we wouldn't accidentally use the parent's hash key / styles.


The comment I added in the code is quite messy, and may be inaccurate as I'm still trying to completely understand how this works. I will update the code comment once I have some reviews and the chance to better understand how this fixes the issue.

Fixes https://github.com/Shopify/restyle/issues/239

Reviewers’ hat-rack :tophat:

Screenshots or videos (if needed)

Checklist

fortmarek commented 1 year ago

I am onboard with the general direction of this PR, I will give this another thorough review once it's no longer a draft 🤞