-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaster-release-sort-by-country.js
82 lines (69 loc) · 2.68 KB
/
master-release-sort-by-country.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// ==UserScript==
// @name Discogs Master Release Default Sort By Country
// @namespace https://www.discogs-enhancer.com
// @version 0.1
// @description Set MR release link to include custom filters by default
// @author Matthew Salcido (discogs.enhancer@gmail.com)
// @match https://www.discogs.com/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
function waitForElement(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
let observer = new MutationObserver(() => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector));
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
const SORT_ORDER = '?sort=country&sort_order=';
let int;
function modifyLinks() {
const links = [...document.querySelectorAll('a')];
links.forEach(link => {
if (link.href.includes('/master/')
&& !link.href.includes(SORT_ORDER)
&& !link.href.includes('/edit/')) {
const regex = /(\d+)$/gm;
// This is to deal with a redirect bug in Discogs where query paramters are not
// maintained after the redirect occurs
// https://www.discogs.com/group/thread/912187?page=1#9412085
if ( link.href.match(regex) ) {
const url = link.href.split('/');
const artist = url[url.length - 3];
const master = url[url.length - 2];
const id = url[url.length - 1];
// Assemble new URL
const newURL = `/${master}/${id}-${artist}`
link.href = newURL + SORT_ORDER
} else {
link.href += SORT_ORDER;
}
}
});
}
function addSearchListener() {
int = setInterval(modifyLinks, 250);
}
function removeSearchListener() {
clearInterval(int);
}
// General /master/ links on any page
modifyLinks();
// Release page specific /master/ links
waitForElement('#release-other-versions a').then(() => modifyLinks())
// Search Bar Results
const target = document.querySelector('#app') ? '[class*="search_"] input' : '#search_q';
document.querySelector(target).addEventListener('focus', addSearchListener, true);
document.querySelector(target).addEventListener('blur', removeSearchListener, true);
})();