File uploads in nicEdit

master
vitalif 2012-10-14 22:37:12 +00:00 committed by Vitaliy Filippov
parent e223cf90e8
commit 40cb6c81dd
3 changed files with 83 additions and 103 deletions

View File

@ -538,6 +538,18 @@ var nicEditorInstance = bkClass.extend({
} }
}, },
selBlockType : function() {
var e = this.selElm();
var t = {'P':1,'PRE':1,'H1':1,'H2':1,'H3':1,'H4':1,'H5':1,'H6':1};
while (e != this.elm) {
if (t[e.nodeName]) {
return e.nodeName;
}
e = e.parentNode;
}
return false;
},
saveRng : function() { saveRng : function() {
this.savedRange = this.getRng(); this.savedRange = this.getRng();
this.savedSel = this.getSel(); this.savedSel = this.getSel();
@ -551,13 +563,9 @@ var nicEditorInstance = bkClass.extend({
keyDown : function(e,t) { keyDown : function(e,t) {
if(e.keyCode == 13 || e.keyCode == 10) { if(e.keyCode == 13 || e.keyCode == 10) {
if (!e.ctrlKey) { if (!e.shiftKey && !this.selBlockType()) {
this.ne.nicCommand('insertHTML','<p></p>'); this.ne.nicCommand('formatBlock', 'p');
} else {
this.ne.nicCommand('insertHTML','<br />');
} }
e.preventDefault();
return false;
} }
if(e.ctrlKey) { if(e.ctrlKey) {
this.ne.fireEvent('key',this,e); this.ne.fireEvent('key',this,e);
@ -990,7 +998,7 @@ var nicEditorAdvancedButton = nicEditorButton.extend({
document._nicCss.appendChild(document.createTextNode( document._nicCss.appendChild(document.createTextNode(
'.niceabf table { border-collapse: collapse; }\n'+ '.niceabf table { border-collapse: collapse; }\n'+
'.niceabf td { padding: 2px 5px 2px 0; }\n'+ '.niceabf td { padding: 2px 5px 2px 0; }\n'+
'.niceabf td.h { vertical-align: top; padding-top: 4px; }\n'+ '.niceabf td.h { vertical-align: top; padding-top: 4px; white-space: nowrap; }\n'+
'.niceabf h2 { font-size: 14px; font-weight: bold; padding: 0; margin: 0; }\n'+ '.niceabf h2 { font-size: 14px; font-weight: bold; padding: 0; margin: 0; }\n'+
'.niceabf input, .niceabf select { vertical-align: middle; font-size: 13px; border: 1px solid #ccc; }\n'+ '.niceabf input, .niceabf select { vertical-align: middle; font-size: 13px; border: 1px solid #ccc; }\n'+
'.niceabf textarea { border: 1px solid #ccc; }\n'+ '.niceabf textarea { border: 1px solid #ccc; }\n'+

View File

@ -1,22 +1,23 @@
/** nicImageGT */ /** nicImageUploadGT (Image+Upload) */
/* START CONFIG */ /* START CONFIG */
var nicImageOptions = { var nicImageUploadGTOptions = {
buttons: { buttons: {
'image': {name: __('Add Image'), type: 'nicImageButton', tags: ['IMG']} 'image': {name: __('Add Image'), type: 'nicImageUploadGTButton', tags: ['IMG']}
} }
}; };
/* END CONFIG */ /* END CONFIG */
var nicImageButton = nicEditorAdvancedButton.extend({ var nicImageUploadGTButton = nicEditorAdvancedButton.extend({
addPane: function() { addPane: function() {
this.im = this.ne.selectedInstance.selElm().parentTag('IMG'); this.im = (this.selElm || this.ne.selectedInstance.selElm()).parentTag('IMG');
var params = this.parseParams(this.im); var s, params = this.parseParams(this.im);
this.addForm({ this.addForm({
'': {type: 'title', txt: __('Add/Edit Image')}, '': {type: 'title', txt: __('Add/Edit Image')},
'src': {type: 'text', txt: __('URL or Name'), style: {width: '150px'}}, 'src': {type: 'text', txt: __('URL or Name'), style: {width: '150px'}},
'upload': {type: 'container', txt: __('Or upload')},
'href': {type: 'text', txt: __('Hyperlink'), style: {width: '150px'}}, 'href': {type: 'text', txt: __('Hyperlink'), style: {width: '150px'}},
'size': {type: 'container', txt: __('Max Size')}, 'size': {type: 'container', txt: __('Max Size')},
'align': {type: 'select', txt: __('Align'), options: {none: __('Inline'), left: __('Left'), right: __('Right')}}, 'align': {type: 'select', txt: __('Align'), options: {none: __('Inline'), left: __('Left'), right: __('Right')}},
@ -24,17 +25,40 @@ var nicImageButton = nicEditorAdvancedButton.extend({
this.hinter = new SimpleAutocomplete(this.inputs['src'], this.gtLoadData.closure(this), null, null, null, false, true); this.hinter = new SimpleAutocomplete(this.inputs['src'], this.gtLoadData.closure(this), null, null, null, false, true);
var s = this.inputs['href'].parentNode; s = this.inputs['href'].parentNode;
new bkElement('br').appendTo(s); new bkElement('br').appendTo(s);
this.inputs['newwindow'] = new bkElement('input').setAttributes({type: 'checkbox', id: 'newwindow', checked: 1 && params.newwindow}).appendTo(s); this.inputs['newwindow'] = new bkElement('input').setAttributes({type: 'checkbox', id: 'newwindow', checked: 1 && params.newwindow}).appendTo(s);
new bkElement('label').setAttributes({htmlFor: 'newwindow'}).setContent(__('Open in new window')).appendTo(s); new bkElement('label').setAttributes({htmlFor: 'newwindow'}).setContent(__('Open in new window')).appendTo(s);
var self = this;
s = this.inputs['upload'];
this.inputs['fileName'] = new bkElement('input').setStyle({width: '150px', height: '20px'}).setAttributes({type: 'button', value: __('Select file')}).appendTo(s);
this.inputs['fileName'].addEvent('click', function() { self.inputs['file'].click(); });
this.inputs['file'] = new bkElement('input').setStyle({width: '150px', display: 'none'}).setAttributes({type: 'file', size: 5}).appendTo(s);
this.inputs['file'].addEvent('change', this.onFileChange.closure(this));
new bkElement('br').appendTo(s);
this.inputs['progress'] = new bkElement('progress')
.setStyle({ width: '100%', display: 'none' })
.setAttributes('max', 100)
.appendTo(s);
s = this.inputs['size']; s = this.inputs['size'];
this.inputs['width'] = new bkElement('input').setAttributes({type: 'text', size: 5, value: params.width||''}).appendTo(s); this.inputs['width'] = new bkElement('input').setAttributes({type: 'text', size: 5, value: params.width||''}).appendTo(s);
s.appendChild(document.createTextNode(' x ')); s.appendChild(document.createTextNode(' x '));
this.inputs['height'] = new bkElement('input').setAttributes({type: 'text', size: 5, value: params.height||''}).appendTo(s); this.inputs['height'] = new bkElement('input').setAttributes({type: 'text', size: 5, value: params.height||''}).appendTo(s);
}, },
onFileChange: function() {
this.inputs['src'].value = '';
this.inputs['fileName'].value = this.inputs['file'].files[0].name;
},
checkNodes: function(e) {
var r = nicEditorAdvancedButton.prototype.checkNodes.apply(this, [e]);
this.selElm = r ? e : null;
return r;
},
parseParams: function(elm) { parseParams: function(elm) {
var r = { getAttribute: function(n) { return this[n]; } }; var r = { getAttribute: function(n) { return this[n]; } };
if (!elm) return r; if (!elm) return r;
@ -82,6 +106,11 @@ var nicImageButton = nicEditorAdvancedButton.extend({
}, },
submit: function(e) { submit: function(e) {
if (!this.inputs['src'].value && this.inputs['file'].files[0]) {
// Upload the file, then continue from a callback
this.uploadFile();
return false;
}
var src = this.inputs['src'].value; var src = this.inputs['src'].value;
var gtId = /^#(\d+)(\s*-\s*)?(.*)/.exec(src); var gtId = /^#(\d+)(\s*-\s*)?(.*)/.exec(src);
var alt = ''; var alt = '';
@ -130,113 +159,54 @@ var nicImageButton = nicEditorAdvancedButton.extend({
align: this.inputs['align'].value align: this.inputs['align'].value
}); });
} }
}
});
nicEditors.registerPlugin(nicPlugin,nicImageOptions);
/** nicUploadGT */
/* START CONFIG */
var nicUploadOptions = {
buttons: {
'upload': {name: __('Upload Image'), type: 'nicUploadButton'}
}
};
/* END CONFIG */
var nicUploadButton = nicEditorAdvancedButton.extend({
errorText: __('Failed to upload image'),
addPane: function() {
if(typeof window.FormData === "undefined") {
return this.onError(__("Image uploads are not supported in this browser, use Chrome, Firefox, or Safari instead."));
}
this.im = this.ne.selectedInstance.selElm().parentTag('IMG');
var container = new bkElement('div')
.setStyle({ padding: '10px' })
.appendTo(this.pane.pane);
new bkElement('div')
.setStyle({ fontSize: '14px', fontWeight: 'bold', paddingBottom: '5px' })
.setContent(__('Insert an Image'))
.appendTo(container);
this.fileInput = new bkElement('input')
.setAttributes({ type: 'file' })
.appendTo(container);
this.progress = new bkElement('progress')
.setStyle({ width: '100%', display: 'none' })
.setAttributes('max', 100)
.appendTo(container);
this.fileInput.onchange = this.uploadFile.closure(this);
},
onError: function(msg) {
this.removePane();
alert(msg || __("Failed to upload image"));
}, },
uploadFile: function() { uploadFile: function() {
var file = this.fileInput.files[0]; var file = this.inputs['file'].files[0];
if (!file || !file.type.match(/image.*/)) { if (!file || !file.type.match(/image.*/)) {
this.onError(__("Only image files can be uploaded")); alert(__("Only image files can be uploaded"));
return; return;
} }
this.fileInput.setStyle({ display: 'none' }); this.inputs['file'].setStyle({display: 'none'});
this.setProgress(0); this.setProgress(0);
var fd = new FormData(); // https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/ var fd = new FormData(); // https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
fd.append("image", file); fd.append("e_file", file);
fd.append("key", "b7ea18a4ecbda8e92203fa4968d10660"); fd.append("e_title", file.name);
var xhr = new XMLHttpRequest();
xhr.open("POST", this.ne.options.uploadURI || this.nicURI);
var self = this;
var xhr = new XMLHttpRequest();
xhr.open("POST", GT.domain+'/file.php?action=save&format=json');
xhr.onload = function() { xhr.onload = function() {
try { try { var res = JSON.parse(xhr.responseText); } catch(e) {}
var res = JSON.parse(xhr.responseText); if (res && (res.file || res.duplicate)) {
} catch(e) { self.onUploaded(res);
return this.onError(); } else {
alert(__('Error uploading file') + (res && res.error ? ': '+res.error : ''));
} }
this.onUploaded(res.upload); };
}.closure(this); xhr.onerror = function(e) { alert(__('Error uploading file')+': '+e); };
xhr.onerror = this.onError.closure(this);
xhr.upload.onprogress = function(e) { xhr.upload.onprogress = function(e) {
this.setProgress(e.loaded / e.total); self.setProgress(e.loaded / e.total);
}.closure(this); };
xhr.send(fd); xhr.send(fd);
}, },
setProgress: function(percent) { onUploaded: function(r) {
this.progress.setStyle({ display: 'block' }); var f = r.file||r.duplicate;
if(percent < .98) { this.inputs['src'].value = '#'+f.id+' - '+f.title;
this.progress.value = percent; this.submit();
} else {
this.progress.removeAttribute('value');
}
}, },
onUploaded: function(options) { setProgress: function(percent) {
this.removePane(); var p = this.inputs['progress'];
var src = options.links.original; p.setStyle({display: 'block'});
if(!this.im) { if(percent < .98) {
this.ne.selectedInstance.restoreRng(); p.value = percent;
var tmp = 'javascript:nicImTemp();'; } else {
this.ne.nicCommand("insertImage", src); p.removeAttribute('value');
this.im = this.findElm('IMG','src', src);
} }
var w = parseInt(this.ne.selectedInstance.elm.getStyle('width')); },
if(this.im) {
this.im.setAttributes({
src: src,
width: (w && options.image.width) ? Math.min(w, options.image.width) : ''
});
}
}
}); });
nicEditors.registerPlugin(nicPlugin,nicUploadOptions); nicEditors.registerPlugin(nicPlugin,nicImageUploadGTOptions);

View File

@ -73,6 +73,8 @@ var nicRu = {
'Open in new window': 'Открывать в новом окне', 'Open in new window': 'Открывать в новом окне',
'Max Size': 'Макс. размер', 'Max Size': 'Макс. размер',
'To insert an image you must select uploaded file ID or enter the image URL!': 'Чтобы вставить картинку, либо выберите её из выпадающего списка (работают подсказки по названию), либо введите её прямой URL!', 'To insert an image you must select uploaded file ID or enter the image URL!': 'Чтобы вставить картинку, либо выберите её из выпадающего списка (работают подсказки по названию), либо введите её прямой URL!',
'Or upload': 'Или загрузить',
'Select file': 'Выбрать файл',
'Upload Image': 'Загрузить картинку', 'Upload Image': 'Загрузить картинку',
'Failed to upload image': 'Ошибка загрузки картинки', 'Failed to upload image': 'Ошибка загрузки картинки',