all files / dom/ MemoryDOMElement.js

87.5% Statements 350/400
74.79% Branches 175/234
91.3% Functions 84/92
89.74% Lines 341/380
6 statements, 1 function, 5 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857                      5226×   5226× 5226×   5226×   5226×             5226×   3288× 3288× 3288× 3288× 3288× 3288× 3288× 3288× 3288× 3288× 3288×       1438× 1438×             494× 494× 494× 494× 494×   28× 28×   466× 466×       494×                                 14×         10×         1823×       687×       736×       83×               11× 11×           11×       3593×             4621×       11×     11×             244526×       2981×   2981×   856× 856×   321× 321×       2981× 2981× 2966×   2981×                               1025×       18× 18×         17× 17×   16×   16×       16× 16×                             10×                             19×       1302×                                 14× 14×         10× 10×   10× 10×   10×       2255×       1187×       108×       17× 17×             1835×       818× 882×               35× 35×                                                 88×       16711×       9870×             3282×       1424×                         1611× 1546× 1546× 1546× 1546×   1611×               58× 58× 58× 58×   58×   57×   58×   58×                             10× 10× 10× 10×   10×   10×       23× 23×       89× 89×   89×       89× 89× 89× 89×       1026×       10× 10×       12×       18× 18× 17×   17× 17× 17× 17×         1024× 1024×       3288× 3288×     3288×           3288× 3288×                     3288×         1693× 38×     1693×   1693×       3292× 65×   3227×         2981×       6889×           307×   298×       480×     480× 57×   480× 480× 463× 463× 17× 17×   479× 56× 56× 54×       423×         86×         86×           86×         86×   86×                         857× 1569×           321× 321× 321× 656×   656× 615× 615× 615×       10× 10×     10× 10×                 12× 12× 12×   12×   10× 10×                                       3292× 3292×     3292×                         2966× 2966× 18× 18× 15×                         11× 11×                     11×           15×   14×       16× 16× 13× 13× 12× 12×                 463× 463×     66× 66× 66× 66× 66× 66× 66× 66×       66× 147× 66×   66×       66× 66× 66× 66× 66×   66× 64× 64×   66×   66×      
import { forEach, isString, isNil, isNumber, last, inBrowser } from '../util'
import ElementType from 'domelementtype'
import cssSelect from '../vendor/css-select'
import DomUtils from '../vendor/domutils'
import DOMElement from './DOMElement'
import parseMarkup from './parseMarkup'
 
export default
class MemoryDOMElement extends DOMElement {
 
  constructor(type, args = {}) {
    super()
 
    this.type = type
    Iif (!type) throw new Error("'type' is mandatory")
 
    this.ownerDocument = args.ownerDocument
    /* istanbul ignore next */
    Iif (type !== 'document' && !this.ownerDocument) {
      throw new Error("'ownerDocument' is mandatory")
    }
 
    // NOTE: there are some properties which are named so that this
    // can be used together with htmlparser2 and css-select
    // but which could have a better naming, e.g., name -> tagName
 
    switch(type) {
      case ElementType.Tag: {
        Iif (!args.name) throw new Error("'name' is mandatory.")
        this.name = this._normalizeName(args.name)
        this.nameWithoutNS = nameWithoutNS(this.name)
        this.properties = new Map()
        this.attributes = new Map()
        this.classes = new Set()
        this.styles = new Map()
        this.eventListeners = []
        this.childNodes = args.children || args.childNodes || []
        this._assign(args)
        break
      }
      case ElementType.Text:
      case ElementType.Comment: {
        this.data = args.data || ''
        break
      }
      case ElementType.CDATA: {
        this.data = args.data || ''
        break
      }
      case ElementType.Directive: {
        Iif (!args.name) throw new Error("'name' is mandatory.")
        this.name = this._normalizeName(args.name)
        this.nameWithoutNS = nameWithoutNS(this.name)
        this.data = args.data
        break
      }
      case 'document': {
        let format = args.format
        this.format = format
        Iif (!format) throw new Error("'format' is mandatory.")
        this.childNodes = args.children || args.childNodes || []
        switch(format) {
          case 'xml':
            this.contentType = 'application/xml'
            break
          case 'html':
            this.contentType = 'text/html'
            break
          default:
            throw new Error('Unsupported format ' + format)
        }
        break
      }
      default:
        this.name = null
        this.properties = new Map()
        this.attributes = new Map()
        this.classes = new Set()
        this.styles = new Map()
        this.eventListeners = []
        this.childNodes = args.children || args.childNodes || []
    }
  }
 
