Ajout d'une horloge analogique

Amélioration de la fenêtre calendrier:
* plus compacte
* horloge analogique
* normalement compatible pop-out
* minimisable (juste la barre de titre)
This commit is contained in:
2023-03-29 22:53:40 +02:00
parent 23af30a538
commit c1d02d9fda
23 changed files with 429 additions and 539 deletions

View File

@ -0,0 +1,67 @@
import { RdDTimestamp } from "./rdd-timestamp.js";
/**
* Extend the base Dialog entity by defining a custom window to perform roll.
* @extends {Dialog}
*/
export class RdDCalendrierEditor extends Dialog {
/* -------------------------------------------- */
constructor(html, calendrier, calendrierData) {
let dialogConf = {
content: html,
title: "Editeur de date/heure",
buttons: {
save: { label: "Enregistrer", callback: html => this.saveCalendrier() }
},
default: "save"
};
let dialogOptions = { classes: ["rdd-dialog-calendar-editor"], width: 400, height: 'fit-content', 'z-index': 99999 }
super(dialogConf, dialogOptions)
this.calendrier = calendrier;
this.calendrierData = calendrierData;
}
activateListeners(html) {
super.activateListeners(html);
this.html = html;
this.html.find("input[name='calendar.annee']").val(this.calendrierData.annee);
this.html.find("select[name='calendar.mois']").val(this.calendrierData.mois.key);
this.html.find("select[name='calendar.heure']").val(this.calendrierData.heure.key);
RdDCalendrierEditor.setLimited(this.html.find("input[name='calendar.jourDuMois']"), this.calendrierData.jourDuMois, 1, 28);
RdDCalendrierEditor.setLimited(this.html.find("input[name='calendar.minute']"), this.calendrierData.minute, 0, 119);
}
static setLimited(input, init, min, max) {
input.val(init);
input.change(event => {
const val = Number.parseInt(input.val());
if (val < min) {
input.val(min);
}
if (val > max) {
input.val(max);
}
});
}
/* -------------------------------------------- */
saveCalendrier() {
const annee = Number.parseInt(this.html.find("input[name='calendar.annee']").val());
const mois = this.html.find("select[name='calendar.mois']").val();
const jour = Number.parseInt(this.html.find("input[name='calendar.jourDuMois']").val());
const heure = this.html.find("select[name='calendar.heure']").val();
const minute = Number.parseInt(this.html.find("input[name='calendar.minute']").val());
this.calendrier.setNewTimestamp(RdDTimestamp.timestamp(annee, mois, jour, heure, minute))
}
/* -------------------------------------------- */
updateData(calendrierData) {
this.calendrierData = duplicate(calendrierData);
}
}

View File

