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

feat(esl-event-listener): add condition descriptor property to legally prevent subscription #1958

Merged
merged 3 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions src/modules/esl-event-listener/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,30 @@ Here is the list of supported keys of `ESLEventDesriptor`:

Supports `PropertyProvider` to declare the computed value as well.

- #### `condition` key

<u>Type:</u> `bollean | PropertyProvider<boolean>`
<u>Default Value:</u> `true`
<u>Description:</u> the function predicate or boolean flag to check if the subscription should be created. Resolves right before the subscription.

Useful in combination with `@listen` decorator to declare subscriptions.

```typescript
class MyEl extends ESLBaseElement {
@attr() enabled = true;

@listen({event: 'click', condition: (that) => that.enabled})
onClick(e) {}

attributeChangedCallback(name, oldValue, newValue) {
if (name === 'enabled') {
ESLEventUtils.unsubscribe(this, this.onClick);
ESLEventUtils.subscribe(this, this.onClick);
}
}
}
```

- #### `capture` key

<u>Type:</u> `boolean`
Expand Down
13 changes: 0 additions & 13 deletions src/modules/esl-event-listener/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,3 @@ export * from './core/api';
export * from './core/targets/resize.target';
export * from './core/targets/decorated.target';
export * from './core/targets/swipe.target';

export type {
ESLListenerHandler,
ESLListenerCriteria,
ESLListenerDescriptor,
ESLListenerDescriptorFn,
ESLListenerDescriptorExt,
ESLListenerTarget,
ESLListenerDefinition
} from './core/types';
export type {
ESLEventListener,
} from './core/listener';
27 changes: 20 additions & 7 deletions src/modules/esl-event-listener/core/api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import {ExportNs} from '../../esl-utils/environment/export-ns';
import {resolveProperty} from '../../esl-utils/misc/functions';
import {dispatchCustomEvent} from '../../esl-utils/dom/events/misc';

import {ESLEventListener} from './listener';
import {getAutoDescriptors, isEventDescriptor, initDescriptor} from './descriptors';

Expand All @@ -9,6 +11,10 @@ import type {
ESLListenerDescriptorFn
ala-n marked this conversation as resolved.
Show resolved Hide resolved
} from './types';

// Export all related types
export type * from './types';
export type {ESLEventListener} from './listener';

@ExportNs('EventUtils')
export class ESLEventUtils {
/**
Expand Down Expand Up @@ -84,16 +90,14 @@ export class ESLEventUtils {
const descriptors = getAutoDescriptors(host);
// TODO: flatMap when ES5 will be out of support list
return descriptors.reduce(
(acc, desc) => acc.concat(ESLEventListener.subscribe(host, desc)),
(acc, desc) => acc.concat(ESLEventUtils.subscribe(host, desc)),
[] as ESLEventListener[]
);
}
if (typeof eventDesc === 'string') eventDesc = {event: eventDesc};
const listeners = ESLEventListener.subscribe(host, handler, eventDesc as ESLListenerDescriptor);
if (!listeners.length) {
const mergedDesc = Object.assign({}, eventDesc, {handler});
console.warn('[ESL]: Empty subscription %o', mergedDesc);
}
const desc = typeof eventDesc === 'string' ? {event: eventDesc} : eventDesc as ESLListenerDescriptor;
if (Object.hasOwnProperty.call(desc, 'condition') && !resolveProperty(desc.condition, host)) return [];
const listeners = ESLEventListener.subscribe(host, handler, desc);
if (!listeners.length) emptySubscriptionWarning(host, desc, handler);
return listeners;
}

Expand All @@ -105,5 +109,14 @@ export class ESLEventUtils {
public static unsubscribe = ESLEventListener.unsubscribe;
}

function emptySubscriptionWarning(host: object, descriptor: ESLListenerDescriptor, handler: ESLListenerHandler): void {
console.warn('[ESL]: Empty subscription %o', {
descriptor,
handler,
event: resolveProperty(descriptor.event, host),
target: resolveProperty(descriptor.target, host)
});
}

/** @deprecated alias for {@link ESLEventUtils} */
export const EventUtils = ESLEventUtils;
6 changes: 6 additions & 0 deletions src/modules/esl-event-listener/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ export type ESLListenerDescriptor<EType extends keyof ESLListenerEventMap = stri
*/
passive?: boolean;

/**
* Condition (boolean value or predicate) to apply subscription
ala-n marked this conversation as resolved.
Show resolved Hide resolved
* Rejected by condition subscription does not count as warning during subscription process
*/
condition?: boolean | PropertyProvider<boolean>;

/** A string (or provider function) representing CSS selector to check delegated event target (undefined (disabled) by default) */
selector?: string | PropertyProvider<string>;
/**
Expand Down
38 changes: 38 additions & 0 deletions src/modules/esl-event-listener/test/listener.condition.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {ESLEventUtils} from '../core/api';

describe('ESlEventListener subscription with conditional statement', () => {
const host = document.createElement('section');

afterEach(() => ESLEventUtils.unsubscribe(host));

test('ESLEventListener rejected by condition does not produce warning', () => {
const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
const handler = jest.fn();
ESLEventUtils.subscribe(host, {event: 'click', condition: false}, handler);
expect(warnSpy).not.toBeCalled();
});

test('ESLEventListener does not subscribe if condition is false', () => {
const handler = jest.fn();
const listeners = ESLEventUtils.subscribe(host, {event: 'click', condition: false}, handler);
expect(listeners.length).toBe(0);
});

test('ESLEventListener subscribes if condition is true', () => {
const handler = jest.fn();
const listeners = ESLEventUtils.subscribe(host, {event: 'click', condition: true}, handler);
expect(listeners.length).toBe(1);
});

test('ESLEventListener does not subscribes if condition is resolves to false', () => {
const handler = jest.fn();
const listeners = ESLEventUtils.subscribe(host, {event: 'click', condition: () => false}, handler);
expect(listeners.length).toBe(0);
});

test('ESLEventListener subscribes if condition is resolves to true', () => {
const handler = jest.fn();
const listeners = ESLEventUtils.subscribe(host, {event: 'click', condition: () => true}, handler);
expect(listeners.length).toBe(1);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import {ESLBaseElement} from '../../esl-base-element/core';
import {ESLEventUtils} from '../core/api';
import {listen} from '../../esl-utils/decorators/listen';

describe('ESLEventListener re-subscribtion usecase with condition', () => {
class TestSubsEl extends ESLBaseElement {
public static override is = 'test-subs-el';
public mockFn = jest.fn();

get enabled() {
return this.hasAttribute('enabled');
}
set enabled(value) {
this.$$attr('enabled', value);
this.$$off(this.onClick);
this.$$on(this.onClick);
}

@listen({event: 'click', condition: (that: TestSubsEl) => that.enabled})
onClick() {
this.mockFn();
}
}

TestSubsEl.register();

const host = TestSubsEl.create();
test('ESLEventListener initial subscription is rejected by condition', () => {
ala-n marked this conversation as resolved.
Show resolved Hide resolved
expect(ESLEventUtils.listeners(host).length).toBe(0);
host.click();
expect(host.mockFn).not.toBeCalled();
});

test('ESLEventListener subscription occurs after condition is resolved to true', () => {
host.enabled = true;
expect(ESLEventUtils.listeners(host).length).toBe(1);
host.click();
expect(host.mockFn).toBeCalled();
});

test('ESLEventListener subscription is removed after condition is resolved to false', () => {
host.enabled = false;
expect(ESLEventUtils.listeners(host).length).toBe(0);
host.click();
expect(host.mockFn).toBeCalledTimes(1);
});
});