GreasyFork User Dashboard

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

当前为 2020-07-27 提交的版本,查看 最新版本

  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.1
  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.1
  21. update layout.
  22.  
  23. [bug]
  24.  
  25. [to do]
  26. run-at で即起動
  27. 本来は履歴ページを見に行ってすべての更新日を保存、グラフに反映させるべき
  28. 履歴ページはその後、当該スクリプトの最終更新日が更新されるたびに見に行けば良い
  29. 1年以上経ったスクリプトに「いまも動作しますよ」的なアップデートを促したいけど・・・別スクリプトかな
  30.  
  31. [possible]
  32. 3カラムのレイアウト崩れる(スクリプト未使用でも発生する)
  33. グラフ数字の日付追加時くるりんぱは位置がズレるので労力に見合わないか
  34.  
  35. [not to do]
  36. */
  37. if(window === top && console.time) console.time(SCRIPTID);
  38. const MS = 1, SECOND = 1000*MS, MINUTE = 60*SECOND, HOUR = 60*MINUTE, DAY = 24*HOUR, WEEK = 7*DAY, MONTH = 30*DAY, YEAR = 365*DAY;
  39. const INTERVAL = 1*SECOND;/* for fetch */
  40. const DRAWINGDELAY = 125*MS;/* for drawing each charts */
  41. const UPDATELINKTEXT = '+';/* for update link text */
  42. const DEFAULTMAX = 10;/* for chart scale */
  43. const DAYS = 180;/* for chart length */
  44. const STATSUPDATE = 1*HOUR;/* stats update interval of greasyfork.org */
  45. const TRANSLATIONEXPIRE = 30*DAY;/* cache time for translations */
  46. const STATSEXPIRE = 10*DAY;/* cache time for stats */
  47. const EASING = 'cubic-bezier(0,.75,.5,1)';/* quick easing */
  48. const STATSPATH = `/stats.csv?${SCRIPTID}`;
  49. let site = {
  50. targets: {
  51. aboutUser: () => $('#about-user'),
  52. userName: () => $('#about-user > h2'),
  53. userProfile: () => $('#user-profile'),
  54. discussions: () => $('#user-discussions'),
  55. scriptSets: () => $('#user-script-sets-section'),/* section for Script Sets */
  56. scripts: () => $('#user-script-list-section'),/* section for Scripts */
  57. userScriptSets: () => $('#user-script-sets'),
  58. userScriptList: () => $('#user-script-list'),
  59. },
  60. ownerTargets: {
  61. controlPanel: () => $('#control-panel'),
  62. newScriptSetLink: () => $('a[href$="/sets/new"]'),
  63. feedback: () => $('#user-discussions-on-scripts-written'),
  64. conversations: () => $('#user-conversations'),
  65. },
  66. get: {
  67. language: (d) => d.documentElement.lang,
  68. firstScript: (list) => list.querySelector('li h2 > a'),
  69. translation: (d, t) => {
  70. let es = {
  71. info: d.querySelector('#script-links > li.current'),
  72. code: d.querySelector('#script-links > li > a[href$="/code"]'),
  73. history: d.querySelector('#script-links > li > a[href$="/versions"]'),
  74. feedback: d.querySelector('#script-links > li > a[href$="/feedback"]'),
  75. stats: d.querySelector('#script-links > li > a[href$="/stats"]'),
  76. derivatives: d.querySelector('#script-links > li > a[href$="/derivatives"]'),
  77. update: d.querySelector('#script-links > li > a[href$="/versions/new"]'),
  78. delete: d.querySelector('#script-links > li > a[href$="/delete"]'),
  79. admin: d.querySelector('#script-links > li > a[href$="/admin"]'),
  80. version: d.querySelector('#script-stats > dt.script-show-version'),
  81. }
  82. Object.keys(es).forEach((key) => t[key] = es[key] ? es[key].textContent : t[key]);
  83. t.feedback = t.feedback.replace(/\s\(\d+\)/, '');
  84. return t;
  85. },
  86. translationOnStats: (d, t) => {
  87. t.installs = d.querySelector('table.stats-table > thead > tr > th:nth-child(2)').textContent || t.installs;
  88. t.updateChecks = d.querySelector('table.stats-table > thead > tr > th:nth-child(3)').textContent || t.updateChecks;
  89. return t;
  90. },
  91. props: (li) => {return {
  92. name: li.querySelector('h2 > a'),
  93. description: li.querySelector('.description'),
  94. stats: li.querySelector('dl.inline-script-stats'),
  95. dailyInstalls: li.querySelector('dd.script-list-daily-installs'),
  96. totalInstalls: li.querySelector('dd.script-list-total-installs'),
  97. ratings: li.querySelector('dd.script-list-ratings'),
  98. goodRatingCount: li.querySelector('span.good-rating-count'),
  99. createdDate: li.querySelector('dd.script-list-created-date'),
  100. updatedDate: li.querySelector('dd.script-list-updated-date'),
  101. scriptVersion: li.dataset.scriptVersion,
  102. }},
  103. scriptUrl: (li) => li.querySelector('h2 > a').href,
  104. },
  105. };
  106. const DEFAULTTRANSLATION = {
  107. info: 'Info',
  108. code: 'Code',
  109. history: 'History',
  110. feedback: 'Feedback',
  111. stats: 'Stats',
  112. derivatives: 'Derivatives',
  113. update: 'Update',
  114. delete: 'Delete',
  115. admin: 'Admin',
  116. version: 'Version',
  117. installs: 'Installs',
  118. updateChecks: 'Update checks',
  119. scriptSets: 'Script Sets',
  120. scripts: 'Scripts',
  121. };
  122. let translation = {};
  123. let elements = {}, storages = {}, timers = {};
  124. let core = {
  125. initialize: function(){
  126. elements.html = document.documentElement;
  127. elements.html.classList.add(SCRIPTID);
  128. core.ready();
  129. core.addStyle();
  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.ownerTargets).then(() => {
  138. log("I'm ready for owner page.");
  139. core.hideControlPanel();
  140. }).catch(e => {
  141. console.error(`${SCRIPTID}:${e.lineNumber} ${e.name}: ${e.message}`);
  142. });
  143. //core.hideUserSection();
  144. core.hideProfile();
  145. core.hideFeedback();
  146. core.addTabNavigation('discussions', [{
  147. selector: 'feedback',
  148. label: elements.feedback ? elements.feedback.querySelector('header').textContent : '',
  149. count: elements.feedback ? elements.feedback.querySelectorAll('.discussion-list-item').length : 0,
  150. selected: elements.feedback ? true : false,
  151. }, {
  152. selector: 'discussions',
  153. label: elements.discussions ? elements.discussions.querySelector('header').textContent : '',
  154. count: elements.discussions ? elements.discussions.querySelectorAll('li').length : 0,
  155. selected: elements.feedback ? false : true,
  156. }, {
  157. selector: 'conversations',
  158. label: elements.conversations ? elements.conversations.querySelector('header').textContent : '',
  159. count: elements.conversations ? elements.conversations.querySelectorAll('li').length : 0,
  160. }]);
  161. core.addTabNavigation('scripts', [{
  162. selector: 'scriptSets',
  163. label: elements.scriptSets ? elements.scriptSets.querySelector('header').textContent : translation.scriptSets,
  164. count: elements.userScriptSets ? elements.userScriptSets.querySelectorAll('li').length : 0,
  165. }, {
  166. selector: 'scripts',
  167. label: elements.scripts ? elements.scripts.querySelector('header').textContent : translation.scripts,
  168. count: elements.userScriptList ? elements.userScriptList.querySelectorAll('li[data-script-id]').length : 0,
  169. selected: true,
  170. }]);
  171. core.addNewScriptSetLink();
  172. core.rebuildScriptList();
  173. core.addChartSwitcher();
  174. }).catch(e => {
  175. console.error(`${SCRIPTID}:${e.lineNumber} ${e.name}: ${e.message}`);
  176. });
  177. },
  178. read: function(){
  179. storages.translations = Storage.read('translations') || {};
  180. storages.shown = Storage.read('shown') || {};
  181. storages.stats = Storage.read('stats') || {};
  182. storages.chartKey = Storage.read('chartKey') || 'updateChecks';
  183. },
  184. clearOldData: function(){
  185. let now = Date.now();
  186. Object.keys(storages.stats).forEach((key) => {
  187. if(storages.stats[key].updated < now - STATSEXPIRE) delete storages.stats[key];
  188. });
  189. Storage.save('stats', storages.stats);
  190. },
  191. prepareTranslations: function(){
  192. let language = site.get.language(document);
  193. translation = storages.translations[language] || DEFAULTTRANSLATION;
  194. if(!Object.keys(DEFAULTTRANSLATION).every((key) => translation[key])){/* some change in translation keys */
  195. Object.keys(DEFAULTTRANSLATION).forEach((key) => translation[key] = translation[key] || DEFAULTTRANSLATION[key]);
  196. core.getTranslations();
  197. }else{
  198. if(site.get.language(document) === 'en') return;
  199. if(Date.now() < (Storage.saved('translations') || 0) + TRANSLATIONEXPIRE) return;
  200. core.getTranslations();
  201. }
  202. },
  203. getTranslations: function(){
  204. let firstScript = site.get.firstScript(elements.userScriptList);
  205. fetch(firstScript.href, {credentials: 'include'})
  206. .then(response => response.text())
  207. .then(text => new DOMParser().parseFromString(text, 'text/html'))
  208. .then(d => translation = storages.translations[site.get.language(d)] = site.get.translation(d, translation))
  209. .then(() => wait(INTERVAL))
  210. .then(() => fetch(firstScript.href + '/stats'))
  211. .then(response => response.text())
  212. .then(text => new DOMParser().parseFromString(text, 'text/html'))
  213. .then(d => {
  214. translation = storages.translations[site.get.language(d)] = site.get.translationOnStats(d, translation);
  215. Storage.save('translations', storages.translations);
  216. });
  217. },
  218. hideUserSection: function(){
  219. if(!elements.userProfile && !elements.controlPanel) return;/* thin enough */
  220. let aboutUser = elements.aboutUser, more = createElement(html.more());
  221. if(!storages.shown.aboutUser) aboutUser.classList.add('hidden');
  222. more.addEventListener('click', function(e){
  223. aboutUser.classList.toggle('hidden');
  224. storages.shown.aboutUser = !aboutUser.classList.contains('hidden');
  225. Storage.save('shown', storages.shown);
  226. });
  227. aboutUser.appendChild(more);
  228. },
  229. hideFeedback: function(){
  230. if(!elements.feedback) return;
  231. let feedback = elements.feedback, more = createElement(html.more());
  232. if(!storages.shown.feedback) feedback.classList.add('hidden');
  233. more.addEventListener('click', function(e){
  234. feedback.classList.toggle('hidden');
  235. storages.shown.feedback = !feedback.classList.contains('hidden');
  236. Storage.save('shown', storages.shown);
  237. });
  238. feedback.appendChild(more);
  239. },
  240. hideProfile: function(){
  241. /* use userName.hidden instead of userProfile.hidden for CSS */
  242. let controlPanel = elements.controlPanel, userName = elements.userName, userProfile = elements.userProfile;
  243. if(!userProfile) return;/* no profile text */
  244. let more = createElement(html.more());
  245. if(controlPanel/* may not be own user page */ && !storages.shown.userProfile) userName.classList.add('hidden');
  246. more.addEventListener('click', function(e){
  247. userName.classList.toggle('hidden');
  248. storages.shown.userProfile = !userName.classList.contains('hidden');
  249. if(controlPanel) Storage.save('shown', storages.shown);
  250. });
  251. userName.appendChild(more);
  252. },
  253. hideControlPanel: function(){
  254. let controlPanel = elements.controlPanel;
  255. if(!controlPanel) return;/* may be not own user page */
  256. document.documentElement.dataset.owner = 'true';/* user owner flag */
  257. let header = controlPanel.firstElementChild;
  258. if(!storages.shown.controlPanel) controlPanel.classList.add('hidden');
  259. header.addEventListener('click', function(e){
  260. controlPanel.classList.toggle('hidden');
  261. storages.shown.controlPanel = !controlPanel.classList.contains('hidden');
  262. Storage.save('shown', storages.shown);
  263. });
  264. },
  265. addTabNavigation: function(name, keys){
  266. let nav = createElement(html.tabNavigation());
  267. let template = nav.querySelector('li.template');
  268. let anchorKey = keys.find(key => elements[key.selector]);
  269. if(anchorKey) elements[anchorKey.selector].parentNode.insertBefore(nav, elements[anchorKey.selector]);
  270. for(let i = 0; keys[i]; i++){
  271. if(!elements[keys[i].selector]) continue;
  272. let li = template.cloneNode(true);
  273. li.classList.remove('template');
  274. li.textContent = keys[i].label + ` (${keys[i].count})`;
  275. li.dataset.target = keys[i].selector;
  276. li.dataset.count = keys[i].count;
  277. li.addEventListener('click', function(e){
  278. /* close tab */
  279. li.parentNode.querySelector('[data-selected="true"]').dataset.selected = 'false';
  280. let openedTarget = $(`[data-tabified="${name}"][data-selected="true"]`);
  281. if(openedTarget) openedTarget.dataset.selected = 'false';
  282. /* open tab */
  283. li.dataset.selected = 'true';
  284. let openingTarget = $(`[data-selector="${li.dataset.target}"]`);
  285. if(openingTarget) openingTarget.dataset.selected = 'true';
  286. });
  287. let target = elements[keys[i].selector];
  288. if(target){
  289. target.dataset.tabified = name;
  290. if(keys[i].selected) li.dataset.selected = target.dataset.selected = 'true';
  291. else li.dataset.selected = target.dataset.selected = 'false';
  292. }else{
  293. if(keys[i].selected) li.dataset.selected = 'true';
  294. else li.dataset.selected = 'false';
  295. }
  296. template.parentNode.insertBefore(li, template);
  297. }
  298. },
  299. addNewScriptSetLink: function(){
  300. let newScriptSetLink = elements.newScriptSetLink;
  301. if(!newScriptSetLink) return;/* may be not own user page */
  302. let link = newScriptSetLink.cloneNode(true), list = elements.userScriptSets, li = document.createElement('li');
  303. li.appendChild(link);
  304. list.appendChild(li);
  305. },
  306. rebuildScriptList: function(){
  307. if(!elements.userScriptList) return;
  308. for(let i = 0, list = elements.userScriptList, li; li = list.children[i]; i++){
  309. if(li.dataset.scriptId === undefined) continue;
  310. let more = createElement(html.more()), props = site.get.props(li), key = li.dataset.scriptName, isLibrary = li.dataset.scriptType === 'library';
  311. if(!storages.shown[key]) li.classList.add('hidden');
  312. more.addEventListener('click', function(e){
  313. li.classList.toggle('hidden');
  314. if(li.classList.contains('hidden')) delete storages.shown[key];/* prevent from getting fat storage */
  315. else storages.shown[key] = true;
  316. Storage.save('shown', storages.shown);
  317. });
  318. li.dataset.scriptUrl = props.name.href;
  319. li.appendChild(more);
  320. if(isLibrary) continue;/* not so critical to skip below by continue */
  321. /* attatch titles */
  322. props.dailyInstalls.previousElementSibling.title = props.dailyInstalls.previousElementSibling.textContent;
  323. props.totalInstalls.previousElementSibling.title = props.totalInstalls.previousElementSibling.textContent;
  324. props.ratings.previousElementSibling.title = props.ratings.previousElementSibling.textContent;
  325. props.createdDate.previousElementSibling.title = props.createdDate.previousElementSibling.textContent;
  326. props.updatedDate.previousElementSibling.title = props.updatedDate.previousElementSibling.textContent;
  327. /* wrap the description to make it an inline element */
  328. let span = document.createElement('span');
  329. span.textContent = props.description.textContent.trim();
  330. props.description.replaceChild(span, props.description.firstChild);
  331. /* Link to Stats from Total installs */
  332. let statsDd = createElement(html.ddLink('script-list-total-installs', props.totalInstalls.textContent, props.name.href + '/stats', translation.stats));
  333. props.stats.replaceChild(statsDd, props.totalInstalls);
  334. /* Link to Feedback from Rating Count */
  335. let feedbackLink = createElement(html.feedbackLink(props.goodRatingCount.textContent, props.name.href + '/feedback'));
  336. props.goodRatingCount.replaceChild(feedbackLink, props.goodRatingCount.firstChild);
  337. /* Link to Code */
  338. let versionLabel = createElement(html.dt('script-list-version', translation.version));
  339. let versionDd = createElement(html.ddLink('script-list-version', props.scriptVersion, props.name.href + '/code', translation.code));
  340. versionLabel.title = versionLabel.textContent;
  341. props.stats.insertBefore(versionLabel, props.createdDate.previousElementSibling);
  342. props.stats.insertBefore(versionDd, props.createdDate.previousElementSibling);
  343. /* Link to Version up */
  344. if(elements.controlPanel){
  345. let updateLink = document.createElement('a');
  346. updateLink.href = props.name.href + '/versions/new';
  347. updateLink.textContent = UPDATELINKTEXT;
  348. updateLink.title = translation.update;
  349. updateLink.classList.add('update');
  350. versionDd.appendChild(updateLink);
  351. }
  352. /* Link to History from Updated date */
  353. let historyDd = createElement(html.ddLink('script-list-updated-date', props.updatedDate.textContent, props.name.href + '/versions', translation.history));
  354. props.stats.replaceChild(historyDd, props.updatedDate);
  355. }
  356. },
  357. addChartSwitcher: function(){
  358. let userScriptList = elements.userScriptList;
  359. if(!userScriptList) return;
  360. const keys = [
  361. {label: translation.installs, selector: 'installs'},
  362. {label: translation.updateChecks, selector: 'updateChecks'},
  363. ];
  364. let nav = createElement(html.chartSwitcher());
  365. let template = nav.querySelector('li.template');
  366. userScriptList.parentNode.appendChild(nav);/* less affected on dom */
  367. for(let i = 0; keys[i]; i++){
  368. let li = template.cloneNode(true);
  369. li.classList.remove('template');
  370. li.textContent = keys[i].label;
  371. li.dataset.key = keys[i].selector;
  372. li.addEventListener('click', function(e){
  373. li.parentNode.querySelector('[data-selected="true"]').dataset.selected = 'false';
  374. li.dataset.selected = 'true';
  375. storages.chartKey = li.dataset.key;
  376. Storage.save('chartKey', storages.chartKey);
  377. core.drawCharts();
  378. });
  379. if(keys[i].selector === storages.chartKey) li.dataset.selected = 'true';
  380. else li.dataset.selected = 'false';
  381. template.parentNode.insertBefore(li, template);
  382. }
  383. core.drawCharts();
  384. },
  385. drawCharts: function(){
  386. let promises = [];
  387. if(timers.charts && timers.charts.length) timers.charts.forEach((id) => clearTimeout(id));/* stop all the former timers */
  388. timers.charts = [];
  389. for(let i = 0, list = elements.userScriptList, li; li = list.children[i]; i++){
  390. if(li.dataset.scriptId === undefined) continue;
  391. if(li.dataset.scriptType === 'library') continue;
  392. /* Draw chart of daily update checks */
  393. let chart = li.querySelector('.chart') || createElement(html.chart()), key = li.dataset.scriptName;
  394. if(storages.stats[key] && storages.stats[key].data){
  395. timers.charts[i] = setTimeout(function(){
  396. core.drawChart(chart, storages.stats[key].data.slice(-DAYS), li.dataset.scriptUpdatedDate);
  397. if(!chart.isConnected) li.appendChild(chart);
  398. }, i * DRAWINGDELAY);/* CPU friendly */
  399. }
  400. let now = Date.now(), updated = (storages.stats[key]) ? storages.stats[key].updated || 0 : 0, past = updated % STATSUPDATE, expire = updated - past + STATSUPDATE;
  401. if(now < expire) continue;/* still up-to-date */
  402. promises.push(new Promise(function(resolve, reject){
  403. timers.charts[i] = setTimeout(function(){
  404. fetch(li.dataset.scriptUrl + STATSPATH, {credentials: 'include'}/* for sensitive scripts */)/* less file size than json */
  405. .then(response => response.text())
  406. .then(csv => {
  407. let lines = csv.split('\n');
  408. lines = lines.slice(1, -1);/* cut the labels + blank line */
  409. storages.stats[key] = {data: [], updated: now};
  410. for(let i = 0; lines[i]; i++){
  411. let p = lines[i].split(',');
  412. storages.stats[key].data[i] = {
  413. date: p[0],
  414. installs: parseInt(p[1]),
  415. updateChecks: parseInt(p[2]),
  416. };
  417. }
  418. core.drawChart(chart, storages.stats[key].data.slice(-DAYS), li.dataset.scriptUpdatedDate);
  419. if(!chart.isConnected) li.appendChild(chart);
  420. resolve();
  421. });
  422. }, i * INTERVAL);/* server friendly */
  423. }));
  424. }
  425. if(promises.length) Promise.all(promises).then((values) => Storage.save('stats', storages.stats));
  426. },
  427. drawChart: function(chart, stats, scriptUpdatedDate){
  428. let dl = chart.querySelector('dl'), dt = dl.querySelector('dt.template'), dd = dl.querySelector('dd.template'), hasBars = (2 < dl.children.length);
  429. let chartKey = storages.chartKey, max = Math.max(DEFAULTMAX, ...stats.map(s => s[chartKey]));
  430. for(let i = last = stats.length - 1; stats[i]; i--){/* from last */
  431. let date = stats[i].date, count = stats[i][chartKey];
  432. let dateDt = dl.querySelector(`dt[data-date="${date}"]`) || dt.cloneNode();
  433. let countDd = dateDt.nextElementSibling || dd.cloneNode();
  434. if(!dateDt.isConnected){
  435. dateDt.classList.remove('template');
  436. countDd.classList.remove('template');
  437. dateDt.dataset.date = dateDt.textContent = date;
  438. if(hasBars){
  439. countDd.style.width = '0px';
  440. dl.insertBefore(dateDt, (i === last) ? dl.lastElementChild.previousElementSibling : dl.querySelector(`dt[data-date="${stats[i + 1].date}"]`));
  441. }else{
  442. dl.insertBefore(dateDt, dl.firstElementChild);
  443. }
  444. dl.insertBefore(countDd, dateDt.nextElementSibling);
  445. }else{
  446. if(dl.dataset.chartKey === chartKey && dl.dataset.max === max && countDd.dataset.count === count && i < last) break;/* it doesn't need update any more. */
  447. }
  448. countDd.title = date + ': ' + count;
  449. countDd.dataset.count = count;
  450. /* highlight the updated date */
  451. if(scriptUpdatedDate === date){
  452. countDd.classList.add('updated');
  453. countDd.title+= ' (last updated)';
  454. }
  455. /* the last date */
  456. if(i === last - 1){
  457. let label = countDd.querySelector('span') || document.createElement('span');
  458. label.textContent = toMetric(count);
  459. if(!label.isConnected) countDd.appendChild(label);
  460. }
  461. }
  462. dl.dataset.chartKey = chartKey, dl.dataset.max = max;
  463. /* for animation */
  464. animate(function(){
  465. for(let i = 0, dds = dl.querySelectorAll('dd.count:not(.template)'), dd; dd = dds[i]; i++){
  466. dd.style.height = ((dd.dataset.count / max) * 100) + '%';
  467. if(hasBars) dd.style.width = '';
  468. }
  469. });
  470. },
  471. getTarget: function(selector, retry = 10, interval = 1*SECOND){
  472. const key = selector.name;
  473. const get = function(resolve, reject){
  474. let selected = selector();
  475. if(selected && selected.length > 0) selected.forEach((s) => s.dataset.selector = key);/* elements */
  476. else if(selected instanceof HTMLElement) selected.dataset.selector = key;/* element */
  477. else if(--retry) return log(`Not found: ${key}, retrying... (${retry})`), setTimeout(get, interval, resolve, reject);
  478. else return reject(new Error(`Not found: ${selector.name}, I give up.`));
  479. elements[key] = selected;
  480. resolve(selected);
  481. };
  482. return new Promise(function(resolve, reject){
  483. get(resolve, reject);
  484. });
  485. },
  486. getTargets: function(selectors, retry = 10, interval = 1*SECOND){
  487. return Promise.all(Object.values(selectors).map(selector => core.getTarget(selector, retry, interval)));
  488. },
  489. addStyle: function(name = 'style'){
  490. if(html[name] === undefined) return;
  491. if(!document.head){
  492. let observer = observe(document.documentElement, function(){
  493. observer.disconnect();
  494. core.addStyle();
  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. margin-top: 0;
  665. position: relative;
  666. }
  667. #user-discussions-on-scripts-written section{
  668. border-radius: 0 5px 0 0;
  669. }
  670. #user-discussions-on-scripts-written.hidden section{
  671. min-height: 5em;
  672. max-height: 10em;
  673. overflow: scroll;
  674. }
  675. #user-discussions-on-scripts-written.hidden section > .discussion-list-item:first-child{
  676. border-top: none;
  677. padding-top: 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 greasyfork.org */
  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;
  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. })();