better handling for errors, don't send filler text to server
[scpubgit/stemmatology.git] / stemmaweb / root / js / relationship.js
CommitLineData
aff524fc 1var MARGIN=30;
2var svg_root = null;
3var svg_root_element = null;
4var start_element_height = 0;
5var reltypes = {};
a8928d1d 6var readingdata = {};
aff524fc 7
7fd1d97a 8function getTextPath() {
aff524fc 9 var currpath = window.location.pathname;
93daee83 10 // Get rid of trailing slash
7fd1d97a 11 if( currpath.lastIndexOf('/') == currpath.length - 1 ) {
12 currpath = currpath.slice( 0, currpath.length - 1)
13 };
93daee83 14 // Get rid of query parameters
15 if( currpath.lastIndexOf('?') != -1 ) {
16 currpath = currpath.slice( 0, currpath.lastIndexOf('?') );
17 };
7fd1d97a 18 var path_elements = currpath.split('/');
19 var textid = path_elements.pop();
20 var basepath = path_elements.join( '/' );
21 var path_parts = [ basepath, textid ];
22 return path_parts;
581aee24 23}
24
72874569 25function getRelativePath() {
26 var path_parts = getTextPath();
27 return path_parts[0];
28}
29
a8928d1d 30function getTextURL( which ) {
72874569 31 var path_parts = getTextPath();
a8928d1d 32 return path_parts[0] + '/' + path_parts[1] + '/' + which;
33}
34
35function getReadingURL( reading_id ) {
36 var path_parts = getTextPath();
37 return path_parts[0] + '/' + path_parts[1] + '/reading/' + reading_id;
581aee24 38}
39
28f2ef34 40// Make an XML ID into a valid selector
41function jq(myid) {
42 return '#' + myid.replace(/(:|\.)/g,'\\$1');
43}
44
1301020e 45// Actions for opening the reading panel
46function node_dblclick_listener( evt ) {
47 // Open the reading dialogue for the given node.
48 // First get the reading info
49 var reading_id = $(this).attr('id');
50 var reading_info = readingdata[reading_id];
51 // and then populate the dialog box with it.
52 // Set the easy properties first
53 $('#reading-form').dialog( 'option', 'title', 'Reading information for "' + reading_info['text'] + '"' );
54 $('#reading_id').val( reading_id );
397f3cf4 55 toggle_checkbox( $('#reading_is_nonsense'), reading_info['is_nonsense'] );
56 toggle_checkbox( $('#reading_grammar_invalid'), reading_info['grammar_invalid'] );
1301020e 57 // Use .text as a backup for .normal_form
58 var normal_form = reading_info['normal_form'];
59 if( !normal_form ) {
60 normal_form = reading_info['text'];
61 }
62 var nfboxsize = 10;
63 if( normal_form.length > 9 ) {
64 nfboxsize = normal_form.length + 1;
65 }
66 $('#reading_normal_form').attr( 'size', nfboxsize )
67 $('#reading_normal_form').val( normal_form );
68 // Now do the morphological properties.
3ba238d4 69 morphology_form( reading_info['lexemes'] );
1301020e 70 // and then open the dialog.
3ba238d4 71 $('#reading-form').dialog("open");
72}
73
397f3cf4 74function toggle_checkbox( box, value ) {
75 if( value == null ) {
76 value = false;
77 }
78 box.attr('checked', value );
79}
80
3ba238d4 81function morphology_form ( lexlist ) {
1301020e 82 $('#morphology').empty();
3ba238d4 83 $.each( lexlist, function( idx, lex ) {
1301020e 84 var morphoptions = [];
fedee8da 85 if( 'wordform_matchlist' in lex ) {
86 $.each( lex['wordform_matchlist'], function( tdx, tag ) {
87 var tagstr = stringify_wordform( tag );
88 morphoptions.push( tagstr );
89 });
90 }
1301020e 91 var formtag = 'morphology_' + idx;
e31609d3 92 var formstr = '';
fedee8da 93 if( 'form' in lex ) {
e31609d3 94 formstr = stringify_wordform( lex['form'] );
1301020e 95 }
e31609d3 96 var form_morph_elements = morph_elements(
97 formtag, lex['string'], formstr, morphoptions );
1301020e 98 $.each( form_morph_elements, function( idx, el ) {
99 $('#morphology').append( el );
100 });
101 });
1301020e 102}
103
104function stringify_wordform ( tag ) {
fedee8da 105 if( tag ) {
106 var elements = tag.split(' // ');
107 return elements[1] + ' // ' + elements[2];
108 }
109 return ''
1301020e 110}
111
e31609d3 112function morph_elements ( formtag, formtxt, currform, morphoptions ) {
113 var clicktag = '(Click to select)';
114 if ( !currform ) {
115 currform = clicktag;
116 }
1301020e 117 var formlabel = $('<label/>').attr( 'id', 'label_' + formtag ).attr(
e31609d3 118 'for', 'reading_' + formtag ).text( formtxt + ': ' );
1301020e 119 var forminput = $('<input/>').attr( 'id', 'reading_' + formtag ).attr(
3ba238d4 120 'name', 'reading_' + formtag ).attr( 'size', '50' ).attr(
121 'class', 'reading_morphology' ).val( currform );
e31609d3 122 forminput.autocomplete({ source: morphoptions, minLength: 0 });
123 forminput.focus( function() {
124 if( $(this).val() == clicktag ) {
125 $(this).val('');
126 }
127 $(this).autocomplete('search', '')
128 });
1301020e 129 var morphel = [ formlabel, forminput, $('<br/>') ];
130 return morphel;
131}
132
ea35b6bb 133function color_inactive ( el ) {
134 var reading_id = $(el).parent().attr('id');
135 var reading_info = readingdata[reading_id];
136 // If the reading info has any non-disambiguated lexemes, color it yellow;
137 // otherwise color it green.
138 $(el).attr( {stroke:'green', fill:'#b3f36d'} );
f52467de 139 if( reading_info ) {
140 $.each( reading_info['lexemes'], function ( idx, lex ) {
141 if( !lex['is_disambiguated'] || lex['is_disambiguated'] == 0 ) {
142 $(el).attr( {stroke:'orange', fill:'#fee233'} );
143 }
144 });
145 }
ea35b6bb 146}
147
4aed7cc5 148function relemmatize () {
149 // Send the reading for a new lemmatization and reopen the form.
2f54cbcd 150 $('#relemmatize_pending').show();
4aed7cc5 151 var reading_id = $('#reading_id').val()
152 ncpath = getReadingURL( reading_id );
153 form_values = {
154 'normal_form': $('#reading_normal_form').val(),
155 'relemmatize': 1 };
156 var jqjson = $.post( ncpath, form_values, function( data ) {
157 // Update the form with the return
158 if( 'id' in data ) {
159 // We got back a good answer. Stash it
160 readingdata[reading_id] = data;
161 // and regenerate the morphology form.
162 morphology_form( data['lexemes'] );
163 } else {
164 alert("Could not relemmatize as requested: " + data['error']);
165 }
2f54cbcd 166 $('#relemmatize_pending').hide();
4aed7cc5 167 });
168}
169
1301020e 170// Initialize the SVG once it exists
581aee24 171function svgEnlargementLoaded() {
63213207 172 //Give some visual evidence that we are working
173 $('#loading_overlay').show();
174 lo_height = $("#enlargement_container").outerHeight();
175 lo_width = $("#enlargement_container").outerWidth();
176 $("#loading_overlay").height( lo_height );
177 $("#loading_overlay").width( lo_width );
178 $("#loading_overlay").offset( $("#enlargement_container").offset() );
179 $("#loading_message").offset(
180 { 'top': lo_height / 2 - $("#loading_message").height() / 2,
181 'left': lo_width / 2 - $("#loading_message").width() / 2 });
72874569 182 //Set viewbox widht and height to widht and height of $('#svgenlargement svg').
aff524fc 183 $('#update_workspace_button').data('locked', false);
184 $('#update_workspace_button').css('background-position', '0px 44px');
72874569 185 //This is essential to make sure zooming and panning works properly.
ea35b6bb 186 var rdgpath = getTextURL( 'readings' );
187 $.getJSON( rdgpath, function( data ) {
188 readingdata = data;
189 $('#svgenlargement ellipse').each( function( i, el ) { color_inactive( el ) });
190 });
1301020e 191 $('#svgenlargement ellipse').parent().dblclick( node_dblclick_listener );
72874569 192 var graph_svg = $('#svgenlargement svg');
193 var svg_g = $('#svgenlargement svg g')[0];
aff524fc 194 if (!svg_g) return;
72874569 195 svg_root = graph_svg.svg().svg('get').root();
aff524fc 196
197 // Find the real root and ignore any text nodes
198 for (i = 0; i < svg_root.childNodes.length; ++i) {
199 if (svg_root.childNodes[i].nodeName != '#text') {
200 svg_root_element = svg_root.childNodes[i];
201 break;
202 }
203 }
204
72874569 205 svg_root.viewBox.baseVal.width = graph_svg.attr( 'width' );
206 svg_root.viewBox.baseVal.height = graph_svg.attr( 'height' );
207 //Now set scale and translate so svg height is about 150px and vertically centered in viewbox.
208 //This is just to create a nice starting enlargement.
209 var initial_svg_height = 250;
210 var scale = initial_svg_height/graph_svg.attr( 'height' );
211 var additional_translate = (graph_svg.attr( 'height' ) - initial_svg_height)/(2*scale);
212 var transform = svg_g.getAttribute('transform');
213 var translate = parseFloat( transform.match( /translate\([^\)]*\)/ )[0].split('(')[1].split(' ')[1].split(')')[0] );
214 translate += additional_translate;
215 var transform = 'rotate(0) scale(' + scale + ') translate(4 ' + translate + ')';
216 svg_g.setAttribute('transform', transform);
217 //used to calculate min and max zoom level:
ea35b6bb 218 start_element_height = $('#__START__').children('ellipse')[0].getBBox().height;
63213207 219 add_relations( function() { $('#loading_overlay').hide(); });
7fd1d97a 220}
221
63213207 222function add_relations( callback_fn ) {
72874569 223 var basepath = getRelativePath();
a8928d1d 224 var textrelpath = getTextURL( 'relationships' );
72874569 225 $.getJSON( basepath + '/definitions', function(data) {
7fd1d97a 226 var rel_types = data.types.sort();
72874569 227 $.getJSON( textrelpath,
7fd1d97a 228 function(data) {
229 $.each(data, function( index, rel_info ) {
230 var type_index = $.inArray(rel_info.type, rel_types);
93daee83 231 var source_found = get_ellipse( rel_info.source );
232 var target_found = get_ellipse( rel_info.target );
233 if( type_index != -1 && source_found.size() && target_found.size() ) {
72874569 234 var relation = relation_manager.create( rel_info.source, rel_info.target, type_index );
235 relation.data( 'type', rel_info.type );
236 relation.data( 'scope', rel_info.scope );
31aaf446 237 relation.data( 'note', rel_info.note );
72874569 238 var node_obj = get_node_obj(rel_info.source);
239 node_obj.set_draggable( false );
240 node_obj.ellipse.data( 'node_obj', null );
241 node_obj = get_node_obj(rel_info.target);
242 node_obj.set_draggable( false );
243 node_obj.ellipse.data( 'node_obj', null );
7fd1d97a 244 }
63213207 245 });
246 callback_fn.call();
72874569 247 });
7fd1d97a 248 });
581aee24 249}
250
251function get_ellipse( node_id ) {
28f2ef34 252 return $( jq( node_id ) + ' ellipse');
581aee24 253}
254
255function get_node_obj( node_id ) {
72874569 256 var node_ellipse = get_ellipse( node_id );
257 if( node_ellipse.data( 'node_obj' ) == null ) {
258 node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
259 };
260 return node_ellipse.data( 'node_obj' );
581aee24 261}
262
581aee24 263function node_obj(ellipse) {
264 this.ellipse = ellipse;
265 var self = this;
266
267 this.x = 0;
268 this.y = 0;
269 this.dx = 0;
270 this.dy = 0;
271 this.node_elements = node_elements_for(self.ellipse);
272
273 this.get_id = function() {
28f2ef34 274 return $(self.ellipse).parent().attr('id')
581aee24 275 }
276
277 this.set_draggable = function( draggable ) {
278 if( draggable ) {
0fa07e25 279 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
280 $(self.ellipse).parent().mousedown( this.mousedown_listener );
281 $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
282 self.ellipse.siblings('text').attr('class', 'noselect draggable');
581aee24 283 } else {
0fa07e25 284 self.ellipse.siblings('text').attr('class', '');
ea35b6bb 285 $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' ).unbind( 'mousedown' );
286 color_inactive( self.ellipse );
581aee24 287 }
288 }
289
290 this.mousedown_listener = function(evt) {
291 evt.stopPropagation();
292 self.x = evt.clientX;
293 self.y = evt.clientY;
294 $('body').mousemove( self.mousemove_listener );
295 $('body').mouseup( self.mouseup_listener );
0fa07e25 296 $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
581aee24 297 self.ellipse.attr( 'fill', '#ff66ff' );
298 first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
299 if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
300 }
301
302 this.mousemove_listener = function(evt) {
72874569 303 self.dx = (evt.clientX - self.x) / mouse_scale;
304 self.dy = (evt.clientY - self.y) / mouse_scale;
581aee24 305 self.move_elements();
0fa07e25 306 evt.returnValue = false;
307 evt.preventDefault();
308 return false;
581aee24 309 }
310
311 this.mouseup_listener = function(evt) {
312 if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
28f2ef34 313 var source_node_id = $(self.ellipse).parent().attr('id');
0fa07e25 314 var source_node_text = self.ellipse.siblings('text').text();
28f2ef34 315 var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
0fa07e25 316 var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
581aee24 317 $('#source_node_id').val( source_node_id );
0fa07e25 318 $('#source_node_text').val( source_node_text );
581aee24 319 $('#target_node_id').val( target_node_id );
0fa07e25 320 $('#target_node_text').val( target_node_text );
581aee24 321 $('#dialog-form').dialog( 'open' );
322 };
323 $('body').unbind('mousemove');
324 $('body').unbind('mouseup');
325 self.ellipse.attr( 'fill', '#fff' );
0fa07e25 326 $(self.ellipse).parent().hover( self.enter_node, self.leave_node );
72874569 327 self.reset_elements();
581aee24 328 }
f26e47cd 329
581aee24 330 this.cpos = function() {
331 return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
332 }
333
334 this.get_g = function() {
335 return self.ellipse.parent('g');
336 }
337
338 this.enter_node = function(evt) {
339 self.ellipse.attr( 'fill', '#ffccff' );
340 }
341
342 this.leave_node = function(evt) {
343 self.ellipse.attr( 'fill', '#fff' );
344 }
345
346 this.greyout_edges = function() {
347 $.each( self.node_elements, function(index, value) {
348 value.grey_out('.edge');
349 });
350 }
351
352 this.ungreyout_edges = function() {
353 $.each( self.node_elements, function(index, value) {
354 value.un_grey_out('.edge');
355 });
356 }
357
358 this.move_elements = function() {
359 $.each( self.node_elements, function(index, value) {
360 value.move(self.dx,self.dy);
361 });
362 }
363
364 this.reset_elements = function() {
365 $.each( self.node_elements, function(index, value) {
366 value.reset();
367 });
368 }
369
370 this.update_elements = function() {
371 self.node_elements = node_elements_for(self.ellipse);
372 }
373
374 self.set_draggable( true );
375}
376
377function svgshape( shape_element ) {
378 this.shape = shape_element;
379 this.move = function(dx,dy) {
380 this.shape.attr( "transform", "translate(" + dx + " " + dy + ")" );
381 }
382 this.reset = function() {
383 this.shape.attr( "transform", "translate( 0, 0 )" );
384 }
385 this.grey_out = function(filter) {
386 if( this.shape.parent(filter).size() != 0 ) {
387 this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
388 }
389 }
390 this.un_grey_out = function(filter) {
391 if( this.shape.parent(filter).size() != 0 ) {
392 this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
393 }
394 }
395}
396
397function svgpath( path_element, svg_element ) {
398 this.svg_element = svg_element;
399 this.path = path_element;
400 this.x = this.path.x;
401 this.y = this.path.y;
402 this.move = function(dx,dy) {
403 this.path.x = this.x + dx;
404 this.path.y = this.y + dy;
405 }
406 this.reset = function() {
407 this.path.x = this.x;
408 this.path.y = this.y;
409 }
410 this.grey_out = function(filter) {
411 if( this.svg_element.parent(filter).size() != 0 ) {
412 this.svg_element.attr('stroke', '#e5e5e5');
413 this.svg_element.siblings('text').attr('fill', '#e5e5e5');
0fa07e25 414 this.svg_element.siblings('text').attr('class', 'noselect');
581aee24 415 }
416 }
417 this.un_grey_out = function(filter) {
418 if( this.svg_element.parent(filter).size() != 0 ) {
419 this.svg_element.attr('stroke', '#000000');
420 this.svg_element.siblings('text').attr('fill', '#000000');
0fa07e25 421 this.svg_element.siblings('text').attr('class', '');
581aee24 422 }
423 }
424}
425
426function node_elements_for( ellipse ) {
427 node_elements = get_edge_elements_for( ellipse );
428 node_elements.push( new svgshape( ellipse.siblings('text') ) );
429 node_elements.push( new svgshape( ellipse ) );
430 return node_elements;
431}
432
433function get_edge_elements_for( ellipse ) {
434 edge_elements = new Array();
28f2ef34 435 node_id = ellipse.parent().attr('id');
581aee24 436 edge_in_pattern = new RegExp( node_id + '$' );
437 edge_out_pattern = new RegExp( '^' + node_id );
438 $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
439 title = $(this).text();
440 if( edge_in_pattern.test(title) ) {
441 polygon = $(this).siblings('polygon');
442 if( polygon.size() > 0 ) {
443 edge_elements.push( new svgshape( polygon ) );
444 }
445 path_segments = $(this).siblings('path')[0].pathSegList;
446 edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
447 }
448 if( edge_out_pattern.test(title) ) {
449 path_segments = $(this).siblings('path')[0].pathSegList;
450 edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
451 }
452 });
453 return edge_elements;
454}
455
456function relation_factory() {
457 var self = this;
458 this.color_memo = null;
459 //TODO: colors hard coded for now
460 this.temp_color = '#FFA14F';
461 this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
462
463 this.create_temporary = function( source_node_id, target_node_id ) {
28f2ef34 464 var relation_id = get_relation_id( source_node_id, target_node_id );
465 var relation = $( jq( relation_id ) );
72874569 466 if( relation.size() == 0 ) {
581aee24 467 draw_relation( source_node_id, target_node_id, self.temp_color );
468 } else {
469 self.color_memo = relation.children('path').attr( 'stroke' );
470 relation.children('path').attr( 'stroke', self.temp_color );
471 }
472 }
473 this.remove_temporary = function() {
474 var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
475 if( self.color_memo != null ) {
476 path_element.attr( 'stroke', self.color_memo );
477 self.color_memo = null;
478 } else {
72874569 479 var temporary = path_element.parent('g').remove();
480 temporary.empty();
481 temporary = null;
581aee24 482 }
483 }
484 this.create = function( source_node_id, target_node_id, color_index ) {
485 //TODO: Protect from (color_)index out of bound..
486 var relation_color = self.relation_colors[ color_index ];
72874569 487 var relation = draw_relation( source_node_id, target_node_id, relation_color );
488 get_node_obj( source_node_id ).update_elements();
489 get_node_obj( target_node_id ).update_elements();
490 return relation;
581aee24 491 }
72874569 492 this.toggle_active = function( relation_id ) {
28f2ef34 493 var relation = $( jq( relation_id ) );
72874569 494 var relation_path = relation.children('path');
495 if( !relation.data( 'active' ) ) {
496 relation_path.css( {'cursor':'pointer'} );
497 relation_path.mouseenter( function(event) {
498 outerTimer = setTimeout( function() {
499 timer = setTimeout( function() {
28f2ef34 500 var related_nodes = get_related_nodes( relation_id );
501 var source_node_id = related_nodes[0];
502 var target_node_id = related_nodes[1];
72874569 503 $('#delete_source_node_id').val( source_node_id );
504 $('#delete_target_node_id').val( target_node_id );
505 self.showinfo(relation);
506 }, 500 )
507 }, 1000 );
508 });
509 relation_path.mouseleave( function(event) {
510 clearTimeout(outerTimer);
511 if( timer != null ) { clearTimeout(timer); }
512 });
513 relation.data( 'active', true );
514 } else {
515 relation_path.unbind( 'mouseenter' );
516 relation_path.unbind( 'mouseleave' );
517 relation_path.css( {'cursor':'inherit'} );
518 relation.data( 'active', false );
519 }
520 }
521 this.showinfo = function(relation) {
31aaf446 522 var htmlstr = 'type: ' + relation.data( 'type' ) + '<br/>scope: ' + relation.data( 'scope' );
523 if( relation.data( 'note' ) ) {
524 htmlstr = htmlstr + '<br/>note: ' + relation.data( 'note' );
525 }
526 $('#delete-form-text').html( htmlstr );
72874569 527 var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
528 var xs = parseFloat( points[0].split(',')[0] );
529 var xe = parseFloat( points[1].split(',')[0] );
530 var ys = parseFloat( points[0].split(',')[1] );
531 var ye = parseFloat( points[3].split(',')[1] );
532 var p = svg_root.createSVGPoint();
533 p.x = xs + ((xe-xs)*1.1);
534 p.y = ye - ((ye-ys)/2);
aff524fc 535 var ctm = svg_root_element.getScreenCTM();
72874569 536 var nx = p.matrixTransform(ctm).x;
537 var ny = p.matrixTransform(ctm).y;
538 var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
539 $('#delete-form').dialog( 'open' );
540 dialog_aria.offset({ left: nx, top: ny });
541 }
542 this.remove = function( relation_id ) {
28f2ef34 543 var relation = $( jq( relation_id ) );
72874569 544 relation.remove();
581aee24 545 }
546}
547
28f2ef34 548// Utility function to create/return the ID of a relation link between
549// a source and target.
550function get_relation_id( source_id, target_id ) {
551 var idlist = [ source_id, target_id ];
552 idlist.sort();
553 return 'relation-' + idlist[0] + '-...-' + idlist[1];
554}
555
556function get_related_nodes( relation_id ) {
557 var srctotarg = relation_id.substr( 9 );
558 return srctotarg.split('-...-');
559}
560
581aee24 561function draw_relation( source_id, target_id, relation_color ) {
72874569 562 var source_ellipse = get_ellipse( source_id );
563 var target_ellipse = get_ellipse( target_id );
28f2ef34 564 var relation_id = get_relation_id( source_id, target_id );
72874569 565 var svg = $('#svgenlargement').children('svg').svg().svg('get');
566 var path = svg.createPath();
567 var sx = parseInt( source_ellipse.attr('cx') );
568 var rx = parseInt( source_ellipse.attr('rx') );
569 var sy = parseInt( source_ellipse.attr('cy') );
570 var ex = parseInt( target_ellipse.attr('cx') );
571 var ey = parseInt( target_ellipse.attr('cy') );
28f2ef34 572 var relation = svg.group( $("#svgenlargement svg g"),
573 { 'class':'relation', 'id':relation_id } );
72874569 574 svg.title( relation, source_id + '->' + target_id );
575 svg.path( relation, path.move( sx, sy ).curveC( sx + (2*rx), sy, ex + (2*rx), ey, ex, ey ), {fill: 'none', stroke: relation_color, strokeWidth: 4});
581aee24 576 var relation_element = $('#svgenlargement .relation').filter( ':last' );
577 relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
72874569 578 return relation_element;
581aee24 579}
580
72874569 581
581aee24 582$(document).ready(function () {
72874569 583
584 timer = null;
581aee24 585 relation_manager = new relation_factory();
72874569 586 $('#update_workspace_button').data('locked', false);
581aee24 587
72874569 588 $('#enlargement').mousedown(function (event) {
581aee24 589 $(this)
72874569 590 .data('down', true)
591 .data('x', event.clientX)
592 .data('y', event.clientY)
593 .data('scrollLeft', this.scrollLeft)
aff524fc 594 stateTf = svg_root_element.getCTM().inverse();
72874569 595 var p = svg_root.createSVGPoint();
596 p.x = event.clientX;
597 p.y = event.clientY;
598 stateOrigin = p.matrixTransform(stateTf);
aff524fc 599 event.returnValue = false;
600 event.preventDefault();
72874569 601 return false;
581aee24 602 }).mouseup(function (event) {
72874569 603 $(this).data('down', false);
581aee24 604 }).mousemove(function (event) {
72874569 605 if( timer != null ) { clearTimeout(timer); }
606 if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
607 var p = svg_root.createSVGPoint();
608 p.x = event.clientX;
609 p.y = event.clientY;
610 p = p.matrixTransform(stateTf);
611 var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
612 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
aff524fc 613 svg_root_element.setAttribute("transform", s);
581aee24 614 }
aff524fc 615 event.returnValue = false;
616 event.preventDefault();
581aee24 617 }).mousewheel(function (event, delta) {
72874569 618 event.returnValue = false;
619 event.preventDefault();
620 if ( $('#update_workspace_button').data('locked') == false ) {
aff524fc 621 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
622 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
72874569 623 if( delta < -9 ) { delta = -9 };
624 var z = 1 + delta/10;
aff524fc 625 z = delta > 0 ? 1 : -1;
626 var g = svg_root_element;
627 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
72874569 628 var root = svg_root;
629 var p = root.createSVGPoint();
aff524fc 630 p.x = event.originalEvent.clientX;
631 p.y = event.originalEvent.clientY;
72874569 632 p = p.matrixTransform(g.getCTM().inverse());
aff524fc 633 var scaleLevel = 1+(z/20);
634 var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
72874569 635 var matrix = g.getCTM().multiply(k);
636 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
637 g.setAttribute("transform", s);
638 }
639 }
581aee24 640 }).css({
641 'overflow' : 'hidden',
642 'cursor' : '-moz-grab'
643 });
644
645
646 $( "#dialog-form" ).dialog({
647 autoOpen: false,
648 height: 270,
649 width: 290,
650 modal: true,
651 buttons: {
cc028ff3 652 "Ok": function( evt ) {
653 $(evt.target).button("disable");
581aee24 654 $('#status').empty();
aff524fc 655 form_values = $('#collapse_node_form').serialize();
a8928d1d 656 ncpath = getTextURL( 'relationships' );
581aee24 657 var jqjson = $.post( ncpath, form_values, function(data) {
658 $.each( data, function(item, source_target) {
988c7619 659 var source_found = get_ellipse( source_target[0] );
660 var target_found = get_ellipse( source_target[1] );
661 if( source_found.size() && target_found.size() ) {
28f2ef34 662 var relation = relation_manager.create( source_target[0], source_target[1], $('#rel_type')[0].selectedIndex-1 );
988c7619 663 relation.data( 'type', $('#rel_type :selected').text() );
664 relation.data( 'scope', $('#scope :selected').text() );
665 relation.data( 'note', $('#note').val() );
28f2ef34 666 relation_manager.toggle_active( relation.attr('id') );
988c7619 667 }
cc028ff3 668 $(evt.target).button("enable");
669 });
581aee24 670 $( "#dialog-form" ).dialog( "close" );
72874569 671 }, 'json' );
581aee24 672 },
673 Cancel: function() {
581aee24 674 $( this ).dialog( "close" );
675 }
676 },
677 create: function(event, ui) {
678 $(this).data( 'relation_drawn', false );
679 //TODO? Err handling?
72874569 680 var basepath = getRelativePath();
681 var jqjson = $.getJSON( basepath + '/definitions', function(data) {
581aee24 682 var types = data.types.sort();
683 $.each( types, function(index, value) {
aff524fc 684 $('#rel_type').append( $('<option />').attr( "value", value ).text(value) );
581aee24 685 $('#keymaplist').append( $('<li>').css( "border-color", relation_manager.relation_colors[index] ).text(value) );
686 });
687 var scopes = data.scopes;
688 $.each( scopes, function(index, value) {
aff524fc 689 $('#scope').append( $('<option />').attr( "value", value ).text(value) );
581aee24 690 });
691 });
692 },
693 open: function() {
694 relation_manager.create_temporary( $('#source_node_id').val(), $('#target_node_id').val() );
72874569 695 $(".ui-widget-overlay").css("background", "none");
696 $("#dialog_overlay").show();
697 $("#dialog_overlay").height( $("#enlargement_container").height() );
63213207 698 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
72874569 699 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
581aee24 700 },
701 close: function() {
72874569 702 relation_manager.remove_temporary();
581aee24 703 $( '#status' ).empty();
704 $("#dialog_overlay").hide();
705 }
706 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
a7f4020a 707 if( ajaxSettings.url == getTextURL('relationships')
708 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
72874569 709 var errobj = jQuery.parseJSON( jqXHR.responseText );
710 $('#status').append( '<p class="error">Error: ' + errobj.error + '</br>The relationship cannot be made.</p>' );
581aee24 711 }
ab06f3ed 712 $(event.target).parent().find('.ui-button').button("enable");
581aee24 713 } );
714
72874569 715 $( "#delete-form" ).dialog({
716 autoOpen: false,
31aaf446 717 height: 135,
72874569 718 width: 160,
719 modal: false,
720 buttons: {
721 Cancel: function() {
722 $( this ).dialog( "close" );
723 },
724 Delete: function() {
a8928d1d 725 form_values = $('#delete_relation_form').serialize();
726 ncpath = getTextURL( 'relationships' );
72874569 727 var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
728 $.each( data, function(item, source_target) {
28f2ef34 729 relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
72874569 730 });
731 $( "#delete-form" ).dialog( "close" );
732 }, dataType: 'json', type: 'DELETE' });
733 }
734 },
735 create: function(event, ui) {
736 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
737 buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
738 var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");
739 dialog_aria.mouseenter( function() {
740 if( mouseWait != null ) { clearTimeout(mouseWait) };
741 })
742 dialog_aria.mouseleave( function() {
743 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
744 })
745 },
746 open: function() {
747 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
748 },
749 close: function() {
750 }
751 });
752
aff524fc 753 // function for reading form dialog should go here; for now hide the element
28f2ef34 754 $('#reading-form').dialog({
755 autoOpen: false,
756 height: 400,
f26e47cd 757 width: 600,
28f2ef34 758 modal: true,
759 buttons: {
760 Cancel: function() {
761 $( this ).dialog( "close" );
762 },
2f54cbcd 763 Update: function( evt ) {
764 // Disable the button
765 $(evt.target).button("disable");
a7f4020a 766 $('#reading_status').empty();
3ba238d4 767 var reading_id = $('#reading_id').val()
768 form_values = {
769 'id' : reading_id,
4aed7cc5 770 'is_nonsense': $('#reading_is_nonsense').is(':checked'),
771 'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
3ba238d4 772 'normal_form': $('#reading_normal_form').val() };
773 // Add the morphology values
774 $('.reading_morphology').each( function() {
a1411d50 775 if( $(this).val() != '(Click to select)' ) {
776 var rmid = $(this).attr('id');
777 rmid = rmid.substring(8);
778 form_values[rmid] = $(this).val();
779 }
3ba238d4 780 });
781 // Make the JSON call
782 ncpath = getReadingURL( reading_id );
783 var reading_element = readingdata[reading_id];
2f54cbcd 784 // $(':button :contains("Update")').attr("disabled", true);
28f2ef34 785 var jqjson = $.post( ncpath, form_values, function(data) {
786 $.each( data, function(key, value) {
3ba238d4 787 reading_element[key] = value;
28f2ef34 788 });
3ba238d4 789 if( $('#update_workspace_button').data('locked') == false ) {
790 color_inactive( get_ellipse( reading_id ) );
791 }
2f54cbcd 792 $(evt.target).button("enable");
28f2ef34 793 $( "#reading-form" ).dialog( "close" );
794 });
3ba238d4 795 // Re-color the node if necessary
796 return false;
28f2ef34 797 }
798 },
3ba238d4 799 create: function() {
3ba238d4 800 },
f26e47cd 801 open: function() {
802 $(".ui-widget-overlay").css("background", "none");
803 $("#dialog_overlay").show();
a7f4020a 804 $('#reading_status').empty();
f26e47cd 805 $("#dialog_overlay").height( $("#enlargement_container").height() );
806 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
807 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
a1411d50 808 $("#reading-form").parent().find('.ui-button').button("enable");
f26e47cd 809 },
28f2ef34 810 close: function() {
811 $("#dialog_overlay").hide();
812 }
a7f4020a 813 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
814 if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
815 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
816 var errobj = jQuery.parseJSON( jqXHR.responseText );
817 $('#reading_status').append( '<p class="error">Error: ' + errobj.error + '</p>' );
818 }
ab06f3ed 819 $(event.target).parent().find('.ui-button').button("enable");
28f2ef34 820 });
ea35b6bb 821
aff524fc 822
581aee24 823 $('#update_workspace_button').click( function() {
824 var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
aff524fc 825 mouse_scale = svg_root_element.getScreenCTM().a;
72874569 826 if( $(this).data('locked') == true ) {
827 $('#svgenlargement ellipse' ).each( function( index ) {
828 if( $(this).data( 'node_obj' ) != null ) {
829 $(this).data( 'node_obj' ).ungreyout_edges();
830 $(this).data( 'node_obj' ).set_draggable( false );
831 var node_id = $(this).data( 'node_obj' ).get_id();
832 toggle_relation_active( node_id );
833 $(this).data( 'node_obj', null );
834 }
581aee24 835 })
581aee24 836 $(this).data('locked', false);
72874569 837 $(this).css('background-position', '0px 44px');
581aee24 838 } else {
72874569 839 var left = $('#enlargement').offset().left;
840 var right = left + $('#enlargement').width();
aff524fc 841 var tf = svg_root_element.getScreenCTM().inverse();
72874569 842 var p = svg_root.createSVGPoint();
843 p.x=left;
844 p.y=100;
845 var cx_min = p.matrixTransform(tf).x;
846 p.x=right;
847 var cx_max = p.matrixTransform(tf).x;
848 $('#svgenlargement ellipse').each( function( index ) {
849 var cx = parseInt( $(this).attr('cx') );
850 if( cx > cx_min && cx < cx_max) {
851 if( $(this).data( 'node_obj' ) == null ) {
852 $(this).data( 'node_obj', new node_obj( $(this) ) );
853 } else {
854 $(this).data( 'node_obj' ).set_draggable( true );
855 }
856 $(this).data( 'node_obj' ).greyout_edges();
857 var node_id = $(this).data( 'node_obj' ).get_id();
858 toggle_relation_active( node_id );
581aee24 859 }
72874569 860 });
861 $(this).css('background-position', '0px 0px');
581aee24 862 $(this).data('locked', true );
581aee24 863 }
864 });
865
9ca77245 866 $('.helptag').popupWindow({
867 height:500,
868 width:800,
869 top:50,
870 left:50,
871 scrollbars:1
872 });
873
874
72874569 875 function toggle_relation_active( node_id ) {
876 $('#svgenlargement .relation').find( "title:contains('" + node_id + "')" ).each( function(index) {
877 matchid = new RegExp( "^" + node_id );
878 if( $(this).text().match( matchid ) != null ) {
28f2ef34 879 var relation_id = $(this).parent().attr('id');
880 relation_manager.toggle_active( relation_id );
72874569 881 };
882 });
581aee24 883 }
581aee24 884
aff524fc 885 expandFillPageClients();
886 $(window).resize(function() {
887 expandFillPageClients();
888 });
889
72874569 890});
581aee24 891
892
aff524fc 893function expandFillPageClients() {
894 $('.fillPage').each(function () {
895 $(this).height($(window).height() - $(this).offset().top - MARGIN);
896 });
897}
898
899function loadSVG(svgData) {
900 var svgElement = $('#svgenlargement');
901
902 $(svgElement).svg('destroy');
903
904 $(svgElement).svg({
905 loadURL: svgData,
906 onLoad : svgEnlargementLoaded
907 });
908}
909
910
911/* OS Gadget stuff
912
913function svg_select_callback(topic, data, subscriberData) {
914 svgData = data;
915 loadSVG(svgData);
916}
917
918function loaded() {
919 var prefs = new gadgets.Prefs();
920 var preferredHeight = parseInt(prefs.getString('height'));
921 if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
922 expandFillPageClients();
923}
924
925if (gadgets.util.hasFeature('pubsub-2')) {
926 gadgets.HubSettings.onConnect = function(hum, suc, err) {
927 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
928 loaded();
929 };
930}
931else gadgets.util.registerOnLoadHandler(loaded);
932*/