UNPKG

@awcrotwell/motion

Version:

Motion allows you to build reactive, real-time frontend UI components in your Amber application using pure Crystal that are reusable, testable & encapsulated. For brevity, we will call them MotionComponents.

73 lines (72 loc) 2.63 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const Subscription_1 = __importDefault(require("./Subscription")); class Subscriptions { constructor(consumer) { this.consumer = consumer; this.subscriptions = []; } create(channelName, mixin) { const channel = channelName; const params = typeof channel === 'object' ? channel : { channel }; const subscription = new Subscription_1.default(this.consumer, params, mixin); return this.add(subscription); } add(subscription) { this.subscriptions.push(subscription); this.consumer.ensureActiveConnection(); this.notify(subscription, 'initialized'); this.joinChannel(subscription); return subscription; } remove(subscription) { this.forget(subscription); if (!this.findAll(subscription.identifier).length) { this.sendCommand(subscription, 'unsubscribe'); } return subscription; } reject(identifier) { return this.findAll(identifier).map((subscription) => { this.forget(subscription); this.notify(subscription, 'rejected'); return subscription; }); } forget(subscription) { this.subscriptions = this.subscriptions.filter((s) => s !== subscription); return subscription; } findAll(identifier) { return this.subscriptions.filter((s) => s.identifier === identifier); } reload() { return this.subscriptions.map((subscription) => this.sendCommand(subscription, 'subscribe')); } notifyAll(callbackName, ...args) { return this.subscriptions.map((subscription) => this.notify(subscription, callbackName, ...args)); } notify(subscription, callbackName, ...args) { let subscriptions; if (typeof subscription === 'string') { subscriptions = this.findAll(subscription); } else { subscriptions = [subscription]; } return subscriptions.map((sub) => typeof sub[callbackName] === 'function' ? sub[callbackName](...args) : undefined); } sendCommand(subscription, command) { const { identifier, channel } = subscription; return this.consumer.send({ command, identifier, channel }); } joinChannel(subscription) { return this.consumer.joinChannel(subscription); } } exports.default = Subscriptions;