UNPKG

luna-data-grid

Version:

Grid for displaying datasets

104 lines (103 loc) 3.27 kB
import Emitter from 'licia/Emitter'; import $ from 'licia/$'; import { classPrefix, getPlatform } from './util'; import each from 'licia/each'; import extend from 'licia/extend'; import defaults from 'licia/defaults'; import remove from 'licia/remove'; import theme from 'licia/theme'; import startWith from 'licia/startWith'; export default class Component extends Emitter { constructor(container, { compName }, { theme: t = 'light' } = {}) { super(); this.subComponents = []; this.theme = ''; this.onThemeChange = (t) => { if (this.options.theme === 'auto') { this.setTheme(t); } }; this.compName = compName; this.c = classPrefix(compName); this.options = {}; this.container = container; this.$container = $(container); this.$container.addClass([ `luna-${compName}`, this.c(`platform-${getPlatform()}`), ]); this.on('changeOption', (name, val) => { if (name === 'theme' && val) { let t = val; if (val === 'auto') { t = theme.get(); } this.setTheme(t); each(this.subComponents, (component) => component.setOption('theme', val)); } }); theme.on('change', this.onThemeChange); this.setOption('theme', t); } destroy() { this.destroySubComponents(); const { $container } = this; const classes = $container.attr('class'); each(classes.split(/\s+/), (c) => { if (startWith(c, `luna-${this.compName}`)) { $container.rmClass(c); } }); $container.html(''); this.emit('destroy'); this.removeAllListeners(); theme.off('change', this.onThemeChange); } setOption(name, val) { const options = this.options; let newOptions = {}; if (typeof name === 'string') { newOptions[name] = val; } else { newOptions = name; } each(newOptions, (val, name) => { const oldVal = options[name]; options[name] = val; if (val === oldVal) { return; } this.emit('changeOption', name, val, oldVal); }); } getOption(name) { return this.options[name]; } addSubComponent(component) { component.setOption('theme', this.options.theme); this.subComponents.push(component); } removeSubComponent(component) { remove(this.subComponents, (com) => com === component); } destroySubComponents() { each(this.subComponents, (component) => component.destroy()); this.subComponents = []; } initOptions(options, defs = {}) { defaults(options, defs); extend(this.options, options); } find(selector) { return this.$container.find(this.c(selector)); } setTheme(theme) { const { c, $container } = this; if (this.theme) { $container.rmClass(c(`theme-${this.theme}`)); } $container.addClass(c(`theme-${theme}`)); this.theme = theme; } }