From 31d339b46b9fc11e50a0cdbf53e937e575531efd Mon Sep 17 00:00:00 2001 From: IRONM00N <64110067+IRONM00N@users.noreply.github.com> Date: Sat, 28 May 2022 12:43:42 -0400 Subject: feat: custom stripIndent --- src/commands/dev/servers.ts | 10 ++-- src/commands/info/snowflake.ts | 60 ++++++++++------------ src/commands/moulberry-bush/report.ts | 21 ++++---- src/commands/utilities/suicide.ts | 21 ++++---- src/lib/badwords.ts | 2 +- src/lib/common/tags.ts | 34 ++++++++++++ src/listeners/bush/supportThread.ts | 8 +-- src/listeners/commands/commandError.ts | 2 +- .../contextCommands/contextCommandError.ts | 2 +- 9 files changed, 95 insertions(+), 65 deletions(-) create mode 100644 src/lib/common/tags.ts (limited to 'src') diff --git a/src/commands/dev/servers.ts b/src/commands/dev/servers.ts index 72fc7d7..0701158 100644 --- a/src/commands/dev/servers.ts +++ b/src/commands/dev/servers.ts @@ -1,4 +1,5 @@ import { BushCommand, ButtonPaginator, type BushMessage, type BushSlashMessage } from '#lib'; +import { stripIndent } from '#tags'; import type { APIEmbed } from 'discord-api-types/v10'; import type { Guild } from 'discord.js'; @@ -25,11 +26,10 @@ export default class ServersCommand extends BushCommand { color: util.colors.default, fields: chunk.map((guild) => ({ name: util.format.input(guild.name), - value: [ - `**ID:** ${guild.id}`, - `**Owner:** ${client.users.cache.has(guild.ownerId) ? client.users.cache.get(guild.ownerId)!.tag : guild.ownerId}`, - `**Members:** ${guild.memberCount.toLocaleString()}` - ].join('\n') + value: stripIndent` + **ID:** ${guild.id} + **Owner:** ${client.users.cache.has(guild.ownerId) ? client.users.cache.get(guild.ownerId)!.tag : guild.ownerId} + **Members:** ${guild.memberCount.toLocaleString()}` })) } as APIEmbed; }); diff --git a/src/commands/info/snowflake.ts b/src/commands/info/snowflake.ts index 933b1ac..07544c9 100644 --- a/src/commands/info/snowflake.ts +++ b/src/commands/info/snowflake.ts @@ -1,4 +1,5 @@ import { BushCommand, type ArgType, type BushMessage, type BushSlashMessage } from '#lib'; +import { stripIndent } from '#tags'; import { ApplicationCommandOptionType, ChannelType, @@ -73,15 +74,12 @@ export default class SnowflakeCommand extends BushCommand { // Guild if (client.guilds.cache.has(snowflake)) { const guild: Guild = client.guilds.cache.get(snowflake)!; - const guildInfo = [ - `**Name:** ${util.discord.escapeMarkdown(guild.name)}`, - `**Owner:** ${util.discord.escapeMarkdown(client.users.cache.get(guild.ownerId)?.tag ?? '¯\\_(ツ)_/¯')} (${ - guild.ownerId - })`, - `**Members:** ${guild.memberCount?.toLocaleString()}` - ]; + const guildInfo = stripIndent` + **Name:** ${util.discord.escapeMarkdown(guild.name)} + **Owner:** ${util.discord.escapeMarkdown(client.users.cache.get(guild.ownerId)?.tag ?? '¯\\_(ツ)_/¯')} (${guild.ownerId}) + **Members:** ${guild.memberCount?.toLocaleString()}`; if (guild.icon) snowflakeEmbed.setThumbnail(guild.iconURL({ size: 2048 })!); - snowflakeEmbed.addFields([{ name: '» Server Info', value: guildInfo.join('\n') }]); + snowflakeEmbed.addFields([{ name: '» Server Info', value: guildInfo }]); snowflakeEmbed.setTitle(`:snowflake: ${util.discord.escapeMarkdown(guild.name)} \`[Server]\``); } @@ -89,50 +87,48 @@ export default class SnowflakeCommand extends BushCommand { const fetchedUser = await client.users.fetch(`${snowflake}`).catch(() => undefined); if (client.users.cache.has(snowflake) || fetchedUser) { const user: User = (client.users.cache.get(snowflake) ?? fetchedUser)!; - const userInfo = [`**Name:** <@${user.id}> (${util.discord.escapeMarkdown(user.tag)})`]; + const userInfo = stripIndent` + **Name:** <@${user.id}> (${util.discord.escapeMarkdown(user.tag)})`; if (user.avatar) snowflakeEmbed.setThumbnail(user.avatarURL({ size: 2048 })!); - snowflakeEmbed.addFields([{ name: '» User Info', value: userInfo.join('\n') }]); + snowflakeEmbed.addFields([{ name: '» User Info', value: userInfo }]); snowflakeEmbed.setTitle(`:snowflake: ${util.discord.escapeMarkdown(user.tag)} \`[User]\``); } // Emoji if (client.emojis.cache.has(snowflake)) { const emoji = client.emojis.cache.get(snowflake)!; - const emojiInfo = [ - `**Name:** ${util.discord.escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')}`, - `**Animated:** ${emoji.animated}` - ]; + const emojiInfo = stripIndent` + **Name:** ${util.discord.escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')} + **Animated:** ${emoji.animated}`; if (emoji.url) snowflakeEmbed.setThumbnail(emoji.url); - snowflakeEmbed.addFields([{ name: '» Emoji Info', value: emojiInfo.join('\n') }]); + snowflakeEmbed.addFields([{ name: '» Emoji Info', value: emojiInfo }]); snowflakeEmbed.setTitle(`:snowflake: ${util.discord.escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')} \`[Emoji]\``); } // Role if (message.guild && message.guild.roles.cache.has(snowflake)) { const role: Role = message.guild.roles.cache.get(snowflake)!; - const roleInfo = [ - `**Name:** <@&${role.id}> (${util.discord.escapeMarkdown(role.name)})`, - `**Members:** ${role.members.size}`, - `**Hoisted:** ${role.hoist}`, - `**Managed:** ${role.managed}`, - `**Position:** ${role.position}`, - `**Hex Color:** ${role.hexColor}` - ]; + const roleInfo = stripIndent` + **Name:** <@&${role.id}> (${util.discord.escapeMarkdown(role.name)}) + **Members:** ${role.members.size} + **Hoisted:** ${role.hoist} + **Managed:** ${role.managed} + **Position:** ${role.position} + **Hex Color:** ${role.hexColor}`; if (role.color) snowflakeEmbed.setColor(role.color); - snowflakeEmbed.addFields([{ name: '» Role Info', value: roleInfo.join('\n') }]); + snowflakeEmbed.addFields([{ name: '» Role Info', value: roleInfo }]); snowflakeEmbed.setTitle(`:snowflake: ${util.discord.escapeMarkdown(role.name)} \`[Role]\``); } // SnowflakeInfo const deconstructedSnowflake: DeconstructedSnowflake = SnowflakeUtil.deconstruct(snowflake); - const snowflakeInfo = [ - `**Timestamp:** ${deconstructedSnowflake.timestamp}`, - `**Created:** ${util.timestamp(new Date(Number(deconstructedSnowflake.timestamp)))}`, - `**Worker ID:** ${deconstructedSnowflake.workerId}`, - `**Process ID:** ${deconstructedSnowflake.processId}`, - `**Increment:** ${deconstructedSnowflake.increment}` - ]; - snowflakeEmbed.addFields([{ name: '» Snowflake Info', value: snowflakeInfo.join('\n') }]); + const snowflakeInfo = stripIndent` + **Timestamp:** ${deconstructedSnowflake.timestamp} + **Created:** ${util.timestamp(new Date(Number(deconstructedSnowflake.timestamp)))} + **Worker ID:** ${deconstructedSnowflake.workerId} + **Process ID:** ${deconstructedSnowflake.processId} + **Increment:** ${deconstructedSnowflake.increment}`; + snowflakeEmbed.addFields([{ name: '» Snowflake Info', value: snowflakeInfo }]); return await message.util.reply({ embeds: [snowflakeEmbed] }); } diff --git a/src/commands/moulberry-bush/report.ts b/src/commands/moulberry-bush/report.ts index f8f6371..0561e13 100644 --- a/src/commands/moulberry-bush/report.ts +++ b/src/commands/moulberry-bush/report.ts @@ -1,4 +1,5 @@ import { AllowedMentions, BushCommand, type ArgType, type BushMessage } from '#lib'; +import { stripIndent } from '#tags'; import assert from 'assert'; import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; @@ -74,21 +75,19 @@ export default class ReportCommand extends BushCommand { .addFields([ { name: 'Reporter', - value: [ - `**Name:**${message.author.tag} <@${message.author.id}>`, - `**Joined:** $${util.timestampAndDelta(message.member!.joinedAt!)}`, - `**Created:** ${util.timestampAndDelta(message.author.createdAt)}`, - `**Sent From**: <#${message.channel.id}> [Jump to context](${message.url})` - ].join('\n'), + value: stripIndent` + **Name:**${message.author.tag} <@${message.author.id}> + **Joined:** $${util.timestampAndDelta(message.member!.joinedAt!)} + **Created:** ${util.timestampAndDelta(message.author.createdAt)} + **Sent From**: <#${message.channel.id}> [Jump to context](${message.url})`, inline: true }, { name: 'Reported User', - value: [ - `**Name:**${member.user.tag} <@${member.user.id}>`, - `**Joined:** $${util.timestampAndDelta(member.joinedAt!)}`, - `**Created:** ${util.timestampAndDelta(member.user.createdAt)}` - ].join('\n'), + value: stripIndent` + **Name:**${member.user.tag} <@${member.user.id}> + **Joined:** $${util.timestampAndDelta(member.joinedAt!)} + **Created:** ${util.timestampAndDelta(member.user.createdAt)}`, inline: true } ]); diff --git a/src/commands/utilities/suicide.ts b/src/commands/utilities/suicide.ts index 2cc16f0..e4609f2 100644 --- a/src/commands/utilities/suicide.ts +++ b/src/commands/utilities/suicide.ts @@ -1,4 +1,5 @@ import { AllowedMentions, BushCommand, type BushMessage, type BushSlashMessage } from '#lib'; +import { stripIndent } from '#tags'; import { EmbedBuilder } from 'discord.js'; export default class SuicideCommand extends BushCommand { @@ -29,20 +30,18 @@ export default class SuicideCommand extends BushCommand { .addFields([ { name: '**National Suicide Prevention Hotline (U.S.):**', - value: [ - '**Call:** 1-800-273-8255, available 24/7 for emotional support', - '**Text: HOME** to 741741', - 'https://suicidepreventionlifeline.org/chat/', - '', - '**Outside the U.S:** Find a supportive resource on [this Wikipedia list of worldwide crisis hotlines](https://en.wikipedia.org/wiki/List_of_suicide_crisis_lines)' - ].join('\n') + value: stripIndent` + **Call:** 1-800-273-8255, available 24/7 for emotional support + **Text: HOME** to 741741 + https://suicidepreventionlifeline.org/chat/ + + **Outside the U.S:** Find a supportive resource on [this Wikipedia list of worldwide crisis hotlines](https://en.wikipedia.org/wiki/List_of_suicide_crisis_lines)` }, { name: '**More Support**', - value: [ - 'For Substance Abuse Support, Eating Disorder Support & Child Abuse and Domestic Violence:', - "[Click to go to Discord's Health & Safety Page](https://discord.com/safety/360044103771-Mental-health-on-Discord#h_01EGRGT08QSZ5BNCH2E9HN0NYV)" - ].join('\n') + value: stripIndent` + For Substance Abuse Support, Eating Disorder Support & Child Abuse and Domestic Violence: + [Click to go to Discord's Health & Safety Page](https://discord.com/safety/360044103771-Mental-health-on-Discord#h_01EGRGT08QSZ5BNCH2E9HN0NYV)` } ]); diff --git a/src/lib/badwords.ts b/src/lib/badwords.ts index aacf152..d9df53a 100644 --- a/src/lib/badwords.ts +++ b/src/lib/badwords.ts @@ -704,7 +704,7 @@ export default { ], /* -------------------------------------------------------------------------- */ - /* Advertising */ + /* Advertising */ /* -------------------------------------------------------------------------- */ "Advertising": [ { diff --git a/src/lib/common/tags.ts b/src/lib/common/tags.ts new file mode 100644 index 0000000..098cf29 --- /dev/null +++ b/src/lib/common/tags.ts @@ -0,0 +1,34 @@ +/* these functions are adapted from the common-tags npm package which is licensed under the MIT license */ +/* the js docs are adapted from the @types/common-tags npm package which is licensed under the MIT license */ + +/** + * Strips the **initial** indentation from the beginning of each line in a multiline string. + */ +export function stripIndent(strings: TemplateStringsArray, ...expressions: any[]) { + const str = format(strings, ...expressions); + // remove the shortest leading indentation from each line + const match = str.match(/^[^\S\n]*(?=\S)/gm); + const indent = match && Math.min(...match.map((el) => el.length)); + if (indent) { + const regexp = new RegExp(`^.{${indent}}`, 'gm'); + return str.replace(regexp, ''); + } + return str; +} + +/** + * Strips **all** of the indentation from the beginning of each line in a multiline string. + */ +export function stripIndents(strings: TemplateStringsArray, ...expressions: any[]) { + const str = format(strings, ...expressions); + // remove all indentation from each line + return str.replace(/^[^\S\n]+/gm, ''); +} + +function format(strings: TemplateStringsArray, ...expressions: any[]) { + const str = strings + .reduce((result, string, index) => ''.concat(result, expressions[index - 1], string)) + .replace(/[^\S\n]+$/gm, '') + .replace(/^\n/, ''); + return str; +} diff --git a/src/listeners/bush/supportThread.ts b/src/listeners/bush/supportThread.ts index c3294ef..e809176 100644 --- a/src/listeners/bush/supportThread.ts +++ b/src/listeners/bush/supportThread.ts @@ -1,4 +1,5 @@ import { BushListener, BushTextChannel, type BushClientEvents } from '#lib'; +import { stripIndent } from '#tags'; import assert from 'assert'; import { EmbedBuilder, MessageType, PermissionFlagsBits } from 'discord.js'; @@ -43,10 +44,11 @@ export default class SupportThreadListener extends BushListener { const embed = new EmbedBuilder() .setTitle('NotEnoughUpdates Support') .setDescription( - `Welcome to Moulberry Bush Support:tm: + stripIndent` + Welcome to Moulberry Bush Support:tm: -Please make sure you have the latest version found in <#693586404256645231>. -Additionally if you need help installing the mod be sure to read <#737444942724726915> for a guide on how to do so.` + Please make sure you have the latest version found in <#693586404256645231>. + Additionally if you need help installing the mod be sure to read <#737444942724726915> for a guide on how to do so.` ) .setColor(util.colors.Blurple); void thread diff --git a/src/listeners/commands/commandError.ts b/src/listeners/commands/commandError.ts index 895cff0..6d669a1 100644 --- a/src/listeners/commands/commandError.ts +++ b/src/listeners/commands/commandError.ts @@ -136,7 +136,7 @@ export default class CommandErrorListener extends BushListener { }n error occurred. Please give the developers code ${util.format.input(`${options.errorNum}`)}.` ); } - const description = new Array(); + const description: string[] = []; if (options.type === 'command-log') { description.push( diff --git a/src/listeners/contextCommands/contextCommandError.ts b/src/listeners/contextCommands/contextCommandError.ts index 86cbac8..45e1114 100644 --- a/src/listeners/contextCommands/contextCommandError.ts +++ b/src/listeners/contextCommands/contextCommandError.ts @@ -101,7 +101,7 @@ export default class ContextCommandErrorListener extends BushListener { }n error occurred. Please give the developers code ${util.format.input(`${options.errorNum}`)}.` ); } - const description = new Array(); + const description: string[] = []; if (options.type === 'command-log') { description.push( -- cgit