-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex-common.js
More file actions
60 lines (51 loc) · 1.57 KB
/
index-common.js
File metadata and controls
60 lines (51 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function escape(str) {
return str.replace(/[&<>"'/]/g, function (char) {
const escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
return escapeMap[char] || char;
});
}
function elem(parent, query, value = undefined, unsafeHtml = false) {
/** @type {HTMLElement} */
const element = parent.querySelector(query);
if (!element) {
throw new Error(`Element not found for query: ${query}`);
}
if (value !== undefined) {
if (unsafeHtml) {
element.innerHTML = value;
} else {
element.textContent = value;
}
} else {
return element;
}
}
function createError({ thing, message }) {
/** @type {HTMLTemplateElement} */
const errorTemplate = document.getElementById("error-template");
const errorElement = errorTemplate.content.firstElementChild.cloneNode(true);
elem(errorElement, `[data-slot="thing"]`, thing);
elem(errorElement, `[data-slot="message"]`, message);
return errorElement;
}
function linkAndEscape(str) {
if (!str) return '';
const escaped = str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
const urlRegex = /(https?:\/\/[^\s]+)/g;
return escaped.replace(urlRegex, (url) => {
const safeUrl = encodeURI(url);
return `<a href="${safeUrl}" target="_blank">${safeUrl}</a>`;
});
}