From: Radek Czajka Date: Tue, 18 Jul 2023 17:04:27 +0000 (+0200) Subject: Some modernizations. X-Git-Url: https://git.mdrn.pl/redakcja.git/commitdiff_plain/9d566b4741eb66bf09b5c7d213aa8541886e100a Some modernizations. --- diff --git a/src/redakcja/static/js/wiki/base.js b/src/redakcja/static/js/wiki/base.js index b4fee85f..7018b1a6 100644 --- a/src/redakcja/static/js/wiki/base.js +++ b/src/redakcja/static/js/wiki/base.js @@ -1,353 +1,353 @@ (function($) { - var noop = function() { }; - - $.wiki = { - perspectives: {}, - cls: {}, - state: { - "version": 1, - "perspectives": { - "ScanGalleryPerspective": { - "show": true, - "page": undefined - }, - "CodeMirrorPerspective": {} - /* - "VisualPerspective": {}, - "HistoryPerspective": {}, - "SummaryPerspective": {} - */ - } - } - }; - - $.wiki.loadConfig = function() { - if(!window.localStorage) - return; - - try { - var value = window.localStorage.getItem(CurrentDocument.id) || "{}"; - var config = JSON.parse(value); - - if (config.version == $.wiki.state.version) { - $.wiki.state.perspectives = $.extend($.wiki.state.perspectives, config.perspectives); - } - } catch(e) { - console.log("Failed to load config, using default."); - } - - console.log("Loaded:", $.wiki.state, $.wiki.state.version); - }; - - $(window).bind('unload', function() { - if(window.localStorage) - window.localStorage.setItem(CurrentDocument.id, JSON.stringify($.wiki.state)); - }) - - - $.wiki.activePerspective = function() { - return this.perspectives[$("#tabs li a.active").parent().attr('id')]; - }; - - $.wiki.exitContext = function() { - var ap = this.activePerspective(); - if(ap) ap.onExit(); - return ap; - }; - - $.wiki.enterContext = function(ap) { - if(ap) ap.onEnter(); - }; - - $.wiki.isDirty = function() { - var ap = this.activePerspective(); - return (!!CurrentDocument && CurrentDocument.has_local_changes) || ap.dirty(); - }; - - $.wiki.newTab = function(doc, title, klass) { - var base_id = 'id' + Math.floor(Math.random()* 5000000000); - var id = (''+klass)+'_' + base_id; - var $tab = $(''); - var $view = $('
'); - - this.perspectives[id] = new $.wiki[klass]({ - doc: doc, - id: id, - base_id: base_id, - }); - - $('#tabs').append($tab); - $view.hide().appendTo('#editor'); - return { - tab: $tab[0], - view: $view[0], - }; - }; - - $.wiki.initTab = function(options) { - var klass = $(options.tab).attr('data-ui-jsclass'); - - return new $.wiki[klass]({ - doc: options.doc, - id: $(options.tab).attr('id'), - callback: function() { - $.wiki.perspectives[this.perspective_id] = this; - if(options.callback) - options.callback.call(this); - } - }); - }; - - $.wiki.perspectiveForTab = function(tab) { // element or id - return this.perspectives[ $(tab).attr('id')]; - } + var noop = function() { }; + + $.wiki = { + perspectives: {}, + cls: {}, + state: { + "version": 1, + "perspectives": { + "ScanGalleryPerspective": { + "show": true, + "page": undefined + }, + "CodeMirrorPerspective": {} + /* + "VisualPerspective": {}, + "HistoryPerspective": {}, + "SummaryPerspective": {} + */ + } + } + }; + + $.wiki.loadConfig = function() { + if(!window.localStorage) + return; + + try { + var value = window.localStorage.getItem(CurrentDocument.id) || "{}"; + var config = JSON.parse(value); + + if (config.version == $.wiki.state.version) { + $.wiki.state.perspectives = $.extend($.wiki.state.perspectives, config.perspectives); + } + } catch(e) { + console.log("Failed to load config, using default."); + } + + console.log("Loaded:", $.wiki.state, $.wiki.state.version); + }; + + $(window).bind('unload', function() { + if(window.localStorage) + window.localStorage.setItem(CurrentDocument.id, JSON.stringify($.wiki.state)); + }) + + + $.wiki.activePerspective = function() { + return this.perspectives[$("#tabs li a.active").parent().attr('id')]; + }; + + $.wiki.exitContext = function() { + var ap = this.activePerspective(); + if(ap) ap.onExit(); + return ap; + }; + + $.wiki.enterContext = function(ap) { + if(ap) ap.onEnter(); + }; + + $.wiki.isDirty = function() { + var ap = this.activePerspective(); + return (!!CurrentDocument && CurrentDocument.has_local_changes) || ap.dirty(); + }; + + $.wiki.newTab = function(doc, title, klass) { + var base_id = 'id' + Math.floor(Math.random()* 5000000000); + var id = (''+klass)+'_' + base_id; + var $tab = $(''); + var $view = $('
'); + + this.perspectives[id] = new $.wiki[klass]({ + doc: doc, + id: id, + base_id: base_id, + }); + + $('#tabs').append($tab); + $view.hide().appendTo('#editor'); + return { + tab: $tab[0], + view: $view[0], + }; + }; + + $.wiki.initTab = function(options) { + var klass = $(options.tab).attr('data-ui-jsclass'); + + return new $.wiki[klass]({ + doc: options.doc, + id: $(options.tab).attr('id'), + callback: function() { + $.wiki.perspectives[this.perspective_id] = this; + if(options.callback) + options.callback.call(this); + } + }); + }; + + $.wiki.perspectiveForTab = function(tab) { // element or id + return this.perspectives[ $(tab).attr('id')]; + } $.wiki.exitTab = function(tab){ - var self = this; - var $tab = $(tab); + var self = this; + var $tab = $(tab); if (!('.active', $tab)) return; - $('.active', $tab).removeClass('active'); - self.perspectives[$tab.attr('id')].onExit(); - $('#' + $tab.attr('data-ui-related')).hide(); + $('.active', $tab).removeClass('active'); + self.perspectives[$tab.attr('id')].onExit(); + $('#' + $tab.attr('data-ui-related')).hide(); } - + $.wiki.switchToTab = function(tab){ - var self = this; - var $tab = $(tab); + var self = this; + var $tab = $(tab); - if($tab.length != 1) - $tab = $(DEFAULT_PERSPECTIVE); + if($tab.length != 1) + $tab = $(DEFAULT_PERSPECTIVE); - var $old_a = $tab.closest('.tabs').find('.active'); + var $old_a = $tab.closest('.tabs').find('.active'); - $old_a.each(function(){ + $old_a.each(function(){ var tab = $(this).parent() - $(this).removeClass('active'); - self.perspectives[tab.attr('id')].onExit(); - $('#' + tab.attr('data-ui-related')).hide(); - }); + $(this).removeClass('active'); + self.perspectives[tab.attr('id')].onExit(); + $('#' + tab.attr('data-ui-related')).hide(); + }); - /* show new */ - $('a', tab).addClass('active'); - $('#' + $tab.attr('data-ui-related')).show(); + /* show new */ + $('a', tab).addClass('active'); + $('#' + $tab.attr('data-ui-related')).show(); - console.log($tab); - console.log($.wiki.perspectives); + console.log($tab); + console.log($.wiki.perspectives); - $.wiki.perspectives[$tab.attr('id')].onEnter(); + $.wiki.perspectives[$tab.attr('id')].onEnter(); }; - /* - * Basic perspective. - */ - $.wiki.Perspective = function(options) { - if(!options) return; - - this.doc = options.doc; - if (options.id) { - this.perspective_id = options.id; - } - else { - this.perspective_id = ''; - } - - if(options.callback) - options.callback.call(this); - }; - - $.wiki.Perspective.prototype.config = function() { - return $.wiki.state.perspectives[this.perspective_id]; - } - - $.wiki.Perspective.prototype.toString = function() { - return this.perspective_id; - }; - - $.wiki.Perspective.prototype.dirty = function() { - return true; - }; - - $.wiki.Perspective.prototype.onEnter = function () { - // called when perspective in initialized - if (!this.noupdate_hash_onenter) { - document.location.hash = '#' + this.perspective_id; - } - }; - - $.wiki.Perspective.prototype.onExit = function () { - // called when user switches to another perspective - if (!this.noupdate_hash_onenter) { - document.location.hash = ''; - } - }; - - $.wiki.Perspective.prototype.destroy = function() { - // pass - }; - - $.wiki.Perspective.prototype.freezeState = function () { - // free UI state (don't store data here) - }; - - $.wiki.Perspective.prototype.unfreezeState = function (frozenState) { - // restore UI state - }; - - /* - * Stub rendering (used in generating history) - */ - $.wiki.renderStub = function(params) - { - params = $.extend({ 'filters': {} }, params); - var $elem = params.stub.clone(); - $elem.removeClass('row-stub'); - params.container.append($elem); - - $('*[data-stub-value]', $elem).each(function() { - var $this = $(this); - var field = $this.attr('data-stub-value'); - - var value = params.data[field]; - - if(params.filters[field]) - value = params.filters[field](value); - - if(value === null || value === undefined) return; - - if(!$this.attr('data-stub-target')) { - $this.text(value); - } - else { - $this.attr($this.attr('data-stub-target'), value); - $this.removeAttr('data-stub-target'); - $this.removeAttr('data-stub-value'); - } - }); - - $elem.show(); - return $elem; - }; - - /* - * Dialogs - */ - function GenericDialog(element) { - if(!element) return; - - var self = this; - - self.$elem = $(element); - - if(!self.$elem.attr('data-ui-initialized')) { - console.log("Initializing dialog", this); - self.initialize(); - self.$elem.attr('data-ui-initialized', true); - } - - self.show(); - }; - - GenericDialog.prototype = { - - /* - * Steps to follow when the dialog in first loaded on page. - */ - initialize: function(){ - var self = this; - - /* bind buttons */ - $('button[data-ui-action]', self.$elem).click(function(event) { - event.preventDefault(); - - var action = $(this).attr('data-ui-action'); - console.log("Button pressed, action: ", action); - - try { - self[action + "Action"].call(self); - } catch(e) { - console.log("Action failed:", e); - // always hide on cancel - if(action == 'cancel') - self.hide(); - } - }); - }, - - /* - * Prepare dialog for user. Clear any unnessary data. - */ - show: function() { - $.blockUI({ - message: this.$elem, - css: { - 'top': '25%', - 'left': '25%', - 'width': '50%', - 'max-height': '75%', - 'overflow-y': 'scroll' - } - }); - }, - - hide: function(){ - $.unblockUI(); - }, - - cancelAction: function() { - this.hide(); - }, - - doneAction: function() { - this.hide(); - }, - - clearForm: function() { - $("*[data-ui-error-for]", this.$elem).text(''); - }, - - reportErrors: function(errors) { - var global = $("*[data-ui-error-for='__all__']", this.$elem); - var unassigned = []; + /* + * Basic perspective. + */ + $.wiki.Perspective = class Perspective { + constructor(options) { + if(!options) return; + + this.doc = options.doc; + if (options.id) { + this.perspective_id = options.id; + } + else { + this.perspective_id = ''; + } + + if(options.callback) + options.callback.call(this); + }; + config() { + return $.wiki.state.perspectives[this.perspective_id]; + } + + toString() { + return this.perspective_id; + } + + dirty() { + return true; + } + + onEnter() { + // called when perspective in initialized + if (!this.noupdate_hash_onenter) { + document.location.hash = '#' + this.perspective_id; + } + } + + onExit () { + // called when user switches to another perspective + if (!this.noupdate_hash_onenter) { + document.location.hash = ''; + } + } + + destroy() { + // pass + } + + freezeState() { + // free UI state (don't store data here) + } + + unfreezeState(frozenState) { + // restore UI state + } + } + + /* + * Stub rendering (used in generating history) + */ + $.wiki.renderStub = function(params) + { + params = $.extend({ 'filters': {} }, params); + var $elem = params.stub.clone(); + $elem.removeClass('row-stub'); + params.container.append($elem); + + $('*[data-stub-value]', $elem).each(function() { + var $this = $(this); + var field = $this.attr('data-stub-value'); + + var value = params.data[field]; + + if(params.filters[field]) + value = params.filters[field](value); + + if(value === null || value === undefined) return; + + if(!$this.attr('data-stub-target')) { + $this.text(value); + } + else { + $this.attr($this.attr('data-stub-target'), value); + $this.removeAttr('data-stub-target'); + $this.removeAttr('data-stub-value'); + } + }); + + $elem.show(); + return $elem; + }; + + /* + * Dialogs + */ + class GenericDialog { + constructor(element) { + if(!element) return; + + var self = this; + + self.$elem = $(element); + + if(!self.$elem.attr('data-ui-initialized')) { + console.log("Initializing dialog", this); + self.initialize(); + self.$elem.attr('data-ui-initialized', true); + } + + self.show(); + } + + /* + * Steps to follow when the dialog in first loaded on page. + */ + initialize(){ + var self = this; + + /* bind buttons */ + $('button[data-ui-action]', self.$elem).click(function(event) { + event.preventDefault(); + + var action = $(this).attr('data-ui-action'); + console.log("Button pressed, action: ", action); + + try { + self[action + "Action"].call(self); + } catch(e) { + console.log("Action failed:", e); + // always hide on cancel + if(action == 'cancel') + self.hide(); + } + }); + } + + /* + * Prepare dialog for user. Clear any unnessary data. + */ + show() { + $.blockUI({ + message: this.$elem, + css: { + 'top': '25%', + 'left': '25%', + 'width': '50%', + 'max-height': '75%', + 'overflow-y': 'scroll' + } + }); + } + + hide() { + $.unblockUI(); + } + + cancelAction() { + this.hide(); + } + + doneAction() { + this.hide(); + } + + clearForm() { $("*[data-ui-error-for]", this.$elem).text(''); - for (var field_name in errors) - { - var span = $("*[data-ui-error-for='"+field_name+"']", this.$elem); + } + + reportErrors(errors) { + var global = $("*[data-ui-error-for='__all__']", this.$elem); + var unassigned = []; - if(!span.length) { - unassigned.push(field_name); - continue; - } + $("*[data-ui-error-for]", this.$elem).text(''); + for (var field_name in errors) + { + var span = $("*[data-ui-error-for='"+field_name+"']", this.$elem); - span.text(errors[field_name].join(' ')); - } + if(!span.length) { + unassigned.push(field_name); + continue; + } - if(unassigned.length > 0) - global.text( global.text() + 'W formularzu wystąpiły błędy'); - } - }; + span.text(errors[field_name].join(' ')); + } - $.wiki.cls.GenericDialog = GenericDialog; + if(unassigned.length > 0) + global.text( global.text() + 'W formularzu wystąpiły błędy'); + } + } - $.wiki.showDialog = function(selector, options) { - var elem = $(selector); + $.wiki.cls.GenericDialog = GenericDialog; - if(elem.length != 1) { - console.log("Failed to show dialog:", selector, elem); - return false; - } + $.wiki.showDialog = function(selector, options) { + var elem = $(selector); - try { - var klass = elem.attr('data-ui-jsclass'); - return new $.wiki.cls[klass](elem, options); - } catch(e) { - console.log("Failed to show dialog", selector, klass, e); - return false; - } - }; + if(elem.length != 1) { + console.log("Failed to show dialog:", selector, elem); + return false; + } + try { + var klass = elem.attr('data-ui-jsclass'); + return new $.wiki.cls[klass](elem, options); + } catch(e) { + console.log("Failed to show dialog", selector, klass, e); + return false; + } + }; window.addEventListener("message", (event) => { event.source.close() @@ -358,7 +358,7 @@ } }); }, false); - + $("#login").click(function (e) { e.preventDefault(); let h = 600; @@ -371,5 +371,5 @@ "width=" + w + " height=" + h + " top=" + y + " left=" + x ); }); - + })(jQuery); diff --git a/src/redakcja/static/js/wiki/dialog_pubmark.js b/src/redakcja/static/js/wiki/dialog_pubmark.js index 902a737c..02493841 100644 --- a/src/redakcja/static/js/wiki/dialog_pubmark.js +++ b/src/redakcja/static/js/wiki/dialog_pubmark.js @@ -4,29 +4,29 @@ */ (function($){ - function PubmarkDialog(element, options){ - if (!options.revision && options.revision != 0) - throw "PubmarkDialog needs a revision number."; + class PubmarkDialog extends $.wiki.cls.GenericDialog { + constructor(element, options) { + if (!options.revision && options.revision != 0) + throw "PubmarkDialog needs a revision number."; - this.ctx = $.wiki.exitContext(); - this.clearForm(); + super(element); + this.ctx = $.wiki.exitContext(); + this.clearForm(); - /* fill out hidden fields */ - this.$form = $('form', element); + /* fill out hidden fields */ + this.$form = $('form', element); - $("input[name='pubmark-id']", this.$form).val(CurrentDocument.id); - $("input[name='pubmark-revision']", this.$form).val(options.revision); + $("input[name='pubmark-id']", this.$form).val(CurrentDocument.id); + $("input[name='pubmark-revision']", this.$form).val(options.revision); - $.wiki.cls.GenericDialog.call(this, element); - }; + } - PubmarkDialog.prototype = $.extend(new $.wiki.cls.GenericDialog(), { - cancelAction: function(){ + cancelAction() { $.wiki.enterContext(this.ctx); this.hide(); - }, + } - saveAction: function(){ + saveAction() { var self = this; self.$elem.block({ @@ -54,7 +54,7 @@ } }); } - }); + } /* make it global */ $.wiki.cls.PubmarkDialog = PubmarkDialog; diff --git a/src/redakcja/static/js/wiki/dialog_revert.js b/src/redakcja/static/js/wiki/dialog_revert.js index 4d550f9d..0771088f 100644 --- a/src/redakcja/static/js/wiki/dialog_revert.js +++ b/src/redakcja/static/js/wiki/dialog_revert.js @@ -4,26 +4,24 @@ */ (function($) { - function RevertDialog(element, options) { - this.ctx = $.wiki.exitContext(); - this.clearForm(); + class RevertDialog extends $.wiki.cls.GenericDialog { + constructor(element, options) { + super(element); + this.ctx = $.wiki.exitContext(); + this.clearForm(); - /* fill out hidden fields */ - this.$form = $('form', element); + /* fill out hidden fields */ + this.$form = $('form', element); - $("input[name='textrevert-revision']", this.$form).val(options.revision); + $("input[name='textrevert-revision']", this.$form).val(options.revision); + } - $.wiki.cls.GenericDialog.call(this, element); - }; + cancelAction() { + $.wiki.enterContext(this.ctx); + this.hide(); + }; - RevertDialog.prototype = new $.wiki.cls.GenericDialog(); - - RevertDialog.prototype.cancelAction = function() { - $.wiki.enterContext(this.ctx); - this.hide(); - }; - - RevertDialog.prototype.revertAction = function() { + revertAction() { var self = this; self.$elem.block({ @@ -33,7 +31,6 @@ $.wiki.blocking = self.$elem; try { - CurrentDocument.revertToVersion({ form: self.$form, success: function(e, msg) { @@ -58,7 +55,8 @@ console.log('Exception:', e) self.$elem.unblock(); } - }; /* end of revert dialog */ + } + } /* make it global */ $.wiki.cls.RevertDialog = RevertDialog; diff --git a/src/redakcja/static/js/wiki/dialog_save.js b/src/redakcja/static/js/wiki/dialog_save.js index 903c0e1c..e3402b17 100644 --- a/src/redakcja/static/js/wiki/dialog_save.js +++ b/src/redakcja/static/js/wiki/dialog_save.js @@ -4,61 +4,60 @@ */ (function($) { - function SaveDialog(element) { - this.ctx = $.wiki.exitContext(); - this.clearForm(); - - /* fill out hidden fields */ - this.$form = $('form', element); - - $("input[name='textsave-parent_revision']", this.$form).val(CurrentDocument.revision); - - $.wiki.cls.GenericDialog.call(this, element); - }; - - SaveDialog.prototype = new $.wiki.cls.GenericDialog(); - - SaveDialog.prototype.cancelAction = function() { - $.wiki.enterContext(this.ctx); - this.hide(); - }; - - SaveDialog.prototype.saveAction = function() { - var self = this; - - self.$elem.block({ - message: "Zapisywanie...
", - fadeIn: 0, - }); + class SaveDialog extends $.wiki.cls.GenericDialog { + constructor(element) { + super(element); + this.ctx = $.wiki.exitContext(); + this.clearForm(); + + /* fill out hidden fields */ + this.$form = $('form', element); + + $("input[name='textsave-parent_revision']", this.$form).val(CurrentDocument.revision); + } + + cancelAction() { + $.wiki.enterContext(this.ctx); + this.hide(); + } + + saveAction() { + var self = this; + + self.$elem.block({ + message: "Zapisywanie...
", + fadeIn: 0, + }); $.wiki.blocking = self.$elem; - try { - - CurrentDocument.save({ - form: self.$form, - success: function(doc, changed, info){ - self.$elem.block({ - message: info, - timeout: 2000, - fadeOut: 0, - onUnblock: function() { - self.hide(); - $.wiki.enterContext(self.ctx); - } - }); - }, - failure: function(doc, info) { - console.log("Failure", info); - self.reportErrors(info); - self.$elem.unblock(); - } - }); - } catch(e) { - console.log('Exception:', e) - self.$elem.unblock(); - } - }; /* end of save dialog */ - - /* make it global */ - $.wiki.cls.SaveDialog = SaveDialog; + try { + + CurrentDocument.save({ + form: self.$form, + success: function(doc, changed, info){ + self.$elem.block({ + message: info, + timeout: 2000, + fadeOut: 0, + onUnblock: function() { + self.hide(); + $.wiki.enterContext(self.ctx); + } + }); + }, + failure: function(doc, info) { + console.log("Failure", info); + self.reportErrors(info); + self.$elem.unblock(); + } + }); + } catch(e) { + console.log('Exception:', e) + self.$elem.unblock(); + } + } + } + + /* make it global */ + $.wiki.cls.SaveDialog = SaveDialog; })(jQuery); diff --git a/src/redakcja/static/js/wiki/view_annotations.js b/src/redakcja/static/js/wiki/view_annotations.js index 771909b9..e7f62391 100644 --- a/src/redakcja/static/js/wiki/view_annotations.js +++ b/src/redakcja/static/js/wiki/view_annotations.js @@ -3,175 +3,171 @@ /* * Perspective */ - function AnnotationsPerspective(options){ - var old_callback = options.callback || function() { }; - - this.vsplitbar = 'PRZYPISY'; - - options.callback = function(){ - var self = this; - - this.$element = $("#side-annotations"); - this.$error = $('.error-message', this.$element); - this.$annos = $('.annotations-list', this.$element); - this.$spinner = $('.spinner', this.$element); - this.$refresh = $('.refresh', this.$element); - - this.$refresh.click(function() { - var $this = $(this); - - self.$refresh.removeClass('active'); - $this.addClass('active'); - var atype = $this.attr('data-tag'); - - self.$annos.hide(); - self.$error.hide(); - self.$spinner.fadeIn(100, function() { - self.refresh(self, atype); - }); - }); - - old_callback.call(this); - }; - - $.wiki.SidebarPerspective.call(this, options); - } - - AnnotationsPerspective.prototype = new $.wiki.SidebarPerspective(); - - AnnotationsPerspective.prototype.updateAnnotationIds = function(self){ - self.annotationToAnchor = {}; - $('#html-view').find('.annotation-inline-box').each( - function(i, annoBox) { - var $annoBox = $(annoBox); - var $anchor = $("a[name|=anchor]", $annoBox); - var htmlContent = $('span', $annoBox).html(); - // TBD: perhaps use a hash of htmlContent as key - self.annotationToAnchor[htmlContent] = $anchor.attr('name'); + class AnnotationsPerspective extends $.wiki.SidebarPerspective { + constructor(options) { + var old_callback = options.callback || function() { }; + + options.callback = function(){ + var self = this; + + this.vsplitbar = 'PRZYPISY'; + this.$element = $("#side-annotations"); + this.$error = $('.error-message', this.$element); + this.$annos = $('.annotations-list', this.$element); + this.$spinner = $('.spinner', this.$element); + this.$refresh = $('.refresh', this.$element); + + this.$refresh.click(function() { + var $this = $(this); + + self.$refresh.removeClass('active'); + $this.addClass('active'); + var atype = $this.attr('data-tag'); + + self.$annos.hide(); + self.$error.hide(); + self.$spinner.fadeIn(100, function() { + self.refresh(atype); + }); }); - }; - - AnnotationsPerspective.prototype.goToAnnotation = function(self, srcNode){ - var content = $(srcNode).html(); - content = content.replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&'); - xml2html({ - xml: ''+content+'', - success: function(txt) { - content = $(txt).html(); - }, - error: function(text) { - $.unblockUI(); - self.$error.html('
' + text + '
'); - self.$spinner.hide(); - self.$error.show(); - } - }); - var anchor = self.annotationToAnchor[content]; - if (anchor != undefined) { - var $htmlView = $("#html-view"); - var top = $htmlView.offset().top + - $("[name=" + anchor + "]", $htmlView).offset().top - - $htmlView.children().eq(0).offset().top; + old_callback.call(this); + }; - $htmlView.animate({scrollTop: top}, 250); + super(options); } - }; - - AnnotationsPerspective.prototype.refresh = function(self, atype) { - var xml; - var persp = $.wiki.activePerspective(); - if (persp == 'CodeMirrorPerspective') { - xml = $.wiki.perspectives[persp].codemirror.getValue(); + updateAnnotationIds() { + let selt = this; + self.annotationToAnchor = {}; + $('#html-view').find('.annotation-inline-box').each( + function(i, annoBox) { + var $annoBox = $(annoBox); + var $anchor = $("a[name|=anchor]", $annoBox); + var htmlContent = $('span', $annoBox).html(); + // TBD: perhaps use a hash of htmlContent as key + self.annotationToAnchor[htmlContent] = $anchor.attr('name'); + } + ); } - else if (persp == 'VisualPerspective') { - html2text({ - element: $('#html-view').find('div').get(0), - success: function(text){ - xml = text; + + goToAnnotation(srcNode) { + let self = this; + var content = $(srcNode).html(); + content = content.replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&'); + xml2html({ + xml: ''+content+'', + success: function(txt) { + content = $(txt).html(); }, - error: function(text){ - self.$error.html('

