try:
document = storage.get(name)
except DocumentNotFound:
- document = Document(storage, name = name, text = '')
-
+ # WTF ?!
+ raise Http404
+ # document = Document(storage, name = name, text = '')
if request.method == 'POST':
form = DocumentForm(request.POST, instance = document)
return urlunquote(name)
def __contains__(self, title):
+ print "Checking ", title
return urlquote(title) in self.repo.dirstate
def __iter__(self):
try:
return open(self._file_path(title), "rb")
except IOError:
+ import traceback
+ print traceback.print_exc()
raise DocumentNotFound()
def page_file_meta(self, title):
float: left;
margin-right: 10px;
margin-top: -6px;
-}
\ No newline at end of file
+}
+
+
+.xml-iframe {
+ margin-left: 40px;
+}
+
+/*
+ * CodeMirror
+ */
+.CodeMirror-line-numbers {
+ background: #e6ddd5;
+ padding-top: 0.35em;
+}
+
+.CodeMirror-line-numbers div {
+ padding: 0;
+ padding-right: 4px;
+
+ font-size: 8pt;
+ line-height: 17px;
+ text-align: right;
+
+ width: 40px;
+}
+
\ No newline at end of file
+++ /dev/null
-/*global Class*/
-var editor;
-var panel_hooks;
-
-
-// prevent a console.log from blowing things up if we are on a browser that
-// does not support it
-if (typeof console === 'undefined') {
- window.console = {} ;
- console.log = console.info = console.warn = console.error = function(){};
-}
-
-
-(function(){
- // Classes
- var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
- this.Class = function(){};
- Class.extend = function(prop) {
- var _super = this.prototype;
- initializing = true;
- var prototype = new this();
- initializing = false;
- for (var name in prop) {
- prototype[name] = typeof prop[name] == "function" &&
- typeof _super[name] == "function" && fnTest.test(prop[name]) ?
- (function(name, fn){
- return function() {
- var tmp = this._super;
- this._super = _super[name];
- var ret = fn.apply(this, arguments);
- this._super = tmp;
- return ret;
- };
- })(name, prop[name]) :
- prop[name];
- }
- function Class() {
- if ( !initializing && this.init )
- this.init.apply(this, arguments);
- }
- Class.prototype = prototype;
- Class.constructor = Class;
- Class.extend = arguments.callee;
- return Class;
- };
-
- // Templates
- var cache = {};
-
- this.render_template = function render_template(str, data){
- // Figure out if we're getting a template, or if we need to
- // load the template - and be sure to cache the result.
- var fn = !/^[\d\s-_]/.test(str) ?
- cache[str] = cache[str] ||
- render_template(document.getElementById(str).innerHTML) :
-
- // Generate a reusable function that will serve as a template
- // generator (and which will be cached).
-
- new Function("obj",
- "var p=[],print=function(){p.push.apply(p,arguments);};" +
-
- // Introduce the data as local variables using with(){}
- "with(obj){p.push('" +
-
- // Convert the template into pure JavaScript
- str
- .replace(/[\r\t\n]/g, " ")
- .split("<%").join("\t")
- .replace(/((^|%>)[^\t]*)'/g, "$1\r")
- .replace(/\t=(.*?)%>/g, "',$1,'")
- .split("\t").join("');")
- .split("%>").join("p.push('")
- .split("\r").join("\\'")
- + "');}return p.join('');");
-
- // Provide some basic currying to the user
- return data ? fn( data ) : fn;
- };
-})();
-
-
-(function() {
- var slice = Array.prototype.slice;
-
- function update(array, args) {
- var arrayLength = array.length, length = args.length;
- while (length--) array[arrayLength + length] = args[length];
- return array;
- };
-
- function merge(array, args) {
- array = slice.call(array, 0);
- return update(array, args);
- };
-
- Function.prototype.bind = function(context) {
- if (arguments.length < 2 && typeof arguments[0] === 'undefined') {
- return this;
- }
- var __method = this;
- var args = slice.call(arguments, 1);
- return function() {
- var a = merge(args, arguments);
- return __method.apply(context, a);
- }
- }
-
-})();
-
-
-var Editor = Editor || {};
-
-// Obiekt implementujący wzorzec KVC/KVO
-Editor.Object = Class.extend({
- _className: 'Editor.Object',
- _observers: {},
- _guid: null,
-
- init: function() {
- this._observers = {};
- },
-
- description: function() {
- return this._className + '(guid = ' + this.guid() + ')';
- },
-
- addObserver: function(observer, property, callback) {
- // console.log('Add observer', observer.description(), 'to', this.description(), '[', property, ']');
- if (!this._observers[property]) {
- this._observers[property] = {}
- }
- this._observers[property][observer.guid()] = callback;
- return this;
- },
-
- removeObserver: function(observer, property) {
- if (!property) {
- for (var property in this._observers) {
- this.removeObserver(observer, property)
- }
- } else {
- // console.log('Remove observer', observer.description(), 'from', this.description(), '[', property, ']');
- delete this._observers[property][observer.guid()];
- }
- return this;
- },
-
- notifyObservers: function(property) {
- var currentValue = this[property];
- for (var guid in this._observers[property]) {
- // console.log(this._observers[property][guid]);
- // console.log('Notifying', guid, 'of', this.description(), '[', property, ']');
- this._observers[property][guid](property, currentValue, this);
- }
- return this;
- },
-
- guid: function() {
- if (!this._guid) {
- this._guid = ('editor-' + Editor.Object._lastGuid++);
- }
- return this._guid;
- },
-
- get: function(property) {
- return this[property];
- },
-
- set: function(property, value) {
- if (this[property] != value) {
- this[property] = value;
- this.notifyObservers(property);
- }
- return this;
- },
-
- dispose: function() {
- delete this._observers;
- }
-});
-
-// Handle JSON error responses in uniform way
-function parseXHRError(response)
-{
- var message = "";
- var level = "";
-
- try {
- var json = $.evalJSON(response.responseText);
-
- if(json.reason == 'xml-parse-error') {
- message = json.message.replace(/(line\s+)(\d+)(\s+)/i,
- "<a class='xml-editor-ref' href='#xml-$2-1'>$1$2$3</a>");
-
- message = message.replace(/(line\s+)(\d+)(\,\s*column\s+)(\d+)/i,
- "<a class='xml-editor-ref' href='#xml-$2-$4'>$1$2$3$4</a>");
-
- level = "warning";
- }
- else if(json.reason == 'xml-non-valid') {
- message = json.message;
- level = "warning";
- }
- else {
- message = json.message || json.reason || "Nieznany błąd :((";
- level = "error";
- }
- } catch(e) {
- // not a valid JSON response
- message = response.statusText || 'Brak połączenia z serwerem';
- level = "error";
- }
-
- return {error_message: message, error_level: level};
-}
-
-function parseXHRResponse(xhr) {
- var response = {}
-
- if(xhr.status >= 200 && xhr.status < 300)
- {
- response.success = true;
- try {
- response.data = $.evalJSON(xhr.responseText);
- } catch(e) {
- response.data = {};
- }
-
- return response;
- }
-
- return parseXHRError(xhr);
-}
-
-Editor.Object._lastGuid = 0;
-
-var panels = [];
\ No newline at end of file
}
}.bind(this);
- this.scriptlets['codemirror_fontsize'] = function(context, params) {
- var frameBody = this.XMLEditorBody(context);
-
- if(params.fontSize) {
- frameBody.css('font-size', params.fontSize);
- }
- else {
- var old_size = parseInt(frameBody.css('font-size'), 10);
- frameBody.css('font-size', old_size + (params.change || 0) );
- }
-
- }.bind(this);
-
this.scriptlets['fulltextregexp'] = function(context, params) {
var exprs = $.map(params.exprs, function(expr) {
var opts = "mg";
+++ /dev/null
-var editor;
-var panel_hooks;
-
-function Hotkey(code) {
- this.code = code;
- this.has_alt = ((code & 0x01 << 8) !== 0);
- this.has_ctrl = ((code & 0x01 << 9) !== 0);
- this.has_shift = ((code & 0x01 << 10) !== 0);
- this.character = String.fromCharCode(code & 0xff);
-}
-
-Hotkey.prototype.toString = function() {
- var mods = [];
- if(this.has_alt) mods.push('Alt');
- if(this.has_ctrl) mods.push('Ctrl');
- if(this.has_shift) mods.push('Shift');
- mods.push('"'+this.character+'"');
- return mods.join('+');
-};
-
-function Panel(panelWrap) {
- var self = this;
- self.hotkeys = [];
- self.wrap = panelWrap;
- self.contentDiv = $('.panel-content', panelWrap);
- self.instanceId = Math.ceil(Math.random() * 1000000000);
- // $.log('new panel - wrap: ', self.wrap);
-
- $(document).bind('panel:unload.' + self.instanceId,
- function(event, data) {
- self.unload(event, data);
- });
-
- $(document).bind('panel:contentChanged', function(event, data) {
- $.log(self, ' got changed event from: ', data);
- if(self != data) {
- self.otherPanelChanged(event.target);
- } else {
- self.markChanged();
- }
- return false;
- });
-}
-
-Panel.prototype.callHook = function() {
- var args = $.makeArray(arguments);
- var hookName = args.splice(0,1)[0];
- var noHookAction = args.splice(0,1)[0];
- var result = false;
-
- $.log('calling hook: ', hookName, 'with args: ', args);
- if(this.hooks && this.hooks[hookName]) {
- result = this.hooks[hookName].apply(this, args);
- } else if (noHookAction instanceof Function) {
- result = noHookAction(args);
- }
- return result;
-};
-
-Panel.prototype._endload = function () {
- // this needs to be here, so we
- this.connectToolbar();
- this.callHook('toolbarResized');
-};
-
-Panel.prototype.load = function (url) {
- // $.log('preparing xhr load: ', this.wrap);
- $(document).trigger('panel:unload', this);
- var self = this;
- self.current_url = url;
-
- $.ajax({
- url: url,
- dataType: 'html',
- success: function(data, tstat) {
- panel_hooks = null;
- $(self.contentDiv).html(data);
- self.hooks = panel_hooks;
- panel_hooks = null;
- self.callHook('load');
- },
- error: function(request, textStatus, errorThrown) {
- $.log('ajax', url, this.target, 'error:', textStatus, errorThrown);
- $(self.contentDiv).html("<p>Wystapił błąd podczas wczytywania panelu.</p>");
- }
- });
-};
-
-Panel.prototype.unload = function(event, data) {
- // $.log('got unload signal', this, ' target: ', data);
- if( data == this ) {
- $(this.contentDiv).html('');
-
- // disconnect the toolbar
- $('div.panel-toolbar span.panel-toolbar-extra', this.wrap).html(
- '<span />');
-
- this.callHook('unload');
- this.hooks = null; // flush the hooks
- return false;
- }
-};
-
-Panel.prototype.refresh = function(event, data) {
- var self = this;
- var reload = function() {
- $.log('hard reload for panel ', self.current_url);
- self.load(self.current_url);
- return true;
- };
-
- if( this.callHook('refresh', reload) ) {
- $('.change-notification', this.wrap).fadeOut();
- }
-};
-
-Panel.prototype.otherPanelChanged = function(other) {
- $.log('Panel ', this, ' is aware that ', other, ' changed.');
- if(!this.callHook('dirty')) {
- $('.change-notification', this.wrap).fadeIn();
- }
-};
-
-Panel.prototype.markChanged = function () {
- this.wrap.addClass('changed');
-};
-
-Panel.prototype.changed = function () {
- return this.wrap.hasClass('changed');
-};
-
-Panel.prototype.unmarkChanged = function () {
- this.wrap.removeClass('changed');
-};
-
-Panel.prototype.saveInfo = function() {
- var saveInfo = {};
- this.callHook('saveInfo', null, saveInfo);
- return saveInfo;
-};
-
-Panel.prototype.connectToolbar = function()
-{
- var self = this;
- self.hotkeys = [];
-
- // check if there is a one
- var toolbar = $("div.toolbar", this.contentDiv);
- // $.log('Connecting toolbar', toolbar);
- if(toolbar.length === 0) return;
-
- // move the extra
- var extra_buttons = $('span.panel-toolbar-extra button', toolbar);
- var placeholder = $('div.panel-toolbar span.panel-toolbar-extra > span', this.wrap);
- placeholder.replaceWith(extra_buttons);
-
- // connect group-switch buttons
- var group_buttons = $('*.toolbar-tabs-container button', toolbar);
-
- // $.log('Found groups:', group_buttons);
-
- group_buttons.each(function() {
- var group = $(this);
- var group_name = group.attr('ui:group');
- // $.log('Connecting group: ' + group_name);
-
- group.click(function() {
- // change the active group
- var active = $("*.toolbar-tabs-container button.active", toolbar);
- if (active != group) {
- active.removeClass('active');
- group.addClass('active');
- $(".toolbar-button-groups-container p", toolbar).each(function() {
- if ( $(this).attr('ui:group') != group_name) {
- $(this).hide();
- } else {
- $(this).show();
- }
- });
- self.callHook('toolbarResized');
- }
- });
- });
-
- // connect action buttons
- var allbuttons = $.makeArray(extra_buttons);
- $.merge(allbuttons,
- $.makeArray($('*.toolbar-button-groups-container button', toolbar)) );
-
- $(allbuttons).each(function() {
- var button = $(this);
- var hk = button.attr('ui:hotkey');
- if(hk) hk = new Hotkey( parseInt(hk) );
-
- try {
- var params = $.evalJSON(button.attr('ui:action-params'));
- } catch(object) {
- $.log('JSON exception in ', button, ': ', object);
- button.attr('disabled', 'disabled');
- return;
- }
-
- var callback = function() {
- editor.callScriptlet(button.attr('ui:action'), self, params);
- };
-
- // connect button
- button.click(callback);
-
- // connect hotkey
- if(hk) {
- self.hotkeys[hk.code] = callback;
- // $.log('hotkey', hk);
- }
-
- // tooltip
- if (button.attr('ui:tooltip') )
- {
- var tooltip = button.attr('ui:tooltip');
- if(hk) tooltip += ' ['+hk+']';
-
- button.wTooltip({
- delay: 1000,
- style: {
- border: "1px solid #7F7D67",
- opacity: 0.9,
- background: "#FBFBC6",
- padding: "1px",
- fontSize: "12px"
- },
- content: tooltip
- });
- }
- });
-};
-
-Panel.prototype.hotkeyPressed = function(event)
-{
- var code = event.keyCode;
- if(event.altKey) code = code | 0x100;
- if(event.ctrlKey) code = code | 0x200;
- if(event.shiftKey) code = code | 0x400;
-
- var callback = this.hotkeys[code];
- if(callback) callback();
-};
-
-Panel.prototype.isHotkey = function(event) {
- var code = event.keyCode;
- if(event.altKey) code = code | 0x100;
- if(event.ctrlKey) code = code | 0x200;
- if(event.shiftKey) code = code | 0x400;
-
- $.log(event.character, this.hotkeys[code]);
-
- if(this.hotkeys[code]) {
- return true;
- }
- return false;
-};
-
-Panel.prototype.fireEvent = function(name) {
- $(document).trigger('panel:'+name, this);
-};
-
-function Editor()
-{
- this.rootDiv = $('#panels');
- this.popupQueue = [];
- this.autosaveTimer = null;
- this.scriplets = {};
-}
-
-Editor.prototype.loadConfig = function() {
- // Load options from cookie
- var defaultOptions = {
- panels: [
- {
- name: 'htmleditor',
- ratio: 0.5
- },
-
- {
- name: 'gallery',
- ratio: 0.5
- }
- ],
- recentFiles: [],
- lastUpdate: 0
- };
-
- try {
- var cookie = $.cookie('options');
- this.options = $.secureEvalJSON(cookie);
- if (!this.options) {
- this.options = defaultOptions;
- }
- } catch (e) {
- this.options = defaultOptions;
- }
-
- this.fileOptions = this.options;
- var self = this;
-
- if(!this.options.recentFiles)
- this.options.recentFiles = [];
-
- $.each(this.options.recentFiles, function(index) {
- if (fileId == self.options.recentFiles[index].fileId) {
- $.log('Found options for', fileId);
- self.fileOptions = self.options.recentFiles[index];
- }
- });
-
- $.log(this.options);
- $.log('fileOptions', this.fileOptions);
-
- this.loadPanelOptions();
- this.savePanelOptions();
-};
-
-Editor.prototype.loadPanelOptions = function() {
- // var self = this;
- // var totalWidth = 0;
- //
- // $('.panel-wrap', self.rootDiv).each(function(index) {
- // var panelWidth = self.fileOptions.panels[index].ratio * self.rootDiv.width();
- // if ($(this).hasClass('last-panel')) {
- // $(this).css({
- // left: totalWidth,
- // right: 0
- // });
- // } else {
- // $(this).css({
- // left: totalWidth,
- // width: panelWidth
- // });
- // totalWidth += panelWidth;
- // }
- // $.log('panel:', this, $(this).css('left'));
- // $('.panel-toolbar option', this).each(function() {
- // if ($(this).attr('p:panel-name') == self.fileOptions.panels[index].name) {
- // $(this).parent('select').val($(this).attr('value'));
- // }
- // });
- // });
-};
-
-Editor.prototype.savePanelOptions = function() {
- var self = this;
- var panels = [];
- $('.panel-wrap', self.rootDiv).not('.panel-content-overlay').each(function() {
- panels.push({
- name: $('.panel-toolbar option:selected', this).attr('p:panel-name'),
- ratio: $(this).width() / self.rootDiv.width()
- });
- });
- self.options.panels = panels;
-
- // Dodaj obecnie oglądany plik do listy recentFiles
- var recentFiles = [{fileId: fileId, panels: panels}];
- var count = 1;
- $.each(self.options.recentFiles, function(index) {
- if (count < 5 && fileId != self.options.recentFiles[index].fileId) {
- recentFiles.push(self.options.recentFiles[index]);
- count++;
- }
- });
- self.options.recentFiles = recentFiles;
-
- self.options.lastUpdate = new Date().getTime() / 1000;
- $.log($.toJSON(self.options));
- $.cookie('options', $.toJSON(self.options), {
- expires: 7,
- path: '/'
- });
-};
-
-Editor.prototype.saveToBranch = function(msg)
-{
- var changed_panel = $('.panel-wrap.changed');
- var self = this;
- $.log('Saving to local branch - panel:', changed_panel);
-
- if(!msg) msg = "Szybki zapis z edytora platformy.";
-
- if( changed_panel.length === 0) {
- $.log('Nothing to save.');
- return true; /* no changes */
- }
-
- if( changed_panel.length > 1) {
- alert('Błąd: więcej niż jeden panel został zmodyfikowany. Nie można zapisać.');
- return false;
- }
-
- var saveInfo = changed_panel.data('ctrl').saveInfo();
- var postData = '';
-
- if (saveInfo.postData instanceof Object) {
- postData = $.param(saveInfo.postData);
- } else {
- postData = saveInfo.postData;
- }
-
- postData += '&' + $.param({
- 'commit_message': msg
- });
-
- self.showPopup('save-waiting', '', -1);
-
- $.ajax({
- url: saveInfo.url,
- dataType: 'json',
- success: function(data, textStatus) {
- if (data.result != 'ok') {
- self.showPopup('save-error', (data.errors && data.errors[0]) || 'Nieznany błąd X_X.');
- }
- else {
- self.refreshPanels();
-
-
- if(self.autosaveTimer) {
- clearTimeout(self.autosaveTimer);
- }
- if (data.warnings === null || data.warning === undefined) {
- self.showPopup('save-successful');
- } else {
- self.showPopup('save-warn', data.warnings[0]);
- }
- }
-
- self.advancePopupQueue();
- },
- error: function(rq, tstat, err) {
- self.showPopup('save-error', '- bład wewnętrzny serwera.');
- self.advancePopupQueue();
- },
- type: 'POST',
- data: postData
- });
-
- return true;
-};
-
-Editor.prototype.autoSave = function()
-{
- this.autosaveTimer = null;
- // first check if there is anything to save
- $.log('Autosave');
- this.saveToBranch("Automatyczny zapis z edytora platformy.");
-};
-
-Editor.prototype.onContentChanged = function(event, data) {
- var self = this;
-
- $('button.provides-save').removeAttr('disabled');
- $('button.requires-save').attr('disabled', 'disabled');
-
- if(this.autosaveTimer) return;
- this.autosaveTimer = setTimeout( function() {
- self.autoSave();
- }, 300000 );
-};
-
-Editor.prototype.updateUserBranch = function() {
- if($('.panel-wrap.changed').length !== 0) {
- alert("There are unsaved changes - can't update.");
- }
-
- var self = this;
- $.ajax({
- url: $('#toolbar-button-update').attr('ui:ajax-action'),
- dataType: 'json',
- success: function(data, textStatus) {
- switch(data.result) {
- case 'done':
- self.showPopup('generic-yes', 'Plik uaktualniony.');
- self.refreshPanels();
- break;
- case 'nothing-to-do':
- self.showPopup('generic-info', 'Brak zmian do uaktualnienia.');
- break;
- default:
- self.showPopup('generic-error', data.errors && data.errors[0]);
- }
- },
- error: function(rq, tstat, err) {
- self.showPopup('generic-error', 'Błąd serwera: ' + err);
- },
- type: 'POST',
- data: {}
- });
-};
-
-Editor.prototype.sendMergeRequest = function (message) {
- if( $('.panel-wrap.changed').length !== 0) {
- alert("There are unsaved changes - can't commit.");
- }
-
- var self = this;
-
- $.ajax({
- url: $('#commit-dialog form').attr('action'),
- dataType: 'json',
- success: function(data, textStatus) {
- switch(data.result) {
- case 'done':
- self.showPopup('generic-yes', 'Łączenie zmian powiodło się.');
-
- if(data.localmodified) {
- self.refreshPanels();
- }
-
- break;
- case 'nothing-to-do':
- self.showPopup('generic-info', 'Brak zmian do połaczenia.');
- break;
- default:
- self.showPopup('generic-error', data.errors && data.errors[0]);
- }
- },
- error: function(rq, tstat, err) {
- self.showPopup('generic-error', 'Błąd serwera: ' + err);
- },
- type: 'POST',
- data: {
- 'message': message
- }
- });
-};
-
-Editor.prototype.postSplitRequest = function(s, f)
-{
- $.ajax({
- url: $('#split-dialog form').attr('action'),
- dataType: 'html',
- success: s,
- error: f,
- type: 'POST',
- data: $('#split-dialog form').serialize()
- });
-};
-
-
-Editor.prototype.allPanels = function() {
- return $('#' + this.rootDiv.attr('id') +' > *.panel-wrap', this.rootDiv.parent());
-};
-
-Editor.prototype.registerScriptlet = function(scriptlet_id, scriptlet_func)
-{
- // I briefly assume, that it's verified not to break the world on SS
- if (!this[scriptlet_id]) {
- this[scriptlet_id] = scriptlet_func;
- }
-};
-
-Editor.prototype.callScriptlet = function(scriptlet_id, panel, params) {
- var func = this[scriptlet_id];
- if(!func) {
- throw 'No scriptlet named "' + scriptlet_id + '" found.';
- }
- return func(this, panel, params);
-};
-
-$(function() {
- $.fbind = function (self, func) {
- return function() {
- return func.apply(self, arguments);
- };
- };
-
- editor = new Editor();
-
- // do the layout
- editor.loadConfig();
- editor.setupUI();
-});
// for now allow only 1 range
if(n > 1) {
- window.alert("Zaznacz jeden obszar");
+ window.alert("Zaznacz jeden obszar.");
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.");
+ return false;
+ }
// verify if the start/end points make even sense -
// they must be inside a x-node (otherwise they will be discarded)
},
iframeClass: 'xml-iframe',
textWrapping: true,
+ lineNumbers: true,
tabMode: 'spaces',
indentUnit: 0,
initCallback: function(editor) {
event.preventDefault();
var params = eval("(" + $(this).attr('ui:action-params') + ")");
scriptletCenter.scriptlets[$(this).attr('ui:action')](editor, params);
- });
+ });
$('.toolbar select').change(function() {
var slug = $(this).val();
+++ /dev/null
-/*global Editor*/
-Editor.MessageCenter = Editor.Object.extend({
- init: function() {
- this.messages = [];
- this.flashMessages = [];
- this.firstFlashMessage = null;
- this.timeout = null;
- console.log("MSC-init:", Date(), this);
- },
-
- addMessage: function(type, tag, text, flash)
- {
- if (!tag) tag = '#default'
-
- if (!flash) {
- flash = text;
- }
-
- this.messages.push({
- type: type,
- text: text
- });
-
- this.flashMessages.push({
- type: type,
- text: flash,
- tag: tag
- });
-
- if(this.timeout) {
- if(this.flashMessages[0] && (this.flashMessages[0].tag == tag))
- {
- clearTimeout(this.timeout);
- this.timeout = null;
- this.changeFlashMessage();
- }
- }
-
- else {
- /* queue was empty at the start */
- if (this.flashMessages.length == 1) {
- console.log("MSC-added-fisrt", Date(), this);
- this.set('firstFlashMessage', this.flashMessages[0]);
- this.timeout = setTimeout(this.changeFlashMessage.bind(this), 3000);
- }
-
- }
-
- },
-
- changeFlashMessage: function()
- {
- console.log("MSC-change", Date(), this);
- var previous = this.flashMessages.splice(0, 1);
-
- if (this.flashMessages.length > 0)
- {
- console.log("MSC-chaning-first", Date(), this);
- this.set('firstFlashMessage', this.flashMessages[0]);
- this.timeout = setTimeout(this.changeFlashMessage.bind(this), 3000);
- } else {
- console.log("MSC-emptying", Date(), this);
- this.set('firstFlashMessage', null);
- }
- }
-
-});
-
-
-var messageCenter = new Editor.MessageCenter();
-
+++ /dev/null
-/*globals Editor fileId SplitView PanelContainerView EditorView FlashView messageCenter*/
-Editor.Model = Editor.Object.extend({
- synced: false,
- data: null
-});
-
-Editor.ToolbarButtonsModel = Editor.Model.extend({
- className: 'Editor.ToolbarButtonsModel',
- buttons: {},
-
- init: function() {
- this._super();
- },
-
- load: function() {
- if (!this.get('buttons').length) {
- $.ajax({
- url: documentInfo.toolbarURL,
- dataType: 'json',
- success: this.loadSucceeded.bind(this)
- });
- }
- },
-
- loadSucceeded: function(data)
- {
- // do some escaping
- $.each(data, function() {
- $.each(this.buttons, function() {
- //do some lame escapes
- this.tooltip = this.tooltip.replace(/"/g, """);
- });
- });
- this.set('buttons', data);
- }
-});
-
-
-//
-// HTML Document Model
-//
-Editor.HTMLModel = Editor.Model.extend({
- _className: 'Editor.HTMLModel',
- textURL: null,
- state: 'empty',
-
- init: function(document, textURL) {
- this._super();
- this.set('state', 'empty');
- this.set('revision', document.get('revision'));
- this.document = document;
-
- this.textURL = textURL;
-
- this.htmlXSL = null;
- this.wlmlXSL = null;
- this.rawText = null;
-
- // create a parser and a serializer
- this.parser = new DOMParser();
- this.serializer = new XMLSerializer();
-
- this.addObserver(this, 'data', this.dataChanged.bind(this));
- },
-
- load: function(force) {
- if (force || this.get('state') == 'empty') {
- this.set('state', 'loading');
- messageCenter.addMessage('info', 'xmlload', 'Wczytuję HTML...');
-
- // request all stylesheets
- $.ajax({
- url: documentInfo.staticURL + 'xsl/wl2html_client.xsl',
- dataType: 'xml',
- success: this.htmlXSLLoadSuccess.bind(this),
- error: this.loadingFailed.bind(this)
- });
-
- $.ajax({
- url: documentInfo.staticURL + 'xsl/html2wl_client.xsl',
- dataType: 'xml',
- success: this.wlmlXSLLoadSuccess.bind(this),
- error: this.loadingFailed.bind(this)
- });
-
- $.ajax({
- url: this.textURL,
- dataType: 'text',
- data: {
- revision: this.get('revision'),
- user: this.document.get('user')
- },
- success: this.textLoadSuccess.bind(this),
- error: this.loadingFailed.bind(this)
- });
- return true;
- }
- return false;
- },
-
- asWLML: function(element, inner)
- {
- console.log("Source", element);
- var doc = this.parser.parseFromString(this.serializer.serializeToString(element), 'text/xml');
-
- var result = this.wlmlXSL.transformToDocument(doc);
-
- if(!result) {
- console.log("Failed", this.wlmlXSL, doc);
- throw "Failed to transform fragment";
- }
-
- console.log("Transformed", doc, " to: ", result.documentElement);
- if(inner) {
- var children = result.documentElement.childNodes;
- var buf = '';
-
- for(var i=0; i < children.length; i++)
- buf += this.serializer.serializeToString(children.item(i));
-
- return buf;
- }
-
- return this.serializer.serializeToString(result.documentElement);
- },
-
- innerAsWLML: function(elem)
- {
- return this.asWLML(elem, true);
- },
-
- updateInnerWithWLML: function($element, innerML)
- {
- var e = $element.clone().html('<span x-node="out-of-flow-text" x-content="%"></span>')[0];
- var s = this.asWLML(e);
- // hurray for dirty hacks :P
- s = s.replace(/>%<\//, '>'+innerML+'</');
- return this.updateWithWLML($element, s);
- },
-
- updateWithWLML: function($element, text)
- {
- // filter the string
- text = text.replace(/\/\s+/g, '<br />');
- try {
- var chunk = this.parser.parseFromString("<chunk>"+text+"</chunk>", "text/xml");
- } catch(e) {
- console.log('Caught parse exception.');
- return "<p>Źle sformatowana zawartość:" + e.toString() + "</p>";
- }
-
- var parseError = chunk.getElementsByTagName('parsererror');
- console.log("Errors:", parseError);
-
- if(parseError.length > 0)
- {
- console.log("Parse errors.")
- return this.serializer.serializeToString(parseError.item(0));
- }
-
- console.log("Transforming to HTML");
- var result = this.htmlXSL.transformToFragment(chunk, $element[0].ownerDocument).firstChild;
-
- if(!result) {
- return "Błąd aplikacji - nie udało się wygenerować nowego widoku HTML.";
- }
-
- var errors = result.getElementsByTagName('error');
- if(errors.length > 0)
- {
- var errorMessage = 'Wystąpiły błędy:<ul>';
- for(var i=0; i < errors.length; i++)
- {
- var estr = this.serializer.serializeToString(errors.item(i));
- console.log("XFRM error:", estr);
- errorMessage += "<li>"+estr+"</li>";
- }
- errorMessage += "</ul>";
- return errorMessage;
- }
-
- try {
- $element.replaceWith(result);
- this.set('state', 'dirty');
- return false;
- } catch(e) {
- return "Błąd podczas wstawiania tekstu: '" + e.toString() + "'";
- }
- },
-
- createXSLT: function(xslt_doc) {
- var p = new XSLTProcessor();
- p.importStylesheet(xslt_doc);
- return p;
- },
-
- htmlXSLLoadSuccess: function(data)
- {
- try {
- this.htmlXSL = this.createXSLT(data);
-
- if(this.wlmlXSL && this.htmlXSL && this.rawText)
- this.loadSuccess();
- } catch(e) {
- console.log(e);
- this.set('error', e.toString() );
- this.set('state', 'error');
- }
- },
-
- wlmlXSLLoadSuccess: function(data)
- {
- try {
- this.wlmlXSL = this.createXSLT(data);
-
- if(this.wlmlXSL && this.htmlXSL && this.rawText)
- this.loadSuccess();
- } catch(e) {
- console.log(e);
- this.set('error', e.toString() );
- this.set('state', 'error');
- }
- },
-
- textLoadSuccess: function(data) {
- this.rawText = data;
-
- if(this.wlmlXSL && this.htmlXSL && this.rawText)
- this.loadSuccess();
- },
-
- loadSuccess: function() {
- if (this.get('state') != 'loading') {
- alert('erroneous state:', this.get('state'));
- }
-
- // prepare text
- var doc = null;
- doc = this.rawText.replace(/\/\s+/g, '<br />');
- doc = this.parser.parseFromString(doc, 'text/xml');
- doc = this.htmlXSL.transformToFragment(doc, document).firstChild;
-
- this.set('data', doc);
- this.set('state', 'synced');
- messageCenter.addMessage('success', 'xmlload', 'Wczytałem HTML :-)');
- },
-
- loadingFailed: function(response)
- {
- if (this.get('state') != 'loading') {
- alert('erroneous state:', this.get('state'));
- }
-
- var message = parseXHRError(response);
-
- this.set('error', '<h2>Błąd przy ładowaniu XML</h2><p>'+message+'</p>');
- this.set('state', 'error');
- messageCenter.addMessage('error', 'xmlload', 'Nie udało mi się wczytać HTML. Spróbuj ponownie :-(');
- },
-
- save: function(message) {
- if (this.get('state') == 'dirty') {
- this.set('state', 'saving');
-
- messageCenter.addMessage('info', 'htmlsave', 'Zapisuję HTML...');
- var wlml = this.asWLML(this.get('data'));
-
- var payload = {
- contents: wlml,
- revision: this.get('revision'),
- user: this.document.get('user')
- };
-
- if (message) {
- payload.message = message;
- }
-
- $.ajax({
- url: this.textURL,
- type: 'post',
- dataType: 'json',
- data: payload,
- success: this.saveSucceeded.bind(this),
- error: this.saveFailed.bind(this)
- });
- return true;
- }
- return false;
- },
-
- saveSucceeded: function(data) {
- if (this.get('state') != 'saving') {
- alert('erroneous state:', this.get('state'));
- }
- this.set('revision', data.revision);
- this.set('state', 'updated');
- messageCenter.addMessage('success', 'htmlsave', 'Zapisałem :-)');
- },
-
- saveFailed: function() {
- if (this.get('state') != 'saving') {
- alert('erroneous state:', this.get('state'));
- }
- messageCenter.addMessage('error', 'htmlsave', 'Nie udało mi się zapisać.');
- this.set('state', 'dirty');
- },
-
- // For debbuging
- set: function(property, value) {
- if (property == 'state') {
- console.log(this.description(), ':', property, '=', value);
- }
- return this._super(property, value);
- },
-
- dataChanged: function(property, value) {
- if (this.get('state') == 'synced') {
- this.set('state', 'dirty');
- }
- },
-
- dispose: function() {
- this.removeObserver(this);
- this._super();
- }
-});
-
-
-// Stany modelu:
-//
-// -> error -> loading
-// /
-// empty -> loading -> synced -> unsynced -> loading
-// \
-// -> dirty -> updating -> updated -> synced
-//
-Editor.XMLModel = Editor.Model.extend({
- _className: 'Editor.XMLModel',
- serverURL: null,
- data: '',
- state: 'empty',
-
- init: function(document, serverURL) {
- this._super();
- this.set('state', 'empty');
- this.set('revision', document.get('revision'));
- this.document = document;
- this.serverURL = serverURL;
- this.toolbarButtonsModel = new Editor.ToolbarButtonsModel();
- this.addObserver(this, 'data', this.dataChanged.bind(this));
- },
-
- load: function(force) {
- if (force || this.get('state') == 'empty') {
- this.set('state', 'loading');
- messageCenter.addMessage('info', 'xmlload', 'Wczytuję XML...');
- $.ajax({
- url: this.serverURL,
- dataType: 'text',
- data: {
- revision: this.get('revision'),
- user: this.document.get('user')
- },
- success: this.loadingSucceeded.bind(this),
- error: this.loadingFailed.bind(this)
- });
- return true;
- }
- return false;
- },
-
- loadingSucceeded: function(data) {
- if (this.get('state') != 'loading') {
- alert('erroneous state:', this.get('state'));
- }
- this.set('data', data);
- this.set('state', 'synced');
- messageCenter.addMessage('success', 'xmlload', 'Wczytałem XML :-)');
- },
-
- loadingFailed: function(response)
- {
- if (this.get('state') != 'loading') {
- alert('erroneous state:', this.get('state'));
- }
-
- var message = parseXHRError(response);
-
- this.set('error', '<h2>Błąd przy ładowaniu XML</h2><p>'+message+'</p>');
- this.set('state', 'error');
- messageCenter.addMessage('error', 'xmlload', 'Nie udało mi się wczytać XML. Spróbuj ponownie :-(');
- },
-
- save: function(message) {
- if (this.get('state') == 'dirty') {
- this.set('state', 'updating');
- messageCenter.addMessage('info', 'xmlsave', 'Zapisuję XML...');
-
- var payload = {
- contents: this.get('data'),
- revision: this.get('revision'),
- user: this.document.get('user')
- };
- if (message) {
- payload.message = message;
- }
-
- $.ajax({
- url: this.serverURL,
- type: 'post',
- dataType: 'json',
- data: payload,
- success: this.saveSucceeded.bind(this),
- error: this.saveFailed.bind(this)
- });
- return true;
- }
- return false;
- },
-
- saveSucceeded: function(data) {
- if (this.get('state') != 'updating') {
- alert('erroneous state:', this.get('state'));
- }
- this.set('revision', data.revision);
- this.set('state', 'updated');
- messageCenter.addMessage('success', 'xmlsave', 'Zapisałem XML :-)');
- },
-
- saveFailed: function() {
- if (this.get('state') != 'updating') {
- alert('erroneous state:', this.get('state'));
- }
- messageCenter.addMessage('error', 'xmlsave', 'Nie udało mi się zapisać XML. Spróbuj ponownie :-(');
- this.set('state', 'dirty');
- },
-
- // For debbuging
- set: function(property, value) {
- if (property == 'state') {
- console.log(this.description(), ':', property, '=', value);
- }
- return this._super(property, value);
- },
-
- dataChanged: function(property, value) {
- if (this.get('state') == 'synced') {
- this.set('state', 'dirty');
- }
- },
-
- dispose: function() {
- this.removeObserver(this);
- this._super();
- }
-});
-
-Editor.ImageGalleryModel = Editor.Model.extend({
- _className: 'Editor.ImageGalleryModel',
- serverURL: null,
- data: [],
- state: 'empty',
-
- init: function(document, serverURL) {
- this._super();
- this.set('state', 'empty');
- this.serverURL = serverURL;
- // olewać data
- this.pages = [];
- },
-
- setGallery: function(path) {
- $.ajax({
- url: this.serverURL,
- type: 'post',
- data: {
- path: path,
- },
- success: this.settingGallerySucceeded.bind(this)
- });
- },
-
- settingGallerySucceeded: function(data) {
- console.log('settingGallerySucceeded');
- this.load(true);
- },
-
- load: function(force) {
- if (force || this.get('state') == 'empty') {
- console.log("setting state");
- this.set('state', 'loading');
- console.log("going ajax");
- $.ajax({
- url: this.serverURL,
- dataType: 'json',
- success: this.loadingSucceeded.bind(this),
- error: this.loadingFailed.bind(this)
- });
- }
- },
-
- loadingSucceeded: function(data)
- {
- console.log("success");
-
- if (this.get('state') != 'loading') {
- alert('erroneous state:', this.get('state'));
- }
-
- console.log('galleries:', data);
-
- if (data.length === 0) {
- this.set('data', []);
- } else {
- this.set('data', data[0].pages);
- }
-
- this.set('state', 'synced');
- },
-
- loadingFailed: function(data) {
- console.log("failed");
-
- if (this.get('state') != 'loading') {
- alert('erroneous state:', this.get('state'));
- }
-
- this.set('state', 'error');
- },
-
- set: function(property, value) {
- if (property == 'state') {
- console.log(this.description(), ':', property, '=', value);
- }
- return this._super(property, value);
- }
-});
-
-
-Editor.DocumentModel = Editor.Model.extend({
- _className: 'Editor.DocumentModel',
- data: null, // name, text_url, revision, latest_shared_rev, parts_url, dc_url, size, merge_url
- contentModels: {},
- state: 'empty',
- errors: '',
- revision: '',
- user: '',
-
- init: function() {
- this._super();
- this.set('state', 'empty');
- },
-
- load: function() {
- if (this.get('state') == 'empty') {
- this.set('state', 'loading');
- messageCenter.addMessage('info', 'docload', 'Ładuję dane dokumentu...');
- $.ajax({
- cache: false,
- url: documentInfo.docURL,
- dataType: 'json',
- success: this.successfulLoad.bind(this),
- error: this.failedLoad.bind(this)
- });
- }
- },
-
- successfulLoad: function(data) {
- this.set('data', data);
- this.set('state', 'synced');
-
- this.set('revision', data.revision);
- this.set('user', data.user);
-
- this.contentModels = {
- 'xml': new Editor.XMLModel(this, data.text_url),
- 'html': new Editor.HTMLModel(this, data.text_url),
- 'gallery': new Editor.ImageGalleryModel(this, data.gallery_url)
- };
-
- for (var key in this.contentModels) {
- this.contentModels[key].addObserver(this, 'state', this.contentModelStateChanged.bind(this));
- }
-
- this.error = '';
-
- messageCenter.addMessage('success', 'docload', 'Dokument załadowany poprawnie :-)');
- },
-
- failedLoad: function(response) {
- if (this.get('state') != 'loading') {
- alert('erroneous state:', this.get('state'));
- }
-
- var err = parseXHRError(response);
- this.set('error', '<h2>Nie udało się wczytać dokumentu</h2><p>'+err.error_message+"</p>");
- this.set('state', 'error');
- },
-
- contentModelStateChanged: function(property, value, contentModel) {
- if (value == 'dirty') {
- this.set('state', 'dirty');
- for (var key in this.contentModels) {
- if (this.contentModels[key].guid() != contentModel.guid()) {
- this.contentModels[key].set('state', 'unsynced');
- }
- }
- } else if (value == 'updated') {
- this.set('state', 'synced');
- for (key in this.contentModels) {
- if (this.contentModels[key].guid() == contentModel.guid()) {
- this.contentModels[key].set('state', 'synced');
- this.revision = this.contentModels[key].get('revision');
-
- }
- }
- for (key in this.contentModels) {
- if (this.contentModels[key].guid() != contentModel.guid()) {
- this.contentModels[key].set('revision', this.revision);
- this.contentModels[key].set('state', 'empty');
- }
- }
- }
- },
-
- saveDirtyContentModel: function(message) {
- for (var key in this.contentModels) {
- if (this.contentModels[key].get('state') == 'dirty') {
- this.contentModels[key].save(message);
- break;
- }
- }
- },
-
- update: function() {
- this.set('state', 'loading');
-
- messageCenter.addMessage('info', 'doc_update',
- 'Uaktualniam dokument...');
-
- $.ajax({
- url: this.data.merge_url,
- dataType: 'json',
- type: 'post',
- data: {
- type: 'update',
- revision: this.get('revision'),
- user: this.get('user')
- },
- complete: this.updateCompleted.bind(this)
- });
- },
-
- updateCompleted: function(xhr, textStatus)
- {
- console.log(xhr.status, xhr.responseText);
- var response = parseXHRResponse(xhr);
- if(response.success)
- {
- if( (response.data.result == 'no-op')
- || (response.data.timestamp == response.data.parent_timestamp))
- {
- if( (response.data.revision) && (response.data.revision != this.get('revision')) )
- {
- // we're out of sync
- this.set('state', 'unsynced');
- return;
- }
-
- messageCenter.addMessage('info', 'doc_update',
- 'Już posiadasz najbardziej aktualną wersję.');
- this.set('state', 'synced');
- return;
- }
-
- // result: success
- this.set('revision', response.data.revision);
- this.set('user', response.data.user);
-
- messageCenter.addMessage('info', 'doc_update',
- 'Uaktualnienie dokumentu do wersji ' + response.data.revision);
-
- for (var key in this.contentModels) {
- this.contentModels[key].set('revision', this.get('revision') );
- this.contentModels[key].set('state', 'empty');
- }
-
- this.set('state', 'synced');
- return;
- }
-
- // no success means trouble
- messageCenter.addMessage(response.error_level, 'doc_update',
- response.error_message);
-
- this.set('state', 'unsynced');
- },
-
- merge: function(message) {
- this.set('state', 'loading');
- messageCenter.addMessage('info', 'doc_merge',
- 'Scalam dokument z głównym repozytorium...');
-
- $.ajax({
- url: this.data.merge_url,
- type: 'post',
- dataType: 'json',
- data: {
- type: 'share',
- revision: this.get('revision'),
- user: this.get('user'),
- message: message
- },
- complete: this.mergeCompleted.bind(this),
- success: function(data) {
- this.set('mergeData', data);
- }.bind(this)
- });
- },
-
- mergeCompleted: function(xhr, textStatus) {
- console.log(xhr.status, xhr.responseText);
- var response = parseXHRResponse(xhr);
-
- if(response.success) {
-
- if( (response.data.result == 'no-op') ||
- ( response.data.shared_parent_timestamp
- && response.data.shared_timestamp
- && (response.data.shared_timestamp == response.data.shared_parent_timestamp)) )
- {
- if( (response.data.revision) && (response.data.revision != this.get('revision')) )
- {
- // we're out of sync
- this.set('state', 'unsynced');
- return;
- }
-
- messageCenter.addMessage('info', 'doc_merge',
- 'Twoja aktualna wersja nie różni się od ostatnio zatwierdzonej.');
- this.set('state', 'synced');
- return;
- }
-
- if( response.data.result == 'accepted')
- {
- messageCenter.addMessage('info', 'doc_merge',
- 'Prośba o zatwierdzenie została przyjęta i oczekuję na przyjęcie.');
- this.set('state', 'synced');
- return;
- }
-
- // result: success
- this.set('revision', response.data.revision);
- this.set('user', response.data.user);
-
- messageCenter.addMessage('info', 'doc_merge',
- 'Twoja wersja dokumentu została zatwierdzona.');
-
- this.set('state', 'synced');
- return;
- }
-
- // no success means trouble
- messageCenter.addMessage(response.error_level, 'doc_merge',
- response.error_message);
-
- this.set('state', 'unsynced');
- },
-
- // For debbuging
- set: function(property, value) {
- if (property == 'state') {
- console.log(this.description(), ':', property, '=', value);
- }
- return this._super(property, value);
- }
-});
-
-
-var leftPanelView, rightPanelContainer, doc;
-
-$(function()
-{
- var flashView = new FlashView('#flashview', messageCenter);
-
- doc = new Editor.DocumentModel();
-
- EditorView = new EditorView('#body-wrap', doc);
- EditorView.freeze("<h1>Wczytuję dokument...</h1>");
-
- leftPanelView = new PanelContainerView('#left-panel-container', doc);
- rightPanelContainer = new PanelContainerView('#right-panel-container', doc);
-
-
-});
+++ /dev/null
-/*globals View render_template scriptletCenter*/
-var ButtonToolbarView = View.extend({
- _className: 'ButtonToolbarView',
- template: null,
- buttons: null,
-
- init: function(element, model, parent, template) {
- this._super(element, model, null);
- this.parent = parent;
- this.template = 'button-toolbar-view-template';
-
- this.model.addObserver(this, 'buttons', this.modelButtonsChanged.bind(this));
- this.buttons = this.model.get('buttons');
- this.model.load();
- this.render();
- },
-
- modelButtonsChanged: function(property, value) {
- this.set('buttons', value);
- this.render();
- },
-
- render: function() {
- $('.buttontoolbarview-tab', this.element).unbind('click.buttontoolbarview');
- $('.buttontoolbarview-button', this.element).unbind('click.buttontoolbarview');
- var self = this;
-
- this.element.html(render_template(this.template, this));
-
- $('.buttontoolbarview-tab', this.element).bind('click.buttontoolbarview', function() {
- var groupIndex = $(this).attr('ui:groupindex');
- $('.buttontoolbarview-group', self.element).each(function() {
- if ($(this).attr('ui:groupindex') == groupIndex) {
- $(this).show();
- } else {
- $(this).hide();
- }
- });
- $(self.element).trigger('resize');
- });
-
- $('.buttontoolbarview-button', this.element).
- bind('click.buttontoolbarview', this.buttonPressed.bind(this) );
-
- $(this.element).trigger('resize');
- },
-
- buttonPressed: function(event)
- {
- var self = this;
- var target = event.target;
-
- var groupIndex = parseInt($(target).attr('ui:groupindex'), 10);
- var buttonIndex = parseInt($(target).attr('ui:buttonindex'), 10);
- var button = this.get('buttons')[groupIndex].buttons[buttonIndex];
- var scriptletId = button.scriptlet_id;
- var params = eval('(' + button.params + ')'); // To nie powinno być potrzebne
-
- console.log('Executing', scriptletId, 'with params', params);
- try {
- self.parent.freeze('Wykonuję akcję...');
- setTimeout(function() {
- scriptletCenter.scriptlets[scriptletId](self.parent, params);
- self.parent.unfreeze();
- }, 10);
- } catch(e) {
- console.log("Scriptlet", scriptletId, "failed.", e);
- }
-
- },
-
- dispose: function() {
- $('.buttontoolbarview-tab', this.element).unbind('click.buttontoolbarview');
- $('.buttontoolbarview-button', this.element).unbind('click.buttontoolbarview');
- this._super();
- }
-});
-
+++ /dev/null
-/*global View render_template panels */
-var EditorView = View.extend({
- _className: 'EditorView',
- element: null,
- model: null,
- template: null,
-
- init: function(element, model, template) {
- this._super(element, model, template);
-
- this.quickSaveButton = $('#action-quick-save', this.element).bind('click.editorview', this.quickSave.bind(this));
- this.commitButton = $('#action-commit', this.element).bind('click.editorview', this.commit.bind(this));
- this.updateButton = $('#action-update', this.element).bind('click.editorview', this.update.bind(this));
- this.mergeButton = $('#action-merge', this.element).bind('click.editorview', this.merge.bind(this));
-
- this.model.addObserver(this, 'state', this.modelStateChanged.bind(this));
- this.modelStateChanged('state', this.model.get('state'));
-
- this.splitView = new SplitView('#splitview', doc);
-
- // Inicjalizacja okien jQuery Modal
- this.commitDialog = new CommitDialog( $('#commit-dialog') );
-
-
- // $('#split-dialog').jqm({
- // modal: true,
- // onShow: $.fbind(self, self.loadSplitDialog)
- // }).
- // jqmAddClose('button.dialog-close-button');
-
- this.model.load();
- },
-
- quickSave: function(event) {
- this.model.saveDirtyContentModel();
- },
-
- commit: function(event)
- {
- this.commitDialog.show( this.doCommit.bind(this) )
-
- },
-
- doCommit: function(message) {
- this.model.saveDirtyContentModel(message);
- },
-
- update: function(event) {
- this.model.update();
- },
-
- merge: function(event) {
- this.commitDialog.show( this.doMerge.bind(this) )
- },
-
- doMerge: function(message) {
- this.model.merge(message);
- },
-
- /*loadRelatedIssues: function(hash) {
- var self = this;
- var c = $('#commit-dialog-related-issues');
-
- $('#commit-dialog').data('context', hash.t);
-
- $("div.loading-box", c).show();
- $("div.fatal-error-box", c).hide();
- $("div.container-box", c).hide();
-
- $.getJSON(c.attr('ui:ajax-src') + '?callback=?',
- function(data, status)
- {
- var fmt = '';
- $(data).each( function() {
- fmt += '<label><input type="checkbox" checked="checked"';
- fmt += ' value="' + this.id + '" />' + this.subject +'</label>\n';
- });
- $("div.container-box", c).html(fmt);
- $("div.loading-box", c).hide();
- $("div.container-box", c).show();
- });
-
- hash.w.show();
- }, */
-
- modelStateChanged: function(property, value) {
- // Uaktualnia stan przycisków
- if (value == 'dirty') {
- this.quickSaveButton.attr('disabled', null);
- this.commitButton.attr('disabled', null);
- this.updateButton.attr('disabled', 'disabled');
- this.mergeButton.attr('disabled', 'disabled');
- } else if (value == 'synced' || value == 'unsynced') {
- this.quickSaveButton.attr('disabled', 'disabled');
- this.commitButton.attr('disabled', 'disabled');
- this.updateButton.attr('disabled', null);
- this.mergeButton.attr('disabled', null);
- this.unfreeze();
- } else if (value == 'empty') {
- this.quickSaveButton.attr('disabled', 'disabled');
- this.commitButton.attr('disabled', 'disabled');
- this.updateButton.attr('disabled', 'disabled');
- this.mergeButton.attr('disabled', 'disabled');
- } else if (value == 'error') {
- this.freeze(this.model.get('error'));
- this.quickSaveButton.attr('disabled', 'disabled');
- this.commitButton.attr('disabled', 'disabled');
- this.updateButton.attr('disabled', 'disabled');
- this.mergeButton.attr('disabled', 'disabled');
-
- }
- },
-
- dispose: function() {
- $('#action-quick-save', this.element).unbind('click.editorview');
- $('#action-commit', this.element).unbind('click.editorview');
- $('#action-update', this.element).unbind('click.editorview');
- $('#action-merge', this.element).unbind('click.editorview');
-
- this.model.removeObserver(this);
- this._super();
- }
-});
-
-
-var AbstractDialog = Class.extend({
- _className: 'AbstractDialog',
-
- init: function($element, modal, overlay)
- {
- this.$window = $element;
- this.$window.jqm({
- modal: modal || true,
- overlay: overlay || 80,
- // toTop: true,
- onShow: this.onShow.bind(this),
- onHide: this.onHide.bind(this)
- });
-
- this.reset();
-
- $('.cancel-button', this.$window).click(this.cancel.bind(this));
- $('.save-button', this.$window).click(this.accept.bind(this));
- },
-
- onShow: function(hash)
- {
- hash.w.show();
- },
-
- onHide: function(hash)
- {
- hash.w.hide();
- hash.o.remove();
- },
-
- reset: function() {
- this.acceptCallback = null;
- this.cancelCallback = null;
- this.errors = [];
-
- $('.error-messages-box', this.$window).html('').hide();
-
- this.userData = {};
- },
-
- show: function(acall, ccall) {
- this.acceptCallback = acall;
- this.cancelCallback = ccall;
-
- // do the show
- this.$window.jqmShow();
- },
-
- cancel: function() {
- this.$window.jqmHide();
- if(this.cancelCallback) this.cancelCallback(this);
- this.reset();
- },
-
- accept: function()
- {
- this.errors = [];
-
- if(!this.validate()) {
- this.displayErrors();
- return;
- }
-
- this.$window.jqmHide();
-
- if(this.acceptCallback)
- this.acceptCallback(this);
-
- this.reset();
- },
-
- validate: function() {
- return true;
- },
-
- displayErrors: function() {
- var errorDiv = $('.error-messages-box', this.$window);
- if(errorDiv.length > 0) {
- var html = '';
- $.each(this.errors, function() {
- html += '<li>' + this + '</li>';
- });
- errorDiv.html('<ul>' + html + '</ul>');
- errorDiv.show();
- console.log('Validation errors:', html);
- }
- else
- throw this.errors;
- }
-
-});
-
-var CommitDialog = AbstractDialog.extend({
- _className: 'CommitDialog',
-
- validate: function()
- {
- var message = $('textarea.commit-message', this.$window).val();
-
- if( message.match(/^\s*$/) ) {
- this.errors.push("Message can't be empty.");
- return false;
- }
-
- // append refs
- $('.related-issues-fields input:checked', this.$window).each(function() {
- message += ' refs #' + $(this).val();
- });
-
- this.userData.message = message;
- return this._super();
- }
- });
-
-
\ No newline at end of file
+++ /dev/null
-/*globals View render_template*/
-var FlashView = View.extend({
- template: 'flash-view-template',
-
- init: function(element, model, template) {
- this.shownMessage = null;
- this._super(element, model, template);
- this.setModel(model);
- },
-
- setModel: function(model) {
- if (this.model) {
- this.model.removeObserver(this);
- }
- this.model = model;
- this.shownMessage = null;
- if (this.model) {
- this.shownMessage = this.model.get('firstFlashMessage');
- this.model.addObserver(this, 'firstFlashMessage', this.modelFirstFlashMessageChanged.bind(this));
- }
- this.render();
- },
-
- render: function() {
- this.element.html(render_template(this.template, this));
- setTimeout(function() {}, 0);
- },
-
- modelFirstFlashMessageChanged: function(property, value) {
- this.element.fadeOut(200, (function() {
-
- this.element.css({'z-index': 0});
- this.shownMessage = value;
- this.render();
-
- if(this.shownMessage) {
- this.element.css({'z-index': 1000});
- this.element.fadeIn();
- };
- }).bind(this));
- }
-});
+++ /dev/null
-/*global View render_template panels */
-var ImageGalleryView = View.extend({
- _className: 'ImageGalleryView',
- element: null,
- model: null,
- currentPage: -1,
- pageZoom: 1.0,
- template: 'image-gallery-view-template',
-
- init: function(element, model, parent, template)
- {
- console.log("init for gallery");
- var submodel = model.contentModels['gallery'];
- this._super(element, submodel, template);
- this.parent = parent;
-
- console.log("gallery model", this.model);
-
- this.model
- .addObserver(this, 'data', this.modelDataChanged.bind(this))
- .addObserver(this, 'state', this.modelStateChanged.bind(this));
-
- //$('.image-gallery-view', this.element).html(this.model.get('data'));
- this.modelStateChanged('state', this.model.get('state'));
- this.model.load();
- },
-
- modelDataChanged: function(property, value)
- {
- console.log(this.model.get('state'), value, value.length);
- if ((this.model.get('state') == 'synced') && (value.length == 0)) {
- console.log('tutaj');
- this.render('image-gallery-empty-template');
- } else {
- this.render();
- this.gotoPage(this.currentPage);
- }
- },
-
- gotoPage: function(index)
- {
- if (index < 0)
- index = 0;
-
- var n = this.$pages.length;
- if (index >= n) index = n-1;
-
- if( (this.currentPage == index) )
- return;
-
- var cpage = this.$currentPage();
-
- if(cpage) {
- var offset = this.pageViewOffset(cpage);
- this.cleanPage(cpage);
- }
-
- this.currentPage = index;
-
- cpage = this.$currentPage()
- this.renderImage(cpage);
-
- if(offset) {
- cpage.css({top: offset.y, left: offset.x});
- }
-
- var self = this;
- $('img', cpage).bind('load', function() {
- if(offset)
- self.setPageViewOffset(cpage, offset);
- });
-
- cpage.show();
-
- if(this.currentPage == n-1)
- this.$nextButton.attr('disabled', 'disabled');
- else
- this.$nextButton.removeAttr('disabled');
-
- if(this.currentPage == 0)
- this.$prevButton.attr('disabled', 'disabled');
- else
- this.$prevButton.removeAttr('disabled');
-
- this.$pageInput.val( (this.currentPage+1) );
- },
-
- reload: function() {},
-
- modelStateChanged: function(property, value) {
- if (value == 'loading') {
- this.freeze('Ładowanie...');
- } else {
- if ((value == 'synced') && (this.model.get('data').length == 0)) {
- this.render('image-gallery-empty-template');
- }
- this.unfreeze();
- }
- },
-
- $currentPage: function() {
- if(this.currentPage >= 0 && this.currentPage < this.$pages.length)
- return $(this.$pages[this.currentPage]);
- else
- return undefined;
- },
-
- cleanPage: function($page) {
- $page.hide();
- $('img', $page).unbind();
-
- $page.empty();
- this.setPageViewOffset($page, {x:0, y:0});
- },
-
- pageDragStart: function(event)
- {
- this.dragStart = {x: event.clientX, y: event.clientY};
- $(window).bind('mousemove.imagedrag', this.pageDrag.bind(this));
- $(window).bind('mouseup.imagedrag', this.pageDragStop.bind(this));
-
- this.$currentPage().css('cursor', 'move');
-
- return false;
- },
-
- pageDrag: function(event)
- {
- if(!this.dragStart) return;
-
- var delta = {
- x: this.dragStart.x - event.clientX,
- y: this.dragStart.y - event.clientY };
-
- var offset = this.pageViewOffset( $(this.$pages[this.currentPage]) );
- offset.x -= delta.x;
- offset.y -= delta.y;
- this.setPageViewOffset( $(this.$pages[this.currentPage]), offset);
-
- this.dragStart = {x: event.clientX, y: event.clientY };
- return false;
- },
-
- pageDragStop: function(event) {
- this.$currentPage().css('cursor', 'auto');
-
- this.dragStart = undefined;
- $(window).unbind('mousemove.imagedrag');
- $(window).unbind('mouseup.imagedrag');
-
- return false;
- },
-
- pageViewOffset: function($page) {
- var left = parseInt($page.css('left'));
- var top = parseInt($page.css('top'));
-
- return {x: left, y: top};
- },
-
- setPageViewOffset: function($page, offset) {
- // check if the image will be actually visible
- // and correct
- var MARGIN = 30;
-
-
- var vp_width = this.$pageListRoot.width();
- var vp_height = this.$pageListRoot.height();
-
- var width = $page.outerWidth();
- var height = $page.outerHeight();
-
- // console.log(offset, vp_width, vp_height, width, height);
- if( offset.x+width-MARGIN < 0 ) {
- // console.log('too much on the left', offset.x, -width)
- offset.x = -width+MARGIN;
- }
-
- // too much on the right
- if( offset.x > vp_width-MARGIN) {
- offset.x = vp_width-MARGIN;
- // console.log('too much on the right', offset.x, vp_width, width)
- }
-
- if( offset.y+height-MARGIN < 0)
- offset.y = -height+MARGIN;
-
- if( offset.y > vp_height-MARGIN)
- offset.y = vp_height-MARGIN;
-
- $page.css({left: offset.x, top: offset.y});
- },
-
- reload: function() {
- this.model.load(true);
- },
-
- renderImage: function(target)
- {
- var source = target.attr('ui:model');
- var orig_width = parseInt(target.attr('ui:width'));
- var orig_height = parseInt(target.attr('ui:height'));
-
- target.html('<img src="' + source
- + '" width="' + Math.floor(orig_width * this.pageZoom)
- + '" height="' + Math.floor(orig_height * this.pageZoom)
- + '" />');
-
- $('img', target).
- css({
- 'user-select': 'none',
- '-webkit-user-select': 'none',
- '-khtml-user-select': 'none',
- '-moz-user-select': 'none'
- }).
- attr('unselectable', 'on').
- mousedown(this.pageDragStart.bind(this));
- },
-
- render: function(template)
- {
- if(!this.model) return;
-
- $('.choose-gallery-button', this.element).unbind();
-
- /* first unbind all */
- if(this.$nextButton) this.$nextButton.unbind();
- if(this.$prevButton) this.$prevButton.unbind();
- if(this.$jumpButton) this.$jumpButton.unbind();
- if(this.$pageInput) this.$pageInput.unbind();
-
- if(this.$zoomInButton) this.$zoomInButton.unbind();
- if(this.$zoomOutButton) this.$zoomOutButton.unbind();
- if(this.$zoomResetButton) this.$zoomResetButton.unbind();
-
- if (!template) {
- /* render */
- this._super();
-
- /* fetch important parts */
- this.$pageListRoot = $('.image-gallery-page-list', this.element);
- this.$pages = $('.image-gallery-page-container', this.$pageListRoot);
-
- this.$nextButton = $('.image-gallery-next-button', this.element);
- this.$prevButton = $('.image-gallery-prev-button', this.element);
- this.$pageInput = $('.image-gallery-current-page', this.element);
-
- // this.$zoomSelect = $('.image-gallery-current-zoom', this.element);
- this.$zoomInButton = $('.image-gallery-zoom-in', this.element);
- this.$zoomOutButton = $('.image-gallery-zoom-out', this.element);
- this.$zoomResetButton = $('.image-gallery-zoom-reset', this.element);
-
- /* re-bind events */
- this.$nextButton.click( this.nextPage.bind(this) );
- this.$prevButton.click( this.prevPage.bind(this) );
- this.$pageInput.change( this.jumpToPage.bind(this) );
-
- // this.$zoomSelect.change( this.zoomChanged.bind(this) );
- this.$zoomInButton.click( this.zoomInOneStep.bind(this) );
- this.$zoomOutButton.click( this.zoomOutOneStep.bind(this) );
- this.$zoomResetButton.click( this.zoomReset.bind(this) );
-
- this.gotoPage(this.currentPage);
- this.changePageZoom(this.pageZoom);
- } else {
- this._super(template);
-
- var self = this;
- $('.choose-gallery-button', self.element).click(function() {
- console.log('CLICK CLICK')
- self.model.setGallery($('#id_subpath', self.element).val());
- });
- }
- },
-
- jumpToPage: function() {
- this.gotoPage(parseInt(this.$pageInput.val())-1);
- },
-
- nextPage: function() {
- this.gotoPage(this.currentPage + 1);
- },
-
- prevPage: function() {
- this.gotoPage(this.currentPage - 1);
- },
-
- zoomReset: function() {
- this.changePageZoom(1.0);
- },
-
- zoomInOneStep: function() {
- var zoom = this.pageZoom + 0.1;
- if(zoom > 3.0) zoom = 3.0;
- this.changePageZoom(zoom);
- },
-
- zoomOutOneStep: function() {
- var zoom = this.pageZoom - 0.1;
- if(zoom < 0.3) zoom = 0.3;
- this.changePageZoom(zoom);
- },
-
- changePageZoom: function(value) {
- var current = this.$currentPage();
-
- if(!current) return;
-
- var alpha = value/this.pageZoom;
- this.pageZoom = value;
-
- var nwidth = current.attr('ui:width') * this.pageZoom;
- var nheight = current.attr('ui:height') * this.pageZoom;
- var off_top = parseInt(current.css('top'));
- var off_left = parseInt(current.css('left'));
-
- var vpx = this.$pageListRoot.width() * 0.5;
- var vpy = this.$pageListRoot.height() * 0.5;
-
- var new_off_left = vpx - alpha*(vpx-off_left);
- var new_off_top = vpy - alpha*(vpy-off_top);
-
- $('img', current).attr('width', nwidth);
- $('img', current).attr('height', nheight);
-
- this.setPageViewOffset(current, {
- y: new_off_top, x: new_off_left
- });
-
- // this.$zoomSelect.val(this.pageZoom);
- // console.log('Zoom is now', this.pageZoom);
- },
-
- dispose: function()
- {
- console.log("Disposing gallery.");
- this.model.removeObserver(this);
- this._super();
- }
-});
-
-// Register view
-panels['gallery'] = ImageGalleryView;
\ No newline at end of file
+++ /dev/null
-/*global View render_template panels */
-var HTMLView = View.extend({
- _className: 'HTMLView',
- element: null,
- model: null,
- template: 'html-view-template',
-
- init: function(element, model, parent, template) {
- var submodel = model.contentModels['html'];
- this._super(element, submodel, template);
- this.parent = parent;
-
- this.themeEditor = new ThemeEditDialog( $('#theme-edit-dialog') );
-
- this.model
- .addObserver(this, 'data', this.modelDataChanged.bind(this))
- .addObserver(this, 'state', this.modelStateChanged.bind(this));
-
- this.modelStateChanged('state', this.model.get('state'));
- this.modelDataChanged('data', this.model.get('data'));
-
- this.model.load();
-
- this.currentOpen = null;
- this.currentFocused = null;
- this.themeBoxes = [];
- },
-
- modelDataChanged: function(property, value)
- {
- if(!value) return;
-
- // the xml model changed
- var container = $('.htmlview', this.element);
- container.empty();
- container.append(value);
-
- this.updatePrintLink();
-
- /* mark themes */
- /* $(".theme-ref", this.$docbase).each(function() {
- var id = $(this).attr('x-theme-class');
-
- var end = $("span.theme-end[x-theme-class = " + id+"]");
- var begin = $("span.theme-begin[x-theme-class = " + id+"]");
-
- var h = $(this).outerHeight();
-
- h = Math.max(h, end.offset().top - begin.offset().top);
- $(this).css('height', h);
- }); */
- },
-
- updatePrintLink: function() {
- var base = this.$printLink.attr('ui:baseref');
- this.$printLink.attr('href', base + "?user="+this.model.document.get('user')+"&revision=" + this.model.get('revision'));
- },
-
- modelStateChanged: function(property, value)
- {
- var self = $(this);
-
- if (value == 'synced' || value == 'dirty') {
- this.unfreeze();
- } else if (value == 'unsynced') {
- if(this.currentOpen) this.closeWithoutSave(this.currentOpen);
- this.freeze('Niezsynchronizowany...');
- } else if (value == 'loading') {
- this.freeze('Ładowanie...');
- } else if (value == 'saving') {
- this.freeze('Zapisywanie...');
- } else if (value == 'error') {
- this.freeze(this.model.get('error'));
- $('.xml-editor-ref', this.overlay).click(
- function(event) {
- console.log("Sending scroll rq.", this);
- try {
- var href = $(this).attr('href').split('-');
- var line = parseInt(href[1]);
- var column = parseInt(href[2]);
-
- $(document).trigger('xml-scroll-request', {
- line:line,
- column:column
- });
- } catch(e) {
- console.log(e);
- }
-
- return false;
- });
- }
- },
-
- render: function() {
- if(this.$docbase)
- this.$docbase.unbind('click');
-
- if(this.$printLink)
- this.$printLink.unbind();
-
- if(this.$addThemeButton)
- this.$addThemeButton.unbind();
-
- if(this.$addAnnotation)
- this.$addAnnotation.unbind();
-
- this._super();
-
- this.$printLink = $('.htmlview-toolbar .html-print-link', this.element);
- this.$docbase = $('.htmlview', this.element);
- this.$addThemeButton = $('.htmlview-toolbar .html-add-theme', this.element);
- this.$addAnnotation = $('.htmlview-toolbar .html-add-annotation', this.element);
- // this.$debugButton = $('.htmlview-toolbar .html-serialize', this.element);
-
- this.updatePrintLink();
- this.$docbase.bind('click', this.itemClicked.bind(this));
- this.$addThemeButton.click( this.addTheme.bind(this) );
- this.$addAnnotation.click( this.addAnnotation.bind(this) );
- // this.$debugButton.click( this.serialized.bind(this) );
- },
-
- /* serialized: function() {
- this.model.set('state', 'dirty');
- console.log( this.model.serializer.serializeToString(this.model.get('data')) );
- }, */
-
- reload: function() {
- this.model.load(true);
- },
-
- dispose: function() {
- this.model.removeObserver(this);
- this._super();
- },
-
- itemClicked: function(event)
- {
- var self = this;
-
- console.log('click:', event, event.ctrlKey, event.target);
- var $e = $(event.target);
-
- if($e.hasClass('annotation'))
- {
- if(this.currentOpen) return false;
-
- var $p = $e.parent();
- if(this.currentFocused)
- {
- console.log(this.currentFocused, $p);
- if($p[0] == this.currentFocused[0]) {
- console.log('unfocus of current');
- this.unfocusAnnotation();
- return false;
- }
-
- console.log('switch unfocus');
- this.unfocusAnnotation();
- }
-
- this.focusAnnotation($p);
- return false;
- }
-
- /*
- * Clicking outside of focused area doesn't unfocus by default
- * - this greatly simplifies the whole click check
- */
-
- if( $e.hasClass('motyw'))
- {
- this.selectTheme($e.attr('theme-class'));
- return false;
- }
-
- if( $e.hasClass('theme-text-list') )
- {
- this.selectTheme($e.parent().attr('theme-class'));
- return false;
- }
-
- /* other buttons */
- try {
- var editable = this.editableFor($e);
-
- if(!editable)
- return false;
-
- if($e.hasClass('delete-button'))
- this.deleteElement(editable);
-
- if($e.hasClass('edit-button'))
- {
- if( editable.hasClass('motyw') )
- this.editTheme(editable);
- else
- this.openForEdit(editable);
- }
-
- if($e.hasClass('accept-button'))
- this.closeWithSave(editable);
-
- if($e.hasClass('reject-button'))
- this.closeWithoutSave(editable);
-
- } catch(e) {
- messageCenter.addMessage('error', "wlsave", 'Błąd:' + e.toString());
- }
-
- return false;
- },
-
- unfocusAnnotation: function()
- {
- if(!this.currentFocused)
- {
- console.log('Redundant unfocus');
- return false;
- }
-
- if(this.currentOpen
- && this.currentOpen.is("*[x-annotation-box]")
- && this.currentOpen.parent()[0] == this.currentFocused[0])
- {
- console.log("Can't unfocus open box");
- return false;
- }
-
- var $box = $("*[x-annotation-box]", this.currentFocused);
- $box.css({
- 'display': 'none'
- });
- // this.currentFocused.removeAttr('x-focused');
- // this.currentFocused.hide();
- this.currentFocused = null;
- },
-
- focusAnnotation: function($e) {
- this.currentFocused = $e;
- var $box = $("*[x-annotation-box]", $e);
- $box.css({
- 'display': 'block'
- });
-
- // $e.attr('x-focused', 'focused');
- },
-
- closeWithSave: function($e) {
- var $edit = $e.data('edit-overlay');
- var newText = $('textarea', $edit).val();
- var errors = null;
-
- errors = this.model.updateInnerWithWLML($e, newText);
-
- if(errors)
- messageCenter.addMessage('error', 'render', errors);
- else {
- $edit.remove();
- this.currentOpen = null;
- }
- },
-
- closeWithoutSave: function($e) {
- var $edit = $e.data('edit-overlay');
- $edit.remove();
- $e.removeAttr('x-open');
- this.currentOpen = null;
- },
-
- editableFor: function($button)
- {
- var $e = $button;
- var n = 0;
-
- while( ($e[0] != this.element[0]) && !($e.attr('x-editable')) && n < 50)
- {
- // console.log($e, $e.parent(), this.element);
- $e = $e.parent();
- n += 1;
- }
-
- if(!$e.attr('x-editable'))
- return null;
-
- console.log("Trigger", $button, " yields editable: ", $e);
- return $e;
- },
-
- openForEdit: function($origin)
- {
- if(this.currentOpen && this.currentOpen != $origin) {
- this.closeWithSave(this.currentOpen);
- }
-
- var $box = null
-
- // annotations overlay their sub box - not their own box //
- if($origin.is(".annotation-inline-box"))
- $box = $("*[x-annotation-box]", $origin);
- else
- $box = $origin;
-
- var x = $box[0].offsetLeft;
- var y = $box[0].offsetTop;
- var w = $box.outerWidth();
- var h = $box.innerHeight();
-
- console.log("Edit origin:", $origin, " box:", $box);
- console.log("offsetParent:", $box[0].offsetParent);
- console.log("Dimensions: ", x, y, w , h);
-
- // start edition on this node
- var $overlay = $('<div class="html-editarea"><textarea></textarea></div>');
-
- h = Math.max(h, 2*parseInt($box.css('line-height')));
-
- $overlay.css({
- position: 'absolute',
- height: h,
- left: x,
- top: y,
- width: '95%'
- });
-
- try {
- $('textarea', $overlay).val( this.model.innerAsWLML($origin[0]) );
-
- if($origin.is(".annotation-inline-box"))
- {
- if(this.currentFocused) {
- // if some other is focused
- if($origin[0] != this.currentFocused[0]) {
- this.unfocusAnnotation();
- this.focusAnnotation($origin);
- }
- // already focues
- }
- else { // nothing was focused
- this.focusAnnotation($origin);
- }
- }
- else { // this item is not focusable
- if(this.currentFocused) this.unfocusAnnotation();
- }
-
- $($box[0].offsetParent).append($overlay);
- $origin.data('edit-overlay', $overlay);
-
- this.currentOpen = $origin;
- $origin.attr('x-open', 'open');
- }
- catch(e) {
- console.log("Can't open", e);
- }
-
- return false;
- },
-
- deleteElement: function($editable)
- {
- var relatedThemes = $("*[x-node='begin'], *[x-node='end']", $editable);
-
- var themeMarks = relatedThemes.map(function() {
- return $(".motyw[theme-class='"+$(this).attr('theme-class')+"']");
- });
-
- if($editable.is("*.motyw"))
- {
- console.log($editable);
- var selector = "[theme-class='"+$editable.attr('theme-class')+"']";
- relatedThemes = relatedThemes.add("*[x-node='begin']"+selector+", *[x-node='end']"+selector);
- }
-
- console.log(relatedThemes, themeMarks);
-
- var del = confirm("Usunięcie elementu jest nieodwracalne.\n"
- +" Czy na pewno chcesz usunąć ten element, wraz z zawartymi motywami ?\n");
-
- if(del) {
- relatedThemes.remove();
- themeMarks.remove();
- $editable.remove();
- }
- },
-
- //
- // Special stuff for themes
- //
-
- // Theme related stuff
- verifyThemeInsertPoint: function(node) {
-
- if(node.nodeType == 3) { // Text Node
- node = node.parentNode;
- }
-
- if(node.nodeType != 1) return false;
-
- console.log('Selection point:', node);
-
- node = $(node);
- var xtype = node.attr('x-node');
-
- if(!xtype || (xtype.search(':') >= 0) ||
- xtype == 'motyw' || xtype == 'begin' || xtype == 'end')
- return false;
-
- // this is hopefully redundant
- //if(! node.is('*.utwor *') )
- // return false;
-
- // don't allow themes inside annotations
- if( node.is('*[x-annotation-box] *') )
- return false;
-
- return true;
- },
-
-
- editTheme: function($element)
- {
- var themeTextSpan = $('.theme-text-list', $element);
- this.themeEditor.setFromString( themeTextSpan.text() );
-
- function _editThemeFinish(dialog) {
- themeTextSpan.text( dialog.userData.themes.join(', ') );
- };
-
- this.themeEditor.show(_editThemeFinish);
- },
-
-
- addTheme: function()
- {
- var selection = window.getSelection();
- var n = selection.rangeCount;
-
- console.log("Range count:", n);
- if(n == 0) {
- window.alert("Nie zaznaczono żadnego obszaru");
- return false;
- }
-
- // for now allow only 1 range
- if(n > 1) {
- window.alert("Zaznacz jeden obszar");
- return false;
- }
-
- // remember the selected range
- var range = selection.getRangeAt(0);
- console.log(range.startContainer, range.endContainer);
-
- // verify if the start/end points make even sense -
- // they must be inside a x-node (otherwise they will be discarded)
- // and the x-node must be a main text
- if(! this.verifyThemeInsertPoint(range.startContainer) ) {
- window.alert("Motyw nie może się zaczynać w tym miejscu.");
- return false;
- }
-
- if(! this.verifyThemeInsertPoint(range.endContainer) ) {
- window.alert("Motyw nie może się kończyć w tym miejscu.");
- return false;
- }
-
- function _addThemeFinish(dialog)
- {
- var date = (new Date()).getTime();
- var random = Math.floor(4000000000*Math.random());
- var id = (''+date) + '-' + (''+random);
-
- var spoint = document.createRange();
- var epoint = document.createRange();
-
- spoint.setStart(range.startContainer, range.startOffset);
- epoint.setStart(range.endContainer, range.endOffset);
-
- var mtag, btag, etag, errors;
- var themesStr = dialog.userData.themes.join(', ');
-
- // insert theme-ref
- mtag = $('<span></span>');
- spoint.insertNode(mtag[0]);
- errors = this.model.updateWithWLML(mtag, '<motyw id="m'+id+'">'+themesStr+'</motyw>');
-
- if(errors) {
- messageCenter.addMessage('error', null, 'Błąd przy dodawaniu motywu :' + errors);
- return false;
- }
-
- // insert theme-begin
- btag = $('<span></span>');
- spoint.insertNode(btag[0]);
- errors = this.model.updateWithWLML(btag, '<begin id="b'+id+'" />');
- if(errors) {
- mtag.remove();
- messageCenter.addMessage('error', null, 'Błąd przy dodawaniu motywu :' + errors);
- return false;
- }
-
- etag = $('<span></span>');
- epoint.insertNode(etag[0]);
- result = this.model.updateWithWLML(etag, '<end id="e'+id+'" />');
- if(errors) {
- btag.remove();
- mtag.remove();
- messageCenter.addMessage('error', null, 'Błąd przy dodawaniu motywu :' + errors);
- return false;
- }
-
- selection.removeAllRanges();
- return true;
- };
-
- // show the modal
- this.themeEditor.setFromString('');
- this.themeEditor.show(_addThemeFinish.bind(this));
- },
-
- selectTheme: function(themeId)
- {
- var selection = window.getSelection();
-
- // remove current selection
- selection.removeAllRanges();
-
- var range = document.createRange();
- var s = $(".motyw[theme-class='"+themeId+"']")[0];
- var e = $(".end[theme-class='"+themeId+"']")[0];
- console.log('Selecting range:', themeId, range, s, e);
-
- if(s && e) {
- range.setStartAfter(s);
- range.setEndBefore(e);
- selection.addRange(range);
- }
- },
-
- addAnnotation: function()
- {
- var selection = window.getSelection();
- var n = selection.rangeCount;
-
- console.log("Range count:", n);
- if(n == 0) {
- window.alert("Nie zaznaczono żadnego obszaru");
- return false;
- }
-
- // for now allow only 1 range
- if(n > 1) {
- window.alert("Zaznacz jeden obszar");
- return false;
- }
-
- // remember the selected range
- var range = selection.getRangeAt(0);
-
- if(! this.verifyThemeInsertPoint(range.endContainer) ) {
- window.alert("Nie można wstawić w to miejsce przypisu.");
- return false;
- }
-
- var text = range.toString();
- var tag = $('<span></span>');
- range.collapse(false);
- range.insertNode(tag[0]);
- var errors = this.model.updateWithWLML(tag, '<pr><slowo_obce>'+text+"</slowo_obce> </pr>");
-
- if(errors) {
- tag.remove();
- messageCenter.addMessage('error', null, 'Błąd przy dodawaniu przypisu:' + errors);
- return false;
- }
-
- return true;
- }
-});
-
-var ThemeEditDialog = AbstractDialog.extend({
-
- validate: function()
- {
- var active = $('input.theme-list-item:checked', this.$window);
-
- if(active.length < 1) {
- this.errors.push("You must select at least one theme.");
- return false;
- }
-
- console.log("Active:", active);
- this.userData.themes = $.makeArray(active.map(function() { return this.value; }) );
- console.log('After validate:', this.userData);
- return this._super();
- },
-
- setFromString: function(string)
- {
- var $unmatchedList = $('tbody.unknown-themes', this.$window);
-
- $("tr:not(.header)", $unmatchedList).remove();
- $unmatchedList.hide();
-
- $('input.theme-list-item', this.$window).removeAttr('checked');
-
- var unmatched = [];
-
- $.each(string.split(','), function() {
- var name = $.trim(this);
- if(!name) return;
-
- console.log('Selecting:', name);
- var checkbox = $("input.theme-list-item[value='"+name+"']", this.$window);
-
- if(checkbox.length > 0)
- checkbox.attr('checked', 'checked');
- else
- unmatched.push(name);
- });
-
- if(unmatched.length > 0)
- {
- $.each(unmatched, function() {
- $('<tr><td colspan="5"><label><input type="checkbox"'+
- ' checked="checked" class="theme-list-item" value="'
- + this+ '" />"'+this+'"</label></td></tr>').
- appendTo($unmatchedList);
- });
-
- $unmatchedList.show();
- }
- },
-
- displayErrors: function() {
- var errorP = $('.error-messages-inline-box', this.$window);
- if(errorP.length > 0) {
- var html = '';
- $.each(this.errors, function() {
- html += '<span>' + this + '</span>';
- });
- errorP.html(html);
- errorP.show();
- console.log('Validation errors:', html);
- }
- else
- this._super();
- },
-
- reset: function()
- {
- this._super();
- $('.error-messages-inline-box', this.$window).html('').hide();
- }
-
- });
-
-// Register view
-panels['html'] = HTMLView;
\ No newline at end of file
+++ /dev/null
-/*globals View render_template panels*/
-
-var PanelContainerView = View.extend({
- _className: 'PanelContainerView',
- element: null,
- model: null,
- template: 'panel-container-view-template',
- contentView: null,
-
- init: function(element, model, template) {
- this._super(element, model, template);
-
- $('.panel-main-toolbar select', this.element.get(0)).bind('change.panel-container-view', this.selectChanged.bind(this));
- $('.panel-main-toolbar .refresh', this.element.get(0))
- .bind('click.panel-container-view', this.refreshButtonClicked.bind(this))
- .attr('disabled', 'disabled');
- },
-
- selectChanged: function(event) {
- var value = $('select', this.element.get(0)).val();
- var klass = panels[value];
-
- if (this.contentView) {
- this.contentView.dispose();
- this.contentView = null;
- }
-
- if( value != 'empty') {
- this.contentView = new klass($('.content-view', this.element.get(0)), this.model, this);
- $('.panel-main-toolbar .refresh', this.element.get(0)).attr('disabled', null);
- }
- },
-
- refreshButtonClicked: function(event) {
- if (this.contentView) {
- console.log('refreshButtonClicked');
- this.contentView.reload();
- }
- },
-
- dispose: function() {
- $('.panel-main-toolbar .refresh', this.element.get(0)).unbind('click.panel-container-view');
- $('.panel-main-toolbar select', this.element.get(0)).unbind('change.panel-container-view');
- this._super();
- }
-});
-
+++ /dev/null
-/*globals View*/
-
-// Split view inspired by jQuery Splitter Plugin http://methvin.com/splitter/
-var SplitView = View.extend({
- _className: 'SplitView',
- splitbarClass: 'splitview-splitbar',
- activeClass: 'splitview-active',
- overlayClass: 'splitview-overlay',
- element: null,
- model: null,
- zombie: null,
- leftViewOffset: 0,
-
- // Cache
- _splitbarWidth: 0,
-
- init: function(element, model) {
- this._super(element, model, null);
- this.element.css('position', 'relative');
- this._resizingSubviews = false;
-
- this.views = $(">*", this.element[0]).css({
- position: 'absolute', // positioned inside splitter container
- 'z-index': 1, // splitbar is positioned above
- '-moz-outline-style': 'none', // don't show dotted outline
- overflow: 'auto'
- });
-
- this.leftView = $(this.views[0]);
- this.rightView = $(this.views[1]);
-
- this.splitbar = $(this.views[2] || '<div></div>')
- .insertAfter(this.leftView)
- .css({
- position: 'absolute',
- 'user-select': 'none',
- '-webkit-user-select': 'none',
- '-khtml-user-select': 'none',
- '-moz-user-select': 'none',
- 'z-index': 100
- })
- .attr('unselectable', 'on')
- .addClass(this.splitbarClass)
- .bind('mousedown.splitview', this.beginResize.bind(this));
-
- this._splitbarWidth = this.splitbar.outerWidth();
-
- // Solomon's algorithm ;-)
- this.resplit(this.element.width() / 2);
- },
-
- beginResize: function(event) {
- this.zombie = this.zombie || this.splitbar.clone(false).insertAfter(this.leftView);
- this.overlay = this.overlay || $('<div></div>').addClass(this.overlayClass).css({
- position: 'absolute',
- width: this.element.width(),
- height: this.element.height(),
- top: this.element.position().top,
- left: this.element.position().left
- }).appendTo(this.element);
- this.views.css("-webkit-user-select", "none"); // Safari selects A/B text on a move
-
- this.splitbar.addClass(this.activeClass);
- this.leftViewOffset = this.leftView[0].offsetWidth - event.pageX;
-
- $(document)
- .bind('mousemove.splitview', this.resizeChanged.bind(this))
- .bind('mouseup.splitview', this.endResize.bind(this));
- },
-
- resizeChanged: function(event) {
- var newPosition = event.pageX + this.leftViewOffset;
- newPosition = Math.max(0, Math.min(newPosition, this.element.width() - this._splitbarWidth));
- this.splitbar.css('left', newPosition);
- },
-
- endResize: function(event) {
- var newPosition = event.pageX + this.leftViewOffset;
- this.zombie.remove();
- this.zombie = null;
- this.overlay.remove();
- this.overlay = null;
- this.resplit(newPosition);
-
- $(document)
- .unbind('mousemove.splitview')
- .unbind('mouseup.splitview');
-
- //from beginResize:
- // this.views.css("-webkit-user-select", "none"); // Safari selects A/B text on a move
- // Restore it!
- this.views.css("-webkit-user-select", "auto");
- },
-
- resized: function(event) {
- if (!this._resizingSubviews) {
- this.resplit(Math.min(this.leftView.width(), this.element.width() - this._splitbarWidth));
- }
- },
-
- resplit: function(newPosition) {
- newPosition = Math.max(0, Math.min(newPosition, this.element.width() - this._splitbarWidth));
- this.splitbar.css('left', newPosition);
- this.leftView.css({
- left: 0,
- width: newPosition
- });
- this.rightView.css({
- left: newPosition + this._splitbarWidth,
- width: this.element.width() - newPosition - this._splitbarWidth
- });
- if (!$.browser.msie) {
- this._resizingSubviews = true;
- $(window).trigger('resize');
- this._resizingSubviews = false;
- }
- },
-
- dispose: function() {
- this.splitter.unbind('mousedown.splitview');
- this._super();
- }
-});
-
+++ /dev/null
-/*globals Editor render_template*/
-var View = Editor.Object.extend({
- _className: 'View',
- element: null,
- model: null,
- template: null,
- overlayClass: 'view-overlay',
- overlay: null,
-
- init: function(element, model, template)
- {
- console.log("init for view");
- this.element = $(element);
- this.model = model;
- this.template = template || this.template;
-
- if (this.template) this.render();
-
- this._resizeHandler = this.resized.bind(this);
- $(window).bind('resize', this._resizeHandler);
- $(this.element).bind('resize', this._resizeHandler);
- },
-
- render: function(template) {
- console.log('rendering:', this._className);
- this.element.html(render_template(template || this.template, this));
- },
-
- frozen: function() {
- return !!this.overlay;
- },
-
- freeze: function(message) {
- if (this.frozen()) {
- this.unfreeze();
- }
- this.overlay = this.overlay || $('<div><div>' + message + '</div></div>');
-
- this.overlay.addClass(this.overlayClass)
- .css({
-
- }).attr('unselectable', 'on')
-
- this.overlay.appendTo(this.element);
-
- var ovc = this.overlay.children('div');
- var padV = (this.overlay.height() - ovc.outerHeight())/2;
- var padH = (this.overlay.width() - ovc.outerWidth())/2;
-
- this.overlay.children('div').css({
- top: padV, left: padH
- });
- },
-
- unfreeze: function() {
- if (this.frozen()) {
- this.overlay.remove();
- this.overlay = null;
- }
- },
-
- resized: function(event) {
- if(this.overlay) {
- var ovc = this.overlay.children('div');
- var padV = (this.overlay.height() - ovc.outerHeight())/2;
- var padH = (this.overlay.width() - ovc.outerWidth())/2;
-
- this.overlay.children('div').css({
- top: padV,
- left: padH
- });
- }
- },
-
- dispose: function() {
- console.log('disposing:', this._className);
- $(window).unbind('resize', this._resizeHandler);
- $(this.element).unbind('resize', this._resizeHandler);
- this.unfreeze();
- this.element.html('');
- }
-});
\ No newline at end of file
+++ /dev/null
-/*global View CodeMirror ToolbarView render_template panels */
-var XMLView = View.extend({
- _className: 'XMLView',
- element: null,
- model: null,
- template: 'xml-view-template',
- editor: null,
- buttonToolbar: null,
-
- init: function(element, model, parent, template) {
- var submodel = model.contentModels['xml'];
- this._super(element, submodel, template);
-
- this.parent = parent;
-
- this.buttonToolbar = new ButtonToolbarView(
- $('.xmlview-toolbar', this.element),
- this.model.toolbarButtonsModel, parent);
-
- this.hotkeys = [];
- var self = this;
-
- $('.xmlview-toolbar', this.element).bind('resize.xmlview', this.resized.bind(this));
-
- // scroll to the given position (if availble)
- this.scrollCallback = this.scrollOnRequest.bind(this);
- $(document).bind('xml-scroll-request', this.scrollCallback);
-
- this.parent.freeze('Ładowanie edytora...');
-
- setTimeout((function(){
-
- this.editor = new CodeMirror($('.xmlview', this.element).get(0), {
- parserfile: 'parsexml.js',
- path: documentInfo.staticURL + "js/lib/codemirror/",
- stylesheet: documentInfo.staticURL + "css/xmlcolors.css",
- parserConfig: {
- useHTMLKludges: false
- },
- textWrapping: true,
- tabMode: 'spaces',
- indentUnit: 0,
- onChange: this.editorDataChanged.bind(this),
- initCallback: this.editorDidLoad.bind(this)
- });
-
- }).bind(this), 0);
- },
-
- resized: function(event) {
- var height = this.element.height() - $('.xmlview-toolbar', this.element).outerHeight();
- $('.xmlview', this.element).height(height);
- },
-
- reload: function() {
- this.model.load(true);
- },
-
- editorDidLoad: function(editor) {
- $(editor.frame).css({
- width: '100%',
- height: '100%'
- });
- this.model
- .addObserver(this, 'data', this.modelDataChanged.bind(this))
- .addObserver(this, 'state', this.modelStateChanged.bind(this))
- .load();
-
- this.editor.setCode(this.model.get('data'));
- this.modelStateChanged('state', this.model.get('state'));
-
- editor.grabKeys(
- this.hotkeyPressed.bind(this),
- this.isHotkey.bind(this)
- );
-
- this.parent.unfreeze();
- },
-
- editorDataChanged: function() {
- this.model.set('data', this.editor.getCode());
- },
-
- modelDataChanged: function(property, value) {
- if (this.editor.getCode() != value) {
- this.editor.setCode(value);
- }
- },
-
- modelStateChanged: function(property, value) {
- if (value == 'synced' || value == 'dirty') {
- this.unfreeze();
- } else if (value == 'unsynced') {
- this.freeze('Niezsynchronizowany...');
- } else if (value == 'loading') {
- this.freeze('Ładowanie danych...');
- } else if (value == 'saving') {
- this.freeze('Zapisywanie...');
- } else if (value == 'error') {
- this.freeze(this.model.get('error'));
- }
- },
-
- dispose: function() {
- $(document).unbind('xml-scroll-request', this.scrollCallback);
-
- this.model.removeObserver(this);
- $(this.editor.frame).remove();
- this._super();
- },
-
- getHotkey: function(event) {
- var code = event.keyCode;
- if(!((code >= 97 && code <= 122)
- || (code >= 65 && code <= 90)) ) return null;
-
- var ch = String.fromCharCode(code & 0xff).toLowerCase();
- /* # console.log(ch.charCodeAt(0), '#', buttons); */
-
- var buttons = $('.buttontoolbarview-button[hotkey='+ch+']', this.element);
- var mod = 0;
-
- if(event.altKey) mod |= 0x01;
- if(event.ctrlKey) mod |= 0x02;
- if(event.shiftKey) mod |= 0x04;
-
- if(buttons.length) {
- var match = null;
-
- buttons.each(function() {
- if( parseInt($(this).attr('ui:hotkey_mod')) == mod ) {
- match = this;
- return;
- }
- })
-
- return match;
- }
- else {
- return null;
- }
- },
-
- isHotkey: function() {
- /* console.log(arguments); */
- if(this.getHotkey.apply(this, arguments))
- return true;
- else
- return false;
- },
-
- hotkeyPressed: function() {
- var button = this.getHotkey.apply(this, arguments);
- this.buttonToolbar.buttonPressed({
- target: button
- });
- },
-
- scrollOnRequest: function(event, data)
- {
- try {
- var line = this.editor.nthLine(data.line);
- this.editor.selectLines(line, (data.column-1));
- } catch(e) {
- console.log('Exception in scrollOnRequest:', e);
- }
- }
-
-});
-
-function Hotkey(code) {
- this.code = code;
- this.has_alt = ((code & 0x01 << 8) !== 0);
- this.has_ctrl = ((code & 0x01 << 9) !== 0);
- this.has_shift = ((code & 0x01 << 10) !== 0);
- this.character = String.fromCharCode(code & 0xff);
-}
-
-Hotkey.prototype.toString = function() {
- var mods = [];
- if(this.has_alt) mods.push('Alt');
- if(this.has_ctrl) mods.push('Ctrl');
- if(this.has_shift) mods.push('Shift');
- mods.push('"'+this.character+'"');
- return mods.join('+');
-};
-
-// Register view
-panels['xml'] = XMLView;
<xsl:apply-templates select="node()" />\r
</xsl:element>\r
</xsl:template> \r
+ \r
+ <xsl:template match="*[@x-node = 'out-of-flow-text']">\r
+ <xsl:apply-templates select="child::node()" />\r
+ </xsl:template>\r
\r
<xsl:template match="*[@x-node = 'out-of-flow-text']/text()"><xsl:value-of select="." /></xsl:template>\r
\r
<xsl:apply-templates select="node()" />\r
</xsl:element>\r
</xsl:template> \r
+ \r
+ <xsl:template match="*[@X-NODE = 'out-of-flow-text']" priority="1">\r
+ <xsl:apply-templates select="child::node()" />\r
+ </xsl:template>\r
\r
<xsl:template match="*[@X-NODE = 'out-of-flow-text']/text()"><xsl:value-of select="." /></xsl:template>\r
\r
<xsl:param name="mixed" />
<xsl:choose>
<xsl:when test="normalize-space(.) = ''" />
- <xsl:when test="not($mixed)"><div x-node="out-of-flow-text" class="out-of-flow-text" x-editable="true"><xsl:value-of select="." /></div></xsl:when>
+ <xsl:when test="not($mixed)">
+ <span x-node="out-of-flow-text" class="out-of-flow-text" x-editable="true">
+ <xsl:value-of select="." />
+ </span>
+ </xsl:when>
<xsl:otherwise><xsl:value-of select="." /></xsl:otherwise>
</xsl:choose>
</xsl:template>