index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // src/middleware/jsx-renderer/index.ts
  2. import { html, raw } from "../../helper/html/index.js";
  3. import { Fragment, createContext, jsx, useContext } from "../../jsx/index.js";
  4. import { renderToReadableStream } from "../../jsx/streaming.js";
  5. var RequestContext = createContext(null);
  6. var createRenderer = (c, Layout, component, options) => (children, props) => {
  7. options = typeof options === "function" ? options(c) : options;
  8. const docType = typeof options?.docType === "string" ? options.docType : options?.docType === false ? "" : "<!DOCTYPE html>";
  9. const currentLayout = component ? jsx(
  10. (props2) => component(props2, c),
  11. {
  12. Layout,
  13. ...props
  14. },
  15. children
  16. ) : children;
  17. const body = html`${raw(docType)}${jsx(
  18. RequestContext.Provider,
  19. { value: c },
  20. currentLayout
  21. )}`;
  22. if (options?.stream) {
  23. if (options.stream === true) {
  24. c.header("Transfer-Encoding", "chunked");
  25. c.header("Content-Type", "text/html; charset=UTF-8");
  26. c.header("Content-Encoding", "Identity");
  27. } else {
  28. for (const [key, value] of Object.entries(options.stream)) {
  29. c.header(key, value);
  30. }
  31. }
  32. return c.body(renderToReadableStream(body));
  33. } else {
  34. return c.html(body);
  35. }
  36. };
  37. var jsxRenderer = (component, options) => function jsxRenderer2(c, next) {
  38. const Layout = c.getLayout() ?? Fragment;
  39. if (component) {
  40. c.setLayout((props) => {
  41. return component({ ...props, Layout }, c);
  42. });
  43. }
  44. c.setRenderer(createRenderer(c, Layout, component, options));
  45. return next();
  46. };
  47. var useRequestContext = () => {
  48. const c = useContext(RequestContext);
  49. if (!c) {
  50. throw new Error("RequestContext is not provided.");
  51. }
  52. return c;
  53. };
  54. export {
  55. RequestContext,
  56. jsxRenderer,
  57. useRequestContext
  58. };