Skip to content

Commit

Permalink
refactor(examples): update rstream usage
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Apr 8, 2023
1 parent a2b8629 commit 55de86b
Show file tree
Hide file tree
Showing 13 changed files with 118 additions and 129 deletions.
10 changes: 5 additions & 5 deletions examples/adaptive-threshold/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { IntBuffer } from "@thi.ng/pixel";
import { sidechainPartitionRAF } from "@thi.ng/rstream";
import { map } from "@thi.ng/transducers/map";
import { syncRAF } from "@thi.ng/rstream";
import { updateDOM } from "@thi.ng/transducers-hdom";
import { map } from "@thi.ng/transducers/map";
import {
type AppState,
type Event,
SET_IMAGE,
SET_KERNEL_OFFSET,
SET_KERNEL_WIDTH,
type AppState,
type Event,
} from "./api";
import { dispatch } from "./events";
import { state } from "./state";
Expand Down Expand Up @@ -112,4 +112,4 @@ const app = (state: AppState) => {
// sidechain to buffer intra-frame state updates. then only passes the
// most recent one to `app()` and its resulting UI tree to the
// `updateDOM()` transducer
sidechainPartitionRAF(state).transform(map(app), updateDOM());
syncRAF(state).transform(map(app), updateDOM());
28 changes: 9 additions & 19 deletions examples/color-themes/src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,12 @@ import {
} from "@thi.ng/color";
import { SYSTEM, XsAdd } from "@thi.ng/random";
import { Stream, debounce, reactive, stream, sync } from "@thi.ng/rstream";
import { serialize } from "@thi.ng/rstream-dot";
import { map } from "@thi.ng/transducers";
import { RANGE_IDs, type MainInputs, type MainOutputs } from "./api";
import { downloadACT } from "./palette";
import { attachSerializer, initFromHash } from "./serialize";

// import { toDot, walk } from "@thi.ng/rstream-dot";

const themePart = (
range: ColorRangePreset,
base: LCH | CSSColorName,
Expand Down Expand Up @@ -114,20 +113,11 @@ sync({
// (also uncomment rstream-dot import above)
// see: https://twitter.com/thing_umbrella/status/1363844585907249156

// console.log(
// toDot(
// walk(
// [
// ...Object.values(parts),
// variance,
// num,
// sorted,
// seed,
// downloadTrigger,
// ],
// {
// values: true,
// }
// )
// )
// );
console.log(
serialize(
[...Object.values(parts), variance, num, sorted, seed, downloadTrigger],
{
values: true,
}
)
);
10 changes: 2 additions & 8 deletions examples/fft-synth/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import { canvas } from "@thi.ng/hdom-canvas";
import { fit, fitClamped } from "@thi.ng/math";
import {
fromAtom,
fromDOMEvent,
merge,
sidechainPartitionRAF,
sync,
} from "@thi.ng/rstream";
import { fromAtom, fromDOMEvent, merge, sync, syncRAF } from "@thi.ng/rstream";
import { gestureStream } from "@thi.ng/rstream-gestures";
import { map, mapIndexed } from "@thi.ng/transducers";
import { updateDOM } from "@thi.ng/transducers-hdom";
Expand Down Expand Up @@ -85,4 +79,4 @@ const app = () => {
// sidechain to buffer intra-frame state updates. then only passes the
// most recent one to `app()` and its resulting UI tree to the
// `updateDOM()` transducer
sidechainPartitionRAF(main).transform(map(app()), updateDOM());
syncRAF(main).transform(map(app()), updateDOM());
10 changes: 2 additions & 8 deletions examples/imgui/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,7 @@ import {
import { GridLayout, gridLayout, layoutBox } from "@thi.ng/layout";
import { PI, clamp } from "@thi.ng/math";
import { setInManyUnsafe } from "@thi.ng/paths";
import {
fromAtom,
fromDOMEvent,
merge,
sidechainPartitionRAF,
sync,
} from "@thi.ng/rstream";
import { fromAtom, fromDOMEvent, merge, sync, syncRAF } from "@thi.ng/rstream";
import { gestureStream } from "@thi.ng/rstream-gestures";
import { float } from "@thi.ng/strings";
import { comp, iterator, map, mapcat, step } from "@thi.ng/transducers";
Expand Down Expand Up @@ -563,4 +557,4 @@ const main = sync({
// sidechain to buffer intra-frame state updates. then only passes the
// most recent one to `app()` and its resulting UI tree to the
// `updateDOM()` transducer
sidechainPartitionRAF(main).transform(map(app()), updateDOM());
syncRAF(main).transform(map(app()), updateDOM());
7 changes: 4 additions & 3 deletions examples/rotating-voronoi/src/stream-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ keyStreamConditional.next(<any>{});

export const scaleStream = reactive(1);
export const animationStream = reactive(true);
export const frameStreamConditional = fromRAF()
.subscribe(sidechainToggle<number, boolean>(animationStream))
.transform(scan(count()));
export const frameStreamConditional = sidechainToggle(
fromRAF(),
animationStream
).transform(scan(count()));

export type AppState = {
scaleValue: number;
Expand Down
4 changes: 2 additions & 2 deletions examples/rstream-dataflow/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { equiv } from "@thi.ng/equiv";
import { start } from "@thi.ng/hdom";
import { getIn } from "@thi.ng/paths";
import { fromRAF } from "@thi.ng/rstream";
import { toDot, walk } from "@thi.ng/rstream-dot";
import { serialize } from "@thi.ng/rstream-dot";
import { gestureStream } from "@thi.ng/rstream-gestures";
import { extract, initGraph, mul, node, node1 } from "@thi.ng/rstream-graph";
import { choices, comp, dedupe, map } from "@thi.ng/transducers";
Expand Down Expand Up @@ -167,4 +167,4 @@ start(() => [
//
// see for more info:
// https://github.com/thi-ng/umbrella/tree/develop/packages/rstream-dot
console.log(toDot(walk([gestures, raf])));
console.log(serialize([gestures, raf]));
2 changes: 1 addition & 1 deletion examples/rstream-event-loop/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ const requestPage = (offset: number) => {
// clear any active timeout before creating new one...
curr.timeoutID !== undefined && clearTimeout(curr.timeoutID);
// simulate pre-loading delay
const timeoutID = setTimeout(() => dispatch([PAGE_READY]), 250);
const timeoutID = setTimeout(() => dispatch([PAGE_READY]), 500);
// IMMUTABLY(!) update app state
state.next(
setInManyUnsafe(
Expand Down
8 changes: 4 additions & 4 deletions examples/rstream-event-loop/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { sidechainPartitionRAF } from "@thi.ng/rstream";
import { updateDOM } from "@thi.ng/transducers-hdom";
import { syncRAF } from "@thi.ng/rstream";
import { map } from "@thi.ng/transducers";
import { type AppState, NEXT, PREV } from "./api";
import { updateDOM } from "@thi.ng/transducers-hdom";
import { NEXT, PREV, type AppState } from "./api";
import { dispatch } from "./events";
import { state } from "./state";

Expand Down Expand Up @@ -72,4 +72,4 @@ const page = (_: any, pageID: number) => ["h1", `Page: ${pageID}`];
// sidechain to buffer intra-frame state updates. then only passes the
// most recent one to `app()` and its resulting UI tree to the
// `updateDOM()` transducer
sidechainPartitionRAF(state).transform(map(app), updateDOM());
syncRAF(state).transform(map(app), updateDOM());
4 changes: 2 additions & 2 deletions examples/rstream-hdom/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
sidechainPartitionRAF,
subscription,
sync,
syncRAF,
type ISubscribable,
type ISubscriber,
} from "@thi.ng/rstream";
Expand Down Expand Up @@ -45,7 +45,7 @@ const ctx = {
* @param ctx - ser context object
*/
const domUpdate = (root: HTMLElement, tree: ISubscribable<any>, ctx?: any) =>
sidechainPartitionRAF(tree).transform(updateDOM({ root, ctx }));
syncRAF(tree).transform(updateDOM({ root, ctx }));

/**
* Generic button component.
Expand Down
8 changes: 4 additions & 4 deletions examples/trace-bitmap/src/components/export.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { div } from "@thi.ng/hiccup-html";
import {
exportJsonTrigger,
exportSvgTrigger,
geometryStats,
jsonExportTrigger,
svgExportTrigger,
} from "../state/process";
import { smallButton, title } from "./common";

Expand All @@ -14,6 +14,6 @@ export const exportControls = div(
),
},
title("Export"),
smallButton(() => exportSvgTrigger.next(true), "export SVG"),
smallButton(() => exportJsonTrigger.next(true), "export JSON")
smallButton(() => svgExportTrigger.next(true), "export SVG"),
smallButton(() => jsonExportTrigger.next(true), "export JSON")
);
82 changes: 45 additions & 37 deletions examples/trace-bitmap/src/state/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import { isString } from "@thi.ng/checks";
import { FMT_yyyyMMdd_HHmmss } from "@thi.ng/date";
import { downloadWithMime } from "@thi.ng/dl-asset";
import {
Group,
asSvg,
group,
line,
points,
polyline,
rect,
splitArcLength,
svgDoc,
Expand All @@ -16,10 +15,24 @@ import { type AxiDrawAttribs } from "@thi.ng/geom-axidraw";
import { traceBitmap } from "@thi.ng/geom-trace-bitmap";
import { smoothStep } from "@thi.ng/math";
import { IntBuffer } from "@thi.ng/pixel";
import { fromView, reactive, stream, sync, syncRAF } from "@thi.ng/rstream";
import { keep, map, sideEffect } from "@thi.ng/transducers";
import {
Stream,
fromView,
reactive,
sidechainTrigger,
stream,
sync,
syncRAF,
} from "@thi.ng/rstream";
import { keep, map } from "@thi.ng/transducers";
import { mulN2, type Vec, type VecPair } from "@thi.ng/vectors";
import { DITHER_MODES, THEME, TRACE_MODES, type LayerParams } from "../api";
import {
DITHER_MODES,
THEME,
TRACE_MODES,
type AxiDrawConfig,
type LayerParams,
} from "../api";
import { DB } from "./atom";
import { addLayer } from "./layers";

Expand Down Expand Up @@ -57,8 +70,6 @@ export const canvasState = syncRAF(fromView(DB, { path: ["canvas"] }), {
id: "canvasState",
});

const axiConfig = fromView(DB, { path: ["axi"] });

/**
* Main stream combinator, initially subscribed only to layer order and the
* processed image. When adding/removing layers (via {@link addLayer} and
Expand All @@ -77,14 +88,15 @@ export const main = sync({
src: {
__order: layerOrder,
__img: imageProcessor,
__axi: axiConfig,
__axi: <Stream<AxiDrawConfig>>fromView(DB, { path: ["axi"] }),
},
clean: true,
id: "main",
xform: map((job) => {
const root = group({ stroke: "none" });
// need to copy pixel buffer because it will be mutated during vectorization
const img = job.__img.copy();
const axi = job.__axi;
// keep stats
let numLines = 0;
let numPoints = 0;
Expand Down Expand Up @@ -119,16 +131,17 @@ export const main = sync({
if (lines && lines.length) {
numLines += lines.length;
root.children.push(
withAttribs(
<Group>splitArcLength(
group(
{ stroke: layer.color },
lines.map(([a, b]) => line(a, b))
),
job.__axi.maxDist
)[0],
{ __axi: <AxiDrawAttribs>{ interleave: { num: 1 } } },
false
splitArcLength(
group(
{
stroke: layer.color,
__axi: <AxiDrawAttribs>{
interleave: { num: 1 },
},
},
lines.map(([a, b]) => polyline([a, b]))
),
axi.maxDist
)
);
}
Expand All @@ -138,7 +151,7 @@ export const main = sync({
points(pts, {
fill: layer.color,
__axi: <AxiDrawAttribs>{
interleave: { num: job.__axi.maxPoints },
interleave: { num: axi.maxPoints },
},
})
);
Expand Down Expand Up @@ -207,52 +220,47 @@ export const scene = sync({
/**
* Trigger stream to initiate SVG export.
*/
export const exportSvgTrigger = stream<boolean>({ id: "triggerSVG" });
export const svgExportTrigger = stream<boolean>({ id: "triggerSVG" });

/**
* Stream combinator to perform SVG export.
*/
sync({
const svgExportSources = sync({
src: {
_: exportSvgTrigger,
geo: main,
img: imageProcessor,
canvas: canvasState,
bg: fromView(DB, { path: ["canvas", "bg"] }),
},
reset: true,
id: "exportSVG",
xform: sideEffect(({ geo, img, canvas }) =>
});

sidechainTrigger(svgExportSources, svgExportTrigger).subscribe({
next: ({ geo, img, bg }) =>
downloadWithMime(
`trace-${FMT_yyyyMMdd_HHmmss()}.svg`,
asSvg(
svgDoc(
{ stroke: "none" },
rect([0, 0], img.size, { fill: canvas.bg }),
rect([0, 0], img.size, { fill: bg }),
geo
)
),
{ mime: "image/svg+xml" }
)
),
),
});

/**
* Trigger stream to initiate SVG export.
*/
export const exportJsonTrigger = stream<boolean>({ id: "triggerJSON" });
export const jsonExportTrigger = stream<boolean>({ id: "triggerJSON" });

/**
* Stream combinator to perform JSON (thi.ng/hiccup) export
*/
sync({
src: { _: exportJsonTrigger, geo: main },
reset: true,
id: "exportJSON",
xform: sideEffect(({ geo }) =>
sidechainTrigger(main, jsonExportTrigger).subscribe({
next: (geo) =>
downloadWithMime(
`trace-${FMT_yyyyMMdd_HHmmss()}.json`,
JSON.stringify(geo.toHiccup()),
{ mime: "application/json" }
)
),
),
});
8 changes: 4 additions & 4 deletions examples/trace-bitmap/src/state/viz.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import { DB } from "./atom";
import { canvasGestures } from "./canvas";
import {
canvasState,
exportJsonTrigger,
exportSvgTrigger,
geometryStats,
imageProcessor,
jsonExportTrigger,
layerOrder,
svgExportTrigger,
} from "./process";

/**
Expand All @@ -24,8 +24,8 @@ export const visualizeTopology = () => {
canvasState,
canvasGestures,
geometryStats,
exportSvgTrigger,
exportJsonTrigger,
svgExportTrigger,
jsonExportTrigger,
...mapcat((layer) => vals(layer.ctrls), vals(layers)),
];
console.log(serialize(roots));
Expand Down
Loading

0 comments on commit 55de86b

Please sign in to comment.