context.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // src/jsx/context.ts
  2. import { raw } from "../helper/html/index.js";
  3. import { JSXFragmentNode } from "./base.js";
  4. import { DOM_RENDERER } from "./constants.js";
  5. import { createContextProviderFunction } from "./dom/context.js";
  6. var globalContexts = [];
  7. var createContext = (defaultValue) => {
  8. const values = [defaultValue];
  9. const context = ((props) => {
  10. values.push(props.value);
  11. let string;
  12. try {
  13. string = props.children ? (Array.isArray(props.children) ? new JSXFragmentNode("", {}, props.children) : props.children).toString() : "";
  14. } catch (e) {
  15. values.pop();
  16. throw e;
  17. }
  18. if (string instanceof Promise) {
  19. return string.finally(() => values.pop()).then((resString) => raw(resString, resString.callbacks));
  20. } else {
  21. values.pop();
  22. return raw(string);
  23. }
  24. });
  25. context.values = values;
  26. context.Provider = context;
  27. context[DOM_RENDERER] = createContextProviderFunction(values);
  28. globalContexts.push(context);
  29. return context;
  30. };
  31. var useContext = (context) => {
  32. return context.values.at(-1);
  33. };
  34. export {
  35. createContext,
  36. globalContexts,
  37. useContext
  38. };