### Install and Start Documentation Site (Bash) Source: https://github.com/mojang/ore-ui/blob/main/README.md Commands to install dependencies and start the documentation site locally. Assumes Node.js and Yarn are installed. ```bash yarn docs:install yarn docs:start ``` -------------------------------- ### Install and Start Documentation Server (Yarn) Source: https://github.com/mojang/ore-ui/blob/main/docs/README.md Commands to install dependencies and start the local development server for the Docusaurus documentation site. Changes are reflected live without requiring a server restart. ```console # From project root yarn docs:install && yarn docs:start # Or from docs directory cd docs && yarn install && yarn start ``` -------------------------------- ### Setup SharedFacetDriverProvider with a Custom Driver Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/getting-started.md This snippet demonstrates how to set up the `SharedFacetDriverProvider` by defining a custom `sharedFacetDriver`. This driver handles requesting facets from a C++ backend and registering listeners for updates, returning a cleanup function. ```tsx const engine = { on: (...args: any[]) => {}, off: (...args: any[]) => {}, trigger: (...args: any[]) => {}, } // ---cut--- import { SharedFacetDriverProvider, OnChange } from '@react-facet/shared-facet' const sharedFacetDriver = (facetName: string, update: OnChange) => { // register a listener engine.on(`facet:updated:${facetName}`, update) // trigger an event to notify C++ we want to listen for updates engine.trigger('facet:request', facetName) // returns a cleanup function once no more components need the facet data return () => { engine.off(`facet:updated:${facetName}`, update) engine.trigger('facet:discard', facetName) } } const App = () => { return ... } ``` -------------------------------- ### React Facet: Basic Counter Example Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/getting-started.md Demonstrates a simple counter component using `useFacetState` for state management and `createRoot` from `@react-facet/dom-fiber` for rendering. It shows how to update state and render dynamic content using `fast-text` components. Dependencies include `@react-facet/core` and `@react-facet/dom-fiber`. ```tsx // @esModuleInterop import React, { useCallback } from 'react' import { useFacetState, NO_VALUE } from '@react-facet/core' import { createRoot } from '@react-facet/dom-fiber' const Counter = () => { const [counter, setCounter] = useFacetState(0) const handleClick = useCallback(() => { setCounter((counter) => (counter !== NO_VALUE ? counter + 1 : counter)) }, [setCounter]) return (

Current count: {/*                                   ^? */}

) } const root = createRoot(document.getElementById('root')) root.render() ``` -------------------------------- ### React Facet: Custom Renderer Example Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/getting-started.md Illustrates using the custom renderer with `@react-facet/dom-fiber`'s `createRoot` function to render components with `fast-div` and `fast-text`. It utilizes `useFacetState` to manage component state for class names and text content. This example requires `@react-facet/core` and `@react-facet/dom-fiber`. ```tsx // @esModuleInterop import { useFacetState } from '@react-facet/core' import { createRoot } from '@react-facet/dom-fiber' const HelloWorld = () => { const [className, setClassName] = useFacetState('root') const [helloWorld, setHelloWorld] = useFacetState('Hello World!') return ( ) } const root = createRoot(document.getElementById('root')) root.render() ``` -------------------------------- ### React Facet: Creating and Using Facets Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/getting-started.md Demonstrates the creation and usage of Facets for managing complex state, including nested objects and callbacks. It utilizes `useFacetState`, `useFacetMap`, and `useFacetCallback` from `@react-facet/core`. The example shows how to handle user input for username and password, update state immutably, and trigger a submit action. This snippet requires `@react-facet/core`. ```tsx export interface UserFacet { username: string signOut(): void } ``` ```tsx // @esModuleInterop import { render } from '@react-facet/dom-fiber' interface Props { onSubmit: (values: any) => void } // ---cut--- import { useFacetMap, useFacetState, useFacetCallback, NO_VALUE } from '@react-facet/core' interface TemporaryValuesFacet { username: string password: string } const UpdateLogin = ({ onSubmit }: Props) => { const [temporaryValues, updateValues] = useFacetState({ username: '', password: '', }) const username = useFacetMap((values) => values.username, [], [temporaryValues]) const password = useFacetMap((values) => values.password, [], [temporaryValues]) const handleClick = useFacetCallback( (values) => () => { onSubmit(values) }, [onSubmit], [temporaryValues], ) return (

User name

{ updateValues((values) => { if (values !== NO_VALUE) { values.username = (event.target as HTMLInputElement).value } return values }) }} />

Password

