Yokan / rebuild
Course 1 8624561

HtmlDom.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/HtmlDom.kt

implementation561 lines
1package eu.friedcutlet.yokan.services.extensions.js23/**4 * Jsoup-like HTML DOM implemented in JavaScript, injected into the QuickJS5 * extension bootstrap. Provides `new Document(html)`, element6 * `select`/`selectFirst`/`querySelector`/`querySelectorAll`/`attr`/`text`/`html`/7 * `ownText`/`hasClass`, a CSS selector engine (descendant/child/sibling8 * combinators, attribute operators, `:not`/`:has`/`:contains`/`:nth-child`/9 * `:first-child`/`:last-child`), Jsoup `abs:` URL resolution, `atob`/`btoa`, and10 * element/string-returning `querySelector`/`querySelectorAll` globals. Elements11 * are hybrids: element methods work and, for extensions that treat results as12 * raw HTML, string methods operate on element outer HTML. Pure JS so every13 * platform's QuickJS behaves identically.14 */15internal const val HTML_DOM_JS = """16// Yokan Jsoup-like HTML DOM for the QuickJS extension runtime.17// Exposes: Document (class), querySelector, querySelectorAll, atob, btoa.18var YokanDom = (function () {19  var VOID = { area:1,base:1,br:1,col:1,command:1,embed:1,hr:1,img:1,input:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1 };20  var RAWTEXT = { script:1, style:1, textarea:1, title:1 };21  var RAWTEXT_CLOSE = {}; // tag -> global closing-tag RegExp, compiled once per raw-text tag22  var SPACE = /\s/;23  var ENTITIES = { amp:"&", lt:"<", gt:">", quot:'"', apos:"'", nbsp:"\u00a0", copy:"\u00a9", reg:"\u00ae", hellip:"\u2026", mdash:"\u2014", ndash:"\u2013", rsquo:"\u2019", lsquo:"\u2018", ldquo:"\u201c", rdquo:"\u201d", trade:"\u2122", times:"\u00d7", middot:"\u00b7", laquo:"\u00ab", raquo:"\u00bb", deg:"\u00b0", eacute:"\u00e9" };2425  function decodeEntities(s) {26    if (s == null) return "";27    s = String(s);28    if (s.indexOf("&") === -1) return s;29    return s.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g, function (whole, body) {30      if (body.charAt(0) === "#") {31        var code = body.charAt(1) === "x" || body.charAt(1) === "X"32          ? parseInt(body.slice(2), 16)33          : parseInt(body.slice(1), 10);34        if (isFinite(code)) {35          try { return String.fromCodePoint(code); } catch (e) { return whole; }36        }37        return whole;38      }39      var named = ENTITIES[body];40      return named != null ? named : whole;41    });42  }4344  function parseAttrs(str) {45    var attrs = {};46    if (!str) return attrs;47    var re = /([^\s"'=\/>]+)(?:\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;48    var m;49    while ((m = re.exec(str))) {50      var name = m[1].toLowerCase();51      if (name === "/") continue;52      var val = m[3] !== undefined ? m[3] : (m[4] !== undefined ? m[4] : (m[5] !== undefined ? m[5] : ""));53      if (!(name in attrs)) attrs[name] = decodeEntities(val);54    }55    return attrs;56  }5758  function Node(type, tag) {59    this.type = type; this.tag = tag || null; this.attrs = {}; this.children = []; this.parent = null; this.textContent = null; this.raw = false;60  }6162  function parse(html) {63    html = String(html == null ? "" : html);64    html = html.replace(/<!--[\s\S]*?-->/g, "").replace(/<!\[CDATA\[[\s\S]*?\]\]>/g, "");65    var root = new Node("element", "#root");66    var stack = [root];67    var tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9:_-]*)((?:"[^"]*"|'[^']*'|[^>])*?)(\/?)>/g;68    var last = 0, m;69    function top() { return stack[stack.length - 1]; }70    function addText(text) {71      if (text === "") return;72      var t = new Node("text");73      t.textContent = text; t.parent = top();74      top().children.push(t);75    }76    while ((m = tagRe.exec(html))) {77      var idx = m.index;78      if (idx > last) addText(html.slice(last, idx));79      last = tagRe.lastIndex;80      var closing = m[1], tag = m[2].toLowerCase(), attrStr = m[3], selfClose = m[4];81      if (tag === "!doctype") continue;82      if (closing) {83        for (var i = stack.length - 1; i > 0; i--) {84          if (stack[i].tag === tag) { stack.length = i; break; }85        }86        continue;87      }88      var node = new Node("element", tag);89      node.attrs = parseAttrs(attrStr);90      node.parent = top();91      top().children.push(node);92      if (VOID[tag] || selfClose) {93        // no children94      } else if (RAWTEXT[tag]) {95        var closeRe = RAWTEXT_CLOSE[tag] || (RAWTEXT_CLOSE[tag] = new RegExp("</" + tag + "\\s*>", "gi"));96        // Search in place from the tag end instead of copying the rest of the document per element.97        closeRe.lastIndex = last;98        var cm = closeRe.exec(html);99        var end = cm ? cm.index : html.length;100        var textNode = new Node("text");101        textNode.textContent = html.slice(last, end); textNode.raw = true; textNode.parent = node;102        node.children.push(textNode);103        last = cm ? end + cm[0].length : html.length;104        tagRe.lastIndex = last;105      } else {106        stack.push(node);107      }108    }109    if (last < html.length) addText(html.slice(last));110    return root;111  }112113  // ---------- selector parsing ----------114  function parseSelectorList(selector) {115    var groups = [];116    var buf = "", depth = 0;117    for (var i = 0; i < selector.length; i++) {118      var ch = selector.charAt(i);119      if (ch === "(" || ch === "[") depth++;120      else if (ch === ")" || ch === "]") depth--;121      if (ch === "," && depth === 0) { groups.push(buf); buf = ""; }122      else buf += ch;123    }124    if (buf.trim()) groups.push(buf);125    return groups.map(parseComplex);126  }127128  function parseComplex(sel) {129    sel = sel.trim();130    var parts = [];131    var i = 0, n = sel.length;132    var pendingCombinator = null;133    while (i < n) {134      var sawSpace = false;135      while (i < n && SPACE.test(sel.charAt(i))) { i++; sawSpace = true; }136      if (i >= n) break;137      var ch = sel.charAt(i);138      if (ch === ">" || ch === "+" || ch === "~") { pendingCombinator = ch; i++; continue; }139      if (sawSpace && parts.length > 0 && pendingCombinator == null) pendingCombinator = " ";140      var start = i, depth = 0;141      while (i < n) {142        var c = sel.charAt(i);143        if (c === "(" || c === "[") depth++;144        else if (c === ")" || c === "]") depth--;145        else if (depth === 0 && (SPACE.test(c) || c === ">" || c === "+" || c === "~")) break;146        i++;147      }148      var compoundStr = sel.slice(start, i);149      parts.push({ comb: parts.length === 0 ? null : (pendingCombinator || " "), compound: parseCompound(compoundStr) });150      pendingCombinator = null;151    }152    return parts;153  }154155  function parseCompound(str) {156    var c = { tag: null, id: null, classes: [], attrs: [], pseudos: [] };157    var re = /([#.]?[a-zA-Z0-9_*-]+|\[[^\]]*\]|:[a-zA-Z-]+(?:\([^)]*\))?)/g;158    var m;159    while ((m = re.exec(str))) {160      var tok = m[1];161      var first = tok.charAt(0);162      if (first === "#") c.id = tok.slice(1);163      else if (first === ".") c.classes.push(tok.slice(1));164      else if (first === "[") {165        var body = tok.slice(1, -1);166        var am = body.match(/^([^\^\$\*~|=!\s]+)\s*([\^\$\*~|]?=)?\s*(.*)$/);167        if (am) {168          var name = am[1].toLowerCase();169          var op = am[2] || null;170          var val = am[3] || "";171          if ((val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') || (val.charAt(0) === "'" && val.charAt(val.length - 1) === "'")) val = val.slice(1, -1);172          c.attrs.push({ name: name, op: op, val: val });173        }174      } else if (first === ":") {175        var pm = tok.match(/^:([a-zA-Z-]+)(?:\(([\s\S]*)\))?$/);176        if (pm) c.pseudos.push({ name: pm[1].toLowerCase(), arg: pm[2] != null ? pm[2] : null });177      } else {178        c.tag = tok.toLowerCase();179      }180    }181    return c;182  }183184  // ---------- matching ----------185  function elementChildren(node) {186    var out = [];187    for (var i = 0; i < node.children.length; i++) if (node.children[i].type === "element") out.push(node.children[i]);188    return out;189  }190  function prevElement(node) {191    if (!node.parent) return null;192    var sibs = node.parent.children, seen = null;193    for (var i = 0; i < sibs.length; i++) {194      if (sibs[i] === node) return seen;195      if (sibs[i].type === "element") seen = sibs[i];196    }197    return null;198  }199  function nodeText(node, collapse) {200    var out = [];201    (function walk(n) {202      for (var i = 0; i < n.children.length; i++) {203        var ch = n.children[i];204        if (ch.type === "text") out.push(ch.raw ? ch.textContent : decodeEntities(ch.textContent));205        else walk(ch);206      }207    })(node);208    var text = out.join("");209    if (collapse !== false) text = text.replace(/\s+/g, " ").trim();210    return text;211  }212  function ownText(node) {213    var out = [];214    for (var i = 0; i < node.children.length; i++) {215      var ch = node.children[i];216      if (ch.type === "text") out.push(ch.raw ? ch.textContent : decodeEntities(ch.textContent));217    }218    return out.join("").replace(/\s+/g, " ").trim();219  }220  function serialize(node, includeSelf) {221    if (node.type === "text") return node.textContent;222    var html = "";223    if (includeSelf && node.tag !== "#root") {224      html += "<" + node.tag;225      for (var k in node.attrs) if (node.attrs.hasOwnProperty(k)) html += " " + k + '="' + String(node.attrs[k]).replace(/"/g, "&quot;") + '"';226      html += ">";227    }228    for (var i = 0; i < node.children.length; i++) {229      var ch = node.children[i];230      html += ch.type === "text" ? ch.textContent : serialize(ch, true);231    }232    if (includeSelf && node.tag !== "#root" && !VOID[node.tag]) html += "</" + node.tag + ">";233    return html;234  }235236  function hasClass(node, cls) {237    var c = node.attrs["class"];238    if (!c) return false;239    return (" " + c.replace(/\s+/g, " ") + " ").indexOf(" " + cls + " ") !== -1;240  }241242  function matchAttr(node, a) {243    var has = node.attrs.hasOwnProperty(a.name);244    if (!a.op) return has;245    if (!has) return false;246    var v = String(node.attrs[a.name]);247    switch (a.op) {248      case "=": return v === a.val;249      case "*=": return a.val !== "" && v.indexOf(a.val) !== -1;250      case "^=": return v.indexOf(a.val) === 0;251      case "$=": return a.val === "" || v.slice(v.length - a.val.length) === a.val;252      case "~=": return (" " + v + " ").indexOf(" " + a.val + " ") !== -1;253      case "|=": return v === a.val || v.indexOf(a.val + "-") === 0;254      default: return false;255    }256  }257258  function matchCompound(node, comp) {259    if (node.type !== "element") return false;260    if (comp.tag && comp.tag !== "*" && node.tag !== comp.tag) return false;261    if (comp.id && node.attrs.id !== comp.id) return false;262    for (var i = 0; i < comp.classes.length; i++) if (!hasClass(node, comp.classes[i])) return false;263    for (var j = 0; j < comp.attrs.length; j++) if (!matchAttr(node, comp.attrs[j])) return false;264    for (var p = 0; p < comp.pseudos.length; p++) if (!matchPseudo(node, comp.pseudos[p])) return false;265    return true;266  }267268  function matchPseudo(node, ps) {269    switch (ps.name) {270      case "not": {271        // Parsed once per selector, not once per candidate node.272        var lists = ps.lists || (ps.lists = parseSelectorList(ps.arg || ""));273        for (var i = 0; i < lists.length; i++) if (matchSeq(node, lists[i], lists[i].length - 1)) return false;274        return true;275      }276      case "has": {277        var sub = ps.lists || (ps.lists = parseSelectorList(ps.arg || ""));278        for (var s = 0; s < sub.length; s++) if (selectWithin(node, sub[s]).length > 0) return true;279        return false;280      }281      case "contains": {282        var needle = String(ps.arg || "").replace(/^['"]|['"]$/g, "").toLowerCase();283        return nodeText(node).toLowerCase().indexOf(needle) !== -1;284      }285      case "first-child": return prevElement(node) === null;286      case "last-child": {287        var sibs = node.parent ? elementChildren(node.parent) : [];288        return sibs.length > 0 && sibs[sibs.length - 1] === node;289      }290      case "nth-child": {291        var sibs2 = node.parent ? elementChildren(node.parent) : [];292        var index = -1;293        for (var q = 0; q < sibs2.length; q++) if (sibs2[q] === node) { index = q + 1; break; }294        var arg = String(ps.arg || "").trim();295        if (arg === "odd") return index % 2 === 1;296        if (arg === "even") return index % 2 === 0;297        var num = parseInt(arg, 10);298        return isFinite(num) ? index === num : false;299      }300      case "empty": return elementChildren(node).length === 0 && nodeText(node) === "";301      default: return true;302    }303  }304305  function matchSeq(node, parts, k) {306    if (!matchCompound(node, parts[k].compound)) return false;307    if (k === 0) return true;308    var comb = parts[k].comb;309    if (comb === ">") return !!node.parent && node.parent.type === "element" && matchSeq(node.parent, parts, k - 1);310    if (comb === " ") {311      var p = node.parent;312      while (p && p.type === "element") { if (matchSeq(p, parts, k - 1)) return true; p = p.parent; }313      return false;314    }315    if (comb === "+") { var sib = prevElement(node); return !!sib && matchSeq(sib, parts, k - 1); }316    if (comb === "~") { var s = prevElement(node); while (s) { if (matchSeq(s, parts, k - 1)) return true; s = prevElement(s); } return false; }317    return false;318  }319320  function collectDescendants(root) {321    var out = [];322    (function walk(n) {323      for (var i = 0; i < n.children.length; i++) {324        var ch = n.children[i];325        if (ch.type === "element") { out.push(ch); walk(ch); }326      }327    })(root);328    return out;329  }330331  function selectWithin(root, parts) {332    var all = collectDescendants(root);333    var res = [];334    for (var i = 0; i < all.length; i++) if (matchSeq(all[i], parts, parts.length - 1)) res.push(all[i]);335    return res;336  }337338  function selectAll(root, selector) {339    var lists = parseSelectorList(selector);340    if (lists.length === 1) return selectWithin(root, lists[0]);341    var all = collectDescendants(root);342    var seen = [], res = [];343    for (var i = 0; i < lists.length; i++) {344      var matched = selectWithin(root, lists[i]);345      for (var j = 0; j < matched.length; j++) if (seen.indexOf(matched[j]) === -1) { seen.push(matched[j]); res.push(matched[j]); }346    }347    res.sort(function (a, b) { return all.indexOf(a) - all.indexOf(b); });348    return res;349  }350351  // ---------- callable string (works as .text and .text()) ----------352  var STRING_METHODS = ["trim","trimStart","trimEnd","toLowerCase","toUpperCase","indexOf","lastIndexOf","includes","startsWith","endsWith","slice","substring","substr","replace","replaceAll","split","match","matchAll","search","charAt","charCodeAt","codePointAt","padStart","padEnd","concat","repeat","normalize","localeCompare"];353  function callableString(value) {354    value = value == null ? "" : String(value);355    var fn = function () { return value; };356    fn.toString = function () { return value; };357    fn.valueOf = function () { return value; };358    fn.toJSON = function () { return value; };359    for (var i = 0; i < STRING_METHODS.length; i++) {360      (function (name) {361        if (typeof value[name] === "function") fn[name] = function () { return value[name].apply(value, arguments); };362      })(STRING_METHODS[i]);363    }364    try { Object.defineProperty(fn, "length", { get: function () { return value.length; } }); } catch (e) {}365    return fn;366  }367368  // ---------- URL resolution (Jsoup abs:) ----------369  function resolveUrl(base, url) {370    url = String(url == null ? "" : url).trim();371    if (url === "") return "";372    if (url.indexOf("//") === 0) return "https:" + url;373    if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)) return url;374    if (!base) return url;375    var schemeMatch = base.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:)\/\/([^\/]*)(\/[^?#]*)?/);376    if (!schemeMatch) return url;377    var origin = schemeMatch[1] + "//" + schemeMatch[2];378    var combined;379    if (url.charAt(0) === "/") combined = origin + url;380    else {381      var path = schemeMatch[3] || "/";382      path = path.replace(/\/[^\/]*$/, "/");383      combined = origin + path + url;384    }385    var mm = combined.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\/]*)(\/.*)?$/);386    if (!mm) return combined;387    var head = mm[1], rest = mm[2] || "/";388    var query = "";389    var qi = rest.search(/[?#]/);390    if (qi !== -1) { query = rest.slice(qi); rest = rest.slice(0, qi); }391    var segs = rest.split("/"), stack = [];392    for (var i = 0; i < segs.length; i++) { if (segs[i] === "..") stack.pop(); else if (segs[i] !== ".") stack.push(segs[i]); }393    return head + stack.join("/") + query;394  }395396  // ---------- Element / Elements ----------397  function Element(node, baseUri) { this._node = node; this._base = baseUri || ""; }398  Element.prototype.attr = function (name) {399    name = String(name);400    if (name.indexOf("abs:") === 0) return resolveUrl(this._base, this._node.attrs[name.slice(4).toLowerCase()] || "");401    var v = this._node.attrs[name.toLowerCase()];402    return v == null ? "" : v;403  };404  Element.prototype.hasAttr = function (name) { return this._node.attrs.hasOwnProperty(String(name).toLowerCase()); };405  Element.prototype.hasClass = function (cls) { return hasClass(this._node, String(cls)); };406  Element.prototype.select = function (sel) { return new Elements(selectAll(this._node, String(sel)), this._base); };407  Element.prototype.selectFirst = function (sel) { var r = selectAll(this._node, String(sel)); return r.length ? new Element(r[0], this._base) : null; };408  Element.prototype.getElementById = function (id) { var r = selectAll(this._node, "#" + id); return r.length ? new Element(r[0], this._base) : null; };409  Element.prototype.getElementsByTag = function (tag) { return new Elements(selectAll(this._node, String(tag)), this._base); };410  Element.prototype.getElementsByClass = function (cls) { return new Elements(selectAll(this._node, "." + cls), this._base); };411  Element.prototype.querySelector = function (sel) { return this.selectFirst(sel); };412  Element.prototype.querySelectorAll = function (sel) { return this.select(sel); };413  Element.prototype.getElementsByTagName = function (tag) { return this.getElementsByTag(tag); };414  Element.prototype.getElementsByName = function (name) { return new Elements(selectAll(this._node, "[name=" + name + "]"), this._base); };415  Element.prototype.children = function () { return new Elements(elementChildren(this._node), this._base); };416  Element.prototype.parent = function () { return this._node.parent && this._node.parent.tag !== "#root" ? new Element(this._node.parent, this._base) : null; };417  Element.prototype.nextElementSibling = function () {418    var sibs = this._node.parent ? this._node.parent.children : [];419    var found = false;420    for (var i = 0; i < sibs.length; i++) { if (found && sibs[i].type === "element") return new Element(sibs[i], this._base); if (sibs[i] === this._node) found = true; }421    return null;422  };423  Element.prototype.previousElementSibling = function () { var p = prevElement(this._node); return p ? new Element(p, this._base) : null; };424  Element.prototype.val = function () { return this._node.tag === "textarea" ? nodeText(this._node, false) : this.attr("value"); };425  Element.prototype.data = function () {426    var out = [];427    for (var i = 0; i < this._node.children.length; i++) if (this._node.children[i].type === "text") out.push(this._node.children[i].textContent);428    return out.join("");429  };430  Element.prototype.tagName = function () { return this._node.tag; };431  Element.prototype.toString = function () { return serialize(this._node, true); };432433  function defineTextProps(proto) {434    Object.defineProperty(proto, "text", { get: function () { return callableString(nodeText(this._node)); } });435    Object.defineProperty(proto, "ownText", { get: function () { return callableString(ownText(this._node)); } });436    Object.defineProperty(proto, "html", { get: function () { return callableString(serialize(this._node, false)); } });437    Object.defineProperty(proto, "outerHtml", { get: function () { return callableString(serialize(this._node, true)); } });438    Object.defineProperty(proto, "wholeText", { get: function () { return callableString(nodeText(this._node, false)); } });439    Object.defineProperty(proto, "id", { get: function () { return this._node.attrs.id || ""; } });440    Object.defineProperty(proto, "className", { get: function () { return this._node.attrs["class"] || ""; } });441    Object.defineProperty(proto, "tag", { get: function () { return this._node.tag; } });442    Object.defineProperty(proto, "baseUri", { get: function () { return this._base; } });443    Object.defineProperty(proto, "getHref", { get: function () { return this.attr("href"); } });444    Object.defineProperty(proto, "getSrc", { get: function () { return this.attr("src"); } });445  }446  defineTextProps(Element.prototype);447  // Hybrid string behavior: extensions that treat selector results as raw HTML448  // strings (regex/.match/.replace/.indexOf/...) operate on the element's outer449  // HTML, while element methods (.attr/.text/.select) also work on the same value.450  var EL_STRING_METHODS = ["match","matchAll","replace","replaceAll","split","indexOf","lastIndexOf","includes","startsWith","endsWith","substring","substr","slice","toLowerCase","toUpperCase","trim","trimStart","trimEnd","charAt","charCodeAt","codePointAt","search","concat","padStart","padEnd","normalize","repeat"];451  EL_STRING_METHODS.forEach(function (name) {452    if (typeof String.prototype[name] === "function" && !Element.prototype[name]) {453      Element.prototype[name] = function () { var s = serialize(this._node, true); return s[name].apply(s, arguments); };454    }455  });456  Element.prototype.valueOf = function () { return serialize(this._node, true); };457  Element.prototype.toJSON = function () { return serialize(this._node, true); };458  try { Object.defineProperty(Element.prototype, "length", { get: function () { return serialize(this._node, true).length; } }); } catch (e) {}459460  function Elements(nodes, baseUri) {461    this._base = baseUri || "";462    this._els = [];463    for (var i = 0; i < nodes.length; i++) this._els.push(nodes[i] instanceof Element ? nodes[i] : new Element(nodes[i], baseUri));464    for (var j = 0; j < this._els.length; j++) this[j] = this._els[j];465    this.length = this._els.length;466  }467  if (typeof Symbol !== "undefined" && Symbol.iterator) {468    Elements.prototype[Symbol.iterator] = function () {469      var index = 0;470      var values = this._els;471      return {472        next: function () {473          return index < values.length474            ? { value: values[index++], done: false }475            : { value: undefined, done: true };476        }477      };478    };479  }480  Elements.prototype.get = function (i) { return this._els[i]; };481  Elements.prototype.eq = function (i) { return new Elements(this._els[i] ? [this._els[i]._node] : [], this._base); };482  Elements.prototype.first = function () { return this._els.length ? this._els[0] : null; };483  Elements.prototype.last = function () { return this._els.length ? this._els[this._els.length - 1] : null; };484  Elements.prototype.size = function () { return this._els.length; };485  Elements.prototype.isEmpty = function () { return this._els.length === 0; };486  Elements.prototype.forEach = function (fn, thisArg) { for (var i = 0; i < this._els.length; i++) fn.call(thisArg, this._els[i], i, this); };487  Elements.prototype.map = function (fn, thisArg) { var out = []; for (var i = 0; i < this._els.length; i++) out.push(fn.call(thisArg, this._els[i], i, this)); return out; };488  Elements.prototype.filter = function (fn, thisArg) { var out = []; for (var i = 0; i < this._els.length; i++) if (fn.call(thisArg, this._els[i], i, this)) out.push(this._els[i]._node); return new Elements(out, this._base); };489  Elements.prototype.slice = function (a, b) { return new Elements(this._els.slice(a, b).map(function (e) { return e._node; }), this._base); };490  Elements.prototype.select = function (sel) { var out = []; for (var i = 0; i < this._els.length; i++) { var r = selectAll(this._els[i]._node, String(sel)); for (var j = 0; j < r.length; j++) out.push(r[j]); } return new Elements(out, this._base); };491  Elements.prototype.attr = function (name) { for (var i = 0; i < this._els.length; i++) { var v = this._els[i].attr(name); if (v) return v; } return ""; };492  Elements.prototype.hasClass = function (c) { for (var i = 0; i < this._els.length; i++) if (this._els[i].hasClass(c)) return true; return false; };493  Elements.prototype.text = function () { var out = []; for (var i = 0; i < this._els.length; i++) out.push(String(this._els[i].text)); return out.join(" ").replace(/\s+/g, " ").trim(); };494  Elements.prototype.toArray = function () { return this._els.slice(); };495  Elements.prototype.remove = function () { return this; };496  Elements.prototype.join = function (sep) { var out = []; for (var i = 0; i < this._els.length; i++) out.push(String(this._els[i])); return out.join(sep === undefined ? "," : sep); };497  Elements.prototype.indexOf = function (el) { for (var i = 0; i < this._els.length; i++) if (this._els[i] === el || this._els[i]._node === (el && el._node)) return i; return -1; };498  Elements.prototype.some = function (fn, thisArg) { for (var i = 0; i < this._els.length; i++) if (fn.call(thisArg, this._els[i], i, this)) return true; return false; };499  Elements.prototype.every = function (fn, thisArg) { for (var i = 0; i < this._els.length; i++) if (!fn.call(thisArg, this._els[i], i, this)) return false; return true; };500  Elements.prototype.reduce = function (fn, acc) { for (var i = 0; i < this._els.length; i++) acc = fn(acc, this._els[i], i, this); return acc; };501  Elements.prototype.reverse = function () { return new Elements(this._els.slice().reverse().map(function (e) { return e._node; }), this._base); };502  Elements.prototype.concat = function (other) { var a = this.toArray(); var b = other && other.toArray ? other.toArray() : (other || []); return new Elements(a.concat(b).map(function (e) { return e._node; }), this._base); };503  Elements.prototype.toString = function () { return this.text(); };504505  function Document(html, baseUri) { Element.call(this, parse(html), baseUri || ""); }506  Document.prototype = Object.create(Element.prototype);507  Document.prototype.constructor = Document;508  Document.prototype.title = function () { var t = this.selectFirst("title"); return t ? String(t.text) : ""; };509  Document.prototype.body = function () { return this.selectFirst("body") || this; };510  Object.defineProperty(Document.prototype, "location", { get: function () { return this._base; } });511512  function querySelectorAll(html, selector, baseUri) {513    if (html instanceof Element) return html.select(selector);514    return new Elements(selectAll(parse(html), String(selector)), baseUri || "");515  }516  function querySelector(html, selector, baseUri) {517    if (html instanceof Element) return html.selectFirst(selector);518    var r = selectAll(parse(html), String(selector));519    return r.length ? new Element(r[0], baseUri || "") : null;520  }521522  var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";523  function btoa(input) {524    input = String(input); var out = "", i = 0;525    while (i < input.length) {526      var c1 = input.charCodeAt(i++), c2 = input.charCodeAt(i++), c3 = input.charCodeAt(i++);527      var e1 = c1 >> 2, e2 = ((c1 & 3) << 4) | (c2 >> 4), e3 = ((c2 & 15) << 2) | (c3 >> 6), e4 = c3 & 63;528      if (isNaN(c2)) { e3 = e4 = 64; } else if (isNaN(c3)) { e4 = 64; }529      out += B64.charAt(e1) + B64.charAt(e2) + (e3 === 64 ? "=" : B64.charAt(e3)) + (e4 === 64 ? "=" : B64.charAt(e4));530    }531    return out;532  }533  function atob(input) {534    input = String(input).replace(/[^A-Za-z0-9+/=]/g, ""); var out = "", i = 0;535    while (i < input.length) {536      var d1 = B64.indexOf(input.charAt(i++)), d2 = B64.indexOf(input.charAt(i++));537      var ch3 = input.charAt(i++), ch4 = input.charAt(i++);538      var d3 = (ch3 === "=" || ch3 === "") ? 64 : B64.indexOf(ch3);539      var d4 = (ch4 === "=" || ch4 === "") ? 64 : B64.indexOf(ch4);540      if (d1 < 0 || d2 < 0) break;541      var c1 = (d1 << 2) | (d2 >> 4), c2 = ((d2 & 15) << 4) | ((d3 & 63) >> 2), c3 = ((d3 & 3) << 6) | (d4 & 63);542      out += String.fromCharCode(c1);543      if (d3 !== 64) out += String.fromCharCode(c2);544      if (d4 !== 64) out += String.fromCharCode(c3);545    }546    return out;547  }548549  return { Document: Document, Element: Element, Elements: Elements, querySelector: querySelector, querySelectorAll: querySelectorAll, atob: atob, btoa: btoa, parse: parse, _selectAll: selectAll };550})();551552553var Document = YokanDom.Document;554var Element = YokanDom.Element;555var Elements = YokanDom.Elements;556var atob = YokanDom.atob;557var btoa = YokanDom.btoa;558function querySelector(html, selector, baseUri) { return YokanDom.querySelector(html, selector, baseUri); }559function querySelectorAll(html, selector, baseUri) { return YokanDom.querySelectorAll(html, selector, baseUri); }560561"""562

Search chapters, reference and source filenames.