  getNativeElement() {
    return this
  }
 
  getNodeType() {
    switch(this.type) {
      case ElementType.Tag:
      case ElementType.Script:
      case ElementType.Style:
        return 'element'
      default:
        return this.type
    }
  }
 
  isTextNode() {
    return this.type === "text"
  }
 
  isElementNode() {
    return this.type === "tag" || this.type === "script"
  }
 
  isCommentNode() {
    return this.type === "comment"
  }
 
  isDocumentNode() {
    return this.type === "document"
  }
 
  isComponentNode() {
    return this.type === "component"
  }
 
  clone(deep) {
    let clone = new MemoryDOMElement(this.type, this)
    if (this.childNodes) {
      clone.childNodes.length = 0
      Iif (deep) {
        this.childNodes.forEach((child) => {
          clone.appendChild(child.clone(deep))
        })
      }
    }
    return clone
  }
 
  get tagName() {
    return this.getTagName()
  }
 
  set tagName(tagName) {
    this.setTagName(tagName)
  }
 
  getTagName() {
    return this.name
  }
 
  setTagName(tagName) {
    if (this._isXML()) {
      this.name = String(tagName)
    } else {
      this.name = String(tagName).toLowerCase()
    }
    return this
  }
 
  hasAttribute(name) {
    return this.attributes.has(name)
  }
 
  getAttribute(name) {
    return this.attributes.get(name)
  }
 
  setAttribute(name, value) {
    value = String(value)
    // Note: keeping the Set version of classes and styles in sync
    switch(name) {
      case 'class':
        parseClasses(this.classes, value)
        break
      case 'style':
        parseStyles(this.styles, value)
        break
      default:
        //
    }
    this.attributes.set(name, value)
    if (this._isHTML()) {
      deriveHTMLPropertyFromAttribute(this, name, value)
    }
    return this
  }
 
  removeAttribute(name) {
    switch(name) {
      case 'class':
        this.classes = new Set()
        break
      case 'style':
        this.styles = new Map()
        break
      default:
        //
    }
    this.attributes.delete(name)
    return this
  }
 
  getAttributes() {
    return this.attributes
  }
 
  getProperty(name) {
    Eif (this.properties) {
      return this.properties.get(name)
    }
  }
 
  setProperty(name, value) {
    Eif (this.properties) {
      if (this._isXML()) {
        throw new Error('setProperty() is only be used on HTML elements')
      }
      _setHTMLPropertyValue(this, name, value)
    }
    return this
  }
 
  hasClass(name) {
    Eif (this.classes) {
      return this.classes.has(name)
    }
  }
 
  addClass(name) {
    this.classes.add(name)
    this.attributes.set('class', stringifyClasses(this.classes))
    return this
  }
 
  removeClass(name) {
    Eif (this.classes && this.classes.has(name)) {
      this.classes.delete(name)
      this.attributes.set('class', stringifyClasses(this.classes))
    }
    return this
  }
 
  getContentType() {
    return this.getOwnerDocument().contentType
  }
 
  getInnerHTML() {
    return DomUtils.getInnerHTML(this)
  }
 
