You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
273 lines
11 KiB
JavaScript
273 lines
11 KiB
JavaScript
(function (global) {
|
|
"use strict";
|
|
|
|
var MAX_FILES = 5;
|
|
var MAX_FILE_BYTES = 5 * 1024 * 1024;
|
|
var MAX_TOTAL_BYTES = 15 * 1024 * 1024;
|
|
var IMAGE_TYPES = {
|
|
"image/jpeg": true,
|
|
"image/png": true,
|
|
"image/gif": true,
|
|
"image/webp": true
|
|
};
|
|
// The administrator ticket thread shares this uploader but does not load
|
|
// the user-copy runtime. User pages always resolve these keys from the
|
|
// published catalog; this map only preserves the administrator baseline.
|
|
var FALLBACKS = {
|
|
"tickets.upload.too_many": "最多选择 5 张图片。", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.upload.unsupported_type": "仅支持 JPG、PNG、GIF 或 WebP 图片。", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.upload.file_too_large": "每张图片不能超过 5 MB。", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.upload.total_too_large": "图片总大小不能超过 15 MB。", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.upload.remove": "移除 {name}", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.feedback.invalid_response": "服务返回了无效数据,请刷新页面核对。", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.feedback.rejected": "提交内容未被接受,请检查后重试。", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.upload.http_error": "请求失败(状态码 {status}),请稍后重试。", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.feedback.effect_unknown": "请求连接已中断,结果可能已经生效。请刷新工单核对,勿重复提交。", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.upload.cancelled": "上传已取消。", // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
"tickets.upload.timeout": "上传超时,请刷新工单核对后重试。" // user-copy: allow admin-compatibility shared-ticket-uploader
|
|
};
|
|
|
|
function copy(key, parameters) {
|
|
var runtime = global.VenixUserCopy;
|
|
var text;
|
|
if (runtime && typeof runtime.text === "function") {
|
|
return runtime.text(key, parameters || {});
|
|
}
|
|
text = FALLBACKS[key] || key;
|
|
Object.keys(parameters || {}).forEach(function (name) {
|
|
text = text.split("{" + name + "}").join(String(parameters[name]));
|
|
});
|
|
return text;
|
|
}
|
|
|
|
function list(value) {
|
|
return Array.prototype.slice.call(value || []);
|
|
}
|
|
|
|
function bytes(size) {
|
|
if (size < 1024) return size + " B";
|
|
if (size < 1024 * 1024) return (size / 1024).toFixed(1) + " KiB";
|
|
return (size / (1024 * 1024)).toFixed(1) + " MiB";
|
|
}
|
|
|
|
function key(file) {
|
|
return [file.name, file.size, file.type, file.lastModified || 0].join("\u0000");
|
|
}
|
|
|
|
function validate(files) {
|
|
var total = 0;
|
|
if (files.length > MAX_FILES) return copy("tickets.upload.too_many");
|
|
for (var index = 0; index < files.length; index += 1) {
|
|
if (!IMAGE_TYPES[files[index].type]) return copy("tickets.upload.unsupported_type");
|
|
if (files[index].size <= 0 || files[index].size > MAX_FILE_BYTES) return copy("tickets.upload.file_too_large");
|
|
total += files[index].size;
|
|
}
|
|
return total > MAX_TOTAL_BYTES ? copy("tickets.upload.total_too_large") : "";
|
|
}
|
|
|
|
function syncInput(input, files) {
|
|
if (!input || typeof global.DataTransfer === "undefined") return;
|
|
try {
|
|
var transfer = new global.DataTransfer();
|
|
files.forEach(function (file) { transfer.items.add(file); });
|
|
input.files = transfer.files;
|
|
} catch (error) {
|
|
/* Older WebKit exposes DataTransfer but keeps input.files read-only. */
|
|
}
|
|
}
|
|
|
|
function mount(root, options) {
|
|
options = options || {};
|
|
var input = root && root.querySelector("input[type='file'][name='attachments[]']");
|
|
var output = root && root.querySelector("[data-file-list]");
|
|
var dropzone = root && root.querySelector(".vu-support-dropzone");
|
|
var files = [];
|
|
var urls = [];
|
|
var listeners = [];
|
|
var destroyed = false;
|
|
|
|
function on(target, event, handler) {
|
|
if (!target) return;
|
|
target.addEventListener(event, handler);
|
|
listeners.push([target, event, handler]);
|
|
}
|
|
|
|
function revoke() {
|
|
if (global.URL && typeof global.URL.revokeObjectURL === "function") {
|
|
urls.forEach(function (url) { global.URL.revokeObjectURL(url); });
|
|
}
|
|
urls = [];
|
|
}
|
|
|
|
function render() {
|
|
if (!output) return;
|
|
revoke();
|
|
output.innerHTML = "";
|
|
output.hidden = files.length === 0;
|
|
files.forEach(function (file, index) {
|
|
var item = document.createElement(options.compact ? "span" : "div");
|
|
var name = document.createElement("strong");
|
|
var size = document.createElement("small");
|
|
var remove = document.createElement("button");
|
|
item.className = options.compact ? "admin-ticket-preview-item" : "vu-support-file";
|
|
name.textContent = file.name;
|
|
size.textContent = bytes(file.size);
|
|
remove.type = "button";
|
|
remove.className = options.compact ? "admin-ticket-preview-remove" : "vu-support-file-remove";
|
|
remove.setAttribute("aria-label", copy("tickets.upload.remove", { name: file.name }));
|
|
remove.innerHTML = '<i class="mdi mdi-close" aria-hidden="true"></i>';
|
|
if (!options.compact) {
|
|
var preview = document.createElement("span");
|
|
var details = document.createElement("span");
|
|
preview.className = "vu-support-file-preview";
|
|
details.className = "vu-support-file-copy";
|
|
if (IMAGE_TYPES[file.type] && global.URL && global.URL.createObjectURL) {
|
|
var image = document.createElement("img");
|
|
var url = global.URL.createObjectURL(file);
|
|
urls.push(url);
|
|
image.alt = "";
|
|
image.src = url;
|
|
preview.appendChild(image);
|
|
} else {
|
|
preview.innerHTML = '<i class="mdi mdi-file-outline" aria-hidden="true"></i>';
|
|
}
|
|
details.appendChild(name);
|
|
details.appendChild(size);
|
|
item.appendChild(preview);
|
|
item.appendChild(details);
|
|
} else {
|
|
item.appendChild(name);
|
|
item.appendChild(size);
|
|
}
|
|
item.appendChild(remove);
|
|
remove.addEventListener("click", function () {
|
|
files.splice(index, 1);
|
|
syncInput(input, files);
|
|
render();
|
|
var nextItem = output.children[Math.min(index, Math.max(0, files.length - 1))];
|
|
var nextControl = nextItem && nextItem.children[nextItem.children.length - 1];
|
|
if (nextControl && typeof nextControl.focus === "function") nextControl.focus();
|
|
else if (input && typeof input.focus === "function") input.focus();
|
|
else if (dropzone && typeof dropzone.focus === "function") dropzone.focus();
|
|
});
|
|
output.appendChild(item);
|
|
});
|
|
}
|
|
|
|
function accept(selected) {
|
|
if (destroyed) return;
|
|
var byKey = {};
|
|
files.concat(list(selected)).forEach(function (file) { byKey[key(file)] = file; });
|
|
var next = Object.keys(byKey).map(function (fileKey) { return byKey[fileKey]; });
|
|
var error = validate(next);
|
|
if (error) {
|
|
if (typeof options.onError === "function") options.onError(error);
|
|
syncInput(input, files);
|
|
return;
|
|
}
|
|
files = next;
|
|
if (typeof options.onError === "function") options.onError("");
|
|
syncInput(input, files);
|
|
render();
|
|
}
|
|
|
|
on(input, "change", function () { accept(input.files); });
|
|
["dragenter", "dragover"].forEach(function (eventName) {
|
|
on(dropzone, eventName, function (event) {
|
|
event.preventDefault();
|
|
dropzone.classList.add("is-dragover");
|
|
});
|
|
});
|
|
["dragleave", "drop"].forEach(function (eventName) {
|
|
on(dropzone, eventName, function (event) {
|
|
event.preventDefault();
|
|
dropzone.classList.remove("is-dragover");
|
|
if (eventName === "drop") accept(event.dataTransfer ? event.dataTransfer.files : []);
|
|
});
|
|
});
|
|
|
|
return {
|
|
files: function () { return files.slice(); },
|
|
clear: function () { files = []; if (input) input.value = ""; syncInput(input, files); render(); },
|
|
destroy: function () {
|
|
destroyed = true;
|
|
revoke();
|
|
listeners.forEach(function (entry) { entry[0].removeEventListener(entry[1], entry[2]); });
|
|
listeners = [];
|
|
}
|
|
};
|
|
}
|
|
|
|
function submit(request) {
|
|
var xhr = new global.XMLHttpRequest();
|
|
var body = new global.FormData();
|
|
var settled = false;
|
|
Object.keys(request.fields || {}).forEach(function (field) {
|
|
body.append(field, request.fields[field] == null ? "" : String(request.fields[field]));
|
|
});
|
|
(request.files || []).forEach(function (file) { body.append("attachments[]", file, file.name); });
|
|
var promise = new Promise(function (resolve, reject) {
|
|
function fail(kind, copyKey, parameters, mayHaveApplied) {
|
|
if (settled) return;
|
|
settled = true;
|
|
var error = new Error(copy(copyKey, parameters));
|
|
error.kind = kind;
|
|
error.copyKey = copyKey;
|
|
error.parameters = parameters || {};
|
|
error.mutationMayHaveApplied = mayHaveApplied === true;
|
|
reject(error);
|
|
}
|
|
xhr.open(request.method || "POST", request.url, true);
|
|
xhr.withCredentials = true;
|
|
xhr.timeout = request.timeout || 60000;
|
|
Object.keys(request.headers || {}).forEach(function (name) {
|
|
xhr.setRequestHeader(name, request.headers[name]);
|
|
});
|
|
if (xhr.upload) xhr.upload.addEventListener("progress", function (event) {
|
|
if (event.lengthComputable && typeof request.onProgress === "function") {
|
|
request.onProgress(Math.min(100, Math.round(event.loaded * 100 / event.total)));
|
|
}
|
|
});
|
|
xhr.addEventListener("load", function () {
|
|
if (settled) return;
|
|
var data;
|
|
try { data = xhr.responseText ? JSON.parse(xhr.responseText) : { ret: 1 }; }
|
|
catch (error) {
|
|
fail("response", "tickets.feedback.invalid_response", {}, true);
|
|
return;
|
|
}
|
|
if (xhr.status < 200 || xhr.status >= 300 || !data.ret) {
|
|
var effectUnknown = xhr.status === 408 || xhr.status >= 500;
|
|
fail(
|
|
"http",
|
|
effectUnknown
|
|
? "tickets.feedback.effect_unknown"
|
|
: !data.ret && xhr.status >= 200 && xhr.status < 300
|
|
? "tickets.feedback.rejected"
|
|
: "tickets.upload.http_error",
|
|
{ status: xhr.status },
|
|
effectUnknown
|
|
);
|
|
return;
|
|
}
|
|
settled = true;
|
|
if (typeof request.onProgress === "function") request.onProgress(100);
|
|
resolve(data);
|
|
});
|
|
xhr.addEventListener("error", function () {
|
|
fail("network", "tickets.feedback.effect_unknown", {}, true);
|
|
});
|
|
xhr.addEventListener("abort", function () {
|
|
fail("cancelled", "tickets.upload.cancelled", {}, false);
|
|
});
|
|
xhr.addEventListener("timeout", function () {
|
|
fail("timeout", "tickets.upload.timeout", {}, true);
|
|
});
|
|
xhr.send(body);
|
|
});
|
|
return { promise: promise, abort: function () { if (!settled) xhr.abort(); } };
|
|
}
|
|
|
|
global.VenixTicketUpload = { mount: mount, submit: submit, validate: validate };
|
|
})(window);
|