User:Beao/svgeditor.js
Jump to navigation
Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
Documentation for this user script can be added at User:Beao/svgeditor. |
(function ($, mw) {
const config = mw.config.get(["wgNamespaceNumber", "wgTitle", "wgPageName"]);
// Only File: namespace pages and SVG files
if (config.wgNamespaceNumber !== 6 || !/\.svg$/i.test(config.wgPageName)) {
return;
}
$.when(
mw.loader.using(["mediawiki.util", "ext.codeEditor.ace"]),
$.ready
).then(function () {
$(window)
.on("hashchange", function () {
if (location.hash === "#svgeditor") {
$("#bodyContent").hide();
$("#bodyContent").after(`
<form id="svgeditor" method="post">
<div style="display: flex; gap: 10px; height: 100vh;">
<div style="flex: 1;">
<div id="svgeditor_source" style="width: 100%; height: 100%;"></div>
</div>
<div style="flex: 1;">
<div id="svgeditor_svg"></div>
</div>
</div>
<input type="submit" value="Save">
</form>
`);
const editor = ace.edit("svgeditor_source");
const svgUrl = "/wiki/Special:Redirect/file/" + config.wgPageName;
fetch(svgUrl)
.then((res) => res.text())
.then((data) => {
editor.setValue(data, -1);
});
editor.session.on("change", function () {
const svg = editor.getValue();
const svgBlob = new Blob([svg], { type: "image/svg+xml" });
const svgUrl = URL.createObjectURL(svgBlob);
$("#svgeditor_svg").html(
`<img style="max-width: 100%;" src="${svgUrl}">`
);
});
$("#svgeditor").on("submit", function (e) {
console.log("svgeditor.js: Submitting SVG Editor data");
e.preventDefault();
$("#svgeditor").find("input[type=submit]").prop("disabled", true);
const svg = editor.getValue();
const svgBlob = new Blob([svg], { type: "image/svg+xml" });
const svgFile = new File([svgBlob], config.wgPageName, {type: "image/svg+xml"});
const api = new mw.Api();
api.upload(svgFile, {
filename: config.wgPageName.replace(/^File:/, ""),
comment: "SVG Editor",
ignorewarnings: true,
}).then(function (data) {
console.log("svgeditor.js: SVG Editor data submitted");
console.log(data);
location.href = "/wiki/" + config.wgPageName;
}).catch(function (error) {
console.log("svgeditor.js: SVG Editor data submitted");
console.log(error);
location.href = "/wiki/" + config.wgPageName;
});
});
}
})
.trigger("hashchange");
// Add SVG Editor tab
mw.util.addPortletLink(
"p-cactions",
"#svgeditor",
"SVG Editor",
"t-svgeditor",
"SVG Editor",
"",
"#ca-history"
);
});
})(jQuery, mw);