Skip to content

Commit

Permalink
perf(system): avoid re-renders
Browse files Browse the repository at this point in the history
  • Loading branch information
juanrgm committed Sep 16, 2024
1 parent cb477af commit db37e9a
Showing 1 changed file with 5 additions and 32 deletions.
37 changes: 5 additions & 32 deletions packages/system/src/inspect.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {
children,
Component,
createComponent,
createContext,
createMemo,
JSX,
useContext,
} from "solid-js";
Expand All @@ -22,15 +22,15 @@ export type InspectResult = JSX.Element | ComponentObject;

export const InspectContext = createContext<{ enabled: boolean }>();

export function inspect(fn: () => JSX.Element): InspectResult[] {
export function inspectChildren(fn: () => JSX.Element): () => InspectResult[] {
const cb = createComponent(InspectContext.Provider, {
value: { enabled: true },
get children() {
return fn();
},
}) as any as () => any;
const result = cb();
return Array.isArray(result) ? result : [result];
}) as any;
const result = children(cb);
return result.toArray;
}

export function componentTrap<T>(fn: Component<T>): Component<T> {
Expand Down Expand Up @@ -62,30 +62,3 @@ export function isComponentObject(input: unknown, component?: Component) {
(!component || (input as PrivateComponentObject).Component === component)
);
}

export function resolveChildren(children: any): unknown {
if (typeof children === "function" && !children.length)
return resolveChildren(children());
if (Array.isArray(children)) {
const results: any[] = [];
for (let i = 0; i < children.length; i++) {
const result = resolveChildren(children[i]);
Array.isArray(result)
? // eslint-disable-next-line prefer-spread
results.push.apply(results, result)
: results.push(result);
}
return results;
}
return children;
}

export function inspectChildren(fn: () => any) {
const children = createMemo(() => inspect(fn));
const memo = createMemo(() => resolveChildren(children()) as any);
(memo as any).toArray = () => {
const c = memo();
return Array.isArray(c) ? c : c != null ? [c] : [];
};
return memo;
}

0 comments on commit db37e9a

Please sign in to comment.