From 633611056e194dd0b935f825fcdf6534e8a837ec Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Sat, 2 May 2020 21:09:38 -0400 Subject: [PATCH] create "catchTalkback" callbag operator --- src/Utilities/Callbag.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/Utilities/Callbag.ts b/src/Utilities/Callbag.ts index 61cc2c3..63328b9 100644 --- a/src/Utilities/Callbag.ts +++ b/src/Utilities/Callbag.ts @@ -189,3 +189,28 @@ export function map(f: (input: I) => O): (source: Callbag) => C }; } +/** + * Intercepts talkback data sent to a source and provides them to a closure instead. + * Does not disconnect signals; they are sent upstream as normal. + */ +export function catchTalkback(talkbackHandler: (data: TB) => void): (source: Source) => Callbag { + return (source: Source) => (type: START | DATA | END, data?: Callbag | TB) => { + if (type !== 0) return; + let sourceTalkback: Callbag | undefined; + const sink = data as Callbag; + source(0, (type: START | DATA | END, data?: Callbag | T) => { + if (type === 0) { + sourceTalkback = data as Callbag; + sink(0, (type: START | DATA | END, data?: Callbag | TB) => { + if (type === 1) { + talkbackHandler(data as TB); + } else { + sourceTalkback?.(type as 0 & 1 & 2, data); + } + }); + } else { + sink(type as 1 & 2, data); + } + }); + }; +}