Skip to content

Commit

Permalink
df-logger: TS->JS downgrade, V12 Compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
flamewave000 committed Feb 3, 2025
1 parent ab16881 commit 7be92e6
Show file tree
Hide file tree
Showing 9 changed files with 174 additions and 62 deletions.
4 changes: 4 additions & 0 deletions df-logger/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# DF User Logger

## Release 2.0.0 (2025-01-30)
- **UPDATE:** Migrated to v12.
- **UPDATE:** Downgraded TS -> JS (such sad).

## Release 1.7.0 (2022-10-17)
- **UPDATE:** Migrated to v10.
- **FIX #400:** Fixed error when user deletes message before timeout does.
Expand Down
File renamed without changes.
14 changes: 5 additions & 9 deletions df-logger/module.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
{
"id": "df-logger",
"title": "DF User Logger",
"version": "1.7.0",
"version": "2.0.0",
"description": "Prints a simple message whenever a user logs-in/out of FoundryVTT",
"author": "flamewave000#0001",
"compatibility": {
"minimum": 10,
"verified": 10.288
},
"esmodules": "{{sources}}",
"styles": "{{css}}",
"authors": [ { "name": "flamewave000", "discord": "flamewave000", "url": "https://github.com/flamewave000" } ],
"compatibility": { "minimum": 12, "verified": 12.331 },
"esmodules": "src/df-logger.mjs",
"styles": "css/df-logger.css",
"languages": [
{ "lang": "en", "name": "English", "path": "lang/en.json" },
{ "lang": "es", "name": "Español", "path": "lang/es.json" },
Expand All @@ -25,7 +22,6 @@
"socket": true,
"manifestPlusVersion": "1.0.0",
"bugs": "https://github.com/flamewave000/dragonflagon-fvtt/issues/new/choose",
"authors": [ { "name": "flamewave000", "discord": "flamewave000#0001", "url": "https://github.com/flamewave000" } ],
"media": [
{ "type": "icon", "url": "https://raw.githubusercontent.com/flamewave000/dragonflagon-fvtt/master/.assets/logo.png" },
{ "type": "screenshot", "url": "https://raw.githubusercontent.com/flamewave000/dragonflagon-fvtt/master/.assets/df-logger/message.png" },
Expand Down
54 changes: 36 additions & 18 deletions df-logger/src/DFLogger.ts → df-logger/src/DFLogger.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import { Message, MessageProcessor } from "./MessageProcessor";
import SETTINGS from "../../common/Settings";

interface Payload {
type: string,
id: string,
msg: string
}
import MessageProcessor from "./MessageProcessor.mjs";
import SETTINGS from "./common/Settings.mjs";

export default class DFLogger {
static EV_LOGIN = 'login';
Expand All @@ -19,14 +13,23 @@ export default class DFLogger {
static get LoginContent() { return game.i18n.localize('DF-LOGGER.Content.Login'); }
static get LogoutContent() { return game.i18n.localize('DF-LOGGER.Content.Logout'); }

static getMessageText(messages: Message[]): string {
/**
* @param {Message[]} messages
* @returns {string}
*/
static getMessageText(messages) {
messages = messages.filter(x => x.tog);
return messages[Math.round(Math.random() * (messages.length * 100)) % messages.length].msg;
}

static async displayMessage(user: User, alias: any, msg: string) {
/**
* @param {User} user
* @param {any} alias
* @param {string} msg
*/
static async displayMessage(user, alias, msg) {
const chatMsg = await ChatMessage.create({
sound: SETTINGS.get<string>(DFLogger.SETTING_SOUND),
sound: SETTINGS.get(DFLogger.SETTING_SOUND),
content: msg.replace(/\{\{username\}\}/g, user.name),
speaker: {
scene: null,
Expand All @@ -35,7 +38,7 @@ export default class DFLogger {
alias: alias
},
whisper: [game.user.id],
type: CONST.CHAT_MESSAGE_TYPES.OOC,
type: CONST.CHAT_MESSAGE_STYLES.OOC,
flags: { 'df-logger': { destroy: !this.Persist } }
});

Expand All @@ -44,17 +47,26 @@ export default class DFLogger {
try {
await chatMsg.delete();
} catch { /* ignore errors here, they only occur if the user deleted the message before our timer did */ }
}, Math.round(SETTINGS.get<number>('delay') * 1000));
}, Math.round(SETTINGS.get('delay') * 1000));
}
}

static onEvent(data: Payload) {
/**
* @param {Payload} data
* @returns
*/
static onEvent(data) {
// ignore message if GM-Only and we are not a GM
if (SETTINGS.get(DFLogger.SETTING_GM_ONLY) && !game.user.isGM) return;
if (data.type === DFLogger.EV_LOGIN) DFLogger.onLogin(data);
else if (data.type === DFLogger.EV_LOGOUT) DFLogger.onLogout(data);
}
static onUserActivity(userId: string, activityData: { active?: boolean } = {}) {
/**
*
* @param {string} userId
* @param { {active?: boolean} } activityData
*/
static onUserActivity(userId, activityData = {}) {
if (!("active" in activityData) || activityData.active === true) return;
DFLogger.onLogout({
type: DFLogger.EV_LOGOUT,
Expand All @@ -64,7 +76,7 @@ export default class DFLogger {
}

static performLogin() {
const payload: Payload = {
/** @type {Payload} */const payload = {
type: DFLogger.EV_LOGIN,
id: game.user.id,
msg: DFLogger.getMessageText(MessageProcessor.loginMessages)
Expand All @@ -74,11 +86,17 @@ export default class DFLogger {
DFLogger.onEvent(payload);
}

static async onLogin(data: Payload) {
/**
* @param {Payload} data
*/
static async onLogin(data) {
await DFLogger.displayMessage(game.users.get(data.id), DFLogger.LoginContent, data.msg);
}

static async onLogout(data: Payload) {
/**
* @param {Payload} data
*/
static async onLogout(data) {
// do not display a logout message for ourselves
if (game.user.id === data.id) return;
await DFLogger.displayMessage(game.users.get(data.id), DFLogger.LogoutContent, data.msg);
Expand Down
44 changes: 29 additions & 15 deletions df-logger/src/DFLoggerMenu.ts → df-logger/src/DFLoggerMenu.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Message, MessageProcessor } from "./MessageProcessor";
import MessageProcessor from "./MessageProcessor.mjs";


export default class DFLoggerMenu extends FormApplication {
static get defaultOptions() {
return <any>mergeObject(super.defaultOptions as Partial<FormApplicationOptions>, {
return mergeObject(super.defaultOptions, {
editable: true,
resizable: true,
submitOnChange: false,
Expand All @@ -17,37 +17,48 @@ export default class DFLoggerMenu extends FormApplication {
});
}

async _updateObject(_event: Event, _formData?: object) {
/**
*
* @param {Event} _event
* @param {object|undefined} _formData
*/
async _updateObject(_event, _formData) {
const loginEntryElements = this.element.find('div[data-tab="login"]>div.message-entry');
const loginEntries: Message[] = [];
/**@type {Message[]}*/const loginEntries = [];
loginEntryElements.each((_, elem) => {
loginEntries.push({
tog: elem.querySelector<HTMLInputElement>('input[type="checkbox"]').checked,
msg: elem.querySelector<HTMLInputElement>('input[type="text"]').value
tog: elem.querySelector('input[type="checkbox"]').checked,
msg: elem.querySelector('input[type="text"]').value
});
});
const logoutEntryElements = this.element.find('div[data-tab="logout"]>div.message-entry');
const logoutEntries: Message[] = [];
/**@type {Message[]}*/const logoutEntries = [];
logoutEntryElements.each((_, elem) => {
logoutEntries.push({
tog: elem.querySelector<HTMLInputElement>('input[type="checkbox"]').checked,
msg: elem.querySelector<HTMLInputElement>('input[type="text"]').value
tog: elem.querySelector('input[type="checkbox"]').checked,
msg: elem.querySelector('input[type="text"]').value
});
});
MessageProcessor.loginMessages = loginEntries;
MessageProcessor.logoutMessages = logoutEntries;
await MessageProcessor.saveMessages();
}

getData(_options?: Application.RenderOptions): any {
/**
* @param {Application.RenderOptions} _options
* @returns {object}
*/
getData(_options) {
return {
login: MessageProcessor.loginMessages,
logout: MessageProcessor.logoutMessages
};
}

/** @override */
activateListeners(html: JQuery<HTMLElement>) {
/**
* @param {JQuery} html
*/
activateListeners(html) {
html.find('div.message-entry').each((_, elem) => this._processEntry($(elem)));
html.find('button[name="add"]').on('click', async () => {
const entry = $(await renderTemplate('modules/df-logger/templates/message-template.hbs', { tog: true, msg: '' }));
Expand All @@ -69,14 +80,17 @@ export default class DFLoggerMenu extends FormApplication {
});
}

private _processEntry(element: JQuery<HTMLElement>) {
/**
* @param {JQuery} element
*/
_processEntry(element) {
const textBlock = element.find('input[type="text"]');
element.find('input[type="checkbox"]').on('change', (event) => {
const input = event.currentTarget as HTMLInputElement;
/**@type {HTMLInputElement}*/const input = event.currentTarget;
if (input.checked) textBlock.removeAttr('disabled');
else textBlock.attr('disabled', '');
});
element.find('button').on('click', (event: JQuery.ClickEvent) => {
element.find('button').on('click', (/**@type {JQuery.ClickEvent}*/event) => {
$(event.currentTarget).parent('.message-entry').remove();
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@

export interface Message {
tog: boolean;
msg: string;
}
export default class MessageProcessor {
/** @type {Promise<void>} */static messageLoadJob = null;
/** @type {Message[]} */static loginMessages = [];
/** @type {Message[]} */static logoutMessages = [];

export class MessageProcessor {

static messageLoadJob: Promise<void> = null;
static loginMessages: Message[] = [];
static logoutMessages: Message[] = [];

static loadMessages(): Promise<void> {
/** @returns { Promise<void> } */
static loadMessages() {
this.messageLoadJob = new Promise(async (res, rej) => {
const response = await fetch('user-logger-messages.json');
if (response.ok) {
Expand All @@ -36,13 +31,13 @@ export class MessageProcessor {
login: this.loginMessages,
logout: this.logoutMessages
})], 'user-logger-messages.json', { type: 'application/json' });
const response: { path?: string; message?: string } = <any>await FilePicker.upload('data', '', file);
/** @type {FilePickerResponse}*/const response = await FilePicker.upload('data', '', file);
if (!response.path)
throw new Error('Could not upload the login.json to server');
}

static async initializeMessages() {
const i18n: { LoginMsg: string[], LogoutMsg: string[] } = <any>game.i18n.translations['DF-LOGGER'];
/** @type {Messages}*/const i18n = game.i18n.translations['DF-LOGGER'];
for (const msg of i18n.LoginMsg) {
this.loginMessages.push({ tog: true, msg });
}
Expand Down
39 changes: 39 additions & 0 deletions df-logger/src/common/Settings.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/// <reference path="../../../node_modules/fvtt-types/src/configuration/globals.d.mts" />
export default class SETTINGS {
/** @type {string} */static MOD_NAME;
/** @param {string} moduleName */
static init(moduleName) {
this.MOD_NAME = moduleName;
if (!String.prototype.localize) {
String.prototype.localize = function () {
return game.i18n.localize(this.valueOf());
};
}
}
/**
* @param {string} key
* @param {ClientSettings.SettingConfig} config
*/
static register(key, config) { game.settings.register(SETTINGS.MOD_NAME, key, config); }
/**
* @param {string} key
* @param {ClientSettings.SettingSubmenuConfig} config
*/
static registerMenu(key, config) { game.settings.registerMenu(SETTINGS.MOD_NAME, key, config); }
/**
* @param {string} key
* @returns {any}
*/
static get(key) { return game.settings.get(SETTINGS.MOD_NAME, key); }
/**
* @param {string} key
* @param {any} value
* @returns {Promise<any>}
*/
static async set(key, value) { return await game.settings.set(SETTINGS.MOD_NAME, key, value); }
/**
* @param {string} key
* @returns {any}
*/
static default(key) { return game.settings.settings.get(SETTINGS.MOD_NAME + '.' + key).default; }
}
14 changes: 7 additions & 7 deletions df-logger/src/df-logger.ts → df-logger/src/df-logger.mjs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import DFLogger from './DFLogger';
import DFLoggerMenu from './DFLoggerMenu';
import { MessageProcessor } from './MessageProcessor';
import SETTINGS from "../../common/Settings";
import DFLogger from './DFLogger.mjs';
import DFLoggerMenu from './DFLoggerMenu.mjs';
import MessageProcessor from './MessageProcessor.mjs';
import SETTINGS from "./common/Settings.mjs";

SETTINGS.init('df-logger');

Hooks.once('init', function () {
SETTINGS.registerMenu('message-manage', {
restricted: true,
type: <any>DFLoggerMenu,
type: DFLoggerMenu,
label: 'DF-LOGGER.Settings.ManageMessages',
icon: 'fas fa-comment-alt'
});
SETTINGS.register<string>(DFLogger.SETTING_SOUND, {
SETTINGS.register(DFLogger.SETTING_SOUND, {
name: 'DF-LOGGER.Settings.Sound_Name',
hint: 'DF-LOGGER.Settings.Sound_Hint',
scope: 'world',
Expand All @@ -38,7 +38,7 @@ Hooks.once('init', function () {
type: Boolean,
default: true
});
SETTINGS.register<number>(DFLogger.SETTING_DELAY, {
SETTINGS.register(DFLogger.SETTING_DELAY, {
name: "DF-LOGGER.Settings.Delay_Name",
hint: "DF-LOGGER.Settings.Delay_Hint",
scope: "client",
Expand Down
Loading

0 comments on commit 7be92e6

Please sign in to comment.