Add source to show() callback

This commit is contained in:
aaron 2025-01-04 00:40:51 +00:00
parent 58a31a1b32
commit c796e48173
3 changed files with 84 additions and 17 deletions

View file

@ -1,16 +1,28 @@
local switch = require "./switch"
local derive = require "./derive"
local untrack = require "./untrack"
local function show<T>(source: () -> any, component: () -> T, fallback: (() -> T)?): () -> T?
local function truthy()
local function show<T, U>(source: () -> T?, component: (() -> T) -> U, fallback: (() -> U)?): () -> U?
local truthy = derive(function()
return not not source()
end
end)
return switch(truthy) {
[true] = component,
[false] = fallback,
}
-- seemingly redundant derivation to extend the reactive graph so that
-- the propogation of the source's update is delayed, giving time for
-- the show() scope to be destroyed before potential effects registered
-- by the component can run when they should not run
-- todo: are there cases this method does not cover?
local derived = derive(function()
return source()
end)
return derive(function()
return
if truthy() then untrack(function() return component(derived :: () -> T) end)
elseif fallback then untrack(fallback)
else nil
end)
end
return show ::
(<T>(source: () -> any, component: () -> T) -> () -> T?) &
(<T, U>(source: () -> any, component: () -> T, fallback: () -> U) -> () -> (T | U)?)
return show :: (
( <T, U>(source: () -> T?, component: (() -> T) -> U) -> () -> U? )
)