// ==UserScript== // @name GreasyFork User Dashboard // @name:ja GreasyFork User Dashboard // @namespace knoa.jp // @description It redesigns user pages to improve the browsability. // @description:ja 一覧性に優れた新しいユーザーページを提供します。 // @include https://greasyfork.org/*/users/* // @version 1.3.1 // @grant none // @downloadURL none // ==/UserScript== (function(){ const SCRIPTNAME = 'GreasyForkUserDashboard'; const DEBUG = false;/* [update] 1.3.1 fix for new "Supporter" advertisement. [bug] [to do] [possible] 3カラムのレイアウト崩れる(スクリプト未使用でも発生する) グラフ数字の日付追加時くるりんぱは位置がズレるので労力に見合わないか [not to do] */ if(window === top && console.time) console.time(SCRIPTNAME); const INTERVAL = 1000;/* for fetch */ const DRAWINGDELAY = 125;/* for drawing each charts */ const UPDATELINKTEXT = '+';/* for update link text */ const DEFAULTMAX = 10;/* for chart scale */ const DAYS = 180;/* for chart length */ const STATSUPDATE = 1000*60*60;/* stats update interval of greasyfork.org */ const TRANSLATIONEXPIRE = 1000*60*60*24*30;/* cache time for translations */ const STATSEXPIRE = 1000*60*60*24*10;/* cache time for stats */ const EASING = 'cubic-bezier(0,.75,.5,1)';/* quick easing */ let site = { targets: { userSection: () => $('body > header + div > section:nth-of-type(1)'), userName: () => $('body > header + div > section:nth-of-type(1) > h2'), userProfile: () => $('#user-profile'), controlPanel: () => $('#control-panel'), newScriptSetLink: () => $('a[href$="/sets/new"]'), discussionList: () => $('ul.discussion-list'), scriptSets: () => $('body > header + div > section:nth-of-type(2)'), scripts: () => $('body > header + div > div:nth-of-type(1)'), userScriptSets: () => $('#user-script-sets'), userScriptList: () => $('#user-script-list'), }, get: { language: (d) => d.documentElement.lang, firstScript: (list) => list.querySelector('li h2 > a'), translation: (d, t) => { let es = { info: d.querySelector('#script-links > li.current'), code: d.querySelector('#script-links > li > a[href$="/code"]'), history: d.querySelector('#script-links > li > a[href$="/versions"]'), feedback: d.querySelector('#script-links > li > a[href$="/feedback"]'), stats: d.querySelector('#script-links > li > a[href$="/stats"]'), derivatives: d.querySelector('#script-links > li > a[href$="/derivatives"]'), update: d.querySelector('#script-links > li > a[href$="/versions/new"]'), delete: d.querySelector('#script-links > li > a[href$="/delete"]'), admin: d.querySelector('#script-links > li > a[href$="/admin"]'), version: d.querySelector('#script-stats > dt.script-show-version'), } Object.keys(es).forEach((key) => t[key] = es[key] ? es[key].textContent : t[key]); t.feedback = t.feedback.replace(/\s\(\d+\)/, ''); return t; }, translationOnStats: (d, t) => { t.installs = d.querySelector('table.stats-table > thead > tr > th:nth-child(2)').textContent || t.installs; t.updateChecks = d.querySelector('table.stats-table > thead > tr > th:nth-child(3)').textContent || t.updateChecks; return t; }, props: (li) => {return { name: li.querySelector('h2 > a'), description: li.querySelector('.description'), stats: li.querySelector('dl.inline-script-stats'), dailyInstalls: li.querySelector('dd.script-list-daily-installs'), totalInstalls: li.querySelector('dd.script-list-total-installs'), ratings: li.querySelector('dd.script-list-ratings'), createdDate: li.querySelector('dd.script-list-created-date'), updatedDate: li.querySelector('dd.script-list-updated-date'), scriptVersion: li.dataset.scriptVersion, }}, scriptUrl: (li) => li.querySelector('h2 > a').href, }, }; const DEFAULTTRANSLATION = { info: 'Info', code: 'Code', history: 'History', feedback: 'Feedback', stats: 'Stats', derivatives: 'Derivatives', update: 'Update', delete: 'Delete', admin: 'Admin', version: 'Version', installs: 'Installs', updateChecks: 'Update checks', scriptSets: 'Script Sets', scripts: 'Scripts', }; let translation = {}; let elements = {}, storages = {}, timers = {}; let core = { initialize: function(){ core.getElements(); core.read(); core.clearOldData(); core.addStyle(); core.prepareTranslations(); core.hideUserSection(); core.hideProfile(); core.hideControlPanel(); core.addTabNavigation(); core.addNewScriptSetLink(); core.rebuildScriptList(); core.addChartSwitcher(); }, getElements: function(){ for(let i = 0, keys = Object.keys(site.targets); keys[i]; i++){ let element = site.targets[keys[i]](); if(!element) log(`Not found: ${keys[i]}`); else{ element.dataset.selector = keys[i]; elements[keys[i]] = element; } } }, read: function(){ storages.translations = Storage.read('translations') || {}; storages.shown = Storage.read('shown') || {}; storages.stats = Storage.read('stats') || {}; storages.chartKey = Storage.read('chartKey') || 'updateChecks'; }, clearOldData: function(){ let now = Date.now(); Object.keys(storages.stats).forEach((key) => { if(storages.stats[key].updated < now - STATSEXPIRE) delete storages.stats[key]; }); Storage.save('stats', storages.stats); }, prepareTranslations: function(){ let language = site.get.language(document); translation = storages.translations[language] || DEFAULTTRANSLATION; if(!Object.keys(DEFAULTTRANSLATION).every((key) => translation[key])){/* some change in translation keys */ Object.keys(DEFAULTTRANSLATION).forEach((key) => translation[key] = translation[key] || DEFAULTTRANSLATION[key]); core.getTranslations(); }else{ if(site.get.language(document) === 'en') return; if(Date.now() < (Storage.saved('translations') || 0) + TRANSLATIONEXPIRE) return; core.getTranslations(); } }, getTranslations: function(){ let firstScript = site.get.firstScript(elements.userScriptList); fetch(firstScript.href, {credentials: 'include'}) .then(response => response.text()) .then(text => new DOMParser().parseFromString(text, 'text/html')) .then(d => translation = storages.translations[site.get.language(d)] = site.get.translation(d, translation)) .then(() => wait(INTERVAL)) .then(() => fetch(firstScript.href + '/stats')) .then(response => response.text()) .then(text => new DOMParser().parseFromString(text, 'text/html')) .then(d => { translation = storages.translations[site.get.language(d)] = site.get.translationOnStats(d, translation); Storage.save('translations', storages.translations); }); }, hideUserSection: function(){ if(!elements.userProfile && !elements.discussionList && !elements.controlPanel) return;/* thin enough */ let userSection = elements.userSection, more = createElement(core.html.more()); if(!storages.shown.userSection) userSection.classList.add('hidden'); more.addEventListener('click', function(e){ userSection.classList.toggle('hidden'); storages.shown.userSection = !userSection.classList.contains('hidden'); Storage.save('shown', storages.shown); }); userSection.appendChild(more); }, hideProfile: function(){ /* use userName.hidden instead of userProfile.hidden for CSS */ let controlPanel = elements.controlPanel, userName = elements.userName, userProfile = elements.userProfile; if(!controlPanel) return;/* may not be own user page */ if(!userProfile) return;/* no profile text */ let more = createElement(core.html.more()); if(!storages.shown.userProfile) userName.classList.add('hidden'); more.addEventListener('click', function(e){ userName.classList.toggle('hidden'); storages.shown.userProfile = !userName.classList.contains('hidden'); Storage.save('shown', storages.shown); }); userName.appendChild(more); }, hideControlPanel: function(){ let controlPanel = elements.controlPanel; if(!controlPanel) return;/* may be not own user page */ document.documentElement.dataset.owner = 'true';/* user owner flag */ let header = controlPanel.firstElementChild; if(!storages.shown.controlPanel) controlPanel.classList.add('hidden'); setTimeout(function(){elements.userSection.style.minHeight = controlPanel.offsetHeight + controlPanel.offsetTop + 'px'}, 250);/* needs delay */ header.addEventListener('click', function(e){ controlPanel.classList.toggle('hidden'); storages.shown.controlPanel = !controlPanel.classList.contains('hidden'); Storage.save('shown', storages.shown); elements.userSection.style.minHeight = controlPanel.offsetHeight + controlPanel.offsetTop + 'px'; }); }, addTabNavigation: function(){ let scriptSets = elements.scriptSets, scripts = elements.scripts; let userScriptSets = elements.userScriptSets, userScriptList = elements.userScriptList; const keys = [{ label: scriptSets ? scriptSets.querySelector('header').textContent : translation.scriptSets, selector: 'scriptSets', count: userScriptSets ? userScriptSets.children.length : 0, }, { label: scripts ? scripts.querySelector('header').textContent : translation.scripts, selector: 'scripts', count: userScriptList ? userScriptList.children.length : 0, selected: true }]; let nav = createElement(core.html.tabNavigation()), anchor = (scriptSets || scripts); let template = nav.querySelector('li.template'); if(anchor) anchor.parentNode.insertBefore(nav, anchor); for(let i = 0; keys[i]; i++){ let li = template.cloneNode(true); li.classList.remove('template'); li.textContent = keys[i].label + ` (${keys[i].count})`; li.dataset.target = keys[i].selector; li.dataset.count = keys[i].count; li.addEventListener('click', function(e){ /* close tab */ li.parentNode.querySelector('[data-selected="true"]').dataset.selected = 'false'; let openedTarget = $('[data-tabified][data-selected="true"]'); if(openedTarget) openedTarget.dataset.selected = 'false'; /* open tab */ li.dataset.selected = 'true'; let openingTarget = $(`[data-selector="${li.dataset.target}"]`); if(openingTarget) openingTarget.dataset.selected = 'true'; }); let target = elements[keys[i].selector]; if(target){ target.dataset.tabified = 'true'; if(keys[i].selected) li.dataset.selected = target.dataset.selected = 'true'; else li.dataset.selected = target.dataset.selected = 'false'; }else{ if(keys[i].selected) li.dataset.selected = 'true'; else li.dataset.selected = 'false'; } template.parentNode.insertBefore(li, template); } }, addNewScriptSetLink: function(){ let newScriptSetLink = elements.newScriptSetLink; if(!newScriptSetLink) return;/* may be not own user page */ let link = newScriptSetLink.cloneNode(true), list = elements.userScriptSets, li = document.createElement('li'); li.appendChild(link); list.appendChild(li); }, rebuildScriptList: function(){ if(!elements.userScriptList) return; for(let i = 0, list = elements.userScriptList, li; li = list.children[i]; i++){ if(li.dataset.scriptId === undefined) continue; let more = createElement(core.html.more()), props = site.get.props(li), key = li.dataset.scriptName, isLibrary = li.dataset.scriptType === 'library'; if(!storages.shown[key]) li.classList.add('hidden'); more.addEventListener('click', function(e){ li.classList.toggle('hidden'); if(li.classList.contains('hidden')) delete storages.shown[key];/* prevent from getting fat storage */ else storages.shown[key] = true; Storage.save('shown', storages.shown); }); li.dataset.scriptUrl = props.name.href; li.appendChild(more); if(isLibrary) continue;/* not so critical to skip below by continue */ /* attatch titles */ props.dailyInstalls.previousElementSibling.title = props.dailyInstalls.previousElementSibling.textContent; props.totalInstalls.previousElementSibling.title = props.totalInstalls.previousElementSibling.textContent; props.ratings.previousElementSibling.title = props.ratings.previousElementSibling.textContent; props.createdDate.previousElementSibling.title = props.createdDate.previousElementSibling.textContent; props.updatedDate.previousElementSibling.title = props.updatedDate.previousElementSibling.textContent; /* wrap the description to make it an inline element */ let span = document.createElement('span'); span.textContent = props.description.textContent.trim(); props.description.replaceChild(span, props.description.firstChild); /* Link to Code */ let versionLabel = createElement(core.html.dt('script-list-version', translation.version)); let versionDd = createElement(core.html.ddLink('script-list-version', props.scriptVersion, props.name.href + '/code', translation.code)); versionLabel.title = versionLabel.textContent; props.stats.insertBefore(versionLabel, props.createdDate.previousElementSibling); props.stats.insertBefore(versionDd, props.createdDate.previousElementSibling); /* Link to Version up */ if(elements.controlPanel){ let updateLink = document.createElement('a'); updateLink.href = props.name.href + '/versions/new'; updateLink.textContent = UPDATELINKTEXT; updateLink.title = translation.update; updateLink.classList.add('update'); versionDd.appendChild(updateLink); } /* Link to Stats from Total installs */ let statsDd = createElement(core.html.ddLink('script-list-total-installs', props.totalInstalls.textContent, props.name.href + '/stats', translation.stats)); props.stats.replaceChild(statsDd, props.totalInstalls); /* Link to History from Updated date */ let historyDd = createElement(core.html.ddLink('script-list-updated-date', props.updatedDate.textContent, props.name.href + '/versions', translation.history)); props.stats.replaceChild(historyDd, props.updatedDate); } }, addChartSwitcher: function(){ let userScriptList = elements.userScriptList; if(!userScriptList) return; const keys = [ {label: translation.installs, selector: 'installs'}, {label: translation.updateChecks, selector: 'updateChecks'}, ]; let nav = createElement(core.html.chartSwitcher()); let template = nav.querySelector('li.template'); userScriptList.parentNode.appendChild(nav);/* less affected on dom */ for(let i = 0; keys[i]; i++){ let li = template.cloneNode(true); li.classList.remove('template'); li.textContent = keys[i].label; li.dataset.key = keys[i].selector; li.addEventListener('click', function(e){ li.parentNode.querySelector('[data-selected="true"]').dataset.selected = 'false'; li.dataset.selected = 'true'; storages.chartKey = li.dataset.key; Storage.save('chartKey', storages.chartKey); core.drawCharts(); }); if(keys[i].selector === storages.chartKey) li.dataset.selected = 'true'; else li.dataset.selected = 'false'; template.parentNode.insertBefore(li, template); } core.drawCharts(); }, drawCharts: function(){ let promises = []; if(timers.charts && timers.charts.length) timers.charts.forEach((id) => clearTimeout(id));/* stop all the former timers */ timers.charts = []; for(let i = 0, list = elements.userScriptList, li; li = list.children[i]; i++){ if(li.dataset.scriptType === 'library') continue; /* Draw chart of daily update checks */ let chart = li.querySelector('.chart') || createElement(core.html.chart()), key = li.dataset.scriptName; if(storages.stats[key] && storages.stats[key].data){ timers.charts[i] = setTimeout(function(){ core.drawChart(chart, storages.stats[key].data.slice(-DAYS)); if(!chart.isConnected) li.appendChild(chart); }, i * DRAWINGDELAY);/* CPU friendly */ } let now = Date.now(), updated = (storages.stats[key]) ? storages.stats[key].updated || 0 : 0, past = updated % STATSUPDATE, expire = updated - past + STATSUPDATE; if(now < expire) continue;/* still up-to-date */ promises.push(new Promise(function(resolve, reject){ timers.charts[i] = setTimeout(function(){ fetch(li.dataset.scriptUrl + '/stats.csv', {credentials: 'include'}/* for sensitive scripts */)/* less file size than json */ .then(response => response.text()) .then(csv => { let lines = csv.split('\n'); lines = lines.slice(1, -1);/* cut the labels + blank line */ storages.stats[key] = {data: [], updated: now}; for(let i = 0; lines[i]; i++){ let p = lines[i].split(','); storages.stats[key].data[i] = { date: p[0], installs: parseInt(p[1]), updateChecks: parseInt(p[2]), }; } core.drawChart(chart, storages.stats[key].data.slice(-DAYS)); if(!chart.isConnected) li.appendChild(chart); resolve(); }); }, i * INTERVAL);/* server friendly */ })); } if(promises.length) Promise.all(promises).then((values) => Storage.save('stats', storages.stats)); }, drawChart: function(chart, stats){ let dl = chart.querySelector('dl'), dt = dl.querySelector('dt.template'), dd = dl.querySelector('dd.template'), hasBars = (2 < dl.children.length); let chartKey = storages.chartKey, max = Math.max(DEFAULTMAX, ...stats.map(s => s[chartKey])); for(let i = last = stats.length - 1; stats[i]; i--){/* from last */ let date = stats[i].date, count = stats[i][chartKey]; let dateDt = dl.querySelector(`dt[data-date="${date}"]`) || dt.cloneNode(); let countDd = dateDt.nextElementSibling || dd.cloneNode(); if(!dateDt.isConnected){ dateDt.classList.remove('template'); countDd.classList.remove('template'); dateDt.dataset.date = dateDt.textContent = date; if(hasBars){ countDd.style.width = '0px'; dl.insertBefore(dateDt, (i === last) ? dl.lastElementChild.previousElementSibling : dl.querySelector(`dt[data-date="${stats[i + 1].date}"]`)); }else{ dl.insertBefore(dateDt, dl.firstElementChild); } dl.insertBefore(countDd, dateDt.nextElementSibling); }else{ if(dl.dataset.chartKey === chartKey && dl.dataset.max === max && countDd.dataset.count === count && i < last) break;/* it doesn't need update any more. */ } countDd.title = date + ': ' + count; countDd.dataset.count = count; if(i === last - 1){ let label = countDd.querySelector('span') || document.createElement('span'); label.textContent = toMetric(count); if(!label.isConnected) countDd.appendChild(label); } } dl.dataset.chartKey = chartKey, dl.dataset.max = max; /* for animation */ animate(function(){ for(let i = 0, dds = dl.querySelectorAll('dd.count:not(.template)'), dd; dd = dds[i]; i++){ dd.style.height = ((dd.dataset.count / max) * 100) + '%'; if(hasBars) dd.style.width = ''; } }); }, addStyle: function(name = 'style'){ let style = createElement(core.html[name]()); document.head.appendChild(style); if(elements[name] && elements[name].isConnected) document.head.removeChild(elements[name]); elements[name] = style; }, html: { more: () => ` `, tabNavigation: () => ` `, chartSwitcher: () => ` `, dt: (className, textContent) => `