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

US134384 - Add new subscription controllers #1927

Merged
merged 7 commits into from
Dec 10, 2021
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ npm install @brightspace-ui/core
* [Tooltip](components/tooltip/): tooltip components
* [Typography](components/typography/): typography styles and components
* [Validation](components/validation/): plugin custom validation logic to native and custom form elements
* Controllers
* [Subscriber](controllers/subscriber/): for managing a registry of subscribers in a many-to-many relationship
* Directives
* [Animate](directives/animate/): animate showing, hiding and removal of elements
* Helpers
Expand Down
177 changes: 177 additions & 0 deletions controllers/subscriber/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# Subscriber Controllers

The `SubscriberRegistryController` and the corresponding `*SubscriberController`s can be used to create a subscription system within your app. Components can setup a subscriber registry instance to keep track of all components subscribed to them with the `SubscriberRegistryController`. Whenever it makes sense to do so, they can iterate over their subscribers to perform some action, update them with new data, etc. Components can subscribe themselves to different registries using the `IdSubscriberController` or the `EventSubscriberController`. This system supports a many-to-many relationship - registry components can contain multiple registry instances with multiple subscribers in each, and subscriber components can subscribe to multiple different registries.

## Usage

Create an instance of the `SubscriberRegistryController` in the component that will be responsible for providing some data or performing some function on all its subscribers:

```js
import { SubscriberRegistryController } from '@brightspace-ui/core/controllers/subscriber/subscriberControllers.js';

class CableSubscription extends LitElement {
constructor() {
super();
this._sportsSubscribers = new SubscriberRegistryController(this,
{ onSubscribe: this._unlockSportsChannels.bind(this) },
{ eventName: 'd2l-channels-subscribe-sports' }
);

this._movieSubscribers = new SubscriberRegistryController(this, {},
{ onSubscribe: this._unlockMovieChannels.bind(this), updateSubscribers: this._sendMovieGuide.bind(this) },
{ eventName: 'd2l-channels-subscribe-movies' }
);

// This controller only supports registering by id - no event is needed
this._kidsChannelSubscribers = new SubscriberRegistryController(this,
{ onSubscribe: this._unlockKidsChannels.bind(this) }, {});
}

getController(controllerId) {
if (controllerId === 'sports') {
return this._sportsSubscribers;
} else if (controllerId === 'movies') {
return this._movieSubscribers;
} else if (controllerId === 'kids') {
return this._kidsChannelSubscribers;
}
}

_sendMovieGuide(subscribers) {
subscribers.forEach(subscriber => subscriber.updateGuide(new MovieGuide(new Date().getMonth())));
}

_unlockMovieChannels(subscriber) {
subscriber.addChannels([330, 331, 332, 333, 334, 335]);
}

...
}
```

When creating the controller, you can pass in callbacks to run whenever a subscriber is added, removed, or `updateSubscribers` is called (which handles request debouncing for you).

The `*subscriberController`s will use a `getController` method that needs to be exposed on the registry component. If you only have one `SubscriberRegistryController` you can simple return that. If you have multiple, you will return the proper controller depending on the id the subscriber component passed to you.

Once this has been set up, components can subscribe to particular registries two different ways:
1. Using a matching event name with `EventSubscriberController`. The component will need to be a child of the registry component for this to work.
2. By pointing to the registry component's id with `IdSubscriberController`. The component will need to be in the same DOM scope as the registry component for this to work.

Like the `SubscriberRegistryController`, these `*subscriberController`s take optional callbacks to throw at different points in the subscription process.

