跳转到内容

MediaWiki:Gadget-EditorAPIs.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
/**
 * EditorAPIs为用户工具的开发者提供统一API接口,是各常用维基代码编辑器的统一抽象层。
 * 通过该接口,用户工具开发者可忽略用户所采用的具体编辑器,专注于编辑功能本身的开发。
 *
 * 该用户工具仅用于用户工具开发者。一般用户安装后不会产生任何效果。
 *
 * EditorAPIs provides a unified interface and abstraction layer for
 * userscript developers across various wiki editors.
 * It enables developers to build editing features with a consistent API,
 * regardless of the user's preferred editor.
 *
 * This script is for developers only and has no visible effect for non-developers.
 *
 * 文档:[[User:逆襲のあまのじゃく/tool/EditorAPIs]]
 * Documentation: [[User:逆襲のあまのじゃく/tool/EditorAPIs/en]]
 */

$(function () {
  'use strict'

  const VERSION = 20260422

  // 加载最新版
  if (window.wikitextEditor && (window.wikitextEditor._version || 0) >= VERSION) {
    return
  }

  // PART 1:基础类和工具函数
  const clampIndex = (pos, len) => Math.max(0, Math.min(len, pos))
  const clampLine = (pos, len) => Math.max(1, Math.min(len, pos))

  const clampSelection = (textLen, [currentStart, currentEnd], [start, end]) => {
    let newStart = (start !== undefined) ? start : (currentStart !== undefined && currentStart !== null ? currentStart : 0)
    let newEnd = (end !== undefined) ? end : (currentEnd !== undefined && currentEnd !== null ? currentEnd : 0)
    newStart = clampIndex(newStart, textLen)
    newEnd = clampIndex(newEnd, textLen)
    if (newStart > newEnd) {
      [newStart, newEnd] = [newEnd, newStart]
    }
    return [newStart, newEnd]
  }

  class BaseApi {
    constructor({
      textboxSelector = '#wpTextbox1',
      summarySelector = '#wpSummary',
      minorEditSelector = '#wpMinoredit',
      submitSelector = '#wpSave',
      diffSelector = '#wpDiff',
      previewSelector = '#wpPreview'
    } = {}) {
      this._textboxSelector = textboxSelector
      this._summarySelector = summarySelector
      this._minorEditSelector = minorEditSelector
      this._submitSelector = submitSelector
      this._diffSelector = diffSelector
      this._previewSelector = previewSelector
    }

    get mode() {
      return 'none'
    }

    get _version() {
      return VERSION
    }

    set text(v) {
      this._textboxSelector && $(this._textboxSelector).val(v)
    }

    get text() {
      const val = $(this._textboxSelector).val()
      if (val === undefined) {
      	return null
      }
      return val
    }

    set summary(v) {
      this._summarySelector && $(this._summarySelector).val(v)
    }

    get summary() {
      const val = $(this._summarySelector).val()
      if (val === undefined) {
      	return null
      }
      return val
    }

    set minorEdit(v) {
      this._minorEditSelector && $(this._minorEditSelector).prop('checked', !!v)
    }

    get minorEdit() {
      return !!$(this._minorEditSelector).prop('checked')
    }

    set selectionStart(pos) {
      this.setSelectionRange(pos, this.selectionEnd)
    }

    get selectionStart() {
      return this.getSelectionRange()[0]
    }

    set selectionEnd(pos) {
      this.setSelectionRange(this.selectionStart, pos)
    }

    get selectionEnd() {
      return this.getSelectionRange()[1]
    }

    set selectionText(text) {
      if (!this._textboxSelector) {
        return
      }
      const t = document.querySelector(this._textboxSelector)
      if (t) {
      	t.setRangeText(text)
      }
    }

    get selectionText() {
      if (!this._textboxSelector) {
        return ''
      }
      const textbox = document.querySelector(this._textboxSelector)
      if (textbox && textbox.value) {
      	return textbox.value.substring(textbox.selectionStart, textbox.selectionEnd)
      } else {
      	return ''
      }
    }

    get readonly() {
      return !!$(this._textboxSelector).prop('readonly')
    }

    async submit() {
      this._submitSelector && $(this._submitSelector).click()
      return !!this._submitSelector
    }

    async showPreview() {
      this._previewSelector && $(this._previewSelector).click()
      return !!this._previewSelector
    }

    async showDiff() {
      this._diffSelector && $(this._diffSelector).click()
      return !!this._diffSelector
    }

    setSelectionRange(start, end) {
      if (!this._textboxSelector) {
        return
      }
      const textbox = document.querySelector(this._textboxSelector)
      if (!textbox) {
        return
      }
      const [newStart, newEnd] = clampSelection(textbox.value.length, [textbox.selectionStart, textbox.selectionEnd], [start, end])
      textbox.selectionStart = newStart
      textbox.selectionEnd = newEnd
    }

    getSelectionRange() {
      if (!this._textboxSelector) {
        return [null, null]
      }
      const textbox = document.querySelector(this._textboxSelector)
      if (!textbox) {
        return [null, null]
      }
      return [textbox.selectionStart, textbox.selectionEnd]
    }

    get lineCount() {
      const txt = this.text || ''
      return txt.split('\n').length
    }

    getLine(n) {
      if (n < 1) {
        return null
      }
      const lines = (this.text || '').split('\n')
      const line = lines[n - 1]
      if (line === undefined) return null
      return line
    }

    indexToPos(index) {
      const text = this.text || ''
      const safeIndex = clampIndex(index, text.length)

      const lines = text.split('\n')
      let currentOffset = 0

      for (let i = 0; i < lines.length; i++) {
        const lineContent = lines[i]
        const lineLength = lineContent.length
        if (safeIndex <= currentOffset + lineLength) {
          return [i + 1, safeIndex - currentOffset]
        }
        currentOffset += lineLength + 1
      }
      let end = 0
      if (lines[lines.length - 1]) {
      	end = lines[lines.length - 1].length
      }
      return [lines.length, end]
    }

    posToIndex(line, col) {
      const text = this.text || ''
      const lines = text.split('\n')
      const totalLines = lines.length

      if (line < 1) {
        return 0
      }
      if (line > totalLines) {
        return text.length
      }

      let offset = 0
      for (let i = 0; i < line - 1; i++) {
        offset += lines[i].length + 1
      }

      const targetLineText = lines[line - 1] || ''
      // col<=0视为0;col>最后一个字符则卡在行末
      const safeCol = clampIndex(col, targetLineText.length)

      return offset + safeCol
    }

    focus() {
      if (!this._textboxSelector) {
        return
      }
      $(this._textboxSelector).focus()
    }

    async insertText(text, pos, { select = true, replace = true } = {}) {
      const currentText = this.text || ''
      const textLen = currentText.length

      let from, to
      if (Array.isArray(pos)) {
        from = clampIndex(pos[0], textLen)
        to = clampIndex(pos[1], textLen)
      } else if (typeof pos === 'number') {
        from = to = clampIndex(pos, textLen)
      } else {
        const currentSel = this.getSelectionRange()
        if (replace) {
          [from, to] = currentSel
        } else {
          from = to = currentSel[1]
        }
      }

      if (from === null || to === null) {
        return false
      }

      this.focus()
      this.setSelectionRange(from, to)
      this.selectionText = text

      const newEnd = from + text.length
      if (select) {
        this.setSelectionRange(from, newEnd)
      } else {
        this.setSelectionRange(newEnd, newEnd)
      }
      this.scrollToCursor()
      return true
    }

    scrollToLine(n) {
      if (!this._textboxSelector) {
        return
      }
      const safeLine = clampLine(n, this.lineCount)
      const textbox = document.querySelector(this._textboxSelector)
      if (!textbox) {
        return
      }

      const style = window.getComputedStyle(textbox)
      let lineHeight = parseFloat(style.lineHeight) || 20
      if (Number.isNaN(lineHeight)) {
        lineHeight = 20
      }
      textbox.scrollTop = (safeLine - 1) * lineHeight
    }

    scrollToCursor() {
      const [line] = this.indexToPos(this.selectionStart)
      this.scrollToLine(line)
    }

    async syncWikiText() {
      return this.text
    }

    async getSelectionWikitext() {
      return this.selectionText
    }
  }

  class NoneApi extends BaseApi {
    constructor() {
      super({
        textboxSelector: null,
        summarySelector: null,
        minorEditSelector: null,
        submitSelector: null,
        diffSelector: null,
        previewSelector: null
      })
    }

    get mode() {
      return 'none'
    }
  }

  // PART 2:各编辑器API的实现
  // 2.1 - 传统编辑器
  class TraditionalEditorApi extends BaseApi {
    constructor() {
      super()
    }

    get mode() {
      return 'wikitext'
    }
  }

  // 2.2 - WikEd编辑器
  class WikEdApi extends BaseApi {
    constructor() {
      super()
    }

    get mode() {
      return 'wikEd'
    }

    get text() {
      wikEd.UpdateTextarea()
      return $(this._textboxSelector).val()
    }

    set text(t) {
      $(this._textboxSelector).val(t)
      wikEd.UpdateFrame()
    }

    get selectionText() {
      var obj = {}
      wikEd.GetText(obj, 'selection, cursor')
      return obj.selection.plain || ''
    }

    set selectionText(text) {
      wikEd.EditButton(null, null, null, function (obj) {
        wikEd.GetText(obj, 'selection, cursor')
        if (obj.selection.plain !== '') {
          obj.changed = obj.selection
        } else {
          obj.changed = obj.cursor
        }
        obj.changed.plain = text
        obj.changed.keepSel = true
        return
      })
    }

    getSelectionRange() {
      let obj = {}
      obj.sel = wikEd.GetSelection()
      wikEd.ParseDOM(obj, wikEd.frameBody)
      const start = Math.min(obj.plainAnchor, obj.plainFocus)
      const end = Math.max(obj.plainAnchor, obj.plainFocus)
      return [start, end]
    }

    // 注意:由于wikEd自身的bug,当选区跨越两行以上时,range设置会静默失败
    setSelectionRange(st, en) {
      wikEd.frameWindow.focus()
      wikEd.frameBody.focus()

      let obj = {}
      obj.sel = wikEd.GetSelection()
      wikEd.ParseDOM(obj, wikEd.frameBody)

      let currentStart = Math.min(obj.plainAnchor, obj.plainFocus)
      let currentEnd = Math.max(obj.plainAnchor, obj.plainFocus)
      let [start, end] = clampSelection(obj.plainLength, [currentStart, currentEnd], [st, en])

      let i = 0
      while ((obj.plainStart[i + 1] <= start) && (obj.plainStart[i + 1] !== undefined)) {
        i++
      }
      const startNode = obj.plainNode[i]
      const startOffset = start - obj.plainStart[i]

      let j = i
      while ((obj.plainStart[j + 1] <= end) && (obj.plainStart[j + 1] !== undefined)) {
        j++
      }
      const endNode = obj.plainNode[j]
      const endOffset = end - obj.plainStart[j]

      if (startNode && endNode) {
        const range = wikEd.frameDocument.createRange()
        wikEd.SetRange(range, startNode, startOffset, endNode, endOffset)

        obj.sel.removeAllRanges()
        obj.sel.addRange(range)

        wikEd.ScrollToSelection()
      }
    }

    focus() {
      wikEd.frameWindow.focus()
    }

    async insertText(text, pos, { select = true, replace = true } = {}) {
      if (Array.isArray(pos)) {
        this.setSelectionRange(pos[0], pos[1])
      } else if (typeof pos === 'number') {
        this.setSelectionRange(pos, pos)
      } else if (!replace) {
        const [, end] = this.getSelectionRange()
        if (end !== null) {
          this.setSelectionRange(end, end)
        } else {
          return false
        }
      }

      wikEd.EditButton(null, null, null, (obj) => {
        wikEd.GetText(obj, 'selection, cursor')

        if (replace && obj.selection.plain !== '') {
          obj.changed = obj.selection
        } else {
          obj.changed = obj.cursor
        }

        obj.changed.plain = text
        obj.changed.keepSel = select // 是否保留选区
      })

      return true
    }

    scrollToLine(n) {
      const body = wikEd.frameBody
      let targetNode = null
      let lineCount = 1

      // 寻找第n行的起始节点
      const walker = wikEd.frameDocument.createTreeWalker(
        body,
        NodeFilter.SHOW_ALL,
        null,
        false
      )

      let node = body.firstChild
      if (n === 1) {
        targetNode = node || body
      } else {
        // 循环直到找到第n-1个<br>,它的下一个节点就是第n行
        while (node) {
          if (node.nodeName === 'BR') {
            lineCount++
            if (lineCount === n) {
              targetNode = node.nextSibling || node
              break
            }
          }
          node = walker.nextNode()
        }
      }

      if (targetNode) {
        // 如果节点是文本节点,或者为了更精确的定位,
        // 我们可以创建一个临时 span 插入其中
        const scrollSpan = wikEd.frameDocument.createElement('span')
        scrollSpan.className = 'wikEdScrollBefore'

        try {
          // 插入锚点
          if (targetNode.nodeName === 'BR') {
            targetNode.parentNode.insertBefore(scrollSpan, targetNode.nextSibling)
          } else {
            targetNode.parentNode.insertBefore(scrollSpan, targetNode)
          }

          wikEd.ScrollToNodes(scrollSpan, scrollSpan)

          // 清理锚点
          scrollSpan.parentNode.removeChild(scrollSpan)
        } catch (e) {
          // 如果DOM插入失败,尝试直接滚动到节点
          wikEd.ScrollToNodes(targetNode, targetNode)
        }
      }
    }

    scrollToCursor() {
      wikEd.ScrollToSelection()
    }
  }

  // 2.3 - CodeMirror 6(新版)
  class CodeMirror6Api extends BaseApi {
    constructor(cm) {
      super()
      this._cm = cm
      this._view = cm.view
    }

    get mode() {
      return 'codemirror6'
    }

    get text() {
      return this._view.state.doc.toString()
    }

    set text(t) {
      this._view.dispatch({
        changes: {
          from: 0,
          to: this._view.state.doc.length,
          insert: t
        }
      })
    }

    get selectionText() {
      return this._cm.textSelection.getSelection()
    }

    set selectionText(text) {
      this._cm.textSelection.replaceSelection(text)
    }

    setSelectionRange(start, end) {
      const [currentStart, currentEnd] = this._cm.textSelection.getCaretPosition({ startAndEnd: true })
      const [newStart, newEnd] = clampSelection(this._view.state.doc.length, [currentStart, currentEnd], [start, end])
      this._cm.textSelection.setSelection({
        start: newStart,
        end: newEnd
      })
    }

    getSelectionRange() {
      const [start, end] = this._cm.textSelection.getCaretPosition({ startAndEnd: true })
      return [start, end]
    }

    get lineCount() {
      const txt = this.text || ''
      return txt.split('\n').length
    }

    getLine(n) {
      if (n < 1) return null
      const lines = (this.text || '').split('\n')
      const line = lines[n - 1]
      if (line === undefined) {
      	return null
      }
      return line
    }

    indexToPos(index) {
      const doc = this._view.state.doc
      const safeIndex = clampIndex(index, doc.length)
      const lineObj = doc.lineAt(safeIndex)
      return [lineObj.number, safeIndex - lineObj.from]
    }

    posToIndex(line, col) {
      const doc = this._view.state.doc
      const lineCount = doc.lines

      // 边界处理
      if (line < 1) {
        return 0
      }
      if (line > lineCount) {
        return doc.length
      }

      const lineObj = doc.line(line)
      // col 越界处理:如果 col 超过行长度,则卡在行末
      const safeCol = clampIndex(col, lineObj.length)

      return lineObj.from + safeCol
    }

    focus() {
      this._view.focus()
    }

    async insertText(text, pos, { select = true, replace = true } = {}) {
      const state = this._view.state
      const mainSel = state.selection.main

      let from, to
      const textLen = state.doc.length
      if (Array.isArray(pos)) {
        from = clampIndex(pos[0], textLen)
        to = clampIndex(pos[1], textLen)
      } else if (typeof pos === 'number') {
        from = to = clampIndex(pos, textLen)
      } else {
        from = replace ? mainSel.from : mainSel.to
        to = mainSel.to
        if (from === null || to === null) {
          return false
        }
      }

      const transaction = {
        changes: { from, to, insert: text },
        scrollIntoView: true
      }

      if (select) {
        transaction.selection = { anchor: from, head: from + text.length }
      }

      this._view.dispatch(transaction)
      this._view.focus()
      return true
    }

    scrollToLine(n) {
      const doc = this._view.state.doc
      const safeLine = clampLine(n, doc.lines)
      const lineObj = doc.line(safeLine)
      const EditorView = this._view.constructor
      this._view.dispatch({
        effects: [
          EditorView.scrollIntoView(lineObj.from, { y: 'center' })
        ]
      })
    }

    scrollToCursor() {
      this._view.dispatch({ scrollIntoView: true })
    }
  }

  // 2.4 - CodeMirror 5(旧版)
  class CodeMirror5Api extends BaseApi {
    constructor() {
      super()
    }

    get mode() {
      return 'codemirror'
    }

    get text() {
      const cm = this._getInstance()
      if (!cm) {
      	return null
      }
      return cm.getValue()
    }

    set text(text) {
      const cm = this._getInstance()
      if (cm) {
      	return cm.setValue(text)
      }
    }

    get selectionText() {
      const cm = this._getInstance()
      if (!cm) {
        return ''
      }
      return cm.getSelection()
    }

    set selectionText(text) {
      const cm = this._getInstance()
      if (!cm) {
        return
      }
      cm.replaceSelection(text, 'around')
    }

    setSelectionRange(start, end) {
      const cm = this._getInstance()
      if (!cm) {
        return
      }
      const [currentStart, currentEnd] = this.getSelectionRange()
      const [newStart, newEnd] = clampSelection(
        cm.getValue().length,
        [currentStart, currentEnd],
        [start, end]
      )
      cm.setSelection(cm.posFromIndex(newStart), cm.posFromIndex(newEnd))
    }

    getSelectionRange() {
      const cm = this._getInstance()
      if (!cm) {
        return [null, null]
      }

      const from = cm.getCursor('from')
      const to = cm.getCursor('to')

      return [
        cm.indexFromPos(from),
        cm.indexFromPos(to)
      ]
    }

    focus() {
      const cm = this._getInstance()
      if (cm) {
      	cm.focus()
      }
    }

    indexToPos(index) {
      const cm = this._getInstance()
      if (!cm) {
        return [1, 0]
      }
      const safeIndex = clampIndex(index, cm.getValue().length)
      const pos = cm.posFromIndex(safeIndex)
      return [pos.line + 1, pos.ch]
    }

    posToIndex(line, col) {
      const cm = this._getInstance()
      if (!cm) {
        return 0
      }

      const safeLine = clampLine(line, cm.lineCount())
      const lineText = cm.getLine(safeLine - 1) || ''
      const safeCol = clampIndex(col, lineText.length)

      return cm.indexFromPos({ line: safeLine - 1, ch: safeCol })
    }

    async insertText(text, pos, { select = true, replace = true } = {}) {
      const cm = this._getInstance()
      if (!cm) {
        return false
      }

      let from, to
      const textLen = cm.getValue().length
      if (Array.isArray(pos)) {
        from = cm.posFromIndex(clampIndex(pos[0], textLen))
        to = cm.posFromIndex(clampIndex(pos[1], textLen))
      } else if (typeof pos === 'number') {
        from = to = cm.posFromIndex(clampIndex(pos, textLen))
      } else {
        const sel = cm.listSelections()[0]
        from = replace ? sel.from() : sel.to()
        to = sel.to()
        if (from === null || to === null) {
          return false
        }
      }

      // 执行替换
      cm.replaceRange(text, from, to)

      if (select) {
        // 计算插入后的结束位置
        const newEndIndex = cm.indexFromPos(from) + text.length
        const newEndPos = cm.posFromIndex(newEndIndex)
        cm.setSelection(from, newEndPos)
      } else {
        // 移动光标到插入内容之后
        const newEndIndex = cm.indexFromPos(from) + text.length
        const newEndPos = cm.posFromIndex(newEndIndex)
        cm.setCursor(newEndPos)
      }

      cm.focus()
      return true
    }

    scrollToLine(n) {
      const cm = this._getInstance()
      if (!cm) {
        return
      }
      const safeLine = clampLine(n, cm.lineCount())
      cm.scrollIntoView({ line: safeLine - 1, ch: 0 }, 200)
    }

    scrollToCursor() {
      const cm = this._getInstance()
      if (cm) {
      	cm.scrollIntoView(null)
      }
    }

    _getInstance() {
      const el = document.querySelector('.CodeMirror')
      return el ? el.CodeMirror : null
    }
  }

  // 2.5 - Wikiplus & InPageEdit
  class QuickEditApi extends BaseApi {
    constructor({
      textboxSelector,
      summarySelector,
      minorEditSelector,
      submitSelector,
      diffSelector,
      previewSelector,
      mode = 'none'
    } = {}) {
      super({
        textboxSelector,
        summarySelector,
        minorEditSelector,
        submitSelector,
        diffSelector,
        previewSelector
      })
      this._mode = mode

    }

    get mode() {
      return this._mode
    }

    get text() {
      const cm = this._getInstance()
      if (cm) {
        return cm.view.state.doc.toString()
      } else {
        return $(this._textboxSelector).val()
      }
    }

    set text(v) {
      const cm = this._getInstance()
      if (cm) {
        cm.view.dispatch({
          changes: {
            from: 0,
            to: cm.view.state.doc.length,
            insert: v
          }
        })
      } else {
        $(this._textboxSelector).val(v)
      }
    }

    get selectionText() {
      const cm = this._getInstance()
      if (cm) {
        const mainSel = cm.view.state.selection.main
        return cm.view.state.sliceDoc(mainSel.from, mainSel.to)
      } else {
        return super.selectionText
      }
    }

    set selectionText(text) {
      const cm = this._getInstance()
      if (cm) {
        const mainSel = cm.view.state.selection.main
        cm.view.dispatch({
          changes: {
            from: mainSel.from,
            to: mainSel.to,
            insert: text
          },
          selection: { anchor: mainSel.from, head: mainSel.from + text.length }
        })
      } else {
        super.selectionText = text
      }
    }

    setSelectionRange(start, end) {
      const cm = this._getInstance()
      if (cm) {
        const mainSel = cm.view.state.selection.main
        const [currentStart, currentEnd] = [mainSel.from, mainSel.to]
        const [newStart, newEnd] = clampSelection(cm.view.state.doc.length, [currentStart, currentEnd], [start, end])
        cm.view.dispatch({
          selection: { anchor: newStart, head: newEnd },
          scrollIntoView: true
        })
        cm.view.focus()
      } else {
        if (!this._textboxSelector) {
          return
        }
        const textbox = document.querySelector(this._textboxSelector)
        if (!textbox) {
          return
        }
        const [newStart, newEnd] = clampSelection(textbox.value.length, [textbox.selectionStart, textbox.selectionEnd], [start, end])
        textbox.selectionStart = newStart
        textbox.selectionEnd = newEnd
      }
    }

    getSelectionRange() {
      const cm = this._getInstance()
      if (cm) {
        const mainSel = cm.view.state.selection.main
        return [mainSel.from, mainSel.to]
      } else {
        return super.getSelectionRange()
      }
    }

    focus() {
      const cm = this._getInstance()
      if (cm) {
        cm.view.focus()
      } else {
        super.focus()
      }
    }

    async insertText(text, pos, { select = true, replace = true } = {}) {
      const cm = this._getInstance()
      if (cm) {
        const view = cm.view
        const state = view.state
        const mainSel = state.selection.main

        let from, to
        const textLen = state.doc.length
        if (Array.isArray(pos)) {
          from = clampIndex(pos[0], textLen)
          to = clampIndex(pos[1], textLen)
        } else if (typeof pos === 'number') {
          from = to = clampIndex(pos, textLen)
        } else {
          from = replace ? mainSel.from : mainSel.to
          to = mainSel.to
          if (from === null || to === null) {
            return false
          }
        }

        const transaction = {
          changes: { from, to, insert: text },
          scrollIntoView: true
        }

        if (select) {
          transaction.selection = { anchor: from, head: from + text.length }
        }

        view.dispatch(transaction)
        view.focus()
        return true
      } else {
        return super.insertText(text, pos, { select, replace })
      }
    }

    scrollToLine(n) {
      const cm = this._getInstance()
      if (cm) {
        const view = cm.view
        const doc = view.state.doc
        const safeLine = clampLine(n, doc.lines)
        const lineObj = doc.line(safeLine)
        const EditorView = view.constructor
        view.dispatch({
          effects: [
            EditorView.scrollIntoView(lineObj.from, { y: 'center' })
          ]
        })
      } else {
        return super.scrollToLine(n)
      }
    }

    scrollToCursor() {
      const cm = this._getInstance()
      if (cm) {
        cm.view.dispatch({ scrollIntoView: true })
      } else {
        return super.scrollToCursor()
      }
    }

    _getInstance() {
      if (!this._textboxSelector) {
        return null
      }
      const targetTextarea = document.querySelector(this._textboxSelector)
      if (targetTextarea && window.CodeMirror6 && CodeMirror6.instances) {
        return CodeMirror6.instances.get(targetTextarea)
      }
      return null
    }
  }

  // 2.7 - AceEditor
  class AceEditorApi extends BaseApi {
    constructor(session) {
      super()
      this._session = session
    }

    get mode() {
      return 'codeeditor'
    }

    get text() {
      return this._session.getValue()
    }

    set text(t) {
      this._session.setValue(t)
    }

    get selectionText() {
      const selection = this._session.getSelection()
      const doc = this._session.getDocument()
      return doc.getTextRange(selection.getRange())
    }

    set selectionText(text) {
      const selection = this._session.getSelection()
      this._session.replace(selection.getRange(), text)
    }

    setSelectionRange(start, end) {
      const AceRange = ace.require('ace/range').Range
      const doc = this._session.getDocument()
      const selection = this._session.getSelection()
      const range = selection.getRange()

      const currentStart = doc.positionToIndex(range.start)
      const currentEnd = doc.positionToIndex(range.end)

      const [newStart, newEnd] = clampSelection(
        doc.getValue().length,
        [currentStart, currentEnd],
        [start, end]
      )

      const startPos = doc.indexToPosition(newStart)
      const endPos = doc.indexToPosition(newEnd)

      selection.setSelectionRange(
        new AceRange(startPos.row, startPos.column, endPos.row, endPos.column)
      )
    }

    getSelectionRange() {
      const selection = this._session.getSelection()
      const start = selection.getRange().start
      const end = selection.getRange().end
      const doc = this._session.getDocument()
      const startPos = doc.positionToIndex(start)
      const endPos = doc.positionToIndex(end)
      return [startPos, endPos]
    }

    indexToPos(index) {
      const doc = this._session.getDocument()
      const safeIndex = clampIndex(index, doc.getValue().length)
      const pos = doc.indexToPosition(safeIndex)
      return [pos.row + 1, pos.column]
    }

    posToIndex(line, col) {
      const doc = this._session.getDocument()
      const safeRow = clampIndex(line - 1, doc.getLength() - 1)
      const lineText = doc.getLine(safeRow)
      const safeCol = clampIndex(col, lineText.length)
      return doc.positionToIndex({ row: safeRow, column: safeCol })
    }

    focus() {
      const ace = this._getEditor()
      if (ace) {
      	ace.focus()
      }
    }

    async insertText(text, pos, { select = true, replace = true } = {}) {
      const doc = this._session.getDocument()
      const Range = ace.require('ace/range').Range

      let range
      const docLen = doc.getValue().length
      if (Array.isArray(pos)) {
        const p1 = doc.indexToPosition(clampIndex(pos[0], docLen))
        const p2 = doc.indexToPosition(clampIndex(pos[1], docLen))
        range = new Range(p1.row, p1.column, p2.row, p2.column)
      } else if (typeof pos === 'number') {
        const p = doc.indexToPosition(clampIndex(pos, docLen))
        range = new Range(p.row, p.column, p.row, p.column)
      } else {
        const selRange = this._session.getSelection().getRange()
        if (replace) {
          range = selRange
        } else {
          range = new Range(selRange.end.row, selRange.end.column, selRange.end.row, selRange.end.column)
        }
      }

      this._session.replace(range, text)

      const startIdx = doc.positionToIndex(range.start)
      const endPos = doc.indexToPosition(startIdx + text.length)
      const selection = this._session.getSelection()

      if (select) {
        selection.setSelectionRange(
          new Range(range.start.row, range.start.column, endPos.row, endPos.column)
        )
      } else {
        selection.clearSelection()
        selection.moveCursorToPosition(endPos)
      }

      this.scrollToCursor()
      return true
    }

    scrollToLine(n) {
      const ace = this._getEditor()
      if (ace) {
        ace.scrollToLine(n - 1, true, true)
      }
    }

    scrollToCursor() {
      const ace = this._getEditor()
      if (ace && ace.renderer) {
        ace.renderer.scrollCursorIntoView()
      }
    }

    _getEditor() {
      const aceItem = document.querySelector('.ace_editor')
      if (aceItem && aceItem.env && aceItem.env.editor) {
      	return aceItem.env.editor
      }
      return null
    }
  }

  // 2.8 - 移动端
  class MobileFrontendApi extends BaseApi {
    constructor() {
      super({
        textboxSelector: '#wikitext-editor',
        summarySelector: '.summary textarea',
        minorEditSelector: null,
        submitSelector: '.mw-overlays-container .header-action button.submit',
        diffSelector: null,
        previewSelector: null
      })
      this._continueSelector = '.mw-overlays-container .header-action button.continue'
    }

    get mode() {
      return 'mobileFrontend'
    }

    // 旧移动端没有该按钮
    get minorEdit() {
      return false
    }

    set minorEdit(v) {
      return
    }

    get text() {
      return $(this._textboxSelector).val()
    }

    set text(t) {
      $(this._textboxSelector).val(t)
      this._triggerChange()
    }

    get summary() {
      const $summary = $(this._summarySelector)
      if ($summary && $summary[0]) {
      	return $summary[0].value
      }
      return null
    }

    set summary(v) {
      const $summary = $(this._summarySelector)
      if ($summary && $summary[0]) {
        $summary[0].value = v
      }
      this._triggerChange()
    }

    get selectionText() {
      return super.selectionText
    }

    set selectionText(t) {
      super.selectionText = t
      this._triggerChange()
    }

    async submit() {
      this._triggerChange()
      $(this._submitSelector).click()
      return true
    }

    async showPreview() {
      this._triggerChange()
      $(this._continueSelector).click()
      return true
    }

    // 移动端没有该按钮
    async showDiff() {
      return false
    }

    _triggerChange() {
      $(this._textboxSelector).trigger('input')
      $(this._summarySelector).trigger('change')
      $(this._continueSelector).removeAttr('disabled')
      $(this._submitSelector).removeAttr('disabled')
    }
  }

  // 2.9 - 模拟编辑器(view模式)
  class ViewModeApi extends BaseApi {
    constructor() {
      super({
        textboxSelector: null,
        summarySelector: null,
        minorEditSelector: null,
        submitSelector: null,
        diffSelector: null,
        previewSelector: null
      })

      this._loading = false
      this._selectionStart = 0
      this._selectionEnd = 0
      this._text = null
      this._summary = ''
      this._minorEdit = false
    }

    get mode() {
      return 'view'
    }

    get text() {
      return this._text
    }

    set text(t) {
      this._text = t
    }

    get summary() {
      return this._summary
    }

    set summary(s) {
      this._summary = s
    }

    get minorEdit() {
      return this._minorEdit
    }

    set minorEdit(v) {
      this._minorEdit = v
    }

    async submit() {
      this._submitForm('wpSave')
      return true
    }

    async showDiff() {
      this._submitForm('wpDiff')
      return true
    }

    async showPreview() {
      this._submitForm('wpPreview')
      return true
    }

    get selectionText() {
      let selStart = this._selectionStart, selEnd = this._selectionEnd
      if (selStart > selEnd) {
        [selStart, selEnd] = [selEnd, selStart]
      }
      return (this._text || '').substring(selStart, selEnd)
    }

    set selectionText(text) {
      let selStart = this._selectionStart, selEnd = this._selectionEnd
      if (selStart > selEnd) {
        [selStart, selEnd] = [selEnd, selStart]
      }
      this._text = (this._text || '').substring(0, selStart) + text + (this._text || '').substring(selEnd)
      this._selectionStart = selStart
      this._selectionEnd = selStart + text.length
    }

    setSelectionRange(start, end) {
      const textLen = (this._text || '').length
      start = clampIndex(start, textLen)
      end = clampIndex(end, textLen)
      if (start > end) {
        [start, end] = [end, start]
      }
      this._selectionStart = start
      this._selectionEnd = end
    }

    getSelectionRange() {
      return [this._selectionStart, this._selectionEnd]
    }

    get readonly() {
      return false
    }

    // 直接在頁面上提交。頁面名稱為目前頁面。
    _submitForm(action) {
      $('<form method="post" style="display:none;">')
        .attr('action', mw.util.getUrl(mw.config.get('wgPageName'), { action: 'submit' }))
        .attr('enctype', 'multipart/form-data')
        .append($('<textarea name="wpTextbox1">').val(this._text || ''),
          $('<input name="wpSummary">').val(this._summary || ''),
          '<input name="wpMinoredit" type="checkbox" value="1"' + (this._minorEdit ? ' checked="checked"' : '') + '>',
          '<input name="format" value="text/x-wiki">',
          '<input name="wpAutoSummary" value="hashhashhashhash">',    // 防止「未填寫摘要」的提示
          '<input name="model" value="wikitext">',
          '<input name="wpEditToken" value="' + mw.user.tokens.get('csrfToken') + '">',
          '<input name="wpUltimateParam" value="1">',
          '<input name="' + (action || 'wpSave') + '" type="hidden" value="1">',
          '<input name="mode" value="text">',
          '<input type="hidden" value="ℳ𝒲♥𝓊𝓃𝒾𝒸ℴ𝒹ℯ" name="wpUnicodeCheck">')
        .appendTo('body').submit()
    }

    async load() {
      this._loading = true
      let result = null

      try {
        const api = new mw.Api()
        const data = await api.get({
          action: 'query',
          prop: 'revisions',
          titles: mw.config.get('wgPageName'),
          rvprop: 'content',
          rvlimit: 1,
          formatversion: 2
        })
        
        if (data && data.query && data.query.pages && data.query.pages[0] && data.query.pages[0].revisions) {
          const content = data.query.pages[0].revisions[0].content
          this._text = content
          result = content
        } else {
          // 可能是空页面,或已删除,因此允许用户继续编辑
          this._text = ''
          result = null
        }
      } finally {
        this._loading = false
      }
      return result
    }
  }

  // 1.8 - VisualEditor与2017编辑器
  class VisualEditorApi extends BaseApi {
    constructor({
      textboxSelector = null,
      summarySelector = null,
      minorEditSelector = null,
      submitSelector = null,
      diffSelector = null,
      previewSelector = null,
      hasSaveDialog = false
    } = {}) {
      super({
        textboxSelector,
        summarySelector,
        minorEditSelector,
        submitSelector,
        diffSelector,
        previewSelector
      })
      this._pendingSummary = null
      this._pendingMinoredit = null

      this._cachedVeWikiText = null
      this._pendingVeWikiText = null
      this._syncTimer = null
      this._isSyncing = false
      this._isProgrammaticChange = false

      if (this._surface.getMode() === 'visual') {
        this.syncWikiText()
      }

      // 如果用户手工修改了编辑器,则置cachedVeWikiText为null,并等用户停笔后自动更新维基代码
      this._surfaceModel.connect(this, { 'documentUpdate': () => this._onDocumentUpdate() })

      // 监视对话框
      if (hasSaveDialog) {
        mw.hook('ve.saveDialog.stateChanged').add(() => {
          const dialog = ve.init.target.saveDialog

          if (!dialog) {
            return
          }
          if (this._pendingSummary !== null) {
            dialog.setEditSummary(this._pendingSummary || '')
            this._pendingSummary = null
          }
          if (this._pendingMinoredit !== null) {
            dialog.checkboxesByName.wpMinoredit.setSelected(!!this._pendingMinoredit)
            this._pendingMinoredit = null
          }
        })
      }
    }

    get mode() {
      if (this._surface.getMode() === 'visual') {
        return 'visual'
      } else {
        return 'wikitext2017'
      }
    }

    get text() {
      if (this._surface.getMode() === 'visual') {
        // VE模式下,由于维基代码是调服务器异步解析的,因此返回缓存值
        if (this._pendingVeWikiText !== null) {
          return this._pendingVeWikiText
        }
        return this._cachedVeWikiText
      }
      var data = this._surfaceModel.documentModel.data
      if (data && data.data) {
        return this._dataNodeToSource(data.data)
      } else {
        return ''
      }
    }

    set text(text) {
      if (this._surface.getMode() === 'visual') {
        this._pendingVeWikiText = text
        this._cachedVeWikiText = text

        this._autoSyncWikitext(1000)
      } else {
        const docModel = this._surfaceModel.documentModel;
        const tx1 = ve.dm.TransactionBuilder.static.newFromRemoval(
          docModel,
          new ve.Range(0, docModel.getLength())
        );
        this._surfaceModel.change(tx1)

        const tx2 = ve.dm.TransactionBuilder.static.newFromInsertion(
          docModel,
          1,
          text
        );
        this._surfaceModel.change(tx2)
      }
    }

    async syncWikiText() {
      if (!ve.init.target.surface) {
        return Promise.resolve(this.text)
      }
      if (this._surface.getMode() !== 'visual' || this._isSyncing) {
        return Promise.resolve(this.text)
      }
      this._isSyncing = true

      try {
        let resultText = ''

        if (this._pendingVeWikiText !== null) {
          // 写回逻辑:Wikitext -> VE
          const textToPush = this._pendingVeWikiText
          const data = await ve.init.target.parseWikitextFragment(textToPush)
          const html = data.visualeditor.content
          const newDoc = ve.createDocumentFromHtml(html)
          const newDocModel = ve.dm.converter.getModelFromDom(newDoc, this._surfaceModel.getDocument())
          const docModel = this._surfaceModel.documentModel
          const entireRange = new ve.Range(0, docModel.getLength())

          this._isProgrammaticChange = true
          try {
            this._surfaceModel.getLinearFragment(entireRange).insertDocument(newDocModel)
            this._surfaceModel.setNullSelection()
          } finally {
            this._isProgrammaticChange = false
          }

          this._pendingVeWikiText = null
          this._cachedVeWikiText = textToPush
          resultText = textToPush
        } else {
          // 读取逻辑:VE -> Wikitext
          const api = new mw.Api()
          const data = await api.postWithToken('csrf', {
            action: 'visualeditoredit',
            paction: 'serialize',
            page: mw.config.get('wgPageName'),
            errorformat: 'html',
            errorlang: mw.config.get('wgUserLanguage'),
            errorsuselocal: true,
            html: this._surfaceModel.getHtml(),
            formatversion: 2,
            oldid: mw.config.get('wgRevisionId')
          })
          resultText = data.visualeditoredit.content
          this._cachedVeWikiText = resultText
        }
        return resultText
      } finally {
        this._isSyncing = false
      }
    }

    get summary() {
      if (ve.init.target.saveDialog) {
        return ve.init.target.saveDialog.editSummaryInput.$input.val()
      } else {
        return this._pendingSummary || ''
      }
    }

    set summary(text) {
      if (ve.init.target.saveDialog) {
        ve.init.target.saveDialog.setEditSummary(text)
      } else {
        this._pendingSummary = text
      }
    }

    get minorEdit() {
      if (ve.init.target.saveDialog) {
        return ve.init.target.saveDialog.checkboxesByName.wpMinoredit.selected
      } else {
        return !!this._pendingMinoredit
      }
    }

    set minorEdit(v) {
      if (ve.init.target.saveDialog) {
        ve.init.target.saveDialog.checkboxesByName.wpMinoredit.setSelected(!!v)
      } else {
        this._pendingMinoredit = !!v
      }
    }

    async _executeAction(action, action2) {
      await this.syncWikiText()

      const target = ve.init.target
      let dialog = target.saveDialog

      if (dialog && dialog.isVisible()) {
        // 对话框已打开,直接触发
        dialog.executeAction(action2)
      } else {
        if (!target.surface.model.hasBeenModified()) {
          // 发布更改按钮不可点击,先制造一个空事务,使其能被点击
          const surfaceModel = target.getSurface().getModel()
          const tx = ve.dm.TransactionBuilder.static.newFromAttributeChanges(
            surfaceModel.getDocument(), 0, 'x'
          )
          surfaceModel.change(tx)
        }

        target.surface.executeCommand(action)

        // 当对话框动画结束后再执行动作
        if (action2 === 'save') {
          const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

          for (let i = 20; i > 0; i--) {
            if (target.saveDialog) {
              target.saveDialog.executeAction(action2)
              return true
            }
            await sleep(100)
          }

          return false
        }
      }
      return true
    }

    async submit() {
      return this._executeAction('showSave', 'save')
    }

    async showPreview() {
      // 备注:可视化模式下没有预览对话框
      if (this._isVE) {
        return false
      }
      return this._executeAction('showPreview', 'preview')
    }

    async showDiff() {
      return this._executeAction('showChanges', 'review')
    }

    get selectionText() {
      // 注意:編輯器失去焦點時,選中區域會變為NullSelection!
      var selection = this._surfaceModel.getSelection()
      if (!(selection instanceof ve.dm.LinearSelection)) {
        return ''
      }
      if (this._isVE) {
        // 在VE模式返回纯文字
        var fragment = this._surfaceModel.getLinearFragment(selection.getRange())
        return fragment.getText()
      } else {
        var fragment = this._surfaceModel.getLinearFragment(selection.getRange())
        return this._dataNodeToSource(fragment.getData())
      }
    }

    set selectionText(text) {
      var selection = this._surfaceModel.getSelection()
      if (selection instanceof ve.dm.LinearSelection) {
        // wiki模式正常插入源代码,VE模式会插入纯文字
        var fragment = this._surfaceModel.getLinearFragment(selection.getRange())
        fragment.insertContent(text)
      }
    }

    setSelectionRange(start, end) {
      let docLen
      if (this._isVE) {
        const data = this._surfaceModel.getDocument().getData()
        if (data) {
          if (data.getLength) {
          	docLen = data.getLength()
          } else {
          	docLen = data.length
          }
        } else {
          data = this.text.length
        }
      } else {
        docLen = this.text.length
      }

      let [currentStart, currentEnd] = this.getSelectionRange()
      if (currentStart === null) {
        currentStart = 0
      }
      if (currentEnd === null) {
        currentEnd = 0
      }
      const [newStart, newEnd] = clampSelection(docLen, [currentStart, currentEnd], [start, end])
      this._surfaceModel.setLinearSelection(new ve.Range(newStart + 1, newEnd + 1))
    }

    getSelectionRange() {
      var selection = this._surfaceModel.getSelection()
      if (selection instanceof ve.dm.LinearSelection) {
        return [selection.getRange().start - 1, selection.getRange().end - 1]
      }
      return [null, null]
    }

    async getSelectionWikitext() {
      if (this._isVE) {
        const doc = this._surfaceModel.getDocument().shallowCloneFromSelection(this._surfaceModel.getSelection())
        return ve.init.target.getWikitextFragment(doc)
      } else {
        return this.selectionText
      }
    }

    get readonly() {
      return this._surface.isReadOnly()
    }

    focus() {
      this._surface.getView().focus()
    }

    async insertText(text, pos, { select = true, replace = true } = {}) {
      if (this._isVE) {
        // 在VE模式中,将text解析成fragment再插入到文档中
        await this.syncWikiText()

        try {
          let range
          let docLen = (this.text || '').length
          if (!docLen) {
            // 兜底
            docLen = this._surfaceModel.getDocument().getData().length
          }
          if (Array.isArray(pos)) {
            range = new ve.Range(clampIndex(pos[0], docLen) + 1, clampIndex(pos[1], docLen) + 1)
          } else if (typeof pos === 'number') {
            const p = clampIndex(pos, docLen)
            range = new ve.Range(p + 1, p + 1)
          } else {
            const selection = this._surfaceModel.getSelection()
            if (!(selection instanceof ve.dm.LinearSelection)) {
              return false
            }
            const curRange = selection.getRange()
            range = replace ? curRange : new ve.Range(curRange.end)
          }

          const data = await ve.init.target.parseWikitextFragment(text)
          const html = data.visualeditor.content
          const doc = ve.createDocumentFromHtml(html)
          let docModel = ve.dm.converter.getModelFromDom(doc, this._surfaceModel.getDocument())

          // 如果只有一行则视为inline
          let paragraphs = docModel.getData().reduce((total, node) => {
            if (node && node.type === 'paragraph') {
              return total + 1
            } else {
              return total
            }
          }, 0)
          if (paragraphs === 1) {
            docModel = docModel.shallowCloneFromRange(new ve.Range(1, docModel.data.getLength() - 3))
          }

          this._isProgrammaticChange = true
          try {
            this._surfaceModel.getLinearFragment(range).insertDocument(docModel)
          } finally {
            this._isProgrammaticChange = false
          }

          const endPos = range.start + docModel.data.getLength()
          if (select) {
            this._surfaceModel.setLinearSelection(new ve.Range(range.start, endPos))
          } else {
            this._surfaceModel.setLinearSelection(new ve.Range(endPos, endPos))
          }

          this._cachedVeWikiText = null

          this.focus()
          return true
        } catch (err) {
          console.error('[EditorAPIs] VE Fragment 插入失败', err)
          return false
        } finally {
          this._isProgrammaticChange = false
        }
      } else {
        return super.insertText(text, pos, { select, replace })
      }
    }

    scrollToLine(n) {
      let index = 0
      if (this._isVE) {
        // 检查是第几个paragraph
        const data = this._surfaceModel.getDocument().getData()
        let row = 0
        if (n > 0) {
          for (let i = 0; i < data.length; i++) {
            if (data[i] && data[i].type === 'paragraph') {
              row++
              if (row === n) {
                index = i
                break
              }
            }
          }
          if (index === 0 && row > 0) {
            index = data.length - 1
          }
        }
      } else {
        index = this.posToIndex(n, 0)
      }
      // 直接利用选中该位置并滚动到选区
      const targetRange = new ve.Range(index + 1, index + 1)
      const virtualSelection = new ve.dm.LinearSelection(targetRange)
      this._surface.scrollSelectionIntoView(virtualSelection)
    }

    scrollToCursor() {
      this._surface.scrollSelectionIntoView()
    }

    get _isVE() {
      return this._surface.getMode() === 'visual'
    }

    get _surface() {
      // 由于用户可能会切换编辑器模式,因此动态获取
      if (ve && ve.init && ve.init.target && ve.init.target.getSurface) {
      	return ve.init.target.getSurface()
      }
      return null
    }

    get _surfaceModel() {
      // 由于用户可能会切换编辑器模式,因此动态获取
      const surface = this._surface
      if (surface) {
      	return surface.getModel()
      }
      return null
    }

    _dataNodeToSource(data) {
      var r = []
      if (data) {
        for (var i = 0; i < data.length; i++) {
          if (typeof data[i] === 'string') {
            r.push(data[i])
          } else if (data[i] && data[i].type === '/paragraph') {
            r.push('\n')
          }
        }
        // 在源代码模式下,最后一个/paragraph不是换行符
        if (r.length > 0 && r[r.length - 1] === '\n') {
          r.pop()
        }
        return r.join('')
      } else {
        return ''
      }
    }

    _autoSyncWikitext(debounceMs = 1000) {
      if (this._isSyncing) {
        return
      }
      // 自动延时同步
      if (this._syncTimer) {
        clearTimeout(this._syncTimer)
      }
      this._syncTimer = setTimeout(() => {
        this._syncTimer = null
        this.syncWikiText()
      }, debounceMs)
    }

    _onDocumentUpdate() {
      if (!this._isProgrammaticChange) {
        this._cachedVeWikiText = null
        this._autoSyncWikitext(60000)
      }
    }
  }

  class DiscussionToolsApi extends VisualEditorApi {
    constructor() {
      super({
        textboxSelector: '.ext-discussiontools-ui-replyWidget',
        summarySelector: '.ext-discussiontools-ui-replyWidget-editSummary > input',
        minorEditSelector: null,
        submitSelector: '.ext-discussiontools-ui-replyWidget-actions .oo-ui-flaggedElement-primary .oo-ui-buttonElement-button',
        diffSelector: null,
        previewSelector: null,
        hasSaveDialog: false
      })
    }

    get mode() {
      return super.mode === 'visual' ? 'visual-discussion' : 'wikitext2017-discussion'
    }

    set summary(text) {
      const $summary = $(this._summarySelector)
      if ($summary && $summary[0]) {
        $summary[0].value = text
      }
    }

    get summary() {
      const $summary = $(this._summarySelector)
      if ($summary && $summary[0]) {
        return $summary[0].value
      }
      return null
    }

    set minorEdit(v) {
      // 忽略
    }

    get minorEdit() {
      return false
    }

    // DiscussionTools自动预览,不能查看diff
    async submit() {
      const $submit = $(this._submitSelector)
      if ($submit && $submit[0]) {
      	$submit[0].click()
      }
      return true
    }

    async showDiff() {
      return false
    }

    async showPreview() {
      return false
    }
  }

  // 移动端可视化编辑器
  class MobileVEApi extends VisualEditorApi {
    constructor() {
      super({
        textboxSelector: null,
        summarySelector: null,
        minorEditSelector: null,
        submitSelector: null,
        diffSelector: null,
        previewSelector: null,
        hasSaveDialog: false
      })
    }

    get mode() {
      return 'visual-mobile'
    }
  }

  // PART 3:检测当前用户使用哪种编辑器,并分配合适的API实现

  // 各类型编辑器单例
  const instances = {
    wikitext: new TraditionalEditorApi(),
    view: new ViewModeApi(),
    none: new NoneApi(),
    codemirror: null,
    wikEd: null,
    cm6: null, // Hook加载
    ace: null, // Hook加载
    ve: null, // Hook加载
    mobile: null, // Hook加载
    vemobile: null, // Hook加载
    wikiplus: null,
    ipe: null,
    discussiontools: null
  }

  // 判定用户当前所用编辑器
  const getActiveApi = () => {
    // 快速编辑器(弹出层优先级最高)
    if ($('#Wikiplus-Quickedit').length) {
      if (!instances.wikiplus) {
        instances.wikiplus = new QuickEditApi({
          mode: 'wikiplus',
          textboxSelector: '#Wikiplus-Quickedit',
          summarySelector: '#Wikiplus-Quickedit-Summary-Input',
          minorEditSelector: '#Wikiplus-Quickedit-MinorEdit',
          submitSelector: '#Wikiplus-Quickedit-Submit',
          previewSelector: '#Wikiplus-Quickedit-Preview-Submit'
        })
      }
      return instances.wikiplus
    }
    if ($('#wpTextbox1.ipe-quickEdit__textarea').length) {
      if (!instances.ipe) {
        instances.ipe = new QuickEditApi({
          mode: 'ipe',
          textboxSelector: '#wpTextbox1.ipe-quickEdit__textarea',
          summarySelector: '#summary',
          minorEditSelector: '#minor',
          submitSelector: '.ipe-modal-modal__buttons .submit-btn',
          previewSelector: '.ipe-modal-modal__buttons .submit-btn + .ipe-modal-btn',
          diffSelector: '.ipe-modal-modal__buttons .submit-btn + .ipe-modal-btn + .ipe-modal-btn'
        })
      }
      return instances.ipe
    }

    // 讨论工具
    if ($('.ext-discussiontools-ui-targetWidget').length) {
      if (!instances.discussiontools) {
        instances.discussiontools = new DiscussionToolsApi()
      }
      return instances.discussiontools
    }

    // VE / Wikitext 2017
    if (window.ve && ve.init && ve.init.target && ve.init.target.surface) {
      // 移动端VE
      if (ve.init.target.constructor.name === 'VeInitMwMobileArticleTarget') {
        if (!instances.vemobile) {
          instances.vemobile = new MobileVEApi({})
        }
        return instances.vemobile
      }
      if (!instances.ve) {
        instances.ve = new VisualEditorApi({
          hasSaveDialog: true
        })
      }
      return instances.ve
    }

    // 移动端
    if ($('#wikitext-editor').length) {
      if (!instances.mobile) {
        instances.mobile = new MobileFrontendApi({})
      }
      return instances.mobile
    }

    // 标准编辑页面
    if (['edit', 'submit'].indexOf(mw.config.get('wgAction')) !== -1) {
      if ($('#mw-content-text #wpTextbox1 + .cm-editor').length && $('.ext-codemirror-wrapper--hidden').length === 0) {
        return instances.cm6 || instances.wikitext
      }
      if ($('#wpTextbox1 + .CodeMirror').length) {
        if (!instances.codemirror) {
          instances.codemirror = new CodeMirror5Api()
        }
        return instances.codemirror
      }
      if ($('.ace_editor').length) {
        return instances.ace || instances.wikitext
      }
      if (window.wikEd && wikEd.useWikEd) {
        if (!instances.wikEd) {
          instances.wikEd = new WikEdApi()
        }
        return instances.wikEd
      }
      return instances.wikitext
    }

    // 阅读模式兜底
    if (mw.config.get('wgNamespaceNumber') !== -1) {
      return instances.view
    }

    return instances.none
  }

  let isInit = !!!window.wikitextEditor
  let lastMode = 'none'

  const editorProxy = new Proxy({}, {
    get(target, prop) {
      const activeApi = getActiveApi()

      // 特殊处理转换内核时的Hook触发
      const mode = activeApi.mode
      if (mode !== lastMode) {
        const oldMode = lastMode
        lastMode = activeApi.mode
        mw.hook('editorapi.ready').fire(editorProxy, { isInit, oldMode })
        isInit = false

        // VE模式要触发一次代码缓存
        if (mode === 'visual' || mode === 'visual-discussion' || mode === 'visual-mobile') {
          activeApi._pendingVeWikiText = null
          activeApi.syncWikiText()
        }
      }

      if (prop === 'mode') return activeApi.mode
      if (prop === '_version') return VERSION
      if (prop === '_rawApi') return activeApi

      const value = activeApi[prop]
      return (typeof value === 'function') ? value.bind(activeApi) : value
    },

    set(target, prop, value) {
      const activeApi = getActiveApi()
      activeApi[prop] = value
      return true
    },

    ownKeys() {
      const prototype = Object.getPrototypeOf(instances.wikitext)
      const keys = new Set([
        ...Reflect.ownKeys(instances.wikitext),
        ...Reflect.ownKeys(prototype)
      ])
      keys.delete('constructor')
      return Array.from(keys)
    },

    getOwnPropertyDescriptor(target, prop) {
      return { enumerable: true, configurable: true }
    }
  })

  const initObserver = () => {
    let timer = null

    const update = () => {
      // 触发一次访问即可更新状态
      const _ = wikitextEditor.mode
    }

    const observer = new MutationObserver((mutations) => {
      // 只有当增加或删除了 DOM 节点时才处理
      const hasSignificantChange = mutations.some(m => m.addedNodes.length || m.removedNodes.length)
      if (!hasSignificantChange) return

      // 防抖
      if (timer) clearTimeout(timer)
      timer = setTimeout(update, 50)
    })
    observer.observe(document.body, { childList: true, subtree: true })
  }

  const init = () => {
    window.wikitextEditor = editorProxy

    // VisualEditor / WikiEditor 2017
    mw.hook('ve.activationComplete').add(function () {
      if (!instances.ve) {
        instances.ve = new VisualEditorApi({
          hasSaveDialog: true
        })
      }
      console.log('[EditorAPIs] VE 实例已就绪并挂载至代理')
    })

    // 移动端
    mw.hook('mobileFrontend.editorOpened').add(function () {
      instances.mobile = new MobileFrontendApi()
      console.log('[EditorAPIs] 移动编辑器实例已就绪并挂载至代理')
    })

    // CodeMirror 6
    mw.hook('ext.CodeMirror.ready').add((cm) => {
      instances.cm6 = new CodeMirror6Api(cm)
      console.log('[EditorAPIs] CodeMirror 6 实例已就绪并挂载至代理')
    })

    // AceEditor
    mw.hook('codeEditor.configure').add((session) => {
      instances.ace = new AceEditorApi(session)
      console.log('[EditorAPIs] AceEditor 实例已就绪并挂载至代理')
    })

    const initialMode = wikitextEditor.mode

    // 兼容旧脚本
    if (initialMode === 'view' && window.editorapi && window.editorapi.useViewMode) {
      instances.view.load()
    }

    // 监听DOM变化以确保即时响应编辑器切换
    initObserver()
  }

  init()
})