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

Add preferNative option #77

Merged
merged 3 commits into from
Jul 26, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ function Title() {

- **`as`** (_optional_): The HTML tag to be used to wrap the text content. Default to `span`.
- **`ratio`** (_optional_): The ratio of “balance-ness”, 0 <= ratio <= 1. Default to `1`.
- **`preferNative`** (_optional_): An option to skip the re-balance logic and use the native CSS text-balancing if supported. Default to `true`.
- **`nonce`** (_optional_): The [nonce](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) attribute to allowlist inline script injection by the component.

### `<Provider>`
Expand Down
43 changes: 33 additions & 10 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,12 @@ interface BalancerOwnProps<
* @default 1
*/
ratio?: number
/**
* An option to skip the re-balance logic
* and use the native CSS text-balancing if supported.
* @default true
*/
preferNative?: boolean
/**
* The nonce attribute to allowlist inline script injection by the component.
*/
Expand All @@ -145,16 +151,31 @@ type BalancerProps<ElementType extends React.ElementType> =
* An optional provider to inject the global relayout function, so all children
* Balancer components can share it.
*/
const BalancerContext = React.createContext<boolean>(false)
const BalancerContext = React.createContext<{
preferNative: boolean
hasProvider: boolean
}>({ preferNative: true, hasProvider: false })
const Provider: React.FC<{
/**
* An option to skip the re-balance logic
* and use the native CSS text-balancing if supported.
* @default true
*/
preferNative?: boolean
/**
* The nonce attribute to allowlist inline script injection by the component
*/
nonce?: string
children?: React.ReactNode
}> = ({ nonce, children }) => {
}> = ({ preferNative = true, nonce, children }) => {
const contextValue = React.useMemo(() => {
return {
preferNative,
hasProvider: true,
}
}, [preferNative])
return (
<BalancerContext.Provider value={true}>
<BalancerContext.Provider value={contextValue}>
{createScriptElement(false, nonce)}
{children}
</BalancerContext.Provider>
Expand All @@ -163,30 +184,32 @@ const Provider: React.FC<{

const Balancer = <ElementType extends React.ElementType = React.ElementType>({
ratio = 1,
preferNative = true,
nonce,
children,
...props
}: BalancerProps<ElementType>) => {
const id = useId()
const wrapperRef = React.useRef<WrapperElement>()
const hasProvider = React.useContext(BalancerContext)
const contextValue = React.useContext(BalancerContext)
const preferNativeBalancing = preferNative && contextValue.preferNative
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hey @shuding,
Should Balancer be able to override the preferNative context value when the provider passes false? It seems to me overriding the true value from context is more likely to happen, as the case mentioned in #75 🤔 So, it only allows overriding preferNative: true for now. What are your thoughts on this? Thanks!

Copy link
Owner

Choose a reason for hiding this comment

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

Yes I think it should be able to override. Maybe we can extend this context to be an array or an object to contain more information if necessary.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated Balancer in b9ceaa1.

If preferNative is not provided to Balancer, the ?? operator will take the value from the context, which defaults to true in createContext and in Provider. So when preferNative is explicitly provided, it can override.

@@ -184,7 +184,7 @@ const Provider: React.FC<{

 const Balancer = <ElementType extends React.ElementType = React.ElementType>({
   ratio = 1,
-  preferNative = true,
+  preferNative,
   nonce,
   children,
   ...props
@@ -192,7 +192,7 @@ const Balancer = <ElementType extends React.ElementType = React.ElementType>({
   const id = useId()
   const wrapperRef = React.useRef<WrapperElement>()
   const contextValue = React.useContext(BalancerContext)
-  const preferNativeBalancing = preferNative && contextValue.preferNative
+  const preferNativeBalancing = preferNative ?? contextValue.preferNative
   const Wrapper: React.ElementType = props.as || 'span'

const Wrapper: React.ElementType = props.as || 'span'

// Re-balance on content change and on mount/hydration.
useIsomorphicLayoutEffect(() => {
// Skip if the browser supports text-balancing natively.
if (self[SYMBOL_NATIVE_KEY] === 1) return
if (preferNativeBalancing && self[SYMBOL_NATIVE_KEY] === 1) return

if (wrapperRef.current) {
// Re-assign the function here as the component can be dynamically rendered, and script tag won't work in that case.
;(self[SYMBOL_KEY] = relayout)(0, ratio, wrapperRef.current)
}
}, [children, ratio])
}, [children, preferNativeBalancing, ratio])

// Remove the observer when unmounting.
useIsomorphicLayoutEffect(() => {
// Skip if the browser supports text-balancing natively.
if (self[SYMBOL_NATIVE_KEY] === 1) return
if (preferNativeBalancing && self[SYMBOL_NATIVE_KEY] === 1) return

return () => {
if (!wrapperRef.current) return
Expand All @@ -197,7 +220,7 @@ const Balancer = <ElementType extends React.ElementType = React.ElementType>({
resizeObserver.disconnect()
delete wrapperRef.current[SYMBOL_OBSERVER_KEY]
}
}, [])
}, [preferNativeBalancing])

if (process.env.NODE_ENV === 'development') {
// In development, we check `children`'s type to ensure we are not wrapping
Expand Down Expand Up @@ -232,14 +255,14 @@ To:
display: 'inline-block',
verticalAlign: 'top',
textDecoration: 'inherit',
textWrap: 'balance',
textWrap: preferNative ? 'balance' : 'initial',
}}
suppressHydrationWarning
>
{children}
</Wrapper>
{createScriptElement(
hasProvider,
contextValue.hasProvider,
nonce,
`self.${SYMBOL_KEY}("${id}",${ratio})`
)}
Expand Down
9 changes: 6 additions & 3 deletions website/src/sections/CustomBalanceRatio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,13 @@ export default function CustomBalanceRatio() {
</Balancer>
</h2>
<h2 className='ratio-title'>
<Balancer ratio={currentRatio}>
<Balancer ratio={currentRatio} preferNative={false}>
The quick brown fox jumps over the lazy dog
</Balancer>
</h2>
<code>{`<Balancer ratio={${ratio.toFixed(2)}}>`}</code>
<code>{`<Balancer ratio={${ratio.toFixed(
2
)}} preferNative={false}>`}</code>
</div>
</div>
</div>
Expand Down Expand Up @@ -88,7 +90,8 @@ export default function CustomBalanceRatio() {
text-wrap: balance
</BlankLink>
) is available, React Wrap Balancer will use it instead. And the `ratio`
option will be ignored in that case.
option will be ignored in that case. You can provide the `preferNative`
option to opt out.
</p>
</>
)
Expand Down