From bca44ba682acd235492263c7fd3fd6fa53d96e97 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Sat, 26 Aug 2023 01:32:39 +0300 Subject: [PATCH] Conserve ending newlines in story string template --- public/script.js | 9 +++++++++ public/scripts/power-user.js | 22 ++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/public/script.js b/public/script.js index 81fd82730..437d8b90e 100644 --- a/public/script.js +++ b/public/script.js @@ -1638,6 +1638,15 @@ function scrollChatToBottom() { } } +/** + * Substitutes {{macro}} parameters in a string. + * @param {string} content - The string to substitute parameters in. + * @param {*} _name1 - The name of the user. Uses global name1 if not provided. + * @param {*} _name2 - The name of the character. Uses global name2 if not provided. + * @param {*} _original - The original message for {{original}} substitution. + * @param {*} _group - The group members list for {{group}} substitution. + * @returns {string} The string with substituted parameters. + */ function substituteParams(content, _name1, _name2, _original, _group) { _name1 = _name1 ?? name1; _name2 = _name2 ?? name2; diff --git a/public/scripts/power-user.js b/public/scripts/power-user.js index 0b4b6acb3..6f5481ff8 100644 --- a/public/scripts/power-user.js +++ b/public/scripts/power-user.js @@ -1015,17 +1015,35 @@ export function fuzzySearchGroups(searchValue) { return ids; } +/** + * Renders a story string template with the given parameters. + * @param {object} params Template parameters. + * @returns {string} The rendered story string. + */ export function renderStoryString(params) { try { + // compile the story string template into a function, with no HTML escaping const compiledTemplate = Handlebars.compile(power_user.context.story_string, { noEscape: true }); + + // render the story string template with the given params let output = compiledTemplate(params); + + // substitute {{macro}} params that are not defined in the story string output = substituteParams(output, params.user, params.char); - output = `${output.trim()}\n`; // add a newline to the end + + // remove leading whitespace + output = output.trimStart(); + + // add a newline to the end of the story string if it doesn't have one + if (!output.endsWith('\n')) { + output += '\n'; + } + return output; } catch (e) { toastr.error('Check the story string template for validity', 'Error rendering story string'); console.error('Error rendering story string', e); - throw e; + throw e; // rethrow the error } }