add jsdoc comments

This commit is contained in:
lchen committed 2026-11-18 10:14:21 +08:00
1 parent 6de354ad47
commit 8c1205bc13
24 files changed
+1228 -425

No files matched your search

+15 -1
View File
@@ -1,3 +1,10 @@
/**
* @param {string} name
* @param {string} value
* @param {number} [expireDays]
* @param {string} [host]
* @param {boolean} [encode]
*/
export function setCookie(name, value, expireDays, host, encode) {
if (name == null) {
return;
@@ -6,7 +13,7 @@ export function setCookie(name, value, expireDays, host, encode) {
if (expireDays != null) {
const d = new Date();
d.setTime(d.getTime() + (expireDays * 24 * 60 * 60 * 1000));
extra += `; expires=${d.toGMTString()}`;
extra += `; expires=${d.toUTCString()}`;
}
if (/^(https|wss):$/.test(location.protocol)) {
extra += '; secure';
@@ -17,6 +24,10 @@ export function setCookie(name, value, expireDays, host, encode) {
document.cookie = `${name}=${value}${extra}`;
}
/**
* @param {string} [name]
* @returns {string | null}
*/
export function getCookie(name) {
if (name == null) {
return null;
@@ -32,6 +43,9 @@ export function getCookie(name) {
return null;
}
/**
* @param {string} name
*/
export function deleteCookie(name) {
setCookie(name, '', -1);
}
+94 -15
View File
@@ -2,14 +2,19 @@ import { getCookie } from "./cookie";
import { get } from "./request";
import { nullOrEmpty } from "./strings";
/** @typedef {import('../types').LanguageResource} LanguageResource */
const g = typeof window !== 'undefined' ? window : self;
/** @type {LanguageResource} */
let cache;
function getCurrentLgId() {
let lgid;
if (typeof consts !== 'undefined') {
lgid = getCookie(consts.cookie?.lang);
if (typeof g.consts !== 'undefined') {
lgid = getCookie(g.consts.cookie?.lang);
if (nullOrEmpty(lgid)) {
lgid = consts.user?.language;
lgid = g.consts.user?.language;
}
}
if (nullOrEmpty(lgid)) {
@@ -42,13 +47,23 @@ function getCurrentLgId() {
return 'en';
}
/**
* @private
* @param {"en" | "en_au" | "en_ca" | "fr_ca" | "zh_cn" | "es" | "fr" | "pt"} lgid
* @returns {string}
*/
function getStorageKey(lgid) {
if (typeof consts !== 'undefined') {
return (consts.prefix || '') + `res_${lgid}`;
if (typeof g.consts !== 'undefined') {
return (g.consts.prefix || '') + `res_${lgid}`;
}
return `res_${lgid}`;
}
/**
* @private
* @param {string} [template]
* @returns {Promise<LanguageResource>}
*/
async function doRefreshLgres(template = '') {
const lgid = getCurrentLgId();
const url = template.length > 0 ? template.replace('{lgid}', lgid) : `language/${lgid}`;
@@ -58,21 +73,27 @@ async function doRefreshLgres(template = '') {
return dict;
}
/**
*
* @param {string} [template]
* @param {LanguageResource | null} [lgres]
* @returns {Promise<LanguageResource>}
*/
async function refreshLgres(template, lgres) {
if (lgres == null || typeof consts === 'undefined') {
if (lgres == null || typeof g.consts === 'undefined') {
lgres = await doRefreshLgres(template);
}
const ver = Number(consts.resver);
const ver = Number(g.consts?.resver);
const currentVer = Number(lgres.ver);
if (isNaN(currentVer) || isNaN(ver) || ver > currentVer) {
console.log(`found new language res version: ${lgres.ver} => ${consts.resver}`);
console.log(`found new language res version: ${lgres.ver} => ${g.consts?.resver}`);
lgres = await doRefreshLgres(template);
}
Object.defineProperty(lgres, 'r', {
writable: false,
configurable: false,
enumerable: false,
value: function (key, defaultValue) {
value: function (/** @type {string} */ key, /** @type {string | undefined} */ defaultValue) {
return getLanguage(this, key, defaultValue);
}
});
@@ -80,15 +101,47 @@ async function refreshLgres(template, lgres) {
return lgres;
}
/**
* @private
* @param {LanguageResource} lgres
* @param {string} [key]
* @param {string | null} [defaultValue]
* @returns {string}
*/
function getLanguage(lgres, key, defaultValue) {
if (key == null) {
return '';
}
let value = lgres[key];
return value ?? defaultValue;
if (value != null && typeof value !== 'string') {
value = String(value);
}
return value ?? defaultValue ?? '';
}
/**
* @private
* @template {keyof HTMLElementTagNameMap} K
* @param {Element} element
* @param {K} tagName
* @returns {element is HTMLElementTagNameMap[K]}
*/
export function isTag(element, tagName) {
return element.tagName.toLowerCase() === tagName;
}
/**
* @private
* @param {HTMLElement} dom
* @param {LanguageResource} result
*/
function applyLanguage(dom, result) {
for (let text of dom.querySelectorAll('[data-lgid]')) {
if (!(text instanceof HTMLElement)) {
continue;
}
const key = text.dataset.lgid;
if (text.tagName === 'INPUT') {
if (isTag(text, 'input')) {
text.value = getLanguage(result, key, text.value);
} else {
text.innerText = getLanguage(result, key, text.innerText);
@@ -97,12 +150,18 @@ function applyLanguage(dom, result) {
text.dataset.lgid = '';
}
for (let title of dom.querySelectorAll('[data-title-lgid]')) {
if (!(title instanceof HTMLElement)) {
continue;
}
const key = title.dataset.titleLgid;
title.setAttribute('title', getLanguage(result, key, title.getAttribute('title')));
// delete title.dataset.titleLgid;
title.dataset.titleLgid = '';
}
for (let holder of dom.querySelectorAll('[data-placeholder-lgid]')) {
if (!(holder instanceof HTMLElement)) {
continue;
}
const key = holder.dataset.placeholderLgid;
holder.setAttribute('placeholder', getLanguage(result, key, holder.getAttribute('placeholder')));
// delete holder.dataset.placeholderLgid;
@@ -110,9 +169,13 @@ function applyLanguage(dom, result) {
}
}
/**
* @returns {Promise<void>}
*/
export function domLoad() {
if (document.readyState === 'loading') {
return new Promise((resolve, reject) => {
/** @type {number | undefined} */
let tid = setTimeout(() => reject('timeout'), 30000);
document.addEventListener('DOMContentLoaded', () => {
clearTimeout(tid);
@@ -124,13 +187,24 @@ export function domLoad() {
return Promise.resolve();
}
/**
* @typedef LgresOptions
* @property {string} [template]
* @property {(result: LanguageResource) => void} [callback]
*/
/**
* @param {HTMLElement} dom
* @param {LgresOptions} options
* @returns
*/
export async function init(dom = document.body, options = {}) {
const lgid = getCurrentLgId();
let lgres = localStorage.getItem(getStorageKey(lgid));
const json = localStorage.getItem(getStorageKey(lgid));
let result;
if (lgres != null) {
if (json != null) {
try {
lgres = JSON.parse(lgres);
const lgres = JSON.parse(json);
result = await refreshLgres(options.template, lgres);
} catch (e) {
console.error('error while parsing lgres, try refresh ...', e);
@@ -152,11 +226,16 @@ export async function init(dom = document.body, options = {}) {
}
}
/**
* @param {string} key
* @param {string | null} [defaultValue]
* @returns {string}
*/
export function r(key, defaultValue) {
if (cache != null) {
return getLanguage(cache, key, defaultValue);
}
return defaultValue;
return defaultValue ?? '';
}
export const lang = {
+60 -21
View File
@@ -1,28 +1,63 @@
const g = typeof window !== 'undefined' ? window : self;
/**
* @private
* @param {string} url
* @returns {string}
*/
function combineUrl(url) {
if (/^(https?|wss?|ftp):/.test(url)) {
return url;
}
if (typeof consts === 'undefined') {
if (typeof g.consts === 'undefined') {
return url;
}
return (consts.path || '') + url;
return (g.consts.path || '') + url;
}
export function get(url, options = {}) {
/**
* @typedef RequestOptions
* @property {string} [method]
* @property {string} [accept]
* @property {Object.<string, string>} [customHeaders]
* @property {RequestMode} [mode]
* @property {AbortSignal | null} [signal]
* @property {boolean} [diagnostic]
* @property {(this: XMLHttpRequestUpload, e: ProgressEvent<XMLHttpRequestEventTarget>) => any} [progress]
*/
/**
* @param {string} url
* @param {RequestOptions} [options]
* @returns {Promise<Response>}
*/
export function get(url, options) {
return fetch(combineUrl(url), {
method: options.method || 'GET',
method: options?.method || 'GET',
headers: {
...options.customHeaders,
'Accept': options.accept ?? 'application/json'
...options?.customHeaders,
'Accept': options?.accept ?? 'application/json'
},
mode: options.mode,
signal: options.signal,
mode: options?.mode,
signal: options?.signal,
cache: 'default'
});
}
export function post(url, data, options = {}) {
// let contentType;
/**
* @typedef DiagnosedResponse
* @property {number} time
* @property {Response} response
*/
/**
* @param {string} url
* @param {BodyInit | null} [data]
* @param {RequestOptions} [options]
* @returns {Promise<Response | DiagnosedResponse>}
*/
export function post(url, data, options) {
const headers = options?.customHeaders ?? {};
if (data instanceof FormData) {
// contentType = 'multipart/form-data';
} else {
@@ -30,21 +65,19 @@ export function post(url, data, options = {}) {
data = JSON.stringify(data);
}
// contentType = 'application/json';
if (options.customHeaders == null) {
options.customHeaders = {};
}
if (options.customHeaders['Content-Type'] == null) {
options.customHeaders['Content-Type'] = 'application/json';
if (headers['Content-Type'] == null) {
headers['Content-Type'] = 'application/json';
}
}
/** @type {RequestInit} */
const opts = {
method: options.method || 'POST',
headers: options.customHeaders,
method: options?.method || 'POST',
headers,
body: data,
signal: options.signal,
signal: options?.signal,
cache: 'no-cache'
};
if (options.diagnostic) {
if (options?.diagnostic) {
const started = new Date().getTime();
return new Promise((resolve, reject) => {
fetch(combineUrl(url), opts).then(response => {
@@ -58,7 +91,13 @@ export function post(url, data, options = {}) {
return fetch(combineUrl(url), opts);
}
export function upload(url, data, options = {}) {
/**
* @param {string} url
* @param {FormData} data
* @param {RequestOptions} options
* @returns {Promise<XMLHttpRequest>}
*/
export function upload(url, data, options) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.onreadystatechange = function () {
@@ -73,7 +112,7 @@ export function upload(url, data, options = {}) {
if (typeof options.progress === 'function') {
request.upload.addEventListener('progress', function (ev) {
if (ev.lengthComputable) {
options.progress.call(this, ev);
options.progress?.call(this, ev);
}
}, false);
}
+41 -7
View File
@@ -1,7 +1,17 @@
/**
* @param {string | null} [s]
* @returns {s is null | undefined | ""}
*/
export function nullOrEmpty(s) {
return s == null || typeof s !== 'string' || s.length === 0;
}
/**
* @param {string} s
* @param {string} key
* @param {boolean} [ignoreCase]
* @returns {boolean}
*/
export function contains(s, key, ignoreCase) {
if (nullOrEmpty(s) || key == null) {
return false;
@@ -15,6 +25,11 @@ export function contains(s, key, ignoreCase) {
return s.includes(key);
}
/**
* @param {string} s
* @param {string} suffix
* @returns {boolean}
*/
export function endsWith(s, suffix) {
if (nullOrEmpty(s) || nullOrEmpty(suffix)) {
return false;
@@ -22,6 +37,12 @@ export function endsWith(s, suffix) {
return s.endsWith(suffix); // === s.length - suffix.length;
}
/**
* @param {string} s
* @param {number} num
* @param {string} char
* @returns {string}
*/
export function padStart(s, num, char) {
if (nullOrEmpty(s) || isNaN(num) || num <= s.length) {
return s;
@@ -29,6 +50,10 @@ export function padStart(s, num, char) {
return (char ?? ' ').repeat(num - s.length);
}
/**
* @param {string} msg
* @returns {string}
*/
export function formatUrl(msg) {
//const urlReg = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ig;
//const urlArrray = str.match(urlReg);
@@ -36,7 +61,7 @@ export function formatUrl(msg) {
const r = msg.match(p);
msg = escapeHtml(msg);
if (r?.length > 0) {
if (r != null && r.length > 0) {
const rs = [];
for (let t of r) {
t = t.replace(/["'\r\n ]/g, '');
@@ -45,13 +70,14 @@ export function formatUrl(msg) {
}
}
const win = typeof window !== 'undefined' ? window : self;
let path;
if (typeof consts !== 'undefined') {
path = consts.path;
} else if (typeof _network !== 'undefined') {
path = _network.root;
} else if (typeof _net !== 'undefined') {
path = _net.root;
if (typeof win.consts !== 'undefined') {
path = win.consts.path;
} else if (typeof win._network !== 'undefined') {
path = win._network.root;
} else if (typeof win._net !== 'undefined') {
path = win._net.root;
}
for (let r of rs) {
msg = msg.replaceAll(r, `<a target="_blank" href="${r}"><svg><use xlink:href="${path || ''}fonts/fa-regular.svg#link"></use></svg></a>`);
@@ -61,6 +87,10 @@ export function formatUrl(msg) {
return msg;
}
/**
* @param {string} text
* @returns {string}
*/
export function escapeHtml(text) {
if (text == null) {
return '';
@@ -74,6 +104,10 @@ export function escapeHtml(text) {
.replaceAll(' ', '&nbsp;');
}
/**
* @param {string} text
* @returns {string}
*/
export function escapeEmoji(text) {
if (text == null) {
return '';