Користувач:MonAx/translatedTemplate.js
Зовнішній вигляд
Увага: Після публікування слід очистити кеш браузера, щоб побачити зміни.
- Firefox / Safari: тримайте Shift, коли натискаєте Оновити, або натисніть Ctrl-F5 чи Ctrl-Shift-R (⌘-R на Apple Mac)
- Google Chrome: натисніть Ctrl-Shift-R (⌘-Shift-R на Apple Mac)
- Edge: тримайте Ctrl, коли натискаєте Оновити, або натисніть Ctrl-F5.
//<nowiki>
(function(){
const translatedTemplateApp = {
data: function() {
return {
showDialog: false,
interwiki: {},
langList: [],
articleName: "",
selectedCode: null,
currentStep: 0
};
},
template: `
<cdx-dialog v-model:open="showDialog"
title="Виберіть мову"
close-button-label="Скасувати"
:default-action="defaultAction"
@default="open = false"
>
<template v-if="currentStep === 0">
<div id="translatedTemplateDialog">
<cdx-label
input-id="translatedTemplateLookup">
Код мови
</cdx-label>
<cdx-lookup
id="translatedTemplateLookup"
:menu-items="langList"
v-model:selected="selectedCode"
@input="onLookupInput">
<template #no-results>Мову не знайдено</template>
</cdx-lookup>
<cdx-label
input-id="translatedTemplateTextInput"
style="margin-top:1em">
Назва статті
</cdx-label>
<cdx-text-input
v-model="articleName"
id="translatedTemplateTextInput">
</cdx-text-input>
</div>
<p style="margin-top:1em; text-align:right;">
<cdx-button action="destructive" @click="closeDialog">Скасувати</cdx-button>
<cdx-button action="progressive" @click="save" style="margin-left:1em">Зберегти</cdx-button>
</p>
</template>
<template v-if="currentStep === 1">
<cdx-progress-bar></cdx-progress-bar>
</template>
</cdx-dialog>
`,
methods: {
openDialog () {
this.showDialog = true;
},
closeDialog () {
this.showDialog = false;
},
onLookupInput (input) {
//console.log(`onLookupInput, input: ${input}`);
entries = Object.entries(this.interwiki).map(([lang, title]) => ({
label: `${lang}: ${title}`,
value: lang
}));
if (input) {
entries = entries.filter((el) => el.value.includes(input));
}
this.langList = entries;
//console.log(this.selectedCode);
if (this.interwiki[this.selectedCode]) {
this.articleName = this.interwiki[this.selectedCode];
}
},
save () {
this.currentStep = 1;
talkPagePrefix = "Обговорення:";
talkPagePostfix = "";
switch (mw.config.get('wgNamespaceNumber')) {
case 4:
case 5:
talkPagePrefix = "Обговорення Вікіпедії:";
break;
case 10:
talkPagePrefix = "Шаблон:";
if (!mw.config.get('wgTitle').includes("/doc") &&
!mw.config.get('wgTitle').includes("/документація")) {
talkPagePostfix = "/документація";
}
// TODO: має бути перевірка, чи є вже документація у "/doc",
// для сторінки власне шаблону
// Поки сподіватимусь на обачність користувачів скрипта
break;
case 12:
case 13:
talkPagePrefix = "Обговорення довідки:";
break;
case 14:
case 15:
talkPagePrefix = "Обговорення категорії:";
break;
case 828:
talkPagePrefix = "Модуль:";
if (!mw.config.get('wgTitle').includes("/doc") &&
!mw.config.get('wgTitle').includes("/документація")) {
talkPagePostfix = "/документація";
}
break;
}
const talkPage = talkPagePrefix + mw.config.get('wgTitle') + talkPagePostfix;
new mw.Api().edit(talkPage, revision => ({
text: `{{Перекладена стаття|${this.selectedCode}|${this.articleName}}}\n` + revision.content,
summary: '[[Користувач:MonAx/translatedTemplate.js|Скрипт]]: вставка шаблону Перекладена стаття',
assert: 'user'
}))
.done(() => setTimeout(() => location.reload(), 1000))
.fail(err => {
if (err === 'nocreate-missing') {
new mw.Api().create(
talkPage,
{ summary: '[[Користувач:MonAx/translatedTemplate.js|Скрипт]]: створення сторінки обговорення та вставка шаблону Перекладена стаття' },
`{{Перекладена стаття|${this.selectedCode}|${this.articleName}}}`
)
.done(() => setTimeout(() => location.reload(), 1000))
.fail(error => this.editErrors(error, talkPage));
} else {
mw.notify(err);
}
});
},
},
mounted() {
const dialogTrigger = mw.util.addPortletLink( 'p-tb', '#', '{{Перекладена стаття}}', 'p-translate-dialog' );
dialogTrigger.addEventListener( 'click', this.openDialog);
document.querySelectorAll('.interlanguage-link').forEach(el => {
const link = el.tagName === 'A' ? el : el.querySelector('a');
if (!link) return;
const href = link.href;
let title = href.split('/').pop();
title = decodeURIComponent(title).replace(/_/g, ' ');
let lang = link.lang;
this.interwiki[lang] = title;
});
this.onLookupInput(); // initial item list
},
unMounted() {
dialogTrigger.removeEventListener( this.openDialog );
}
};
function init() {
window.translatedTemplate = window.translatedTemplate || {};
if ( translatedTemplate.isRunning ) return;
translatedTemplate.isRunning = true;
const mountPoint = document.body.appendChild( document.createElement( 'div' ) );
const { CdxButton, CdxDialog, CdxLookup, CdxTextInput, CdxLabel, CdxProgressBar } = mw.loader.require( '@wikimedia/codex' );
const { createMwApp } = mw.loader.require( 'vue' );
mw.loader.using( ['vue', '@wikimedia/codex'] ).then( function( require ) {
Vue.createMwApp( translatedTemplateApp )
.component( 'cdx-button', CdxButton )
.component( 'cdx-dialog', CdxDialog )
.component( 'cdx-lookup', CdxLookup )
.component( 'cdx-text-input', CdxTextInput )
.component( 'cdx-label', CdxLabel )
.component( 'cdx-progress-bar', CdxProgressBar )
.mount( mountPoint );
} );
}
// Працює у основному просторі, "Вікіпедія", "Довідка", "Категорія".
// Також для шаблонів і модулів, але на сторінці документації
if ([0,1,4,5,10,12,13,14,15,828].includes(mw.config.get('wgNamespaceNumber'))) {
mw.hook( 'wikipage.content' ).add( init );
}
}());
//</nowiki>