From cc263991ea749029b82f46f1369e7b1e16620376 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Fri, 30 Oct 2020 10:47:19 -0300 Subject: lazy load images in commentary --- upd8.js | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 2 deletions(-) (limited to 'upd8.js') diff --git a/upd8.js b/upd8.js index 74d6aba4..522fb27b 100644 --- a/upd8.js +++ b/upd8.js @@ -363,6 +363,57 @@ function transformInline(text) { }); } +function parseAttributes(string) { + const attributes = Object.create(null); + const skipWhitespace = i => { + const ws = /\s/; + if (ws.test(string[i])) { + const match = string.slice(i).match(/[^\s]/); + if (match) { + return i + match.index; + } else { + return string.length; + } + } else { + return i; + } + }; + + for (let i = 0; i < string.length;) { + i = skipWhitespace(i); + const aStart = i; + const aEnd = i + string.slice(i).match(/[\s=]|$/).index; + const attribute = string.slice(aStart, aEnd); + i = skipWhitespace(aEnd); + if (string[i] === '=') { + i = skipWhitespace(i + 1); + let end, endOffset; + if (string[i] === '"' || string[i] === "'") { + end = string[i]; + endOffset = 1; + i++; + } else { + end = '\\s'; + endOffset = 0; + } + const vStart = i; + const vEnd = i + string.slice(i).match(new RegExp(`${end}|$`)).index; + const value = string.slice(vStart, vEnd); + i = vEnd + endOffset; + attributes[attribute] = value; + } else { + attributes[attribute] = attribute; + } + } + return Object.fromEntries(Object.entries(attributes).map(([ key, val ]) => [ + key, + val === 'true' ? true : + val === 'false' ? false : + val === key ? true : + val + ])); +} + function transformMultiline(text, treatAsDocument=false) { // Heck yes, HTML magics. @@ -376,7 +427,11 @@ function transformMultiline(text, treatAsDocument=false) { let inList = false; for (let line of text.split(/\r|\n|\r\n/)) { - line = line.replace(//g, '$&'); + line = line.replace(//g, (match, attributes) => img({ + lazy: true, + link: true, + ...parseAttributes(attributes) + })); if (line.startsWith('- ')) { if (!inList) { outLines.push('