GreasyFork User Dashboard

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

目前為 2020-11-09 提交的版本,檢視 最新版本

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

QingJ © 2025

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