GreasyFork User Dashboard

为 Greasy Fork 提供一个一览性出色的新用户页面。

当前为 2020-10-18 提交的版本,查看 最新版本

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