{ updateValues((values) => { if (values !== NO_VALUE) { values.password = (event.target as HTMLInputElement).value } return values }) }} />
) } ``` -------------------------------- ### Define and Consume a Shared User Facet Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/getting-started.md This example shows how to define a shared facet for user data (`UserFacet`) using `sharedFacet` and then consume it within a React component using the `useSharedFacet` hook. It also demonstrates creating a selector with `sharedSelector` to extract specific data from the facet. ```tsx // @esModuleInterop import { render } from '@react-facet/dom-fiber' // ---cut--- import { useSharedFacet, sharedFacet, sharedSelector } from '@react-facet/shared-facet' interface UserFacet { username: string signOut(): void } const userFacet = sharedFacet('data.user', { username: 'Alex', signOut() {}, }) const usernameSelector = sharedSelector((value) => value.username, [userFacet]) export const CurrentUser = () => { const username = useSharedFacet(usernameSelector) return } ``` -------------------------------- ### Compare Benchmarks with Yarn Source: https://github.com/mojang/ore-ui/blob/main/examples/benchmarking/README.md Compares two benchmark examples automatically using Chrome. It takes the names of the two examples and a target relative performance as arguments. ```bash yarn compare progressBarFacet progressBarState 74 ``` -------------------------------- ### Serve Project with Yarn Source: https://github.com/mojang/ore-ui/blob/main/examples/benchmarking/README.md Starts an HTTP server using Yarn, commonly used to serve built project files for local testing. This allows access to HTML entry points like `listMemoFacet.html`. ```bash yarn serve ``` -------------------------------- ### React Facet Manual Usage Example Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/rendering/using-facets-manually.md Demonstrates how to manually consume a Facet in React by listening to its changes and updating the DOM imperatively. This example uses `useFacetState` and `useFacetEffect` to manage and react to state changes, providing an alternative to the standard custom renderer for scenarios like React Native or performance optimizations. ```tsx // @esModuleInterop import React, { useCallback, useRef } from 'react' import { useFacetEffect, useFacetState, NO_VALUE } from '@react-facet/core' const Counter = () => { const [counter, setCounter] = useFacetState(0) const ref = useRef(null) useFacetEffect( (counterValue) => { if (ref.current == null) return ref.current.textContent = `${counterValue}` }, [], [counter], ) const handleClick = useCallback(() => { setCounter((counterValue) => { return counterValue !== NO_VALUE ? counterValue + 1 : counterValue }) }, [setCounter]) return (

Counter:

) } ``` -------------------------------- ### Stable Reference Example for createOptionalValueEqualityCheck Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/create-optional-value-equality-check.md Provides correct and incorrect examples of how to use `createOptionalValueEqualityCheck` with React hooks like `useFacetMap`. It emphasizes the importance of maintaining a stable reference to the created equality check by defining it outside the component or using `useMemo` to prevent unnecessary re-renders and state loss. ```tsx // ❌ WRONG - Creates new equality check on every render const Component = () => { const result = useFacetMap( (data) => transform(data), [], [dataFacet], createOptionalValueEqualityCheck(shallowArrayEqualityCheck), // New reference every render! ) } // ✅ CORRECT - Define outside component const optionalArrayCheck = createOptionalValueEqualityCheck(shallowArrayEqualityCheck) const Component = () => { const result = useFacetMap((data) => transform(data), [], [dataFacet], optionalArrayCheck) } // ✅ ALSO CORRECT - Use useMemo const Component = () => { const equalityCheck = useMemo(() => createOptionalValueEqualityCheck(shallowArrayEqualityCheck), []) const result = useFacetMap((data) => transform(data), [], [dataFacet], equalityCheck) } ``` -------------------------------- ### Good Performance Example: ViewModel Facet Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/shallow-object-array-equality-check.md An example demonstrating good performance characteristics for `shallowObjectArrayEqualityCheck`. This facet maps player data to view models, suitable for reasonably sized arrays (under 100 items) with a limited number of properties per object, ensuring efficient updates. ```tsx // ✅ Reasonable size (< 100 items, < 10 properties each) const viewModelsFacet = useFacetMap( (players) => players.map((p) => ({ id: p.id, name: p.name, score: p.score, })), [], [playersFacet], shallowObjectArrayEqualityCheck, ) ``` -------------------------------- ### Fast Text Component Example Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/fast-components.md Illustrates the usage of the fast-text component, which renders text content directly as a text node. It accepts a 'text' prop that can be a Facet containing a string, avoiding extra DOM elements. ```tsx // @esModuleInterop import { createRoot } from '@react-facet/dom-fiber' import { useFacetWrap } from '@react-facet/core' // --- const Example = () => ( ) ``` -------------------------------- ### Start Facet Transition with React Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/helpers.md The `startFacetTransition` function ensures that state changes from facet updates are managed within a React transition, similar to React's `startTransition`. This helps in prioritizing UI updates and preventing blocking operations. It takes a callback function that performs the state updates. ```tsx import { startFacetTransition, useFacetState } from '@react-facet/core' const DataLoader = () => { const [dataFacet, setData] = useFacetState([]) const loadData = () => { // Mark heavy update as low-priority transition startFacetTransition(() => { const newData = Array.from({ length: 10000 }, (_, i) => `Item ${i}`) setData(newData) }) } return } ``` -------------------------------- ### Range Generation Example (React/TypeScript) Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/shallow-array-equality-check.md An example of using `useFacetMap` and `shallowArrayEqualityCheck` to generate an array of page numbers based on the total number of pages. ```tsx import { useFacetMap, shallowArrayEqualityCheck } from '@react-facet/core' const pageNumbersFacet = useFacetMap( (totalPages) => Array.from({ length: totalPages }, (_, i) => i + 1), [], [totalPagesFacet], shallowArrayEqualityCheck, ) ``` -------------------------------- ### Render React App with @react-facet/dom-fiber Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/rendering/using-the-custom-renderer.md This snippet demonstrates how to render a React application using `createRoot` from the `@react-facet/dom-fiber` package. It shows the setup for a simple counter component with state management using `useFacetState` and custom `fast-text` components. This approach replaces the deprecated `render` function from older React versions. ```tsx // @esModuleInterop import React, { useCallback } from 'react' import { createRoot } from '@react-facet/dom-fiber' import { useFacetState, NO_VALUE } from '@react-facet/core' const Counter = () => { const [counter, setCounter] = useFacetState(0) const handleIncrement = useCallback( () => setCounter((counter) => { return counter !== NO_VALUE ? counter + 1 : counter }), [], ) const handleDecrement = useCallback( () => setCounter((counter) => { return counter !== NO_VALUE ? counter - 1 : counter }), [], ) return (

