Skip to content

Commit

Permalink
Add Option Groups + Setup World Scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
mclemente committed Jul 2, 2024
1 parent e8afd03 commit 06aa961
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 40 deletions.
7 changes: 3 additions & 4 deletions src/languages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@
"advanced-macros": {
"MACROS": {
"runForSpecificUser": "Execute for Specific User",
"runForSpecificUserTooltip": "This will cause the macro to be executed by the GM for a specific player connected.\nFor security reasons, only applies to GM-created macros with no other owners.",
"runForEveryone": "Everyone",
"runForEveryoneElse": "Everyone else",
"none": "None",
"runAsWorldScript": "World Script",
"runAsWorldScriptTooltip": "This will cause the macro to be executed automatically be the world once it's loaded.\nFor security reasons, only applies to GM-created macros with no other owners."
"WorldScript": "World Script",
"runAsWorldScript": "Ready Hook",
"runAsWorldScriptSetup": "Setup Hook"
},
"setting": {
"legacySlashCommand": {
Expand Down
2 changes: 1 addition & 1 deletion src/languages/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"advanced-macros": {
"MACROS": {
"none": "Nadie",
"runAsWorldScript": "Script de mundo",
"WorldScript": "Script de mundo",
"runForSpecificUser": "Ejecutar para el usuario específico",
"runForSpecificUserTooltip": "Esto hará que la macro sea ejecutada por el GM para un jugador concreto que esté conectado.\nPor motivos de seguridad, solo aplica a macros creadas por los GM que no tengan ningún otro propietario.",
"runForEveryone": "Todo el mundo",
Expand Down
2 changes: 1 addition & 1 deletion src/languages/fi.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"runForEveryone": "Kaikille",
"runForEveryoneElse": "Kaikille muille",
"none": "Ei mitään",
"runAsWorldScript": "Maailmaskripti",
"WorldScript": "Maailmaskripti",
"runAsWorldScriptTooltip": "Tämä makro suoritetaan automaattisesti, kun maailma on ladattu.\nTurvallisuussyistä tämä koskee vain PJ:n luomia makroja, joilla ei ole muita omistajia."
}
}
Expand Down
1 change: 0 additions & 1 deletion src/languages/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
"runForSpecificUserTooltip": "Ainsi, la macro sera exécutée par le MJ pour un joueur spécifique connecté.\nPour des raisons de sécurité, ne s'applique qu'aux macros créées par le MJ et n'ayant aucun autre propriétaire.",
"none": "Aucun",
"runForEveryoneElse": "Tous les autres",
"runAsWorldScript": "World Script",
"runAsWorldScriptTooltip": "La macro sera alors exécutée automatiquement pour le monde une fois qu'elle aura été chargée.\nPour des raisons de sécurité, ne s'applique qu'aux macros créées par le MJ et n'ayant pas d'autres propriétaires."
},
"setting": {
Expand Down
2 changes: 1 addition & 1 deletion src/languages/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"runAsGMTooltip": "Makro zostanie uruchomione przez GMa kiedy gracz włączy makro. \nDla bezpieczeństwa, tylko dotyczy makra stworzone przez GMa i nie posiadające innych twórców.",
"runForSpecificUserTooltip": "Makro zostanie uruchomione przez GMa tylko dla wybranego zalogowanego gracza. \nDla bezpieczeństwa, tylko dotyczy makra stworzone przez GMa i nie posiadające innych twórców.",
"runForEveryoneElse": "Wszyscy inni",
"runAsWorldScript": "Skrypt globalny",
"WorldScript": "Skrypt globalny",
"runAsWorldScriptTooltip": "Spowoduje to automatyczne wykonanie makra na świecie po jego załadowaniu.\nZe względów bezpieczeństwa dotyczy tylko makr stworzonych przez GM bez innych właścicieli."
},
"setting": {
Expand Down
4 changes: 2 additions & 2 deletions src/languages/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
"MACROS": {
"runForSpecificUser": "Executar para usuário específico",
"runForSpecificUserTooltip": "Isto fará com que a macro seja executada pelo MJ para um usuário específico conectado.\nPor questões de segurança, só se aplica a macros criadas pelo MJ sem outros donos.",
"runAsGM": "Mestre do Jogo",
"runForEveryone": "Todos",
"runForEveryoneElse": "Todos os outros",
"none": "Ninguém",
"runAsWorldScript": "Script do Mundo",
"WorldScript": "Script do Mundo",
"runAsGM": "Como {gm}",
"runAsWorldScriptTooltip": "Isto fará com que a macro seja executada automaticamente quando o Mundo for carregado.\nPor questões de segurança, só se aplica a macros criadas pelo MJ sem outros donos."
},
"setting": {
Expand Down
71 changes: 41 additions & 30 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,22 @@ Hooks.on("chatMessage", (chatLog, message, chatData) => {
return true;
});

function runWorldScripts(key) {
const worldScripts = game.macros.contents.filter(
(macro) => macro.getFlag("advanced-macros", "runForSpecificUser") === key
);
for (const macro of worldScripts) {
try {
macro.execute();
console.debug(`Advanced Macros | Executed "${macro.name}" world script (ID: ${macro.id})`);
} catch(err) {
console.error(`Advanced Macros | Error executing "${macro.name}" world script (ID: ${macro.id})`, err);
}
}
}

Hooks.once("setup", () => runWorldScripts("runAsWorldScriptSetup"));

Hooks.once("ready", () => {
Hooks.on("renderMacroConfig", (obj, html, data) => {
if (!game.user.isGM) return;
Expand All @@ -176,64 +192,59 @@ Hooks.once("ready", () => {
const typeGroup = form.find("select[name=type]").parent(".form-group");
const runForSpecificUser = macro.getFlag("advanced-macros", "runForSpecificUser");
const options = [
{ value: "", label: game.i18n.localize("advanced-macros.MACROS.none") },
{
value: "GM",
label: game.i18n.localize("USER.RoleGamemaster"),
selected: runForSpecificUser === "GM",
},
...["runForEveryone", "runForEveryoneElse", "runAsWorldScript"].map((run) => ({
...["runForEveryone", "runForEveryoneElse"].map((run) => ({
value: run,
label: game.i18n.localize(`advanced-macros.MACROS.${run}`),
selected: runForSpecificUser === run,
group: "DOCUMENT.Users"
})),
...["runAsWorldScriptSetup", "runAsWorldScript"].map((run) => ({
value: run,
label: game.i18n.localize(`advanced-macros.MACROS.${run}`),
selected: runForSpecificUser === run,
group: "advanced-macros.MACROS.WorldScript"
})),
...game.users
.filter((user) => !user.isGM)
...game.users.players
.map((user) => ({
value: user.id,
label: user.name,
selected: runForSpecificUser === user.id,
group: "PLAYERS.Title",
})),
]; // filter out null values
];

const optionElements = options
.map((option) => {
const selectedAttr = option.selected ? 'selected="selected"' : "";
return `<option value="${option.value}" ${selectedAttr}>${option.label}</option>`;
})
.join("");
const selected = options.find((option) => option.selected)?.value ?? "";
const select = foundry.applications.fields.createSelectInput({
name: "flags.advanced-macros.runForSpecificUser",
options,
value: selected,
blank: "",
labelAttr: "label",
localize: true,
disabled: !canRunAsGM(macro)
});

const specificOneDiv = $(`
<div class="form-group"
${macro.type === "chat" ? 'style="display: none"' : ""}
data-tooltip="${game.i18n.localize("advanced-macros.MACROS.runForSpecificUserTooltip")}"
data-tooltip-direction="UP">
<div class="form-group" ${macro.type === "chat" ? 'style="display: none"' : ""}>
<label>${game.i18n.localize("advanced-macros.MACROS.runForSpecificUser")}</label>
<select name="flags.advanced-macros.runForSpecificUser" ${canRunAsGM(macro) ? "" : "disabled"}>
${optionElements}
</select>
${select.outerHTML}
</div>
`);

specificOneDiv.insertAfter(typeGroup);

const typeSelect = form.find("select[name=type]");
const typeSelect = form.find("select[name='type']");
typeSelect.on("change", (event) => {
if (event.target.value === "chat") specificOneDiv.hide();
else specificOneDiv.show();
});
});
const worldScripts = game.macros.contents.filter(
(macro) => macro.getFlag("advanced-macros", "runForSpecificUser") === "runAsWorldScript"
);
for (const macro of worldScripts) {
try {
macro.execute();
console.debug(`Advanced Macros | Executed "${macro.name}" world script (ID: ${macro.id})`);
} catch(err) {
console.error(`Advanced Macros | Error executing "${macro.name}" world script (ID: ${macro.id})`, err);
}
}
runWorldScripts("runAsWorldScript");
});

/**
Expand Down

0 comments on commit 06aa961

Please sign in to comment.