-
Notifications
You must be signed in to change notification settings - Fork 1
/
panel.js
215 lines (194 loc) · 6.45 KB
/
panel.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
var myWindowId;
const contentBox = document.querySelector("#content");
const editList = document.querySelector("#editList");
function safe_tags(str) {
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
function safe_attrs(str) {
return safe_tags(str).replace(/"/g,'"').replace(/'<'/g,''');
}
function _processText(text) {
return text
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
.replace(/\*(.*?)\*/g, '<i>$1</i>')
.replace(/\[\[LINK\|([^|]*)\|([^|]*)\|([^|]*)\]\]/g, "<a target='_blank' href='https://everipedia.org/wiki/$1/$2'>$3</a>")
.replace(/\[\[CITE\|([^|]*)\|([^|]*)\]\]/g, "<a target='_blank' href='$2'>[$1]</a>");
}
function _toHtmlItem(j) {
if(j.type === 'sentence') {
return _processText(j.text);
} else if(j.type === 'text') {
return j.content.map(c => _toHtmlItem(c)).join('');
} else if(j.type === 'tag' || j.type === 'list_item' || j.type === 'dl' || j.type === 'samp' || j.tag_type !== undefined
|| j.rows !== undefined || j.cells !== undefined)
{
const attrs = j.attrs !== undefined
? " " + Object.entries(j.attrs)
.map(x => `${x[0].replace(/^className$/, 'class')}=${x[0] === 'href' ? x[1].replace(/^\//, "https://everipedia.org/") : x[0] == 'style' ? Object.entries(x[0]).map(y => `${y[0]}='${safe_attrs(y[1])}'`) : safe_attrs(`'${x[1]}'`)}`)
.join(' ')
: "";
const tag_type = j.tag_type !== undefined ? j.tag_type : j.type;
if(tag_type === 'table') {
return _toHtmlItem(j.items[0].thead) + _toHtmlItem(j.items[0].tbody) + _toHtmlItem(j.items[0].tfoot);
}
return (j.content || j.items || j.rows || j.cells)
? `<${tag_type}${attrs}>${(j.content ? j.content : j.items ? j.items : j.rows ? j.rows : j.cells).map(c => _toHtmlItem(c)).join('')}</${tag_type}>`
: j.sentences
? `<${tag_type}${attrs}>${j.sentences.map(c => _processText(c.text)).join('')}</${tag_type}>`
: `<${tag_type}${attrs}/>`;
} else {
return "";
}
}
function toHtml(j) {
let result = "";
for(a of j) {
for(b of a.paragraphs) {
result += `<${safe_tags(b.tag_type)}>`;
if(b.tag_type === 'table') {
result += _toHtmlItem(b);
} else {
for(item of b.items) {
result += _toHtmlItem(item);
}
}
result += `</${safe_tags(b.tag_type)}>`;
}
}
return result;
}
function _newPagePopup(url) {
// if(window.browser) {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, {kind: "askCreate", url});
});
// } else {
// askCreate(url);
// }
}
function _addUrl(url) {
editList.innerHTML +=
`<li><a target="_blank" href="#">${safe_tags(url)}</a></li>`;
if(contentBox.innerHTML === '') return;
}
function _buildUrlsList(url) {
let list = [];
if(url !== undefined) {
list.push(url);
let url2 = url.replace(/\?.*/, '');
if(url2 !== url) list.push(url2);
for(;;) {
const url3 = url2.replace(/([^\/]+|[^\/]*\/)$/, '');
try {
new URL(url3);
}
catch(_) {
break;
}
if(url3 !== url2) {
list.push(url3);
} else {
break;
}
url2 = url3;
}
}
return list;
}
// TODO: Duplicate code.
function pageName(url) {
return encodeURIComponent(url).replace(/\//g, '%2F');
}
// Returns true if the first URL is existing.
async function updateContentByUrl(url) {
editList.innerHTML = '';
contentBox.innerHTML = '';
const urls = _buildUrlsList(url);
const doFetch = function(i) {
const encoded = pageName(urls[i]).replace(/%/g, '_u_').replace(/\./g, ''); // duplicate code
console.log("https://api.everipedia.org/v2/wiki/slug/lang_en/" + encoded)
return fetch("https://api.everipedia.org/v2/wiki/slug/lang_en/" + encoded)
.then(async html => {
if(html.status === 200) {
contentBox.innerHTML = toHtml((await html.json()).page_body);
return true;
} else {
if(i !== urls.length - 1) {
await doFetch(i + 1);
}
return false;
}
})
.catch(async e => {
if(i !== urls.length - 1) {
await doFetch(i + 1);
}
return false;
});
}
const fetchResult = await doFetch(0);
console.log('fetchResult', fetchResult)
if(fetchResult) {
const encoded = pageName(url).replace(/%/g, '_u_').replace(/\./g, ''); // duplicate code
const everipediaUrl = "https://everipedia.org/wiki/lang_en/" + encoded;
editList.innerHTML += `<li><a target="_blank" href="${safe_attrs(everipediaUrl)}">${safe_tags(url)}</a></li>`;
} else {
for(suburl of urls) _addUrl(suburl);
// preventDefault is broken if done earlier // FIXME: Bug if clicked before preventDefault() is added.
for(let i = 0; i < urls.length; ++i) {
editList.childNodes[i].firstChild.onclick = event => { event.preventDefault(); _newPagePopup(urls[i]); };
}
contentBox.innerHTML = "There is no information about this page.";
}
}
/*
Update the sidebar's content.
1) Get the active tab in this sidebar's window.
2) Get its stored content.
3) Put it in the content box.
*/
async function updateContent() {
if(window.browser) {
browser.tabs.query({windowId: myWindowId, active: true})
// .then((tabs) => {
// return browser.storage.local.get(tabs[0].url);
// })
.then(async (tabs) => {
const url = tabs[0].url;
if(!/^(about|file):/.test(url)) {
await updateContentByUrl(url);
} else {
editList.innerHTML = '';
contentBox.innerHTML = '';
}
});
} else {
await updateContentByUrl(window.myParentUrl);
}
}
if(!window.browser) {
const url = decodeURIComponent(window.location.href.match(/\burl=([^&;]*)/)[1]);
window.addEventListener('load', async () => {
document.getElementById('close').onclick = () => {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, {kind: "closePanel", url});
});
return false;
};
document.getElementById('close').style.display = 'block';
await updateContentByUrl(url);
});
}
if(window.browser) {
browser.windows.getCurrent({populate: true}).then(async (windowInfo) => {
myWindowId = windowInfo.id;
await updateContent();
});
}
async function handleMessage(request, sender, sendResponse) {
await updateContentByUrl(request.url);
}
function closeWindow() {
window.close();
}
chrome.runtime.onMessage.addListener(handleMessage);