{"version":3,"file":"dom.cjs","sources":["../packages/dom/css/css.js","../packages/dom/execute/execute.js","../packages/dom/interfaces.js","../packages/polyfill/setImmediate.js","../packages/dom/didPaint/didPaint.js","../packages/dom/html/html.js","../packages/dom/paint/paint.js","../packages/dom/paint/render/render.js","../packages/dom/repaint/repaint.js","../packages/dom/retouch/retouch.js","../packages/dom/willPaint/willPaint.js"],"sourcesContent":["/**\n * Template tag `css` que gera uma instância de `CSSStyleSheet` a partir de um template literal.\n *\n * @param {TemplateStringsArray} strings - Fragmentos de strings literais do template CSS.\n * @param {...any} values - Valores interpolados no template.\n * @returns {CSSStyleSheet} Uma instância de folha de estilo pronta para ser aplicada.\n *\n * @description\n * Ideal para uso em Web Components com `adoptedStyleSheets`, fornecendo uma API declarativa\n * para definir estilos encapsulados.\n *\n * @example\n * const primary = \"blue\";\n * const styleSheet = css`\n *   :host {\n *     color: ${primary};\n *     display: block;\n *   }\n * `;\n *\n * shadowRoot.adoptedStyleSheets = [styleSheet];\n */\nconst css = (strings, ...values) => {\n  const styleSheet = new CSSStyleSheet();\n  const text = String.raw({ raw: strings }, ...values);\n  styleSheet.replaceSync(text);\n  return styleSheet;\n};\n\nexport default css;\n","/**\n * Registra a execução de um método após um evento do ciclo de vida de um Custom Element.\n *\n * @param {string|Symbol} method - Nome do método a ser executado.\n * @returns {{ on: (target: Object) => { after: (event: string) => void } }}\n *\n * @description\n * A função `execute` permite registrar de forma fluente a execução de um método de instância\n * logo após a invocação de um evento de ciclo de vida padrão do Web Component,\n * como `connectedCallback`, `disconnectedCallback` ou `adoptedCallback`.\n *\n * Internamente, a função substitui o callback nativo com um Proxy que mantém o comportamento\n * original e executa o método decorado após a conclusão do callback.\n *\n * @example\n * import execute from '@directive/execute';\n *\n * execute('onConnect').on(MyElement.prototype).after('connectedCallback');\n *\n * // Equivalente a:\n * // MyElement.prototype.connectedCallback = new Proxy(...);\n */\nconst execute = (method) => ({\n  /**\n   * Define o alvo (normalmente o prototype do Custom Element).\n   *\n   * @param {Object} target - O protótipo onde o método de ciclo de vida será interceptado.\n   * @returns {{ after: (event: string) => void }}\n   */\n  on: (target) => ({\n    /**\n     * Registra o método para execução após o evento especificado.\n     *\n     * @param {string} event - Nome do evento de ciclo de vida (ex: 'connectedCallback').\n     * @returns {void}\n     */\n    after: (event) => {\n      target[event] = new Proxy(target[event] || (() => {}), {\n        async apply(original, context, args) {\n          await original.apply(context, args);\n          await context[method]();\n        },\n      });\n    },\n  }),\n});\n\nexport default execute;\n","/**\n * Symbolic property used to indicate if the component has already been rendered.\n *\n * This flag is automatically set to `true` after executing the `paintCallback`,\n * and is used internally by decorators like `@repaint` to condition new rendering\n * only when the component has already undergone an initial rendering.\n */\nexport const isPainted = Symbol.for(\"isPainted\");\n\n/**\n * Unique identifier for the callback executed after component rendering.\n *\n * Used internally by decorators and helpers like `@didPaint` to ensure that the\n * associated method is executed after applying styles and updating the DOM.\n */\nexport const didPaintCallback = Symbol(\"didPaintCallback\");\n\n/**\n * Unique identifier for the callback to update the component's HTML content.\n *\n * This callback is invoked during the `paint` or `repaint` process, and is responsible for\n * rendering the HTML in the `shadowRoot` (or in the element directly, if `shadowRoot` doesn't exist).\n *\n * Can be used in isolation with decorators like `@html`, or in conjunction with `@paint` and `@repaint`.\n */\nexport const htmlCallback = Symbol(\"htmlCallback\");\n\n/**\n * Unique identifier for the callback to apply component styles.\n *\n * This callback is called to obtain the styles (CSSStyleSheet) that should be applied\n * via `adoptedStyleSheets`. It can be used in isolation through the `@retouch` decorator\n * or combined in broader flows like `@paint`.\n *\n * Must return a `CSSStyleSheet` instance or a Promise that resolves to one.\n */\nexport const cssCallback = Symbol(\"cssCallback\");\n\n/**\n * Unique identifier for the callback executed before component rendering.\n *\n * Used by decorators like `@willPaint` to indicate that a method should be executed\n * before any DOM manipulation, within the `connectedCallback`.\n */\nexport const willPaintCallback = Symbol(\"willPaintCallback\");\n","/**\n * Polyfill for setImmediate function.\n *\n * @description\n * Provides setImmediate functionality for environments that don't support it natively.\n * Falls back to setTimeout with 0 delay.\n *\n * @example\n * import \"@hive/std/polyfill/setImmediate\";\n *\n * setImmediate(() => {\n *   console.log(\"This runs asynchronously\");\n * });\n */\nif (typeof globalThis.setImmediate !== \"function\") {\n  Reflect.defineProperty(globalThis, \"setImmediate\", {\n    value(fn) {\n      return setTimeout(fn, 0);\n    },\n    writable: true,\n    configurable: true,\n  });\n}\n","import execute from \"@dom/execute\";\nimport { didPaintCallback } from \"@dom/interfaces\";\n\n/**\n * Decorator that executes a method after the component's rendering in the DOM lifecycle.\n *\n * @param {Object} target - The prototype of the decorated Custom Element.\n * @param {string|symbol} method - Name of the method to be executed after render.\n * @returns {void}\n *\n * @description\n * The `didPaint` decorator registers a method to be executed immediately after\n * the component's content rendering, inside the `connectedCallback`, and after\n * applying styles and updating `innerHTML`.\n *\n * This decorator is useful for performing tasks that depend on the already rendered DOM,\n * such as layout measurement, animations, focus, or third-party integration.\n * It is triggered after `requestAnimationFrame`.\n *\n * @example\n * import { didPaint } from '@hive/std/dom';\n *\n * class MyElement extends HTMLElement {\n *   @didPaint\n *   finalize() {\n *     console.log('render completed');\n *   }\n * }\n */\nconst didPaint = (target, method) =>\n  execute(method).on(target).after(didPaintCallback);\n\nexport default didPaint;\n","/**\n * Template tag `html` para gerar strings HTML de forma segura e controlada.\n *\n * @param {TemplateStringsArray} strings - Array com os pedaços literais do template.\n * @param {...any} values - Valores interpolados no template.\n * @returns {string} HTML combinado como string.\n *\n * @description\n * Essa função será utilizada no helper `component` para definir o conteúdo HTML\n * dos Web Components de forma declarativa, usando template literals.\n *\n * O comportamento atual apenas concatena os valores e strings,\n * respeitando a interpolação dos dados sem aplicar nenhuma transformação\n * ou sanitização. Versões futuras podem incluir minificação, limpeza ou validação.\n *\n * @example\n * const name = \"Clebão\";\n * const text = html`<h1>Olá, ${name}!</h1>`;\n * console.log(text); // \"<h1>Olá, Clebão!</h1>\"\n */\nconst html = (strings, ...values) => {\n  return String.raw(\n    { raw: strings },\n    ...values.map((value) => [].concat(value).join(\"\")),\n  );\n};\n\nexport default html;\n","import render from \"@dom/paint/render\";\n\n/**\n * Decorator that renders a component with styles when connected to the DOM.\n *\n * @param {Function} component - Function responsible for returning the component's HTML. Receives `this` as argument.\n * @param {...Function} styles - Functions that return `CSSStyleSheet`. Each receives `this` as argument.\n * @returns {void}\n *\n * @description\n * The `paint` decorator enables rendering of a custom component\n * at the moment it is connected to the DOM, also applying encapsulated styles\n * via `adoptedStyleSheets` in the `shadowRoot` or directly on the element itself.\n *\n * It supports the execution of `willPaintCallback`, `paintCallback` and `didPaintCallback`\n * callbacks to allow control over the rendering lifecycle.\n *\n * @example\n * import { paint } from '@hive/std/dom';\n *\n * const component = (el) => `<p>Hello, ${el.name}</p>`;\n * const style = (el) => new CSSStyleSheet();\n *\n * @paint(component, style)\n * class MyElement extends HTMLElement {\n *   name = 'world';\n * }\n */\nconst paint =\n  (component, ...styles) =>\n  (target) =>\n    render(component).with(styles).on(target).whenConnected();\n\nexport default paint;\n","import {\n  cssCallback,\n  didPaintCallback,\n  htmlCallback,\n  isPainted,\n  willPaintCallback,\n} from \"@dom/interfaces\";\n\n/**\n * Registra a renderização de um componente com estilos quando o Custom Element é conectado ao DOM.\n *\n * @param {Function} component - Função que retorna o HTML do componente. Recebe `this` como argumento.\n * @returns {{ with: (styles: Function[]) => { on: (target: Object) => { whenConnected: () => void } } }}\n *\n * @description\n * O helper `render` permite executar de forma fluente a renderização de um componente,\n * aplicando estilos dinâmicos ao `shadowRoot` (ou ao elemento diretamente),\n * logo após a execução do `connectedCallback`.\n *\n * Ele suporta os callbacks `willPaintCallback`, `paintCallback` e `didPaintCallback`,\n * além de aplicar folhas de estilo usando `adoptedStyleSheets`.\n *\n * @example\n * render(component)\n *   .with([style])\n *   .on(MyElement.prototype)\n *   .whenConnected();\n */\nconst render = (component) => ({\n  /**\n   * Define os estilos a serem aplicados ao shadowRoot ou document.\n   *\n   * @param {Function[]} styles - Lista de funções que retornam CSSStyleSheet (recebem `this`).\n   * @returns {{ on: (target: Object) => { whenConnected: () => void } }}\n   */\n  with: (styles) => ({\n    /**\n     * Define o protótipo alvo onde a lógica será aplicada.\n     *\n     * @param {Object} target - O prototype do Custom Element decorado.\n     * @returns {{ whenConnected: () => void }}\n     */\n    on: (target) => ({\n      /**\n       * Finaliza a definição e intercepta o connectedCallback para aplicar a renderização e os estilos.\n       *\n       * @returns {void}\n       */\n      whenConnected: () => {\n        target.prototype.connectedCallback = new Proxy(\n          target.prototype.connectedCallback || (() => {}),\n          {\n            async apply(original, context, args) {\n              await original.apply(context, args);\n\n              context[htmlCallback] = (resolve) => {\n                requestAnimationFrame(async () => {\n                  (context.shadowRoot ?? context).innerHTML =\n                    await component(context);\n                  resolve();\n                });\n              };\n\n              context[cssCallback] = (resolve) => {\n                requestAnimationFrame(async () => {\n                  const styleSheets = styles.map((style) => style(context));\n                  (context.shadowRoot ?? document).adoptedStyleSheets =\n                    await Promise.all(styleSheets);\n                  resolve();\n                });\n              };\n\n              await context[willPaintCallback]?.();\n              await Promise.all([\n                new Promise(context[htmlCallback]),\n                new Promise(context[cssCallback]),\n              ]);\n              context[isPainted] = true;\n              await context[didPaintCallback]?.();\n            },\n          },\n        );\n      },\n    }),\n  }),\n});\n\nexport default render;\n","import \"@polyfill/setImmediate\";\nimport {\n  cssCallback,\n  didPaintCallback,\n  htmlCallback,\n  isPainted,\n  willPaintCallback,\n} from \"@dom/interfaces\";\n\n/**\n * Decorator that forces a new component rendering after a method or setter execution.\n *\n * @param {Object} target - The prototype of the decorated Custom Element.\n * @param {string|symbol} propertyKey - The name of the decorated method or setter.\n * @param {PropertyDescriptor} descriptor - The descriptor of the method or setter.\n * @returns {void}\n *\n * @description\n * The `repaint` decorator intercepts the execution of methods or setters and,\n * if the component has already been rendered (`isPainted = true`),\n * re-executes the rendering cycle through the `paintCallback`.\n *\n * This behavior is useful for keeping the UI automatically updated after state changes.\n *\n * @example\n * import { repaint } from '@hive/std/dom';\n *\n * class MyElement extends HTMLElement {\n *   @repaint\n *   set data(value) {\n *     this._data = value;\n *   }\n *\n *   @repaint\n *   update() {\n *     this._updated = true;\n *   }\n * }\n */\nconst repaint = (_target, _propertyKey, descriptor) => {\n  const apply = (original, context, args) => {\n    setImmediate(async () => {\n      if (context[isPainted]) {\n        await context[willPaintCallback]?.();\n        await Promise.all([\n          new Promise(context[htmlCallback]),\n          new Promise(context[cssCallback]),\n        ]);\n        await context[didPaintCallback]?.();\n      }\n    });\n\n    return original.apply(context, args);\n  };\n\n  if (descriptor.set) {\n    descriptor.set = new Proxy(descriptor.set, { apply });\n  }\n\n  if (descriptor.value) {\n    descriptor.value = new Proxy(descriptor.value, { apply });\n  }\n};\n\nexport default repaint;\n","import \"@polyfill/setImmediate\";\nimport { cssCallback, isPainted } from \"@dom/interfaces\";\n\n/**\n * Decorator that reapplies the component's styles after a method or setter execution.\n *\n * @param {Object} target - The prototype of the decorated Custom Element.\n * @param {string|symbol} propertyKey - The name of the decorated method or setter.\n * @param {PropertyDescriptor} descriptor - The descriptor of the method or setter.\n * @returns {void}\n *\n * @description\n * The `retouch` decorator intercepts the execution of methods or setters and,\n * if the component has already been rendered (`isPainted = true`),\n * re-executes the style application defined in the `cssCallback`.\n *\n * This is useful when the component's style depends on dynamic data\n * that may change during the component's execution.\n *\n * @example\n * import { retouch } from '@hive/std/dom';\n *\n * class MyElement extends HTMLElement {\n *   static [cssCallback]() {\n *     const sheet = new CSSStyleSheet();\n *     sheet.replaceSync(`:host { color: ${this.color}; }`);\n *     return sheet;\n *   }\n *\n *   @retouch\n *   set color(value) {\n *     this._color = value;\n *   }\n *\n *   @retouch\n *   updateStyle() {\n *     this._refresh = true;\n *   }\n * }\n */\nconst retouch = (_target, _propertyKey, descriptor) => {\n  const apply = (original, context, args) => {\n    setImmediate(async () => {\n      if (context[isPainted]) {\n        await new Promise(context[cssCallback]);\n      }\n    });\n\n    return original.apply(context, args);\n  };\n\n  if (descriptor.set) {\n    descriptor.set = new Proxy(descriptor.set, { apply });\n  }\n\n  if (descriptor.value) {\n    descriptor.value = new Proxy(descriptor.value, { apply });\n  }\n};\n\nexport default retouch;\n","import execute from \"@dom/execute\";\nimport { willPaintCallback } from \"@dom/interfaces\";\n\n/**\n * Decorator that executes a method before the component's rendering in the DOM lifecycle.\n *\n * @param {Object} target - The prototype of the decorated Custom Element.\n * @param {string|symbol} method - Name of the method to be executed before render.\n * @returns {void}\n *\n * @description\n * The `willPaint` decorator registers a method to be executed immediately before\n * the component's content rendering, inside the `connectedCallback`, and before\n * applying styles and updating `innerHTML`.\n *\n * This decorator is useful for preparing the component's state before it is painted.\n * It is triggered before `requestAnimationFrame`, ensuring that any pre-rendering logic\n * occurs in advance.\n *\n * @example\n * import { willPaint } from '@hive/std/dom';\n *\n * class MyElement extends HTMLElement {\n *   @willPaint\n *   prepare() {\n *     this.setAttribute('data-loading', 'true');\n *   }\n * }\n */\nconst willPaint = (target, method) =>\n  execute(method).on(target).after(willPaintCallback);\n\nexport default willPaint;\n"],"names":["execute","method","on","target","after","event","Proxy","original","context","args","apply","isPainted","Symbol","for","didPaintCallback","htmlCallback","cssCallback","willPaintCallback","globalThis","setImmediate","Reflect","defineProperty","value","fn","setTimeout","writable","configurable","strings","values","styleSheet","CSSStyleSheet","text","String","raw","replaceSync","map","concat","join","component","styles","with","whenConnected","prototype","connectedCallback","resolve","requestAnimationFrame","async","shadowRoot","innerHTML","styleSheets","style","document","adoptedStyleSheets","Promise","all","_target","_propertyKey","descriptor","set"],"mappings":";;AAsBK,MCACA,IAAWC,CAAAA,QAAM,EAOrBC,IAAKC,CAAAA,QAAM,EAOTC,OAAQC,CAAAA;AACNF,EAAAA,GAAOE,EAAAA,IAAS,IAAIC,MAAMH,GAAOE,EAAAA,MAAM,MAAA;AAAA,EAAa,IAAG,EACrD,YAAYE,IAAUC,IAASC,IAAAA;AAAAA,UACvBF,GAASG,MAAMF,IAASC,WACxBD,GAAQP,EAAAA,EAAAA;AAAAA,EAChB;AACA,EAAA,GAAA,ICnCKU,IAAYC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