mirror of
https://github.com/BookStackApp/BookStack.git
synced 2025-06-07 03:14:33 +08:00
Merge pull request #4193 from BookStackApp/custom_dropzone
Custom dropzone implementation
This commit is contained in:
@ -8,15 +8,16 @@ export class Attachments extends Component {
|
||||
this.pageId = this.$opts.pageId;
|
||||
this.editContainer = this.$refs.editContainer;
|
||||
this.listContainer = this.$refs.listContainer;
|
||||
this.mainTabs = this.$refs.mainTabs;
|
||||
this.list = this.$refs.list;
|
||||
this.linksContainer = this.$refs.linksContainer;
|
||||
this.listPanel = this.$refs.listPanel;
|
||||
this.attachLinkButton = this.$refs.attachLinkButton;
|
||||
|
||||
this.setupListeners();
|
||||
}
|
||||
|
||||
setupListeners() {
|
||||
const reloadListBound = this.reloadList.bind(this);
|
||||
this.container.addEventListener('dropzone-success', reloadListBound);
|
||||
this.container.addEventListener('dropzone-upload-success', reloadListBound);
|
||||
this.container.addEventListener('ajax-form-success', reloadListBound);
|
||||
|
||||
this.container.addEventListener('sortable-list-sort', event => {
|
||||
@ -39,16 +40,29 @@ export class Attachments extends Component {
|
||||
markdown: contentTypes['text/plain'],
|
||||
});
|
||||
});
|
||||
|
||||
this.attachLinkButton.addEventListener('click', () => {
|
||||
this.showSection('links');
|
||||
});
|
||||
}
|
||||
|
||||
showSection(section) {
|
||||
const sectionMap = {
|
||||
links: this.linksContainer,
|
||||
edit: this.editContainer,
|
||||
list: this.listContainer,
|
||||
};
|
||||
|
||||
for (const [name, elem] of Object.entries(sectionMap)) {
|
||||
elem.toggleAttribute('hidden', name !== section);
|
||||
}
|
||||
}
|
||||
|
||||
reloadList() {
|
||||
this.stopEdit();
|
||||
/** @var {Tabs} */
|
||||
const tabs = window.$components.firstOnElement(this.mainTabs, 'tabs');
|
||||
tabs.show('attachment-panel-items');
|
||||
window.$http.get(`/attachments/get/page/${this.pageId}`).then(resp => {
|
||||
this.list.innerHTML = resp.data;
|
||||
window.$components.init(this.list);
|
||||
this.listPanel.innerHTML = resp.data;
|
||||
window.$components.init(this.listPanel);
|
||||
});
|
||||
}
|
||||
|
||||
@ -59,8 +73,7 @@ export class Attachments extends Component {
|
||||
}
|
||||
|
||||
async startEdit(id) {
|
||||
this.editContainer.classList.remove('hidden');
|
||||
this.listContainer.classList.add('hidden');
|
||||
this.showSection('edit');
|
||||
|
||||
showLoading(this.editContainer);
|
||||
const resp = await window.$http.get(`/attachments/edit/${id}`);
|
||||
@ -69,8 +82,7 @@ export class Attachments extends Component {
|
||||
}
|
||||
|
||||
stopEdit() {
|
||||
this.editContainer.classList.add('hidden');
|
||||
this.listContainer.classList.remove('hidden');
|
||||
this.showSection('list');
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,74 +1,238 @@
|
||||
import DropZoneLib from 'dropzone';
|
||||
import {fadeOut} from '../services/animations';
|
||||
import {Component} from './component';
|
||||
import {Clipboard} from '../services/clipboard';
|
||||
import {
|
||||
elem, getLoading, onSelect, removeLoading,
|
||||
} from '../services/dom';
|
||||
|
||||
export class Dropzone extends Component {
|
||||
|
||||
setup() {
|
||||
this.container = this.$el;
|
||||
this.statusArea = this.$refs.statusArea;
|
||||
this.dropTarget = this.$refs.dropTarget;
|
||||
this.selectButtons = this.$manyRefs.selectButton || [];
|
||||
|
||||
this.isActive = true;
|
||||
|
||||
this.url = this.$opts.url;
|
||||
this.successMessage = this.$opts.successMessage;
|
||||
this.removeMessage = this.$opts.removeMessage;
|
||||
this.uploadLimit = Number(this.$opts.uploadLimit);
|
||||
this.errorMessage = this.$opts.errorMessage;
|
||||
this.uploadLimitMb = Number(this.$opts.uploadLimit);
|
||||
this.uploadLimitMessage = this.$opts.uploadLimitMessage;
|
||||
this.timeoutMessage = this.$opts.timeoutMessage;
|
||||
this.zoneText = this.$opts.zoneText;
|
||||
this.fileAcceptTypes = this.$opts.fileAccept;
|
||||
|
||||
this.setupListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Public method to allow external disabling/enabling of this drag+drop dropzone.
|
||||
* @param {Boolean} active
|
||||
*/
|
||||
toggleActive(active) {
|
||||
this.isActive = active;
|
||||
}
|
||||
|
||||
setupListeners() {
|
||||
onSelect(this.selectButtons, this.manualSelectHandler.bind(this));
|
||||
this.setupDropTargetHandlers();
|
||||
}
|
||||
|
||||
setupDropTargetHandlers() {
|
||||
let depth = 0;
|
||||
|
||||
const reset = () => {
|
||||
this.hideOverlay();
|
||||
depth = 0;
|
||||
};
|
||||
|
||||
this.dropTarget.addEventListener('dragenter', event => {
|
||||
event.preventDefault();
|
||||
depth += 1;
|
||||
|
||||
if (depth === 1 && this.isActive) {
|
||||
this.showOverlay();
|
||||
}
|
||||
});
|
||||
|
||||
this.dropTarget.addEventListener('dragover', event => {
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
this.dropTarget.addEventListener('dragend', reset);
|
||||
this.dropTarget.addEventListener('dragleave', () => {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
reset();
|
||||
}
|
||||
});
|
||||
this.dropTarget.addEventListener('drop', event => {
|
||||
event.preventDefault();
|
||||
reset();
|
||||
|
||||
if (!this.isActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
const clipboard = new Clipboard(event.dataTransfer);
|
||||
const files = clipboard.getFiles();
|
||||
for (const file of files) {
|
||||
this.createUploadFromFile(file);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
manualSelectHandler() {
|
||||
const input = elem('input', {type: 'file', style: 'left: -400px; visibility: hidden; position: fixed;', accept: this.fileAcceptTypes});
|
||||
this.container.append(input);
|
||||
input.click();
|
||||
input.addEventListener('change', () => {
|
||||
for (const file of input.files) {
|
||||
this.createUploadFromFile(file);
|
||||
}
|
||||
input.remove();
|
||||
});
|
||||
}
|
||||
|
||||
showOverlay() {
|
||||
const overlay = this.dropTarget.querySelector('.dropzone-overlay');
|
||||
if (!overlay) {
|
||||
const zoneElem = elem('div', {class: 'dropzone-overlay'}, [this.zoneText]);
|
||||
this.dropTarget.append(zoneElem);
|
||||
}
|
||||
}
|
||||
|
||||
hideOverlay() {
|
||||
const overlay = this.dropTarget.querySelector('.dropzone-overlay');
|
||||
if (overlay) {
|
||||
overlay.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {File} file
|
||||
* @return {Upload}
|
||||
*/
|
||||
createUploadFromFile(file) {
|
||||
const {
|
||||
dom, status, progress, dismiss,
|
||||
} = this.createDomForFile(file);
|
||||
this.statusArea.append(dom);
|
||||
const component = this;
|
||||
this.dz = new DropZoneLib(this.container, {
|
||||
addRemoveLinks: true,
|
||||
dictRemoveFile: this.removeMessage,
|
||||
timeout: Number(window.uploadTimeout) || 60000,
|
||||
maxFilesize: this.uploadLimit,
|
||||
url: this.url,
|
||||
withCredentials: true,
|
||||
init() {
|
||||
this.dz = this;
|
||||
this.dz.on('sending', component.onSending.bind(component));
|
||||
this.dz.on('success', component.onSuccess.bind(component));
|
||||
this.dz.on('error', component.onError.bind(component));
|
||||
|
||||
const upload = {
|
||||
file,
|
||||
dom,
|
||||
updateProgress(percentComplete) {
|
||||
progress.textContent = `${percentComplete}%`;
|
||||
progress.style.width = `${percentComplete}%`;
|
||||
},
|
||||
markError(message) {
|
||||
status.setAttribute('data-status', 'error');
|
||||
status.textContent = message;
|
||||
removeLoading(dom);
|
||||
this.updateProgress(100);
|
||||
},
|
||||
markSuccess(message) {
|
||||
status.setAttribute('data-status', 'success');
|
||||
status.textContent = message;
|
||||
removeLoading(dom);
|
||||
setTimeout(dismiss, 2400);
|
||||
component.$emit('upload-success', {
|
||||
name: file.name,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// Enforce early upload filesize limit
|
||||
if (file.size > (this.uploadLimitMb * 1000000)) {
|
||||
upload.markError(this.uploadLimitMessage);
|
||||
return upload;
|
||||
}
|
||||
|
||||
this.startXhrForUpload(upload);
|
||||
|
||||
return upload;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Upload} upload
|
||||
*/
|
||||
startXhrForUpload(upload) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', upload.file, upload.file.name);
|
||||
const component = this;
|
||||
|
||||
const req = window.$http.createXMLHttpRequest('POST', this.url, {
|
||||
error() {
|
||||
upload.markError(component.errorMessage);
|
||||
},
|
||||
readystatechange() {
|
||||
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
|
||||
upload.markSuccess(component.successMessage);
|
||||
} else if (this.readyState === XMLHttpRequest.DONE && this.status >= 400) {
|
||||
const content = this.responseText;
|
||||
const data = content.startsWith('{') ? JSON.parse(content) : {message: content};
|
||||
const message = data?.message || data?.error || content;
|
||||
upload.markError(message);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
onSending(file, xhr, data) {
|
||||
const token = window.document.querySelector('meta[name=token]').getAttribute('content');
|
||||
data.append('_token', token);
|
||||
|
||||
xhr.ontimeout = () => {
|
||||
this.dz.emit('complete', file);
|
||||
this.dz.emit('error', file, this.timeoutMessage);
|
||||
};
|
||||
}
|
||||
|
||||
onSuccess(file, data) {
|
||||
this.$emit('success', {file, data});
|
||||
|
||||
if (this.successMessage) {
|
||||
window.$events.emit('success', this.successMessage);
|
||||
}
|
||||
|
||||
fadeOut(file.previewElement, 800, () => {
|
||||
this.dz.removeFile(file);
|
||||
req.upload.addEventListener('progress', evt => {
|
||||
const percent = Math.min(Math.ceil((evt.loaded / evt.total) * 100), 100);
|
||||
upload.updateProgress(percent);
|
||||
});
|
||||
|
||||
req.setRequestHeader('Accept', 'application/json');
|
||||
req.send(formData);
|
||||
}
|
||||
|
||||
onError(file, errorMessage, xhr) {
|
||||
this.$emit('error', {file, errorMessage, xhr});
|
||||
/**
|
||||
* @param {File} file
|
||||
* @return {{image: Element, dom: Element, progress: Element, status: Element, dismiss: function}}
|
||||
*/
|
||||
createDomForFile(file) {
|
||||
const image = elem('img', {src: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M9.224 7.373a.924.924 0 0 0-.92.925l-.006 7.404c0 .509.412.925.921.925h5.557a.928.928 0 0 0 .926-.925v-5.553l-2.777-2.776Zm3.239 3.239V8.067l2.545 2.545z' style='fill:%23000;fill-opacity:.75'/%3E%3C/svg%3E"});
|
||||
const status = elem('div', {class: 'dropzone-file-item-status'}, []);
|
||||
const progress = elem('div', {class: 'dropzone-file-item-progress'});
|
||||
const imageWrap = elem('div', {class: 'dropzone-file-item-image-wrap'}, [image]);
|
||||
|
||||
const setMessage = message => {
|
||||
const messsageEl = file.previewElement.querySelector('[data-dz-errormessage]');
|
||||
messsageEl.textContent = message;
|
||||
const dom = elem('div', {class: 'dropzone-file-item'}, [
|
||||
imageWrap,
|
||||
elem('div', {class: 'dropzone-file-item-text-wrap'}, [
|
||||
elem('div', {class: 'dropzone-file-item-label'}, [file.name]),
|
||||
getLoading(),
|
||||
status,
|
||||
]),
|
||||
progress,
|
||||
]);
|
||||
|
||||
if (file.type.startsWith('image/')) {
|
||||
image.src = URL.createObjectURL(file);
|
||||
}
|
||||
|
||||
const dismiss = () => {
|
||||
dom.classList.add('dismiss');
|
||||
dom.addEventListener('animationend', () => {
|
||||
dom.remove();
|
||||
});
|
||||
};
|
||||
|
||||
if (xhr && xhr.status === 413) {
|
||||
setMessage(this.uploadLimitMessage);
|
||||
} else if (errorMessage.file) {
|
||||
setMessage(errorMessage.file);
|
||||
}
|
||||
}
|
||||
dom.addEventListener('click', dismiss);
|
||||
|
||||
removeAll() {
|
||||
this.dz.removeAllFiles(true);
|
||||
return {
|
||||
dom, progress, status, dismiss,
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef Upload
|
||||
* @property {File} file
|
||||
* @property {Element} dom
|
||||
* @property {function(Number)} updateProgress
|
||||
* @property {function(String)} markError
|
||||
* @property {function(String)} markSuccess
|
||||
*/
|
||||
|
@ -18,7 +18,10 @@ export class ImageManager extends Component {
|
||||
this.listContainer = this.$refs.listContainer;
|
||||
this.filterTabs = this.$manyRefs.filterTabs;
|
||||
this.selectButton = this.$refs.selectButton;
|
||||
this.uploadButton = this.$refs.uploadButton;
|
||||
this.uploadHint = this.$refs.uploadHint;
|
||||
this.formContainer = this.$refs.formContainer;
|
||||
this.formContainerPlaceholder = this.$refs.formContainerPlaceholder;
|
||||
this.dropzoneContainer = this.$refs.dropzoneContainer;
|
||||
|
||||
// Instance data
|
||||
@ -54,18 +57,14 @@ export class ImageManager extends Component {
|
||||
this.resetListView();
|
||||
this.resetSearchView();
|
||||
this.loadGallery();
|
||||
this.cancelSearch.classList.remove('active');
|
||||
});
|
||||
|
||||
this.searchInput.addEventListener('input', () => {
|
||||
this.cancelSearch.classList.toggle('active', this.searchInput.value.trim());
|
||||
});
|
||||
|
||||
onChildEvent(this.listContainer, '.load-more', 'click', async event => {
|
||||
showLoading(event.target);
|
||||
onChildEvent(this.listContainer, '.load-more button', 'click', async event => {
|
||||
const wrapper = event.target.closest('.load-more');
|
||||
showLoading(wrapper);
|
||||
this.page += 1;
|
||||
await this.loadGallery();
|
||||
event.target.remove();
|
||||
wrapper.remove();
|
||||
});
|
||||
|
||||
this.listContainer.addEventListener('event-emit-select-image', this.onImageSelectEvent.bind(this));
|
||||
@ -87,8 +86,11 @@ export class ImageManager extends Component {
|
||||
}
|
||||
});
|
||||
|
||||
this.formContainer.addEventListener('ajax-form-success', this.refreshGallery.bind(this));
|
||||
this.container.addEventListener('dropzone-success', this.refreshGallery.bind(this));
|
||||
this.formContainer.addEventListener('ajax-form-success', () => {
|
||||
this.refreshGallery();
|
||||
this.resetEditForm();
|
||||
});
|
||||
this.container.addEventListener('dropzone-upload-success', this.refreshGallery.bind(this));
|
||||
}
|
||||
|
||||
show(callback, type = 'gallery') {
|
||||
@ -97,7 +99,15 @@ export class ImageManager extends Component {
|
||||
this.callback = callback;
|
||||
this.type = type;
|
||||
this.getPopup().show();
|
||||
this.dropzoneContainer.classList.toggle('hidden', type !== 'gallery');
|
||||
|
||||
const hideUploads = type !== 'gallery';
|
||||
this.dropzoneContainer.classList.toggle('hidden', hideUploads);
|
||||
this.uploadButton.classList.toggle('hidden', hideUploads);
|
||||
this.uploadHint.classList.toggle('hidden', hideUploads);
|
||||
|
||||
/** @var {Dropzone} * */
|
||||
const dropzone = window.$components.firstOnElement(this.container, 'dropzone');
|
||||
dropzone.toggleActive(!hideUploads);
|
||||
|
||||
if (!this.hasData) {
|
||||
this.loadGallery();
|
||||
@ -163,6 +173,7 @@ export class ImageManager extends Component {
|
||||
|
||||
resetEditForm() {
|
||||
this.formContainer.innerHTML = '';
|
||||
this.formContainerPlaceholder.removeAttribute('hidden');
|
||||
}
|
||||
|
||||
resetListView() {
|
||||
@ -209,6 +220,7 @@ export class ImageManager extends Component {
|
||||
const params = requestDelete ? {delete: true} : {};
|
||||
const {data: formHtml} = await window.$http.get(`/images/edit/${imageId}`, params);
|
||||
this.formContainer.innerHTML = formHtml;
|
||||
this.formContainerPlaceholder.setAttribute('hidden', '');
|
||||
window.$components.init(this.formContainer);
|
||||
}
|
||||
|
||||
|
@ -30,7 +30,6 @@ export class Clipboard {
|
||||
*/
|
||||
getImages() {
|
||||
const {types} = this.data;
|
||||
const {files} = this.data;
|
||||
const images = [];
|
||||
|
||||
for (const type of types) {
|
||||
@ -40,15 +39,21 @@ export class Clipboard {
|
||||
}
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
if (file.type.includes('image')) {
|
||||
images.push(file);
|
||||
}
|
||||
}
|
||||
const imageFiles = this.getFiles().filter(f => f.type.includes('image'));
|
||||
images.push(...imageFiles);
|
||||
|
||||
return images;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the files included in the clipboard data.
|
||||
* @return {File[]}
|
||||
*/
|
||||
getFiles() {
|
||||
const {files} = this.data;
|
||||
return [...files];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export async function copyTextToClipboard(text) {
|
||||
|
@ -1,3 +1,29 @@
|
||||
/**
|
||||
* Create a new element with the given attrs and children.
|
||||
* Children can be a string for text nodes or other elements.
|
||||
* @param {String} tagName
|
||||
* @param {Object<String, String>} attrs
|
||||
* @param {Element[]|String[]}children
|
||||
* @return {*}
|
||||
*/
|
||||
export function elem(tagName, attrs = {}, children = []) {
|
||||
const el = document.createElement(tagName);
|
||||
|
||||
for (const [key, val] of Object.entries(attrs)) {
|
||||
el.setAttribute(key, val);
|
||||
}
|
||||
|
||||
for (const child of children) {
|
||||
if (typeof child === 'string') {
|
||||
el.append(document.createTextNode(child));
|
||||
} else {
|
||||
el.append(child);
|
||||
}
|
||||
}
|
||||
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the given callback against each element that matches the given selector.
|
||||
* @param {String} selector
|
||||
@ -108,6 +134,17 @@ export function showLoading(element) {
|
||||
element.innerHTML = '<div class="loading-container"><div></div><div></div><div></div></div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a loading element indicator element.
|
||||
* @returns {Element}
|
||||
*/
|
||||
export function getLoading() {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.classList.add('loading-container');
|
||||
wrap.innerHTML = '<div></div><div></div><div></div>';
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove any loading indicators within the given element.
|
||||
* @param {Element} element
|
||||
|
@ -45,6 +45,27 @@ export class HttpError extends Error {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {String} method
|
||||
* @param {String} url
|
||||
* @param {Object} events
|
||||
* @return {XMLHttpRequest}
|
||||
*/
|
||||
export function createXMLHttpRequest(method, url, events = {}) {
|
||||
const csrfToken = document.querySelector('meta[name=token]').getAttribute('content');
|
||||
const req = new XMLHttpRequest();
|
||||
|
||||
for (const [eventName, callback] of Object.entries(events)) {
|
||||
req.addEventListener(eventName, callback.bind(req));
|
||||
}
|
||||
|
||||
req.open(method, url);
|
||||
req.withCredentials = true;
|
||||
req.setRequestHeader('X-CSRF-TOKEN', csrfToken);
|
||||
|
||||
return req;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new HTTP request, setting the required CSRF information
|
||||
* to communicate with the back-end. Parses & formats the response.
|
||||
|
Reference in New Issue
Block a user