Skip to content

Commit 3926aaf

Browse files
committed
refactor(dark-page-handler, dom-observer, index): streamline dark page handling and improve logging
1 parent d93b231 commit 3926aaf

File tree

10 files changed

+207
-78
lines changed

10 files changed

+207
-78
lines changed

src/background/index.ts

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,46 @@ browser.runtime.onMessage.addListener(async (message: any, sender: any) => {
179179
await method_change(message.key || parsed?.host, message.value);
180180
break;
181181
}
182+
case 'log_dark_page_check': {
183+
const timestamp = new Date().toISOString();
184+
const logEntry = {
185+
url: message.key,
186+
isDark: message.value,
187+
timestamp: timestamp,
188+
};
189+
// Store in browser storage for persistence
190+
try {
191+
const existingLogs = await browser.storage.local.get('darkPageLogs');
192+
const logs = existingLogs.darkPageLogs || [];
193+
logs.push(logEntry);
194+
// Keep only last 100 entries to prevent storage overflow
195+
if (logs.length > 100) {
196+
logs.splice(0, logs.length - 100);
197+
}
198+
await browser.storage.local.set({ darkPageLogs: logs });
199+
} catch (error) {
200+
console.error('Failed to store dark page log:', error);
201+
}
202+
break;
203+
}
204+
case 'get_dark_page_logs': {
205+
try {
206+
const existingLogs = await browser.storage.local.get('darkPageLogs');
207+
const logs = existingLogs.darkPageLogs || [];
208+
// Find the most recent log entry for the given URL
209+
const urlLogs = logs.filter(
210+
(log: { url: string }) => log.url === message.key,
211+
);
212+
if (urlLogs.length > 0) {
213+
const mostRecent = urlLogs[urlLogs.length - 1];
214+
return mostRecent.isDark;
215+
}
216+
return null; // No logs found for this URL
217+
} catch (error) {
218+
console.error('Failed to retrieve dark page logs:', error);
219+
return null;
220+
}
221+
}
182222
default:
183223
console.error('Unknown message action:', message.action);
184224
break;
@@ -230,7 +270,7 @@ async function send_prefs(changes: {
230270
window.configured_tabs = ${JSON.stringify(configured_tabs)};
231271
window.rendered_stylesheets = ${JSON.stringify(rendered_stylesheets)};
232272
if (window.content_script_state !== 'registered_content_script_first') { /* #226 part 1 workaround */
233-
window.do_it(${JSON.stringify(changes)});
273+
console.log("sadm DOIT!111");window.do_it(${JSON.stringify(changes)});
234274
}
235275
`;
236276
for (const key of Object.keys(from_manifest)) {

src/common/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ export interface MethodMetadataWithStylesheets extends MethodMetadataBare {
107107
}
108108
export interface MethodExecutor {
109109
load_into_window(): void;
110-
unload_from_window(): void;
110+
unload_from_window(light?: boolean, callback?: () => void): void;
111111
}
112112
export interface MethodExecutorStatic {
113113
new (window: Window, options: AddonOptions): MethodExecutor;

src/content/dark-page-handler.ts

Lines changed: 74 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
import type {
2-
MethodIndex,
3-
MethodMetadataWithExecutors,
4-
} from '../common/types';
1+
import type { MethodIndex, MethodMetadataWithExecutors } from '../common/types';
52
import { generate_urls } from '../common/generate-urls';
63
import { isPageDark } from '../utils/isPageDark';
74
import { DISABLED_ID } from '../methods/methods';
@@ -21,46 +18,91 @@ export class DarkPageHandler {
2118
private disconnectAllObservers: () => void,
2219
) {}
2320

24-
async checkAndPersistDarkPage(): Promise<void> {
21+
async disableDarkMode() {
22+
this.disconnectAllObservers();
23+
const urlKey = generate_urls(window.document.documentURI)[0];
24+
const mergedConfigured = window.merged_configured;
25+
if (!mergedConfigured[urlKey] || mergedConfigured[urlKey] !== DISABLED_ID) {
26+
const tabId = await this.tabIdPromise;
27+
const configuredTabs = window.configured_tabs;
28+
const url = configuredTabs?.[tabId as number];
29+
await browser.runtime.sendMessage({
30+
action: 'set_configured_page',
31+
key: url,
32+
value: DISABLED_ID,
33+
});
34+
window.do_it({}, DISABLED_ID);
35+
}
36+
}
37+
38+
async checkAndPersistDarkPage(retry = false): Promise<void> {
2539
const isDefaultMethod =
2640
(await this.methodResolver.isDefaultMethod(window.document.documentURI))
2741
|| (await this.methodResolver.isDefaultMethod(window.location.hostname));
2842

29-
if (!isDefaultMethod) return;
43+
if (!isDefaultMethod) {
44+
return;
45+
}
3046

31-
const method = await this.methodResolver.getMethodForUrl(
47+
// Check if we have a previous log entry for this URL
48+
if (window.location.hostname) {
49+
let result = await browser.runtime.sendMessage({
50+
action: 'get_dark_page_logs',
51+
key: window.location.hostname,
52+
});
53+
if (result === undefined || result === null) {
54+
// Try again with documentURI if no result
55+
result = await browser.runtime.sendMessage({
56+
action: 'get_dark_page_logs',
57+
key: window.document.documentURI,
58+
});
59+
}
60+
if (result === false) {
61+
return;
62+
}
63+
}
64+
65+
const currentMethod = await this.methodResolver.getMethodForUrl(
3266
window.document.documentURI,
3367
);
34-
const sheets = document.querySelectorAll('.dblt-ykjmwcnxmi');
3568

36-
for (const sheet of sheets) {
37-
sheet?.setAttribute('media', '(not all)');
38-
}
69+
const method = await this.methodResolver.getMethodForUrl(
70+
window.document.documentURI,
71+
);
3972

40-
if (isPageDark(method)) {
41-
this.disconnectAllObservers();
73+
if (retry) {
74+
// If not the initial check do a simple check
75+
if (isPageDark(method)) {
76+
await this.disableDarkMode();
77+
}
78+
} else {
79+
const sheets = document.querySelectorAll('.dblt-ykjmwcnxmi');
4280
for (const sheet of sheets) {
43-
sheet?.setAttribute('media', '');
81+
sheet?.setAttribute('media', '(not all)');
4482
}
45-
const urlKey = generate_urls(window.document.documentURI)[0];
46-
const mergedConfigured = window.merged_configured;
47-
if (
48-
!mergedConfigured[urlKey]
49-
|| mergedConfigured[urlKey] !== DISABLED_ID
50-
) {
51-
const tabId = await this.tabIdPromise;
52-
const configuredTabs = window.configured_tabs;
53-
const url = configuredTabs?.[tabId as number];
54-
await browser.runtime.sendMessage({
55-
action: 'set_configured_page',
56-
key: url,
57-
value: DISABLED_ID,
83+
const keepFromBlinding = document.createElement('style');
84+
keepFromBlinding.appendChild(
85+
document.createTextNode('* { background: #000 !important; }'),
86+
);
87+
document.body.appendChild(keepFromBlinding);
88+
89+
await window.do_it({}, DISABLED_ID, async () => {
90+
requestAnimationFrame(async () => {
91+
if (isPageDark(method)) {
92+
await this.disableDarkMode();
93+
} else {
94+
await browser.runtime.sendMessage({
95+
action: 'log_dark_page_check',
96+
key: window.location.hostname,
97+
value: false,
98+
});
99+
for (const sheet of sheets) {
100+
sheet?.setAttribute('media', '');
101+
}
102+
await window.do_it({}, currentMethod.number);
103+
}
104+
keepFromBlinding.remove();
58105
});
59-
window.do_it({}, DISABLED_ID);
60-
}
61-
} else {
62-
sheets.forEach((link) => {
63-
link.setAttribute('media', '');
64106
});
65107
}
66108
}

src/content/dom-observer.ts

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
import { darkDatas, isPageDark } from '../utils/isPageDark';
22
import type { MethodIndex, MethodMetadataWithExecutors } from '../common/types';
33

4-
interface DomObserverDeps {
5-
methodResolver: {
6-
getMethodForUrl: (url: string, forceMethod?: MethodIndex) => Promise<MethodMetadataWithExecutors>;
7-
};
8-
}
9-
10-
export function createDomObserver(deps: DomObserverDeps) {
11-
const { methodResolver } = deps;
12-
let darkPageHandler: { checkAndPersistDarkPage: () => Promise<void> } | null = null;
4+
export function createDomObserver(methodResolver: {
5+
getMethodForUrl: (
6+
url: string,
7+
forceMethod?: MethodIndex,
8+
) => Promise<MethodMetadataWithExecutors>;
9+
}) {
10+
let darkPageHandler: {
11+
checkAndPersistDarkPage: (retry: boolean) => Promise<void>;
12+
} | null = null;
1313
const observers: MutationObserver[] = [];
1414
let disconnected = false;
1515
let timeout: number | undefined;
@@ -24,7 +24,7 @@ export function createDomObserver(deps: DomObserverDeps) {
2424

2525
function observeClassListChanges(): void {
2626
timeout = setTimeout(() => disconnectAll(), 45000);
27-
27+
2828
const callback = async (mutationsList: MutationRecord[]) => {
2929
for (const mutation of mutationsList) {
3030
if (
@@ -33,10 +33,12 @@ export function createDomObserver(deps: DomObserverDeps) {
3333
|| mutation.attributeName?.startsWith('data-'))
3434
) {
3535
if (darkPageHandler) {
36-
darkPageHandler.checkAndPersistDarkPage();
36+
darkPageHandler.checkAndPersistDarkPage(true);
3737
}
38-
const method = await methodResolver.getMethodForUrl(window.document.documentURI);
39-
if (isPageDark(method)) {
38+
const method = await methodResolver.getMethodForUrl(
39+
window.document.documentURI,
40+
);
41+
if (isPageDark(method, true)) {
4042
disconnectAll();
4143
}
4244
break;
@@ -65,7 +67,9 @@ export function createDomObserver(deps: DomObserverDeps) {
6567
}
6668
}
6769

68-
function setDarkPageHandler(handler: { checkAndPersistDarkPage: () => Promise<void> }): void {
70+
function setDarkPageHandler(handler: {
71+
checkAndPersistDarkPage: () => Promise<void>;
72+
}): void {
6973
darkPageHandler = handler;
7074
}
7175

@@ -74,4 +78,4 @@ export function createDomObserver(deps: DomObserverDeps) {
7478
observeClassListChanges,
7579
setDarkPageHandler,
7680
};
77-
}
81+
}

src/content/index.ts

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { createMethodResolver } from './method-resolver';
1111
import { DarkPageHandler } from './dark-page-handler';
1212
import { createDomObserver } from './dom-observer';
1313
import { createMessageHandler } from './message-handler';
14+
import { methods } from '../methods/methods-with-executors';
1415

1516
const tabId_promise = browser.runtime.sendMessage({ action: 'query_tabId' });
1617
const is_iframe = detectIframe();
@@ -29,7 +30,9 @@ declare global {
2930
do_it: (
3031
changes: { [s: string]: browser.storage.StorageChange },
3132
forceMethod?: MethodIndex,
33+
unloadCallback?: () => void,
3234
) => Promise<void>;
35+
_sadam_test: boolean | undefined;
3336
}
3437
}
3538

@@ -59,9 +62,7 @@ let current_method_promise: Promise<MethodMetadataWithExecutors> = new Promise(
5962
let current_method_executor: MethodExecutor | undefined;
6063

6164
// Initialize DOM observer first (needed for disconnectAll reference)
62-
const domObserver = createDomObserver({
63-
methodResolver,
64-
});
65+
const domObserver = createDomObserver(methodResolver);
6566

6667
// Initialize dark page handler
6768
const darkPageHandler = new DarkPageHandler(methodResolver, tabId_promise, () =>
@@ -81,12 +82,12 @@ window.do_it = async function do_it(
8182
[s: string]: browser.storage.StorageChange;
8283
},
8384
forceMethod?: MethodIndex,
85+
unloadCallback?: () => void,
8486
): Promise<void> {
8587
try {
86-
const new_method = await methodResolver.getMethodForUrl(
87-
window.document.documentURI,
88-
forceMethod,
89-
);
88+
const new_method = forceMethod
89+
? methods[forceMethod]
90+
: await methodResolver.getMethodForUrl(window.document.documentURI);
9091
if (resolve_current_method_promise) {
9192
resolve_current_method_promise(new_method);
9293
resolve_current_method_promise = null;
@@ -124,7 +125,9 @@ window.do_it = async function do_it(
124125
}
125126
}
126127
if (current_method_executor) {
127-
current_method_executor.unload_from_window();
128+
current_method_executor.unload_from_window(false, () => {
129+
unloadCallback?.();
130+
});
128131
current_method_executor = undefined;
129132
}
130133
if (new_method.executor) {

src/methods/executors/invert.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,15 @@ export class InvertMethod implements MethodExecutor {
2020
}
2121
}
2222

23-
unload_from_window() {
23+
unload_from_window(_light: boolean, callback?: () => void) {
2424
const el = this.window.document.querySelector(
2525
'#mybpwaycfxccmnp-dblt-backdrop-filter',
2626
);
2727
if (el !== null) {
2828
el.parentElement!.removeChild(el);
2929
}
30+
if (callback) {
31+
callback();
32+
}
3033
}
3134
}

src/methods/executors/stylesheet-color-processor.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,8 +188,13 @@ export class StylesheetColorProcessor
188188
lighten_or_darken_color(color_array, !is_dark_background, default_colors);
189189
}
190190

191-
unload_from_window() {
192-
StylesheetProcessorAbstract.prototype.unload_from_window.call(this, false);
191+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
192+
unload_from_window(_light = false, callback?: () => void) {
193+
StylesheetProcessorAbstract.prototype.unload_from_window.call(
194+
this,
195+
false,
196+
callback,
197+
);
193198
}
194199

195200
all_sheets_have_been_processed() {

0 commit comments

Comments
 (0)