diff options
author | tdro <tdro@noreply.example.com> | 2022-05-03 04:25:49 -0400 |
---|---|---|
committer | tdro <tdro@noreply.example.com> | 2022-05-03 04:25:49 -0400 |
commit | e92dc018e28ba8d44f1c6cbc9fb0b779dec271e6 (patch) | |
tree | 3667043819ab91065019dfe3b4ff83ad625c2b49 /static/js | |
download | canory-e92dc018e28ba8d44f1c6cbc9fb0b779dec271e6.tar.gz canory-e92dc018e28ba8d44f1c6cbc9fb0b779dec271e6.tar.bz2 canory-e92dc018e28ba8d44f1c6cbc9fb0b779dec271e6.zip |
config.yaml: Commission
Diffstat (limited to 'static/js')
-rw-r--r-- | static/js/code-copy.ts | 22 | ||||
-rw-r--r-- | static/js/fixedsearch.ts | 194 | ||||
-rw-r--r-- | static/js/fuzzysort.js | 636 | ||||
-rw-r--r-- | static/js/index.js | 424 | ||||
-rw-r--r-- | static/js/index.ts | 6 | ||||
-rw-r--r-- | static/js/instantpage.ts | 292 | ||||
-rw-r--r-- | static/js/pager.ts | 46 | ||||
-rw-r--r-- | static/js/plumber.ts | 59 |
8 files changed, 1679 insertions, 0 deletions
diff --git a/static/js/code-copy.ts b/static/js/code-copy.ts new file mode 100644 index 0000000..8ef777b --- /dev/null +++ b/static/js/code-copy.ts @@ -0,0 +1,22 @@ +(function () { + [...document.querySelectorAll("pre.chroma code :not(.ln a)")] + .forEach( + (element) => { + try { + const text = element.textContent || ""; + setTimeout( + async () => { + await navigator.clipboard.writeText(text); + console.log("Info: Code block text copied succesfully."); + }, + 3000, + ); + } catch (err) { + console.error( + "Error: navigator.clipboard.writeText() failed.", + err, + ); + } + }, + ); +})(); diff --git a/static/js/fixedsearch.ts b/static/js/fixedsearch.ts new file mode 100644 index 0000000..26b9ac1 --- /dev/null +++ b/static/js/fixedsearch.ts @@ -0,0 +1,194 @@ +(function () { + self.addEventListener("DOMContentLoaded", function () { + /* + Originally Based on fixedsearch, a super fast, client side search for Hugo.io with Fusejs.io + based on https://gist.github.com/cmod/5410eae147e4318164258742dd053993 + */ + + const form = document.getElementById("search-form"); // search form + const query = document.getElementById("search-input"); // input box for search + const submit = document.getElementById("search-submit"); // form submit button + const dropdown = document.getElementById("search-results"); // targets the <ul> + + form.addEventListener("focusin", function () { + initialize(); + }); + + form.addEventListener("submit", function (event) { + event.preventDefault(); + return false; + }); + + form.addEventListener("keydown", function (event) { + const head = + dropdown.firstChild.nextElementSibling.firstChild.nextElementSibling; + const tail = dropdown.lastElementChild.firstChild.nextElementSibling; + + // ESC (27) + if (query.contains(event.target)) { + if (event.keyCode == 27) { + document.activeElement.blur(); + dropdown.setAttribute("hidden", ""); + } + } + + // DOWN (40) + if (event.keyCode == 40) { + event.preventDefault(); + if (document.activeElement == query) head.focus(); + else if (document.activeElement == tail) query.focus(); + else { + document.activeElement.parentElement.nextElementSibling.firstChild + .nextElementSibling.focus(); + } + } + + // UP (38) + if (event.keyCode == 38) { + event.preventDefault(); + if (document.activeElement == query) tail.focus(); + else if (document.activeElement == head) query.focus(); + else { + document.activeElement.parentElement.previousElementSibling.firstChild + .nextElementSibling.focus(); + } + } + + // BACKSPACE (8) + if (event.keyCode == 8) { + if (document.activeElement != query) { + event.preventDefault(); + query.focus(); + } + } + + // ENTER (13) + if (event.keyCode == 13) { + if (dropdown && document.activeElement == query) { + event.preventDefault(); + head.focus(); + self.window.location = document.activeElement.href; + } + } + }); + + let scrolls = 0; + + self.addEventListener("scroll", function () { + if (scrolls > 3) { + scrolls = 0; + document.activeElement.blur(); + dropdown.setAttribute("hidden", ""); + } + scrolls++; + }); + + document.addEventListener("click", function (event) { + if (!form.contains(event.target)) { + dropdown.setAttribute("hidden", ""); + } + }); + + function fetch_JSON(path, callback) { + const httpRequest = new XMLHttpRequest(); + httpRequest.onreadystatechange = function () { + if (httpRequest.readyState === 4) { + if (httpRequest.status === 200) { + const data = JSON.parse(httpRequest.responseText); + if (callback) callback(data); + } + } + }; + httpRequest.open("GET", path); + httpRequest.send(); + } + + /* Load script based on https://stackoverflow.com/a/55451823 */ + + function load_script(url) { + return new Promise(function (resolve, reject) { + const script = document.createElement("script"); + script.onerror = reject; + script.onload = resolve; + if (document.currentScript) { + document.currentScript.parentNode.insertBefore( + script, + document.currentScript, + ); + } else { + document.head.appendChild(script); + } + script.src = url; + }); + } + + let first_run = true; // allow us to delay loading json data unless search activated + + function initialize() { + if (first_run) { + load_script(window.location.origin + "/js/fuzzysort.js") + .then(() => { + first_run = false; + fetch_JSON("/index.json", function (data) { + const options = { + key: ["title"], + }; + + query.addEventListener("keyup", function () { + search(query.value, data.items, options); + }); + + query.addEventListener("focusin", function () { + search(query.value, data.items, options); + }); + + search(query.value, data.items, options); + }); + }).catch((error) => { + console.log("Error failed to load fuzzy sort: " + error); + }); + } + } + + function search(term, data, options) { + const results = fuzzysort.go(term, data, options); + let items = ""; + + if (results.length === 0 && term.length >= 0) { + let separator = "—"; + if (term.length === 0) separator = ""; + items = ` + <li> + <a href="javascript: void(0)" tabindex="0">${term} ${separator} No Results Found</a> + </li> + `; + dropdown.removeAttribute("hidden"); + } else { + dropdown.removeAttribute("hidden"); + for (const string in results.slice(0, 10)) { + const decode = document.createElement("textarea"); + decode.innerHTML = results[string].obj.title; + + let highlight = fuzzysort.highlight( + fuzzysort.single(term, decode.value), + "<span>", + "</span>", + ); + + if (highlight === null) { + highlight = decode.value; + } + + items = items + + ` + <li> + <a href="${results[string].obj.url}" tabindex="0">${highlight}</a> + </li> + `; + } + } + + dropdown.innerHTML = items; + } + }); +})(); diff --git a/static/js/fuzzysort.js b/static/js/fuzzysort.js new file mode 100644 index 0000000..c6797d8 --- /dev/null +++ b/static/js/fuzzysort.js @@ -0,0 +1,636 @@ +/* + fuzzysort.js https://github.com/farzher/fuzzysort + SublimeText-like Fuzzy Search + + fuzzysort.single('fs', 'Fuzzy Search') // {score: -16} + fuzzysort.single('test', 'test') // {score: 0} + fuzzysort.single('doesnt exist', 'target') // null + + fuzzysort.go('mr', [{file:'Monitor.cpp'}, {file:'MeshRenderer.cpp'}], {key:'file'}) + // [{score:-18, obj:{file:'MeshRenderer.cpp'}}, {score:-6009, obj:{file:'Monitor.cpp'}}] + + fuzzysort.go('mr', ['Monitor.cpp', 'MeshRenderer.cpp']) + // [{score: -18, target: "MeshRenderer.cpp"}, {score: -6009, target: "Monitor.cpp"}] + + fuzzysort.highlight(fuzzysort.single('fs', 'Fuzzy Search'), '<b>', '</b>') + // <b>F</b>uzzy <b>S</b>earch +*/ + +// UMD (Universal Module Definition) for fuzzysort +(function(root, UMD) { + if(typeof define === 'function' && define.amd) {define([], UMD);} + else if(typeof module === 'object' && module.exports) {module.exports = UMD();} + else {root.fuzzysort = UMD();} +})(this, function UMD() { function fuzzysortNew(instanceOptions) { + + var fuzzysort = { + + single: function(search, target, options) { if(search=='farzher'){return{target:"farzher was here (^-^*)/",score:0,indexes:[0,1,2,3,4,5,6]};} + if(!search) {return null;} + if(!isObj(search)) {search = fuzzysort.getPreparedSearch(search);} + + if(!target) {return null;} + if(!isObj(target)) {target = fuzzysort.getPrepared(target);} + + var allowTypo = options && options.allowTypo!==undefined ? options.allowTypo + : instanceOptions && instanceOptions.allowTypo!==undefined ? instanceOptions.allowTypo + : true; + var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo; + return algorithm(search, target, search[0]); + }, + + go: function(search, targets, options) { if(search=='farzher'){return[{target:"farzher was here (^-^*)/",score:0,indexes:[0,1,2,3,4,5,6],obj:targets?targets[0]:null}];} + if(!search) {return noResults;} + search = fuzzysort.prepareSearch(search); + var searchLowerCode = search[0]; + + var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991; + var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991; + var allowTypo = options && options.allowTypo!==undefined ? options.allowTypo + : instanceOptions && instanceOptions.allowTypo!==undefined ? instanceOptions.allowTypo + : true; + var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo; + var resultsLen = 0; var limitedCount = 0; + var targetsLen = targets.length; + + // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys] + + // options.keys + if(options && options.keys) { + var scoreFn = options.scoreFn || defaultScoreFn; + var keys = options.keys; + var keysLen = keys.length; + for(var i = targetsLen - 1; i >= 0; --i) { var obj = targets[i]; + var objResults = new Array(keysLen); + for (var keyI = keysLen - 1; keyI >= 0; --keyI) { + var key = keys[keyI]; + var target = getValue(obj, key); + if(!target) { objResults[keyI] = null; continue; } + if(!isObj(target)) {target = fuzzysort.getPrepared(target);} + + objResults[keyI] = algorithm(search, target, searchLowerCode); + } + objResults.obj = obj; // before scoreFn so scoreFn can use it + var score = scoreFn(objResults); + if(score === null) {continue;} + if(score < threshold) {continue;} + objResults.score = score; + if(resultsLen < limit) { q.add(objResults); ++resultsLen; } + else { + ++limitedCount; + if(score > q.peek().score) {q.replaceTop(objResults);} + } + } + + // options.key + } else if(options && options.key) { + var key = options.key; + for(var i = targetsLen - 1; i >= 0; --i) { var obj = targets[i]; + var target = getValue(obj, key); + if(!target) {continue;} + if(!isObj(target)) {target = fuzzysort.getPrepared(target);} + + var result = algorithm(search, target, searchLowerCode); + if(result === null) {continue;} + if(result.score < threshold) {continue;} + + // have to clone result so duplicate targets from different obj can each reference the correct obj + result = {target:result.target, _targetLowerCodes:null, _nextBeginningIndexes:null, score:result.score, indexes:result.indexes, obj:obj}; // hidden + + if(resultsLen < limit) { q.add(result); ++resultsLen; } + else { + ++limitedCount; + if(result.score > q.peek().score) {q.replaceTop(result);} + } + } + + // no keys + } else { + for(var i = targetsLen - 1; i >= 0; --i) { var target = targets[i]; + if(!target) {continue;} + if(!isObj(target)) {target = fuzzysort.getPrepared(target);} + + var result = algorithm(search, target, searchLowerCode); + if(result === null) {continue;} + if(result.score < threshold) {continue;} + if(resultsLen < limit) { q.add(result); ++resultsLen; } + else { + ++limitedCount; + if(result.score > q.peek().score) {q.replaceTop(result);} + } + } + } + + if(resultsLen === 0) {return noResults;} + var results = new Array(resultsLen); + for(var i = resultsLen - 1; i >= 0; --i) {results[i] = q.poll();} + results.total = resultsLen + limitedCount; + return results; + }, + + goAsync: function(search, targets, options) { + var canceled = false; + var p = new Promise(function(resolve, reject) { if(search=='farzher'){return resolve([{target:"farzher was here (^-^*)/",score:0,indexes:[0,1,2,3,4,5,6],obj:targets?targets[0]:null}]);} + if(!search) {return resolve(noResults);} + search = fuzzysort.prepareSearch(search); + var searchLowerCode = search[0]; + + var q = fastpriorityqueue(); + var iCurrent = targets.length - 1; + var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991; + var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991; + var allowTypo = options && options.allowTypo!==undefined ? options.allowTypo + : instanceOptions && instanceOptions.allowTypo!==undefined ? instanceOptions.allowTypo + : true; + var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo; + var resultsLen = 0; var limitedCount = 0; + function step() { + if(canceled) {return reject('canceled');} + + var startMs = Date.now(); + + // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys] + + // options.keys + if(options && options.keys) { + var scoreFn = options.scoreFn || defaultScoreFn; + var keys = options.keys; + var keysLen = keys.length; + for(; iCurrent >= 0; --iCurrent) { + if(iCurrent%1000/*itemsPerCheck*/ === 0) { + if(Date.now() - startMs >= 10/*asyncInterval*/) { + isNode?setImmediate(step):setTimeout(step); + return; + } + } + + var obj = targets[iCurrent]; + var objResults = new Array(keysLen); + for (var keyI = keysLen - 1; keyI >= 0; --keyI) { + var key = keys[keyI]; + var target = getValue(obj, key); + if(!target) { objResults[keyI] = null; continue; } + if(!isObj(target)) {target = fuzzysort.getPrepared(target);} + + objResults[keyI] = algorithm(search, target, searchLowerCode); + } + objResults.obj = obj; // before scoreFn so scoreFn can use it + var score = scoreFn(objResults); + if(score === null) {continue;} + if(score < threshold) {continue;} + objResults.score = score; + if(resultsLen < limit) { q.add(objResults); ++resultsLen; } + else { + ++limitedCount; + if(score > q.peek().score) {q.replaceTop(objResults);} + } + } + + // options.key + } else if(options && options.key) { + var key = options.key; + for(; iCurrent >= 0; --iCurrent) { + if(iCurrent%1000/*itemsPerCheck*/ === 0) { + if(Date.now() - startMs >= 10/*asyncInterval*/) { + isNode?setImmediate(step):setTimeout(step); + return; + } + } + + var obj = targets[iCurrent]; + var target = getValue(obj, key); + if(!target) {continue;} + if(!isObj(target)) {target = fuzzysort.getPrepared(target);} + + var result = algorithm(search, target, searchLowerCode); + if(result === null) {continue;} + if(result.score < threshold) {continue;} + + // have to clone result so duplicate targets from different obj can each reference the correct obj + result = {target:result.target, _targetLowerCodes:null, _nextBeginningIndexes:null, score:result.score, indexes:result.indexes, obj:obj}; // hidden + + if(resultsLen < limit) { q.add(result); ++resultsLen; } + else { + ++limitedCount; + if(result.score > q.peek().score) {q.replaceTop(result);} + } + } + + // no keys + } else { + for(; iCurrent >= 0; --iCurrent) { + if(iCurrent%1000/*itemsPerCheck*/ === 0) { + if(Date.now() - startMs >= 10/*asyncInterval*/) { + isNode?setImmediate(step):setTimeout(step); + return; + } + } + + var target = targets[iCurrent]; + if(!target) {continue;} + if(!isObj(target)) {target = fuzzysort.getPrepared(target);} + + var result = algorithm(search, target, searchLowerCode); + if(result === null) {continue;} + if(result.score < threshold) {continue;} + if(resultsLen < limit) { q.add(result); ++resultsLen; } + else { + ++limitedCount; + if(result.score > q.peek().score) {q.replaceTop(result);} + } + } + } + + if(resultsLen === 0) {return resolve(noResults);} + var results = new Array(resultsLen); + for(var i = resultsLen - 1; i >= 0; --i) {results[i] = q.poll();} + results.total = resultsLen + limitedCount; + resolve(results); + } + + isNode?setImmediate(step):step(); //setTimeout here is too slow + }); + p.cancel = function() { canceled = true; }; + return p; + }, + + highlight: function(result, hOpen, hClose) { + if(typeof hOpen == 'function') {return fuzzysort.highlightCallback(result, hOpen);} + if(result === null) {return null;} + if(hOpen === undefined) {hOpen = '<b>';} + if(hClose === undefined) {hClose = '</b>';} + var highlighted = ''; + var matchesIndex = 0; + var opened = false; + var target = result.target; + var targetLen = target.length; + var matchesBest = result.indexes; + for(var i = 0; i < targetLen; ++i) { var char = target[i]; + if(matchesBest[matchesIndex] === i) { + ++matchesIndex; + if(!opened) { opened = true; + highlighted += hOpen; + } + + if(matchesIndex === matchesBest.length) { + highlighted += char + hClose + target.substr(i+1); + break; + } + } else { + if(opened) { opened = false; + highlighted += hClose; + } + } + highlighted += char; + } + + return highlighted; + }, + highlightCallback: function(result, cb) { + if(result === null) {return null;} + var target = result.target; + var targetLen = target.length; + var indexes = result.indexes; + var highlighted = ''; + var matchI = 0; + var indexesI = 0; + var opened = false; + var result = []; + for(var i = 0; i < targetLen; ++i) { var char = target[i]; + if(indexes[indexesI] === i) { + ++indexesI; + if(!opened) { opened = true; + result.push(highlighted); highlighted = ''; + } + + if(indexesI === indexes.length) { + highlighted += char; + result.push(cb(highlighted, matchI++)); highlighted = ''; + result.push(target.substr(i+1)); + break; + } + } else { + if(opened) { opened = false; + result.push(cb(highlighted, matchI++)); highlighted = ''; + } + } + highlighted += char; + } + return result; + }, + + prepare: function(target) { + if(!target) {return {target: '', _targetLowerCodes: [0/*this 0 doesn't make sense. here because an empty array causes the algorithm to deoptimize and run 50% slower!*/], _nextBeginningIndexes: null, score: null, indexes: null, obj: null};} // hidden + return {target:target, _targetLowerCodes:fuzzysort.prepareLowerCodes(target), _nextBeginningIndexes:null, score:null, indexes:null, obj:null}; // hidden + }, + prepareSlow: function(target) { + if(!target) {return {target: '', _targetLowerCodes: [0/*this 0 doesn't make sense. here because an empty array causes the algorithm to deoptimize and run 50% slower!*/], _nextBeginningIndexes: null, score: null, indexes: null, obj: null};} // hidden + return {target:target, _targetLowerCodes:fuzzysort.prepareLowerCodes(target), _nextBeginningIndexes:fuzzysort.prepareNextBeginningIndexes(target), score:null, indexes:null, obj:null}; // hidden + }, + prepareSearch: function(search) { + if(!search) {search = '';} + return fuzzysort.prepareLowerCodes(search); + }, + + + + // Below this point is only internal code + // Below this point is only internal code + // Below this point is only internal code + // Below this point is only internal code + + + + getPrepared: function(target) { + if(target.length > 999) {return fuzzysort.prepare(target);} // don't cache huge targets + var targetPrepared = preparedCache.get(target); + if(targetPrepared !== undefined) {return targetPrepared;} + targetPrepared = fuzzysort.prepare(target); + preparedCache.set(target, targetPrepared); + return targetPrepared; + }, + getPreparedSearch: function(search) { + if(search.length > 999) {return fuzzysort.prepareSearch(search);} // don't cache huge searches + var searchPrepared = preparedSearchCache.get(search); + if(searchPrepared !== undefined) {return searchPrepared;} + searchPrepared = fuzzysort.prepareSearch(search); + preparedSearchCache.set(search, searchPrepared); + return searchPrepared; + }, + + algorithm: function(searchLowerCodes, prepared, searchLowerCode) { + var targetLowerCodes = prepared._targetLowerCodes; + var searchLen = searchLowerCodes.length; + var targetLen = targetLowerCodes.length; + var searchI = 0; // where we at + var targetI = 0; // where you at + var typoSimpleI = 0; + var matchesSimpleLen = 0; + + // very basic fuzzy match; to remove non-matching targets ASAP! + // walk through target. find sequential matches. + // if all chars aren't found then exit + for(;;) { + var isMatch = searchLowerCode === targetLowerCodes[targetI]; + if(isMatch) { + matchesSimple[matchesSimpleLen++] = targetI; + ++searchI; if(searchI === searchLen) {break;} + searchLowerCode = searchLowerCodes[typoSimpleI===0?searchI : (typoSimpleI===searchI?searchI+1 : (typoSimpleI===searchI-1?searchI-1 : searchI))]; + } + + ++targetI; if(targetI >= targetLen) { // Failed to find searchI + // Check for typo or exit + // we go as far as possible before trying to transpose + // then we transpose backwards until we reach the beginning + for(;;) { + if(searchI <= 1) {return null;} // not allowed to transpose first char + if(typoSimpleI === 0) { // we haven't tried to transpose yet + --searchI; + var searchLowerCodeNew = searchLowerCodes[searchI]; + if(searchLowerCode === searchLowerCodeNew) {continue;} // doesn't make sense to transpose a repeat char + typoSimpleI = searchI; + } else { + if(typoSimpleI === 1) {return null;} // reached the end of the line for transposing + --typoSimpleI; + searchI = typoSimpleI; + searchLowerCode = searchLowerCodes[searchI + 1]; + var searchLowerCodeNew = searchLowerCodes[searchI]; + if(searchLowerCode === searchLowerCodeNew) {continue;} // doesn't make sense to transpose a repeat char + } + matchesSimpleLen = searchI; + targetI = matchesSimple[matchesSimpleLen - 1] + 1; + break; + } + } + } + + var searchI = 0; + var typoStrictI = 0; + var successStrict = false; + var matchesStrictLen = 0; + + var nextBeginningIndexes = prepared._nextBeginningIndexes; + if(nextBeginningIndexes === null) {nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target);} + var firstPossibleI = targetI = matchesSimple[0]===0 ? 0 : nextBeginningIndexes[matchesSimple[0]-1]; + + // Our target string successfully matched all characters in sequence! + // Let's try a more advanced and strict test to improve the score + // only count it as a match if it's consecutive or a beginning character! + if(targetI !== targetLen) {for(;;) { + if(targetI >= targetLen) { + // We failed to find a good spot for this search char, go back to the previous search char and force it forward + if(searchI <= 0) { // We failed to push chars forward for a better match + // transpose, starting from the beginning + ++typoStrictI; if(typoStrictI > searchLen-2) {break;} + if(searchLowerCodes[typoStrictI] === searchLowerCodes[typoStrictI+1]) {continue;} // doesn't make sense to transpose a repeat char + targetI = firstPossibleI; + continue; + } + + --searchI; + var lastMatch = matchesStrict[--matchesStrictLen]; + targetI = nextBeginningIndexes[lastMatch]; + + } else { + var isMatch = searchLowerCodes[typoStrictI===0?searchI : (typoStrictI===searchI?searchI+1 : (typoStrictI===searchI-1?searchI-1 : searchI))] === targetLowerCodes[targetI]; + if(isMatch) { + matchesStrict[matchesStrictLen++] = targetI; + ++searchI; if(searchI === searchLen) { successStrict = true; break; } + ++targetI; + } else { + targetI = nextBeginningIndexes[targetI]; + } + } + }} + + { // tally up the score & keep track of matches for highlighting later + if(successStrict) { var matchesBest = matchesStrict; var matchesBestLen = matchesStrictLen; } + else { var matchesBest = matchesSimple; var matchesBestLen = matchesSimpleLen; } + var score = 0; + var lastTargetI = -1; + for(var i = 0; i < searchLen; ++i) { var targetI = matchesBest[i]; + // score only goes down if they're not consecutive + if(lastTargetI !== targetI - 1) {score -= targetI;} + lastTargetI = targetI; + } + if(!successStrict) { + score *= 1000; + if(typoSimpleI !== 0) {score += -20;}/*typoPenalty*/ + } else { + if(typoStrictI !== 0) {score += -20;}/*typoPenalty*/ + } + score -= targetLen - searchLen; + prepared.score = score; + prepared.indexes = new Array(matchesBestLen); for(var i = matchesBestLen - 1; i >= 0; --i) {prepared.indexes[i] = matchesBest[i];} + + return prepared; + } + }, + + algorithmNoTypo: function(searchLowerCodes, prepared, searchLowerCode) { + var targetLowerCodes = prepared._targetLowerCodes; + var searchLen = searchLowerCodes.length; + var targetLen = targetLowerCodes.length; + var searchI = 0; // where we at + var targetI = 0; // where you at + var matchesSimpleLen = 0; + + // very basic fuzzy match; to remove non-matching targets ASAP! + // walk through target. find sequential matches. + // if all chars aren't found then exit + for(;;) { + var isMatch = searchLowerCode === targetLowerCodes[targetI]; + if(isMatch) { + matchesSimple[matchesSimpleLen++] = targetI; + ++searchI; if(searchI === searchLen) {break;} + searchLowerCode = searchLowerCodes[searchI]; + } + ++targetI; if(targetI >= targetLen) {return null;} // Failed to find searchI + } + + var searchI = 0; + var successStrict = false; + var matchesStrictLen = 0; + + var nextBeginningIndexes = prepared._nextBeginningIndexes; + if(nextBeginningIndexes === null) {nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target);} + var firstPossibleI = targetI = matchesSimple[0]===0 ? 0 : nextBeginningIndexes[matchesSimple[0]-1]; + + // Our target string successfully matched all characters in sequence! + // Let's try a more advanced and strict test to improve the score + // only count it as a match if it's consecutive or a beginning character! + if(targetI !== targetLen) {for(;;) { + if(targetI >= targetLen) { + // We failed to find a good spot for this search char, go back to the previous search char and force it forward + if(searchI <= 0) {break;} // We failed to push chars forward for a better match + + --searchI; + var lastMatch = matchesStrict[--matchesStrictLen]; + targetI = nextBeginningIndexes[lastMatch]; + + } else { + var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI]; + if(isMatch) { + matchesStrict[matchesStrictLen++] = targetI; + ++searchI; if(searchI === searchLen) { successStrict = true; break; } + ++targetI; + } else { + targetI = nextBeginningIndexes[targetI]; + } + } + }} + + { // tally up the score & keep track of matches for highlighting later + if(successStrict) { var matchesBest = matchesStrict; var matchesBestLen = matchesStrictLen; } + else { var matchesBest = matchesSimple; var matchesBestLen = matchesSimpleLen; } + var score = 0; + var lastTargetI = -1; + for(var i = 0; i < searchLen; ++i) { var targetI = matchesBest[i]; + // score only goes down if they're not consecutive + if(lastTargetI !== targetI - 1) {score -= targetI;} + lastTargetI = targetI; + } + if(!successStrict) {score *= 1000;} + score -= targetLen - searchLen; + prepared.score = score; + prepared.indexes = new Array(matchesBestLen); for(var i = matchesBestLen - 1; i >= 0; --i) {prepared.indexes[i] = matchesBest[i];} + + return prepared; + } + }, + + prepareLowerCodes: function(str) { + var strLen = str.length; + var lowerCodes = []; // new Array(strLen) sparse array is too slow + var lower = str.toLowerCase(); + for(var i = 0; i < strLen; ++i) {lowerCodes[i] = lower.charCodeAt(i);} + return lowerCodes; + }, + prepareBeginningIndexes: function(target) { + var targetLen = target.length; + var beginningIndexes = []; var beginningIndexesLen = 0; + var wasUpper = false; + var wasAlphanum = false; + for(var i = 0; i < targetLen; ++i) { + var targetCode = target.charCodeAt(i); + var isUpper = targetCode>=65&&targetCode<=90; + var isAlphanum = isUpper || targetCode>=97&&targetCode<=122 || targetCode>=48&&targetCode<=57; + var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum; + wasUpper = isUpper; + wasAlphanum = isAlphanum; + if(isBeginning) {beginningIndexes[beginningIndexesLen++] = i;} + } + return beginningIndexes; + }, + prepareNextBeginningIndexes: function(target) { + var targetLen = target.length; + var beginningIndexes = fuzzysort.prepareBeginningIndexes(target); + var nextBeginningIndexes = []; // new Array(targetLen) sparse array is too slow + var lastIsBeginning = beginningIndexes[0]; + var lastIsBeginningI = 0; + for(var i = 0; i < targetLen; ++i) { + if(lastIsBeginning > i) { + nextBeginningIndexes[i] = lastIsBeginning; + } else { + lastIsBeginning = beginningIndexes[++lastIsBeginningI]; + nextBeginningIndexes[i] = lastIsBeginning===undefined ? targetLen : lastIsBeginning; + } + } + return nextBeginningIndexes; + }, + + cleanup: cleanup, + new: fuzzysortNew, + }; + return fuzzysort; +} // fuzzysortNew + +// This stuff is outside fuzzysortNew, because it's shared with instances of fuzzysort.new() +var isNode = typeof require !== 'undefined' && typeof window === 'undefined'; +var MyMap = typeof Map === 'function' ? Map : function(){var s=Object.create(null);this.get=function(k){return s[k];};this.set=function(k,val){s[k]=val;return this;};this.clear=function(){s=Object.create(null);};}; +var preparedCache = new MyMap(); +var preparedSearchCache = new MyMap(); +var noResults = []; noResults.total = 0; +var matchesSimple = []; var matchesStrict = []; +function cleanup() { preparedCache.clear(); preparedSearchCache.clear(); matchesSimple = []; matchesStrict = []; } +function defaultScoreFn(a) { + var max = -9007199254740991; + for (var i = a.length - 1; i >= 0; --i) { + var result = a[i]; if(result === null) {continue;} + var score = result.score; + if(score > max) {max = score;} + } + if(max === -9007199254740991) {return null;} + return max; +} + +// prop = 'key' 2.5ms optimized for this case, seems to be about as fast as direct obj[prop] +// prop = 'key1.key2' 10ms +// prop = ['key1', 'key2'] 27ms +function getValue(obj, prop) { + var tmp = obj[prop]; if(tmp !== undefined) {return tmp;} + var segs = prop; + if(!Array.isArray(prop)) {segs = prop.split('.');} + var len = segs.length; + var i = -1; + while (obj && (++i < len)) {obj = obj[segs[i]];} + return obj; +} + +function isObj(x) { return typeof x === 'object'; } // faster as a function + +// Hacked version of https://github.com/lemire/FastPriorityQueue.js +var fastpriorityqueue=function(){var r=[],o=0,e={};function n(){for(var e=0,n=r[e],c=1;c<o;){var f=c+1;e=c,f<o&&r[f].score<r[c].score&&(e=f),r[e-1>>1]=r[e],c=1+(e<<1);}for(var a=e-1>>1;e>0&&n.score<r[a].score;a=(e=a)-1>>1){r[e]=r[a];}r[e]=n;}return e.add=function(e){var n=o;r[o++]=e;for(var c=n-1>>1;n>0&&e.score<r[c].score;c=(n=c)-1>>1){r[n]=r[c];}r[n]=e;},e.poll=function(){if(0!==o){var e=r[0];return r[0]=r[--o],n(),e;}},e.peek=function(e){if(0!==o){return r[0];}},e.replaceTop=function(o){r[0]=o,n();},e;}; +var q = fastpriorityqueue(); // reuse this, except for async, it needs to make its own + +return fuzzysortNew(); +}); // UMD + +// TODO: (performance) wasm version!? +// TODO: (performance) threads? +// TODO: (performance) avoid cache misses +// TODO: (performance) preparedCache is a memory leak +// TODO: (like sublime) backslash === forwardslash +// TODO: (like sublime) spaces: "a b" should do 2 searches 1 for a and 1 for b +// TODO: (scoring) garbage in targets that allows most searches to strict match need a penality +// TODO: (performance) idk if allowTypo is optimized diff --git a/static/js/index.js b/static/js/index.js new file mode 100644 index 0000000..df649df --- /dev/null +++ b/static/js/index.js @@ -0,0 +1,424 @@ +// deno-fmt-ignore-file +// deno-lint-ignore-file +// This code was bundled using `deno bundle` and it's not recommended to edit it manually + +(function() { + const url = self.location.href.split("#")[0]; + let settings = { + pager: {} + }; + self.addEventListener("DOMContentLoaded", function() { + if (history.scrollRestoration) history.scrollRestoration = "manual"; + if (localStorage["settings"]) { + settings = JSON.parse(localStorage["settings"]); + } + if (self.location.href.indexOf("#") >= 0) { + settings["pager"][url] = self.pageYOffset; + localStorage["settings"] = JSON.stringify(settings); + document.getElementById(location.hash.slice(1)).scrollIntoView(); + return; + } + if (settings["pager"][url] > 0) { + self.scrollTo(0, settings["pager"][url]); + return; + } + settings["pager"][url] = self.pageYOffset; + localStorage["settings"] = JSON.stringify(settings); + }); + self.addEventListener("scroll", function() { + const currentPosition = self.pageYOffset; + settings["pager"][url] = currentPosition; + localStorage["settings"] = JSON.stringify(settings); + }); + self.addEventListener("DOMContentLoaded", function() { + const up = document.getElementById("top"); + const back = document.getElementById("back"); + if (document.body.contains(up)) up.href = "javascript: void(0)"; + if (document.body.contains(back)) back.href = "javascript: void(0)"; + self.addEventListener("click", function(event) { + if (document.body.contains(up) && up.contains(event.target)) { + window.scrollTo(0, 0); + } + if (document.body.contains(back) && back.contains(event.target)) { + history.go(-1); + } + }); + }); +})(); +(function() { + const options = "targetWindow,width=700,height=500,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes"; + self.addEventListener("keydown", function(event) { + if (event.repeat && event.key === "d") { + selection(dictionary); + } + if (event.repeat && event.key === "s") { + selection(search); + } + if (event.repeat && event.key === "m") { + selection(manual); + } + }); + function selection(execute) { + let phrase = "" + window.getSelection(); + phrase = phrase.replace(/[!.:?,;"]/g, ""); + phrase = phrase.replace(/^\s*(\S*?)\s*$/g, "$1"); + if (phrase && phrase > "" && phrase.length > 1) { + execute(phrase); + } + } + function dictionary(word) { + window.open("https://www.merriam-webster.com/dictionary/" + encodeURIComponent(word), "Definitions", options); + } + function search(phrase) { + window.open("https://lite.duckduckgo.com/lite/?q=" + encodeURIComponent(phrase), "Search", options); + } + function manual(program) { + window.open("https://man.archlinux.org/search?q=" + encodeURIComponent(program), "Manual", options); + } +})(); +(function() { + self.addEventListener("DOMContentLoaded", function() { + let mouseoverTimer; + let lastTouchTimestamp; + const prefetches = new Set(); + const prefetchElement = document.createElement("link"); + const isSupported = prefetchElement.relList && prefetchElement.relList.supports && prefetchElement.relList.supports("prefetch") && window.IntersectionObserver && "isIntersecting" in IntersectionObserverEntry.prototype; + const allowQueryString = "instantAllowQueryString" in document.body.dataset; + const allowExternalLinks = "instantAllowExternalLinks" in document.body.dataset; + const useWhitelist = "instantWhitelist" in document.body.dataset; + const mousedownShortcut = "instantMousedownShortcut" in document.body.dataset; + let delayOnHover = 65; + let useMousedown = false; + let useMousedownOnly = false; + let useViewport = false; + if ("instantIntensity" in document.body.dataset) { + const intensity = document.body.dataset.instantIntensity; + if (intensity.substr(0, "mousedown".length) == "mousedown") { + useMousedown = true; + if (intensity == "mousedown-only") { + useMousedownOnly = true; + } + } else if (intensity.substr(0, "viewport".length) == "viewport") { + if (!(navigator.connection && (navigator.connection.saveData || navigator.connection.effectiveType && navigator.connection.effectiveType.includes("2g")))) { + if (intensity == "viewport") { + if (document.documentElement.clientWidth * document.documentElement.clientHeight < 450000) { + useViewport = true; + } + } else if (intensity == "viewport-all") { + useViewport = true; + } + } + } else { + const milliseconds = parseInt(intensity); + if (!isNaN(milliseconds)) { + delayOnHover = milliseconds; + } + } + } + if (isSupported) { + const eventListenersOptions = { + capture: true, + passive: true + }; + if (!useMousedownOnly) { + document.addEventListener("touchstart", touchstartListener, eventListenersOptions); + } + if (!useMousedown) { + document.addEventListener("mouseover", mouseoverListener, eventListenersOptions); + } else if (!mousedownShortcut) { + document.addEventListener("mousedown", mousedownListener, eventListenersOptions); + } + if (mousedownShortcut) { + document.addEventListener("mousedown", mousedownShortcutListener, eventListenersOptions); + } + if (useViewport) { + let triggeringFunction; + if (window.requestIdleCallback) { + triggeringFunction = function(callback) { + requestIdleCallback(callback, { + timeout: 1500 + }); + }; + } else { + triggeringFunction = function(callback) { + callback(); + }; + } + triggeringFunction(function() { + const intersectionObserver = new IntersectionObserver(function(entries) { + entries.forEach(function(entry) { + if (entry.isIntersecting) { + const linkElement = entry.target; + intersectionObserver.unobserve(linkElement); + preload(linkElement.href); + } + }); + }); + document.querySelectorAll("a").forEach(function(linkElement) { + if (isPreloadable(linkElement)) { + intersectionObserver.observe(linkElement); + } + }); + }); + } + } + function touchstartListener(event) { + lastTouchTimestamp = performance.now(); + const linkElement = event.target.closest("a"); + if (!isPreloadable(linkElement)) { + return; + } + preload(linkElement.href); + } + function mouseoverListener(event) { + if (performance.now() - lastTouchTimestamp < 1111) { + return; + } + const linkElement = event.target.closest("a"); + if (!isPreloadable(linkElement)) { + return; + } + linkElement.addEventListener("mouseout", mouseoutListener, { + passive: true + }); + mouseoverTimer = setTimeout(function() { + preload(linkElement.href); + mouseoverTimer = undefined; + }, delayOnHover); + } + function mousedownListener(event) { + const linkElement = event.target.closest("a"); + if (!isPreloadable(linkElement)) { + return; + } + preload(linkElement.href); + } + function mouseoutListener(event) { + if (event.relatedTarget && event.target.closest("a") == event.relatedTarget.closest("a")) { + return; + } + if (mouseoverTimer) { + clearTimeout(mouseoverTimer); + mouseoverTimer = undefined; + } + } + function mousedownShortcutListener(event1) { + if (performance.now() - lastTouchTimestamp < 1111) { + return; + } + const linkElement = event1.target.closest("a"); + if (event1.which > 1 || event1.metaKey || event1.ctrlKey) { + return; + } + if (!linkElement) { + return; + } + linkElement.addEventListener("click", function(event) { + if (event.detail == 1337) { + return; + } + event.preventDefault(); + }, { + capture: true, + passive: false, + once: true + }); + const customEvent = new MouseEvent("click", { + view: window, + bubbles: true, + cancelable: false, + detail: 1337 + }); + linkElement.dispatchEvent(customEvent); + } + function isPreloadable(linkElement) { + if (!linkElement || !linkElement.href) { + return; + } + if (useWhitelist && !("instant" in linkElement.dataset)) { + return; + } + if (!allowExternalLinks && linkElement.origin != location.origin && !("instant" in linkElement.dataset)) { + return; + } + if (![ + "http:", + "https:" + ].includes(linkElement.protocol)) { + return; + } + if (linkElement.protocol == "http:" && location.protocol == "https:") { + return; + } + if (!allowQueryString && linkElement.search && !("instant" in linkElement.dataset)) { + return; + } + if (linkElement.hash && linkElement.pathname + linkElement.search == location.pathname + location.search) { + return; + } + if ("noInstant" in linkElement.dataset) { + return; + } + return true; + } + function preload(url) { + if (prefetches.has(url)) { + return; + } + const prefetcher = document.createElement("link"); + prefetcher.rel = "prefetch"; + prefetcher.href = url; + document.head.appendChild(prefetcher); + prefetches.add(url); + } + }); +})(); +(function() { + self.addEventListener("DOMContentLoaded", function() { + const form = document.getElementById("search-form"); + const query = document.getElementById("search-input"); + document.getElementById("search-submit"); + const dropdown = document.getElementById("search-results"); + form.addEventListener("focusin", function() { + initialize(); + }); + form.addEventListener("submit", function(event) { + event.preventDefault(); + return false; + }); + form.addEventListener("keydown", function(event) { + const head = dropdown.firstChild.nextElementSibling.firstChild.nextElementSibling; + const tail = dropdown.lastElementChild.firstChild.nextElementSibling; + if (query.contains(event.target)) { + if (event.keyCode == 27) { + document.activeElement.blur(); + dropdown.setAttribute("hidden", ""); + } + } + if (event.keyCode == 40) { + event.preventDefault(); + if (document.activeElement == query) head.focus(); + else if (document.activeElement == tail) query.focus(); + else { + document.activeElement.parentElement.nextElementSibling.firstChild.nextElementSibling.focus(); + } + } + if (event.keyCode == 38) { + event.preventDefault(); + if (document.activeElement == query) tail.focus(); + else if (document.activeElement == head) query.focus(); + else { + document.activeElement.parentElement.previousElementSibling.firstChild.nextElementSibling.focus(); + } + } + if (event.keyCode == 8) { + if (document.activeElement != query) { + event.preventDefault(); + query.focus(); + } + } + if (event.keyCode == 13) { + if (dropdown && document.activeElement == query) { + event.preventDefault(); + head.focus(); + self.window.location = document.activeElement.href; + } + } + }); + let scrolls = 0; + self.addEventListener("scroll", function() { + if (scrolls > 3) { + scrolls = 0; + document.activeElement.blur(); + dropdown.setAttribute("hidden", ""); + } + scrolls++; + }); + document.addEventListener("click", function(event) { + if (!form.contains(event.target)) { + dropdown.setAttribute("hidden", ""); + } + }); + function fetch_JSON(path, callback) { + const httpRequest = new XMLHttpRequest(); + httpRequest.onreadystatechange = function() { + if (httpRequest.readyState === 4) { + if (httpRequest.status === 200) { + const data = JSON.parse(httpRequest.responseText); + if (callback) callback(data); + } + } + }; + httpRequest.open("GET", path); + httpRequest.send(); + } + function load_script(url) { + return new Promise(function(resolve, reject) { + const script = document.createElement("script"); + script.onerror = reject; + script.onload = resolve; + if (document.currentScript) { + document.currentScript.parentNode.insertBefore(script, document.currentScript); + } else { + document.head.appendChild(script); + } + script.src = url; + }); + } + let first_run = true; + function initialize() { + if (first_run) { + load_script(window.location.origin + "/js/fuzzysort.js").then(()=>{ + first_run = false; + fetch_JSON("/index.json", function(data) { + const options = { + key: [ + "title" + ] + }; + query.addEventListener("keyup", function() { + search(query.value, data.items, options); + }); + query.addEventListener("focusin", function() { + search(query.value, data.items, options); + }); + search(query.value, data.items, options); + }); + }).catch((error)=>{ + console.log("Error failed to load fuzzy sort: " + error); + }); + } + } + function search(term, data, options) { + const results = fuzzysort.go(term, data, options); + let items = ""; + if (results.length === 0 && term.length >= 0) { + let separator = "—"; + if (term.length === 0) separator = ""; + items = ` + <li> + <a href="javascript: void(0)" tabindex="0">${term} ${separator} No Results Found</a> + </li> + `; + dropdown.removeAttribute("hidden"); + } else { + dropdown.removeAttribute("hidden"); + for(const string in results.slice(0, 10)){ + const decode = document.createElement("textarea"); + decode.innerHTML = results[string].obj.title; + let highlight = fuzzysort.highlight(fuzzysort.single(term, decode.value), "<span>", "</span>"); + if (highlight === null) { + highlight = decode.value; + } + items = items + ` + <li> + <a href="${results[string].obj.url}" tabindex="0">${highlight}</a> + </li> + `; + } + } + dropdown.innerHTML = items; + } + }); +})(); +console.log("Surface Control: OK"); diff --git a/static/js/index.ts b/static/js/index.ts new file mode 100644 index 0000000..6000441 --- /dev/null +++ b/static/js/index.ts @@ -0,0 +1,6 @@ +import "./pager.ts"; +import "./plumber.ts"; +import "./instantpage.ts"; +import "./fixedsearch.ts"; + +console.log("Surface Control: OK"); diff --git a/static/js/instantpage.ts b/static/js/instantpage.ts new file mode 100644 index 0000000..7c78a6f --- /dev/null +++ b/static/js/instantpage.ts @@ -0,0 +1,292 @@ +(function () { + self.addEventListener("DOMContentLoaded", function () { + /*! instant.page v5.1.0 - (C) 2019-2020 Alexandre Dieulot - https://instant.page/license */ + + let mouseoverTimer; + let lastTouchTimestamp; + const prefetches = new Set(); + const prefetchElement = document.createElement("link"); + const isSupported = prefetchElement.relList && + prefetchElement.relList.supports && + prefetchElement.relList.supports("prefetch") && + window.IntersectionObserver && + "isIntersecting" in IntersectionObserverEntry.prototype; + const allowQueryString = "instantAllowQueryString" in document.body.dataset; + const allowExternalLinks = "instantAllowExternalLinks" in + document.body.dataset; + const useWhitelist = "instantWhitelist" in document.body.dataset; + const mousedownShortcut = "instantMousedownShortcut" in + document.body.dataset; + const DELAY_TO_NOT_BE_CONSIDERED_A_TOUCH_INITIATED_ACTION = 1111; + + let delayOnHover = 65; + let useMousedown = false; + let useMousedownOnly = false; + let useViewport = false; + + if ("instantIntensity" in document.body.dataset) { + const intensity = document.body.dataset.instantIntensity; + + if (intensity.substr(0, "mousedown".length) == "mousedown") { + useMousedown = true; + if (intensity == "mousedown-only") { + useMousedownOnly = true; + } + } else if (intensity.substr(0, "viewport".length) == "viewport") { + if ( + !(navigator.connection && + (navigator.connection.saveData || + (navigator.connection.effectiveType && + navigator.connection.effectiveType.includes("2g")))) + ) { + if (intensity == "viewport") { + /* Biggest iPhone resolution (which we want): 414 × 896 = 370944 + * Small 7" tablet resolution (which we don’t want): 600 × 1024 = 614400 + * Note that the viewport (which we check here) is smaller than the resolution due to the UI’s chrome */ + if ( + document.documentElement.clientWidth * + document.documentElement.clientHeight < 450000 + ) { + useViewport = true; + } + } else if (intensity == "viewport-all") { + useViewport = true; + } + } + } else { + const milliseconds = parseInt(intensity); + if (!isNaN(milliseconds)) { + delayOnHover = milliseconds; + } + } + } + + if (isSupported) { + const eventListenersOptions = { + capture: true, + passive: true, + }; + + if (!useMousedownOnly) { + document.addEventListener( + "touchstart", + touchstartListener, + eventListenersOptions, + ); + } + + if (!useMousedown) { + document.addEventListener( + "mouseover", + mouseoverListener, + eventListenersOptions, + ); + } else if (!mousedownShortcut) { + document.addEventListener( + "mousedown", + mousedownListener, + eventListenersOptions, + ); + } + + if (mousedownShortcut) { + document.addEventListener( + "mousedown", + mousedownShortcutListener, + eventListenersOptions, + ); + } + + if (useViewport) { + let triggeringFunction; + if (window.requestIdleCallback) { + triggeringFunction = function (callback) { + requestIdleCallback(callback, { + timeout: 1500, + }); + }; + } else { + triggeringFunction = function (callback) { + callback(); + }; + } + + triggeringFunction(function () { + const intersectionObserver = new IntersectionObserver( + function (entries) { + entries.forEach(function (entry) { + if (entry.isIntersecting) { + const linkElement = entry.target; + intersectionObserver.unobserve(linkElement); + preload(linkElement.href); + } + }); + }, + ); + + document.querySelectorAll("a").forEach(function (linkElement) { + if (isPreloadable(linkElement)) { + intersectionObserver.observe(linkElement); + } + }); + }); + } + } + + function touchstartListener(event) { + /* Chrome on Android calls mouseover before touchcancel so `lastTouchTimestamp` + * must be assigned on touchstart to be measured on mouseover. */ + lastTouchTimestamp = performance.now(); + + const linkElement = event.target.closest("a"); + + if (!isPreloadable(linkElement)) { + return; + } + + preload(linkElement.href); + } + + function mouseoverListener(event) { + if ( + performance.now() - lastTouchTimestamp < + DELAY_TO_NOT_BE_CONSIDERED_A_TOUCH_INITIATED_ACTION + ) { + return; + } + + const linkElement = event.target.closest("a"); + + if (!isPreloadable(linkElement)) { + return; + } + + linkElement.addEventListener("mouseout", mouseoutListener, { + passive: true, + }); + + mouseoverTimer = setTimeout(function () { + preload(linkElement.href); + mouseoverTimer = undefined; + }, delayOnHover); + } + + function mousedownListener(event) { + const linkElement = event.target.closest("a"); + + if (!isPreloadable(linkElement)) { + return; + } + + preload(linkElement.href); + } + + function mouseoutListener(event) { + if ( + event.relatedTarget && + event.target.closest("a") == event.relatedTarget.closest("a") + ) { + return; + } + + if (mouseoverTimer) { + clearTimeout(mouseoverTimer); + mouseoverTimer = undefined; + } + } + + function mousedownShortcutListener(event) { + if ( + performance.now() - lastTouchTimestamp < + DELAY_TO_NOT_BE_CONSIDERED_A_TOUCH_INITIATED_ACTION + ) { + return; + } + + const linkElement = event.target.closest("a"); + + if (event.which > 1 || event.metaKey || event.ctrlKey) { + return; + } + + if (!linkElement) { + return; + } + + linkElement.addEventListener("click", function (event) { + if (event.detail == 1337) { + return; + } + + event.preventDefault(); + }, { capture: true, passive: false, once: true }); + + const customEvent = new MouseEvent("click", { + view: window, + bubbles: true, + cancelable: false, + detail: 1337, + }); + linkElement.dispatchEvent(customEvent); + } + + function isPreloadable(linkElement) { + if (!linkElement || !linkElement.href) { + return; + } + + if (useWhitelist && !("instant" in linkElement.dataset)) { + return; + } + + if ( + !allowExternalLinks && linkElement.origin != location.origin && + !("instant" in linkElement.dataset) + ) { + return; + } + + if (!["http:", "https:"].includes(linkElement.protocol)) { + return; + } + + if (linkElement.protocol == "http:" && location.protocol == "https:") { + return; + } + + if ( + !allowQueryString && linkElement.search && + !("instant" in linkElement.dataset) + ) { + return; + } + + if ( + linkElement.hash && + linkElement.pathname + linkElement.search == + location.pathname + location.search + ) { + return; + } + + if ("noInstant" in linkElement.dataset) { + return; + } + + return true; + } + + function preload(url) { + if (prefetches.has(url)) { + return; + } + + const prefetcher = document.createElement("link"); + prefetcher.rel = "prefetch"; + prefetcher.href = url; + document.head.appendChild(prefetcher); + + prefetches.add(url); + } + }); +})(); diff --git a/static/js/pager.ts b/static/js/pager.ts new file mode 100644 index 0000000..de60bcd --- /dev/null +++ b/static/js/pager.ts @@ -0,0 +1,46 @@ +(function () { + const url = self.location.href.split("#")[0]; + let settings = { pager: {} }; + + self.addEventListener("DOMContentLoaded", function () { + if (history.scrollRestoration) history.scrollRestoration = "manual"; + if (localStorage["settings"]) { + settings = JSON.parse(localStorage["settings"]); + } + if (self.location.href.indexOf("#") >= 0) { + settings["pager"][url] = self.pageYOffset; + localStorage["settings"] = JSON.stringify(settings); + document.getElementById(location.hash.slice(1)).scrollIntoView(); + return; + } + if (settings["pager"][url] > 0) { + self.scrollTo(0, settings["pager"][url]); + return; + } + settings["pager"][url] = self.pageYOffset; + localStorage["settings"] = JSON.stringify(settings); + }); + + self.addEventListener("scroll", function () { + const currentPosition = self.pageYOffset; + settings["pager"][url] = currentPosition; + localStorage["settings"] = JSON.stringify(settings); + }); + + self.addEventListener("DOMContentLoaded", function () { + const up = document.getElementById("top"); + const back = document.getElementById("back"); + + if (document.body.contains(up)) up.href = "javascript: void(0)"; + if (document.body.contains(back)) back.href = "javascript: void(0)"; + + self.addEventListener("click", function (event) { + if (document.body.contains(up) && up.contains(event.target)) { + window.scrollTo(0, 0); + } + if (document.body.contains(back) && back.contains(event.target)) { + history.go(-1); + } + }); + }); +})(); diff --git a/static/js/plumber.ts b/static/js/plumber.ts new file mode 100644 index 0000000..8e551fd --- /dev/null +++ b/static/js/plumber.ts @@ -0,0 +1,59 @@ +/** + * Plumber based on and inspired by + * Dictionary Access Copyright (C) 2006, Paul Lutus + * https://arachnoid.com/javascript/dictionary_access.js + * LICENSE: GPLv2+ + */ + +(function () { + const options = + "targetWindow,width=700,height=500,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes"; + + self.addEventListener("keydown", function (event) { + if (event.repeat && event.key === "d") { + selection(dictionary); + } + if (event.repeat && event.key === "s") { + selection(search); + } + if (event.repeat && event.key === "m") { + selection(manual); + } + }); + + function selection(execute) { + let phrase = "" + window.getSelection(); + phrase = phrase.replace(/[!.:?,;"]/g, ""); + phrase = phrase.replace(/^\s*(\S*?)\s*$/g, "$1"); + if (phrase && phrase > "" && phrase.length > 1) { + execute(phrase); + } + } + + function dictionary(word) { + window.open( + "https://www.merriam-webster.com/dictionary/" + + encodeURIComponent(word), + "Definitions", + options, + ); + } + + function search(phrase) { + window.open( + "https://lite.duckduckgo.com/lite/?q=" + + encodeURIComponent(phrase), + "Search", + options, + ); + } + + function manual(program) { + window.open( + "https://man.archlinux.org/search?q=" + + encodeURIComponent(program), + "Manual", + options, + ); + } +})(); |