@bhsd/codemirror-mediawiki 2.29.0 → 2.29.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/config.js +171 -112
- package/dist/mw.min.js +1 -1
- package/dist/token.js +1529 -1432
- package/dist/wiki.min.js +1 -1
- package/i18n/en.json +1 -1
- package/i18n/zh-hans.json +1 -1
- package/i18n/zh-hant.json +1 -1
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -130,7 +130,7 @@ or
|
|
|
130
130
|
|
|
131
131
|
**param**: `HTMLTextAreaElement` the textarea element to be replaced by CodeMirror
|
|
132
132
|
**param**: `string` the language mode to be used, default as plain text
|
|
133
|
-
**param**: `unknown` the
|
|
133
|
+
**param**: `unknown` the language configuration, only required for the MediaWiki mode and the mixed MediaWiki-HTML mode
|
|
134
134
|
**param**: `boolean` whether to initialize immediately, default as true
|
|
135
135
|
|
|
136
136
|
```js
|
package/dist/config.js
CHANGED
|
@@ -1,119 +1,178 @@
|
|
|
1
|
+
// src/config.ts
|
|
2
|
+
import { tags, Tag } from "@lezer/highlight";
|
|
3
|
+
|
|
4
|
+
// ../wikiparser-node/config/default.json
|
|
5
|
+
var html = [
|
|
6
|
+
[
|
|
7
|
+
"b",
|
|
8
|
+
"bdi",
|
|
9
|
+
"del",
|
|
10
|
+
"i",
|
|
11
|
+
"ins",
|
|
12
|
+
"u",
|
|
13
|
+
"font",
|
|
14
|
+
"big",
|
|
15
|
+
"small",
|
|
16
|
+
"sub",
|
|
17
|
+
"sup",
|
|
18
|
+
"h1",
|
|
19
|
+
"h2",
|
|
20
|
+
"h3",
|
|
21
|
+
"h4",
|
|
22
|
+
"h5",
|
|
23
|
+
"h6",
|
|
24
|
+
"cite",
|
|
25
|
+
"code",
|
|
26
|
+
"em",
|
|
27
|
+
"s",
|
|
28
|
+
"strike",
|
|
29
|
+
"strong",
|
|
30
|
+
"tt",
|
|
31
|
+
"var",
|
|
32
|
+
"div",
|
|
33
|
+
"center",
|
|
34
|
+
"blockquote",
|
|
35
|
+
"ol",
|
|
36
|
+
"ul",
|
|
37
|
+
"dl",
|
|
38
|
+
"table",
|
|
39
|
+
"caption",
|
|
40
|
+
"pre",
|
|
41
|
+
"ruby",
|
|
42
|
+
"rb",
|
|
43
|
+
"rp",
|
|
44
|
+
"rt",
|
|
45
|
+
"rtc",
|
|
46
|
+
"p",
|
|
47
|
+
"span",
|
|
48
|
+
"abbr",
|
|
49
|
+
"dfn",
|
|
50
|
+
"kbd",
|
|
51
|
+
"samp",
|
|
52
|
+
"data",
|
|
53
|
+
"time",
|
|
54
|
+
"mark",
|
|
55
|
+
"tr",
|
|
56
|
+
"td",
|
|
57
|
+
"th",
|
|
58
|
+
"q",
|
|
59
|
+
"bdo"
|
|
60
|
+
],
|
|
61
|
+
[
|
|
62
|
+
"li",
|
|
63
|
+
"dt",
|
|
64
|
+
"dd"
|
|
65
|
+
],
|
|
66
|
+
[
|
|
67
|
+
"br",
|
|
68
|
+
"wbr",
|
|
69
|
+
"hr",
|
|
70
|
+
"meta",
|
|
71
|
+
"link",
|
|
72
|
+
"img"
|
|
73
|
+
]
|
|
74
|
+
];
|
|
75
|
+
|
|
76
|
+
// src/config.ts
|
|
1
77
|
/**
|
|
2
78
|
* @file Configuration for the MediaWiki highlighting mode for CodeMirror.
|
|
3
79
|
* @author MusikAnimal and others
|
|
4
80
|
* @license GPL-2.0-or-later
|
|
5
81
|
* @see https://gerrit.wikimedia.org/g/mediawiki/extensions/CodeMirror
|
|
6
82
|
*/
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
* These are custom tokens (a.k.a. tags) that aren't mapped to any of the standardized tags.
|
|
96
|
-
*
|
|
97
|
-
* @see https://codemirror.net/docs/ref/#language.StreamParser.tokenTable
|
|
98
|
-
* @see https://lezer.codemirror.net/docs/ref/#highlight.Tag%5Edefine
|
|
99
|
-
*/
|
|
100
|
-
tokenTable = (() => {
|
|
101
|
-
const table = {
|
|
102
|
-
variable: tags.variableName,
|
|
103
|
-
'variable-2': tags.special(tags.variableName),
|
|
104
|
-
'string-2': tags.special(tags.string),
|
|
105
|
-
def: tags.definition(tags.variableName),
|
|
106
|
-
tag: tags.tagName,
|
|
107
|
-
attribute: tags.attributeName,
|
|
108
|
-
type: tags.typeName,
|
|
109
|
-
builtin: tags.standard(tags.variableName),
|
|
110
|
-
qualifier: tags.modifier,
|
|
111
|
-
error: tags.invalid,
|
|
112
|
-
header: tags.heading,
|
|
113
|
-
property: tags.propertyName,
|
|
114
|
-
};
|
|
115
|
-
for (const className of Object.values(tokens)) {
|
|
116
|
-
table[className] = Tag.define();
|
|
117
|
-
}
|
|
118
|
-
return table;
|
|
83
|
+
var htmlTags = html.flat();
|
|
84
|
+
var voidHtmlTags = html[2];
|
|
85
|
+
var selfClosingTags = html[1];
|
|
86
|
+
var tokens = {
|
|
87
|
+
apostrophes: "mw-apostrophes",
|
|
88
|
+
comment: "mw-comment",
|
|
89
|
+
convertBracket: "mw-convert-bracket",
|
|
90
|
+
convertDelimiter: "mw-convert-delimiter",
|
|
91
|
+
convertFlag: "mw-convert-flag",
|
|
92
|
+
convertLang: "mw-convert-lang",
|
|
93
|
+
doubleUnderscore: "mw-double-underscore",
|
|
94
|
+
em: "mw-em",
|
|
95
|
+
error: "mw-error",
|
|
96
|
+
extLink: "mw-extlink",
|
|
97
|
+
extLinkBracket: "mw-extlink-bracket",
|
|
98
|
+
extLinkProtocol: "mw-extlink-protocol",
|
|
99
|
+
extLinkText: "mw-extlink-text",
|
|
100
|
+
extTag: "mw-exttag",
|
|
101
|
+
extTagAttribute: "mw-exttag-attribute",
|
|
102
|
+
extTagAttributeValue: "mw-exttag-attribute-value",
|
|
103
|
+
extTagBracket: "mw-exttag-bracket",
|
|
104
|
+
extTagName: "mw-exttag-name",
|
|
105
|
+
fileDelimiter: "mw-file-delimiter",
|
|
106
|
+
fileText: "mw-file-text",
|
|
107
|
+
freeExtLink: "mw-free-extlink",
|
|
108
|
+
freeExtLinkProtocol: "mw-free-extlink-protocol",
|
|
109
|
+
hr: "mw-hr",
|
|
110
|
+
htmlEntity: "mw-entity",
|
|
111
|
+
htmlTagAttribute: "mw-htmltag-attribute",
|
|
112
|
+
htmlTagAttributeValue: "mw-htmltag-attribute-value",
|
|
113
|
+
htmlTagBracket: "mw-htmltag-bracket",
|
|
114
|
+
htmlTagName: "mw-htmltag-name",
|
|
115
|
+
imageParameter: "mw-image-parameter",
|
|
116
|
+
linkBracket: "mw-link-bracket",
|
|
117
|
+
linkDelimiter: "mw-link-delimiter",
|
|
118
|
+
linkPageName: "mw-link-pagename",
|
|
119
|
+
linkText: "mw-link-text",
|
|
120
|
+
linkToSection: "mw-link-tosection",
|
|
121
|
+
list: "mw-list",
|
|
122
|
+
magicLink: "mw-magic-link",
|
|
123
|
+
pageName: "mw-pagename",
|
|
124
|
+
parserFunction: "mw-parserfunction",
|
|
125
|
+
parserFunctionBracket: "mw-parserfunction-bracket",
|
|
126
|
+
parserFunctionDelimiter: "mw-parserfunction-delimiter",
|
|
127
|
+
parserFunctionName: "mw-parserfunction-name",
|
|
128
|
+
redirect: "mw-redirect",
|
|
129
|
+
section: "mw-section",
|
|
130
|
+
sectionHeader: "mw-section-header",
|
|
131
|
+
signature: "mw-signature",
|
|
132
|
+
skipFormatting: "mw-skipformatting",
|
|
133
|
+
strong: "mw-strong",
|
|
134
|
+
tableBracket: "mw-table-bracket",
|
|
135
|
+
tableCaption: "mw-table-caption",
|
|
136
|
+
tableDefinition: "mw-table-definition",
|
|
137
|
+
tableDefinitionValue: "mw-table-definition-value",
|
|
138
|
+
tableDelimiter: "mw-table-delimiter",
|
|
139
|
+
tableDelimiter2: "mw-table-delimiter2",
|
|
140
|
+
tableTd: "mw-table-td",
|
|
141
|
+
tableTh: "mw-table-th",
|
|
142
|
+
template: "mw-template",
|
|
143
|
+
templateArgumentName: "mw-template-argument-name",
|
|
144
|
+
templateBracket: "mw-template-bracket",
|
|
145
|
+
templateDelimiter: "mw-template-delimiter",
|
|
146
|
+
templateName: "mw-template-name",
|
|
147
|
+
templateVariable: "mw-templatevariable",
|
|
148
|
+
templateVariableBracket: "mw-templatevariable-bracket",
|
|
149
|
+
templateVariableDelimiter: "mw-templatevariable-delimiter",
|
|
150
|
+
templateVariableName: "mw-templatevariable-name"
|
|
151
|
+
};
|
|
152
|
+
var tokenTable = (() => {
|
|
153
|
+
const table = {
|
|
154
|
+
variable: tags.variableName,
|
|
155
|
+
"variable-2": tags.special(tags.variableName),
|
|
156
|
+
"string-2": tags.special(tags.string),
|
|
157
|
+
def: tags.definition(tags.variableName),
|
|
158
|
+
tag: tags.tagName,
|
|
159
|
+
attribute: tags.attributeName,
|
|
160
|
+
type: tags.typeName,
|
|
161
|
+
builtin: tags.standard(tags.variableName),
|
|
162
|
+
qualifier: tags.modifier,
|
|
163
|
+
error: tags.invalid,
|
|
164
|
+
header: tags.heading,
|
|
165
|
+
property: tags.propertyName
|
|
166
|
+
};
|
|
167
|
+
for (const className of Object.values(tokens)) {
|
|
168
|
+
table[className] = Tag.define();
|
|
169
|
+
}
|
|
170
|
+
return table;
|
|
119
171
|
})();
|
|
172
|
+
export {
|
|
173
|
+
htmlTags,
|
|
174
|
+
selfClosingTags,
|
|
175
|
+
tokenTable,
|
|
176
|
+
tokens,
|
|
177
|
+
voidHtmlTags
|
|
178
|
+
};
|
package/dist/mw.min.js
CHANGED
|
@@ -39,7 +39,7 @@ end`,{label:"if",detail:"/ else block",type:"keyword"}),Re("while ${condition} d
|
|
|
39
39
|
${p}`,g=1),/[\n\r]/u.test(h.sliceDoc(d,d+1))||(p+=`
|
|
40
40
|
`,b=1)),[p,g,b]};if(a!==void 0)pv.setSelection.call(this,{start:a,end:l});else if(r&&n&&!t&&!i&&/^\s*=.*=\s*$/u.test(e)){const{selection:{main:{from:u,to:d}}}=h,[p]=f(u,d,e);return c.dispatch({changes:{from:u,to:d,insert:p},selection:{anchor:u+p.length}}),this}return Kn.replaceSelections(c,(u,{from:d,to:p})=>{const g=s&&d===p,b=n||d===p?e:h.sliceDoc(d,p),[x,S,C]=f(d,p,dv(b,t,i,o)),A=d+x.length;return g?[x,d+t.length+S,A-i.length-C]:[x,A]}),this},getCaretPosition(t){const{state:{selection:{main:{from:e,to:i,head:r}}}}=Ne(this).view;return t!=null&&t.startAndEnd?[e,i]:r},scrollToCaretPosition(){return Ne(this).scrollTo(),this}},Nh={getContents(){return Ne(this).model.getValue()},setContents(t){return Ne(this).model.setValue(t),this},getSelection(){const{model:t,editor:e}=Ne(this);return t.getValueInRange(e.getSelection())},setSelection({start:t,end:e=t}){const{model:i,editor:r}=Ne(this);return r.setSelection(zZ(monaco,i,[t,e])),this},replaceSelection(t){const{editor:e}=Ne(this);return e.executeEdits("replaceSelection",[{range:e.getSelection(),text:t,forceMoveMarkers:!0}]),this},encapsulateSelection({pre:t="",peri:e="",post:i="",ownline:r,replace:n,splitlines:s,selectionStart:o,selectionEnd:a}){const{model:l,editor:c}=Ne(this),h=({startColumn:u,endColumn:d,endLineNumber:p},g)=>(r&&u>1?`
|
|
41
41
|
`:"")+g+(r&&d<=l.getLineLength(p)?`
|
|
42
|
-
`:"");if(o!==void 0)Nh.setSelection.call(this,{start:o,end:a});else if(r&&n&&!t&&!i&&/^\s*=.*=\s*$/u.test(e)){const u=c.getSelection();return c.executeEdits("encapsulateSelection",[{range:u,text:h(u,e),forceMoveMarkers:!0}]),this}const f=c.getSelections().map(u=>{const d=n||u.isEmpty()?e:l.getValueInRange(u),p=h(u,dv(d,t,i,s));return{range:u,text:p,forceMoveMarkers:!0}});return c.executeEdits("encapsulateSelection",f),this},getCaretPosition(t){const{editor:e,model:i}=Ne(this),r=e.getSelection(),n=i.getOffsetAt(r.getEndPosition());return t!=null&&t.startAndEnd?[i.getOffsetAt(r.getStartPosition()),n]:n},scrollToCaretPosition(){const{editor:t}=Ne(this);return t.revealPosition(t.getPosition()),this}},BZ=(()=>{const t=["bold-header","format-leakage","fostered-content","h1","illegal-attr","insecure-style","invalid-gallery","invalid-imagemap","invalid-invoke","invalid-isbn","lonely-apos","lonely-bracket","lonely-http","nested-link","no-arg","no-duplicate","no-ignored","obsolete-attr","obsolete-tag","parsing-order","pipe-like","table-layout","tag-like","unbalanced-header","unclosed-comment","unclosed-quote","unclosed-table","unescaped","unknown-page","unmatched-tag","unterminated-url","url-encoding","var-anchor","void-ext","invalid-css"];return Object.freeze(t),t})(),mv="codemirror-mediawiki-i18n",ua="npm/@bhsd/codemirror-mediawiki@2.29.0",da=ua.slice(ua.lastIndexOf("@")+1),gv=(p0=(d0=mw.language)==null?void 0:d0.getFallbackLanguageChain())!=null?p0:[mw.config.get("wgUserLanguage")],Gn=(m0=vi(mv))!=null?m0:{},{version:Ov}=Gn,VZ=async t=>{try{await If(`${t}/${ua}/i18n`,da,gv,mv,Gn)}catch(e){e instanceof Error&&(mw.notify(e.message,{type:"error"}),console.error(e))}for(const[e,i]of Object.entries(Gn))e.endsWith("-mac")?Ch&&mw.messages.set(`cm-mw-${e.slice(0,-4)}`,i):mw.messages.set(`cm-mw-${e}`,i)},je=(t,...e)=>mw.msg(`cm-mw-${t}`,...e),bv=t=>(t.find("a").add(t.filter("a")).attr("target","_blank"),t);function Ih(t,e){const i=mw.message(`cm-mw-${t}`);return e?i.parse():bv(i.parseDom())}var vv=async(t,...e)=>{const i=bv($("<p>",{html:je(t,...e)}));return await mw.notify(i,{type:"success",autoHideSeconds:"long"}),i},NZ=async(t,e)=>{let i;Ov?e.length>0&&!Nf(Ov,t)&&(i=await vv("welcome-addons",`<a href="https://github.com/bhsd-harry/codemirror-mediawiki/blob/npm/CHANGELOG.md#${da.replace(/\./gu,"")}" target="_blank">${da}</a>`,String(e.length),e.map(r=>`<li>${Ih(`addon-${r}`,!0)}</li>`).join(""))):i=await vv("welcome"),i==null||i.find("#settings").click(r=>{r.preventDefault(),document.getElementById("cm-settings").dispatchEvent(new MouseEvent("click"))})},yv=t=>{t.localize(Object.fromEntries(Object.entries(Gn).filter(([e])=>e.startsWith("phrase-")).map(([e,i])=>[e.slice(7).replace(/-/gu," "),i])))},wv="codemirror-mediawiki-addons",kv="codemirror-mediawiki-monaco",Gh=["wiki","javascript","css","lua","json"],IZ=["Wikitext","JavaScript","CSS","Lua","JSON"],xv="codemirror-mediawiki-wikilint",pa=["ESLint","Stylelint"],Ir=((g0=mw.config.get("wgUserGroups"))==null?void 0:g0.includes("user"))&&mw.config.get("wgUserName"),Sv=Ir?`User:${Ir}/codemirror-mediawiki.json`:void 0,ma="codemirror-mediawiki-indent",_e=new Set(vi(wv)),Et=new Set((O0=vi(kv))!=null?O0:_e.has("useMonaco")?Gh:[]),Ft=(b0=vi(xv))!=null?b0:{},qi=new Map(pa.map(t=>[t,vi(`codemirror-mediawiki-${t}`)])),Un,Uh,ga,Oa,ba,di=(v0=localStorage.getItem(ma))!=null?v0:"",Fh={},Qv=new Map,$v=(t,e)=>{const i=t==="http"||t==="okay-but-empty"?`MediaWiki API request failed: ${t}`:$("<ul>",{html:e.errors.map(({html:r})=>$("<li>",{html:r}))});mw.notify(i,{type:"error",autoHideSeconds:"long"})},Pv=(async()=>{if(Ir)return await mw.loader.using("mediawiki.api"),new mw.Api({parameters:{errorformat:"html",formatversion:"2"}})})(),Tv=(async()=>{if(!Ir)return;const t={action:"query",prop:"revisions",titles:Sv,rvprop:"content",rvlimit:1};(await Pv).get(t).then(e=>{var r,n;const{query:{pages:[i]}}=e;if(i!=null&&i.revisions){const s=JSON.parse(i.revisions[0].content);if(!((r=s.addons)!=null&&r.includes("save")))return;_e.clear();for(const o of s.addons)_e.add(o);Et.clear();for(const o of(n=s.useMonaco)!=null?n:_e.has("useMonaco")?Gh:[])Et.add(o);s.indent&&localStorage.setItem(ma,s.indent);for(const o of pa)s[o]&&qi.set(o,s[o]);s.wikilint&&Object.assign(Ft,s.wikilint)}},$v)})(),GZ=async t=>{if(await mw.loader.using(["oojs-ui-windows","oojs-ui-widgets","oojs-ui.styles.icons-content","mediawiki.jqueryMsg"]),await Tv,Un)ga.setValue([..._e]),Oa.setValue([...Et]),ba.setValue(di);else{Un=new OO.ui.MessageDialog({id:"cm-preference"}),Un.$element.css("z-index","801");const i=new OO.ui.WindowManager;i.$element.appendTo(document.body),i.addWindows([Un]),Uh=new OO.ui.IndexLayout;const r=new OO.ui.TabPanelLayout("main",{label:je("title")}),n=new OO.ui.TabPanelLayout("wikilint",{label:"WikiLint"}),s={};for(const c of pa){const h=qi.get(c);Fh[c]=new OO.ui.MultilineTextInputWidget({value:h?JSON.stringify(h,null,di||" "):""});const f=new OO.ui.FieldLayout(Fh[c],{label:je(`${c}-config`),align:"top"}),u=new OO.ui.TabPanelLayout(c,{label:c,$content:f.$element});u.on("active",d=>{const[p]=u.$element.find("textarea");d&&!ui.has(p)&&(async()=>{const{editor:g}=await Kn.fromTextArea(p,"json");g&&(g.getContainerDomNode().style.height=`${Math.max(g.getContentHeight(),400)}px`)})()}),s[c]=u}Uh.addTabPanels([r,n,...Object.values(s)],0),ga=new OO.ui.CheckboxMultiselectInputWidget({options:[{disabled:!0},...Object.keys(Gn).filter(c=>c!=="addon-indent"&&c!=="addon-useMonaco"&&c.startsWith("addon-")&&!c.endsWith("-mac")).map(c=>({data:c.slice(6),label:Ih(c),disabled:c==="addon-wikiEditor"&&!mw.loader.getState("ext.wikiEditor")||c==="addon-save"&&!Ir}))],value:[..._e]}),Oa=new OO.ui.CheckboxMultiselectInputWidget({options:Gh.map((c,h)=>({data:c,label:IZ[h]})),value:[...Et]}),ba=new OO.ui.TextInputWidget({value:di,placeholder:String.raw`\t`});const o=new OO.ui.FieldLayout(ga,{label:je("label"),align:"top"}),a=new OO.ui.FieldLayout(Oa,{label:je("addon-useMonaco"),align:"top"}),l=new OO.ui.FieldLayout(ba,{label:je("addon-indent")});r.$element.append(o.$element,a.$element,l.$element,$("<p>",{html:je("feedback","codemirror-mediawiki")})),n.$element.append(...BZ.map(c=>{var d,p;const h=c==="no-arg"?"0":"1",f=new OO.ui.DropdownInputWidget({options:[{data:"0",label:je("wikilint-off")},{data:"1",label:je("wikilint-error")},{data:"2",label:je("wikilint-on")}],value:(d=Ft[c])!=null?d:h}),u=new OO.ui.FieldLayout(f,{label:c});return Qv.set(c,f),(p=Ft[c])!=null||(Ft[c]=h),u.$element}),$("<p>",{html:je("feedback","wikiparser-node")}))}const e=await Un.open({message:Uh.$element,actions:[{action:"reject",label:mw.msg("ooui-dialog-message-reject")},{action:"accept",label:mw.msg("ooui-dialog-message-accept"),flags:"progressive"}],size:"medium"}).closing;if(typeof e=="object"&&e.action==="accept"){const i=di,r=_e.has("save");di=ba.getValue();let n=di!==i;if(n){for(const a of t)a==null||a.setIndent(di||" ");localStorage.setItem(ma,di)}for(const[a,l]of Qv){const c=l.getValue();n||(n=c!==Ft[a]),Ft[a]=c}yi(xv,Ft);const s=[];for(const a of pa)try{const l=JSON.parse(Fh[a].getValue().trim()||"null");n||(n=JSON.stringify(l)!==JSON.stringify(qi.get(a))),qi.set(a,l),yi(`codemirror-mediawiki-${a}`,l)}catch{s.push(a)}s.length>0&&OO.ui.alert(je("json-error",s.join(je("and"))));let o=Oa.getValue();if(o.length!==Et.size||!o.every(a=>Et.has(a))){n=!0,Et.clear();for(const a of o)Et.add(a);yi(kv,o)}if(_e.delete("useMonaco"),o=ga.getValue(),o.length!==_e.size||!o.every(a=>_e.has(a))){n=!0,_e.clear();for(const a of o)_e.add(a);for(const a of t)a==null||a.prefer(o)}if(Et.size>0&&_e.add("useMonaco"),o=[..._e],yi(wv,o),n&&Ir&&(r||_e.has("save"))){const a={action:"edit",title:Sv,text:JSON.stringify({addons:o,useMonaco:[...Et],indent:di,wikilint:Ft,ESLint:qi.get("ESLint"),Stylelint:qi.get("Stylelint")}),summary:je("save-summary")};(await Pv).postWithToken("csrf",a).then(()=>{mw.notify(Ih("save-success"),{type:"success"})},$v)}}},Hh=new Map,UZ=(t,e)=>async(i,r=0,n)=>{n&&(i=e+i);try{const[,s]=await t.get({action:"opensearch",search:i,namespace:r,limit:"max"});if(n){const{length:o}=e;return s.map(a=>[a.slice(o)])}return r===0?s.map(o=>[o]):s.map(o=>[new mw.Title(o).getMainText()])}catch{return[]}},FZ=(t,e)=>async i=>{var r,n;i.startsWith("/")&&(i=e+i);try{if(i=new mw.Title(i,10).getPrefixedDb(),Hh.has(i))return Hh.get(i);const{pages:s}=await t.get({action:"templatedata",titles:i,redirects:!0,converttitles:!0,lang:mw.config.get("wgUserLanguage")}),o=Object.entries((n=(r=Object.values(s)[0])==null?void 0:r.params)!=null?n:{}),a=[];for(const[l,{aliases:c,label:h}]of o){const f=h!=null?h:"";a.push([l,f],...c.map(u=>[u,f]))}return Hh.set(i,a),a}catch{return[]}},HZ=async t=>{await mw.loader.using(["mediawiki.api","mediawiki.Title"]);const e=new mw.Api({parameters:{formatversion:2}});return{linkSuggest:UZ(e,t),paramSuggest:FZ(e,t)}},Cv=(t,e,i,r,n)=>({id:t,label:e,keybindings:[monaco.KeyMod.CtrlCmd|monaco.KeyCode[i]],contextMenuGroupId:"1_modification",run(s){const o=s.getModel(),a=s.getSelections().filter(l=>!l.isEmpty());if(a.length===0)s.trigger(t,r,void 0);else{const l=a.map(c=>({range:c,text:n(o.getValueInRange(c))}));s.executeEdits(t,l)}}}),KZ=()=>[Cv("escape.html","Escape HTML Entity","BracketLeft","editor.action.indentLines",mb),Cv("escape.uri","URI Encode/Decode","BracketRight","editor.action.outdentLines",gb)],Fn=new WeakMap,va,JZ=(t,e)=>{if(e&&!Fn.has(t))va!=null||(va=KZ()),Fn.set(t,va.map(i=>t.addAction(i)));else if(e===!1&&Fn.has(t)){for(const i of Fn.get(t))i.dispose();Fn.delete(t)}};function Zv(t,e,i){const r=t==null?void 0:t.find(`${ya(e==="toggle"?"":"more")}>[rel=${e}]`);return i?r==null?void 0:r.children().addBack():r}var Av=(t,e)=>Zv(t,e).hasClass("tool-active"),ya=t=>Array.isArray(t)?t.map(e=>ya(e)).join():`.group-codemirror6${t&&`-${t}`}`,Hn=(t,e,i)=>{var r;(r=Zv(t,e,!0))==null||r.toggleClass("tool-active",i)},Rv=(t,e)=>{t&&(Hn(t,"toggle",e),t.find(ya(["format","more"])).toggle(e),t.find(".group-codeeditor-main").toggle(e===void 0?void 0:!e))},Yi=(t,e,i)=>({type:"button",oouiIcon:t,label:i,action:{type:"callback",execute(r){const n=Ne(r.$textarea);if(typeof e=="function"){e(r,n);return}const[s,o,a]=e;a&&!n.visible?a(r):n.view?s(n.view):n.editor&&n.editor.trigger("wikiEditor",o,void 0)}}}),eA=async(t,e,i)=>{if(!mw.loader.getState("ext.wikiEditor"))throw new Error("no-wikiEditor");let r=t.data("wikiEditorContext");const n=new Promise(o=>{if(r){o();return}t.on("wikiEditor-toolbar-doneInitialSections",()=>{o()})});if(await mw.loader.using(["ext.wikiEditor","oojs-ui.styles.icons-interactions","ext.codeEditor.icons"]),r)r.modules.toolbar.$toolbar.find(".group-insert>.tool:not([rel])").hide();else if(typeof mw.addWikiEditor=="function")mw.addWikiEditor(t);else{const{wikiEditor:{modules:{dialogs:{config:o}}}}=$;t.wikiEditor("addModule",{...$.wikiEditor.modules.toolbar.config.getDefaultConfig(),...o.getDefaultConfig()}),o.replaceIcons(t)}await n,r!=null||(r=t.data("wikiEditorContext"));const{$toolbar:s}=r.modules.toolbar;t.wikiEditor("addToToolbar",{section:"main",groups:{codemirror6:{tools:{toggle:Yi("highlight",(o,a)=>{a.toggle()},"CodeMirror 6")}},"codemirror6-format":{tools:{indent:Yi("indent",[So,"editor.action.indentLines"]),outdent:Yi("outdent",[Qo,"editor.action.outdentLines"])}},"codemirror6-more":{tools:{invisibleChars:Yi("pilcrow",(o,a)=>{const l=!Av(s,"invisibleChars");a.prefer({highlightSpecialChars:l,highlightWhitespace:l})}),lineWrapping:Yi("wrapping",(o,a)=>{const l=!Av(s,"lineWrapping");a.setLineWrapping(l),Hn(s,"lineWrapping",l)}),gotoLine:Yi("gotoLine",[cg,"editor.action.gotoLine"]),preferences:Yi("settings",()=>{document.getElementById("cm-settings").click()},je("title"))}},"codemirror6-search":{tools:{cmSearch:Yi("articleSearch",[Ic,"editor.action.startFindReplaceAction",o=>{$.wikiEditor.modules.dialogs.api.openDialog(o,"search-and-replace")}],mw.msg("wikieditor-toolbar-tool-replace"))}}}}),Rv(s,!0),s.toggleClass("codemirror-readonly",e).toggleClass("codemirror-wiki",i).toggleClass("codemirror-coding",!i)},wa={},tA=new Set(["javascript","css","lua","json"]),Wv={"sanitized-css":"css",js:"javascript",scribunto:"lua",wikitext:"mediawiki","proofread-page":"mediawiki"},iA={mediawiki:"wikitext",template:"wikitext",gadget:"javascript",plain:"plaintext"},rA=[["allowMultipleSelections","multiCursorLimit",1,void 0],["autocompletion","quickSuggestions",!1,!0],["bracketMatching","matchBrackets","never","always"],["closeBrackets",["autoClosingBrackets","autoClosingQuotes"],"never","always"],["codeFolding","folding",!1,!0],["colorPicker","colorDecorators",!1,!0],["highlightActiveLine","renderLineHighlight","gutter","all"],["highlightSelectionMatches","occurrencesHighlight","off","singleFile"],["highlightSpecialChars","renderControlCharacters",!1,!0],["highlightWhitespace","renderWhitespace","selection","all"],["openLinks","links",!1,!0],["scrollPastEnd","scrollBeyondLastLine",!1,!0],["hover","hover",{enabled:!1},void 0],["signatureHelp","parameterHints",{enabled:!1},void 0],["inlayHints","inlayHints",{enabled:"offUnlessPressed"},{enabled:"onUnlessPressed"}]],Kh=t=>!t.closest("#cm-preference"),Kn=(Li=class extends cv{constructor(i,r,n,s,o=!0,a=mw.config.get("wgPageName")){var c;if(ui.has(i))throw new RangeError("The textarea has already been replaced by CodeMirror.");const l=h=>{h.textarea===i&&h.destroy()};mw.hook("ext.CodeMirror.ready").add(l);super(i,r,s,!1);we(this,Jt);we(this,gi,!0);we(this,Dt);we(this,De);we(this,rt);we(this,ps);we(this,Fr," ");we(this,ms);this.ns=n,this.page=a,this.$textarea=$(i),ze(this,ms,l),ui.set(i,this),this.initialize(s,!o),Kh(i)?(mw.hook("wiki-codemirror6").fire(this),i.id==="wpTextbox1"&&((c=i.form)==null||c.addEventListener("submit",()=>{const h=document.querySelector("#wpScrolltop");h&&this.view&&Z(this,gi)&&(h.value=String(this.view.scrollDOM.scrollTop))}))):mw.hook("wiki-codemirror6.setting").fire(this)}get visible(){return Z(this,gi)&&this.textarea.isConnected}get model(){return Z(this,De)}get editor(){return Z(this,rt)}get $toolbar(){var i;return(i=this.$textarea.data("wikiEditorContext"))==null?void 0:i.modules.toolbar.$toolbar}initialize(i,r){if(Z(this,De))throw new Error("A Monaco editor is already initialized!");if(r){ze(this,ps,Ze(this,Jt,iy).call(this)),this.$textarea.data("jquery.textSelection",Nh);return}super.initialize(i),Ze(this,Jt,wf).call(this,i);const n=[...this.textarea.classList].find(s=>s.startsWith("mw-editfont-"));n&&this.view.contentDOM.classList.add(n),Hn(this.$toolbar,"lineWrapping",!0)}toggle(i=!Z(this,gi)){const{textarea:r,$textarea:n}=this;Z(this,De)?i&&!Z(this,gi)?(Z(this,De).setValue(r.value),Ze(this,Jt,kf).call(this),Z(this,Dt).style.display="",r.style.display="none",n.data("jquery.textSelection",Nh)):!i&&Z(this,gi)&&(Z(this,Dt).style.display="none",r.style.display="",n.removeData("jquery.textSelection")):(super.toggle(i),n.data("jquery.textSelection",i&&pv)),ze(this,gi,i),Rv(this.$toolbar,i)}destroy(){var i;this.visible&&this.toggle(!1),Z(this,rt)&&(Z(this,rt).dispose(),Z(this,De).dispose(),Z(this,Dt).remove()),this.$textarea.data("CodeMirror6",null),(i=this.$toolbar)==null||i.removeClass(["readonly","wiki","coding"].map(r=>`codemirror-${r}`).join(" ")).find(ya(["","format","more","search"])).remove(),mw.hook("ext.CodeMirror.ready").remove(Z(this,ms)),super.destroy()}async setLanguage(i,r){var s;if(Z(this,De))throw new Error("Cannot change the language of a Monaco editor!");const n=i==="mediawiki"||i==="html";n&&Object.assign(r,await HZ(this.page)),super.setLanguage(i,r),Ze(this,Jt,wf).call(this,r),(s=this.$toolbar)==null||s.toggleClass("codemirror-coding",!n)}setContent(i){Z(this,De)?Z(this,De).setValue(i):super.setContent(i)}getContent(){return this.view?this.view.state.doc.toString():Z(this,De).getValue()}setIndent(i){if(Z(this,rt)){ze(this,Fr,i);const r=i.includes(" ");Z(this,rt).updateOptions({tabSize:r?4:Number(i),insertSpaces:!r})}else super.setIndent(i)}setLineWrapping(i){Z(this,rt)?Z(this,rt).updateOptions({wordWrap:i?"on":"off"}):super.setLineWrapping(i)}async getLinter(i){const r=await super.getLinter(i);return wa[this.lang]=r,r}async defaultLint(i,r=this.ns){if(!i){this.lint();return}const{lang:n}=this,s=n in wa,o=n==="mediawiki";let a,l;if(typeof r=="number"?o&&r!==10&&r!==828&&r!==2?l={include:!1}:n==="javascript"&&(l={...VT,...r===8||r===2300?{parserOptions:{ecmaVersion:8}}:{}}):a=r,a||!s){if(o){const c={getConfig:this.getWikiConfig,i18n:gv};a=a?{...c,...a}:h=>h?Ft:{...c,...l}}else n==="javascript"?a!=null||(a=()=>({...l,...qi.get("ESLint")})):n==="css"&&(a!=null||(a=()=>qi.get("Stylelint")));await this.getLinter(a)}wa[n]&&this.lint(wa[n])}async getWikiConfig(){const[i,r]=await Promise.all([uv(Zh),wikiparse.getConfig()]);return jZ(r,i)}prefer(i){!Kh(this.textarea)&&Array.isArray(i)&&(i=i.filter(l=>l!=="scrollPastEnd"));const r=Array.isArray(i)?l=>i.includes(l):l=>i[l],n=r("lint"),s=r("highlightSpecialChars")&&r("highlightWhitespace"),o=this.lang==="mediawiki";if(s!==void 0&&Hn(this.$toolbar,"invisibleChars",s),this.view){super.prefer(i),n!==void 0&&this.defaultLint(n);return}else{if(!Z(this,rt)||!Z(this,De))throw new Error("The editor is not initialized!");n!==void 0&&Z(this,De).lint&&Z(this,De).lint(n)}o&&JZ(Z(this,rt),r("escape"));const a={};for(const[l,c,h,f]of rA){const u=r(l);if(u!==void 0)if(typeof c=="string")a[c]=u?f:h;else for(const d of c)a[d]=u?f:h}Z(this,rt).updateOptions(a)}static async fromTextArea(i,r,n,s){var d;if(!r&&n===void 0){const{wgAction:p,wgNamespaceNumber:g,wgPageContentModel:b,wgCanonicalSpecialPageName:x}=mw.config.get();p==="edit"||p==="submit"?(n=g,r=g===274?"html":b.toLowerCase()):x==="Upload"?(n=6,r="wikitext"):x==="ExpandTemplates"&&i.name==="wpInput"?(n=0,r="wikitext"):(await mw.loader.using("oojs-ui-windows"),r=(d=await OO.ui.prompt(je("contentmodel"))||void 0)==null?void 0:d.toLowerCase())}let o;r&&r in Wv&&(r==="sanitized-css"&&(o=r),r=Wv[r]);const a=$(i),l=r==="mediawiki"||r==="html";if(_e.has("wikiEditor")&&Kh(i))try{await eA(a,i.readOnly,l)}catch(p){p instanceof Error&&p.message==="no-wikiEditor"&&mw.notify(je(p.message),{type:"error"}),_e.delete("wikiEditor")}const c=!Et.has(tA.has(r)?r:"wiki"),h=c&&l,f=new Li(i,h?void 0:r,n,o,c,s);f.dialect=o,a.data("CodeMirror6",f),h&&await f.setLanguage(r,await uv(Zh)),await Promise.all([Tv,Z(f,ps)]),f.prefer([..._e]);const u=localStorage.getItem(ma);return u&&f.setIndent(u),f}},gi=new WeakMap,Dt=new WeakMap,De=new WeakMap,rt=new WeakMap,ps=new WeakMap,Fr=new WeakMap,ms=new WeakMap,Jt=new WeakSet,wf=function(i){this.lang==="mediawiki"&&(this.langConfig=$.extend(!0,{titleParser:_Z(i),isbnParser:LZ},i))},iy=async function(){var h,f,u,d,p;typeof monaco!="object"&&await $.ajax(`${tn}/npm/monaco-wiki@${(f=(h=mw.libs.wphl)==null?void 0:h.monacoVersion)!=null?f:"latest"}/dist/all.min.js`,{dataType:"script",cache:!0});const{textarea:i,lang:r}=this,n=(u=iA[r])!=null?u:r,s=n==="wikitext",o=s||n==="html"||n==="plaintext",a=Z(this,Fr).includes(" "),l="monaco-container";await monaco;for(const g of monaco.editor.getEditors())g.getContainerDomNode().classList.contains(l)&&!((d=g.getDomNode())!=null&&d.isConnected)&&((p=g.getModel())==null||p.dispose(),g.dispose());ze(this,De,monaco.editor.createModel(i.value,n)),ze(this,Dt,document.createElement("div")),Z(this,Dt).className=l,Ze(this,Jt,kf).call(this),i.before(Z(this,Dt)),i.style.display="none",ze(this,rt,monaco.editor.create(Z(this,Dt),{model:Z(this,De),automaticLayout:!0,theme:"monokai",readOnly:i.readOnly,wordWrap:o?"on":"off",wordBreak:"keepAll",tabSize:a?4:Number(Z(this,Fr)),insertSpaces:!a,glyphMargin:!0,fontSize:parseFloat(getComputedStyle(i).fontSize),unicodeHighlight:{ambiguousCharacters:!s&&n!=="html"&&n!=="plaintext"},multiCursorModifier:"ctrlCmd"}));let c;Z(this,De).onDidChangeContent(()=>{clearTimeout(c),c=setTimeout(()=>{i.value=Z(this,De).getValue()},400)}),Hn(this.$toolbar,"lineWrapping",o)},kf=function(){const{textarea:{offsetHeight:i,style:{height:r}}}=this;Z(this,Dt).style.height=i?`${i}px`:r},Da(Li,"version",da),Da(Li,"instances",ui),Li),nA="2.29",sA=["bracketMatching"];mw.loader.load(`${tn}/${ua}/mediawiki.css`,"text/css"),$.valHooks.textarea={get(t){const e=ui.get(t);return e!=null&&e.visible?e.getContent():t.value},set(t,e){const i=ui.get(t);i!=null&&i.visible?i.setContent(e):t.value=e}},document.body.addEventListener("click",t=>{t.target instanceof HTMLTextAreaElement&&t.shiftKey&&!ui.has(t.target)&&(t.preventDefault(),Kn.fromTextArea(t.target))}),(async()=>{var e;const t={minerva:"page-actions-overflow",moeskin:"moe-global-toolbar:visible #p-tb,#moe-mobile-toolbar:visible",citizen:"p-tb"};await Promise.all([mw.loader.using("mediawiki.util"),VZ(tn)]),mw.hook("wiki-codemirror6").add(yv),mw.hook("wiki-codemirror6.setting").add(yv),mw.util.addPortletLink((e=t[mw.config.get("skin")])!=null?e:"p-cactions","#",je("title"),"cm-settings").addEventListener("click",i=>{i.preventDefault();const r=".cm-editor+textarea,.monaco-container+textarea",n=[...document.querySelectorAll(r)];GZ(n.map(s=>ui.get(s)))}),NZ(nA,sA)})(),Object.assign(globalThis,{CodeMirror6:Kn});/**
|
|
42
|
+
`:"");if(o!==void 0)Nh.setSelection.call(this,{start:o,end:a});else if(r&&n&&!t&&!i&&/^\s*=.*=\s*$/u.test(e)){const u=c.getSelection();return c.executeEdits("encapsulateSelection",[{range:u,text:h(u,e),forceMoveMarkers:!0}]),this}const f=c.getSelections().map(u=>{const d=n||u.isEmpty()?e:l.getValueInRange(u),p=h(u,dv(d,t,i,s));return{range:u,text:p,forceMoveMarkers:!0}});return c.executeEdits("encapsulateSelection",f),this},getCaretPosition(t){const{editor:e,model:i}=Ne(this),r=e.getSelection(),n=i.getOffsetAt(r.getEndPosition());return t!=null&&t.startAndEnd?[i.getOffsetAt(r.getStartPosition()),n]:n},scrollToCaretPosition(){const{editor:t}=Ne(this);return t.revealPosition(t.getPosition()),this}},BZ=(()=>{const t=["bold-header","format-leakage","fostered-content","h1","illegal-attr","insecure-style","invalid-gallery","invalid-imagemap","invalid-invoke","invalid-isbn","lonely-apos","lonely-bracket","lonely-http","nested-link","no-arg","no-duplicate","no-ignored","obsolete-attr","obsolete-tag","parsing-order","pipe-like","table-layout","tag-like","unbalanced-header","unclosed-comment","unclosed-quote","unclosed-table","unescaped","unknown-page","unmatched-tag","unterminated-url","url-encoding","var-anchor","void-ext","invalid-css"];return Object.freeze(t),t})(),mv="codemirror-mediawiki-i18n",ua="npm/@bhsd/codemirror-mediawiki@2.29.2",da=ua.slice(ua.lastIndexOf("@")+1),gv=(p0=(d0=mw.language)==null?void 0:d0.getFallbackLanguageChain())!=null?p0:[mw.config.get("wgUserLanguage")],Gn=(m0=vi(mv))!=null?m0:{},{version:Ov}=Gn,VZ=async t=>{try{await If(`${t}/${ua}/i18n`,da,gv,mv,Gn)}catch(e){e instanceof Error&&(mw.notify(e.message,{type:"error"}),console.error(e))}for(const[e,i]of Object.entries(Gn))e.endsWith("-mac")?Ch&&mw.messages.set(`cm-mw-${e.slice(0,-4)}`,i):mw.messages.set(`cm-mw-${e}`,i)},je=(t,...e)=>mw.msg(`cm-mw-${t}`,...e),bv=t=>(t.find("a").add(t.filter("a")).attr("target","_blank"),t);function Ih(t,e){const i=mw.message(`cm-mw-${t}`);return e?i.parse():bv(i.parseDom())}var vv=async(t,...e)=>{const i=bv($("<p>",{html:je(t,...e)}));return await mw.notify(i,{type:"success",autoHideSeconds:"long"}),i},NZ=async(t,e)=>{let i;Ov?e.length>0&&!Nf(Ov,t)&&(i=await vv("welcome-addons",`<a href="https://github.com/bhsd-harry/codemirror-mediawiki/blob/npm/CHANGELOG.md#${da.replace(/\./gu,"")}" target="_blank">${da}</a>`,String(e.length),e.map(r=>`<li>${Ih(`addon-${r}`,!0)}</li>`).join(""))):i=await vv("welcome"),i==null||i.find("#settings").click(r=>{r.preventDefault(),document.getElementById("cm-settings").dispatchEvent(new MouseEvent("click"))})},yv=t=>{t.localize(Object.fromEntries(Object.entries(Gn).filter(([e])=>e.startsWith("phrase-")).map(([e,i])=>[e.slice(7).replace(/-/gu," "),i])))},wv="codemirror-mediawiki-addons",kv="codemirror-mediawiki-monaco",Gh=["wiki","javascript","css","lua","json"],IZ=["Wikitext","JavaScript","CSS","Lua","JSON"],xv="codemirror-mediawiki-wikilint",pa=["ESLint","Stylelint"],Ir=((g0=mw.config.get("wgUserGroups"))==null?void 0:g0.includes("user"))&&mw.config.get("wgUserName"),Sv=Ir?`User:${Ir}/codemirror-mediawiki.json`:void 0,ma="codemirror-mediawiki-indent",_e=new Set(vi(wv)),Et=new Set((O0=vi(kv))!=null?O0:_e.has("useMonaco")?Gh:[]),Ft=(b0=vi(xv))!=null?b0:{},qi=new Map(pa.map(t=>[t,vi(`codemirror-mediawiki-${t}`)])),Un,Uh,ga,Oa,ba,di=(v0=localStorage.getItem(ma))!=null?v0:"",Fh={},Qv=new Map,$v=(t,e)=>{const i=t==="http"||t==="okay-but-empty"?`MediaWiki API request failed: ${t}`:$("<ul>",{html:e.errors.map(({html:r})=>$("<li>",{html:r}))});mw.notify(i,{type:"error",autoHideSeconds:"long"})},Pv=(async()=>{if(Ir)return await mw.loader.using("mediawiki.api"),new mw.Api({parameters:{errorformat:"html",formatversion:"2"}})})(),Tv=(async()=>{if(!Ir)return;const t={action:"query",prop:"revisions",titles:Sv,rvprop:"content",rvlimit:1};(await Pv).get(t).then(e=>{var r,n;const{query:{pages:[i]}}=e;if(i!=null&&i.revisions){const s=JSON.parse(i.revisions[0].content);if(!((r=s.addons)!=null&&r.includes("save")))return;_e.clear();for(const o of s.addons)_e.add(o);Et.clear();for(const o of(n=s.useMonaco)!=null?n:_e.has("useMonaco")?Gh:[])Et.add(o);s.indent&&localStorage.setItem(ma,s.indent);for(const o of pa)s[o]&&qi.set(o,s[o]);s.wikilint&&Object.assign(Ft,s.wikilint)}},$v)})(),GZ=async t=>{if(await mw.loader.using(["oojs-ui-windows","oojs-ui-widgets","oojs-ui.styles.icons-content","mediawiki.jqueryMsg"]),await Tv,Un)ga.setValue([..._e]),Oa.setValue([...Et]),ba.setValue(di);else{Un=new OO.ui.MessageDialog({id:"cm-preference"}),Un.$element.css("z-index","801");const i=new OO.ui.WindowManager;i.$element.appendTo(document.body),i.addWindows([Un]),Uh=new OO.ui.IndexLayout;const r=new OO.ui.TabPanelLayout("main",{label:je("title")}),n=new OO.ui.TabPanelLayout("wikilint",{label:"WikiLint"}),s={};for(const c of pa){const h=qi.get(c);Fh[c]=new OO.ui.MultilineTextInputWidget({value:h?JSON.stringify(h,null,di||" "):""});const f=new OO.ui.FieldLayout(Fh[c],{label:je(`${c}-config`),align:"top"}),u=new OO.ui.TabPanelLayout(c,{label:c,$content:f.$element});u.on("active",d=>{const[p]=u.$element.find("textarea");d&&!ui.has(p)&&(async()=>{const{editor:g}=await Kn.fromTextArea(p,"json");g&&(g.getContainerDomNode().style.height=`${Math.max(g.getContentHeight(),400)}px`)})()}),s[c]=u}Uh.addTabPanels([r,n,...Object.values(s)],0),ga=new OO.ui.CheckboxMultiselectInputWidget({options:[{disabled:!0},...Object.keys(Gn).filter(c=>c!=="addon-indent"&&c!=="addon-useMonaco"&&c.startsWith("addon-")&&!c.endsWith("-mac")).map(c=>({data:c.slice(6),label:Ih(c),disabled:c==="addon-wikiEditor"&&!mw.loader.getState("ext.wikiEditor")||c==="addon-save"&&!Ir}))],value:[..._e]}),Oa=new OO.ui.CheckboxMultiselectInputWidget({options:Gh.map((c,h)=>({data:c,label:IZ[h]})),value:[...Et]}),ba=new OO.ui.TextInputWidget({value:di,placeholder:String.raw`\t`});const o=new OO.ui.FieldLayout(ga,{label:je("label"),align:"top"}),a=new OO.ui.FieldLayout(Oa,{label:je("addon-useMonaco"),align:"top"}),l=new OO.ui.FieldLayout(ba,{label:je("addon-indent")});r.$element.append(o.$element,a.$element,l.$element,$("<p>",{html:je("feedback","codemirror-mediawiki")})),n.$element.append(...BZ.map(c=>{var d,p;const h=c==="no-arg"?"0":"1",f=new OO.ui.DropdownInputWidget({options:[{data:"0",label:je("wikilint-off")},{data:"1",label:je("wikilint-error")},{data:"2",label:je("wikilint-on")}],value:(d=Ft[c])!=null?d:h}),u=new OO.ui.FieldLayout(f,{label:c});return Qv.set(c,f),(p=Ft[c])!=null||(Ft[c]=h),u.$element}),$("<p>",{html:je("feedback","wikiparser-node")}))}const e=await Un.open({message:Uh.$element,actions:[{action:"reject",label:mw.msg("ooui-dialog-message-reject")},{action:"accept",label:mw.msg("ooui-dialog-message-accept"),flags:"progressive"}],size:"medium"}).closing;if(typeof e=="object"&&e.action==="accept"){const i=di,r=_e.has("save");di=ba.getValue();let n=di!==i;if(n){for(const a of t)a==null||a.setIndent(di||" ");localStorage.setItem(ma,di)}for(const[a,l]of Qv){const c=l.getValue();n||(n=c!==Ft[a]),Ft[a]=c}yi(xv,Ft);const s=[];for(const a of pa)try{const l=JSON.parse(Fh[a].getValue().trim()||"null");n||(n=JSON.stringify(l)!==JSON.stringify(qi.get(a))),qi.set(a,l),yi(`codemirror-mediawiki-${a}`,l)}catch{s.push(a)}s.length>0&&OO.ui.alert(je("json-error",s.join(je("and"))));let o=Oa.getValue();if(o.length!==Et.size||!o.every(a=>Et.has(a))){n=!0,Et.clear();for(const a of o)Et.add(a);yi(kv,o)}if(_e.delete("useMonaco"),o=ga.getValue(),o.length!==_e.size||!o.every(a=>_e.has(a))){n=!0,_e.clear();for(const a of o)_e.add(a);for(const a of t)a==null||a.prefer(o)}if(Et.size>0&&_e.add("useMonaco"),o=[..._e],yi(wv,o),n&&Ir&&(r||_e.has("save"))){const a={action:"edit",title:Sv,text:JSON.stringify({addons:o,useMonaco:[...Et],indent:di,wikilint:Ft,ESLint:qi.get("ESLint"),Stylelint:qi.get("Stylelint")}),summary:je("save-summary")};(await Pv).postWithToken("csrf",a).then(()=>{mw.notify(Ih("save-success"),{type:"success"})},$v)}}},Hh=new Map,UZ=(t,e)=>async(i,r=0,n)=>{n&&(i=e+i);try{const[,s]=await t.get({action:"opensearch",search:i,namespace:r,limit:"max"});if(n){const{length:o}=e;return s.map(a=>[a.slice(o)])}return r===0?s.map(o=>[o]):s.map(o=>[new mw.Title(o).getMainText()])}catch{return[]}},FZ=(t,e)=>async i=>{var r,n;i.startsWith("/")&&(i=e+i);try{if(i=new mw.Title(i,10).getPrefixedDb(),Hh.has(i))return Hh.get(i);const{pages:s}=await t.get({action:"templatedata",titles:i,redirects:!0,converttitles:!0,lang:mw.config.get("wgUserLanguage")}),o=Object.entries((n=(r=Object.values(s)[0])==null?void 0:r.params)!=null?n:{}),a=[];for(const[l,{aliases:c,label:h}]of o){const f=h!=null?h:"";a.push([l,f],...c.map(u=>[u,f]))}return Hh.set(i,a),a}catch{return[]}},HZ=async t=>{await mw.loader.using(["mediawiki.api","mediawiki.Title"]);const e=new mw.Api({parameters:{formatversion:2}});return{linkSuggest:UZ(e,t),paramSuggest:FZ(e,t)}},Cv=(t,e,i,r,n)=>({id:t,label:e,keybindings:[monaco.KeyMod.CtrlCmd|monaco.KeyCode[i]],contextMenuGroupId:"1_modification",run(s){const o=s.getModel(),a=s.getSelections().filter(l=>!l.isEmpty());if(a.length===0)s.trigger(t,r,void 0);else{const l=a.map(c=>({range:c,text:n(o.getValueInRange(c))}));s.executeEdits(t,l)}}}),KZ=()=>[Cv("escape.html","Escape HTML Entity","BracketLeft","editor.action.indentLines",mb),Cv("escape.uri","URI Encode/Decode","BracketRight","editor.action.outdentLines",gb)],Fn=new WeakMap,va,JZ=(t,e)=>{if(e&&!Fn.has(t))va!=null||(va=KZ()),Fn.set(t,va.map(i=>t.addAction(i)));else if(e===!1&&Fn.has(t)){for(const i of Fn.get(t))i.dispose();Fn.delete(t)}};function Zv(t,e,i){const r=t==null?void 0:t.find(`${ya(e==="toggle"?"":"more")}>[rel=${e}]`);return i?r==null?void 0:r.children().addBack():r}var Av=(t,e)=>Zv(t,e).hasClass("tool-active"),ya=t=>Array.isArray(t)?t.map(e=>ya(e)).join():`.group-codemirror6${t&&`-${t}`}`,Hn=(t,e,i)=>{var r;(r=Zv(t,e,!0))==null||r.toggleClass("tool-active",i)},Rv=(t,e)=>{t&&(Hn(t,"toggle",e),t.find(ya(["format","more"])).toggle(e),t.find(".group-codeeditor-main").toggle(e===void 0?void 0:!e))},Yi=(t,e,i)=>({type:"button",oouiIcon:t,label:i,action:{type:"callback",execute(r){const n=Ne(r.$textarea);if(typeof e=="function"){e(r,n);return}const[s,o,a]=e;a&&!n.visible?a(r):n.view?s(n.view):n.editor&&n.editor.trigger("wikiEditor",o,void 0)}}}),eA=async(t,e,i)=>{if(!mw.loader.getState("ext.wikiEditor"))throw new Error("no-wikiEditor");let r=t.data("wikiEditorContext");const n=new Promise(a=>{if(r){a();return}t.on("wikiEditor-toolbar-doneInitialSections",()=>{a()})}),s=mw.loader.getState("ext.codeEditor")!==null;if(await Promise.all([mw.loader.using(["ext.wikiEditor","oojs-ui.styles.icons-interactions",...s?["ext.codeEditor.icons"]:[]]),s?new mw.Api().loadMessagesIfMissing(["codeeditor-indent","codeeditor-outdent","codeeditor-invisibleChars-toggle","codeeditor-lineWrapping-toggle","codeeditor-gotoline"]):!1]),r)r.modules.toolbar.$toolbar.find(".group-insert>.tool:not([rel])").hide();else if(typeof mw.addWikiEditor=="function")mw.addWikiEditor(t);else{const{wikiEditor:{modules:{dialogs:{config:a}}}}=$;t.wikiEditor("addModule",{...$.wikiEditor.modules.toolbar.config.getDefaultConfig(),...a.getDefaultConfig()}),a.replaceIcons(t)}await n,r!=null||(r=t.data("wikiEditorContext"));const{$toolbar:o}=r.modules.toolbar;t.wikiEditor("addToToolbar",{section:"main",groups:{codemirror6:{tools:{toggle:Yi("highlight",(a,l)=>{l.toggle()},"CodeMirror 6")}},...s?{"codemirror6-format":{tools:{indent:Yi("indent",[So,"editor.action.indentLines"],mw.msg("codeeditor-indent")),outdent:Yi("outdent",[Qo,"editor.action.outdentLines"],mw.msg("codeeditor-outdent"))}}}:{},"codemirror6-more":{tools:{...s?{invisibleChars:Yi("pilcrow",(a,l)=>{const c=!Av(o,"invisibleChars");l.prefer({highlightSpecialChars:c,highlightWhitespace:c})},mw.msg("codeeditor-invisibleChars-toggle")),lineWrapping:Yi("wrapping",(a,l)=>{const c=!Av(o,"lineWrapping");l.setLineWrapping(c),Hn(o,"lineWrapping",c)},mw.msg("codeeditor-lineWrapping-toggle")),gotoLine:Yi("gotoLine",[cg,"editor.action.gotoLine"],mw.msg("codeeditor-gotoline"))}:{},preferences:Yi("settings",()=>{document.getElementById("cm-settings").click()},je("title"))}},"codemirror6-search":{tools:{cmSearch:Yi("articleSearch",[Ic,"editor.action.startFindReplaceAction",a=>{$.wikiEditor.modules.dialogs.api.openDialog(a,"search-and-replace")}],mw.msg("wikieditor-toolbar-tool-replace"))}}}}),Rv(o,!0),o.toggleClass("codemirror-readonly",e).toggleClass("codemirror-wiki",i).toggleClass("codemirror-coding",!i)},wa={},tA=new Set(["javascript","css","lua","json"]),Wv={"sanitized-css":"css",js:"javascript",scribunto:"lua",wikitext:"mediawiki","proofread-page":"mediawiki"},iA={mediawiki:"wikitext",template:"wikitext",gadget:"javascript",plain:"plaintext"},rA=[["allowMultipleSelections","multiCursorLimit",1,void 0],["autocompletion","quickSuggestions",!1,!0],["bracketMatching","matchBrackets","never","always"],["closeBrackets",["autoClosingBrackets","autoClosingQuotes"],"never","always"],["codeFolding","folding",!1,!0],["colorPicker","colorDecorators",!1,!0],["highlightActiveLine","renderLineHighlight","gutter","all"],["highlightSelectionMatches","occurrencesHighlight","off","singleFile"],["highlightSpecialChars","renderControlCharacters",!1,!0],["highlightWhitespace","renderWhitespace","selection","all"],["openLinks","links",!1,!0],["scrollPastEnd","scrollBeyondLastLine",!1,!0],["hover","hover",{enabled:!1},void 0],["signatureHelp","parameterHints",{enabled:!1},void 0],["inlayHints","inlayHints",{enabled:"offUnlessPressed"},{enabled:"onUnlessPressed"}]],Kh=t=>!t.closest("#cm-preference"),Kn=(Li=class extends cv{constructor(i,r,n,s,o=!0,a=mw.config.get("wgPageName")){var c;if(ui.has(i))throw new RangeError("The textarea has already been replaced by CodeMirror.");const l=h=>{h.textarea===i&&h.destroy()};mw.hook("ext.CodeMirror.ready").add(l);super(i,r,s,!1);we(this,Jt);we(this,gi,!0);we(this,Dt);we(this,De);we(this,rt);we(this,ps);we(this,Fr," ");we(this,ms);this.ns=n,this.page=a,this.$textarea=$(i),ze(this,ms,l),ui.set(i,this),this.initialize(s,!o),Kh(i)?(mw.hook("wiki-codemirror6").fire(this),i.id==="wpTextbox1"&&((c=i.form)==null||c.addEventListener("submit",()=>{const h=document.querySelector("#wpScrolltop");h&&this.view&&Z(this,gi)&&(h.value=String(this.view.scrollDOM.scrollTop))}))):mw.hook("wiki-codemirror6.setting").fire(this)}get visible(){return Z(this,gi)&&this.textarea.isConnected}get model(){return Z(this,De)}get editor(){return Z(this,rt)}get $toolbar(){var i;return(i=this.$textarea.data("wikiEditorContext"))==null?void 0:i.modules.toolbar.$toolbar}initialize(i,r){if(Z(this,De))throw new Error("A Monaco editor is already initialized!");if(r){ze(this,ps,Ze(this,Jt,iy).call(this)),this.$textarea.data("jquery.textSelection",Nh);return}super.initialize(i),Ze(this,Jt,wf).call(this,i);const n=[...this.textarea.classList].find(s=>s.startsWith("mw-editfont-"));n&&this.view.contentDOM.classList.add(n),Hn(this.$toolbar,"lineWrapping",!0)}toggle(i=!Z(this,gi)){const{textarea:r,$textarea:n}=this;Z(this,De)?i&&!Z(this,gi)?(Z(this,De).setValue(r.value),Ze(this,Jt,kf).call(this),Z(this,Dt).style.display="",r.style.display="none",n.data("jquery.textSelection",Nh)):!i&&Z(this,gi)&&(Z(this,Dt).style.display="none",r.style.display="",n.removeData("jquery.textSelection")):(super.toggle(i),n.data("jquery.textSelection",i&&pv)),ze(this,gi,i),Rv(this.$toolbar,i)}destroy(){var i;this.visible&&this.toggle(!1),Z(this,rt)&&(Z(this,rt).dispose(),Z(this,De).dispose(),Z(this,Dt).remove()),this.$textarea.data("CodeMirror6",null),(i=this.$toolbar)==null||i.removeClass(["readonly","wiki","coding"].map(r=>`codemirror-${r}`).join(" ")).find(ya(["","format","more","search"])).remove(),mw.hook("ext.CodeMirror.ready").remove(Z(this,ms)),super.destroy()}async setLanguage(i,r){var s;if(Z(this,De))throw new Error("Cannot change the language of a Monaco editor!");const n=i==="mediawiki"||i==="html";n&&Object.assign(r,await HZ(this.page)),super.setLanguage(i,r),Ze(this,Jt,wf).call(this,r),(s=this.$toolbar)==null||s.toggleClass("codemirror-coding",!n)}setContent(i){Z(this,De)?Z(this,De).setValue(i):super.setContent(i)}getContent(){return this.view?this.view.state.doc.toString():Z(this,De).getValue()}setIndent(i){if(Z(this,rt)){ze(this,Fr,i);const r=i.includes(" ");Z(this,rt).updateOptions({tabSize:r?4:Number(i),insertSpaces:!r})}else super.setIndent(i)}setLineWrapping(i){Z(this,rt)?Z(this,rt).updateOptions({wordWrap:i?"on":"off"}):super.setLineWrapping(i)}async getLinter(i){const r=await super.getLinter(i);return wa[this.lang]=r,r}async defaultLint(i,r=this.ns){if(!i){this.lint();return}const{lang:n}=this,s=n in wa,o=n==="mediawiki";let a,l;if(typeof r=="number"?o&&r!==10&&r!==828&&r!==2?l={include:!1}:n==="javascript"&&(l={...VT,...r===8||r===2300?{parserOptions:{ecmaVersion:8}}:{}}):a=r,a||!s){if(o){const c={getConfig:this.getWikiConfig,i18n:gv};a=a?{...c,...a}:h=>h?Ft:{...c,...l}}else n==="javascript"?a!=null||(a=()=>({...l,...qi.get("ESLint")})):n==="css"&&(a!=null||(a=()=>qi.get("Stylelint")));await this.getLinter(a)}wa[n]&&this.lint(wa[n])}async getWikiConfig(){const[i,r]=await Promise.all([uv(Zh),wikiparse.getConfig()]);return jZ(r,i)}prefer(i){!Kh(this.textarea)&&Array.isArray(i)&&(i=i.filter(l=>l!=="scrollPastEnd"));const r=Array.isArray(i)?l=>i.includes(l):l=>i[l],n=r("lint"),s=r("highlightSpecialChars")&&r("highlightWhitespace"),o=this.lang==="mediawiki";if(s!==void 0&&Hn(this.$toolbar,"invisibleChars",s),this.view){super.prefer(i),n!==void 0&&this.defaultLint(n);return}else{if(!Z(this,rt)||!Z(this,De))throw new Error("The editor is not initialized!");n!==void 0&&Z(this,De).lint&&Z(this,De).lint(n)}o&&JZ(Z(this,rt),r("escape"));const a={};for(const[l,c,h,f]of rA){const u=r(l);if(u!==void 0)if(typeof c=="string")a[c]=u?f:h;else for(const d of c)a[d]=u?f:h}Z(this,rt).updateOptions(a)}static async fromTextArea(i,r,n,s){var d;if(!r&&n===void 0){const{wgAction:p,wgNamespaceNumber:g,wgPageContentModel:b,wgCanonicalSpecialPageName:x}=mw.config.get();p==="edit"||p==="submit"?(n=g,r=g===274?"html":b.toLowerCase()):x==="Upload"?(n=6,r="wikitext"):x==="ExpandTemplates"&&i.name==="wpInput"?(n=0,r="wikitext"):(await mw.loader.using("oojs-ui-windows"),r=(d=await OO.ui.prompt(je("contentmodel"))||void 0)==null?void 0:d.toLowerCase())}let o;r&&r in Wv&&(r==="sanitized-css"&&(o=r),r=Wv[r]);const a=$(i),l=r==="mediawiki"||r==="html";if(_e.has("wikiEditor")&&Kh(i))try{await eA(a,i.readOnly,l)}catch(p){p instanceof Error&&p.message==="no-wikiEditor"&&mw.notify(je(p.message),{type:"error"}),_e.delete("wikiEditor")}const c=!Et.has(tA.has(r)?r:"wiki"),h=c&&l,f=new Li(i,h?void 0:r,n,o,c,s);f.dialect=o,a.data("CodeMirror6",f),h&&await f.setLanguage(r,await uv(Zh)),await Promise.all([Tv,Z(f,ps)]),f.prefer([..._e]);const u=localStorage.getItem(ma);return u&&f.setIndent(u),f}},gi=new WeakMap,Dt=new WeakMap,De=new WeakMap,rt=new WeakMap,ps=new WeakMap,Fr=new WeakMap,ms=new WeakMap,Jt=new WeakSet,wf=function(i){this.lang==="mediawiki"&&(this.langConfig=$.extend(!0,{titleParser:_Z(i),isbnParser:LZ},i))},iy=async function(){var h,f,u,d,p;typeof monaco!="object"&&await $.ajax(`${tn}/npm/monaco-wiki@${(f=(h=mw.libs.wphl)==null?void 0:h.monacoVersion)!=null?f:"latest"}/dist/all.min.js`,{dataType:"script",cache:!0});const{textarea:i,lang:r}=this,n=(u=iA[r])!=null?u:r,s=n==="wikitext",o=s||n==="html"||n==="plaintext",a=Z(this,Fr).includes(" "),l="monaco-container";await monaco;for(const g of monaco.editor.getEditors())g.getContainerDomNode().classList.contains(l)&&!((d=g.getDomNode())!=null&&d.isConnected)&&((p=g.getModel())==null||p.dispose(),g.dispose());ze(this,De,monaco.editor.createModel(i.value,n)),ze(this,Dt,document.createElement("div")),Z(this,Dt).className=l,Ze(this,Jt,kf).call(this),i.before(Z(this,Dt)),i.style.display="none",ze(this,rt,monaco.editor.create(Z(this,Dt),{model:Z(this,De),automaticLayout:!0,theme:"monokai",readOnly:i.readOnly,wordWrap:o?"on":"off",wordBreak:"keepAll",tabSize:a?4:Number(Z(this,Fr)),insertSpaces:!a,glyphMargin:!0,fontSize:parseFloat(getComputedStyle(i).fontSize),unicodeHighlight:{ambiguousCharacters:!s&&n!=="html"&&n!=="plaintext"},multiCursorModifier:"ctrlCmd"}));let c;Z(this,De).onDidChangeContent(()=>{clearTimeout(c),c=setTimeout(()=>{i.value=Z(this,De).getValue()},400)}),Hn(this.$toolbar,"lineWrapping",o)},kf=function(){const{textarea:{offsetHeight:i,style:{height:r}}}=this;Z(this,Dt).style.height=i?`${i}px`:r},Da(Li,"version",da),Da(Li,"instances",ui),Li),nA="2.29",sA=["bracketMatching"];mw.loader.load(`${tn}/${ua}/mediawiki.css`,"text/css"),$.valHooks.textarea={get(t){const e=ui.get(t);return e!=null&&e.visible?e.getContent():t.value},set(t,e){const i=ui.get(t);i!=null&&i.visible?i.setContent(e):t.value=e}},document.body.addEventListener("click",t=>{t.target instanceof HTMLTextAreaElement&&t.shiftKey&&!ui.has(t.target)&&(t.preventDefault(),Kn.fromTextArea(t.target))}),(async()=>{var e;const t={minerva:"page-actions-overflow",moeskin:"moe-global-toolbar:visible #p-tb,#moe-mobile-toolbar:visible",citizen:"p-tb"};await Promise.all([mw.loader.using("mediawiki.util"),VZ(tn)]),mw.hook("wiki-codemirror6").add(yv),mw.hook("wiki-codemirror6.setting").add(yv),mw.util.addPortletLink((e=t[mw.config.get("skin")])!=null?e:"p-cactions","#",je("title"),"cm-settings").addEventListener("click",i=>{i.preventDefault();const r=".cm-editor+textarea,.monaco-container+textarea",n=[...document.querySelectorAll(r)];GZ(n.map(s=>ui.get(s)))}),NZ(nA,sA)})(),Object.assign(globalThis,{CodeMirror6:Kn});/**
|
|
43
43
|
* @file Configuration for the MediaWiki highlighting mode for CodeMirror.
|
|
44
44
|
* @author MusikAnimal and others
|
|
45
45
|
* @license GPL-2.0-or-later
|