跳转到内容

User:David Xuang/scripts/mos-dates.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
/**
 * MOS dates — CS1模板日期格式工具
 * 2010-2022 [[:en:User:Ohconfucius/script/MOSNUM_dates.js]]
 * 2016-2023 [[User:Vozhuo/Tool/MOSNUM_dates.js]]
 *
 * [[Special:MyPage/common.js]]加入:
 * importScript('User:David Xuang/scripts/mos-dates.js')
 */
(function () {
  'use strict';

  // adapted from [[:en:User:Ohconfucius/script/MOSNUM_utils.js]]
  const EnglishDateTokens = Object.freeze({
    month:
      '(?:January|February|March|April|May|June|July|August|September|October|November|December|Jan\\.|Jan|Feb\\.|Feb|Mar\\.|Mar|Apr\\.|Apr|May|Jun\\.|Jun|Jul\\.|Jul|Aug\\.|Aug|Sep\\.|Sept\\.|Sept|Sep|Oct\\.|Oct|Nov\\.|Nov|Dec\\.|Dec)',
    shortMonths: Object.freeze(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']),
  });

  const englishDMY = new RegExp(
    String.raw`^(?:(\d{1,2})(?:st|nd|rd|th)?\s+)?(${EnglishDateTokens.month}),?\s+(\d{4})$`,
    'i',
  );
  const englishMDY = new RegExp(
    String.raw`^(${EnglishDateTokens.month})\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})$`,
    'i',
  );

  function iso(year, month, day) {
    year = Number(year);
    month = Number(month);
    if (year < 1 || year > 9999 || month < 1 || month > 12) return null;
    const yearMonth = `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}`;
    if (day === undefined) return yearMonth;
    day = Number(day);
    const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (day < 1 || day > days[month - 1]) {
      return null;
    }
    return `${yearMonth}-${String(day).padStart(2, '0')}`;
  }

  // Returns a normalized string, null for an invalid/unmatched value, or NaN
  // for a valid year-last numeric date whose order is unresolved in default mode.
  function parseDate(value, operation) {
    let m;
    if (operation === 'en') {
      const monthNumber = (s) =>
        EnglishDateTokens.shortMonths.findIndex((name) => name.toLowerCase() === s.slice(0, 3).toLowerCase()) + 1;
      m = value.match(englishDMY);
      if (m) return iso(m[3], monthNumber(m[2]), m[1]);
      m = value.match(englishMDY);
      return m ? iso(m[3], monthNumber(m[1]), m[2]) : null;
    }
    if (operation === 'zh') {
      m = value.match(/^(\d{4})\s*年\s*(\d{1,2})\s*月(?:\s*(\d{1,2})\s*日)?$/);
      return m ? iso(m[1], m[2], m[3]) : null;
    }
    // Normalize forms with an explicit year position before considering the
    // selected day/month order. Preserve the precision of year-month values.
    m = value.match(/^(\d{4})([-/.])(\d{1,2})\2(\d{1,2})$/);
    if (m) return iso(m[1], m[3], m[4]);
    m = value.match(/^(\d{4})[-/.](\d{1,2})$/);
    if (m) return iso(m[1], m[2]);
    m = value.match(/^(\d{1,2})[-/.](\d{4})$/);
    if (m) return iso(m[2], m[1]);
    m = value.match(/^(\d{1,2})([-/.])(\d{1,2})\2(\d{4})$/);
    if (!m) return null;
    if (operation === 'dmy') return iso(m[4], m[3], m[1]);
    if (operation === 'mdy') return iso(m[4], m[1], m[3]);
    const dmy = iso(m[4], m[3], m[1]);
    const mdy = iso(m[4], m[1], m[3]);
    return dmy && mdy && dmy !== mdy ? NaN : null;
  }

  // A small boundary scanner, not a complete MediaWiki parser. Record only direct
  // template parameters. Comments, literal/code tags, links and {{{arguments}}}
  // shield their pipes. Unclosed constructs are left untouched.
  function templates(text) {
    const tokens =
      /<!--[\s\S]*?(?:-->|$)|<(nowiki|pre|source|syntaxhighlight|math|code|timeline|templatedata|score|gallery)\b[^>]*\/\s*>|<(nowiki|pre|source|syntaxhighlight|math|code|timeline|templatedata|score|gallery)\b[^>]*>[\s\S]*?(?:<\/\2\s*>|$)|<[^>]*>|\{\{\{|\{\{|\}\}\}|\}\}|\[\[|\]\]|\[(?=(?:[a-z][a-z\d+.-]*:|\/\/))|\]|\|/gi;
    const stack = [];
    const found = [];
    let match;
    while ((match = tokens.exec(text))) {
      const token = match[0];
      const top = stack[stack.length - 1];
      if (token[0] === '<') continue;
      if (top && (top.type === '[[' || top.type === '[')) {
        if ((top.type === '[[' && token === ']]') || (top.type === '[' && token === ']')) {
          stack.pop();
        }
        continue;
      }
      // A single bracket opens an external link only before a URL. Literal
      // text such as "[Deluxe Edition)" must not shield the rest of the page.
      if (token === '{{' || token === '{{{' || token === '[[' || token === '[') {
        stack.push({
          type: token,
          start: match.index,
          pipes: [],
          children: [],
        });
      } else if (token === '|' && top && top.type === '{{') {
        top.pipes.push(match.index);
      } else if (top && ((top.type === '{{' && token.startsWith('}}')) || (top.type === '{{{' && token === '}}}'))) {
        // A run of three braces can close a template and then start the
        // close of its parent; let the tokenizer revisit the extra brace.
        const width = top.type === '{{' ? 2 : 3;
        tokens.lastIndex = match.index + width;
        stack.pop();
        top.end = match.index;
        const nodes = top.children.concat(top.type === '{{' ? [top] : []);
        if (stack.length) stack[stack.length - 1].children.push(...nodes);
        else found.push(...nodes);
      }
    }
    return found;
  }

  // Deliberately explicit: infobox dates and unrelated language= parameters are
  // outside this tool's scope. Add local citation aliases here when needed.
  function isCitation(name) {
    name = name
      .trim()
      .replace(/_/g, ' ')
      .replace(/\s+/g, ' ')
      .replace(/^(?:Template|模板)\s*:\s*/i, '');
    return /^(?:cite(?:\s+.+)?|citation|引用|引用网页|引用網頁|引用新闻|引用新聞|引用书籍|引用書籍|引用期刊|网页引用|網頁引用)$/i.test(
      name,
    );
  }

  function transform(text, options = {}) {
    const numeric = options.numeric || 'default';
    const language = options.language || 'none';
    if (!['none', 'default', 'dmy', 'mdy'].includes(numeric) || !['none', 'local', 'all'].includes(language)) {
      throw new Error('Invalid processing options');
    }
    const dateOperations = [];
    if (numeric !== 'none') dateOperations.push(numeric);
    if (options.english) dateOperations.push('en');
    if (options.chinese) dateOperations.push('zh');
    const languageOperation = language === 'local' ? 'language-local' : 'language';
    const changedOperations = new Set();
    const edits = [];
    let dates = 0;
    let languages = 0;
    let formats = 0;
    let ambiguous = 0;
    for (const node of templates(text)) {
      const first = node.pipes.length ? node.pipes[0] : node.end;
      if (!isCitation(text.slice(node.start + 2, first))) continue;
      const fields = node.pipes
        .map((start, index) => {
          const end = node.pipes[index + 1] === undefined ? node.end : node.pipes[index + 1];
          const raw = text.slice(start + 1, end);
          const m = raw.match(/^(\s*([^=|{}\[\]<>]+?)\s*=)(\s*)([\s\S]*?)(\s*)$/);
          return (
            m && {
              start,
              end,
              key: m[2].trim().toLowerCase(),
              value: m[4],
              valueStart: start + 1 + m[1].length + m[3].length,
            }
          );
        })
        .filter(Boolean);
      let convertedEnglish = false;
      for (const field of fields) {
        if (field.key === 'language') {
          if (
            language !== 'none' &&
            !/[{}\[\]<>]/.test(field.value) &&
            (language === 'all' || /^zh(?:-[a-z0-9]+)*$/i.test(field.value))
          ) {
            edits.push({ start: field.start, end: field.end, text: '' });
            languages++;
            changedOperations.add(languageOperation);
          }
        } else if (/^(?:(?:access-?|archive-?)?date|year)$/.test(field.key)) {
          for (const operation of dateOperations) {
            const value = parseDate(field.value, operation);
            if (value === null) continue;
            if (Number.isNaN(value)) {
              ambiguous++;
              break;
            }
            if (value !== field.value) {
              edits.push({
                start: field.valueStart,
                end: field.valueStart + field.value.length,
                text: value,
              });
              if (operation === 'en') convertedEnglish = true;
              dates++;
              changedOperations.add(operation);
            }
            break;
          }
        }
      }
      // df controls citation date rendering. Remove it only when this
      // citation's English date actually changed; keep page-wide Use ... dates.
      if (convertedEnglish) {
        for (const field of fields) {
          if (field.key === 'df' && /^[\w-]*$/.test(field.value)) {
            edits.push({ start: field.start, end: field.end, text: '' });
            formats++;
          }
        }
      }
    }
    // Nested templates can yield overlapping edits, e.g. a language value
    // containing another template. Such complex language values are skipped above.
    edits.sort((a, b) => b.start - a.start);
    let output = text;
    for (const edit of edits) output = `${output.slice(0, edit.start)}${edit.text}${output.slice(edit.end)}`;
    const operations = [...dateOperations, languageOperation].filter((operation) => changedOperations.has(operation));
    return { text: output, dates, languages, formats, changes: edits.length, operations, ambiguous };
  }

  function appendSummary(existing, addition) {
    existing = existing || '';
    if (existing.includes(addition)) return existing;
    return `${existing}${existing && !/\s$/.test(existing) ? ' ' : ''}${addition}`;
  }

  // CommonJS only for the local regression tests
  if (typeof module === 'object' && module.exports) {
    module.exports = { transform, parseDate, appendSummary };
    return;
  }
  if (window.isoDatesLoaded) return;
  window.isoDatesLoaded = true;

  mw.loader
    .using([
      'mediawiki.util',
      'oojs-ui-core',
      'oojs-ui-widgets',
      'oojs-ui-windows',
      'ext.gadget.HanAssist',
      'ext.gadget.EditorAPIs',
    ])
    .then(function (require) {
      const { conv } = require('ext.gadget.HanAssist');
      const t = (hans, hant) => conv({ hans, hant: hant || hans });
      const title = t('CS1模板日期格式');
      const summaries = {
        en: t('英文日期转为ISO格式', '英文日期轉為ISO格式'),
        zh: t('中文日期转为ISO格式', '中文日期轉為ISO格式'),
        default: t('部分数字日期转为ISO格式', '部分數字日期轉為ISO格式'),
        dmy: t('DMY数字日期转为ISO格式', 'DMY數字日期轉為ISO格式'),
        mdy: t('MDY数字日期转为ISO格式', 'MDY數字日期轉為ISO格式'),
        language: t('删除language参数', '刪除language參數'),
        'language-local': t('删除本地语言代码language参数', '刪除本地語言代碼language參數'),
      };
      let epoch = 0;
      let windowManager;
      let dialog;
      let opening = false;
      function supported(editor) {
        return (
          editor &&
          !editor.readonly &&
          !['none', 'codeeditor'].includes(editor.mode) &&
          mw.config.get('wgPageContentModel') === 'wikitext'
        );
      }
      const editFirst = t(
        '请先打开维基代码或可视化编辑器,再使用本工具。',
        '請先開啟維基代碼或視覺化編輯器,再使用本工具。',
      );

      function DatesDialog(config) {
        DatesDialog.super.call(this, config);
        this.busy = false;
        this.finished = false;
      }
      OO.inheritClass(DatesDialog, OO.ui.ProcessDialog);
      DatesDialog.static.name = 'mosDatesDialog';
      DatesDialog.static.title = title;
      DatesDialog.static.actions = [
        { action: 'execute', label: t('执行', '執行'), flags: ['primary', 'progressive'], modes: 'setup' },
        { action: 'cancel', label: '取消', flags: 'safe', modes: 'setup' },
        {
          action: 'processing',
          label: t('处理中', '處理中'),
          flags: 'primary',
          disabled: true,
          modes: 'processing',
        },
        { action: 'finish', label: t('完成'), flags: ['primary', 'progressive'], modes: 'result' },
      ];

      DatesDialog.prototype.initialize = function () {
        DatesDialog.super.prototype.initialize.apply(this, arguments);
        this.content = new OO.ui.PanelLayout({ padded: true, expanded: false });
        this.result = new OO.ui.MessageWidget({ type: 'notice', classes: ['mos-dates-result'] });
        this.result.toggle(false);
        this.english = new OO.ui.CheckboxInputWidget({ selected: true });
        this.chinese = new OO.ui.CheckboxInputWidget({ selected: true });
        this.numeric = new OO.ui.RadioSelectInputWidget({
          value: 'default',
          options: [
            { data: 'none', label: t('不转换', '不轉換') },
            { data: 'default', label: t('仅确定性转换', '僅確定性轉換') },
            { data: 'dmy', label: t('从日月年格式(DMY)转换', '從日月年格式(DMY)轉換') },
            { data: 'mdy', label: t('从月日年格式(MDY)转换', '從月日年格式(MDY)轉換') },
          ],
        });
        this.language = new OO.ui.RadioSelectInputWidget({
          value: 'none',
          options: [
            { data: 'none', label: t('保留所有') },
            { data: 'local', label: t('删除本地语言代码', '刪除本地語言代碼') },
            { data: 'all', label: t('删除所有', '刪除所有') },
          ],
        });
        this.inputs = [this.english, this.chinese, this.numeric, this.language];
        const textDates = new OO.ui.FieldsetLayout({ label: t('文字日期格式') });
        textDates.addItems([
          new OO.ui.FieldLayout(this.english, { label: t('转换英文日期', '轉換英文日期'), align: 'inline' }),
          new OO.ui.FieldLayout(this.chinese, { label: t('转换中文日期', '轉換中文日期'), align: 'inline' }),
        ]);
        const numeric = new OO.ui.FieldsetLayout({ label: t('数字日期格式', '數字日期格式') });
        numeric.addItems([this.numeric]);
        const language = new OO.ui.FieldsetLayout({ label: t('语言参数处理', '語言參數處理') });
        language.addItems([this.language]);
        this.content.$element.append(
          this.result.$element, textDates.$element, numeric.$element, language.$element,
        );
        this.$body.append(this.content.$element);
      };

      DatesDialog.prototype.getSetupProcess = function (data) {
        return DatesDialog.super.prototype.getSetupProcess.call(this, data).next(() => {
          this.busy = false;
          this.finished = false;
          this.openEditor = data.editor;
          this.openMode = data.mode;
          this.openEpoch = data.epoch;
          this.result.toggle(false);
          this.inputs.forEach((input) => input.setDisabled(false));
          this.actions.setMode('setup');
        });
      };

      DatesDialog.prototype.getBodyHeight = function () {
        return this.content.$element.outerHeight(true);
      };

      DatesDialog.prototype.getActionProcess = function (action) {
        // Escape and repeated clicks must not close or rerun a pending operation.
        if (this.busy) return new OO.ui.Process();
        if (action === 'execute' && !this.finished) {
          return new OO.ui.Process(() => this.execute());
        }
        if (action === 'cancel' || action === 'finish' || action === '') {
          return new OO.ui.Process(() => {
            this.close({ action });
          });
        }
        return DatesDialog.super.prototype.getActionProcess.call(this, action);
      };

      DatesDialog.prototype.execute = async function () {
        if (this.busy || this.finished) return;
        this.busy = true;
        this.actions.setMode('processing');
        this.inputs.forEach((input) => input.setDisabled(true));
        const editor = this.openEditor;
        const mode = editor && editor.mode;
        const sameEditor = () =>
          supported(editor) &&
          window.wikitextEditor === editor &&
          editor.mode === mode &&
          mode === this.openMode &&
          epoch === this.openEpoch;
        try {
          if (!sameEditor()) throw new Error(editFirst);
          const before = await editor.syncWikiText();
          if (!sameEditor() || editor.text !== before) {
            throw new Error(
              t('编辑器或内容已改变,请关闭对话框后重试。', '編輯器或內容已改變,請關閉對話框後重試。'),
            );
          }
          const result = transform(before, {
            english: this.english.isSelected(),
            chinese: this.chinese.isSelected(),
            numeric: this.numeric.getValue(),
            language: this.language.getValue(),
          });
          if (result.text !== before) {
            editor.text = result.text;
            editor.summary = appendSummary(
              editor.summary,
              `CS1模板${result.operations.map((operation) => summaries[operation]).join('、')}([[User:David Xuang/scripts/mos-dates.js|MOS dates]])`,
            );
            await editor.syncWikiText();
            if (!sameEditor()) {
              throw new Error(
                t(
                  '同步期间编辑器已切换,请检查原编辑器中的修改。',
                  '同步期間編輯器已切換,請檢查原編輯器中的修改。',
                ),
              );
            }
          }
          const counts = [];
          if (result.dates) counts.push(t(`${result.dates}个日期`, `${result.dates}個日期`));
          if (result.languages)
            counts.push(t(`${result.languages}个language参数`, `${result.languages}個language參數`));
          if (result.formats) counts.push(t(`${result.formats}个df参数`, `${result.formats}個df參數`));
          if (result.ambiguous)
            counts.push(t(`仍有歧义的日期:${result.ambiguous}个`, `仍有歧義的日期:${result.ambiguous}個`));
          const status = counts.length
            ? `${result.changes ? '完成:' : ''}${counts.join(',')}。`
            : t('没有可更改的内容。', '沒有可更改的內容。');
          this.result.setType(result.ambiguous ? 'warning' : result.changes ? 'success' : 'notice');
          this.result.setLabel(status);
          this.result.toggle(true);
          if (mode === 'view' && result.text !== before) {
            editor.minorEdit = true;
            await editor.showDiff();
          }
        } catch (error) {
          console.error('MOS dates:', error);
          this.result.setType('error');
          this.result.setLabel(
            `${t('执行失败,请检查编辑器中的内容和摘要后重试。', '執行失敗,請檢查編輯器中的內容和摘要後重試。')}${error.message}`,
          );
          this.result.toggle(true);
        } finally {
          this.busy = false;
          this.finished = true;
          this.actions.setMode('result');
          this.updateSize();
        }
      };

      function createDialog() {
        mw.util.addCSS(`
          .mos-dates-result {
            margin-block-end: var(--spacing-100, 16px);
          }
        `);
        windowManager = new OO.ui.WindowManager();
        $(document.body).append(windowManager.$element);
        dialog = new DatesDialog({ size: 'medium' });
        windowManager.addWindows([dialog]);
      }

      async function openDialog(event) {
        event.preventDefault();
        if (
          opening ||
          (dialog && (dialog.isOpened() || dialog.isOpening() || dialog.isClosing() || dialog.busy))
        ) return;
        opening = true;
        try {
          const editor = window.wikitextEditor;
          const mode = editor && editor.mode;
          const openEpoch = epoch;
          if (!supported(editor)) {
            mw.notify(editFirst, { type: 'warn' });
            return;
          }
          if (mode === 'view') {
            // Wait for load() before exposing Execute; never overwrite a new
            // active editor if the user switches modes while the request runs.
            const text = await editor.load();
            if (!supported(editor) || window.wikitextEditor !== editor || editor.mode !== mode || epoch !== openEpoch) {
              throw new Error(t('编辑器已改变,请重新打开工具。', '編輯器已改變,請重新開啟工具。'));
            }
            if (typeof text !== 'string') {
              throw new Error(t('未能读取页面源码。', '未能讀取頁面原始碼。'));
            }
          }
          if (!dialog) createDialog();
          await windowManager.openWindow(dialog, { editor, mode, epoch: openEpoch }).opened;
        } catch (error) {
          console.error('MOS dates: opening failed', error);
          mw.notify(`${t('无法打开日期工具:', '無法開啟日期工具:')}${error.message}`, { type: 'error' });
        } finally {
          opening = false;
        }
      }
      mw.hook('editorapi.ready').add(function () {
        epoch++;
        // The hook can fire repeatedly, including after an initially unsupported mode.
        if (mw.config.get('wgPageContentModel') !== 'wikitext' || document.getElementById('ca-mos-dates')) return;
        const link = mw.util.addPortletLink('p-cactions', '#', title, 'ca-mos-dates');
        if (link) $(link).on('click', openDialog);
      });
    })
    .catch(function (error) {
      window.isoDatesLoaded = false;
      console.error('MOS dates: dependency loading failed', error);
      mw.notify('MOS dates:依赖模块加载失败,请刷新后重试。', {
        type: 'error',
      });
    });
})();