Passing data down with contexts
What the card is read in, given in the tree or by the intent, and decisions that change along it.
At the dinner, the family reads Grandma's card on the TV. Before that, Sam proofreads it on a phone. The same card should fit both, and Sam wants the photo beside the words on the TV and above them on the phone. The card needs to know where it is read.
You will learn
- How
createContext,<Ctx.Provider>anduseContextgive a component what it is read in - How an intent gives contexts to every evaluation, and how one evaluation gets its own
- How a decision can change along an axis of a context
- How a host's measurement in one context rules possibilities out and weighs them there
A context
One card, read on two screens:
/** @jsxImportSource @reintent/core */
import { choices, createContext, host, useChoose, useContext } from '@reintent/core';
export const TONES = ['warm', 'funny', 'formal'] as const;
export type Tone = (typeof TONES)[number];
export const LOOK: Record<Tone, { background: string; accent: string }> = {
warm: { background: '#fdebd3', accent: '#b5562b' },
funny: { background: '#fff2a8', accent: '#7a4fd6' },
formal: { background: '#f1eee8', accent: '#2b2b2b' },
};
/** Where the card is shown. */
export type Screen = { id: string; label: string; width: number };
export const PHONE: Screen = { id: 'phone', label: 'Sam’s phone', width: 390 };
export const TV: Screen = { id: 'tv', label: 'The TV at the dinner', width: 1920 };
export const ScreenCtx = createContext<Screen>('Screen', { names: 'anywhere' });
export function useTone() {
return useChoose(choices<Tone>(...TONES), { of: 'card', name: 'tone', defaultValue: 'warm' });
}
/** The same card, sized for the screen it is read on. */
export function Card() {
const screen = useContext(ScreenCtx);
const tone = useTone();
const small = screen.width < 600;
return host('div', {
style: { marginBottom: 12 },
children: [
host('small', { children: `${screen.label}, ${screen.width} px` }),
host('div', {
style: {
maxWidth: small ? 220 : 380,
padding: small ? '0.5em 1em' : '1em 1.5em',
borderRadius: 12,
background: LOOK[tone].background,
color: '#3a2a1c',
fontSize: small ? 12 : 18,
},
children: [
host('h2', { style: { color: LOOK[tone].accent }, children: 'Happy 90th birthday, Grandma!' }),
host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: '— Sam' }),
],
}),
],
});
}
export default function App() {
return host('div', {
children: [
<ScreenCtx.Provider value={PHONE}>
<Card />
</ScreenCtx.Provider>,
<ScreenCtx.Provider value={TV}>
<Card />
</ScreenCtx.Provider>,
],
});
}
Starting…
Starting…
Nothing logged.
createContext<Screen>('Screen', { names: 'anywhere' }) makes an IntentContext<Screen>: a value a component reads without being passed it as a prop. <ScreenCtx.Provider value={PHONE}> gives it to the subtree inside, and useContext(ScreenCtx) reads the nearest one. One Card, two providers: the phone gets a small card, the TV a large one.
A context's key names its value, by default its id (or else its JSON). Every read says what it was read in, and What happened shows card#tone read on phone and on tv. It is still one choice: pick funny in Choices, and both screens turn funny.
A context names the reads when the evaluation is handed it, the way the next section gives it. One that only a Provider in the program gives is part of the program, and names nothing. Naming is not tracking: a read under such a Provider still follows its value, which changes only with the program or a choice; names: 'anywhere' says the screens name the reads all the same. A judge is never asked again because of a context: what it reads of one, the read hands it in uses.
Contexts from the intent
Sam's app knows the screen it runs on, and gives it to the card from outside:
/** @jsxImportSource @reintent/core */
import { action, choices, createContext, host, useChoose, useContext, type Id } from '@reintent/core';
export const TONES = ['warm', 'funny', 'formal'] as const;
export type Tone = (typeof TONES)[number];
export const LOOK: Record<Tone, { background: string; accent: string }> = {
warm: { background: '#fdebd3', accent: '#b5562b' },
funny: { background: '#fff2a8', accent: '#7a4fd6' },
formal: { background: '#f1eee8', accent: '#2b2b2b' },
};
/** Where the card is shown. */
export type Screen = { id: string; label: string; width: number };
export const PHONE: Screen = { id: 'phone', label: 'Sam’s phone', width: 390 };
export const TV: Screen = { id: 'tv', label: 'The TV at the dinner', width: 1920 };
export const ScreenCtx = createContext<Screen>('Screen');
/** What a button does. A function names nothing: its key is undefined. */
export const Decide = createContext<(id: Id, value: unknown) => void>('Decide', { key: () => undefined });
export function useTone() {
return useChoose(choices<Tone>(...TONES), { of: 'card', name: 'tone', defaultValue: 'warm' });
}
/** The same card, sized for the screen it is read on. */
export function Card() {
const screen = useContext(ScreenCtx);
const tone = useTone();
const small = screen.width < 600;
return host('div', {
style: { marginBottom: 12 },
children: [
host('small', { children: `${screen.label}, ${screen.width} px` }),
host('div', {
style: {
maxWidth: small ? 220 : 380,
padding: small ? '0.5em 1em' : '1em 1.5em',
borderRadius: 12,
background: LOOK[tone].background,
color: '#3a2a1c',
fontSize: small ? 12 : 18,
},
children: [
host('h2', { style: { color: LOOK[tone].accent }, children: 'Happy 90th birthday, Grandma!' }),
host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: '— Sam' }),
],
}),
host('p', {
children: TONES.map((v) =>
host('button', {
disabled: v === tone,
onClick: action.decide({ of: 'card', name: 'tone' }, v),
children: v,
}),
),
}),
],
});
}
export default function App() {
return <Card />;
}
Starting…
Starting…
Nothing logged.
createIntent({ provide: [[ScreenCtx, PHONE], …] })gives contexts to every evaluation. The buttons'Decidecomes the same way, as in Quick start.provideandintent.realizeboth take aProvide, a list of[context, value]pairs.index.intent.tsxnames its own,onTv.intent.realize([[ScreenCtx, TV]])evaluates once in another context, which comes after the intent's, so here the TV wins. A host that shows one program in several places evaluates it once for each.Decideis made withkey: () => undefined. A function names nothing worth keeping, so reads leave it out of theirctx.
Decisions along an axis
On the phone, a photo beside the words leaves them no room. Sam wants it beside them from 600 px wide:
/** @jsxImportSource @reintent/core */
import {
action,
choices,
createContext,
host,
useChoiceStatus,
useContext,
type Decided,
type Id,
type Piecewise,
} from '@reintent/core';
/** Where the card is shown. Its width is an axis: a number a decision can be piecewise on. */
export type Screen = { id: string; label: string; width: number };
export const PHONE: Screen = { id: 'phone', label: 'Sam’s phone', width: 390 };
export const TV: Screen = { id: 'tv', label: 'The TV at the dinner', width: 1920 };
export const ScreenCtx = createContext<Screen>('Screen', { axes: { width: (s) => s.width } });
export const Decide = createContext<(id: Id, value: Decided<Layout>) => void>('Decide', {
key: () => undefined,
});
export const Forget = createContext<(id: Id) => void>('Forget', { key: () => undefined });
export const LAYOUTS = ['stacked', 'side'] as const;
export type Layout = (typeof LAYOUTS)[number];
export const LAYOUT: Id = { of: 'card', name: 'layout' };
/** Side by side from 600 px wide; below that, nothing is decided. */
export const FROM_600: Piecewise<Layout> = { $axis: 'Screen.width', segments: [{ lo: 600, value: 'side' }] };
/** The photo above the words, or beside them. */
export function useLayout() {
return useChoiceStatus(choices<Layout>(...LAYOUTS), { ...LAYOUT, defaultValue: 'stacked' });
}
export function Card() {
const screen = useContext(ScreenCtx);
const layout = useLayout();
const small = screen.width < 600;
return host('div', {
style: { marginBottom: 12 },
children: [
host('small', { children: `${screen.label}, ${screen.width} px · ${layout.value} (${layout.source})` }),
host('div', {
style: {
maxWidth: small ? 220 : 380,
display: 'flex',
flexDirection: layout.value === 'side' ? 'row' : 'column',
gap: 12,
padding: small ? '0.5em 1em' : '1em 1.5em',
borderRadius: 12,
background: '#fdebd3',
color: '#3a2a1c',
fontSize: small ? 12 : 18,
},
children: [
host('div', {
style: { minWidth: 80, minHeight: 60, borderRadius: 8, background: '#c8b8a6' },
}),
host('div', {
children: [
host('h2', {
style: { color: '#b5562b', marginTop: 0 },
children: 'Happy 90th birthday, Grandma!',
}),
host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: '— Sam' }),
],
}),
],
}),
],
});
}
/** Sam's buttons: one layout everywhere, or side by side only from 600 px wide. */
export function Buttons() {
return host('p', {
children: [
host('button', { onClick: action.decide(LAYOUT, 'stacked'), children: 'stacked' }),
host('button', { onClick: action.decide(LAYOUT, 'side'), children: 'side by side' }),
host('button', {
onClick: action.decide(LAYOUT, FROM_600),
children: 'side by side from 600 px',
}),
host('button', {
onClick: action.forget(LAYOUT),
style: { marginLeft: 12, borderStyle: 'dashed', background: 'transparent', fontStyle: 'italic' },
children: 'no preference',
}),
],
});
}
export default function App() {
return host('div', {
children: [
<Buttons />,
<ScreenCtx.Provider value={PHONE}>
<Card />
</ScreenCtx.Provider>,
<ScreenCtx.Provider value={TV}>
<Card />
</ScreenCtx.Provider>,
],
});
}
Starting…
Starting…
Nothing logged.
createContext('Screen', { axes: { width: (s) => s.width } }) gives the context an axis, a number read off its value, named Screen.width. A decision can then be piecewise along it. FROM_600 is a Piecewise, { $axis: 'Screen.width', segments: [{ lo: 600, value: 'side' }] }, and each Segment covers lo ≤ width < hi. intent.decide takes a Decided, which is one value or a piecewise one, and isPiecewise(v) tells which.
Press side by side from 600 px. The TV is side by side, by Sam's decision. The phone's 390 px is in no segment, so it keeps its default, stacked. Press stacked or side by side, and one value holds on every screen.
Outside its segments, a decision falls through
Where no segment covers the point, the choice reads the layers below, as if nothing were decided there: System One's judgment, the code's prior, or the default.
What the host measured
The phone has room for the words beside the photo or above it, but not for three photos in a row. Only the host knows: it lays the card out, and it can lay out each possibility in turn. It does not pick one. It says what it found, and the choice's layers decide:
const read = intent.realize(phone).reads.find((r) => r.name === 'photos')!;
intent.measure(read, {
row: { feasible: false },
grid: { feasible: true, score: 0.4 },
column: { feasible: true, score: 1 },
});intent.measure takes a read, which says the choice and the context it was read in, and a Measurement for each possibility: whether it fits there, and how well, as a weight against the others (the best 1). The code's Reduce, reduceMeasured, turns it into the choice's layers for that context only: what does not fit is ruled out, as a constraint would, and each possibility is weighed by its score, as a preference would. The TV, which was not measured, reads as before.
- A measurement is below a person: their decision holds where it does not fit, and their constraint too. When the measurement would rule out all that a person left, it is set aside: the read says
unfit, and the choice is unresolved with nothing that fits (reason: 'none',cause: 'measured'). A<World onUnresolved>around it decides what happens; with none, the one that measured best stands in, and no model is asked. - It is above System One: a sure judgment decides wherever it fits, and one that points only at what does not fit says nothing about the rest, which the code's prior and the measurement then settle. One that gave only part of itself to what fits speaks for that part, and the prior for the rest. A judgment that is not sure is weighed by the measurement, since both hold.
- With nothing else said, the measurement alone settles the choice, and its
sourceis'measured'. - What the host prefers on this screen is not evidence. A host whose layout engine also has a taste (stack on a narrow screen, fewer pages) gives it as
prior, notscore: it multiplies the code's prior for that context, and a judgment replaces it, as it replaces the prior. Without a judgment the taste settles what fits, and thesourceis'prior'.facts, the numbers a fit was decided on (the smallest text in px, characters a line), are kept as they were said, for an explanation; the cascade does not read them. - The context is the key, so a view that shows less than another (an editor that shows one screen of a carousel) is a context of its own, not a part of the
stamp: two views kept under one key would write over each other. - A question can ask what to take where the default does not fit. Read with
instead: true, the judgment counts only there: where a person left the default and the host measured it to fit, System One is not asked and its answer does not weigh. Givestays: { question }too, and there it is asked that other question instead (whether another would be better where the default fits). It is another question with its own stamp, so each answer weighs only where its own question holds, and above the taste. - It is a cache, as a judgment is: not a commit, not in the history, kept by context as a
Measuredwith thestampthe host gives it. The same measurement again writes nothing. A read carries the evaluation it came from: a late measurement of an older one does not overwrite a newer one, and a preview's read is not measured into the world shown. A score of 0 rules a possibility out, as not fitting does.
Recap
createContext(name, { key, axes })makes a context, anduseContextreads the nearest value.<Ctx.Provider value>gives it to a subtree,createIntent({ provide })to every evaluation, andintent.realize([[Ctx, value]])to one.keynames a value in reads; a context of functions names nothing (key: () => undefined).- A context handed to the evaluation names the reads; one a Provider in the program gives names them with
names: 'anywhere'. - A decision can be piecewise along an axis (
$axis,segments), andisPiecewisetells it apart. - Where no segment applies, the layers below decide.
intent.measure(read, by)writes what the host measured in the read's context: what does not fit is ruled out there, and scores weigh.
Last updated on
Edit on GitHub