Defining menu items
Char count, Button groups
Iframe, fullPage and use CodeMirror (^5.0.0)
Image management
Attached files
Attach image
0KB
Video list
<!-- image list -->
<div id="image_wrapper" class="image-list">
<div class="file-list-info">
<span>Attached files</span>
<span class="xefu-btn">
<span class="files-text">Attach image</span>
</span>
<input type="file" id="files_upload" accept="image/*" multiple="multiple" class="files-text files-input"/>
<span id="image_size" class="total-size text-small-2">0KB</span>
<button class="btn btn-md btn-danger" id="image_remove" disabled onclick="deleteCheckedImages()">Remove</button>
</div>
<div class="file-list">
<ul id="image_list">
</ul>
</div>
</div>
<!-- video list -->
<div class="image-list">
<div class="file-list-info">
<span>Video list</span>
</div>
<div class="video-file-list">
<ul id="video_list">
</ul>
</div>
</div>
const imageWrapper = document.getElementById('image_wrapper');
const imageSize = document.getElementById('image_size');
const imageRemove = document.getElementById('image_remove');
const imageTable = document.getElementById('image_list');
let imageList = [];
let selectedImages = [];
const videoTable = document.getElementById('video_list');
let videoList = [];
// Array.prototype.findIndex (IE)
function findIndex(arr, index) {
let idx = -1;
arr.some(function (a, i) {
if ((typeof a === 'number' ? a : a.index) === index) {
idx = i;
return true;
}
return false;
})
return idx;
}
/** event registration */
editorImageSample.onImageUpload = imageUpload;
editorImageSample.onVideoUpload = videoUpload;
/** --- image list --- */
const editorImageSample = SUNEDITOR.create('imageManagement', {
buttonList: [
['undo', 'redo'],
['formatBlock'],
['horizontalRule', 'list', 'table'],
['image', 'video'],
['showBlocks', 'fullScreen', 'preview', 'print']
],
})
editorImageSample.onImageUpload = function (targetElement, index, state, imageInfo, remainingFilesCount) {
if (state === 'delete') {
imageList.splice(findIndex(imageList, index), 1)
} else {
if (state === 'create') {
imageList.push(imageInfo)
} else { // update }
}
if (remainingFilesCount === 0) {
setImageList(imageList)
}
}
// Upload from outside the editor
document.getElementById('files_upload').addEventListener('change', function (e) {
if (e.target.files) {
editorImageSample.insertImage(e.target.files)
e.target.value = ''
}
})
// Edit image list
function setImageList () {
let list = '';
let size = 0;
for (let i = 0, image, fixSize; i < imageList.length; i++) {
image = imageList[i];
fixSize = (image.size / 1000).toFixed(1) * 1
list += '<li id="img_' + image.index + '">' +
'<div onclick="checkImage(' + image.index + ')">' +
'<div class="image-wrapper"><img src="' + image.src + '"></div>' +
'</div>' +
'<a href="javascript:void(0)" onclick="selectImage(\'select\',' + image.index + ')" class="image-size">' + fixSize + 'KB</a>' +
'<div class="image-check"><svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"></path></svg></div>' +
'</li>';
size += fixSize;
}
imageSize.innerText = size.toFixed(1) + 'KB';
imageTable.innerHTML = list;
}
// Click the file size
function selectImage (type, index) {
imageList[findIndex(imageList, index)][type]();
}
// Image check
function checkImage (index) {
const li = imageTable.querySelector('#img_' + index);
const currentImageIdx = findIndex(selectedImages, index)
if (currentImageIdx > -1) {
selectedImages.splice(currentImageIdx, 1)
li.className = '';
} else {
selectedImages.push(index)
li.className = 'checked';
}
if (selectedImages.length > 0) {
imageRemove.removeAttribute('disabled');
} else {
imageRemove.setAttribute('disabled', true);
}
}
// Click the remove button
function deleteCheckedImages() {
const iamgesInfo = editorImageSample.getImagesInfo();
for (let i = 0; i < iamgesInfo.length; i++) {
if (selectedImages.indexOf(iamgesInfo[i].index) > -1) {
iamgesInfo[i].delete();
i--;
}
}
selectedImages = []
}
/** --- video list --- */
function videoUpload (targetElement, index, state, videoInfo, remainingFilesCount) {
console.log('videoInfo', videoInfo);
if (state === 'delete') {
videoList.splice(findIndex(videoList, index), 1)
} else {
if (state === 'create') {
videoList.push(videoInfo)
} else { // update
//
}
}
if (remainingFilesCount === 0) {
console.log('videoList', videoList)
setVideoList(videoList)
}
}
function setVideoList () {
let list = '';
for (let i = 0, video; i < videoList.length; i++) {
video = videoList[i];
list += '<li>' +
'<button title="delete" onclick="selectVideo(\'delete\',' + video.index + ')">X</button>' +
'<a href="javascript:void(0)" onclick="selectVideo(\'select\',' + video.index + ')">' + video.src + '</a>' +
'</li>';
}
videoTable.innerHTML = list;
}
function selectVideo (type, index) {
videoList[findIndex(videoList, index)][type]();
}
User Functions
import suneditor from 'suneditor'
function sun_setOptions() {
editor.setOptions({
mode: 'inline',
minHeight: '300px',
colorList: [
['#ccc', '#dedede', 'OrangeRed', 'Orange', 'RoyalBlue', 'SaddleBrown']
],
buttonList: [
['fontColor', 'hiliteColor']
]
});
}
function sun_resetOptions() {
editor.setOptions({
mode: 'classic',
minHeight: null,
colorList: null,
buttonList: [
['undo', 'redo'],
['bold', 'underline', 'italic', 'strike', 'subscript', 'superscript'],
['removeFormat'],
['outdent', 'indent'],
['fullScreen', 'showBlocks', 'codeView'],
['preview', 'print'],
['image']
],
});
}
function sun_setDefaultStyle() {
editor.setDefaultStyle('font-family: cursive; font-size: 10px;');
}
function sun_resetDefaultStyle() {
editor.setDefaultStyle('');
}
const editor = suneditor.create('example');
// Add or reset option property
editor.setOptions({
minHeight: '300px',
buttonList: [
['fontColor', 'hiliteColor']
],
colorList: [
['#ccc', '#dedede', 'OrangeRed', 'Orange', 'RoyalBlue', 'SaddleBrown']
]
});
// Open a notice area
editor.noticeOpen('test notice');
// Close a notice area
editor.noticeClose();
// Copies the contents of the suneditor into a [textarea]
editor.save();
// Gets the suneditor's context object. Contains settings, plugins, and cached element objects
editor.getContext();
// Gets the contents of the suneditor
// onlyContents {Boolean}: Return only the contents of the body without headers when the "fullPage" option is true
editor.getContents(onlyContents: Boolean);
// Gets uploaded images informations
/**
* {
* index: data index
* name: file name
* size: file size
* select: select function
* delete: delete function
* element: image element
* src: imgage src
* }
**/
editor.getImagesInfo();
// Gets uploaded videos informations
/**
* {
* index: data index
* select: select function
* delete: delete function
* src: iframe src
* element: iframe element
* }
**/
editor.getVideosInfo();
// Upload images using image plugin
// document.getElementById('example_files_input').files
editor.insertImage(FileList);
// Inserts an HTML element or HTML string or plain string at the current cursor position
editor.insertHTML('<img src="http://suneditor.com/sample/img/sunset.jpg">');
// Change the contents of the suneditor
editor.setContents('set contents');
// Add content to the suneditor
editor.appendContents('append contents');
// Disable the suneditor
editor.disabled();
// Enabled the suneditor
editor.enabled();
// Hide the suneditor
editor.hide();
// Show the suneditor
editor.show();
// Destroy the suneditor
editor.destroy();
// Toolbar methods
// Disable the suneditor
editor.toolbar.disabled();
// Enabled the suneditor
editor.toolbar.enabled();
// Hide the suneditor
editor.toolbar.hide();
// Show the suneditor
editor.toolbar.show();
// Event functions -------------------------------------------------------------------------------------
// It can be redefined by receiving event object as parameter.
// It is not called in exceptional cases and is called after the default event function has finished.
editor.onScroll = function (e, core) { console.log('onScroll', e) }
editor.onClick = function (e, core) { console.log('onClick', e) }
editor.onMouseDown = function (e, core) { console.log('onMouseDown', e) }
editor.onInput = function (e, core) { console.log('onInput', e) }
editor.onKeyDown = function (e, core) { console.log('onKeyDown', e) }
editor.onKeyUp = function (e, core) { console.log('onKeyUp', e) }
editor.onDrop = function (e, core) { console.log('onDrop', e) }
editor.onChange = function (contents, core) { console.log('onChange', contents) }
editor.onFocus = function (e, core) { console.log('onFocus', e) }
editor.onBlur = function (e, core) { console.log('onBlur', e) }
// onload event
// When reloaded with the "setOptions" method, the value of the "reload" argument is true.
editor.onload = function (core, reload) {
console.log('onload-core', core)
console.log('onload-reload', reload)
}
// Paste event.
// Called before the editor's default event action.
// If it returns false, it stops without executing the rest of the action.
/**
* cleanData : HTML string modified for editor format
* maxCharCount : maxChartCount option (true if max character is exceeded)
*/
editor.onPaste = function (e, cleanData, maxCharCount, core) { console.log('onPaste', e, cleanData, maxCharCount) }
// Called when the image is uploaded, updated, deleted.
/**
* targetElement: Current img element
* index: Uploaded index (key value)
* state: Upload status ('create', 'update', 'delete')
* imageInfo: Image infomation (getImagesInfo)
* remainingFilesCount: Count of remaining files to upload (0 when added as a url)
*/
editor.onImageUpload = function (targetElement, index, state, imageInfo, remainingFilesCount, core) {
console.log(`targetElement:${targetElement}, index:${index}, state('create', 'update', 'delete'):${state}`)
console.log(`imageInfo:${imageInfo}, remainingFilesCount:${remainingFilesCount}`)
}
// Called when the image is upload failed.
// If you return false, the default notices are not called.
/**
* errorMessage: Error message to show
* result: Result object
*/
editor.onImageUploadError = function (errorMessage, result, core) {
alert(errorMessage)
}
// Called before the image is uploaded.
// If false is returned, no image upload is performed.
editor.onImageUploadBefore = null
// It replaces the default callback function of the image upload.
editor.imageUploadHandler = null
// Called when the videos(iframe) is uploaded, updated, deleted.
/**
* targetElement: Current iframe element
* index: Uploaded index (key value)
* state: Upload status ('create', 'update', 'delete')
* videoInfo: Video infomation (getVideosInfo)
* remainingFilesCount: Count of remaining files to upload (0 when added as a url)
*/
editor.onImageUpload = function (targetElement, index, state, videoInfo, remainingFilesCount, core) {
console.log(`targetElement:${targetElement}, index:${index}, state('create', 'update', 'delete'):${state}`)
console.log(`videoInfo:${videoInfo}, remainingFilesCount:${remainingFilesCount}`)
}
// Called just before the inline toolbar is positioned and displayed on the screen.
/**
* toolbar: Toolbar Element
* context: The editor's context object (editor.getContext()|core.context)
* core: Core object
*/
editor.showInline = function (toolbar, context, core) {
console.log('toolbar', toolbar);
console.log('context', context);
}
// Called just after the controller is positioned and displayed on the screen.
// controller - editing elements displayed on the screen [image resizing, table editor, link editor..]]
/**
* name: The name of the plugin that called the controller
* controllers: Array of Controller elements
* core: Core object
*/
editor.showController = function (name, controllers, core) {
console.log('plugin name', name);
console.log('controller elements', controllers);
}