2024-04-17 03:38:53 -05:00
|
|
|
import opts from 'astro:react:opts';
|
2022-03-18 17:35:45 -05:00
|
|
|
import React from 'react';
|
2022-03-31 11:51:29 -05:00
|
|
|
import ReactDOM from 'react-dom/server';
|
2023-05-04 09:23:00 -05:00
|
|
|
import { incrementId } from './context.js';
|
2024-02-27 06:15:27 -05:00
|
|
|
import StaticHtml from './static-html.js';
|
2022-03-18 17:35:45 -05:00
|
|
|
|
2022-06-23 10:12:46 -05:00
|
|
|
const slotName = (str) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase());
|
2022-03-18 17:35:45 -05:00
|
|
|
const reactTypeof = Symbol.for('react.element');
|
|
|
|
|
2022-04-21 11:10:06 -05:00
|
|
|
async function check(Component, props, children) {
|
2022-03-18 17:35:45 -05:00
|
|
|
// 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') {
|
2023-07-03 07:59:43 -05:00
|
|
|
return Component['$$typeof'].toString().slice('Symbol('.length).startsWith('react');
|
2022-03-18 17:35:45 -05:00
|
|
|
}
|
|
|
|
if (typeof Component !== 'function') return false;
|
2023-12-20 14:00:58 -05:00
|
|
|
if (Component.name === 'QwikComponent') return false;
|
2022-03-18 17:35:45 -05:00
|
|
|
|
2023-12-18 08:41:44 -05:00
|
|
|
// 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;
|
2023-12-18 08:41:44 -05:00
|
|
|
|
2022-03-18 17:35:45 -05:00
|
|
|
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;
|
|
|
|
}
|
2024-08-09 07:01:25 -05:00
|
|
|
} catch {}
|
2022-03-18 17:35:45 -05:00
|
|
|
|
|
|
|
return React.createElement('div');
|
|
|
|
}
|
|
|
|
|
2022-04-21 11:10:06 -05:00
|
|
|
await renderToStaticMarkup(Tester, props, children, {});
|
2022-03-18 17:35:45 -05:00
|
|
|
|
|
|
|
return isReactComponent;
|
|
|
|
}
|
|
|
|
|
2022-04-21 11:10:06 -05:00
|
|
|
async function getNodeWritable() {
|
2023-11-16 08:47:46 -05:00
|
|
|
let nodeStreamBuiltinModuleName = 'node:stream';
|
2022-08-30 02:25:34 -05:00
|
|
|
let { Writable } = await import(/* @vite-ignore */ nodeStreamBuiltinModuleName);
|
2022-04-21 11:10:06 -05:00
|
|
|
return Writable;
|
|
|
|
}
|
|
|
|
|
2023-05-17 09:18:04 -05:00
|
|
|
function needsHydration(metadata) {
|
|
|
|
// Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot`
|
|
|
|
return metadata.astroStaticSlot ? !!metadata.hydrate : true;
|
|
|
|
}
|
|
|
|
|
2022-06-23 10:10:54 -05:00
|
|
|
async function renderToStaticMarkup(Component, props, { default: children, ...slotted }, metadata) {
|
2023-05-04 09:23:00 -05:00
|
|
|
let prefix;
|
|
|
|
if (this && this.result) {
|
2023-05-04 09:25:03 -05:00
|
|
|
prefix = incrementId(this.result);
|
2023-05-04 09:23:00 -05:00
|
|
|
}
|
|
|
|
const attrs = { prefix };
|
|
|
|
|
2022-03-18 17:35:45 -05:00
|
|
|
delete props['class'];
|
2022-06-23 10:10:54 -05:00
|
|
|
const slots = {};
|
|
|
|
for (const [key, value] of Object.entries(slotted)) {
|
|
|
|
const name = slotName(key);
|
2023-05-17 09:18:04 -05:00
|
|
|
slots[name] = React.createElement(StaticHtml, {
|
|
|
|
hydrate: needsHydration(metadata),
|
|
|
|
value,
|
2023-05-17 09:20:24 -05:00
|
|
|
name,
|
2023-05-17 09:18:04 -05:00
|
|
|
});
|
2022-06-23 10:10:54 -05:00
|
|
|
}
|
|
|
|
// Note: create newProps to avoid mutating `props` before they are serialized
|
2022-06-23 10:12:46 -05:00
|
|
|
const newProps = {
|
2022-03-18 17:35:45 -05:00
|
|
|
...props,
|
2022-06-23 10:10:54 -05:00
|
|
|
...slots,
|
2022-06-23 10:12:46 -05:00
|
|
|
};
|
2023-01-25 17:31:57 -05:00
|
|
|
const newChildren = children ?? props.children;
|
2023-08-16 12:40:57 -05:00
|
|
|
if (children && opts.experimentalReactChildren) {
|
2023-10-24 07:05:19 -05:00
|
|
|
attrs['data-react-children'] = true;
|
2023-08-16 12:44:01 -05:00
|
|
|
const convert = await import('./vnode-children.js').then((mod) => mod.default);
|
2023-08-16 12:40:57 -05:00
|
|
|
newProps.children = convert(children);
|
|
|
|
} else if (newChildren != null) {
|
2023-05-17 09:18:04 -05:00
|
|
|
newProps.children = React.createElement(StaticHtml, {
|
|
|
|
hydrate: needsHydration(metadata),
|
2023-05-17 09:20:24 -05:00
|
|
|
value: newChildren,
|
2023-05-17 09:18:04 -05:00
|
|
|
});
|
2022-09-14 14:42:38 -05:00
|
|
|
}
|
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];
|
|
|
|
}
|
2022-06-23 10:10:54 -05:00
|
|
|
const vnode = React.createElement(Component, newProps);
|
2023-05-04 09:23:00 -05:00
|
|
|
const renderOptions = {
|
2023-05-04 09:25:03 -05:00
|
|
|
identifierPrefix: prefix,
|
2024-05-22 07:24:55 -05:00
|
|
|
formState,
|
2023-05-04 09:25:03 -05:00
|
|
|
};
|
2022-03-18 17:35:45 -05:00
|
|
|
let html;
|
2024-04-30 07:01:21 -05:00
|
|
|
if ('renderToReadableStream' in ReactDOM) {
|
|
|
|
html = await renderToReadableStreamAsync(vnode, renderOptions);
|
2022-03-18 17:35:45 -05:00
|
|
|
} else {
|
2024-04-30 07:01:21 -05:00
|
|
|
html = await renderToPipeableStreamAsync(vnode, renderOptions);
|
2022-03-18 17:35:45 -05:00
|
|
|
}
|
2023-05-04 09:23:00 -05:00
|
|
|
return { html, attrs };
|
2022-03-18 17:35:45 -05:00
|
|
|
}
|
|
|
|
|
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;
|
|
|
|
|
2024-07-30 10:04:10 -05:00
|
|
|
const { searchParams } = new URL(request.url);
|
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"
|
|
|
|
*/
|
2024-07-30 10:04:10 -05:00
|
|
|
const actionName =
|
|
|
|
searchParams.get('_astroAction') ??
|
|
|
|
/* Legacy. TODO: remove for stable */ formData
|
|
|
|
.get('_astroAction')
|
|
|
|
?.toString();
|
2024-05-22 07:24:55 -05:00
|
|
|
|
|
|
|
if (!actionKey || !actionName) return undefined;
|
|
|
|
|
2024-07-30 10:42:52 -05:00
|
|
|
return [actionResult, actionKey, actionName];
|
2024-05-22 07:24:55 -05:00
|
|
|
}
|
|
|
|
|
2023-05-04 09:23:00 -05:00
|
|
|
async function renderToPipeableStreamAsync(vnode, options) {
|
2022-04-21 11:10:06 -05:00
|
|
|
const Writable = await getNodeWritable();
|
|
|
|
let html = '';
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
let error = undefined;
|
|
|
|
let stream = ReactDOM.renderToPipeableStream(vnode, {
|
2023-05-04 09:23:00 -05:00
|
|
|
...options,
|
2022-04-21 11:10:06 -05:00
|
|
|
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);
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
},
|
2022-04-21 11:10:06 -05:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-09-07 18:41:37 -05:00
|
|
|
/**
|
|
|
|
* 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) {
|
2022-09-08 11:30:49 -05:00
|
|
|
const { done, value } = await reader.read();
|
|
|
|
if (done) {
|
2022-09-08 11:32:36 -05:00
|
|
|
if (value) {
|
2022-09-08 11:30:49 -05:00
|
|
|
result += decoder.decode(value);
|
|
|
|
} else {
|
|
|
|
// This closes the decoder
|
|
|
|
decoder.decode(new Uint8Array());
|
|
|
|
}
|
2022-09-08 11:32:36 -05:00
|
|
|
|
2022-09-08 11:30:49 -05:00
|
|
|
return result;
|
|
|
|
}
|
2022-09-08 11:32:36 -05:00
|
|
|
result += decoder.decode(value, { stream: true });
|
|
|
|
}
|
2022-09-07 18:41:37 -05:00
|
|
|
}
|
|
|
|
|
2023-05-04 09:23:00 -05:00
|
|
|
async function renderToReadableStreamAsync(vnode, options) {
|
|
|
|
return await readResult(await ReactDOM.renderToReadableStream(vnode, options));
|
2022-04-21 11:10:06 -05:00
|
|
|
}
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2022-03-18 17:35:45 -05:00
|
|
|
export default {
|
2024-06-14 00:52:17 -05:00
|
|
|
name: '@astrojs/react',
|
2022-03-18 17:35:45 -05:00
|
|
|
check,
|
|
|
|
renderToStaticMarkup,
|
2023-05-17 09:18:04 -05:00
|
|
|
supportsAstroStaticSlot: true,
|
2022-03-18 17:35:45 -05:00
|
|
|
};
|