Skip to content

Commit

Permalink
Restore deferred-mount and undo Suspense
Browse files Browse the repository at this point in the history
  • Loading branch information
pirelenito committed Nov 14, 2023
1 parent 99b03b7 commit 939711d
Show file tree
Hide file tree
Showing 12 changed files with 827 additions and 109 deletions.
1 change: 0 additions & 1 deletion packages/@react-facet/core/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,4 @@ export * from './useFacetRef'
export * from './useFacetReducer'
export * from './useFacetState'
export * from './useFacetUnwrap'
export * from './useFacetUnwrapTransition'
export * from './useFacetWrap'
36 changes: 4 additions & 32 deletions packages/@react-facet/core/src/hooks/useFacetUnwrap.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React, { Suspense } from 'react'
import React from 'react'
import { render, act } from '@react-facet/dom-fiber-testing-library'
import { useFacetUnwrap } from './useFacetUnwrap'
import { createFacet } from '../facet'
import { asPromise } from '../helpers'
import { NO_VALUE } from '../types'
import { NO_VALUE } from '..'

describe('when mounting facets with values', () => {
it('renders only once for Immutable value of type string', () => {
Expand Down Expand Up @@ -133,6 +132,7 @@ it('re-renders when facet is mutated', () => {

const ComponentWithFacetEffect = () => {
const adaptValue = useFacetUnwrap(demoFacet)
if (adaptValue === NO_VALUE) return null
return <span>{adaptValue.foo}</span>
}

Expand Down Expand Up @@ -169,6 +169,7 @@ it('re-renders when facet is mutated to undefined', () => {

const ComponentWithFacetEffect = () => {
const adaptValue = useFacetUnwrap(demoFacet)
if (adaptValue === NO_VALUE) return null
return <span>{adaptValue.foo}</span>
}

Expand Down Expand Up @@ -217,35 +218,6 @@ it('does not trigger a re-render when changing a facet from undefined to undefin
expect(renderedMock).toHaveBeenCalledTimes(0)
})

describe('suspense', () => {
it('throws when a facet has NO_VALUE', async () => {
const demoFacet = createFacet<string>({ initialValue: NO_VALUE })
const renderedMock = jest.fn()

const ComponentWithFacetEffect = () => {
const adaptValue = useFacetUnwrap(demoFacet)
renderedMock()

return <span>{adaptValue}</span>
}

render(
<Suspense>
<ComponentWithFacetEffect />
</Suspense>,
)

expect(renderedMock).toHaveBeenCalledTimes(0)

await act(async () => {
demoFacet.set('updated value')
await asPromise(demoFacet)
})

expect(renderedMock).toHaveBeenCalledTimes(1)
})
})

it('supports custom equality checks', () => {
const value = {}
const demoFacet = createFacet({ initialValue: value })
Expand Down
19 changes: 4 additions & 15 deletions packages/@react-facet/core/src/hooks/useFacetUnwrap.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
import { useLayoutEffect, useState } from 'react'
import { isFacet, Value, NO_VALUE, Option, FacetProp, EqualityCheck } from '../types'
import { asPromise } from '../helpers'
import { FacetProp, isFacet, Value, NoValue, EqualityCheck, NO_VALUE } from '../types'
import { defaultEqualityCheck } from '../equalityChecks'

/**
* Hook that allows consuming values from a Facet
* It acts as a regular react state, triggering a re-render of the component
*
* If the provided value is not a Facet, it will simply be forwarded untouched.
*
* @param facet
* @returns value of the Facet
*/
export function useFacetUnwrap<T extends Value>(
prop: FacetProp<T>,
equalityCheck: EqualityCheck<T> = defaultEqualityCheck,
): T {
const [state, setState] = useState<{ value: Option<T> }>(() => {
): T | NoValue {
const [state, setState] = useState<{ value: T | NoValue }>(() => {
if (!isFacet(prop)) return { value: prop }

return {
Expand Down Expand Up @@ -74,12 +70,5 @@ export function useFacetUnwrap<T extends Value>(
}
}, [prop, equalityCheck])

if (!isFacet(prop)) return prop

// If we don't have a value for the Facet yet, we can throw a Promise to trigger React's Suspense.
if (state.value === NO_VALUE) {
throw asPromise(prop)
}

return state.value
return isFacet(prop) ? state.value : prop
}
61 changes: 0 additions & 61 deletions packages/@react-facet/core/src/hooks/useFacetUnwrapTransition.ts

This file was deleted.

21 changes: 21 additions & 0 deletions packages/@react-facet/deferred-mount/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.

MIT License

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.
79 changes: 79 additions & 0 deletions packages/@react-facet/deferred-mount/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# @react-facet/deferred-mount

React Facet is a state management for performant game UIs. For more information on how to use this package check the official documentation available at https://react-facet.mojang.com/.

This package allows you to defer the mounting of a component to the next frame. By wrapping components on a big list you can keep the frame time low while everything is mounted.

When the `DeferredMountProvider` is used, it requires that there is at least one descendent as a `DeferredMount` or `DeferredMountWithCallback`, otherwise it will wait forever as `deferring`.

### Example

In the example below it will mount:

- Mounting: nothing
- First Frame: `First`
- Second Frame: `First` and `Second`
- Third Frame: `First`, `Second` and `Third`

The `useIsDeferring` hook allows to check what is the status of the deferred mounting (by returning a Facet) so we can, for example, show a spinner.

```tsx
const SampleComponent = () => {
const isDeferringFacet = useIsDeferring()

return (
<>
<fast-text text={useFacetMap((isDeferring) => (isDeferring ? 'deferring' : 'done'), [], [isDeferringFacet])} />
<DeferredMount>
<div>First</div>
</DeferredMount>
<DeferredMount>
<div>Second</div>
</DeferredMount>
<DeferredMount>
<div>Third</div>
</DeferredMount>
</>
)
}

render(
<DeferredMountProvider frameTimeBudget={16}>
<SampleComponent />
</DeferredMountProvider>,
document.getElementById('root'),
)
```

The `frameTimeBudget` prop allows the tweaking of how much time the library has available to do work on a given frame (by default it targets 60fps).

## Deferring Asynchronous Renders

Some components may need to wait some time before they can be considered fully rendered (for example if they are fetching data). For these cases you should use `DeferredMountWithCallback` with the `useNotifyMountComplete` hook.

### Example

```tsx
const DelayedComponent = () => {
const notifyMountComplete = useNotifyMountComplete()
const [data, setData] = useState()

useEffect(() => {
fetch('mock-api').then((data) => {
setData(data)
notifyMountComplete()
})
}, [notifyMountComplete])

return <div>{data}</div>
}

render(
<DeferredMountProvider>
<DeferredMountWithCallback>
<DelayedComponent />
</DeferredMountWithCallback>
</DeferredMountProvider>,
document.getElementById('root'),
)
```
11 changes: 11 additions & 0 deletions packages/@react-facet/deferred-mount/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* eslint-env node */

const baseConfig = require('../../../jest.base.config')
const projectName = require('./package.json').name

module.exports = {
...baseConfig,
name: projectName,
displayName: projectName,
rootDir: './',
}
53 changes: 53 additions & 0 deletions packages/@react-facet/deferred-mount/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"name": "@react-facet/deferred-mount",
"repository": {
"type": "git",
"url": "https://github.com/Mojang/ore-ui.git",
"directory": "packages/@react-facet/deferred-mount"
},
"author": {
"name": "Paulo Ragonha",
"email": "paulo@ragonha.me"
},
"contributors": [
{
"name": "Danila Dergachev",
"email": "dderg@protonmail.com"
},
{
"name": "Fernando Via Canel",
"email": "fernando.via@gmail.com"
},
{
"name": "Marlon Huber-Smith",
"email": "marlonhubersmith@gmail.com"
}
],
"files": [
"dist/**/*"
],
"homepage": "https://react-facet.mojang.com/",
"bugs": "https://github.com/Mojang/ore-ui/issues",
"license": "MIT",
"version": "0.5.3",
"main": "src/index.tsx",
"publishConfig": {
"main": "dist/index.js",
"types": "dist/index.d.ts"
},
"sideEffects": false,
"scripts": {
"build": "rimraf dist && tsc",
"prepublish": "yarn build"
},
"peerDependencies": {
"@react-facet/core": "0.5.3",
"react": "^16.9.0"
},
"devDependencies": {
"@react-facet/dom-fiber-testing-library": "0.5.3",
"react": "^16.9.0",
"rimraf": "^3.0.2",
"typescript": "^4.8.2"
}
}
Loading

0 comments on commit 939711d

Please sign in to comment.