GreasyFork User Dashboard

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

目前为 2020-10-10 提交的版本。查看 最新版本

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