-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fix-pixiv-thumbnails.user.js
367 lines (328 loc) · 14.2 KB
/
Fix-pixiv-thumbnails.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/* eslint-disable max-len */
// ==UserScript==
// @name Improve pixiv thumbnails
// @name:ja pixivサムネイルを改善する
// @namespace https://www.kepstin.ca/userscript/
// @license MIT; https://spdx.org/licenses/MIT.html
// @version 20240918.2
// @description Stop pixiv from cropping thumbnails to a square. Use higher resolution thumbnails on Retina displays.
// @description:ja 正方形にトリミングされて表示されるのを防止します。Retinaディスプレイで高解像度のサムネイルを使用します。
// @author Calvin Walton
// @match https://www.pixiv.net/*
// @match https://dic.pixiv.net/*
// @match https://en-dic.pixiv.net/*
// @exclude https://www.pixiv.net/fanbox*
// @noframes
// @run-at document-start
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_addValueChangeListener
// ==/UserScript==
/* eslint-enable max-len */
/* global GM_addValueChangeListener */
// Copyright © 2020 Calvin Walton <calvin.walton@kepstin.ca>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(function kepstinFixPixivThumbnails () {
'use strict'
// Use an alternate domain (CDN) to load images
// Configure this by setting `domainOverride` in userscript values
let domainOverride = ''
// Use custom (uploader-provided) thumbnail crops
// If you enable this setting, then if the uploader has set a custom square crop on the image, it will
// be used. Automatically cropped images will continue to be converted to uncropped images
// Configure this by setting `allowCustom` in userscript values
let allowCustom = false
// Browser feature detection for CSS 4 image-set()
let imageSetSupported = false
let imageSetPrefix = ''
if (CSS.supports('background-image', 'image-set(url("image1") 1x, url("image2") 2x)')) {
imageSetSupported = true
} else if (CSS.supports('background-image', '-webkit-image-set(url("image1") 1x, url("image2") 2x)')) {
imageSetSupported = true
imageSetPrefix = '-webkit-'
}
// A regular expression that matches pixiv thumbnail urls
// Has 5 captures:
// $1: domain name
// $2: thumbnail width (optional)
// $3: thumbnail height (optional)
// $4: everything in the URL after the thumbnail size up to the image suffix
// $5: thumbnail crop type: square (auto crop), custom (manual crop), master (no crop)
// eslint-disable-next-line max-len
const srcRegexp = /https?:\/\/(i[^.]*\.pximg\.net)(?:\/c\/(\d+)x(\d+)(?:_[^/]*)?)?\/(?:custom-thumb|img-master)\/(.*?)_(custom|master|square)1200.jpg/
// Look for a URL pattern for a thumbnail image in a string and return its properties
// Returns null if no image found, otherwise a structure containing the domain, width, height, path.
function matchThumbnail (str) {
const m = str.match(srcRegexp)
if (!m) { return null }
let [_, domain, width, height, path, crop] = m
// The 1200 size does not include size in the URL, so fill in the values here when missing
width = width || 1200
height = height || 1200
if (domainOverride) { domain = domainOverride }
return { domain, width, height, path, crop }
}
// List of image sizes and paths possible for original aspect thumbnail images
// This must be in order from small to large for the image set generation to work
const imageSizes = [
{ size: 150, path: '/c/150x150' },
{ size: 240, path: '/c/240x240' },
{ size: 360, path: '/c/360x360_70' },
{ size: 600, path: '/c/600x600' },
{ size: 1200, path: '' }
]
// Generate a list of original thumbnail images in various sizes for an image,
// and determine a default image based on the display size and screen resolution
function genImageSet (size, m) {
if (allowCustom && m.crop === 'custom') {
return imageSizes.map((imageSize) => ({
src: `https://${m.domain}${imageSize.path}/custom-thumb/${m.path}_custom1200.jpg`,
scale: imageSize.size / size
}))
}
return imageSizes.map((imageSize) => ({
src: `https://${m.domain}${imageSize.path}/img-master/${m.path}_master1200.jpg`,
scale: imageSize.size / size
}))
}
// Create a srcset= attribute on the img, with appropriate dpi scaling values
// Also update the src= attribute
function imgSrcset (img, size, m) {
const imageSet = genImageSet(size, m)
img.srcset = imageSet.map((image) => `${image.src} ${image.scale}x`).join(', ')
// IMG tag src attribute is assumed to be 1x scale
const defaultSrc = imageSet.find((image) => image.scale >= 1) || imageSet[imageSet.length - 1]
img.src = defaultSrc.src
img.style.objectFit = 'contain'
if (!img.attributes.width && !img.style.width) { img.setAttribute('width', size) }
if (!img.attributes.height && !img.style.height) { img.setAttribute('height', size) }
}
// Set up a css background-image with image-set() where supported, falling back
// to a single image
function cssImageSet (node, size, m) {
const imageSet = genImageSet(size, m)
node.style.backgroundSize = 'contain'
node.style.backgroundPosition = 'center'
node.style.backgroundRepeat = 'no-repeat'
if (imageSetSupported) {
const cssImageList = imageSet.map((image) => `url("${image.src}") ${image.scale}x`).join(', ')
node.style.backgroundImage = `${imageSetPrefix}image-set(${cssImageList})`
} else {
const optimalSrc = imageSet.find((image) => image.scale >= window.devicePixelRatio) || imageSet[imageSet.length - 1]
node.style.backgroundImage = `url("${optimalSrc.src}")`
}
}
// Parse a CSS length value to a number of pixels. Returns NaN for other units.
function cssPx (value) {
if (!value.endsWith('px')) { return NaN }
return +value.replace(/[^\d.-]/g, '')
}
function findParentSize (node) {
let e = node
while (e.parentElement) {
let size = Math.max(e.getAttribute('width'), e.getAttribute('height'))
if (size > 0) { return size }
size = Math.max(cssPx(e.style.width), cssPx(e.style.height))
if (size > 0) { return size }
e = e.parentElement
}
e = node
while (e.parentElement) {
const cstyle = window.getComputedStyle(e)
const size = Math.max(cssPx(cstyle.width), cssPx(cstyle.height))
if (size > 0) { return size }
e = e.parentElement
}
return 0
}
function handleImg (node) {
if (node.dataset.kepstinThumbnail === 'bad') { return }
// Check for lazy-loaded images, which have a temporary URL
// They'll be updated later when the src is set
if (node.src === '' || node.src.startsWith('data:') || node.src.endsWith('transparent.gif')) { return }
// Terrible hack: A few pages on pixiv create temporary IMG tags to... preload? the images, then switch
// to setting a background on a DIV afterwards. This would be fine, except the temporary images have
// the height/width set to 0, breaking the hidpi image selection
if (
node.getAttribute('width') === '0' && node.getAttribute('height') === '0' &&
/^\/(?:discovery|(?:bookmark|mypixiv)_new_illust(?:_r18)?\.php)/.test(window.location.pathname)
) {
// Set the width/height to the expected values
node.setAttribute('width', 198)
node.setAttribute('height', 198)
}
const m = matchThumbnail(node.src || node.srcset)
if (!m) { node.dataset.kepstinThumbnail = 'bad'; return }
if (node.dataset.kepstinThumbnail === m.path) { return }
// Cancel image load if it's not already loaded
if (!node.complete) {
node.src = ''
node.srcset = ''
}
// layout-thumbnail type don't have externally set size, but instead element size is determined
// from image size. For other types we have to calculate size.
let size = Math.max(m.width, m.height)
if (node.matches('div._layout-thumbnail img')) {
node.setAttribute('width', m.width)
node.setAttribute('height', m.height)
} else {
const newSize = findParentSize(node)
if (newSize > 16) { size = newSize }
}
imgSrcset(node, size, m)
node.dataset.kepstinThumbnail = m.path
}
function handleCSSBackground (node) {
if (node.dataset.kepstinThumbnail === 'bad') { return }
// Check for lazy-loaded images
// They'll be updated later when the background image (in style attribute) is set
if (
node.classList.contains('js-lazyload') ||
node.classList.contains('lazyloaded') ||
node.classList.contains('lazyloading')
) { return }
const m = matchThumbnail(node.style.backgroundImage)
if (!m) { node.dataset.kepstinThumbnail = 'bad'; return }
if (node.dataset.kepstinThumbnail === m.path) { return }
node.style.backgroundImage = ''
let size = Math.max(cssPx(node.style.width), cssPx(node.style.height))
if (!(size > 0)) {
const cstyle = window.getComputedStyle(node)
size = Math.max(cssPx(cstyle.width), cssPx(cstyle.height))
}
if (!(size > 0)) { size = Math.max(m.width, m.height) }
cssImageSet(node, size, m)
node.dataset.kepstinThumbnail = m.path
}
function onetimeThumbnails (parentNode) {
parentNode.querySelectorAll('IMG').forEach((node) => {
handleImg(node)
})
parentNode.querySelectorAll('DIV[style*=background-image]').forEach((node) => {
handleCSSBackground(node)
})
parentNode.querySelectorAll('A[style*=background-image]').forEach((node) => {
handleCSSBackground(node)
})
}
function mutationObserverCallback (mutationList, _observer) {
mutationList.forEach((mutation) => {
const target = mutation.target
switch (mutation.type) {
case 'childList':
mutation.addedNodes.forEach((node) => {
if (node.nodeType !== Node.ELEMENT_NODE) return
if (node.nodeName === 'IMG') {
handleImg(node)
} else if ((node.nodeName === 'DIV' || node.nodeName === 'A') && node.style.backgroundImage) {
handleCSSBackground(node)
} else {
onetimeThumbnails(node)
}
})
break
case 'attributes':
if (target.nodeType !== Node.ELEMENT_NODE) break
if ((target.nodeName === 'DIV' || target.nodeName === 'A') && target.style.backgroundImage) {
handleCSSBackground(target)
} else if (target.nodeName === 'IMG') {
handleImg(target)
}
break
// no default
}
})
}
function addStylesheet() {
if (!(window.location.host == "www.pixiv.net")) { return; }
if (document.head === null) {
document.addEventListener("DOMContentLoaded", addStylesheet, { once: true });
return;
}
let s = document.createElement("style");
s.textContent = `
div:has(>div[width][height]), div:has(>label div[width][height]), div[type="illust"] {
border-radius: 0;
}
div[width][height]:hover img[data-kepstin-thumbnail], div[type="illust"] a:hover img {
opacity: 1 !important;
background-color: var(--charcoal-background1-hover);
}
div[radius] img[data-kepstin-thumbnail], div[type="illust"] img {
border-radius: 0;
background-color: var(--charcoal-background1);
transition: background-color 0.2s;
}
div[radius]::before, div[type="illust"] a > div::before {
border-radius: 0;
background: transparent;
box-shadow: inset 0 0 0 1px var(--charcoal-border);
}
`;
document.head.appendChild(s);
}
function loadSettings () {
const gmDomainOverride = GM_getValue('domainOverride')
if (typeof gmDomainOverride === 'undefined') {
// migrate settings
domainOverride = localStorage.getItem('kepstinDomainOverride') || ''
localStorage.removeItem('kepstinDomainOverride')
} else {
domainOverride = gmDomainOverride || ''
}
if (domainOverride !== gmDomainOverride) {
GM_setValue('domainOverride', domainOverride)
}
const gmAllowCustom = GM_getValue('allowCustom')
if (typeof gmAllowCustom === 'undefined') {
// migrate settings
allowCustom = !!localStorage.getItem('kepstinAllowCustom')
localStorage.removeItem('kepstinAllowCustom')
} else {
allowCustom = !!gmAllowCustom
}
if (allowCustom !== gmAllowCustom) {
GM_setValue('allowCustom', allowCustom)
}
}
if (typeof GM_getValue !== 'undefined' && typeof GM_setValue !== 'undefined') {
loadSettings()
}
if (typeof GM_addValueChangeListener !== 'undefined') {
GM_addValueChangeListener('domainOverride', (_name, _oldValue, newValue, remote) => {
if (!remote) { return }
domainOverride = newValue || ''
if (domainOverride !== newValue) {
GM_setValue('domainOverride', domainOverride)
}
})
GM_addValueChangeListener('allowCustom', (_name, _oldValue, newValue, remote) => {
if (!remote) { return }
allowCustom = !!newValue
if (allowCustom !== newValue) {
GM_setValue('allowCustom', allowCustom)
}
})
}
addStylesheet()
onetimeThumbnails(document.firstElementChild)
const thumbnailObserver = new MutationObserver(mutationObserverCallback)
thumbnailObserver.observe(document.firstElementChild, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['class', 'src', 'style']
})
}())