-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcontext.js
More file actions
484 lines (418 loc) · 15.3 KB
/
Copy pathcontext.js
File metadata and controls
484 lines (418 loc) · 15.3 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
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
class Context {
static EXTENSION_SELECTOR_PREFIX = WhichExtension;
static BOX_CLASS = `${Context.EXTENSION_SELECTOR_PREFIX}-box`;
static BOX_SELECTOR = `.${Context.BOX_CLASS}`;
static STYLE_ELEMENT_ID = `${Context.EXTENSION_SELECTOR_PREFIX}-style`;
static OPTICHAT_MAIN_STYLE_ELEMENT_ID = `optichat-main`;
static MOBILE_CLASS = 'mobile';
static engines = {};
static engine = {};
static processEngine = {};
static save = {};
static settingsListeners = {};
static boxes = [];
static extpay = null;
static extpayUser = null;
static get onMobile() {
return Context.computeIsOnMobile();
}
/** @type {HTMLElement | null} */
static _rightColumnElement = null;
static set rightColumn(value) {
Context._rightColumnElement = value;
if (value)
value.dataset.optisearchColumn = Context.get('wideColumn');
}
static get rightColumn() {
return Context._rightColumnElement;
}
static get boxContainer() {
const firstResultRow = $(Context.engine.resultRow);
return Context.onMobile
? firstResultRow
? firstResultRow.parentElement
: Context.centerColumn
: Context.rightColumn;
}
static centerColumn = null;
static get inTestMode() {
return !!new URL(location).searchParams.get("optisearch-test-mode");
}
/** Start the content script, should be run only once */
static async run() {
Context.extpay = ExtPay('optisearch');
Context.docHead = document.head || document.documentElement;
Context.save = await loadSettings();
Context.engines = await loadEngines();
const matches = Object.entries(Context.engines)
.find(([_, { regex }]) => window.location.hostname.search(new RegExp(regex)) !== -1);
if (!matches) {
debug("Not valid engine");
return;
}
Context.engineName = matches[0];
Context.engine = Context.engines[Context.engineName];
if (!Context.engine) {
debug("Not valid engine");
return;
}
debug(`${Context.engineName} — "${parseSearchParam()}"`);
if (Context.engineName === Google && new URL(window.location.href).searchParams.get('tbm'))
return;
// Update color if the theme has somehow changed
let prevBg = null;
setInterval(() => {
const bg = getBackgroundColor();
if (bg === prevBg)
return;
prevBg = bg;
Context.updateColor();
}, 200);
Context.checkPremiumSubscription();
Context.initChat();
await Context.injectStyle();
Context.execute();
}
/** Parse document and execute tools, might be run multiple times if the parsing failed once */
static async execute() {
Context.centerColumn = await awaitElement(Context.engine.centerColumn);
if (Context.engineName === Baidu && Context.centerColumn) {
let oldSearchParam = parseSearchParam();
const observer = setObserver(_ => {
const searchParam = parseSearchParam();
if (oldSearchParam === searchParam)
return;
oldSearchParam = searchParam;
observer.disconnect();
Context.execute();
}, $('#wrapper_wrapper'), { childList: true });
}
Context.searchString = parseSearchParam();
Context.setupRightColumn();
if (Context.engineName in Context.processEngine){
await Context.processEngine[Context.engineName]();
}
if (!Context.boxContainer) {
return;
}
chrome.runtime.onMessage.addListener((message, _, sendResponse) => {
if (message.type === 'updateSetting') {
Context.save[message.key] = message.value;
Context.dispatchUpdateSetting(message.key, message.value);
}
sendResponse(true);
});
Context.chatSessions.forEach((session) => {
Context.appendPanel(session.panel);
});
if (typeof Sites !== 'undefined' && Context.parseResults) {
Context.parseResults();
}
}
static async checkIfUserStillNotPremium() {
return Context.get('premium') === false && await Context.checkPremiumSubscription() === false;
}
/**
* Opens premium popup if the user doesn't have premium features.
* Useful to use like this at the beginning of an onclick handler from a premium feature:
* `if (await Context.handleNotPremium()) return;`
*
* @returns {Promise<boolean>} true if the user DOESN'T have premium features
*/
static async handleNotPremium() {
if(await Context.checkIfUserStillNotPremium()) {
premiumPresentationPopup();
return true;
}
return false;
}
/**
* Ask extpay API if the user is a premium user
* @returns {Promise<true | false | null>} True if the user is a premium user, false otherwise and null if
* there is an error.
*/
static async checkPremiumSubscription() {
await Context.extpay.getUser()
.then(user => {
Context.extpayUser = user;
Context.set('premium', user.paid);
})
.catch(_ => {
err(`Failed to retrieve user subscription state`);
Context.set('premium', null);
});
return Context.get('premium');
}
static isActive(tool) {
return !!Context.get(tool);
}
static get(saveKey) {
return Context.save[saveKey];
}
static set(saveKey, value) {
Context.save[saveKey] = value;
saveSettings(Context.save);
Context.dispatchUpdateSetting(saveKey, value);
}
static addSettingListener(key, callback) {
Context.settingsListeners[key] ||= [];
Context.settingsListeners[key].push(callback);
}
static dispatchUpdateSetting(key, value) {
Context.settingsListeners[key]?.forEach(callback => callback(value));
}
static async injectStyle() {
let styles = ['chatgpt', 'panel', 'code-light-theme', 'code-dark-theme'];
if (isOptiSearch) {
styles.push('mdn', 'w3schools', 'wikipedia', 'genius');
}
let cssContents = await Promise.all(styles.map(s => read(`src/styles/${s}.css`)));
let allCss = this.addCssParentSelector(cssContents.join('\n'));
// Engine specifics styles must not have css parent selector added to everything
if (Context.engine.style) {
allCss += "\n";
allCss += Context.engine.style.trim().replaceAll(".optisearchbox", Context.BOX_SELECTOR);
}
el('style', { id: Context.STYLE_ELEMENT_ID, textContent: allCss }, Context.docHead);
}
static addCssParentSelector(cssContent) {
const cssRuleRegex = /(?!\s)([^{}%\/\\]+)({[^{}]*})/g; //avoid spaces, comments, @media, @keyframes
return cssContent.replace(cssRuleRegex, (_, selector, body) =>
`${selector.split(",").map(s => {
const sTrim = s.trim();
if (sTrim[0] === ':') return sTrim;
if (sTrim.includes('.optisearchbox')) {
return sTrim.replace('.optisearchbox', Context.BOX_SELECTOR);
}
if (sTrim.includes('.dark')) {
return sTrim.replace('.dark', `${Context.BOX_SELECTOR}.dark`);
}
if (sTrim.includes('.bright')) {
return sTrim.replace('.bright', `${Context.BOX_SELECTOR}.bright`);
}
return `${Context.BOX_SELECTOR} ${sTrim}`;
}).join(", ")} ${body}\n`
);
}
/**
* Append pannel to the side of the result page
* @param {Element} panel the content of the panel
* @returns {Element} the box where the panel is
*/
static appendPanel(panel) {
const buildTopButtons = () => {
const topButtonsContainer = el('div', { className: 'top-buttons-container headerhover' });
const thumb = el('div', { title: _t("Rate this extension") }, topButtonsContainer);
thumb.dataset.emoji = 'thumb';
el('a', { textContent: '👍', href: webstore + '/reviews' }, thumb);
const star = el('div', { title: _t("Premium subscription"), textContent: '⭐' }, topButtonsContainer);
star.dataset.emoji = "star";
star.onclick = premiumPresentationPopup;
Context.addSettingListener('premium', () => {
star.onclick = Context.extpayUser.paidAt ? Context.extpay.openPaymentPage : premiumPresentationPopup;
});
const heart = el('div', { title: _t("Donate") }, topButtonsContainer);
heart.dataset.emoji = "heart";
el('a', { textContent: '❤️', href: donationLink }, heart);
return topButtonsContainer;
}
const buildExpandArrow = () => {
const expandArrow = el('div', { className: 'expand-arrow' });
setSvg(expandArrow, SVG.chevron);
const setTitleExpand = () => expandArrow.title = Context.get('wideColumn') ? _t("Minimize the panel") : _t("Expand the panel");
setTitleExpand();
expandArrow.addEventListener('click', () => Context.set('wideColumn', !Context.get('wideColumn')));
Context.addSettingListener('wideColumn', setTitleExpand);
return expandArrow;
}
const header = $('.optiheader', panel);
if (header) {
header.prepend(el('div', { className: 'watermark', textContent: _t("optisearchName") }, header));
header.prepend(buildTopButtons());
let rightButtonsContainer = $('.right-buttons-container', header);
if (!rightButtonsContainer) {
rightButtonsContainer = el('div', { className: 'right-buttons-container' }, header);
}
rightButtonsContainer.classList.add('headerhover');
rightButtonsContainer.append(buildExpandArrow());
}
const box = panel;
box.classList.add(Context.BOX_CLASS, 'bright', EngineTechnicalNames[Context.engineName]);
Context.boxes.push(box);
if (Context.computeIsOnMobile()) {
box.classList.add(Context.MOBILE_CLASS);
}
Context.appendBoxes([box]);
Context.updateColor();
return box;
}
static appendBoxes(boxes) {
const isOnMobile = Context.computeIsOnMobile();
const firstResultRow = $(Context.engine.resultRow);
const boxContainer = Context.boxContainer;
if (!boxContainer) return;
const startEl = $('.optisearch-start', boxContainer);
for(let box of boxes) {
const boxChat = box.getAttribute("optichat");
if (boxChat && $(`[optichat=${boxChat}]`, boxContainer)) {
return;
}
if (isOnMobile && firstResultRow) {
boxContainer.insertBefore(box, firstResultRow);
return;
}
if (!boxChat && !Context.get("putAbove")) {
if (Context.engine.canPutBefore) {
const toInsertBefore = $(Context.engine.canPutBefore, boxContainer);
if (toInsertBefore) {
boxContainer.insertBefore(box, toInsertBefore);
return;
}
}
boxContainer.append(box);
return;
}
const chatBoxes = $$(Context.BOX_SELECTOR, Context.boxContainer);
if (chatBoxes.length) {
insertAfter(box, chatBoxes.at(-1));
return;
}
if (startEl) {
insertAfter(box, startEl);
return;
}
boxContainer.prepend(box);
}
}
/**
* Parse or add right column to the results page.
* Handle widening mechanism.
*/
static setupRightColumn() {
const rightColumnSelector = Context.engine.rightColumn;
const selectorToDiv = (selector) => {
const div = el('div');
const selectorParts = [
...selector.split(',')[0].matchAll(/[\.#\[][^\.#,\[]+/g)
].map(a => a[0]);
selectorParts.forEach(token => {
switch (token[0]) {
case '.': div.classList.add(token.slice(1)); break;
case '#': div.id = token.slice(1); break;
case '[':
const match = token.trim().slice(1, -1).match(/([^\]=]+)(?:=['"]?([^\]'"]+))?/);
if (match) {
match[2] ? div.setAttribute(match[1], match[2]) : div.toggleAttribute(match[1], true);
}
}
});
return div;
}
Context.rightColumn = $(rightColumnSelector);
if (!Context.rightColumn) {
if (!Context.centerColumn) {
err("No center column detected");
Context.rightColumn = null;
return;
}
Context.rightColumn = selectorToDiv(rightColumnSelector);
Context.rightColumn.classList.add('optisearch-created');
insertAfter(Context.rightColumn, Context.centerColumn);
}
Context.setupMultiExtensionsSettingListener();
}
static setupMultiExtensionsSettingListener() {
const updateWideState = (value) => {
Context.boxContainer.dataset.optisearchColumn = value ? "wide" : "thin";
}
updateWideState(Context.get('wideColumn'));
Context.addSettingListener('wideColumn', updateWideState);
setObserver(mutations => {
mutations.some(m => {
if (m.attributeName !== "data-optisearch-column") return;
if(!m.target.dataset.optisearchColumn) {
Context.set('wideColumn', Context.get('wideColumn')); // to set again the column attribute
return;
}
const isWide = m.target.dataset.optisearchColumn === 'wide';
if (Context.get('wideColumn') !== isWide) {
Context.set('wideColumn', isWide);
}
})
}, Context.boxContainer, { attributes: true });
const updateMainChat = (value, start=false) => {
if (!start || Context.isChatIncluded(value)) {
Context.setStyleMainChat(value);
}
}
updateMainChat(Context.get('mainChat'), true);
Context.addSettingListener('mainChat', updateMainChat);
setObserver(
(mutations) => {
mutations.forEach((mutation) => {
if (
mutation.type === "characterData" ||
mutation.type === "childList"
) {
const styleMainChat = Context.getStyleMainChat();
if (Context.get("mainChat") !== styleMainChat) {
Context.set("mainChat", styleMainChat);
}
}
});
},
Context.mainChatStyleEl,
{
characterData: true,
childList: true,
subtree: true,
}
);
}
static get mainChatStyleEl() {
let styleMainChat = Context.docHead.querySelector("#" + Context.OPTICHAT_MAIN_STYLE_ELEMENT_ID);
if (styleMainChat) {
return styleMainChat;
}
styleMainChat = el('style', {
id: Context.OPTICHAT_MAIN_STYLE_ELEMENT_ID,
textContent: `[optichat]:not([optichat=${DefaultChat}]) { display: none; }`
}, Context.docHead);
return styleMainChat;
}
static getStyleMainChat() {
return Context.mainChatStyleEl.textContent.match(/optichat=(\w+)/)?.[1];
}
static setStyleMainChat(value) {
return Context.mainChatStyleEl.textContent = `[optichat]:not([optichat=${value}]) { display: none; }`;
}
static updateColor() {
const bg = getBackgroundColor();
const dark = isDarkMode();
for (let box of $$(Context.BOX_SELECTOR)) {
box.classList.toggle('dark', dark);
box.classList.toggle('bright', !dark);
box.style.backgroundColor = dark ? colorLuminance(bg, 0.02) : '';
box.style.setProperty('--dark-secondary-background-color', dark ? colorLuminance(bg, 0.005) : '');
}
}
/**
* @returns {boolean} Are we on a mobile device
*/
static computeIsOnMobile() {
if (Context.engineName === DuckDuckGo) {
const scriptInfo = [...document.querySelectorAll('script')].find(s => s.textContent.includes('isMobile'));
if (!scriptInfo)
return false;
const isMobileMatch = scriptInfo.textContent.match(/"isMobile" *: *(false|true)/);
if (isMobileMatch && isMobileMatch[1] === 'true')
return true;
return false;
}
if (!('onMobile' in Context.engine))
return false;
else if (typeof (Context.engine.onMobile) === 'number')
return window.innerWidth < Context.engine.onMobile;
return !!$(Context.engine.onMobile);
}
}