```js
import { EventSubscriberController, IdSubscriberController } from '@brightspace-ui/core/controllers/subscriber/subscriberControllers.js';

class GeneralViewer extends LitElement {
static get properties() {
return {
_subscribedChannels: { type: Object }
};
}

constructor() {
super();
this._subscribedChannels = new Set();

this._sportsSubscription = new EventSubscriberController(this,
{ onError: this._onSportsError.bind(this) }
{ eventName: 'd2l-channels-subscribe-sports', controllerId: 'sports' }
);

this._movieSubscription = new EventSubscriberController(this, {},
{ eventName: 'd2l-channels-subscribe-movies', controllerId: 'movies' }
);
}

addChannels(channels) {
channels.forEach(channel => this._subscribedChannels.add(channel));
}

_onSportsError() {
throw new Error('Where are the sports?');
}

...
}

class YoungerViewer extends LitElement {
static get properties() {
return {
for: { type: String },
_subscribedChannels: { type: Object }
};
}

constructor() {
super();
this._subscribedChannels = new Set();

this._kidsSubscription = new IdSubscriberController(this,
{ onSubscribe: this._onSubscribe.bind(this), onUnsubscribe: this._onUnsubscribe.bind(this) },
{ idPropertyName: 'for', controllerId: 'kids' }
);
}

addChannels(channels) {
channels.forEach(channel => this._subscribedChannels.add(channel));
}

_onSubscribe(cableProvider) {
console.log(`Subscribed with ${cableProvider.id} successfully.`);
}

_onUnsubscribe(cableProviderId) {
console.log(`Looks like ${cableProviderId} is having an outage again.`);
}

...
}
```

An example of what this could look like altogether:
```html
<cable-subscription id="rogers">
<general-viewer></general-viewer>
</cable-subscription>
<younger-viewer for="rogers"></younger-viewer>
```

NOTE: Until we are on Lit 2, the controller lifecycle events will need to be manually called:
```js
connectedCallback() {
super.connectedCallback();
if (this._subscriptionController) this._subscriptionController.hostConnected();
}

disconnectedCallback() {
super.disconnectedCallback();
if (this._subscriptionController) this._subscriptionController.hostDisconnected();
}

updated(changedProperties) {
super.updated(changedProperties);
if (this._subscriptionController) this._subscriptionController.hostUpdated(changedProperties);
}
```

## Available Callbacks

### SubscriberRegistryController
| Callback Name | Description | Passed to Callback |
|---|---|---|
| `onSubscribe` | Runs whenever a new subscriber is added | Subscriber that was just subscribed |
| `onUnsubscribe` | Runs whenever a subscriber is removed | Subscriber that was just unsubscribed |
| `updateSubscribers` | Runs whenever `updateSubscribers` is called on the controller, handles debouncing requests for you | Map of all current subscribers |

### EventSubscriberController
| Callback Name | Description | Passed to Callback |
|---|---|---|
| `onSubscribe` | Runs when successfully subscribed to a registry component | Registry that was just subscribed to |
| `onError` | Runs if the event was unacknowledged and no registry component was found | None |

### IdSubscriberController
| Callback Name | Description | Passed to Callback |
|---|---|---|
| `onSubscribe` | Runs whenever a registry component is successfully subscribed to | Registry that was just subscribed to |
| `onUnsubscribe` | Runs whenever we unsubscribe to a registry (because it is now gone, or its id was removed from the id property list) | Id of the registry that was just unsubscribed to |
| `onError` | Runs if no registry component was found for an id | Id of the registry we do not have a component for |
180 changes: 180 additions & 0 deletions controllers/subscriber/subscriberControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { cssEscape } from '../../helpers/dom.js';

export class SubscriberRegistryController {

constructor(host, callbacks, options) {
this._host = host;
this._callbacks = callbacks || {};
this._eventName = options && options.eventName;
this._subscribers = new Map();

this._handleSubscribe = this._handleSubscribe.bind(this);
}

get subscribers() {
return this._subscribers;
}

hostConnected() {
if (this._eventName) this._host.addEventListener(this._eventName, this._handleSubscribe);
}

hostDisconnected() {
if (this._eventName) this._host.removeEventListener(this._eventName, this._handleSubscribe);
}

subscribe(target) {
if (this._subscribers.has(target)) return;
this._subscribers.set(target, target);
if (this._callbacks.onSubscribe) this._callbacks.onSubscribe(target);
}

unsubscribe(target) {
this._subscribers.delete(target);
if (this._callbacks.onUnsubscribe) this._callbacks.onUnsubscribe(target);
}

updateSubscribers() {
if (!this._subscribers || this._subscribers.size === 0) return;
if (!this._callbacks.updateSubscribers) return;

// debounce the updates
if (this._updateSubscribersRequested) return;

this._updateSubscribersRequested = true;
setTimeout(() => {
this._callbacks.updateSubscribers(this._subscribers);
this._updateSubscribersRequested = false;
}, 0);
}

_handleSubscribe(e) {
e.stopPropagation();
e.detail.registry = this._host;
const target = e.composedPath()[0];
this.subscribe(target);
}
}

