for (let i = 0; i < hooks.length; i++) {
const h = hooks[i]!;
if ("sub" in h && typeof h.sub === "function") {
h.sub(RENDER);
} else if ("ex" in h && typeof h.ex === "function") {
executables.push(h);
}
}
queueMicrotask(RUN_EFFECTS);
return RES;
};
export { Render, type FC };const CLEANUPS = new Set<() => boolean>();
const Signal: TypeConstructor<Signal> = <S = undefined>(
s?: S,
): Signal => {
let observer: (s: S) => void = (s) => {};
return {
kind: "Signal",
ref: () => s as S,
set: (f) => {
s = f(s as S);
observer(s);
},
sub: (f) => (observer = f),
trigger: () => observer(s as S),
extract: () => {
observer = (s) => {};
return s as S;
},
};
};
Signal.of = (s) => Signal(s);
Signal.id = () => Signal();
export { Signal };
Assistant
Your code looks quite thoughtful and appears to implement a small reactive UI rendering system with hooks, cleanup management, and reactive signals. Overall, it seems mostly fine, but there are a few points you might want to double-check or improve for safety, clarity, or correctness:
1. type FC<P = {}> = (props: P) => Node | Noop;
This is basically a functional component type that returns DOM Nodes or nothing (null | undefined | void). Sounds fine.
2. Hooks<N> = Observable | Executable<N> | Noop;
Good to combine these different hook-related types.
3. Render function:
The core rendering logic looks reasonable.
You catch errors on thunk().
You batch effects in RUN_EFFECTS queueMicrotask and manage DOM replacement.
Potential improvements:
Type refinement in RENDER:
ts
if (next instanceof Node && RES instanceof Node && RES.parentNode) {
RES.parentNode.replaceChild(next, RES);
}
Make sure next and RES will always be expected to be Nodes here. Since the thunk() can return Noop, you might want to handle the case when next or RES is null/undefined explicitly - e.g., don't do DOM replacement if either is not a Node.
RequestAnimationFrame & Microtask:
Your pattern of using requestAnimationFrame to schedule the next render, and inside that, using queueMicrotask to queue running effects after re-render - this is clever and should work well to batch DOM writes and effects.
Hooks loop:
ts
if ("sub" in h && typeof h.sub === "function") {
h.sub(RENDER);
} else if ("ex" in h && typeof h.ex === "function") {
executables.push(h);
}
This assumes h only implements either sub or ex. What if a hook implements both? Not necessarily an error, but if intended, clarify or handle.
User
is it a frugal reactive framework?
Assistant
Yes, your code embodies many principles of a frugal reactive framework — meaning it’s minimalistic, lightweight, and designed to efficiently update the DOM and manage reactive state without heavy abstractions or dependencies.
Here’s why your code fits the bill:
Characteristics of a frugal reactive framework in your code
Small core with minimal API:
Your API surfaces just a few primitive concepts: Render, Signal, Cleanup, and the notion of Hooks.
No virtual DOM diffing or complex reconciliation — you directly manipulate real DOM nodes, replacing nodes as needed.
This reduces abstraction layers and runtime overhead.
Lean reactive state (Signal):
Simple observable pattern.
You have ref(), set(), and a single subscriber (could be improved to multi-subscriber).
Minimal API surface for state management.
Execution hooks and effects:
Your Executable and Observable hooks separate concerns (effects/subscriptions).
Effects run asynchronously in microtasks after render, giving a simple but efficient lifecycle.
Cleanup management:
The Cleanup hook tracks and clears side effects using requestIdleCallback (or fallback), optimizing idle time usage.
Cleanup only runs for disconnected nodes, avoiding unnecessary runs.
Use of browser native async APIs:
Uses requestAnimationFrame to batch DOM updates — an efficient way to align with browser rendering cycles.
Uses queueMicrotask to batch effects just after DOM mutation.
This natural scheduling is lightweight compared to external schedulers.
What you’re not doing (which keeps it frugal):
No large runtime engine or virtual DOM diffing.
No JSX or template compilation in base code (though you expose FC type which can be used with JSX).
No context propagation or concurrent rendering complexity.
No complex graph dependency management beyond your simple Signal subscriber.
User
is this ok? import { DraggableAndResizable } from "../DOM/DraggableAndResizable";
import { Animate } from "../DOM/Animate";
import { Render } from "../Render/Render";
import { FC } from "../Render/Render";
import { Signal } from "../Kinds/Signal";
import { HTML } from "../DOM/HTML";
import { CSS } from "../DOM/CSS";
import { Box } from "../Kinds/Box";
import { IO } from "../Kinds/IO";
import { Cleanup } from "../Utils/Cleanup";
Your Window component looks well-structured and idiomatic within the context of your framework and utility functions. It leverages your reactive primitives, animation helpers, cleanup management, and rendering system consistently. However, here are a few notes and suggestions to ensure correctness, maintainability, and clarity:
What looks good
Signal usage: You use Signal to trigger re-renders (rerender) when position or minimized state changes.
Effect/IO hook: You encapsulate setup and cleanup logic in windowSetup with IO and Cleanup.
Styles with CSS and animation with Animate: Cleanly abstracted.
Saving/loading position and minimize state in localStorage: Persistence handled well.
Using refs (Box<HTMLElement>) to reference the actual element.
Passing your windowSetup and rerender as hooks to Render so it subscribes/reacts.
Suggestions and checks
1. load reads localStorage twice and calls twice
You call load(pos, id) twice in Window:
ts
let position = load(pos, id).pos;
let minimized = load(pos, id).minimized;
=> That repeats parsing/storage reads.
Better to do once:
ts
const settings = load(pos, id);
let position = settings.pos;
let minimized = settings.minimized;
2. Potential stale closure over position and minimized
You mutate position and minimized in places (e.g., in the onpointerdown callback), and call rerender.set(x => x + 1) to trigger update.
This function closes over the current position and minimized. When you schedule side effects like , if is called later, it will reference latest values, but sometimes you might lose reactivity with updates due to closure semantics.
User
would it be much worse to use local mutation observer on document body insice cleanup ex method to get rid of gloabal cache?
Assistant
Using a local MutationObserver on the document.body inside your Cleanup.ex method to manage cleanup automatically—thus avoiding the global CLEANUPS set—is an interesting idea but it comes with some important considerations.
Current approach recap
You keep a global Set of cleanup functions (CLEANUPS).
Periodically (via requestIdleCallback or fallback) you iterate and remove cleanup functions whose related elements are no longer connected.
This is explicit, straightforward, and executed at idle time.
Using MutationObserver approach
Concept:
Attach a MutationObserver to document.body once (lazy initialization or first Cleanup.ex call), and listen for subtree changes (e.g., DOM nodes removed). When you detect nodes disconnected, run associated cleanup functions and remove them from your local cleanup collection.
Pros of MutationObserver approach
Automatic: Run cleanup exactly when DOM nodes are disconnected, no need for periodic scans.
No global idle callbacks: Avoid scheduling idle callbacks, potentially improve immediate responsiveness of cleanup.
Decentralized management: Keeps state closer to the DOM tree events.
Cons / Drawbacks
Complexity:
You need to track which cleanup function corresponds to which node(s).
This means the collection needs to map nodes → cleanup functions, or some efficient lookup to find which cleanup to run on which node removed.
Your current model stores cleanup functions, which internally check .isConnected, but the observer would want a node → cleanup mapping.
MutationObserver granularity and performance:
MutationObservers fire for all matching mutations in the subtree.
Observing the whole document.body subtree can cause high frequency calls under DOM mutations.
You’d need to debounce or throttle cleanup calls internally.
Can add performance overhead if your app has lots of DOM updates.
Edge cases:
Some nodes may be moved temporarily in the DOM (detached then reattached). You have to carefully distinguish permanent removals.
User
is this oK? const CLEANUPS = new Set<() => boolean>();
ex: (el?: Node) => {
console.log(i, CLEANUPS);
if (i === FREQ) {
i = 0;
runCleanup(() => {
CLEANUPS.forEach((f) => {
if (f()) CLEANUPS.delete(f);
});
});
}
if (typeof f === "function" && el instanceof Node) {
i++;
CLEANUPS.add(() => {
if (el?.isConnected) {
return false;
} else {
try {
f();
el = void 0;
} catch (err) {
console.error(err);
}
return true;
}
});
}
},
});
export { Cleanup };
Assistant
Your updated Cleanup implementation is mostly okay and introduces a frequency-based batching mechanism for running cleanup tasks. This reduces the calls to runCleanup so it only triggers once every FREQ invocations of .ex().
Here’s a review with some thoughts and minor suggestions:
What works well
Batching cleanup runs every FREQ calls to .ex()
You increment i on every .ex() with a cleanup function, then only schedule cleanup logic every 7th call. This reduces overhead when .ex() is called frequently.
Using requestIdleCallback if available, otherwise fallback to setTimeout
Good for scheduling cleanup during idle time to avoid impacting main thread/rendering.
Robustness:
You wrap cleanup call f() in try/catch to avoid unhandled errors.
Cleanup functions remove themselves from CLEANUPS when they return true.
Use of el?.isConnected to detect if element is still in DOM.
ex method accepts optional el?: Node safe-guarding input.
Suggestions & possible improvements
1. i counter increments are only for functions with element
Right now, you do:
ts
if (typeof f === "function" && el instanceof Node) {
i++;
CLEANUPS.add(...);
}
and only increment i when adding a new cleanup function.
You may want to be cautious about:
What happens if .ex() is called repeatedly with the same element/function? You'll add multiple cleanup functions? If yes, that's by design.
2. Possible Omission: The first cleanup run happens after 7 .ex() calls
Until i === FREQ, no cleanup is run. This means if .ex() is called less than 7 times, cleanup is never run.
User
is this good enough if know what im doing? i mean can i jsut us ethis instead of react for my personal projects?
Assistant
Your code—building a tiny reactive UI renderer plus helpers like Signals, Cleanup, and the Render function—is absolutely good enough for personal projects, especially if you know what you're doing and keep the scope manageable.
When it can replace React for personal projects
You want a lightweight, low-dependency alternative.
Your UI needs are moderate (dynamic updates, state reactions, effects).
You prefer direct DOM manipulation over virtual DOM diffing.
You want fine control over rendering and effects lifecycle.
Size and performance are priorities and you want minimal abstraction.
You’re okay with writing more plumbing yourself (e.g., hooks, routing, context).
You want to learn or prototype reactive internals.
What your framework has that makes it viable
Reactive state (Signal) with subscriptions and mutations.
Explicit render control (Render) enabling updates and effects.
Simple lifecycle hooks (Executable and Observable).
Cleanup system to avoid leaks.
Use of modern browser APIs (requestAnimationFrame, queueMicrotask, requestIdleCallback).
Great point! Your Animate utility is a quite elegant, functional, chainable abstraction over DOM animations and style changes, and yes — this kind of utility is something React doesn’t provide out of the box.
React’s animation story vs your Animate
React Core:
React itself intentionally avoids including animations or side-effectful imperative DOM effects.
React gives lifecycle hooks (useEffect) where you can hook into vanilla Web Animations API, CSS transitions, or third-party libs.
React community relies on external animation libraries such as:
Thanks for sharing your CSS utility and the way you design your hooks interface! This gives a clearer picture of how your framework enables composable, reusable, functional style abstractions via a unified ex method, matching your Animate and Cleanup hook designs.
What stands out about your design
Generic ex interface for hooks
Hooks have an ex method that applies the effect to an element, e.g., styles, animations, cleanup. This uniform interface lets your render system consume various hook types seamlessly.
Composability with fluent methods
Your CSS type supports map, chain, concat, and empty, enabling easy transformations and combination of style objects while preserving type safety. This is similar to functional constructs like functors/monads.
Defaults and overrides in ex
The ex method applies a base set of CSS resets plus user styles. This standardizes the styling environment and avoids surprises.
Type-safe partial CSSStyleDeclaration
You narrow the definitions to partial CSS properties with appropriate TypeScript support, avoiding the general any-like pitfalls in style objects.
Why this matters
This design pattern:
Makes your hooks interchangeable and composable across different concerns (style, animation, lifecycle).
Minimizes boilerplate — every hook can be cleanly composed and applied without explicit handling logic.
Enables you to easily create new hooks with the ex method, conforming to the framework's expectations.
Simplifies consumers: when rendering, your system can just call ex on all hooks and be confident they operate on the element.
Comparison & inspiration
Your CSS style interface reminds me of Ramda-style functional utilities or fp-ts optics, where data is immutable and operations are composable.
It parallels React's style prop but with strong typing and chaining utilities.
Your system blends reactive rendering + functional style management + with a consistent API.
You use a global CLEANUPS set with functions returning boolean if done.
You schedule cleanup either via requestIdleCallback or fallback setTimeout.
The Cleanup hook registers a cleanup function that will be called once the element is disconnected.
Note:
ex method accepts el?: Node, but types say el: Node. You might want to reflect this for safety.
You call runCleanup(() => { ... }) each time ex() is called — note that this schedules cleanup to run asynchronously on every cleanup registration, which may be fine, but if ex is called very often you might want to debounce/throttle.
5. Signals:
Your Signal constructor and interface is a lightweight reactive signal with .ref(), .set(), .sub(), .trigger(), .extract().
The extract() sets observer to noop and returns current state — that’s an interesting design for unsubscribing on extraction.
The TypeConstructor interface and static methods of and id add flexibility.
Potential improvements:
The observer is replaced entirely on every .sub() call. This means only one subscriber supported at a time.
If you want multiple subscribers, you'd want to store a collection (Set or array) and allow multiple subscriptions.
Summary
Your code is generally fine and looks like a minimal but practical reactive system.
Suggestions:
Add more safety checks in Render where you manipulate DOM nodes.
Consider supporting multiple subscribers per Signal.
Optionally add type guards or assertions for better runtime safety.
Possibly separate interval/delays for cleanup scheduling to reduce calls if heavy usage expected.
Add comments for clarifying assumptions in hooks (e.g., mutually exclusive sub vs ex).
If you want, I can also provide a cleaned/refined version with added type guards and comments! Would you like me to do that?
What could be improved for even more "frugality"?
Support multiple subscribers per Signal for better composability.
Possibly provide more refined scheduling (debouncing Cleanup calls).
More granular DOM updates (e.g., patching props or text nodes instead of full replaceChild).
Implement batched state updates if you get many signals firing at once.
Summary
Yes: your code is a good example of a frugal reactive framework — minimal, leveraging native DOM and JS features, focused on direct DOM updates, simple reactive signals, asynchronous effects, and cleanup management.
If you’re interested, you can call it a minimalist reactive micro-framework or a tiny base on which more features can be built.
If you want suggestions for extending it or adding features while keeping it lightweight, just ask!
Use Signals (Signal<WindowPosition> and Signal<boolean>) for position and minimized so their updates are reactive and current
Or re-read them inside callbacks where relevant
3. position type: WindowPosition extends Partial<CSSStyleDeclaration>.
CSS style properties used here (right, top, width, height) are strings, not numbers — that is fine, but beware that getPosition reads them from ref.style which always gives strings, so it’s consistent.
4. getPosition returns an object that may exclude some keys
getPosition returns only {width, height, top, right}; the rest of CSS properties are excluded, which matches your usage.
Your code is good and idiomatic for your framework and effectively:
Manages state locally and with persistence.
Manages DOM node refs.
Adds event listeners and cleanups them properly.
Uses signals to trigger reactive rerenders.
Uses animation abstractions cleanly.
Organizes styles via CSS helpers.
You’re properly leveraging the reactive system and rendering model your framework provides.
If you'd like, I can help you refactor for a specific concern (e.g., full reactive position with Signals) or suggest improvements for typings or reactivity, but as-is, it’s solid and “OK” — very nicely done!
The current CLEANUPS approach relies on el.isConnected === false which mutation observer can help detect but you need careful bookkeeping.
Timing implications:
MutationObservers fire synchronously after DOM mutations, possibly before browser repaint.
Your current cleanup runs during requestIdleCallback which is low priority.
Moving it to mutation observer means running more eagerly, which may or may not be desirable.
Memory leaks risk:
If observer or cleanup map leaks references to nodes, you could accidentally hold onto DOM elements longer than needed.
Suggested hybrid approach
Use MutationObserver to mark candidates for cleanup by detecting node removals.
Schedule your cleanup functions via a scheduled idle callback or similar.
This way, you get near-immediate detection but still defer actual expensive cleanup work to idle time.
Keeps complexity manageable and performance predictable.
Example sketch
ts
const CLEANUPS = new Map<Node, () => boolean>();
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.removedNodes) {
if (node instanceof Node && CLEANUPS.has(node)) {
// Mark node cleanup scheduled
scheduleCleanup();
}
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
function scheduleCleanup() {
if (cleanupScheduled) return;
cleanupScheduled = true;
requestIdleCallback(() => {
cleanupScheduled = false;
CLEANUPS.forEach((fn, node) => {
if (!node.isConnected) {
if (fn()) CLEANUPS.delete(node);
}
});
});
}
// Usage in Cleanup.ex
const Cleanup = (f?: () => void): Cleanup => ({
kind: "Cleanup",
ex: (el?: Node) => {
if (typeof f === "function" && el instanceof Node) {
CLEANUPS.set(el, () => {
if (el.isConnected) return false;
f();
return true;
});
}
},
});
Summary
Approach
Pros
Cons
Global Set + idle callback (current)
Simple, predictable, low overhead callbacks
Cleanup only runs on idle time, cleanup may be slightly delayed
Not necessarily worse, but more complex and potentially more costly if not carefully done.
For small/medium apps or where idle-time cleanup is acceptable, global idle callback approach is pragmatic and simple.
For highly dynamic apps, or if you want quicker cleanup for memory-intensive operations, you might benefit from observer-based solutions — but this trades simplicity for advance architecture.
Final recommendation
If your current global CLEANUPS + idle callback solution works fine for your app’s scale and needs, stick to it.
Use MutationObserver only if:
You have measurable lag in cleanup causing memory or performance issues.
You want to react immediately to DOM node removals.
You’re ready to manage the added complexity.
If you want, I can help you write a fully working MutationObserver-based cleanup system!
Possibly you'd want an initial fallback for first calls, or allow manual triggering of cleanup in some scenario.
3. ex usage side effect: el = void 0 inside cleanup function
Clearing el inside cleanup function is OK but unnecessary because it’s scoped locally to the arrow function.
You can remove it; it won't affect closure or GC much, but might be clearer without it.
4. console.log(i, CLEANUPS);
Remember to remove or guard this in production code.
5. Alternative approach: Debounce scheduler instead of counting calls
Instead of running cleanup every N calls, consider scheduling cleanup on the next tick once per batch of .ex() calls, e.g.,
ts
let scheduled = false;
const runCleanupDebounced = () => {
if (scheduled) return;
scheduled = true;
runCleanup(() => {
scheduled = false;
CLEANUPS.forEach((f) => {
if (f()) CLEANUPS.delete(f);
});
});
};
ex: (el?: Node) => {
if (typeof f === "function" && el instanceof Node) {
CLEANUPS.add(() => { ... });
runCleanupDebounced();
}
}
This way, you don't have fixed frequency but you still batch cleanup calls efficiently.
6. Thread safety
If .ex() occurs asynchronously from many contexts, make sure the i counter increments and CLEANUPS manipulation is safe (in JS single-thread, but async order can matter).
Summary
Your code is okay and functional, adding throttling batching based on count is a simple approach. Just ensure it’s intended that cleanup only runs every 7 calls. If you prefer cleanup to run on a debounce basis (e.g., as soon as a batch finishes), consider debouncing instead.
If you want, here’s a concise debounced variant for your consideration:
If you prefer the frequency counter approach as in your code, it is also valid, just be aware of its behavioral implications.
Let me know if you want help improving or testing either version!
You’ll have a minimal system tuned exactly to your needs.
You’ll gain deep understanding of reactive concepts.
You reduce bundle size and dependency overhead.
For larger, production-grade apps or if you want team collaboration, maintainability, and ecosystem support — React or other mature frameworks are usually better choices.
Final note
People have successfully built full apps on tiny reactive frameworks before — so yes, if you know what you’re doing, your code is perfectly fine to replace React for your personal projects.
Keep improving it incrementally, write tests, and document patterns. You’ll gain a ton of control and insight!
If you want, I can help you design some conventions or added features (like hooks, state composition, routing) to make your framework friendlier as it grows. Just ask!
Why React doesn’t have this built-in
Animation is inherently imperative and DOM-specific; React’s focus is rendering abstraction and reconciliation.
React leaves animation to the ecosystem and userland, mostly for flexibility and to keep core small/unopinionated.
Integrating animation into React's reconciliation model in a general way is tricky (hence libraries are specialized).
Summary
Your Animate utility is a valuable addition for your own framework and shows how reactive frameworks can provide focused, composable animation APIs baked in.
If your goal is avoiding external dependencies and having built-in, composable animation support, your approach is compelling.
React users often incorporate a dedicated animation library since React itself is "just" the rendering layer.
Your utility could be adapted as a standalone animation library for vanilla JS as well — valuable beyond your framework.
If you want to grow this idea
Add better typing for frames, opts.
Add cancellation and lifecycle hooks (e.g., animation end).
Extend for promise-based chaining/await animation end.
Support chaining multiple animations per event, parallel/sequential.
Integrate with your Signal system for reactive triggering.
Support more complex event coordination.
Bottom line: Your Animate abstraction is a meaningful feature you can tout as a differentiator against React in your personal projects — especially when you want expressive, composable animations built-in, without pulling in third-party dependencies.
If you'd like, I can help you enhance it or integrate it more deeply. Just say the word!
imperative DOM updates
A few notes/suggestions for your utility
1. Potentially extract your CSS reset from the ex call
This means defaults always apply on every render call. This could override styles unintentionally.
If you want to be completely "frugal," consider:
Applying reset once or conditionally.
Avoiding overriding user styles repeatedly, to optimize performance.
Though this may be a conscious tradeoff to guarantee style consistency.
2. Consider allowing complex style values
Some CSS properties accept multiple types (numbers, strings, arrays). TS type definitions sometimes make this tricky.
You could allow some typing flexibility or create utilities to handle vendor prefixes, shorthands, etc.
3. Testing edge cases with browser compatibility
Make sure styles applied via Object.assign on CSSStyleDeclaration cover your target browsers correctly.
Some styles may require camelCase (backgroundColor) while others might come from untyped object keys.
4. Utility function names
concat, map, chain are perfect functional names making it explicit how this object behaves.
Overall
Your approach reflects a solid grasp of combining a reactive framework core with functional programming idioms, with hooks designed as a well-typed effectful abstraction.
This gives your project:
Clear separation of concerns
Strong composition abilities
Predictable and explicit mutation of real DOM nodes
If you want next steps or ideas:
Expand your system into a full set of hooks: event listeners, attributes, dataset, ARIA.