  // TODO: parse html using settings from el,
  // clear old childNodes and append new childNodes
  setInnerHTML(html) {
    Eif (this.childNodes) {
      let _doc = parseMarkup(html, {
        ownerDocument: this.getOwnerDocument()
      })
      this.empty()
      // ATTENTION: important to copy the childNodes array first
      // as appendChild removes from parent
      _doc.childNodes.slice(0).forEach((child) => {
        this.appendChild(child)
      })
    }
    return this
  }
 
  getOuterHTML() {
    return DomUtils.getOuterHTML(this, { xmlMode: this._isXML() })
  }
 
  getTextContent() {
    return DomUtils.getText(this)
  }
 
  setTextContent(text) {
    switch(this.type) {
      case ElementType.Text:
      case ElementType.Comment:
      case ElementType.CDATA: {
        this.data = text
        break
      }
      default: {
        Eif (this.childNodes) {
          let child = this.createTextNode(text)
          this.empty()
          this.appendChild(child)
        }
      }
    }
    return this
  }
 
  getStyle(name) {
    Eif (this.styles) {
      return this.styles.get(name)
    }
  }
 
  setStyle(name, value) {
    Eif (this.styles) {
      if (DOMElement.pxStyles[name] && isNumber(value)) {
        value = value + "px"
      }
      this.styles.set(name, value)
      this.attributes.set('style', stringifyStyles(this.styles))
    }
    return this
  }
 
  is(cssSelector) {
    return cssSelect.is(this, cssSelector, { xmlMode: this._isXML() })
  }
 
  find(cssSelector) {
    return cssSelect.selectOne(cssSelector, this, { xmlMode: this._isXML() })
  }
 
  findAll(cssSelector) {
    return cssSelect.selectAll(cssSelector, this, { xmlMode: this._isXML() })
  }
 
  getChildCount() {
    Eif (this.childNodes) {
      return this.childNodes.length
    } else {
      return 0
    }
  }
 
  getChildNodes() {
    return this.childNodes.slice(0)
  }
 
  getChildren() {
    return this.childNodes.filter(function(node) {
      return node.type === "tag"
    })
  }
 
  get children() {
    return this.getChildren()
  }
 
  getChildAt(pos) {
    Eif (this.childNodes) {
      return this.childNodes[pos]
    }
  }
 
  getChildIndex(child) {
    Eif (this.childNodes) {
      return this.childNodes.indexOf(child)
    }
  }
 
  getLastChild() {
    Eif (this.childNodes) {
      return last(this.childNodes)
    }
  }
 
  getFirstChild() {
    Eif (this.childNodes) {
      return this.childNodes[0]
    }
  }
 
  getNextSibling() {
    return this.next
  }
 
  getPreviousSibling() {
    return this.prev
  }
 
  getParent() {
    return this.parent
  }
 
  getOwnerDocument() {
    return (this.type === 'document') ? this : this.ownerDocument
  }
 
  getFormat() {
    return this.getOwnerDocument().format
  }
 
  createDocument(format) {
    return MemoryDOMElement.createDocument(format)
  }
 
  createElement(tagName) {
    return new MemoryDOMElement(ElementType.Tag, { name: tagName, ownerDocument: this.getOwnerDocument() })
  }
 
  createTextNode(text) {
    return new MemoryDOMElement(ElementType.Text, { data: text, ownerDocument: this.getOwnerDocument() })
  }
 
  createComment(data) {
    return new MemoryDOMElement(ElementType.Comment, { data: data, ownerDocument: this.getOwnerDocument() })
  }
 
  createProcessingInstruction(name, data) {
    return new MemoryDOMElement(ElementType.Directive, { name: name, data: data, ownerDocument: this.getOwnerDocument() })
  }
 
  createCDATASection(data) {
    return new MemoryDOMElement(ElementType.CDATA, { data: data, ownerDocument: this.getOwnerDocument() })
  }
 
