html.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { truncator, inspectList } from './helpers'
  2. export function inspectAttribute([key, value], options) {
  3. options.truncate -= 3
  4. if (!value) {
  5. return `${options.stylize(key, 'yellow')}`
  6. }
  7. return `${options.stylize(key, 'yellow')}=${options.stylize(`"${value}"`, 'string')}`
  8. }
  9. export function inspectHTMLCollection(collection, options) {
  10. // eslint-disable-next-line no-use-before-define
  11. return inspectList(collection, options, inspectHTML, '\n')
  12. }
  13. export default function inspectHTML(element, options) {
  14. const properties = element.getAttributeNames()
  15. const name = element.tagName.toLowerCase()
  16. const head = options.stylize(`<${name}`, 'special')
  17. const headClose = options.stylize(`>`, 'special')
  18. const tail = options.stylize(`</${name}>`, 'special')
  19. options.truncate -= name.length * 2 + 5
  20. let propertyContents = ''
  21. if (properties.length > 0) {
  22. propertyContents += ' '
  23. propertyContents += inspectList(
  24. properties.map(key => [key, element.getAttribute(key)]),
  25. options,
  26. inspectAttribute,
  27. ' '
  28. )
  29. }
  30. options.truncate -= propertyContents.length
  31. const truncate = options.truncate
  32. let children = inspectHTMLCollection(element.children, options)
  33. if (children && children.length > truncate) {
  34. children = `${truncator}(${element.children.length})`
  35. }
  36. return `${head}${propertyContents}${headClose}${children}${tail}`
  37. }