Skip to content

Commit

Permalink
Create document object in interaction handler scope (#31)
Browse files Browse the repository at this point in the history
* use jsdom document scoped within interaction

* rename variable
  • Loading branch information
AlecM33 authored Mar 23, 2024
1 parent 651e7e0 commit 7daa471
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
12 changes: 6 additions & 6 deletions modules/interaction-handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,6 @@ module.exports = {
wordcloudHandler: async (interaction) => {
console.info(`WORDCLOUD command invoked by guild: ${interaction.guildId}`);
await interaction.deferReply();
// TODO: d3-cloud requires that document be defined in the global scope. Long-term, this is a problem.
global.document = new JSDOM().window.document;
const author = interaction.options.getString('author')?.trim();
const quotesForCloud = author && author.length > 0
? await queries.getQuotesFromAuthor(author, interaction.guildId)
Expand All @@ -199,26 +197,28 @@ module.exports = {
return;
}
try {
const nodeDocument = new JSDOM().window.document;
const wordsWithOccurrences = utilities.mapQuotesToFrequencies(quotesForCloud);
const constructor = await wordcloudConstructor;
const initializationResult = constructor.initialize(
wordsWithOccurrences
.sort((a, b) => a.frequency >= b.frequency ? -1 : 1)
.slice(0, constants.MAX_WORDCLOUD_WORDS),
constants.WORDCLOUD_SIZE
constants.WORDCLOUD_SIZE,
nodeDocument
);
initializationResult.cloud.on('end', () => {
const d3 = constructor.draw(
initializationResult.cloud,
initializationResult.words,
global.document.body
nodeDocument.body
);
const buffer = Buffer.from(d3.select(global.document.body).node().innerHTML.toString());
const buffer = Buffer.from(d3.select(nodeDocument.body).node().innerHTML.toString());
sharp(buffer)
.resize(constants.WORDCLOUD_SIZE, constants.WORDCLOUD_SIZE)
.png()
.toBuffer()
.then(async (data) => {
.then(async data => {
await interaction.followUp({
files: [new AttachmentBuilder(data, { name: 'wordcloud.png' })],
content: author && author.length > 0
Expand Down
3 changes: 2 additions & 1 deletion modules/wordcloud-constructor.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const CONFIG = {

module.exports = import('d3').then((d3) => {
return {
initialize: (wordsWithOccurrences, size) => {
initialize: (wordsWithOccurrences, size, nodeDocument) => {
const wordcloud = cloud();
CONFIG.COLORS = randomColor({
luminosity: 'light',
Expand All @@ -30,6 +30,7 @@ module.exports = import('d3').then((d3) => {
.padding(CONFIG.WORD_PADDING)
.rotate(CONFIG.WORD_ROTATION)
.timeInterval(10)
.canvas(() => nodeDocument.createElement('canvas'))
.fontSize(function (d) {
return d.size;
});
Expand Down

0 comments on commit 7daa471

Please sign in to comment.