Skip to content

Commit

Permalink
refactor: validate dom function
Browse files Browse the repository at this point in the history
  • Loading branch information
guivictorr committed Oct 29, 2023
1 parent 5a9ced2 commit ec93f61
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,42 @@ function addChorusButtonTo(node: Element) {
}

function validateBodyMutations(domMutation: MutationRecord) {
const addedNode = domMutation.addedNodes.item(0) as Element;
const isNodeValid =
typeof addedNode === 'object' &&
addedNode !== null &&
'getAttribute' in addedNode;
const addedNode = getFirstValidAddedNode(domMutation);

if (!isNodeValid) {
if (!addedNode) {
return;
}

const trackListRow = addedNode.querySelector(
'div[data-testid="tracklist-row"]',
);

if (trackListRow !== null) {
addChorusButtonTo(trackListRow.lastElementChild!);
}

const nowPlayingWidget = document.querySelector(
'[data-testid="now-playing-widget"]',
);

if (trackListRow) {
addChorusButtonTo(trackListRow.lastElementChild!);
}

if (nowPlayingWidget) {
addChorusButtonTo(nowPlayingWidget);
}
}

function getFirstValidAddedNode(domMutation: MutationRecord) {
const addedNode = domMutation.addedNodes.item(0) as Element;

if (isValidElement(addedNode)) {
return addedNode;
}

return null;
}

function isValidElement(element: Element | null): boolean {
return element instanceof Element && element.getAttribute !== undefined;
}

const observer = new MutationObserver(mutations => {
mutations.forEach(validateBodyMutations);
});
Expand Down

0 comments on commit ec93f61

Please sign in to comment.