@ -0,0 +1,453 @@
import { MAX_NOMBRE_ASTRAL, RdDTimestamp, WORLD_TIMESTAMP_SETTING } from "./rdd-timestamp.js";
import { RdDCalendrierEditor } from "./rdd-calendrier-editor.js";
import { RdDResolutionTable } from "../rdd-resolution-table.js";
import { RdDUtility } from "../rdd-utility.js";
import { RdDDice } from "../rdd-dice.js";
import { Misc } from "../misc.js";
import { DialogChronologie } from "../dialog-chronologie.js";
import { HIDE_DICE, SHOW_DICE, SYSTEM_RDD, SYSTEM_SOCKET_ID } from "../constants.js";
import { ReglesOptionelles } from "../settings/regles-optionelles.js";
import { DialogChateauDormant } from "../sommeil/dialog-chateau-dormant.js";
import { APP_ASTROLOGIE_REFRESH, AppAstrologie } from "../sommeil/app-astrologie.js";
const TEMPLATE_CALENDRIER = "systems/foundryvtt-reve-de-dragon/templates/time/calendar.hbs";
const INITIAL_CALENDAR_POS = { top: 200, left: 200, horlogeAnalogique: true };
/* -------------------------------------------- */
export class RdDCalendrier extends Application {
static init() {
game.settings.register(SYSTEM_RDD, "liste-nombre-astral", {
name: "liste-nombre-astral",
scope: "world",
config: false,
default: [],
type: Object
});
game.settings.register(SYSTEM_RDD, "calendrier-pos", {
name: "calendrierPos",
scope: "client",
config: false,
default: INITIAL_CALENDAR_POS,
type: Object
});
}
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
title: "Calendrier",
template: TEMPLATE_CALENDRIER,
classes: ["calendar"],
popOut: true,
resizable: false,
width: 'fit-content',
height: 'fit-content',
});
}
constructor() {
super();
this.timestamp = RdDTimestamp.getWorldTime();
if (Misc.isUniqueConnectedGM()) { // Uniquement si GM
RdDTimestamp.setWorldTime(this.timestamp);
this.nombresAstraux = this.getNombresAstraux();
this.rebuildNombresAstraux(HIDE_DICE); // Ensure always up-to-date
}
Hooks.on('updateSetting', async (setting, update, options, id) => this.onUpdateSetting(setting, update, options, id));
}
get title() {
const calendrier = this.timestamp.toCalendrier();
return `${calendrier.heure.label}, ${calendrier.jourDuMois} ${calendrier.mois.label} ${calendrier.annee} (${calendrier.mois.saison})`;
}
savePosition() {
game.settings.set(SYSTEM_RDD, "calendrier-pos", {
top: this.position.top,
left: this.position.left,
horlogeAnalogique: this.horlogeAnalogique
});
}
getSavePosition() {
const pos = game.settings.get(SYSTEM_RDD, "calendrier-pos");
if (pos?.top == undefined) {
return INITIAL_CALENDAR_POS;
}
this.horlogeAnalogique = pos.horlogeAnalogique;
return pos
}
setPosition(position) {
super.setPosition(position)
this.savePosition()
}
display() {
const pos = this.getSavePosition()
this.render(true, { left: pos.left, top: pos.top});
return this;
}
_getHeaderButtons() {
const buttons = [];
if (game.user.isGM) {
buttons.unshift({
class: "calendar-astrologie",
icon: "fa-solid fa-moon-over-sun",
onclick: ev => this.showAstrologieEditor()
},
{
class: "calendar-set-datetime",
icon: "fa-solid fa-calendar-pen",
onclick: ev => this.showCalendarEditor()
});
}
return buttons
}
async maximize() {
await super.maximize()
this.render(true)
}
async onUpdateSetting(setting, update, options, id) {
if (setting.key == SYSTEM_RDD + '.' + WORLD_TIMESTAMP_SETTING) {
this.timestamp = RdDTimestamp.getWorldTime();
this.updateDisplay();
Hooks.callAll(APP_ASTROLOGIE_REFRESH);
}
}
getData() {
const formData = super.getData();
this.fillCalendrierData(formData);
return formData;
}
/* -------------------------------------------- */
fillCalendrierData(formData = {}) {
mergeObject(formData, this.timestamp.toCalendrier());
formData.isGM = game.user.isGM;
formData.heures = RdDTimestamp.definitions()
formData.horlogeAnalogique = this.horlogeAnalogique;
return formData;
}
/* -------------------------------------------- */
/** @override */
async activateListeners(html) {
super.activateListeners(html);
this.html = html;
this.updateDisplay();
this.html.find('.ajout-chronologie').click(ev => DialogChronologie.create());
this.html.find('.toggle-horloge-analogique').click(ev => this.onToggleHorlogeAnalogique())
this.html.find('.calendar-btn').click(ev => this.onCalendarButton(ev));
this.html.find('.horloge-roue .horloge-heure').click(event => {
const h = this.html.find(event.currentTarget)?.data('heure');
this.positionnerHeure(Number(h));
})
this.html.find('.calendar-set-datetime').click(ev => {
ev.preventDefault();
this.showCalendarEditor();
});
this.html.find('.calendar-astrologie').click(ev => {
ev.preventDefault();
this.showAstrologieEditor();
});
}
onToggleHorlogeAnalogique() {
this.horlogeAnalogique = !this.horlogeAnalogique;
this.savePosition()
this.render(true)
}
/* -------------------------------------------- */
getNombresAstraux() {
return game.settings.get(SYSTEM_RDD, "liste-nombre-astral") ?? [];
}
/* -------------------------------------------- */
dateCourante() {
return this.timestamp.formatDate();
}
isAfterIndexDate(indexDate) {
// TODO: standardize
return indexDate < this.timestamp.indexDate;
}
/* -------------------------------------------- */
heureCourante() { return RdDTimestamp.definition(this.timestamp.heure); }
/* -------------------------------------------- */
getCurrentMinute() { return this.timestamp.indexMinute; }
getTimestamp() {
return this.timestamp;
}
getTimestampFinChateauDormant(nbJours = 0) {
return this.timestamp.nouveauJour().addJours(nbJours);
}
getTimestampFinHeure(nbHeures = 0) {
return this.timestamp.nouvelleHeure().addHeures(nbHeures);
}
/* -------------------------------------------- */
getIndexFromDate(jour, mois) {
const addYear = mois < this.timestamp.mois || (mois == this.timestamp.mois && jour < this.timestamp.jour)
const time = RdDTimestamp.timestamp(this.timestamp.annee + (addYear ? 1 : 0), mois, jour);
return time.indexDate;
}
/* -------------------------------------------- */
getJoursSuivants(count) {
return Misc.intArray(this.timestamp.indexDate, this.timestamp.indexDate + count)
.map(i => { return { label: RdDTimestamp.formatIndexDate(i), index: i } })
}
/* -------------------------------------------- */
async ajouterNombreAstral(indexDate, showDice = SHOW_DICE) {
const nombreAstral = await RdDDice.rollTotal("1dh", { showDice: showDice, rollMode: "selfroll" });
const dateFuture = RdDTimestamp.formatIndexDate(indexDate);
if (showDice != HIDE_DICE) {
ChatMessage.create({
whisper: ChatMessage.getWhisperRecipients("GM"),
content: `Le chiffre astrologique du ${dateFuture} sera le ${nombreAstral}`
});
}
return {
nombreAstral: nombreAstral,
valeursFausses: [],
index: indexDate
}
}
/* -------------------------------------------- */
resetNombresAstraux() {
this.nombresAstraux = [];
game.settings.set(SYSTEM_RDD, "liste-nombre-astral", []);
game.socket.emit(SYSTEM_SOCKET_ID, {
msg: "msg_reset_nombre_astral",
data: {}
});
}
/**
*
* @param {*} indexDate la date pour laquelle obtenir le nombre astral. Si undefined, on prend la date du jour
* @returns le nombre astral pour la date, ou pour la date du jour si la date n'est pas fournie.
* Si aucun nombre astral n'est trouvé, retourne 0 (cas où l'on demanderait un nombre astral en dehors des 12 jours courant et à venir)
*/
getNombreAstral(indexDate = undefined) {
if (indexDate == undefined) {
indexDate = this.timestamp.indexDate;
}
this.nombresAstraux = this.getNombresAstraux();
let astralData = this.nombresAstraux.find((nombreAstral, i) => nombreAstral.index == indexDate);
return astralData?.nombreAstral ?? 0;
}
/* -------------------------------------------- */
async rebuildNombresAstraux(showDice = HIDE_DICE) {
if (Misc.isUniqueConnectedGM()) {
let newList = [];
for (let i = 0; i < MAX_NOMBRE_ASTRAL; i++) {
let dayIndex = this.timestamp.indexDate + i;
let na = this.nombresAstraux.find(n => n.index == dayIndex);
if (na) {
newList[i] = na;
} else {
newList[i] = await this.ajouterNombreAstral(dayIndex, showDice);
}
}
this.nombresAstraux = newList;
game.settings.set(SYSTEM_RDD, "liste-nombre-astral", newList);
game.actors.filter(it => it.isPersonnage()).forEach(actor => actor.supprimerAnciensNombresAstraux());
this.notifyChangeNombresAstraux();
}
}
notifyChangeNombresAstraux() {
Hooks.callAll(APP_ASTROLOGIE_REFRESH);
game.socket.emit(SYSTEM_SOCKET_ID, {
msg: "msg_refresh_nombre_astral",
data: {}
});
}
/* -------------------------------------------- */
async setNewTimestamp(newTimestamp) {
const oldTimestamp = this.timestamp;
await Promise.all(game.actors.map(async actor => await actor.onTimeChanging(oldTimestamp, newTimestamp)));
RdDTimestamp.setWorldTime(newTimestamp);
if (oldTimestamp.indexDate + 1 == newTimestamp.indexDate && ReglesOptionelles.isUsing("chateau-dormant-gardien")) {
await DialogChateauDormant.create();
}
this.timestamp = newTimestamp;
await this.rebuildNombresAstraux();
this.updateDisplay();
this.display();
}
/* -------------------------------------------- */
async onCalendarButton(ev) {
ev.preventDefault();
const calendarAvance = ev.currentTarget.attributes['data-calendar-avance'];
const calendarSet = ev.currentTarget.attributes['data-calendar-set'];
if (calendarAvance) {
await this.incrementTime(Number(calendarAvance.value));
}
else if (calendarSet) {
this.positionnerHeure(Number(calendarSet.value));
}
this.updateDisplay();
}
/* -------------------------------------------- */
async incrementTime(minutes = 0) {
if (game.user.isGM) {
await this.setNewTimestamp(this.timestamp.addMinutes(minutes));
Hooks.callAll(APP_ASTROLOGIE_REFRESH);
}
}
/* -------------------------------------------- */
async incrementerJour() {
await this.setNewTimestamp(this.timestamp.nouveauJour());
}
/* -------------------------------------------- */
async positionnerHeure(heure) {
if (game.user.isGM) {
const indexDate = this.timestamp.indexDate;
const addDay = this.timestamp.heure < heure ? 0 : 1;
const newTimestamp = new RdDTimestamp({ indexDate: indexDate + addDay }).addHeures(heure);
await this.setNewTimestamp(newTimestamp)
Hooks.callAll(APP_ASTROLOGIE_REFRESH);
}
}
/* -------------------------------------------- */
getLectureAstrologieDifficulte(dateIndex) {
let indexNow = this.timestamp.indexDate;
let diffDay = dateIndex - indexNow;
return - Math.floor(diffDay / 2);
}
/* -------------------------------------------- */
async requestNombreAstral(request) {
const actor = game.actors.get(request.id);
if (Misc.isUniqueConnectedGM()) { // Only once
console.log(request);
let jourDiff = this.getLectureAstrologieDifficulte(request.date);
let niveau = Number(request.astrologie.system.niveau) + Number(request.conditions) + Number(jourDiff) + Number(request.etat);
let rollData = {
caracValue: request.carac_vue,
finalLevel: niveau,
showDice: HIDE_DICE,
rollMode: "blindroll"
};
await RdDResolutionTable.rollData(rollData);
request.rolled = rollData.rolled;
request.isValid = request.rolled.isSuccess;
request.nbAstral = this.getNombreAstral(request.date);
if (request.rolled.isSuccess) {
if (request.rolled.isPart) {
// Gestion expérience (si existante)
request.competence = actor.getCompetence("astrologie")
request.selectedCarac = actor.system.carac["vue"];
actor.appliquerAjoutExperience(request, 'hide');
}
}
else {
request.nbAstral = await RdDDice.rollTotal("1dhr" + request.nbAstral, {
rollMode: "selfroll", showDice: HIDE_DICE
});
// Mise à jour des nombres astraux du joueur
this.addNbAstralIncorect(request.id, request.date, request.nbAstral);
}
if (Misc.getActiveUser(request.userId)?.isGM) {
RdDUtility.responseNombreAstral(request);
} else {
game.socket.emit(SYSTEM_SOCKET_ID, {
msg: "msg_response_nombre_astral",
data: request
});
}
}
}
addNbAstralIncorect(actorId, date, nbAstral) {
const astralData = this.nombresAstraux.find((nombreAstral, i) => nombreAstral.index == date);
astralData.valeursFausses.push({ actorId: actorId, nombreAstral: nbAstral });
game.settings.set(SYSTEM_RDD, "liste-nombre-astral", this.nombresAstraux);
}
/* -------------------------------------------- */
getAjustementAstrologique(heureNaissance, name = undefined) {
const defHeure = RdDTimestamp.findHeure(heureNaissance);
if (defHeure) {
return RdDTimestamp.ajustementAstrologiqueHeure(defHeure.heure, this.getNombreAstral(), this.timestamp.heure);
}
else if (name) {
ui.notifications.warn(name + " n'a pas d'heure de naissance, ou elle est incorrecte : " + heureNaissance);
}
else {
ui.notifications.warn(heureNaissance + " ne correspond pas à une heure de naissance");
}
return 0;
}
/* -------------------------------------------- */
updateDisplay() {
const calendrier = this.fillCalendrierData();
for (const heure of document.getElementsByClassName("calendar-heure-texte")) {
heure.innerHTML = calendrier.heure.label;
}
for (const minute of document.getElementsByClassName("calendar-minute-texte")) {
minute.innerHTML = `${calendrier.minute} minutes`;
}
this.postionnerAiguilles()
}
postionnerAiguilles() {
const timestamp = this.getTimestamp();
this.html.find(`div.horloge-roue div.horloge-aiguille-heure img`).css(Misc.cssRotation(timestamp.angleHeure));
this.html.find(`div.horloge-roue div.horloge-aiguille-minute img`).css(Misc.cssRotation(timestamp.angleMinute));
}
/* -------------------------------------------- */
async saveEditeur(calendrierData) {
const newTimestamp = RdDTimestamp.timestamp(
Number.parseInt(calendrierData.annee),
calendrierData.mois.heure,
Number.parseInt(calendrierData.jourMois),
calendrierData.heure.heure,
Number.parseInt(calendrierData.minutes)
);
await this.setNewTimestamp(newTimestamp);
}
/* -------------------------------------------- */
async showCalendarEditor() {
const calendrierData = this.fillCalendrierData();
if (this.editeur == undefined) {
const html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/time/calendar-editor.hbs', calendrierData);
this.editeur = new RdDCalendrierEditor(html, this, calendrierData)
}
this.editeur.updateData(calendrierData);
this.editeur.render(true);
}
/* -------------------------------------------- */
async showAstrologieEditor() {
await AppAstrologie.create();
}
}

