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.

68 lines (67 loc) 2.35 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const Amber_1 = __importDefault(require("./Amber")); class Connection { constructor(consumer) { this.socket = new Amber_1.default.Socket('/cable'); this.connectionPromise = this.open.call(this); this.consumer = consumer; this.subscriptions = this.consumer.subscriptions; this.disconnected = true; this.channel = undefined; this.channels = []; this.reopenDelay = 500; this.handleWindowOffload(); } send(data) { this.connectionPromise.then(() => { const topic = data.identifier.channel; this.channels.forEach(channel => { if (channel.topic === topic) { channel.push('message_new', data); } }); }); } joinChannel(data) { this.connectionPromise.then(() => { data.connected(); this.channel = this.socket.channel(data.channel); this.channels.push(this.channel); this.channel.join({ identifier: data.identifier }); this.channel.on('message_new', (payload) => { data.received(payload.html); }); this.channel.on('leave', (payload) => { console.log(payload); }); }); } open() { return this.socket.connect(); } close({ allowReconnect } = { allowReconnect: true }) { return this.socket.disconnect(); } /* eslint-disable class-methods-use-this */ isActive() { // eslint-disable-next-line no-console console.log('TODO: Connect#isActive is always true'); return true; } /* eslint-enable class-methods-use-this */ // For some reason the documentLifecycle promise wasn't ever hitting this // Check client & client#shutdown for more info handleWindowOffload() { window.addEventListener('beforeunload', this.shutdown.bind(this)); } shutdown() { this.channels.forEach(channel => { channel.push('unsubscribe', { command: 'unsubscribe' }); }); } } exports.default = Connection;