This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathiconfix.user.js
343 lines (321 loc) · 13.5 KB
/
iconfix.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
// ==UserScript==
// @name iconfix
// @version 2.7
// @description fixes tumblr post headers
// @author dragongirlsnout
// @match https://www.tumblr.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=tumblr.com
// @downloadURL https://raw.githubusercontent.com/enchanted-sword/dashboard-unfucker/main/iconfix.user.js
// @updateURL https://raw.githubusercontent.com/enchanted-sword/dashboard-unfucker/main/iconfix.user.js
// @require https://code.jquery.com/jquery-3.6.4.min.js
// @grant none
// @run-at document-end
// ==/UserScript==
/* globals tumblr */
'use strict';
var $ = window.jQuery;
const main = async function () {
const $a = selector => document.querySelectorAll(selector);
const $str = str => {
let elem = document.createElement("div");
elem.innerHTML = str;
elem = elem.firstElementChild;
return elem;
};
const css = (elem, properties = {}) => {
for (let property in properties) {
elem.style[property] = properties[property];
};
};
const hide = elem => {
if (elem.length) elem.forEach(item => item.style.display = "none");
else elem.style.display = "none";
};
const waitFor = (selector, retried = 0,) => new Promise((resolve) => {
if ($a(selector).length) { resolve() } else if (retried < 50) { requestAnimationFrame(() => waitFor(selector, retried + 1).then(resolve)) }
});
const getUtilities = async function () {
let retries = 0;
while (retries++ < 1000 && (typeof window.tumblr === "undefined" || typeof window.tumblr.getCssMap === "undefined")) {
await new Promise((resolve) => setTimeout(resolve));
}
const cssMap = await window.tumblr.getCssMap();
const keyToClasses = (...keys) => keys.flatMap(key => cssMap[key]).filter(Boolean);
const keyToCss = (...keys) => `:is(${keyToClasses(...keys).map(className => `.${className}`).join(", ")})`;
const tr = string => `${window.tumblr.languageData.translations[string] || string}`;
return { keyToClasses, keyToCss, tr };
};
getUtilities().then(({ keyToCss, keyToClasses, tr }) => {
const state = window.___INITIAL_STATE___
const userName = state.queries.queries[0].state.data.user.name;
const postSelector = '[tabindex="-1"][data-id] article';
const postHeaderTargetSelector = `${keyToCss('main')} > :not(${keyToCss('blogTimeline')}) [data-timeline]:not([data-timeline*='posts/'],${keyToCss('masonry')}) [tabindex='-1'][data-id] article:not(.ΘΔavatarFixed)`;
const newNodes = [];
const target = document.getElementById("root");
const userAvatar = name => $str(`
<div class="ΘΔavatarOuter">
<div class="ΘΔavatarWrapper" role="figure" aria-label="${tr("avatar")}">
<span class="ΘΔtargetWrapper">
<a href="https://${name}.tumblr.com/" title="${name}" target="_blank" rel="noopener" role="link" class="ΘΔblogLink" tabindex="0">
<div class="ΘΔavatarInner" style="width: 64px; height: 64px;">
<div class="ΘΔavatarWrapperInner">
<div class="ΘΔplaceholder" style="padding-bottom: 100%;">
<img
class="ΘΔavatarImage"
src="https://api.tumblr.com/v2/blog/${name}/avatar"
sizes="64px"
alt="${tr("Avatar")}"
style="width: 64px; height: 64px;"
loading="eager">
</div>
</div>
</div>
</a>
</span>
</div>
</div>
`);
const addUserPortrait = () => {
const bar = $(`${keyToCss('postColumn')} > ${keyToCss('bar')}`);
if (bar) {
const userAvatarWrapper = $str('<div class="ΘΔuserAvatarWrapper"></div>');
bar.prepend(userAvatarWrapper);
if (location.pathname.split('/')[1] === 'blog') userAvatarWrapper.append(userAvatar(location.pathname.split('/')[2]));
else userAvatarWrapper.append(userAvatar(userName));
userAvatarWrapper.querySelector('.ΘΔblogLink').addEventListener('click', () => window.tumblr.navigate(`/${userName}`));
}
};
const fixHeaderAvatar = posts => {
for (const post of posts) {
try {
const stickyContainer = $str(`<div class="ΘΔstickyContainer"></div>`);
const avatar = post.querySelector(`header > ${keyToCss('avatar')}`);
post.prepend(stickyContainer);
stickyContainer.append(avatar);
avatar.querySelector(`${keyToCss('targetWrapper')} img`).sizes = "64px";
avatar.querySelectorAll(`${keyToCss('subAvatarTargetWrapper')} img`).forEach(img => img.sizes = "32px");
post.classList.add('ΘΔavatarFixed');
} catch (e) {
console.error('an error occurred processing a post avatar:', e);
console.error(post);
console.error(fetchNpf(post));
}
}
};
const reblogIcon = () => $str(`
<span class="ΘΔreblogIcon">
<svg xmlns="http://www.w3.org/2000/svg" height="15" width="15" role="presentation" style="--icon-color-primary: rgba(var(--black), 0.65);">
<use href="#managed-icon__reblog-compact"></use>
</svg>
</span>
`);
const fixHeader = posts => {
for (const post of posts) {
if (window.location.pathname.split('/').some(x => ['inbox', 'messages'].includes(x))) return;
try {
const { id, parentPostUrl } = fetchNpf(post);
post.id = `post${id}`;
const header = post.querySelector('header');
const attribution = header.querySelector(keyToCss('attribution'));
let rebloggedFrom = attribution.querySelector(keyToCss('rebloggedFromName'));
let addingNewRebloggedFrom = false;
let rebloggedFromName;
if (parentPostUrl) rebloggedFromName = parentPostUrl.split('/')[3];
if (!rebloggedFrom && rebloggedFromName) {
const labels = post.querySelectorAll(`:scope ${keyToCss('username')} ${keyToCss('label')}`);
if (labels.length !== 0) {
addingNewRebloggedFrom = true;
rebloggedFrom = [...labels].find(node => node.querySelector(keyToCss('attribution')).innerText === rebloggedFromName).cloneNode(true);
const classes = keyToClasses('rebloggedFromName');
rebloggedFrom.classList.add(...classes);
css(rebloggedFrom.querySelector(keyToCss('attribution')), { color: 'rgba(var(--black),.65)' });
const follow = rebloggedFrom.querySelector(keyToCss('followButton'));
if (follow) hide(follow);
}
}
[...attribution.childNodes].filter(node => node.nodeName === '#text').forEach(function (node) {node.textContent = ''});
if (addingNewRebloggedFrom) attribution.append(rebloggedFrom);
if (rebloggedFrom && !header.querySelector('.ΘΔreblogIcon')) {
rebloggedFrom.before(reblogIcon());
}
post.classList.add('ΘΔheaderFixed');
} catch (e) {
console.error('an error occurred processing a post header:', e);
console.error(post);
console.error(fetchNpf(post));
}
}
};
const fetchNpf = obj => {
const fiberKey = Object.keys(obj).find(key => key.startsWith("__reactFiber"));
let fiber = obj[fiberKey];
while (fiber !== null) {
const { timelineObject } = fiber.memoizedProps || {};
if (timelineObject !== undefined) {
return timelineObject;
} else {
fiber = fiber.return;
};
};
};
const sortNodes = () => {
const nodes = newNodes.splice(0);
if (nodes.length !== 0 && (nodes.some(node => node.matches(postSelector) || node.querySelector(postSelector)))) {
const posts = [
...nodes.filter(node => node.matches(postSelector)),
...nodes.flatMap(node => [...node.querySelectorAll(postSelector)])
].filter((value, index, array) => index === array.indexOf(value));
if (posts.length) fixHeader(posts);
}
if (nodes.length !== 0 && (nodes.some(node => node.matches(postHeaderTargetSelector) || node.querySelector(postHeaderTargetSelector)))) {
const posts = [
...nodes.filter(node => node.matches(postHeaderTargetSelector)),
...nodes.flatMap(node => [...node.querySelectorAll(postHeaderTargetSelector)])
].filter((value, index, array) => index === array.indexOf(value));
if (posts.length) fixHeaderAvatar(posts);
}
};
const observer = new MutationObserver(mutations => {
const nodes = mutations
.flatMap(({ addedNodes }) => [...addedNodes])
.filter(node => node instanceof Element)
.filter(node => node.isConnected);
newNodes.push(...nodes);
sortNodes();
});
const style = $str(`
<style>
div:not(${keyToCss('mainContentIsMasonry')}) > div > ${keyToCss("main")}${keyToCss("reblogRedesignEnabled")} { max-width: 625px !important; }
${keyToCss("tabsHeader")} { margin-left: -93px !important ;}
${keyToCss("mainContentWrapper")}${keyToCss("reblogRedesignEnabled")} { min-width: 890px !important; flex-basis: 890px !important; }
article.ΘΔheaderFixed header ${keyToCss('communityLabel')} { display: none !important; }
.ΘΔreblogIcon {
height: 14px;
display: inline-block;
transform: translateY(3px);
margin: 0 5px;
}
.ΘΔuserAvatarWrapper {
top: 0;
position: absolute;
left: -84px;
}
.ΘΔuserAvatarWrapper > .ΘΔavatarOuter {
position: absolute !important;
top: 0 !important;
}
.ΘΔstickyContainer {
color: RGB(var(--white-on-dark));
height: 100%;
position: absolute;
left: -84px;
}
.ΘΔstickyContainer > ${keyToCss('avatar')} {
position: sticky;
top: 18px;
transition: top .25s;
}
.ΘΔstickyContainer ${keyToCss('blogLink')} > ${keyToCss('avatar')},
.ΘΔstickyContainer ${keyToCss('blogLink')} > ${keyToCss('avatar')} ${keyToCss('image')},
.ΘΔstickyContainer ${keyToCss('anonymous')} {
width: 64px !important;
height: 64px !important;
}
.ΘΔstickyContainer ${keyToCss('blogLink')} > ${keyToCss('subavatar')},
.ΘΔstickyContainer ${keyToCss('blogLink')} > ${keyToCss('subavatar')} ${keyToCss('image')} {
width: 32px !important;
height: 32px !important;
}
.ΘΔstickyContainer ${keyToCss('badge')} { display: none; }
.ΘΔavatarOuter {
position: sticky;
top: 18px;
transition: top .25s;
}
.ΘΔavatarWrapper { position: relative; }
.ΘΔblogLink {
cursor: pointer;
word-break: break-word;
text-decoration: none;
}
.ΘΔtargetWrapper {
width: inherit;
vertical-align: top;
display: inline-block;
}
.ΘΔavatarInner { position: relative; }
.ΘΔavatarWrapperInner {
border-radius: var(--border-radius-small);
width: 100%;
height: 100%;
overflow: hidden;
}
.ΘΔplaceholder {
width: 100%;
line-height: 0;
position: relative;
}
.ΘΔavatarImage {
position: absolute;
top: 0;
left: 0;
object-fit: cover;
visibility: visible;
}
figure${keyToCss('anonymous')} { background-image: url(https://assets.tumblr.com/pop/src/assets/images/avatar/anonymous_avatar_96-223fabe0.png) !important; }
${keyToCss('attribution')} > ${keyToCss('badgeContainer')} { margin-left: 5px; }
</style>
`);
const unfuck = async function () {
requestAnimationFrame(() => {
observer.observe(target, { childList: true, subtree: true });
fixHeader(Array.from($a(postSelector)));
fixHeaderAvatar(Array.from($a(postHeaderTargetSelector)));
addUserPortrait();
document.head.appendChild(style);
});
console.log("icons fixed!");
};
unfuck();
window.tumblr.on('navigation', () => window.setTimeout(() => {
unfuck().then(() => {
window.setTimeout(() => {
if (!$a("#__m").length) unfuck();
}, 400)
}).catch((e) =>
window.setTimeout(unfuck, 400)
)}, 400
));
});
};
const getNonce = () => {
const { nonce } = [...document.scripts].find(script => script.getAttributeNames().includes("nonce")) || "";
return nonce;
}
const script = $(`
<script id="__u" nonce="${getNonce()}">
const unfuckDashboard = ${main.toString()};
unfuckDashboard();
</script>
`);
if ($("head").length === 0) {
const newNodes = [];
const findHead = () => {
const nodes = newNodes.splice(0);
if (nodes.length !== 0 && (nodes.some(node => node.matches("head") || node.querySelector("head") !== null))) {
const head = nodes.find(node => node.matches("head"));
script.attr("nonce", getNonce());
$(head).append(script);
}
};
const observer = new MutationObserver(mutations => {
const nodes = mutations
.flatMap(({ addedNodes }) => [...addedNodes])
.filter(node => node instanceof Element)
.filter(node => node.isConnected);
newNodes.push(...nodes);
findHead();
});
observer.observe(document.documentElement, { childList: true, subtree: true });
} else $(document.head).append(script);
if (script.attr("nonce") === "") console.error("empty script nonce attribute: script may not inject");