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

Implement async function component rendering #4571

Closed
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
10 changes: 5 additions & 5 deletions compat/client.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const { render, hydrate, unmountComponentAtNode } = require('preact/compat');

function createRoot(container) {
async function createRoot(container) {
return {
// eslint-disable-next-line
render: function (children) {
render(children, container);
render: async function (children) {
await render(children, container);
},
// eslint-disable-next-line
unmount: function () {
Expand All @@ -15,7 +15,7 @@ function createRoot(container) {

exports.createRoot = createRoot;

exports.hydrateRoot = function (container, children) {
hydrate(children, container);
exports.hydrateRoot = async function (container, children) {
await hydrate(children, container);
return createRoot(container);
};
10 changes: 5 additions & 5 deletions compat/client.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { render, hydrate, unmountComponentAtNode } from 'preact/compat';

export function createRoot(container) {
export async function createRoot(container) {
return {
// eslint-disable-next-line
render: function (children) {
render(children, container);
render: async function (children) {
await render(children, container);
},
// eslint-disable-next-line
unmount: function () {
Expand All @@ -13,8 +13,8 @@ export function createRoot(container) {
};
}

export function hydrateRoot(container, children) {
hydrate(children, container);
export async function hydrateRoot(container, children) {
await hydrate(children, container);
return createRoot(container);
}

Expand Down
10 changes: 5 additions & 5 deletions src/component.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export function getDomSibling(vnode, childIndex) {
* Trigger in-place re-rendering of a component.
* @param {Component} component The component to rerender
*/
function renderComponent(component) {
async function renderComponent(component) {
let oldVNode = component._vnode,
oldDom = oldVNode._dom,
commitQueue = [],
Expand All @@ -131,7 +131,7 @@ function renderComponent(component) {
newVNode._original = oldVNode._original + 1;
if (options.vnode) options.vnode(newVNode);

diff(
await diff(
component._parentDom,
newVNode,
oldVNode,
Expand All @@ -146,7 +146,7 @@ function renderComponent(component) {

newVNode._original = oldVNode._original;
newVNode._parent._children[newVNode._index] = newVNode;
commitRoot(commitQueue, newVNode, refQueue);
await commitRoot(commitQueue, newVNode, refQueue);

if (newVNode._dom != oldDom) {
updateParentDomPointers(newVNode);
Expand Down Expand Up @@ -218,15 +218,15 @@ export function enqueueRender(c) {
const depthSort = (a, b) => a._vnode._depth - b._vnode._depth;

/** Flush the render queue by rerendering all queued components */
function process() {
async function process() {
let c;
rerenderQueue.sort(depthSort);
// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary
// process() calls from getting scheduled while `queue` is still being consumed.
while ((c = rerenderQueue.shift())) {
if (c._dirty) {
let renderQueueLength = rerenderQueue.length;
renderComponent(c);
await renderComponent(c);
if (rerenderQueue.length > renderQueueLength) {
// When i.e. rerendering a provider additional new items can be injected, we want to
// keep the order from top to bottom with those new items so we can handle them in a
Expand Down
26 changes: 15 additions & 11 deletions src/diff/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
* @param {boolean} isHydrating Whether or not we are in hydration
* @param {any[]} refQueue an array of elements needed to invoke refs
*/
export function diff(
export async function diff(
parentDom,
newVNode,
oldVNode,
Expand Down Expand Up @@ -244,7 +244,11 @@
tmp != null && tmp.type === Fragment && tmp.key == null;
let renderResult = isTopLevelFragment ? tmp.props.children : tmp;

oldDom = diffChildren(
if (renderResult && renderResult.then) {
renderResult = await renderResult;
}

oldDom = await diffChildren(
parentDom,
isArray(renderResult) ? renderResult : [renderResult],
newVNode,
Expand Down Expand Up @@ -303,7 +307,7 @@
newVNode._children = oldVNode._children;
newVNode._dom = oldVNode._dom;
} else {
oldDom = newVNode._dom = diffElementNodes(
oldDom = newVNode._dom = await diffElementNodes(
oldVNode._dom,
newVNode,
oldVNode,
Expand All @@ -326,26 +330,26 @@
* which have callbacks to invoke in commitRoot
* @param {VNode} root
*/
export function commitRoot(commitQueue, root, refQueue) {
export async function commitRoot(commitQueue, root, refQueue) {
for (let i = 0; i < refQueue.length; i++) {
applyRef(refQueue[i], refQueue[++i], refQueue[++i]);
}

if (options._commit) options._commit(root, commitQueue);

commitQueue.some(c => {
for (const c of commitQueue) {
try {
// @ts-expect-error Reuse the commitQueue variable here so the type changes
commitQueue = c._renderCallbacks;
c._renderCallbacks = [];
commitQueue.some(cb => {
for (const cb of commitQueue) {
// @ts-expect-error See above comment on commitQueue
cb.call(c);
});
await cb.call(c);
}
} catch (e) {
options._catchError(e, c._vnode);
}
});
}
}

/**
Expand All @@ -361,9 +365,9 @@
* to invoke in commitRoot
* @param {boolean} isHydrating Whether or not we are in hydration
* @param {any[]} refQueue an array of elements needed to invoke refs
* @returns {PreactElement}

Check failure on line 368 in src/diff/index.js

View workflow job for this annotation

GitHub Actions / Build & Test / Build & Test

Type 'PreactElement' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.
*/
function diffElementNodes(
async function diffElementNodes(
dom,
newVNode,
oldVNode,
Expand Down Expand Up @@ -510,7 +514,7 @@
} else {
if (oldHtml) dom.innerHTML = '';

diffChildren(
await diffChildren(
dom,
isArray(newChildren) ? newChildren : [newChildren],
newVNode,
Expand Down
10 changes: 5 additions & 5 deletions src/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { slice } from './util';
* @param {PreactElement | object} [replaceNode] Optional: Attempt to re-use an
* existing DOM tree rooted at `replaceNode`
*/
export function render(vnode, parentDom, replaceNode) {
export async function render(vnode, parentDom, replaceNode) {
// https://github.com/preactjs/preact/issues/3794
if (parentDom === document) {
parentDom = document.documentElement;
Expand Down Expand Up @@ -39,7 +39,7 @@ export function render(vnode, parentDom, replaceNode) {
// List of effects that need to be called after diffing.
let commitQueue = [],
refQueue = [];
diff(
await diff(
parentDom,
// Determine the new vnode tree and store it on the DOM element on
// our custom `_children` property.
Expand All @@ -65,14 +65,14 @@ export function render(vnode, parentDom, replaceNode) {
);

// Flush all queued effects
commitRoot(commitQueue, vnode, refQueue);
await commitRoot(commitQueue, vnode, refQueue);
}

/**
* Update an existing DOM element with data from a Preact virtual node
* @param {ComponentChild} vnode The virtual node to render
* @param {PreactElement} parentDom The DOM element to update
*/
export function hydrate(vnode, parentDom) {
render(vnode, parentDom, hydrate);
export async function hydrate(vnode, parentDom) {
await render(vnode, parentDom, hydrate);
}
50 changes: 50 additions & 0 deletions test/browser/asyncFunctionComponent.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { h, render } from 'preact';
import { useState, useEffect } from 'preact/hooks';
import { setupScratch, teardown } from '../_util/helpers';

describe('Async Function Component', () => {
let scratch;

beforeEach(() => {
scratch = setupScratch();
});

afterEach(() => {
teardown(scratch);
});

it('should render async function component correctly', async () => {
const AsyncComponent = async () => {
await new Promise(resolve => setTimeout(resolve, 50));
return <div>Async Component</div>;
};

render(<AsyncComponent />, scratch);
await new Promise(resolve => setTimeout(resolve, 100));

expect(scratch.innerHTML).to.equal('<div>Async Component</div>');
});

it('should handle async operations in function component', async () => {
const AsyncComponent = () => {
const [data, setData] = useState(null);

useEffect(() => {
const fetchData = async () => {
await new Promise(resolve => setTimeout(resolve, 50));
setData('Fetched Data');
};

fetchData();
}, []);

return <div>{data || 'Loading...'}</div>;
};

render(<AsyncComponent />, scratch);
expect(scratch.innerHTML).to.equal('<div>Loading...</div>');

await new Promise(resolve => setTimeout(resolve, 100));
expect(scratch.innerHTML).to.equal('<div>Fetched Data</div>');
});
});
Loading