import Reflux from 'reflux'; import uuid from 'node-uuid'; export default Reflux.createStore({ sessionKey: null, init: function() { this.sessionKey = window.localStorage.getItem('sessionKey'); if(!this.sessionKey) { this.sessionKey = uuid.v4(); window.localStorage.setItem('sessionKey', this.sessionKey); } } });
import Reflux from "reflux" import {SetSearchProp} from "actions/LandingPageActions.js" export default Reflux.createStore({ init: function () { this.searchProps = {}; this.listenTo(SetSearchProp, "onSetSearchProp"); }, onSetSearchProp: function (propName, prop) { this.searchProps[propName] = prop; this.validate(); }, validate: function () { let isValid = false; let searchProps = this.searchProps; if(searchProps.departure && searchProps.arrival && searchProps.flightDate) isValid = true; this.trigger({isValid: isValid}); } })
module.exports = tableStore = Reflux.createStore({ listenables: actions, init() { this.rows = {}; }, onLoadTable(name, payload) { var key = payload.key || "", keyParts = key.split("-"), startKey, endKey; if (keyParts.length == 1) { startKey = endKey = keyParts[0]; } else { startKey = keyParts[0]; endKey = keyParts[1]; } payload.startKey = startKey; payload.endKey = endKey; request.get('/api/tables/' + name, payload) .end(function(err, res){ if (err) { actions.loadTable.failed(err); } else { actions.loadTable.completed(res.body); } }) }, onLoadTableCompleted(payload) { this.trigger(payload); } });
var ModalProgressStore = Reflux.createStore({ model: defaultModel, listenables: ModalProgressActions, onShowModalProgress: function(message, delay){ if(!this.model.isModalOpen){ this.model.seconds = 0; var f = (function(self){ return function(){ self.model.messageArray = null; self.model.message = message; self.model.isModalOpen = true; self.trigger(self.model); }; }(this)); if(delay && delay > 0){ this._modalProgressTimeout = setTimeout(f, delay); } else { f(); } } }, onSecondsIncrement: function(){ this.model.seconds += 1; this.trigger(this.model); }, onShowModalMessageArray: function(message){ this.model.messageArray = message; this.model.message = null; this.model.isModalOpen = true; this.trigger(this.model); }, onUpdateMessage: function(message){ this.model.message = message; this.trigger(this.model); }, onHideModalProgress: function(){ if(this._modalProgressTimeout){ clearTimeout(this._modalProgressTimeout); this._modalProgressTimeout = null; } if(this.model.isModalOpen){ this.model.isModalOpen = false; this.trigger(this.model); } }, onToggleModalProgress: function(){ if(this._modalProgressTimeout){ clearTimeout(this._modalProgressTimeout); this._modalProgressTimeout = null; } this.model.isModalOpen = !this.model.isModalOpen; this.trigger(this.model); } });
export default Reflux.createStore({ listenables: TagAction, onSelect(id){ let url = '/admin/api/tag'; if(id){ url += '/' + id; } let req = superagent.get(url); return firekylin.request(req).then( data => this.trigger(data, id ? 'getTagInfo' : 'getTagList') ); }, onSave(data){ let id = data.id; delete data.id; let url = '/admin/api/tag'; if(id){ url += '/' + id + '?method=put'; } let req = superagent.post(url); req.type('form').send(data); return firekylin.request(req).then( data => { if(data.id && data.id.type === 'exist') { this.trigger('TAG_EXIST', 'saveTagFail'); } else this.trigger(data, 'saveTagSuccess'); }, err => this.trigger(err, 'saveTagFail') ); }, onDelete(id) { let url = '/admin/api/tag'; if(id) { url += '/' + id + '?method=delete'; } let req = superagent.post(url); return firekylin.request(req).then( data => this.trigger(data, 'deleteTagSuccess'), err => this.trigger(err, 'deleteTagFail') ); } })
const LdapGroupsStore = Reflux.createStore({ listenables: [LdapGroupsActions], sourceUrl: '/system/ldap', groups: undefined, mapping: undefined, getInitialState() { return {groups: this.groups, mapping: this.mapping}; }, loadGroups() { const url = URLUtils.qualifyUrl(`${this.sourceUrl}/groups`); const promise = fetch('GET', url); promise.then( response => { this.groups = response; this.trigger({groups: this.groups}); }, error => { if (error.additional.status !== 400) { UserNotification.error(`Loading LDAP group list failed with status: ${error}`, 'Could not load LDAP group list'); } } ); LdapGroupsActions.loadGroups.promise(promise); }, loadMapping() { const url = URLUtils.qualifyUrl(`${this.sourceUrl}/settings/groups`); const promise = fetch('GET', url); promise.then( response => { this.mapping = response; this.trigger({mapping: this.mapping}); }, error => { UserNotification.error(`Loading LDAP group mapping failed with status: ${error}`, 'Could not load LDAP group mapping'); } ); LdapGroupsActions.loadMapping.promise(promise); }, saveMapping(mapping) { const url = URLUtils.qualifyUrl(`${this.sourceUrl}/settings/groups`); const promise = fetch('PUT', url, mapping); promise.then( () => { this.loadMapping(); UserNotification.success('LDAP group mapping successfully updated.'); }, error => { UserNotification.error(`Updating LDAP group mapping failed with status: ${error}`, 'Could not update LDAP group mapping'); } ); LdapGroupsActions.saveMapping.promise(promise); }, });
let ConversationsStore = Reflux.createStore({ init () { this.listenTo(Actions.connection, this.onConnection); this.listenTo(Actions.messageReceived, this.onMessageReceived); this.listenTo(Actions.messageMarked, this.onMessageMarked); this.listenTo(Actions.sendMessage, this.onSendMessage); this.listenTo(Actions.sendStateChange, this.onSendStateChange); this.listenTo(Actions.logout, this.onLogout); this.listenTo(Actions.markMessage, this.onMarkMessage); this.listenTo(Actions.confirmMessageDelivery, this.onConfirmMessageDelivery); this.listenTo(Actions.clearChat, this.onClearChat); this.getInitialState(); }, onConnection (connection) { this.connection = connection; }, onMessageReceived (stanza) { if (stanza.querySelectorAll('forwarded').length > 0) { // XEP-0280: Message Carbons stanza = stanza.querySelector('forwarded message'); } let from = stanza.getAttribute('from'); let to = stanza.getAttribute('to'); let fromJID = Strophe.getBareJidFromJid(from); let toJID = Strophe.getBareJidFromJid(to); let threadJID = fromJID; let msgID = stanza.getAttribute('id'); if (fromJID === Strophe.getBareJidFromJid(this.connection.jid)) { // XEP-0280: Message Carbons threadJID = toJID; } // Chat State Notification let states = stanza.querySelectorAll('active, composing, inactive, paused, gone'); if (states.length > 0) { Actions.rosterStateChange(fromJID, states[0].tagName); } // Chat Markers and Message Delivery Receipts let markers = stanza.querySelectorAll('received, displayed, acknowledged'); if (markers.length > 0) { Actions.messageMarked(threadJID, markers[0].getAttribute('id'), markers[0].tagName); } if (stanza.querySelectorAll('body, sticker').length === 0) { return; } let body; let type; if (stanza.querySelectorAll('sticker').length > 0) { body = stanza.querySelector('sticker').getAttribute('uid'); type = 'sticker'; } else { body = stanza.querySelector('body').textContent; type = 'text'; } let timestamp = moment().format(); if (stanza.querySelectorAll('delay').length > 0) { timestamp = stanza.querySelector('delay').getAttribute('stamp'); } this.messages = this.messages.update(threadJID, Immutable.List(), function (val) { return val.push(Immutable.Map({ id: msgID, from: fromJID, body: body, time: timestamp, type: type, status: 'received', })); }); this.trigger(this.messages); this._persist(); if (stanza.querySelectorAll('markable').length > 0) { // Chat Markers Actions.markMessage.triggerAsync(fromJID, msgID, 'received'); } if (stanza.querySelectorAll('request').length > 0) { // Message Delivery Receipts Actions.confirmMessageDelivery.triggerAsync(fromJID, msgID); } }, onMessageMarked (jid, id, marker) { id = id * 1; this.messages = this.messages.update(jid, Immutable.List(), function (val) { return val.map(function (item) { if (item.get('from') !== jid && item.get('id', 0) <= id && MARKERS[item.get('status')] < MARKERS[marker]) { return item.set('status', marker); } else { return item; } }); }); this.trigger(this.messages); this._persist(); }, onMarkMessage (jid, id, marker) { let sender = this.connection.jid; let stanza = $msg({ from: sender, to: jid, }).c(marker, { xmlns: Strophe.NS.CHAT_MARKERS, id: id, }).up(); this.connection.send(stanza); this.messages = this.messages.update(jid, Immutable.List(), function (val) { return val.map(function (item) { if (item.get('from') === jid && item.get('id') === id) { return item.set('status', marker); } else { return item; } }); }); this.trigger(this.messages); this._persist(); }, onConfirmMessageDelivery (jid, id) { let sender = this.connection.jid; let stanza = $msg({ from: sender, to: jid, }).c('received', { xmlns: Strophe.NS.RECEIPTS, id: id, }).up(); this.connection.send(stanza); this.messages = this.messages.update(jid, Immutable.List(), function (val) { return val.map(function (item) { if (item.get('from') === jid && item.get('id') === id) { return item.set('status', 'received'); } else { return item; } }); }); this.trigger(this.messages); this._persist(); }, onSendMessage (jid, body, type) { let sender = this.connection.jid; let msgID = this.messages.get(jid, Immutable.List()).size; let stanza = $msg({ from: sender, to: jid, type: 'chat', id: msgID, }); if (type === 'text') { stanza = stanza.c('body').t(body).up().c('active', { xmlns: Strophe.NS.CHATSTATES, }).up(); } else if (type === 'sticker') { body = [body.org, body.pack, body.id].join('.'); stanza = stanza.c('sticker', { xmlns: Strophe.NS.STICKERS, uid: body, }).up(); } stanza = stanza.c('markable', { xmlns: Strophe.NS.CHAT_MARKERS }).up(); stanza = stanza.c('request', { xmlns: Strophe.NS.RECEIPTS }).up(); this.connection.send(stanza); this.messages = this.messages.update(jid, Immutable.List(), function (val) { return val.push(Immutable.Map({ id: msgID, from: Strophe.getBareJidFromJid(sender), body: body, time: moment().format(), type: type, status: 'sending', })); }); this.trigger(this.messages); this._persist(); }, onClearChat (jid) { this.messages = this.messages.update(jid, Immutable.List(), function (val) { return val.clear(); }); this.trigger(this.messages); this._persist(); }, onSendStateChange (jid, state) { let sender = this.connection.jid; let stanza = $msg({ from: sender, to: jid, type: 'chat', }).c(state, { xmlns: Strophe.NS.CHATSTATES, }).up(); this.connection.send(stanza); }, onLogout () { localStorage.removeItem(STORE_NAME); }, getInitialState () { if (typeof this.messages === 'undefined') { this.messages = Immutable.Map(); this._load(); } return this.messages; }, _load () { if (typeof localStorage[STORE_NAME] === 'undefined') { return; } this.messages = Immutable.fromJS(JSON.parse(localStorage[STORE_NAME])); }, _persist () { localStorage[STORE_NAME] = JSON.stringify(this.messages.toJS()); }, });
module.exports = Reflux.createStore({ init() { this.cards = heroCardStore.getDefaultData(); this.filters = heroCardFilterStore.getDefaultData(); this.filteredCards = []; this.listenTo(heroCardStore, this.onHeroCardUpdate); this.listenTo(heroCardFilterStore, this.onHeroCardFilterUpdate); }, getAllState() { return this.filters.filter(this.cards); }, getDefaultData() { return this.getAllState(); }, onHeroCardUpdate(cards) { this.cards = cards; this.trigger(this.getAllState()); }, onHeroCardFilterUpdate(filters) { this.filters = filters; this.trigger(this.getAllState()); }, retrieveCardData() { request .get('/_/hero.json') .end((err, res) => { if (err) { console.error(err); } else { this.updateCards(res.body); } }); } });
export default function initPlugins(roomName) { if (roomName === 'thedrawingroom' || roomName === 'lovenest' || roomName === 'has') { Heim.hook('page-bottom', () => { return ( <style key="drawingroom-style" dangerouslySetInnerHTML={{__html: ` .chat-pane.timestamps-visible { background: #333; } .main-pane .room .name, .info-pane .thread-list .thread .info .title { color: #222; } .chat-pane time { opacity: .5; } .main-pane .room .state, .nick { background: #e8e8e8 !important; } .message-emote { background: #f3f3f3 !important; } .mention-nick { color: #000 !important; font-weight: bold; } a { color: #444; text-decoration: none; font-weight: bold; } `}} /> ) }) } if (roomName === 'space') { const Embed = require('./ui/Embed').default Heim.hook('main-sidebar', () => { return ( <div key="norman" className="norman"> <p>norman</p> <Embed kind="imgur" imgur_id="UKbitCO" /> </div> ) }) Heim.hook('page-bottom', () => { return ( <style key="norman-style" dangerouslySetInnerHTML={{__html: ` .norman { opacity: .5; transition: opacity .15s ease; } .norman:hover { opacity: 1; } .norman p { margin: 0; font-size: 12px; } .norman .embed { width: 100% !important; height: 87px; border: none; } `}} /> ) }) } if (roomName === 'music' || roomName === 'youtube') { const Embed = require('./ui/Embed').default const MessageText = require('./ui/MessageText').default let clientTimeOffset = 0 Heim.chat.store.socket.on('receive', ev => { if (ev.type === 'ping-event') { clientTimeOffset = Date.now() / 1000 - ev.data.time } }) const TVActions = Reflux.createActions([ 'changeVideo', 'changeNotice', ]) Heim.ui.createCustomPane('youtube-tv', {readOnly: true}) const TVStore = Reflux.createStore({ listenables: [ TVActions, {chatChange: Heim.chat.store}, ], init() { this.state = Immutable.fromJS({ video: { time: 0, messageId: null, youtubeId: null, youtubeTime: 0, title: '', }, notice: { time: 0, content: '', }, }) }, getInitialState() { return this.state }, changeVideo(video) { this.state = this.state.set('video', Immutable.fromJS(video)) this.trigger(this.state) }, changeNotice(notice) { this.state = this.state.set('notice', Immutable.fromJS(notice)) this.trigger(this.state) }, }) const SyncedEmbed = React.createClass({ displayName: 'SyncedEmbed', propTypes: { youtubeId: React.PropTypes.string, youtubeTime: React.PropTypes.number, startedAt: React.PropTypes.number, className: React.PropTypes.string, }, shouldComponentUpdate(nextProps) { return nextProps.youtubeId !== this.props.youtubeId || nextProps.youtubeTime !== this.props.youtubeTime }, render() { return ( <Embed className={this.props.className} kind="youtube" autoplay="1" start={Math.max(0, Math.floor(Date.now() / 1000 - this.props.startedAt - clientTimeOffset)) + this.props.youtubeTime} youtube_id={this.props.youtubeId} /> ) }, }) const YouTubeTV = React.createClass({ displayName: 'YouTubeTV', mixins: [ Reflux.connect(TVStore, 'tv'), require('react-addons-pure-render-mixin'), ], render() { return ( <SyncedEmbed className="youtube-tv" youtubeId={this.state.tv.getIn(['video', 'youtubeId'])} startedAt={this.state.tv.getIn(['video', 'time'])} youtubeTime={this.state.tv.getIn(['video', 'youtubeTime'])} /> ) }, }) const YouTubePane = React.createClass({ displayName: 'YouTubePane', mixins: [ Reflux.connect(TVStore, 'tv'), require('react-addons-pure-render-mixin'), ], render() { return ( <div className="chat-pane-container youtube-pane"> <div className="top-bar"> <MessageText className="title" content={':notes: :tv: :notes: ' + this.state.tv.getIn(['video', 'title'])} /> </div> <div className="aspect-wrapper"> <YouTubeTV /> </div> <MessageText className="notice-board" content={this.state.tv.getIn(['notice', 'content'])} /> </div> ) }, }) const parseYoutubeTime = function parseYoutubeTime(time) { const timeReg = /([0-9]+h)?([0-9]+m)?([0-9]+s?)?/ const match = time.match(timeReg) if (!match) { return 0 } const hours = parseInt(match[1] || 0, 10) const minutes = parseInt(match[2] || 0, 10) const seconds = parseInt(match[3] || 0, 10) return hours * 3600 + minutes * 60 + seconds } Heim.hook('thread-panes', () => { return <YouTubePane key="youtube-tv" /> }) Heim.hook('main-pane-top', function YouTubeTVInject() { return this.state.ui.thin ? <YouTubeTV key="youtube-tv" /> : null }) Heim.chat.messagesChanged.listen(function onMessagesChanged(ids, state) { const candidates = Immutable.Seq(ids) .map(messageId => { const msg = state.messages.get(messageId) const valid = messageId !== '__root' && msg.get('content') return valid && msg }) .filter(Boolean) const playRe = /!play [^?]*\?v=([-\w]+)(?:&t=([0-9hms]+))?/ const video = candidates .map(msg => { const match = msg.get('content').match(playRe) return match && { time: msg.get('time'), messageId: msg.get('id'), youtubeId: match[1], youtubeTime: match[2] ? parseYoutubeTime(match[2]) : 0, title: msg.get('content'), } }) .filter(Boolean) .sortBy(v => v.time) .last() if (video && video.time > TVStore.state.getIn(['video', 'time'])) { TVActions.changeVideo(video) } const noticeRe = /^!notice(\S*?)\s([^]*)$/ const notices = candidates .map(msg => { const match = msg.get('content').match(noticeRe) return match && { id: msg.get('id'), time: msg.get('time'), display: !match[1].length, content: match[2], } }) .filter(Boolean) .cacheResult() const noticeMaxSummaryLength = 80 notices.forEach(notice => { const lines = notice.content.split('\n') let content = lines[0] if (content.length >= noticeMaxSummaryLength || lines.length > 1) { content = content.substr(0, noticeMaxSummaryLength) + '…' } state.messages.mergeNodes(notice.id, { content: '/me changed the notice to: "' + content + '"', }) }) const latestNotice = notices .filter(n => n.display) .sortBy(notice => notice.time) .last() if (latestNotice && latestNotice.time > TVStore.state.getIn(['notice', 'time'])) { TVActions.changeNotice(latestNotice) } }) Heim.hook('page-bottom', () => { return ( <style key="youtubetv-style" dangerouslySetInnerHTML={{__html: ` .youtube-pane { z-index: 9; } .youtube-pane .title { width: 0; } .youtube-pane .aspect-wrapper { flex-shrink: 0; position: relative; width: 100%; box-shadow: 0 0 12px rgba(0, 0, 0, .25); z-index: 5; } .youtube-pane .aspect-wrapper:before { content: ''; display: block; padding-top: 75%; } .youtube-pane .youtube-tv { position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; } .youtube-tv { border: none; height: 60vmin; } .youtube-pane .notice-board { background: white; padding: 10px; overflow: auto; white-space: pre-wrap; flex: 1; } `}} /> ) }) } if (roomName === 'adventure' || roomName === 'chess' || roomName === 'monospace') { Heim.hook('page-bottom', () => { return ( <style key="adventure-style" dangerouslySetInnerHTML={{__html: ` .messages-container, .messages-container input, .messages-container textarea { font-family: Droid Sans Mono, monospace; } `}} /> ) }) Heim.chat.setRoomSettings({collapse: false}) } if (location.hash.substr(1) === 'spooky') { Heim.hook('page-bottom', () => { return ( <style key="spooky-style" dangerouslySetInnerHTML={{__html: ` #ui { background: #281f3d; } .info-pane, .sidebar-pane, .top-bar { background: #2e293c; } .info-pane *, .top-bar *, .sidebar-pane * { color: darkorange !important; } .nick, .message-emote { color: black !important; -webkit-filter: saturate(2) brightness(.75); filter: saturate(2) brightness(.75); } .top-bar button { background: darkorange !important; } .main-pane .top-bar .hex { fill: darkorange !important; } .top-bar button .inner, .top-bar button .inner * { color: black !important; } .info-pane .thread-list-container { border: none !important; } .info-pane .thread-list-container:after { box-shadow: none; } .info-pane .thread-list-container .info:hover, .info-pane .thread-list-container .info.selected { background: black !important; } .info-pane .mode-selector { background: #444 !important; } .info-pane .mode-selector button .inner { filter: grayscale(1) invert(1); -webkit-filter: grayscale(1) invert(1); } .info-pane .mode-selector button.selected { background: darkorange !important; } .info-pane .mode-selector button.selected .inner { filter: grayscale(1) invert(1) brightness(0); -webkit-filter: grayscale(1) invert(1) brightness(0); } .info-pane .notification { background: none !important; } .messages .timestamp { color: darkorange !important; } .messages-content { background: none !important; } .messages-container, .youtube-pane .notice { background: linear-gradient(to bottom, #423553 40px, #443e5d) !important; } .timestamps-visible .messages-container { background: linear-gradient(to right, #262334 72px, transparent 72px), linear-gradient(to bottom, #423553 40px, #443e5d) !important; } .replies .entry:before { background-color: transparent !important; } .indent-line, .replies .entry:before, .expand-rest .inner:before { filter: invert(1) !important; -webkit-filter: invert(1) !important; } .expand-rest { color: darkorange !important; } .entry { background: rgba(0, 0, 0, .15) !important; } .entry .nick { background: rgba(255, 255, 255, .25) !important; } .entry input.nick { z-index: 10; } .entry-focus .entry, .expand-rest.focus-target { background: #90561f !important; border-bottom-color: darkorange !important; color: white !important; } .entry-focus .entry textarea, .line .message, .message-preview { color: white !important; text-shadow: 0 1px 1px black !important; } .message-emote { text-shadow: none !important; } .mention > .line .message { background: darkorange !important; } .message a { color: darkorange !important; } .expando:after { background: none !important; } .last-visit hr { border-color: darkorange !important; } .last-visit .label { color: darkorange !important; } .spinner { filter: invert(1) brightness(2); -webkit-filter: invert(1) brightness(2); } .new-count { color: #afa !important; } .youtube-pane .notice { color: white; } ::-webkit-scrollbar { width: 6px; background: none !important; } ::-webkit-scrollbar-track, ::-webkit-scrollbar { background: none !important; } ::-webkit-scrollbar-thumb { background: darkorange !important; border-radius: 2px; } ::-webkit-scrollbar-button { display: none; } @keyframes spooky { 0% { transform: rotate(0deg) scale(1); } 50% { transform: rotate(360deg) scale(1.5); } 100% { transform: rotate(720deg) scale(1); } } .message .emoji-1f47b, .message .emoji-1f480, .message .emoji-1f383 { animation-name: spooky; animation-duration: 4s; animation-iteration-count: 3; animation-timing-function: linear; z-index: 1000; } `}} /> ) }) } if (roomName === 'sandersforpresident') { Heim.hook('main-pane-top', function BernieBarInject() { const MessageText = require('./ui/MessageText').default return ( <div key="sanders-top-bar" className="secondary-top-bar"><MessageText onlyEmoji content=":us:" /> Welcome to the <a href="https://reddit.com/r/sandersforpresident" target="_blank">/r/SandersForPresident</a> live chat! Please <a href="https://www.reddit.com/r/SandersForPresident/wiki/livechat" target="_blank">read our rules</a>.</div> ) }) Heim.hook('page-bottom', () => { return ( <style key="sanders-style" dangerouslySetInnerHTML={{__html: ` .top-bar { background: #327bbe; } .top-bar button:not(.manager-toggle) { background: rgba(255, 255, 255, .5) !important; } .secondary-top-bar { color: white; background: #193e60; padding: 10px 6px; } .secondary-top-bar a, .main-pane .top-bar .room .name { color: white; } .sidebar-pane { background: #f2f2f2; } .sidebar-pane h1 { color: #4d5763; }, `}} /> ) }) } if (location.hash.substr(1) === 'darcula') { Heim.hook('page-bottom', () => { return ( <style key="darcula-style" dangerouslySetInnerHTML={{__html: ` #ui { background: #281f3d; } .info-pane, .sidebar-pane, .top-bar { background: #4C5053; } .info-pane *, .top-bar *, .sidebar-pane * { color: #758076 !important; } .nick, .message-emote { color: black !important; -webkit-filter: saturate(2) brightness(.75); filter: saturate(2) brightness(.75); } .top-bar button { background: #4477B2 !important; } .top-bar button .inner, .top-bar button .inner * { color: black !important; } .info-pane .thread-list-container { border: none !important; } .info-pane .thread-list-container:after { box-shadow: none; } .info-pane .thread-list-container .info:hover, .info-pane .thread-list-container .info.selected { background: black !important; } .info-pane .mode-selector { background: #444 !important; } .info-pane .mode-selector button .inner { filter: grayscale(1) invert(1); -webkit-filter: grayscale(1) invert(1); } .info-pane .mode-selector button.selected { background: darkorange !important; } .info-pane .mode-selector button.selected .inner { filter: grayscale(1) invert(1) brightness(0); -webkit-filter: grayscale(1) invert(1) brightness(0); } .info-pane .notification { background: none !important; } .messages .timestamp { color: #849AAB !important; } .messages-content { background: none !important; } .messages-container, .youtube-pane .notice { background: linear-gradient(to bottom, #423553 40px, #443e5d) !important; } .timestamps-visible .messages-container { background: linear-gradient(to right, #3A3C3E 72px, transparent 72px), linear-gradient(to bottom, #1B1F20 40px, #1c2021) !important } .replies .entry:before { background-color: transparent !important; } .indent-line, .replies .entry:before, .expand-rest .inner:before { filter: invert(1) !important; -webkit-filter: invert(1) !important; } .expand-rest { color: #662E72 !important; } .entry { background: rgba(0, 0, 0, .15) !important; } .entry .nick { background: rgba(255, 255, 255, 1) !important; } .entry input.nick { z-index: 10; } .entry-focus .entry, .expand-rest.focus-target { background: #1e1f36 !important; border-bottom-color: #37385d !important; color: white !important; } .entry-focus .entry textarea, .line .message, .message-preview { color: white !important; text-shadow: 0 1px 1px black !important; } .message-emote { text-shadow: none !important; } .mention > .line .message { background: #4477B2 !important; } .message a { color: #662E72 !important; } .expando:after { background: none !important; } .last-visit hr { border-color: darkgray !important; } .last-visit .label { color: darkgray !important; } .spinner { filter: invert(1) brightness(2); -webkit-filter: invert(1) brightness(2); } .new-count { color: #afa !important; } .youtube-pane .notice { color: white; } ::-webkit-scrollbar { width: 6px; background: none !important; } ::-webkit-scrollbar-track, ::-webkit-scrollbar { background: none !important; } ::-webkit-scrollbar-thumb { background: darkgray !important; border-radius: 2px; } ::-webkit-scrollbar-button { display: none; } `}} /> ) }) } if (roomName === 'xkcd') { Heim.hook('main-pane-top', () => { return ( <div key="xkcd-top-bar" className="secondary-top-bar"><span className="motto" title="All problems are solvable by being thrown at with bots">Omnes quæstiones solvuntur eis iactandis per machinis</span></div> ) }) Heim.hook('page-bottom', () => { return ( <style key="xkcd-top-style" dangerouslySetInnerHTML={{__html: ` .secondary-top-bar { color: black; background: white; padding: 0.25em; text-align: center; box-shadow: 0 0 8px rgba(0, 0, 0, 0.25); z-index: 10; } .motto { font-family: "Droid Serif", Georgia, serif; text-transform: uppercase; cursor: help; } .motto::before { content: "~ "; } .motto::after { content: " ~"; } `}} /> ) }) if (location.hash.substr(1) === 'spooky') { Heim.hook('page-bottom', () => { return ( <style key="xkcd-top-spooky-style" dangerouslySetInnerHTML={{__html: ` .secondary-top-bar { color: darkorange; background: #2e293c; } `}} /> ) }) } } }
import Reflux from 'reflux'; import http from '../common/http.js'; import actions from '../actions.js'; var sectores = {}; export default Reflux.createStore({ listenables: actions, init: function () { http.get('/data/sectores') .then(function (response) { actions.loadSectores.completed(response.body); }) .catch(function (response) { actions.loadSectores.failed(response.message || (response.statusCode + ': ' + response.body)); }); }, getInitialState: function () { return {}; }, onLoadSectoresCompleted: function(res) { sectores = res; this.trigger(sectores); }, onLoadSectoresFailed: function(res) { sectores = {}; actions.error(res); this.trigger(sectores); } });
var Reflux = require('reflux'); var actions = require('../actions/index'); var store = Reflux.createStore({ listenables: [actions], data: {title : 'To the moon'}, init() { this.trigger(this.data); }, onFire(res){ console.log('your data response', res.data); }, getInitialState() { return this.data; } }); module.exports = store;
var NotificationsStore = Reflux.createStore({ listenables: Actions, init: function () { this._notifications = []; }, updateTrayIcon: function (notifications) { if (notifications.length > 0) { ipc.sendChannel('update-icon', 'TrayActive'); } else { ipc.sendChannel('update-icon', 'TrayIdle'); } }, onGetNotifications: function () { var self = this; apiRequests .getAuth('https://api.github.com/notifications') .end(function (err, response) { if (response && response.ok) { // Success - Do Something. Actions.getNotifications.completed(response.body); self.updateTrayIcon(response.body); } else { // Error - Show messages. Actions.getNotifications.failed(err); } }); }, onGetNotificationsCompleted: function (notifications) { var groupedNotifications = _.groupBy(notifications, function (object) { return object.repository.full_name; }); var array = []; _.map(groupedNotifications, function (obj) { array.push(obj); }); this._notifications = array; this.trigger(this._notifications); }, onGetNotificationsFailed: function () { this._notifications = []; this.trigger(this._notifications); } });
const InputTypesStore = Reflux.createStore({ listenables: [InputTypesActions], sourceUrl: '/system/inputs/types', inputTypes: undefined, inputDescriptions: undefined, init() { this.list(); }, getInitialState() { return {inputTypes: this.inputTypes, inputDescriptions: this.inputDescriptions}; }, list() { const promiseTypes = fetch('GET', URLUtils.qualifyUrl(this.sourceUrl)); const promiseDescriptions = fetch('GET', URLUtils.qualifyUrl(this.sourceUrl + '/all')); const promise = Promise.all([promiseTypes, promiseDescriptions]); promise .then( responses => { this.inputTypes = responses[0].types; this.inputDescriptions = responses[1]; this.trigger(this.getInitialState()); }, error => { UserNotification.error('Fetching Input Types failed with status: ' + error, 'Could not retrieve Inputs'); }); InputTypesActions.list.promise(promise); }, get(inputTypeId) { const promise = fetch('GET', URLUtils.qualifyUrl(`${this.sourceUrl}/${inputTypeId}`)); promise .catch(error => { UserNotification.error(`Fetching input ${inputTypeId} failed with status: ${error}`, 'Could not retrieve input'); }); InputTypesActions.get.promise(promise); }, });
var confDocActions = require('../actions/confDoc'); var confDocStore = Reflux.createStore({ listenables: [confDocActions], docConf: [], getInitialState: function() { this.docConf = [{estado : true, ident : 'verde', nombre : 'para las mastas'}, {estado : false, ident : 'azul', nombre : 'para el cielo'}, {estado : true, ident : 'rojoj', nombre : 'para el amor'} ]; return { 'docConf':this.docConf } }, onFetchConfDocument: function(){ this.docConf.docConf = [{estado : true, ident : 'verde', nombre : 'para 1'}, {estado : false, ident : 'azul', nombre : 'para 2'}, {estado : true, ident : 'rojoj', nombre : 'para 3'}] this.trigger(); }, onSaveConfDocument: function(data){ this.docConf.docConf = data this.trigger(this.docConf); }, }); module.exports = confDocStore;
const PipelineConnectionsStore = Reflux.createStore({ listenables: [PipelineConnectionsActions], connections: undefined, getInitialState() { return { connections: this.connections }; }, list() { const failCallback = (error) => { UserNotification.error(`Fetching pipeline connections failed with status: ${error.message}`, 'Could not retrieve pipeline connections'); }; const url = URLUtils.qualifyUrl(ApiRoutes.ConnectionsController.list().url); const promise = fetch('GET', url); promise.then((response) => { this.connections = response; this.trigger({ connections: response }); }, failCallback); }, connectToStream(connection) { const url = URLUtils.qualifyUrl(ApiRoutes.ConnectionsController.to_stream().url); const updatedConnection = { stream_id: connection.stream, pipeline_ids: connection.pipelines, }; const promise = fetch('POST', url, updatedConnection); promise.then( (response) => { if (this.connections.filter(c => c.stream_id === response.stream_id)[0]) { this.connections = this.connections.map(c => (c.stream_id === response.stream_id ? response : c)); } else { this.connections.push(response); } this.trigger({ connections: this.connections }); UserNotification.success('Pipeline connections updated successfully'); }, this._failUpdateCallback, ); }, connectToPipeline(reverseConnection) { const url = URLUtils.qualifyUrl(ApiRoutes.ConnectionsController.to_pipeline().url); const updatedConnection = { pipeline_id: reverseConnection.pipeline, stream_ids: reverseConnection.streams, }; const promise = fetch('POST', url, updatedConnection); promise.then( (response) => { response.forEach((connection) => { if (this.connections.filter(c => c.stream_id === connection.stream_id)[0]) { this.connections = this.connections.map(c => (c.stream_id === connection.stream_id ? connection : c)); } else { this.connections.push(connection); } }); this.trigger({ connections: this.connections }); UserNotification.success('Pipeline connections updated successfully'); }, this._failUpdateCallback, ); }, _failUpdateCallback(error) { UserNotification.error(`Updating pipeline connections failed with status: ${error.message}`, 'Could not update pipeline connections'); }, });
module.exports = Reflux.createStore({ listenables: require('act/Log.js'), init: function(){ _.extend(this, { messageBoxes: [], }); // C++ API callin. window.alert2 = this.errorBox; }, getInitialState: function(){ return { messageBox: this.messageBoxes.slice(-1)[0], }; }, triggerSync: function(){ this.trigger(this.getInitialState()); }, MsgType: { NORMAL: 0, DEBUG: 1, INFO: 2, WARNINIG: 3, ERROR: 4, }, renderMessage: function(args){ return _.map(args, function(arg){ if (typeof arg === 'undefined'){ return '[undefined]'; } else if (arg === null){ return '[null]'; } else if (typeof arg === 'object'){ try { return JSON.stringify(arg); } catch(e) { return arg.toString(); } } else { return arg.toString(); } }.bind(this)).join('\n'); }, // Action handlers. debug: function(){ console.debug.apply(console, arguments); }, debugBox: function(){ this.debug.apply(this, arguments); this.messageBoxes.push({ msg: this.renderMessage(arguments), title: 'Debug', type: this.MsgType.DEBUG, }); this.triggerSync(); }, info: function(){ console.info.apply(console, arguments); }, infoBox: function(){ this.info.apply(this, arguments); this.messageBoxes.push({ msg: this.renderMessage(arguments), title: 'Info', type: this.MsgType.INFO, }); this.triggerSync(); }, warning: function(){ console.warn.apply(console, arguments); }, warningBox: function(){ this.warning.apply(this, arguments); this.messageBoxes.push({ msg: this.renderMessage(arguments), title: 'Warning', type: this.MsgType.WARNING, }); this.triggerSync(); }, error: function(){ console.error.apply(console, arguments); }, errorBox: function(){ this.error.apply(this, arguments); this.messageBoxes.push({ msg: this.renderMessage(arguments), title: 'Error', type: this.MsgType.ERROR, }); this.triggerSync(); }, messageBox: function(msg, title){ this.messageBoxes.push({ msg: msg || '(no message)', title: title || 'Message', type: this.MsgType.NORMAL, }); this.triggerSync(); }, popMessageBox: function(){ this.messageBoxes.pop(); this.triggerSync(); }, });
export default (Actions) => Reflux.createStore({ /* * queries relation collections * keeps last query result in pouch (_local/rcs.rcs) for fast delivery * app.js sets default _local/rcs.rcs = [] if not exists on app start * rc's are arrays of the form: * [collectionType, rcName, combining, organization, * {Beschreibung: xxx, Datenstand: xxx, Link: xxx, Nutzungsbedingungen: xxx}, count: xxx] * * when this store triggers it passes two variables: * rcs: the relation collections * rcsQuerying: true/false: are rcs being queryied? if true: show warning in symbols */ listenables: Actions, rcsQuerying: false, getRcs() { return new Promise((resolve, reject) => { app.localDb.get('_local/rcs') .then((doc) => resolve(doc.rcs)) .catch((error) => reject(`userStore: error getting relation collections from localDb: ${error}`) ) }) }, saveRc(rc) { let rcs app.localDb.get('_local/rcs') .then((doc) => { doc.rcs.push(rc) doc.rcs = doc.rcs.sort((c) => c.name) rcs = doc.rcs return app.localDb.put(doc) }) .then(() => this.trigger(rcs, this.rcsQuerying)) .catch((error) => addError({ title: 'Fehler in relationCollectionsStore, saveRc:', msg: error }) ) }, saveRcs(rcs) { app.localDb.get('_local/rcs') .then((doc) => { doc.rcs = rcs return app.localDb.put(doc) }) .catch((error) => addError({ title: 'Fehler in relationCollectionsStore, saveRcs:', msg: error }) ) }, removeRcByName(name) { let rcs app.localDb.get('_local/rcs') .then((doc) => { doc.rcs = _reject(doc.rcs, (rc) => rc.name === name) rcs = doc.rcs return app.localDb.put(doc) }) .then(() => this.trigger(rcs, this.rcsQuerying)) .catch((error) => addError({ title: 'Fehler in relationCollectionsStore, removeRcByName:', msg: error }) ) }, getRcByName(name) { return new Promise((resolve, reject) => { this.getRcs() .then((rcs) => { const rc = rcs.find((c) => c.name === name) resolve(rc) }) .catch((error) => reject(error)) }) }, onQueryRelationCollections() { // if rc's exist, send them immediately this.rcsQuerying = true this.getRcs() .then((rcs) => this.trigger(rcs, this.rcsQuerying)) .catch((error) => addError({ title: 'relationCollectionsStore, error getting existing rcs:', msg: error }) ) // now fetch up to date rc's queryRcs() .then((rcs) => { this.rcsQuerying = false this.trigger(rcs, this.rcsQuerying) return this.saveRcs(rcs) }) .catch((error) => addError({ title: 'relationCollectionsStore, error querying up to date rcs:', msg: error }) ) } })
const AlarmCallbacksStore = Reflux.createStore({ listenables: [AlarmCallbacksActions], list(streamId) { const failCallback = (error) => UserNotification.error(`Fetching alert notifications failed with status: ${error.message}`, 'Could not retrieve alert notification'); const url = URLUtils.qualifyUrl(ApiRoutes.AlarmCallbacksApiController.list(streamId).url); const promise = fetch('GET', url).then((response) => response.alarmcallbacks, failCallback); AlarmCallbacksActions.list.promise(promise); }, save(streamId, alarmCallback) { const failCallback = (error) => { const errorMessage = (error.additional && error.additional.status === 400 ? error.additional.body.message : error.message); UserNotification.error(`Saving alert notification failed with status: ${errorMessage}`, 'Could not save alert notification'); }; const url = URLUtils.qualifyUrl(ApiRoutes.AlarmCallbacksApiController.create(streamId).url); const promise = fetch('POST', url, alarmCallback); promise.then( () => UserNotification.success('Alert notification saved successfully'), failCallback ); AlarmCallbacksActions.save.promise(promise); }, delete(streamId, alarmCallbackId) { const failCallback = (error) => UserNotification.error(`Removing alert notification failed with status: ${error.message}`, 'Could not remove alert notification'); const url = URLUtils.qualifyUrl(ApiRoutes.AlarmCallbacksApiController.delete(streamId, alarmCallbackId).url); const promise = fetch('DELETE', url); promise.then( () => UserNotification.success('Alert notification deleted successfully'), failCallback ); AlarmCallbacksActions.delete.promise(promise); }, update(streamId, alarmCallbackId, deltas) { const failCallback = (error) => { const errorMessage = (error.additional && error.additional.status === 400 ? error.additional.body.message : error.message); UserNotification.error(`Updating alert notification '${alarmCallbackId}' failed with status: ${errorMessage}`, 'Could not update alert notification'); }; const url = URLUtils.qualifyUrl(ApiRoutes.AlarmCallbacksApiController.update(streamId, alarmCallbackId).url); const promise = fetch('PUT', url, deltas); promise.then( () => UserNotification.success('Alert notification updated successfully'), failCallback ); AlarmCallbacksActions.update.promise(promise); }, });
var systemStore = Reflux.createStore({ listenables: [systemActions], getMaster: function() { return this.masterData || null; }, onGetMaster: function() { if (!this.masterData) { ajaxActions.request('/api/system/getMaster', {}, this.didGetMaster); } else { systemActions.getMaster.done(this.masterData); } }, onIniModule: function(item) { systemActions.iniModule.done(item); }, didGetMaster: function(res) { console.log('didGetMaster', res); if (res.status===true) { systemActions.getMaster.done(res.data); this.masterData = res.data; return; } systemActions.getMaster.error(res.error); }, onSignout: function() { console.log("requestSignOut"); ajaxActions.request('/api/system/signout', {}, this.didSignout); }, didSignout: function(res) { if (res.status===true) { systemActions.signout.done(); return; } systemActions.signout.error(res.error); }, onSignoutTransport: function() { ajaxActions.request('/api/system/signoutTransport', {}, this.didSignoutTransport); }, didSignoutTransport: function(res) { if (res.status===true) { systemActions.signoutTransport.done(); return; } systemActions.signoutTransport.error(res.error); }, onPing: function() { ajaxActions.request('/api/system/ping', {}, this.didPing); }, didPing: function(res) { if (res.status===true) { systemActions.ping.done(res.sessionID); return; } systemActions.ping.error(res.error); }, onGetIDCardReaders: function() { $.ajax({ url:'//localhost:9001/idcard/readers', type:'get', dataType:'json', success: function(result) { // console.log('onReadIDCardReaders', result); if (result.status===true) { systemActions.getIDCardReaders.done(result.readers); } else { systemActions.getIDCardReaders.error(); } }, error: function() { systemActions.getIDCardReaders.error(); } }); }, onReadIDCard: function(reader, ref) { $.ajax({ url:'//localhost:9001/idcard/read' + (reader ? '/'+reader : ''), type:'get', dataType:'json', success: function(result) { //console.log('onReadIDCard', result); if (result.status===true) { systemActions.readIDCard.done(result.idcard, ref); } else { systemActions.readIDCard.error(); } }, error: function(e) { systemActions.readIDCard.error(); } }); }, onReadIDCardPhoto: function(reader, ref) { $.ajax({ url:'//localhost:9001/idcard/readPhoto' + (reader ? '/'+reader : ''), type:'get', dataType:'json', success: function(result) { console.log('onReadIDCardPhoto', result); if (result.status===true) { systemActions.readIDCardPhoto.done({ nationid: result.nationid, photoPath: '//localhost:9001/idcard/photo/' + result.nationid + '.jpg', ref: ref }); } else { systemActions.readIDCardPhoto.error(); } }, error: function(e) { systemActions.readIDCardPhoto.error(); } }); }, onPrinterList: function(param) { $.ajax({ url:param.url + '/printer/list', type:'get', dataType:'json', success: function(result) { systemActions.printerList.done({ ref:param.ref, printers: result.printers }); }, error: function(err) { systemActions.printerList.error(err); } }) }, onPrint: function(req) { var option = storage.load('system.printers', { printerLaserUrl: 'http://localhost:9001', printerDotUrl: 'http://localhost:9001', printerLaser: 'Foxit Reader PDF Printer', printerDot: 'Foxit Reader PDF Printer' }); var param = { uuid: helper.newUUID(), report: '', param: {url: req.url}, format: 'PDFURL', printer: req.printer || option.printerLaser, numCopy: req.numCopy || 1 }; console.log(param); $.ajax({ type:'post', url:option.printerLaserUrl + '/printer/submit', contentType: 'application/json; charset=utf-8', data:JSON.stringify(param), dataType:'json', success: function(result) { systemActions.print.done(); }, error: function(e) { systemActions.print.error(e); } }); }, onGetCounts: function(param) { ajaxActions.request(param.request, param.list, this.didGetCounts); }, didGetCounts: function(res) { console.log(res); systemActions.getCounts.done(res); if (res.status===true) { systemActions.getCounts.done(res.counts); return; } systemActions.getCounts.error(); }, });
var commissionStore = Reflux.createStore({ listenables: [commissionActions], // commissionActions.list onList: function(param) { ajaxActions.request('/api/installment/commission-close/list', param, this.doneList); }, doneList: function(res) { if (res.status===true) { console.log('data=',res.data); commissionActions.list.done(res.data, res.opt); // menuActions.updateCount('commission.sell', res.opt.totalRows); } else { commissionActions.list.error(res.error); } }, // commissionActions.list onExport: function(param) { ajaxActions.request('/api/installment/commission-close/export', param, this.doneExport); }, doneExport: function(res) { if (res.status===true) { commissionActions.export.done(res.file); } else { commissionActions.export.error(res.error); } }, onFacetList: function() { ajaxActions.request('/api/installment/commission-close/facetList', {}, this.doneFacetList); }, doneFacetList: function(res) { if (res.status === true) { commissionActions.facetList.done(res); } else { commissionActions.facetList.error(res.error); } }, onFacetDetail: function(param) { ajaxActions.request('/api/installment/commission-close/facetDetail', param, this.doneFacetDetail); }, doneFacetDetail: function(res) { if (res.status === true) { commissionActions.facetDetail.done(res); } else { commissionActions.facetDetail.error(res.error); } }, onCommissionDetail: function(param) { ajaxActions.request('/api/installment/commission-close/commissionDetail', param, this.doneCommissionDetail); }, doneCommissionDetail: function(res) { if (res.status === true) { commissionActions.commissionDetail.done(res); } else { commissionActions.commissionDetail.error(res.error); } }, onSaveCommission: function(param) { ajaxActions.request('/api/installment/commission-close/saveCommission', param, this.doneSaveCommission); }, doneSaveCommission: function(res) { if (res.status === true) { commissionActions.saveCommission.done(res); } else { commissionActions.saveCommission.error(res.error); } }, onVoidCommission: function(id) { ajaxActions.request('/api/installment/commission-close/voidCommission', {id:id}, this.doneVoidCommission); }, doneVoidCommission: function(res) { if (res.status===true) { commissionActions.voidCommission.done(); } else { commissionActions.voidCommission.error(res.error); } }, onPaidCommission: function(id) { ajaxActions.request('/api/installment/commission-close/paidCommission', {id:id}, this.donePaidCommission); }, donePaidCommission: function(res) { if (res.status===true) { commissionActions.paidCommission.done(); } else { commissionActions.paidCommission.error(res.error); } } });
* const ServerStatsComponent = require('mongodb-server-stats').ServerStatsComponent; * const ServerStatsStore = require('./server-stats-store'); * * var component = <ServerStatsComponent store={ServerStatsStore} />; * ReactDOM.render(component, document.getElementById('server-stats-container')); * */ const ServerStatsStore = Reflux.createStore({ /** * Initializing the store should set up the listener for * the 'pollServerStats' command. */ init: function() { this.listenTo(Actions.pollServerStats, this.serverStats); }, /** * In Compass, we would use the data service to get the serverStats * then trigger with the result and a potential error if * there was one. */ serverStats: function() { app.dataService.serverstats((error, doc) => { this.trigger(error, doc); }); } }); module.exports = ServerStatsStore;
var ItemStore = Reflux.createStore({ listenables: ItemActions, _items: [], _itemsParsed: [], getStoreItems: function() { return this._items; }, getStoreParsedItems: function() { return this._itemsParsed; }, getAllItems: function() { console.log("start ajax"); $.ajax({ type: 'GET', url: '/items' }) .done(function (itemsTuple) { console.log("finished ajax", itemsTuple); this._items = itemsTuple[0]; this._itemsParsed = itemsTuple[1]; // broadcast that items has changed this.trigger(); }.bind(this)) .fail(function(error) { // console.log("cheating workaround to not setup api endpoint"); // this._items = staticDeployTuple[0]; // this._itemsParsed = staticDeployTuple[1]; // this.trigger(); console.error(error); }.bind(this)); } });
export default Reflux.createStore({ listenables: [BookmarkActions], init: function() { this.onFetch(); }, onFetch: function() { const self = this; Utils.fetch('http://localhost:3000/bookmarks').then(function(bookmarks) { // console.log(bookmarks); self.trigger({ data: bookmarks, match: '' }); }); }, onSearch: function(keyword) { var self = this; Utils.fetch('http://localhost:3000/bookmarks?title_like=' + keyword).then(function(bookmarks) { // console.log(bookmarks,keyword); self.trigger({ data: bookmarks, match: keyword }); }); } });
module.exports = Reflux.createStore({ // this will set up listeners to all publishers in actions, using onKeyname (or keyname) as callbacks listenables: [Actions], onEditItem: function(itemKey, newLabel) { var foundItem = getItemByKey(this.list, itemKey); if (!foundItem) { return; } foundItem.label = newLabel; this.updateList(this.list); }, onAddItem: function(label) { this.updateList([{ key: todoCounter++, created: new Date(), isComplete: false, label: label }].concat(this.list)); }, onRemoveItem: function(itemKey) { this.updateList(_.filter(this.list, function(item) { return item.key !== itemKey; })); }, onToggleItem: function(itemKey) { var foundItem = getItemByKey(this.list, itemKey); if (foundItem) { foundItem.isComplete = !foundItem.isComplete; this.updateList(this.list); } }, onToggleAllItems: function(checked) { this.updateList(_.map(this.list, function(item) { item.isComplete = checked; return item; })); }, onClearCompleted: function() { this.updateList(_.filter(this.list, function(item) { return !item.isComplete; })); }, // called whenever we change a list. normally this would mean a database API call updateList: function(list) { localStorage.setItem(localStorageKey, JSON.stringify(list)); // if we used a real database, we would likely do the below in a callback this.list = list; this.trigger(list); // sends the updated list to all listening components (TodoApp) }, // this will be called by all listening components as they register their listeners getInitialState: function() { var loadedList = localStorage.getItem(localStorageKey); if (!loadedList) { // If no list is in localstorage, start out with a default one this.list = [{ key: todoCounter++, created: new Date(), isComplete: false, label: 'Rule the web' }]; } else { this.list = _.map(JSON.parse(loadedList), function(item) { // just resetting the key property for each todo item item.key = todoCounter++; return item; }); } return this.list; } })
var Reflux = require('reflux'); var tickerActions = require('../actions/tickerActions'); var tickerStore = Reflux.createStore({ count: 0, init: function () { this.listenTo(tickerActions.tick, 'output'); }, output: function () { this.count += 1; this.trigger({count: this.count}); } }); module.exports = tickerStore;
import Reflux from 'reflux' var viewUrl = null; import SearchActions from './actions.js' var SearchStore = Reflux.createStore({ result: [], listenables: [SearchActions], onSearching: function (text) { console.log('seaching action'); var results = GoogleApi.search(text); this.results = results; this.trigger({ results: this.results }); }, onInit: function () { //searchingResults this.results = [{title: 'default', url: 'https://www.google.co.jp'}]; this.trigger({ results: this.results }); } }); //sample var GoogleApi = { search: function (text) { return [{title: 'ブログ', url: 'http://katoyuu.hatenablog.jp/entry/nurseryschool' }, {title: 'github', url: 'https://github.com'}, {title: 'yahoo', url: 'http://www.yahoo.co.jp'}, {title: 'google', url: 'https://www.google.co.jp'}, { title: 'hatenaB(はてぶ)', url: 'http://b.hatena.ne.jp' }] } };
var TimerStore = Reflux.createStore({ // this will set up listeners to all publishers in TodoActions, using onKeyname (or keyname) as callbacks listenables: [TimerActions], init: function() { console.log('TimerStore initialized'); // todo: consider loading state from localStorage this.state = Immutable.Map({ length: 10 * 60, /* 10 minutes, in seconds */ timeRemaining: 10 * 60, ticking: false }); }, onSetTimeRemaining: function(seconds) { this.setState({ timeRemaining: Math.round(seconds) }); }, onSetLength: function(seconds) { this.setState({ length: Math.round(seconds) }) }, onAddTime: function(seconds) { this.setState({ length: Math.round(this.state.get('length') + seconds), timeRemaining: Math.round(this.state.get('timeRemaining') + seconds) }); }, tick: function() { if (!this.state.get('ticking')) { return; } var newTimeRemaining = this.state.get('timeRemaining') - 1; TimerActions.setTimeRemaining(newTimeRemaining); console.log('tick - new time remaining', newTimeRemaining); if (newTimeRemaining <= 0) { TimerActions.end(); } }, start: function() { this.interval = setInterval(this.tick.bind(this), 1000); // todo: compensate for processing time by calculating time since last tick and subtracting it (as long as it's under 1000) this.setState({ticking:true}); }, stop: function() { clearInterval(this.interval); this.setState({ticking: false}) }, toggle: function() { if (this.state.get('ticking')) { TimerActions.stop(); } else { TimerActions.start(); } }, onEnd: function() { console.log('store.end') TimerActions.stop(); }, onReset: function(seconds) { seconds = (typeof seconds == "number") ? Math.round(seconds) : this.state.get('length'); this.setState({ length: seconds, timeRemaining: seconds }); }, setState: function(state) { console.log('updating state', state); this.state = this.state.merge(state); this.trigger(this.state.toJS()); }, getInitialState: function() { return this.state.toJS(); } });
let Http = Reflux.createStore({ /** * Small abstraction over $.ajax */ init: function() { actions.login.completed.listen(this.onLogin); actions.register.completed.listen(this.onLogin); actions.auth.completed.listen(this.onAuth); $.ajaxSetup( { xhr: function() { return new window.XMLHttpRequest( { mozSystem: true }); } }); }, access_token: false, authCompleted: false, requestQueue: [], processRequestQueue: function() { // We collect all requests to API until auth is completed console.debug("processing request queue", this.requestQueue); for (let key in this.requestQueue) { this.requestQueue[key](); } this.requestQueue = []; }, onAuth: function(resp) { console.debug('Utils:Auth completed', resp); this.authCompleted = true; if (resp.success === true) { this.access_token = Cookies.get('access_token'); } else { console.debug('Utils:auth failed, redirecting to login'); window.location.hash = '#/Login'; } this.processRequestQueue(); }, onLogin: function(resp) { console.debug('Utils:onLogin', resp, resp.s); this.authCompleted = true; if (resp.success === true) { console.debug('Util: Login successful - setting cookie', Cookies); Cookies.set('access_token', resp.user.access_token); this.access_token = resp.user.access_token; this.processRequestQueue(); console.log('CCC', Cookies.get('access_token')); } }, post: function(url, data, success, error) { let exec = function() { if (this.access_token) { data.access_token = this.access_token; } console.debug('POST ', url, data); $.ajax({ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, url: base_url + url, type: 'POST', dataType: 'json', data: JSON.stringify(data), success: success, error: error }); }.bind(this); if (this.authCompleted || url.indexOf('login') === 0) { exec(); } else { this.requestQueue.push(exec); } }, put: function(url, data, success, error) { let exec = function() { if (this.access_token) { data.access_token = this.access_token; } $.ajax({ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, url: base_url + url, type: 'PUT', dataType: 'json', data: JSON.stringify(data), success: success, error: error }); }.bind(this); if (this.authCompleted || url.indexOf('login') === 0) { exec(); } else { this.requestQueue.push(exec); } }, get: function(url, success, error) { let exec = function() { if (this.access_token) { let contractor = url.indexOf('?') > -1 ? '&' : '?'; url += contractor + 'access_token=' + this.access_token; } console.debug('GET ' + base_url + url); $.ajax({ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, url: base_url + url, type: 'GET', dataType: 'json', success: success, error: error }); }.bind(this); console.debug('GET ', url, this.authCompleted); if (this.authCompleted || url.indexOf('auth') === 0 ) { console.debug('Executing GET'); exec(); } else { console.debug('Adding to requestQueue'); this.requestQueue.push(exec); } }, delete: function(url, success, error) { let exec = function() { if (this.access_token) { let contractor = url.indexOf('?') > -1 ? '&' : '?'; url += contractor + 'access_token=' + this.access_token; } $.ajax({ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, url: base_url + url, type: 'DELETE', dataType: 'json', success: success, error: error }); }.bind(this); console.debug('DELETE ', url, this.authCompleted); if (this.authCompleted || url.indexOf('auth') === 0 ) { console.debug('Executing DELETE'); exec(); } else { console.debug('Adding to requestQueue'); this.requestQueue.push(exec); } } });
var Store=Reflux.createStore({ listenables:Actions, onNextMonth:function(){ if(data.month==12){ data.year++ data.month=1 } else { data.month++ } this.trigger() }, onPrevMonth:function(){ if(data.month==1){ data.year-- data.month=12 } else { data.month-- } this.trigger() }, onReset:function(){ data=this.init() data.isInit=false data.visable=true this.trigger() }, onEnter:function(node){ utils.addClass(node,'hover') }, onLeave:function(node){ utils.removeClass(node,'hover') }, onChoose:function(actionData){ console.log(actionData) var time=actionData.split('-') ,yy=time[0] ,mm=time[1] ,dd=time[2] //data.displayDate=utils.MiniMonth[mm-1]+" "+dd+", "+yy; data.displayDate=[yy,mm,dd] data.visable=false; this.trigger() }, onShow:function(){ data.visable=!data.visable this.trigger() }, load:function(){ //console.log(this.data) return [ data.year, data.month, data.date, data.displayDate, data.visable ] }, init:function(){ return { year:timestamp.getFullYear(), month:timestamp.getMonth()+1, date:timestamp.getDate(), displayDate:utils.DisplayNow(), visable:false } }, //getInitialState:function(){ // this.data=this.init(); //}, refresh:function(){ var time = this.load() var isInit = data.isInit===undefined data.isInit = false return { year: time[0], month: time[1], days: refreshDays(time[0],time[1]), date:time[2], display:time[3], visable:time[4], isInit:isInit } } })
const IndicesStore = Reflux.createStore({ listenables: [IndicesActions], indices: undefined, closedIndices: undefined, init() { IndicesActions.list(); }, getInitialState() { return { indices: this.indices, closedIndices: this.closedIndices }; }, list() { const urlList = URLUtils.qualifyUrl(ApiRoutes.IndicesApiController.list().url); const promise = fetch('GET', urlList).then((response) => { this.indices = response.all.indices; this.closedIndices = response.closed.indices; this.trigger({ indices: this.indices, closedIndices: this.closedIndices }); return { indices: this.indices, closedIndices: this.closedIndices }; }); IndicesActions.list.promise(promise); }, close(indexName) { const url = URLUtils.qualifyUrl(ApiRoutes.IndicesApiController.close(indexName).url); const promise = fetch('POST', url); IndicesActions.close.promise(promise); }, closeCompleted() { IndicesActions.list(); }, delete(indexName) { const url = URLUtils.qualifyUrl(ApiRoutes.IndicesApiController.delete(indexName).url); const promise = fetch('DELETE', url); IndicesActions.delete.promise(promise); }, deleteCompleted() { IndicesActions.list(); }, reopen(indexName) { const url = URLUtils.qualifyUrl(ApiRoutes.IndicesApiController.reopen(indexName).url); const promise = fetch('POST', url); IndicesActions.reopen.promise(promise); }, reopenCompleted() { IndicesActions.list(); }, });