User:מקף/wikilambda editsource.js

From Wikifunctions

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/*
Welcome to the wikilambda source editor 🔌λ
This script will allow you to edit the source of pages whose content model is a WikiLambda object.

Just jump into [[Special:mypage/common.js]] and add the following line:
mw.loader.load( '//www.wikifunctions.org/w/index.php?title=User:מקף/wikilambda_editsource.js&action=raw&ctype=text/javascript' ); // [[:f:User:מקף/wikilambda_editsource.js]]

Hope this will serve you and be very helpful,
~ user:מקף, (user:Hyphen)
*/

script_page = ":f:User:מקף/wikilambda_editsource.js";
em = "λ🔌";
defaultSummary = `${em}\tedited in source view`;
var zid = window.location.href.match(/\/(Z\d+)\b/)?.[1];

$.when(
	mw.loader.using(["mediawiki.util"], $.ready).then(function () {
		function getJson(zid, oldJsonCB) {
			fetch(`https://www.wikifunctions.org/wiki/${zid}?action=raw`)
				.then((response) => {
					return response.text();
				})
				.then((data) => oldJsonCB(data));
		}

		function save(zid, newJson, summary) {
			summary = summary ? `${summary}` : defaultSummary;
			summary += `\t ~ [[${script_page}|#wikilambda_editsource v0]]`;

			return new Promise((resolve, reject) => {
				var api = new mw.Api();
				api
					.post({
						action: "wikilambda_edit",
						format: "json",
						summary: summary,
						zid: zid,
						zobject: newJson,
						token: mw.user.tokens.get("csrfToken"),
					})
					.then((response) => {
						getJson(zid, function (curJson) {
							const saveSuccessful = curJson === newJson;
							resolve(saveSuccessful);
						});
					})
					.catch((error) => {
						reject(error);
					});
			});
		}

		function editIt(zid, content) {
			var editor = $(
				'<div class="ext-wikilambda-widget-base" id="wikilambda_editsource" style="background-color: ghostwhite; max-width: none;"></div>'
			);
			var title = $(`<div></div>`)
				.addClass("ext-wikilambda-widget-base-header-title")
				.append(
					$(`<a href="${mw.util.getUrl(script_page)}"></a>`).text(`${em}:\t`)
				)
				.append(
					$('<strong style="direction:lrt">').text(
						`\tWikilambda Source Editing of ${zid}`
					)
				);

			var textarea = $("<textarea></textarea>")
				.css({
					width: "100%",
					height: "350px",
					"min-height": "200px",
					resize: "vertical",
					direction: "ltr",
					clear: "both",
				})
				.val(content);

			var userSummary = $("<input>")
				.attr({ type: "text", placeholder: " Summary..." })
				.css({
					width: "75%",
					resize: "horizontal",
					height: "30px",
					clear: "both",
				});

			var buttonSave = $("<button>Save</button>")
				.addClass(
					"cdx-button cdx-button--action-progressive cdx-button--weight-primary cdx-button--size-medium cdx-button--framed ext-wikilambda-publish-widget__publish-button"
				)
				.css({
					float: "inline-end",
					margin: "0",
				})
				.on("click", function () {
					if (!textarea.val()) {
						mw.notify(
							$("<strong>").text(
								`${em}:\t Please fill the source before saving.`
							)
						);
						return;
					}
					if (textarea.val() === content) {
						mw.notify(
							$("<strong>").text(
								`${em}:\t No changes detected, nothing new to save.`
							)
						);
						return;
					}
					save(zid, textarea.val(), userSummary.val())
						.then((success) => {
							editor.remove();
							mw.notify(
								$("<a>")
									.append(
										$("<strong>").text(`${em}:\t🔃 Click to see the changes`)
									)
									.on("click", function () {
										window.location.assign(
											window.location.href.replace(
												/#wikilambda_editsource$/,
												""
											)
										);
									})
							);
						})
						.catch((error) => {
							console.error("Error occurred during save:", error);
							mw.notify(
								$("<strong>").text(
									`${em}:\t An error occurred during save. Please check the JSON format or try again.`
								)
							);
						});
				});

			var buttonClose = $("<button>Close</button>")
				.addClass(
					"cdx-button cdx-button--action-default cdx-button--weight-primary cdx-button--size-medium cdx-button--framed ext-wikilambda-publish-widget__cancel-button"
				)
				.css({
					float: "inline-end",
					margin: "0",
				})

				.on("click", function () {
					editor.remove();
					mw.notify($("<strong>").text(`${em}:\t Closed`));
				});

			editor.append(title, textarea, userSummary, buttonSave, buttonClose);
			$("#bodyContent").prepend(editor);
		}

		function wikilambda_editsource() {
			$("#wikilambda_editsource").remove();
			if (zid) {
				getJson(zid, function (oldJson) {
					editIt(zid, oldJson);
				});
			}
		}
		if (
			mw.config.wgPageContentModel === "wikilambda" ||
			mw.config.wgPageContentModel === "Wikibase Item" ||
			zid
		) {
			var node = mw.util.addPortletLink(
				"p-views",
				"#wikilambda_editsource",
				`${em}`,
				"" /* 'id'*/,
				"Edit Zobject as Json",
				"r" /*, 'nextnode'*/
			);
			$(node).on("click", function () {
				wikilambda_editsource();
			});
		}
	})
);