MCPcopy
hub / github.com/darkreader/darkreader / deepWatchForInlineStyles

Function deepWatchForInlineStyles

src/inject/dynamic-theme/inline-style.ts:177–273  ·  view source on GitHub ↗
(
    root: Document | ShadowRoot,
    elementStyleDidChange: (element: HTMLElement) => void,
    shadowRootDiscovered: (root: ShadowRoot) => void,
)

Source from the content-addressed store, hash-verified

175}
176
177function deepWatchForInlineStyles(
178 root: Document | ShadowRoot,
179 elementStyleDidChange: (element: HTMLElement) => void,
180 shadowRootDiscovered: (root: ShadowRoot) => void,
181): void {
182 if (treeObservers.has(root)) {
183 treeObservers.get(root)!.disconnect();
184 attrObservers.get(root)!.disconnect();
185 }
186
187 const discoveredNodes = new WeakSet<Node>();
188
189 function discoverNodes(node: Node) {
190 getInlineStyleElements(node).forEach((el: HTMLElement) => {
191 if (discoveredNodes.has(el)) {
192 return;
193 }
194 discoveredNodes.add(el);
195 elementStyleDidChange(el);
196 });
197 iterateShadowHosts(node, (n) => {
198 if (discoveredNodes.has(n)) {
199 return;
200 }
201 discoveredNodes.add(n);
202 shadowRootDiscovered(n.shadowRoot!);
203 deepWatchForInlineStyles(n.shadowRoot!, elementStyleDidChange, shadowRootDiscovered);
204 });
205 variablesStore.matchVariablesAndDependents();
206 }
207
208 const treeObserver = createOptimizedTreeObserver(root, {
209 onMinorMutations: (_root, {additions}) => {
210 additions.forEach((added) => discoverNodes(added));
211 },
212 onHugeMutations: () => {
213 discoverNodes(root);
214 },
215 });
216 treeObservers.set(root, treeObserver);
217
218 let attemptCount = 0;
219 let start: number | null = null;
220 const ATTEMPTS_INTERVAL = getDuration({seconds: 10});
221 const RETRY_TIMEOUT = getDuration({seconds: 2});
222 const MAX_ATTEMPTS_COUNT = 50;
223 let cache: MutationRecord[] = [];
224 let timeoutId: ReturnType<typeof setTimeout> | null = null;
225
226 const handleAttributeMutations = throttle((mutations: MutationRecord[]) => {
227 const handledTargets = new Set<Node>();
228 mutations.forEach((m) => {
229 const target = m.target as HTMLElement;
230 if (handledTargets.has(target)) {
231 return;
232 }
233 if (INLINE_STYLE_ATTRS.includes(m.attributeName!)) {
234 handledTargets.add(target);

Callers 2

watchForInlineStylesFunction · 0.85
discoverNodesFunction · 0.85

Calls 11

getDurationFunction · 0.90
throttleFunction · 0.90
discoverNodesFunction · 0.85
handleAttributeMutationsFunction · 0.85
disconnectMethod · 0.80
addMethod · 0.80
hasMethod · 0.65
getMethod · 0.65
setMethod · 0.65

Tested by

no test coverage detected