  appendChild(child) {
    if (this.childNodes && !isNil(child)) {
      child = this._normalizeChild(child)
      Iif (!child) return this
      DomUtils.appendChild(this, child)
      child.ownerDocument = this.getOwnerDocument()
    }
    return this
  }
 
  removeChild(child) {
    Eif (child.parentNode === this) {
      child.remove()
    }
  }
 
  insertAt(pos, child) {
    child = this._normalizeChild(child)
    Iif (!child) return this
    let childNodes = this.childNodes
    Eif (childNodes) {
      // NOTE: manipulating htmlparser's internal children array
      if (pos >= childNodes.length) {
        DomUtils.appendChild(this, child)
      } else {
        DomUtils.prepend(childNodes[pos], child)
      }
      child.ownerDocument = this.getOwnerDocument()
    }
    return this
  }
 
  insertBefore(newChild, before) {
    Eif (this.childNodes) {
      var pos = this.childNodes.indexOf(before)
      Eif (pos > -1) {
        DomUtils.prepend(before, newChild)
        newChild.ownerDocument = this.getOwnerDocument()
      } else {
        throw new Error('insertBefore(): reference node is not a child of this element.')
      }
    }
    return this
  }
 
  removeAt(pos) {
    let childNodes = this.childNodes
    Eif (childNodes) {
      let child = childNodes[pos]
      child.remove()
    }
    return this
  }
 
  empty() {
    let childNodes = this.childNodes
    Eif (childNodes) {
      childNodes.forEach((child) => {
        child.next = child.prev = child.parent = null
      })
      childNodes.length = 0
    }
    return this
  }
 
  remove() {
    DomUtils.removeElement(this)
    return this
  }
 
  replaceChild(oldChild, newChild) {
    Eif (oldChild.parent === this) {
      oldChild.replaceWith(newChild)
    }
    return this
  }
 
  replaceWith(newEl) {
    newEl = this._normalizeChild(newEl)
    DomUtils.replaceElement(this, newEl)
    newEl.ownerDocument = this.getOwnerDocument()
    return this
  }
 
  getEventListeners() {
    return this.eventListeners
  }
 
  click() {
    this.emit('click', { target: this })
    return this
  }
 
  emit(name, data) {
    this._propagateEvent(new MemoryDOMElementEvent(name, this, data))
  }
 
  _propagateEvent(event) {
    let listeners = this.eventListeners
    if (listeners) {
      let listener = listeners.find((l) => {
        return l.eventName === event.type
      })
      if (listener) listener.handler(event)
      Iif (event.stopped) return
      let p = this.parentNode
      if (p) p._propagateEvent(event)
    }
  }
 
  removeAllEventListeners() {
    this.eventListeners = []
    return this
  }
 
  _assign(other) {
    Eif (other.name) this.name = other.name
    if (this.classes && other.classes) {
      other.classes.forEach((val) => {
        this.classes.add(val)
      })
    }
    if (this.styles && other.styles) {
      forEach(other.styles, (val, name) => {
        this.styles.set(name, val)
      })
    }
    // TODO: while it is 'smart' to deal with 'style' and 'class'
    // implicitly, it introduces some confusion here
    let otherAttributes = other.attributes || other.attribs
    if (this.attributes && otherAttributes) {
      forEach(otherAttributes, (val, name) => {
        switch (name) {
          case 'class': {
            parseClasses(this.classes, val)
            break
          }
          case 'style': {
            parseStyles(this.styles, val)
            break
          }
          default:
            this.attributes.set(name, val)
        }
      })
    }
    if (this.eventListeners && other.eventListeners) {
      this.eventListeners = this.eventListeners.concat(other.eventListeners)
    }
  }
 
  _normalizeChild(child) {
    if (isString(child)) {
      child = this.createTextNode(child)
    }
    /* istanbul ignore next */
    Iif (!child || !child._isMemoryDOMElement) {
      throw new Error('Illegal argument: only String and MemoryDOMElement instances are valid.')
    }
    return child
  }
 
