browser.js 686 B

123456789101112131415161718192021222324252627282930
  1. /**
  2. * @typedef {import('hast').Root} Root
  3. *
  4. * @typedef {typeof import('./index.js').fromHtmlIsomorphic} FromHtmlIsomorphic
  5. */
  6. import {fromDom} from 'hast-util-from-dom'
  7. const parser = new DOMParser()
  8. /** @type {FromHtmlIsomorphic} */
  9. export function fromHtmlIsomorphic(value, options) {
  10. const node = options?.fragment
  11. ? parseFragment(value)
  12. : parser.parseFromString(value, 'text/html')
  13. return /** @type {Root} */ (fromDom(node))
  14. }
  15. /**
  16. * Parse as a fragment.
  17. *
  18. * @param {string} value
  19. * @returns {DocumentFragment}
  20. */
  21. function parseFragment(value) {
  22. const template = document.createElement('template')
  23. template.innerHTML = value
  24. return template.content
  25. }