get relationship mapper to work even without morphology extension
[scpubgit/stemmaweb.git] / root / js / relationship-readonly.js
CommitLineData
20198e59 1var MARGIN=30;
2var svg_root = null;
3var svg_root_element = null;
4var start_element_height = 0;
5var reltypes = {};
6var readingdata = {};
7
20198e59 8function getTextURL( which ) {
3f9d7ae5 9 return basepath + textid + '/' + which;
20198e59 10}
11
12function getReadingURL( reading_id ) {
3f9d7ae5 13 return basepath + textid + '/reading/' + reading_id;
20198e59 14}
15
16// Make an XML ID into a valid selector
17function jq(myid) {
18 return '#' + myid.replace(/(:|\.)/g,'\\$1');
19}
20
21// Actions for opening the reading panel
22function node_dblclick_listener( evt ) {
23 // Open the reading dialogue for the given node.
24 // First get the reading info
25 var reading_id = $(this).attr('id');
26 var reading_info = readingdata[reading_id];
27 // and then populate the dialog box with it.
28 // Set the easy properties first
29 $('#reading-form').dialog( 'option', 'title', 'Reading information for "' + reading_info['text'] + '"' );
30 $('#reading_id').val( reading_id );
31 toggle_checkbox( $('#reading_is_nonsense'), reading_info['is_nonsense'] );
32 toggle_checkbox( $('#reading_grammar_invalid'), reading_info['grammar_invalid'] );
33 // Use .text as a backup for .normal_form
34 var normal_form = reading_info['normal_form'];
35 if( !normal_form ) {
36 normal_form = reading_info['text'];
37 }
38 var nfboxsize = 10;
39 if( normal_form.length > 9 ) {
40 nfboxsize = normal_form.length + 1;
41 }
42 $('#reading_normal_form').attr( 'size', nfboxsize )
43 $('#reading_normal_form').val( normal_form );
44 // Now do the morphological properties.
45 morphology_form( reading_info['lexemes'] );
46 // and then open the dialog.
47 $('#reading-form').dialog("open");
48}
49
50function toggle_checkbox( box, value ) {
51 if( value == null ) {
52 value = false;
53 }
54 box.attr('checked', value );
55}
56
57function morphology_form ( lexlist ) {
58 $('#morphology').empty();
59 $.each( lexlist, function( idx, lex ) {
60 var morphoptions = [];
61 if( 'wordform_matchlist' in lex ) {
62 $.each( lex['wordform_matchlist'], function( tdx, tag ) {
63 var tagstr = stringify_wordform( tag );
64 morphoptions.push( tagstr );
65 });
66 }
67 var formtag = 'morphology_' + idx;
68 var formstr = '';
69 if( 'form' in lex ) {
70 formstr = stringify_wordform( lex['form'] );
71 }
72 var form_morph_elements = morph_elements(
73 formtag, lex['string'], formstr, morphoptions );
74 $.each( form_morph_elements, function( idx, el ) {
75 $('#morphology').append( el );
76 });
77 });
78}
79
80function stringify_wordform ( tag ) {
81 if( tag ) {
82 var elements = tag.split(' // ');
83 return elements[1] + ' // ' + elements[2];
84 }
85 return ''
86}
87
88function morph_elements ( formtag, formtxt, currform, morphoptions ) {
89 var clicktag = '(Click to select)';
90 if ( !currform ) {
91 currform = clicktag;
92 }
93 var formlabel = $('<label/>').attr( 'id', 'label_' + formtag ).attr(
94 'for', 'reading_' + formtag ).text( formtxt + ': ' );
95 var forminput = $('<input/>').attr( 'id', 'reading_' + formtag ).attr(
96 'name', 'reading_' + formtag ).attr( 'size', '50' ).attr(
97 'class', 'reading_morphology' ).val( currform );
98 forminput.autocomplete({ source: morphoptions, minLength: 0 });
99 forminput.focus( function() {
100 if( $(this).val() == clicktag ) {
101 $(this).val('');
102 }
103 $(this).autocomplete('search', '')
104 });
105 var morphel = [ formlabel, forminput, $('<br/>') ];
106 return morphel;
107}
108
109function color_inactive ( el ) {
110 var reading_id = $(el).parent().attr('id');
111 var reading_info = readingdata[reading_id];
112 // If the reading info has any non-disambiguated lexemes, color it yellow;
113 // otherwise color it green.
114 $(el).attr( {stroke:'green', fill:'#b3f36d'} );
115 if( reading_info ) {
116 $.each( reading_info['lexemes'], function ( idx, lex ) {
117 if( !lex['is_disambiguated'] || lex['is_disambiguated'] == 0 ) {
118 $(el).attr( {stroke:'orange', fill:'#fee233'} );
119 }
120 });
121 }
122}
123
124function relemmatize () {
125 // Send the reading for a new lemmatization and reopen the form.
126 $('#relemmatize_pending').show();
127 var reading_id = $('#reading_id').val()
128 ncpath = getReadingURL( reading_id );
129 form_values = {
130 'normal_form': $('#reading_normal_form').val(),
131 'relemmatize': 1 };
132 var jqjson = $.post( ncpath, form_values, function( data ) {
133 // Update the form with the return
134 if( 'id' in data ) {
135 // We got back a good answer. Stash it
136 readingdata[reading_id] = data;
137 // and regenerate the morphology form.
138 morphology_form( data['lexemes'] );
139 } else {
140 alert("Could not relemmatize as requested: " + data['error']);
141 }
142 $('#relemmatize_pending').hide();
143 });
144}
145
146// Initialize the SVG once it exists
147function svgEnlargementLoaded() {
148 //Give some visual evidence that we are working
149 $('#loading_overlay').show();
150 lo_height = $("#enlargement_container").outerHeight();
151 lo_width = $("#enlargement_container").outerWidth();
152 $("#loading_overlay").height( lo_height );
153 $("#loading_overlay").width( lo_width );
154 $("#loading_overlay").offset( $("#enlargement_container").offset() );
155 $("#loading_message").offset(
156 { 'top': lo_height / 2 - $("#loading_message").height() / 2,
157 'left': lo_width / 2 - $("#loading_message").width() / 2 });
158 //Set viewbox widht and height to widht and height of $('#svgenlargement svg').
159 //This is essential to make sure zooming and panning works properly.
160 var rdgpath = getTextURL( 'readings' );
161 $.getJSON( rdgpath, function( data ) {
162 readingdata = data;
163 $('#svgenlargement ellipse').each( function( i, el ) { color_inactive( el ) });
164 });
165 $('#svgenlargement ellipse').parent().dblclick( node_dblclick_listener );
166 var graph_svg = $('#svgenlargement svg');
167 var svg_g = $('#svgenlargement svg g')[0];
168 if (!svg_g) return;
169 svg_root = graph_svg.svg().svg('get').root();
170
171 // Find the real root and ignore any text nodes
172 for (i = 0; i < svg_root.childNodes.length; ++i) {
173 if (svg_root.childNodes[i].nodeName != '#text') {
174 svg_root_element = svg_root.childNodes[i];
175 break;
176 }
177 }
178
179 svg_root.viewBox.baseVal.width = graph_svg.attr( 'width' );
180 svg_root.viewBox.baseVal.height = graph_svg.attr( 'height' );
181 //Now set scale and translate so svg height is about 150px and vertically centered in viewbox.
182 //This is just to create a nice starting enlargement.
183 var initial_svg_height = 250;
184 var scale = initial_svg_height/graph_svg.attr( 'height' );
185 var additional_translate = (graph_svg.attr( 'height' ) - initial_svg_height)/(2*scale);
186 var transform = svg_g.getAttribute('transform');
187 var translate = parseFloat( transform.match( /translate\([^\)]*\)/ )[0].split('(')[1].split(' ')[1].split(')')[0] );
188 translate += additional_translate;
189 var transform = 'rotate(0) scale(' + scale + ') translate(4 ' + translate + ')';
190 svg_g.setAttribute('transform', transform);
191 //used to calculate min and max zoom level:
192 start_element_height = $('#__START__').children('ellipse')[0].getBBox().height;
193 add_relations( function() { $('#loading_overlay').hide(); });
194}
195
196function add_relations( callback_fn ) {
20198e59 197 var textrelpath = getTextURL( 'relationships' );
3f9d7ae5 198 $.getJSON( basepath + 'definitions', function(data) {
20198e59 199 var rel_types = data.types.sort();
200 $.each( rel_types, function(index, value) {
201 $('#keymaplist').append( $('<li>').css( "border-color", relation_manager.relation_colors[index] ).text(value) );
202 });
203 $.getJSON( textrelpath, function(data) {
204 $.each(data, function( index, rel_info ) {
205 var type_index = $.inArray(rel_info.type, rel_types);
206 var source_found = get_ellipse( rel_info.source );
207 var target_found = get_ellipse( rel_info.target );
208 if( type_index != -1 && source_found.size() && target_found.size() ) {
209 var relation = relation_manager.create( rel_info.source, rel_info.target, type_index );
210 relation.data( 'type', rel_info.type );
211 relation.data( 'scope', rel_info.scope );
212 relation.data( 'note', rel_info.note );
213 var node_obj = get_node_obj(rel_info.source);
214 node_obj.ellipse.data( 'node_obj', null );
215 node_obj = get_node_obj(rel_info.target);
216 node_obj.ellipse.data( 'node_obj', null );
217 }
218 });
219 callback_fn.call();
220 });
221 });
222}
223
224function get_ellipse( node_id ) {
225 return $( jq( node_id ) + ' ellipse');
226}
227
228function get_node_obj( node_id ) {
229 var node_ellipse = get_ellipse( node_id );
230 if( node_ellipse.data( 'node_obj' ) == null ) {
231 node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
232 };
233 return node_ellipse.data( 'node_obj' );
234}
235
236function node_obj(ellipse) {
237 this.ellipse = ellipse;
238 var self = this;
239
240 this.x = 0;
241 this.y = 0;
242 this.dx = 0;
243 this.dy = 0;
244 this.node_elements = node_elements_for(self.ellipse);
245
246 this.update_elements = function() {
247 self.node_elements = node_elements_for(self.ellipse);
248 }
249}
250
251function svgshape( shape_element ) {
252 this.shape = shape_element;
253 this.move = function(dx,dy) {
254 this.shape.attr( "transform", "translate(" + dx + " " + dy + ")" );
255 }
256 this.reset = function() {
257 this.shape.attr( "transform", "translate( 0, 0 )" );
258 }
259 this.grey_out = function(filter) {
260 if( this.shape.parent(filter).size() != 0 ) {
261 this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
262 }
263 }
264 this.un_grey_out = function(filter) {
265 if( this.shape.parent(filter).size() != 0 ) {
266 this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
267 }
268 }
269}
270
271function svgpath( path_element, svg_element ) {
272 this.svg_element = svg_element;
273 this.path = path_element;
274 this.x = this.path.x;
275 this.y = this.path.y;
276 this.move = function(dx,dy) {
277 this.path.x = this.x + dx;
278 this.path.y = this.y + dy;
279 }
280 this.reset = function() {
281 this.path.x = this.x;
282 this.path.y = this.y;
283 }
284 this.grey_out = function(filter) {
285 if( this.svg_element.parent(filter).size() != 0 ) {
286 this.svg_element.attr('stroke', '#e5e5e5');
287 this.svg_element.siblings('text').attr('fill', '#e5e5e5');
288 this.svg_element.siblings('text').attr('class', 'noselect');
289 }
290 }
291 this.un_grey_out = function(filter) {
292 if( this.svg_element.parent(filter).size() != 0 ) {
293 this.svg_element.attr('stroke', '#000000');
294 this.svg_element.siblings('text').attr('fill', '#000000');
295 this.svg_element.siblings('text').attr('class', '');
296 }
297 }
298}
299
300function node_elements_for( ellipse ) {
301 node_elements = get_edge_elements_for( ellipse );
302 node_elements.push( new svgshape( ellipse.siblings('text') ) );
303 node_elements.push( new svgshape( ellipse ) );
304 return node_elements;
305}
306
307function get_edge_elements_for( ellipse ) {
308 edge_elements = new Array();
309 node_id = ellipse.parent().attr('id');
310 edge_in_pattern = new RegExp( node_id + '$' );
311 edge_out_pattern = new RegExp( '^' + node_id );
312 $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
313 title = $(this).text();
314 if( edge_in_pattern.test(title) ) {
315 polygon = $(this).siblings('polygon');
316 if( polygon.size() > 0 ) {
317 edge_elements.push( new svgshape( polygon ) );
318 }
319 path_segments = $(this).siblings('path')[0].pathSegList;
320 edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
321 }
322 if( edge_out_pattern.test(title) ) {
323 path_segments = $(this).siblings('path')[0].pathSegList;
324 edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
325 }
326 });
327 return edge_elements;
328}
329
330function relation_factory() {
331 var self = this;
332 this.color_memo = null;
333 //TODO: colors hard coded for now
334 this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
335
336 this.create = function( source_node_id, target_node_id, color_index ) {
337 //TODO: Protect from (color_)index out of bound..
338 var relation_color = self.relation_colors[ color_index ];
339 var relation = draw_relation( source_node_id, target_node_id, relation_color );
340 var relation_id = get_relation_id( source_node_id, target_node_id );
341 get_node_obj( source_node_id ).update_elements();
342 get_node_obj( target_node_id ).update_elements();
343 // Set it active by default. May need to restore toggling if having all
344 // relationships active is too much of a performance hit.
345 var relation_path = relation.children('path');
346 // All relations active in order to allow hover information?
347 // Else we will have to deactivate them when they go off-screen.
348 relation_path.css( {'cursor':'pointer'} );
349 relation_path.mouseenter( function(event) {
350 outerTimer = setTimeout( function() {
351 timer = setTimeout( function() {
352 var related_nodes = get_related_nodes( relation_id );
353 var source_node_id = related_nodes[0];
354 var target_node_id = related_nodes[1];
355 $('#delete_source_node_id').val( source_node_id );
356 $('#delete_target_node_id').val( target_node_id );
357 self.showinfo(relation);
358 }, 500 )
359 }, 1000 );
360 });
361 relation_path.mouseleave( function(event) {
362 clearTimeout(outerTimer);
363 if( timer != null ) { clearTimeout(timer); }
364 });
365
366 return relation;
367 }
368
369 this.showinfo = function(relation) {
370 var htmlstr = 'type: ' + relation.data( 'type' ) + '<br/>scope: ' + relation.data( 'scope' );
371 if( relation.data( 'note' ) ) {
372 htmlstr = htmlstr + '<br/>note: ' + relation.data( 'note' );
373 }
374 $('#delete-form-text').html( htmlstr );
375 var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
376 var xs = parseFloat( points[0].split(',')[0] );
377 var xe = parseFloat( points[1].split(',')[0] );
378 var ys = parseFloat( points[0].split(',')[1] );
379 var ye = parseFloat( points[3].split(',')[1] );
380 var p = svg_root.createSVGPoint();
381 p.x = xs + ((xe-xs)*1.1);
382 p.y = ye - ((ye-ys)/2);
383 var ctm = svg_root_element.getScreenCTM();
384 var nx = p.matrixTransform(ctm).x;
385 var ny = p.matrixTransform(ctm).y;
386 var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
387 $('#delete-form').dialog( 'open' );
388 dialog_aria.offset({ left: nx, top: ny });
389 }
390 /* Do we need this in readonly mode?
391 this.remove = function( relation_id ) {
392 var relation = $( jq( relation_id ) );
393 relation.remove();
394 }
395 */
396}
397
398// Utility function to create/return the ID of a relation link between
399// a source and target.
400function get_relation_id( source_id, target_id ) {
401 var idlist = [ source_id, target_id ];
402 idlist.sort();
403 return 'relation-' + idlist[0] + '-...-' + idlist[1];
404}
405
406function get_related_nodes( relation_id ) {
407 var srctotarg = relation_id.substr( 9 );
408 return srctotarg.split('-...-');
409}
410
411function draw_relation( source_id, target_id, relation_color ) {
412 var source_ellipse = get_ellipse( source_id );
413 var target_ellipse = get_ellipse( target_id );
414 var relation_id = get_relation_id( source_id, target_id );
415 var svg = $('#svgenlargement').children('svg').svg().svg('get');
416 var path = svg.createPath();
417 var sx = parseInt( source_ellipse.attr('cx') );
418 var rx = parseInt( source_ellipse.attr('rx') );
419 var sy = parseInt( source_ellipse.attr('cy') );
420 var ex = parseInt( target_ellipse.attr('cx') );
421 var ey = parseInt( target_ellipse.attr('cy') );
422 var relation = svg.group( $("#svgenlargement svg g"),
423 { 'class':'relation', 'id':relation_id } );
424 svg.title( relation, source_id + '->' + target_id );
425 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});
426 var relation_element = $('#svgenlargement .relation').filter( ':last' );
427 relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
428 return relation_element;
429}
430
431$(document).ready(function () {
432
433 timer = null;
434 relation_manager = new relation_factory();
435
436 $('#enlargement').mousedown(function (event) {
437 $(this)
438 .data('down', true)
439 .data('x', event.clientX)
440 .data('y', event.clientY)
441 .data('scrollLeft', this.scrollLeft)
442 stateTf = svg_root_element.getCTM().inverse();
443 var p = svg_root.createSVGPoint();
444 p.x = event.clientX;
445 p.y = event.clientY;
446 stateOrigin = p.matrixTransform(stateTf);
447 event.returnValue = false;
448 event.preventDefault();
449 return false;
450 }).mouseup(function (event) {
451 $(this).data('down', false);
452 }).mousemove(function (event) {
453 if( timer != null ) { clearTimeout(timer); }
454 if ( ($(this).data('down') == true) ) {
455 var p = svg_root.createSVGPoint();
456 p.x = event.clientX;
457 p.y = event.clientY;
458 p = p.matrixTransform(stateTf);
459 var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
460 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
461 svg_root_element.setAttribute("transform", s);
462 }
463 event.returnValue = false;
464 event.preventDefault();
465 }).mousewheel(function (event, delta) {
466 event.returnValue = false;
467 event.preventDefault();
468 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
469 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
470 if( delta < -9 ) { delta = -9 };
471 var z = 1 + delta/10;
472 z = delta > 0 ? 1 : -1;
473 var g = svg_root_element;
474 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
475 var root = svg_root;
476 var p = root.createSVGPoint();
477 p.x = event.originalEvent.clientX;
478 p.y = event.originalEvent.clientY;
479 p = p.matrixTransform(g.getCTM().inverse());
480 var scaleLevel = 1+(z/20);
481 var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
482 var matrix = g.getCTM().multiply(k);
483 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
484 g.setAttribute("transform", s);
485 }
486 }).css({
487 'overflow' : 'hidden',
488 'cursor' : '-moz-grab'
489 });
490
491 $( "#delete-form" ).dialog({
492 autoOpen: false,
493 height: 135,
494 width: 160,
495 modal: false,
496 buttons: {
497 OK: function() {
498 $( this ).dialog( "close" );
499 }
500 },
501 create: function(event, ui) {
502 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
503 buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
504 var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");
505 dialog_aria.mouseenter( function() {
506 if( mouseWait != null ) { clearTimeout(mouseWait) };
507 })
508 dialog_aria.mouseleave( function() {
509 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
510 })
511 },
512 open: function() {
513 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
514 },
515 close: function() {
516 }
517 });
518
519 // function for reading form dialog should go here; for now hide the element
520 $('#reading-form').dialog({
521 autoOpen: false,
522 height: 400,
523 width: 600,
524 modal: true,
525 buttons: {
526 OK: function() {
527 $( this ).dialog( "close" );
528 }
529 },
530 create: function() {
531 },
532 open: function() {
533 $(".ui-widget-overlay").css("background", "none");
534 $("#dialog_overlay").show();
535 $('#reading_status').empty();
536 $("#dialog_overlay").height( $("#enlargement_container").height() );
537 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
538 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
539 $("#reading-form").parent().find('.ui-button').button("enable");
540 },
541 close: function() {
542 $("#dialog_overlay").hide();
543 }
544 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
545 if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
546 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
547 var errobj = jQuery.parseJSON( jqXHR.responseText );
548 $('#reading_status').append( '<p class="error">Error: ' + errobj.error + '</p>' );
549 }
550 $(event.target).parent().find('.ui-button').button("enable");
551 });
552
69ac99fc 553 // Hide the unused elements
554 $('#dialog-form').hide();
20198e59 555 $('#update_workspace_button').hide();
556
557 $('.helptag').popupWindow({
558 height:500,
559 width:800,
560 top:50,
561 left:50,
562 scrollbars:1
563 });
564
565
566 expandFillPageClients();
567 $(window).resize(function() {
568 expandFillPageClients();
569 });
570
571});
572
573
574function expandFillPageClients() {
575 $('.fillPage').each(function () {
576 $(this).height($(window).height() - $(this).offset().top - MARGIN);
577 });
578}
579
580function loadSVG(svgData) {
581 var svgElement = $('#svgenlargement');
582
583 $(svgElement).svg('destroy');
584
585 $(svgElement).svg({
586 loadURL: svgData,
587 onLoad : svgEnlargementLoaded
588 });
589}
590
591
592/* OS Gadget stuff
593
594function svg_select_callback(topic, data, subscriberData) {
595 svgData = data;
596 loadSVG(svgData);
597}
598
599function loaded() {
600 var prefs = new gadgets.Prefs();
601 var preferredHeight = parseInt(prefs.getString('height'));
602 if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
603 expandFillPageClients();
604}
605
606if (gadgets.util.hasFeature('pubsub-2')) {
607 gadgets.HubSettings.onConnect = function(hum, suc, err) {
608 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
609 loaded();
610 };
611}
612else gadgets.util.registerOnLoadHandler(loaded);
613*/