  _normalizeName(name) {
    if (this._isXML()) {
      return name
    } else {
      return name.toLowerCase()
    }
  }
 
  _isHTML() {
    return this.getFormat() === 'html'
  }
 
  _isXML() {
    return this.getFormat() === 'xml'
  }
 
}
 
MemoryDOMElement.prototype._isMemoryDOMElement = true
 
MemoryDOMElement.createDocument = function(format) {
  if (format === 'xml') {
    return new MemoryDOMElement('document', { format: format })
  } else {
    return MemoryDOMElement.parseMarkup(DOMElement.EMPTY_HTML, 'html')
  }
}
 
MemoryDOMElement.parseMarkup = function(str, format, options={}) {
  Iif (!str) {
    return MemoryDOMElement.createDocument(format)
  }
  if (options.snippet) {
    str = `<__snippet__>${str}</__snippet__>`
  }
  let doc
  if (format === 'html') {
    doc = parseMarkup(str, { format: format })
    _sanitizeHTMLStructure(doc)
  } else Eif (format === 'xml') {
    doc = parseMarkup(str, { format: format })
  }
  if (options.snippet) {
    let childNodes = doc.find('__snippet__').childNodes
    if (childNodes.length === 1) {
      return childNodes[0]
    } else {
      return childNodes
    }
  } else {
    return doc
  }
}
 
MemoryDOMElement.wrap =
MemoryDOMElement.wrapNativeElement = function(el) {
  Eif (inBrowser) {
    // HACK: at many places we have an `isBrowser` check
    // to skip code that uses window or window.document
    // To be able to test such code together with the memory DOM implementation
    // we stub out window and document
    Iif (el === window || el === window.document) {
      return new DOMElementStub()
    }
    // HACK: additionally, if a window.document.Node or a BrowserDOMElement is given
    // as it happens when trying to mount onto t.sandbox with DefaultDOMElement using MemoryDOMElement as default
    // we just return a new root element
    else Iif (el instanceof window.Node || el._isBrowserDOMElement) {
      // return MemoryDOMElement.createDocument('html').createElement('div')
    }
  }
  /* istanbul ignore next */
  Iif (!el._isMemoryDOMElement) {
    throw new Error('Illegal argument: expected MemoryDOMElement instance')
  }
  return el
}
 
MemoryDOMElement.unwrap = function(el) {
  /* istanbul ignore next */
  if (!el._isMemoryDOMElement) {
    throw new Error('Illegal argument: expected MemoryDOMElement instance')
  }
  return el
}
 
// TODO: this is used only in browser to determine if
// a selection  is reverse.
/* istanbul ignore next */
MemoryDOMElement.isReverse = function() {
  return false
}
 
function parseClasses(classes, classStr) {
  classStr.split(/\s+/).forEach((name) => {
    classes.add(name)
  })
}
 
function stringifyClasses(classes) {
  return Array.from(classes).join(' ')
}
 
function parseStyles(styles, styleStr) {
  styleStr = (styleStr || '').trim()
  Iif (!styleStr) return
  styleStr.split(';').forEach((style) => {
    let n = style.indexOf(':')
    // skip if there is no :, or if it is the first/last character
    if (n < 1 || n === style.length-1) return
    let name = style.slice(0,n).trim()
    let val = style.slice(n+1).trim()
    styles.set(name, val)
  })
}
 
function stringifyStyles(styles) {
  Iif (!styles) return ''
  let str = Object.keys(styles).map((name) => {
    return name + ':' + styles[name]
  }).join(';')
  Iif (str.length > 0) str += ';'
  return str
}
 
const BUILTIN_EVENTS = [
  'keydown', 'keyup', 'keypress',
  'mousedown', 'mouseup', 'mouseover', 'click', 'dblclick'
].reduce((m, k)=>{m[k]=true;return m}, {})
 
class MemoryDOMElementEvent {
 