Counter:

) } const root = createRoot(document.getElementById('root')) root.render() ``` -------------------------------- ### Contrast: Conditional Rendering with Mount without Type Refinement (React/TypeScript) Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/mount-components.md This example demonstrates the limitations of the 'Mount' component for type refinement compared to 'With'. When using 'Mount', TypeScript cannot automatically infer that the Facet's value has been refined, potentially leading to type errors. The 'With' component is recommended for scenarios requiring automatic type narrowing. ```tsx // @esModuleInterop import { render } from '@react-facet/dom-fiber' import { useFacetWrap, useFacetMap, Mount, FacetProp } from '@react-facet/core' type UserDataProps = { name: FacetProp middlename?: FacetProp } const UserData = ({ name, middlename }: UserDataProps) => { const nameFacet = useFacetWrap(name) const middlenameFacet = useFacetWrap(middlename) return (

Name:

middlename != null, [], [middlenameFacet])}>

Middlename: middlename || '', [], [middlenameFacet])} />

{/* Since TypeScript cannot know that `middlenameFacet` now holds a `string` for sure, it will still believe that it could be `string | undefined`. The only way to solve this issue is to extract a new component or use a type assertion. Neither is a good option, hence we recommend using `With` instead in this scenario. */}
) } ``` -------------------------------- ### Use useFacetRef Hook with Facet in React Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/hooks/use-facet-ref.md This example demonstrates how to use the useFacetRef hook to get a ref to a Facet's current value within a React component. It logs the facet's value when the component renders. Ensure '@react-facet/core' is installed as a dependency. ```tsx import { useEffect } from 'react' import { useFacetRef, Facet } from '@react-facet/core' const LogWhenRendered = ({ exampleFacet }: { exampleFacet: Facet }) => { const facetRef = useFacetRef(exampleFacet) useEffect(() => { console.log(`The exampleFacet value at the time of rendering: ${facetRef.current}`) }) return null } ``` -------------------------------- ### Build Project with Yarn Source: https://github.com/mojang/ore-ui/blob/main/examples/benchmarking/README.md Builds the project using Yarn, typically for production deployment. This command prepares the project's assets and code. ```bash yarn build ``` -------------------------------- ### Build Static Documentation Site (Yarn) Source: https://github.com/mojang/ore-ui/blob/main/docs/README.md Commands to generate the static content for the documentation website. The output is placed in the 'build' directory, ready for deployment on any static hosting service. ```console # From project root yarn docs:build # Or from docs directory cd docs && yarn build ``` -------------------------------- ### Uniform Object Equality Check with Mixed Types (Limitation) Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/create-uniform-object-equality-check.md Highlights a limitation of `createUniformObjectEqualityCheck` where it expects all properties to be comparable with the same equality check. This example shows a `MixedTypes` type with an array and a string, indicating that this setup will fail or produce incorrect results at runtime. For mixed types, `createObjectWithKeySpecificEqualityCheck` should be used. Requires `@react-facet/core`. ```tsx //@esModuleInterop import { createUniformObjectEqualityCheck, shallowArrayEqualityCheck } from '@react-facet/core' // ❌ Won't work correctly - mixed types type MixedTypes = { numbers: number[] // Array name: string // Primitive - different type! } // This will fail at runtime or give incorrect results const check = createUniformObjectEqualityCheck(shallowArrayEqualityCheck)() ``` -------------------------------- ### Testing Facet Components with React Facet Testing Library Source: https://context7.com/mojang/ore-ui/llms.txt Demonstrates how to test facet-based components using the provided custom testing library integration. It covers rendering components, simulating user interactions like input changes and button clicks, and asserting component behavior using `waitFor` for asynchronous updates. Dependencies include `@react-facet/dom-fiber-testing-library`, `@react-facet/core`, and `@testing-library/jest-dom`. ```typescript import { render, fireEvent, waitFor } from '@react-facet/dom-fiber-testing-library' import { useFacetState, Unwrap } from '@react-facet/core' import '@testing-library/jest-dom' function TodoList() { const [todos, setTodos] = useFacetState([]) const [input, setInput] = useFacetState('') const addTodo = () => { const value = input.get() if (value !== NO_VALUE && value.trim()) { setTodos(prev => [...(prev === NO_VALUE ? [] : prev), value]) setInput('') } } return (
setInput(e.target.value)} /> {(items) => (
    {items.map((todo, i) => (
  • {todo}
  • ))}
)}
) } // Test suite describe('TodoList', () => { it('adds todo items when button is clicked', async () => { const { getByTestId, getByText } = render() const input = getByTestId('todo-input') as HTMLInputElement const button = getByTestId('add-button') // Add first todo fireEvent.change(input, { target: { value: 'Buy groceries' } }) fireEvent.click(button) await waitFor(() => { expect(getByText('Buy groceries')).toBeInTheDocument() }) // Add second todo fireEvent.change(input, { target: { value: 'Walk the dog' } }) fireEvent.click(button) await waitFor(() => { expect(getByText('Walk the dog')).toBeInTheDocument() }) const list = getByTestId('todo-list') expect(list.children).toHaveLength(2) }) it('does not add empty todos', () => { const { getByTestId } = render() const button = getByTestId('add-button') fireEvent.click(button) const list = getByTestId('todo-list') expect(list.children).toHaveLength(0) }) }) ``` -------------------------------- ### User Greeting with Default Return (React/TypeScript) Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/hooks/use-facet-callback.md Illustrates using `useFacetCallback` with a string `defaultReturn` for generating user greetings. The callback returns a string, and the default is 'Welcome, Guest!'. This ensures a greeting is always displayed even if the user facet is uninitialized. ```tsx // @esModuleInterop import { useFacetState, useFacetCallback } from '@react-facet/core' const UserGreeting = () => { const [userFacet] = useFacetState({ name: 'Alice', isAdmin: false }) // Returns a string, so defaultReturn is a string const getGreeting = useFacetCallback( (user) => () => { return user.isAdmin ? `Welcome back, Admin ${user.name}!` : `Hello, ${user.name}!` }, [], [userFacet], 'Welcome, Guest!', // Default greeting when userFacet is not initialized ) return
{getGreeting()}
} ``` -------------------------------- ### Replace React DOM Testing with Facet DOM Fiber Testing Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/rendering/overview.md This code snippet demonstrates how to switch from the standard '@testing-library/react' to '@react-facet/dom-fiber-testing-library' for testing components that use the custom facet renderer. This change ensures that tests are run with the facet-aware rendering engine, providing accurate results for facet-based applications. It involves a simple import replacement in your test files. ```diff -import {render, fireEvent, waitFor, screen} from '@testing-library/react' +import {render, fireEvent, waitFor, screen} from '@react-facet/dom-fiber-testing-library' ``` -------------------------------- ### Extract Property Values Example (React/TypeScript) Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/shallow-array-equality-check.md Demonstrates using `useFacetMap` with `shallowArrayEqualityCheck` to extract specific property values (e.g., names) from an array of objects. ```tsx import { useFacetMap, shallowArrayEqualityCheck } from '@react-facet/core' const playerNamesFacet = useFacetMap( (players) => players.map((p) => p.name), [], [playersFacet], shallowArrayEqualityCheck, ) ``` -------------------------------- ### Filter and Sort Array Example (React/TypeScript) Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/shallow-array-equality-check.md A common pattern using `useFacetMap` and `shallowArrayEqualityCheck` to filter and sort an array of IDs based on an active flag. ```tsx import { useFacetMap, shallowArrayEqualityCheck } from '@react-facet/core' const sortedActiveIdsFacet = useFacetMap( (ids, activeFlag) => ids.filter((id) => activeFlag[id]).sort((a, b) => a - b), [], [idsFacet, activeFlagsFacet], shallowArrayEqualityCheck, ) ``` -------------------------------- ### Creating Standalone Facets Source: https://context7.com/mojang/ore-ui/llms.txt Utilize the low-level API `createFacet` to instantiate facets outside of React components, with options for subscriptions and custom equality checks. ```APIDOC ## Creating Standalone Facets ### Description Low-level API for creating facets outside of React components with optional subscriptions and equality checks. ### Method `createFacet` ### Usage Example ```typescript import { createFacet, NO_VALUE, defaultEqualityCheck } from '@react-facet/core' // Create a simple facet const temperatureFacet = createFacet({ initialValue: 20, equalityCheck: defaultEqualityCheck }) // Set values temperatureFacet.set(25) temperatureFacet.setWithCallback((prev) => { const current = prev === NO_VALUE ? 0 : prev return current + 5 }) // Get current value const currentTemp = temperatureFacet.get() // 30 // Subscribe to changes const unsubscribe = temperatureFacet.observe((temp) => { console.log(`Temperature changed to: ${temp}°C`) if (temp > 100) { console.warn('Temperature critical!') } }) // Later: cleanup unsubscribe() ``` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Performance Comparison: Transitions vs. No Transitions Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/hooks/use-facet-transition.md Contrasts the UI update behavior with and without transitions. Without transitions, heavy updates block the UI, delaying user interactions. With `startTransition`, heavy updates occur in the background, keeping the UI responsive to user interactions. ```tsx // Without transitions: // Heavy update blocks the UI setData(expensiveComputation()) // User interactions are delayed until this completes ``` ```tsx // With transitions: startTransition(() => { setData(expensiveComputation()) }) // User interactions remain responsive // Heavy update happens in the background ``` -------------------------------- ### Equality Check for Empty Arrays Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/create-uniform-array-equality-check.md This example confirms that empty arrays are considered equal by `createUniformArrayEqualityCheck`. When comparing two empty arrays, the function returns `true`. ```tsx //@esModuleInterop import { createUniformArrayEqualityCheck, shallowArrayEqualityCheck } from '@react-facet/core' const check = createUniformArrayEqualityCheck(shallowArrayEqualityCheck)() check([]) console.log(check([])) // true ✅ ``` -------------------------------- ### Observe Multiple Facets Simultaneously Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/helpers.md The `multiObserve` function allows observing an array of `Facet` objects for changes. It takes a callback function that receives the current values of the observed facets and an array of the facets to observe. It returns an `unObserve` function to stop listening for changes. ```ts import { createFacet, multiObserve } from '@react-facet/core' const userNameFacet = createFacet({ initialValue: 'Jane' }) const userLevelFacet = createFacet({ initialValue: 'maintainer' }) const unObserve = multiObserve( (userName, userLevel) => { console.log(`${userName} is now ${userLevel}`) }, [userNameFacet, userLevelFacet], ) // Logs "Jane is now maintainer" userLevelFacet.set('admin') // Logs "Jane is now admin" unObserve() userNameFacet.set('Janice') // Does not log anything ``` -------------------------------- ### Combining Multiple Arrays Example (React/TypeScript) Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/shallow-array-equality-check.md Shows how to combine two arrays (user tags and system tags) into a single array using `useFacetMap` and `shallowArrayEqualityCheck`. ```tsx import { useFacetMap, shallowArrayEqualityCheck } from '@react-facet/core' const allTagsFacet = useFacetMap( (userTags, systemTags) => [...userTags, ...systemTags], [], [userTagsFacet, systemTagsFacet], shallowArrayEqualityCheck, ) ``` -------------------------------- ### Good Performance with Small Arrays (React/TypeScript) Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/shallow-array-equality-check.md Highlights that `shallowArrayEqualityCheck` offers good performance for small to medium-sized arrays (typically less than 100 elements), as demonstrated in this example with tags. ```tsx // ✅ Small to medium arrays (< 100 elements) const tagsFacet = useFacetMap((data) => data.tags, [], [dataFacet], shallowArrayEqualityCheck) ``` -------------------------------- ### Basic Usage of createOptionalValueEqualityCheck Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/create-optional-value-equality-check.md Demonstrates the fundamental usage of `createOptionalValueEqualityCheck` with `shallowArrayEqualityCheck`. It shows how the resulting equality check correctly evaluates arrays, null values, and transitions between them, ensuring accurate state comparisons in UI components. ```tsx //@esModuleInterop import { createOptionalValueEqualityCheck, shallowArrayEqualityCheck } from '@react-facet/core' const equalityCheck = createOptionalValueEqualityCheck(shallowArrayEqualityCheck)() equalityCheck([1, 2, 3]) console.log(equalityCheck([1, 2, 3])) // true - same array console.log(equalityCheck(null)) // false - changed to null console.log(equalityCheck(null)) // true - still null console.log(equalityCheck([4, 5])) // false - back to defined value console.log(equalityCheck([4, 5])) // true - same array ``` -------------------------------- ### Basic Derivation with useFacetMap Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/hooks/use-facet-map.md An example of using useFacetMap to derive a facet that determines a CSS class based on player health and a threshold. This prepares facets for use with fast components. ```tsx // @esModuleInterop import { render } from '@react-facet/dom-fiber' // --- import { useFacetState, useFacetMap } from '@react-facet/core' const HealthBar = ({ lowHealthThreshold }: { lowHealthThreshold: number }) => { const [playerFacet, setPlayerFacet] = useFacetState({ health: 80, mana: 65, }) const className = useFacetMap( ({ health }) => (health > lowHealthThreshold ? 'healthy' : 'hurt'), [lowHealthThreshold], [playerFacet], ) return } ``` -------------------------------- ### Using useFacetUnwrap for Complex Conditional Logic in React Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/hooks/use-facet-unwrap.md Shows an example of using useFacetUnwrap for complex conditional rendering logic that might be difficult to express with other Facet components. It highlights the need to handle `NO_VALUE` and `null` states. ```tsx // @esModuleInterop import { useFacetState, useFacetUnwrap, NO_VALUE } from '@react-facet/core' const ComplexConditional = () => { const [statusFacet] = useFacetState<'loading' | 'error' | 'success'>('loading') const [dataFacet] = useFacetState<{ items: string[] } | null>(null) // ⚠️ Complex logic that's hard to express otherwise const status = useFacetUnwrap(statusFacet) const data = useFacetUnwrap(dataFacet) if (status === 'loading') return
Loading...
if (status === 'error') return
Error!
if (data === NO_VALUE || data === null) return
No data
return (
{data.items.map((item, i) => (
{item}
))}
) } ``` -------------------------------- ### Mapping Facet Values Source: https://context7.com/mojang/ore-ui/llms.txt Transform facet values into new facets using `useFacetMap` for lightweight transformations without intermediate caching. ```APIDOC ## Mapping Facet Values ### Description Transform one or more facet values into a new facet using `useFacetMap` for lightweight transformations without caching. ### Method `useFacetMap` ### Usage Example ```typescript import { useFacetState, useFacetMap, Unwrap } from '@react-facet/core' function UserProfile() { const [user, setUser] = useFacetState({ firstName: 'John', lastName: 'Doe', age: 30 }) // Map multiple values to create a display name const displayName = useFacetMap( ({ firstName, lastName, age }) => `${firstName} ${lastName} (${age} years old)`, [], [user] ) const updateUser = () => { setUser({ firstName: 'Jane', lastName: 'Smith', age: 25 }) } return (
{(name) =>

{name}

}
) } ``` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Nested Object Equality Check with Arrays Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/create-uniform-object-equality-check.md Demonstrates nesting `createUniformObjectEqualityCheck` to handle deeply structured objects containing arrays. This example defines a `DeepUniform` type and applies nested checks for comparing nested arrays. Requires `@react-facet/core`. ```tsx //@esModuleInterop import { createUniformObjectEqualityCheck, shallowArrayEqualityCheck } from '@react-facet/core' // Objects containing objects containing arrays type DeepUniform = { region1: { x: number[]; y: number[] } region2: { x: number[]; y: number[] } } const innerCheck = createUniformObjectEqualityCheck(shallowArrayEqualityCheck) const outerCheck = createUniformObjectEqualityCheck(innerCheck)() outerCheck({ region1: { x: [1, 2], y: [3, 4] }, region2: { x: [5, 6], y: [7, 8] }, }) console.log( outerCheck({ region1: { x: [1, 2], y: [3, 4] }, region2: { x: [5, 6], y: [7, 8] }, }), ) // true ✅ ``` -------------------------------- ### Mounting Search Results with Mount and useFacetMap Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/mount-components.md Illustrates a common use case for the Mount component combined with useFacetMap to display search results only when the search bar has content. Requires @react-facet/core. ```tsx // @esModuleInterop const SomeComponent = () => null // --- import { useFacetState, useFacetMap, Mount } from '@react-facet/core' const Example = () => { const [valueFacet, setValueFacet] = useFacetState('') const isValueNotNullOrEmptyFacet = useFacetMap( (value) => { return value != null && value.length > 0 }, [], [valueFacet], ) return ( ) } ``` -------------------------------- ### Custom React Root Rendering with @react-facet/dom-fiber Source: https://context7.com/mojang/ore-ui/llms.txt The `createRoot` function from `@react-facet/dom-fiber` enables the creation of a custom React root that is aware of React Facet. This integration ensures optimal performance for applications heavily utilizing facet-based state management, allowing seamless rendering and updates of facet-driven components within a standard DOM environment. ```typescript import { createRoot } from '@react-facet/dom-fiber' import { useFacetState, Unwrap } from '@react-facet/core' function App() { const [message, setMessage] = useFacetState('Hello from Facet DOM Fiber!') return (
{(text) =>

{text}

}
) } // Create root and render const container = document.getElementById('root') if (container) { const root = createRoot(container) root.render() // Later: cleanup // root.unmount() } ``` -------------------------------- ### Synchronous DOM Measurement with useFacetLayoutEffect in TypeScript Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/hooks/use-facet-layout-effect.md This example demonstrates how to use useFacetLayoutEffect to synchronously measure DOM element dimensions after they change. It utilizes a ref to access the DOM element and logs its dimensions. It depends on dimensionsFacet for triggering the effect. ```tsx // @esModuleInterop import { useFacetLayoutEffect, useFacetState, Facet } from '@react-facet/core' import { useRef } from 'react' const MeasureElement = ({ dimensionsFacet }: { dimensionsFacet: Facet<{ width: number; height: number }> }) => { const elementRef = useRef(null) useFacetLayoutEffect( (dimensions) => { // Synchronously measure the element after dimensions change if (elementRef.current) { const rect = elementRef.current.getBoundingClientRect() console.log('Element measured:', rect.width, 'x', rect.height) } }, [], [dimensionsFacet], ) return
Measured content
} ``` -------------------------------- ### Equality Check Limitation: Mixed Types Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/create-uniform-array-equality-check.md This example highlights a limitation of `createUniformArrayEqualityCheck`: it assumes all elements within an array can be compared using the same equality check. Providing an array with mixed types (e.g., `number[]` and `string`) can lead to incorrect results or errors. ```tsx //@esModuleInterop import { createUniformArrayEqualityCheck, shallowArrayEqualityCheck } from '@react-facet/core' // ❌ Won't work correctly - mixed types type MixedArray = (number[] | string)[] // Some elements are arrays, some are strings // This will fail or give incorrect results const check = createUniformArrayEqualityCheck(shallowArrayEqualityCheck)() ``` -------------------------------- ### Shared Facets with Driver Pattern in TypeScript Source: https://context7.com/mojang/ore-ui/llms.txt Demonstrates creating shared facets that synchronize state across multiple component instances using a driver pattern. It involves defining facets, implementing a driver to fetch and update data, and providing this driver through React Context. Dependencies include '@react-facet/shared-facet'. ```typescript import { sharedFacet } from '@react-facet/shared-facet' import { SharedFacetDriver } from '@react-facet/shared-facet' import { createContext, useContext, ReactNode } from 'react' // Define shared facets const userProfileFacet = sharedFacet<{ name: string, status: string }>('userProfile') const onlineCountFacet = sharedFacet('onlineCount', 0) // Create driver const sharedFacetDriver: SharedFacetDriver = (name, onChange, onError) => { // Connect to data source (e.g., WebSocket, API) if (name === 'userProfile') { const interval = setInterval(() => { onChange({ name: 'Player' + Math.floor(Math.random() * 1000), status: Math.random() > 0.5 ? 'online' : 'away' }) }, 5000) return () => clearInterval(interval) } if (name === 'onlineCount') { const interval = setInterval(() => { onChange(Math.floor(Math.random() * 1000)) }, 3000) return () => clearInterval(interval) } return () => {} } // Context setup const DriverContext = createContext(null) function SharedFacetProvider({ children }: { children: ReactNode }) { return ( {children} ) } function UserStatus() { const driver = useContext(DriverContext) const profile = userProfileFacet(driver!) return ( {(user) =>
{user.name} is {user.status}
}
) } function OnlineCounter() { const driver = useContext(DriverContext) const count = onlineCountFacet(driver!) return ( {(num) =>
{num} players online
}
) } ``` -------------------------------- ### Uniform Object Equality Check Ignoring Property Order Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/create-uniform-object-equality-check.md Demonstrates that `createUniformObjectEqualityCheck` from `@react-facet/core` ignores the order of properties when comparing objects. This example uses `strictEqualityCheck` and shows that comparing objects with the same properties but in different orders results in `true`. Requires `@react-facet/core`. ```tsx //@esModuleInterop import { createUniformObjectEqualityCheck, strictEqualityCheck } from '@react-facet/core' const check = createUniformObjectEqualityCheck(strictEqualityCheck)() check({ a: 1, b: 2 }) // Same values, different order console.log(check({ b: 2, a: 1 })) // true ✅ ``` -------------------------------- ### Common Pattern: User Profile Facet Creation Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/create-object-key-specific-check.md Shows how to create a `useFacetMap` for a User Profile, utilizing various equality checks for different property types including primitives, arrays, and nested objects. This pattern helps manage and compare complex user data efficiently. ```tsx import { useFacetMap, createObjectWithKeySpecificEqualityCheck, strictEqualityCheck, shallowArrayEqualityCheck, shallowObjectEqualityCheck, } from '@react-facet/core' type UserProfile = { id: string displayName: string roles: string[] preferences: { theme: string; language: string } } const profileFacet = useFacetMap( (user) => ({ id: user.id, displayName: `${user.firstName} ${user.lastName}`, roles: user.roles, preferences: user.preferences, }), [], [userFacet], createObjectWithKeySpecificEqualityCheck({ id: strictEqualityCheck, displayName: strictEqualityCheck, roles: shallowArrayEqualityCheck, preferences: shallowObjectEqualityCheck, }), ) ``` -------------------------------- ### Common Pattern: Search Results Equality Check Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/equality-checks/shallow-object-array-equality-check.md Example of using `shallowObjectArrayEqualityCheck` with `useFacetMap` to manage search results. The facet filters items based on a query and maps them to display objects, ensuring efficient updates when the results array changes. ```tsx import { useFacetMap, shallowObjectArrayEqualityCheck } from '@react-facet/core' const searchResultsFacet = useFacetMap( (items, query) => items .filter((item) => item.name.toLowerCase().includes(query.toLowerCase())) .map((item) => ({ id: item.id, displayName: item.name, matchScore: calculateMatchScore(item.name, query), })), [], [itemsFacet, queryFacet], shallowObjectArrayEqualityCheck, ) ``` -------------------------------- ### Animate 1000 Markers at 60fps using React Facet Source: https://context7.com/mojang/ore-ui/llms.txt This TypeScript code demonstrates a high-performance animation of 1000 markers using React Facet. It utilizes `useFacetState` for managing marker positions and `useFacetMap` for deriving style properties. The animation loop uses `window.requestAnimationFrame` for smooth updates. Dependencies include `@react-facet/core` and `@react-facet/dom-fiber`. It takes an array of marker objects as input and outputs their animated positions on a fixed-size canvas. ```typescript import { useFacetState, useFacetMap, Map, Facet, NO_VALUE } from '@react-facet/core' import { createRoot } from '@react-facet/dom-fiber' import { useEffect } from 'react' interface Marker { x: number y: number } function AnimatedMarker({ marker }: { marker: Facet }) { const leftValue = useFacetMap(({ x }) => `${x * 1920}px`, [], [marker]) const topValue = useFacetMap(({ y }) => `${y * 1080}px`, [], [marker]) return (
) } function MarkerPerformanceTest() { const [markers, setMarkers] = useFacetState( Array.from({ length: 1000 }, () => ({ x: Math.random(), y: Math.random() })) ) useEffect(() => { let frameId: number const animate = () => { setMarkers((current) => { if (current === NO_VALUE) return [] // Mutate for performance (array reference stays same) for (let i = 0; i < current.length; i++) { current[i].x = (current[i].x + Math.random() * 0.01 - 0.005) % 1 current[i].y = (current[i].y + Math.random() * 0.01 - 0.005) % 1 } return current }) frameId = window.requestAnimationFrame(animate) } animate() return () => window.cancelAnimationFrame(frameId) }, [setMarkers]) return (
{(item, index) => }
) } const container = document.getElementById('root') if (container) { createRoot(container).render() } ``` -------------------------------- ### General State Update Patterns with NO_VALUE Source: https://github.com/mojang/ore-ui/blob/main/docs/docs/api/hooks/use-facet-state.md Provides a collection of common state update patterns using `useFacetState`, including incrementing numbers, appending to arrays, and replacing array elements. All examples consistently check for `NO_VALUE` before modifying state. ```tsx // @esModuleInterop import { useFacetState, NO_VALUE } from '@react-facet/core' const Examples = () => { const [countFacet, setCount] = useFacetState(0) const [itemsFacet, setItems] = useFacetState([]) // Incrementing a number const increment = () => { setCount((current) => (current !== NO_VALUE ? current + 1 : 1)) } // Appending to array const appendItem = (item: string) => { setItems((current) => (current !== NO_VALUE ? [...current, item] : [item])) } // Replacing array element const replaceItem = (index: number, newItem: string) => { setItems((current) => (current !== NO_VALUE ? current.map((item, i) => (i === index ? newItem : item)) : [newItem])) } return
Examples
} ```