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