MCPcopy
hub / github.com/lit/lit / MutationController

Class MutationController

packages/labs/observers/src/mutation-controller.ts:63–167  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

61 * The controller's `value` is usable during the host's update cycle.
62 */
63export class MutationController<T = unknown> implements ReactiveController {
64 private _host: ReactiveControllerHost;
65 private _targets = new Set<Element>();
66 private _config: MutationObserverInit;
67 private _observer!: MutationObserver;
68 private _skipInitial = false;
69 /**
70 * Flag used to help manage calling the `callback` when observe is called
71 * in addition to when a mutation occurs. This is done to help setup initial
72 * state and is performed async by requesting a host update and calling
73 * `handleChanges` once by checking and then resetting this flag.
74 */
75 private _unobservedUpdate = false;
76 /**
77 * The result of processing the observer's changes via the `callback`
78 * function.
79 */
80 value?: T;
81 /**
82 * Function that returns a value processed from the observer's changes.
83 * The result is stored in the `value` property.
84 */
85 callback?: MutationValueCallback<T>;
86 constructor(
87 host: ReactiveControllerHost & Element,
88 {target, config, callback, skipInitial}: MutationControllerConfig<T>
89 ) {
90 this._host = host;
91 // Target defaults to `host` unless explicitly `null`.
92 if (target !== null) {
93 this._targets.add(target ?? host);
94 }
95 this._config = config;
96 this._skipInitial = skipInitial ?? this._skipInitial;
97 this.callback = callback;
98 if (isServer) {
99 return;
100 }
101 // Check browser support.
102 if (!window.MutationObserver) {
103 console.warn(
104 `MutationController error: browser does not support MutationObserver.`
105 );
106 return;
107 }
108 this._observer = new MutationObserver((records: MutationRecord[]) => {
109 this.handleChanges(records);
110 this._host.requestUpdate();
111 });
112 host.addController(this);
113 }
114
115 /**
116 * Process the observer's changes with the controller's `callback`
117 * function to produce a result stored in the `value` property.
118 */
119 protected handleChanges(records: MutationRecord[]) {
120 this.value = this.callback?.(records, this._observer);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…