Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#2581: add initialize trigger #2584

Merged
merged 3 commits into from
Feb 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/devTools/editor/tabs/trigger/TriggerConfiguration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ function supportsSelector(trigger: Trigger) {
}

function supportsTargetMode(trigger: Trigger) {
// XXX: why doesn't `appear` support target mode?
return supportsSelector(trigger) && trigger !== "appear";
}

Expand All @@ -50,6 +51,9 @@ const TriggerConfiguration: React.FC<{
if (!supportsSelector(nextTrigger)) {
setFieldValue("extensionPoint.definition.rootSelector", null);
setFieldValue("extensionPoint.definition.attachMode", null);
}

if (!supportsTargetMode(nextTrigger)) {
setFieldValue("extensionPoint.definition.targetMode", null);
}

Expand All @@ -75,6 +79,7 @@ const TriggerConfiguration: React.FC<{
>
<option value="load">Page Load</option>
<option value="interval">Interval</option>
<option value="initialize">Initialize</option>
<option value="appear">Appear</option>
<option value="click">Click</option>
<option value="dblclick">Double Click</option>
Expand Down
2 changes: 1 addition & 1 deletion src/devTools/editor/toolbar/ReloadToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function isPanelElement(element: FormState | null): boolean {
* @param element
*/
function isAutomaticTrigger(element: FormState): boolean {
const automatic = ["load", "appear", "interval"];
const automatic = ["load", "appear", "initialize", "interval"];
return (
element?.type === "trigger" &&
automatic.includes(element?.extensionPoint.definition.trigger)
Expand Down
148 changes: 79 additions & 69 deletions src/extensionPoints/triggerExtension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,10 @@ export type Trigger =
| "interval"
// `appear` is triggered when an element enters the user's viewport
| "appear"
| "click"
// `initialize` is triggered when an element is added to the DOM
| "initialize"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any other names? Maybe "add", "insert", "create"?

Copy link
Contributor Author

@twschiller twschiller Feb 4, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the configuration I'm going to keep as-is with initialize. That's how JS libraries seem to refer to it

We'll have to change the names of events in the page editor. E.g., non-developers don't know what a "blur" handler is

| "blur"
| "click"
| "dblclick"
| "mouseover"
| "change";
Expand Down Expand Up @@ -143,24 +145,6 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig

abstract get triggerSelector(): string | null;

/**
* Cancel awaiting the element during this.run()
* @private
*/
private cancelInitialWaitElements: (() => void) | null;

/**
* Cancel the initialization observer in "watch" attachMode.
* @private
*/
private cancelWatchNewElements: (() => void) | null;

/**
* Observer to watch for new elements to appear, or undefined if the trigger is not an `appear` trigger
* @private
*/
private appearObserver: IntersectionObserver | undefined;

/**
* Installed DOM event listeners, e.g., `click`
* @private
Expand All @@ -176,10 +160,10 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
private readonly boundEventHandler: JQuery.EventHandler<unknown>;

/**
* Controller to abort/cancel the currently running interval loop
* Controller to drop all listeners and timers
* @private
*/
private intervalController: AbortController | null;
private abortController = new AbortController();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a new JS feature by the way. You can initialize properties right here and they'll be called in the constructor. In most cases you can replace:

class {
	  constructor() {
		  this.prop = myInitialization()
	  }
}

with:

class {
	prop = myInitialization()
}

Copy link
Contributor

@fregante fregante Feb 4, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This actually allows for some coool usage like pre-bound methods:

class {
   constructor() {
     super(id, name, description, icon);
     // Bind so we can pass as callback
     this.boundEventHandler = this.eventHandler.bind(this);
   }
   eventHandler() {
     // Bind me please
   } 
}

becomes:

class {
   eventHandler = () => {
     // Look ma, no constructor()
   }
}

I'm waiting for the lint rule to materialize:sindresorhus/eslint-plugin-unicorn#314


protected constructor(
id: string,
Expand All @@ -188,8 +172,6 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
icon = "faBolt"
) {
super(id, name, description, icon);
this.cancelInitialWaitElements = null;
this.cancelWatchNewElements = null;

// Bind so we can pass as callback
this.boundEventHandler = this.eventHandler.bind(this);
Expand All @@ -199,6 +181,18 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
return this.isAvailable();
}

cancelObservers(): void {
// Inform registered listeners
this.abortController.abort();

// Allow new registrations
this.abortController = new AbortController();
}

addCancelHandler(callback: () => void): void {
this.abortController.signal.addEventListener("abort", callback);
}

removeExtensions(): void {
// NOP: the removeExtensions method doesn't need to unregister anything from the page because the
// observers/handlers are installed for the extensionPoint itself, not the extensions. I.e., there's a single
Expand All @@ -212,14 +206,7 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
});

// Clean up observers
this.cancelInitialWaitElements?.();
this.cancelWatchNewElements?.();
this.appearObserver?.disconnect();
this.appearObserver = null;
this.cancelInitialWaitElements = null;
this.cancelWatchNewElements = null;

this.clearInterval();
this.cancelObservers();

// Find the latest set of DOM elements and uninstall handlers
if (this.triggerSelector) {
Expand Down Expand Up @@ -353,7 +340,7 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
? awaitElementOnce(rootSelector)
: [document, noop];

this.cancelInitialWaitElements = cancelRun;
this.addCancelHandler(cancelRun);

try {
await rootPromise;
Expand All @@ -363,8 +350,6 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
}

throw error;
} finally {
this.cancelInitialWaitElements = null;
}

// AwaitElementOnce doesn't work with multiple elements. Get everything that's on the current page
Expand All @@ -377,21 +362,12 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
return $root;
}

private clearInterval() {
console.debug("triggerExtension:clearInterval");
this.intervalController?.abort();
this.intervalController = null;
}

private attachInterval() {
this.clearInterval();
this.cancelObservers();

if (this.intervalMillis > 0) {
this.logger.debug("Attaching interval trigger");

// Cast setInterval return value to number. For some reason Typescript is using the Node types for setInterval
const controller = new AbortController();

const intervalEffect = async () => {
const $root = await this.getRoot();
await Promise.allSettled(
Expand All @@ -402,12 +378,10 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
void interval({
intervalMillis: this.intervalMillis,
effectGenerator: intervalEffect,
signal: controller.signal,
signal: this.abortController.signal,
requestAnimationFrame: !this.allowBackground,
});

this.intervalController = controller;

console.debug("triggerExtension:attachInterval", {
intervalMillis: this.intervalMillis,
});
Expand All @@ -418,12 +392,46 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
}
}

private attachAppearTrigger($element: JQuery): void {
// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
private attachInitializeTrigger(
$element: JQuery<Document | HTMLElement>
): void {
this.cancelObservers();

// The caller will have already waited for the element. So $element will contain at least one element
if (this.attachMode === "once") {
for (const element of $element.get()) {
void this.runTrigger(element);
}

return;
}

const observer = initialize(
this.triggerSelector,
(index, element) => {
void this.runTrigger(element as HTMLElement).then((errors) => {
Comment on lines +411 to +412
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: We can use a regular async function here

Suggested change
(index, element) => {
void this.runTrigger(element as HTMLElement).then((errors) => {
async (index, element) => {
const errors = await this.runTrigger(element as HTMLElement);

if (errors.length > 0) {
console.error("An error occurred while running a trigger", {
errors,
});
notifyError("An error occurred while running a trigger");
}
});
},
// `target` is a required option
{ target: document }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the default

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apparently not… :(

);

this.appearObserver?.disconnect();
this.addCancelHandler(() => {
observer.disconnect();
});
}

private attachAppearTrigger($element: JQuery): void {
this.cancelObservers();

this.appearObserver = new IntersectionObserver(
// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
const appearObserver = new IntersectionObserver(
(entries) => {
for (const entry of entries.filter((x) => x.isIntersecting)) {
void this.runTrigger(entry.target as HTMLElement).then((errors) => {
Expand All @@ -444,7 +452,7 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
);

for (const element of $element) {
this.appearObserver.observe(element);
appearObserver.observe(element);
}

if (this.attachMode === "watch") {
Expand All @@ -455,15 +463,19 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
selector,
(index, element) => {
console.debug("initialize: %s", selector);
this.appearObserver.observe(element);
appearObserver.observe(element);
},
// `target` is a required option
{ target: document }
);

this.cancelWatchNewElements = mutationObserver.disconnect.bind(
mutationObserver
);
this.addCancelHandler(() => {
mutationObserver.disconnect();
});
}

this.addCancelHandler(() => {
appearObserver.disconnect();
});
}

private attachDOMTrigger(
Expand Down Expand Up @@ -498,8 +510,7 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
if (watch) {
// Clear out the existing mutation observer on SPA navigation events.
// On mutation events, this watch branch is not executed because the mutation handler below passes `watch: false`
this.cancelWatchNewElements?.();
this.cancelWatchNewElements = null;
this.cancelObservers();

// Watch for new elements on the page
const mutationObserver = initialize(
Expand All @@ -508,11 +519,12 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
// Already watching, so don't re-watch on the recursive call
this.attachDOMTrigger($(element as HTMLElement), { watch: false });
},
// `target` is a required option
{ target: document }
);
this.cancelWatchNewElements = mutationObserver.disconnect.bind(
mutationObserver
);
this.addCancelHandler(() => {
mutationObserver.disconnect();
});
}
}

Expand All @@ -524,13 +536,6 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
}
}

private cancelObservers() {
this.cancelInitialWaitElements?.();
this.cancelWatchNewElements?.();
this.cancelInitialWaitElements = null;
this.cancelWatchNewElements = null;
}

async run(): Promise<void> {
this.cancelObservers();

Expand All @@ -550,6 +555,11 @@ export abstract class TriggerExtensionPoint extends ExtensionPoint<TriggerConfig
break;
}

case "initialize": {
this.attachInitializeTrigger($root);
break;
}

case "appear": {
this.assertElement($root);
this.attachAppearTrigger($root);
Expand Down