0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-23 21:53:55 -05:00
astro/packages/integrations/react/server.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

212 lines
6.1 KiB
JavaScript
Raw Normal View History

2024-04-17 03:38:53 -05:00
import opts from 'astro:react:opts';
import React from 'react';
import ReactDOM from 'react-dom/server';
import { incrementId } from './context.js';
import StaticHtml from './static-html.js';
2022-06-23 10:12:46 -05:00
const slotName = (str) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase());
const reactTypeof = Symbol.for('react.element');
async function check(Component, props, children) {
// Note: there are packages that do some unholy things to create "components".
// Checking the $$typeof property catches most of these patterns.
if (typeof Component === 'object') {
return Component['$$typeof'].toString().slice('Symbol('.length).startsWith('react');
}
if (typeof Component !== 'function') return false;
2023-12-20 14:00:58 -05:00
if (Component.name === 'QwikComponent') return false;
// Preact forwarded-ref components can be functions, which React does not support
2023-12-18 08:42:49 -05:00
if (typeof Component === 'function' && Component['$$typeof'] === Symbol.for('react.forward_ref'))
return false;
if (Component.prototype != null && typeof Component.prototype.render === 'function') {
return React.Component.isPrototypeOf(Component) || React.PureComponent.isPrototypeOf(Component);
}
let isReactComponent = false;
function Tester(...args) {
try {
const vnode = Component(...args);
if (vnode && vnode['$$typeof'] === reactTypeof) {
isReactComponent = true;
}
} catch {}
return React.createElement('div');
}
await renderToStaticMarkup(Tester, props, children, {});
return isReactComponent;
}
async function getNodeWritable() {
let nodeStreamBuiltinModuleName = 'node:stream';
2022-08-30 02:25:34 -05:00
let { Writable } = await import(/* @vite-ignore */ nodeStreamBuiltinModuleName);
return Writable;
}
function needsHydration(metadata) {
// Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot`
return metadata.astroStaticSlot ? !!metadata.hydrate : true;
}
async function renderToStaticMarkup(Component, props, { default: children, ...slotted }, metadata) {
let prefix;
if (this && this.result) {
2023-05-04 09:25:03 -05:00
prefix = incrementId(this.result);
}
const attrs = { prefix };
delete props['class'];
const slots = {};
for (const [key, value] of Object.entries(slotted)) {
const name = slotName(key);
slots[name] = React.createElement(StaticHtml, {
hydrate: needsHydration(metadata),
value,
2023-05-17 09:20:24 -05:00
name,
});
}
// Note: create newProps to avoid mutating `props` before they are serialized
2022-06-23 10:12:46 -05:00
const newProps = {
...props,
...slots,
2022-06-23 10:12:46 -05:00
};
const newChildren = children ?? props.children;
if (children && opts.experimentalReactChildren) {
attrs['data-react-children'] = true;
2023-08-16 12:44:01 -05:00
const convert = await import('./vnode-children.js').then((mod) => mod.default);
newProps.children = convert(children);
} else if (newChildren != null) {
newProps.children = React.createElement(StaticHtml, {
hydrate: needsHydration(metadata),
2023-05-17 09:20:24 -05:00
value: newChildren,
});
}
Actions: React 19 progressive enhancement support (#11071) * deps: react 19 * feat: react progressive enhancement with useActionState * refactor: revert old action state implementation * feat(test): react 19 action with useFormStatus * fix: remove unused context arg * fix: wrote actions to wrong test fixture! * deps: revert react 19 beta to 18 for actions-blog fixture * chore: remove unused overrides * chore: remove unused actions export * chore: spaces vs tabs ugh * chore: fix conflicting fixture names * chore: changeset * chore: bump changeset to minor * Actions: support React 19 `useActionState()` with progressive enhancement (#11074) * feat(ex): Like with useActionState * feat: useActionState progressive enhancement! * feat: getActionState utility * chore: revert actions-blog fixture experimentation * fix: add back actions.ts export * feat(test): Like with use action state test * fix: stub form state client-side to avoid hydration error * fix: bad .safe chaining * fix: update actionState for client call * fix: correctly resume form state client side * refactor: unify and document reactServerActionResult * feat(test): useActionState assertions * feat(docs): explain my mess * refactor: add experimental_ prefix * refactor: move all react internals to integration * chore: remove unused getIslandProps * chore: remove unused imports * chore: undo format changes * refactor: get actionResult from middleware directly * refactor: remove bad result type * fix: like button disabled timeout * chore: changeset * refactor: remove request cloning * Update .changeset/gentle-windows-enjoy.md Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> * changeset grammar tense --------- Co-authored-by: Emanuele Stoppa <my.burning@gmail.com> Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2024-05-22 07:24:55 -05:00
const formState = this ? await getFormState(this) : undefined;
if (formState) {
attrs['data-action-result'] = JSON.stringify(formState[0]);
attrs['data-action-key'] = formState[1];
attrs['data-action-name'] = formState[2];
}
const vnode = React.createElement(Component, newProps);
const renderOptions = {
2023-05-04 09:25:03 -05:00
identifierPrefix: prefix,
Actions: React 19 progressive enhancement support (#11071) * deps: react 19 * feat: react progressive enhancement with useActionState * refactor: revert old action state implementation * feat(test): react 19 action with useFormStatus * fix: remove unused context arg * fix: wrote actions to wrong test fixture! * deps: revert react 19 beta to 18 for actions-blog fixture * chore: remove unused overrides * chore: remove unused actions export * chore: spaces vs tabs ugh * chore: fix conflicting fixture names * chore: changeset * chore: bump changeset to minor * Actions: support React 19 `useActionState()` with progressive enhancement (#11074) * feat(ex): Like with useActionState * feat: useActionState progressive enhancement! * feat: getActionState utility * chore: revert actions-blog fixture experimentation * fix: add back actions.ts export * feat(test): Like with use action state test * fix: stub form state client-side to avoid hydration error * fix: bad .safe chaining * fix: update actionState for client call * fix: correctly resume form state client side * refactor: unify and document reactServerActionResult * feat(test): useActionState assertions * feat(docs): explain my mess * refactor: add experimental_ prefix * refactor: move all react internals to integration * chore: remove unused getIslandProps * chore: remove unused imports * chore: undo format changes * refactor: get actionResult from middleware directly * refactor: remove bad result type * fix: like button disabled timeout * chore: changeset * refactor: remove request cloning * Update .changeset/gentle-windows-enjoy.md Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> * changeset grammar tense --------- Co-authored-by: Emanuele Stoppa <my.burning@gmail.com> Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2024-05-22 07:24:55 -05:00
formState,
2023-05-04 09:25:03 -05:00
};
let html;
if ('renderToReadableStream' in ReactDOM) {
html = await renderToReadableStreamAsync(vnode, renderOptions);
} else {
html = await renderToPipeableStreamAsync(vnode, renderOptions);
}
return { html, attrs };
}
Actions: React 19 progressive enhancement support (#11071) * deps: react 19 * feat: react progressive enhancement with useActionState * refactor: revert old action state implementation * feat(test): react 19 action with useFormStatus * fix: remove unused context arg * fix: wrote actions to wrong test fixture! * deps: revert react 19 beta to 18 for actions-blog fixture * chore: remove unused overrides * chore: remove unused actions export * chore: spaces vs tabs ugh * chore: fix conflicting fixture names * chore: changeset * chore: bump changeset to minor * Actions: support React 19 `useActionState()` with progressive enhancement (#11074) * feat(ex): Like with useActionState * feat: useActionState progressive enhancement! * feat: getActionState utility * chore: revert actions-blog fixture experimentation * fix: add back actions.ts export * feat(test): Like with use action state test * fix: stub form state client-side to avoid hydration error * fix: bad .safe chaining * fix: update actionState for client call * fix: correctly resume form state client side * refactor: unify and document reactServerActionResult * feat(test): useActionState assertions * feat(docs): explain my mess * refactor: add experimental_ prefix * refactor: move all react internals to integration * chore: remove unused getIslandProps * chore: remove unused imports * chore: undo format changes * refactor: get actionResult from middleware directly * refactor: remove bad result type * fix: like button disabled timeout * chore: changeset * refactor: remove request cloning * Update .changeset/gentle-windows-enjoy.md Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> * changeset grammar tense --------- Co-authored-by: Emanuele Stoppa <my.burning@gmail.com> Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2024-05-22 07:24:55 -05:00
/**
* @returns {Promise<[actionResult: any, actionKey: string, actionName: string] | undefined>}
*/
async function getFormState({ result }) {
const { request, actionResult } = result;
if (!actionResult) return undefined;
if (!isFormRequest(request.headers.get('content-type'))) return undefined;
const { searchParams } = new URL(request.url);
Actions: React 19 progressive enhancement support (#11071) * deps: react 19 * feat: react progressive enhancement with useActionState * refactor: revert old action state implementation * feat(test): react 19 action with useFormStatus * fix: remove unused context arg * fix: wrote actions to wrong test fixture! * deps: revert react 19 beta to 18 for actions-blog fixture * chore: remove unused overrides * chore: remove unused actions export * chore: spaces vs tabs ugh * chore: fix conflicting fixture names * chore: changeset * chore: bump changeset to minor * Actions: support React 19 `useActionState()` with progressive enhancement (#11074) * feat(ex): Like with useActionState * feat: useActionState progressive enhancement! * feat: getActionState utility * chore: revert actions-blog fixture experimentation * fix: add back actions.ts export * feat(test): Like with use action state test * fix: stub form state client-side to avoid hydration error * fix: bad .safe chaining * fix: update actionState for client call * fix: correctly resume form state client side * refactor: unify and document reactServerActionResult * feat(test): useActionState assertions * feat(docs): explain my mess * refactor: add experimental_ prefix * refactor: move all react internals to integration * chore: remove unused getIslandProps * chore: remove unused imports * chore: undo format changes * refactor: get actionResult from middleware directly * refactor: remove bad result type * fix: like button disabled timeout * chore: changeset * refactor: remove request cloning * Update .changeset/gentle-windows-enjoy.md Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> * changeset grammar tense --------- Co-authored-by: Emanuele Stoppa <my.burning@gmail.com> Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2024-05-22 07:24:55 -05:00
const formData = await request.clone().formData();
/**
* The key generated by React to identify each `useActionState()` call.
* @example "k511f74df5a35d32e7cf266450d85cb6c"
*/
const actionKey = formData.get('$ACTION_KEY')?.toString();
/**
* The action name returned by an action's `toString()` property.
* This matches the endpoint path.
* @example "/_actions/blog.like"
*/
const actionName =
searchParams.get('_astroAction') ??
/* Legacy. TODO: remove for stable */ formData
.get('_astroAction')
?.toString();
Actions: React 19 progressive enhancement support (#11071) * deps: react 19 * feat: react progressive enhancement with useActionState * refactor: revert old action state implementation * feat(test): react 19 action with useFormStatus * fix: remove unused context arg * fix: wrote actions to wrong test fixture! * deps: revert react 19 beta to 18 for actions-blog fixture * chore: remove unused overrides * chore: remove unused actions export * chore: spaces vs tabs ugh * chore: fix conflicting fixture names * chore: changeset * chore: bump changeset to minor * Actions: support React 19 `useActionState()` with progressive enhancement (#11074) * feat(ex): Like with useActionState * feat: useActionState progressive enhancement! * feat: getActionState utility * chore: revert actions-blog fixture experimentation * fix: add back actions.ts export * feat(test): Like with use action state test * fix: stub form state client-side to avoid hydration error * fix: bad .safe chaining * fix: update actionState for client call * fix: correctly resume form state client side * refactor: unify and document reactServerActionResult * feat(test): useActionState assertions * feat(docs): explain my mess * refactor: add experimental_ prefix * refactor: move all react internals to integration * chore: remove unused getIslandProps * chore: remove unused imports * chore: undo format changes * refactor: get actionResult from middleware directly * refactor: remove bad result type * fix: like button disabled timeout * chore: changeset * refactor: remove request cloning * Update .changeset/gentle-windows-enjoy.md Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> * changeset grammar tense --------- Co-authored-by: Emanuele Stoppa <my.burning@gmail.com> Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2024-05-22 07:24:55 -05:00
if (!actionKey || !actionName) return undefined;
return [actionResult, actionKey, actionName];
Actions: React 19 progressive enhancement support (#11071) * deps: react 19 * feat: react progressive enhancement with useActionState * refactor: revert old action state implementation * feat(test): react 19 action with useFormStatus * fix: remove unused context arg * fix: wrote actions to wrong test fixture! * deps: revert react 19 beta to 18 for actions-blog fixture * chore: remove unused overrides * chore: remove unused actions export * chore: spaces vs tabs ugh * chore: fix conflicting fixture names * chore: changeset * chore: bump changeset to minor * Actions: support React 19 `useActionState()` with progressive enhancement (#11074) * feat(ex): Like with useActionState * feat: useActionState progressive enhancement! * feat: getActionState utility * chore: revert actions-blog fixture experimentation * fix: add back actions.ts export * feat(test): Like with use action state test * fix: stub form state client-side to avoid hydration error * fix: bad .safe chaining * fix: update actionState for client call * fix: correctly resume form state client side * refactor: unify and document reactServerActionResult * feat(test): useActionState assertions * feat(docs): explain my mess * refactor: add experimental_ prefix * refactor: move all react internals to integration * chore: remove unused getIslandProps * chore: remove unused imports * chore: undo format changes * refactor: get actionResult from middleware directly * refactor: remove bad result type * fix: like button disabled timeout * chore: changeset * refactor: remove request cloning * Update .changeset/gentle-windows-enjoy.md Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> * changeset grammar tense --------- Co-authored-by: Emanuele Stoppa <my.burning@gmail.com> Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2024-05-22 07:24:55 -05:00
}
async function renderToPipeableStreamAsync(vnode, options) {
const Writable = await getNodeWritable();
let html = '';
return new Promise((resolve, reject) => {
let error = undefined;
let stream = ReactDOM.renderToPipeableStream(vnode, {
...options,
onError(err) {
error = err;
reject(error);
},
onAllReady() {
2022-04-21 11:11:09 -05:00
stream.pipe(
new Writable({
write(chunk, _encoding, callback) {
html += chunk.toString('utf-8');
callback();
},
destroy() {
resolve(html);
},
}),
);
},
});
});
}
/**
* Use a while loop instead of "for await" due to cloudflare and Vercel Edge issues
* See https://github.com/facebook/react/issues/24169
*/
async function readResult(stream) {
2022-09-08 11:32:36 -05:00
const reader = stream.getReader();
let result = '';
const decoder = new TextDecoder('utf-8');
while (true) {
const { done, value } = await reader.read();
if (done) {
2022-09-08 11:32:36 -05:00
if (value) {
result += decoder.decode(value);
} else {
// This closes the decoder
decoder.decode(new Uint8Array());
}
2022-09-08 11:32:36 -05:00
return result;
}
2022-09-08 11:32:36 -05:00
result += decoder.decode(value, { stream: true });
}
}
async function renderToReadableStreamAsync(vnode, options) {
return await readResult(await ReactDOM.renderToReadableStream(vnode, options));
}
Actions: React 19 progressive enhancement support (#11071) * deps: react 19 * feat: react progressive enhancement with useActionState * refactor: revert old action state implementation * feat(test): react 19 action with useFormStatus * fix: remove unused context arg * fix: wrote actions to wrong test fixture! * deps: revert react 19 beta to 18 for actions-blog fixture * chore: remove unused overrides * chore: remove unused actions export * chore: spaces vs tabs ugh * chore: fix conflicting fixture names * chore: changeset * chore: bump changeset to minor * Actions: support React 19 `useActionState()` with progressive enhancement (#11074) * feat(ex): Like with useActionState * feat: useActionState progressive enhancement! * feat: getActionState utility * chore: revert actions-blog fixture experimentation * fix: add back actions.ts export * feat(test): Like with use action state test * fix: stub form state client-side to avoid hydration error * fix: bad .safe chaining * fix: update actionState for client call * fix: correctly resume form state client side * refactor: unify and document reactServerActionResult * feat(test): useActionState assertions * feat(docs): explain my mess * refactor: add experimental_ prefix * refactor: move all react internals to integration * chore: remove unused getIslandProps * chore: remove unused imports * chore: undo format changes * refactor: get actionResult from middleware directly * refactor: remove bad result type * fix: like button disabled timeout * chore: changeset * refactor: remove request cloning * Update .changeset/gentle-windows-enjoy.md Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> * changeset grammar tense --------- Co-authored-by: Emanuele Stoppa <my.burning@gmail.com> Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2024-05-22 07:24:55 -05:00
const formContentTypes = ['application/x-www-form-urlencoded', 'multipart/form-data'];
function isFormRequest(contentType) {
// Split off parameters like charset or boundary
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type#content-type_in_html_forms
const type = contentType?.split(';')[0].toLowerCase();
return formContentTypes.some((t) => type === t);
}
export default {
name: '@astrojs/react',
check,
renderToStaticMarkup,
supportsAstroStaticSlot: true,
};