Wystąpił błąd:

' + text + '
'); + error: function(text) { + $.unblockUI(); + self.$error.html('
' + text + '
'); self.$spinner.hide(); self.$error.show(); } }); - self.updateAnnotationIds(self); - } - else { - xml = this.doc.text; - } - var parser = new DOMParser(); - var serializer = new XMLSerializer(); - var doc = parser.parseFromString(xml, 'text/xml'); - var error = $('parsererror', doc); + var anchor = self.annotationToAnchor[content]; + if (anchor != undefined) { + var $htmlView = $("#html-view"); + var top = $htmlView.offset().top + + $("[name=" + anchor + "]", $htmlView).offset().top - + $htmlView.children().eq(0).offset().top; - if (error.length > 0) { - self.$error.html('
Błąd parsowania XML.'); - self.$spinner.hide(); - self.$error.show(); - } - else { - self.$annos.html(''); - var anno_list = []; - var annos = $(atype, doc); - var counter = annos.length; - var atype_rx = atype.replace(/,/g, '|'); - var ann_expr = new RegExp("^<("+atype_rx+")[^>]*>|$", "g"); - - if (annos.length == 0) - { - self.$annos.html('
Nie ma żadnych przypisów
'); - self.$spinner.hide(); - self.$annos.show(); + $htmlView.animate({scrollTop: top}, 250); } - annos.each(function (i, elem) { - var xml_text = serializer.serializeToString(elem).replace(ann_expr, ""); - xml2html({ - xml: "" + xml_text + "", - success: function(xml_text){ - return function(elem){ - elem.sortby = $(elem).text().trim(); - $(elem).append("
"+ xml_text.replace(/&/g, "&").replace(/"); - anno_list.push(elem); - $(".src", elem).click(function() { self.goToAnnotation(self, this); }); - counter--; - - if (!counter) { - anno_list.sort(function(a, b){return a.sortby.localeCompare(b.sortby);}); - for (i in anno_list) - self.$annos.append(anno_list[i]); - self.$spinner.hide(); - self.$annos.show(); - } + } - } - }(xml_text), - error: function(text) { - $.unblockUI(); - self.$error.html('
' + text + '
'); + refresh(atype) { + let self = this; + var xml; + + var persp = $.wiki.activePerspective(); + if (persp == 'CodeMirrorPerspective') { + xml = $.wiki.perspectives[persp].codemirror.getValue(); + } + else if (persp == 'VisualPerspective') { + html2text({ + element: $('#html-view').find('div').get(0), + success: function(text){ + xml = text; + }, + error: function(text){ + self.$error.html('

Wystąpił błąd:

' + text + '
'); self.$spinner.hide(); self.$error.show(); } }); - }); - } - }; - - - AnnotationsPerspective.prototype.onEnter = function(){ - $.wiki.SidebarPerspective.prototype.onEnter.call(this); - - this.$refresh.filter('.active').trigger('click'); + self.updateAnnotationIds(); + } + else { + xml = this.doc.text; + } - }; + var parser = new DOMParser(); + var serializer = new XMLSerializer(); + var doc = parser.parseFromString(xml, 'text/xml'); + var error = $('parsererror', doc); - AnnotationsPerspective.prototype.onExit = function(success, failure) { + if (error.length > 0) { + self.$error.html('
Błąd parsowania XML.'); + self.$spinner.hide(); + self.$error.show(); + } + else { + self.$annos.html(''); + var anno_list = []; + var annos = $(atype, doc); + var counter = annos.length; + var atype_rx = atype.replace(/,/g, '|'); + var ann_expr = new RegExp("^<("+atype_rx+")[^>]*>|$", "g"); + + if (annos.length == 0) + { + self.$annos.html('
Nie ma żadnych przypisów
'); + self.$spinner.hide(); + self.$annos.show(); + } + annos.each(function (i, elem) { + var xml_text = serializer.serializeToString(elem).replace(ann_expr, ""); + xml2html({ + xml: "" + xml_text + "", + success: function(xml_text){ + return function(elem){ + elem.sortby = $(elem).text().trim(); + $(elem).append("
"+ xml_text.replace(/&/g, "&").replace(/"); + anno_list.push(elem); + $(".src", elem).click(function() { self.goToAnnotation(this); }); + counter--; + + if (!counter) { + anno_list.sort(function(a, b){return a.sortby.localeCompare(b.sortby);}); + for (i in anno_list) + self.$annos.append(anno_list[i]); + self.$spinner.hide(); + self.$annos.show(); + } + } + }(xml_text), + error: function(text) { + $.unblockUI(); + self.$error.html('
' + text + '
'); + self.$spinner.hide(); + self.$error.show(); + } + }); + }); + } + } + onEnter() { + super.onEnter(); + this.$refresh.filter('.active').trigger('click'); }; + onExit(success, failure) {}; + } $.wiki.AnnotationsPerspective = AnnotationsPerspective; })(jQuery); diff --git a/src/redakcja/static/js/wiki/view_column_diff.js b/src/redakcja/static/js/wiki/view_column_diff.js index 33ffb6a0..beb36ed5 100644 --- a/src/redakcja/static/js/wiki/view_column_diff.js +++ b/src/redakcja/static/js/wiki/view_column_diff.js @@ -1,35 +1,28 @@ (function($){ - function DiffPerspective(options) { - var old_callback = options.callback || function() {}; - var self = this; - - options.callback = function(){ - self.base_id = options.base_id; - old_callback.call(this); - }; - - $.wiki.Perspective.call(this, options); - }; - - DiffPerspective.prototype = new $.wiki.Perspective(); - - DiffPerspective.prototype.freezeState = function(){ - // must - }; - - DiffPerspective.prototype.destroy = function() { - $.wiki.switchToTab('#HistoryPerspective'); - $('#' + this.base_id).remove(); - $('#' + this.perspective_id).remove(); - }; - - DiffPerspective.prototype.onEnter = function(success, failure){ - $.wiki.Perspective.prototype.onEnter.call(this); - console.log("Entered diff view"); - }; - - $.wiki.DiffPerspective = DiffPerspective; + class DiffPerspective extends $.wiki.Perspective { + constructor(options) { + var old_callback = options.callback || function() {}; + + options.callback = function() { + var self = this; + self.base_id = options.base_id; + old_callback.call(this); + }; + super(options); + } + + freezeState() { + // must + }; + + destroy() { + $.wiki.switchToTab('#HistoryPerspective'); + $('#' + this.base_id).remove(); + $('#' + this.perspective_id).remove(); + } + } + $.wiki.DiffPerspective = DiffPerspective; })(jQuery); diff --git a/src/redakcja/static/js/wiki/view_editor_source.js b/src/redakcja/static/js/wiki/view_editor_source.js index ab8eaf08..0766acfb 100644 --- a/src/redakcja/static/js/wiki/view_editor_source.js +++ b/src/redakcja/static/js/wiki/view_editor_source.js @@ -1,76 +1,73 @@ (function($) { - function CodeMirrorPerspective(options) { - var old_callback = options.callback; - options.callback = function(){ - var self = this; - - this.codemirror = CodeMirror.fromTextArea($( - '#codemirror_placeholder').get(0), { - mode: 'xml', - lineWrapping: true, - lineNumbers: true, - readOnly: CurrentDocument.readonly || false, - identUnit: 0, + class CodeMirrorPerspective extends $.wiki.Perspective { + constructor(options) { + var old_callback = options.callback; + options.callback = function(){ + var self = this; + + this.codemirror = CodeMirror.fromTextArea($( + '#codemirror_placeholder').get(0), { + mode: 'xml', + lineWrapping: true, + lineNumbers: true, + readOnly: CurrentDocument.readonly || false, + identUnit: 0, + }); + + $('#source-editor').keydown(function(event) { + if(!event.altKey) + return; + + var c = event.key; + var button = $("#source-editor button[data-ui-accesskey='"+c+"']"); + if(button.length == 0) + return; + button.get(0).click(); + event.preventDefault(); }); + $('#source-editor .toolbar').toolbarize({ + actionContext: self.codemirror + }); - $('#source-editor').keydown(function(event) { - if(!event.altKey) - return; - - var c = event.key; - var button = $("#source-editor button[data-ui-accesskey='"+c+"']"); - if(button.length == 0) - return; - button.get(0).click(); - event.preventDefault(); - }); - - $('#source-editor .toolbar').toolbarize({ - actionContext: self.codemirror - }); - - // textarea is no longer needed - $('#codemirror_placeholder').remove(); - old_callback.call(self); - } - - $.wiki.Perspective.call(this, options); - }; - - - CodeMirrorPerspective.prototype = new $.wiki.Perspective(); + // textarea is no longer needed + $('#codemirror_placeholder').remove(); + old_callback.call(self); + } + super(options); + } - CodeMirrorPerspective.prototype.freezeState = function() { - this.config().position = this.codemirror.getScrollInfo().top; - }; + freezeState() { + this.config().position = this.codemirror.getScrollInfo().top; + } - CodeMirrorPerspective.prototype.unfreezeState = function () { - this.codemirror.scrollTo(0, this.config().position || 0); - }; + unfreezeState () { + this.codemirror.scrollTo(0, this.config().position || 0); + } - CodeMirrorPerspective.prototype.onEnter = function(success, failure) { - $.wiki.Perspective.prototype.onEnter.call(this); + onEnter(success, failure) { + super.onEnter(); - this.codemirror.setValue(this.doc.text); + this.codemirror.setValue(this.doc.text); - this.unfreezeState(this._uistate); + this.unfreezeState(this._uistate); - if(success) success(); - } + if(success) success(); + } - CodeMirrorPerspective.prototype.onExit = function(success, failure) { - this.freezeState(); + onExit(success, failure) { + this.freezeState(); - $.wiki.Perspective.prototype.onExit.call(this); - this.doc.setText(this.codemirror.getValue()); + super.onExit(); + this.doc.setText(this.codemirror.getValue()); $.wiki.exitTab('#SearchPerspective'); - if(success) success(); - } + if(success) success(); + } + } - $.wiki.CodeMirrorPerspective = CodeMirrorPerspective; + $.wiki.CodeMirrorPerspective = CodeMirrorPerspective; })(jQuery); diff --git a/src/redakcja/static/js/wiki/view_editor_wysiwyg.js b/src/redakcja/static/js/wiki/view_editor_wysiwyg.js index bd67db6c..c8f84e1f 100644 --- a/src/redakcja/static/js/wiki/view_editor_wysiwyg.js +++ b/src/redakcja/static/js/wiki/view_editor_wysiwyg.js @@ -121,9 +121,6 @@ - - - /* Insert theme using current selection */ function addTheme(){ @@ -141,11 +138,9 @@ return false; } - // remember the selected range var range = selection.getRangeAt(0); - if ($(range.startContainer).is('.html-editarea') || $(range.endContainer).is('.html-editarea')) { window.alert("Motywy można oznaczać tylko na tekście nie otwartym do edycji. \n Zamknij edytowany fragment i spróbuj ponownie."); @@ -294,20 +289,20 @@ if (insertVal.length == 2) { var startTag = insertVal[0]; var endTag = insertVal[1]; - var textAreaOpened = editArea; - //IE support - if (document.selection) { - textAreaOpened.focus(); - sel = document.selection.createRange(); - sel.text = startTag + sel.text + endTag; - } - //MOZILLA/NETSCAPE support - else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') { - var startPos = textAreaOpened.selectionStart; - var endPos = textAreaOpened.selectionEnd; - textAreaOpened.value = textAreaOpened.value.substring(0, startPos) - + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length); - } + var textAreaOpened = editArea; + //IE support + if (document.selection) { + textAreaOpened.focus(); + sel = document.selection.createRange(); + sel.text = startTag + sel.text + endTag; + } + //MOZILLA/NETSCAPE support + else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') { + var startPos = textAreaOpened.selectionStart; + var endPos = textAreaOpened.selectionEnd; + textAreaOpened.value = textAreaOpened.value.substring(0, startPos) + + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length); + } } else { insertAtCaret(editArea, insertVal); } @@ -432,7 +427,7 @@ if ($origin.is('*[x-edit-no-format]')) { - $('.akap-edit-button').remove(); + $('.akap-edit-button').remove(); } if ($origin.is('[x-node="motyw"]')) { @@ -516,7 +511,6 @@ xml = '<' + nodeName + '>' + insertedText + ''; } - xml2html({ xml: xml, success: function(element){ @@ -545,42 +539,42 @@ }); } - $('.akap-edit-button', $overlay).click(function(){ - var textAreaOpened = $('textarea', $overlay)[0]; - var startTag = ""; - var endTag = ""; - var buttonName = this.innerHTML; - - if(buttonName == "słowo obce") { - startTag = ""; - endTag = ""; - } else if (buttonName == "wyróżnienie") { - startTag = ""; - endTag = ""; - } else if (buttonName == "tytuł dzieła") { - startTag = ""; - endTag = ""; - } else if(buttonName == "znak spec."){ - addSymbol(); - return false; - } - - var myField = textAreaOpened; - - //IE support - if (document.selection) { - textAreaOpened.focus(); - sel = document.selection.createRange(); - sel.text = startTag + sel.text + endTag; - } - //MOZILLA/NETSCAPE support - else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') { - var startPos = textAreaOpened.selectionStart; - var endPos = textAreaOpened.selectionEnd; - textAreaOpened.value = textAreaOpened.value.substring(0, startPos) - + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length); - } - }); + $('.akap-edit-button', $overlay).click(function(){ + var textAreaOpened = $('textarea', $overlay)[0]; + var startTag = ""; + var endTag = ""; + var buttonName = this.innerHTML; + + if(buttonName == "słowo obce") { + startTag = ""; + endTag = ""; + } else if (buttonName == "wyróżnienie") { + startTag = ""; + endTag = ""; + } else if (buttonName == "tytuł dzieła") { + startTag = ""; + endTag = ""; + } else if(buttonName == "znak spec."){ + addSymbol(); + return false; + } + + var myField = textAreaOpened; + + //IE support + if (document.selection) { + textAreaOpened.focus(); + sel = document.selection.createRange(); + sel.text = startTag + sel.text + endTag; + } + //MOZILLA/NETSCAPE support + else if (textAreaOpened.selectionStart || textAreaOpened.selectionStart == '0') { + var startPos = textAreaOpened.selectionStart; + var endPos = textAreaOpened.selectionEnd; + textAreaOpened.value = textAreaOpened.value.substring(0, startPos) + + startTag + textAreaOpened.value.substring(startPos, endPos) + endTag + textAreaOpened.value.substring(endPos, textAreaOpened.value.length); + } + }); $('.accept-button', $overlay).click(function(){ save(); @@ -613,272 +607,285 @@ }); } - function VisualPerspective(options){ - perspective = self = this; - - var old_callback = options.callback; - - options.callback = function(){ - var element = $("#html-view"); - var button = $(''); - var uwagaButton = $(''); + class VisualPerspective extends $.wiki.Perspective { + constructor(options) { + var old_callback = options.callback; + + options.callback = function(){ + let self = this; + var element = $("#html-view"); + var button = $(''); + var uwagaButton = $(''); + + if (!CurrentDocument.readonly) { + + $('#html-view').bind('mousemove', function(event){ + var editable = $(event.target).closest('*[x-editable]'); + $('.active', element).not(editable).removeClass('active').children('.active-block-button').remove(); + + if (!editable.hasClass('active')) { + editable.addClass('active').append(button); + if (!editable.is('[x-edit-attribute]') && + !editable.is('.annotation-inline-box') && + !editable.is('[x-edit-no-format]') + ) { + editable.append(uwagaButton); + } + } + if (editable.is('.annotation-inline-box')) { + $('*[x-annotation-box]', editable).css({ + }).show(); + } + }); - if (!CurrentDocument.readonly) { + self.caret = new Caret(element); - $('#html-view').bind('mousemove', function(event){ - var editable = $(event.target).closest('*[x-editable]'); - $('.active', element).not(editable).removeClass('active').children('.active-block-button').remove(); + $('#insert-reference-button').click(function(){ + self.addReference(); + return false; + }); - if (!editable.hasClass('active')) { - editable.addClass('active').append(button); - if (!editable.is('[x-edit-attribute]') && - !editable.is('.annotation-inline-box') && - !editable.is('[x-edit-no-format]') - ) { - editable.append(uwagaButton); - } - } - if (editable.is('.annotation-inline-box')) { - $('*[x-annotation-box]', editable).css({ - }).show(); - } - }); + $('#insert-annotation-button').click(function(){ + addAnnotation(); + return false; + }); - perspective.caret = new Caret(element); - - $('#insert-reference-button').click(function(){ - self.addReference(); - return false; - }); + $('#insert-theme-button').click(function(){ + addTheme(); + return false; + }); - $('#insert-annotation-button').click(function(){ - addAnnotation(); - return false; - }); - $('#insert-theme-button').click(function(){ - addTheme(); - return false; - }); + $(".insert-inline-tag").click(function() { + self.insertInlineTag($(this).attr('data-tag')); + return false; + }); + $(".insert-char").click(function() { + addSymbol(caret=self.caret); + return false; + }); - $(".insert-inline-tag").click(function() { - perspective.insertInlineTag($(this).attr('data-tag')); - return false; - }); + $(document).on('click', '.edit-button', function(event){ + event.preventDefault(); + openForEdit($(this).parent()); + }); - $(".insert-char").click(function() { - addSymbol(caret=perspective.caret); - return false; - }); + $(document).on('click', '.uwaga-button', function(event){ + event.preventDefault(); + createUwagaBefore($(this).parent()); + }); + } - $(document).on('click', '.edit-button', function(event){ - event.preventDefault(); - openForEdit($(this).parent()); + $(document).on('click', '[x-node="motyw"]', function(){ + selectTheme($(this).attr('theme-class')); }); - $(document).on('click', '.uwaga-button', function(event){ + element.on('click', '.annotation', function(event) { event.preventDefault(); - createUwagaBefore($(this).parent()); + event.redakcja_caret_ignore = true; + $('[x-annotation-box]', $(this).parent()).toggleClass('editing'); + self.caret.detach(); }); - } - - $(document).on('click', '[x-node="motyw"]', function(){ - selectTheme($(this).attr('theme-class')); - }); - - element.on('click', '.annotation', function(event) { - event.preventDefault(); - event.redakcja_caret_ignore = true; - $('[x-annotation-box]', $(this).parent()).toggleClass('editing'); - perspective.caret.detach(); - }); - - old_callback.call(this); - }; - - $.wiki.Perspective.call(this, options); - }; - - VisualPerspective.prototype = new $.wiki.Perspective(); - VisualPerspective.prototype.onEnter = function(success, failure){ - $.wiki.Perspective.prototype.onEnter.call(this); - - $.blockUI({ - message: 'Uaktualnianie widoku...' - }); + old_callback.call(this); + }; - function _finalize(callback){ - $.unblockUI(); - if (callback) - callback(); + super(options); } - perspective = this; - xml2html({ - xml: this.doc.text, - base: this.doc.getBase(), - success: function(element){ + onEnter(success, failure) { + super.onEnter(); - var htmlView = $('#html-view'); - htmlView.html(element); + $.blockUI({ + message: 'Uaktualnianie widoku...' + }); - _finalize(success); - }, - error: function(text, source){ - err = '

Wystąpił błąd:

'+text+'

'; - if (source) - err += '
'+source.replace(/&/g, '&').replace(/'
-                $('#html-view').html(err);
-                _finalize(failure);
+            function _finalize(callback){
+                $.unblockUI();
+                if (callback)
+                    callback();
             }
-        });
-    };
 