View File

@ -0,0 +1,339 @@
import { SHOW_DICE, SYSTEM_RDD } from "../constants.js";
import { Grammar } from "../grammar.js";
import { Misc } from "../misc.js";
import { RdDDice } from "../rdd-dice.js";
export const WORLD_TIMESTAMP_SETTING = "calendrier";
const RDD_JOURS_PAR_AN = 336; //RDD_JOURS_PAR_MOIS * RDD_MOIS_PAR_AN;
const RDD_MOIS_PAR_AN = 12;
export const RDD_JOURS_PAR_MOIS = 28;
export const RDD_HEURES_PAR_JOUR = 12;
export const MAX_NOMBRE_ASTRAL = 12;
export const RDD_MINUTES_PAR_HEURES = 120;
export const RDD_MINUTES_PAR_JOUR = 1440; //RDD_HEURES_PAR_JOUR * RDD_MINUTES_PAR_HEURES;
const ROUNDS_PAR_MINUTE = 10;
const DEFINITION_HEURES = [
{ key: "vaisseau", label: "Vaisseau", lettreFont: 'v', saison: "Printemps" },
{ key: "sirene", label: "Sirène", lettreFont: 'i', saison: "Printemps" },
{ key: "faucon", label: "Faucon", lettreFont: 'f', saison: "Printemps" },
{ key: "couronne", label: "Couronne", lettreFont: '', saison: "Eté" },
{ key: "dragon", label: "Dragon", lettreFont: 'd', saison: "Eté" },
{ key: "epees", label: "Epées", lettreFont: 'e', saison: "Eté" },
{ key: "lyre", label: "Lyre", lettreFont: 'l', saison: "Automne" },
{ key: "serpent", label: "Serpent", lettreFont: 's', saison: "Automne" },
{ key: "poissonacrobate", label: "Poisson Acrobate", lettreFont: 'p', saison: "Automne" },
{ key: "araignee", label: "Araignée", lettreFont: 'a', saison: "Hiver" },
{ key: "roseau", label: "Roseau", lettreFont: 'r', saison: "Hiver" },
{ key: "chateaudormant", label: "Château Dormant", lettreFont: 'c', saison: "Hiver" },
]
const FORMULES_DUREE = [
{ code: "", label: "", calcul: async (t, actor) => t.addJours(100 * RDD_JOURS_PAR_AN) },
{ code: "jour", label: "1 jour", calcul: async (t, actor) => t.nouveauJour().addJours(1) },
{ code: "1d7jours", label: "1d7 jour", calcul: async (t, actor) => t.nouveauJour().addJours(await RdDDice.rollTotal('1d7', { showDice: SHOW_DICE })) },
{ code: "1ddr", label: "Un dé draconique jours", calcul: async (t, actor) => t.nouveauJour().addJours(await RdDDice.rollTotal('1dr+7', { showDice: SHOW_DICE })) },
{ code: "hn", label: "Fin de l'Heure de Naissance", calcul: async (t, actor) => t.finHeure(actor.getHeureNaissance()) },
// { code: "1h", label: "Une heure", calcul: async (t, actor) => t.nouvelleHeure().addHeures(1) },
// { code: "12h", label: "12 heures", calcul: async (t, actor) => t.nouvelleHeure().addHeures(12) },
// { code: "chateaudormant", label: "Fin Chateau dormant", calcul: async (t, actor) => t.nouveauJour() },
// { code: "special", label: "Spéciale", calcul: async (t, actor) => t.addJours(100 * RDD_JOURS_PAR_AN) },
]
const FORMULES_PERIODE = [
{ code: 'round', label: "Rounds", calcul: async (t, nombre) => t.addMinutes(nombre / 10) },
{ code: 'minute', label: "Minutes", calcul: async (t, nombre) => t.addMinutes(nombre) },
{ code: 'heure', label: "Heures", calcul: async (t, nombre) => t.addHeures(nombre) },
{ code: 'jour', label: "Jours", calcul: async (t, nombre) => t.addJours(nombre) },
]
export class RdDTimestamp {
static init() {
game.settings.register(SYSTEM_RDD, WORLD_TIMESTAMP_SETTING, {
name: WORLD_TIMESTAMP_SETTING,
scope: "world",
config: false,
default: { indexDate: 0, indexMinute: 0 },
type: Object
});
for (let i = 0; i < DEFINITION_HEURES.length; i++) {
DEFINITION_HEURES[i].heure = i;
DEFINITION_HEURES[i].hh = RdDTimestamp.hh(i);
DEFINITION_HEURES[i].icon = RdDTimestamp.iconeHeure(i);
DEFINITION_HEURES[i].webp = DEFINITION_HEURES[i].icon.replace(".svg", ".webp");
}
}
static hh(heure) {
return heure < 9 ? `0${heure + 1}` : `${heure + 1}`;
}
static iconeHeure(heure) {
return `systems/foundryvtt-reve-de-dragon/icons/heures/hd${RdDTimestamp.hh(heure)}.svg`;
}
static definitions() {
return DEFINITION_HEURES
}
static formulesDuree() {
return FORMULES_DUREE
}
static formulesPeriode() {
return FORMULES_PERIODE
}
static heures() {
return Misc.intArray(0, RDD_HEURES_PAR_JOUR)
}
/**
* @param signe
* @returns L'entrée de DEFINITION_HEURES correspondant au signe
*/
static definition(signe) {
if (signe == undefined) {
signe = 0;
}
if (Number.isInteger(signe)) {
return DEFINITION_HEURES[signe % RDD_HEURES_PAR_JOUR];
}
let definition = DEFINITION_HEURES.find(it => it.key == signe);
if (!definition) {
definition = Misc.findFirstLike(signe, DEFINITION_HEURES, { mapper: it => it.label, description: 'signe' });
}
return definition
}
static imgSigneHeure(heure) {
return RdDTimestamp.imgSigne(RdDTimestamp.definition(heure));
}
static imgSigne(signe) {
return signe == undefined ? '' : `<img class="img-signe-heure" src="${signe.webp}" alt="${signe.label}" title="${signe.label}"/>`
}
static ajustementAstrologiqueHeure(hn, nbAstral, heure) {
let ecart = (hn + nbAstral - heure) % RDD_HEURES_PAR_JOUR;
if (ecart < 0) {
ecart = (ecart + RDD_HEURES_PAR_JOUR) % RDD_HEURES_PAR_JOUR;
}
switch (ecart) {
case 0: return 4;
case 4: case 8: return 2;
case 6: return -4;
case 3: case 9: return -2;
}
return 0;
}
static handleTimestampEditor(html, path, consumeTimestamp = async (path, timestamp) => { }) {
const fields = {
annee: html.find(`input[name="${path}.annee"]`),
mois: html.find(`select[name="${path}.mois"]`),
jourDuMois: html.find(`input[name="${path}.jourDuMois"]`),
heure: html.find(`select[name="${path}.heure"]`),
minute: html.find(`input[name="${path}.minute"]`)
};
async function onChangeTimestamp(fields, path) {
const annee = Number(fields.annee.val());
const mois = fields.mois.val();
const jour = Number(fields.jourDuMois.val());
const heure = fields.heure.val();
const minute = Number(fields.minute.val());
await consumeTimestamp(path, RdDTimestamp.timestamp(annee, mois, jour, heure, minute));
}
fields.annee.change(async (event) => await onChangeTimestamp(fields, path));
fields.mois.change(async (event) => await onChangeTimestamp(fields, path));
fields.jourDuMois.change(async (event) => await onChangeTimestamp(fields, path));
fields.heure.change(async (event) => await onChangeTimestamp(fields, path));
fields.minute.change(async (event) => await onChangeTimestamp(fields, path));
}
static findHeure(heure) {
heure = Grammar.toLowerCaseNoAccentNoSpace(heure);
let parHeureOuLabel = DEFINITION_HEURES.filter(it => (it.heure) == parseInt(heure) % RDD_HEURES_PAR_JOUR || Grammar.toLowerCaseNoAccentNoSpace(it.label) == heure);
if (parHeureOuLabel.length == 1) {
return parHeureOuLabel[0];
}
let parLabelPartiel = DEFINITION_HEURES.filter(it => Grammar.toLowerCaseNoAccentNoSpace(it.label).includes(heure));
if (parLabelPartiel.length > 0) {
parLabelPartiel.sort(Misc.ascending(h => h.label.length));
return parLabelPartiel[0];
}
return undefined;
}
/**
* @param indexDate: la date (depuis le jour 0)
* @return la version formattée de la date
*/
static formatIndexDate(indexDate) {
return new RdDTimestamp({ indexDate }).formatDate()
}
static splitIndexDate(indexDate) {
const timestamp = new RdDTimestamp({ indexDate });
return {
jour: timestamp.jour + 1,
mois: RdDTimestamp.definition(timestamp.mois).key
}
}
static getWorldTime() {
let worldTime = game.settings.get(SYSTEM_RDD, WORLD_TIMESTAMP_SETTING);
if (worldTime.indexJour != undefined && worldTime.heureRdD != undefined) {
// Migration
worldTime = {
indexDate: worldTime.indexJour,
indexMinute: worldTime.heureRdD * 120 + worldTime.minutesRelative
};
RdDTimestamp.setWorldTime(new RdDTimestamp(worldTime))
}
return new RdDTimestamp(worldTime);
}
static setWorldTime(timestamp) {
game.settings.set(SYSTEM_RDD, WORLD_TIMESTAMP_SETTING, duplicate(timestamp));
}
/** construit un RdDTimestamp à partir de l'année/mois/jour/heure?/minute? */
static timestamp(annee, mois, jour, heure = 0, minute = 0) {
mois = this.definition(mois)?.heure
heure = this.definition(heure)?.heure
return new RdDTimestamp({
indexDate: (jour - 1) + (mois + annee * RDD_MOIS_PAR_AN) * RDD_JOURS_PAR_MOIS,
indexMinute: heure * RDD_MINUTES_PAR_HEURES + minute
})
}
/**
* Constructeur d'un timestamp.
* Selon les paramètres, l'objet construit se base su:
* - le timestamp
* - la date numérique + minute (dans la journée)
* @param indexDate: la date à utiliser pour ce timestamp
* @param indexMinute: la minute de la journée à utiliser pour ce timestamp
*
*/
constructor({ indexDate, indexMinute = undefined }) {
this.indexDate = indexDate
this.indexMinute = indexMinute ?? 0
}
/**
* Convertit le timestamp en une structure avec les informations utiles
* pour afficher la date et l'heure
*/
toCalendrier() {
return {
timestamp: this,
annee: this.annee,
mois: RdDTimestamp.definition(this.mois),
jour: this.jour,
jourDuMois: this.jour + 1,
heure: RdDTimestamp.definition(this.heure),
minute: this.minute
};
}
get annee() { return Math.floor(this.indexDate / RDD_JOURS_PAR_AN) }
get mois() { return Math.floor((this.indexDate % RDD_JOURS_PAR_AN) / RDD_JOURS_PAR_MOIS) }
get jour() { return (this.indexDate % RDD_JOURS_PAR_AN) % RDD_JOURS_PAR_MOIS }
get heure() { return Math.floor(this.indexMinute / RDD_MINUTES_PAR_HEURES) }
get minute() { return this.indexMinute % RDD_MINUTES_PAR_HEURES }
get round() { return ROUNDS_PAR_MINUTE * (this.indexMinute - Math.floor(this.indexMinute)) }
get angleHeure() { return this.indexMinute / RDD_MINUTES_PAR_JOUR * 360 - 45 }
get angleMinute() { return this.indexMinute / RDD_MINUTES_PAR_HEURES * 360 + 45}
formatDate() {
const jour = this.jour + 1;
const mois = RdDTimestamp.definition(this.mois).label;
const annee = this.annee ?? '';
return `${jour} ${mois}` + (annee ? ' ' + annee : '');
}
nouveauJour() { return new RdDTimestamp({ indexDate: this.indexDate + 1, indexMinute: 0 }) }
nouvelleHeure() {
return this.heure >= RDD_HEURES_PAR_JOUR ? this.nouveauJour() : new RdDTimestamp({
indexDate: this.indexDate,
indexMinute: (this.heure + 1) * RDD_MINUTES_PAR_HEURES
})
}
addJours(jours) {
return jours == 0 ? this : new RdDTimestamp({
indexDate: this.indexDate + jours,
indexMinute: this.indexMinute
})
}
addHeures(heures) {
if (heures == 0) {
return this
}
const heure = this.heure + heures;
return new RdDTimestamp({
indexDate: this.indexDate + Math.floor(heure / RDD_HEURES_PAR_JOUR),
indexMinute: this.indexMinute + (heure % RDD_HEURES_PAR_JOUR) * RDD_MINUTES_PAR_HEURES
})
}
addMinutes(minutes) {
if (minutes == 0) {
return this;
}
const indexMinute = this.indexMinute + minutes;
const jours = Math.floor(indexMinute / RDD_MINUTES_PAR_JOUR)
return new RdDTimestamp({
indexDate: this.indexDate + jours,
indexMinute: indexMinute - (jours * RDD_MINUTES_PAR_JOUR)
})
}
addPeriode(nombre, unite) {
const formule = FORMULES_PERIODE.find(it => it.code == unite);
if (formule) {
return formule.calcul(this, nombre);
}
else {
ui.notifications.info(`Pas de période pour ${unite ?? 'Aucune uinité définie'}`)
}
return this;
}
finHeure(heure) {
return this.nouvelleHeure().addHeures((12 + heure - this.heure) % 12);
}
async appliquerDuree(duree, actor) {
const formule = FORMULES_DUREE.find(it => it.code == duree) ?? FORMULES_DUREE.find(it => it.code == "");
return await formule.calcul(this, actor);
}
compare(timestamp) {
let diff = this.indexDate - timestamp.indexDate
if (diff == 0) {
diff = this.indexMinute - timestamp.indexMinute
}
return diff < 0 ? -1 : diff > 0 ? 1 : 0;
}
difference(timestamp) {
const jours = this.indexDate - timestamp.indexDate;
const minutes = this.indexMinute - timestamp.indexMinute;
return {
jours: jours,
heures: Math.floor(minutes / RDD_MINUTES_PAR_HEURES),
minutes: minutes % RDD_MINUTES_PAR_HEURES
}
}
}