Skip to content

Commit 84b1cde

Browse files
committed
Improvements for keywords linker
- Better performance & safety - Support for custom keywords
1 parent 93e5127 commit 84b1cde

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

web/public/mta-keyword_linker.js

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ const wantedScopes = new Set([
99
"support.function.lua"
1010
]);
1111

12-
const luaGlobals = ["_G", "_VERSION", "math.pi", "math.huge"];
12+
const luaGlobals = new Set(["_G", "_VERSION", "math.pi", "math.huge"]);
13+
14+
const customLinks = new Map([
15+
16+
]);
1317

1418
function extractFunctions(tmLanguage, textContent) {
1519
const result = new Set();
@@ -50,7 +54,7 @@ function extractFunctions(tmLanguage, textContent) {
5054
const funcs = funcsMatch.split("|");
5155
funcs.forEach(fn => {
5256
result.add(fn);
53-
luaGlobals.push(fn);
57+
luaGlobals.add(fn);
5458
});
5559
return;
5660
} else {
@@ -76,16 +80,31 @@ function initKeywordLinker() {
7680

7781
spans.forEach(span => {
7882
const text = span.textContent;
79-
if (allFunctions.has(text)) {
80-
let url = `/reference/${text}`;
83+
console.log(span.dataset.linked);
84+
if (!span.dataset.linked && (allFunctions.has(text) || customLinks.has(text))) {
85+
span.dataset.linked = "true";
86+
87+
let url = customLinks.get(text) ?? `/reference/${text}`;
88+
89+
// Lua keywords
8190
const [lib] = text.split(".");
82-
if (["string", "math", "table", "os", "debug", "coroutine"].includes(lib) || luaGlobals.includes(text)) {
91+
if (["string", "math", "table", "os", "debug", "coroutine"].includes(lib) || luaGlobals.has(text)) {
8392
url = `https://www.lua.org/manual/5.1/manual.html#pdf-${text}`;
8493
}
8594

86-
const isExternalURL = url.startsWith("https://www.");
95+
const a = document.createElement("a");
96+
a.href = url;
97+
a.textContent = text;
98+
a.className = "mta-keyword-link";
99+
100+
// Open external links in a new tab
101+
const isExternalURL = /^https?:\/\//.test(url);
102+
if (isExternalURL) {
103+
a.target = "_blank";
104+
a.rel = "noopener noreferrer";
105+
}
87106

88-
span.innerHTML = `<a href="${url}" class="mta-keyword-link" ${isExternalURL ? 'target="_blank" rel="noopener noreferrer"' : ""}>${text}</a>`;
107+
span.replaceChildren(a);
89108
}
90109
});
91110
}

0 commit comments

Comments
 (0)