cvzi / genius-lyrics-userscript

A userscript library to show lyrics from genius.com on other websites
GNU General Public License v3.0
14 stars 5 forks source link

[TODO] Code Change #79

Closed cyfung1031 closed 6 days ago

cyfung1031 commented 1 month ago
const elmBuild = (tag, ...contents) => {
  /** @type {HTMLElement} */
  const elm = typeof tag === 'string' ? document.createElement(tag) : tag;
  for (const content of contents) {
    if (!content || typeof content !== 'object' || (content instanceof Node)) {
      elm.append(content)
    } else if (content.length > 0) {
      elm.appendChild(elmBuild(...content))
    } else if (content.style) {
      Object.assign(elm.style, content.style);
    } else if (content.classList) {
      elm.classList.add(...content.classList)
    } else if (content.attr) {
      for (const [attr, val] of Object.entries(content.attr)) elm.setAttribute(attr, val);
    } else {
      Object.assign(elm, content)
    }
  }
  return elm;
}
const elmBuildNS = (tag, ...contents) => {
  const ns = 'http://www.w3.org/2000/svg'
  /** @type {Element} */
  const elm = typeof tag === 'string' ? document.createElementNS(ns, tag) : tag;
  for (const content of contents) {
    if (!content || typeof content !== 'object' || (content instanceof Node)) {
      elm.append(content)
    } else if (content.length > 0) {
      elm.appendChild(elmBuildNS(...content))
    } else if (content.style) {
      Object.assign(elm.style, content.style);
    } else if (content.classList) {
      elm.classList.add(...content.classList)
    } else if (content.attr) {
      for (const [attr, val] of Object.entries(content.attr)) elm.setAttributeNS(ns, attr, val);
    } else {
      Object.assign(elm, content)
    }
  }
  return elm;
}

Coding Example

elmBuild(container,
  ['h2',
    'This script only works in ',
    ['a', {
      'target': '_blank',
      'href': 'https://addons.mozilla.org/en-US/firefox/addon/tampermonkey/'
    }, 'Tampermonkey'],
  ],
  'Greasemonkey is no longer supported because of this ',
  ['a', {
    'target': '_blank',
    'href': 'https://github.com/greasemonkey/greasemonkey/issues/2574'
  }, 'bug greasemonkey/issues/2574'],
  ' in Greasemonkey.',
)

Preview