Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add optimization #41

Merged
merged 1 commit into from
Jan 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions examples/todo/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { createState, upsert, useEffect } from "@idealjs/sapling";
import { createProxy, createRef, upsert, useEffect } from "@idealjs/sapling";

const TodoItem = (props: { name: number; count: number }) => {
let { name, count } = props;
const state = createState(0);
const ref = createState<HTMLParagraphElement>(null);
const state = createProxy({ val: 0 });
const ref = createRef<HTMLParagraphElement>(null);
useEffect(() => {
const handler = setInterval(() => {
state.val++;
Expand All @@ -25,7 +25,7 @@ const TodoItem = (props: { name: number; count: number }) => {

<button
onClick={() => {
ref.val?.appendChild(document.createElement("div"));
ref.current?.appendChild(document.createElement("div"));
}}
>
test element function
Expand All @@ -43,7 +43,9 @@ const TodoItem = (props: { name: number; count: number }) => {
};

const Component = () => {
const items = createState<{ id: number; count: number }[]>([]);
const items = createProxy<{ val: { id: number; count: number }[] }>({
val: [],
});
return (
<div>
<button
Expand Down
10 changes: 9 additions & 1 deletion packages/core/src/createElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ export class SaplingElement {
prev: SaplingElement | null = null,
): SaplingElement | null => {
if (child.el != null && prev?.el != null) {
if (child.el.parentElement != null) {
// skip append for optimization
return child;
}
this.el?.insertBefore(child.el, prev.el.nextSibling);
this.children.add(child);
return child;
Expand All @@ -118,7 +122,11 @@ export class SaplingElement {
// skip append for optimization
return child;
}
this.el?.appendChild(child.el);
if (this.el?.firstChild != null) {
this.el?.insertBefore(child.el, this.el?.firstChild);
} else {
this.el?.appendChild(child.el);
}
this.children.add(child);
return child;
}
Expand Down