-    VisualPerspective.prototype.onExit = function(success, failure){
-        var self = this;
+            xml2html({
+                xml: this.doc.text,
+                base: this.doc.getBase(),
+                success: function(element){
+
+                    var htmlView = $('#html-view');
+                    htmlView.html(element);
+
+                    _finalize(success);
+                },
+                error: function(text, source){
+                    let err = '

Wystąpił błąd:

'+text+'

'; + if (source) + err += '
'+source.replace(/&/g, '&').replace(/'
+                    $('#html-view').html(err);
+                    _finalize(failure);
+                }
+            });
+        };
 
-        self.caret.detach();
+        onExit(success, failure) {
+            var self = this;
 
-        $.wiki.exitTab('#PropertiesPerspective');
-        
-        $.blockUI({
-            message: 'Zapisywanie widoku...'
-        });
+            self.caret.detach();
 
-        function _finalize(callback){
-            $.unblockUI();
-            if (callback)
-                callback();
-        }
+            $.wiki.exitTab('#PropertiesPerspective');
 
-        if ($('#html-view .error').length > 0)
-            return _finalize(failure);
+            $.blockUI({
+                message: 'Zapisywanie widoku...'
+            });
 
-        html2text({
-            element: $('#html-view').get(0),
-            stripOuter: true,
-            success: function(text){
-                self.doc.setText(text);
-                _finalize(success);
-            },
-            error: function(text){
-                $('#source-editor').html('

Wystąpił błąd:

' + text + '
'); - _finalize(failure); + function _finalize(callback){ + $.unblockUI(); + if (callback) + callback(); } - }); - }; - VisualPerspective.prototype.insertInlineTag = function(tag) { - this.caret.detach(); + if ($('#html-view .error').length > 0) + return _finalize(failure); + + html2text({ + element: $('#html-view').get(0), + stripOuter: true, + success: function(text){ + self.doc.setText(text); + _finalize(success); + }, + error: function(text){ + $('#source-editor').html('

Wystąpił błąd:

' + text + '
'); + _finalize(failure); + } + }); + }; - let selection = window.getSelection(); - var n = selection.rangeCount; - if (n != 1 || selection.isCollapsed) { - window.alert("Nie zaznaczono obszaru"); - return false - } - let range = selection.getRangeAt(0); + insertInlineTag(tag) { + this.caret.detach(); - // Make sure that: - // Both ends are in the same x-node container. - // TODO: That the container is a inline-text container. - let node = range.startContainer; - if (node.nodeType == node.TEXT_NODE) { - node = node.parentNode; - } - let endNode = range.endContainer; - if (endNode.nodeType == endNode.TEXT_NODE) { - endNode = endNode.parentNode; - } - if (node != endNode) { - window.alert("Zły obszar."); - return false; - } + let selection = window.getSelection(); + var n = selection.rangeCount; + if (n != 1 || selection.isCollapsed) { + window.alert("Nie zaznaczono obszaru"); + return false + } + let range = selection.getRangeAt(0); - // We will construct a HTML element with the range selected. - let div = $(""); + // Make sure that: + // Both ends are in the same x-node container. + // Both ends are set to text nodes. + // TODO: That the container is a inline-text container. + let commonNode = range.endContainer; - contents = $(node).contents(); - let startChildIndex = node == range.startContainer ? 0 : contents.index(range.startContainer); - let endChildIndex = contents.index(range.endContainer); + if (commonNode.nodeType == Node.TEXT_NODE) { + commonNode = commonNode.parentNode; + } + let node = range.startContainer; + if (node.nodeType == Node.TEXT_NODE) { + node = node.parentNode; + } + if (node != commonNode) { + window.alert("Zły obszar."); + return false; + } - current = range.startContainer; - if (current.nodeType == current.TEXT_NODE) { - current = current.splitText(range.startOffset); - } - while (current != range.endContainer) { - n = current.nextSibling; - $(current).appendTo(div); - current = n; - } - if (current.nodeType == current.TEXT_NODE) { - end = current.splitText(range.endOffset); - } - $(current).appendTo(div); - - html2text({ - element: div[0], - success: function(d) { - xml2html({ - xml: d = '<' + tag + '>' + d + '', - success: function(html) { - // What if no end? - node.insertBefore($(html)[0], end); - } - }); - }, - error: function(a, b) { - console.log(a, b); + let end; + if (range.endContainer.nodeType == Node.TEXT_NODE) { + end = range.endContainer.splitText(range.endOffset); + } else { + end = document.createTextNode(''); + let cont = $(range.endContainer).contents(); + if (range.endOffset < cont.length) { + range.endContainer.insertBefore(end, cont[range.endOffset]) + } else { + range.endContainer.append(end); + } } - }); - }; - VisualPerspective.prototype.insertAtRange = function(range, elem) { - let self = this; - let $end = $(range.endContainer); - if ($end.attr('id') == 'caret') { - self.caret.insert(elem); - } else { - range.insertNode(elem[0]); - } - } + let current; + if (range.startContainer.nodeType == Node.TEXT_NODE) { + current = range.startContainer.splitText(range.startOffset); + } else { + current = document.createTextNode(''); + let cont = $(range.startContainer).contents(); + if (range.startOffset < cont.length) { + range.startContainer.insertBefore(current, cont[range.startOffset]) + } else { + startNode.append(current); + } + } - VisualPerspective.prototype.addReference = function() { - let self = this; - var selection = window.getSelection(); - var n = selection.rangeCount; + // We will construct a HTML element with the range selected. + let div = $(""); + while (current != end) { + n = current.nextSibling; + $(current).appendTo(div); + current = n; + } - // TODO: if no selection, take caret position.. - if (n == 0) { - window.alert("Nie zaznaczono żadnego obszaru"); - return false; + html2text({ + element: div[0], + success: function(d) { + xml2html({ + xml: d = '<' + tag + '>' + d + '', + success: function(html) { + // What if no end? + node.insertBefore($(html)[0], end); + } + }); + }, + error: function(a, b) { + console.log(a, b); + } + }); } - var range = selection.getRangeAt(n - 1); - if (!verifyTagInsertPoint(range.endContainer)) { - window.alert("Nie można wstawić w to miejsce referencji."); - return false; + insertAtRange(range, elem) { + let self = this; + let $end = $(range.endContainer); + if ($end.attr('id') == 'caret') { + self.caret.insert(elem); + } else { + range.insertNode(elem[0]); + } } - var tag = $(''); + addReference() { + let self = this; + var selection = window.getSelection(); + var n = selection.rangeCount; - range.collapse(false); - self.insertAtRange(range, tag); + // TODO: if no selection, take caret position.. + if (n == 0) { + window.alert("Nie zaznaczono żadnego obszaru"); + return false; + } - xml2html({ - xml: '', - success: function(text){ - var t = $(text); - tag.replaceWith(t); - openForEdit(t); - }, - error: function(){ - tag.remove(); - alert('Błąd przy dodawaniu referncji:' + errors); + var range = selection.getRangeAt(n - 1); + if (!verifyTagInsertPoint(range.endContainer)) { + window.alert("Nie można wstawić w to miejsce referencji."); + return false; } - }) + + var tag = $(''); + + range.collapse(false); + self.insertAtRange(range, tag); + + xml2html({ + xml: '', + success: function(text){ + var t = $(text); + tag.replaceWith(t); + openForEdit(t); + }, + error: function(){ + tag.remove(); + alert('Błąd przy dodawaniu referncji:' + errors); + } + }) + } } $.wiki.VisualPerspective = VisualPerspective; diff --git a/src/redakcja/static/js/wiki/view_gallery.js b/src/redakcja/static/js/wiki/view_gallery.js index bb1c3d8a..ac91d79b 100644 --- a/src/redakcja/static/js/wiki/view_gallery.js +++ b/src/redakcja/static/js/wiki/view_gallery.js @@ -44,266 +44,259 @@ /* * Perspective */ - function ScanGalleryPerspective(options){ - var old_callback = options.callback || function() { }; - - this.vsplitbar = 'GALERIA'; - - options.callback = function(){ - var self = this; - - this.dimensions = {}; - this.zoomFactor = 1; - if (this.config().page == undefined) - this.config().page = CurrentDocument.galleryStart; - this.$element = $("#side-gallery"); - this.$numberInput = $('.page-number', this.$element); - - // ... - var origin = {}; - var imageOrigin = {}; - - this.$image = $('.gallery-image img', this.$element).attr('unselectable', 'on'); + class ScanGalleryPerspective extends $.wiki.SidebarPerspective { + constructor(options){ + var old_callback = options.callback || function() { }; + + options.callback = function(){ + var self = this; + + this.vsplitbar = 'GALERIA'; + this.dimensions = {}; + this.zoomFactor = 1; + if (this.config().page == undefined) + this.config().page = CurrentDocument.galleryStart; + this.$element = $("#side-gallery"); + this.$numberInput = $('.page-number', this.$element); + + // ... + var origin = {}; + var imageOrigin = {}; + + this.$image = $('.gallery-image img', this.$element).attr('unselectable', 'on'); + + // button handlers + this.$numberInput.change(function(event){ + event.preventDefault(); + self.setPage($(this).val()); + }); - // button handlers - this.$numberInput.change(function(event){ - event.preventDefault(); - self.setPage($(this).val()); - }); - - $('.start-page', this.$element).click(function(){ - self.setPage(CurrentDocument.galleryStart); - }); + $('.start-page', this.$element).click(function(){ + self.setPage(CurrentDocument.galleryStart); + }); - $('.previous-page', this.$element).click(function(){ - self.setPage(parseInt(self.$numberInput.val(),10) - 1); - }); + $('.previous-page', this.$element).click(function(){ + self.setPage(parseInt(self.$numberInput.val(),10) - 1); + }); - $('.next-page', this.$element).click(function(){ - self.setPage(parseInt(self.$numberInput.val(),10) + 1); - }); + $('.next-page', this.$element).click(function(){ + self.setPage(parseInt(self.$numberInput.val(),10) + 1); + }); - $('.zoom-in', this.$element).click(function(){ - self.alterZoom(0.2); - }); + $('.zoom-in', this.$element).click(function(){ + self.alterZoom(0.2); + }); - $('.zoom-out', this.$element).click(function(){ - self.alterZoom((-0.2)); - }); + $('.zoom-out', this.$element).click(function(){ + self.alterZoom((-0.2)); + }); - $('.ctrl-gallery-setstart', this.$element).click(function(e) { - e.preventDefault(); - CurrentDocument.setGalleryStart(self.config().page); - }); - $('.ctrl-gallery-edit', this.$element).click(function(e) { - e.preventDefault(); - CurrentDocument.openGalleryEdit(); - }); - $('.ctrl-gallery-refresh', this.$element).click(function(e) { - e.preventDefault(); - self.refreshGallery(); - }); - $('#gallery-chooser').on('show.bs.modal', function (event) { - var modal = $(this); - var datalist = modal.find('.modal-body'); - datalist.html(''); - self.doc.withGalleryList(function(galleries) { - console.log(galleries); - $.each(galleries, (i, gallery) => { - item = $('
'); - $('input', item).val(gallery); - $('label', item).append(gallery); - if (gallery == self.doc.galleryLink) { - item.addClass('text-primary') - $('input', item).prop('checked', true); - } + $('.ctrl-gallery-setstart', this.$element).click(function(e) { + e.preventDefault(); + CurrentDocument.setGalleryStart(self.config().page); + }); + $('.ctrl-gallery-edit', this.$element).click(function(e) { + e.preventDefault(); + CurrentDocument.openGalleryEdit(); + }); + $('.ctrl-gallery-refresh', this.$element).click(function(e) { + e.preventDefault(); + self.refreshGallery(); + }); + $('#gallery-chooser').on('show.bs.modal', function (event) { + var modal = $(this); + var datalist = modal.find('.modal-body'); + datalist.html(''); + self.doc.withGalleryList(function(galleries) { + let item; + $.each(galleries, (i, gallery) => { + item = $('
'); + $('input', item).val(gallery); + $('label', item).append(gallery); + if (gallery == self.doc.galleryLink) { + item.addClass('text-primary') + $('input', item).prop('checked', true); + } + item.appendTo(datalist); + }); + item = $('
'); + item.appendTo(datalist); + item = $('
'); item.appendTo(datalist); }); - item = $('
'); - item.appendTo(datalist); - item = $('
'); - item.appendTo(datalist); - }); - }) - $('#gallery-chooser .ctrl-ok').on('click', function (event) { - let item = $('#gallery-chooser :checked'); - let name; - if (item.hasClass('ctrl-none')) { - name = ''; - } - else if (item.hasClass('ctrl-new')) { - name = $('#gallery-chooser .ctrl-name').val(); - } else { - name = item.val(); - } - - self.doc.setGallery(name); - $('#gallery-chooser').modal('hide'); - self.refreshGallery(function() { - self.setPage(1); + }) + $('#gallery-chooser .ctrl-ok').on('click', function (event) { + let item = $('#gallery-chooser :checked'); + let name; + if (item.hasClass('ctrl-none')) { + name = ''; + } + else if (item.hasClass('ctrl-new')) { + name = $('#gallery-chooser .ctrl-name').val(); + } else { + name = item.val(); + } + + self.doc.setGallery(name); + $('#gallery-chooser').modal('hide'); + self.refreshGallery(function() { + self.setPage(1); + }); }); - }); - - $(window).resize(function(){ - self.dimensions.galleryWidth = self.$image.parent().width(); - self.dimensions.galleryHeight = self.$image.parent().height(); - }); - - this.$image.load(function(){ - console.log("Image loaded.") - self._resizeImage(); - }).bind('mousedown', function() { - self.imageMoveStart.apply(self, arguments); - }); + $(window).resize(function(){ + self.dimensions.galleryWidth = self.$image.parent().width(); + self.dimensions.galleryHeight = self.$image.parent().height(); + }); + this.$image.load(function(){ + self._resizeImage(); + }).bind('mousedown', function() { + self.imageMoveStart.apply(self, arguments); + }); - old_callback.call(this); - }; + old_callback.call(this); + }; - $.wiki.SidebarPerspective.call(this, options); - }; + super(options); + } - ScanGalleryPerspective.prototype = new $.wiki.SidebarPerspective(); + _resizeImage() { + var $img = this.$image; - ScanGalleryPerspective.prototype._resizeImage = function(){ - var $img = this.$image; + $img.css({ + width: '', + height: '' + }); - $img.css({ - width: '', - height: '' - }); + this.dimensions = { + width: $img.width() * this.zoomFactor, + height: $img.height() * this.zoomFactor, + originWidth: $img.width(), + originHeight: $img.height(), + galleryWidth: $img.parent().width(), + galleryHeight: $img.parent().height() + }; + + if (!(this.dimensions.width && this.dimensions.height)) { + setTimeout(function(){ + $img.load(); + }, 100); + } - this.dimensions = { - width: $img.width() * this.zoomFactor, - height: $img.height() * this.zoomFactor, - originWidth: $img.width(), - originHeight: $img.height(), - galleryWidth: $img.parent().width(), - galleryHeight: $img.parent().height() - }; + var position = normalizePosition($img.position().left, $img.position().top, this.dimensions.galleryWidth, this.dimensions.galleryHeight, this.dimensions.width, this.dimensions.height); - if (!(this.dimensions.width && this.dimensions.height)) { - setTimeout(function(){ - $img.load(); - }, 100); + $img.css({ + left: position.x, + top: position.y, + width: $img.width() * this.zoomFactor, + height: $img.height() * this.zoomFactor + }); } - var position = normalizePosition($img.position().left, $img.position().top, this.dimensions.galleryWidth, this.dimensions.galleryHeight, this.dimensions.width, this.dimensions.height); - - $img.css({ - left: position.x, - top: position.y, - width: $img.width() * this.zoomFactor, - height: $img.height() * this.zoomFactor - }); - }; + setPage(newPage) { + newPage = normalizeNumber(newPage, this.doc.galleryImages.length); + this.$numberInput.val(newPage); + this.config().page = newPage; + $('.gallery-image img', this.$element).attr('src', this.doc.galleryImages[newPage - 1].url); + } - ScanGalleryPerspective.prototype.setPage = function(newPage){ - newPage = normalizeNumber(newPage, this.doc.galleryImages.length); - this.$numberInput.val(newPage); - this.config().page = newPage; - $('.gallery-image img', this.$element).attr('src', this.doc.galleryImages[newPage - 1].url); - }; + alterZoom(delta) { + var zoomFactor = this.zoomFactor + delta; + if (zoomFactor < 0.2) + zoomFactor = 0.2; + if (zoomFactor > 2) + zoomFactor = 2; + this.setZoom(zoomFactor); + } - ScanGalleryPerspective.prototype.alterZoom = function(delta){ - var zoomFactor = this.zoomFactor + delta; - if (zoomFactor < 0.2) - zoomFactor = 0.2; - if (zoomFactor > 2) - zoomFactor = 2; - this.setZoom(zoomFactor); - }; + setZoom(factor) { + this.zoomFactor = factor; + this.dimensions.width = this.dimensions.originWidth * this.zoomFactor; + this.dimensions.height = this.dimensions.originHeight * this.zoomFactor; - ScanGalleryPerspective.prototype.setZoom = function(factor){ - this.zoomFactor = factor; + // var position = normalizePosition(this.$image.position().left, this.$image.position().top, this.dimensions.galleryWidth, this.dimensions.galleryHeight, this.dimensions.width, this.dimensions.height); - this.dimensions.width = this.dimensions.originWidth * this.zoomFactor; - this.dimensions.height = this.dimensions.originHeight * this.zoomFactor; + this._resizeImage(); + } - // var position = normalizePosition(this.$image.position().left, this.$image.position().top, this.dimensions.galleryWidth, this.dimensions.galleryHeight, this.dimensions.width, this.dimensions.height); + /* + * Movement + */ + imageMoved(event) { + event.preventDefault(); - this._resizeImage(); - }; + // origin is where the drag started + // imageOrigin is where the drag started on the image - /* - * Movement - */ - ScanGalleryPerspective.prototype.imageMoved = function(event){ - event.preventDefault(); + var newX = event.clientX - this.origin.x + this.imageOrigin.left; + var newY = event.clientY - this.origin.y + this.imageOrigin.top; - // origin is where the drag started - // imageOrigin is where the drag started on the image + var position = normalizePosition(newX, newY, this.dimensions.galleryWidth, this.dimensions.galleryHeight, this.dimensions.width, this.dimensions.height); - var newX = event.clientX - this.origin.x + this.imageOrigin.left; - var newY = event.clientY - this.origin.y + this.imageOrigin.top; + this.$image.css({ + left: position.x, + top: position.y, + }); - var position = normalizePosition(newX, newY, this.dimensions.galleryWidth, this.dimensions.galleryHeight, this.dimensions.width, this.dimensions.height); + return false; + } - this.$image.css({ - left: position.x, - top: position.y, - }); + imageMoveStart(event) { + event.preventDefault(); - return false; - }; + var self = this; - ScanGalleryPerspective.prototype.imageMoveStart = function(event){ - event.preventDefault(); + this.origin = { + x: event.clientX, + y: event.clientY + }; - var self = this; + this.imageOrigin = self.$image.position(); + $(document).bind('mousemove.gallery', function(){ + self.imageMoved.apply(self, arguments); + }).bind('mouseup.gallery', function() { + self.imageMoveStop.apply(self, arguments); + }); - this.origin = { - x: event.clientX, - y: event.clientY - }; + return false; + } - this.imageOrigin = self.$image.position(); - $(document).bind('mousemove.gallery', function(){ - self.imageMoved.apply(self, arguments); - }).bind('mouseup.gallery', function() { - self.imageMoveStop.apply(self, arguments); - }); + imageMoveStop(event) { + $(document).unbind('mousemove.gallery').unbind('mouseup.gallery'); + } - return false; - }; + /* + * Loading gallery + */ + refreshGallery(success, failure) { + var self = this; + this.doc.refreshGallery({ + success: function(doc, data){ + self.$image.show(); + console.log("gconfig:", self.config().page ); + self.setPage( self.config().page ); + $('#imagesCount').html("/" + doc.galleryImages.length); + + $('.error_message', self.$element).hide(); + if(success) success(); + }, + failure: function(doc, message){ + self.$image.hide(); + $('.error_message', self.$element).show().html(message); + if(failure) failure(); + } + }); + } - ScanGalleryPerspective.prototype.imageMoveStop = function(event){ - $(document).unbind('mousemove.gallery').unbind('mouseup.gallery'); - }; + onEnter(success, failure) { + super.onEnter() + this.refreshGallery(success, failure); + } - /* - * Loading gallery - */ - ScanGalleryPerspective.prototype.refreshGallery = function(success, failure) { - var self = this; - this.doc.refreshGallery({ - success: function(doc, data){ - self.$image.show(); - console.log("gconfig:", self.config().page ); - self.setPage( self.config().page ); - $('#imagesCount').html("/" + doc.galleryImages.length); - - $('.error_message', self.$element).hide(); - if(success) success(); - }, - failure: function(doc, message){ - self.$image.hide(); - $('.error_message', self.$element).show().html(message); - if(failure) failure(); - } - }); + onExit(success, failure) { + }; } - - ScanGalleryPerspective.prototype.onEnter = function(success, failure){ - $.wiki.SidebarPerspective.prototype.onEnter.call(this); - this.refreshGallery(success, failure); - }; - - ScanGalleryPerspective.prototype.onExit = function(success, failure) { - - }; - $.wiki.ScanGalleryPerspective = ScanGalleryPerspective; })(jQuery); diff --git a/src/redakcja/static/js/wiki/view_history.js b/src/redakcja/static/js/wiki/view_history.js index c56b7f7a..e9693b71 100644 --- a/src/redakcja/static/js/wiki/view_history.js +++ b/src/redakcja/static/js/wiki/view_history.js @@ -1,219 +1,215 @@ (function($){ - function HistoryPerspective(options) { - var old_callback = options.callback || function() {}; - - options.callback = function() { - var self = this; - if (CurrentDocument.diff) { - rev_from = CurrentDocument.diff[0]; - rev_to = CurrentDocument.diff[1]; - this.doc.fetchDiff({ - from: rev_from, - to: rev_to, - success: function(doc, data){ - var result = $.wiki.newTab(doc, ''+rev_from +' -> ' + rev_to, 'DiffPerspective'); - - $(result.view).html(data); - $.wiki.switchToTab(result.tab); - } - }); - } - - // first time page is rendered - $('#make-diff-button').click(function() { - self.makeDiff(); - }); - - $('#pubmark-changeset-button').click(function() { - self.showPubmarkForm(); - }); - - $('#doc-revert-button').click(function() { - self.revertDialog(); - }); - - $('#open-preview-button').click(function(event) { - var selected = $('#changes-list .entry.selected'); - - if (selected.length != 1) { - window.alert("Wybierz dokładnie *jedną* wersję."); - return; - } - - var version = parseInt($("*[data-stub-value='version']", selected[0]).text()); - window.open($(this).attr('data-basehref') + "?revision=" + version); + class HistoryPerspective extends $.wiki.Perspective { + constructor(options) { + var old_callback = options.callback || function() {}; + + options.callback = function() { + var self = this; + if (CurrentDocument.diff) { + rev_from = CurrentDocument.diff[0]; + rev_to = CurrentDocument.diff[1]; + this.doc.fetchDiff({ + from: rev_from, + to: rev_to, + success: function(doc, data){ + var result = $.wiki.newTab(doc, ''+rev_from +' -> ' + rev_to, 'DiffPerspective'); + + $(result.view).html(data); + $.wiki.switchToTab(result.tab); + } + }); + } - event.preventDefault(); - }); + // first time page is rendered + $('#make-diff-button').click(function() { + self.makeDiff(); + }); - $(document).on('click', '#changes-list .entry', function(){ - var $this = $(this); + $('#pubmark-changeset-button').click(function() { + self.showPubmarkForm(); + }); - var selected_count = $("#changes-list .entry.selected").length; + $('#doc-revert-button').click(function() { + self.revertDialog(); + }); - if ($this.hasClass('selected')) { - $this.removeClass('selected'); - selected_count -= 1; - } - else { - if (selected_count < 2) { - $this.addClass('selected'); - selected_count += 1; - }; - }; + $('#open-preview-button').click(function(event) { + var selected = $('#changes-list .entry.selected'); - $('#history-view-editor .toolbar button').attr('disabled', 'disabled'). - filter('*[data-enabled-when~="' + selected_count + '"]'). - attr('disabled', null); - }); + if (selected.length != 1) { + window.alert("Wybierz dokładnie *jedną* wersję."); + return; + } - $(document).on('click', '#changes-list span.tag', function(event){ - return false; - }); + var version = parseInt($("*[data-stub-value='version']", selected[0]).text()); + window.open($(this).attr('data-basehref') + "?revision=" + version); - $('#history-view').on('scroll', function() { - if (self.finished || self.fetching) return; - var elemTop = $('#history-view .message-box').offset().top; - var windowH = $(window).innerHeight(); - if (elemTop - 20 < windowH) { - self.triggerFetch(); - } - }); + event.preventDefault(); + }); - old_callback.call(this); - } + $(document).on('click', '#changes-list .entry', function(){ + var $this = $(this); - $.wiki.Perspective.call(this, options); - }; + var selected_count = $("#changes-list .entry.selected").length; - HistoryPerspective.prototype = new $.wiki.Perspective(); + if ($this.hasClass('selected')) { + $this.removeClass('selected'); + selected_count -= 1; + } + else { + if (selected_count < 2) { + $this.addClass('selected'); + selected_count += 1; + }; + }; + + $('#history-view-editor .toolbar button').attr('disabled', 'disabled'). + filter('*[data-enabled-when~="' + selected_count + '"]'). + attr('disabled', null); + }); - HistoryPerspective.prototype.freezeState = function(){ - // must - }; + $(document).on('click', '#changes-list span.tag', function(event){ + return false; + }); - HistoryPerspective.prototype.onEnter = function(success, failure){ - $.wiki.Perspective.prototype.onEnter.call(this); - this.startFetching(); - success && success(); - }; + $('#history-view').on('scroll', function() { + if (self.finished || self.fetching) return; + var elemTop = $('#history-view .message-box').offset().top; + var windowH = $(window).innerHeight(); + if (elemTop - 20 < windowH) { + self.triggerFetch(); + } + }); - HistoryPerspective.prototype.startFetching = function() { - $('#history-view .message-box').html('Wczytywanie historii…').show(); - $('#changes-list').html(''); - this.finished = false; - this.before = ''; - this.triggerFetch(); - }; - HistoryPerspective.prototype.stopFetching = function() { - self.finished = true; - $('#history-view .message-box').hide() - }; + old_callback.call(this); + } + super(options); + } - HistoryPerspective.prototype.triggerFetch = function() { - var self = this; - self.fetching = true; + freezeState() { + // must + } - function _finalize() { - self.fetching = false; + onEnter(success, failure) { + super.onEnter(); + this.startFetching(); + success && success(); } - function _failure(doc, message){ - $('#history-view .message-box').html('Nie udało się odświeżyć historii:' + message).show(); - _finalize(); - }; + startFetching() { + $('#history-view .message-box').html('Wczytywanie historii…').show(); + $('#changes-list').html(''); + this.finished = false; + this.before = ''; + this.triggerFetch(); + } + stopFetching() { + self.finished = true; + $('#history-view .message-box').hide() + } - function _success(doc, data){ - //$('#history-view .message-box').hide(); ONLY AFTER LAST! - var changes_list = $('#changes-list'); - var $stub = $('#history-view .row-stub'); + triggerFetch() { + var self = this; + self.fetching = true; - if (!data.length) { - self.stopFetching(); + function _finalize() { + self.fetching = false; } - $.each(data, function(){ - $.wiki.renderStub({ - container: changes_list, - stub: $stub, - data: this, - }); - self.before = this.version; - if (this.version == 1) { - self.stopFetching(); - } - }); + function _failure(doc, message){ + $('#history-view .message-box').html('Nie udało się odświeżyć historii:' + message).show(); + _finalize(); + }; - _finalize(); - }; + function _success(doc, data){ + //$('#history-view .message-box').hide(); ONLY AFTER LAST! + var changes_list = $('#changes-list'); + var $stub = $('#history-view .row-stub'); - this.doc.fetchHistory({ - success: _success, - failure: _failure, - before: this.before, - }); - } + if (!data.length) { + self.stopFetching(); + } + $.each(data, function(){ + $.wiki.renderStub({ + container: changes_list, + stub: $stub, + data: this, + }); + self.before = this.version; + if (this.version == 1) { + self.stopFetching(); + } + }); - HistoryPerspective.prototype.showPubmarkForm = function(){ - var selected = $('#changes-list .entry.selected'); + _finalize(); + }; - if (selected.length != 1) { - window.alert("Musisz zaznaczyć dokładnie jedną wersję."); - return; + this.doc.fetchHistory({ + success: _success, + failure: _failure, + before: this.before, + }); } - var version = parseInt($("*[data-stub-value='version']", selected[0]).text()); - $.wiki.showDialog('#pubmark_dialog', {'revision': version}); - }; + showPubmarkForm() { + var selected = $('#changes-list .entry.selected'); - HistoryPerspective.prototype.makeDiff = function() { - var changelist = $('#changes-list'); - var selected = $('.entry.selected', changelist); + if (selected.length != 1) { + window.alert("Musisz zaznaczyć dokładnie jedną wersję."); + return; + } - if (selected.length != 2) { - window.alert("Musisz zaznaczyć dokładnie dwie wersje do porównania."); - return; + var version = parseInt($("*[data-stub-value='version']", selected[0]).text()); + $.wiki.showDialog('#pubmark_dialog', {'revision': version}); } - $.blockUI({ - message: 'Wczytywanie porównania...' - }); - - var rev_from = $("*[data-stub-value='version']", selected[1]).text(); - var rev_to = $("*[data-stub-value='version']", selected[0]).text(); - - return this.doc.fetchDiff({ - from: rev_from, - to: rev_to, - success: function(doc, data){ - var result = $.wiki.newTab(doc, ''+rev_from +' -> ' + rev_to, 'DiffPerspective'); - - $(result.view).html(data); - $.wiki.switchToTab(result.tab); - $.unblockUI(); - }, - failure: function(doc){ - $.unblockUI(); + makeDiff() { + var changelist = $('#changes-list'); + var selected = $('.entry.selected', changelist); + + if (selected.length != 2) { + window.alert("Musisz zaznaczyć dokładnie dwie wersje do porównania."); + return; } - }); - }; - HistoryPerspective.prototype.revertDialog = function(){ - var self = this; - var selected = $('#changes-list .entry.selected'); + $.blockUI({ + message: 'Wczytywanie porównania...' + }); - if (selected.length != 1) { - window.alert("Musisz zaznaczyć dokładnie jedną wersję."); - return; + var rev_from = $("*[data-stub-value='version']", selected[1]).text(); + var rev_to = $("*[data-stub-value='version']", selected[0]).text(); + + return this.doc.fetchDiff({ + from: rev_from, + to: rev_to, + success: function(doc, data){ + var result = $.wiki.newTab(doc, ''+rev_from +' -> ' + rev_to, 'DiffPerspective'); + $(result.view).html(data); + $.wiki.switchToTab(result.tab); + $.unblockUI(); + }, + failure: function(doc){ + $.unblockUI(); + } + }); } - var version = parseInt($("*[data-stub-value='version']", selected[0]).text()); - $.wiki.showDialog('#revert_dialog', {revision: version}); - }; + revertDialog() { + var self = this; + var selected = $('#changes-list .entry.selected'); + + if (selected.length != 1) { + window.alert("Musisz zaznaczyć dokładnie jedną wersję."); + return; + } + var version = parseInt($("*[data-stub-value='version']", selected[0]).text()); + $.wiki.showDialog('#revert_dialog', {revision: version}); + } + } $.wiki.HistoryPerspective = HistoryPerspective; })(jQuery); diff --git a/src/redakcja/static/js/wiki/view_properties.js b/src/redakcja/static/js/wiki/view_properties.js index e38a7d07..35d00690 100644 --- a/src/redakcja/static/js/wiki/view_properties.js +++ b/src/redakcja/static/js/wiki/view_properties.js @@ -2,7 +2,7 @@ let w = function() {}; w = console.log; - + const elementDefs = { "ilustr": { "attributes": [ @@ -38,387 +38,380 @@ } }; - function PropertiesPerspective(options) { - let oldCallback = options.callback || function() {}; - this.vsplitbar = 'WŁAŚCIWOŚCI'; + class PropertiesPerspective extends $.wiki.SidebarPerspective { + constructor(options) { + let oldCallback = options.callback || function() {}; - options.callback = function() { - let self = this; + options.callback = function() { + let self = this; - self.$pane = $("#side-properties"); - - $("#simple-editor").on('click', '[x-node]', function(e) { - if (!e.redakcja_edited) { - e.redakcja_edited = true; - self.edit(this); - } - }); + self.vsplitbar = 'WŁAŚCIWOŚCI'; + self.$pane = $("#side-properties"); - self.$pane.on('click', '#parents li', function(e) { - self.edit($(this).data('node')); - }); + $("#simple-editor").on('click', '[x-node]', function(e) { + if (!e.redakcja_edited) { + e.redakcja_edited = true; + self.edit(this); + } + }); - $(document).on('click', '#bubbles .badge', function(e) { - self.edit($(this).data('node')); - }); + self.$pane.on('click', '#parents li', function(e) { + self.edit($(this).data('node')); + }); - self.$pane.on('change', '.form-control', function() { - let $input = $(this); + $(document).on('click', '#bubbles .badge', function(e) { + self.edit($(this).data('node')); + }); - let inputval; - if ($input.attr('type') == 'checkbox') { - inputval = $input.is(':checked'); - } else { - inputval = $input.val(); - } - - if ($input.data("edited")) { - if ($input.data("edited-attr")) { - $input.data("edited").attr($input.data("edited-attr"), inputval); + self.$pane.on('change', '.form-control', function() { + let $input = $(this); + + let inputval; + if ($input.attr('type') == 'checkbox') { + inputval = $input.is(':checked'); } else { - $input.data("edited").text(inputval); + inputval = $input.val(); } - return; - } - - html2text({ - element: self.$edited[0], - success: function(xml) { - w(222) - let $xmlelem = $($.parseXML(xml)); - w(333, $xmlelem) - w($input.data('property'), $input.val()); - $xmlelem.contents().attr($input.data('property'), inputval); - w(444, $xmlelem) - let newxml = (new XMLSerializer()).serializeToString($xmlelem[0]); - w(555, newxml) - xml2html({ - xml: newxml, - base: self.doc.getBase(), - success: function(html) { - let htmlElem = $(html); - self.$edited.replaceWith(htmlElem); - self.edit(htmlElem); - } - }); - }, - error: function(e) {console.log(e);}, + + if ($input.data("edited")) { + if ($input.data("edited-attr")) { + $input.data("edited").attr($input.data("edited-attr"), inputval); + } else { + $input.data("edited").text(inputval); + } + return; + } + + html2text({ + element: self.$edited[0], + success: function(xml) { + w(222) + let $xmlelem = $($.parseXML(xml)); + w(333, $xmlelem) + w($input.data('property'), $input.val()); + $xmlelem.contents().attr($input.data('property'), inputval); + w(444, $xmlelem) + let newxml = (new XMLSerializer()).serializeToString($xmlelem[0]); + w(555, newxml) + xml2html({ + xml: newxml, + base: self.doc.getBase(), + success: function(html) { + let htmlElem = $(html); + self.$edited.replaceWith(htmlElem); + self.edit(htmlElem); + } + }); + }, + error: function(e) {console.log(e);}, + }); + self.$edited; }); - self.$edited; - }); - - self.$pane.on('click', '.meta-add', function() { - // create a metadata item - let $fg = $(this).parent(); - let ns = $fg.data('ns'); - let tag = $fg.data('tag'); - let field = $fg.data('field'); - let span = $(''); - span.attr('x-node', tag); - span.attr('x-ns', ns) - if (field.value_type.hasLanguage) { - span.attr('x-a-xml-lang', 'pl'); - } - rdf = $("> [x-node='RDF']", self.$edited); - if (!rdf.length) { - rdf = $(""); - self.$edited.prepend(rdf); - self.$edited.prepend('\n '); - - } - rdfdesc = $("> [x-node='Description']", rdf); - if (!rdfdesc.length) { - rdfdesc = $(""); - rdf.prepend(rdfdesc); - rdf.prepend('\n '); + self.$pane.on('click', '.meta-add', function() { + // create a metadata item + let $fg = $(this).parent(); + let ns = $fg.data('ns'); + let tag = $fg.data('tag'); + let field = $fg.data('field'); + let span = $(''); + span.attr('x-node', tag); + span.attr('x-ns', ns) + if (field.value_type.hasLanguage) { + span.attr('x-a-xml-lang', 'pl'); + } + + let rdf = $("> [x-node='RDF']", self.$edited); + if (!rdf.length) { + rdf = $(""); + self.$edited.prepend(rdf); + self.$edited.prepend('\n '); + + } + let rdfdesc = $("> [x-node='Description']", rdf); + if (!rdfdesc.length) { + rdfdesc = $(""); + rdf.prepend(rdfdesc); + rdf.prepend('\n '); + rdfdesc.append('\n '); + rdf.append('\n '); + } + span.appendTo(rdfdesc); rdfdesc.append('\n '); - rdf.append('\n '); - } - span.appendTo(rdfdesc); - rdfdesc.append('\n '); - self.displayMetaProperty($fg); - - return false; - }); - - self.$pane.on('click', '.meta-delete', function() { - let $fg = $(this).closest('.form-group'); - $('input', $fg).data('edited').remove(); - self.displayMetaProperty($fg); - return false; - }); + self.displayMetaProperty($fg); + return false; + }); - $('#media-chooser').on('show.bs.modal', function (event) { - var input = $("input", $(event.relatedTarget).parent()); - var modal = $(this); - modal.data('target-input', input); - var imglist = modal.find('.modal-body'); - imglist.html(''); - $.each(self.doc.galleryImages, (i, imgItem) => { - img = $("").attr("src", imgItem.thumb).attr('title', imgItem.url).data('url', imgItem.url).on('click', function() { - imglist.find('img').removeClass('active'); - $(this).addClass('active'); - }); - imglist.append(img); + self.$pane.on('click', '.meta-delete', function() { + let $fg = $(this).closest('.form-group'); + $('input', $fg).data('edited').remove(); + self.displayMetaProperty($fg); + return false; }); - }) - $('#media-chooser .ctrl-ok').on('click', function (event) { - $('#media-chooser').data('target-input') - .val( - (new URL($('#media-chooser .active').data('url'), document.baseURI)).href - ).trigger('change'); - $('#media-chooser').modal('hide'); - }); - - self.$pane.on('click', '.current-convert', function() { - self.convert($(this).attr('data-to')); - }); - self.$pane.on('click', '#current-delete', function() { - self.delete(); - }); - - - oldCallback.call(this); - }; - $.wiki.SidebarPerspective.call(this, options); - } + $('#media-chooser').on('show.bs.modal', function (event) { + var input = $("input", $(event.relatedTarget).parent()); + var modal = $(this); + modal.data('target-input', input); + var imglist = modal.find('.modal-body'); + imglist.html(''); + $.each(self.doc.galleryImages, (i, imgItem) => { + img = $("").attr("src", imgItem.thumb).attr('title', imgItem.url).data('url', imgItem.url).on('click', function() { + imglist.find('img').removeClass('active'); + $(this).addClass('active'); + }); + imglist.append(img); + }); + }) + $('#media-chooser .ctrl-ok').on('click', function (event) { + $('#media-chooser').data('target-input') + .val( + (new URL($('#media-chooser .active').data('url'), document.baseURI)).href + ).trigger('change'); + $('#media-chooser').modal('hide'); + }); - PropertiesPerspective.prototype = new $.wiki.SidebarPerspective(); + self.$pane.on('click', '.current-convert', function() { + self.convert($(this).attr('data-to')); + }); + self.$pane.on('click', '#current-delete', function() { + self.delete(); + }); - PropertiesPerspective.prototype.edit = function(element) { - let self = this; + oldCallback.call(this); + }; - $("#parents", self.$pane).empty(); - $("#bubbles").empty(); + super(options); + } - $f = $("#properties-form", self.$pane); - $f.empty(); + edit(element) { + let self = this; - if (element === null) { - self.$edited = null; - return; - } + $("#parents", self.$pane).empty(); + $("#bubbles").empty(); - let $node = $(element); - let b = $("
").text($node.attr('x-node')); - b.data('node', element); - $("#bubbles").append(b); + let $f = $("#properties-form", self.$pane); + $f.empty(); - $node.parents('[x-node]').each(function() { - let a = $("
  • " ) - .append( "
    " + t + "
    " ) - .appendTo( ul ); - }; + addMetaInput(cont, field, element) { + let self = this; + + let ig = $('
    '); + //ig.data('edited', element); + ig.appendTo(cont); + + if (field.value_type.hasLanguage) { + let pp = $("
    "); + let lang_input = $(""); + lang_input.data('edited', $(element)); + lang_input.data('edited-attr', 'x-a-xml-lang'); + lang_input.val( + $(element).attr('x-a-xml-lang') + ); + lang_input.appendTo(pp); + pp.appendTo(ig); } - } - $aninput.data('edited', $(element)) - $aninput.val( - $(element).text() - ); - $aninput.appendTo(ig); - - let ap = $("
    "); - ap.appendTo(ig); - $("").appendTo(ap); - - // lang - }; - - PropertiesPerspective.prototype.displayMetaProperty = function($fg) { - let self = this; - let ns = $fg.data('ns'); - let tag = $fg.data('tag'); - let field = $fg.data('field'); + let $aninput; + if (field.value_type.widget == 'select') { + $aninput = $(""); + if (field.value_type.autocomplete) { + let autoOptions = field.value_type.autocomplete; + $aninput.autocomplete(autoOptions).autocomplete('instance')._renderItem = function(ul, item) { + let t = item.label; + if (item.name) t += '
    ' + item.name + ''; + if (item.description) t += '
    ' + item.description + ''; + return $( "
  • " ) + .append( "
    " + t + "
    " ) + .appendTo( ul ); + }; + } + } + $aninput.data('edited', $(element)) + $aninput.val( + $(element).text() + ); + $aninput.appendTo(ig); - // clear container - $('.c', $fg).empty(); + let ap = $("
    "); + ap.appendTo(ig); + $("").appendTo(ap); - let selector = "> [x-node='RDF'] > [x-node='Description'] > [x-node='"+tag+"']"; - if (ns) { - selector += "[x-ns='"+ns+"']"; + // lang } - $(selector, self.$edited).each(function() { - self.addMetaInput( - $('.c', $fg), - field, - this); - }); - - count = $('.c > .input-group', $fg).length; - if (field.required) { - if (!count) { - $('
    WYMAGANE
    ').appendTo($('.c', $fg)); + + displayMetaProperty($fg) { + let self = this; + let ns = $fg.data('ns'); + let tag = $fg.data('tag'); + let field = $fg.data('field'); + + // clear container + $('.c', $fg).empty(); + + let selector = "> [x-node='RDF'] > [x-node='Description'] > [x-node='"+tag+"']"; + if (ns) { + selector += "[x-ns='"+ns+"']"; } - } - }; - - - - PropertiesPerspective.prototype.addEditField = function(defn, value, elem) { - let self = this; - let $form = $("#properties-form", self.$pane); - - let $fg = $("
    "); - $("