Skip to content

TagSpaces is an offline, open source, document manager with tagging support

Added edit in place for the title in opened file

uggrock820f3122f9ec
diff --git a/data/js/core.ui.js b/data/js/core.ui.js
index 4c594e6d2..4eee5f32f 100644
--- a/data/js/core.ui.js
+++ b/data/js/core.ui.js
@@ -87,9 +87,9 @@ define(function(require, exports, module) {
tips
.text( t )
.addClass( "ui-state-highlight" );
- setTimeout(function() {
- tips.removeClass( "ui-state-highlight", 1500 );
- }, 500 );
+ window.setTimeout(function() {
+ tips.removeClass( "ui-state-highlight", 1500 );
+ }, 500 );
}
function checkLength( o, n, min, max ) {
diff --git a/data/js/fileopener.js b/data/js/fileopener.js
index ca9068345..ef75c80a1 100644
--- a/data/js/fileopener.js
+++ b/data/js/fileopener.js
@@ -16,6 +16,10 @@ define(function(require, exports, module) {
// If a file is currently opened for editing, this var should be true
var _isEditMode = false;
+
+ function isFileEdited() {
+ return _isEditMode;
+ }
function isFileOpened() {
return _isFileOpened;
@@ -31,7 +35,13 @@ define(function(require, exports, module) {
function openFile(filePath) {
console.debug("Opening file: "+filePath);
-
+
+ if(TSCORE.FileOpener.isFileEdited()) {
+ if(!confirm("Any unsaved changes will be lost! \nDo you want to continue?")) {
+ return false;
+ }
+ }
+
_isEditMode = false;
_openedFilePath = filePath;
@@ -115,9 +125,18 @@ define(function(require, exports, module) {
var tags = TSCORE.TagUtils.extractTags(filePath);
var title = TSCORE.TagUtils.extractTitle(filePath);
+
+ $("#fileTitle").unbind('.editInPlace');
+ $("#fileTitle").data('editInPlace',false);
$( "#fileTitle" ).text(title);
+ $( "#fileTitle" ).editInPlace({
+ callback: function(unused, newTitle) { TSCORE.TagUtils.changeTitle(filePath,newTitle); },
+ show_buttons: false,
+ callback_skip_dom_reset: true
+ });
+
// Generate tag buttons
$( "#fileTags" ).empty();
for (var i=0; i < tags.length; i++) {
@@ -282,8 +301,6 @@ define(function(require, exports, module) {
}
};
saveFile(filePath);
- // TODO not a nice solution using setTimeOut for this
- window.setTimeout(openFile(filePath), 1000);
}
}
$( this ).button( "option", options );
@@ -372,6 +389,7 @@ define(function(require, exports, module) {
// Methods
exports.openFile = openFile;
exports.isFileOpened = isFileOpened;
+ exports.isFileEdited = isFileEdited;
exports.setFileOpened = setFileOpened;
exports.getOpenedFilePath = getOpenedFilePath;
exports.updateEditorContent = updateEditorContent;
diff --git a/data/js/ioapi.mozilla.receiver.js b/data/js/ioapi.mozilla.receiver.js
index 61aa764dd..180810cb1 100644
--- a/data/js/ioapi.mozilla.receiver.js
+++ b/data/js/ioapi.mozilla.receiver.js
@@ -42,7 +42,7 @@ console.debug("Loading messaging.mozilla.js..");
TSCORE.updateLogger("Rename success");
// message.content contains the name of the file after the rename
if(TSCORE.FileOpener.isFileOpened()) {
- TSCORE.FileOpener.openFile(message.content);
+ TSCORE.FileOpener.openFile(message.content);
}
// TODO to be replaced with a function which replaced the
// renamed file in the model of the perspective
@@ -53,7 +53,10 @@ console.debug("Loading messaging.mozilla.js..");
break;
case "saveTextFile":
if(message.success){
- TSCORE.updateLogger("Save success");
+ if(TSCORE.FileOpener.isFileOpened()) {
+ // TODO Automatically reopening of the file is not desirable in every case ...
+ TSCORE.FileOpener.openFile(message.content);
+ }
} else {
TSCORE.updateLogger("Save failed");
}
diff --git a/data/js/tagutils.js b/data/js/tagutils.js
index 875037c9c..ca9947f63 100644
--- a/data/js/tagutils.js
+++ b/data/js/tagutils.js
@@ -222,6 +222,26 @@ define(function(require, exports, module) {
IOAPI.renameFile(filePath, containingDirectoryPath+DIR_SEPARATOR+newFileName);
}
+
+ function changeTitle(filePath, newTitle) {
+ console.debug("Changing title for file: "+filePath);
+
+ var containingDirectoryPath = extractContainingDirectoryPath(filePath);
+
+ var extractedTags = extractTags(filePath);
+
+ var fileExt = extractFileExtension(filePath);
+ if(fileExt.length > 0) {
+ fileExt = "."+fileExt;
+ }
+
+ // TODO generalize generateFileName to support fileTitle & fileExtension
+ var newFileName = generateFileName(newTitle, extractedTags);
+
+ IOAPI.renameFile(filePath, containingDirectoryPath+DIR_SEPARATOR+newFileName+fileExt);
+
+ return true;
+ }
// Removing a tag from a filename
function removeTag(filePath, tagName) {
@@ -260,5 +280,6 @@ define(function(require, exports, module) {
exports.renameTag = renameTag;
exports.removeTag = removeTag;
exports.addTag = addTag;
+ exports.changeTitle = changeTitle;
});
\ No newline at end of file
diff --git a/data/libs/jqueryeditinplace/LICENSE b/data/libs/jqueryeditinplace/LICENSE
new file mode 100644
index 000000000..eaa9f40ff
--- /dev/null
+++ b/data/libs/jqueryeditinplace/LICENSE
@@ -0,0 +1,31 @@
+Software License Agreement (BSD License)
+
+Copyright (c) 2009, Dave Hauenstein <[email protected]>
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms, with or
+without modification, are permitted provided that the following conditions
+are met:
+
+- Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+- Neither the name of Dave Hauenstein, nor the names of any contributors may be
+ used to endorse or promote products derived from this software without
+ specific prior written permission of the contributor.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/data/libs/jqueryeditinplace/README b/data/libs/jqueryeditinplace/README
new file mode 100644
index 000000000..ff15824ab
--- /dev/null
+++ b/data/libs/jqueryeditinplace/README
@@ -0,0 +1,58 @@
+INTRODUCTION
+------------
+
+editInPlace is a jQuery plugin that turns any element or group of elements
+into an Ajax in-place editor using only one line of code. It’s written using the jQuery
+library, which is freely available at http://jquery.com.
+
+
+SUPPORT AND BUG REPORTS
+-----------------------
+
+Bug reports, as well as feature requests, may be submitted [on the google code page](http://code.google.com/p/jquery-in-place-editor/issues/list)
+
+
+QUICK START
+-----------
+
+Include jquery and the editin place scripts in your html page (preferably at the bottom so the page loads faster).
+
+ <script type="text/javascript" src="path/to/js/jquery.js"></script>
+ <script type="text/javascript" src="path/to/js/jquery.editinplace.js"></script>
+ <script type="text/javascript">
+ $(".inplace-editor").editInPlace({
+ url: "path/to/server/script.php"
+ });
+ </script>
+
+Create a div with the class 'inplace-editor'
+
+ <div class="inplace-editor"></div>
+
+Create a server side handler script (php, python, etc...), this example will use php
+
+The following parameters will be sent via a POST requeset to the server script
+
+* update_value
+* element_id
+* original_html
+
+e.g. in script.php:
+
+ $_POST['update_value']
+ $_POST['element_id']
+ $_POST['original_html']
+
+Alternatively you can set the option callback, so you can controll the whole saving process yourself (update other parts of the webpage and possibly not even save to the server at all). The editor accepts a wealth of other options to customize how it behaves. They are documented inline [in the sourcecode](lib/jquery.editInPlace.js) and are exposed as $.fn.editInPlace.defaults where you can change them globally for your app. For more examples of how to use the editor, have [a look at the demo html](demo/index.html) and [javascript](demo/js/demo.js).
+
+
+DOCUMENTATION
+-------------
+
+The Editor works in two stages. After initialization it is closed, wich means that it listens to a click on the element it was bound to. When clicked it will open, which means it replaces the content of the bound field with the configured GUI (input, textarea or select), preinitialized to show the value that was shown in that DOM element before. If the user then cancels or doesn't change anything, everything is returned to what it was before. If the user makes a change and commits, that new value is either submitted to the configured URL or to the configured callback and then the editor GUI is again replaced by just the edited value and the editor again listenes to a click.
+
+To support automated acceptance tests better the editor will set the class .editInPlace-active as soon as it opens, and will only remove it when it has finished any interaction with the server or the callback interface has told it so.
+
+More documenataion can be found on [the google code page of this product](http://code.google.com/p/jquery-in-place-editor/)
+
+Thats it! Have fun using it!
diff --git a/data/libs/jqueryeditinplace/jquery.editinplace.js b/data/libs/jqueryeditinplace/jquery.editinplace.js
new file mode 100644
index 000000000..7a0bb8072
--- /dev/null
+++ b/data/libs/jqueryeditinplace/jquery.editinplace.js
@@ -0,0 +1,646 @@
+/*
+
+A jQuery edit in place plugin
+
+Version 2.3.0
+
+Authors:
+ Dave Hauenstein
+ Martin Häcker <spamfaenger [at] gmx [dot] de>
+
+Project home:
+ http://code.google.com/p/jquery-in-place-editor/
+
+Patches with tests welcomed! For guidance see the tests </spec/unit/>. To submit, attach them to the bug tracker.
+
+License:
+This source file is subject to the BSD license bundled with this package.
+Available online: {@link http://www.opensource.org/licenses/bsd-license.php}
+If you did not receive a copy of the license, and are unable to obtain it,
+learn to use a search engine.
+
+*/
+
+(function($){
+
+$.fn.editInPlace = function(options) {
+
+ var settings = $.extend({}, $.fn.editInPlace.defaults, options);
+ assertMandatorySettingsArePresent(settings);
+ preloadImage(settings.saving_image);
+
+ return this.each(function() {
+ var dom = $(this);
+ // This won't work with live queries as there is no specific element to attach this
+ // one way to deal with this could be to store a reference to self and then compare that in click?
+ if (dom.data('editInPlace'))
+ return; // already an editor here
+ dom.data('editInPlace', true);
+
+ new InlineEditor(settings, dom).init();
+ });
+};
+
+/// Switch these through the dictionary argument to $(aSelector).editInPlace(overideOptions)
+/// Required Options: Either url or callback, so the editor knows what to do with the edited values.
+$.fn.editInPlace.defaults = {
+ url: "", // string: POST URL to send edited content
+ bg_over: "#ffc", // string: background color of hover of unactivated editor
+ bg_out: "transparent", // string: background color on restore from hover
+ hover_class: "", // string: class added to root element during hover. Will override bg_over and bg_out
+ show_buttons: false, // boolean: will show the buttons: cancel or save; will automatically cancel out the onBlur functionality
+ save_button: '<button class="inplace_save">Save</button>', // string: image button tag to use as “Save” button
+ cancel_button: '<button class="inplace_cancel">Cancel</button>', // string: image button tag to use as “Cancel” button
+ params: "", // string: example: first_name=dave&last_name=hauenstein extra paramters sent via the post request to the server
+ field_type: "text", // string: "text", "textarea", or "select"; The type of form field that will appear on instantiation
+ default_text: "(Click here to add text)", // string: text to show up if the element that has this functionality is empty
+ use_html: false, // boolean, set to true if the editor should use jQuery.fn.html() to extract the value to show from the dom node
+ textarea_rows: 10, // integer: set rows attribute of textarea, if field_type is set to textarea. Use CSS if possible though
+ textarea_cols: 25, // integer: set cols attribute of textarea, if field_type is set to textarea. Use CSS if possible though
+ select_text: "Choose new value", // string: default text to show up in select box
+ select_options: "", // string or array: Used if field_type is set to 'select'. Can be comma delimited list of options 'textandValue,text:value', Array of options ['textAndValue', 'text:value'] or array of arrays ['textAndValue', ['text', 'value']]. The last form is especially usefull if your labels or values contain colons)
+ text_size: null, // integer: set cols attribute of text input, if field_type is set to text. Use CSS if possible though
+
+ // Specifying callback_skip_dom_reset will disable all saving_* options
+ saving_text: undefined, // string: text to be used when server is saving information. Example "Saving..."
+ saving_image: "", // string: uses saving text specify an image location instead of text while server is saving
+ saving_animation_color: 'transparent', // hex color string, will be the color the pulsing animation during the save pulses to. Note: Only works if jquery-ui is loaded
+
+ value_required: false, // boolean: if set to true, the element will not be saved unless a value is entered
+ element_id: "element_id", // string: name of parameter holding the id or the editable
+ update_value: "update_value", // string: name of parameter holding the updated/edited value
+ original_value: 'original_value', // string: name of parameter holding the updated/edited value
+ original_html: "original_html", // string: name of parameter holding original_html value of the editable /* DEPRECATED in 2.2.0 */ use original_value instead.
+ save_if_nothing_changed: false, // boolean: submit to function or server even if the user did not change anything
+ on_blur: "save", // string: "save" or null; what to do on blur; will be overridden if show_buttons is true
+ cancel: "", // string: if not empty, a jquery selector for elements that will not cause the editor to open even though they are clicked. E.g. if you have extra buttons inside editable fields
+
+ // All callbacks will have this set to the DOM node of the editor that triggered the callback
+
+ callback: null, // function: function to be called when editing is complete; cancels ajax submission to the url param. Prototype: function(idOfEditor, enteredText, orinalHTMLContent, settingsParams, callbacks). The function needs to return the value that should be shown in the dom. Returning undefined means cancel and will restore the dom and trigger an error. callbacks is a dictionary with two functions didStartSaving and didEndSaving() that you can use to tell the inline editor that it should start and stop any saving animations it has configured. /* DEPRECATED in 2.1.0 */ Parameter idOfEditor, use $(this).attr('id') instead
+ callback_skip_dom_reset: false, // boolean: set this to true if the callback should handle replacing the editor with the new value to show
+ success: null, // function: this function gets called if server responds with a success. Prototype: function(newEditorContentString)
+ error: null, // function: this function gets called if server responds with an error. Prototype: function(request)
+ error_sink: function(idOfEditor, errorString) { alert(errorString); }, // function: gets id of the editor and the error. Make sure the editor has an id, or it will just be undefined. If set to null, no error will be reported. /* DEPRECATED in 2.1.0 */ Parameter idOfEditor, use $(this).attr('id') instead
+ preinit: null, // function: this function gets called after a click on an editable element but before the editor opens. If you return false, the inline editor will not open. Prototype: function(currentDomNode). DEPRECATED in 2.2.0 use delegate shouldOpenEditInPlace call instead
+ postclose: null, // function: this function gets called after the inline editor has closed and all values are updated. Prototype: function(currentDomNode). DEPRECATED in 2.2.0 use delegate didCloseEditInPlace call instead
+ delegate: null // object: if it has methods with the name of the callbacks documented below in delegateExample these will be called. This means that you just need to impelment the callbacks you are interested in.
+};
+
+// Lifecycle events that the delegate can implement
+// this will always be fixed to the delegate
+var delegateExample = {
+ // called while opening the editor.
+ // return false to prevent editor from opening
+ shouldOpenEditInPlace: function(aDOMNode, aSettingsDict, triggeringEvent) {},
+ // return content to show in inplace editor
+ willOpenEditInPlace: function(aDOMNode, aSettingsDict) {},
+ didOpenEditInPlace: function(aDOMNode, aSettingsDict) {},
+
+ // called while closing the editor
+ // return false to prevent the editor from closing
+ shouldCloseEditInPlace: function(aDOMNode, aSettingsDict, triggeringEvent) {},
+ // return value will be shown during saving
+ willCloseEditInPlace: function(aDOMNode, aSettingsDict) {},
+ didCloseEditInPlace: function(aDOMNode, aSettingsDict) {},
+
+ missingCommaErrorPreventer:''
+};
+
+
+function InlineEditor(settings, dom) {
+ this.settings = settings;
+ this.dom = dom;
+ this.originalValue = null;
+ this.didInsertDefaultText = false;
+ this.shouldDelayReinit = false;
+};
+
+$.extend(InlineEditor.prototype, {
+
+ init: function() {
+ this.setDefaultTextIfNeccessary();
+ this.connectOpeningEvents();
+ },
+
+ reinit: function() {
+ if (this.shouldDelayReinit)
+ return;
+
+ this.triggerCallback(this.settings.postclose, /* DEPRECATED in 2.1.0 */ this.dom);
+ this.triggerDelegateCall('didCloseEditInPlace');
+
+ this.markEditorAsInactive();
+ this.connectOpeningEvents();
+ },
+
+ setDefaultTextIfNeccessary: function() {
+ if('' !== this.dom.html())
+ return;
+
+ this.dom.html(this.settings.default_text);
+ this.didInsertDefaultText = true;
+ },
+
+ connectOpeningEvents: function() {
+ var that = this;
+ this.dom
+ .bind('mouseenter.editInPlace', function(){ that.addHoverEffect(); })
+ .bind('mouseleave.editInPlace', function(){ that.removeHoverEffect(); })
+ .bind('click.editInPlace', function(anEvent){ that.openEditor(anEvent); });
+ },
+
+ disconnectOpeningEvents: function() {
+ // prevent re-opening the editor when it is already open
+ this.dom.unbind('.editInPlace');
+ },
+
+ addHoverEffect: function() {
+ if (this.settings.hover_class)
+ this.dom.addClass(this.settings.hover_class);
+ else
+ this.dom.css("background-color", this.settings.bg_over);
+ },
+
+ removeHoverEffect: function() {
+ if (this.settings.hover_class)
+ this.dom.removeClass(this.settings.hover_class);
+ else
+ this.dom.css("background-color", this.settings.bg_out);
+ },
+
+ openEditor: function(anEvent) {
+ if ( ! this.shouldOpenEditor(anEvent))
+ return;
+
+ this.disconnectOpeningEvents();
+ this.removeHoverEffect();
+ this.removeInsertedDefaultTextIfNeccessary();
+ this.saveOriginalValue();
+ this.markEditorAsActive();
+ this.replaceContentWithEditor();
+ this.setInitialValue();
+ this.workAroundMissingBlurBug();
+ this.connectClosingEventsToEditor();
+ this.triggerDelegateCall('didOpenEditInPlace');
+ },
+
+ shouldOpenEditor: function(anEvent) {
+ if (this.isClickedObjectCancelled(anEvent.target))
+ return false;
+
+ if (false === this.triggerCallback(this.settings.preinit, /* DEPRECATED in 2.1.0 */ this.dom))
+ return false;
+
+ if (false === this.triggerDelegateCall('shouldOpenEditInPlace', true, anEvent))
+ return false;
+
+ return true;
+ },
+
+ removeInsertedDefaultTextIfNeccessary: function() {
+ if ( ! this.didInsertDefaultText
+ || this.dom.html() !== this.settings.default_text)
+ return;
+
+ this.dom.html('');
+ this.didInsertDefaultText = false;
+ },
+
+ isClickedObjectCancelled: function(eventTarget) {
+ if ( ! this.settings.cancel)
+ return false;
+
+ var eventTargetAndParents = $(eventTarget).parents().andSelf();
+ var elementsMatchingCancelSelector = eventTargetAndParents.filter(this.settings.cancel);
+ return 0 !== elementsMatchingCancelSelector.length;
+ },
+
+ saveOriginalValue: function() {
+ if (this.settings.use_html)
+ this.originalValue = this.dom.html();
+ else
+ this.originalValue = trim(this.dom.text());
+ },
+
+ restoreOriginalValue: function() {
+ this.setClosedEditorContent(this.originalValue);
+ },
+
+ setClosedEditorContent: function(aValue) {
+ if (this.settings.use_html)
+ this.dom.html(aValue);
+ else
+ this.dom.text(aValue);
+ },
+
+ workAroundMissingBlurBug: function() {
+ // Strangely, all browser will forget to send a blur event to an input element
+ // when another one is created and selected programmatically. (at least under some circumstances).
+ // This means that if another inline editor is opened, existing inline editors will _not_ close
+ // if they are configured to submit when blurred.
+
+ // Using parents() instead document as base to workaround the fact that in the unittests
+ // the editor is not a child of window.document but of a document fragment
+ var ourInput = this.dom.find(':input');
+ this.dom.parents(':last').find('.editInPlace-active :input').not(ourInput).blur();
+ },
+
+ replaceContentWithEditor: function() {
+ var buttons_html = (this.settings.show_buttons) ? this.settings.save_button + ' ' + this.settings.cancel_button : '';
+ var editorElement = this.createEditorElement(); // needs to happen before anything is replaced
+ /* insert the new in place form after the element they click, then empty out the original element */
+ this.dom.html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;"></form>')
+ .find('form')
+ .append(editorElement)
+ .append(buttons_html);
+ },
+
+ createEditorElement: function() {
+ if (-1 === $.inArray(this.settings.field_type, ['text', 'textarea', 'select']))
+ throw "Unknown field_type <fnord>, supported are 'text', 'textarea' and 'select'";
+
+ var editor = null;
+ if ("select" === this.settings.field_type)
+ editor = this.createSelectEditor();
+ else if ("text" === this.settings.field_type)
+ editor = $('<input type="text" ' + this.inputNameAndClass()
+ + ' size="' + this.settings.text_size + '" />');
+ else if ("textarea" === this.settings.field_type)
+ editor = $('<textarea ' + this.inputNameAndClass()
+ + ' rows="' + this.settings.textarea_rows + '" '
+ + ' cols="' + this.settings.textarea_cols + '" />');
+
+ return editor;
+ },
+
+ setInitialValue: function() {
+ var initialValue = this.triggerDelegateCall('willOpenEditInPlace', this.originalValue);
+ var editor = this.dom.find(':input');
+ editor.val(initialValue);
+
+ // Workaround for select fields which don't contain the original value.
+ // Somehow the browsers don't like to select the instructional choice (disabled) in that case
+ if (editor.val() !== initialValue)
+ editor.val(''); // selects instructional choice
+ },
+
+ inputNameAndClass: function() {
+ return ' name="inplace_value" class="inplace_field" ';
+ },
+
+ createSelectEditor: function() {
+ var editor = $('<select' + this.inputNameAndClass() + '>'
+ + '<option disabled="true" value="">' + this.settings.select_text + '</option>'
+ + '</select>');
+
+ var optionsArray = this.settings.select_options;
+ if ( ! $.isArray(optionsArray))
+ optionsArray = optionsArray.split(',');
+
+ for (var i=0; i<optionsArray.length; i++) {
+ var currentTextAndValue = optionsArray[i];
+ if ( ! $.isArray(currentTextAndValue))
+ currentTextAndValue = currentTextAndValue.split(':');
+
+ var value = trim(currentTextAndValue[1] || currentTextAndValue[0]);
+ var text = trim(currentTextAndValue[0]);
+
+ var option = $('<option>').val(value).text(text);
+ editor.append(option);
+ }
+
+ return editor;
+ },
+
+ connectClosingEventsToEditor: function() {
+ var that = this;
+ function cancelEditorAction(anEvent) {
+ that.handleCancelEditor(anEvent);
+ return false; // stop event bubbling
+ }
+ function saveEditorAction(anEvent) {
+ that.handleSaveEditor(anEvent);
+ return false; // stop event bubbling
+ }
+
+ var form = this.dom.find("form");
+
+ form.find(".inplace_field").focus().select();
+ form.find(".inplace_cancel").click(cancelEditorAction);
+ form.find(".inplace_save").click(saveEditorAction);
+
+ if ( ! this.settings.show_buttons) {
+ // TODO: Firefox has a bug where blur is not reliably called when focus is lost
+ // (for example by another editor appearing)
+ if ("save" === this.settings.on_blur)
+ form.find(".inplace_field").blur(saveEditorAction);
+ else
+ form.find(".inplace_field").blur(cancelEditorAction);
+
+ // workaround for msie & firefox bug where it won't submit on enter if no button is shown
+ if ($.browser.mozilla || $.browser.msie)
+ this.bindSubmitOnEnterInInput();
+ }
+
+ form.keyup(function(anEvent) {
+ // allow canceling with escape
+ var escape = 27;
+ if (escape === anEvent.which)
+ return cancelEditorAction();
+ });
+
+ // workaround for webkit nightlies where they won't submit at all on enter
+ // REFACT: find a way to just target the nightlies
+ if ($.browser.safari)
+ this.bindSubmitOnEnterInInput();
+
+
+ form.submit(saveEditorAction);
+ },
+
+ bindSubmitOnEnterInInput: function() {
+ if ('textarea' === this.settings.field_type)
+ return; // can't enter newlines otherwise
+
+ var that = this;
+ this.dom.find(':input').keyup(function(event) {
+ var enter = 13;
+ if (enter === event.which)
+ return that.dom.find('form').submit();
+ });
+
+ },
+
+ handleCancelEditor: function(anEvent) {
+ // REFACT: remove duplication between save and cancel
+ if (false === this.triggerDelegateCall('shouldCloseEditInPlace', true, anEvent))
+ return;
+
+ var enteredText = this.dom.find(':input').val();
+ enteredText = this.triggerDelegateCall('willCloseEditInPlace', enteredText);
+
+ this.restoreOriginalValue();
+ if (hasContent(enteredText)
+ && ! this.isDisabledDefaultSelectChoice())
+ this.setClosedEditorContent(enteredText);
+ this.reinit();
+ },
+
+ handleSaveEditor: function(anEvent) {
+ if (false === this.triggerDelegateCall('shouldCloseEditInPlace', true, anEvent))
+ return;
+
+ var enteredText = this.dom.find(':input').val();
+ enteredText = this.triggerDelegateCall('willCloseEditInPlace', enteredText);
+
+ if (this.isDisabledDefaultSelectChoice()
+ || this.isUnchangedInput(enteredText)) {
+ this.handleCancelEditor(anEvent);
+ return;
+ }
+
+ if (this.didForgetRequiredText(enteredText)) {
+ this.handleCancelEditor(anEvent);
+ this.reportError("Error: You must enter a value to save this field");
+ return;
+ }
+
+ this.showSaving(enteredText);
+
+ if (this.settings.callback)
+ this.handleSubmitToCallback(enteredText);
+ else
+ this.handleSubmitToServer(enteredText);
+ },
+
+ didForgetRequiredText: function(enteredText) {
+ return this.settings.value_required
+ && ("" === enteredText
+ || undefined === enteredText
+ || null === enteredText);
+ },
+
+ isDisabledDefaultSelectChoice: function() {
+ return this.dom.find('option').eq(0).is(':selected:disabled');
+ },
+
+ isUnchangedInput: function(enteredText) {
+ return ! this.settings.save_if_nothing_changed
+ && this.originalValue === enteredText;
+ },
+
+ showSaving: function(enteredText) {
+ if (this.settings.callback && this.settings.callback_skip_dom_reset)
+ return;
+
+ var savingMessage = enteredText;
+ if (hasContent(this.settings.saving_text))
+ savingMessage = this.settings.saving_text;
+ if(hasContent(this.settings.saving_image))
+ // REFACT: alt should be the configured saving message
+ savingMessage = $('<img />').attr('src', this.settings.saving_image).attr('alt', savingMessage);
+ this.dom.html(savingMessage);
+ },
+
+ handleSubmitToCallback: function(enteredText) {
+ // REFACT: consider to encode enteredText and originalHTML before giving it to the callback
+ this.enableOrDisableAnimationCallbacks(true, false);
+ var newHTML = this.triggerCallback(this.settings.callback, /* DEPRECATED in 2.1.0 */ this.id(), enteredText, this.originalValue,
+ this.settings.params, this.savingAnimationCallbacks());
+
+ if (this.settings.callback_skip_dom_reset)
+ ; // do nothing
+ else if (undefined === newHTML) {
+ // failure; put original back
+ this.reportError("Error: Failed to save value: " + enteredText);
+ this.restoreOriginalValue();
+ }
+ else
+ // REFACT: use setClosedEditorContent
+ this.dom.html(newHTML);
+
+ if (this.didCallNoCallbacks()) {
+ this.enableOrDisableAnimationCallbacks(false, false);
+ this.reinit();
+ }
+ },
+
+ handleSubmitToServer: function(enteredText) {
+ var data = this.settings.update_value + '=' + encodeURIComponent(enteredText)
+ + '&' + this.settings.element_id + '=' + this.dom.attr("id")
+ + ((this.settings.params) ? '&' + this.settings.params : '')
+ + '&' + this.settings.original_html + '=' + encodeURIComponent(this.originalValue) /* DEPRECATED in 2.2.0 */
+ + '&' + this.settings.original_value + '=' + encodeURIComponent(this.originalValue);
+
+ this.enableOrDisableAnimationCallbacks(true, false);
+ this.didStartSaving();
+ var that = this;
+ $.ajax({
+ url: that.settings.url,
+ type: "POST",
+ data: data,
+ dataType: "html",
+ complete: function(request){
+ that.didEndSaving();
+ },
+ success: function(html){
+ var new_text = html || that.settings.default_text;
+
+ /* put the newly updated info into the original element */
+ // FIXME: should be affected by the preferences switch
+ that.dom.html(new_text);
+ // REFACT: remove dom parameter, already in this, not documented, should be easy to remove
+ // REFACT: callback should be able to override what gets put into the DOM
+ that.triggerCallback(that.settings.success, html);
+ },
+ error: function(request) {
+ that.dom.html(that.originalHTML); // REFACT: what about a restorePreEditingContent()
+ if (that.settings.error)
+ // REFACT: remove dom parameter, already in this, not documented, can remove without deprecation
+ // REFACT: callback should be able to override what gets entered into the DOM
+ that.triggerCallback(that.settings.error, request);
+ else
+ that.reportError("Failed to save value: " + request.responseText || 'Unspecified Error');
+ }
+ });
+ },
+
+ // Utilities .........................................................
+
+ triggerCallback: function(aCallback /*, arguments */) {
+ if ( ! aCallback)
+ return; // callback wasn't specified after all
+
+ var callbackArguments = Array.prototype.slice.call(arguments, 1);
+ return aCallback.apply(this.dom[0], callbackArguments);
+ },
+
+ /// defaultReturnValue is only used if the delegate returns undefined
+ triggerDelegateCall: function(aDelegateMethodName, defaultReturnValue, optionalEvent) {
+ // REFACT: consider to trigger equivalent callbacks automatically via a mapping table?
+ if ( ! this.settings.delegate
+ || ! $.isFunction(this.settings.delegate[aDelegateMethodName]))
+ return defaultReturnValue;
+
+ var delegateReturnValue = this.settings.delegate[aDelegateMethodName](this.dom, this.settings, optionalEvent);
+ return (undefined === delegateReturnValue)
+ ? defaultReturnValue
+ : delegateReturnValue;
+ },
+
+ reportError: function(anErrorString) {
+ this.triggerCallback(this.settings.error_sink, /* DEPRECATED in 2.1.0 */ this.id(), anErrorString);
+ },
+
+ // REFACT: this method should go, callbacks should get the dom node itself as an argument
+ id: function() {
+ return this.dom.attr('id');
+ },
+
+ markEditorAsActive: function() {
+ this.dom.addClass('editInPlace-active');
+ },
+
+ markEditorAsInactive: function() {
+ this.dom.removeClass('editInPlace-active');
+ },
+
+ // REFACT: consider rename, doesn't deal with animation directly
+ savingAnimationCallbacks: function() {
+ var that = this;
+ return {
+ didStartSaving: function() { that.didStartSaving(); },
+ didEndSaving: function() { that.didEndSaving(); }
+ };
+ },
+
+ enableOrDisableAnimationCallbacks: function(shouldEnableStart, shouldEnableEnd) {
+ this.didStartSaving.enabled = shouldEnableStart;
+ this.didEndSaving.enabled = shouldEnableEnd;
+ },
+
+ didCallNoCallbacks: function() {
+ return this.didStartSaving.enabled && ! this.didEndSaving.enabled;
+ },
+
+ assertCanCall: function(methodName) {
+ if ( ! this[methodName].enabled)
+ throw new Error('Cannot call ' + methodName + ' now. See documentation for details.');
+ },
+
+ didStartSaving: function() {
+ this.assertCanCall('didStartSaving');
+ this.shouldDelayReinit = true;
+ this.enableOrDisableAnimationCallbacks(false, true);
+
+ this.startSavingAnimation();
+ },
+
+ didEndSaving: function() {
+ this.assertCanCall('didEndSaving');
+ this.shouldDelayReinit = false;
+ this.enableOrDisableAnimationCallbacks(false, false);
+ this.reinit();
+
+ this.stopSavingAnimation();
+ },
+
+ startSavingAnimation: function() {
+ var that = this;
+ this.dom
+ .animate({ backgroundColor: this.settings.saving_animation_color }, 400)
+ .animate({ backgroundColor: 'transparent'}, 400, 'swing', function(){
+ // In the tests animations are turned off - i.e they happen instantaneously.
+ // Hence we need to prevent this from becomming an unbounded recursion.
+ setTimeout(function(){ that.startSavingAnimation(); }, 10);
+ });
+ },
+
+ stopSavingAnimation: function() {
+ this.dom
+ .stop(true)
+ .css({backgroundColor: ''});
+ },
+
+ missingCommaErrorPreventer:''
+});
+
+
+
+// Private helpers .......................................................
+
+function assertMandatorySettingsArePresent(options) {
+ // one of these needs to be non falsy
+ if (options.url || options.callback)
+ return;
+
+ throw new Error("Need to set either url: or callback: option for the inline editor to work.");
+}
+
+/* preload the loading icon if it is configured */
+function preloadImage(anImageURL) {
+ if ('' === anImageURL)
+ return;
+
+ var loading_image = new Image();
+ loading_image.src = anImageURL;
+}
+
+function trim(aString) {
+ return aString
+ .replace(/^\s+/, '')
+ .replace(/\s+$/, '');
+}
+
+function hasContent(something) {
+ if (undefined === something || null === something)
+ return false;
+
+ if (0 === something.length)
+ return false;
+
+ return true;
+}
+
+})(jQuery);
diff --git a/lib/ioutils.js b/lib/ioutils.js
index e856a0402..25c465942 100644
--- a/lib/ioutils.js
+++ b/lib/ioutils.js
@@ -348,12 +348,14 @@ exports.saveTextFile = function saveTextFile(filePath, content, worker) {
out.close();
worker.postMessage({
"command": "saveTextFile",
+ "content": filePath,
"success": true
});
console.debug("Save successed!");
} catch(ex) {
worker.postMessage({
"command": "saveTextFile",
+ "content": filePath,
"success": false
});
console.error("Save failed "+ex);