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

fix(IconButton): Remove useLayoutEffect to avoid SSR warning #2831

Merged
merged 3 commits into from Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 15 additions & 4 deletions packages/components/src/Button/IconButton.spec.tsx
Expand Up @@ -26,6 +26,8 @@

import 'jest-styled-components'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { ComponentsProvider } from '@looker/components-providers'
import { renderWithTheme } from '@looker/components-test-utils'
import { Favorite } from '@styled-icons/material/Favorite'
import {
Expand Down Expand Up @@ -314,13 +316,22 @@ describe('IconButton', () => {
const button = screen.getByRole('button')
expect(button).toHaveStyle({
'--ripple-color': '#71767a',
'--ripple-scale-end': '12.041594578792294',
'--ripple-scale-start': '12.041594578792294',
'--ripple-size': '30px',
'--ripple-translate': '165px, 0',
'--ripple-scale-end': '1.414',
'--ripple-scale-start': '1.414',
'--ripple-size': '100%',
'--ripple-translate': '0, 0',
Copy link
Contributor Author

Choose a reason for hiding this comment

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

A square IconButton now uses the size prop instead of a measurement to make the ripple extend to the corners.

})
/* eslint-disable-next-line @typescript-eslint/unbound-method */
Element.prototype.getBoundingClientRect = globalGetBoundingClientRect
})
})

test('No useLayoutEffect warning', () => {
// A React warning would cause the test to fail
ReactDOMServer.renderToString(
<ComponentsProvider>
<IconButton icon={<Favorite />} label="Test" />
</ComponentsProvider>
)
})
})
2 changes: 2 additions & 0 deletions packages/components/src/Button/IconButton.tsx
Expand Up @@ -35,6 +35,7 @@ import { Icon } from '../Icon'
import {
rippleHandlerKeys,
rippleStyle,
SQUARE_RIPPLE,
useRipple,
useRippleHandlers,
} from '../Ripple'
Expand Down Expand Up @@ -84,6 +85,7 @@ export const IconButton = styled(
} = useRipple({
bounded: shape === 'square',
color: toggle ? toggleColor : undefined,
size: shape === 'square' ? SQUARE_RIPPLE : 1,
})

const ref = useForkedRef(forwardedRef, rippleRef)
Expand Down
4 changes: 3 additions & 1 deletion packages/components/src/Ripple/Ripple.stories.tsx
Expand Up @@ -35,14 +35,16 @@ import { useRipple, useRippleHandlers, rippleStyle } from './'
type RippleProps = SimpleLayoutProps & UseRippleProps & { className?: string }

