Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 58 additions & 32 deletions src/modules/experiments/modules/sort-daily-draw-reverse/index.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,76 @@
/**
* Reverse daily_draw elements.
*/
const reverseDailyDrawElements = () => {
const container = document.querySelector('.daily_draw')?.parentElement;
if (! container) {
let originalTogglePopup;

const init = async () => {
if (originalTogglePopup) {
return;
}

const dailyDrawDivs = [...container.querySelectorAll('.daily_draw')];
if (dailyDrawDivs.length === 0) {
// Check if messenger exists (it should if loaded after page load, usually)
if (! messenger?.UI?.notification) {
return;
}

const emptyDiv = container.querySelector('.empty');
originalTogglePopup = messenger.UI.notification.togglePopup;

dailyDrawDivs.reverse().forEach((div) => {
if (emptyDiv) {
emptyDiv.before(div);
} else {
container.append(div);
}
});
};
messenger.UI.notification.togglePopup = function (...args) {
// Run the original function
const result = originalTogglePopup.apply(this, args);

let _originalTogglePopup;
// Start observing specifically for the daily draw to appear
const observer = new MutationObserver((_mutations, obs) => {
const dailyDraw = document.querySelector('.daily_draw');
if (dailyDraw) {
const container = dailyDraw.parentElement;
if (! container) {
return;
}

/**
* Initialize the module.
*/
const init = async () => {
if (_originalTogglePopup || ! messenger?.UI?.notification) {
return;
}
const dailyDrawDivs = [...container.querySelectorAll('.daily_draw')];
if (dailyDrawDivs.length === 0) {
return;
}

_originalTogglePopup = messenger.UI.notification.togglePopup;
// Check if sorted
const lastSorted = container._mhSortedChildren;
if (
lastSorted &&
lastSorted.length === dailyDrawDivs.length &&
lastSorted.every((el, index) => el === dailyDrawDivs[index])
) {
return;
}

const emptyDiv = container.querySelector('.empty');

// Reverse
dailyDrawDivs.reverse().forEach((div) => {
if (emptyDiv) {
emptyDiv.before(div);
} else {
container.append(div);
}
});

container._mhSortedChildren = [...container.querySelectorAll('.daily_draw')];
obs.disconnect();
}
});

// Observe body to catch wherever it gets inserted
observer.observe(document.body, {
childList: true,
subtree: true,
});

// Timeout to stop observing if it never appears
setTimeout(() => {
observer.disconnect();
}, 5000);

messenger.UI.notification.togglePopup = function (...args) {
const result = _originalTogglePopup.apply(this, args);
setTimeout(reverseDailyDrawElements, 400);
return result;
};
};

/**
* Module definition.
*/
export default {
id: 'reverse-daily-draw-order',
name: 'Daily Draw: Reverse Order',
Expand Down
Loading