Add manager sort block

This commit is contained in:
Rob Garrison 2017-12-23 03:11:46 +03:00 committed by tophf
parent 1fd0c26e1d
commit 5a07bbb1e3
12 changed files with 372 additions and 132 deletions

View File

@ -49,6 +49,7 @@ globals:
tNodeList: false
tDocLoader: false
tWordBreak: false
formatDate: false
# dom.js
onDOMready: false
onDOMscriptReady: false

View File

@ -214,6 +214,10 @@
"message": "Disabled",
"description": "Used in various lists/options to indicate that something is disabled"
},
"genericEnabledLabel": {
"message": "Enabled",
"description": "Used in various lists/options to indicate that something is enabled"
},
"genericHistoryLabel": {
"message": "History",
"description": "Used in various places to show a history log of something"
@ -234,6 +238,14 @@
"message": "Saved",
"description": "Used in various parts of the UI to indicate that something was saved"
},
"genericTitle": {
"message": "Title",
"description": "Used in various parts of the UI to indicate the title of something"
},
"genericUnknown": {
"message": "Unknown",
"description": "Used in various parts of the UI to indicate if something is unknown (e.g. an unknown date)"
},
"confirmNo": {
"message": "No",
"description": "'No' button in a confirm dialog"
@ -262,6 +274,14 @@
"message": "Close",
"description": "'Close' button in a confirm dialog"
},
"dateInstalled": {
"message": "Date installed",
"description": "Option text for the user to sort the style by install date"
},
"dateUpdated": {
"message": "Date updated",
"description": "Option text for the user to sort the style by last update date"
},
"dbError": {
"message": "An error has occurred using the Stylus database. Would you like to visit a web page with possible solutions?",
"description": "Prompt when a DB error is encountered"
@ -816,6 +836,34 @@
"shortcutsNote": {
"message": "Define keyboard shortcuts"
},
"sortLabel": {
"message": "Select a sort to apply to the installed styles",
"description": "Title on the sort select to indicate it is used for sorting entries"
},
"sortDateNewestFirst": {
"message": "newest first",
"description": "Text added to indicate that sorting a date would add the newest entries at the top"
},
"sortDateOldestFirst": {
"message": "oldest first",
"description": "Text added to indicate that sorting a date would add the oldest entries at the top"
},
"sortLabelTitleAsc": {
"message": "Title Ascending",
"description": "Text added to option group to indicate a block of options that apply a title ascending (A to Z) sort"
},
"sortLabelTitleDesc": {
"message": "Title Descending",
"description": "Text added to option group to indicate a block of options that apply a title descending (Z to A) sort"
},
"sortStylesHelpTitle": {
"message": "Sort contents",
"description": "Label for the sort info popup on the Manage styles page"
},
"sortStylesHelp": {
"message": "Choose the type of sort to apply to the installed entries from within the sort dropdown. The default setting applies an ascending sort (A to Z) to the entry titles. Sorts within the \"Title Descending\" group will apply a descending sort (Z to A) to the title.\nThere are other presets that will allow sorting the entries by multiple criteria. Think of this like sorting a table with multiple columns and each category in a select (between the plus signs) represents a column, or group.\nFor example, if the setting is \"Enabled (first) + Title\", the entries would sort so that all the enabled entries are sorted to the top of the list, then an entry title ascending sort (A to Z) is applied to both the enabled and disabled entries separately.",
"description": "Text in the minihelp displayed when clicking (i) icon to the right of the sort input field on the Manage styles page"
},
"styleBadRegexp": {
"message": "Regexp is invalid.",
"description": "Validation message for a bad regexp in a style"

View File

@ -197,3 +197,15 @@ function tWordBreak(text) {
return text.length <= 10 ? text :
text.replace(/([\d\w\u007B-\uFFFF]{10}|[\d\w\u007B-\uFFFF]{5,10}[!-/]|((?!\s)\W){10})(?!\b|\s)/g, '$&\u00AD');
}
function formatDate(date) {
return !date ? '' : tryCatch(() => {
const newDate = new Date(parseInt(date));
const string = newDate.toLocaleDateString([t.cache.browserUIlanguage, 'en'], {
day: '2-digit',
month: 'short',
year: newDate.getYear() === new Date().getYear() ? undefined : '2-digit',
});
return string === 'Invalid Date' ? '' : string;
}) || '';
}

View File

@ -36,6 +36,7 @@ var prefs = new function Prefs() {
'manage.newUI.favicons': false, // show favicons for the sites in applies-to
'manage.newUI.faviconsGray': true, // gray out favicons
'manage.newUI.targets': 3, // max number of applies-to targets visible: 0 = none
'manage.newUI.sort': 'title,asc',
'editor.options': {}, // CodeMirror.defaults.*
'editor.options.expanded': true, // UI element state: expanded/collapsed

View File

@ -155,6 +155,7 @@
<script src="manage/object-diff.js"></script>
<script src="vendor-overwrites/colorpicker/colorpicker.js"></script>
<script src="manage/config-dialog.js"></script>
<script src="manage/sort.js"></script>
<script src="manage/manage.js"></script>
</head>
@ -248,6 +249,16 @@
</details>
<div id="sort-wrapper">
<div class="sorter-selection" i18n-title="sortLabel">
<select id="manage.newUI.sort"></select>
<svg class="svg-icon select-arrow"><use xlink:href="#svg-icon-select-arrow"/></svg>
</div>
<a href="#" id="sorter-help">
<svg class="svg-icon info"><use xlink:href="#svg-icon-help"/></svg>
</a>
</div>
<p class="nowrap">
<button id="check-all-updates" i18n-text="checkAllUpdates"><span id="update-progress"></span></button>
<a href="#" id="update-history" i18n-title="genericHistoryLabel">

View File

@ -1,4 +1,5 @@
/* global installed messageBox */
/* global sorter */
'use strict';
const filtersSelector = {
@ -15,10 +16,12 @@ if (location.search) {
}
HTMLSelectElement.prototype.adjustWidth = function () {
const option0 = this.selectedOptions[0];
if (!option0) return;
const parent = this.parentNode;
const singleSelect = this.cloneNode(false);
singleSelect.style.width = '';
singleSelect.appendChild(this.selectedOptions[0].cloneNode(true));
singleSelect.appendChild(option0.cloneNode(true));
parent.replaceChild(singleSelect, this);
if (this.style.width !== singleSelect.offsetWidth + 'px') {
this.style.width = singleSelect.offsetWidth + 'px';
@ -154,6 +157,7 @@ function filterOnChange({target: el, forceRefilter}) {
});
if (installed) {
reapplyFilter();
sorter.update();
}
}
@ -190,17 +194,12 @@ function reapplyFilter(container = installed) {
filterContainer({hide: false});
}
// filtering needed or a single-element job from handleUpdate()
const entries = installed.children;
const numEntries = entries.length;
let numVisible = numEntries - $$('.entry.hidden').length;
for (const entry of toUnhide.children || toUnhide) {
const next = findInsertionPoint(entry);
if (entry.nextElementSibling !== next) {
installed.insertBefore(entry, next);
if (!entry.parentNode) {
installed.appendChild(entry);
}
if (entry.classList.contains('hidden')) {
entry.classList.remove('hidden');
numVisible++;
}
}
// B: hide
@ -218,18 +217,10 @@ function reapplyFilter(container = installed) {
// 1. add all hidden entries to the end
// 2. add the visible entries before the first hidden entry
if (container instanceof DocumentFragment) {
for (const entry of toHide) {
installed.appendChild(entry);
}
installed.insertBefore(container, $('.entry.hidden'));
installed.appendChild(container);
showFiltersStats();
return;
}
// normal filtering of the page or a single-element job from handleUpdate()
// we need to keep the visible entries together at the start
// first pass only moves one hidden entry in hidden groups with odd number of items
shuffle(false);
setTimeout(shuffle, 0, true);
// single-element job from handleEvent(): add the last wraith
if (toHide.length === 1 && toHide[0].parentElement !== installed) {
installed.appendChild(toHide[0]);
@ -256,95 +247,6 @@ function reapplyFilter(container = installed) {
toUnhide = $$(selector, container);
}
}
function shuffle(fullPass) {
if (fullPass && !document.body.classList.contains('update-in-progress')) {
$('#check-all-updates').disabled = !$('.updatable:not(.can-update)');
}
// 1. skip the visible group on top
let firstHidden = $('#installed > .hidden');
let entry = firstHidden;
let i = [...entries].indexOf(entry);
let horizon = entries[numVisible];
const skipGroup = state => {
const start = i;
const first = entry;
while (entry && entry.classList.contains('hidden') === state) {
entry = entry.nextElementSibling;
i++;
}
return {first, start, len: i - start};
};
let prevGroup = i ? {first: entries[0], start: 0, len: i} : skipGroup(true);
// eslint-disable-next-line no-unmodified-loop-condition
while (entry) {
// 2a. find the next hidden group's start and end
// 2b. find the next visible group's start and end
const isHidden = entry.classList.contains('hidden');
const group = skipGroup(isHidden);
const hidden = isHidden ? group : prevGroup;
const visible = isHidden ? prevGroup : group;
// 3. move the shortest group; repeat 2-3
if (hidden.len < visible.len && (fullPass || hidden.len % 2)) {
// 3a. move hidden under the horizon
for (let j = 0; j < (fullPass ? hidden.len : 1); j++) {
const entry = entries[hidden.start];
installed.insertBefore(entry, horizon);
horizon = entry;
i--;
}
prevGroup = isHidden ? skipGroup(false) : group;
firstHidden = entry;
} else if (isHidden || !fullPass) {
prevGroup = group;
} else {
// 3b. move visible above the horizon
for (let j = 0; j < visible.len; j++) {
const entry = entries[visible.start + j];
installed.insertBefore(entry, firstHidden);
}
prevGroup = {
first: firstHidden,
start: hidden.start + visible.len,
len: hidden.len + skipGroup(true).len,
};
}
}
if (fullPass) {
showFiltersStats({immediately: true});
}
}
function findInsertionPoint(entry) {
const nameLLC = entry.styleNameLowerCase;
let a = 0;
let b = Math.min(numEntries, numVisible) - 1;
if (b < 0) {
return entries[numVisible];
}
if (entries[0].styleNameLowerCase > nameLLC) {
return entries[0];
}
if (entries[b].styleNameLowerCase <= nameLLC) {
return entries[numVisible];
}
// bisect
while (a < b - 1) {
const c = (a + b) / 2 | 0;
if (nameLLC < entries[c].styleNameLowerCase) {
b = c;
} else {
a = c;
}
}
if (entries[a].styleNameLowerCase > nameLLC) {
return entries[a];
}
while (a <= b && entries[a].styleNameLowerCase < nameLLC) {
a++;
}
return entries[entries[a].styleNameLowerCase <= nameLLC ? a + 1 : a];
}
}

View File

@ -264,11 +264,14 @@ select {
}
#add-style-wrapper,
#options :last-child,
#backup :last-child {
margin-bottom: 0;
}
#options p:last-of-type {
margin-top: 0;
}
#header details:not([open]),
#header details:not([open]) h2 {
padding-bottom: 0;
@ -311,7 +314,7 @@ select {
display: table-row;
}
.newUI .entry:nth-child(2n) {
.newUI .entry.odd {
background-color: rgba(128, 128, 128, 0.05);
}
@ -320,14 +323,20 @@ select {
margin: 0;
display: table-cell;
vertical-align: middle;
contain: content;
}
.newUI .entry .actions {
contain: layout;
}
/************ checkbox & select************/
.newUI .checker {
margin: 0;
}
#newUIoptions > div {
#newUIoptions > div, #newUIoptions > label {
margin: 4px 0;
}
@ -454,9 +463,18 @@ select {
color: hsla(180, 100%, 15%, 1);
}
.newUI .homepage:not([href=""]) {
position: absolute;
margin-left: -28px;
.newUI .style-name:after {
text-indent: 1.2rem;
}
.newUI .actions:after {
text-indent: -25px;
}
.newUI .actions .homepage[href=""] {
display: inline-block;
visibility: hidden;
height: 0;
}
.newUI .actions {
@ -833,13 +851,23 @@ input[id^="manage.newUI"] {
display: none;
}
#search-wrapper {
#search-wrapper, #sort-wrapper {
display: flex;
align-items: center;
flex-wrap: wrap;
}
#search {
#sort-wrapper {
margin-top: .25em;
}
#sort-wrapper .sorter-selection {
position: relative;
width: calc(100% - 15px);
}
#search, #manage\.newUI\.sort {
max-width: 100%;
flex-grow: 1;
margin: 0.25rem 0 0;
background: #fff;
@ -849,13 +877,26 @@ input[id^="manage.newUI"] {
font: 400 12px Arial;
color: #000;
border: 1px solid hsl(0, 0%, 66%);
border-radius: 0.25rem;
}
#search-help {
#manage\.newUI\.sort {
padding-right: 18px;
width: 100%;
}
.firefox #manage\.newUI\.sort {
padding: 0;
}
#search-help, #sorter-help {
margin: 4px -5px 0 2px;
}
#sort-wrapper .select-arrow {
top: 7px;
right: 4px;
}
#message-box.help-text > div {
max-width: 26rem;
}
@ -941,6 +982,21 @@ input[id^="manage.newUI"] {
text-overflow: ellipsis;
}
/* sort font */
@font-face {
font-family: 'sorticon';
src: url('data:application/x-font-ttf;base64,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') format('truetype');
font-weight: normal;
font-style: normal;
unicode-range: U+21E9;
}
#manage\.newUI\.sort {
font-family: 'sorticon', Arial;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@keyframes fadein {
from {
opacity: 0;
@ -1026,6 +1082,7 @@ input[id^="manage.newUI"] {
}
#installed {
margin-top: 0;
padding-left: 0;
}

View File

@ -3,6 +3,7 @@
/* global checkUpdate, handleUpdateInstalled */
/* global objectDiff */
/* global configDialog */
/* global sorter */
'use strict';
let installed;
@ -58,6 +59,9 @@ function initGlobalEvents() {
$('#manage-options-button').onclick = () => chrome.runtime.openOptionsPage();
$('#manage-shortcuts-button').onclick = () => openURL({url: URLS.configureCommands});
$$('#header a[href^="http"]').forEach(a => (a.onclick = handleEvent.external));
// show date installed & last update on hover
installed.addEventListener('mouseover', handleEvent.lazyAddEntryTitle);
installed.addEventListener('mouseout', handleEvent.lazyAddEntryTitle);
// remember scroll position on normal history navigation
window.onbeforeunload = rememberScrollPosition;
@ -81,6 +85,7 @@ function initGlobalEvents() {
// N.B. triggers existing onchange listeners
setupLivePrefs();
sorter.init();
$$('[id^="manage.newUI"]')
.forEach(el => (el.oninput = (el.onchange = switchUI)));
@ -103,10 +108,17 @@ function initGlobalEvents() {
function showStyles(styles = []) {
const sorted = styles
.map(style => ({name: style.name.toLocaleLowerCase(), style}))
.sort((a, b) => (a.name < b.name ? -1 : a.name === b.name ? 0 : 1));
const sorted = sorter.sort({
styles: styles.map(style => ({
style,
name: style.name.toLocaleLowerCase() + '\n' + style.name,
})),
}).map((info, index) => {
info.index = index;
return info;
});
let index = 0;
installed.dataset.total = styles.length;
const scrollY = (history.state || {}).scrollY;
const shouldRenderAll = scrollY > window.innerHeight || sessionStorage.justEditedStyleId;
const renderBin = document.createDocumentFragment();
@ -149,7 +161,7 @@ function showStyles(styles = []) {
}
function createStyleElement({style, name}) {
function createStyleElement({style, name, index}) {
// query the sub-elements just once, then reuse the references
if ((createStyleElement.parts || {}).newUI !== newUI.enabled) {
const entry = template[`style${newUI.enabled ? 'Compact' : ''}`];
@ -188,6 +200,7 @@ function createStyleElement({style, name}) {
(style.enabled ? 'enabled' : 'disabled') +
(style.updateUrl ? ' updatable' : '') +
(style.usercssData ? ' usercss' : '');
if (index !== undefined) entry.classList.add(index % 2 ? 'odd' : 'even');
if (style.url) {
$('.homepage', entry).appendChild(parts.homepageIcon.cloneNode(true));
@ -395,6 +408,27 @@ Object.assign(handleEvent, {
event.preventDefault();
configDialog(styleMeta);
},
lazyAddEntryTitle({type, target}) {
const cell = target.closest('h2.style-name');
if (cell) {
const link = $('.style-name-link', cell);
if (type === 'mouseover' && !link.title) {
debounce(handleEvent.addEntryTitle, 50, link);
} else {
debounce.unregister(handleEvent.addEntryTitle);
}
}
},
addEntryTitle(link) {
const entry = link.closest('.entry');
link.title = [
{prop: 'installDate', name: 'dateInstalled'},
{prop: 'updateDate', name: 'dateUpdated'},
].map(({prop, name}) =>
t(name) + ': ' + (formatDate(entry.styleMeta[prop]) || '—')).join('\n');
}
});
@ -416,6 +450,7 @@ function handleUpdate(style, {reason, method} = {}) {
handleUpdateInstalled(entry, reason);
}
filterAndAppend({entry});
sorter.update();
if (!entry.matches('.hidden') && reason !== 'import') {
animateElement(entry);
scrollElementIntoView(entry);

174
manage/sort.js Normal file
View File

@ -0,0 +1,174 @@
/* global installed updateStripes */
/* global messageBox */
'use strict';
const sorter = (() => {
const sorterType = {
alpha: (a, b) => a < b ? -1 : a === b ? 0 : 1,
number: (a, b) => (a || 0) - (b || 0),
};
const tagData = {
title: {
text: t('genericTitle'),
parse: ({name}) => name,
sorter: sorterType.alpha
},
usercss: {
text: 'Usercss',
parse: ({style}) => style.usercssData ? 0 : 1,
sorter: sorterType.number
},
disabled: {
text: '', // added as either "enabled" or "disabled" by the addOptions function
parse: ({style}) => style.enabled ? 1 : 0,
sorter: sorterType.number
},
dateInstalled: {
text: t('dateInstalled'),
parse: ({style}) => style.installDate,
sorter: sorterType.number
},
dateUpdated: {
text: t('dateUpdated'),
parse: ({style}) => style.updateDate,
sorter: sorterType.number
}
};
// Adding (assumed) most commonly used ('title,asc' should always be first)
// whitespace before & after the comma is ignored
const selectOptions = [
'{groupAsc}',
'title,asc',
'dateInstalled,desc, title,asc',
'dateInstalled,asc, title,asc',
'dateUpdated,desc, title,asc',
'dateUpdated,asc, title,asc',
'usercss,asc, title,asc',
'usercss,desc, title,asc',
'disabled,asc, title,asc',
'disabled,desc, title,asc',
'disabled,desc, usercss,asc, title,asc',
'{groupDesc}',
'title,desc',
'usercss,asc, title,desc',
'usercss,desc, title,desc',
'disabled,desc, title,desc',
'disabled,desc, usercss,asc, title,desc'
];
const splitRegex = /\s*,\s*/;
function addOptions() {
let container;
const select = $('#manage.newUI.sort');
const renderBin = document.createDocumentFragment();
const option = $create('option');
const optgroup = $create('optgroup');
const meta = {
desc: ' \u21E9',
enabled: t('genericEnabledLabel'),
disabled: t('genericDisabledLabel'),
dateNew: ` (${t('sortDateNewestFirst')})`,
dateOld: ` (${t('sortDateOldestFirst')})`,
groupAsc: t('sortLabelTitleAsc'),
groupDesc: t('sortLabelTitleDesc')
};
const optgroupRegex = /\{\w+\}/;
selectOptions.forEach(sort => {
if (optgroupRegex.test(sort)) {
if (container) {
renderBin.appendChild(container);
}
container = optgroup.cloneNode();
container.label = meta[sort.substring(1, sort.length - 1)];
return;
}
let lastTag = '';
const opt = option.cloneNode();
opt.textContent = sort.split(splitRegex).reduce((acc, val) => {
if (tagData[val]) {
lastTag = val;
return acc + (acc !== '' ? ' + ' : '') + tagData[val].text;
}
if (lastTag.indexOf('date') > -1) return acc + meta[val === 'desc' ? 'dateNew' : 'dateOld'];
if (lastTag === 'disabled') return acc + meta[val === 'desc' ? 'enabled' : 'disabled'];
return acc + (meta[val] || '');
}, '');
opt.value = sort;
container.appendChild(opt);
});
renderBin.appendChild(container);
select.appendChild(renderBin);
select.value = prefs.get('manage.newUI.sort');
}
function sort({styles}) {
const sortBy = prefs.get('manage.newUI.sort').split(splitRegex);
const len = sortBy.length;
return styles.sort((a, b) => {
let types, direction;
let result = 0;
let index = 0;
// multi-sort
while (result === 0 && index < len) {
types = tagData[sortBy[index++]];
direction = sortBy[index++] === 'asc' ? 1 : -1;
result = types.sorter(types.parse(a), types.parse(b)) * direction;
}
return result;
});
}
function update() {
if (!installed) return;
const current = [...installed.children];
const sorted = sort({
styles: current.map(entry => ({
entry,
name: entry.styleNameLowerCase + '\n' + entry.styleMeta.name,
style: BG.cachedStyles.byId.get(entry.styleId),
}))
});
if (current.some((entry, index) => entry !== sorted[index].entry)) {
const renderBin = document.createDocumentFragment();
sorted.forEach(({entry}) => renderBin.appendChild(entry));
installed.appendChild(renderBin);
updateStripes();
}
}
function updateStripes() {
let index = 0;
[...installed.children].forEach(entry => {
const list = entry.classList;
if (!list.contains('hidden')) {
list.add(index % 2 ? 'odd' : 'even');
list.remove(index++ % 2 ? 'even' : 'odd');
}
});
}
function showHelp(event) {
event.preventDefault();
messageBox({
className: 'help-text',
title: t('sortStylesHelpTitle'),
contents:
$create('div',
t('sortStylesHelp').split('\n').map(line =>
$create('p', line))),
buttons: [t('confirmOK')],
});
}
function init() {
prefs.subscribe(['manage.newUI.sort'], update);
$('#sorter-help').onclick = showHelp;
addOptions();
}
return {init, update, sort, updateStripes};
})();

View File

@ -1,6 +1,6 @@
/* global messageBox */
/* global ENTRY_ID_PREFIX, newUI */
/* global filtersSelector, filterAndAppend */
/* global filtersSelector, filterAndAppend, sorter */
'use strict';
onDOMready().then(() => {
@ -144,6 +144,7 @@ function reportUpdateState(state, style, details) {
}
if (filtersSelector.hide) {
filterAndAppend({entry});
sorter.update();
}
}

View File

@ -117,6 +117,14 @@
overflow-wrap: break-word;
}
#message-box-contents p:first-child {
margin-top: 0;
}
#message-box-contents p:last-child {
margin-bottom: 0;
}
#message-box-buttons {
padding: .75rem .375rem;
background-color: #f0f0f0;

View File

@ -16,8 +16,6 @@ window.addEventListener('showStyles:done', function _() {
const BASE_URL = 'https://userstyles.org';
const UPDATE_URL = 'https://update.userstyles.org/%.md5';
const UI_LANG = chrome.i18n.getUILanguage();
// normal category is just one word like 'github' or 'google'
// but for some sites we need a fallback
// key: category.tld
@ -459,17 +457,9 @@ window.addEventListener('showStyles:done', function _() {
Object.assign($('[data-type="updated"] time', entry), {
dateTime: result.updated,
textContent: tryCatch(lang => {
const date = new Date(result.updated);
return date.toLocaleDateString(lang, {
day: '2-digit',
month: 'short',
year: date.getYear() === new Date().getYear() ? undefined : '2-digit',
});
}, [UI_LANG, 'en']) || '',
textContent: formatDate(result.updated)
});
$('[data-type="weekly"] dd', entry).textContent = formatNumber(result.weekly_install_count);
$('[data-type="total"] dd', entry).textContent = formatNumber(result.total_install_count);