Fix onchangelistener to use e.target

For some reason the change listener for the edit fields used e.srcElement, this didn't seem to work everywhere.
Using e.target should fix this.
This commit is contained in:
Hugvey Central Command 2019-05-13 14:12:54 +02:00
parent 8f8386505c
commit 480e8a49bc

View file

@ -28,7 +28,7 @@ class Panopticon {
}, },
loadNarrative: function( code, file ) { loadNarrative: function( code, file ) {
panopticon.hugveys.selectedId = null; panopticon.hugveys.selectedId = null;
if(panopticon.hasGraph) { if(panopticon.hasGraph) {
return panopticon.loadNarrative( code, file ); return panopticon.loadNarrative( code, file );
} }
@ -79,16 +79,16 @@ class Panopticon {
this.socket = new ReconnectingWebSocket( "ws://localhost:8888/ws", null, { debug: false, reconnectInterval: 3000 } ); this.socket = new ReconnectingWebSocket( "ws://localhost:8888/ws", null, { debug: false, reconnectInterval: 3000 } );
if(this.hasGraph) { if(this.hasGraph) {
this.graph = new Graph(); this.graph = new Graph();
} }
this.socket.addEventListener( 'open', ( e ) => { this.socket.addEventListener( 'open', ( e ) => {
this.send( { action: 'init' } ); this.send( { action: 'init' } );
} ); } );
// request close before unloading // request close before unloading
window.addEventListener('beforeunload', function(){ window.addEventListener('beforeunload', function(){
panopticon.socket.close(); panopticon.socket.close();
@ -102,7 +102,7 @@ class Panopticon {
console.log("Websocket connected") console.log("Websocket connected")
return; return;
} }
let msg = JSON.parse( e.data ); let msg = JSON.parse( e.data );
if ( typeof msg['alert'] !== 'undefined' ) { if ( typeof msg['alert'] !== 'undefined' ) {
alert( msg['alert'] ); alert( msg['alert'] );
@ -112,9 +112,9 @@ class Panopticon {
console.error( "not a valid message: " + e.data ); console.error( "not a valid message: " + e.data );
return; return;
} }
console.debug(msg); console.debug(msg);
switch ( msg['action'] ) { switch ( msg['action'] ) {
case 'status': case 'status':
@ -134,28 +134,28 @@ class Panopticon {
} }
} ); } );
} }
updateSelectedHugvey() { updateSelectedHugvey() {
let hv = null; let hv = null;
if(this.hugveys.selectedId) { if(this.hugveys.selectedId) {
hv = this.getHugvey(this.hugveys.selectedId); hv = this.getHugvey(this.hugveys.selectedId);
if(this.hasGraph) { if(this.hasGraph) {
if(hv.language && this.graph.language_code != hv.language) { if(hv.language && this.graph.language_code != hv.language) {
this.loadNarrative(hv.language); this.loadNarrative(hv.language);
} }
} }
// let varEl = document.getElementById("variables"); // let varEl = document.getElementById("variables");
// varEl.innerHTML = ""; // varEl.innerHTML = "";
} }
if(this.hasGraph) { if(this.hasGraph) {
this.graph.updateHugveyStatus(hv); this.graph.updateHugveyStatus(hv);
} }
} }
getHugvey(id) { getHugvey(id) {
for(let hv of this.hugveys.hugveys) { for(let hv of this.hugveys.hugveys) {
if(hv.id == id) { if(hv.id == id) {
@ -206,7 +206,7 @@ class Panopticon {
let graph = this.graph; let graph = this.graph;
req.addEventListener( "load", function( e ) { req.addEventListener( "load", function( e ) {
graph.loadData( JSON.parse( this.response ), code ); graph.loadData( JSON.parse( this.response ), code );
// console.log(, e); // console.log(, e);
} ); } );
req.open( "GET", "/local/" + file ); req.open( "GET", "/local/" + file );
req.send(); req.send();
@ -236,7 +236,7 @@ class Panopticon {
console.log("Light", hv_id, light_id); console.log("Light", hv_id, light_id);
this.send( { action: 'change_light', hugvey: hv_id, light_id: light_id } ); this.send( { action: 'change_light', hugvey: hv_id, light_id: light_id } );
} }
playFromSelected(msg_id, reloadStory) { playFromSelected(msg_id, reloadStory) {
if(!this.hugveys.selectedId) { if(!this.hugveys.selectedId) {
alert('No hugvey selected'); alert('No hugvey selected');
@ -337,17 +337,17 @@ class Graph {
// used eg. after a condition creation. // used eg. after a condition creation.
this.showMsg( this.selectedMsg ); this.showMsg( this.selectedMsg );
} }
getAudioUrlForMsg(msg) { getAudioUrlForMsg(msg) {
let isVariable = msg['text'].includes('$') ? '1' : '0'; let isVariable = msg['text'].includes('$') ? '1' : '0';
let lang = panopticon.graph.language_code; let lang = panopticon.graph.language_code;
return `http://localhost:8888/voice?text=${encodeURIComponent(msg['text'])}&variable=${isVariable}&lang=${lang}&filename=0`; return `http://localhost:8888/voice?text=${encodeURIComponent(msg['text'])}&variable=${isVariable}&lang=${lang}&filename=0`;
} }
getConfig() { getConfig() {
} }
getNumericId(prefix) { getNumericId(prefix) {
let id, i = 0; let id, i = 0;
let hasId= function(a, id) { let hasId= function(a, id) {
@ -362,10 +362,10 @@ class Graph {
id = prefix + i; id = prefix + i;
i++; i++;
} while(hasId(this.data, id)) } while(hasId(this.data, id))
return id; return id;
} }
createDiversion(type) { createDiversion(type) {
let div = { let div = {
"@id": this.getNumericId(this.language_code.substring( 0, 2 ) + `-div-${type}#`), "@id": this.getNumericId(this.language_code.substring( 0, 2 ) + `-div-${type}#`),
@ -373,7 +373,7 @@ class Graph {
'type': type, 'type': type,
'params': {} 'params': {}
} }
if(type == 'no_response') { if(type == 'no_response') {
div['params']['consecutiveSilences'] = 3; div['params']['consecutiveSilences'] = 3;
div['params']['timesOccured'] = 0; div['params']['timesOccured'] = 0;
@ -399,33 +399,33 @@ class Graph {
div['params']['msgId'] = ""; div['params']['msgId'] = "";
} }
else if(type == 'repeat') { else if(type == 'repeat') {
div['params']['regex'] = "can you repeat that\\?"; div['params']['regex'] = "can you repeat that\\?";
} else { } else {
console.log("invalid type", type); console.log("invalid type", type);
alert('invalid type for diversion'); alert('invalid type for diversion');
} }
if(type != 'repeat' && type != 'interrupt') { if(type != 'repeat' && type != 'interrupt') {
div['params']['notAfterMsgId'] = ""; div['params']['notAfterMsgId'] = "";
} }
this.data.push( div ); this.data.push( div );
this.updateFromData(); this.updateFromData();
this.build(); this.build();
this.showDiversions(); this.showDiversions();
return msg; return msg;
} }
deleteDiversion(div) { deleteDiversion(div) {
this._rmNode( div ); this._rmNode( div );
this.showDiversions( ); this.showDiversions( );
} }
showDiversions( ) { showDiversions( ) {
let msgEl = document.getElementById( 'msg' ); let msgEl = document.getElementById( 'msg' );
msgEl.innerHTML = ""; msgEl.innerHTML = "";
let divsNoResponse =[], divsRepeat = [], divsReplyContains = [], divsTimeouts = [], divsInterrupts = []; let divsNoResponse =[], divsRepeat = [], divsReplyContains = [], divsTimeouts = [], divsInterrupts = [];
for(let div of this.diversions) { for(let div of this.diversions) {
@ -448,7 +448,7 @@ class Graph {
}}, ...notMsgOptions) }}, ...notMsgOptions)
); );
} }
if(div['type'] == 'no_response') { if(div['type'] == 'no_response') {
let returnAttrs = { let returnAttrs = {
'type': 'checkbox', 'type': 'checkbox',
@ -468,7 +468,7 @@ class Graph {
} }
msgOptions.push(crel('option', optionParams , startMsg['@id'])); msgOptions.push(crel('option', optionParams , startMsg['@id']));
} }
divsNoResponse.push(crel( divsNoResponse.push(crel(
'div', { 'div', {
'class': 'diversion', 'class': 'diversion',
@ -539,7 +539,7 @@ class Graph {
} }
msgOptions.push(crel('option', optionParams , startMsg['@id'])); msgOptions.push(crel('option', optionParams , startMsg['@id']));
} }
divsReplyContains.push(crel( divsReplyContains.push(crel(
'div', { 'div', {
'class': 'diversion', 'class': 'diversion',
@ -606,7 +606,7 @@ class Graph {
), ),
notAfterMsgIdEl notAfterMsgIdEl
)); ));
} }
if(div['type'] == 'timeout') { if(div['type'] == 'timeout') {
let returnAttrs = { let returnAttrs = {
'type': 'checkbox', 'type': 'checkbox',
@ -617,7 +617,7 @@ class Graph {
if(div['params']['returnAfterStrand']) { if(div['params']['returnAfterStrand']) {
returnAttrs['checked'] = 'checked'; returnAttrs['checked'] = 'checked';
} }
let totalOrLocalAttrs = { let totalOrLocalAttrs = {
'type': 'checkbox', 'type': 'checkbox',
'on': { 'on': {
@ -627,7 +627,7 @@ class Graph {
if(div['params']['fromLastMessage']) { if(div['params']['fromLastMessage']) {
totalOrLocalAttrs['checked'] = 'checked'; totalOrLocalAttrs['checked'] = 'checked';
} }
let msgOptions = [crel('option',"")]; let msgOptions = [crel('option',"")];
let starts = this.messages.filter( m => m.hasOwnProperty('start') && m['start'] == true); let starts = this.messages.filter( m => m.hasOwnProperty('start') && m['start'] == true);
for(let startMsg of starts) { for(let startMsg of starts) {
@ -637,7 +637,7 @@ class Graph {
} }
msgOptions.push(crel('option', optionParams , startMsg['@id'])); msgOptions.push(crel('option', optionParams , startMsg['@id']));
} }
divsTimeouts.push(crel( divsTimeouts.push(crel(
'div', { 'div', {
'class': 'diversion', 'class': 'diversion',
@ -734,7 +734,7 @@ class Graph {
} }
msgOptions.push(crel('option', optionParams , startMsg['@id'])); msgOptions.push(crel('option', optionParams , startMsg['@id']));
} }
divsInterrupts.push(crel( divsInterrupts.push(crel(
'div', {'class': 'diversion'}, 'div', {'class': 'diversion'},
crel('h3', div['@id']), crel('h3', div['@id']),
@ -753,9 +753,9 @@ class Graph {
)); ));
} }
} }
console.log(divsReplyContains, divsNoResponse, divsRepeat, divsTimeouts, divsInterrupts); console.log(divsReplyContains, divsNoResponse, divsRepeat, divsTimeouts, divsInterrupts);
let divEl = crel( let divEl = crel(
'div', 'div',
{ {
@ -797,7 +797,7 @@ class Graph {
'on': { 'on': {
'click': (e) => this.createDiversion('repeat') 'click': (e) => this.createDiversion('repeat')
} }
}, },
'New case for repeat' 'New case for repeat'
) )
), ),
@ -810,7 +810,7 @@ class Graph {
'on': { 'on': {
'click': (e) => this.createDiversion('timeout') 'click': (e) => this.createDiversion('timeout')
} }
}, },
'New case for timeout' 'New case for timeout'
) )
) )
@ -824,12 +824,12 @@ class Graph {
// 'on': { // 'on': {
// 'click': (e) => this.createDiversion('interrupt') // 'click': (e) => this.createDiversion('interrupt')
// } // }
// }, // },
// 'New case for Interrupt' // 'New case for Interrupt'
// ) // )
// ) // )
); );
msgEl.appendChild(divEl); msgEl.appendChild(divEl);
} }
@ -891,19 +891,19 @@ class Graph {
}) })
) )
); );
document.getElementById("interface").appendChild(configEl); document.getElementById("interface").appendChild(configEl);
} }
showMsg( msg ) { showMsg( msg ) {
let msgEl = document.getElementById( 'msg' ); let msgEl = document.getElementById( 'msg' );
msgEl.innerHTML = ""; msgEl.innerHTML = "";
if(msg == null){ if(msg == null){
return; return;
} }
let startAttributes = { let startAttributes = {
'name': msg['@id'] + '-start', 'name': msg['@id'] + '-start',
// 'readonly': 'readonly', // 'readonly': 'readonly',
@ -926,7 +926,7 @@ class Graph {
if ( msg['beginning'] == true ) { if ( msg['beginning'] == true ) {
beginningAttributes['checked'] = 'checked'; beginningAttributes['checked'] = 'checked';
} }
// chapter marker: // chapter marker:
let chapterAttributes = { let chapterAttributes = {
'name': msg['@id'] + '-chapterStart', 'name': msg['@id'] + '-chapterStart',
@ -939,14 +939,14 @@ class Graph {
if ( typeof msg['chapterStart'] !== 'undefined' && msg['chapterStart'] == true ) { if ( typeof msg['chapterStart'] !== 'undefined' && msg['chapterStart'] == true ) {
chapterAttributes['checked'] = 'checked'; chapterAttributes['checked'] = 'checked';
} }
let params = {}; let params = {};
if(msg.hasOwnProperty('params')) { if(msg.hasOwnProperty('params')) {
params = msg['params']; params = msg['params'];
} else { } else {
msg['params'] = {}; msg['params'] = {};
} }
let audioSrcEl = crel('source', {'src': msg['audio'] ? msg['audio']['file'] : this.getAudioUrlForMsg(msg)}); let audioSrcEl = crel('source', {'src': msg['audio'] ? msg['audio']['file'] : this.getAudioUrlForMsg(msg)});
let audioSpan = crel( let audioSpan = crel(
'span', 'span',
@ -1092,7 +1092,7 @@ class Graph {
} }
} ) } )
), ),
// color for beter overview // color for beter overview
crel( 'label', crel( 'label',
@ -1110,9 +1110,9 @@ class Graph {
) )
); );
msgEl.appendChild( msgInfoEl ); msgEl.appendChild( msgInfoEl );
if(panopticon.hugveys.selectedId) { if(panopticon.hugveys.selectedId) {
msgEl.appendChild(crel( msgEl.appendChild(crel(
'div', 'div',
@ -1148,9 +1148,9 @@ class Graph {
"Continue on #" + panopticon.hugveys.selectedId "Continue on #" + panopticon.hugveys.selectedId
) )
)); ));
} }
// let directionHEl = document.createElement('h2'); // let directionHEl = document.createElement('h2');
// directionHEl.innerHTML = "Directions"; // directionHEl.innerHTML = "Directions";
@ -1207,13 +1207,13 @@ class Graph {
'on': { 'on': {
'click': ( e ) => { 'click': ( e ) => {
if(confirm("Do you want to remove this direction and its conditions?")) { if(confirm("Do you want to remove this direction and its conditions?")) {
g.rmDirection( direction ); g.rmDirection( direction );
} }
} }
} }
}, 'disconnect') }, 'disconnect')
); );
for ( let conditionId of direction['conditions'] ) { for ( let conditionId of direction['conditions'] ) {
let condition = this.getNodeById( conditionId ); let condition = this.getNodeById( conditionId );
directionEl.appendChild( this.getEditConditionFormEl( condition, direction ) ); directionEl.appendChild( this.getEditConditionFormEl( condition, direction ) );
@ -1233,7 +1233,7 @@ class Graph {
'click': ( e ) => { 'click': ( e ) => {
if(confirm("Do you want to remove this condition?")) { if(confirm("Do you want to remove this condition?")) {
// console.log('remove condition for direction', condition, direction); // console.log('remove condition for direction', condition, direction);
panopticon.graph.rmCondition( condition, direction ); panopticon.graph.rmCondition( condition, direction );
} }
} }
} }
@ -1251,7 +1251,7 @@ class Graph {
} ); } );
labelLabel.appendChild( labelInput ); labelLabel.appendChild( labelInput );
conditionEl.appendChild( labelLabel ); conditionEl.appendChild( labelLabel );
// for ( let v in condition['vars'] ) { // for ( let v in condition['vars'] ) {
// let varLabel = document.createElement( 'label' ); // let varLabel = document.createElement( 'label' );
@ -1296,14 +1296,14 @@ class Graph {
} }
}; };
} }
getConditionInputsForType( type, conditionId, values ) { getConditionInputsForType( type, conditionId, values ) {
let inputs = []; let inputs = [];
let vars = this.getConditionTypes()[type]; let vars = this.getConditionTypes()[type];
for ( let v in vars ) { for ( let v in vars ) {
let attr = vars[v]; let attr = vars[v];
let inputType = attr.hasOwnProperty('tag') ? attr['tag'] : 'input'; let inputType = attr.hasOwnProperty('tag') ? attr['tag'] : 'input';
attr['name'] = typeof conditionId == 'undefined' ? v : `${conditionId}-vars.${v}`; attr['name'] = typeof conditionId == 'undefined' ? v : `${conditionId}-vars.${v}`;
if(typeof values != 'undefined') { if(typeof values != 'undefined') {
let value = this._getValueForPath(v, values); let value = this._getValueForPath(v, values);
@ -1313,12 +1313,12 @@ class Graph {
} }
attr['value'] = typeof value == 'undefined' ? "": value; attr['value'] = typeof value == 'undefined' ? "": value;
attr['on'] = { attr['on'] = {
'change': this.getEditEventListener() 'change': this.getEditEventListener()
} ; } ;
} else { } else {
// console.log(attr); // console.log(attr);
} }
inputs.push( inputs.push(
crel( 'label', crel( 'label',
crel( 'span', { crel( 'span', {
@ -1339,7 +1339,7 @@ class Graph {
conditionForm.appendChild(i); conditionForm.appendChild(i);
} }
} }
_getValueForPath(path, vars) { _getValueForPath(path, vars) {
path = path.split( '.' ); // use vars.test to set ['vars']['test'] = value path = path.split( '.' ); // use vars.test to set ['vars']['test'] = value
let v = vars; let v = vars;
@ -1359,7 +1359,7 @@ class Graph {
} }
return result; return result;
} }
/** /**
* Save an array path (string) with a value to an object. Used to turn * Save an array path (string) with a value to an object. Used to turn
* strings into nested arrays * strings into nested arrays
@ -1408,7 +1408,7 @@ class Graph {
form.delete( 'type' ); form.delete( 'type' );
let label = form.get( 'label' ); let label = form.get( 'label' );
form.delete( 'label' ); form.delete( 'label' );
// checkboxes to true/false // checkboxes to true/false
let defs = g.getConditionTypes()[type]; let defs = g.getConditionTypes()[type];
// console.log(defs); // console.log(defs);
@ -1419,13 +1419,13 @@ class Graph {
form.set(field, form.has(field)); form.set(field, form.has(field));
} }
} }
let vars = {}; let vars = {};
for ( var pair of form.entries() ) { for ( var pair of form.entries() ) {
// FormData only has strings & blobs, we want booleans: // FormData only has strings & blobs, we want booleans:
if(pair[1] === 'true') pair[1] = true; if(pair[1] === 'true') pair[1] = true;
if(pair[1] === 'false') pair[1] = false; if(pair[1] === 'false') pair[1] = false;
vars = g._formPathToVars(pair[0], pair[1], vars); vars = g._formPathToVars(pair[0], pair[1], vars);
} }
// TODO: checkboxes // TODO: checkboxes
@ -1468,7 +1468,7 @@ class Graph {
return addConditionEl; return addConditionEl;
} }
/** /**
* remove condition from the graph or merely from the given direction * remove condition from the graph or merely from the given direction
* @param {any} condition The condition to remove * @param {any} condition The condition to remove
@ -1483,7 +1483,7 @@ class Graph {
if(pos > -1) { if(pos > -1) {
direction['conditions'].splice(pos, 1); direction['conditions'].splice(pos, 1);
} }
for(let dir of this.directions) { for(let dir of this.directions) {
// console.log('check if condition exists for dir', dir) // console.log('check if condition exists for dir', dir)
if(dir['conditions'].indexOf(id) > -1) { if(dir['conditions'].indexOf(id) > -1) {
@ -1534,14 +1534,14 @@ class Graph {
"afterrunTime": 0.5, "afterrunTime": 0.5,
} }
this.data.push( msg ); this.data.push( msg );
console.log("skip or not to skip?", skipRebuild); console.log("skip or not to skip?", skipRebuild);
if(typeof skipRebuild == 'undefined' || !skipRebuild) { if(typeof skipRebuild == 'undefined' || !skipRebuild) {
this.updateFromData(); this.updateFromData();
this.build(); this.build();
this.selectMsg(msg); this.selectMsg(msg);
} }
return msg; return msg;
} }
@ -1598,7 +1598,7 @@ class Graph {
"conditions": [] "conditions": []
} }
this.data.push( dir ); this.data.push( dir );
let skipDistances; let skipDistances;
// orphaned target and source has no other destinations. We can copy the vertical position: // orphaned target and source has no other destinations. We can copy the vertical position:
if(this.getDirectionsFrom( source ).length < 1 && this.getDirectionsFrom( target ).length < 1 && this.getDirectionsTo( target ).length < 1) { if(this.getDirectionsFrom( source ).length < 1 && this.getDirectionsFrom( target ).length < 1 && this.getDirectionsTo( target ).length < 1) {
@ -1607,11 +1607,11 @@ class Graph {
let d = [distance[0] + 1, distance[1]]; let d = [distance[0] + 1, distance[1]];
// create a distance based on source's position // create a distance based on source's position
// this saves us from running the slow calculateDistancesFromStart // this saves us from running the slow calculateDistancesFromStart
this.distances[target['@id']] = d; this.distances[target['@id']] = d;
} else { } else {
skipDistances = false; skipDistances = false;
} }
this.updateFromData(skipDistances); this.updateFromData(skipDistances);
this.build(); this.build();
return dir; return dir;
@ -1626,18 +1626,18 @@ class Graph {
this.addMsg(); this.addMsg();
this.build(); this.build();
} }
createConnectedMsg(sourceMsg) { createConnectedMsg(sourceMsg) {
console.time('createConnected'); console.time('createConnected');
console.time("Add"); console.time("Add");
let newMsg = this.addMsg(true); // skipRebuild = true, as addDirection() already rebuilds the graph let newMsg = this.addMsg(true); // skipRebuild = true, as addDirection() already rebuilds the graph
this.getNodeById(newMsg['@id']).y = this.getNodeById(sourceMsg['@id']).y; this.getNodeById(newMsg['@id']).y = this.getNodeById(sourceMsg['@id']).y;
if(this.getNodeById(sourceMsg['@id']).hasOwnProperty('color')){ if(this.getNodeById(sourceMsg['@id']).hasOwnProperty('color')){
this.getNodeById(newMsg['@id']).color = this.getNodeById(sourceMsg['@id']).color this.getNodeById(newMsg['@id']).color = this.getNodeById(sourceMsg['@id']).color
} }
console.timeEnd("Add"); console.timeEnd("Add");
console.time("direction"); console.time("direction");
this.addDirection(sourceMsg, newMsg); this.addDirection(sourceMsg, newMsg);
console.timeEnd("direction"); console.timeEnd("direction");
@ -1664,15 +1664,15 @@ class Graph {
let graph = this; let graph = this;
let el = function( e ) { let el = function( e ) {
console.info("Changed", e); console.info("Changed", e);
let parts = e.srcElement.name.split( '-' ); let parts = e.target.name.split( '-' );
let field = parts.pop(); let field = parts.pop();
let id = parts.join('-'); let id = parts.join('-');
let node = graph.getNodeById( id ); let node = graph.getNodeById( id );
let path = field.split( '.' ); // use vars.test to set ['vars']['test'] = value let path = field.split( '.' ); // use vars.test to set ['vars']['test'] = value
var res = node; var res = node;
let value = e.srcElement.value let value = e.target.value
if(e.srcElement.type == 'checkbox') { if(e.target.type == 'checkbox') {
value = e.srcElement.checked; value = e.target.checked;
} }
for ( var i = 0; i < path.length; i++ ) { for ( var i = 0; i < path.length; i++ ) {
if ( i == ( path.length - 1 ) ) { if ( i == ( path.length - 1 ) ) {
@ -1685,7 +1685,7 @@ class Graph {
// node[field] = e.srcElement.value; // node[field] = e.srcElement.value;
graph.build(); graph.build();
if(typeof callback !== 'undefined'){ if(typeof callback !== 'undefined'){
callback(); callback();
} }
@ -1756,11 +1756,11 @@ class Graph {
console.info("Save json", formData ); console.info("Save json", formData );
var request = new XMLHttpRequest(); var request = new XMLHttpRequest();
request.open( "POST", "http://localhost:8888/upload" ); request.open( "POST", "http://localhost:8888/upload" );
if(callback) { if(callback) {
request.addEventListener( "load", callback); request.addEventListener( "load", callback);
} }
request.send( formData ); request.send( formData );
} }
@ -1776,13 +1776,13 @@ class Graph {
this.directions = this.data.filter(( node ) => node['@type'] == 'Direction' ); this.directions = this.data.filter(( node ) => node['@type'] == 'Direction' );
this.conditions = this.data.filter(( node ) => node['@type'] == 'Condition' ); this.conditions = this.data.filter(( node ) => node['@type'] == 'Condition' );
this.diversions = this.data.filter(( node ) => node['@type'] == 'Diversion' ); this.diversions = this.data.filter(( node ) => node['@type'] == 'Diversion' );
let configurations = this.data.filter(( node ) => node['@type'] == 'Configuration' ); let configurations = this.data.filter(( node ) => node['@type'] == 'Configuration' );
this.configuration = configurations.length > 0 ? configurations[0] : { this.configuration = configurations.length > 0 ? configurations[0] : {
"@id": "config", "@id": "config",
"@type": "Configuration" "@type": "Configuration"
}; };
document.getElementById('current_lang').innerHTML = ""; document.getElementById('current_lang').innerHTML = "";
document.getElementById('current_lang').appendChild(crel('span', { document.getElementById('current_lang').appendChild(crel('span', {
'class': 'flag-icon ' + this.language_code 'class': 'flag-icon ' + this.language_code
@ -1790,7 +1790,7 @@ class Graph {
let storyEl = document.getElementById('story'); let storyEl = document.getElementById('story');
storyEl.classList.remove(... panopticon.languages.map((l) => l['code'])) storyEl.classList.remove(... panopticon.languages.map((l) => l['code']))
storyEl.classList.add(this.language_code); storyEl.classList.add(this.language_code);
if(typeof skipDistances == 'undefined' || !skipDistances) { if(typeof skipDistances == 'undefined' || !skipDistances) {
this.distances = this.calculateDistancesFromStart(); this.distances = this.calculateDistancesFromStart();
} }
@ -1798,7 +1798,7 @@ class Graph {
// save state; // save state;
this.saveState(); this.saveState();
} }
updateHugveyStatus(hv) { updateHugveyStatus(hv) {
let els = document.getElementsByClassName('beenHit'); let els = document.getElementsByClassName('beenHit');
while(els.length > 0) { while(els.length > 0) {
@ -1807,11 +1807,11 @@ class Graph {
if(!hv || typeof hv['history'] == 'undefined') { if(!hv || typeof hv['history'] == 'undefined') {
return; return;
} }
if(hv['history'].hasOwnProperty('messages')){ if(hv['history'].hasOwnProperty('messages')){
for(let msg of hv['history']['messages']) { for(let msg of hv['history']['messages']) {
document.getElementById(msg[0]['id']).classList.add('beenHit'); document.getElementById(msg[0]['id']).classList.add('beenHit');
} }
} }
if(hv['history'].hasOwnProperty('directions')){ if(hv['history'].hasOwnProperty('directions')){
for(let msg of hv['history']['directions']) { for(let msg of hv['history']['directions']) {
@ -1844,7 +1844,7 @@ class Graph {
return fx; return fx;
}).strength(50)) }).strength(50))
.force( "forceY", d3.forceY(function(m){ .force( "forceY", d3.forceY(function(m){
// if(panopticon.graph.distances[m['@id']] !== null ) // if(panopticon.graph.distances[m['@id']] !== null )
// console.log(panopticon.graph.distances[m['@id']][1]); // console.log(panopticon.graph.distances[m['@id']][1]);
let fy = panopticon.graph.distances[m['@id']] !== null ? panopticon.graph.distances[m['@id']][1] * panopticon.graph.nodeSize * 3: 0 let fy = panopticon.graph.distances[m['@id']] !== null ? panopticon.graph.distances[m['@id']][1] * panopticon.graph.nodeSize * 3: 0
// console.log('fx', m['@id'], panopticon.graph.distances[m['@id']], fx); // console.log('fx', m['@id'], panopticon.graph.distances[m['@id']], fx);
@ -1859,7 +1859,7 @@ class Graph {
.selectAll( "g" ) .selectAll( "g" )
.data( this.messages, n => n['@id'] ) .data( this.messages, n => n['@id'] )
; ;
// Update existing nodes // Update existing nodes
let newNode = node.enter(); let newNode = node.enter();
@ -1874,7 +1874,7 @@ class Graph {
.attr( 'r', this.nodeSize ) .attr( 'r', this.nodeSize )
// .text(d => d.id) // .text(d => d.id)
; ;
let textId = newNodeG.append( "text" ).attr( 'class', 'msg_id' ); let textId = newNodeG.append( "text" ).attr( 'class', 'msg_id' );
let textContent = newNodeG.append( "text" ).attr( 'class', 'msg_txt' ); let textContent = newNodeG.append( "text" ).attr( 'class', 'msg_txt' );
let statusIcon = newNodeG.append( "image" ) let statusIcon = newNodeG.append( "image" )
@ -1888,7 +1888,7 @@ class Graph {
// remove // remove
node.exit().remove(); node.exit().remove();
node = node.merge( newNodeG ); node = node.merge( newNodeG );
// for all existing nodes: // for all existing nodes:
node.attr( 'class', msg => { node.attr( 'class', msg => {
@ -1903,9 +1903,9 @@ class Graph {
return classes.join( ' ' ); return classes.join( ' ' );
} ) } )
.on(".drag", null) .on(".drag", null)
.call( .call(
d3.drag( this.simulation ) d3.drag( this.simulation )
.on("start", function(d){ .on("start", function(d){
if (!d3.event.active) panopticon.graph.simulation.alphaTarget(0.3).restart(); if (!d3.event.active) panopticon.graph.simulation.alphaTarget(0.3).restart();
@ -1922,9 +1922,9 @@ class Graph {
d.fy = null; d.fy = null;
}) })
// .container(document.getElementById('container')) // .container(document.getElementById('container'))
); );
node.select('circle').attr('style', (d) => 'fill: ' + (d.hasOwnProperty('color') ? d['color'] : '#77618e')); node.select('circle').attr('style', (d) => 'fill: ' + (d.hasOwnProperty('color') ? d['color'] : '#77618e'));
let link = this.linkG let link = this.linkG
@ -1934,7 +1934,7 @@ class Graph {
let newLink = link.enter() let newLink = link.enter()
.append( "line" ) .append( "line" )
; ;
//remove //remove
link.exit().remove(); link.exit().remove();
link = link.merge( newLink ); link = link.merge( newLink );
@ -2019,7 +2019,7 @@ class Graph {
} }
return this.svg.node(); return this.svg.node();
} }
calculateDistancesFromStart() { calculateDistancesFromStart() {
console.time('calculateDistancesFromStart'); console.time('calculateDistancesFromStart');
let starts = this.messages.filter( m => m.hasOwnProperty('start') && m['start'] == true); let starts = this.messages.filter( m => m.hasOwnProperty('start') && m['start'] == true);
@ -2027,26 +2027,26 @@ class Graph {
console.error("No start set"); console.error("No start set");
return; return;
} }
//initiate distances //initiate distances
let distances = {}; let distances = {};
for(let msg of this.messages) { for(let msg of this.messages) {
// distances[msg['@id']] = msg === startMsg ? 0 : null; // distances[msg['@id']] = msg === startMsg ? 0 : null;
distances[msg['@id']] = null; distances[msg['@id']] = null;
} }
let targetsPerMsg = {}; let targetsPerMsg = {};
let sourcesPerMsg = {}; let sourcesPerMsg = {};
// console.log("dir", this.directions); // console.log("dir", this.directions);
for(let direction of this.directions) { for(let direction of this.directions) {
let from = typeof direction['source'] == "string" ? direction['source'] : direction['source']['@id']; let from = typeof direction['source'] == "string" ? direction['source'] : direction['source']['@id'];
let to = typeof direction['target'] == "string" ? direction['target'] : direction['target']['@id']; let to = typeof direction['target'] == "string" ? direction['target'] : direction['target']['@id'];
if(!targetsPerMsg.hasOwnProperty(from)) { if(!targetsPerMsg.hasOwnProperty(from)) {
targetsPerMsg[from] = []; targetsPerMsg[from] = [];
} }
targetsPerMsg[from].push(to); targetsPerMsg[from].push(to);
if(!sourcesPerMsg.hasOwnProperty(to)) { if(!sourcesPerMsg.hasOwnProperty(to)) {
sourcesPerMsg[to] = []; sourcesPerMsg[to] = [];
@ -2061,21 +2061,21 @@ class Graph {
// end of trail // end of trail
return yPos; return yPos;
} }
let i = 0, y =0; let i = 0, y =0;
for(let childMsgId of msgsPerMsg[msgId]) { for(let childMsgId of msgsPerMsg[msgId]) {
if(distances[childMsgId] !== null){ if(distances[childMsgId] !== null){
continue; continue;
} }
if(distances[childMsgId] === null || (goingDown && distances[childMsgId][0] > depth)) { if(distances[childMsgId] === null || (goingDown && distances[childMsgId][0] > depth)) {
if(distances[childMsgId] === null) { if(distances[childMsgId] === null) {
if(i > 0){ if(i > 0){
yPos++; yPos++;
} }
i++; i++;
console.log('set for id', childMsgId, goingDown, depth, yPos); console.log('set for id', childMsgId, goingDown, depth, yPos);
distances[childMsgId] = [depth, yPos]; distances[childMsgId] = [depth, yPos];
@ -2093,7 +2093,7 @@ class Graph {
if(distances[childMsgId] === null) { if(distances[childMsgId] === null) {
distances[childMsgId] = [depth, yPos]; distances[childMsgId] = [depth, yPos];
} }
// console.log('a', depth); // console.log('a', depth);
yPos = traverseMsg(childMsgId, depth - 1, goingDown, yPos); yPos = traverseMsg(childMsgId, depth - 1, goingDown, yPos);
} else { } else {
@ -2101,7 +2101,7 @@ class Graph {
} }
} }
// if( i == 0 && y == 1) { // if( i == 0 && y == 1) {
// // we reached an item that branches back into the tree // // we reached an item that branches back into the tree
// return yPos -1; // return yPos -1;
@ -2109,7 +2109,7 @@ class Graph {
// console.log('yPos',msgId,yPos); // console.log('yPos',msgId,yPos);
return yPos; return yPos;
} }
let yPos = 0; let yPos = 0;
console.time('step1'); console.time('step1');
for(let startMsg of starts) { for(let startMsg of starts) {
@ -2135,7 +2135,7 @@ class Graph {
console.timeEnd('polish: '+ msgId); console.timeEnd('polish: '+ msgId);
} }
console.timeEnd('step2'); console.timeEnd('step2');
// let additionalsDepth = 0; // let additionalsDepth = 0;
//// now the secondary strands: //// now the secondary strands:
// for(let msgId in distances) { // for(let msgId in distances) {
@ -2145,11 +2145,11 @@ class Graph {
// } // }
// distances[msgId] = additionalsDepth; // distances[msgId] = additionalsDepth;
// traverseMsg(msgId, additionalsDepth+1, true); // traverseMsg(msgId, additionalsDepth+1, true);
// //
// } // }
console.timeEnd("calculateDistancesFromStart"); console.timeEnd("calculateDistancesFromStart");
return distances; return distances;
} }
} }
// //
// //