MediaWiki:Gadget-tidy-on-save-summary.js

Definition från Wiktionary, den fria ordlistan.
Hoppa till navigering Hoppa till sök

OBS: Efter du har publicerat sidan kan du behöva tömma din webbläsares cache för att se ändringarna.

  • Firefox / Safari: Håll ned Skift och klicka på Uppdatera sidan eller tryck Ctrl-F5 eller Ctrl-R (⌘-R på Mac)
  • Google Chrome: Tryck Ctrl-Skift-R (⌘-Skift-R på Mac)
  • Internet Explorer / Edge: Håll ned Ctrl och klicka på Uppdatera eller tryck Ctrl-F5
  • Opera: Tryck Ctrl-F5.
// @ts-check

module.exports = processSummary;

/**
 * @typedef ProcessSummaryOptions
 * @property {string} summary Pre-existing summary.
 * @property {boolean} warn Whether the wikitext caused a `{{tidy}}` warning.
 * @property {string[]} cats Transformation categories.
 * @property {boolean} bot Whether the current user is a bot.
 * @property {"save" | "preview"} action The current action.
 */

/**
 * @param {ProcessSummaryOptions} opts
 * @returns {string | undefined}
 * If the summary was updated, it is returned, otherwise `undefined`.
 */
function processSummary(opts) {
  var summary = opts.summary.trim();
  var orig = summary;
  var cats = opts.cats;

  // Add a ZWNJ (zero-width non-joiner) \u200C, in order to allow users to
  // write an edit summary containing `{{tidy}}` that won't
  // automatically be removed.
  var reWarn = /{{tidy\u200C}}/;
  var reCats = /\[\[Wiktionary:Finesser\/Tidy\|Tidy]]: \u200C.+?\u200C/;

  if (reWarn.test(summary) || reCats.test(summary)) {
    // For bots, accumulate all transformation categories, rather than
    // replacing them.
    if (opts.bot) {
      var catsMatch = reCats.exec(summary);
      if (catsMatch) {
        cats = Array.from(
          new Set(cats.concat(catsMatch[0].split("\u200C")[1].split(", ")))
        );
      }
    }

    // Remove `{{tidy}}` and `Tidy: cat 1, cat 2`.
    var reSep = "[; -]*";
    summary = summary
      .split(
        new RegExp(
          reSep + "(?:" + reWarn.source + "|" + reCats.source + ")" + reSep
        )
      )
      .filter(Boolean)
      .join("; ");
  }

  var isEmpty =
    !summary ||
    // A pre-filled summary such as `/* Svenska */` is considered empty.
    /^\/\*.+?\*\/ ?$/.test(summary);

  var toAdd = [
    // Add `{{tidy}}` if the template was added to the wikitext.
    opts.warn && "{{tidy\u200C}}",

    // Add `Tidy: cat 1, cat 2` if there's no other summary when saving, or if
    // we're a bot.
    cats.length &&
      ((isEmpty && opts.action === "save") || opts.bot) &&
      "[[Wiktionary:Finesser/Tidy|Tidy]]: \u200C" + cats.join(", ") + "\u200C",
  ]
    .filter(Boolean)
    .join("; ");

  // Combine previous summary with Tidy's addition. If the previous summary
  // ends with e.g. `*/` (editing a section), combine with a space instead of a
  // semicolon.
  summary = [summary, toAdd]
    .filter(Boolean)
    .join(/[/.] ?$/.test(summary) ? " " : "; ");

  return summary === orig ? undefined : summary;
}