render.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. // src/jsx/dom/render.ts
  2. import { toArray } from "../children.js";
  3. import {
  4. DOM_ERROR_HANDLER,
  5. DOM_INTERNAL_TAG,
  6. DOM_MEMO,
  7. DOM_RENDERER,
  8. DOM_STASH
  9. } from "../constants.js";
  10. import { globalContexts as globalJSXContexts, useContext } from "../context.js";
  11. import { STASH_EFFECT } from "../hooks/index.js";
  12. import { normalizeIntrinsicElementKey, styleObjectForEach } from "../utils.js";
  13. import { createContext } from "./context.js";
  14. var HONO_PORTAL_ELEMENT = "_hp";
  15. var eventAliasMap = {
  16. Change: "Input",
  17. DoubleClick: "DblClick"
  18. };
  19. var nameSpaceMap = {
  20. svg: "2000/svg",
  21. math: "1998/Math/MathML"
  22. };
  23. var buildDataStack = [];
  24. var refCleanupMap = /* @__PURE__ */ new WeakMap();
  25. var nameSpaceContext = void 0;
  26. var getNameSpaceContext = () => nameSpaceContext;
  27. var isNodeString = (node) => "t" in node;
  28. var eventCache = {
  29. // pre-define events that are used very frequently
  30. onClick: ["click", false]
  31. };
  32. var getEventSpec = (key) => {
  33. if (!key.startsWith("on")) {
  34. return void 0;
  35. }
  36. if (eventCache[key]) {
  37. return eventCache[key];
  38. }
  39. const match = key.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);
  40. if (match) {
  41. const [, eventName, capture] = match;
  42. return eventCache[key] = [(eventAliasMap[eventName] || eventName).toLowerCase(), !!capture];
  43. }
  44. return void 0;
  45. };
  46. var toAttributeName = (element, key) => nameSpaceContext && element instanceof SVGElement && /[A-Z]/.test(key) && (key in element.style || // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc.
  47. key.match(/^(?:o|pai|str|u|ve)/)) ? key.replace(/([A-Z])/g, "-$1").toLowerCase() : key;
  48. var normalizeFormValue = (value) => value === null || value === void 0 || value === false ? null : value;
  49. var applySelectValue = (select, props) => {
  50. if (!("value" in props)) {
  51. return;
  52. }
  53. select.value = normalizeFormValue(props["value"]);
  54. if (!select.multiple && select.selectedIndex === -1) {
  55. select.selectedIndex = 0;
  56. }
  57. };
  58. var applyProps = (container, attributes, oldAttributes) => {
  59. attributes ||= {};
  60. for (let key in attributes) {
  61. const value = attributes[key];
  62. if (key !== "children" && (!oldAttributes || oldAttributes[key] !== value)) {
  63. key = normalizeIntrinsicElementKey(key);
  64. const eventSpec = getEventSpec(key);
  65. if (eventSpec) {
  66. if (oldAttributes?.[key] !== value) {
  67. if (oldAttributes) {
  68. container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1]);
  69. }
  70. if (value != null) {
  71. if (typeof value !== "function") {
  72. throw new Error(`Event handler for "${key}" is not a function`);
  73. }
  74. container.addEventListener(eventSpec[0], value, eventSpec[1]);
  75. }
  76. }
  77. } else if (key === "dangerouslySetInnerHTML" && value) {
  78. container.innerHTML = value.__html;
  79. } else if (key === "ref") {
  80. let cleanup;
  81. if (typeof value === "function") {
  82. cleanup = value(container) || (() => value(null));
  83. } else if (value && "current" in value) {
  84. value.current = container;
  85. cleanup = () => value.current = null;
  86. }
  87. refCleanupMap.set(container, cleanup);
  88. } else if (key === "style") {
  89. const style = container.style;
  90. if (typeof value === "string") {
  91. style.cssText = value;
  92. } else {
  93. style.cssText = "";
  94. if (value != null) {
  95. styleObjectForEach(value, style.setProperty.bind(style));
  96. }
  97. }
  98. } else {
  99. if (key === "value") {
  100. const nodeName = container.nodeName;
  101. if (nodeName === "SELECT") {
  102. continue;
  103. } else if (nodeName === "INPUT" || nodeName === "TEXTAREA") {
  104. ;
  105. container.value = normalizeFormValue(value);
  106. if (nodeName === "TEXTAREA") {
  107. container.textContent = value;
  108. continue;
  109. }
  110. }
  111. } else if (key === "checked" && container.nodeName === "INPUT" || key === "selected" && container.nodeName === "OPTION") {
  112. ;
  113. container[key] = value;
  114. }
  115. const k = toAttributeName(container, key);
  116. if (value === null || value === void 0 || value === false) {
  117. container.removeAttribute(k);
  118. } else if (value === true) {
  119. container.setAttribute(k, "");
  120. } else if (typeof value === "string" || typeof value === "number") {
  121. container.setAttribute(k, value);
  122. } else {
  123. container.setAttribute(k, value.toString());
  124. }
  125. }
  126. }
  127. }
  128. if (oldAttributes) {
  129. for (let key in oldAttributes) {
  130. const value = oldAttributes[key];
  131. if (key !== "children" && !(key in attributes)) {
  132. key = normalizeIntrinsicElementKey(key);
  133. const eventSpec = getEventSpec(key);
  134. if (eventSpec) {
  135. container.removeEventListener(eventSpec[0], value, eventSpec[1]);
  136. } else if (key === "ref") {
  137. refCleanupMap.get(container)?.();
  138. } else {
  139. container.removeAttribute(toAttributeName(container, key));
  140. }
  141. }
  142. }
  143. }
  144. };
  145. var invokeTag = (context, node) => {
  146. node[DOM_STASH][0] = 0;
  147. buildDataStack.push([context, node]);
  148. const func = node.tag[DOM_RENDERER] || node.tag;
  149. const props = func.defaultProps ? {
  150. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  151. ...func.defaultProps,
  152. ...node.props
  153. } : node.props;
  154. try {
  155. return [func.call(null, props)];
  156. } finally {
  157. buildDataStack.pop();
  158. }
  159. };
  160. var getNextChildren = (node, container, nextChildren, childrenToRemove, callbacks) => {
  161. if (node.vR?.length) {
  162. childrenToRemove.push(...node.vR);
  163. delete node.vR;
  164. }
  165. if (typeof node.tag === "function") {
  166. node[DOM_STASH][1][STASH_EFFECT]?.forEach((data) => callbacks.push(data));
  167. }
  168. node.vC.forEach((child) => {
  169. if (isNodeString(child)) {
  170. nextChildren.push(child);
  171. } else {
  172. if (typeof child.tag === "function" || child.tag === "") {
  173. child.c = container;
  174. const currentNextChildrenIndex = nextChildren.length;
  175. getNextChildren(child, container, nextChildren, childrenToRemove, callbacks);
  176. if (child.s) {
  177. for (let i = currentNextChildrenIndex; i < nextChildren.length; i++) {
  178. nextChildren[i].s = true;
  179. }
  180. child.s = false;
  181. }
  182. } else {
  183. nextChildren.push(child);
  184. if (child.vR?.length) {
  185. childrenToRemove.push(...child.vR);
  186. delete child.vR;
  187. }
  188. }
  189. }
  190. });
  191. };
  192. var findInsertBefore = (node) => {
  193. while (node && (node.tag === HONO_PORTAL_ELEMENT || !node.e)) {
  194. node = node.tag === HONO_PORTAL_ELEMENT || !node.vC?.[0] ? node.nN : node.vC[0];
  195. }
  196. return node?.e;
  197. };
  198. var removeNode = (node) => {
  199. if (!isNodeString(node)) {
  200. node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data) => data[2]?.());
  201. refCleanupMap.get(node.e)?.();
  202. if (node.p === 2) {
  203. node.vC?.forEach((n) => n.p = 2);
  204. }
  205. node.vC?.forEach(removeNode);
  206. }
  207. if (!node.p) {
  208. node.e?.remove();
  209. delete node.e;
  210. }
  211. if (typeof node.tag === "function") {
  212. updateMap.delete(node);
  213. fallbackUpdateFnArrayMap.delete(node);
  214. delete node[DOM_STASH][3];
  215. node.a = true;
  216. }
  217. };
  218. var apply = (node, container, isNew) => {
  219. node.c = container;
  220. applyNodeObject(node, container, isNew);
  221. };
  222. var findChildNodeIndex = (childNodes, child) => {
  223. if (!child) {
  224. return;
  225. }
  226. for (let i = 0, len = childNodes.length; i < len; i++) {
  227. if (childNodes[i] === child) {
  228. return i;
  229. }
  230. }
  231. return;
  232. };
  233. var cancelBuild = /* @__PURE__ */ Symbol();
  234. var applyNodeObject = (node, container, isNew) => {
  235. const next = [];
  236. const remove = [];
  237. const callbacks = [];
  238. getNextChildren(node, container, next, remove, callbacks);
  239. remove.forEach(removeNode);
  240. const childNodes = isNew ? void 0 : container.childNodes;
  241. let offset;
  242. let insertBeforeNode = null;
  243. if (isNew) {
  244. offset = -1;
  245. } else if (!childNodes.length) {
  246. offset = 0;
  247. } else {
  248. const offsetByNextNode = findChildNodeIndex(childNodes, findInsertBefore(node.nN));
  249. if (offsetByNextNode !== void 0) {
  250. insertBeforeNode = childNodes[offsetByNextNode];
  251. offset = offsetByNextNode;
  252. } else {
  253. offset = findChildNodeIndex(childNodes, next.find((n) => n.tag !== HONO_PORTAL_ELEMENT && n.e)?.e) ?? -1;
  254. }
  255. if (offset === -1) {
  256. isNew = true;
  257. }
  258. }
  259. for (let i = 0, len = next.length; i < len; i++, offset++) {
  260. const child = next[i];
  261. let el;
  262. if (child.s && child.e) {
  263. el = child.e;
  264. child.s = false;
  265. } else {
  266. const isNewLocal = isNew || !child.e;
  267. if (isNodeString(child)) {
  268. if (child.e && child.d) {
  269. child.e.textContent = child.t;
  270. }
  271. child.d = false;
  272. el = child.e ||= document.createTextNode(child.t);
  273. } else {
  274. el = child.e ||= child.n ? document.createElementNS(child.n, child.tag) : document.createElement(child.tag);
  275. applyProps(el, child.props, child.pP);
  276. applyNodeObject(child, el, isNewLocal);
  277. if (child.tag === "select") {
  278. applySelectValue(el, child.props);
  279. }
  280. }
  281. }
  282. if (child.tag === HONO_PORTAL_ELEMENT) {
  283. offset--;
  284. } else if (isNew) {
  285. if (!el.parentNode) {
  286. container.appendChild(el);
  287. }
  288. } else if (childNodes[offset] !== el && childNodes[offset - 1] !== el) {
  289. if (childNodes[offset + 1] === el) {
  290. container.appendChild(childNodes[offset]);
  291. } else {
  292. container.insertBefore(el, insertBeforeNode || childNodes[offset] || null);
  293. }
  294. }
  295. }
  296. if (node.pP) {
  297. node.pP = void 0;
  298. }
  299. if (callbacks.length) {
  300. const useLayoutEffectCbs = [];
  301. const useEffectCbs = [];
  302. callbacks.forEach(([, useLayoutEffectCb, , useEffectCb, useInsertionEffectCb]) => {
  303. if (useLayoutEffectCb) {
  304. useLayoutEffectCbs.push(useLayoutEffectCb);
  305. }
  306. if (useEffectCb) {
  307. useEffectCbs.push(useEffectCb);
  308. }
  309. useInsertionEffectCb?.();
  310. });
  311. useLayoutEffectCbs.forEach((cb) => cb());
  312. if (useEffectCbs.length) {
  313. requestAnimationFrame(() => {
  314. useEffectCbs.forEach((cb) => cb());
  315. });
  316. }
  317. }
  318. };
  319. var isSameContext = (oldContexts, newContexts) => !!(oldContexts && oldContexts.length === newContexts.length && oldContexts.every((ctx, i) => ctx[1] === newContexts[i][1]));
  320. var fallbackUpdateFnArrayMap = /* @__PURE__ */ new WeakMap();
  321. var build = (context, node, children) => {
  322. const buildWithPreviousChildren = !children && node.pC;
  323. if (children) {
  324. node.pC ||= node.vC;
  325. }
  326. let foundErrorHandler;
  327. try {
  328. children ||= typeof node.tag == "function" ? invokeTag(context, node) : toArray(node.props.children);
  329. if (children[0]?.tag === "" && children[0][DOM_ERROR_HANDLER]) {
  330. foundErrorHandler = children[0][DOM_ERROR_HANDLER];
  331. context[5].push([context, foundErrorHandler, node]);
  332. }
  333. const oldVChildren = buildWithPreviousChildren ? [...node.pC] : node.vC ? [...node.vC] : void 0;
  334. const vChildren = [];
  335. let prevNode;
  336. for (let i = 0; i < children.length; i++) {
  337. if (Array.isArray(children[i])) {
  338. children.splice(i, 1, ...children[i].flat(Infinity));
  339. i--;
  340. continue;
  341. }
  342. let child = buildNode(children[i]);
  343. if (child) {
  344. if (typeof child.tag === "function" && // eslint-disable-next-line @typescript-eslint/no-explicit-any
  345. !child.tag[DOM_INTERNAL_TAG]) {
  346. if (globalJSXContexts.length > 0) {
  347. child[DOM_STASH][2] = globalJSXContexts.map((c) => [c, c.values.at(-1)]);
  348. }
  349. if (context[5]?.length) {
  350. child[DOM_STASH][3] = context[5].at(-1);
  351. }
  352. }
  353. let oldChild;
  354. if (oldVChildren && oldVChildren.length) {
  355. const i2 = oldVChildren.findIndex(
  356. isNodeString(child) ? (c) => isNodeString(c) : child.key !== void 0 ? (c) => c.key === child.key && c.tag === child.tag : (c) => c.tag === child.tag
  357. );
  358. if (i2 !== -1) {
  359. oldChild = oldVChildren[i2];
  360. oldVChildren.splice(i2, 1);
  361. }
  362. }
  363. if (oldChild) {
  364. if (isNodeString(child)) {
  365. if (oldChild.t !== child.t) {
  366. ;
  367. oldChild.t = child.t;
  368. oldChild.d = true;
  369. }
  370. child = oldChild;
  371. } else {
  372. const pP = oldChild.pP = oldChild.props;
  373. oldChild.props = child.props;
  374. oldChild.f ||= child.f || node.f;
  375. if (typeof child.tag === "function") {
  376. const oldContexts = oldChild[DOM_STASH][2];
  377. oldChild[DOM_STASH][2] = child[DOM_STASH][2] || [];
  378. oldChild[DOM_STASH][3] = child[DOM_STASH][3];
  379. if (!oldChild.f && ((oldChild.o || oldChild) === child.o || // The code generated by the react compiler is memoized under this condition.
  380. oldChild.tag[DOM_MEMO]?.(pP, oldChild.props)) && // The `memo` function is memoized under this condition.
  381. isSameContext(oldContexts, oldChild[DOM_STASH][2])) {
  382. oldChild.s = true;
  383. }
  384. }
  385. child = oldChild;
  386. }
  387. } else if (!isNodeString(child) && nameSpaceContext) {
  388. const ns = useContext(nameSpaceContext);
  389. if (ns) {
  390. child.n = ns;
  391. }
  392. }
  393. if (!isNodeString(child) && !child.s) {
  394. build(context, child);
  395. delete child.f;
  396. }
  397. vChildren.push(child);
  398. if (prevNode && !prevNode.s && !child.s) {
  399. for (let p = prevNode; p && !isNodeString(p); p = p.vC?.at(-1)) {
  400. p.nN = child;
  401. }
  402. }
  403. prevNode = child;
  404. }
  405. }
  406. node.vR = buildWithPreviousChildren ? [...node.vC, ...oldVChildren || []] : oldVChildren || [];
  407. node.vC = vChildren;
  408. if (buildWithPreviousChildren) {
  409. delete node.pC;
  410. }
  411. } catch (e) {
  412. node.f = true;
  413. if (e === cancelBuild) {
  414. if (foundErrorHandler) {
  415. return;
  416. } else {
  417. throw e;
  418. }
  419. }
  420. const [errorHandlerContext, errorHandler, errorHandlerNode] = node[DOM_STASH]?.[3] || [];
  421. if (errorHandler) {
  422. const fallbackUpdateFn = () => update([0, false, context[2]], errorHandlerNode);
  423. const fallbackUpdateFnArray = fallbackUpdateFnArrayMap.get(errorHandlerNode) || [];
  424. fallbackUpdateFnArray.push(fallbackUpdateFn);
  425. fallbackUpdateFnArrayMap.set(errorHandlerNode, fallbackUpdateFnArray);
  426. const fallback = errorHandler(e, () => {
  427. const fnArray = fallbackUpdateFnArrayMap.get(errorHandlerNode);
  428. if (fnArray) {
  429. const i = fnArray.indexOf(fallbackUpdateFn);
  430. if (i !== -1) {
  431. fnArray.splice(i, 1);
  432. return fallbackUpdateFn();
  433. }
  434. }
  435. });
  436. if (fallback) {
  437. if (context[0] === 1) {
  438. context[1] = true;
  439. } else {
  440. build(context, errorHandlerNode, [fallback]);
  441. if ((errorHandler.length === 1 || context !== errorHandlerContext) && errorHandlerNode.c) {
  442. apply(errorHandlerNode, errorHandlerNode.c, false);
  443. return;
  444. }
  445. }
  446. throw cancelBuild;
  447. }
  448. }
  449. throw e;
  450. } finally {
  451. if (foundErrorHandler) {
  452. context[5].pop();
  453. }
  454. }
  455. };
  456. var buildNode = (node) => {
  457. if (node === void 0 || node === null || typeof node === "boolean") {
  458. return void 0;
  459. } else if (typeof node === "string" || typeof node === "number") {
  460. return { t: node.toString(), d: true };
  461. } else {
  462. if ("vR" in node) {
  463. node = {
  464. tag: node.tag,
  465. props: node.props,
  466. key: node.key,
  467. f: node.f,
  468. type: node.tag,
  469. ref: node.props.ref,
  470. o: node.o || node
  471. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  472. };
  473. }
  474. if (typeof node.tag === "function") {
  475. ;
  476. node[DOM_STASH] = [0, []];
  477. } else {
  478. const ns = nameSpaceMap[node.tag];
  479. if (ns) {
  480. nameSpaceContext ||= createContext("");
  481. node.props.children = [
  482. {
  483. tag: nameSpaceContext,
  484. props: {
  485. value: node.n = `http://www.w3.org/${ns}`,
  486. children: node.props.children
  487. }
  488. }
  489. ];
  490. }
  491. }
  492. return node;
  493. }
  494. };
  495. var replaceContainer = (node, from, to) => {
  496. if (node.c === from) {
  497. node.c = to;
  498. node.vC.forEach((child) => replaceContainer(child, from, to));
  499. }
  500. };
  501. var updateSync = (context, node) => {
  502. node[DOM_STASH][2]?.forEach(([c, v]) => {
  503. c.values.push(v);
  504. });
  505. try {
  506. build(context, node, void 0);
  507. } catch {
  508. return;
  509. }
  510. if (node.a) {
  511. delete node.a;
  512. return;
  513. }
  514. node[DOM_STASH][2]?.forEach(([c]) => {
  515. c.values.pop();
  516. });
  517. if (context[0] !== 1 || !context[1]) {
  518. apply(node, node.c, false);
  519. }
  520. };
  521. var updateMap = /* @__PURE__ */ new WeakMap();
  522. var currentUpdateSets = [];
  523. var update = async (context, node) => {
  524. context[5] ||= [];
  525. const existing = updateMap.get(node);
  526. if (existing) {
  527. existing[0](void 0);
  528. }
  529. let resolve;
  530. const promise = new Promise((r) => resolve = r);
  531. updateMap.set(node, [
  532. resolve,
  533. () => {
  534. if (context[2]) {
  535. context[2](context, node, (context2) => {
  536. updateSync(context2, node);
  537. }).then(() => resolve(node));
  538. } else {
  539. updateSync(context, node);
  540. resolve(node);
  541. }
  542. }
  543. ]);
  544. if (currentUpdateSets.length) {
  545. ;
  546. currentUpdateSets.at(-1).add(node);
  547. } else {
  548. await Promise.resolve();
  549. const latest = updateMap.get(node);
  550. if (latest) {
  551. updateMap.delete(node);
  552. latest[1]();
  553. }
  554. }
  555. return promise;
  556. };
  557. var renderNode = (node, container) => {
  558. const context = [];
  559. context[5] = [];
  560. context[4] = true;
  561. build(context, node, void 0);
  562. context[4] = false;
  563. const fragment = document.createDocumentFragment();
  564. apply(node, fragment, true);
  565. replaceContainer(node, fragment, container);
  566. container.replaceChildren(fragment);
  567. };
  568. var render = (jsxNode, container) => {
  569. renderNode(buildNode({ tag: "", props: { children: jsxNode } }), container);
  570. };
  571. var flushSync = (callback) => {
  572. const set = /* @__PURE__ */ new Set();
  573. currentUpdateSets.push(set);
  574. callback();
  575. set.forEach((node) => {
  576. const latest = updateMap.get(node);
  577. if (latest) {
  578. updateMap.delete(node);
  579. latest[1]();
  580. }
  581. });
  582. currentUpdateSets.pop();
  583. };
  584. var createPortal = (children, container, key) => ({
  585. tag: HONO_PORTAL_ELEMENT,
  586. props: {
  587. children
  588. },
  589. key,
  590. e: container,
  591. p: 1
  592. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  593. });
  594. export {
  595. build,
  596. buildDataStack,
  597. buildNode,
  598. createPortal,
  599. flushSync,
  600. getNameSpaceContext,
  601. render,
  602. renderNode,
  603. update
  604. };