(() => { const sourceURL = new URL(document.currentScript.src); const params = sourceURL.searchParams; const target = new URL(params.get("target")); const type = params.get("type") || 'code'; const lineSplit = target.hash.split("-"); const startLine = target.hash !== "" && lineSplit[0].replace("#L", "") || -1; const endLine = target.hash !== "" && lineSplit.length > 1 && lineSplit[1].replace("L", "") || startLine; const pathSplit = target.pathname.split("/"); const user = pathSplit[1]; const repository = pathSplit[2]; const branch = pathSplit[4]; const filePath = pathSplit.slice(5, pathSplit.length).join("/"); const directoryPath = pathSplit.slice(5, pathSplit.length - 1).join("/"); const fileExtension = filePath.split('.').length > 1 ? filePath.split('.').pop() : 'txt'; const fileURL = target.href; const serviceProvider = new URL("./", sourceURL.href).href; const rawFileURL = `https://raw.githubusercontent.com/${user}/${repository}/${branch}/${filePath}`; const rawDirectoryURL = `https://raw.githubusercontent.com/${user}/${repository}/${branch}/${directoryPath}/`; const showFullPath = true; const containerId = Math.random().toString(36).substring(2); document.currentScript.insertAdjacentHTML( 'afterend', `
`); const promises = []; const fetchFile = fetch(rawFileURL).then((response) => { if (response.ok) { return response.text(); } return Promise.reject(`${response.status}\nFailed to download ${rawFileURL}`); }); promises.push(fetchFile); Promise.allSettled(promises).then((result) => { const targetDiv = document.getElementById(containerId); const fetchSuccess = result[0].status === "fulfilled"; if (type === 'code') { let codeText; if (fetchSuccess) { codeText = result[0].value; if (codeText[codeText.length - 1] === "\n") { // First remove the ending newline codeText = codeText.slice(0, -1); } let codeTextSplit = codeText.split("\n"); if (startLine > 0) { codeTextSplit = codeTextSplit.slice(startLine - 1, endLine); } // Strip leading whitespace as otherwise we get pointless whitespace/indentation // for code snippets from the middle of functions (#22) while (true) { const firstChars = codeTextSplit.filter(s => s.length > 0).map(s => s[0]); if (new Set(firstChars).size === 1 && [' ', '\t'].includes(firstChars[0])) { // If all the lines begin with ' ' or '\t', strip the first char codeTextSplit = codeTextSplit.map(s => s.slice(1)); } else { break; } } codeText = codeTextSplit.join("\n"); // Then add the newline back codeText = codeText + "\n"; } else { codeText = result[0].reason; } let codeTag = targetDiv.querySelector('.highlightjs'); codeTag.textContent = codeText; codeTag.dataset.startLine = ((startLine > 0 && fetchSuccess) ? Number.parseInt(startLine, 10) : 1).toString(); delete codeTag.dataset.highlighted; targetDiv.querySelector('[data-code] code').textContent = codeText; window.initHljs(codeTag); } }); })();