  constructor(type, target, detail) {
    this.type = type
    this.timeStamp = Date.now()
    this.target = target
 
    if (BUILTIN_EVENTS[type]) {
      // TODO: dunno if this is the best way of doing it
      Eif (detail) {
        Object.assign(this, detail)
      }
    } else {
      this.detail = detail
    }
  }
 
  stopPropagation() {
    this.stopped = true
  }
 
  preventDefault() {
    this.defaultPrevented = true
  }
}
 
class DOMElementStub {
  on() {}
  off(){}
}
 
function nameWithoutNS(name) {
  const idx = name.indexOf(':')
  Iif (idx > 0) {
    return name.slice(idx)
  } else {
    return name
  }
}
 
// Note: some attributes are used to initialize an
// element property
const ATTR_TO_PROPS = {
  "input": {
    "value": true,
    "checked": (el, name, value) => {
      const checked = (value !== 'off')
      el.setProperty('checked', checked)
    }
  }
}
 
function deriveHTMLPropertyFromAttribute(el, name, value) {
  const mappings = ATTR_TO_PROPS[el.tagName]
  if (mappings) {
    let mapper = mappings[name]
    if (mapper === true) {
      el.setProperty(name, value)
    } else if (mapper) {
      mapper(el, name, value)
    }
  }
}
 
const PROPERTY_TRANSFORMATIONS = {
  "input": {
    "checked": (el, name, value) => {
      Eif (value === true) {
        el.properties.set(name, true)
        el.properties.set('value', 'on')
      } else {
        el.properties.set(name, false)
        el.properties.set('value', 'off')
      }
    },
    "value": (el, name, value) => {
      let type = el.getAttribute('type')
      switch(type) {
        case 'checkbox':
          if (value === 'on') {
            el.properties.set(name, true)
            el.properties.set('value', 'on')
          } else {
            el.properties.set(name, false)
            el.properties.set('value', 'off')
          }
          break
        default:
          _setProperty(el, name, value)
      }
    }
  }
}
 
function _setProperty(el, name, value) {
  if (value === undefined) {
    el.properties.delete(name)
  } else {
    el.properties.set(name, String(value))
  }
}
 
function _setHTMLPropertyValue(el, name, value) {
  const trafos = PROPERTY_TRANSFORMATIONS[el.tagName]
  if (trafos) {
    let mapper = trafos[name]
    if (mapper) {
      mapper(el, name, value)
      return
    }
  }
  _setProperty(el, name, value)
}
 
function _sanitizeHTMLStructure(doc) {
  // as opposed to DOMParser in the browser
  // htmlparser2 does not create <head> and <body> per se
  // thus we need to make sure that everything is working
  // similar as in the browser
  let htmlEl = doc.find('html')
  if (!htmlEl) {
    // remove head and nodes which must go into the head
    // so they do not go into the body
    let headEl = doc.find('head')
    let titleEl = doc.find('title')
    let metaEls = doc.findAll('meta')
    let bodyEl = doc.find('body')
    Iif (headEl) headEl.remove()
    if (titleEl) titleEl.remove()
    metaEls.forEach(e => e.remove())
    if (bodyEl) bodyEl.remove()
 
    // keep the remaining content nodes,
    // we will add them to the body
    let contentNodes = doc.childNodes.slice()
    contentNodes.forEach((c)=>{c.parent = null})
    doc.childNodes.length = 0
 
    htmlEl = doc.createElement('html')
    // if not there create a <head> and
    // add all the elements that are supposed to
    // go there
    Eif (!headEl) {
      headEl = doc.createElement('head')
      headEl.appendChild(titleEl)
      headEl.append(metaEls)
      htmlEl.appendChild(headEl)
    }
    if (!bodyEl) {
      bodyEl = doc.createElement('body')
      bodyEl.append(contentNodes)
    }
    htmlEl.appendChild(bodyEl)
 
    doc.append(htmlEl)
  }
}