eslint frontend folder (#923)

This commit is contained in:
Devin Howard 2016-11-07 15:25:08 -05:00 committed by GitHub
parent 9df974a037
commit a176cdf231
61 changed files with 1723 additions and 1809 deletions

View file

@ -20,6 +20,7 @@ module.exports = {
"rules": { "rules": {
"react/jsx-uses-react": [2], "react/jsx-uses-react": [2],
"react/jsx-uses-vars": [2], "react/jsx-uses-vars": [2],
"space-before-function-paren": [2, "never"],
"yoda": [2, "never", { "exceptRange": true }] "yoda": [2, "never", { "exceptRange": true }]
} }
} }

View file

@ -25,13 +25,12 @@ const Admin = {
liClickHandler: function() { liClickHandler: function() {
var self = Admin var self = Admin
if ($(this).attr('class') != 'toggledOff') { if ($(this).attr('class') !== 'toggledOff') {
$(this).addClass('toggledOff') $(this).addClass('toggledOff')
var value_to_remove = $(this).attr('id') const valueToRemove = $(this).attr('id')
self.selectMetacodes.splice(self.selectMetacodes.indexOf(value_to_remove), 1) self.selectMetacodes.splice(self.selectMetacodes.indexOf(valueToRemove), 1)
$('#metacodes_value').val(self.selectMetacodes.toString()) $('#metacodes_value').val(self.selectMetacodes.toString())
} } else if ($(this).attr('class') === 'toggledOff') {
else if ($(this).attr('class') == 'toggledOff') {
$(this).removeClass('toggledOff') $(this).removeClass('toggledOff')
self.selectMetacodes.push($(this).attr('id')) self.selectMetacodes.push($(this).attr('id'))
$('#metacodes_value').val(self.selectMetacodes.toString()) $('#metacodes_value').val(self.selectMetacodes.toString())
@ -40,7 +39,7 @@ const Admin = {
validate: function() { validate: function() {
var self = Admin var self = Admin
if (self.selectMetacodes.length == 0) { if (self.selectMetacodes.length === 0) {
window.alert('Would you pretty please select at least one metacode for the set?') window.alert('Would you pretty please select at least one metacode for the set?')
return false return false
} }

View file

@ -28,22 +28,19 @@ const AutoLayout = {
self.timeToTurn = 0 self.timeToTurn = 0
// going right? turn down // going right? turn down
if (self.nextXshift == 1 && self.nextYshift == 0) { if (self.nextXshift === 1 && self.nextYshift === 0) {
self.nextXshift = 0 self.nextXshift = 0
self.nextYshift = 1 self.nextYshift = 1
} } else if (self.nextXshift === 0 && self.nextYshift === 1) {
// going down? turn left // going down? turn left
else if (self.nextXshift == 0 && self.nextYshift == 1) {
self.nextXshift = -1 self.nextXshift = -1
self.nextYshift = 0 self.nextYshift = 0
} } else if (self.nextXshift === -1 && self.nextYshift === 0) {
// going left? turn up // going left? turn up
else if (self.nextXshift == -1 && self.nextYshift == 0) {
self.nextXshift = 0 self.nextXshift = 0
self.nextYshift = -1 self.nextYshift = -1
} } else if (self.nextXshift === 0 && self.nextYshift === -1) {
// going up? turn right // going up? turn right
else if (self.nextXshift == 0 && self.nextYshift == -1) {
self.nextXshift = 1 self.nextXshift = 1
self.nextYshift = 0 self.nextYshift = 0
} }

View file

@ -18,7 +18,7 @@ const Control = {
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 || 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) Selected.Nodes.push(node)
@ -126,18 +126,16 @@ const Control = {
} }
if (!Active.Map) return if (!Active.Map) return
var l = Selected.Nodes.length, const l = Selected.Nodes.length
i, const authorized = Active.Map.authorizeToEdit(Active.Mapper)
node,
authorized = Active.Map.authorizeToEdit(Active.Mapper)
if (!authorized) { if (!authorized) {
GlobalUI.notifyUser('Cannot edit Public map.') GlobalUI.notifyUser('Cannot edit Public map.')
return return
} }
for (i = l - 1; i >= 0; i -= 1) { for (let i = l - 1; i >= 0; i -= 1) {
node = Selected.Nodes[i] const node = Selected.Nodes[i]
Control.removeNode(node.id) Control.removeNode(node.id)
} }
}, },
@ -163,12 +161,9 @@ const Control = {
Control.hideNode(nodeid) Control.hideNode(nodeid)
}, },
hideSelectedNodes: function() { hideSelectedNodes: function() {
var l = Selected.Nodes.length, const l = Selected.Nodes.length
i, for (let i = l - 1; i >= 0; i -= 1) {
node const node = Selected.Nodes[i]
for (i = l - 1; i >= 0; i -= 1) {
node = Selected.Nodes[i]
Control.hideNode(node.id) Control.hideNode(node.id)
} }
}, },
@ -190,7 +185,7 @@ const Control = {
}) })
setTimeout(function() { setTimeout(function() {
if (nodeid === Visualize.mGraph.root) { // && Visualize.type === "RGraph" if (nodeid === Visualize.mGraph.root) { // && 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) Visualize.mGraph.graph.removeNode(nodeid)
@ -199,9 +194,9 @@ const Control = {
Filter.checkMappers() 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 || Selected.Edges.indexOf(edge) !== -1) return
var width = Mouse.edgeHoveringOver === edge ? 4 : 2 var width = Mouse.edgeHoveringOver === edge ? 4 : 2
edge.setDataset('current', { edge.setDataset('current', {
@ -243,9 +238,6 @@ const Control = {
Selected.Edges.indexOf(edge), 1) Selected.Edges.indexOf(edge), 1)
}, },
deleteSelectedEdges: function() { // refers to deleting topics permanently deleteSelectedEdges: function() { // refers to deleting topics permanently
var edge,
l = Selected.Edges.length
if (!Active.Map) return if (!Active.Map) return
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = Active.Map.authorizeToEdit(Active.Mapper)
@ -255,8 +247,9 @@ const Control = {
return return
} }
for (var i = l - 1; i >= 0; i -= 1) { const l = Selected.Edges.length
edge = Selected.Edges[i] for (let i = l - 1; i >= 0; i -= 1) {
const edge = Selected.Edges[i]
Control.deleteEdge(edge) Control.deleteEdge(edge)
} }
}, },
@ -301,9 +294,7 @@ const Control = {
// Topic view is handled by removeSelectedNodes // Topic view is handled by removeSelectedNodes
if (!Active.Map) return if (!Active.Map) return
var l = Selected.Edges.length, const l = Selected.Edges.length
i,
edge
var authorized = Active.Map.authorizeToEdit(Active.Mapper) var authorized = Active.Map.authorizeToEdit(Active.Mapper)
@ -312,8 +303,8 @@ const Control = {
return return
} }
for (i = l - 1; i >= 0; i -= 1) { for (let i = l - 1; i >= 0; i -= 1) {
edge = Selected.Edges[i] const edge = Selected.Edges[i]
Control.removeEdge(edge) Control.removeEdge(edge)
} }
Selected.Edges = [ ] Selected.Edges = [ ]
@ -351,11 +342,9 @@ const Control = {
}]) }])
}, },
hideSelectedEdges: function() { hideSelectedEdges: function() {
var edge, const l = Selected.Edges.length
l = Selected.Edges.length, for (let i = l - 1; i >= 0; i -= 1) {
i const edge = Selected.Edges[i]
for (i = l - 1; i >= 0; i -= 1) {
edge = Selected.Edges[i]
Control.hideEdge(edge) Control.hideEdge(edge)
} }
Selected.Edges = [ ] Selected.Edges = [ ]
@ -381,12 +370,12 @@ const Control = {
GlobalUI.notifyUser('Working...') GlobalUI.notifyUser('Working...')
// variables to keep track of how many nodes and synapses you had the ability to change the permission of // variables to keep track of how many nodes and synapses you had the ability to change the permission of
var nCount = 0, var nCount = 0
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
var l = Selected.Edges.length const edgesLength = Selected.Edges.length
for (var i = l - 1; i >= 0; i -= 1) { for (let i = edgesLength - 1; i >= 0; i -= 1) {
edge = Selected.Edges[i] edge = Selected.Edges[i]
synapse = edge.getData('synapses')[0] synapse = edge.getData('synapses')[0]
@ -399,8 +388,8 @@ const Control = {
} }
// 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 const nodesLength = Selected.Nodes.length
for (var i = l - 1; i >= 0; i -= 1) { for (let i = nodesLength - 1; i >= 0; i -= 1) {
node = Selected.Nodes[i] node = Selected.Nodes[i]
topic = node.getData('topic') topic = node.getData('topic')
@ -418,12 +407,12 @@ const Control = {
var message = nString + sString + ' you created updated to ' + permission var message = nString + sString + ' you created updated to ' + permission
GlobalUI.notifyUser(message) GlobalUI.notifyUser(message)
}, },
updateSelectedMetacodes: function (metacode_id) { updateSelectedMetacodes: function(metacodeId) {
var node, topic var node, topic
GlobalUI.notifyUser('Working...') GlobalUI.notifyUser('Working...')
var metacode = DataModel.Metacodes.get(metacode_id) var metacode = DataModel.Metacodes.get(metacodeId)
// variables to keep track of how many nodes and synapses you had the ability to change the permission of // variables to keep track of how many nodes and synapses you had the ability to change the permission of
var nCount = 0 var nCount = 0
@ -436,7 +425,7 @@ const Control = {
if (topic.authorizeToEdit(Active.Mapper)) { if (topic.authorizeToEdit(Active.Mapper)) {
topic.save({ topic.save({
'metacode_id': metacode_id 'metacode_id': metacodeId
}) })
nCount++ nCount++
} }

View file

@ -32,20 +32,20 @@ const Create = {
toggleMetacodeSelected: function() { toggleMetacodeSelected: function() {
var self = Create var self = Create
if ($(this).attr('class') != 'toggledOff') { if ($(this).attr('class') !== 'toggledOff') {
$(this).addClass('toggledOff') $(this).addClass('toggledOff')
var value_to_remove = $(this).attr('id') var valueToRemove = $(this).attr('id')
var name_to_remove = $(this).attr('data-name') var nameToRemove = $(this).attr('data-name')
self.newSelectedMetacodes.splice(self.newSelectedMetacodes.indexOf(value_to_remove), 1) self.newSelectedMetacodes.splice(self.newSelectedMetacodes.indexOf(valueToRemove), 1)
self.newSelectedMetacodeNames.splice(self.newSelectedMetacodeNames.indexOf(name_to_remove), 1) self.newSelectedMetacodeNames.splice(self.newSelectedMetacodeNames.indexOf(nameToRemove), 1)
} else if ($(this).attr('class') == 'toggledOff') { } else if ($(this).attr('class') === 'toggledOff') {
$(this).removeClass('toggledOff') $(this).removeClass('toggledOff')
self.newSelectedMetacodes.push($(this).attr('id')) self.newSelectedMetacodes.push($(this).attr('id'))
self.newSelectedMetacodeNames.push($(this).attr('data-name')) self.newSelectedMetacodeNames.push($(this).attr('data-name'))
} }
}, },
updateMetacodeSet: function(set, index, custom) { updateMetacodeSet: function(set, index, custom) {
if (custom && Create.newSelectedMetacodes.length == 0) { if (custom && Create.newSelectedMetacodes.length === 0) {
window.alert('Please select at least one metacode to use!') window.alert('Please select at least one metacode to use!')
return false return false
} }
@ -62,8 +62,7 @@ const Create = {
Create.selectedMetacodeNames = [] Create.selectedMetacodeNames = []
Create.newSelectedMetacodes = [] Create.newSelectedMetacodes = []
Create.newSelectedMetacodeNames = [] Create.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
Create.selectedMetacodes = Create.newSelectedMetacodes.slice(0) Create.selectedMetacodes = Create.newSelectedMetacodes.slice(0)
Create.selectedMetacodeNames = Create.newSelectedMetacodeNames.slice(0) Create.selectedMetacodeNames = Create.newSelectedMetacodeNames.slice(0)
@ -120,7 +119,7 @@ const Create = {
var self = Create var self = Create
self.isSwitchingSet = false self.isSwitchingSet = false
if (self.selectedMetacodeSet != 'metacodeset-custom') { if (self.selectedMetacodeSet !== 'metacodeset-custom') {
$('.customMetacodeList li').addClass('toggledOff') $('.customMetacodeList li').addClass('toggledOff')
self.selectedMetacodes = [] self.selectedMetacodes = []
self.selectedMetacodeNames = [] self.selectedMetacodeNames = []
@ -149,8 +148,7 @@ const Create = {
if (Create.newTopic.pinned) { if (Create.newTopic.pinned) {
$('.pinCarousel').removeClass('isPinned') $('.pinCarousel').removeClass('isPinned')
Create.newTopic.pinned = false Create.newTopic.pinned = false
} } else {
else {
$('.pinCarousel').addClass('isPinned') $('.pinCarousel').addClass('isPinned')
Create.newTopic.pinned = true Create.newTopic.pinned = true
} }
@ -174,13 +172,13 @@ const Create = {
[{ [{
name: 'topic_autocomplete', name: 'topic_autocomplete',
limit: 8, limit: 8,
display: function (s) { return s.label; }, display: function(s) { return s.label },
templates: { templates: {
suggestion: function(s) { suggestion: function(s) {
return Hogan.compile($('#topicAutocompleteTemplate').html()).render(s) return Hogan.compile($('#topicAutocompleteTemplate').html()).render(s)
} }
}, },
source: topicBloodhound, source: topicBloodhound
}] }]
) )
@ -246,15 +244,13 @@ const Create = {
}, },
newSynapse: { newSynapse: {
init: function() { init: function() {
var self = Create.newSynapse
var synapseBloodhound = new Bloodhound({ var synapseBloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace, queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: { remote: {
url: '/search/synapses?term=%QUERY', url: '/search/synapses?term=%QUERY',
wildcard: '%QUERY', wildcard: '%QUERY'
}, }
}) })
var existingSynapseBloodhound = new Bloodhound({ var existingSynapseBloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
@ -269,42 +265,44 @@ const Create = {
} else { } else {
return null return null
} }
}, }
}, }
}) })
// initialize the autocomplete results for synapse creation // initialize the autocomplete results for synapse creation
$('#synapse_desc').typeahead( $('#synapse_desc').typeahead(
{ {
highlight: true, highlight: true,
minLength: 2, minLength: 2
}, },
[{ [{
name: 'synapse_autocomplete', name: 'synapse_autocomplete',
display: function (s) { return s.label; }, display: function(s) { return s.label },
templates: { templates: {
suggestion: function(s) { suggestion: function(s) {
return Hogan.compile("<div class='genericSynapseDesc'>{{label}}</div>").render(s) return Hogan.compile("<div class='genericSynapseDesc'>{{label}}</div>").render(s)
}
}, },
}, source: synapseBloodhound
source: synapseBloodhound,
}, },
{ {
name: 'existing_synapses', name: 'existing_synapses',
limit: 50, limit: 50,
display: function (s) { return s.label; }, display: function(s) { return s.label },
templates: { templates: {
suggestion: function(s) { suggestion: function(s) {
return Hogan.compile($('#synapseAutocompleteTemplate').html()).render(s) return Hogan.compile($('#synapseAutocompleteTemplate').html()).render(s)
}, },
header: '<h3>Existing synapses</h3>' header: '<h3>Existing synapses</h3>'
}, },
source: existingSynapseBloodhound, source: existingSynapseBloodhound
}] }]
) )
$('#synapse_desc').keyup(function(e) { $('#synapse_desc').keyup(function(e) {
var ESC = 27, BACKSPACE = 8, DELETE = 46 const ESC = 27
const BACKSPACE = 8
const DELETE = 46
if (e.keyCode === BACKSPACE && $(this).val() === '' || if (e.keyCode === BACKSPACE && $(this).val() === '' ||
e.keyCode === DELETE && $(this).val() === '' || e.keyCode === DELETE && $(this).val() === '' ||
e.keyCode === ESC) { e.keyCode === ESC) {
@ -348,7 +346,7 @@ const Create = {
Create.newSynapse.topic2id = 0 Create.newSynapse.topic2id = 0
Mouse.synapseStartCoordinates = [] Mouse.synapseStartCoordinates = []
if (Visualize.mGraph) Visualize.mGraph.plot() if (Visualize.mGraph) Visualize.mGraph.plot()
}, }
} }
} }

View file

@ -9,11 +9,6 @@ import InfoBox from '../Map/InfoBox'
import Mapper from '../Mapper' import Mapper from '../Mapper'
import Realtime from '../Realtime' import Realtime from '../Realtime'
import MapperCollection from './MapperCollection'
import TopicCollection from './TopicCollection'
import SynapseCollection from './SynapseCollection'
import MappingCollection from './MappingCollection'
const Map = Backbone.Model.extend({ const Map = Backbone.Model.extend({
urlRoot: '/maps', urlRoot: '/maps',
blacklist: ['created_at', 'updated_at', 'created_at_clean', 'updated_at_clean', 'user_name', 'contributor_count', 'topic_count', 'synapse_count', 'topics', 'synapses', 'mappings', 'mappers'], blacklist: ['created_at', 'updated_at', 'created_at_clean', 'updated_at_clean', 'user_name', 'contributor_count', 'topic_count', 'synapse_count', 'topics', 'synapses', 'mappings', 'mappers'],

View file

@ -210,8 +210,7 @@ const Filter = {
}, },
checkMappers: function() { checkMappers: function() {
var self = Filter var self = Filter
var onMap = Active.Map ? true : false if (Active.Map) {
if (onMap) {
self.updateFilters('Mappings', 'user_id', 'Mappers', 'mappers', 'mapper') self.updateFilters('Mappings', 'user_id', 'Mappers', 'mappers', 'mapper')
} else { } else {
// on topic view // on topic view
@ -274,13 +273,13 @@ const Filter = {
// to reduce code redundancy // to reduce code redundancy
// gets called in the context of a list item in a filter box // gets called in the context of a list item in a filter box
toggleLi: function(whichToFilter) { toggleLi: function(whichToFilter) {
var self = Filter, index var self = Filter
var id = $(this).attr('data-id') var id = $(this).attr('data-id')
if (self.visible[whichToFilter].indexOf(id) == -1) { if (self.visible[whichToFilter].indexOf(id) === -1) {
self.visible[whichToFilter].push(id) self.visible[whichToFilter].push(id)
$(this).removeClass('toggledOff') $(this).removeClass('toggledOff')
} else { } else {
index = self.visible[whichToFilter].indexOf(id) const index = self.visible[whichToFilter].indexOf(id)
self.visible[whichToFilter].splice(index, 1) self.visible[whichToFilter].splice(index, 1)
$(this).addClass('toggledOff') $(this).addClass('toggledOff')
} }
@ -293,8 +292,7 @@ const Filter = {
if (self.visible.metacodes.length === self.filters.metacodes.length) { if (self.visible.metacodes.length === self.filters.metacodes.length) {
$('.showAllMetacodes').addClass('active') $('.showAllMetacodes').addClass('active')
$('.hideAllMetacodes').removeClass('active') $('.hideAllMetacodes').removeClass('active')
} } else if (self.visible.metacodes.length === 0) {
else if (self.visible.metacodes.length === 0) {
$('.showAllMetacodes').removeClass('active') $('.showAllMetacodes').removeClass('active')
$('.hideAllMetacodes').addClass('active') $('.hideAllMetacodes').addClass('active')
} else { } else {
@ -309,8 +307,7 @@ const Filter = {
if (self.visible.mappers.length === self.filters.mappers.length) { if (self.visible.mappers.length === self.filters.mappers.length) {
$('.showAllMappers').addClass('active') $('.showAllMappers').addClass('active')
$('.hideAllMappers').removeClass('active') $('.hideAllMappers').removeClass('active')
} } else if (self.visible.mappers.length === 0) {
else if (self.visible.mappers.length === 0) {
$('.showAllMappers').removeClass('active') $('.showAllMappers').removeClass('active')
$('.hideAllMappers').addClass('active') $('.hideAllMappers').addClass('active')
} else { } else {
@ -325,8 +322,7 @@ const Filter = {
if (self.visible.synapses.length === self.filters.synapses.length) { if (self.visible.synapses.length === self.filters.synapses.length) {
$('.showAllSynapses').addClass('active') $('.showAllSynapses').addClass('active')
$('.hideAllSynapses').removeClass('active') $('.hideAllSynapses').removeClass('active')
} } else if (self.visible.synapses.length === 0) {
else if (self.visible.synapses.length === 0) {
$('.showAllSynapses').removeClass('active') $('.showAllSynapses').removeClass('active')
$('.hideAllSynapses').addClass('active') $('.hideAllSynapses').addClass('active')
} else { } else {
@ -339,45 +335,38 @@ const Filter = {
var visible = self.visible var visible = self.visible
var passesMetacode, passesMapper, passesSynapse var passesMetacode, passesMapper, passesSynapse
var onMap
if (Active.Map) { var opacityForFilter = Active.Map ? 0 : 0.4
onMap = true
}
else if (Active.Topic) {
onMap = false
}
var opacityForFilter = onMap ? 0 : 0.4
DataModel.Topics.each(function(topic) { DataModel.Topics.each(function(topic) {
var n = topic.get('node') var n = topic.get('node')
var metacode_id = topic.get('metacode_id').toString() var metacodeId = topic.get('metacode_id').toString()
if (visible.metacodes.indexOf(metacode_id) == -1) passesMetacode = false if (visible.metacodes.indexOf(metacodeId) === -1) passesMetacode = false
else passesMetacode = true else passesMetacode = true
if (onMap) { if (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
var user_id = topic.getMapping().get('user_id').toString() let userId = topic.getMapping().get('user_id').toString()
if (visible.mappers.indexOf(user_id) == -1) passesMapper = false if (visible.mappers.indexOf(userId) === -1) passesMapper = false
else passesMapper = true else passesMapper = true
} else { } else {
// when on a topic view, // when on a topic view,
// we filter by mapper according to the person who created the // we filter by mapper according to the person who created the
// topic or synapse // topic or synapse
var user_id = topic.get('user_id').toString() let userId = topic.get('user_id').toString()
if (visible.mappers.indexOf(user_id) == -1) passesMapper = false if (visible.mappers.indexOf(userId) === -1) passesMapper = false
else passesMapper = true else passesMapper = true
} }
if (passesMetacode && passesMapper) { if (passesMetacode && passesMapper) {
if (n) { if (n) {
n.setData('alpha', 1, 'end') n.setData('alpha', 1, 'end')
} else {
console.log(topic)
} }
else console.log(topic)
} else { } else {
if (n) { if (n) {
Control.deselectNode(n, true) Control.deselectNode(n, true)
@ -385,8 +374,9 @@ const Filter = {
n.eachAdjacency(function(e) { n.eachAdjacency(function(e) {
Control.deselectEdge(e, true) Control.deselectEdge(e, true)
}) })
} else {
console.log(topic)
} }
else console.log(topic)
} }
}) })
@ -398,7 +388,7 @@ const Filter = {
DataModel.Synapses.each(function(synapse) { DataModel.Synapses.each(function(synapse) {
var e = synapse.get('edge') var e = synapse.get('edge')
var desc var desc
var user_id = synapse.get('user_id').toString() var userId = synapse.get('user_id').toString()
if (e && !e.getData('touched')) { if (e && !e.getData('touched')) {
var synapses = e.getData('synapses') var synapses = e.getData('synapses')
@ -406,7 +396,7 @@ const Filter = {
// if any of the synapses represent by the edge are still unfiltered // if any of the synapses represent by the edge are still unfiltered
// leave the edge visible // leave the edge visible
passesSynapse = false passesSynapse = false
for (var i = 0; i < synapses.length; i++) { for (let i = 0; i < synapses.length; i++) {
desc = synapses[i].get('desc') desc = synapses[i].get('desc')
if (visible.synapses.indexOf(desc) > -1) passesSynapse = true if (visible.synapses.indexOf(desc) > -1) passesSynapse = true
} }
@ -416,9 +406,9 @@ const Filter = {
var displayIndex = e.getData('displayIndex') ? e.getData('displayIndex') : 0 var displayIndex = e.getData('displayIndex') ? e.getData('displayIndex') : 0
var displayedSynapse = synapses[displayIndex] var displayedSynapse = synapses[displayIndex]
desc = displayedSynapse.get('desc') desc = displayedSynapse.get('desc')
if (passesSynapse && visible.synapses.indexOf(desc) == -1) { if (passesSynapse && visible.synapses.indexOf(desc) === -1) {
// iterate and find an unfiltered one // iterate and find an unfiltered one
for (var i = 0; i < synapses.length; i++) { for (let i = 0; i < synapses.length; i++) {
desc = synapses[i].get('desc') desc = synapses[i].get('desc')
if (visible.synapses.indexOf(desc) > -1) { if (visible.synapses.indexOf(desc) > -1) {
e.setData('displayIndex', i) e.setData('displayIndex', i)
@ -427,13 +417,13 @@ const Filter = {
} }
} }
if (onMap) { if (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
user_id = synapse.getMapping().get('user_id').toString() userId = synapse.getMapping().get('user_id').toString()
} }
if (visible.mappers.indexOf(user_id) == -1) passesMapper = false if (visible.mappers.indexOf(userId) === -1) passesMapper = false
else passesMapper = true else passesMapper = true
var color = Settings.colors.synapses.normal var color = Settings.colors.synapses.normal
@ -446,8 +436,9 @@ const Filter = {
} }
e.setData('touched', true) e.setData('touched', true)
} else if (!e) {
console.log(synapse)
} }
else if (!e) console.log(synapse)
}) })
// run the animation // run the animation

View file

@ -83,7 +83,6 @@ const CreateMap = {
GlobalUI.notifyUser('Working...') GlobalUI.notifyUser('Working...')
}, },
throwMapNameError: function() { throwMapNameError: function() {
var formId = GlobalUI.lightbox === 'forkmap' ? '#fork_map' : '#new_map' var formId = GlobalUI.lightbox === 'forkmap' ? '#fork_map' : '#new_map'
var $form = $(formId) var $form = $(formId)
@ -97,7 +96,6 @@ const CreateMap = {
}, 5000) }, 5000)
}, },
success: function(model) { success: function(model) {
var self = CreateMap
// push the new map onto the collection of 'my maps' // push the new map onto the collection of 'my maps'
DataModel.Maps.Mine.add(model) DataModel.Maps.Mine.add(model)

View file

@ -19,7 +19,7 @@ const Import = {
synapseWhitelist: [ synapseWhitelist: [
'topic1', 'topic2', 'category', 'direction', 'desc', 'description', 'permission' 'topic1', 'topic2', 'category', 'direction', 'desc', 'description', 'permission'
], ],
cidMappings: {}, // to be filled by import_id => cid mappings cidMappings: {}, // to be filled by importId => cid mappings
handleTSV: function(text) { handleTSV: function(text) {
const results = Import.parseTabbedString(text) const results = Import.parseTabbedString(text)
@ -37,14 +37,14 @@ const Import = {
if (synapsesText) synapsesText = synapsesText[2].replace(topicsRegex, '') if (synapsesText) synapsesText = synapsesText[2].replace(topicsRegex, '')
// merge default options and extra options passed in parserOpts argument // merge default options and extra options passed in parserOpts argument
const csv_parser_options = Object.assign({ const csvParserOptions = Object.assign({
columns: true, // get headers columns: true, // get headers
relax_column_count: true, relax_column_count: true,
skip_empty_lines: true skip_empty_lines: true
}, parserOpts) }, parserOpts)
const topicsPromise = $.Deferred() const topicsPromise = $.Deferred()
parse(topicsText, csv_parser_options, (err, data) => { parse(topicsText, csvParserOptions, (err, data) => {
if (err) { if (err) {
console.warn(err) console.warn(err)
return topicsPromise.resolve([]) return topicsPromise.resolve([])
@ -53,7 +53,7 @@ const Import = {
}) })
const synapsesPromise = $.Deferred() const synapsesPromise = $.Deferred()
parse(synapsesText, csv_parser_options, (err, data) => { parse(synapsesText, csvParserOptions, (err, data) => {
if (err) { if (err) {
console.warn(err) console.warn(err)
return synapsesPromise.resolve([]) return synapsesPromise.resolve([])
@ -113,8 +113,8 @@ const Import = {
var topicHeaders = [] var topicHeaders = []
var synapseHeaders = [] var synapseHeaders = []
lines.forEach(function (line_raw, index) { lines.forEach(function(lineRaw, index) {
var line = line_raw.split('\t') const line = lineRaw.split('\t')
var noblanks = line.filter(function(elt) { var noblanks = line.filter(function(elt) {
return elt !== '' return elt !== ''
}) })
@ -227,7 +227,7 @@ const Import = {
coords, coords,
name: topic.name, name: topic.name,
permission: topic.permission, permission: topic.permission,
import_id: topic.id importId: topic.id
}) })
return // "continue" return // "continue"
} }
@ -277,31 +277,31 @@ const Import = {
}) })
}, },
createTopicWithParameters: function (name, metacode_name, permission, desc, createTopicWithParameters: function(name, metacodeName, permission, desc,
link, xloc, yloc, import_id, opts = {}) { link, xloc, yloc, importId, opts = {}) {
var self = Import var self = Import
$(document).trigger(Map.events.editedByActiveMapper) $(document).trigger(Map.events.editedByActiveMapper)
var metacode = DataModel.Metacodes.where({name: metacode_name})[0] || null var metacode = DataModel.Metacodes.where({name: metacodeName})[0] || null
if (metacode === null) { if (metacode === null) {
metacode = DataModel.Metacodes.where({ name: 'Wildcard' })[0] metacode = DataModel.Metacodes.where({ name: 'Wildcard' })[0]
console.warn("Couldn't find metacode " + metacode_name + ' so used Wildcard instead.') console.warn("Couldn't find metacode " + metacodeName + ' so used Wildcard instead.')
} }
var topic_permission = permission || Active.Map.get('permission') const topicPermision = permission || Active.Map.get('permission')
var defer_to_map_id = permission === topic_permission ? Active.Map.get('id') : null var deferToMapId = permission === topicPermision ? 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,
permission: topic_permission, permission: topicPermision,
defer_to_map_id: defer_to_map_id, defer_to_map_id: deferToMapId,
desc: desc || '', desc: desc || '',
link: link || '', link: link || '',
calculated_permission: Active.Map.get('permission') calculated_permission: Active.Map.get('permission')
}) })
DataModel.Topics.add(topic) DataModel.Topics.add(topic)
if (import_id !== null && import_id !== undefined) { if (importId !== null && importId !== undefined) {
self.cidMappings[import_id] = topic.cid self.cidMappings[importId] = topic.cid
} }
var mapping = new DataModel.Mapping({ var mapping = new DataModel.Mapping({
@ -356,7 +356,7 @@ const Import = {
const name = opts.name || 'Link' const name = opts.name || 'Link'
const metacode = opts.metacode || 'Reference' const metacode = opts.metacode || 'Reference'
const import_id = opts.import_id || null // don't store a cidMapping const importId = opts.importId || null // don't store a cidMapping
const permission = opts.permission || null // use default const permission = opts.permission || null // use default
const desc = opts.desc || url const desc = opts.desc || url
@ -368,7 +368,7 @@ const Import = {
url, url,
coords.x, coords.x,
coords.y, coords.y,
import_id, importId,
{ {
success: function(topic) { success: function(topic) {
if (topic.get('name') !== 'Link') return if (topic.get('name') !== 'Link') return

View file

@ -13,7 +13,6 @@ import Filter from './Filter'
import GlobalUI from './GlobalUI' import GlobalUI from './GlobalUI'
import Map from './Map' import Map from './Map'
import Mouse from './Mouse' import Mouse from './Mouse'
import Realtime from './Realtime'
import Selected from './Selected' import Selected from './Selected'
import Settings from './Settings' import Settings from './Settings'
import Synapse from './Synapse' import Synapse from './Synapse'
@ -746,111 +745,109 @@ const JIT = {
if (node && !node.nodeFrom) { if (node && !node.nodeFrom) {
self.handleSelectionBeforeDragging(node, e) self.handleSelectionBeforeDragging(node, e)
var pos = eventInfo.getPos(), const pos = eventInfo.getPos()
EDGE_THICKNESS = 30 /** Metamaps.Visualize.mGraph.canvas.scaleOffsetX*/, const EDGE_THICKNESS = 30
SHIFT = 2 / Metamaps.Visualize.mGraph.canvas.scaleOffsetX, const SHIFT = 2 / Visualize.mGraph.canvas.scaleOffsetX
PERIOD = 5; const PERIOD = 5
// self.virtualPointer = pos; // self.virtualPointer = pos;
// if it's a left click, or a touch, move the node // if it's a left click, or a touch, move the node
if (e.touches || (e.button === 0 && !e.altKey && !e.ctrlKey && (e.buttons === 0 || e.buttons === 1 || e.buttons === undefined))) { if (e.touches || (e.button === 0 && !e.altKey && !e.ctrlKey && (e.buttons === 0 || e.buttons === 1 || e.buttons === undefined))) {
const width = Visualize.mGraph.canvas.getSize().width
var width = Visualize.mGraph.canvas.getSize().width, const height = Visualize.mGraph.canvas.getSize().height
height = Visualize.mGraph.canvas.getSize().height, const xPix = Util.coordsToPixels(Visualize.mGraph, pos).x
xPix = Util.coordsToPixels(Visualize.mGraph, pos).x, const yPix = Util.coordsToPixels(Visualize.mGraph, pos).y
yPix = Util.coordsToPixels(Visualize.mGraph, pos).y;
if (self.dragFlag === 0) { if (self.dragFlag === 0) {
self.mouseDownPix = Util.coordsToPixels(Visualize.mGraph, eventInfo.getPos()); self.mouseDownPix = Util.coordsToPixels(Visualize.mGraph, eventInfo.getPos())
self.dragFlag = 1; self.dragFlag = 1
} }
if (Util.getDistance(Util.coordsToPixels(Visualize.mGraph, pos), self.mouseDownPix) > 2 && !self.dragTolerance) { if (Util.getDistance(Util.coordsToPixels(Visualize.mGraph, pos), self.mouseDownPix) > 2 && !self.dragTolerance) {
self.dragTolerance = 1; self.dragTolerance = 1
} }
if (xPix < EDGE_THICKNESS && self.dragTolerance) { if (xPix < EDGE_THICKNESS && self.dragTolerance) {
clearInterval(self.dragLeftEdge); clearInterval(self.dragLeftEdge)
clearInterval(self.dragRightEdge); clearInterval(self.dragRightEdge)
clearInterval(self.dragTopEdge); clearInterval(self.dragTopEdge)
clearInterval(self.dragBottomEdge); clearInterval(self.dragBottomEdge)
self.virtualPointer = { x: Util.pixelsToCoords(Visualize.mGraph, { x: EDGE_THICKNESS, y: yPix }).x - SHIFT, y: pos.y } self.virtualPointer = { x: Util.pixelsToCoords(Visualize.mGraph, { x: EDGE_THICKNESS, y: yPix }).x - SHIFT, y: pos.y }
Visualize.mGraph.canvas.translate(SHIFT, 0); Visualize.mGraph.canvas.translate(SHIFT, 0)
self.updateTopicPositions(node, self.virtualPointer); self.updateTopicPositions(node, self.virtualPointer)
Visualize.mGraph.plot(); Visualize.mGraph.plot()
self.dragLeftEdge = setInterval(function() { self.dragLeftEdge = setInterval(function() {
self.virtualPointer = { x: Util.pixelsToCoords(Visualize.mGraph, { x: EDGE_THICKNESS, y: yPix }).x - SHIFT, y: pos.y } self.virtualPointer = { x: Util.pixelsToCoords(Visualize.mGraph, { x: EDGE_THICKNESS, y: yPix }).x - SHIFT, y: pos.y }
Visualize.mGraph.canvas.translate(SHIFT, 0); Visualize.mGraph.canvas.translate(SHIFT, 0)
self.updateTopicPositions(node,self.virtualPointer); self.updateTopicPositions(node, self.virtualPointer)
Visualize.mGraph.plot(); Visualize.mGraph.plot()
} , PERIOD); }, PERIOD)
} }
if (width - xPix < EDGE_THICKNESS && self.dragTolerance) { if (width - xPix < EDGE_THICKNESS && self.dragTolerance) {
clearInterval(self.dragLeftEdge); clearInterval(self.dragLeftEdge)
clearInterval(self.dragRightEdge); clearInterval(self.dragRightEdge)
clearInterval(self.dragTopEdge); clearInterval(self.dragTopEdge)
clearInterval(self.dragBottomEdge); clearInterval(self.dragBottomEdge)
self.virtualPointer = { x: Util.pixelsToCoords(Visualize.mGraph, { x: width - EDGE_THICKNESS, y: yPix }).x + SHIFT, y: pos.y } self.virtualPointer = { x: Util.pixelsToCoords(Visualize.mGraph, { x: width - EDGE_THICKNESS, y: yPix }).x + SHIFT, y: pos.y }
Visualize.mGraph.canvas.translate(-SHIFT, 0); Visualize.mGraph.canvas.translate(-SHIFT, 0)
self.updateTopicPositions(node, self.virtualPointer); self.updateTopicPositions(node, self.virtualPointer)
Visualize.mGraph.plot(); Visualize.mGraph.plot()
self.dragRightEdge = setInterval(function() { self.dragRightEdge = setInterval(function() {
self.virtualPointer = { x: Util.pixelsToCoords(Visualize.mGraph, { x: width - EDGE_THICKNESS, y: yPix }).x + SHIFT, y: pos.y } self.virtualPointer = { x: Util.pixelsToCoords(Visualize.mGraph, { x: width - EDGE_THICKNESS, y: yPix }).x + SHIFT, y: pos.y }
Visualize.mGraph.canvas.translate(-SHIFT, 0); Visualize.mGraph.canvas.translate(-SHIFT, 0)
self.updateTopicPositions(node, self.virtualPointer); self.updateTopicPositions(node, self.virtualPointer)
Visualize.mGraph.plot(); Visualize.mGraph.plot()
} , PERIOD); }, PERIOD)
} }
if (yPix < EDGE_THICKNESS && self.dragTolerance) { if (yPix < EDGE_THICKNESS && self.dragTolerance) {
clearInterval(self.dragLeftEdge); clearInterval(self.dragLeftEdge)
clearInterval(self.dragRightEdge); clearInterval(self.dragRightEdge)
clearInterval(self.dragTopEdge); clearInterval(self.dragTopEdge)
clearInterval(self.dragBottomEdge); clearInterval(self.dragBottomEdge)
self.virtualPointer = { x: pos.x, y: Util.pixelsToCoords(Visualize.mGraph, { x: xPix, y: EDGE_THICKNESS }).y - SHIFT } self.virtualPointer = { x: pos.x, y: Util.pixelsToCoords(Visualize.mGraph, { x: xPix, y: EDGE_THICKNESS }).y - SHIFT }
Visualize.mGraph.canvas.translate(0, SHIFT); Visualize.mGraph.canvas.translate(0, SHIFT)
self.updateTopicPositions(node, self.virtualPointer); self.updateTopicPositions(node, self.virtualPointer)
Visualize.mGraph.plot(); Visualize.mGraph.plot()
self.dragTopEdge = setInterval(function() { self.dragTopEdge = setInterval(function() {
self.virtualPointer = { x: pos.x, y: Util.pixelsToCoords(Visualize.mGraph, { x: xPix, y: EDGE_THICKNESS }).y - SHIFT } self.virtualPointer = { x: pos.x, y: Util.pixelsToCoords(Visualize.mGraph, { x: xPix, y: EDGE_THICKNESS }).y - SHIFT }
Visualize.mGraph.canvas.translate(0, SHIFT); Visualize.mGraph.canvas.translate(0, SHIFT)
self.updateTopicPositions(node, self.virtualPointer); self.updateTopicPositions(node, self.virtualPointer)
Visualize.mGraph.plot(); Visualize.mGraph.plot()
} , PERIOD); }, PERIOD)
} }
if (height - yPix < EDGE_THICKNESS && self.dragTolerance) { if (height - yPix < EDGE_THICKNESS && self.dragTolerance) {
clearInterval(self.dragLeftEdge); clearInterval(self.dragLeftEdge)
clearInterval(self.dragRightEdge); clearInterval(self.dragRightEdge)
clearInterval(self.dragTopEdge); clearInterval(self.dragTopEdge)
clearInterval(self.dragBottomEdge); clearInterval(self.dragBottomEdge)
self.virtualPointer = { x: pos.x, y: Util.pixelsToCoords(Visualize.mGraph, { x: xPix, y: height - EDGE_THICKNESS }).y + SHIFT } self.virtualPointer = { x: pos.x, y: Util.pixelsToCoords(Visualize.mGraph, { x: xPix, y: height - EDGE_THICKNESS }).y + SHIFT }
Visualize.mGraph.canvas.translate(0, -SHIFT); Visualize.mGraph.canvas.translate(0, -SHIFT)
self.updateTopicPositions(node, self.virtualPointer); self.updateTopicPositions(node, self.virtualPointer)
Visualize.mGraph.plot(); Visualize.mGraph.plot()
self.dragBottomEdge = setInterval(function() { self.dragBottomEdge = setInterval(function() {
self.virtualPointer = { x: pos.x, y: Util.pixelsToCoords(Visualize.mGraph, { x: xPix, y: height - EDGE_THICKNESS }).y + SHIFT } self.virtualPointer = { x: pos.x, y: Util.pixelsToCoords(Visualize.mGraph, { x: xPix, y: height - EDGE_THICKNESS }).y + SHIFT }
Visualize.mGraph.canvas.translate(0, -SHIFT); Visualize.mGraph.canvas.translate(0, -SHIFT)
self.updateTopicPositions(node, self.virtualPointer); self.updateTopicPositions(node, self.virtualPointer)
Visualize.mGraph.plot(); Visualize.mGraph.plot()
}, PERIOD) }, PERIOD)
} }
if (xPix >= EDGE_THICKNESS && width - xPix >= EDGE_THICKNESS && yPix >= EDGE_THICKNESS && height - yPix >= EDGE_THICKNESS) { if (xPix >= EDGE_THICKNESS && width - xPix >= EDGE_THICKNESS && yPix >= EDGE_THICKNESS && height - yPix >= EDGE_THICKNESS) {
clearInterval(self.dragLeftEdge); clearInterval(self.dragLeftEdge)
clearInterval(self.dragRightEdge); clearInterval(self.dragRightEdge)
clearInterval(self.dragTopEdge); clearInterval(self.dragTopEdge)
clearInterval(self.dragBottomEdge); clearInterval(self.dragBottomEdge)
self.updateTopicPositions(node,pos); self.updateTopicPositions(node, pos)
Visualize.mGraph.plot() Visualize.mGraph.plot()
} }
} } else if ((e.button === 2 || (e.button === 0 && e.altKey) || e.buttons === 2) && authorized) {
// if it's a right click or holding down alt, start synapse creation ->third option is for firefox // if it's a right click or holding down alt, start synapse creation ->third option is for firefox
else if ((e.button === 2 || (e.button === 0 && e.altKey) || e.buttons === 2) && authorized) {
if (JIT.tempInit === false) { if (JIT.tempInit === false) {
JIT.tempNode = node JIT.tempNode = node
JIT.tempInit = true JIT.tempInit = true
@ -913,11 +910,9 @@ const JIT = {
y: pos.y y: pos.y
} }
} }
} } else if ((e.button === 2 || (e.button === 0 && e.altKey) || e.buttons === 2) && Active.Topic) {
else if ((e.button === 2 || (e.button === 0 && e.altKey) || e.buttons === 2) && Active.Topic) {
GlobalUI.notifyUser('Cannot create in Topic view.') GlobalUI.notifyUser('Cannot create in Topic view.')
} } else if ((e.button === 2 || (e.button === 0 && e.altKey) || e.buttons === 2) && !authorized) {
else if ((e.button === 2 || (e.button === 0 && e.altKey) || e.buttons === 2) && !authorized) {
GlobalUI.notifyUser('Cannot edit this map.') GlobalUI.notifyUser('Cannot edit this map.')
} }
} }
@ -933,21 +928,23 @@ const JIT = {
Visualize.mGraph.plot() Visualize.mGraph.plot()
}, // onDragCancelHandler }, // onDragCancelHandler
onDragEndTopicHandler: function(node, eventInfo, e) { onDragEndTopicHandler: function(node, eventInfo, e) {
var self = JIT; const self = JIT
var midpoint = {}, pixelPos, mapping const midpoint = {}
let pixelPos
let mapping
clearInterval(self.dragLeftEdge); clearInterval(self.dragLeftEdge)
clearInterval(self.dragRightEdge); clearInterval(self.dragRightEdge)
clearInterval(self.dragTopEdge); clearInterval(self.dragTopEdge)
clearInterval(self.dragBottomEdge); clearInterval(self.dragBottomEdge)
delete self.dragLeftEdge; delete self.dragLeftEdge
delete self.dragRightEdge; delete self.dragRightEdge
delete self.dragTopEdge; delete self.dragTopEdge
delete self.dragBottomEdge; delete self.dragBottomEdge
self.dragFlag = 0; self.dragFlag = 0
self.dragTolerance = 0; self.dragTolerance = 0
if (JIT.tempInit && JIT.tempNode2 === null) { if (JIT.tempInit && JIT.tempNode2 === null) {
// this means you want to add a new topic, and then a synapse // this means you want to add a new topic, and then a synapse
@ -1047,35 +1044,35 @@ const JIT = {
} }
}, // canvasClickHandler }, // canvasClickHandler
updateTopicPositions: function(node, pos) { updateTopicPositions: function(node, pos) {
var len = Selected.Nodes.length; const len = Selected.Nodes.length
var topic;
// this is used to send nodes that are moving to // this is used to send nodes that are moving to
// other realtime collaborators on the same map // other realtime collaborators on the same map
var positionsToSend = {}; const positionsToSend = {}
// first define offset for each node // first define offset for each node
var xOffset = [] var xOffset = []
var yOffset = [] var yOffset = []
for (var i = 0; i < len; i += 1) { for (let i = 0; i < len; i += 1) {
var n = Selected.Nodes[i] const n = Selected.Nodes[i]
xOffset[i] = n.pos.getc().x - node.pos.getc().x xOffset[i] = n.pos.getc().x - node.pos.getc().x
yOffset[i] = n.pos.getc().y - node.pos.getc().y yOffset[i] = n.pos.getc().y - node.pos.getc().y
} // for } // for
for (var i = 0; i < len; i += 1) { for (let i = 0; i < len; i += 1) {
var n = Selected.Nodes[i] const n = Selected.Nodes[i]
var x = pos.x + xOffset[i] const x = pos.x + xOffset[i]
var y = pos.y + yOffset[i] const y = pos.y + yOffset[i]
if (n.pos.rho || n.pos.rho === 0) { if (n.pos.rho || n.pos.rho === 0) {
// this means we're in topic view // this means we're in topic view
var rho = Math.sqrt(x * x + y * y) const rho = Math.sqrt(x * x + y * y)
var theta = Math.atan2(y, x) const theta = Math.atan2(y, x)
n.pos.setp(theta, rho) n.pos.setp(theta, rho)
} else {
n.pos.setc(x, y)
} }
else n.pos.setc(x, y)
if (Active.Map) { if (Active.Map) {
topic = n.getData('topic') const topic = n.getData('topic')
// we use the topic ID not the node id // we use the topic ID not the node id
// because we can't depend on the node id // because we can't depend on the node id
// to be the same as on other collaborators // to be the same as on other collaborators
@ -1303,7 +1300,7 @@ const JIT = {
const self = JIT const self = JIT
// Copy topic title to clipboard // Copy topic title to clipboard
if(e.button===1 && e.ctrlKey) clipboard.copy(node.name); if (e.button === 1 && e.ctrlKey) clipboard.copy(node.name)
// catch right click on mac, which is often like ctrl+click // catch right click on mac, which is often like ctrl+click
if (navigator.platform.indexOf('Mac') !== -1 && e.ctrlKey) { if (navigator.platform.indexOf('Mac') !== -1 && e.ctrlKey) {
@ -1345,22 +1342,21 @@ const JIT = {
duration: 500 duration: 500
}) })
Visualize.mGraph.plot() Visualize.mGraph.plot()
} else { } else {
if (!e.ctrlKey) { if (!e.ctrlKey) {
var len = Selected.Nodes.length; var len = Selected.Nodes.length
for (let i = 0; i < len; i += 1) { for (let i = 0; i < len; i += 1) {
let n = Selected.Nodes[i]; let n = Selected.Nodes[i]
let result = Metamaps.Util.openLink(Metamaps.Topics.get(n.id).attributes.link); let result = Util.openLink(DataModel.Topics.get(n.id).attributes.link)
if (!result) { // if link failed to open if (!result) { // if link failed to open
break; break
} }
} }
if (!node.selected) { if (!node.selected) {
Metamaps.Util.openLink(Metamaps.Topics.get(node.id).attributes.link); Util.openLink(DataModel.Topics.get(node.id).attributes.link)
} }
} }
} }
@ -1589,9 +1585,9 @@ const JIT = {
if (Visualize.mGraph.busy) return if (Visualize.mGraph.busy) return
const self = JIT const self = JIT
var synapseText = adj.data.$synapses[0].attributes.desc; var synapseText = adj.data.$synapses[0].attributes.desc
// Copy synapse label to clipboard // Copy synapse label to clipboard
if(e.button===1 && e.ctrlKey && synapseText !== "") clipboard.copy(synapseText); if (e.button === 1 && e.ctrlKey && synapseText !== '') clipboard.copy(synapseText)
// catch right click on mac, which is often like ctrl+click // catch right click on mac, which is often like ctrl+click
if (navigator.platform.indexOf('Mac') !== -1 && e.ctrlKey) { if (navigator.platform.indexOf('Mac') !== -1 && e.ctrlKey) {

View file

@ -7,22 +7,22 @@ const CheatSheet = {
$('#quickReference').tabs().addClass('ui-tabs-vertical ui-helper-clearfix') $('#quickReference').tabs().addClass('ui-tabs-vertical ui-helper-clearfix')
$('#quickReference .ui-tabs-nav li').removeClass('ui-corner-top').addClass('ui-corner-left') $('#quickReference .ui-tabs-nav li').removeClass('ui-corner-top').addClass('ui-corner-left')
// id = the id of a vimeo video // // id = the id of a vimeo video
var switchVideo = function (element, id) { // var switchVideo = function(element, id) {
$('.tutorialItem').removeClass('active') // $('.tutorialItem').removeClass('active')
$(element).addClass('active') // $(element).addClass('active')
$('#tutorialVideo').attr('src', '//player.vimeo.com/video/' + id) // $('#tutorialVideo').attr('src', '//player.vimeo.com/video/' + id)
} // }
$('#gettingStarted').click(function () { // $('#gettingStarted').click(function() {
// switchVideo(this,'88334167') // switchVideo(this,'88334167')
}) // })
$('#upYourSkillz').click(function () { // $('#upYourSkillz').click(function() {
// switchVideo(this,'100118167') // switchVideo(this,'100118167')
}) // })
$('#advancedMapping').click(function () { // $('#advancedMapping').click(function() {
// switchVideo(this,'88334167') // switchVideo(this,'88334167')
}) // })
} }
} }

View file

@ -51,7 +51,7 @@ const InfoBox = {
self.userImageUrl = serverData['user.png'] self.userImageUrl = serverData['user.png']
var querystring = window.location.search.replace(/^\?/, '') var querystring = window.location.search.replace(/^\?/, '')
if (querystring == 'new') { if (querystring === 'new') {
self.open() self.open()
$('.mapInfoBox').addClass('mapRequestTitle') $('.mapInfoBox').addClass('mapRequestTitle')
$('#mapInfoName').trigger('click') $('#mapInfoName').trigger('click')
@ -206,27 +206,27 @@ const InfoBox = {
var collaborators = { var collaborators = {
name: 'collaborators', name: 'collaborators',
limit: 9999, limit: 9999,
display: function(s) { return s.label; }, display: function(s) { return s.label },
templates: { templates: {
notFound: function(s) { notFound: function(s) {
return Hogan.compile($('#collaboratorSearchTemplate').html()).render({ return Hogan.compile($('#collaboratorSearchTemplate').html()).render({
value: "No results", value: 'No results',
label: "No results", label: 'No results',
rtype: "noresult", rtype: 'noresult',
profile: self.userImageUrl profile: self.userImageUrl
}); })
}, },
suggestion: function(s) { suggestion: function(s) {
return Hogan.compile($('#collaboratorSearchTemplate').html()).render(s); return Hogan.compile($('#collaboratorSearchTemplate').html()).render(s)
}, }
}, },
source: new Bloodhound({ source: new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace, queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: { remote: {
url: '/search/mappers?term=%QUERY', url: '/search/mappers?term=%QUERY',
wildcard: '%QUERY', wildcard: '%QUERY'
}, }
}) })
} }
@ -234,7 +234,7 @@ const InfoBox = {
if (Active.Mapper && Active.Mapper.id === Active.Map.get('user_id')) { if (Active.Mapper && Active.Mapper.id === Active.Map.get('user_id')) {
$('.collaboratorSearchField').typeahead( $('.collaboratorSearchField').typeahead(
{ {
highlight: false, highlight: false
}, },
[collaborators] [collaborators]
) )
@ -283,7 +283,6 @@ const InfoBox = {
$('.mapInfoBox .mapPermission').removeClass('commons public private').addClass(perm) $('.mapInfoBox .mapPermission').removeClass('commons public private').addClass(perm)
}, },
createContributorList: function() { createContributorList: function() {
var self = InfoBox
var relevantPeople = Active.Map.get('permission') === 'commons' ? DataModel.Mappers : DataModel.Collaborators var relevantPeople = Active.Map.get('permission') === 'commons' ? DataModel.Mappers : DataModel.Collaborators
var activeMapperIsCreator = Active.Mapper && Active.Mapper.id === Active.Map.get('user_id') var activeMapperIsCreator = Active.Mapper && Active.Mapper.id === Active.Map.get('user_id')
var string = '' var string = ''
@ -308,20 +307,23 @@ const InfoBox = {
updateNumbers: function() { updateNumbers: function() {
if (!Active.Map) return if (!Active.Map) return
var self = InfoBox const self = InfoBox
var mapper = Active.Mapper
var relevantPeople = Active.Map.get('permission') === 'commons' ? DataModel.Mappers : DataModel.Collaborators var relevantPeople = Active.Map.get('permission') === 'commons' ? DataModel.Mappers : DataModel.Collaborators
var contributors_class = '' let contributorsClass = ''
if (relevantPeople.length === 2) contributors_class = 'multiple mTwo' if (relevantPeople.length === 2) {
else if (relevantPeople.length > 2) contributors_class = 'multiple' contributorsClass = 'multiple mTwo'
} else if (relevantPeople.length > 2) {
contributorsClass = 'multiple'
}
var contributors_image = self.userImageUrl let contributorsImage = self.userImageUrl
if (relevantPeople.length > 0) { if (relevantPeople.length > 0) {
// get the first contributor and use their image // get the first contributor and use their image
contributors_image = relevantPeople.models[0].get('image') contributorsImage = relevantPeople.models[0].get('image')
} }
$('.mapContributors img').attr('src', contributors_image).removeClass('multiple mTwo').addClass(contributors_class) $('.mapContributors img').attr('src', contributorsImage).removeClass('multiple mTwo').addClass(contributorsClass)
$('.mapContributors span').text(relevantPeople.length) $('.mapContributors span').text(relevantPeople.length)
$('.mapContributors .tip').html(self.createContributorList()) $('.mapContributors .tip').html(self.createContributorList())
self.addTypeahead() self.addTypeahead()
@ -390,8 +392,7 @@ const InfoBox = {
map.destroy() map.destroy()
Router.home() Router.home()
GlobalUI.notifyUser('Map eliminated!') GlobalUI.notifyUser('Map eliminated!')
} } else if (!authorized) {
else if (!authorized) {
window.alert("Hey now. We can't just go around willy nilly deleting other people's maps now can we? Run off and find something constructive to do, eh?") window.alert("Hey now. We can't just go around willy nilly deleting other people's maps now can we? Run off and find something constructive to do, eh?")
} }
} }

View file

@ -1,6 +1,7 @@
/* global $ */ /* global $ */
import outdent from 'outdent' import outdent from 'outdent'
import { find as _find } from 'lodash'
import Active from '../Active' import Active from '../Active'
import AutoLayout from '../AutoLayout' import AutoLayout from '../AutoLayout'
@ -29,8 +30,8 @@ const Map = {
var self = Map var self = Map
$('#wrapper').mousedown(function(e) { $('#wrapper').mousedown(function(e) {
if(e.button === 1)return false; if (e.button === 1) return false
}); })
$('.starMap').click(function() { $('.starMap').click(function() {
if ($(this).is('.starred')) self.unstar() if ($(this).is('.starred')) self.unstar()
@ -62,7 +63,7 @@ const Map = {
setAccessRequest: function(requests, activeMapper) { setAccessRequest: function(requests, activeMapper) {
let className = 'isViewOnly ' let className = 'isViewOnly '
if (activeMapper) { if (activeMapper) {
const request = _.find(requests, r => r.user_id === activeMapper.id) const request = _find(requests, r => r.user_id === activeMapper.id)
if (!request) className += 'sendRequest' if (!request) className += 'sendRequest'
else if (request && !request.answered) className += 'sentRequest' else if (request && !request.answered) className += 'sentRequest'
else if (request && request.answered && !request.approved) className += 'requestDenied' else if (request && request.answered && !request.approved) className += 'requestDenied'
@ -89,8 +90,7 @@ const Map = {
// add class to .wrapper for specifying whether you can edit the map // add class to .wrapper for specifying whether you can edit the map
if (map.authorizeToEdit(mapper)) { if (map.authorizeToEdit(mapper)) {
$('.wrapper').addClass('canEditMap') $('.wrapper').addClass('canEditMap')
} } else {
else {
Map.setAccessRequest(data.requests, mapper) Map.setAccessRequest(data.requests, mapper)
} }
@ -177,32 +177,32 @@ const Map = {
if (!Active.Map) return if (!Active.Map) return
$.post('/maps/' + Active.Map.id + '/unstar') $.post('/maps/' + Active.Map.id + '/unstar')
DataModel.Stars = DataModel.Stars.filter(function (s) { return s.user_id != Active.Mapper.id }) DataModel.Stars = DataModel.Stars.filter(function(s) { return s.user_id !== Active.Mapper.id })
DataModel.Maps.Starred.remove(Active.Map) DataModel.Maps.Starred.remove(Active.Map)
self.updateStar() self.updateStar()
}, },
fork: function() { fork: function() {
GlobalUI.openLightbox('forkmap') GlobalUI.openLightbox('forkmap')
var nodes_data = '', let nodesData = ''
synapses_data = '' let synapsesData = ''
var nodes_array = [] let nodesArray = []
var synapses_array = [] let synapsesArray = []
// collect the unfiltered topics // collect the unfiltered topics
Visualize.mGraph.graph.eachNode(function(n) { 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
nodes_array.push(id) nodesArray.push(id)
var x, y let x, y
if (n.pos.x && n.pos.y) { if (n.pos.x && n.pos.y) {
x = n.pos.x x = n.pos.x
y = n.pos.y y = n.pos.y
} else { } else {
var x = Math.cos(n.pos.theta) * n.pos.rho x = Math.cos(n.pos.theta) * n.pos.rho
var y = Math.sin(n.pos.theta) * n.pos.rho y = Math.sin(n.pos.theta) * n.pos.rho
} }
nodes_data += id + '/' + x + '/' + y + ',' nodesData += id + '/' + x + '/' + y + ','
} }
}) })
// collect the unfiltered synapses // collect the unfiltered synapses
@ -212,18 +212,18 @@ const Map = {
var descNotFiltered = Filter.visible.synapses.indexOf(desc) > -1 var descNotFiltered = 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 = nodes_array.indexOf(synapse.get('topic1_id')) > -1 var topicsNotFiltered = nodesArray.indexOf(synapse.get('topic1_id')) > -1
topicsNotFiltered = topicsNotFiltered && nodes_array.indexOf(synapse.get('topic2_id')) > -1 topicsNotFiltered = topicsNotFiltered && nodesArray.indexOf(synapse.get('topic2_id')) > -1
if (descNotFiltered && topicsNotFiltered) { if (descNotFiltered && topicsNotFiltered) {
synapses_array.push(synapse.id) synapsesArray.push(synapse.id)
} }
}) })
synapses_data = synapses_array.join() synapsesData = synapsesArray.join()
nodes_data = nodes_data.slice(0, -1) nodesData = nodesData.slice(0, -1)
GlobalUI.CreateMap.topicsToMap = nodes_data GlobalUI.CreateMap.topicsToMap = nodesData
GlobalUI.CreateMap.synapsesToMap = synapses_data GlobalUI.CreateMap.synapsesToMap = synapsesData
}, },
leavePrivateMap: function() { leavePrivateMap: function() {
var map = Active.Map var map = Active.Map
@ -233,7 +233,7 @@ const Map = {
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' 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') Active.Map.trigger('changeByOther')
}, },
@ -273,18 +273,18 @@ const Map = {
return this.size return this.size
} }
canvas.scale = function(x, y) { canvas.scale = function(x, y) {
var px = this.scaleOffsetX * x, const px = this.scaleOffsetX * x
py = this.scaleOffsetY * y const py = this.scaleOffsetY * y
var dx = this.translateOffsetX * (x - 1) / px, const dx = this.translateOffsetX * (x - 1) / px
dy = this.translateOffsetY * (y - 1) / py const dy = this.translateOffsetY * (y - 1) / py
this.scaleOffsetX = px this.scaleOffsetX = px
this.scaleOffsetY = py this.scaleOffsetY = py
this.getCtx().scale(x, y) this.getCtx().scale(x, y)
this.translate(dx, dy) this.translate(dx, dy)
} }
canvas.translate = function(x, y) { canvas.translate = function(x, y) {
var sx = this.scaleOffsetX, const sx = this.scaleOffsetX
sy = this.scaleOffsetY const sy = this.scaleOffsetY
this.translateOffsetX += x * sx this.translateOffsetX += x * sx
this.translateOffsetY += y * sy this.translateOffsetY += y * sy
this.getCtx().translate(x, y) this.getCtx().translate(x, y)
@ -304,14 +304,14 @@ const Map = {
// pass true to avoid basing it on a selection // pass true to avoid basing it on a selection
JIT.zoomExtents(null, canvas, true) JIT.zoomExtents(null, canvas, true)
var c = canvas.canvas, const c = canvas.canvas
ctx = canvas.getCtx(), const ctx = canvas.getCtx()
scale = canvas.scaleOffsetX const scale = canvas.scaleOffsetX
// draw a grey background // draw a grey background
ctx.fillStyle = '#d8d9da' ctx.fillStyle = '#d8d9da'
var xPoint = (-(c.width / scale) / 2) - (canvas.translateOffsetX / scale), const xPoint = (-(c.width / scale) / 2) - (canvas.translateOffsetX / scale)
yPoint = (-(c.height / scale) / 2) - (canvas.translateOffsetY / scale) const yPoint = (-(c.height / scale) / 2) - (canvas.translateOffsetY / scale)
ctx.fillRect(xPoint, yPoint, c.width / scale, c.height / scale) ctx.fillRect(xPoint, yPoint, c.width / scale, c.height / scale)
// draw the graph // draw the graph
@ -340,7 +340,7 @@ const Map = {
var today = new Date() var today = new Date()
var dd = today.getDate() var dd = today.getDate()
var mm = today.getMonth() + 1; // January is 0! var mm = today.getMonth() + 1 // January is 0!
var yyyy = today.getFullYear() var yyyy = today.getFullYear()
if (dd < 10) { if (dd < 10) {
dd = '0' + dd dd = '0' + dd
@ -359,7 +359,7 @@ const Map = {
GlobalUI.notifyUser(downloadMessage) GlobalUI.notifyUser(downloadMessage)
canvas.canvas.toBlob(imageBlob => { canvas.canvas.toBlob(imageBlob => {
const formData = new window.FormData(); const formData = new window.FormData()
formData.append('map[screenshot]', imageBlob, filename) formData.append('map[screenshot]', imageBlob, filename)
$.ajax({ $.ajax({
type: 'PATCH', type: 'PATCH',

View file

@ -8,14 +8,14 @@ import JIT from './JIT'
const Organize = { const Organize = {
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') {
var numNodes = _.size(Visualize.mGraph.graph.nodes); // this will always be an integer, the # of nodes on your graph visualization const numNodes = _.size(Visualize.mGraph.graph.nodes) // this will always be an integer, the # of nodes on your graph visualization
var 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
var GRIDSPACE = 400 const GRIDSPACE = 400
var row = 0 let row = 0
var column = 0 let column = 0
Visualize.mGraph.graph.eachNode(function(n) { Visualize.mGraph.graph.eachNode(function(n) {
if (column == numColumns) { if (column === numColumns) {
column = 0 column = 0
row += 1 row += 1
} }
@ -26,25 +26,25 @@ const Organize = {
column += 1 column += 1
}) })
Visualize.mGraph.animate(JIT.ForceDirected.animateSavedLayout) Visualize.mGraph.animate(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
var numNodes = _.size(Visualize.mGraph.graph.nodes) const numNodes = _.size(Visualize.mGraph.graph.nodes)
// var 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
// var GRIDSPACE = 400 const height = Visualize.mGraph.canvas.getSize(0).height
var height = Visualize.mGraph.canvas.getSize(0).height const width = Visualize.mGraph.canvas.getSize(0).width
var width = Visualize.mGraph.canvas.getSize(0).width const totalArea = height * width
var totalArea = height * width const cellArea = totalArea / numNodes
var cellArea = totalArea / numNodes const ratio = height / width
var ratio = height / width const cellWidth = Math.sqrt(cellArea / ratio)
var cellWidth = sqrt(cellArea / ratio) const cellHeight = cellArea / cellWidth
var cellHeight = cellArea / cellWidth const GRIDSPACE = 400
var row = floor(height / cellHeight) let row = Math.floor(height / cellHeight)
var column = floor(width / cellWidth) let column = Math.floor(width / cellWidth)
var totalCells = row * column const totalCells = row * column
if (totalCells) { if (totalCells) {
Visualize.mGraph.graph.eachNode(function(n) { Visualize.mGraph.graph.eachNode(function(n) {
if (column == numColumns) { if (column === numColumns) {
column = 0 column = 0
row += 1 row += 1
} }
@ -56,7 +56,7 @@ const Organize = {
}) })
} }
Visualize.mGraph.animate(JIT.ForceDirected.animateSavedLayout) Visualize.mGraph.animate(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
centerNode.setPos(centerNode.getPos(), 'end') centerNode.setPos(centerNode.getPos(), 'end')
@ -66,15 +66,15 @@ const Organize = {
var usedNodes = {} var usedNodes = {}
usedNodes[centerNode.id] = centerNode usedNodes[centerNode.id] = centerNode
var radial = function(node, level, degree) { var radial = function(node, level, degree) {
if (level == 1) { if (level === 1) {
var numLinksTemp = _.size(node.adjacencies) var numLinksTemp = _.size(node.adjacencies)
var angleTemp = 2 * Math.PI / numLinksTemp var angleTemp = 2 * Math.PI / numLinksTemp
} else { } else {
angleTemp = 2 * Math.PI / 20 angleTemp = 2 * Math.PI / 20
} }
node.eachAdjacency(function(a) { node.eachAdjacency(function(a) {
var isSecondLevelNode = (centerNode.adjacencies[a.nodeTo.id] != undefined && level > 1) var isSecondLevelNode = (centerNode.adjacencies[a.nodeTo.id] !== undefined && level > 1)
if (usedNodes[a.nodeTo.id] == undefined && !isSecondLevelNode) { if (usedNodes[a.nodeTo.id] === undefined && !isSecondLevelNode) {
var newPos = new $jit.Complex() var newPos = new $jit.Complex()
newPos.x = level * lineLength * Math.sin(degree) + centerX newPos.x = level * lineLength * Math.sin(degree) + centerX
newPos.y = level * lineLength * Math.cos(degree) + centerY newPos.y = level * lineLength * Math.cos(degree) + centerY
@ -88,13 +88,11 @@ const Organize = {
} }
radial(centerNode, 1, 0) radial(centerNode, 1, 0)
Visualize.mGraph.animate(JIT.ForceDirected.animateSavedLayout) Visualize.mGraph.animate(JIT.ForceDirected.animateSavedLayout)
} else if (layout == 'center_viewport') { } else if (layout === 'center_viewport') {
var lowX = 0, let lowX = 0
lowY = 0, let lowY = 0
highX = 0, let highX = 0
highY = 0 let highY = 0
var oldOriginX = Visualize.mGraph.canvas.translateOffsetX
var oldOriginY = Visualize.mGraph.canvas.translateOffsetY
Visualize.mGraph.graph.eachNode(function(n) { Visualize.mGraph.graph.eachNode(function(n) {
if (n.id === 1) { if (n.id === 1) {
@ -109,9 +107,9 @@ const Organize = {
if (n.getPos().y > highY) highY = n.getPos().y if (n.getPos().y > highY) highY = n.getPos().y
}) })
console.log(lowX, lowY, highX, highY) console.log(lowX, lowY, highX, highY)
var newOriginX = (lowX + highX) / 2 } else {
var newOriginY = (lowY + highY) / 2 window.alert('please call function with a valid layout dammit!')
} else window.alert('please call function with a valid layout dammit!') }
} }
} }

View file

@ -13,13 +13,13 @@ const PasteInput = {
// intercept dragged files // intercept dragged files
// see http://stackoverflow.com/questions/6756583 // see http://stackoverflow.com/questions/6756583
window.addEventListener("dragover", function(e) { window.addEventListener('dragover', function(e) {
e = e || window.event; e = e || window.event
e.preventDefault(); e.preventDefault()
}, false); }, false)
window.addEventListener("drop", function(e) { window.addEventListener('drop', function(e) {
e = e || window.event; e = e || window.event
e.preventDefault(); e.preventDefault()
var coords = Util.pixelsToCoords(Visualize.mGraph, { x: e.clientX, y: e.clientY }) var coords = Util.pixelsToCoords(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)
@ -32,7 +32,7 @@ const PasteInput = {
} }
}) })
} }
}, false); }, false)
// allow pasting onto canvas (but don't break existing inputs/textareas) // allow pasting onto canvas (but don't break existing inputs/textareas)
$('body').bind('paste', function(e) { $('body').bind('paste', function(e) {

View file

@ -1,15 +1,11 @@
/* global $ */ /* global $ */
import _ from 'lodash'
import SimpleWebRTC from 'simplewebrtc' import SimpleWebRTC from 'simplewebrtc'
import SocketIoConnection from 'simplewebrtc/socketioconnection' import SocketIoConnection from 'simplewebrtc/socketioconnection'
import Active from '../Active' import Active from '../Active'
import DataModel from '../DataModel' import DataModel from '../DataModel'
import GlobalUI from '../GlobalUI'
import JIT from '../JIT' import JIT from '../JIT'
import Synapse from '../Synapse'
import Topic from '../Topic'
import Util from '../Util' import Util from '../Util'
import Views from '../Views' import Views from '../Views'
import Visualize from '../Visualize' import Visualize from '../Visualize'
@ -67,7 +63,7 @@ import {
synapseUpdated, synapseUpdated,
synapseRemoved, synapseRemoved,
synapseDeleted, synapseDeleted,
mapUpdated, mapUpdated
} from './receivable' } from './receivable'
import { import {
@ -348,13 +344,12 @@ let Realtime = {
positionVideos: function() { positionVideos: function() {
var self = Realtime var self = Realtime
var videoIds = Object.keys(self.room.videos) var videoIds = Object.keys(self.room.videos)
var numOfVideos = videoIds.length // var numOfVideos = videoIds.length
var numOfVideosToPosition = _.filter(videoIds, function (id) { // var numOfVideosToPosition = _.filter(videoIds, function(id) {
return !self.room.videos[id].manuallyPositioned // return !self.room.videos[id].manuallyPositioned
}).length // }).length
var screenHeight = $(document).height() var screenHeight = $(document).height()
var screenWidth = $(document).width()
var topExtraPadding = 20 var topExtraPadding = 20
var topPadding = 30 var topPadding = 30
var leftPadding = 30 var leftPadding = 30
@ -431,12 +426,7 @@ let Realtime = {
}, },
positionPeerIcon: function(id) { positionPeerIcon: function(id) {
var self = Realtime var self = Realtime
var boundary = self.chatOpen ? '#wrapper' : document
var mapper = self.mappersOnMap[id] var mapper = self.mappersOnMap[id]
var xMax = $(boundary).width()
var yMax = $(boundary).height()
var compassDiameter = 56
var compassArrowSize = 24
var origPixels = Util.coordsToPixels(Visualize.mGraph, mapper.coords) var origPixels = Util.coordsToPixels(Visualize.mGraph, mapper.coords)
var pixels = self.limitPixelsToScreen(origPixels) var pixels = self.limitPixelsToScreen(origPixels)
@ -448,12 +438,11 @@ let Realtime = {
if (origPixels.x !== pixels.x || origPixels.y !== pixels.y) { if (origPixels.x !== pixels.x || origPixels.y !== pixels.y) {
var dy = origPixels.y - pixels.y // opposite var dy = origPixels.y - pixels.y // opposite
var dx = origPixels.x - pixels.x // adjacent var dx = origPixels.x - pixels.x // adjacent
var ratio = dy / dx
var angle = Math.atan2(dy, dx) var angle = Math.atan2(dy, dx)
$('#compassArrow' + id).show().css({ $('#compassArrow' + id).show().css({
transform: 'rotate(' + angle + 'rad)', transform: 'rotate(' + angle + 'rad)',
'-webkit-transform': 'rotate(' + angle + 'rad)', '-webkit-transform': 'rotate(' + angle + 'rad)'
}) })
if (dx > 0) { if (dx > 0) {

View file

@ -4,6 +4,8 @@
everthing in this file happens as a result of websocket events everthing in this file happens as a result of websocket events
*/ */
import { indexOf } from 'lodash'
import { JUNTO_UPDATED } from './events' import { JUNTO_UPDATED } from './events'
import Active from '../Active' import Active from '../Active'
@ -31,7 +33,7 @@ export const synapseRemoved = self => data => {
Control.hideEdge(edge) Control.hideEdge(edge)
} }
var index = _.indexOf(edge.getData('synapses'), synapse) var index = indexOf(edge.getData('synapses'), 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)
if (edge.getData('displayIndex')) { if (edge.getData('displayIndex')) {
@ -49,7 +51,6 @@ export const synapseDeleted = self => data => {
export const synapseCreated = self => data => { export const synapseCreated = self => data => {
var topic1, topic2, node1, node2, synapse, mapping, cancel, mapper var topic1, topic2, node1, node2, synapse, mapping, cancel, mapper
function waitThenRenderSynapse() { function waitThenRenderSynapse() {
if (synapse && mapping && mapper) { if (synapse && mapping && mapper) {
topic1 = synapse.getTopic1() topic1 = synapse.getTopic1()
@ -58,8 +59,7 @@ export const synapseCreated = self => data => {
node2 = topic2.get('node') node2 = topic2.get('node')
Synapse.renderSynapse(mapping, synapse, node1, node2, false) Synapse.renderSynapse(mapping, synapse, node1, node2, false)
} } else if (!cancel) {
else if (!cancel) {
setTimeout(waitThenRenderSynapse, 10) setTimeout(waitThenRenderSynapse, 10)
} }
} }
@ -115,8 +115,7 @@ export const topicCreated = self => data => {
function waitThenRenderTopic() { function waitThenRenderTopic() {
if (topic && mapping && mapper) { if (topic && mapping && mapper) {
Topic.renderTopic(mapping, topic, false, false) Topic.renderTopic(mapping, topic, false, false)
} } else if (!cancel) {
else if (!cancel) {
setTimeout(waitThenRenderTopic, 10) setTimeout(waitThenRenderTopic, 10)
} }
} }
@ -168,11 +167,9 @@ export const mapUpdated = self => data => {
var canEditNow = model.authorizeToEdit(Active.Mapper) var canEditNow = model.authorizeToEdit(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) {
Map.cantEditNow() Map.cantEditNow()
} } else if (!couldEditBefore && canEditNow) {
else if (!couldEditBefore && canEditNow) {
Map.canEditNow() Map.canEditNow()
} else { } else {
model.trigger('changeByOther') model.trigger('changeByOther')
@ -311,7 +308,7 @@ export const newMapper = self => data => {
} }
export const callAccepted = self => userid => { export const callAccepted = self => userid => {
var username = self.mappersOnMap[userid].name // const username = self.mappersOnMap[userid].name
GlobalUI.notifyUser('Conversation starting...') GlobalUI.notifyUser('Conversation starting...')
self.joinCall() self.joinCall()
self.room.chat.invitationAnswered(userid) self.room.chat.invitationAnswered(userid)

View file

@ -1,3 +1,5 @@
/* global $ */
import Active from '../Active' import Active from '../Active'
import GlobalUI from '../GlobalUI' import GlobalUI from '../GlobalUI'

View file

@ -93,7 +93,7 @@ const _Router = Backbone.Router.extend({
document.title = 'Explore My Maps | Metamaps' document.title = 'Explore My Maps | Metamaps'
} }
if (Active.Mapper && section != 'mapper') $('.homeButton a').attr('href', '/explore/' + section) if (Active.Mapper && section !== 'mapper') $('.homeButton a').attr('href', '/explore/' + section)
$('.wrapper').removeClass('homePage mapPage topicPage') $('.wrapper').removeClass('homePage mapPage topicPage')
$('.wrapper').addClass('explorePage') $('.wrapper').addClass('explorePage')

View file

@ -17,7 +17,7 @@ const Synapse = {
// @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 (DataModel.Synapses.get(id) === undefined) {
$.ajax({ $.ajax({
url: '/synapses/' + id + '.json', url: '/synapses/' + id + '.json',
success: function(data) { success: function(data) {
@ -29,8 +29,6 @@ const Synapse = {
}, },
renderSynapse: function(mapping, synapse, node1, node2, createNewInDB) { renderSynapse: function(mapping, synapse, node1, node2, createNewInDB) {
var self = Synapse
var edgeOnViz var edgeOnViz
var newedge = synapse.createEdge(mapping) var newedge = synapse.createEdge(mapping)
@ -74,13 +72,13 @@ const Synapse = {
} }
}, },
createSynapseLocally: function() { createSynapseLocally: function() {
var self = Synapse, var self = Synapse
topic1, let topic1
topic2, let topic2
node1, let node1
node2, let node2
synapse, let synapse
mapping let mapping
$(document).trigger(Map.events.editedByActiveMapper) $(document).trigger(Map.events.editedByActiveMapper)
@ -91,7 +89,7 @@ const Synapse = {
node2 = topic2.get('node') node2 = topic2.get('node')
var len = Selected.Nodes.length var len = Selected.Nodes.length
if (len == 0) { if (len === 0) {
topic1 = DataModel.Topics.get(Create.newSynapse.topic1id) topic1 = DataModel.Topics.get(Create.newSynapse.topic1id)
synapsesToCreate[0] = topic1.get('node') synapsesToCreate[0] = topic1.get('node')
} else if (len > 0) { } else if (len > 0) {
@ -104,13 +102,13 @@ const Synapse = {
synapse = new DataModel.Synapse({ synapse = new DataModel.Synapse({
desc: Create.newSynapse.description, desc: 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) 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) DataModel.Mappings.add(mapping)
@ -121,22 +119,18 @@ const Synapse = {
Create.newSynapse.hide() Create.newSynapse.hide()
}, },
getSynapseFromAutocomplete: function(id) { getSynapseFromAutocomplete: function(id) {
var self = Synapse, var self = Synapse
topic1,
topic2,
node1,
node2
self.get(id, synapse => { self.get(id, synapse => {
var mapping = new DataModel.Mapping({ const mapping = new DataModel.Mapping({
mappable_type: 'Synapse', mappable_type: 'Synapse',
mappable_id: synapse.id, mappable_id: synapse.id
}) })
DataModel.Mappings.add(mapping) DataModel.Mappings.add(mapping)
topic1 = DataModel.Topics.get(Create.newSynapse.topic1id) const topic1 = DataModel.Topics.get(Create.newSynapse.topic1id)
node1 = topic1.get('node') const node1 = topic1.get('node')
topic2 = DataModel.Topics.get(Create.newSynapse.topic2id) const topic2 = DataModel.Topics.get(Create.newSynapse.topic2id)
node2 = topic2.get('node') const node2 = topic2.get('node')
Create.newSynapse.hide() Create.newSynapse.hide()
self.renderSynapse(mapping, synapse, node1, node2, true) self.renderSynapse(mapping, synapse, node1, node2, true)
}) })

View file

@ -18,20 +18,20 @@ const SynapseCard = {
Control.deselectEdge(edge) 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
// create the wrapper around the form elements, including permissions // create the wrapper around the form elements, including permissions
// classes to make best_in_place happy // classes to make best_in_place happy
var edit_div = document.createElement('div') var editDiv = document.createElement('div')
edit_div.innerHTML = '<div id="editSynUpperBar"></div><div id="editSynLowerBar"></div>' editDiv.innerHTML = '<div id="editSynUpperBar"></div><div id="editSynLowerBar"></div>'
edit_div.setAttribute('id', 'edit_synapse') editDiv.setAttribute('id', 'edit_synapse')
if (synapse.authorizeToEdit(Active.Mapper)) { if (synapse.authorizeToEdit(Active.Mapper)) {
edit_div.className = 'permission canEdit' editDiv.className = 'permission canEdit'
edit_div.className += synapse.authorizePermissionChange(Active.Mapper) ? ' yourEdge' : '' editDiv.className += synapse.authorizePermissionChange(Active.Mapper) ? ' yourEdge' : ''
} else { } else {
edit_div.className = 'permission cannotEdit' editDiv.className = 'permission cannotEdit'
} }
$('#wrapper').append(edit_div) $('#wrapper').append(editDiv)
self.populateShowCard(edge, synapse) self.populateShowCard(edge, synapse)
@ -72,7 +72,7 @@ const SynapseCard = {
$('#editSynUpperBar').append('<div id="synapseCardCount">' + count + '</div>') $('#editSynUpperBar').append('<div id="synapseCardCount">' + count + '</div>')
}, },
add_desc_form: function(synapse) { add_desc_form: function(synapse) {
var data_nil = 'Click to add description.' var dataNil = 'Click to add description.'
// TODO make it so that this would work even in sandbox mode, // TODO make it so that this would work even in sandbox mode,
// currently with Best_in_place it won't // currently with Best_in_place it won't
@ -83,15 +83,15 @@ const SynapseCard = {
$('#edit_synapse_desc').attr('data-bip-object', 'synapse') $('#edit_synapse_desc').attr('data-bip-object', 'synapse')
$('#edit_synapse_desc').attr('data-bip-attribute', 'desc') $('#edit_synapse_desc').attr('data-bip-attribute', 'desc')
$('#edit_synapse_desc').attr('data-bip-type', 'textarea') $('#edit_synapse_desc').attr('data-bip-type', 'textarea')
$('#edit_synapse_desc').attr('data-bip-nil', data_nil) $('#edit_synapse_desc').attr('data-bip-nil', dataNil)
$('#edit_synapse_desc').attr('data-bip-url', '/synapses/' + synapse.id) $('#edit_synapse_desc').attr('data-bip-url', '/synapses/' + synapse.id)
$('#edit_synapse_desc').attr('data-bip-value', synapse.get('desc')) $('#edit_synapse_desc').attr('data-bip-value', synapse.get('desc'))
$('#edit_synapse_desc').html(synapse.get('desc')) $('#edit_synapse_desc').html(synapse.get('desc'))
// if edge data is blank or just whitespace, populate it with data_nil // 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(Active.Mapper)) {
$('#edit_synapse_desc').html(data_nil) $('#edit_synapse_desc').html(dataNil)
} else { } else {
$('#edit_synapse_desc').html('(no description)') $('#edit_synapse_desc').html('(no description)')
} }
@ -105,7 +105,7 @@ const SynapseCard = {
}) })
$('#edit_synapse_desc').bind('ajax:success', function() { $('#edit_synapse_desc').bind('ajax:success', function() {
var desc = $(this).html() var desc = $(this).html()
if (desc == data_nil) { if (desc === dataNil) {
synapse.set('desc', '') synapse.set('desc', '')
} else { } else {
synapse.set('desc', desc) synapse.set('desc', desc)
@ -227,14 +227,16 @@ const SynapseCard = {
// determine which node is to the left and the right // determine which node is to the left and the right
// if directly in a line, top is left // if directly in a line, top is left
let left
let right
if (edge.nodeFrom.pos.x < edge.nodeTo.pos.x || if (edge.nodeFrom.pos.x < edge.nodeTo.pos.x ||
edge.nodeFrom.pos.x == edge.nodeTo.pos.x && edge.nodeFrom.pos.x === edge.nodeTo.pos.x &&
edge.nodeFrom.pos.y < edge.nodeTo.pos.y) { edge.nodeFrom.pos.y < edge.nodeTo.pos.y) {
var left = edge.nodeTo.getData('topic') left = edge.nodeTo.getData('topic')
var right = edge.nodeFrom.getData('topic') right = edge.nodeFrom.getData('topic')
} else { } else {
var left = edge.nodeFrom.getData('topic') left = edge.nodeFrom.getData('topic')
var right = edge.nodeTo.getData('topic') right = edge.nodeTo.getData('topic')
} }
/* /*
@ -243,17 +245,17 @@ const SynapseCard = {
* Else check the 'left' checkbox since the arrow is incoming. * Else check the 'left' checkbox since the arrow is incoming.
*/ */
var directionCat = synapse.get('category'); // both, none, from-to var directionCat = synapse.get('category') // both, none, from-to
if (directionCat == 'from-to') { if (directionCat === 'from-to') {
var from_to = [synapse.get('topic1_id'), synapse.get('topic2_id')] var fromTo = [synapse.get('topic1_id'), synapse.get('topic2_id')]
if (from_to[0] == left.id) { if (fromTo[0] === left.id) {
// check left checkbox // check left checkbox
$('#edit_synapse_left').addClass('checked') $('#edit_synapse_left').addClass('checked')
} else { } else {
// check right checkbox // check right checkbox
$('#edit_synapse_right').addClass('checked') $('#edit_synapse_right').addClass('checked')
} }
} else if (directionCat == 'both') { } else if (directionCat === 'both') {
// check both checkboxes // check both checkboxes
$('#edit_synapse_left').addClass('checked') $('#edit_synapse_left').addClass('checked')
$('#edit_synapse_right').addClass('checked') $('#edit_synapse_right').addClass('checked')

View file

@ -25,7 +25,7 @@ const Topic = {
// @param id = the id of the topic to retrieve // @param id = the id of the topic 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.Topics.get(id) == undefined) { if (DataModel.Topics.get(id) === undefined) {
$.ajax({ $.ajax({
url: '/topics/' + id + '.json', url: '/topics/' + id + '.json',
success: function(data) { success: function(data) {
@ -94,20 +94,20 @@ const Topic = {
Active.Topic = DataModel.Topics.get(nodeid) Active.Topic = DataModel.Topics.get(nodeid)
} }
}, },
fetchRelatives: function (nodes, metacode_id) { fetchRelatives: function(nodes, metacodeId) {
var self = this var self = this
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 = DataModel.Topics.map(function(t) { return t.id })
var topics_string = topics.join() var topicsString = topics.join()
var creators = DataModel.Creators.map(function(t) { return t.id }) var creators = DataModel.Creators.map(function(t) { return t.id })
var creators_string = 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 (Visualize.mGraph.busy) {
// don't clash with centerOn // don't clash with centerOn
@ -150,12 +150,12 @@ const Topic = {
}) })
}) })
if ($.isArray(nodes) && nodes.length > 1) { if ($.isArray(nodes) && nodes.length > 1) {
self.fetchRelatives(nodes.slice(1), metacode_id) self.fetchRelatives(nodes.slice(1), metacodeId)
} }
} }
var paramsString = metacode_id ? 'metacode=' + metacode_id + '&' : '' let paramsString = metacodeId ? 'metacode=' + metacodeId + '&' : ''
paramsString += 'network=' + topics_string + '&creators=' + creators_string paramsString += 'network=' + topicsString + '&creators=' + creatorsString
$.ajax({ $.ajax({
type: 'GET', type: 'GET',
@ -168,13 +168,12 @@ const Topic = {
// opts is additional options in a hash // opts is additional options in a hash
// TODO: move createNewInDB and permitCreateSynapseAfter into opts // TODO: move createNewInDB and permitCreateSynapseAfter into opts
renderTopic: function(mapping, topic, createNewInDB, permitCreateSynapseAfter, opts = {}) { renderTopic: function(mapping, topic, createNewInDB, permitCreateSynapseAfter, opts = {}) {
var self = Topic
var nodeOnViz, tempPos var nodeOnViz, tempPos
var newnode = topic.createNode() var newnode = topic.createNode()
var midpoint = {}, pixelPos var midpoint = {}
var pixelPos
if (!$.isEmptyObject(Visualize.mGraph.graph.nodes)) { if (!$.isEmptyObject(Visualize.mGraph.graph.nodes)) {
Visualize.mGraph.graph.addNode(newnode) Visualize.mGraph.graph.addNode(newnode)
@ -315,7 +314,7 @@ const Topic = {
xloc: nextCoords ? nextCoords.x : Create.newTopic.x, xloc: nextCoords ? nextCoords.x : Create.newTopic.x,
yloc: nextCoords ? nextCoords.y : Create.newTopic.y, yloc: nextCoords ? nextCoords.y : Create.newTopic.y,
mappable_id: topic.cid, mappable_id: topic.cid,
mappable_type: 'Topic', mappable_type: 'Topic'
}) })
DataModel.Mappings.add(mapping) DataModel.Mappings.add(mapping)
@ -344,7 +343,7 @@ const Topic = {
xloc: nextCoords ? nextCoords.x : Create.newTopic.x, xloc: nextCoords ? nextCoords.x : Create.newTopic.x,
yloc: nextCoords ? nextCoords.y : Create.newTopic.y, yloc: nextCoords ? nextCoords.y : Create.newTopic.y,
mappable_type: 'Topic', mappable_type: 'Topic',
mappable_id: topic.id, mappable_id: topic.id
}) })
DataModel.Mappings.add(mapping) DataModel.Mappings.add(mapping)
@ -371,7 +370,7 @@ const Topic = {
xloc: Create.newTopic.x, xloc: Create.newTopic.x,
yloc: Create.newTopic.y, yloc: Create.newTopic.y,
mappable_id: topic.cid, mappable_id: topic.cid,
mappable_type: 'Topic', mappable_type: 'Topic'
}) })
DataModel.Mappings.add(mapping) DataModel.Mappings.add(mapping)
@ -394,7 +393,7 @@ const Topic = {
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) DataModel.Mappings.add(mapping)
self.renderTopic(mapping, topic, true, true) self.renderTopic(mapping, topic, true, true)

View file

@ -63,8 +63,6 @@ const TopicCard = {
self.authorizedToEdit = false self.authorizedToEdit = false
}, },
embedlyCardRendered: function(iframe) { embedlyCardRendered: function(iframe) {
var self = TopicCard
$('#embedlyLinkLoader').hide() $('#embedlyLinkLoader').hide()
// means that the embedly call returned 404 not found // means that the embedly call returned 404 not found
@ -93,15 +91,15 @@ const TopicCard = {
}, },
showLinkLoader: function() { showLinkLoader: function() {
var loader = new CanvasLoader('embedlyLinkLoader') var loader = new CanvasLoader('embedlyLinkLoader')
loader.setColor('#4fb5c0'); // default is '#000000' loader.setColor('#4fb5c0') // default is '#000000'
loader.setDiameter(28) // default is 40 loader.setDiameter(28) // default is 40
loader.setDensity(41) // default is 40 loader.setDensity(41) // default is 40
loader.setRange(0.9); // default is 1.3 loader.setRange(0.9) // default is 1.3
loader.show() // Hidden by default loader.show() // Hidden by default
}, },
showLink: function(topic) { showLink: function(topic) {
var e = embedly('card', document.getElementById('embedlyLink')) var e = embedly('card', document.getElementById('embedlyLink'))
if (!e && TopicCard.RAILS_ENV != 'development') { if (!e && TopicCard.RAILS_ENV !== 'development') {
TopicCard.handleInvalidLink() TopicCard.handleInvalidLink()
} else if (!e) { } else if (!e) {
$('#embedlyLink').attr('target', '_blank').html(topic.get('link')).show() $('#embedlyLink').attr('target', '_blank').html(topic.get('link')).show()
@ -129,7 +127,7 @@ const TopicCard = {
var element = this var element = this
setTimeout(function() { setTimeout(function() {
var text = $(element).val() var text = $(element).val()
if (event.type == 'paste' || (event.type == 'keyup' && event.which == 13)) { if (event.type === 'paste' || (event.type === 'keyup' && event.which === 13)) {
// TODO evaluate converting this to '//' no matter what (infer protocol) // TODO evaluate converting this to '//' no matter what (infer protocol)
if (text.slice(0, 7) !== 'http://' && if (text.slice(0, 7) !== 'http://' &&
text.slice(0, 8) !== 'https://' && text.slice(0, 8) !== 'https://' &&
@ -219,7 +217,6 @@ const TopicCard = {
var windowHeight = $(window).height() var windowHeight = $(window).height()
var showcardTop = parseInt($('.showcard').css('top')) var showcardTop = parseInt($('.showcard').css('top'))
var topicTitleHeight = $('.showcard .title').height() + parseInt($('.showcard .title').css('padding-top')) + parseInt($('.showcard .title').css('padding-bottom')) var topicTitleHeight = $('.showcard .title').height() + parseInt($('.showcard .title').css('padding-top')) + parseInt($('.showcard .title').css('padding-bottom'))
var heightOfSetList = $('.showcard .metacodeSelect').height()
var distanceFromBottom = windowHeight - (showcardTop + topicTitleHeight) var distanceFromBottom = windowHeight - (showcardTop + topicTitleHeight)
if (distanceFromBottom < MAX_METACODELIST_HEIGHT) { if (distanceFromBottom < MAX_METACODELIST_HEIGHT) {
$('.metacodeSelect').addClass('onBottomEdge') $('.metacodeSelect').addClass('onBottomEdge')
@ -383,7 +380,7 @@ const TopicCard = {
var html = self.generateShowcardHTML.render(topicForTemplate) var html = self.generateShowcardHTML.render(topicForTemplate)
if (topic.authorizeToEdit(Active.Mapper)) { if (topic.authorizeToEdit(Active.Mapper)) {
var perm = document.createElement('div') let perm = document.createElement('div')
var string = 'permission canEdit' var string = 'permission canEdit'
if (topic.authorizePermissionChange(Active.Mapper)) string += ' yourTopic' if (topic.authorizePermissionChange(Active.Mapper)) string += ' yourTopic'
@ -391,7 +388,7 @@ const TopicCard = {
perm.innerHTML = html perm.innerHTML = html
showCard.appendChild(perm) showCard.appendChild(perm)
} else { } else {
var perm = document.createElement('div') let perm = document.createElement('div')
perm.className = 'permission cannotEdit' perm.className = 'permission cannotEdit'
perm.innerHTML = html perm.innerHTML = html
showCard.appendChild(perm) showCard.appendChild(perm)
@ -402,8 +399,6 @@ const TopicCard = {
generateShowcardHTML: null, // will be initialized into a Hogan template within init function generateShowcardHTML: null, // will be initialized into a Hogan template within init function
// generateShowcardHTML // generateShowcardHTML
buildObject: function(topic) { buildObject: function(topic) {
var self = TopicCard
var nodeValues = {} var nodeValues = {}
var authorized = topic.authorizeToEdit(Active.Mapper) var authorized = topic.authorizeToEdit(Active.Mapper)
@ -438,18 +433,18 @@ const TopicCard = {
nodeValues.inmaps = '' nodeValues.inmaps = ''
if (inmapsAr.length < 6) { if (inmapsAr.length < 6) {
for (let i = 0; i < inmapsAr.length; i++) { for (let i = 0; i < inmapsAr.length; i++) {
var url = '/maps/' + inmapsLinks[i] const url = '/maps/' + inmapsLinks[i]
nodeValues.inmaps += '<li><a href="' + url + '">' + inmapsAr[i] + '</a></li>' nodeValues.inmaps += '<li><a href="' + url + '">' + inmapsAr[i] + '</a></li>'
} }
} else { } else {
for (let i = 0; i < 5; i++) { for (let i = 0; i < 5; i++) {
var url = '/maps/' + inmapsLinks[i] const url = '/maps/' + inmapsLinks[i]
nodeValues.inmaps += '<li><a href="' + url + '">' + inmapsAr[i] + '</a></li>' nodeValues.inmaps += '<li><a href="' + url + '">' + inmapsAr[i] + '</a></li>'
} }
var extra = inmapsAr.length - 5 const extra = inmapsAr.length - 5
nodeValues.inmaps += '<li><span class="showMore">See ' + extra + ' more...</span></li>' nodeValues.inmaps += '<li><span class="showMore">See ' + extra + ' more...</span></li>'
for (let i = 5; i < inmapsAr.length; i++) { for (let i = 5; i < inmapsAr.length; i++) {
var url = '/maps/' + inmapsLinks[i] const url = '/maps/' + inmapsLinks[i]
nodeValues.inmaps += '<li class="hideExtra extraText"><a href="' + url + '">' + inmapsAr[i] + '</a></li>' nodeValues.inmaps += '<li class="hideExtra extraText"><a href="' + url + '">' + inmapsAr[i] + '</a></li>'
} }
} }

View file

@ -9,13 +9,13 @@ const Util = {
// you may copy this code but please keep the copyright notice as well // you may copy this code but please keep the copyright notice as well
splitLine: function(st, n) { splitLine: function(st, n) {
var b = '' var b = ''
var s = st ? st : '' var s = st || ''
while (s.length > n) { while (s.length > n) {
var c = s.substring(0, n) var c = s.substring(0, n)
var d = c.lastIndexOf(' ') var d = c.lastIndexOf(' ')
var e = c.lastIndexOf('\n') var e = c.lastIndexOf('\n')
if (e != -1) d = e if (e !== -1) d = e
if (d == -1) d = n if (d === -1) d = n
b += c.substring(0, d) + '\n' b += c.substring(0, d) + '\n'
s = s.substring(d + 1) s = s.substring(d + 1)
} }
@ -31,9 +31,9 @@ const Util = {
}, },
decodeEntities: function(desc) { decodeEntities: function(desc) {
var str, temp = document.createElement('p') let temp = document.createElement('p')
temp.innerHTML = desc // browser handles the topics temp.innerHTML = desc // browser handles the topics
str = temp.textContent || temp.innerText let str = temp.textContent || temp.innerText
temp = null // delete the element temp = null // delete the element
return str return str
}, // decodeEntities }, // decodeEntities
@ -45,18 +45,17 @@ const Util = {
// Try using Visualize.mGraph // Try using Visualize.mGraph
coordsToPixels: function(mGraph, coords) { coordsToPixels: function(mGraph, coords) {
if (mGraph) { if (mGraph) {
var canvas = mGraph.canvas, const canvas = mGraph.canvas
s = canvas.getSize(), const s = canvas.getSize()
p = canvas.getPos(), const p = canvas.getPos()
ox = canvas.translateOffsetX, const ox = canvas.translateOffsetX
oy = canvas.translateOffsetY, const oy = canvas.translateOffsetY
sx = canvas.scaleOffsetX, const sx = canvas.scaleOffsetX
sy = canvas.scaleOffsetY const sy = canvas.scaleOffsetY
var pixels = { return {
x: (coords.x / (1 / sx)) + p.x + s.width / 2 + ox, x: (coords.x / (1 / sx)) + p.x + s.width / 2 + ox,
y: (coords.y / (1 / sy)) + p.y + s.height / 2 + oy y: (coords.y / (1 / sy)) + p.y + s.height / 2 + oy
} }
return pixels
} else { } else {
return { return {
x: 0, x: 0,
@ -67,26 +66,24 @@ const Util = {
// Try using Visualize.mGraph // Try using Visualize.mGraph
pixelsToCoords: function(mGraph, pixels) { pixelsToCoords: function(mGraph, pixels) {
var coords
if (mGraph) { if (mGraph) {
var canvas = mGraph.canvas, const canvas = mGraph.canvas
s = canvas.getSize(), const s = canvas.getSize()
p = canvas.getPos(), const p = canvas.getPos()
ox = canvas.translateOffsetX, const ox = canvas.translateOffsetX
oy = canvas.translateOffsetY, const oy = canvas.translateOffsetY
sx = canvas.scaleOffsetX, const sx = canvas.scaleOffsetX
sy = canvas.scaleOffsetY const sy = canvas.scaleOffsetY
coords = { return {
x: (pixels.x - p.x - s.width / 2 - ox) * (1 / sx), x: (pixels.x - p.x - s.width / 2 - ox) * (1 / sx),
y: (pixels.y - p.y - s.height / 2 - oy) * (1 / sy), y: (pixels.y - p.y - s.height / 2 - oy) * (1 / sy)
} }
} else { } else {
coords = { return {
x: 0, x: 0,
y: 0 y: 0
} }
} }
return coords
}, },
getPastelColor: function(opts = {}) { getPastelColor: function(opts = {}) {
const rseed = opts.rseed === undefined ? Math.random() : opts.rseed const rseed = opts.rseed === undefined ? Math.random() : opts.rseed
@ -107,9 +104,9 @@ const Util = {
lum = lum || 0 lum = lum || 0
// convert to decimal and change luminosity // convert to decimal and change luminosity
var rgb = '#', c, i var rgb = '#'
for (i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
c = parseInt(hex.substr(i * 2, 2), 16) let c = parseInt(hex.substr(i * 2, 2), 16)
c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16) c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16)
rgb += ('00' + c).substr(c.length) rgb += ('00' + c).substr(c.length)
} }
@ -117,15 +114,15 @@ const Util = {
return rgb return rgb
}, },
openLink: function(url) { openLink: function(url) {
var win = (url !== "") ? window.open(url, '_blank') : "empty"; var win = (url !== '') ? window.open(url, '_blank') : 'empty'
if (win) { if (win) {
// Browser has allowed it to be opened // Browser has allowed it to be opened
return true; return true
} else { } else {
// Browser has blocked it // Browser has blocked it
alert('Please allow popups in order to open the link'); window.alert('Please allow popups in order to open the link')
return false; return false
} }
}, },
mdToHTML: text => { mdToHTML: text => {
@ -139,19 +136,19 @@ const Util = {
return { return {
scaleX: canvas.scaleOffsetX, scaleX: canvas.scaleOffsetX,
scaleY: canvas.scaleOffsetY, scaleY: canvas.scaleOffsetY,
centreCoords: Util.pixelsToCoords(fakeMgraph, { x: canvas.canvases[0].size.width / 2, y: canvas.canvases[0].size.height / 2 }), centreCoords: Util.pixelsToCoords(fakeMgraph, { x: canvas.canvases[0].size.width / 2, y: canvas.canvases[0].size.height / 2 })
}; }
}, },
resizeCanvas: function(canvas) { resizeCanvas: function(canvas) {
// Store the current canvas attributes, i.e. scale and map-coordinate at the centre of the user's screen // Store the current canvas attributes, i.e. scale and map-coordinate at the centre of the user's screen
const oldAttr = Util.logCanvasAttributes(canvas); const oldAttr = Util.logCanvasAttributes(canvas)
// Resize the canvas to fill the new window size. Based on how JIT works, this also resets the map back to scale 1 and tranlations = 0 // Resize the canvas to fill the new window size. Based on how JIT works, this also resets the map back to scale 1 and tranlations = 0
canvas.resize($(window).width(), $(window).height()) canvas.resize($(window).width(), $(window).height())
// Return the map to the original scale, and then put the previous central map-coordinate back to the centre of user's newly resized screen // Return the map to the original scale, and then put the previous central map-coordinate back to the centre of user's newly resized screen
canvas.scale(oldAttr.scaleX, oldAttr.scaleY) canvas.scale(oldAttr.scaleX, oldAttr.scaleY)
const newAttr = Util.logCanvasAttributes(canvas); const newAttr = Util.logCanvasAttributes(canvas)
canvas.translate(newAttr.centreCoords.x - oldAttr.centreCoords.x, newAttr.centreCoords.y - oldAttr.centreCoords.y) canvas.translate(newAttr.centreCoords.x - oldAttr.centreCoords.x, newAttr.centreCoords.y - oldAttr.centreCoords.y)
} }
} }

View file

@ -4,6 +4,7 @@ import React from 'react'
import ReactDOM from 'react-dom' // TODO ensure this isn't a double import import ReactDOM from 'react-dom' // TODO ensure this isn't a double import
import Active from '../Active' import Active from '../Active'
import DataModel from '../DataModel'
import GlobalUI from '../GlobalUI' import GlobalUI from '../GlobalUI'
import Realtime from '../Realtime' import Realtime from '../Realtime'
import Loading from '../Loading' import Loading from '../Loading'
@ -35,15 +36,15 @@ const ExploreMaps = {
section: self.collection.id, section: self.collection.id,
maps: self.collection, maps: self.collection,
juntoState: Realtime.juntoState, juntoState: Realtime.juntoState,
moreToLoad: self.collection.page != 'loadedAll', moreToLoad: self.collection.page !== 'loadedAll',
user: self.collection.id === 'mapper' ? self.mapper : null, user: self.collection.id === 'mapper' ? self.mapper : null,
loadMore: self.loadMore, loadMore: self.loadMore,
pending: self.pending, pending: self.pending,
onStar: function(map) { onStar: function(map) {
$.post('/maps/' + map.id + '/star') $.post('/maps/' + map.id + '/star')
map.set('star_count', map.get('star_count') + 1) map.set('star_count', map.get('star_count') + 1)
if (Metamaps.Stars) Metamaps.Stars.push({ user_id: Active.Mapper.id, map_id: map.id }) if (DataModel.Stars) DataModel.Stars.push({ user_id: Active.Mapper.id, map_id: map.id })
Metamaps.Maps.Starred.add(map) DataModel.Maps.Starred.add(map)
GlobalUI.notifyUser('Map is now starred') GlobalUI.notifyUser('Map is now starred')
self.render() self.render()
}, },
@ -64,7 +65,7 @@ const ExploreMaps = {
}, },
loadMore: function() { loadMore: function() {
var self = ExploreMaps var self = ExploreMaps
if (self.collection.page != "loadedAll") { if (self.collection.page !== 'loadedAll') {
self.collection.getMaps() self.collection.getMaps()
self.pending = true self.pending = true
} }
@ -77,19 +78,19 @@ const ExploreMaps = {
self.fetchUserThenRender(cb) self.fetchUserThenRender(cb)
} else { } else {
self.render(cb) self.render(cb)
Metamaps.Loading.hide() Loading.hide()
} }
}, },
handleError: function() { handleError: function() {
console.log('error loading maps!') // TODO console.log('error loading maps!') // TODO
Metamaps.Loading.hide() Loading.hide()
}, },
fetchUserThenRender: function(cb) { fetchUserThenRender: function(cb) {
var self = ExploreMaps var self = ExploreMaps
if (self.mapper && self.mapper.id === self.collection.mapperId) { if (self.mapper && self.mapper.id === self.collection.mapperId) {
self.render(cb) self.render(cb)
return Metamaps.Loading.hide() return Loading.hide()
} }
// first load the mapper object and then call the render function // first load the mapper object and then call the render function
@ -98,11 +99,11 @@ const ExploreMaps = {
success: function(response) { success: function(response) {
self.mapper = response self.mapper = response
self.render(cb) self.render(cb)
Metamaps.Loading.hide() Loading.hide()
}, },
error: function() { error: function() {
self.render(cb) self.render(cb)
Metamaps.Loading.hide() Loading.hide()
} }
}) })
} }

View file

@ -14,8 +14,6 @@ import ChatView from './ChatView'
import VideoView from './VideoView' import VideoView from './VideoView'
const Room = function(opts = {}) { const Room = function(opts = {}) {
var self = this
this.isActiveRoom = false this.isActiveRoom = false
this.socket = opts.socket this.socket = opts.socket
this.webrtc = opts.webrtc this.webrtc = opts.webrtc
@ -112,21 +110,19 @@ Room.prototype.init = function () {
if (data.name === 'audio') { if (data.name === 'audio') {
v.audioStatus = false v.audioStatus = false
} } else if (data.name === 'video') {
else if (data.name === 'video') {
v.videoStatus = false v.videoStatus = false
v.$avatar.show() v.$avatar.show()
} }
if (!v.audioStatus && !v.videoStatus) v.$container.hide() if (!v.audioStatus && !v.videoStatus) v.$container.hide()
}) })
this.webrtc.on('unmute', function(data) { this.webrtc.on('unmute', function(data) {
var v = self.videos[data.id] const v = self.videos[data.id]
if (!v) return if (!v) return
if (data.name === 'audio') { if (data.name === 'audio') {
v.audioStatus = true v.audioStatus = true
} } else if (data.name === 'video') {
else if (data.name === 'video') {
v.videoStatus = true v.videoStatus = true
v.$avatar.hide() v.$avatar.hide()
} }
@ -144,19 +140,17 @@ Room.prototype.init = function () {
} }
Room.prototype.addVideo = function(peer) { Room.prototype.addVideo = function(peer) {
var const id = this.webrtc.getDomId(peer)
id = this.webrtc.getDomId(peer), const video = attachMediaStream(peer.stream)
video = attachMediaStream(peer.stream)
var const v = new VideoView(video, null, id, false, { DOUBLE_CLICK_TOLERANCE: 200, avatar: peer.avatar, username: peer.username })
v = new VideoView(video, null, id, false, { DOUBLE_CLICK_TOLERANCE: 200, avatar: peer.avatar, username: peer.username })
this.videos[peer.id] = v this.videos[peer.id] = v
if (this._videoAdded) this._videoAdded(v, peer.nick) if (this._videoAdded) this._videoAdded(v, peer.nick)
} }
Room.prototype.removeVideo = function(peer) { Room.prototype.removeVideo = function(peer) {
var id = typeof peer == 'string' ? peer : peer.id var id = typeof peer === 'string' ? peer : peer.id
if (this.videos[id]) { if (this.videos[id]) {
this.videos[id].remove() this.videos[id].remove()
delete this.videos[id] delete this.videos[id]
@ -170,7 +164,7 @@ Room.prototype.init = function () {
var m = new DataModel.Message({ var m = new DataModel.Message({
message: data.message, message: data.message,
resource_id: Active.Map.id, resource_id: Active.Map.id,
resource_type: "Map" resource_type: 'Map'
}) })
m.save(null, { m.save(null, {
success: function(model, response) { success: function(model, response) {
@ -198,7 +192,7 @@ Room.prototype.init = function () {
* @static * @static
*/ */
Room.events = { Room.events = {
newMessage: "Room:newMessage" newMessage: 'Room:newMessage'
} }
export default Room export default Room

View file

@ -2,57 +2,57 @@
var Private = { var Private = {
addControls: function() { addControls: function() {
var self = this; var self = this
this.$audioControl = $('<div class="video-audio"></div>'); this.$audioControl = $('<div class="video-audio"></div>')
this.$videoControl = $('<div class="video-video"></div>'); this.$videoControl = $('<div class="video-video"></div>')
this.$audioControl.on('click', function() { this.$audioControl.on('click', function() {
Handlers.audioControlClick.call(self); Handlers.audioControlClick.call(self)
}); })
this.$videoControl.on('click', function() { this.$videoControl.on('click', function() {
Handlers.videoControlClick.call(self); Handlers.videoControlClick.call(self)
}); })
this.$container.append(this.$audioControl); this.$container.append(this.$audioControl)
this.$container.append(this.$videoControl); this.$container.append(this.$videoControl)
}, },
cancelClick: function() { cancelClick: function() {
this.mouseIsDown = false; this.mouseIsDown = false
if (this.hasMoved) { if (this.hasMoved) {
} }
$(document).trigger(VideoView.events.dragEnd); $(document).trigger(VideoView.events.dragEnd)
}
} }
};
var Handlers = { var Handlers = {
mousedown: function(event) { mousedown: function(event) {
this.mouseIsDown = true; this.mouseIsDown = true
this.hasMoved = false; this.hasMoved = false
this.mouseMoveStart = { this.mouseMoveStart = {
x: event.pageX, x: event.pageX,
y: event.pageY y: event.pageY
}; }
this.posStart = { this.posStart = {
x: parseInt(this.$container.css('left'), '10'), x: parseInt(this.$container.css('left'), '10'),
y: parseInt(this.$container.css('top'), '10') y: parseInt(this.$container.css('top'), '10')
} }
$(document).trigger(VideoView.events.mousedown); $(document).trigger(VideoView.events.mousedown)
}, },
mouseup: function(event) { mouseup: function(event) {
$(document).trigger(VideoView.events.mouseup, [this]); $(document).trigger(VideoView.events.mouseup, [this])
var storedTime = this.lastClick; var storedTime = this.lastClick
var now = Date.now(); var now = Date.now()
this.lastClick = now; this.lastClick = now
if (now - storedTime < this.config.DOUBLE_CLICK_TOLERANCE) { if (now - storedTime < this.config.DOUBLE_CLICK_TOLERANCE) {
$(document).trigger(VideoView.events.doubleClick, [this]); $(document).trigger(VideoView.events.doubleClick, [this])
} }
}, },
mousemove: function(event) { mousemove: function(event) {
@ -60,130 +60,129 @@ var Handlers = {
diffX, diffX,
diffY, diffY,
newX, newX,
newY; newY
if (this.$parent && this.mouseIsDown) { if (this.$parent && this.mouseIsDown) {
this.manuallyPositioned = true; this.manuallyPositioned = true
this.hasMoved = true; this.hasMoved = true
diffX = event.pageX - this.mouseMoveStart.x; diffX = event.pageX - this.mouseMoveStart.x
diffY = this.mouseMoveStart.y - event.pageY; diffY = this.mouseMoveStart.y - event.pageY
newX = this.posStart.x + diffX; newX = this.posStart.x + diffX
newY = this.posStart.y - diffY; newY = this.posStart.y - diffY
this.$container.css({ this.$container.css({
top: newY, top: newY,
left: newX left: newX
}); })
} }
}, },
audioControlClick: function() { audioControlClick: function() {
if (this.audioStatus) { if (this.audioStatus) {
this.audioOff(); this.audioOff()
} else { } else {
this.audioOn(); this.audioOn()
} }
$(document).trigger(VideoView.events.audioControlClick, [this]); $(document).trigger(VideoView.events.audioControlClick, [this])
}, },
videoControlClick: function() { videoControlClick: function() {
if (this.videoStatus) { if (this.videoStatus) {
this.videoOff(); this.videoOff()
} else { } else {
this.videoOn(); this.videoOn()
}
$(document).trigger(VideoView.events.videoControlClick, [this])
}
} }
$(document).trigger(VideoView.events.videoControlClick, [this]);
},
};
var VideoView = function(video, $parent, id, isMyself, config) { var VideoView = function(video, $parent, id, isMyself, config) {
var self = this; var self = this
this.$parent = $parent; // mapView this.$parent = $parent // mapView
this.video = video; this.video = video
this.id = id; this.id = id
this.config = config; this.config = config
this.mouseIsDown = false; this.mouseIsDown = false
this.mouseDownOffset = { x: 0, y: 0 }; this.mouseDownOffset = { x: 0, y: 0 }
this.lastClick = null; this.lastClick = null
this.hasMoved = false; this.hasMoved = false
this.audioStatus = true; this.audioStatus = true
this.videoStatus = true; this.videoStatus = true
this.$container = $('<div></div>'); this.$container = $('<div></div>')
this.$container.addClass('collaborator-video' + (isMyself ? ' my-video' : '')); this.$container.addClass('collaborator-video' + (isMyself ? ' my-video' : ''))
this.$container.attr('id', 'container_' + id); this.$container.attr('id', 'container_' + id)
var $vidContainer = $('<div></div>')
$vidContainer.addClass('video-cutoff')
$vidContainer.append(this.video)
var $vidContainer = $('<div></div>'); this.avatar = config.avatar
$vidContainer.addClass('video-cutoff'); this.$avatar = $('<img draggable="false" class="collaborator-video-avatar" src="' + config.avatar + '" width="150" height="150" />')
$vidContainer.append(this.video); $vidContainer.append(this.$avatar)
this.avatar = config.avatar; this.$container.append($vidContainer)
this.$avatar = $('<img draggable="false" class="collaborator-video-avatar" src="' + config.avatar + '" width="150" height="150" />');
$vidContainer.append(this.$avatar);
this.$container.append($vidContainer);
this.$container.on('mousedown', function(event) { this.$container.on('mousedown', function(event) {
Handlers.mousedown.call(self, event); Handlers.mousedown.call(self, event)
}); })
if (isMyself) { if (isMyself) {
Private.addControls.call(this); Private.addControls.call(this)
} }
// suppress contextmenu // suppress contextmenu
this.video.oncontextmenu = function () { return false; }; this.video.oncontextmenu = function() { return false }
if (this.$parent) this.setParent(this.$parent); if (this.$parent) this.setParent(this.$parent)
}; }
VideoView.prototype.setParent = function($parent) { VideoView.prototype.setParent = function($parent) {
var self = this; var self = this
this.$parent = $parent; this.$parent = $parent
this.$parent.off('.video' + this.id); this.$parent.off('.video' + this.id)
this.$parent.on('mouseup.video' + this.id, function(event) { this.$parent.on('mouseup.video' + this.id, function(event) {
Handlers.mouseup.call(self, event); Handlers.mouseup.call(self, event)
Private.cancelClick.call(self); Private.cancelClick.call(self)
}); })
this.$parent.on('mousemove.video' + this.id, function(event) { this.$parent.on('mousemove.video' + this.id, function(event) {
Handlers.mousemove.call(self, event); Handlers.mousemove.call(self, event)
}); })
} }
VideoView.prototype.setAvatar = function(src) { VideoView.prototype.setAvatar = function(src) {
this.$avatar.attr('src', src); this.$avatar.attr('src', src)
this.avatar = src; this.avatar = src
} }
VideoView.prototype.remove = function() { VideoView.prototype.remove = function() {
this.$container.off(); this.$container.off()
if (this.$parent) this.$parent.off('.video' + this.id); if (this.$parent) this.$parent.off('.video' + this.id)
this.$container.remove(); this.$container.remove()
} }
VideoView.prototype.videoOff = function() { VideoView.prototype.videoOff = function() {
this.$videoControl.addClass('active'); this.$videoControl.addClass('active')
this.$avatar.show(); this.$avatar.show()
this.videoStatus = false; this.videoStatus = false
} }
VideoView.prototype.videoOn = function() { VideoView.prototype.videoOn = function() {
this.$videoControl.removeClass('active'); this.$videoControl.removeClass('active')
this.$avatar.hide(); this.$avatar.hide()
this.videoStatus = true; this.videoStatus = true
} }
VideoView.prototype.audioOff = function() { VideoView.prototype.audioOff = function() {
this.$audioControl.addClass('active'); this.$audioControl.addClass('active')
this.audioStatus = false; this.audioStatus = false
} }
VideoView.prototype.audioOn = function() { VideoView.prototype.audioOn = function() {
this.$audioControl.removeClass('active'); this.$audioControl.removeClass('active')
this.audioStatus = true; this.audioStatus = true
} }
/** /**
@ -191,12 +190,12 @@ VideoView.prototype.audioOn = function () {
* @static * @static
*/ */
VideoView.events = { VideoView.events = {
mousedown: "VideoView:mousedown", mousedown: 'VideoView:mousedown',
mouseup: "VideoView:mouseup", mouseup: 'VideoView:mouseup',
doubleClick: "VideoView:doubleClick", doubleClick: 'VideoView:doubleClick',
dragEnd: "VideoView:dragEnd", dragEnd: 'VideoView:dragEnd',
audioControlClick: "VideoView:audioControlClick", audioControlClick: 'VideoView:audioControlClick',
videoControlClick: "VideoView:videoControlClick", videoControlClick: 'VideoView:videoControlClick'
}; }
export default VideoView export default VideoView

View file

@ -40,21 +40,20 @@ const Visualize = {
// 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) {
lastDist = 0
if (!self.mGraph.events.touchMoved && !Visualize.touchDragNode) TopicCard.hideCurrentCard() if (!self.mGraph.events.touchMoved && !Visualize.touchDragNode) TopicCard.hideCurrentCard()
self.mGraph.events.touched = self.mGraph.events.touchMoved = false self.mGraph.events.touched = self.mGraph.events.touchMoved = false
Visualize.touchDragNode = false Visualize.touchDragNode = false
}) })
}, },
computePositions: function() { computePositions: function() {
var self = Visualize, const self = Visualize
mapping
if (self.type == 'RGraph') { if (self.type === 'RGraph') {
var i, l, startPos, endPos, topic, synapse let i
let l
self.mGraph.graph.eachNode(function(n) { self.mGraph.graph.eachNode(function(n) {
topic = DataModel.Topics.get(n.id) const topic = DataModel.Topics.get(n.id)
topic.set({ node: n }, { silent: true }) topic.set({ node: n }, { silent: true })
topic.updateNode() topic.updateNode()
@ -64,7 +63,7 @@ const Visualize = {
l = edge.getData('synapseIDs').length l = edge.getData('synapseIDs').length
for (i = 0; i < l; i++) { for (i = 0; i < l; i++) {
synapse = DataModel.Synapses.get(edge.getData('synapseIDs')[i]) const synapse = DataModel.Synapses.get(edge.getData('synapseIDs')[i])
synapse.set({ edge: edge }, { silent: true }) synapse.set({ edge: edge }, { silent: true })
synapse.updateEdge() synapse.updateEdge()
} }
@ -75,34 +74,32 @@ const Visualize = {
pos.setc(-200, -200) pos.setc(-200, -200)
}) })
self.mGraph.compute('end') self.mGraph.compute('end')
} else if (self.type == 'ForceDirected') { } else if (self.type === 'ForceDirected') {
var i, l, startPos, endPos, topic, synapse
self.mGraph.graph.eachNode(function(n) { self.mGraph.graph.eachNode(function(n) {
topic = DataModel.Topics.get(n.id) const topic = DataModel.Topics.get(n.id)
topic.set({ node: n }, { silent: true }) topic.set({ node: n }, { silent: true })
topic.updateNode() topic.updateNode()
mapping = topic.getMapping() const mapping = topic.getMapping()
n.eachAdjacency(function(edge) { n.eachAdjacency(function(edge) {
if (!edge.getData('init')) { if (!edge.getData('init')) {
edge.setData('init', true) edge.setData('init', true)
l = edge.getData('synapseIDs').length const l = edge.getData('synapseIDs').length
for (i = 0; i < l; i++) { for (let i = 0; i < l; i++) {
synapse = DataModel.Synapses.get(edge.getData('synapseIDs')[i]) const synapse = DataModel.Synapses.get(edge.getData('synapseIDs')[i])
synapse.set({ edge: edge }, { silent: true }) synapse.set({ edge: edge }, { silent: true })
synapse.updateEdge() synapse.updateEdge()
} }
} }
}) })
startPos = new $jit.Complex(0, 0) const startPos = new $jit.Complex(0, 0)
endPos = new $jit.Complex(mapping.get('xloc'), mapping.get('yloc')) const endPos = new $jit.Complex(mapping.get('xloc'), mapping.get('yloc'))
n.setPos(startPos, 'start') n.setPos(startPos, 'start')
n.setPos(endPos, 'end') n.setPos(endPos, 'end')
}) })
} else if (self.type == 'ForceDirected3D') { } else if (self.type === 'ForceDirected3D') {
self.mGraph.compute() self.mGraph.compute()
} }
}, },
@ -111,13 +108,13 @@ const Visualize = {
* *
*/ */
render: function() { render: function() {
var self = Visualize, RGraphSettings, FDSettings const self = Visualize
if (self.type == 'RGraph') { if (self.type === 'RGraph') {
// clear the previous canvas from #infovis // clear the previous canvas from #infovis
$('#infovis').empty() $('#infovis').empty()
RGraphSettings = $.extend(true, {}, JIT.ForceDirected.graphSettings) const RGraphSettings = $.extend(true, {}, JIT.ForceDirected.graphSettings)
$jit.RGraph.Plot.NodeTypes.implement(JIT.ForceDirected.nodeSettings) $jit.RGraph.Plot.NodeTypes.implement(JIT.ForceDirected.nodeSettings)
$jit.RGraph.Plot.EdgeTypes.implement(JIT.ForceDirected.edgeSettings) $jit.RGraph.Plot.EdgeTypes.implement(JIT.ForceDirected.edgeSettings)
@ -128,11 +125,11 @@ const Visualize = {
RGraphSettings.levelDistance = JIT.RGraph.levelDistance RGraphSettings.levelDistance = 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()
FDSettings = $.extend(true, {}, JIT.ForceDirected.graphSettings) const FDSettings = $.extend(true, {}, JIT.ForceDirected.graphSettings)
$jit.ForceDirected.Plot.NodeTypes.implement(JIT.ForceDirected.nodeSettings) $jit.ForceDirected.Plot.NodeTypes.implement(JIT.ForceDirected.nodeSettings)
$jit.ForceDirected.Plot.EdgeTypes.implement(JIT.ForceDirected.edgeSettings) $jit.ForceDirected.Plot.EdgeTypes.implement(JIT.ForceDirected.edgeSettings)
@ -141,7 +138,7 @@ const Visualize = {
FDSettings.height = $('body').height() FDSettings.height = $('body').height()
self.mGraph = new $jit.ForceDirected(FDSettings) self.mGraph = new $jit.ForceDirected(FDSettings)
} else if (self.type == 'ForceDirected3D' && !self.mGraph) { } else if (self.type === 'ForceDirected3D' && !self.mGraph) {
// clear the previous canvas from #infovis // clear the previous canvas from #infovis
$('#infovis').empty() $('#infovis').empty()
@ -152,8 +149,7 @@ const Visualize = {
self.mGraph.graph.empty() self.mGraph.graph.empty()
} }
if (self.type === 'ForceDirected' && Active.Mapper) $.post('/maps/' + Active.Map.id + '/events/user_presence')
if (self.type == 'ForceDirected' && Active.Mapper) $.post('/maps/' + Active.Map.id + '/events/user_presence')
function runAnimation() { function runAnimation() {
Loading.hide() Loading.hide()
@ -171,11 +167,11 @@ const Visualize = {
// 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(JIT.RGraph.animate)
} else if (self.type == 'ForceDirected') { } else if (self.type === 'ForceDirected') {
self.mGraph.animate(JIT.ForceDirected.animateSavedLayout) self.mGraph.animate(JIT.ForceDirected.animateSavedLayout)
} else if (self.type == 'ForceDirected3D') { } else if (self.type === 'ForceDirected3D') {
self.mGraph.animate(JIT.ForceDirected.animateFDLayout) self.mGraph.animate(JIT.ForceDirected.animateFDLayout)
} }
} }
@ -184,21 +180,24 @@ const Visualize = {
// 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() {
var unique = _.uniq(DataModel.Topics.models, function (metacode) { return metacode.get('metacode_id'); }), const unique = _.uniq(DataModel.Topics.models, function(metacode) { return metacode.get('metacode_id') })
requiredMetacodes = _.map(unique, function (metacode) { return metacode.get('metacode_id'); }), const requiredMetacodes = _.map(unique, function(metacode) { return metacode.get('metacode_id') })
loadedCount = 0 let loadedCount = 0
_.each(requiredMetacodes, function (metacode_id) { _.each(requiredMetacodes, function(metacodeId) {
var metacode = DataModel.Metacodes.get(metacode_id), const metacode = DataModel.Metacodes.get(metacodeId)
img = metacode ? metacode.get('image') : false const img = metacode ? metacode.get('image') : false
if (img && (img.complete || (typeof img.naturalWidth !== 'undefined' && img.naturalWidth !== 0))) { if (img && (img.complete || (typeof img.naturalWidth !== 'undefined' && img.naturalWidth !== 0))) {
loadedCount += 1 loadedCount += 1
} }
}) })
if (loadedCount === requiredMetacodes.length || tries > 80) runAnimation() if (loadedCount === requiredMetacodes.length || tries > 80) {
else setTimeout(function () { tries++; hold() }, 50) runAnimation()
} else {
setTimeout(function() { tries++; hold() }, 50)
}
} }
hold() hold()
@ -210,8 +209,7 @@ const Visualize = {
if (m && window.location.pathname !== '/maps/' + m.id) { if (m && window.location.pathname !== '/maps/' + m.id) {
Router.navigate('/maps/' + m.id) Router.navigate('/maps/' + m.id)
} } else if (t && window.location.pathname !== '/topics/' + t.id) {
else if (t && window.location.pathname !== '/topics/' + t.id) {
Router.navigate('/topics/' + t.id) Router.navigate('/topics/' + t.id)
} }
}, 800) }, 800)
@ -221,7 +219,7 @@ const Visualize = {
Visualize.mGraph.plot() Visualize.mGraph.plot()
JIT.centerMap(Visualize.mGraph.canvas) JIT.centerMap(Visualize.mGraph.canvas)
$('#infovis').empty() $('#infovis').empty()
}, }
} }
export default Visualize export default Visualize

View file

@ -70,10 +70,6 @@ Metamaps.Topic = Topic
Metamaps.TopicCard = TopicCard Metamaps.TopicCard = TopicCard
Metamaps.Util = Util Metamaps.Util = Util
Metamaps.Views = Views Metamaps.Views = Views
Metamaps.Views.ExploreMaps = ExploreMaps
Metamaps.Views.ChatView = ChatView
Metamaps.Views.VideoView = VideoView
Metamaps.Views.Room = Room
Metamaps.Visualize = Visualize Metamaps.Visualize = Visualize
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
@ -94,14 +90,14 @@ document.addEventListener('DOMContentLoaded', function () {
Views.ExploreMaps.setCollection(DataModel.Maps[capitalize]) Views.ExploreMaps.setCollection(DataModel.Maps[capitalize])
if (Metamaps.currentPage === 'mapper') { if (Metamaps.currentPage === 'mapper') {
ExploreMaps.fetchUserThenRender() Views.ExploreMaps.fetchUserThenRender()
} else { } else {
ExploreMaps.render() Views.ExploreMaps.render()
} }
GlobalUI.showDiv('#explore') GlobalUI.showDiv('#explore')
} else if (Metamaps.currentSection === '' && Active.Mapper) { } else if (Metamaps.currentSection === '' && Active.Mapper) {
ExploreMaps.setCollection(DataModel.Maps.Active) Views.ExploreMaps.setCollection(DataModel.Maps.Active)
ExploreMaps.render() Views.ExploreMaps.render()
GlobalUI.showDiv('#explore') GlobalUI.showDiv('#explore')
} else if (Active.Map || Active.Topic) { } else if (Active.Map || Active.Topic) {
Loading.show() Loading.show()

View file

@ -87,10 +87,6 @@ class MapCard extends Component {
const hasMapper = hasMap && !hasConversation const hasMapper = hasMap && !hasConversation
const mapperList = hasMap && Object.keys(hasMap).map(id => juntoState.connectedPeople[id]) const mapperList = hasMap && Object.keys(hasMap).map(id => juntoState.connectedPeople[id])
function capitalize (string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
const n = map.get('name') const n = map.get('name')
const d = map.get('desc') const d = map.get('desc')

View file

@ -31,9 +31,9 @@ class Maps extends Component {
const { maps, user, currentUser } = this.props const { maps, user, currentUser } = this.props
const numCards = maps.length + (user || currentUser ? 1 : 0) const numCards = maps.length + (user || currentUser ? 1 : 0)
const mapSpaces = Math.floor(document.body.clientWidth / MAP_WIDTH) const mapSpaces = Math.floor(document.body.clientWidth / MAP_WIDTH)
const mapsWidth = document.body.clientWidth <= MOBILE_VIEW_BREAKPOINT ? const mapsWidth = document.body.clientWidth <= MOBILE_VIEW_BREAKPOINT
document.body.clientWidth - MOBILE_VIEW_PADDING : ? document.body.clientWidth - MOBILE_VIEW_PADDING
Math.min(MAX_COLUMNS, Math.min(numCards, mapSpaces)) * MAP_WIDTH : Math.min(MAX_COLUMNS, Math.min(numCards, mapSpaces)) * MAP_WIDTH
this.setState({ mapsWidth }) this.setState({ mapsWidth })
} }
@ -46,7 +46,7 @@ class Maps extends Component {
} }
render = () => { render = () => {
const { maps, currentUser, juntoState, pending, section, user, moreToLoad, loadMore, onStar, onRequest } = this.props const { maps, currentUser, juntoState, pending, section, user, onStar, onRequest } = this.props
const style = { width: this.state.mapsWidth + 'px' } const style = { width: this.state.mapsWidth + 'px' }
const mobile = document && document.body.clientWidth <= MOBILE_VIEW_BREAKPOINT const mobile = document && document.body.clientWidth <= MOBILE_VIEW_BREAKPOINT

View file

@ -26,7 +26,6 @@ module.exports = function (io, store) {
}) })
io.on('connection', function(socket) { io.on('connection', function(socket) {
io.sockets.emit(JUNTO_UPDATED, store.getState()) io.sockets.emit(JUNTO_UPDATED, store.getState())
socket.on(JOIN_MAP, data => store.dispatch({ type: JOIN_MAP, payload: data })) socket.on(JOIN_MAP, data => store.dispatch({ type: JOIN_MAP, payload: data }))

View file

@ -23,7 +23,6 @@ const { mapRoom, userMapRoom } = require('./rooms')
module.exports = function(io, store) { module.exports = function(io, store) {
io.on('connection', function(socket) { io.on('connection', function(socket) {
socket.on(CHECK_FOR_CALL, function(data) { socket.on(CHECK_FOR_CALL, function(data) {
var callInProgress = Object.keys(io.nsps['/'].adapter.rooms[data.room] || {}).length var callInProgress = Object.keys(io.nsps['/'].adapter.rooms[data.room] || {}).length
if (callInProgress) socket.emit(CALL_IN_PROGRESS) if (callInProgress) socket.emit(CALL_IN_PROGRESS)

View file

@ -26,7 +26,6 @@ const { mapRoom, userMapRoom } = require('./rooms')
module.exports = function(io, store) { module.exports = function(io, store) {
io.on('connection', function(socket) { io.on('connection', function(socket) {
// this will ping everyone on a map that there's a person just joined the map // this will ping everyone on a map that there's a person just joined the map
socket.on(JOIN_MAP, function(data) { socket.on(JOIN_MAP, function(data) {
socket.mapid = data.mapid socket.mapid = data.mapid

View file

@ -1,10 +1,9 @@
var const io = require('socket.io')()
io = require('socket.io')(), const signalling = require('./signal')
signalling = require('./signal'), const junto = require('./junto')
junto = require('./junto'), const map = require('./map')
map = require('./map'), const global = require('./global')
global = require('./global'), const stunservers = [{'url': 'stun:stun.l.google.com:19302'}]
stunservers = [{"url": "stun:stun.l.google.com:19302"}]
const { createStore } = require('redux') const { createStore } = require('redux')
const reducer = require('./reducer') const reducer = require('./reducer')

View file

@ -5,9 +5,9 @@ const uuid = require('node-uuid')
function safeCb(cb) { function safeCb(cb) {
if (typeof cb === 'function') { if (typeof cb === 'function') {
return cb; return cb
} else { } else {
return function () {}; return function() {}
} }
} }
@ -74,8 +74,8 @@ module.exports = function(io, stunservers, state) {
}) })
socket.on('create', function(name, cb) { socket.on('create', function(name, cb) {
if (arguments.length == 2) { if (arguments.length === 2) {
cb = (typeof cb == 'function') ? cb : function () {} cb = (typeof cb === 'function') ? cb : function() {}
name = name || uuid() name = name || uuid()
} else { } else {
cb = name cb = name
@ -111,8 +111,4 @@ module.exports = function(io, stunservers, state) {
}) })
return result return result
} }
function socketsInRoom(name) {
return io.sockets.sockets(name).length
}
} }