try to fix everything by changing references

This commit is contained in:
Connor Turland 2017-03-22 20:54:40 -04:00
parent 7fe26ea022
commit b7a6e615a0
32 changed files with 1023 additions and 1043 deletions

View file

@ -4,8 +4,7 @@ import _ from 'lodash'
import Backbone from 'backbone' import Backbone from 'backbone'
try { Backbone.$ = window.$ } catch (err) {} try { Backbone.$ = window.$ } catch (err) {}
import Active from '../Active' //import InfoBox from '../Map/InfoBox'
import InfoBox from '../Map/InfoBox'
import Mapper from '../Mapper' import Mapper from '../Mapper'
const Map = Backbone.Model.extend({ const Map = Backbone.Model.extend({

View file

@ -2,10 +2,10 @@ import _ from 'lodash'
import Backbone from 'backbone' import Backbone from 'backbone'
try { Backbone.$ = window.$ } catch (err) {} try { Backbone.$ = window.$ } catch (err) {}
import Active from '../Active' /*import Active from '../Active'
import Map from '../Map' import Map from '../Map'
import Synapse from '../Synapse' import Synapse from '../Synapse'
import Topic from '../Topic' import Topic from '../Topic'*/
const Mapping = Backbone.Model.extend({ const Mapping = Backbone.Model.extend({
urlRoot: '/mappings', urlRoot: '/mappings',

View file

@ -3,10 +3,11 @@ import outdent from 'outdent'
import Backbone from 'backbone' import Backbone from 'backbone'
try { Backbone.$ = window.$ } catch (err) {} try { Backbone.$ = window.$ } catch (err) {}
/*
import Active from '../Active' import Active from '../Active'
import Filter from '../Filter' import Filter from '../Filter'
import SynapseCard from '../SynapseCard' import SynapseCard from '../SynapseCard'
import Visualize from '../Visualize' import Visualize from '../Map/Visualize'*/
import DataModel from './index' import DataModel from './index'

View file

@ -2,10 +2,10 @@ import _ from 'lodash'
import Backbone from 'backbone' import Backbone from 'backbone'
try { Backbone.$ = window.$ } catch (err) {} try { Backbone.$ = window.$ } catch (err) {}
import Active from '../Active' import Active from '../Map/Active'
import Filter from '../Filter' import Filter from '../Map/Filter'
import TopicCard from '../Views/TopicCard' import TopicCard from '../Map/TopicCard'
import Visualize from '../Visualize' import Visualize from '../Map/Visualize'
import DataModel from './index' import DataModel from './index'

View file

@ -2,7 +2,7 @@
import outdent from 'outdent' import outdent from 'outdent'
import Active from '../Active' //import Active from '../Active'
import DataModel from '../DataModel' import DataModel from '../DataModel'
import DataModelMap from '../DataModel/Map' import DataModelMap from '../DataModel/Map'
import GlobalUI from './index' import GlobalUI from './index'

View file

@ -6,7 +6,7 @@ import outdent from 'outdent'
import ImportDialogBox from '../../components/MapView/ImportDialogBox' import ImportDialogBox from '../../components/MapView/ImportDialogBox'
import PasteInput from '../PasteInput' import PasteInput from '../Map/PasteInput'
import Map from '../Map' import Map from '../Map'
const ImportDialog = { const ImportDialog = {

View file

@ -10,7 +10,7 @@ import ImportDialog from './ImportDialog'
import Mapper from '../DataModel/Mapper' import Mapper from '../DataModel/Mapper'
import ExploreMaps from '../ExploreMaps' import ExploreMaps from '../ExploreMaps'
import { mapControl } from '../Map' import { mapControl } from '../Map'
import { topicControl } from '../Topic' //import { topicControl } from '../Topic'
import makeRoutes from '../../components/makeRoutes' import makeRoutes from '../../components/makeRoutes'
let routes let routes
@ -193,7 +193,7 @@ const ReactApp = {
participants: [], participants: [],
messages: [] messages: []
} }
const { ChatView, Realtime } = self.openMap const { ChatView, Realtime } = self.openMap
return { return {
unreadMessages: ChatView.unreadMessages, unreadMessages: ChatView.unreadMessages,
conversationLive: ChatView.conversationLive, conversationLive: ChatView.conversationLive,
@ -217,7 +217,7 @@ const ReactApp = {
getFilterProps: function() { getFilterProps: function() {
const self = ReactApp const self = ReactApp
if (!self.openMap) return {} if (!self.openMap) return {}
const { Filter } = self.openMap const { Filter } = self.openMap
return { return {
filterData: Filter.dataForPresentation, filterData: Filter.dataForPresentation,
allForFiltering: Filter.filters, allForFiltering: Filter.filters,

View file

@ -1,8 +1,8 @@
/* global $, Hogan, Bloodhound, CanvasLoader */ ReactApp.currentUserReactApp.currentUser/* global $, Hogan, Bloodhound, CanvasLoader */
import { browserHistory } from 'react-router' import { browserHistory } from 'react-router'
import Active from '../Active' import ReactApp from './ReactApp'
const Search = { const Search = {
locked: false, locked: false,
@ -41,8 +41,8 @@ const Search = {
startTypeahead: function() { startTypeahead: function() {
var self = Search var self = Search
var mapheader = Active.Mapper ? '<div class="searchMapsHeader searchHeader"><h3 class="search-heading">Maps</h3><input type="checkbox" class="limitToMe" id="limitMapsToMe"></input><label for="limitMapsToMe" class="limitToMeLabel">added by me</label><div class="minimizeResults minimizeMapResults"></div><div class="clearfloat"></div></div>' : '<div class="searchMapsHeader searchHeader"><h3 class="search-heading">Maps</h3><div class="minimizeResults minimizeMapResults"></div><div class="clearfloat"></div></div>' var mapheader = ReactApp.currentUser ? '<div class="searchMapsHeader searchHeader"><h3 class="search-heading">Maps</h3><input type="checkbox" class="limitToMe" id="limitMapsToMe"></input><label for="limitMapsToMe" class="limitToMeLabel">added by me</label><div class="minimizeResults minimizeMapResults"></div><div class="clearfloat"></div></div>' : '<div class="searchMapsHeader searchHeader"><h3 class="search-heading">Maps</h3><div class="minimizeResults minimizeMapResults"></div><div class="clearfloat"></div></div>'
var topicheader = Active.Mapper ? '<div class="searchTopicsHeader searchHeader"><h3 class="search-heading">Topics</h3><input type="checkbox" class="limitToMe" id="limitTopicsToMe"></input><label for="limitTopicsToMe" class="limitToMeLabel">added by me</label><div class="minimizeResults minimizeTopicResults"></div><div class="clearfloat"></div></div>' : '<div class="searchTopicsHeader searchHeader"><h3 class="search-heading">Topics</h3><div class="minimizeResults minimizeTopicResults"></div><div class="clearfloat"></div></div>' var topicheader = ReactApp.currentUser ? '<div class="searchTopicsHeader searchHeader"><h3 class="search-heading">Topics</h3><input type="checkbox" class="limitToMe" id="limitTopicsToMe"></input><label for="limitTopicsToMe" class="limitToMeLabel">added by me</label><div class="minimizeResults minimizeTopicResults"></div><div class="clearfloat"></div></div>' : '<div class="searchTopicsHeader searchHeader"><h3 class="search-heading">Topics</h3><div class="minimizeResults minimizeTopicResults"></div><div class="clearfloat"></div></div>'
var mapperheader = '<div class="searchMappersHeader searchHeader"><h3 class="search-heading">Mappers</h3><div class="minimizeResults minimizeMapperResults"></div><div class="clearfloat"></div></div>' var mapperheader = '<div class="searchMappersHeader searchHeader"><h3 class="search-heading">Mappers</h3><div class="minimizeResults minimizeMapperResults"></div><div class="clearfloat"></div></div>'
var topics = { var topics = {
@ -71,8 +71,8 @@ const Search = {
url: '/search/topics', url: '/search/topics',
prepare: function(query, settings) { prepare: function(query, settings) {
settings.url += '?term=' + query settings.url += '?term=' + query
if (Active.Mapper && self.limitTopicsToMe) { if (ReactApp.currentUser && self.limitTopicsToMe) {
settings.url += '&user=' + Active.Mapper.id.toString() settings.url += '&user=' + ReactApp.currentUser.id.toString()
} }
return settings return settings
} }
@ -104,8 +104,8 @@ const Search = {
url: '/search/maps', url: '/search/maps',
prepare: function(query, settings) { prepare: function(query, settings) {
settings.url += '?term=' + query settings.url += '?term=' + query
if (Active.Mapper && self.limitMapsToMe) { if (ReactApp.currentUser && self.limitMapsToMe) {
settings.url += '&user=' + Active.Mapper.id.toString() settings.url += '&user=' + ReactApp.currentUser.id.toString()
} }
return settings return settings
} }

View file

@ -2,8 +2,6 @@
import clipboard from 'clipboard-js' import clipboard from 'clipboard-js'
import Create from '../Create'
import ReactApp from './ReactApp' import ReactApp from './ReactApp'
import Search from './Search' import Search from './Search'
import CreateMap from './CreateMap' import CreateMap from './CreateMap'
@ -67,7 +65,7 @@ const GlobalUI = {
}, 200) }, 200)
if (which === 'switchMetacodes') { if (which === 'switchMetacodes') {
Create.isSwitchingSet = true ReactApp.openMap && (ReactApp.openMap.Create.isSwitchingSet = true)
} }
}, },
@ -91,8 +89,8 @@ const GlobalUI = {
if (self.lightbox === 'forkmap') GlobalUI.CreateMap.reset('fork_map') if (self.lightbox === 'forkmap') GlobalUI.CreateMap.reset('fork_map')
if (self.lightbox === 'newmap') GlobalUI.CreateMap.reset('new_map') if (self.lightbox === 'newmap') GlobalUI.CreateMap.reset('new_map')
if (Create && Create.isSwitchingSet) { if (ReactApp.openMap && ReactApp.openMap.Create.isSwitchingSet) {
Create.cancelMetacodeSetSwitch() ReactApp.openMap.Create.cancelMetacodeSetSwitch()
} }
self.lightbox = null self.lightbox = null
}, },

View file

@ -1,8 +1,8 @@
const Active = (map = null, mapper = null, topic = null) => { const Active = () => {
return { return {
Map: map, Map: null,
Mapper: mapper, Mapper: null,
Topic: topic Topic: null
} }
} }

View file

@ -2,9 +2,9 @@
import { indexOf } from 'lodash' import { indexOf } from 'lodash'
import Mapper from './Mapper' import Mapper from '../Mapper'
const Cable = ({Active, Control, DataModel, Map, Synapse, Topic, ChatView, Visualize}) => { const Cable = (map) => {
const toExport = { const toExport = {
subscribeToMap: id => { subscribeToMap: id => {
let self = toExport let self = toExport
@ -25,12 +25,12 @@ const toExport = {
// containing only the information we need to determine whether the active mapper // containing only the information we need to determine whether the active mapper
// can view this synapse and the two topics it connects, // can view this synapse and the two topics it connects,
// then if we determine it can, we make a call for the full model // then if we determine it can, we make a call for the full model
const m = Active.Mapper const m = map.Active.Mapper
const s = new DataModel.Synapse(event.synapse) const s = new DataModel.Synapse(event.synapse)
const t1 = new DataModel.Topic(event.topic1) const t1 = new DataModel.Topic(event.topic1)
const t2 = new DataModel.Topic(event.topic2) const t2 = new DataModel.Topic(event.topic2)
if (t1.authorizeToShow(m) && t2.authorizeToShow(m) && s.authorizeToShow(m) && !DataModel.Synapses.get(event.synapse.id)) { if (t1.authorizeToShow(m) && t2.authorizeToShow(m) && s.authorizeToShow(m) && !map.DataModel.Synapses.get(event.synapse.id)) {
// refactor the heck outta this, its adding wicked wait time // refactor the heck outta this, its adding wicked wait time
var topic1, topic2, node1, node2, synapse, mapping, cancel, mapper var topic1, topic2, node1, node2, synapse, mapping, cancel, mapper
@ -41,24 +41,24 @@ const toExport = {
topic2 = synapse.getTopic2() topic2 = synapse.getTopic2()
node2 = topic2.get('node') node2 = topic2.get('node')
Synapse.renderSynapse(mapping, synapse, node1, node2, false) map.Synapse.renderSynapse(mapping, synapse, node1, node2, false)
} else if (!cancel) { } else if (!cancel) {
setTimeout(waitThenRenderSynapse, 10) setTimeout(waitThenRenderSynapse, 10)
} }
} }
mapper = DataModel.Mappers.get(event.synapse.user_id) mapper = map.DataModel.Mappers.get(event.synapse.user_id)
if (mapper === undefined) { if (mapper === undefined) {
Mapper.get(event.synapse.user_id, function(m) { Mapper.get(event.synapse.user_id, function(m) {
DataModel.Mappers.add(m) map.DataModel.Mappers.add(m)
mapper = m mapper = m
}) })
} }
$.ajax({ $.ajax({
url: '/synapses/' + event.synapse.id + '.json', url: '/synapses/' + event.synapse.id + '.json',
success: function(response) { success: function(response) {
DataModel.Synapses.add(response) map.DataModel.Synapses.add(response)
synapse = DataModel.Synapses.get(response.id) synapse = map.DataModel.Synapses.get(response.id)
}, },
error: function() { error: function() {
cancel = true cancel = true
@ -67,8 +67,8 @@ const toExport = {
$.ajax({ $.ajax({
url: '/mappings/' + event.mapping_id + '.json', url: '/mappings/' + event.mapping_id + '.json',
success: function(response) { success: function(response) {
DataModel.Mappings.add(response) map.DataModel.Mappings.add(response)
mapping = DataModel.Mappings.get(response.id) mapping = map.DataModel.Mappings.get(response.id)
}, },
error: function() { error: function() {
cancel = true cancel = true
@ -79,7 +79,7 @@ const toExport = {
}, },
synapseUpdated: event => { synapseUpdated: event => {
// TODO: handle case where permission changed // TODO: handle case where permission changed
var synapse = DataModel.Synapses.get(event.id) var synapse = map.DataModel.Synapses.get(event.id)
if (synapse) { if (synapse) {
// edge reset necessary because fetch causes model reset // edge reset necessary because fetch causes model reset
var edge = synapse.get('edge') var edge = synapse.get('edge')
@ -92,12 +92,12 @@ const toExport = {
} }
}, },
synapseRemoved: event => { synapseRemoved: event => {
var synapse = DataModel.Synapses.get(event.id) var synapse = map.DataModel.Synapses.get(event.id)
if (synapse) { if (synapse) {
var edge = synapse.get('edge') var edge = synapse.get('edge')
var mapping = synapse.getMapping() var mapping = synapse.getMapping()
if (edge.getData('mappings').length - 1 === 0) { if (edge.getData('mappings').length - 1 === 0) {
Control.hideEdge(edge) map.Control.hideEdge(edge)
} }
var index = indexOf(edge.getData('synapses'), synapse) var index = indexOf(edge.getData('synapses'), synapse)
@ -106,41 +106,41 @@ const toExport = {
if (edge.getData('displayIndex')) { if (edge.getData('displayIndex')) {
delete edge.data.$displayIndex delete edge.data.$displayIndex
} }
DataModel.Synapses.remove(synapse) map.DataModel.Synapses.remove(synapse)
DataModel.Mappings.remove(mapping) map.DataModel.Mappings.remove(mapping)
} }
}, },
topicAdded: event => { topicAdded: event => {
const m = Active.Mapper const m = map.Active.Mapper
// we receive a contentless model from the server // we receive a contentless model from the server
// containing only the information we need to determine whether the active mapper // containing only the information we need to determine whether the active mapper
// can view this topic, then if we determine it can, we make a call for the full model // can view this topic, then if we determine it can, we make a call for the full model
const t = new DataModel.Topic(event.topic) const t = new DataModel.Topic(event.topic)
if (t.authorizeToShow(m) && !DataModel.Topics.get(event.topic.id)) { if (t.authorizeToShow(m) && !map.DataModel.Topics.get(event.topic.id)) {
// refactor the heck outta this, its adding wicked wait time // refactor the heck outta this, its adding wicked wait time
var topic, mapping, mapper, cancel var topic, mapping, mapper, cancel
const waitThenRenderTopic = () => { const waitThenRenderTopic = () => {
if (topic && mapping && mapper) { if (topic && mapping && mapper) {
Topic.renderTopic(mapping, topic, false, false) map.Topic.renderTopic(mapping, topic, false, false)
} else if (!cancel) { } else if (!cancel) {
setTimeout(waitThenRenderTopic, 10) setTimeout(waitThenRenderTopic, 10)
} }
} }
mapper = DataModel.Mappers.get(event.topic.user_id) mapper = map.DataModel.Mappers.get(event.topic.user_id)
if (mapper === undefined) { if (mapper === undefined) {
Mapper.get(event.topic.user_id, function(m) { Mapper.get(event.topic.user_id, function(m) {
DataModel.Mappers.add(m) map.DataModel.Mappers.add(m)
mapper = m mapper = m
}) })
} }
$.ajax({ $.ajax({
url: '/topics/' + event.topic.id + '.json', url: '/topics/' + event.topic.id + '.json',
success: function(response) { success: function(response) {
DataModel.Topics.add(response) map.DataModel.Topics.add(response)
topic = DataModel.Topics.get(response.id) topic = map.DataModel.Topics.get(response.id)
}, },
error: function() { error: function() {
cancel = true cancel = true
@ -149,8 +149,8 @@ const toExport = {
$.ajax({ $.ajax({
url: '/mappings/' + event.mapping_id + '.json', url: '/mappings/' + event.mapping_id + '.json',
success: function(response) { success: function(response) {
DataModel.Mappings.add(response) map.DataModel.Mappings.add(response)
mapping = DataModel.Mappings.get(response.id) mapping = map.DataModel.Mappings.get(response.id)
}, },
error: function() { error: function() {
cancel = true cancel = true
@ -161,7 +161,7 @@ const toExport = {
}, },
topicUpdated: event => { topicUpdated: event => {
// TODO: handle case where permission changed // TODO: handle case where permission changed
var topic = DataModel.Topics.get(event.id) var topic = map.DataModel.Topics.get(event.id)
if (topic) { if (topic) {
var node = topic.get('node') var node = topic.get('node')
topic.fetch({ topic.fetch({
@ -174,38 +174,38 @@ const toExport = {
}, },
topicMoved: event => { topicMoved: event => {
var topic, node, mapping var topic, node, mapping
if (Active.Map) { if (map.Active.Map) {
topic = DataModel.Topics.get(event.id) topic = map.DataModel.Topics.get(event.id)
mapping = DataModel.Mappings.get(event.mapping_id) mapping = map.DataModel.Mappings.get(event.mapping_id)
mapping.set('xloc', event.x) mapping.set('xloc', event.x)
mapping.set('yloc', event.y) mapping.set('yloc', event.y)
if (topic) node = topic.get('node') if (topic) node = topic.get('node')
if (node) node.pos.setc(event.x, event.y) if (node) node.pos.setc(event.x, event.y)
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
} }
}, },
topicRemoved: event => { topicRemoved: event => {
var topic = DataModel.Topics.get(event.id) var topic = map.DataModel.Topics.get(event.id)
if (topic) { if (topic) {
var node = topic.get('node') var node = topic.get('node')
var mapping = topic.getMapping() var mapping = topic.getMapping()
Control.hideNode(node.id) map.Control.hideNode(node.id)
DataModel.Topics.remove(topic) map.DataModel.Topics.remove(topic)
DataModel.Mappings.remove(mapping) map.DataModel.Mappings.remove(mapping)
} }
}, },
messageCreated: event => { messageCreated: event => {
if (Active.Mapper && Active.Mapper.id === event.message.user_id) return if (map.Active.Mapper && map.Active.Mapper.id === event.message.user_id) return
ChatView.addMessages(new DataModel.MessageCollection(event.message)) map.ChatView.addMessages(new DataModel.MessageCollection(event.message))
}, },
mapUpdated: event => { mapUpdated: event => {
var map = Active.Map var map = map.Active.Map
var couldEditBefore = map.authorizeToEdit(Active.Mapper) var couldEditBefore = map.authorizeToEdit(map.Active.Mapper)
var idBefore = map.id var idBefore = map.id
map.fetch({ map.fetch({
success: function(model, response) { success: function(model, response) {
var idNow = model.id var idNow = model.id
var canEditNow = model.authorizeToEdit(Active.Mapper) var canEditNow = model.authorizeToEdit(map.Active.Mapper)
if (idNow !== idBefore) { if (idNow !== idBefore) {
Map.leavePrivateMap() // this means the map has been changed to private Map.leavePrivateMap() // this means the map has been changed to private
} else if (couldEditBefore && !canEditNow) { } else if (couldEditBefore && !canEditNow) {

View file

@ -5,7 +5,7 @@ import { Howl } from 'howler'
import ReactApp from '../GlobalUI/ReactApp' import ReactApp from '../GlobalUI/ReactApp'
const ChatView = ({Active, DataModel}) => { const ChatView = (map) => {
const toExport = { const toExport = {
isOpen: false, isOpen: false,
unreadMessages: 0, unreadMessages: 0,
@ -39,7 +39,7 @@ const toExport = {
self.render() self.render()
}, },
render: () => { render: () => {
if (!Active.Map) return if (!map.Active.Map) return
const self = toExport const self = toExport
ReactApp.render() ReactApp.render()
}, },
@ -127,7 +127,7 @@ const toExport = {
if (toExport.alertSound) toExport.sound.play('sendchat') if (toExport.alertSound) toExport.sound.play('sendchat')
var m = new DataModel.Message({ var m = new DataModel.Message({
message: message.message, message: message.message,
resource_id: Active.Map.id, resource_id: map.Active.Map.id,
resource_type: 'Map' resource_type: 'Map'
}) })
m.save(null, { m.save(null, {

View file

@ -1,59 +1,59 @@
import _ from 'lodash' import _ from 'lodash'
import outdent from 'outdent' import outdent from 'outdent'
import GlobalUI from './GlobalUI' import GlobalUI from '../GlobalUI'
import Settings from './Settings' import Settings from '../Settings'
const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => { const Control = (map) => {
return { return {
selectNode: function(node, e) { selectNode: function(node, e) {
var filtered = node.getData('alpha') === 0 var filtered = node.getData('alpha') === 0
if (filtered || Selected.Nodes.indexOf(node) !== -1) return if (filtered || map.Selected.Nodes.indexOf(node) !== -1) return
node.selected = true node.selected = true
node.setData('dim', 30, 'current') node.setData('dim', 30, 'current')
Selected.Nodes.push(node) map.Selected.Nodes.push(node)
}, },
selectNeighbors: function() { selectNeighbors: function() {
if (Selected.Nodes.length > 0) { if (map.Selected.Nodes.length > 0) {
//For each selected node, select all connected node and the synapses too //For each selected node, select all connected node and the synapses too
Selected.Nodes.forEach((item) => { map.Selected.Nodes.forEach((item) => {
if (Visualize.mGraph.graph.getNode(item.id).adjacencies) { if (map.Visualize.mGraph.graph.getNode(item.id).adjacencies) {
for (const adjID in Visualize.mGraph.graph.getNode(item.id).adjacencies) { for (const adjID in map.Visualize.mGraph.graph.getNode(item.id).adjacencies) {
Control.selectNode(Visualize.mGraph.graph.getNode(adjID)) map.Control.selectNode(map.Visualize.mGraph.graph.getNode(adjID))
Control.selectEdge(Visualize.mGraph.graph.getNode(item.id).adjacencies[adjID]) map.Control.selectEdge(map.Visualize.mGraph.graph.getNode(item.id).adjacencies[adjID])
} }
} }
}) })
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
} }
}, },
deselectAllNodes: function() { deselectAllNodes: function() {
var l = Selected.Nodes.length var l = map.Selected.Nodes.length
for (var i = l - 1; i >= 0; i -= 1) { for (var i = l - 1; i >= 0; i -= 1) {
var node = Selected.Nodes[i] var node = map.Selected.Nodes[i]
Control.deselectNode(node) map.Control.deselectNode(node)
} }
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
}, },
deselectNode: function(node) { deselectNode: function(node) {
delete node.selected delete node.selected
node.setData('dim', 25, 'current') node.setData('dim', 25, 'current')
// remove the node // remove the node
Selected.Nodes.splice( map.Selected.Nodes.splice(
Selected.Nodes.indexOf(node), 1) map.Selected.Nodes.indexOf(node), 1)
}, },
deleteSelected: function() { deleteSelected: function() {
if (!Active.Map) return if (!map.Active.Map) return
var n = Selected.Nodes.length var n = map.Selected.Nodes.length
var e = Selected.Edges.length var e = map.Selected.Edges.length
var ntext = n === 1 ? '1 topic' : n + ' topics' var ntext = n === 1 ? '1 topic' : n + ' topics'
var etext = e === 1 ? '1 synapse' : e + ' synapses' var etext = e === 1 ? '1 synapse' : e + ' synapses'
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = map.Active.Map.authorizeToEdit(map.Active.Mapper)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit Public map.') GlobalUI.notifyUser('Cannot edit Public map.')
@ -65,162 +65,162 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
to permanently delete them all? This will remove them from all to permanently delete them all? This will remove them from all
maps they appear on.`) maps they appear on.`)
if (r) { if (r) {
Control.deleteSelectedEdges() map.Control.deleteSelectedEdges()
Control.deleteSelectedNodes() map.Control.deleteSelectedNodes()
} }
if (DataModel.Topics.length === 0) { if (map.DataModel.Topics.length === 0) {
Map.setHasLearnedTopicCreation(false) Map.setHasLearnedTopicCreation(false)
} }
}, },
deleteSelectedNodes: function() { // refers to deleting topics permanently deleteSelectedNodes: function() { // refers to deleting topics permanently
if (!Active.Map) return if (!map.Active.Map) return
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = map.Active.Map.authorizeToEdit(map.Active.Mapper)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit Public map.') GlobalUI.notifyUser('Cannot edit Public map.')
return return
} }
var l = Selected.Nodes.length var l = map.Selected.Nodes.length
for (var i = l - 1; i >= 0; i -= 1) { for (var i = l - 1; i >= 0; i -= 1) {
var node = Selected.Nodes[i] var node = map.Selected.Nodes[i]
Control.deleteNode(node.id) map.Control.deleteNode(node.id)
} }
}, },
deleteNode: function(nodeid) { // refers to deleting topics permanently deleteNode: function(nodeid) { // refers to deleting topics permanently
if (!Active.Map) return if (!map.Active.Map) return
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = map.Active.Map.authorizeToEdit(map.Active.Mapper)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit Public map.') GlobalUI.notifyUser('Cannot edit Public map.')
return return
} }
var node = Visualize.mGraph.graph.getNode(nodeid) var node = map.Visualize.mGraph.graph.getNode(nodeid)
var topic = node.getData('topic') var topic = node.getData('topic')
var permToDelete = Active.Mapper.id === topic.get('user_id') || Active.Mapper.get('admin') var permToDelete = map.Active.Mapper.id === topic.get('user_id') || map.Active.Mapper.get('admin')
if (permToDelete) { if (permToDelete) {
var mapping = node.getData('mapping') var mapping = node.getData('mapping')
topic.destroy() topic.destroy()
DataModel.Mappings.remove(mapping) map.DataModel.Mappings.remove(mapping)
Control.hideNode(nodeid) map.Control.hideNode(nodeid)
} else { } else {
GlobalUI.notifyUser('Only topics you created can be deleted') GlobalUI.notifyUser('Only topics you created can be deleted')
} }
}, },
removeSelectedNodes: function() { // refers to removing topics permanently from a map removeSelectedNodes: function() { // refers to removing topics permanently from a map
if (Active.Topic) { if (map.Active.Topic) {
// hideNode will handle synapses as well // hideNode will handle synapses as well
var nodeids = _.map(Selected.Nodes, function(node) { var nodeids = _.map(map.Selected.Nodes, function(node) {
return node.id return node.id
}) })
_.each(nodeids, function(nodeid) { _.each(nodeids, function(nodeid) {
if (Active.Topic.id !== nodeid) { if (map.Active.Topic.id !== nodeid) {
DataModel.Topics.remove(nodeid) map.DataModel.Topics.remove(nodeid)
Control.hideNode(nodeid) map.Control.hideNode(nodeid)
} }
}) })
return return
} }
if (!Active.Map) return if (!map.Active.Map) return
const l = Selected.Nodes.length const l = map.Selected.Nodes.length
const authorized = Active.Map.authorizeToEdit(Active.Mapper) const authorized = map.Active.Map.authorizeToEdit(map.Active.Mapper)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit this map.') GlobalUI.notifyUser('Cannot edit this map.')
return return
} }
if (Active.Mapper.get('follow_map_on_contributed')) { if (map.Active.Mapper.get('follow_map_on_contributed')) {
Active.Mapper.followMap(Active.Map.id) map.Active.Mapper.followMap(map.Active.Map.id)
} }
for (let i = l - 1; i >= 0; i -= 1) { for (let i = l - 1; i >= 0; i -= 1) {
const node = Selected.Nodes[i] const node = map.Selected.Nodes[i]
Control.removeNode(node.id) map.Control.removeNode(node.id)
} }
}, },
removeNode: function(nodeid) { // refers to removing topics permanently from a map removeNode: function(nodeid) { // refers to removing topics permanently from a map
if (!Active.Map) return if (!map.Active.Map) return
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = map.Active.Map.authorizeToEdit(map.Active.Mapper)
var node = Visualize.mGraph.graph.getNode(nodeid) var node = map.Visualize.mGraph.graph.getNode(nodeid)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit this map.') GlobalUI.notifyUser('Cannot edit this map.')
return return
} }
if (Active.Mapper.get('follow_map_on_contributed')) { if (map.Active.Mapper.get('follow_map_on_contributed')) {
Active.Mapper.followMap(Active.Map.id) map.Active.Mapper.followMap(map.Active.Map.id)
} }
var topic = node.getData('topic') var topic = node.getData('topic')
var mapping = node.getData('mapping') var mapping = node.getData('mapping')
mapping.destroy() mapping.destroy()
DataModel.Topics.remove(topic) map.DataModel.Topics.remove(topic)
Control.hideNode(nodeid) map.Control.hideNode(nodeid)
}, },
hideSelectedNodes: function() { hideSelectedNodes: function() {
const l = Selected.Nodes.length const l = map.Selected.Nodes.length
for (let i = l - 1; i >= 0; i -= 1) { for (let i = l - 1; i >= 0; i -= 1) {
const node = Selected.Nodes[i] const node = map.Selected.Nodes[i]
Control.hideNode(node.id) map.Control.hideNode(node.id)
} }
}, },
hideNode: function(nodeid) { hideNode: function(nodeid) {
var node = Visualize.mGraph.graph.getNode(nodeid) var node = map.Visualize.mGraph.graph.getNode(nodeid)
var graph = Visualize.mGraph var graph = map.Visualize.mGraph
Control.deselectNode(node) map.Control.deselectNode(node)
node.setData('alpha', 0, 'end') node.setData('alpha', 0, 'end')
node.eachAdjacency(function(adj) { node.eachAdjacency(function(adj) {
adj.setData('alpha', 0, 'end') adj.setData('alpha', 0, 'end')
}) })
Visualize.mGraph.fx.animate({ map.Visualize.mGraph.fx.animate({
modes: ['node-property:alpha', modes: ['node-property:alpha',
'edge-property:alpha' 'edge-property:alpha'
], ],
duration: 500 duration: 500
}) })
setTimeout(function() { setTimeout(function() {
if (nodeid === Visualize.mGraph.root) { // && Visualize.type === "RGraph" if (nodeid === map.Visualize.mGraph.root) { // && map.Visualize.type === "RGraph"
var newroot = _.find(graph.graph.nodes, function(n) { return n.id !== nodeid }) var newroot = _.find(graph.graph.nodes, function(n) { return n.id !== nodeid })
graph.root = newroot ? newroot.id : null graph.root = newroot ? newroot.id : null
} }
Visualize.mGraph.graph.removeNode(nodeid) map.Visualize.mGraph.graph.removeNode(nodeid)
}, 500) }, 500)
Filter.checkMetacodes() map.Filter.checkMetacodes()
Filter.checkMappers() map.Filter.checkMappers()
}, },
selectEdge: function(edge) { selectEdge: function(edge) {
var filtered = edge.getData('alpha') === 0 // don't select if the edge is filtered var filtered = edge.getData('alpha') === 0 // don't select if the edge is filtered
if (filtered || Selected.Edges.indexOf(edge) !== -1) return if (filtered || map.Selected.Edges.indexOf(edge) !== -1) return
var width = Mouse.edgeHoveringOver === edge ? 4 : 2 var width = map.Mouse.edgeHoveringOver === edge ? 4 : 2
edge.setDataset('current', { edge.setDataset('current', {
showDesc: true, showDesc: true,
lineWidth: width, lineWidth: width,
color: Settings.colors.synapses.selected color: Settings.colors.synapses.selected
}) })
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
Selected.Edges.push(edge) map.Selected.Edges.push(edge)
}, },
deselectAllEdges: function() { deselectAllEdges: function() {
var l = Selected.Edges.length var l = map.Selected.Edges.length
for (var i = l - 1; i >= 0; i -= 1) { for (var i = l - 1; i >= 0; i -= 1) {
var edge = Selected.Edges[i] var edge = map.Selected.Edges[i]
Control.deselectEdge(edge) map.Control.deselectEdge(edge)
} }
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
}, },
deselectEdge: function(edge) { deselectEdge: function(edge) {
edge.setData('showDesc', false, 'current') edge.setData('showDesc', false, 'current')
@ -230,39 +230,39 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
color: Settings.colors.synapses.normal color: Settings.colors.synapses.normal
}) })
if (Mouse.edgeHoveringOver === edge) { if (map.Mouse.edgeHoveringOver === edge) {
edge.setDataset('current', { edge.setDataset('current', {
showDesc: true, showDesc: true,
lineWidth: 4 lineWidth: 4
}) })
} }
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
// remove the edge // remove the edge
Selected.Edges.splice( map.Selected.Edges.splice(
Selected.Edges.indexOf(edge), 1) map.Selected.Edges.indexOf(edge), 1)
}, },
deleteSelectedEdges: function() { // refers to deleting topics permanently deleteSelectedEdges: function() { // refers to deleting topics permanently
if (!Active.Map) return if (!map.Active.Map) return
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = map.Active.Map.authorizeToEdit(map.Active.Mapper)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit Public map.') GlobalUI.notifyUser('Cannot edit Public map.')
return return
} }
const l = Selected.Edges.length const l = map.Selected.Edges.length
for (let i = l - 1; i >= 0; i -= 1) { for (let i = l - 1; i >= 0; i -= 1) {
const edge = Selected.Edges[i] const edge = map.Selected.Edges[i]
Control.deleteEdge(edge) map.Control.deleteEdge(edge)
} }
}, },
deleteEdge: function(edge) { deleteEdge: function(edge) {
if (!Active.Map) return if (!map.Active.Map) return
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = map.Active.Map.authorizeToEdit(map.Active.Mapper)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit Public map.') GlobalUI.notifyUser('Cannot edit Public map.')
@ -274,15 +274,15 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
var synapse = edge.getData('synapses')[index] var synapse = edge.getData('synapses')[index]
var mapping = edge.getData('mappings')[index] var mapping = edge.getData('mappings')[index]
var permToDelete = Active.Mapper.id === synapse.get('user_id') || Active.Mapper.get('admin') var permToDelete = map.Active.Mapper.id === synapse.get('user_id') || map.Active.Mapper.get('admin')
if (permToDelete) { if (permToDelete) {
if (edge.getData('synapses').length - 1 === 0) { if (edge.getData('synapses').length - 1 === 0) {
Control.hideEdge(edge) map.Control.hideEdge(edge)
} }
synapse.destroy() synapse.destroy()
// the server will destroy the mapping, we just need to remove it here // the server will destroy the mapping, we just need to remove it here
DataModel.Mappings.remove(mapping) map.DataModel.Mappings.remove(mapping)
edge.getData('mappings').splice(index, 1) edge.getData('mappings').splice(index, 1)
edge.getData('synapses').splice(index, 1) edge.getData('synapses').splice(index, 1)
if (edge.getData('displayIndex')) { if (edge.getData('displayIndex')) {
@ -294,43 +294,43 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
}, },
removeSelectedEdges: function() { removeSelectedEdges: function() {
// Topic view is handled by removeSelectedNodes // Topic view is handled by removeSelectedNodes
if (!Active.Map) return if (!map.Active.Map) return
const l = Selected.Edges.length const l = map.Selected.Edges.length
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = map.Active.Map.authorizeToEdit(map.Active.Mapper)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit this map.') GlobalUI.notifyUser('Cannot edit this map.')
return return
} }
if (Active.Mapper.get('follow_map_on_contributed')) { if (map.Active.Mapper.get('follow_map_on_contributed')) {
Active.Mapper.followMap(Active.Map.id) map.Active.Mapper.followMap(map.Active.Map.id)
} }
for (let i = l - 1; i >= 0; i -= 1) { for (let i = l - 1; i >= 0; i -= 1) {
const edge = Selected.Edges[i] const edge = map.Selected.Edges[i]
Control.removeEdge(edge) map.Control.removeEdge(edge)
} }
Selected.Edges = [ ] map.Selected.Edges = [ ]
}, },
removeEdge: function(edge) { removeEdge: function(edge) {
if (!Active.Map) return if (!map.Active.Map) return
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = map.Active.Map.authorizeToEdit(map.Active.Mapper)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit this map.') GlobalUI.notifyUser('Cannot edit this map.')
return return
} }
if (Active.Mapper.get('follow_map_on_contributed')) { if (map.Active.Mapper.get('follow_map_on_contributed')) {
Active.Mapper.followMap(Active.Map.id) map.Active.Mapper.followMap(map.Active.Map.id)
} }
if (edge.getData('mappings').length - 1 === 0) { if (edge.getData('mappings').length - 1 === 0) {
Control.hideEdge(edge) map.Control.hideEdge(edge)
} }
var index = edge.getData('displayIndex') ? edge.getData('displayIndex') : 0 var index = edge.getData('displayIndex') ? edge.getData('displayIndex') : 0
@ -339,7 +339,7 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
var mapping = edge.getData('mappings')[index] var mapping = edge.getData('mappings')[index]
mapping.destroy() mapping.destroy()
DataModel.Synapses.remove(synapse) map.DataModel.Synapses.remove(synapse)
edge.getData('mappings').splice(index, 1) edge.getData('mappings').splice(index, 1)
edge.getData('synapses').splice(index, 1) edge.getData('synapses').splice(index, 1)
@ -348,27 +348,27 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
} }
}, },
hideSelectedEdges: function() { hideSelectedEdges: function() {
const l = Selected.Edges.length const l = map.Selected.Edges.length
for (let i = l - 1; i >= 0; i -= 1) { for (let i = l - 1; i >= 0; i -= 1) {
const edge = Selected.Edges[i] const edge = map.Selected.Edges[i]
Control.hideEdge(edge) map.Control.hideEdge(edge)
} }
Selected.Edges = [ ] map.Selected.Edges = [ ]
}, },
hideEdge: function(edge) { hideEdge: function(edge) {
var from = edge.nodeFrom.id var from = edge.nodeFrom.id
var to = edge.nodeTo.id var to = edge.nodeTo.id
edge.setData('alpha', 0, 'end') edge.setData('alpha', 0, 'end')
Control.deselectEdge(edge) map.Control.deselectEdge(edge)
Visualize.mGraph.fx.animate({ map.Visualize.mGraph.fx.animate({
modes: ['edge-property:alpha'], modes: ['edge-property:alpha'],
duration: 500 duration: 500
}) })
setTimeout(function() { setTimeout(function() {
Visualize.mGraph.graph.removeAdjacence(from, to) map.Visualize.mGraph.graph.removeAdjacence(from, to)
}, 500) }, 500)
Filter.checkSynapses() map.Filter.checkSynapses()
Filter.checkMappers() map.Filter.checkMappers()
}, },
updateSelectedPermissions: function(permission) { updateSelectedPermissions: function(permission) {
var edge, synapse, node, topic var edge, synapse, node, topic
@ -380,12 +380,12 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
var sCount = 0 var sCount = 0
// change the permission of the selected synapses, if logged in user is the original creator // change the permission of the selected synapses, if logged in user is the original creator
const edgesLength = Selected.Edges.length const edgesLength = map.Selected.Edges.length
for (let i = edgesLength - 1; i >= 0; i -= 1) { for (let i = edgesLength - 1; i >= 0; i -= 1) {
edge = Selected.Edges[i] edge = map.Selected.Edges[i]
synapse = edge.getData('synapses')[0] synapse = edge.getData('synapses')[0]
if (synapse.authorizePermissionChange(Active.Mapper)) { if (synapse.authorizePermissionChange(map.Active.Mapper)) {
synapse.save({ synapse.save({
permission: permission permission: permission
}) })
@ -394,12 +394,12 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
} }
// change the permission of the selected topics, if logged in user is the original creator // change the permission of the selected topics, if logged in user is the original creator
const nodesLength = Selected.Nodes.length const nodesLength = map.Selected.Nodes.length
for (let i = nodesLength - 1; i >= 0; i -= 1) { for (let i = nodesLength - 1; i >= 0; i -= 1) {
node = Selected.Nodes[i] node = map.Selected.Nodes[i]
topic = node.getData('topic') topic = node.getData('topic')
if (topic.authorizePermissionChange(Active.Mapper)) { if (topic.authorizePermissionChange(map.Active.Mapper)) {
topic.save({ topic.save({
permission: permission permission: permission
}) })
@ -424,12 +424,12 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
var nCount = 0 var nCount = 0
// change the permission of the selected topics, if logged in user is the original creator // change the permission of the selected topics, if logged in user is the original creator
var l = Selected.Nodes.length var l = map.Selected.Nodes.length
for (var i = l - 1; i >= 0; i -= 1) { for (var i = l - 1; i >= 0; i -= 1) {
node = Selected.Nodes[i] node = map.Selected.Nodes[i]
topic = node.getData('topic') topic = node.getData('topic')
if (topic.authorizeToEdit(Active.Mapper)) { if (topic.authorizeToEdit(map.Active.Mapper)) {
topic.save({ topic.save({
'metacode_id': metacodeId 'metacode_id': metacodeId
}) })
@ -441,7 +441,7 @@ const Control = ({Active, DataModel, Filter, Mouse, Selected, Visualize}) => {
var message = nString + ' you can edit updated to ' + metacode.get('name') var message = nString + ' you can edit updated to ' + metacode.get('name')
GlobalUI.notifyUser(message) GlobalUI.notifyUser(message)
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
} }
} }
} }

View file

@ -1,8 +1,8 @@
/* global $, Hogan, Bloodhound */ /* global $, Hogan, Bloodhound */
import GlobalUI from './GlobalUI' import GlobalUI from '../GlobalUI'
const toExport = ({DataModel, Map, Mouse, Selected, Synapse, Topic, Visualize}) => { const toExport = (map) => {
const toExport = { const toExport = {
isSwitchingSet: false, // indicates whether the metacode set switch lightbox is open isSwitchingSet: false, // indicates whether the metacode set switch lightbox is open
selectedMetacodeSet: null, selectedMetacodeSet: null,
@ -103,8 +103,8 @@ const toExport = {
toExport.newSelectedMetacodeNames = [] toExport.newSelectedMetacodeNames = []
} else if (custom) { } else if (custom) {
// uses .slice to avoid setting the two arrays to the same actual array // uses .slice to avoid setting the two arrays to the same actual array
toExport.selectedMetacodes = Create.newSelectedMetacodes.slice(0) toExport.selectedMetacodes = map.Create.newSelectedMetacodes.slice(0)
toExport.selectedMetacodeNames = Create.newSelectedMetacodeNames.slice(0) toExport.selectedMetacodeNames = map.Create.newSelectedMetacodeNames.slice(0)
codesToSwitchToIds = toExport.selectedMetacodes.slice(0) codesToSwitchToIds = toExport.selectedMetacodes.slice(0)
} }
@ -137,7 +137,7 @@ const toExport = {
var mdata = { var mdata = {
'metacodes': { 'metacodes': {
'value': custom ? toExport.selectedMetacodes.toString() : Create.selectedMetacodeSet 'value': custom ? toExport.selectedMetacodes.toString() : map.Create.selectedMetacodeSet
} }
} }
$.ajax({ $.ajax({
@ -276,7 +276,7 @@ const toExport = {
$('.pinCarousel').removeClass('isPinned') $('.pinCarousel').removeClass('isPinned')
toExport.newTopic.pinned = false toExport.newTopic.pinned = false
} }
if (DataModel.Topics.length === 0) { if (map.DataModel.Topics.length === 0) {
Map.setHasLearnedTopicCreation(false) Map.setHasLearnedTopicCreation(false)
} }
toExport.newTopic.beingCreated = false toExport.newTopic.beingCreated = false
@ -301,7 +301,7 @@ const toExport = {
remote: { remote: {
url: '/search/synapses?topic1id=%TOPIC1&topic2id=%TOPIC2', url: '/search/synapses?topic1id=%TOPIC1&topic2id=%TOPIC2',
prepare: function(query, settings) { prepare: function(query, settings) {
if (Selected.Nodes.length < 2 && toExport.newSynapse.topic1id && self.newSynapse.topic2id) { if (map.Selected.Nodes.length < 2 && toExport.newSynapse.topic1id && self.newSynapse.topic2id) {
settings.url = settings.url.replace('%TOPIC1', toExport.newSynapse.topic1id).replace('%TOPIC2', toExport.newSynapse.topic2id) settings.url = settings.url.replace('%TOPIC1', toExport.newSynapse.topic1id).replace('%TOPIC2', toExport.newSynapse.topic2id)
return settings return settings
} else { } else {
@ -353,7 +353,7 @@ const toExport = {
$('#synapse_desc').focusout(function() { $('#synapse_desc').focusout(function() {
if (toExport.newSynapse.beingCreated) { if (toExport.newSynapse.beingCreated) {
Synapse.createSynapseLocally() map.Synapse.createSynapseLocally()
} }
}) })
@ -361,7 +361,7 @@ const toExport = {
const TAB = 9 const TAB = 9
if (toExport.newSynapse.beingCreated && e.keyCode === TAB) { if (toExport.newSynapse.beingCreated && e.keyCode === TAB) {
e.preventDefault() e.preventDefault()
Synapse.createSynapseLocally() map.Synapse.createSynapseLocally()
} }
}) })
@ -370,7 +370,7 @@ const toExport = {
Synapse.getSynapseFromAutocomplete(datum.id) Synapse.getSynapseFromAutocomplete(datum.id)
} else { } else {
toExport.newSynapse.description = datum.value toExport.newSynapse.description = datum.value
Synapse.createSynapseLocally() map.Synapse.createSynapseLocally()
} }
}) })
}, },
@ -392,8 +392,8 @@ const toExport = {
toExport.newTopic.addSynapse = false toExport.newTopic.addSynapse = false
toExport.newSynapse.topic1id = 0 toExport.newSynapse.topic1id = 0
toExport.newSynapse.topic2id = 0 toExport.newSynapse.topic2id = 0
Mouse.synapseStartCoordinates = [] map.Mouse.synapseStartCoordinates = []
if (Visualize.mGraph) Visualize.mGraph.plot() if (map.Visualize.mGraph) map.Visualize.mGraph.plot()
} }
} }
} }

View file

@ -2,10 +2,10 @@
import _ from 'lodash' import _ from 'lodash'
import GlobalUI, { ReactApp } from './GlobalUI' import GlobalUI, { ReactApp } from '../GlobalUI'
import Settings from './Settings' import Settings from '../Settings'
const Filter = ({Active, Control, DataModel, Visualize}) => { const Filter = (map) => {
const toExport = { const toExport = {
dataForPresentation: { dataForPresentation: {
metacodes: {}, metacodes: {},
@ -99,7 +99,7 @@ const toExport = {
}, },
checkMappers: function() { checkMappers: function() {
var self = toExport var self = toExport
if (Active.Map) { if (map.Active.Map) {
self.updateFilters('Mappings', 'user_id', 'Mappers', 'mappers', 'mapper') self.updateFilters('Mappings', 'user_id', 'Mappers', 'mappers', 'mapper')
} else { } else {
// on topic view // on topic view
@ -160,16 +160,16 @@ const toExport = {
var passesMetacode, passesMapper, passesSynapse var passesMetacode, passesMapper, passesSynapse
var opacityForFilter = Active.Map ? 0 : 0.4 var opacityForFilter = map.Active.Map ? 0 : 0.4
DataModel.Topics.each(function(topic) { map.DataModel.Topics.each(function(topic) {
var n = topic.get('node') var n = topic.get('node')
var metacodeId = topic.get('metacode_id').toString() var metacodeId = topic.get('metacode_id').toString()
if (visible.metacodes.indexOf(metacodeId) === -1) passesMetacode = false if (visible.metacodes.indexOf(metacodeId) === -1) passesMetacode = false
else passesMetacode = true else passesMetacode = true
if (Active.Map) { if (map.Active.Map) {
// when on a map, // when on a map,
// we filter by mapper according to the person who added the // we filter by mapper according to the person who added the
// topic or synapse to the map // topic or synapse to the map
@ -193,10 +193,10 @@ const toExport = {
} }
} else { } else {
if (n) { if (n) {
Control.deselectNode(n, true) map.Control.deselectNode(n, true)
n.setData('alpha', opacityForFilter, 'end') n.setData('alpha', opacityForFilter, 'end')
n.eachAdjacency(function(e) { n.eachAdjacency(function(e) {
Control.deselectEdge(e, true) map.Control.deselectEdge(e, true)
}) })
} else { } else {
console.log(topic) console.log(topic)
@ -205,11 +205,11 @@ const toExport = {
}) })
// flag all the edges back to 'untouched' // flag all the edges back to 'untouched'
DataModel.Synapses.each(function(synapse) { map.DataModel.Synapses.each(function(synapse) {
var e = synapse.get('edge') var e = synapse.get('edge')
e.setData('touched', false) e.setData('touched', false)
}) })
DataModel.Synapses.each(function(synapse) { map.DataModel.Synapses.each(function(synapse) {
var e = synapse.get('edge') var e = synapse.get('edge')
var desc var desc
var userId = synapse.get('user_id').toString() var userId = synapse.get('user_id').toString()
@ -241,7 +241,7 @@ const toExport = {
} }
} }
if (Active.Map) { if (map.Active.Map) {
// when on a map, // when on a map,
// we filter by mapper according to the person who added the // we filter by mapper according to the person who added the
// topic or synapse to the map // topic or synapse to the map
@ -255,7 +255,7 @@ const toExport = {
e.setData('alpha', 1, 'end') e.setData('alpha', 1, 'end')
e.setData('color', color, 'end') e.setData('color', color, 'end')
} else { } else {
Control.deselectEdge(e, true) map.Control.deselectEdge(e, true)
e.setData('alpha', opacityForFilter, 'end') e.setData('alpha', opacityForFilter, 'end')
} }
@ -266,7 +266,7 @@ const toExport = {
}) })
// run the animation // run the animation
Visualize.mGraph.fx.animate({ map.Visualize.mGraph.fx.animate({
modes: ['node-property:alpha', modes: ['node-property:alpha',
'edge-property:alpha'], 'edge-property:alpha'],
duration: 200 duration: 200

View file

@ -3,9 +3,9 @@
import parse from 'csv-parse' import parse from 'csv-parse'
import _ from 'lodash' import _ from 'lodash'
import GlobalUI from './GlobalUI' import GlobalUI from '../GlobalUI'
const Import = ({Active, AutoLayout, DataModel, Map, Synapse, Topic}) => { const Import = (map) => {
const toExport = { const toExport = {
// note that user is not imported // note that user is not imported
topicWhitelist: [ topicWhitelist: [
@ -213,7 +213,7 @@ const toExport = {
parsedTopics.forEach(topic => { parsedTopics.forEach(topic => {
let coords = { x: topic.x, y: topic.y } let coords = { x: topic.x, y: topic.y }
if (!coords.x || !coords.y) { if (!coords.x || !coords.y) {
coords = AutoLayout.getNextCoord({ mappings: DataModel.Mappings }) coords = map.AutoLayout.getNextCoord({ mappings: map.DataModel.Mappings })
} }
if (!topic.name && topic.link || if (!topic.name && topic.link ||
@ -240,10 +240,10 @@ const toExport = {
parsedSynapses.forEach(function(synapse) { parsedSynapses.forEach(function(synapse) {
// only createSynapseWithParameters once both topics are persisted // only createSynapseWithParameters once both topics are persisted
// if there isn't a cidMapping, check by topic name instead // if there isn't a cidMapping, check by topic name instead
var topic1 = DataModel.Topics.get(self.cidMappings[synapse.topic1]) var topic1 = map.DataModel.Topics.get(self.cidMappings[synapse.topic1])
if (!topic1) topic1 = DataModel.Topics.findWhere({ name: synapse.topic1 }) if (!topic1) topic1 = map.DataModel.Topics.findWhere({ name: synapse.topic1 })
var topic2 = DataModel.Topics.get(self.cidMappings[synapse.topic2]) var topic2 = map.DataModel.Topics.get(self.cidMappings[synapse.topic2])
if (!topic2) topic2 = DataModel.Topics.findWhere({ name: synapse.topic2 }) if (!topic2) topic2 = map.DataModel.Topics.findWhere({ name: synapse.topic2 })
if (!topic1 || !topic2) { if (!topic1 || !topic2) {
console.error("One of the two topics doesn't exist!") console.error("One of the two topics doesn't exist!")
@ -282,8 +282,8 @@ const toExport = {
console.warn("Couldn't find metacode " + metacodeName + ' so used Wildcard instead.') console.warn("Couldn't find metacode " + metacodeName + ' so used Wildcard instead.')
} }
const topicPermision = permission || Active.Map.get('permission') const topicPermision = permission || map.Active.Map.get('permission')
var deferToMapId = permission === topicPermision ? Active.Map.get('id') : null var deferToMapId = permission === topicPermision ? map.Active.Map.get('id') : null
var topic = new DataModel.Topic({ var topic = new DataModel.Topic({
name: name, name: name,
metacode_id: metacode.id, metacode_id: metacode.id,
@ -292,7 +292,7 @@ const toExport = {
desc: desc || '', desc: desc || '',
link: link || '' link: link || ''
}) })
DataModel.Topics.add(topic) map.DataModel.Topics.add(topic)
if (importId !== null && importId !== undefined) { if (importId !== null && importId !== undefined) {
self.cidMappings[importId] = topic.cid self.cidMappings[importId] = topic.cid
@ -304,14 +304,14 @@ const toExport = {
mappable_id: topic.cid, mappable_id: topic.cid,
mappable_type: 'Topic' mappable_type: 'Topic'
}) })
DataModel.Mappings.add(mapping) map.DataModel.Mappings.add(mapping)
// this function also includes the creation of the topic in the database // this function also includes the creation of the topic in the database
Topic.renderTopic(mapping, topic, true, true, { map.Topic.renderTopic(mapping, topic, true, true, {
success: opts.success success: opts.success
}) })
Map.setHasLearnedTopicCreation(true) map.Map.setHasLearnedTopicCreation(true)
}, },
createSynapseWithParameters: function(desc, category, permission, createSynapseWithParameters: function(desc, category, permission,
@ -331,21 +331,21 @@ const toExport = {
topic1_id: topic1.id, topic1_id: topic1.id,
topic2_id: topic2.id topic2_id: topic2.id
}) })
DataModel.Synapses.add(synapse) map.DataModel.Synapses.add(synapse)
var mapping = new DataModel.Mapping({ var mapping = new DataModel.Mapping({
mappable_type: 'Synapse', mappable_type: 'Synapse',
mappable_id: synapse.cid mappable_id: synapse.cid
}) })
DataModel.Mappings.add(mapping) map.DataModel.Mappings.add(mapping)
Synapse.renderSynapse(mapping, synapse, node1, node2, true) map.Synapse.renderSynapse(mapping, synapse, node1, node2, true)
}, },
handleURL: function(url, opts = {}) { handleURL: function(url, opts = {}) {
let coords = opts.coords let coords = opts.coords
if (!coords || coords.x === undefined || coords.y === undefined) { if (!coords || coords.x === undefined || coords.y === undefined) {
coords = AutoLayout.getNextCoord({ mappings: DataModel.Mappings }) coords = map.AutoLayout.getNextCoord({ mappings: map.DataModel.Mappings })
} }
const name = opts.name || 'Link' const name = opts.name || 'Link'

View file

@ -6,7 +6,7 @@ import { browserHistory } from 'react-router'
import GlobalUI, { ReactApp } from '../GlobalUI' import GlobalUI, { ReactApp } from '../GlobalUI'
import Util from '../Util' import Util from '../Util'
const InfoBox = ({Active, DataModel}) => { const InfoBox = (map) => {
const toExport = { const toExport = {
isOpen: false, isOpen: false,
selectingPermission: false, selectingPermission: false,
@ -86,13 +86,13 @@ const toExport = {
load: function() { load: function() {
var self = toExport var self = toExport
var map = Active.Map var map = map.Active.Map
var obj = map.pick('permission', 'topic_count', 'synapse_count') var obj = map.pick('permission', 'topic_count', 'synapse_count')
var isCreator = map.authorizePermissionChange(Active.Mapper) var isCreator = map.authorizePermissionChange(map.Active.Mapper)
var canEdit = map.authorizeToEdit(Active.Mapper) var canEdit = map.authorizeToEdit(map.Active.Mapper)
var relevantPeople = map.get('permission') === 'commons' ? DataModel.Mappers : DataModel.Collaborators var relevantPeople = map.get('permission') === 'commons' ? map.DataModel.Mappers : map.DataModel.Collaborators
var shareable = map.get('permission') !== 'private' var shareable = map.get('permission') !== 'private'
obj['name'] = canEdit ? Hogan.compile(self.nameHTML).render({id: map.id, name: map.get('name')}) : map.get('name') obj['name'] = canEdit ? Hogan.compile(self.nameHTML).render({id: map.id, name: map.get('name')}) : map.get('name')
@ -139,8 +139,8 @@ const toExport = {
$('.mapInfoName .best_in_place_name').unbind('ajax:success').bind('ajax:success', function() { $('.mapInfoName .best_in_place_name').unbind('ajax:success').bind('ajax:success', function() {
var name = $(this).html() var name = $(this).html()
Active.Map.set('name', name) map.Active.Map.set('name', name)
Active.Map.trigger('saved') map.Active.Map.trigger('saved')
// mobile menu // mobile menu
$('#header_content').html(name) $('#header_content').html(name)
$('.maptoExport').removeClass('mapRequestTitle') $('.maptoExport').removeClass('mapRequestTitle')
@ -150,8 +150,8 @@ const toExport = {
$('.mapInfoDesc .best_in_place_desc').unbind('ajax:success').bind('ajax:success', function() { $('.mapInfoDesc .best_in_place_desc').unbind('ajax:success').bind('ajax:success', function() {
var desc = $(this).html() var desc = $(this).html()
Active.Map.set('desc', desc) map.Active.Map.set('desc', desc)
Active.Map.trigger('saved') map.Active.Map.trigger('saved')
}) })
$('.mapInfoDesc .best_in_place_desc, .mapInfoName .best_in_place_name').unbind('keypress').keypress(function(e) { $('.mapInfoDesc .best_in_place_desc, .mapInfoName .best_in_place_name').unbind('keypress').keypress(function(e) {
@ -186,7 +186,7 @@ const toExport = {
addTypeahead: function() { addTypeahead: function() {
var self = toExport var self = toExport
if (!Active.Map) return if (!map.Active.Map) return
// for autocomplete // for autocomplete
var collaborators = { var collaborators = {
@ -217,7 +217,7 @@ const toExport = {
} }
// for adding map collaborators, who will have edit rights // for adding map collaborators, who will have edit rights
if (Active.Mapper && Active.Mapper.id === Active.Map.get('user_id')) { if (map.Active.Mapper && map.Active.Mapper.id === map.Active.Map.get('user_id')) {
$('.collaboratorSearchField').typeahead( $('.collaboratorSearchField').typeahead(
{ {
highlight: false highlight: false
@ -232,24 +232,24 @@ const toExport = {
}, },
removeCollaborator: function(collaboratorId) { removeCollaborator: function(collaboratorId) {
var self = toExport var self = toExport
DataModel.Collaborators.remove(DataModel.Collaborators.get(collaboratorId)) map.DataModel.Collaborators.remove(map.DataModel.Collaborators.get(collaboratorId))
var mapperIds = DataModel.Collaborators.models.map(function(mapper) { return mapper.id }) var mapperIds = map.DataModel.Collaborators.models.map(function(mapper) { return mapper.id })
$.post('/maps/' + Active.Map.id + '/access', { access: mapperIds }) $.post('/maps/' + map.Active.Map.id + '/access', { access: mapperIds })
self.updateNumbers() self.updateNumbers()
}, },
addCollaborator: function(newCollaboratorId) { addCollaborator: function(newCollaboratorId) {
var self = toExport var self = toExport
if (DataModel.Collaborators.get(newCollaboratorId)) { if (map.DataModel.Collaborators.get(newCollaboratorId)) {
GlobalUI.notifyUser('That user already has access') GlobalUI.notifyUser('That user already has access')
return return
} }
function callback(mapper) { function callback(mapper) {
DataModel.Collaborators.add(mapper) map.DataModel.Collaborators.add(mapper)
var mapperIds = DataModel.Collaborators.models.map(function(mapper) { return mapper.id }) var mapperIds = map.DataModel.Collaborators.models.map(function(mapper) { return mapper.id })
$.post('/maps/' + Active.Map.id + '/access', { access: mapperIds }) $.post('/maps/' + map.Active.Map.id + '/access', { access: mapperIds })
var name = DataModel.Collaborators.get(newCollaboratorId).get('name') var name = map.DataModel.Collaborators.get(newCollaboratorId).get('name')
GlobalUI.notifyUser(name + ' will be notified') GlobalUI.notifyUser(name + ' will be notified')
self.updateNumbers() self.updateNumbers()
} }
@ -269,13 +269,13 @@ const toExport = {
$('.maptoExport .mapPermission').removeClass('commons public private').addClass(perm) $('.maptoExport .mapPermission').removeClass('commons public private').addClass(perm)
}, },
createContributorList: function() { createContributorList: function() {
var relevantPeople = Active.Map.get('permission') === 'commons' ? DataModel.Mappers : DataModel.Collaborators var relevantPeople = map.Active.Map.get('permission') === 'commons' ? map.DataModel.Mappers : map.DataModel.Collaborators
var activeMapperIsCreator = Active.Mapper && Active.Mapper.id === Active.Map.get('user_id') var activeMapperIsCreator = map.Active.Mapper && map.Active.Mapper.id === map.Active.Map.get('user_id')
var string = '' var string = ''
string += '<ul>' string += '<ul>'
relevantPeople.each(function(m) { relevantPeople.each(function(m) {
var isCreator = Active.Map.get('user_id') === m.get('id') var isCreator = map.Active.Map.get('user_id') === m.get('id')
string += '<li><a href="/explore/mapper/' + m.get('id') + '">' + '<img class="rtUserImage" width="25" height="25" src="' + m.get('image') + '" />' + m.get('name') string += '<li><a href="/explore/mapper/' + m.get('id') + '">' + '<img class="rtUserImage" width="25" height="25" src="' + m.get('image') + '" />' + m.get('name')
if (isCreator) string += ' (creator)' if (isCreator) string += ' (creator)'
string += '</a>' string += '</a>'
@ -291,11 +291,11 @@ const toExport = {
return string return string
}, },
updateNumbers: function() { updateNumbers: function() {
if (!Active.Map) return if (!map.Active.Map) return
const self = toExport const self = toExport
var relevantPeople = Active.Map.get('permission') === 'commons' ? DataModel.Mappers : DataModel.Collaborators var relevantPeople = map.Active.Map.get('permission') === 'commons' ? map.DataModel.Mappers : map.DataModel.Collaborators
let contributorsClass = '' let contributorsClass = ''
if (relevantPeople.length === 2) { if (relevantPeople.length === 2) {
@ -316,8 +316,8 @@ const toExport = {
$('.mapContributors .tip').unbind().click(function(event) { $('.mapContributors .tip').unbind().click(function(event) {
event.stopPropagation() event.stopPropagation()
}) })
$('.mapTopics').text(DataModel.Topics.length) $('.mapTopics').text(map.DataModel.Topics.length)
$('.mapSynapses').text(DataModel.Synapses.length) $('.mapSynapses').text(map.DataModel.Synapses.length)
$('.mapEditedAt').html('<span>Last edited: </span>' + Util.nowDateFormatted()) $('.mapEditedAt').html('<span>Last edited: </span>' + Util.nowDateFormatted())
}, },
@ -350,10 +350,10 @@ const toExport = {
self.selectingPermission = false self.selectingPermission = false
var permission = $(this).attr('class') var permission = $(this).attr('class')
Active.Map.save({ map.Active.Map.save({
permission: permission permission: permission
}) })
Active.Map.updateMapWrapper() map.Active.Map.updateMapWrapper()
const shareable = permission === 'private' ? '' : 'shareable' const shareable = permission === 'private' ? '' : 'shareable'
$('.mapPermission').removeClass('commons public private minimize').addClass(permission) $('.mapPermission').removeClass('commons public private minimize').addClass(permission)
$('.mapPermission .permissionSelect').remove() $('.mapPermission .permissionSelect').remove()
@ -365,13 +365,13 @@ const toExport = {
confirmString += 'This action is irreversible. It will not delete the topics and synapses on the map.' confirmString += 'This action is irreversible. It will not delete the topics and synapses on the map.'
var doIt = window.confirm(confirmString) var doIt = window.confirm(confirmString)
var map = Active.Map var map = map.Active.Map
var mapper = Active.Mapper var mapper = map.Active.Mapper
var authorized = map.authorizePermissionChange(mapper) var authorized = map.authorizePermissionChange(mapper)
if (doIt && authorized) { if (doIt && authorized) {
toExport.close() toExport.close()
DataModel.Maps.Active.remove(map) DataModel.Maps.map.Active.remove(map)
DataModel.Maps.Featured.remove(map) DataModel.Maps.Featured.remove(map)
DataModel.Maps.Mine.remove(map) DataModel.Maps.Mine.remove(map)
DataModel.Maps.Shared.remove(map) DataModel.Maps.Shared.remove(map)

File diff suppressed because it is too large Load diff

View file

@ -1,14 +1,14 @@
/* global $ */ /* global $ */
import Util from './Util' import Util from '../Util'
import { Search } from './GlobalUI' import { Search } from '../GlobalUI'
const Listeners = ({ Active, Create, Control, DataModel, JIT, Realtime, Selected, Topic, Visualize }) => { const Listeners = (map) => {
return { return {
activate: function() { activate: function() {
var self = this var self = this
$(document).on('keydown.map', function(e) { $(document).on('keydown.map', function(e) {
if (!(Active.Map || Active.Topic)) return if (!(map.Active.Map || map.Active.Topic)) return
const onCanvas = e.target.tagName === 'BODY' const onCanvas = e.target.tagName === 'BODY'
@ -16,72 +16,72 @@ return {
case 13: // if enter key is pressed case 13: // if enter key is pressed
// prevent topic creation if sending a message // prevent topic creation if sending a message
if (e.target.className !== 'chat-input') { if (e.target.className !== 'chat-input') {
JIT.enterKeyHandler() map.JIT.enterKeyHandler()
} }
break break
case 27: // if esc key is pressed case 27: // if esc key is pressed
JIT.escKeyHandler() map.JIT.escKeyHandler()
break break
case 38: // if UP key is pressed case 38: // if UP key is pressed
if ((e.ctrlKey || e.metaKey) && e.shiftKey) { if ((e.ctrlKey || e.metaKey) && e.shiftKey) {
Control.selectNeighbors() map.Control.selectNeighbors()
} }
break break
case 46: // if DEL is pressed case 46: // if DEL is pressed
if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && (Selected.Nodes.length + Selected.Edges.length) > 0) { if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && (map.Selected.Nodes.length + map.Selected.Edges.length) > 0) {
e.preventDefault() e.preventDefault()
Control.removeSelectedNodes() map.Control.removeSelectedNodes()
Control.removeSelectedEdges() map.Control.removeSelectedEdges()
} }
break break
case 65: // if a or A is pressed case 65: // if a or A is pressed
if (Create.isSwitchingSet && e.ctrlKey || e.metaKey) { if (map.Create.isSwitchingSet && e.ctrlKey || e.metaKey) {
Create.metacodeSelectorToggleSelectAll() map.Create.metacodeSelectorToggleSelectAll()
e.preventDefault() e.preventDefault()
break break
} else if ((e.ctrlKey || e.metaKey) && onCanvas) { } else if ((e.ctrlKey || e.metaKey) && onCanvas) {
const nodesCount = Object.keys(Visualize.mGraph.graph.nodes).length const nodesCount = Object.keys(map.Visualize.mGraph.graph.nodes).length
const selectedNodesCount = Selected.Nodes.length const selectedNodesCount = map.Selected.Nodes.length
e.preventDefault() e.preventDefault()
// Hit Ctrl+A once to select all nodes // Hit Ctrl+A once to select all nodes
Control.deselectAllNodes() map.Control.deselectAllNodes()
Visualize.mGraph.graph.eachNode(node => { map.Visualize.mGraph.graph.eachNode(node => {
Control.selectNode(node, e) map.Control.selectNode(node, e)
}) })
// Hitting Ctrl+A a second time will select all edges too // Hitting Ctrl+A a second time will select all edges too
Control.deselectAllEdges() map.Control.deselectAllEdges()
if (nodesCount === selectedNodesCount) { if (nodesCount === selectedNodesCount) {
DataModel.Synapses.models.forEach(synapse => { map.DataModel.Synapses.models.forEach(synapse => {
const topic1id = synapse.get('topic1_id') const topic1id = synapse.get('topic1_id')
const topic2id = synapse.get('topic2_id') const topic2id = synapse.get('topic2_id')
const edge = Visualize.mGraph.graph.edges[topic1id][topic2id] const edge = map.Visualize.mGraph.graph.edges[topic1id][topic2id]
Control.selectEdge(edge, e) map.Control.selectEdge(edge, e)
}) })
} }
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
} }
break break
case 68: // if d or D is pressed case 68: // if d or D is pressed
if (e.ctrlKey || e.metaKey) { if (e.ctrlKey || e.metaKey) {
e.preventDefault() e.preventDefault()
Control.deleteSelected() map.Control.deleteSelected()
} }
break break
case 69: // if e or E is pressed case 69: // if e or E is pressed
if ((e.ctrlKey || e.metaKey) && Active.Map) { if ((e.ctrlKey || e.metaKey) && map.Active.Map) {
e.preventDefault() e.preventDefault()
JIT.zoomExtents(null, Visualize.mGraph.canvas) map.JIT.zoomExtents(null, map.Visualize.mGraph.canvas)
break break
} }
if (e.altKey && Active.Topic) { if (e.altKey && map.Active.Topic) {
e.preventDefault() e.preventDefault()
if (Active.Topic) { if (map.Active.Topic) {
self.centerAndReveal(Selected.Nodes, { self.centerAndReveal(map.Selected.Nodes, {
center: true, center: true,
reveal: false reveal: false
}) })
@ -92,30 +92,30 @@ return {
case 72: // if h or H is pressed case 72: // if h or H is pressed
if (e.ctrlKey || e.metaKey) { if (e.ctrlKey || e.metaKey) {
e.preventDefault() e.preventDefault()
Control.hideSelectedNodes() map.Control.hideSelectedNodes()
Control.hideSelectedEdges() map.Control.hideSelectedEdges()
} }
break break
case 77: // if m or M is pressed case 77: // if m or M is pressed
if (e.ctrlKey || e.metaKey) { if (e.ctrlKey || e.metaKey) {
e.preventDefault() e.preventDefault()
Control.removeSelectedNodes() map.Control.removeSelectedNodes()
Control.removeSelectedEdges() map.Control.removeSelectedEdges()
} }
break break
case 82: // if r or R is pressed case 82: // if r or R is pressed
if (e.altKey && Active.Topic) { if (e.altKey && map.Active.Topic) {
e.preventDefault() e.preventDefault()
self.centerAndReveal(Selected.Nodes, { self.centerAndReveal(map.Selected.Nodes, {
center: false, center: false,
reveal: true reveal: true
}) })
} }
break break
case 84: // if t or T is pressed case 84: // if t or T is pressed
if (e.altKey && Active.Topic) { if (e.altKey && map.Active.Topic) {
e.preventDefault() e.preventDefault()
self.centerAndReveal(Selected.Nodes, { self.centerAndReveal(map.Selected.Nodes, {
center: true, center: true,
reveal: true reveal: true
}) })
@ -132,24 +132,24 @@ return {
} }
}) })
$(window).on('resize.map', function() { $(window).on('resize.map', function() {
if (Visualize && Visualize.mGraph) { if (Visualize && map.Visualize.mGraph) {
Util.resizeCanvas(Visualize.mGraph.canvas) Util.resizeCanvas(map.Visualize.mGraph.canvas)
} }
if (Active.Map && Realtime.inConversation) Realtime.positionVideos() if (map.Active.Map && map.Realtime.inConversation) map.Realtime.positionVideos()
}) })
}, },
centerAndReveal: function(nodes, opts) { centerAndReveal: function(nodes, opts) {
if (nodes.length < 1) return if (nodes.length < 1) return
var node = nodes[nodes.length - 1] var node = nodes[nodes.length - 1]
if (opts.center && opts.reveal) { if (opts.center && opts.reveal) {
Topic.centerOn(node.id, function() { map.Topic.centerOn(node.id, function() {
Topic.fetchRelatives(nodes) map.Topic.fetchRelatives(nodes)
}) })
} else if (opts.center) { } else if (opts.center) {
Topic.centerOn(node.id) map.Topic.centerOn(node.id)
} else if (opts.reveal) { } else if (opts.reveal) {
Topic.fetchRelatives(nodes) map.Topic.fetchRelatives(nodes)
} }
} }
} }

View file

@ -1,18 +1,18 @@
import _ from 'lodash' import _ from 'lodash'
import $jit from '../patched/JIT' import $jit from '../../patched/JIT'
const Organize = ({Visualize, JIT}) => { const Organize = (map) => {
const toExport = { const toExport = {
arrange: function(layout, centerNode) { arrange: function(layout, centerNode) {
// first option for layout to implement is 'grid', will do an evenly spaced grid with its center at the 0,0 origin // first option for layout to implement is 'grid', will do an evenly spaced grid with its center at the 0,0 origin
if (layout === 'grid') { if (layout === 'grid') {
const numNodes = _.size(Visualize.mGraph.graph.nodes) // this will always be an integer, the # of nodes on your graph visualization const numNodes = _.size(map.Visualize.mGraph.graph.nodes) // this will always be an integer, the # of nodes on your graph visualization
const numColumns = Math.floor(Math.sqrt(numNodes)) // the number of columns to make an even grid const numColumns = Math.floor(Math.sqrt(numNodes)) // the number of columns to make an even grid
const GRIDSPACE = 400 const GRIDSPACE = 400
let row = 0 let row = 0
let column = 0 let column = 0
Visualize.mGraph.graph.eachNode(function(n) { map.Visualize.mGraph.graph.eachNode(function(n) {
if (column === numColumns) { if (column === numColumns) {
column = 0 column = 0
row += 1 row += 1
@ -23,13 +23,13 @@ const toExport = {
n.setPos(newPos, 'end') n.setPos(newPos, 'end')
column += 1 column += 1
}) })
Visualize.mGraph.animate(JIT.ForceDirected.animateSavedLayout) map.Visualize.mGraph.animate(map.JIT.ForceDirected.animateSavedLayout)
} else if (layout === 'grid_full') { } else if (layout === 'grid_full') {
// this will always be an integer, the # of nodes on your graph visualization // this will always be an integer, the # of nodes on your graph visualization
const numNodes = _.size(Visualize.mGraph.graph.nodes) const numNodes = _.size(map.Visualize.mGraph.graph.nodes)
const numColumns = Math.floor(Math.sqrt(numNodes)) // the number of columns to make an even grid const numColumns = Math.floor(Math.sqrt(numNodes)) // the number of columns to make an even grid
const height = Visualize.mGraph.canvas.getSize(0).height const height = map.Visualize.mGraph.canvas.getSize(0).height
const width = Visualize.mGraph.canvas.getSize(0).width const width = map.Visualize.mGraph.canvas.getSize(0).width
const totalArea = height * width const totalArea = height * width
const cellArea = totalArea / numNodes const cellArea = totalArea / numNodes
const ratio = height / width const ratio = height / width
@ -41,7 +41,7 @@ const toExport = {
const totalCells = row * column const totalCells = row * column
if (totalCells) { if (totalCells) {
Visualize.mGraph.graph.eachNode(function(n) { map.Visualize.mGraph.graph.eachNode(function(n) {
if (column === numColumns) { if (column === numColumns) {
column = 0 column = 0
row += 1 row += 1
@ -53,7 +53,7 @@ const toExport = {
column += 1 column += 1
}) })
} }
Visualize.mGraph.animate(JIT.ForceDirected.animateSavedLayout) map.Visualize.mGraph.animate(map.JIT.ForceDirected.animateSavedLayout)
} else if (layout === 'radial') { } else if (layout === 'radial') {
var centerX = centerNode.getPos().x var centerX = centerNode.getPos().x
var centerY = centerNode.getPos().y var centerY = centerNode.getPos().y
@ -85,14 +85,14 @@ const toExport = {
}) })
} }
radial(centerNode, 1, 0) radial(centerNode, 1, 0)
Visualize.mGraph.animate(JIT.ForceDirected.animateSavedLayout) map.Visualize.mGraph.animate(map.JIT.ForceDirected.animateSavedLayout)
} else if (layout === 'center_viewport') { } else if (layout === 'center_viewport') {
let lowX = 0 let lowX = 0
let lowY = 0 let lowY = 0
let highX = 0 let highX = 0
let highY = 0 let highY = 0
Visualize.mGraph.graph.eachNode(function(n) { map.Visualize.mGraph.graph.eachNode(function(n) {
if (n.id === 1) { if (n.id === 1) {
lowX = n.getPos().x lowX = n.getPos().x
lowY = n.getPos().y lowY = n.getPos().y

View file

@ -1,8 +1,8 @@
/* global $ */ /* global $ */
import Util from './Util' import Util from '../Util'
const PasteInput = ({Import, Visualize}) => { const PasteInput = (map) => {
const toReturn = { const toReturn = {
// thanks to https://github.com/kevva/url-regex // thanks to https://github.com/kevva/url-regex
// eslint-disable-next-line no-useless-escape // eslint-disable-next-line no-useless-escape
@ -24,7 +24,7 @@ const toReturn = {
if (event.target.id !== 'infovis-canvas') return if (event.target.id !== 'infovis-canvas') return
e.preventDefault() e.preventDefault()
var coords = Util.pixelsToCoords(Visualize.mGraph, { x: e.clientX, y: e.clientY }) var coords = Util.pixelsToCoords(map.Visualize.mGraph, { x: e.clientX, y: e.clientY })
if (e.dataTransfer.files.length > 0) { if (e.dataTransfer.files.length > 0) {
self.handleFile(e.dataTransfer.files[0], coords) self.handleFile(e.dataTransfer.files[0], coords)
} }
@ -66,14 +66,14 @@ const toReturn = {
var self = toReturn var self = toReturn
if (text.match(self.URL_REGEX)) { if (text.match(self.URL_REGEX)) {
Import.handleURL(text, coords) map.Import.handleURL(text, coords)
} else if (text[0] === '{') { } else if (text[0] === '{') {
Import.handleJSON(text) map.Import.handleJSON(text)
} else if (text.match(/\t/)) { } else if (text.match(/\t/)) {
Import.handleTSV(text) map.Import.handleTSV(text)
} else { } else {
// just try to see if CSV works // just try to see if CSV works
Import.handleCSV(text) map.Import.handleCSV(text)
} }
} }
} }

View file

@ -3,7 +3,7 @@
import SimpleWebRTC from 'simplewebrtc' import SimpleWebRTC from 'simplewebrtc'
import SocketIoConnection from 'simplewebrtc/socketioconnection' import SocketIoConnection from 'simplewebrtc/socketioconnection'
import Util from '../Util' import Util from '../../Util'
import Views from '../Views' import Views from '../Views'
import { import {
@ -58,7 +58,7 @@ import {
dragTopic dragTopic
} from './sendable' } from './sendable'
const Realtime = ({Active, Cable, DataModel, JIT, Visualize}) => { const Realtime = (map) => {
const toExport = { const toExport = {
videoId: 'video-wrapper', videoId: 'video-wrapper',
socket: null, socket: null,
@ -88,7 +88,7 @@ const toExport = {
self.socket.on('connect', function() { self.socket.on('connect', function() {
console.log('connected') console.log('connected')
if (Active.Map && Active.Mapper && Active.Map.authorizeToEdit(Active.Mapper)) { if (map.Active.Map && map.Active.Mapper && map.Active.Map.authorizeToEdit(map.Active.Mapper)) {
self.checkForCall() self.checkForCall()
self.joinMap() self.joinMap()
} }
@ -99,7 +99,7 @@ const toExport = {
self.disconnected = true self.disconnected = true
}) })
if (Active.Mapper) { if (map.Active.Mapper) {
self.webrtc = new SimpleWebRTC({ self.webrtc = new SimpleWebRTC({
connection: self.socket, connection: self.socket,
localVideoEl: self.videoId, localVideoEl: self.videoId,
@ -117,7 +117,7 @@ const toExport = {
video: true, video: true,
audio: true audio: true
}, },
nick: Active.Mapper.id nick: map.Active.Mapper.id
}) })
self.webrtc.webrtc.on('iceFailed', function(peer) { self.webrtc.webrtc.on('iceFailed', function(peer) {
console.log('local ice failure', peer) console.log('local ice failure', peer)
@ -133,7 +133,7 @@ const toExport = {
$video: $video, $video: $video,
view: new Views.VideoView($video[0], $('body'), 'me', true, { view: new Views.VideoView($video[0], $('body'), 'me', true, {
DOUBLE_CLICK_TOLERANCE: 200, DOUBLE_CLICK_TOLERANCE: 200,
avatar: Active.Mapper ? Active.Mapper.get('image') : '' avatar: map.Active.Mapper ? map.Active.Mapper.get('image') : ''
}) })
} }
@ -146,7 +146,7 @@ const toExport = {
config: { DOUBLE_CLICK_TOLERANCE: 200 } config: { DOUBLE_CLICK_TOLERANCE: 200 }
}) })
self.room.videoAdded(self.handleVideoAdded) self.room.videoAdded(self.handleVideoAdded)
} // if Active.Mapper } // if map.Active.Mapper
}, },
addJuntoListeners: function() { addJuntoListeners: function() {
var self = toExport var self = toExport
@ -176,14 +176,14 @@ const toExport = {
}, },
startActiveMap: function() { startActiveMap: function() {
var self = toExport var self = toExport
if (Active.Map && Active.Mapper) { if (map.Active.Map && map.Active.Mapper) {
if (Active.Map.authorizeToEdit(Active.Mapper)) { if (map.Active.Map.authorizeToEdit(map.Active.Mapper)) {
self.turnOn() self.turnOn()
self.checkForCall() self.checkForCall()
self.joinMap() self.joinMap()
} }
self.setupChat() // chat can happen on public maps too self.setupChat() // chat can happen on public maps too
Cable.subscribeToMap(Active.Map.id) // people with edit rights can still see live updates map.Cable.subscribeToMap(map.Active.Map.id) // people with edit rights can still see live updates
} }
}, },
endActiveMap: function() { endActiveMap: function() {
@ -194,17 +194,17 @@ const toExport = {
self.leaveMap() self.leaveMap()
$('.collabCompass').remove() $('.collabCompass').remove()
if (self.room) self.room.leave() if (self.room) self.room.leave()
Cable.unsubscribeFromMap() map.Cable.unsubscribeFromMap()
}, },
turnOn: function(notify) { turnOn: function(notify) {
var self = toExport var self = toExport
$('.collabCompass').show() $('.collabCompass').show()
self.room.room = 'map-' + Active.Map.id self.room.room = 'map-' + map.Active.Map.id
self.activeMapper = { self.activeMapper = {
id: Active.Mapper.id, id: map.Active.Mapper.id,
name: Active.Mapper.get('name'), name: map.Active.Mapper.get('name'),
username: Active.Mapper.get('name'), username: map.Active.Mapper.get('name'),
image: Active.Mapper.get('image'), image: map.Active.Mapper.get('image'),
color: Util.getPastelColor(), color: Util.getPastelColor(),
self: true self: true
} }
@ -215,24 +215,24 @@ const toExport = {
}, },
setupChat: function() { setupChat: function() {
const self = toExport const self = toExport
ChatView.setNewMap() map.ChatView.setNewMap()
ChatView.addParticipant(self.activeMapper) map.ChatView.addParticipant(self.activeMapper)
ChatView.addMessages(new DataModel.MessageCollection(DataModel.Messages), true) map.ChatView.addMessages(new DataModel.MessageCollection(map.DataModel.Messages), true)
}, },
setupLocalEvents: function() { setupLocalEvents: function() {
var self = toExport var self = toExport
// local event listeners that trigger events // local event listeners that trigger events
$(document).on(JIT.events.zoom + '.map', self.positionPeerIcons) $(document).on(map.JIT.events.zoom + '.map', self.positionPeerIcons)
$(document).on(JIT.events.pan + '.map', self.positionPeerIcons) $(document).on(map.JIT.events.pan + '.map', self.positionPeerIcons)
$(document).on('mousemove.map', function(event) { $(document).on('mousemove.map', function(event) {
var pixels = { var pixels = {
x: event.pageX, x: event.pageX,
y: event.pageY y: event.pageY
} }
var coords = Util.pixelsToCoords(Visualize.mGraph, pixels) var coords = Util.pixelsToCoords(map.Visualize.mGraph, pixels)
self.sendCoords(coords) self.sendCoords(coords)
}) })
$(document).on(JIT.events.topicDrag + '.map', function(event, positions) { $(document).on(map.JIT.events.topicDrag + '.map', function(event, positions) {
self.dragTopic(positions) self.dragTopic(positions)
}) })
}, },
@ -305,7 +305,7 @@ const toExport = {
callEnded: function() { callEnded: function() {
var self = toExport var self = toExport
ChatView.conversationEnded() map.ChatView.conversationEnded()
self.room.leaveVideoOnly() self.room.leaveVideoOnly()
self.inConversation = false self.inConversation = false
self.localVideo.view.$container.hide().css({ self.localVideo.view.$container.hide().css({
@ -340,7 +340,7 @@ const toExport = {
var self = toExport var self = toExport
var mapper = self.mappersOnMap[id] var mapper = self.mappersOnMap[id]
var origPixels = Util.coordsToPixels(Visualize.mGraph, mapper.coords) var origPixels = Util.coordsToPixels(map.Visualize.mGraph, mapper.coords)
var pixels = self.limitPixelsToScreen(origPixels) var pixels = self.limitPixelsToScreen(origPixels)
$('#compass' + id).css({ $('#compass' + id).css({
left: pixels.x + 'px', left: pixels.x + 'px',
@ -400,25 +400,25 @@ const sendables = [
['dragTopic', dragTopic] ['dragTopic', dragTopic]
] ]
sendables.forEach(sendable => { sendables.forEach(sendable => {
toExport[sendable[0]] = sendable[1](toExport) toExport[sendable[0]] = sendable[1](toExport, map)
}) })
const subscribeToEvents = (toExport, socket) => { const subscribeToEvents = (toExport, socket) => {
socket.on(JUNTO_UPDATED, juntoUpdated(toExport)) socket.on(JUNTO_UPDATED, juntoUpdated(toExport, map))
socket.on(INVITED_TO_CALL, invitedToCall(toExport)) socket.on(INVITED_TO_CALL, invitedToCall(toExport, map))
socket.on(INVITED_TO_JOIN, invitedToJoin(toExport)) socket.on(INVITED_TO_JOIN, invitedToJoin(toExport, map))
socket.on(CALL_ACCEPTED, callAccepted(toExport)) socket.on(CALL_ACCEPTED, callAccepted(toExport, map))
socket.on(CALL_DENIED, callDenied(toExport)) socket.on(CALL_DENIED, callDenied(toExport, map))
socket.on(INVITE_DENIED, inviteDenied(toExport)) socket.on(INVITE_DENIED, inviteDenied(toExport, map))
socket.on(CALL_IN_PROGRESS, callInProgress(toExport)) socket.on(CALL_IN_PROGRESS, callInProgress(toExport, map))
socket.on(CALL_STARTED, callStarted(toExport)) socket.on(CALL_STARTED, callStarted(toExport, map))
socket.on(MAPPER_LIST_UPDATED, mapperListUpdated(toExport)) socket.on(MAPPER_LIST_UPDATED, mapperListUpdated(toExport, map))
socket.on(MAPPER_JOINED_CALL, mapperJoinedCall(toExport)) socket.on(MAPPER_JOINED_CALL, mapperJoinedCall(toExport, map))
socket.on(MAPPER_LEFT_CALL, mapperLeftCall(toExport)) socket.on(MAPPER_LEFT_CALL, mapperLeftCall(toExport, map))
socket.on(PEER_COORDS_UPDATED, peerCoordsUpdated(toExport)) socket.on(PEER_COORDS_UPDATED, peerCoordsUpdated(toExport, map))
socket.on(NEW_MAPPER, newMapper(toExport)) socket.on(NEW_MAPPER, newMapper(toExport, map))
socket.on(LOST_MAPPER, lostMapper(toExport)) socket.on(LOST_MAPPER, lostMapper(toExport, map))
socket.on(TOPIC_DRAGGED, topicDragged(toExport)) socket.on(TOPIC_DRAGGED, topicDragged(toExport, map))
} }
return toExport return toExport
} }

View file

@ -6,48 +6,44 @@ everthing in this file happens as a result of websocket events
import { JUNTO_UPDATED } from './events' import { JUNTO_UPDATED } from './events'
import Active from '../Active' import GlobalUI, { ReactApp } from '../../GlobalUI'
import { ChatView } from '../Views' import Util from '../../Util'
import DataModel from '../DataModel'
import GlobalUI, { ReactApp } from '../GlobalUI'
import Util from '../Util'
import Visualize from '../Visualize'
export const juntoUpdated = self => state => { export const juntoUpdated = (self, map) => state => {
ReactApp.juntoState = state ReactApp.juntoState = state
$(document).trigger(JUNTO_UPDATED) $(document).trigger(JUNTO_UPDATED)
} }
/* All the following events are received through the nodejs realtime server /* All the following events are received through the nodejs realtime server
and are done this way because they are transient data, not persisted to the server */ and are done this way because they are transient data, not persisted to the server */
export const topicDragged = self => positions => { export const topicDragged = (self, map) => positions => {
var topic var topic
var node var node
if (Active.Map) { if (map.Active.Map) {
for (var key in positions) { for (var key in positions) {
topic = DataModel.Topics.get(key) topic = map.DataModel.Topics.get(key)
if (topic) node = topic.get('node') if (topic) node = topic.get('node')
if (node) node.pos.setc(positions[key].x, positions[key].y) if (node) node.pos.setc(positions[key].x, positions[key].y)
} // for } // for
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
} }
} }
export const peerCoordsUpdated = self => data => { export const peerCoordsUpdated = (self, map) => data => {
if (!self.mappersOnMap[data.userid]) return if (!self.mappersOnMap[data.userid]) return
self.mappersOnMap[data.userid].coords = {x: data.usercoords.x, y: data.usercoords.y} self.mappersOnMap[data.userid].coords = {x: data.usercoords.x, y: data.usercoords.y}
self.positionPeerIcon(data.userid) self.positionPeerIcon(data.userid)
} }
export const lostMapper = self => data => { export const lostMapper = (self, map) => data => {
// data.userid // data.userid
// data.username // data.username
delete self.mappersOnMap[data.userid] delete self.mappersOnMap[data.userid]
ChatView.sound.play('leavemap') map.ChatView.sound.play('leavemap')
// $('#mapper' + data.userid).remove() // $('#mapper' + data.userid).remove()
$('#compass' + data.userid).remove() $('#compass' + data.userid).remove()
ChatView.removeParticipant(ChatView.participants.findWhere({id: data.userid})) map.ChatView.removeParticipant(map.ChatView.participants.findWhere({id: data.userid}))
GlobalUI.notifyUser(data.username + ' just left the map') GlobalUI.notifyUser(data.username + ' just left the map')
@ -57,7 +53,7 @@ export const lostMapper = self => data => {
} }
} }
export const mapperListUpdated = self => data => { export const mapperListUpdated = (self, map) => data => {
// data.userid // data.userid
// data.username // data.username
// data.avatar // data.avatar
@ -75,16 +71,16 @@ export const mapperListUpdated = self => data => {
} }
} }
if (data.userid !== Active.Mapper.id) { if (data.userid !== map.Active.Mapper.id) {
ChatView.addParticipant(self.mappersOnMap[data.userid]) map.ChatView.addParticipant(self.mappersOnMap[data.userid])
if (data.userinconversation) ChatView.mapperJoinedCall(data.userid) if (data.userinconversation) map.ChatView.mapperJoinedCall(data.userid)
// create a div for the collaborators compass // create a div for the collaborators compass
self.createCompass(data.username, data.userid, data.avatar, self.mappersOnMap[data.userid].color) self.createCompass(data.username, data.userid, data.avatar, self.mappersOnMap[data.userid].color)
} }
} }
export const newMapper = self => data => { export const newMapper = (self, map) => data => {
// data.userid // data.userid
// data.username // data.username
// data.avatar // data.avatar
@ -104,9 +100,9 @@ export const newMapper = self => data => {
} }
// create an item for them in the realtime box // create an item for them in the realtime box
if (data.userid !== Active.Mapper.id) { if (data.userid !== map.Active.Mapper.id) {
ChatView.sound.play('joinmap') map.ChatView.sound.play('joinmap')
ChatView.addParticipant(self.mappersOnMap[data.userid]) map.ChatView.addParticipant(self.mappersOnMap[data.userid])
// create a div for the collaborators compass // create a div for the collaborators compass
self.createCompass(data.username, data.userid, data.avatar, self.mappersOnMap[data.userid].color) self.createCompass(data.username, data.userid, data.avatar, self.mappersOnMap[data.userid].color)
@ -121,30 +117,30 @@ export const newMapper = self => data => {
} }
} }
export const callAccepted = self => userid => { export const callAccepted = (self, map) => userid => {
// const username = self.mappersOnMap[userid].name // const username = (self, map).mappersOnMap[userid].name
GlobalUI.notifyUser('Conversation starting...') GlobalUI.notifyUser('Conversation starting...')
self.joinCall() self.joinCall()
ChatView.invitationAnswered(userid) map.ChatView.invitationAnswered(userid)
} }
export const callDenied = self => userid => { export const callDenied = (self, map) => userid => {
var username = self.mappersOnMap[userid].name var username = (self, map).mappersOnMap[userid].name
GlobalUI.notifyUser(username + " didn't accept your invitation") GlobalUI.notifyUser(username + " didn't accept your invitation")
ChatView.invitationAnswered(userid) map.ChatView.invitationAnswered(userid)
} }
export const inviteDenied = self => userid => { export const inviteDenied = (self, map) => userid => {
var username = self.mappersOnMap[userid].name var username = (self, map).mappersOnMap[userid].name
GlobalUI.notifyUser(username + " didn't accept your invitation") GlobalUI.notifyUser(username + " didn't accept your invitation")
ChatView.invitationAnswered(userid) map.ChatView.invitationAnswered(userid)
} }
export const invitedToCall = self => inviter => { export const invitedToCall = (self, map) => inviter => {
ChatView.sound.stop(self.soundId) map.ChatView.sound.stop(self.soundId)
self.soundId = ChatView.sound.play('sessioninvite') self.soundId = map.ChatView.sound.play('sessioninvite')
var username = self.mappersOnMap[inviter].name var username = (self, map).mappersOnMap[inviter].name
var notifyText = '<img src="' + self['junto_spinner_darkgrey.gif'] + '" style="display: inline-block; margin-top: -12px; margin-bottom: -6px; vertical-align: top;" />' var notifyText = '<img src="' + self['junto_spinner_darkgrey.gif'] + '" style="display: inline-block; margin-top: -12px; margin-bottom: -6px; vertical-align: top;" />'
notifyText += username + ' is inviting you to a conversation. Join live?' notifyText += username + ' is inviting you to a conversation. Join live?'
notifyText += ' <button type="button" class="toast-button button yes">Yes</button>' notifyText += ' <button type="button" class="toast-button button yes">Yes</button>'
@ -154,11 +150,11 @@ export const invitedToCall = self => inviter => {
$('#toast button.no').click(e => self.denyCall(inviter)) $('#toast button.no').click(e => self.denyCall(inviter))
} }
export const invitedToJoin = self => inviter => { export const invitedToJoin = (self, map) => inviter => {
ChatView.sound.stop(self.soundId) map.ChatView.sound.stop(self.soundId)
self.soundId = ChatView.sound.play('sessioninvite') self.soundId = map.ChatView.sound.play('sessioninvite')
var username = self.mappersOnMap[inviter].name var username = (self, map).mappersOnMap[inviter].name
var notifyText = username + ' is inviting you to the conversation. Join?' var notifyText = username + ' is inviting you to the conversation. Join?'
notifyText += ' <button type="button" class="toast-button button yes">Yes</button>' notifyText += ' <button type="button" class="toast-button button yes">Yes</button>'
notifyText += ' <button type="button" class="toast-button button btn-no no">No</button>' notifyText += ' <button type="button" class="toast-button button btn-no no">No</button>'
@ -167,8 +163,8 @@ export const invitedToJoin = self => inviter => {
$('#toast button.no').click(e => self.denyInvite(inviter)) $('#toast button.no').click(e => self.denyInvite(inviter))
} }
export const mapperJoinedCall = self => id => { export const mapperJoinedCall = (self, map) => id => {
var mapper = self.mappersOnMap[id] var mapper = (self, map).mappersOnMap[id]
if (mapper) { if (mapper) {
if (self.inConversation) { if (self.inConversation) {
var username = mapper.name var username = mapper.name
@ -176,12 +172,12 @@ export const mapperJoinedCall = self => id => {
GlobalUI.notifyUser(notifyText) GlobalUI.notifyUser(notifyText)
} }
mapper.inConversation = true mapper.inConversation = true
ChatView.mapperJoinedCall(id) map.ChatView.mapperJoinedCall(id)
} }
} }
export const mapperLeftCall = self => id => { export const mapperLeftCall = (self, map) => id => {
var mapper = self.mappersOnMap[id] var mapper = (self, map).mappersOnMap[id]
if (mapper) { if (mapper) {
if (self.inConversation) { if (self.inConversation) {
var username = mapper.name var username = mapper.name
@ -189,7 +185,7 @@ export const mapperLeftCall = self => id => {
GlobalUI.notifyUser(notifyText) GlobalUI.notifyUser(notifyText)
} }
mapper.inConversation = false mapper.inConversation = false
ChatView.mapperLeftCall(id) map.ChatView.mapperLeftCall(id)
if ((self.inConversation && self.countOthersInConversation() === 0) || if ((self.inConversation && self.countOthersInConversation() === 0) ||
(!self.inConversation && self.countOthersInConversation() === 1)) { (!self.inConversation && self.countOthersInConversation() === 1)) {
self.callEnded() self.callEnded()
@ -197,17 +193,17 @@ export const mapperLeftCall = self => id => {
} }
} }
export const callInProgress = self => () => { export const callInProgress = (self, map) => () => {
var notifyText = "There's a conversation happening, want to join?" var notifyText = "There's a conversation happening, want to join?"
notifyText += ' <button type="button" class="toast-button button yes">Yes</button>' notifyText += ' <button type="button" class="toast-button button yes">Yes</button>'
notifyText += ' <button type="button" class="toast-button button btn-no no">No</button>' notifyText += ' <button type="button" class="toast-button button btn-no no">No</button>'
GlobalUI.notifyUser(notifyText, { leaveOpen: true }) GlobalUI.notifyUser(notifyText, { leaveOpen: true })
$('#toast button.yes').click(e => self.joinCall()) $('#toast button.yes').click(e => self.joinCall())
$('#toast button.no').click(e => GlobalUI.clearNotify()) $('#toast button.no').click(e => GlobalUI.clearNotify())
ChatView.conversationInProgress() map.ChatView.conversationInProgress()
} }
export const callStarted = self => () => { export const callStarted = (self, map) => () => {
if (self.inConversation) return if (self.inConversation) return
var notifyText = "There's a conversation starting, want to join?" var notifyText = "There's a conversation starting, want to join?"
notifyText += ' <button type="button" class="toast-button button">Yes</button>' notifyText += ' <button type="button" class="toast-button button">Yes</button>'
@ -215,6 +211,5 @@ export const callStarted = self => () => {
GlobalUI.notifyUser(notifyText, { leaveOpen: true }) GlobalUI.notifyUser(notifyText, { leaveOpen: true })
$('#toast button.yes').click(e => self.joinCall()) $('#toast button.yes').click(e => self.joinCall())
$('#toast button.no').click(e => GlobalUI.clearNotify()) $('#toast button.no').click(e => GlobalUI.clearNotify())
ChatView.conversationInProgress() map.ChatView.conversationInProgress()
} }

View file

@ -1,8 +1,6 @@
/* global $ */ /* global $ */
import Active from '../Active' import GlobalUI from '../../GlobalUI'
import { ChatView } from '../Views'
import GlobalUI from '../GlobalUI'
import { import {
JOIN_MAP, JOIN_MAP,
@ -20,38 +18,38 @@ import {
DRAG_TOPIC DRAG_TOPIC
} from './events' } from './events'
export const joinMap = self => () => { export const joinMap = (self, map) => () => {
self.socket.emit(JOIN_MAP, { self.socket.emit(JOIN_MAP, {
userid: Active.Mapper.id, userid: map.Active.Mapper.id,
username: Active.Mapper.get('name'), username: map.Active.Mapper.get('name'),
avatar: Active.Mapper.get('image'), avatar: map.Active.Mapper.get('image'),
mapid: Active.Map.id, mapid: map.Active.Map.id,
map: Active.Map.attributes map: map.Active.Map.attributes
}) })
} }
export const leaveMap = self => () => { export const leaveMap = (self, map) => () => {
self.socket.emit(LEAVE_MAP) self.socket.emit(LEAVE_MAP)
} }
export const checkForCall = self => () => { export const checkForCall = (self, map) => () => {
self.socket.emit(CHECK_FOR_CALL, { room: self.room.room, mapid: Active.Map.id }) self.socket.emit(CHECK_FOR_CALL, { room: self.room.room, mapid: map.Active.Map.id })
} }
export const sendMapperInfo = self => userid => { export const sendMapperInfo = (self, map) => userid => {
// send this new mapper back your details, and the awareness that you've loaded the map // send this new mapper back your details, and the awareness that you've loaded the map
var update = { var update = {
userToNotify: userid, userToNotify: userid,
username: Active.Mapper.get('name'), username: map.Active.Mapper.get('name'),
avatar: Active.Mapper.get('image'), avatar: map.Active.Mapper.get('image'),
userid: Active.Mapper.id, userid: map.Active.Mapper.id,
userinconversation: self.inConversation, userinconversation: self.inConversation,
mapid: Active.Map.id mapid: map.Active.Map.id
} }
self.socket.emit(SEND_MAPPER_INFO, update) self.socket.emit(SEND_MAPPER_INFO, update)
} }
export const joinCall = self => () => { export const joinCall = (self, map) => () => {
self.webrtc.off('readyToCall') self.webrtc.off('readyToCall')
self.webrtc.once('readyToCall', function() { self.webrtc.once('readyToCall', function() {
self.videoInitialized = true self.videoInitialized = true
@ -63,26 +61,26 @@ export const joinCall = self => () => {
$('#wrapper').append(self.localVideo.view.$container) $('#wrapper').append(self.localVideo.view.$container)
} }
self.room.join() self.room.join()
ChatView.conversationInProgress(true) map.ChatView.conversationInProgress(true)
}) })
self.inConversation = true self.inConversation = true
self.socket.emit(JOIN_CALL, { self.socket.emit(JOIN_CALL, {
mapid: Active.Map.id, mapid: map.Active.Map.id,
id: Active.Mapper.id id: map.Active.Mapper.id
}) })
self.webrtc.startLocalVideo() self.webrtc.startLocalVideo()
GlobalUI.clearNotify() GlobalUI.clearNotify()
ChatView.mapperJoinedCall(Active.Mapper.id) map.ChatView.mapperJoinedCall(map.Active.Mapper.id)
} }
export const leaveCall = self => () => { export const leaveCall = (self, map) => () => {
self.socket.emit(LEAVE_CALL, { self.socket.emit(LEAVE_CALL, {
mapid: Active.Map.id, mapid: map.Active.Map.id,
id: Active.Mapper.id id: map.Active.Mapper.id
}) })
ChatView.mapperLeftCall(Active.Mapper.id) map.ChatView.mapperLeftCall(map.Active.Mapper.id)
ChatView.leaveConversation() // the conversation will carry on without you map.ChatView.leaveConversation() // the conversation will carry on without you
self.room.leaveVideoOnly() self.room.leaveVideoOnly()
self.inConversation = false self.inConversation = false
self.localVideo.view.$container.hide() self.localVideo.view.$container.hide()
@ -94,74 +92,73 @@ export const leaveCall = self => () => {
} }
} }
export const acceptCall = self => userid => { export const acceptCall = (self, map) => userid => {
ChatView.sound.stop(self.soundId) map.ChatView.sound.stop(self.soundId)
self.socket.emit(ACCEPT_CALL, { self.socket.emit(ACCEPT_CALL, {
mapid: Active.Map.id, mapid: map.Active.Map.id,
invited: Active.Mapper.id, invited: map.Active.Mapper.id,
inviter: userid inviter: userid
}) })
$.post('/maps/' + Active.Map.id + '/events/conversation') $.post('/maps/' + map.Active.Map.id + '/events/conversation')
self.joinCall() self.joinCall()
GlobalUI.clearNotify() GlobalUI.clearNotify()
} }
export const denyCall = self => userid => { export const denyCall = (self, map) => userid => {
ChatView.sound.stop(self.soundId) map.ChatView.sound.stop(self.soundId)
self.socket.emit(DENY_CALL, { self.socket.emit(DENY_CALL, {
mapid: Active.Map.id, mapid: map.Active.Map.id,
invited: Active.Mapper.id, invited: map.Active.Mapper.id,
inviter: userid inviter: userid
}) })
GlobalUI.clearNotify() GlobalUI.clearNotify()
} }
export const denyInvite = self => userid => { export const denyInvite = (self, map) => userid => {
ChatView.sound.stop(self.soundId) map.ChatView.sound.stop(self.soundId)
self.socket.emit(DENY_INVITE, { self.socket.emit(DENY_INVITE, {
mapid: Active.Map.id, mapid: map.Active.Map.id,
invited: Active.Mapper.id, invited: map.Active.Mapper.id,
inviter: userid inviter: userid
}) })
GlobalUI.clearNotify() GlobalUI.clearNotify()
} }
export const inviteACall = self => userid => { export const inviteACall = (self, map) => userid => {
self.socket.emit(INVITE_A_CALL, { self.socket.emit(INVITE_A_CALL, {
mapid: Active.Map.id, mapid: map.Active.Map.id,
inviter: Active.Mapper.id, inviter: map.Active.Mapper.id,
invited: userid invited: userid
}) })
ChatView.invitationPending(userid) map.ChatView.invitationPending(userid)
GlobalUI.clearNotify() GlobalUI.clearNotify()
} }
export const inviteToJoin = self => userid => { export const inviteToJoin = (self, map) => userid => {
self.socket.emit(INVITE_TO_JOIN, { self.socket.emit(INVITE_TO_JOIN, {
mapid: Active.Map.id, mapid: map.Active.Map.id,
inviter: Active.Mapper.id, inviter: map.Active.Mapper.id,
invited: userid invited: userid
}) })
ChatView.invitationPending(userid) map.ChatView.invitationPending(userid)
} }
export const sendCoords = self => coords => { export const sendCoords = (self, map) => coords => {
var map = Active.Map var map = map.Active.Map
var mapper = Active.Mapper var mapper = map.Active.Mapper
if (map && map.authorizeToEdit(mapper)) { if (map && map.authorizeToEdit(mapper)) {
var update = { var update = {
usercoords: coords, usercoords: coords,
userid: Active.Mapper.id, userid: map.Active.Mapper.id,
mapid: Active.Map.id mapid: map.Active.Map.id
} }
self.socket.emit(SEND_COORDS, update) self.socket.emit(SEND_COORDS, update)
} }
} }
export const dragTopic = self => positions => { export const dragTopic = (self, map) => positions => {
if (Active.Map) { if (map.Active.Map) {
positions.mapid = Active.Map.id positions.mapid = map.Active.Map.id
self.socket.emit(DRAG_TOPIC, positions) self.socket.emit(DRAG_TOPIC, positions)
} }
} }

View file

@ -1,24 +1,24 @@
/* global $ */ /* global $ */
import Settings from './Settings' import Settings from '../Settings'
const noOp = () => {} const noOp = () => {}
const Synapse = ({Active, Control, Create, DataModel, Map, Selected, Visualize}) => { const Synapse = (map) => {
const toExport = { const toExport = {
// this function is to retrieve a synapse JSON object from the database // this function is to retrieve a synapse JSON object from the database
// @param id = the id of the synapse to retrieve // @param id = the id of the synapse to retrieve
get: function(id, callback = noOp) { get: function(id, callback = noOp) {
// if the desired topic is not yet in the local topic repository, fetch it // if the desired topic is not yet in the local topic repository, fetch it
if (DataModel.Synapses.get(id) === undefined) { if (map.DataModel.Synapses.get(id) === undefined) {
$.ajax({ $.ajax({
url: '/synapses/' + id + '.json', url: '/synapses/' + id + '.json',
success: function(data) { success: function(data) {
DataModel.Synapses.add(data) map.DataModel.Synapses.add(data)
callback(DataModel.Synapses.get(id)) callback(map.DataModel.Synapses.get(id))
} }
}) })
} else callback(DataModel.Synapses.get(id)) } else callback(map.DataModel.Synapses.get(id))
}, },
renderSynapse: function(mapping, synapse, node1, node2, createNewInDB) { renderSynapse: function(mapping, synapse, node1, node2, createNewInDB) {
@ -26,19 +26,19 @@ const toExport = {
var newedge = synapse.createEdge(mapping) var newedge = synapse.createEdge(mapping)
Visualize.mGraph.graph.addAdjacence(node1, node2, newedge.data) map.Visualize.mGraph.graph.addAdjacence(node1, node2, newedge.data)
edgeOnViz = Visualize.mGraph.graph.getAdjacence(node1.id, node2.id) edgeOnViz = map.Visualize.mGraph.graph.getAdjacence(node1.id, node2.id)
synapse.set('edge', edgeOnViz) synapse.set('edge', edgeOnViz)
synapse.updateEdge() // links the synapse and the mapping to the edge synapse.updateEdge() // links the synapse and the mapping to the edge
Control.selectEdge(edgeOnViz) map.Control.selectEdge(edgeOnViz)
var synapseSuccessCallback = function(synapseModel, response) { var synapseSuccessCallback = function(synapseModel, response) {
if (Active.Map) { if (map.Active.Map) {
mapping.save({ mappable_id: synapseModel.id }, { mapping.save({ mappable_id: synapseModel.id }, {
success: function(model, response) { success: function(model, response) {
if (Active.Mapper.get('follow_map_on_contributed')) { if (map.Active.Mapper.get('follow_map_on_contributed')) {
Active.Mapper.followMap(Active.Map.id) map.Active.Mapper.followMap(map.Active.Map.id)
} }
}, },
error: function(model, response) { error: function(model, response) {
@ -56,11 +56,11 @@ const toExport = {
console.log('error saving synapse to database') console.log('error saving synapse to database')
} }
}) })
} else if (!synapse.isNew() && Active.Map) { } else if (!synapse.isNew() && map.Active.Map) {
mapping.save(null, { mapping.save(null, {
success: function(model, response) { success: function(model, response) {
if (Active.Mapper.get('follow_map_on_contributed')) { if (map.Active.Mapper.get('follow_map_on_contributed')) {
Active.Mapper.followMap(Active.Map.id) map.Active.Mapper.followMap(map.Active.Map.id)
} }
}, },
error: function(model, response) { error: function(model, response) {
@ -84,38 +84,38 @@ const toExport = {
// for each node in this array we will create a synapse going to the position2 node. // for each node in this array we will create a synapse going to the position2 node.
var synapsesToCreate = [] var synapsesToCreate = []
topic2 = DataModel.Topics.get(Create.newSynapse.topic2id) topic2 = map.DataModel.Topics.get(map.Create.newSynapse.topic2id)
node2 = topic2.get('node') node2 = topic2.get('node')
var len = Selected.Nodes.length var len = map.Selected.Nodes.length
if (len === 0) { if (len === 0) {
topic1 = DataModel.Topics.get(Create.newSynapse.topic1id) topic1 = map.DataModel.Topics.get(map.Create.newSynapse.topic1id)
synapsesToCreate[0] = topic1.get('node') synapsesToCreate[0] = topic1.get('node')
} else if (len > 0) { } else if (len > 0) {
synapsesToCreate = Selected.Nodes synapsesToCreate = map.Selected.Nodes
} }
for (var i = 0; i < synapsesToCreate.length; i++) { for (var i = 0; i < synapsesTomap.Create.length; i++) {
node1 = synapsesToCreate[i] node1 = synapsesToCreate[i]
topic1 = node1.getData('topic') topic1 = node1.getData('topic')
synapse = new DataModel.Synapse({ synapse = new DataModel.Synapse({
desc: Create.newSynapse.description, desc: map.Create.newSynapse.description,
topic1_id: topic1.isNew() ? topic1.cid : topic1.id, topic1_id: topic1.isNew() ? topic1.cid : topic1.id,
topic2_id: topic2.isNew() ? topic2.cid : topic2.id topic2_id: topic2.isNew() ? topic2.cid : topic2.id
}) })
DataModel.Synapses.add(synapse) map.DataModel.Synapses.add(synapse)
mapping = new DataModel.Mapping({ mapping = new DataModel.Mapping({
mappable_type: 'Synapse', mappable_type: 'Synapse',
mappable_id: synapse.cid mappable_id: synapse.cid
}) })
DataModel.Mappings.add(mapping) map.DataModel.Mappings.add(mapping)
// this function also includes the creation of the synapse in the database // this function also includes the creation of the synapse in the database
self.renderSynapse(mapping, synapse, node1, node2, true) self.renderSynapse(mapping, synapse, node1, node2, true)
} // for each in synapsesToCreate } // for each in synapsesToCreate
Create.newSynapse.hide() map.Create.newSynapse.hide()
}, },
getSynapseFromAutocomplete: function(id) { getSynapseFromAutocomplete: function(id) {
var self = toExport var self = toExport
@ -125,12 +125,12 @@ const toExport = {
mappable_type: 'Synapse', mappable_type: 'Synapse',
mappable_id: synapse.id mappable_id: synapse.id
}) })
DataModel.Mappings.add(mapping) map.DataModel.Mappings.add(mapping)
const topic1 = DataModel.Topics.get(Create.newSynapse.topic1id) const topic1 = map.DataModel.Topics.get(map.Create.newSynapse.topic1id)
const node1 = topic1.get('node') const node1 = topic1.get('node')
const topic2 = DataModel.Topics.get(Create.newSynapse.topic2id) const topic2 = map.DataModel.Topics.get(map.Create.newSynapse.topic2id)
const node2 = topic2.get('node') const node2 = topic2.get('node')
Create.newSynapse.hide() map.Create.newSynapse.hide()
self.renderSynapse(mapping, synapse, node1, node2, true) self.renderSynapse(mapping, synapse, node1, node2, true)
}) })
} }

View file

@ -1,7 +1,7 @@
/* global $ */ /* global $ */
import Mapper from './Mapper' import Mapper from '../Mapper'
const SynapseCard = ({Active, Control, Visualize}) => { const SynapseCard = (map) => {
const toExport = { const toExport = {
openSynapseCard: null, openSynapseCard: null,
showCard: function(edge, e) { showCard: function(edge, e) {
@ -13,7 +13,7 @@ const toExport = {
$('#edit_synapse').remove() $('#edit_synapse').remove()
// so label is missing while editing // so label is missing while editing
Control.deselectEdge(edge) map.Control.deselectEdge(edge)
var index = edge.getData('displayIndex') ? edge.getData('displayIndex') : 0 var index = edge.getData('displayIndex') ? edge.getData('displayIndex') : 0
var synapse = edge.getData('synapses')[index] // for now, just get the first synapse var synapse = edge.getData('synapses')[index] // for now, just get the first synapse
@ -23,9 +23,9 @@ const toExport = {
var editDiv = document.createElement('div') var editDiv = document.createElement('div')
editDiv.innerHTML = '<div id="editSynUpperBar"></div><div id="editSynLowerBar"></div>' editDiv.innerHTML = '<div id="editSynUpperBar"></div><div id="editSynLowerBar"></div>'
editDiv.setAttribute('id', 'edit_synapse') editDiv.setAttribute('id', 'edit_synapse')
if (synapse.authorizeToEdit(Active.Mapper)) { if (synapse.authorizeToEdit(map.Active.Mapper)) {
editDiv.className = 'permission canEdit' editDiv.className = 'permission canEdit'
editDiv.className += synapse.authorizePermissionChange(Active.Mapper) ? ' yourEdge' : '' editDiv.className += synapse.authorizePermissionChange(map.Active.Mapper) ? ' yourEdge' : ''
} else { } else {
editDiv.className = 'permission cannotEdit' editDiv.className = 'permission cannotEdit'
} }
@ -89,7 +89,7 @@ const toExport = {
// if edge data is blank or just whitespace, populate it with dataNil // if edge data is blank or just whitespace, populate it with dataNil
if ($('#edit_synapse_desc').html().trim() === '') { if ($('#edit_synapse_desc').html().trim() === '') {
if (synapse.authorizeToEdit(Active.Mapper)) { if (synapse.authorizeToEdit(map.Active.Mapper)) {
$('#edit_synapse_desc').html(dataNil) $('#edit_synapse_desc').html(dataNil)
} else { } else {
$('#edit_synapse_desc').html('(no description)') $('#edit_synapse_desc').html('(no description)')
@ -110,8 +110,8 @@ const toExport = {
synapse.set('desc', desc) synapse.set('desc', desc)
} }
synapse.trigger('saved') synapse.trigger('saved')
Control.selectEdge(synapse.get('edge')) map.Control.selectEdge(synapse.get('edge'))
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
}) })
}, },
add_drop_down: function(edge, synapse) { add_drop_down: function(edge, synapse) {
@ -153,7 +153,7 @@ const toExport = {
e.stopPropagation() e.stopPropagation()
var index = parseInt($(this).attr('data-synapse-index')) var index = parseInt($(this).attr('data-synapse-index'))
edge.setData('displayIndex', index) edge.setData('displayIndex', index)
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
toExport.showCard(edge, false) toExport.showCard(edge, false)
}) })
} }
@ -211,7 +211,7 @@ const toExport = {
$('#edit_synapse .permissionSelect').remove() $('#edit_synapse .permissionSelect').remove()
} }
if (synapse.authorizePermissionChange(Active.Mapper)) { if (synapse.authorizePermissionChange(map.Active.Mapper)) {
$('#edit_synapse.yourEdge .mapPerm').click(openPermissionSelect) $('#edit_synapse.yourEdge .mapPerm').click(openPermissionSelect)
$('#edit_synapse').click(hidePermissionSelect) $('#edit_synapse').click(hidePermissionSelect)
} }
@ -260,7 +260,7 @@ const toExport = {
$('#edit_synapse_right').addClass('checked') $('#edit_synapse_right').addClass('checked')
} }
if (synapse.authorizeToEdit(Active.Mapper)) { if (synapse.authorizeToEdit(map.Active.Mapper)) {
$('#edit_synapse_left, #edit_synapse_right').click(function() { $('#edit_synapse_left, #edit_synapse_right').click(function() {
$(this).toggleClass('checked') $(this).toggleClass('checked')
@ -284,7 +284,7 @@ const toExport = {
topic1_id: dir[0], topic1_id: dir[0],
topic2_id: dir[1] topic2_id: dir[1]
}) })
Visualize.mGraph.plot() map.Visualize.mGraph.plot()
}) })
} // if } // if
} // add_direction_form } // add_direction_form

View file

@ -1,42 +1,42 @@
/* global $ */ /* global $ */
import $jit from '../patched/JIT' import $jit from '../../patched/JIT'
import GlobalUI, { ReactApp } from './GlobalUI' import GlobalUI, { ReactApp } from '../GlobalUI'
import Loading from './Loading' import Loading from '../Loading'
import Settings from './Settings' import Settings from '../Settings'
import Util from './Util' import Util from '../Util'
const noOp = () => {} const noOp = () => {}
const Topic = ({Active, AutoLayout, Create, DataModel, Filter, JIT, MAP, Selected, SynapseCard, TopicCard, Visualize}) => { const Topic = (map) => {
const toExport = { const toExport = {
get: function(id, callback = noOp) { get: function(id, callback = noOp) {
// if the desired topic is not yet in the local topic repository, fetch it // if the desired topic is not yet in the local topic repository, fetch it
if (DataModel.Topics.get(id) === undefined) { if (map.DataModel.Topics.get(id) === undefined) {
$.ajax({ $.ajax({
url: '/topics/' + id + '.json', url: '/topics/' + id + '.json',
success: function(data) { success: function(data) {
DataModel.Topics.add(data) map.DataModel.Topics.add(data)
callback(DataModel.Topics.get(id)) callback(map.DataModel.Topics.get(id))
} }
}) })
} else callback(DataModel.Topics.get(id)) } else callback(map.DataModel.Topics.get(id))
}, },
launch: function(id) { launch: function(id) {
var dataIsReadySetupTopic = function() { var dataIsReadySetupTopic = function() {
Visualize.type = 'RGraph' map.Visualize.type = 'RGraph'
JIT.prepareVizData() map.JIT.prepareVizData()
Selected.reset() map.Selected.reset()
Filter.reset() map.Filter.reset()
Filter.checkMetacodes() map.Filter.checkMetacodes()
Filter.checkSynapses() map.Filter.checkSynapses()
Filter.checkMappers() map.Filter.checkMappers()
document.title = Active.Topic.get('name') + ' | Metamaps' document.title = map.Active.Topic.get('name') + ' | Metamaps'
ReactApp.mobileTitle = Active.Topic.get('name') ReactApp.mobileTitle = map.Active.Topic.get('name')
ReactApp.render() ReactApp.render()
} }
if (Active.Topic && Active.Topic.id === id) { if (map.Active.Topic && map.Active.Topic.id === id) {
dataIsReadySetupTopic() dataIsReadySetupTopic()
} }
else { else {
@ -44,10 +44,10 @@ const toExport = {
$.ajax({ $.ajax({
url: '/topics/' + id + '/network.json', url: '/topics/' + id + '/network.json',
success: function(data) { success: function(data) {
Active.Topic = new DataModel.Topic(data.topic) map.Active.Topic = new DataModel.Topic(data.topic)
DataModel.Creators = new DataModel.MapperCollection(data.creators) map.DataModel.Creators = new DataModel.MapperCollection(data.creators)
DataModel.Topics = new DataModel.TopicCollection([data.topic].concat(data.relatives)) map.DataModel.Topics = new DataModel.TopicCollection([data.topic].concat(data.relatives))
DataModel.Synapses = new DataModel.SynapseCollection(data.synapses) map.DataModel.Synapses = new DataModel.SynapseCollection(data.synapses)
DataModel.attachCollectionEvents() DataModel.attachCollectionEvents()
dataIsReadySetupTopic() dataIsReadySetupTopic()
} }
@ -55,36 +55,36 @@ const toExport = {
} }
}, },
end: function() { end: function() {
if (Active.Topic) { if (map.Active.Topic) {
$('.rightclickmenu').remove() $('.rightclickmenu').remove()
TopicCard.hideCard() map.TopicCard.hideCard()
SynapseCard.hideCard() map.SynapseCard.hideCard()
} }
}, },
centerOn: function(nodeid, callback) { centerOn: function(nodeid, callback) {
// don't clash with fetchRelatives // don't clash with fetchRelatives
if (!Visualize.mGraph.busy) { if (!map.Visualize.mGraph.busy) {
Visualize.mGraph.onClick(nodeid, { map.Visualize.mGraph.onClick(nodeid, {
hideLabels: false, hideLabels: false,
duration: 1000, duration: 1000,
onComplete: function() { onComplete: function() {
if (callback) callback() if (callback) callback()
} }
}) })
Active.Topic = DataModel.Topics.get(nodeid) map.Active.Topic = map.DataModel.Topics.get(nodeid)
} }
}, },
onTopicFollow: topic => { onTopicFollow: topic => {
const isFollowing = topic.isFollowedBy(Active.Mapper) const isFollowing = topic.isFollowedBy(map.Active.Mapper)
$.post({ $.post({
url: `/topics/${topic.id}/${isFollowing ? 'un' : ''}follow` url: `/topics/${topic.id}/${isFollowing ? 'un' : ''}follow`
}) })
if (isFollowing) { if (isFollowing) {
GlobalUI.notifyUser('You are no longer following this topic') GlobalUI.notifyUser('You are no longer following this topic')
Active.Mapper.unfollowTopic(topic.id) map.Active.Mapper.unfollowTopic(topic.id)
} else { } else {
GlobalUI.notifyUser('You are now following this topic') GlobalUI.notifyUser('You are now following this topic')
Active.Mapper.followTopic(topic.id) map.Active.Mapper.followTopic(topic.id)
} }
ReactApp.render() ReactApp.render()
}, },
@ -93,31 +93,31 @@ const toExport = {
var node = $.isArray(nodes) ? nodes[0] : nodes var node = $.isArray(nodes) ? nodes[0] : nodes
var topics = DataModel.Topics.map(function(t) { return t.id }) var topics = map.DataModel.Topics.map(function(t) { return t.id })
var topicsString = topics.join() var topicsString = topics.join()
var creators = DataModel.Creators.map(function(t) { return t.id }) var creators = map.DataModel.Creators.map(function(t) { return t.id })
var creatorsString = creators.join() var creatorsString = creators.join()
var topic = node.getData('topic') var topic = node.getData('topic')
var successCallback var successCallback
successCallback = function(data) { successCallback = function(data) {
if (Visualize.mGraph.busy) { if (map.Visualize.mGraph.busy) {
// don't clash with centerOn // don't clash with centerOn
window.setTimeout(function() { successCallback(data) }, 100) window.setTimeout(function() { successCallback(data) }, 100)
return return
} }
if (data.creators.length > 0) DataModel.Creators.add(data.creators) if (data.creators.length > 0) map.DataModel.Creators.add(data.creators)
if (data.topics.length > 0) DataModel.Topics.add(data.topics) if (data.topics.length > 0) map.DataModel.Topics.add(data.topics)
if (data.synapses.length > 0) DataModel.Synapses.add(data.synapses) if (data.synapses.length > 0) map.DataModel.Synapses.add(data.synapses)
var topicColl = new DataModel.TopicCollection(data.topics) var topicColl = new DataModel.TopicCollection(data.topics)
topicColl.add(topic) topicColl.add(topic)
var synapseColl = new DataModel.SynapseCollection(data.synapses) var synapseColl = new DataModel.SynapseCollection(data.synapses)
var graph = JIT.convertModelsToJIT(topicColl, synapseColl)[0] var graph = map.JIT.convertModelsToJIT(topicColl, synapseColl)[0]
Visualize.mGraph.op.sum(graph, { map.Visualize.mGraph.op.sum(graph, {
type: 'fade', type: 'fade',
duration: 500, duration: 500,
hideLabels: false hideLabels: false
@ -125,8 +125,8 @@ const toExport = {
var i, l, t, s var i, l, t, s
Visualize.mGraph.graph.eachNode(function(n) { map.Visualize.mGraph.graph.eachNode(function(n) {
t = DataModel.Topics.get(n.id) t = map.DataModel.Topics.get(n.id)
t.set({ node: n }, { silent: true }) t.set({ node: n }, { silent: true })
t.updateNode() t.updateNode()
@ -136,7 +136,7 @@ const toExport = {
l = edge.getData('synapseIDs').length l = edge.getData('synapseIDs').length
for (i = 0; i < l; i++) { for (i = 0; i < l; i++) {
s = DataModel.Synapses.get(edge.getData('synapseIDs')[i]) s = map.DataModel.Synapses.get(edge.getData('synapseIDs')[i])
s.set({ edge: edge }, { silent: true }) s.set({ edge: edge }, { silent: true })
s.updateEdge() s.updateEdge()
} }
@ -169,56 +169,56 @@ const toExport = {
var midpoint = {} var midpoint = {}
var pixelPos var pixelPos
if (!$.isEmptyObject(Visualize.mGraph.graph.nodes)) { if (!$.isEmptyObject(map.Visualize.mGraph.graph.nodes)) {
Visualize.mGraph.graph.addNode(newnode) map.Visualize.mGraph.graph.addNode(newnode)
nodeOnViz = Visualize.mGraph.graph.getNode(newnode.id) nodeOnViz = map.Visualize.mGraph.graph.getNode(newnode.id)
topic.set('node', nodeOnViz, {silent: true}) topic.set('node', nodeOnViz, {silent: true})
topic.updateNode() // links the topic and the mapping to the node topic.updateNode() // links the topic and the mapping to the node
nodeOnViz.setData('dim', 1, 'start') nodeOnViz.setData('dim', 1, 'start')
nodeOnViz.setData('dim', 25, 'end') nodeOnViz.setData('dim', 25, 'end')
if (Visualize.type === 'RGraph') { if (map.Visualize.type === 'RGraph') {
tempPos = new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')) tempPos = new $jit.Complex(mapping.get('xloc'), mapping.get('yloc'))
tempPos = tempPos.toPolar() tempPos = tempPos.toPolar()
nodeOnViz.setPos(tempPos, 'current') nodeOnViz.setPos(tempPos, 'current')
nodeOnViz.setPos(tempPos, 'start') nodeOnViz.setPos(tempPos, 'start')
nodeOnViz.setPos(tempPos, 'end') nodeOnViz.setPos(tempPos, 'end')
} else if (Visualize.type === 'ForceDirected') { } else if (map.Visualize.type === 'ForceDirected') {
nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'current') nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'current')
nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'start') nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'start')
nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'end') nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'end')
} }
if (Create.newTopic.addSynapse && permitCreateSynapseAfter) { if (map.Create.newTopic.addSynapse && permitCreateSynapseAfter) {
Create.newSynapse.topic1id = JIT.tempNode.getData('topic').id map.Create.newSynapse.topic1id = map.JIT.tempNode.getData('topic').id
// position the form // position the form
midpoint.x = JIT.tempNode.pos.getc().x + (nodeOnViz.pos.getc().x - JIT.tempNode.pos.getc().x) / 2 midpoint.x = map.JIT.tempNode.pos.getc().x + (nodeOnViz.pos.getc().x - map.JIT.tempNode.pos.getc().x) / 2
midpoint.y = JIT.tempNode.pos.getc().y + (nodeOnViz.pos.getc().y - JIT.tempNode.pos.getc().y) / 2 midpoint.y = map.JIT.tempNode.pos.getc().y + (nodeOnViz.pos.getc().y - map.JIT.tempNode.pos.getc().y) / 2
pixelPos = Util.coordsToPixels(Visualize.mGraph, midpoint) pixelPos = Util.coordsToPixels(map.Visualize.mGraph, midpoint)
$('#new_synapse').css('left', pixelPos.x + 'px') $('#new_synapse').css('left', pixelPos.x + 'px')
$('#new_synapse').css('top', pixelPos.y + 'px') $('#new_synapse').css('top', pixelPos.y + 'px')
// show the form // show the form
Create.newSynapse.open() map.Create.newSynapse.open()
Visualize.mGraph.fx.animate({ map.Visualize.mGraph.fx.animate({
modes: ['node-property:dim'], modes: ['node-property:dim'],
duration: 500, duration: 500,
onComplete: function() { onComplete: function() {
JIT.tempNode = null map.JIT.tempNode = null
JIT.tempNode2 = null map.JIT.tempNode2 = null
JIT.tempInit = false map.JIT.tempInit = false
} }
}) })
} else { } else {
Visualize.mGraph.fx.plotNode(nodeOnViz, Visualize.mGraph.canvas) map.Visualize.mGraph.fx.plotNode(nodeOnViz, map.Visualize.mGraph.canvas)
Visualize.mGraph.fx.animate({ map.Visualize.mGraph.fx.animate({
modes: ['node-property:dim'], modes: ['node-property:dim'],
duration: 500, duration: 500,
onComplete: function() {} onComplete: function() {}
}) })
} }
} else { } else {
Visualize.mGraph.loadJSON(newnode) map.Visualize.mGraph.loadJSON(newnode)
nodeOnViz = Visualize.mGraph.graph.getNode(newnode.id) nodeOnViz = map.Visualize.mGraph.graph.getNode(newnode.id)
topic.set('node', nodeOnViz, {silent: true}) topic.set('node', nodeOnViz, {silent: true})
topic.updateNode() // links the topic and the mapping to the node topic.updateNode() // links the topic and the mapping to the node
@ -227,8 +227,8 @@ const toExport = {
nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'current') nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'current')
nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'start') nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'start')
nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'end') nodeOnViz.setPos(new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')), 'end')
Visualize.mGraph.fx.plotNode(nodeOnViz, Visualize.mGraph.canvas) map.Visualize.mGraph.fx.plotNode(nodeOnViz, map.Visualize.mGraph.canvas)
Visualize.mGraph.fx.animate({ map.Visualize.mGraph.fx.animate({
modes: ['node-property:dim'], modes: ['node-property:dim'],
duration: 500, duration: 500,
onComplete: function() {} onComplete: function() {}
@ -236,8 +236,8 @@ const toExport = {
} }
var mappingSuccessCallback = function(mappingModel, response, topicModel) { var mappingSuccessCallback = function(mappingModel, response, topicModel) {
if (Active.Mapper.get('follow_map_on_contributed')) { if (map.Active.Mapper.get('follow_map_on_contributed')) {
Active.Mapper.followMap(Active.Map.id) map.Active.Mapper.followMap(map.Active.Map.id)
} }
// call a success callback if provided // call a success callback if provided
if (opts.success) { if (opts.success) {
@ -245,10 +245,10 @@ const toExport = {
} }
} }
var topicSuccessCallback = function(topicModel, response) { var topicSuccessCallback = function(topicModel, response) {
if (Active.Mapper.get('follow_topic_on_created')) { if (map.Active.Mapper.get('follow_topic_on_created')) {
Active.Mapper.followTopic(topicModel.id) map.Active.Mapper.followTopic(topicModel.id)
} }
if (Active.Map) { if (map.Active.Map) {
mapping.save({ mappable_id: topicModel.id }, { mapping.save({ mappable_id: topicModel.id }, {
success: function(model, response) { success: function(model, response) {
mappingSuccessCallback(model, response, topicModel) mappingSuccessCallback(model, response, topicModel)
@ -259,8 +259,8 @@ const toExport = {
}) })
} }
if (Create.newTopic.addSynapse) { if (map.Create.newTopic.addSynapse) {
Create.newSynapse.topic2id = topicModel.id map.Create.newSynapse.topic2id = topicModel.id
} }
} }
@ -272,7 +272,7 @@ const toExport = {
console.log('error saving topic to database') console.log('error saving topic to database')
} }
}) })
} else if (!topic.isNew() && Active.Map) { } else if (!topic.isNew() && map.Active.Map) {
mapping.save(null, { mapping.save(null, {
success: mappingSuccessCallback success: mappingSuccessCallback
}) })
@ -282,7 +282,7 @@ const toExport = {
createTopicLocally: function() { createTopicLocally: function() {
var self = toExport var self = toExport
if (Create.newTopic.name === '') { if (map.Create.newTopic.name === '') {
GlobalUI.notifyUser('Please enter a topic title...') GlobalUI.notifyUser('Please enter a topic title...')
return return
} }
@ -291,29 +291,29 @@ const toExport = {
$(document).trigger(Map.events.editedByActiveMapper) $(document).trigger(Map.events.editedByActiveMapper)
var metacode = DataModel.Metacodes.get(Create.newTopic.metacode) var metacode = DataModel.Metacodes.get(map.Create.newTopic.metacode)
var topic = new DataModel.Topic({ var topic = new DataModel.Topic({
name: Create.newTopic.name, name: map.Create.newTopic.name,
metacode_id: metacode.id, metacode_id: metacode.id,
defer_to_map_id: Active.Map.id defer_to_map_id: map.Active.Map.id
}) })
DataModel.Topics.add(topic) map.DataModel.Topics.add(topic)
if (Create.newTopic.pinned) { if (map.Create.newTopic.pinned) {
var nextCoords = AutoLayout.getNextCoord({ mappings: DataModel.Mappings }) var nextCoords = map.AutoLayout.getNextCoord({ mappings: map.DataModel.Mappings })
} }
var mapping = new DataModel.Mapping({ var mapping = new DataModel.Mapping({
xloc: nextCoords ? nextCoords.x : Create.newTopic.x, xloc: nextCoords ? nextCoords.x : map.Create.newTopic.x,
yloc: nextCoords ? nextCoords.y : Create.newTopic.y, yloc: nextCoords ? nextCoords.y : map.Create.newTopic.y,
mappable_id: topic.cid, mappable_id: topic.cid,
mappable_type: 'Topic' mappable_type: 'Topic'
}) })
DataModel.Mappings.add(mapping) map.DataModel.Mappings.add(mapping)
// these can't happen until the value is retrieved, which happens in the line above // these can't happen until the value is retrieved, which happens in the line above
if (!Create.newTopic.pinned) Create.newTopic.hide() if (!map.Create.newTopic.pinned) map.Create.newTopic.hide()
Create.newTopic.reset() map.Create.newTopic.reset()
self.renderTopic(mapping, topic, true, true) // this function also includes the creation of the topic in the database self.renderTopic(mapping, topic, true, true) // this function also includes the creation of the topic in the database
}, },
@ -324,24 +324,24 @@ const toExport = {
$(document).trigger(Map.events.editedByActiveMapper) $(document).trigger(Map.events.editedByActiveMapper)
if (!Create.newTopic.pinned) Create.newTopic.hide() if (!map.Create.newTopic.pinned) map.Create.newTopic.hide()
Create.newTopic.reset() map.Create.newTopic.reset()
self.get(id, (topic) => { self.get(id, (topic) => {
if (Create.newTopic.pinned) { if (map.Create.newTopic.pinned) {
var nextCoords = AutoLayout.getNextCoord({ mappings: DataModel.Mappings }) var nextCoords = map.AutoLayout.getNextCoord({ mappings: map.DataModel.Mappings })
} }
var mapping = new DataModel.Mapping({ var mapping = new DataModel.Mapping({
xloc: nextCoords ? nextCoords.x : Create.newTopic.x, xloc: nextCoords ? nextCoords.x : map.Create.newTopic.x,
yloc: nextCoords ? nextCoords.y : Create.newTopic.y, yloc: nextCoords ? nextCoords.y : map.Create.newTopic.y,
mappable_type: 'Topic', mappable_type: 'Topic',
mappable_id: topic.id mappable_id: topic.id
}) })
DataModel.Mappings.add(mapping) map.DataModel.Mappings.add(mapping)
self.renderTopic(mapping, topic, true, true) self.renderTopic(mapping, topic, true, true)
// this blocked the enterKeyHandler from creating a new topic as well // this blocked the enterKeyHandler from creating a new topic as well
if (Create.newTopic.pinned) Create.newTopic.beingCreated = true if (map.Create.newTopic.pinned) map.Create.newTopic.beingCreated = true
}) })
}, },
getMapFromAutocomplete: function(data) { getMapFromAutocomplete: function(data) {
@ -353,26 +353,26 @@ const toExport = {
var topic = new DataModel.Topic({ var topic = new DataModel.Topic({
name: data.name, name: data.name,
metacode_id: metacode.id, metacode_id: metacode.id,
defer_to_map_id: Active.Map.id, defer_to_map_id: map.Active.Map.id,
link: window.location.origin + '/maps/' + data.id link: window.location.origin + '/maps/' + data.id
}) })
DataModel.Topics.add(topic) map.DataModel.Topics.add(topic)
var mapping = new DataModel.Mapping({ var mapping = new DataModel.Mapping({
xloc: Create.newTopic.x, xloc: map.Create.newTopic.x,
yloc: Create.newTopic.y, yloc: map.Create.newTopic.y,
mappable_id: topic.cid, mappable_id: topic.cid,
mappable_type: 'Topic' mappable_type: 'Topic'
}) })
DataModel.Mappings.add(mapping) map.DataModel.Mappings.add(mapping)
// these can't happen until the value is retrieved, which happens in the line above // these can't happen until the value is retrieved, which happens in the line above
if (!Create.newTopic.pinned) Create.newTopic.hide() if (!map.Create.newTopic.pinned) map.Create.newTopic.hide()
Create.newTopic.reset() map.Create.newTopic.reset()
self.renderTopic(mapping, topic, true, true) // this function also includes the creation of the topic in the database self.renderTopic(mapping, topic, true, true) // this function also includes the creation of the topic in the database
// this blocked the enterKeyHandler from creating a new topic as well // this blocked the enterKeyHandler from creating a new topic as well
if (Create.newTopic.pinned) Create.newTopic.beingCreated = true if (map.Create.newTopic.pinned) map.Create.newTopic.beingCreated = true
}, },
getTopicFromSearch: function(event, id) { getTopicFromSearch: function(event, id) {
var self = toExport var self = toExport
@ -380,14 +380,14 @@ const toExport = {
$(document).trigger(Map.events.editedByActiveMapper) $(document).trigger(Map.events.editedByActiveMapper)
self.get(id, (topic) => { self.get(id, (topic) => {
var nextCoords = AutoLayout.getNextCoord({ mappings: DataModel.Mappings }) var nextCoords = map.AutoLayout.getNextCoord({ mappings: map.DataModel.Mappings })
var mapping = new DataModel.Mapping({ var mapping = new DataModel.Mapping({
xloc: nextCoords.x, xloc: nextCoords.x,
yloc: nextCoords.y, yloc: nextCoords.y,
mappable_type: 'Topic', mappable_type: 'Topic',
mappable_id: topic.id mappable_id: topic.id
}) })
DataModel.Mappings.add(mapping) map.DataModel.Mappings.add(mapping)
self.renderTopic(mapping, topic, true, true) self.renderTopic(mapping, topic, true, true)
GlobalUI.notifyUser('Topic was added to your map!') GlobalUI.notifyUser('Topic was added to your map!')
}) })

View file

@ -55,7 +55,7 @@ Room.prototype.init = function() {
this.webrtc.webrtc.off('peerStreamAdded') this.webrtc.webrtc.off('peerStreamAdded')
this.webrtc.webrtc.off('peerStreamRemoved') this.webrtc.webrtc.off('peerStreamRemoved')
this.webrtc.on('peerStreamAdded', function(peer) { this.webrtc.on('peerStreamAdded', function(peer) {
var mapper = Realtime.mappersOnMap[peer.nick] var mapper = map.Realtime.mappersOnMap[peer.nick]
peer.avatar = mapper.image peer.avatar = mapper.image
peer.username = mapper.name peer.username = mapper.name
if (self.isActiveRoom) { if (self.isActiveRoom) {

View file

@ -1,22 +1,17 @@
/* global $ */ /* global $ */
import ChatView from './ChatView'
import VideoView from './VideoView' import VideoView from './VideoView'
import Room from './Room' import Room from './Room'
import TopicCard from './TopicCard'
import { JUNTO_UPDATED } from '../Realtime/events' import { JUNTO_UPDATED } from '../Realtime/events'
const Views = { const Views = {
init: (serverData) => { init: (serverData) => {
$(document).on(JUNTO_UPDATED, () => ExploreMaps.render()) $(document).on(JUNTO_UPDATED, () => ExploreMaps.render())
ChatView.init([serverData['sounds/MM_sounds.mp3'], serverData['sounds/MM_sounds.ogg']]) //map.ChatView.init([serverData['sounds/MM_sounds.mp3'], serverData['sounds/MM_sounds.ogg']])
}, },
ExploreMaps,
ChatView,
VideoView, VideoView,
Room, Room
TopicCard
} }
export { ChatView, VideoView, Room, TopicCard } export { VideoView, Room }
export default Views export default Views

View file

@ -2,15 +2,11 @@
import _ from 'lodash' import _ from 'lodash'
import $jit from '../patched/JIT' import $jit from '../../patched/JIT'
import Active from './Active' import Loading from '../Loading'
import DataModel from './DataModel'
import JIT from './JIT'
import Loading from './Loading'
import TopicCard from './Views/TopicCard'
const Visualize = ({Active, DataModel, JIT, TopicCard}) => { const Visualize = (map) => {
const toExport = { const toExport = {
mGraph: null, // a reference to the graph object. mGraph: null, // a reference to the graph object.
cameraPosition: null, // stores the camera position when using a 3D visualization cameraPosition: null, // stores the camera position when using a 3D visualization
@ -35,14 +31,14 @@ const toExport = {
// prevent touch events on the canvas from default behaviour // prevent touch events on the canvas from default behaviour
$('#infovis-canvas').bind('touchmove', function(event) { $('#infovis-canvas').bind('touchmove', function(event) {
// JIT.touchPanZoomHandler(event) // map.JIT.touchPanZoomHandler(event)
}) })
// prevent touch events on the canvas from default behaviour // prevent touch events on the canvas from default behaviour
$('#infovis-canvas').bind('touchend touchcancel', function(event) { $('#infovis-canvas').bind('touchend touchcancel', function(event) {
if (!self.mGraph.events.touchMoved && !Visualize.touchDragNode) TopicCard.hideCurrentCard() if (!self.mGraph.events.touchMoved && !map.Visualize.touchDragNode) map.TopicCard.hideCurrentCard()
self.mGraph.events.touched = self.mGraph.events.touchMoved = false self.mGraph.events.touched = self.mGraph.events.touchMoved = false
Visualize.touchDragNode = false map.Visualize.touchDragNode = false
}) })
}, },
computePositions: function() { computePositions: function() {
@ -53,7 +49,7 @@ const toExport = {
let l let l
self.mGraph.graph.eachNode(function(n) { self.mGraph.graph.eachNode(function(n) {
const topic = DataModel.Topics.get(n.id) const topic = map.DataModel.Topics.get(n.id)
topic.set({ node: n }, { silent: true }) topic.set({ node: n }, { silent: true })
topic.updateNode() topic.updateNode()
@ -63,7 +59,7 @@ const toExport = {
l = edge.getData('synapseIDs').length l = edge.getData('synapseIDs').length
for (i = 0; i < l; i++) { for (i = 0; i < l; i++) {
const synapse = DataModel.Synapses.get(edge.getData('synapseIDs')[i]) const synapse = map.DataModel.Synapses.get(edge.getData('synapseIDs')[i])
synapse.set({ edge: edge }, { silent: true }) synapse.set({ edge: edge }, { silent: true })
synapse.updateEdge() synapse.updateEdge()
} }
@ -76,7 +72,7 @@ const toExport = {
self.mGraph.compute('end') self.mGraph.compute('end')
} else if (self.type === 'ForceDirected') { } else if (self.type === 'ForceDirected') {
self.mGraph.graph.eachNode(function(n) { self.mGraph.graph.eachNode(function(n) {
const topic = DataModel.Topics.get(n.id) const topic = map.DataModel.Topics.get(n.id)
topic.set({ node: n }, { silent: true }) topic.set({ node: n }, { silent: true })
topic.updateNode() topic.updateNode()
const mapping = topic.getMapping() const mapping = topic.getMapping()
@ -87,7 +83,7 @@ const toExport = {
const l = edge.getData('synapseIDs').length const l = edge.getData('synapseIDs').length
for (let i = 0; i < l; i++) { for (let i = 0; i < l; i++) {
const synapse = DataModel.Synapses.get(edge.getData('synapseIDs')[i]) const synapse = map.DataModel.Synapses.get(edge.getData('synapseIDs')[i])
synapse.set({ edge: edge }, { silent: true }) synapse.set({ edge: edge }, { silent: true })
synapse.updateEdge() synapse.updateEdge()
} }
@ -114,25 +110,25 @@ const toExport = {
// clear the previous canvas from #infovis // clear the previous canvas from #infovis
$('#infovis').empty() $('#infovis').empty()
const RGraphSettings = $.extend(true, {}, JIT.ForceDirected.graphSettings) const RGraphSettings = $.extend(true, {}, map.JIT.ForceDirected.graphSettings)
$jit.RGraph.Plot.NodeTypes.implement(JIT.ForceDirected.nodeSettings) $jit.RGraph.Plot.NodeTypes.implement(map.JIT.ForceDirected.nodeSettings)
$jit.RGraph.Plot.EdgeTypes.implement(JIT.ForceDirected.edgeSettings) $jit.RGraph.Plot.EdgeTypes.implement(map.JIT.ForceDirected.edgeSettings)
RGraphSettings.width = $(document).width() RGraphSettings.width = $(document).width()
RGraphSettings.height = $(document).height() RGraphSettings.height = $(document).height()
RGraphSettings.background = JIT.RGraph.background RGraphSettings.background = map.JIT.RGraph.background
RGraphSettings.levelDistance = JIT.RGraph.levelDistance RGraphSettings.levelDistance = map.JIT.RGraph.levelDistance
self.mGraph = new $jit.RGraph(RGraphSettings) self.mGraph = new $jit.RGraph(RGraphSettings)
} else if (self.type === 'ForceDirected') { } else if (self.type === 'ForceDirected') {
// clear the previous canvas from #infovis // clear the previous canvas from #infovis
$('#infovis').empty() $('#infovis').empty()
const FDSettings = $.extend(true, {}, JIT.ForceDirected.graphSettings) const FDSettings = $.extend(true, {}, map.JIT.ForceDirected.graphSettings)
$jit.ForceDirected.Plot.NodeTypes.implement(JIT.ForceDirected.nodeSettings) $jit.ForceDirected.Plot.NodeTypes.implement(map.JIT.ForceDirected.nodeSettings)
$jit.ForceDirected.Plot.EdgeTypes.implement(JIT.ForceDirected.edgeSettings) $jit.ForceDirected.Plot.EdgeTypes.implement(map.JIT.ForceDirected.edgeSettings)
FDSettings.width = $('body').width() FDSettings.width = $('body').width()
FDSettings.height = $('body').height() FDSettings.height = $('body').height()
@ -143,7 +139,7 @@ const toExport = {
$('#infovis').empty() $('#infovis').empty()
// init ForceDirected3D // init ForceDirected3D
self.mGraph = new $jit.ForceDirected3D(JIT.ForceDirected3D.graphSettings) self.mGraph = new $jit.ForceDirected3D(map.JIT.ForceDirected3D.graphSettings)
self.cameraPosition = self.mGraph.canvas.canvases[0].camera.position self.cameraPosition = self.mGraph.canvas.canvases[0].camera.position
} else { } else {
self.mGraph.graph.empty() self.mGraph.graph.empty()
@ -155,22 +151,22 @@ const toExport = {
if (!self.loadLater) { if (!self.loadLater) {
// load JSON data. // load JSON data.
var rootIndex = 0 var rootIndex = 0
if (Active.Topic) { if (map.Active.Topic) {
var node = _.find(JIT.vizData, function(node) { var node = _.find(map.JIT.vizData, function(node) {
return node.id === Active.Topic.id return node.id === map.Active.Topic.id
}) })
rootIndex = _.indexOf(JIT.vizData, node) rootIndex = _.indexOf(map.JIT.vizData, node)
} }
self.mGraph.loadJSON(JIT.vizData, rootIndex) self.mGraph.loadJSON(map.JIT.vizData, rootIndex)
// compute positions and plot. // compute positions and plot.
self.computePositions() self.computePositions()
self.mGraph.busy = true self.mGraph.busy = true
if (self.type === 'RGraph') { if (self.type === 'RGraph') {
self.mGraph.fx.animate(JIT.RGraph.animate) self.mGraph.fx.animate(map.JIT.RGraph.animate)
} else if (self.type === 'ForceDirected') { } else if (self.type === 'ForceDirected') {
self.mGraph.animate(JIT.ForceDirected.animateSavedLayout) self.mGraph.animate(map.JIT.ForceDirected.animateSavedLayout)
} else if (self.type === 'ForceDirected3D') { } else if (self.type === 'ForceDirected3D') {
self.mGraph.animate(JIT.ForceDirected.animateFDLayout) self.mGraph.animate(map.JIT.ForceDirected.animateFDLayout)
} }
} }
} }
@ -178,7 +174,7 @@ const toExport = {
// hold for a maximum of 80 passes, or 4 seconds of waiting time // hold for a maximum of 80 passes, or 4 seconds of waiting time
var tries = 0 var tries = 0
function hold() { function hold() {
const unique = _.uniq(DataModel.Topics.models, function(metacode) { return metacode.get('metacode_id') }) const unique = _.uniq(map.DataModel.Topics.models, function(metacode) { return metacode.get('metacode_id') })
const requiredMetacodes = _.map(unique, function(metacode) { return metacode.get('metacode_id') }) const requiredMetacodes = _.map(unique, function(metacode) { return metacode.get('metacode_id') })
let loadedCount = 0 let loadedCount = 0
@ -203,7 +199,7 @@ const toExport = {
const self = toExport const self = toExport
self.mGraph.graph.empty() self.mGraph.graph.empty()
self.mGraph.plot() self.mGraph.plot()
JIT.centerMap(Visualize.mGraph.canvas) map.JIT.centerMap(map.Visualize.mGraph.canvas)
$('#infovis').empty() $('#infovis').empty()
} }
} }

View file

@ -4,37 +4,36 @@ import outdent from 'outdent'
import { find as _find } from 'lodash' import { find as _find } from 'lodash'
import { browserHistory } from 'react-router' import { browserHistory } from 'react-router'
import Active from '../Active' import Active from './Active'
import AutoLayout from '../AutoLayout' import AutoLayout from './AutoLayout'
import Cable from '../Cable' import Cable from './Cable'
import Control from '../Control' import CheatSheet from './CheatSheet'
import Create from '../Create' import Control from './Control'
import Create from './Create'
import DataModel from '../DataModel' import DataModel from '../DataModel'
import DataModelMap from '../DataModel/Map' import DataModelMap from '../DataModel/Map'
import MapperCollection from '../DataModel/MapperCollection' import MapperCollection from '../DataModel/MapperCollection'
import TopicCollection from '../DataModel/TopicCollection' import TopicCollection from '../DataModel/TopicCollection'
import SynapseCollection from '../DataModel/SynapseCollection' import SynapseCollection from '../DataModel/SynapseCollection'
import MappingCollection from '../DataModel/MappingCollection' import MappingCollection from '../DataModel/MappingCollection'
import Filter from '../Filter' import Filter from './Filter'
import GlobalUI, { ReactApp } from '../GlobalUI' import GlobalUI, { ReactApp } from '../GlobalUI'
import Import from '../Import' import Import from './Import'
import InfoBox from './InfoBox' import InfoBox from './InfoBox'
import JIT from '../JIT' import JIT from './JIT'
import Listeners from '../Listeners' import Listeners from './Listeners'
import Loading from '../Loading' import Loading from '../Loading'
import Mouse from '../Mouse' import Mouse from './Mouse'
import Organize from '../Organize' import Organize from './Organize'
import PasteInput from '../PasteInput' import PasteInput from './PasteInput'
import Realtime from '../Realtime' import Realtime from './Realtime'
import Selected from '../Selected' import Selected from './Selected'
import Synapse from '../Synapse' import Synapse from './Synapse'
import SynapseCard from '../SynapseCard' import SynapseCard from './SynapseCard'
import Topic from '../Topic' import Topic from './Topic'
import TopicCard from '../Views/TopicCard' import TopicCard from './TopicCard'
import ChatView from '../Views/ChatView' import ChatView from './ChatView'
import Visualize from '../Visualize' import Visualize from './Visualize'
import CheatSheet from './CheatSheet'
const mapControl = { const mapControl = {
launch: function(id, serverData) { launch: function(id, serverData) {
@ -85,10 +84,11 @@ const mapControl = {
newMap.Topic = Topic(newMap) newMap.Topic = Topic(newMap)
newMap.TopicCard = TopicCard(newMap) newMap.TopicCard = TopicCard(newMap)
newMap.Visualize = Visualize(newMap) newMap.Visualize = Visualize(newMap)
console.log(newMap) console.log(newMap)
newMap.Active.Map = new DataModelMap(data.map) newMap.Active.Map = new DataModelMap(data.map)
newMap.Active.Mapper = ReactApp.currentUser
newMap.DataModel.Mappers = new MapperCollection(data.mappers) newMap.DataModel.Mappers = new MapperCollection(data.mappers)
newMap.DataModel.Collaborators = new MapperCollection(data.collaborators) newMap.DataModel.Collaborators = new MapperCollection(data.collaborators)
newMap.DataModel.Topics = new TopicCollection(data.topics) newMap.DataModel.Topics = new TopicCollection(data.topics)
@ -129,7 +129,7 @@ const mapControl = {
$('.rightclickmenu').remove() $('.rightclickmenu').remove()
map.AutoLayout.resetSpiral() map.AutoLayout.resetSpiral()
map.TopicCard.hideCard() map.TopicCard.hideCard()
map.SynapseCard.hideCard() map.map.SynapseCard.hideCard()
map.Create.newTopic.hide(true) // true means force (and override pinned) map.Create.newTopic.hide(true) // true means force (and override pinned)
map.Create.newSynapse.hide() map.Create.newSynapse.hide()
map.InfoBox.close() map.InfoBox.close()
@ -140,7 +140,7 @@ const mapControl = {
} }
export { mapControl } export { mapControl }
const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => { const Map = (map) => {
const toExport = { const toExport = {
mapIsStarred: false, mapIsStarred: false,
requests: [], requests: [],
@ -171,12 +171,12 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
requestAccess: function() { requestAccess: function() {
const self = toExport const self = toExport
self.requests.push({ self.requests.push({
user_id: Active.Mapper.id, user_id: map.Active.Mapper.id,
answered: false, answered: false,
approved: false approved: false
}) })
self.setAccessRequest() self.setAccessRequest()
const mapId = Active.Map.id const mapId = map.Active.Map.id
$.post({ $.post({
url: `/maps/${mapId}/access_request` url: `/maps/${mapId}/access_request`
}) })
@ -184,8 +184,8 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
}, },
setAccessRequest: function() { setAccessRequest: function() {
const self = toExport const self = toExport
if (Active.Mapper) { if (map.Active.Mapper) {
const request = _find(self.requests, r => r.user_id === Active.Mapper.id) const request = _find(self.requests, r => r.user_id === map.Active.Mapper.id)
if (!request) { if (!request) {
self.userRequested = false self.userRequested = false
self.requestAnswered = false self.requestAnswered = false
@ -207,10 +207,10 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
star: function() { star: function() {
var self = toExport var self = toExport
if (!Active.Map) return if (!map.Active.Map) return
$.post('/maps/' + Active.Map.id + '/star') $.post('/maps/' + map.Active.Map.id + '/star')
DataModel.Stars.push({ user_id: Active.Mapper.id, map_id: Active.Map.id }) map.DataModel.Stars.push({ user_id: map.Active.Mapper.id, map_id: map.Active.Map.id })
DataModel.Maps.Starred.add(Active.Map) DataModel.Maps.Starred.add(map.Active.Map)
GlobalUI.notifyUser('Map is now starred') GlobalUI.notifyUser('Map is now starred')
self.mapIsStarred = true self.mapIsStarred = true
ReactApp.render() ReactApp.render()
@ -218,10 +218,10 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
unstar: function() { unstar: function() {
var self = toExport var self = toExport
if (!Active.Map) return if (!map.Active.Map) return
$.post('/maps/' + Active.Map.id + '/unstar') $.post('/maps/' + map.Active.Map.id + '/unstar')
DataModel.Stars = DataModel.Stars.filter(function(s) { return s.user_id !== Active.Mapper.id }) map.DataModel.Stars = map.DataModel.Stars.filter(function(s) { return s.user_id !== map.Active.Mapper.id })
DataModel.Maps.Starred.remove(Active.Map) DataModel.Maps.Starred.remove(map.Active.Map)
self.mapIsStarred = false self.mapIsStarred = false
ReactApp.render() ReactApp.render()
}, },
@ -233,7 +233,7 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
let nodesArray = [] let nodesArray = []
let synapsesArray = [] let synapsesArray = []
// collect the unfiltered topics // collect the unfiltered topics
Visualize.mGraph.graph.eachNode(function(n) { map.Visualize.mGraph.graph.eachNode(function(n) {
// if the opacity is less than 1 then it's filtered // if the opacity is less than 1 then it's filtered
if (n.getData('alpha') === 1) { if (n.getData('alpha') === 1) {
var id = n.getData('topic').id var id = n.getData('topic').id
@ -250,10 +250,10 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
} }
}) })
// collect the unfiltered synapses // collect the unfiltered synapses
DataModel.Synapses.each(function(synapse) { map.DataModel.Synapses.each(function(synapse) {
var desc = synapse.get('desc') var desc = synapse.get('desc')
var descNotFiltered = Filter.visible.synapses.indexOf(desc) > -1 var descNotFiltered = map.Filter.visible.synapses.indexOf(desc) > -1
// make sure that both topics are being added, otherwise, it // make sure that both topics are being added, otherwise, it
// doesn't make sense to add the synapse // doesn't make sense to add the synapse
var topicsNotFiltered = nodesArray.indexOf(synapse.get('topic1_id')) > -1 var topicsNotFiltered = nodesArray.indexOf(synapse.get('topic1_id')) > -1
@ -270,16 +270,16 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
GlobalUI.CreateMap.synapsesToMap = synapsesData GlobalUI.CreateMap.synapsesToMap = synapsesData
}, },
leavePrivateMap: function() { leavePrivateMap: function() {
var map = Active.Map var map = map.Active.Map
DataModel.Maps.Active.remove(map) DataModel.Maps.map.Active.remove(map)
DataModel.Maps.Featured.remove(map) DataModel.Maps.Featured.remove(map)
browserHistory.push('/') browserHistory.push('/')
GlobalUI.notifyUser('Sorry! That map has been changed to Private.') GlobalUI.notifyUser('Sorry! That map has been changed to Private.')
}, },
cantEditNow: function() { cantEditNow: function() {
Realtime.turnOff(true) // true is for 'silence' map.Realtime.turnOff(true) // true is for 'silence'
GlobalUI.notifyUser('Map was changed to Public. Editing is disabled.') GlobalUI.notifyUser('Map was changed to Public. Editing is disabled.')
Active.Map.trigger('changeByOther') map.Active.Map.trigger('changeByOther')
}, },
canEditNow: function() { canEditNow: function() {
var confirmString = "You've been granted permission to edit this map. " var confirmString = "You've been granted permission to edit this map. "
@ -290,13 +290,13 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
} }
}, },
editedByActiveMapper: function() { editedByActiveMapper: function() {
if (Active.Mapper) { if (map.Active.Mapper) {
DataModel.Mappers.add(Active.Mapper) DataModel.Mappers.add(map.Active.Mapper)
} }
}, },
offerScreenshotDownload: () => { offerScreenshotDownload: () => {
const canvas = toExport.getMapCanvasForScreenshots() const canvas = toExport.getMapCanvasForScreenshots()
const filename = toExport.getMapScreenshotFilename(Active.Map) const filename = toExport.getMapScreenshotFilename(map.Active.Map)
var downloadMessage = outdent` var downloadMessage = outdent`
Captured map screenshot! Captured map screenshot!
@ -310,7 +310,7 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
}, },
uploadMapScreenshot: () => { uploadMapScreenshot: () => {
const canvas = toExport.getMapCanvasForScreenshots() const canvas = toExport.getMapCanvasForScreenshots()
const filename = toExport.getMapScreenshotFilename(Active.Map) const filename = toExport.getMapScreenshotFilename(map.Active.Map)
canvas.canvas.toBlob(imageBlob => { canvas.canvas.toBlob(imageBlob => {
const formData = new window.FormData() const formData = new window.FormData()
@ -318,7 +318,7 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
$.ajax({ $.ajax({
type: 'PATCH', type: 'PATCH',
dataType: 'json', dataType: 'json',
url: `/maps/${Active.Map.id}`, url: `/maps/${map.Active.Map.id}`,
data: formData, data: formData,
processData: false, processData: false,
contentType: false, contentType: false,
@ -376,14 +376,14 @@ const Map = ({Active, DataModel, JIT, Visualize, Realtime}) => {
// center it // center it
canvas.getCtx().translate(1880 / 2, 1260 / 2) canvas.getCtx().translate(1880 / 2, 1260 / 2)
var mGraph = Visualize.mGraph var mGraph = map.Visualize.mGraph
var id = mGraph.root var id = mGraph.root
var root = mGraph.graph.getNode(id) var root = mGraph.graph.getNode(id)
var T = !!root.visited var T = !!root.visited
// pass true to avoid basing it on a selection // pass true to avoid basing it on a selection
JIT.zoomExtents(null, canvas, true) map.JIT.zoomExtents(null, canvas, true)
const c = canvas.canvas const c = canvas.canvas
const ctx = canvas.getCtx() const ctx = canvas.getCtx()