const Ripple = styled(
({ className, bounded, color, ...props }: RippleProps) => {
({ className, bounded, color, height, width, ...props }: RippleProps) => {
const {
callbacks,
className: rippleClassName,
...rippleProps
} = useRipple({
bounded,
color,
height,
width,
})

const rippleHandlers = useRippleHandlers(callbacks, {})
Expand Down
4 changes: 4 additions & 0 deletions packages/components/src/Ripple/constants.ts
Expand Up @@ -31,3 +31,7 @@
* for measurement or calculation.
*/
export const RIPPLE_RATIO = 1.167
/**
* The diagonal of a square, to make the ripple extend to the corners
*/
export const SQUARE_RIPPLE = 1.414
1 change: 1 addition & 0 deletions packages/components/src/Ripple/index.ts
Expand Up @@ -28,5 +28,6 @@ export * from './constants'
export * from './inputRippleColor'
export * from './rippleStyle'
export * from './types'
export * from './useBoundedRipple'
export * from './useRipple'
export * from './useRippleHandlers'
56 changes: 56 additions & 0 deletions packages/components/src/Ripple/types.ts
Expand Up @@ -24,9 +24,65 @@

*/

import type { ExtendedStatefulColor } from '@looker/design-tokens'
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Moved types from useRipple into this file.

import type { CSSProperties } from 'react'

export type RippleCallbacks = {
endBG: () => void
endFG: () => void
startBG: () => void
startFG: () => void
}

export type UseBoundedRippleProps = {
/**
* Change the color of the ripple background and foreground
* @default neutral
*/
color?: ExtendedStatefulColor
/**
* Decimal multiplier, e.g. 1.5.
* Use for unbounded ripple that needs to extend past element dimensions,
* don't use with overflow: hidden
* @default 1
*/
size?: number
}

export type UseRippleProps = UseBoundedRippleProps & {
/**
* Use for elements where the ripple disappears at the edges of
* a visible rectangle, e.g. a default Button
* @default false
*/
bounded?: boolean
/**
* Internal use only
* @private
*/
width?: number
/**
* Internal use only
* @private
*/
height?: number
}

export type UseRippleResponse = {
/**
* The start and end functions for the background and foreground
*/
callbacks: RippleCallbacks
/**
* The class names used in rippleStyle to trigger the animations
*/
className: string
/**
* ref is only used for bounded ripple, to detect element dimensions
*/
ref?: (node: HTMLElement | null) => void
/**
* style contains CSS variables to control the animation
*/
style: CSSProperties
}
35 changes: 35 additions & 0 deletions packages/components/src/Ripple/useBoundedRipple.ts
@@ -0,0 +1,35 @@
/*

MIT License

Copyright (c) 2021 Looker Data Sciences, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

*/
import { useMeasuredElement, useCallbackRef } from '../utils'
import { useRipple } from './useRipple'
import type { UseBoundedRippleProps } from './types'

export const useBoundedRipple = (props: UseBoundedRippleProps) => {
const [element, ref] = useCallbackRef()
const [{ height, width }] = useMeasuredElement(element)
Copy link

Choose a reason for hiding this comment

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

With an eye to the (not-too-distant) future do you think useMeasuredElement could be refactored to be more "defensive"? Basically just check if window exists and skip calculation if not?

I went ahead and logged a ticket to keep track of this requirement for that work: https://b.corp.google.com/issues/199953481 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think so. But in order to make that change, we should set up a test app that uses SSR. It sounds like neither useEffect nor useLayoutEffect should be used with SSR so I'm curious to see what falls apart with our components.

const result = useRipple({ ...props, bounded: true, height, width })
return { ...result, ref }
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Currently not used but will be for Button, ListItem, etc.

Expand Up @@ -24,55 +24,12 @@

*/

import type { ExtendedStatefulColor } from '@looker/design-tokens'
import type { CSSProperties } from 'react'
import { useContext } from 'react'
import { ThemeContext } from 'styled-components'
import { useMeasuredElement, useCallbackRef } from '../utils'
import type { RippleCallbacks } from './types'
import type { UseRippleProps, UseRippleResponse } from './types'
import { useRippleState } from './useRippleState'
import { useRippleStateBG } from './useRippleStateBG'

export type UseRippleProps = {
/**
* Use for elements where the ripple disappears at the edges of
* a visible rectangle, e.g. a default Button
* @default false
*/
bounded?: boolean
/**
* Change the color of the ripple background and foreground
* @default neutral
*/
color?: ExtendedStatefulColor
/**
* Decimal multiplier, e.g. 1.5.
* Use for unbounded ripple that needs to extend past element dimensions,
* don't use with overflow: hidden
* @default 1
*/
size?: number
}

export type UseRippleResponse = {
/**
* The start and end functions for the background and foreground
*/
callbacks: RippleCallbacks
/**
* The class names used in rippleStyle to trigger the animations
*/
className: string
/**
* ref is only used for bounded ripple, to detect element dimensions
*/
ref?: (node: HTMLElement | null) => void
/**
* style contains CSS variables to control the animation
*/
style: CSSProperties
}

const getMinMaxDimensions = (width: number, height: number) => {
const min = Math.min(width, height)
const max = Math.max(width, height)
Expand All @@ -88,7 +45,7 @@ const getRippleScaleRange = (
): [number, number] => {
// For squares it looks best to start the ripple very small
const start = 0.1
if (bounded) {
if (bounded && min > 0 && max > 0) {
// For rectangles it looks better to start at the size of the smaller dimension
// which is 1 because of how size is calculated
const startBounded = min === max ? start : 1
Expand Down Expand Up @@ -127,12 +84,10 @@ const getRippleOffset = (min: number, max: number, bounded?: boolean) => {
export const useRipple = ({
bounded = false,
color = 'neutral',
height = 0,
size = 1,
width = 0,
}: UseRippleProps): UseRippleResponse => {
// ref is actually only used for bounded, when dimensions are needed
// otherwise ref is wasteful since it triggers a state update & re-render
const [element, ref] = useCallbackRef()
const [{ width, height }] = useMeasuredElement(element)
// Get the theme colors to apply the right value for the color prop
// brandAnimation toggles the animation
const {
Expand Down Expand Up @@ -162,7 +117,7 @@ export const useRipple = ({
['--ripple-color' as any]: colors[color],
['--ripple-scale-end' as any]: rippleScaleRange[1] || 1,
['--ripple-scale-start' as any]: rippleScaleRange[0],
['--ripple-size' as any]: bounded ? `${min}px` : '100%',
['--ripple-size' as any]: bounded && min > 0 ? `${min}px` : '100%',
['--ripple-translate' as any]: rippleOffset,
// bounded ripple scales up larger than the container
// but should not show beyond its edges
Expand All @@ -180,8 +135,6 @@ export const useRipple = ({
},
// Props to be applied to the same element that gets rippleStyle
className: `${bgClass} ${fgClass}`,
// bounded needs to get the element size
ref: bounded ? ref : undefined,
style,
}
}