Solid · guide

Draw only what changed

Each time something arrives you get a new object, and every part of it that did not change is the same object as before. A screen can tell by comparing.

Install it
pnpm add @niscorp/solid zod
Step 1 of 3

An answer with a card in it

A long text, and a card that is finished early.

An answer with a card in it
import { z } from 'zod';
import { createStream } from '@niscorp/solid';

const Answer = z.object({
  card: z.object({ show: z.string(), seats: z.array(z.string()) }),
  text: z.string(),
});
const stream = createStream({ schema: Answer });
Step 2 of 3

Listen to each part

A listener on a part is called once when it is added, and after that only when its part changed.

Listen to each part
let card = 0;
let text = 0;
stream.select('card').on(() => (card += 1));
stream.select('text').on(() => (text += 1));
Step 3 of 3

The card, then a long text

After the card has arrived, the text arrives in six pieces. The card is kept from before the text and compared after it.

The card, then a long text
stream.write('{"card":{"show":"The Tempest","seats":["C4","C5"]},"text":"');
const before = stream.current();
for (const word of ['Two ', 'seats ', 'together ', 'in ', 'row ', 'C."}']) stream.write(word);
const after = stream.current();

console.log('card listener:', card, '· text listener:', text);
console.log('same card:', before.card === after.card, '· same answer:', before === after);
Then

Run it.

Each listener is called once when it is added. After that the card’s is called once, for the piece that brought the card, and the text’s once for each of its six pieces. The card is the same object before and after the text.

Run it
npx tsx changed.mts
It prints
card listener: 2 · text listener: 7
same card: true · same answer: false