foundryvtt-reve-de-dragon/module/misc.js

259 lines
7.0 KiB
JavaScript
Raw Normal View History

import { Grammar } from "./grammar.js";
/**
* This class is intended as a placeholder for utility methods unrelated
* to actual classes of the game system or of FoundryVTT
*/
export class Misc {
static isFunction(v) {
return v && {}.toString.call(v) === '[object Function]';
}
static upperFirst(text) {
return text.charAt(0).toUpperCase() + text.slice(1);
}
2021-06-30 01:01:24 +02:00
static lowerFirst(text) {
return text.charAt(0).toLowerCase() + text.slice(1);
}
static toSignedString(number) {
const value = parseInt(number)
const isPositiveNumber = value != NaN && value > 0;
return isPositiveNumber ? "+" + number : number
}
static modulo(n, m) {
return ((n % m) + m) % m;
}
2021-03-29 18:08:18 +02:00
static sum() {
return (a, b) => Number(a) + Number(b);
2021-03-29 18:08:18 +02:00
}
2021-05-11 21:45:43 +02:00
static ascending(orderFunction = x => x) {
2021-03-29 18:08:18 +02:00
return (a, b) => Misc.sortingBy(orderFunction(a), orderFunction(b));
2021-05-11 21:45:43 +02:00
}
2021-03-29 18:08:18 +02:00
2021-05-11 21:45:43 +02:00
static descending(orderFunction = x => x) {
2021-03-29 18:08:18 +02:00
return (a, b) => Misc.sortingBy(orderFunction(b), orderFunction(a));
2021-05-11 21:45:43 +02:00
}
2021-03-29 18:08:18 +02:00
static sortingBy(a, b) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
}
static typeName(type, subType) {
2023-06-20 02:59:26 +02:00
return subType ? game.i18n.localize(`TYPES.${type}.${Misc.upperFirst(subType)}`)
: '';
}
2022-12-28 23:36:48 +01:00
static arrayOrEmpty(items) {
return items?.length ? items : [];
}
/**
* Converts the value to an integer, or to 0 if undefined/null/not representing integer
* @param {*} value value to convert to an integer using parseInt
*/
static toInt(value) {
if (value == undefined) {
return 0;
}
const parsed = parseInt(value);
return isNaN(parsed) ? 0 : parsed;
}
2021-04-11 23:01:10 +02:00
static keepDecimals(num, decimals) {
2021-05-11 21:45:43 +02:00
if (decimals <= 0 || decimals > 6) return num;
2023-11-04 03:42:39 +01:00
const power10n = Math.pow(10, parseInt(decimals));
return Math.round(num * power10n) / power10n;
2021-04-11 23:01:10 +02:00
}
static getFractionHtml(diviseur) {
if (!diviseur || diviseur <= 1) return undefined;
switch (diviseur || 1) {
case 2: return '&frac12;';
case 4: return '&frac14;';
default: return '1/' + diviseur;
}
}
static indexLowercase(list) {
const obj = {};
const addToObj = (map, val) => {
const key = Grammar.toLowerCaseNoAccent(val);
if (key && !map[key]) map[key] = val
}
list.forEach(it => addToObj(obj, it))
return obj;
}
2023-01-18 00:11:10 +01:00
static concat(lists) {
return lists.reduce((a, b) => a.concat(b), []);
}
2021-05-07 01:47:51 +02:00
static classify(items, classifier = it => it.type) {
2022-06-12 08:17:59 +02:00
let itemsBy = {}
Misc.classifyInto(itemsBy, items, classifier)
return itemsBy
}
2021-03-19 22:20:01 +01:00
static classifyFirst(items, classifier) {
let itemsBy = {};
for (const item of items) {
const classification = classifier(item);
if (!itemsBy[classification]) {
itemsBy[classification] = item;
}
}
return itemsBy;
}
2021-03-29 18:08:18 +02:00
2021-05-07 01:47:51 +02:00
static classifyInto(itemsBy, items, classifier = it => it.type) {
for (const item of items) {
2022-06-12 08:17:59 +02:00
const classification = classifier(item)
let list = itemsBy[classification];
if (!list) {
2022-06-12 08:17:59 +02:00
list = []
itemsBy[classification] = list
}
2022-06-12 08:17:59 +02:00
list.push(item)
}
}
/**
* @returns an array of incremental integers (including from / excluding to).
* if max<min, the array is decrementing integers
*/
static intArray(from, to) {
if (from > to) {
return Array.from(Array(from - to).keys()).map(i => from - i)
}
return Array.from(Array(to - from).keys()).map(i => from + i)
}
static distinct(array) {
return [...new Set(array)];
}
2021-11-26 23:29:06 +01:00
static join(params, separator = '') {
return params?.reduce(Misc.joining(separator)) ?? '';
}
static joining(separator = '') {
return (a, b) => a + separator + b;
2021-11-26 23:29:06 +01:00
}
static connectedGMOrUser(ownerId = undefined) {
2021-05-11 21:45:43 +02:00
if (ownerId && game.user.id == ownerId) {
return ownerId;
}
return Misc.firstConnectedGM()?.id ?? game.user.id;
}
static isRollModeHiddenToPlayer() {
2022-12-28 23:36:48 +01:00
switch (game.settings.get("core", "rollMode")) {
case CONST.DICE_ROLL_MODES.BLIND:
case CONST.DICE_ROLL_MODES.SELF: return true;
}
return false
}
2022-01-11 23:39:51 +01:00
static getActiveUser(id) {
return game.users.find(u => u.id == id && u.active);
}
2022-01-11 23:39:51 +01:00
static firstConnectedGM() {
return game.users.filter(u => u.isGM && u.active).sort(Misc.ascending(u => u.id)).find(u => u.isGM && u.active);
}
2022-12-28 23:36:48 +01:00
static isOwnerPlayer(actor, user = undefined) {
return actor.testUserPermission(user ?? game.user, CONST.DOCUMENT_PERMISSION_LEVELS.OWNER)
}
2022-12-28 23:36:48 +01:00
static isOwnerPlayerOrUniqueConnectedGM(actor, user = undefined) {
return Misc.isOwnerPlayer(actor, user) ?? Misc.isUniqueConnectedGM();
}
/**
* @returns true pour un seul utilisateur: le premier GM connecté par ordre d'id
*/
static isUniqueConnectedGM() {
return game.user.id == Misc.firstConnectedGMId();
}
static firstConnectedGMId() {
return Misc.firstConnectedGM()?.id;
}
2021-11-26 23:29:06 +01:00
/* -------------------------------------------- */
static findPlayer(name) {
return Misc.findFirstLike(name, game.users, { description: 'joueur' });
}
/* -------------------------------------------- */
static findActor(name, actors = game.actors) {
return Misc.findFirstLike(name, actors, { description: 'acteur' });
}
/* -------------------------------------------- */
static findFirstLike(value, elements, options = {}) {
options = mergeObject({
mapper: it => it.name,
preFilter: it => true,
description: 'valeur',
onMessage: m => ui.notifications.info(m)
}, options);
const subset = this.findAllLike(value, elements, options);
if (subset.length == 0) {
console.log(`Aucune ${options.description} pour ${value}`);
return undefined
}
if (subset.length == 1) {
return subset[0]
}
let single = subset.find(it => Grammar.toLowerCaseNoAccent(options.mapper(it)) == Grammar.toLowerCaseNoAccent(value));
if (!single) {
single = subset[0];
2021-11-26 23:29:06 +01:00
const choices = Misc.join(subset.map(it => options.mapper(it)), '<br>');
options.onMessage(`Plusieurs choix de ${options.description}s possibles:<br>${choices}<br>Le premier sera choisi: ${options.mapper(single)}`);
}
return single;
}
static findAllLike(value, elements, options = {}) {
options = mergeObject({
mapper: it => it.name,
preFilter: it => true,
description: 'valeur',
onMessage: m => ui.notifications.info(m)
}, options);
if (!value) {
options.onMessage(`Pas de ${options.description} correspondant à une valeur vide`);
return [];
}
value = Grammar.toLowerCaseNoAccent(value);
const subset = elements.filter(options.preFilter)
.filter(it => Grammar.toLowerCaseNoAccent(options.mapper(it))?.includes(value));
if (subset.length == 0) {
options.onMessage(`Pas de ${options.description} correspondant à ${value}`);
}
return subset;
}
static cssRotation(angle) {
const rotation = `rotate(${angle}deg)`;
return {
'transform': rotation,
'-ms-transform': rotation,
'-moz-transform': rotation,
'-webkit-transform': rotation,
'-o-transform': rotation
};
}
2022-11-17 01:18:06 +01:00
}