Swapping the realizer
Who turns the program into λ, how to give an intent another one, and the entry points underneath.
Every sandbox so far evaluates Sam's card with Reintent's own kernel. Sam's app is a React app, and the card's components can just as well run as React components. Either way the intent calls one function for each evaluation, a realizer, and Sam can give it any realizer that keeps the contract.
You will learn
- How to evaluate a program with React:
reactRealizer - What an
Realizertakes and returns, and howcreateIntent({ realizer })uses it - What
<Card />compiles to:@reintent/core/jsx-runtime - Who
@reintent/core/internalis for
Evaluating with React
The same card, evaluated by React in App.tsx:
/** @jsxImportSource @reintent/core */
import { action, choices, host, useChoiceStatus } from '@reintent/core';
export type Person = { to: string; age: number; from: string };
export const TONES = ['warm', 'funny', 'formal'] as const;
export type Tone = (typeof TONES)[number];
export const GRANDMA: Person = { to: 'Grandma', age: 90, from: 'Sam' };
export const LOOK: Record<Tone, { background: string; accent: string }> = {
warm: { background: '#fdebd3', accent: '#b5562b' },
funny: { background: '#fff2a8', accent: '#7a4fd6' },
formal: { background: '#f1eee8', accent: '#2b2b2b' },
};
export function title(p: Person, tone: Tone) {
if (tone === 'formal') return `Many happy returns, ${p.to}.`;
if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
return `${p.age} laps around the sun, ${p.to}!`;
}
/** The card's tone, and which layer it came from: System One weighs it; a person's decision is above its judgment. */
export function useToneStatus() {
return useChoiceStatus(choices<Tone>(...TONES), {
of: 'card',
name: 'tone',
defaultValue: 'warm',
question: 'Which tone suits a birthday card for Grandma, turning 90?',
ask: ['model'],
});
}
export function useTone() {
return useToneStatus().value;
}
export function Card(p: Person) {
const tone = useTone();
return host('div', {
style: {
maxWidth: 380,
padding: '1.5em',
borderRadius: 12,
background: LOOK[tone].background,
color: '#3a2a1c',
},
children: [
host('h1', { style: { color: LOOK[tone].accent }, children: title(p, tone) }),
host('p', { children: 'Wishing you a wonderful day.' }),
host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: `— ${p.from}` }),
],
});
}
export function Buttons() {
const tone = useToneStatus();
const row = <T extends string>(name: string, values: readonly T[], now: { value: T; source: string }) =>
host('p', {
children: [
...values.map((v) =>
// A person's decision is pressed; a value the card took on its own is only marked.
host('button', {
disabled: now.source === 'decision' && v === now.value,
...(now.source !== 'decision' &&
v === now.value && { style: { textDecoration: 'underline dotted' } }),
onClick: action.decide({ of: 'card', name }, v),
children: v,
}),
),
// The person's way of not deciding: forget the decision, and the card picks again.
host('button', {
disabled: now.source !== 'decision',
onClick: action.forget({ of: 'card', name }),
style: {
marginLeft: 12,
borderStyle: 'dashed',
fontStyle: 'italic',
...(now.source === 'decision' && { background: 'transparent' }),
},
children: 'no preference',
}),
],
});
return host('div', { children: [row('tone', TONES, tone)] });
}
export default function App() {
return host('div', { children: [<Card {...GRANDMA} />, <Buttons />] });
}
Starting…
Starting…
Nothing logged.
createIntent({ realizer: reactRealizer }) makes an intent whose program React evaluates. reactRealizer from @reintent/react turns each element into a React element and calls each component inside React, so useChoose and every other hook work unchanged. It renders synchronously with react-dom/server, so an evaluation is still a value. What happened logs 'the same λ:' true: the kernel's intent and React's give the same tree. The buttons under the card decide on React's intent.
A realizer of your own
Sam wants to count how often the card is really evaluated:
import { createIntent, type Realizer } from '@reintent/core';
import { renderOnce } from '@reintent/core/internal';
import { Card, GRANDMA } from './App.intent';
let runs = 0;
const counting: Realizer = (element, inputs, provide) => {
runs++;
return renderOnce(element, inputs, provide);
};
const intent = createIntent({ program: <Card {...GRANDMA} />, realizer: counting });
intent.realize();
intent.realize();
console.log(runs, intent.stats); // → 1 { renders: 1, skipped: 1 }An Realizer takes the element, the inputs (the choices' layers) and the contexts, and returns { picks, result }: what the components took from the inputs, and λ with everything they reported. The intent compares the picks to skip an evaluation whose inputs have not changed, so a skipped evaluation never reaches the realizer, and runs stays at 1. renderOnce is the kernel's realizer, the default. reactRealizer keeps the same contract.
Previews and explanations go through it too
intent.preview evaluates the program through the same realizer every time, with nothing skipped. intent.explain evaluates it once for each state of the layers and each context, and explaining again before anything changes calls nothing. intent.stats counts neither.
What JSX compiles to
An intent file starts with /** @jsxImportSource @reintent/core */, or its tsconfig sets "jsxImportSource": "@reintent/core" (Installation). Either way the compiler turns each tag into a call to jsx from @reintent/core/jsx-runtime:
/** @jsxImportSource @reintent/core */
import { host } from '@reintent/core';
import { jsx } from '@reintent/core/jsx-runtime';
function Card(p: { to: string }) {
return host('h1', { children: `Happy birthday, ${p.to}!` });
}
console.log(<Card to="Grandma" />);
console.log(jsx(Card, { to: 'Grandma' }));
// both: { '$$element': true, type: [Function: Card], props: { to: 'Grandma' }, key: undefined }An element is plain data: a type, props and a key. jsxs, for a tag with several children, and jsxDEV, for development builds, are the same function. <>…</> is an element whose type is Fragment. The JSX namespace types these files, and its IntrinsicElements is empty: every tag is a component, so a host node is written host('h1', …).
What @reintent/core/internal is for
An intent and a host need only @reintent/core and @reintent/react. @reintent/core/internal holds what lies underneath them, for whoever builds on the machinery:
- a realizer:
renderOnce,inScope, the element tests (isElement,isHostNode,isBoundary,hostKindOf,contextOfProvider) andBoundary.reactRealizer, inpackages/react/src/realizer.ts, is written withinScopeand the element tests; - the layer store, where an intent keeps its layers and their history:
createLayerStoreandlayerStoreOf(intent), for tools and tests that write the layers directly; - tools and tests that look inside: working with distributions, the cascade, input stamps, and taking a trace apart.
Recap
createIntent({ realizer: reactRealizer })evaluates the program with React, and gives the same λ as the kernel.- A
Realizertakes the element, the inputs and the contexts and returns{ picks, result }; the intent skips calling it while the picks are equal. <Card />compiles tojsx(Card, {})from@reintent/core/jsx-runtime, an element made of plain data.@reintent/core/internalis for realizers, the layer store, tools and tests.
Last updated on
Edit on GitHub