export class EventSubscriberController {

constructor(host, callbacks, options) {
this._host = host;
this._callbacks = callbacks || {};
this._eventName = options && options.eventName;
this._controllerId = options && options.controllerId;
this._registry = null;
}

get registry() {
return this._registry;
}

hostConnected() {
// delay subscription otherwise import/upgrade order can cause selection mixin to miss event
requestAnimationFrame(() => {
const evt = new CustomEvent(this._eventName, {
bubbles: true,
composed: true,
detail: {}
});
this._host.dispatchEvent(evt);
this._registry = evt.detail.registry;

if (!this._registry) {
if (this._callbacks.onError) this._callbacks.onError();
return;
}
if (this._callbacks.onSubscribe) this._callbacks.onSubscribe(this._registry);
});
}

hostDisconnected() {
if (this._registry) this._registry.getController(this._controllerId).unsubscribe(this._host);
}

}

export class IdSubscriberController {

constructor(host, callbacks, options) {
this._host = host;
this._callbacks = callbacks || {};
this._idPropertyName = options && options.idPropertyName;
this._controllerId = options && options.controllerId;
this._registries = new Map();
this._timeouts = new Set();
}

get registries() {
return Array.from(this._registries.values());
}

hostDisconnected() {
if (this._registryObserver) this._registryObserver.disconnect();
this._timeouts.forEach(timeoutId => clearTimeout(timeoutId));
this._registries.forEach(registry => {
registry.getController(this._controllerId).unsubscribe(this._host);
});
}

hostUpdated(changedProperties) {
if (!changedProperties.has(this._idPropertyName)) return;

if (this._registryObserver) this._registryObserver.disconnect();
this._registries.forEach(registry => {
registry.getController(this._controllerId).unsubscribe(this._host);
if (this._callbacks.onUnsubscribe) this._callbacks.onUnsubscribe(registry.id);
});
this._registries = new Map();

this._updateRegistries();

this._registryObserver = new MutationObserver(() => {
this._updateRegistries();
});

this._registryObserver.observe(this._host.getRootNode(), {
childList: true,
subtree: true
});
}

_updateRegistries() {
let registryIds = this._host[this._idPropertyName];
if (!registryIds) return;

registryIds = registryIds.split(' ');
registryIds.forEach(registryId => {
this._updateRegistry(registryId, 0);
});
}

_updateRegistry(registryId, elapsedTime) {
let registryComponent = this._host.getRootNode().querySelector(`#${cssEscape(registryId)}`);
if (!registryComponent && this._callbacks.onError) {
if (elapsedTime < 3000) {
const timeoutId = setTimeout(() => {
this._timeouts.delete(timeoutId);
this._updateRegistry(registryId, elapsedTime + 100);
}, 100);
this._timeouts.add(timeoutId);
} else {
this._callbacks.onError(registryId);
}
}

registryComponent = registryComponent || undefined;
if (this._registries.get(registryId) === registryComponent) return;

if (registryComponent) {
registryComponent.getController(this._controllerId).subscribe(this._host);
this._registries.set(registryId, registryComponent);
if (this._callbacks.onSubscribe) this._callbacks.onSubscribe(registryComponent);
} else {
this._registries.delete(registryId);
if (this._callbacks.onUnsubscribe) this._callbacks.onUnsubscribe(registryId);
}
}

}
3 changes: 3 additions & 0 deletions controllers/subscriber/test/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "brightspace/open-wc-testing-config"
}
Loading