docs: explain shared CatWar utility functions
This commit is contained in:
1 parent
c3603692a2
commit
06229ed658
1 file changed
+26
@@ -3170,6 +3170,7 @@
|
|||||||
$('#cw3BkgPos').val(globals.cw3BkgPos);
|
$('#cw3BkgPos').val(globals.cw3BkgPos);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Imports a selected settings dataset after validation and confirmation.
|
||||||
function mergeData(dataKey) {
|
function mergeData(dataKey) {
|
||||||
$(`[data-result]`).empty();
|
$(`[data-result]`).empty();
|
||||||
let exp = $(`[data-export="${dataKey}"]`).val();
|
let exp = $(`[data-export="${dataKey}"]`).val();
|
||||||
@@ -3238,6 +3239,7 @@
|
|||||||
mergeDataDone(dataKey, text);
|
mergeDataDone(dataKey, text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Checks imported settings for the expected schema before applying them.
|
||||||
function mergeDataValidate(dataKey, data) {
|
function mergeDataValidate(dataKey, data) {
|
||||||
let error = false
|
let error = false
|
||||||
, text = [];
|
, text = [];
|
||||||
@@ -3289,6 +3291,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Displays a localized import error and identifies the failing data key.
|
||||||
function mergeDataError(dataKey, type, text = []) {
|
function mergeDataError(dataKey, type, text = []) {
|
||||||
let errorText = 'Ошибка: ';
|
let errorText = 'Ошибка: ';
|
||||||
const errors = {
|
const errors = {
|
||||||
@@ -3299,12 +3302,14 @@
|
|||||||
$(`[data-result="${dataKey}"]`).append(`<p class="cwmod-error">${errorText}</p>${text.join('<br>')}`);
|
$(`[data-result="${dataKey}"]`).append(`<p class="cwmod-error">${errorText}</p>${text.join('<br>')}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Completes a settings import, persists it, and reports success to the user.
|
||||||
function mergeDataDone(dataKey, text = []) {
|
function mergeDataDone(dataKey, text = []) {
|
||||||
let resultText = 'Данные успешно объединены';
|
let resultText = 'Данные успешно объединены';
|
||||||
if (dataKey === 'settings') resultText = 'Настройки успешно обновлены';
|
if (dataKey === 'settings') resultText = 'Настройки успешно обновлены';
|
||||||
$(`[data-result="${dataKey}"]`).append(`<p class="cwmod-done">${resultText}!</p>${text.join('<br>')}`);
|
$(`[data-result="${dataKey}"]`).append(`<p class="cwmod-done">${resultText}!</p>${text.join('<br>')}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Adds or replaces a named style block used by a configurable feature.
|
||||||
function addCSS(css, key) {
|
function addCSS(css, key) {
|
||||||
const styleId = key ? 'cwmod-style-' + key : 'cwmod-style';
|
const styleId = key ? 'cwmod-style-' + key : 'cwmod-style';
|
||||||
const style = $('#' + styleId);
|
const style = $('#' + styleId);
|
||||||
@@ -3316,10 +3321,12 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Removes the named feature style block when that feature is disabled.
|
||||||
function removeCSS(key) {
|
function removeCSS(key) {
|
||||||
$('#cwmod-style-' + key).remove();
|
$('#cwmod-style-' + key).remove();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Loads persisted settings and merges them with current defaults.
|
||||||
function loadSettings() {
|
function loadSettings() {
|
||||||
const key = 'cwmod_settings';
|
const key = 'cwmod_settings';
|
||||||
try {
|
try {
|
||||||
@@ -3340,6 +3347,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Saves one setting value and refreshes the storage-backed state object.
|
||||||
function saveData(key, data) {
|
function saveData(key, data) {
|
||||||
try {
|
try {
|
||||||
window.localStorage.setItem('cwmod_' + key, JSON.stringify(data));
|
window.localStorage.setItem('cwmod_' + key, JSON.stringify(data));
|
||||||
@@ -3349,6 +3357,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Shows the short confirmation used after a preference is saved.
|
||||||
function addSaveAlert() {
|
function addSaveAlert() {
|
||||||
window.addEventListener('beforeunload', beforeunload);
|
window.addEventListener('beforeunload', beforeunload);
|
||||||
$('input[type=submit]').click(function() {
|
$('input[type=submit]').click(function() {
|
||||||
@@ -3362,12 +3371,14 @@
|
|||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tests the current URL against a page name and optional match fragment.
|
||||||
function isPage(page, match) {
|
function isPage(page, match) {
|
||||||
if (page instanceof RegExp) return page.test(window.location.href);
|
if (page instanceof RegExp) return page.test(window.location.href);
|
||||||
const re = new RegExp('catwar\.su/' + page.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + (match ? '(#.*)?$' : ''));
|
const re = new RegExp('catwar\.su/' + page.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + (match ? '(#.*)?$' : ''));
|
||||||
return re.test(window.location.href);
|
return re.test(window.location.href);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Converts seconds into the localized hours/minutes/seconds display.
|
||||||
function secToTime(sec) {
|
function secToTime(sec) {
|
||||||
if (!sec) return '0 c';
|
if (!sec) return '0 c';
|
||||||
const d = Math.floor(convertTime('s d', sec));
|
const d = Math.floor(convertTime('s d', sec));
|
||||||
@@ -3385,19 +3396,23 @@
|
|||||||
return result.join(' ');
|
return result.join(' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pads a numeric time component to two characters.
|
||||||
function leadingZero(num) {
|
function leadingZero(num) {
|
||||||
return num < 10 ? '0' + num.toString() : num;
|
return num < 10 ? '0' + num.toString() : num;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Escapes text before inserting it into HTML markup.
|
||||||
function escapeHTML(str) {
|
function escapeHTML(str) {
|
||||||
return str.replace('<', '$lt;').replace('>', '$gt;');
|
return str.replace('<', '$lt;').replace('>', '$gt;');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Decodes HTML entities when importing text from the game DOM.
|
||||||
function decodeHTML(str) {
|
function decodeHTML(str) {
|
||||||
const doc = new DOMParser().parseFromString(str, "text/html");
|
const doc = new DOMParser().parseFromString(str, "text/html");
|
||||||
return doc.documentElement.textContent;
|
return doc.documentElement.textContent;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Looks up a locally saved note by cat ID.
|
||||||
function getNoteByCatId(catId) {
|
function getNoteByCatId(catId) {
|
||||||
try {
|
try {
|
||||||
const savedNotes = JSON.parse(window.localStorage.getItem('cwmod_notes') || '{}');
|
const savedNotes = JSON.parse(window.localStorage.getItem('cwmod_notes') || '{}');
|
||||||
@@ -3409,6 +3424,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Inserts the selected BBCode wrapper around the active editor selection.
|
||||||
function addBBcode(type) {
|
function addBBcode(type) {
|
||||||
const bb = $('.bbcode').parent();
|
const bb = $('.bbcode').parent();
|
||||||
if (!bb.length) return;
|
if (!bb.length) return;
|
||||||
@@ -3441,6 +3457,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Resolves and inserts the avatar image for a cat into matching elements.
|
||||||
function setAvatar(catId, selector) {
|
function setAvatar(catId, selector) {
|
||||||
$.get('/cat' + catId.toString()
|
$.get('/cat' + catId.toString()
|
||||||
, function(data) {
|
, function(data) {
|
||||||
@@ -3458,6 +3475,7 @@
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Resolves a cat name and updates matching labels while preserving fallback text.
|
||||||
function setCatName(catId, selector, oldName) {
|
function setCatName(catId, selector, oldName) {
|
||||||
$.post('/preview', {
|
$.post('/preview', {
|
||||||
text: `[link${catId}]`
|
text: `[link${catId}]`
|
||||||
@@ -3470,6 +3488,7 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Requests a cat ID by name and invokes the callback with the result.
|
||||||
function getCatIdByName(name, callback) {
|
function getCatIdByName(name, callback) {
|
||||||
$.post('/ajax/top_cat', {
|
$.post('/ajax/top_cat', {
|
||||||
name: name
|
name: name
|
||||||
@@ -3479,6 +3498,7 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Resolves the current user's cat identity for features needing an owner ID.
|
||||||
function getCurrentUser(callback) {
|
function getCurrentUser(callback) {
|
||||||
$.get('/'
|
$.get('/'
|
||||||
, function(data) {
|
, function(data) {
|
||||||
@@ -3492,12 +3512,14 @@
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Formats a Date object as the compact calendar string used by the mod.
|
||||||
function dateToString(date) {
|
function dateToString(date) {
|
||||||
if (typeof date === 'number') date = new Date(date);
|
if (typeof date === 'number') date = new Date(date);
|
||||||
const dateString = date.toISOStringLocal();
|
const dateString = date.toISOStringLocal();
|
||||||
return dateString.slice(0, 16);
|
return dateString.slice(0, 16);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Selects the correct Russian plural form for a numeric value.
|
||||||
function declOfNum(n, titles) {
|
function declOfNum(n, titles) {
|
||||||
n = Math.abs(n);
|
n = Math.abs(n);
|
||||||
if (isNaN(n)) return titles[2];
|
if (isNaN(n)) return titles[2];
|
||||||
@@ -3510,6 +3532,7 @@
|
|||||||
return titles[2];
|
return titles[2];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Converts a duration between the mod's supported time units.
|
||||||
function convertTime(units, val) {
|
function convertTime(units, val) {
|
||||||
const allUnits = ['ms', 's', 'm', 'h', 'd'];
|
const allUnits = ['ms', 's', 'm', 'h', 'd'];
|
||||||
units = units.split(' ');
|
units = units.split(' ');
|
||||||
@@ -3529,16 +3552,19 @@
|
|||||||
return val;
|
return val;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Extracts a recognizable date from free-form game text.
|
||||||
function findDate(text) {
|
function findDate(text) {
|
||||||
return text.match(/(\d?\d )?[а-я]+ (\d{4} )?в \d?\d:\d\d/i)[0];
|
return text.match(/(\d?\d )?[а-я]+ (\d{4} )?в \d?\d:\d\d/i)[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Converts CatWar calendar components into an absolute millisecond value.
|
||||||
function catTimeToMs(y, m, d, h, min, s) {
|
function catTimeToMs(y, m, d, h, min, s) {
|
||||||
// отсчёт месяцев с 0, дней с 1
|
// отсчёт месяцев с 0, дней с 1
|
||||||
const result = (((((((y * 12 + m) * 28 + --d) * 24 + h) * 60) + min) * 60) + s) * 1000 / 7;
|
const result = (((((((y * 12 + m) * 28 + --d) * 24 + h) * 60) + min) * 60) + s) * 1000 / 7;
|
||||||
return Math.round(result);
|
return Math.round(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Converts an absolute timestamp back into CatWar calendar components.
|
||||||
function timestampToCatTime(timestamp) {
|
function timestampToCatTime(timestamp) {
|
||||||
const secInYear = 12 * 28 * 24 * 60 * 60;
|
const secInYear = 12 * 28 * 24 * 60 * 60;
|
||||||
const secInMonth = 28 * 24 * 60 * 60;
|
const secInMonth = 28 * 24 * 60 * 60;
|
||||||
|
|||||||
Reference in new issue
Block a user