GreasyFork User Dashboard

It redesigns Greasy Fork镜像 user pages to improve the browsability.

目前為 2020-08-06 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name GreasyFork User Dashboard
  3. // @name:ja GreasyFork User Dashboard
  4. // @name:zh-CN GreasyFork User Dashboard
  5. // @description It redesigns Greasy Fork镜像 user pages to improve the browsability.
  6. // @description:ja Greasy Fork镜像 で一覧性に優れた新しいユーザーページを提供します。
  7. // @description:zh-CN 为 Greasy Fork镜像 提供一个一览性出色的新用户页面。
  8. // @namespace knoa.jp
  9. // @include https://gf.qytechs.cn/*/users/*
  10. // @include https://sleazyfork.org/*/users/*
  11. // @run-at document-start
  12. // @version 1.7.4
  13. // @grant none
  14. // ==/UserScript==
  15.  
  16. (function(){
  17. const SCRIPTID = 'GreasyForkUserDashboard';
  18. const SCRIPTNAME = 'GreasyFork User Dashboard';
  19. const DEBUG = false;/*
  20. [update] 1.7.4
  21. adjust for greasyfork update.
  22.  
  23. [bug]
  24.  
  25. [to do]
  26. 本来は履歴ページを見に行ってすべての更新日を保存、グラフに反映させるべき
  27. 履歴ページはその後、当該スクリプトの最終更新日が更新されるたびに見に行けば良い
  28. 1年以上経ったスクリプトに「いまも動作しますよ」的なアップデートを促したいけど・・・別スクリプトかな
  29.  
  30. [possible]
  31. 3カラムのレイアウト崩れる(スクリプト未使用でも発生する)
  32. グラフ数字の日付追加時くるりんぱは位置がズレるので労力に見合わないか
  33.  
  34. [not to do]
  35. */
  36. if(window === top && console.time) console.time(SCRIPTID);
  37. const MS = 1, SECOND = 1000*MS, MINUTE = 60*SECOND, HOUR = 60*MINUTE, DAY = 24*HOUR, WEEK = 7*DAY, MONTH = 30*DAY, YEAR = 365*DAY;
  38. const INTERVAL = 1*SECOND;/* for fetch */
  39. const DRAWINGDELAY = 125*MS;/* for drawing each charts */
  40. const UPDATELINKTEXT = '+';/* for update link text */
  41. const DEFAULTMAX = 10;/* for chart scale */
  42. const DAYS = 180;/* for chart length */
  43. const STATSUPDATE = 1*HOUR;/* stats update interval of gf.qytechs.cn */
  44. const TRANSLATIONEXPIRE = 30*DAY;/* cache time for translations */
  45. const STATSEXPIRE = 10*DAY;/* cache time for stats */
  46. const EASING = 'cubic-bezier(0,.75,.5,1)';/* quick easing */
  47. const STATSPATH = `/stats.csv?${SCRIPTID}`;
  48. let site = {
  49. targets: {
  50. aboutUser: () => $('#about-user'),
  51. userName: () => $('#about-user > h2'),
  52. userProfile: () => $('#user-profile'),
  53. discussions: () => $('#user-discussions'),
  54. scriptSets: () => $('#user-script-sets-section'),/* section for Script Sets */
  55. scripts: () => $('#user-script-list-section'),/* section for Scripts */
  56. userScriptSets: () => $('#user-script-sets'),
  57. userScriptList: () => $('#user-script-list'),
  58. },
  59. ownerTargets: {
  60. controlPanel: () => $('#control-panel'),
  61. newScriptSetLink: () => $('a[href$="/sets/new"]'),
  62. feedback: () => $('#user-discussions-on-scripts-written'),
  63. conversations: () => $('#user-conversations'),
  64. },
  65. get: {
  66. language: (d) => d.documentElement.lang,
  67. firstScript: (list) => list.querySelector('li h2 > a'),
  68. translation: (d, t) => {
  69. let es = {
  70. info: d.querySelector('#script-links > li.current'),
  71. code: d.querySelector('#script-links > li > a[href$="/code"]'),
  72. history: d.querySelector('#script-links > li > a[href$="/versions"]'),
  73. feedback: d.querySelector('#script-links > li > a[href$="/feedback"]'),
  74. stats: d.querySelector('#script-links > li > a[href$="/stats"]'),
  75. derivatives: d.querySelector('#script-links > li > a[href$="/derivatives"]'),
  76. update: d.querySelector('#script-links > li > a[href$="/versions/new"]'),
  77. delete: d.querySelector('#script-links > li > a[href$="/delete"]'),
  78. admin: d.querySelector('#script-links > li > a[href$="/admin"]'),
  79. version: d.querySelector('#script-stats > dt.script-show-version'),
  80. }
  81. Object.keys(es).forEach((key) => t[key] = es[key] ? es[key].textContent : t[key]);
  82. t.feedback = t.feedback.replace(/\s\(\d+\)/, '');
  83. return t;
  84. },
  85. translationOnStats: (d, t) => {
  86. t.installs = d.querySelector('table.stats-table > thead > tr > th:nth-child(2)').textContent || t.installs;
  87. t.updateChecks = d.querySelector('table.stats-table > thead > tr > th:nth-child(3)').textContent || t.updateChecks;
  88. return t;
  89. },
  90. props: (li) => {return {
  91. name: li.querySelector('h2 > a'),
  92. description: li.querySelector('.description'),
  93. stats: li.querySelector('dl.inline-script-stats'),
  94. dailyInstalls: li.querySelector('dd.script-list-daily-installs'),
  95. totalInstalls: li.querySelector('dd.script-list-total-installs'),
  96. ratings: li.querySelector('dd.script-list-ratings'),
  97. goodRatingCount: li.querySelector('span.good-rating-count'),
  98. createdDate: li.querySelector('dd.script-list-created-date'),
  99. updatedDate: li.querySelector('dd.script-list-updated-date'),
  100. scriptVersion: li.dataset.scriptVersion,
  101. }},
  102. scriptUrl: (li) => li.querySelector('h2 > a').href,
  103. },
  104. };
  105. const DEFAULTTRANSLATION = {
  106. info: 'Info',
  107. code: 'Code',
  108. history: 'History',
  109. feedback: 'Feedback',
  110. stats: 'Stats',
  111. derivatives: 'Derivatives',
  112. update: 'Update',
  113. delete: 'Delete',
  114. admin: 'Admin',
  115. version: 'Version',
  116. installs: 'Installs',
  117. updateChecks: 'Update checks',
  118. scriptSets: 'Script Sets',
  119. scripts: 'Scripts',
  120. };
  121. let translation = {};
  122. let elements = {}, storages = {}, timers = {};
  123. let core = {
  124. initialize: function(){
  125. elements.html = document.documentElement;
  126. elements.html.classList.add(SCRIPTID);
  127. core.ready();
  128. core.addStyle();
  129. },
  130. ready: function(){
  131. core.getTargets(site.targets).then(() => {
  132. log("I'm ready.");
  133. core.read();
  134. core.clearOldData();
  135. core.prepareTranslations();
  136. core.getTargets(site.ownerTargets).then(() => {
  137. log("I'm ready for owner page.");
  138. core.hideControlPanel();
  139. }).catch(e => {
  140. console.error(`${SCRIPTID}:${e.lineNumber} ${e.name}: ${e.message}`);
  141. });
  142. //core.hideUserSection();
  143. core.hideProfile();
  144. core.hideFeedback();
  145. core.addTabNavigation('discussions', [{
  146. selector: 'feedback',
  147. label: elements.feedback ? elements.feedback.querySelector('header').textContent : '',
  148. count: elements.feedback ? elements.feedback.querySelectorAll('.discussion-list-item').length : 0,
  149. selected: elements.feedback ? true : false,
  150. }, {
  151. selector: 'discussions',
  152. label: elements.discussions ? elements.discussions.querySelector('header').textContent : '',
  153. count: elements.discussions ? elements.discussions.querySelectorAll('li').length : 0,
  154. selected: elements.feedback ? false : true,
  155. }, {
  156. selector: 'conversations',
  157. label: elements.conversations ? elements.conversations.querySelector('header').textContent : '',
  158. count: elements.conversations ? elements.conversations.querySelectorAll('li').length : 0,
  159. }]);
  160. core.addTabNavigation('scripts', [{
  161. selector: 'scriptSets',
  162. label: elements.scriptSets ? elements.scriptSets.querySelector('header').textContent : translation.scriptSets,
  163. count: elements.userScriptSets ? elements.userScriptSets.querySelectorAll('li').length : 0,
  164. }, {
  165. selector: 'scripts',
  166. label: elements.scripts ? elements.scripts.querySelector('header').textContent : translation.scripts,
  167. count: elements.userScriptList ? elements.userScriptList.querySelectorAll('li[data-script-id]').length : 0,
  168. selected: true,
  169. }]);
  170. core.addNewScriptSetLink();
  171. core.rebuildScriptList();
  172. core.addChartSwitcher();
  173. }).catch(e => {
  174. console.error(`${SCRIPTID}:${e.lineNumber} ${e.name}: ${e.message}`);
  175. });
  176. },
  177. read: function(){
  178. storages.translations = Storage.read('translations') || {};
  179. storages.shown = Storage.read('shown') || {};
  180. storages.stats = Storage.read('stats') || {};
  181. storages.chartKey = Storage.read('chartKey') || 'updateChecks';
  182. },
  183. clearOldData: function(){
  184. let now = Date.now();
  185. Object.keys(storages.stats).forEach((key) => {
  186. if(storages.stats[key].updated < now - STATSEXPIRE) delete storages.stats[key];
  187. });
  188. Storage.save('stats', storages.stats);
  189. },
  190. prepareTranslations: function(){
  191. let language = site.get.language(document);
  192. translation = storages.translations[language] || DEFAULTTRANSLATION;
  193. if(!Object.keys(DEFAULTTRANSLATION).every((key) => translation[key])){/* some change in translation keys */
  194. Object.keys(DEFAULTTRANSLATION).forEach((key) => translation[key] = translation[key] || DEFAULTTRANSLATION[key]);
  195. core.getTranslations();
  196. }else{
  197. if(site.get.language(document) === 'en') return;
  198. if(Date.now() < (Storage.saved('translations') || 0) + TRANSLATIONEXPIRE) return;
  199. core.getTranslations();
  200. }
  201. },
  202. getTranslations: function(){
  203. let firstScript = site.get.firstScript(elements.userScriptList);
  204. fetch(firstScript.href, {credentials: 'include'})
  205. .then(response => response.text())
  206. .then(text => new DOMParser().parseFromString(text, 'text/html'))
  207. .then(d => translation = storages.translations[site.get.language(d)] = site.get.translation(d, translation))
  208. .then(() => wait(INTERVAL))
  209. .then(() => fetch(firstScript.href + '/stats'))
  210. .then(response => response.text())
  211. .then(text => new DOMParser().parseFromString(text, 'text/html'))
  212. .then(d => {
  213. translation = storages.translations[site.get.language(d)] = site.get.translationOnStats(d, translation);
  214. Storage.save('translations', storages.translations);
  215. });
  216. },
  217. hideUserSection: function(){
  218. if(!elements.userProfile && !elements.controlPanel) return;/* thin enough */
  219. let aboutUser = elements.aboutUser, more = createElement(html.more());
  220. if(!storages.shown.aboutUser) aboutUser.classList.add('hidden');
  221. more.addEventListener('click', function(e){
  222. aboutUser.classList.toggle('hidden');
  223. storages.shown.aboutUser = !aboutUser.classList.contains('hidden');
  224. Storage.save('shown', storages.shown);
  225. });
  226. aboutUser.appendChild(more);
  227. },
  228. hideFeedback: function(){
  229. if(!elements.feedback) return;
  230. let feedback = elements.feedback, more = createElement(html.more());
  231. if(!storages.shown.feedback) feedback.classList.add('hidden');
  232. more.addEventListener('click', function(e){
  233. feedback.classList.toggle('hidden');
  234. storages.shown.feedback = !feedback.classList.contains('hidden');
  235. Storage.save('shown', storages.shown);
  236. });
  237. feedback.appendChild(more);
  238. },
  239. hideProfile: function(){
  240. /* use userName.hidden instead of userProfile.hidden for CSS */
  241. let controlPanel = elements.controlPanel, userName = elements.userName, userProfile = elements.userProfile;
  242. if(!userProfile) return;/* no profile text */
  243. let more = createElement(html.more());
  244. if(controlPanel/* may not be own user page */ && !storages.shown.userProfile) userName.classList.add('hidden');
  245. more.addEventListener('click', function(e){
  246. userName.classList.toggle('hidden');
  247. storages.shown.userProfile = !userName.classList.contains('hidden');
  248. if(controlPanel) Storage.save('shown', storages.shown);
  249. });
  250. userName.appendChild(more);
  251. },
  252. hideControlPanel: function(){
  253. let controlPanel = elements.controlPanel;
  254. if(!controlPanel) return;/* may be not own user page */
  255. document.documentElement.dataset.owner = 'true';/* user owner flag */
  256. let header = controlPanel.firstElementChild;
  257. if(!storages.shown.controlPanel) controlPanel.classList.add('hidden');
  258. header.addEventListener('click', function(e){
  259. controlPanel.classList.toggle('hidden');
  260. storages.shown.controlPanel = !controlPanel.classList.contains('hidden');
  261. Storage.save('shown', storages.shown);
  262. });
  263. },
  264. addTabNavigation: function(name, keys){
  265. let nav = createElement(html.tabNavigation());
  266. let template = nav.querySelector('li.template');
  267. let anchorKey = keys.find(key => elements[key.selector]);
  268. if(anchorKey) elements[anchorKey.selector].parentNode.insertBefore(nav, elements[anchorKey.selector]);
  269. for(let i = 0; keys[i]; i++){
  270. if(!elements[keys[i].selector]) continue;
  271. let li = template.cloneNode(true);
  272. li.classList.remove('template');
  273. li.textContent = keys[i].label + ` (${keys[i].count})`;
  274. li.dataset.target = keys[i].selector;
  275. li.dataset.count = keys[i].count;
  276. li.addEventListener('click', function(e){
  277. /* close tab */
  278. li.parentNode.querySelector('[data-selected="true"]').dataset.selected = 'false';
  279. let openedTarget = $(`[data-tabified="${name}"][data-selected="true"]`);
  280. if(openedTarget) openedTarget.dataset.selected = 'false';
  281. /* open tab */
  282. li.dataset.selected = 'true';
  283. let openingTarget = $(`[data-selector="${li.dataset.target}"]`);
  284. if(openingTarget) openingTarget.dataset.selected = 'true';
  285. });
  286. let target = elements[keys[i].selector];
  287. if(target){
  288. target.dataset.tabified = name;
  289. if(keys[i].selected) li.dataset.selected = target.dataset.selected = 'true';
  290. else li.dataset.selected = target.dataset.selected = 'false';
  291. }else{
  292. if(keys[i].selected) li.dataset.selected = 'true';
  293. else li.dataset.selected = 'false';
  294. }
  295. template.parentNode.insertBefore(li, template);
  296. }
  297. },
  298. addNewScriptSetLink: function(){
  299. let newScriptSetLink = elements.newScriptSetLink;
  300. if(!newScriptSetLink) return;/* may be not own user page */
  301. let link = newScriptSetLink.cloneNode(true), list = elements.userScriptSets, li = document.createElement('li');
  302. li.appendChild(link);
  303. list.appendChild(li);
  304. },
  305. rebuildScriptList: function(){
  306. if(!elements.userScriptList) return;
  307. for(let i = 0, list = elements.userScriptList, li; li = list.children[i]; i++){
  308. if(li.dataset.scriptId === undefined) continue;
  309. let more = createElement(html.more()), props = site.get.props(li), key = li.dataset.scriptName, isLibrary = li.dataset.scriptType === 'library';
  310. if(!storages.shown[key]) li.classList.add('hidden');
  311. more.addEventListener('click', function(e){
  312. li.classList.toggle('hidden');
  313. if(li.classList.contains('hidden')) delete storages.shown[key];/* prevent from getting fat storage */
  314. else storages.shown[key] = true;
  315. Storage.save('shown', storages.shown);
  316. });
  317. li.dataset.scriptUrl = props.name.href;
  318. li.appendChild(more);
  319. if(isLibrary) continue;/* not so critical to skip below by continue */
  320. /* attatch titles */
  321. props.dailyInstalls.previousElementSibling.title = props.dailyInstalls.previousElementSibling.textContent;
  322. props.totalInstalls.previousElementSibling.title = props.totalInstalls.previousElementSibling.textContent;
  323. props.ratings.previousElementSibling.title = props.ratings.previousElementSibling.textContent;
  324. props.createdDate.previousElementSibling.title = props.createdDate.previousElementSibling.textContent;
  325. props.updatedDate.previousElementSibling.title = props.updatedDate.previousElementSibling.textContent;
  326. /* wrap the description to make it an inline element */
  327. let span = document.createElement('span');
  328. span.textContent = props.description.textContent.trim();
  329. props.description.replaceChild(span, props.description.firstChild);
  330. /* Link to Stats from Total installs */
  331. let statsDd = createElement(html.ddLink('script-list-total-installs', props.totalInstalls.textContent, props.name.href + '/stats', translation.stats));
  332. props.stats.replaceChild(statsDd, props.totalInstalls);
  333. /* Link to Feedback from Rating Count */
  334. let feedbackLink = createElement(html.feedbackLink(props.goodRatingCount.textContent, props.name.href + '/feedback'));
  335. props.goodRatingCount.replaceChild(feedbackLink, props.goodRatingCount.firstChild);
  336. /* Link to Code */
  337. let versionLabel = createElement(html.dt('script-list-version', translation.version));
  338. let versionDd = createElement(html.ddLink('script-list-version', props.scriptVersion, props.name.href + '/code', translation.code));
  339. versionLabel.title = versionLabel.textContent;
  340. props.stats.insertBefore(versionLabel, props.createdDate.previousElementSibling);
  341. props.stats.insertBefore(versionDd, props.createdDate.previousElementSibling);
  342. /* Link to Version up */
  343. if(elements.controlPanel){
  344. let updateLink = document.createElement('a');
  345. updateLink.href = props.name.href + '/versions/new';
  346. updateLink.textContent = UPDATELINKTEXT;
  347. updateLink.title = translation.update;
  348. updateLink.classList.add('update');
  349. versionDd.appendChild(updateLink);
  350. }
  351. /* Link to History from Updated date */
  352. let historyDd = createElement(html.ddLink('script-list-updated-date', props.updatedDate.textContent, props.name.href + '/versions', translation.history));
  353. props.stats.replaceChild(historyDd, props.updatedDate);
  354. }
  355. },
  356. addChartSwitcher: function(){
  357. let userScriptList = elements.userScriptList;
  358. if(!userScriptList) return;
  359. const keys = [
  360. {label: translation.installs, selector: 'installs'},
  361. {label: translation.updateChecks, selector: 'updateChecks'},
  362. ];
  363. let nav = createElement(html.chartSwitcher());
  364. let template = nav.querySelector('li.template');
  365. userScriptList.parentNode.appendChild(nav);/* less affected on dom */
  366. for(let i = 0; keys[i]; i++){
  367. let li = template.cloneNode(true);
  368. li.classList.remove('template');
  369. li.textContent = keys[i].label;
  370. li.dataset.key = keys[i].selector;
  371. li.addEventListener('click', function(e){
  372. li.parentNode.querySelector('[data-selected="true"]').dataset.selected = 'false';
  373. li.dataset.selected = 'true';
  374. storages.chartKey = li.dataset.key;
  375. Storage.save('chartKey', storages.chartKey);
  376. core.drawCharts();
  377. });
  378. if(keys[i].selector === storages.chartKey) li.dataset.selected = 'true';
  379. else li.dataset.selected = 'false';
  380. template.parentNode.insertBefore(li, template);
  381. }
  382. core.drawCharts();
  383. },
  384. drawCharts: function(){
  385. let promises = [];
  386. if(timers.charts && timers.charts.length) timers.charts.forEach((id) => clearTimeout(id));/* stop all the former timers */
  387. timers.charts = [];
  388. for(let i = 0, list = elements.userScriptList, li; li = list.children[i]; i++){
  389. if(li.dataset.scriptId === undefined) continue;
  390. if(li.dataset.scriptType === 'library') continue;
  391. /* Draw chart of daily update checks */
  392. let chart = li.querySelector('.chart') || createElement(html.chart()), key = li.dataset.scriptName;
  393. if(storages.stats[key] && storages.stats[key].data){
  394. timers.charts[i] = setTimeout(function(){
  395. core.drawChart(chart, storages.stats[key].data.slice(-DAYS), li.dataset.scriptUpdatedDate);
  396. if(!chart.isConnected) li.appendChild(chart);
  397. }, i * DRAWINGDELAY);/* CPU friendly */
  398. }
  399. let now = Date.now(), updated = (storages.stats[key]) ? storages.stats[key].updated || 0 : 0, past = updated % STATSUPDATE, expire = updated - past + STATSUPDATE;
  400. if(now < expire) continue;/* still up-to-date */
  401. promises.push(new Promise(function(resolve, reject){
  402. timers.charts[i] = setTimeout(function(){
  403. fetch(li.dataset.scriptUrl + STATSPATH, {credentials: 'include'}/* for sensitive scripts */)/* less file size than json */
  404. .then(response => response.text())
  405. .then(csv => {
  406. let lines = csv.split('\n');
  407. lines = lines.slice(1, -1);/* cut the labels + blank line */
  408. storages.stats[key] = {data: [], updated: now};
  409. for(let i = 0; lines[i]; i++){
  410. let p = lines[i].split(',');
  411. storages.stats[key].data[i] = {
  412. date: p[0],
  413. installs: parseInt(p[1]),
  414. updateChecks: parseInt(p[2]),
  415. };
  416. }
  417. core.drawChart(chart, storages.stats[key].data.slice(-DAYS), li.dataset.scriptUpdatedDate);
  418. if(!chart.isConnected) li.appendChild(chart);
  419. resolve();
  420. });
  421. }, i * INTERVAL);/* server friendly */
  422. }));
  423. }
  424. if(promises.length) Promise.all(promises).then((values) => Storage.save('stats', storages.stats));
  425. },
  426. drawChart: function(chart, stats, scriptUpdatedDate){
  427. let dl = chart.querySelector('dl'), dt = dl.querySelector('dt.template'), dd = dl.querySelector('dd.template'), hasBars = (2 < dl.children.length);
  428. let chartKey = storages.chartKey, max = Math.max(DEFAULTMAX, ...stats.map(s => s[chartKey]));
  429. for(let i = last = stats.length - 1; stats[i]; i--){/* from last */
  430. let date = stats[i].date, count = stats[i][chartKey];
  431. let dateDt = dl.querySelector(`dt[data-date="${date}"]`) || dt.cloneNode();
  432. let countDd = dateDt.nextElementSibling || dd.cloneNode();
  433. if(!dateDt.isConnected){
  434. dateDt.classList.remove('template');
  435. countDd.classList.remove('template');
  436. dateDt.dataset.date = dateDt.textContent = date;
  437. if(hasBars){
  438. countDd.style.width = '0px';
  439. dl.insertBefore(dateDt, (i === last) ? dl.lastElementChild.previousElementSibling : dl.querySelector(`dt[data-date="${stats[i + 1].date}"]`));
  440. }else{
  441. dl.insertBefore(dateDt, dl.firstElementChild);
  442. }
  443. dl.insertBefore(countDd, dateDt.nextElementSibling);
  444. }else{
  445. if(dl.dataset.chartKey === chartKey && dl.dataset.max === max && countDd.dataset.count === count && i < last) break;/* it doesn't need update any more. */
  446. }
  447. countDd.title = date + ': ' + count;
  448. countDd.dataset.count = count;
  449. /* highlight the updated date */
  450. if(scriptUpdatedDate === date){
  451. countDd.classList.add('updated');
  452. countDd.title+= ' (last updated)';
  453. }
  454. /* the last date */
  455. if(i === last - 1){
  456. let label = countDd.querySelector('span') || document.createElement('span');
  457. label.textContent = toMetric(count);
  458. if(!label.isConnected) countDd.appendChild(label);
  459. }
  460. }
  461. dl.dataset.chartKey = chartKey, dl.dataset.max = max;
  462. /* for animation */
  463. animate(function(){
  464. for(let i = 0, dds = dl.querySelectorAll('dd.count:not(.template)'), dd; dd = dds[i]; i++){
  465. dd.style.height = ((dd.dataset.count / max) * 100) + '%';
  466. if(hasBars) dd.style.width = '';
  467. }
  468. });
  469. },
  470. getTarget: function(selector, retry = 10, interval = 1*SECOND){
  471. const key = selector.name;
  472. const get = function(resolve, reject){
  473. let selected = selector();
  474. if(selected && selected.length > 0) selected.forEach((s) => s.dataset.selector = key);/* elements */
  475. else if(selected instanceof HTMLElement) selected.dataset.selector = key;/* element */
  476. else if(--retry) return log(`Not found: ${key}, retrying... (${retry})`), setTimeout(get, interval, resolve, reject);
  477. else return reject(new Error(`Not found: ${selector.name}, I give up.`));
  478. elements[key] = selected;
  479. resolve(selected);
  480. };
  481. return new Promise(function(resolve, reject){
  482. get(resolve, reject);
  483. });
  484. },
  485. getTargets: function(selectors, retry = 10, interval = 1*SECOND){
  486. return Promise.all(Object.values(selectors).map(selector => core.getTarget(selector, retry, interval)));
  487. },
  488. addStyle: function(name = 'style'){
  489. if(html[name] === undefined) return;
  490. if(!document.head){
  491. let observer = observe(document.documentElement, function(){
  492. if(!document.head) return;
  493. observer.disconnect();
  494. core.addStyle(name);
  495. });
  496. return;
  497. }
  498. let style = createElement(html[name]());
  499. document.head.appendChild(style);
  500. if(elements[name] && elements[name].isConnected) document.head.removeChild(elements[name]);
  501. elements[name] = style;
  502. },
  503. };
  504. const html = {
  505. more: () => `<button class="more"></button>`,
  506. tabNavigation: () => `
  507. <nav id="tabNavigation">
  508. <ul>
  509. <li class="template"></li>
  510. </ul>
  511. </nav>
  512. `,
  513. chartSwitcher: () => `
  514. <nav id="chartSwitcher">
  515. <ul>
  516. <li class="template"></li>
  517. </ul>
  518. </nav>
  519. `,
  520. dt: (className, textContent) => `<dt class="${className}"><span>${textContent}</span></dt>`,
  521. ddLink: (className, textContent, href, title) => `<dd class="${className}"><a href="${href}" title="${title}">${textContent}</a></dd>`,
  522. feedbackLink: (textContent, href) => `<a href="${href}">${textContent}</a>`,
  523. chart: () => `
  524. <div class="chart">
  525. <dl>
  526. <dt class="template date"></dt>
  527. <dd class="template count"></dd>
  528. </dl>
  529. </div>
  530. `,
  531. style: () => `
  532. <style type="text/css" id="${SCRIPTID}-style">
  533. /* red scale: 103-206 */
  534. /* gray scale: 119-(136)-153-(170)-187-(204)-221 (34/17 step) */
  535. /* common */
  536. h2, h3{
  537. margin: 0;
  538. }
  539. ul, ol{
  540. margin: 0;
  541. padding: 0 0 0 2em;
  542. }
  543. a:hover,
  544. a:focus{
  545. color: rgb(206,0,0);
  546. }
  547. .template{
  548. display: none !important;
  549. }
  550. section.text-content{
  551. position: relative;
  552. padding: 0 0 14px;
  553. }
  554. section.text-content > *{
  555. margin: 14px;
  556. }
  557. section.text-content h2{
  558. text-align: left !important;
  559. margin-bottom: 0;
  560. }
  561. section > header + *{
  562. margin: 0 !important;
  563. }
  564. button.more{
  565. color: rgb(153,153,153);
  566. border: 1px solid rgb(187,187,187);
  567. background: white;
  568. padding: 0;
  569. cursor: pointer;
  570. }
  571. button.more::-moz-focus-inner{
  572. border: none;
  573. }
  574. button.more::after{
  575. font-size: medium;
  576. content: "▴";
  577. }
  578. .hidden button.more{
  579. background: rgb(221, 221, 221);
  580. }
  581. .hidden button.more::after{
  582. content: "▾";
  583. }
  584. /* User panel */
  585. #about-user > h2:only-child{
  586. margin-bottom: 14px;/* no content in user panel */
  587. }
  588. #about-user.hidden{
  589. min-height: 5em;
  590. max-height: 10em;
  591. overflow: hidden;
  592. }
  593. #about-user > button.more{
  594. width: 100%;
  595. margin: 0;
  596. border: none;
  597. border-top: 1px solid rgba(187, 187, 187);
  598. border-radius: 0 0 5px 5px;
  599. }
  600. #about-user.hidden > button.more{
  601. position: absolute;
  602. }
  603. /* User Name + Profile */
  604. h2[data-selector="userName"]{
  605. display: flex;
  606. align-items: center;
  607. }
  608. h2[data-selector="userName"] > button.more{
  609. background: rgb(242, 229, 229);
  610. border: 1px solid rgb(230, 221, 214);
  611. border-radius: 5px;
  612. padding: 0 .5em;
  613. margin: 0 .5em;
  614. }
  615. h2[data-selector="userName"].hidden + [data-selector="userProfile"]{
  616. display: none;
  617. }
  618. /* Control panel */
  619. section#control-panel{
  620. font-size: smaller;
  621. width: 200px;
  622. position: absolute;
  623. top: 0;
  624. right: 0;
  625. z-index: 1;
  626. }
  627. section#control-panel h3{
  628. font-size: 1em;
  629. padding: .25em 1em;
  630. border-radius: 5px 5px 0 0;
  631. background: rgb(103, 0, 0);
  632. color: white;
  633. cursor: pointer;
  634. }
  635. section#control-panel.hidden h3{
  636. border-radius: 5px 5px 5px 5px;
  637. }
  638. section#control-panel h3::after{
  639. content: " ▴";
  640. margin-left: .25em;
  641. }
  642. section#control-panel.hidden h3::after{
  643. content: " ▾";
  644. }
  645. ul#user-control-panel{
  646. list-style-type: square;
  647. color: rgb(187, 187, 187);
  648. width: 100%;
  649. margin: .5em 0;
  650. padding: .5em .5em .5em 1.5em;
  651. -webkit-padding-start: 25px;/* ajustment for Chrome */
  652. background: white;
  653. border-radius: 0 0 5px 5px;
  654. border: 1px solid rgb(187, 187, 187);
  655. border-top: none;
  656. box-sizing: border-box;
  657. }
  658. section#control-panel.hidden > ul#user-control-panel{
  659. display: none;
  660. }
  661. /* Discussions on your scripts */
  662. #user-discussions-on-scripts-written{
  663. font-size: 90%;
  664. }
  665. #user-discussions-on-scripts-written section{
  666. border-radius: 0 5px 0 0;
  667. }
  668. #user-discussions-on-scripts-written.hidden section{
  669. min-height: 5em;
  670. max-height: 10em;
  671. overflow: scroll;
  672. }
  673. #user-discussions-on-scripts-written section .discussion-list-container{
  674. margin: 0 14px;
  675. }
  676. #user-discussions-on-scripts-written section .discussion-list-item a.discussion-title{
  677. padding: 4px 0 4px 0;
  678. }
  679. #user-discussions-on-scripts-written section + button.more{
  680. bottom: 0;
  681. width: 100%;
  682. margin: 0;
  683. border: 1px solid rgba(187, 187, 187);
  684. border-top: none;
  685. border-radius: 0 0 5px 5px;
  686. }
  687. /* tabs */
  688. #tabNavigation{
  689. display: inline-block;
  690. }
  691. #tabNavigation > ul{
  692. list-style-type: none;
  693. padding: 0;
  694. display: flex;
  695. }
  696. #tabNavigation > ul > li{
  697. font-weight: bold;
  698. background: white;
  699. padding: .25em 1em;
  700. border: 1px solid rgb(187, 187, 187);
  701. border-bottom: none;
  702. border-radius: 5px 5px 0 0;
  703. box-shadow: 0 0 5px rgb(221, 221, 221);
  704. }
  705. #tabNavigation > ul > li[data-selected="false"]{
  706. color: rgb(153,153,153);
  707. background: rgb(221, 221, 221);
  708. cursor: pointer;
  709. }
  710. [data-tabified]{
  711. margin: 0 0 14px;
  712. }
  713. [data-tabified="discussions"] > section,
  714. #user-script-sets-section[data-tabified] > section,
  715. #user-script-list-section[data-tabified] > #user-script-list{
  716. border-radius: 0 5px 5px 5px;
  717. }
  718. [data-tabified] header{
  719. display: none;
  720. }
  721. [data-tabified][data-selected="false"]{
  722. display: none;
  723. }
  724. /* Ad */
  725. #user-script-list #codefund{
  726. border-bottom: 1px solid rgb(221, 221, 221);
  727. }
  728. #user-script-list #codefund #cf{
  729. position: relative;
  730. }
  731. #user-script-list #codefund span.cf-wrapper{
  732. border-radius: 0 5px 0 0;
  733. }
  734. #user-script-list #codefund a.cf-text > strong,
  735. #user-script-list #codefund a.cf-text > span,
  736. #user-script-list #codefund a.cf-powered-by{
  737. display: inline-block;
  738. transform-origin: bottom left;
  739. }
  740. #user-script-list #codefund a.cf-text > strong{
  741. }
  742. #user-script-list #codefund a.cf-text > span{
  743. font-size: 90%;
  744. line-height: .90;
  745. }
  746. #user-script-list #codefund a.cf-powered-by{
  747. position: absolute;
  748. bottom: 0;
  749. right: 5px;
  750. line-height: 1.5;
  751. }
  752. /* Scripts */
  753. #user-script-list-section{
  754. position: relative;
  755. }
  756. #user-script-list-section > div > section > header + p/* no scripts */{
  757. background: white;
  758. border: 1px solid rgb(187, 187, 187);
  759. border-radius: 0 5px 5px 5px;
  760. box-shadow: 0 0 5px rgb(221, 221, 221);
  761. padding: 14px;
  762. }
  763. #user-script-list li{
  764. padding: .25em 1em;
  765. position: relative;
  766. }
  767. #user-script-list li:last-child{
  768. border-bottom: none;/* missing in gf.qytechs.cn */
  769. }
  770. #user-script-list li article{
  771. position: relative;
  772. z-index: 1;/* over the .chart */
  773. pointer-events: none;
  774. }
  775. #user-script-list li article h2 > a{
  776. margin-right: 4em;/* for preventing from hiding chart's count number */
  777. display: inline-block;
  778. }
  779. #user-script-list li article h2 > a + .script-type{
  780. color: rgb(119, 119, 119);
  781. font-size: 80%;
  782. margin-left: -5em;/* trick */
  783. }
  784. #user-script-list li article h2 > a,
  785. #user-script-list li article h2 > .description/* it's block! */ > span,
  786. #user-script-list li article dl > dt > *,
  787. #user-script-list li article dl > dd > *{
  788. pointer-events: auto;/* apply on inline elements */
  789. }
  790. #user-script-list li button.more{
  791. border-radius: 5px;
  792. position: absolute;
  793. top: 0;
  794. right: 0;
  795. margin: 5px;
  796. width: 20px;
  797. z-index: 1;/* over the .chart */
  798. }
  799. #user-script-list li .description{
  800. font-size: small;
  801. margin: 0 0 0 .1em;/* ajust first letter position */
  802. }
  803. #user-script-list li dl.inline-script-stats{
  804. margin-top: .25em;
  805. column-count: 3;
  806. max-height: 4em;/* Firefox bug? */
  807. }
  808. #user-script-list li dl.inline-script-stats dt{
  809. overflow: hidden;
  810. white-space: nowrap;
  811. text-overflow: ellipsis;
  812. max-width: 200px;/* stretching column mystery on long-lettered languages such as fr-CA */
  813. }
  814. #user-script-list li dl.inline-script-stats .script-list-author{
  815. display: none;
  816. }
  817. #user-script-list li dl.inline-script-stats dt{
  818. width: 55%;
  819. }
  820. #user-script-list li dl.inline-script-stats dd{
  821. width: 45%;
  822. }
  823. #user-script-list li dl.inline-script-stats dd a{
  824. padding: 0 .25em;
  825. margin: 0 -.25em;
  826. overflow-wrap: normal;
  827. }
  828. #user-script-list li dl.inline-script-stats dt.script-list-daily-installs,
  829. #user-script-list li dl.inline-script-stats dt.script-list-total-installs{
  830. width: 65%;
  831. }
  832. #user-script-list li dl.inline-script-stats dd.script-list-daily-installs,
  833. #user-script-list li dl.inline-script-stats dd.script-list-total-installs{
  834. width: 35%;
  835. }
  836. #user-script-list li dl.inline-script-stats dd.script-list-ratings span.good-rating-count > a{
  837. color: inherit;
  838. padding: 0 .5em;
  839. margin: 0 -.5em;
  840. }
  841. #user-script-list li dl.inline-script-stats dd.script-list-version a.update{
  842. padding: 0 .75em 0 .25em;/* enough space for right side */
  843. margin: 0 .25em 0 .50em;
  844. }
  845. #user-script-list li.hidden .description,
  846. #user-script-list li.hidden .inline-script-stats{
  847. display: none;
  848. }
  849. /* chartSwitcher */
  850. [data-selector="scripts"] > div > section{
  851. position: relative;/* position anchor */
  852. }
  853. #chartSwitcher{
  854. display: inline-block;
  855. position: absolute;
  856. top: -1.5em;
  857. right: 0;
  858. line-height: 1.25em;
  859. }
  860. #chartSwitcher > ul{
  861. list-style-type: none;
  862. font-size: small;
  863. padding: 0;
  864. margin: 0;
  865. }
  866. #chartSwitcher > ul > li{
  867. color: rgb(187,187,187);
  868. font-weight: bold;
  869. display: inline-block;
  870. border-right: 1px solid rgb(187,187,187);
  871. padding: 0 1em;
  872. margin: 0;
  873. cursor: pointer;
  874. }
  875. #chartSwitcher > ul > li[data-selected="true"]{
  876. color: black;
  877. cursor: auto;
  878. }
  879. #chartSwitcher > ul > li:nth-last-child(2)/* 2nd including template */{
  880. border-right: none;
  881. }
  882. /* chart */
  883. .chart{
  884. position: absolute;
  885. top: 0;
  886. right: 0;
  887. width: 100%;
  888. height: 100%;
  889. overflow: hidden;
  890. mask-image: linear-gradient(to right, rgba(0,0,0,.5), black);
  891. -webkit-mask-image: linear-gradient(to right, rgba(0,0,0,.5), black);
  892. }
  893. .chart > dl{
  894. position: absolute;
  895. bottom: 0;
  896. right: 2em;
  897. margin: 0;
  898. height: calc(100% - 5px);
  899. display: flex;
  900. align-items: flex-end;
  901. }
  902. .chart > dl > dt.date{
  903. display: none;
  904. }
  905. .chart > dl > dd.count{
  906. background: rgb(221,221,221);
  907. border-left: 1px solid white;
  908. margin: 0;
  909. width: 3px;
  910. height: 0%;/* will stretch */
  911. transition: height 250ms ${EASING}, width 250ms ${EASING};
  912. }
  913. .chart > dl > dd.count.updated{
  914. background: rgb(204,204,204);
  915. }
  916. .chart > dl > dd.count:nth-last-of-type(3)/* 3rd including template */,
  917. .chart > dl > dd.count:hover{
  918. background: rgb(187,187,187);
  919. }
  920. .chart > dl > dd.count.updated:nth-last-of-type(3)/* 3rd including template */,
  921. .chart > dl > dd.count.updated:hover{
  922. background: rgb(170,170,170);
  923. }
  924. .chart > dl > dd.count:nth-last-of-type(3):hover{
  925. background: rgb(153,153,153);
  926. }
  927. .chart > dl > dd.count.updated:nth-last-of-type(3):hover{
  928. background: rgb(136,136,136);
  929. }
  930. .chart > dl > dd.count > span{
  931. display: none;/* default */
  932. }
  933. .chart > dl > dd.count:nth-last-of-type(3) > span{
  934. display: inline;/* overwrite */
  935. font-weight: bold;
  936. color: rgb(153,153,153);
  937. position: absolute;
  938. top: 5px;
  939. right: 10px;
  940. pointer-events: none;
  941. }
  942. .chart > dl > dd.count:nth-last-of-type(3)[data-count="0"] > span{
  943. color: rgb(221,221,221);
  944. }
  945. .chart > dl > dd.count:nth-last-of-type(3):hover > span{
  946. color: rgb(119,119,119);
  947. }
  948. /* sidebar */
  949. .sidebar{
  950. padding-top: 0 !important;
  951. }
  952. [data-owner="true"] .ad/* excuse me, it disappears only in my own user page :-) */,
  953. [data-owner="true"] #script-list-filter{
  954. display: none !important;
  955. }
  956. </style>
  957. `,
  958. };
  959. class Storage{
  960. static key(key){
  961. return (SCRIPTID) ? (SCRIPTID + '-' + key) : key;
  962. }
  963. static save(key, value, expire = null){
  964. key = Storage.key(key);
  965. localStorage[key] = JSON.stringify({
  966. value: value,
  967. saved: Date.now(),
  968. expire: expire,
  969. });
  970. }
  971. static read(key){
  972. key = Storage.key(key);
  973. if(localStorage[key] === undefined) return undefined;
  974. let data = JSON.parse(localStorage[key]);
  975. if(data.value === undefined) return data;
  976. if(data.expire === undefined) return data;
  977. if(data.expire === null) return data.value;
  978. if(data.expire < Date.now()) return localStorage.removeItem(key);
  979. return data.value;
  980. }
  981. static delete(key){
  982. key = Storage.key(key);
  983. delete localStorage.removeItem(key);
  984. }
  985. static saved(key){
  986. key = Storage.key(key);
  987. if(localStorage[key] === undefined) return undefined;
  988. let data = JSON.parse(localStorage[key]);
  989. if(data.saved) return data.saved;
  990. else return undefined;
  991. }
  992. }
  993. const $ = function(s){return document.querySelector(s)};
  994. const $$ = function(s){return document.querySelectorAll(s)};
  995. const animate = function(callback, ...params){requestAnimationFrame(() => requestAnimationFrame(() => callback(...params)))};
  996. const wait = function(ms){return new Promise((resolve) => setTimeout(resolve, ms))};
  997. const createElement = function(html){
  998. let outer = document.createElement('div');
  999. outer.innerHTML = html;
  1000. return outer.firstElementChild;
  1001. };
  1002. const observe = function(element, callback, options = {childList: true, characterData: false, subtree: false, attributes: false, attributeFilter: undefined}){
  1003. let observer = new MutationObserver(callback.bind(element));
  1004. observer.observe(element, options);
  1005. return observer;
  1006. };
  1007. const toMetric = function(number, fixed = 1){
  1008. switch(true){
  1009. case(number < 1e3): return (number);
  1010. case(number < 1e6): return (number/ 1e3).toFixed(fixed) + 'K';
  1011. case(number < 1e9): return (number/ 1e6).toFixed(fixed) + 'M';
  1012. case(number < 1e12): return (number/ 1e9).toFixed(fixed) + 'G';
  1013. default: return (number/1e12).toFixed(fixed) + 'T';
  1014. }
  1015. };
  1016. const log = function(){
  1017. if(!DEBUG) return;
  1018. let l = log.last = log.now || new Date(), n = log.now = new Date();
  1019. let error = new Error(), line = log.format.getLine(error), callers = log.format.getCallers(error);
  1020. //console.log(error.stack);
  1021. console.log(
  1022. SCRIPTID + ':',
  1023. /* 00:00:00.000 */ n.toLocaleTimeString() + '.' + n.getTime().toString().slice(-3),
  1024. /* +0.000s */ '+' + ((n-l)/1000).toFixed(3) + 's',
  1025. /* :00 */ ':' + line,
  1026. /* caller.caller */ (callers[2] ? callers[2] + '() => ' : '') +
  1027. /* caller */ (callers[1] || '') + '()',
  1028. ...arguments
  1029. );
  1030. };
  1031. log.formats = [{
  1032. name: 'Firefox Scratchpad',
  1033. detector: /MARKER@Scratchpad/,
  1034. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1],
  1035. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1036. }, {
  1037. name: 'Firefox Console',
  1038. detector: /MARKER@debugger/,
  1039. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1],
  1040. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1041. }, {
  1042. name: 'Firefox Greasemonkey 3',
  1043. detector: /\/gm_scripts\//,
  1044. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1],
  1045. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1046. }, {
  1047. name: 'Firefox Greasemonkey 4+',
  1048. detector: /MARKER@user-script:/,
  1049. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1] - 500,
  1050. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1051. }, {
  1052. name: 'Firefox Tampermonkey',
  1053. detector: /MARKER@moz-extension:/,
  1054. getLine: (e) => e.stack.split('\n')[1].match(/([0-9]+):[0-9]+$/)[1] - 6,
  1055. getCallers: (e) => e.stack.match(/^[^@]*(?=@)/gm),
  1056. }, {
  1057. name: 'Chrome Console',
  1058. detector: /at MARKER \(<anonymous>/,
  1059. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)$/)[1],
  1060. getCallers: (e) => e.stack.match(/[^ ]+(?= \(<anonymous>)/gm),
  1061. }, {
  1062. name: 'Chrome Tampermonkey',
  1063. detector: /at MARKER \((userscript\.html|chrome-extension:)/,
  1064. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+)\)$/)[1] - 6,
  1065. getCallers: (e) => e.stack.match(/[^ ]+(?= \((userscript\.html|chrome-extension:))/gm),
  1066. }, {
  1067. name: 'Edge Console',
  1068. detector: /at MARKER \(eval/,
  1069. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)$/)[1],
  1070. getCallers: (e) => e.stack.match(/[^ ]+(?= \(eval)/gm),
  1071. }, {
  1072. name: 'Edge Tampermonkey',
  1073. detector: /at MARKER \(Function/,
  1074. getLine: (e) => e.stack.split('\n')[2].match(/([0-9]+):[0-9]+\)$/)[1] - 4,
  1075. getCallers: (e) => e.stack.match(/[^ ]+(?= \(Function)/gm),
  1076. }, {
  1077. name: 'Safari',
  1078. detector: /^MARKER$/m,
  1079. getLine: (e) => 0,/*e.lineが用意されているが最終呼び出し位置のみ*/
  1080. getCallers: (e) => e.stack.split('\n'),
  1081. }, {
  1082. name: 'Default',
  1083. detector: /./,
  1084. getLine: (e) => 0,
  1085. getCallers: (e) => [],
  1086. }];
  1087. log.format = log.formats.find(function MARKER(f){
  1088. if(!f.detector.test(new Error().stack)) return false;
  1089. //console.log('//// ' + f.name + '\n' + new Error().stack);
  1090. return true;
  1091. });
  1092. core.initialize();
  1093. if(window === top && console.timeEnd) console.timeEnd(SCRIPTID);
  1094. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址