Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add user filtering to the Notebook #2835

Merged
merged 6 commits into from
Dec 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions src/sidebar/components/filter-select.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { createElement } from 'preact';
import propTypes from 'prop-types';

import Menu from './menu';
import MenuItem from './menu-item';
import SvgIcon from '../../shared/components/svg-icon';

/**
* @typedef {import('../store/modules/filters').FilterOption} FilterOption
*/

/**
* @typedef FilterSelectProps
* @prop {FilterOption} defaultOption
* @prop {string} [icon]
* @prop {(selectedFilter: FilterOption) => any} onSelect
* @prop {FilterOption[]} options
* @prop {FilterOption} [selectedOption]
* @prop {string} title
*/

/**
* A select-element-like control for selecting one of a defined set of
* options.
*
* @param {FilterSelectProps} props
*/
function FilterSelect({
defaultOption,
icon,
onSelect,
options,
selectedOption,
title,
}) {
const filterOptions = [defaultOption, ...options];
const selected = selectedOption ?? defaultOption;

const menuLabel = (
<span className="filter-select__menu-label">
{icon && <SvgIcon name={icon} className="filter-select__menu-icon" />}
{selected.display}
</span>
);

return (
<Menu label={menuLabel} title={title}>
{filterOptions.map(filterOption => (
<MenuItem
onClick={() => onSelect(filterOption)}
key={filterOption.value}
isSelected={filterOption.value === selected.value}
label={filterOption.display}
/>
))}
</Menu>
);
}

FilterSelect.propTypes = {
defaultOption: propTypes.object,
icon: propTypes.string,
onSelect: propTypes.func,
options: propTypes.array,
selectedOption: propTypes.object,
title: propTypes.string,
};

export default FilterSelect;
111 changes: 111 additions & 0 deletions src/sidebar/components/hooks/test/use-filter-options-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { mount } from 'enzyme';
import { createElement } from 'preact';

import { useUserFilterOptions } from '../use-filter-options';
import { $imports } from '../use-filter-options';

describe('sidebar/components/hooks/use-user-filter-options', () => {
let fakeStore;
let lastUserOptions;

// Mount a dummy component to be able to use the hook
function DummyComponent() {
lastUserOptions = useUserFilterOptions();
}

function annotationFixtures() {
return [
{
user: 'acct:dingbat@localhost',
user_info: { display_name: 'Ding Bat' },
},
{
user: 'acct:abalone@localhost',
user_info: { display_name: 'Aba Lone' },
},
{
user: 'acct:bananagram@localhost',
user_info: { display_name: 'Zerk' },
},
{
user: 'acct:dingbat@localhost',
user_info: { display_name: 'Ding Bat' },
},
];
}

beforeEach(() => {
fakeStore = {
allAnnotations: sinon.stub().returns([]),
getFocusFilters: sinon.stub().returns({}),
isFeatureEnabled: sinon.stub().returns(false),
};

$imports.$mock({
'../../store/use-store': { useStoreProxy: () => fakeStore },
});
});

afterEach(() => {
$imports.$restore();
});

it('should return a user filter option for each user who has authored an annotation', () => {
fakeStore.allAnnotations.returns(annotationFixtures());

mount(<DummyComponent />);

assert.deepEqual(lastUserOptions, [
{ value: 'abalone', display: 'abalone' },
{ value: 'bananagram', display: 'bananagram' },
{ value: 'dingbat', display: 'dingbat' },
]);
});

it('should use display names if feature flag enabled', () => {
fakeStore.allAnnotations.returns(annotationFixtures());
fakeStore.isFeatureEnabled.withArgs('client_display_names').returns(true);

mount(<DummyComponent />);

assert.deepEqual(lastUserOptions, [
{ value: 'abalone', display: 'Aba Lone' },
{ value: 'dingbat', display: 'Ding Bat' },
{ value: 'bananagram', display: 'Zerk' },
]);
});

it('should add focused-user filter information if configured', () => {
fakeStore.allAnnotations.returns(annotationFixtures());
fakeStore.isFeatureEnabled.withArgs('client_display_names').returns(true);
fakeStore.getFocusFilters.returns({
user: { value: 'carrotNumberOne', display: 'Number One Carrot' },
});

mount(<DummyComponent />);

assert.deepEqual(lastUserOptions, [
{ value: 'abalone', display: 'Aba Lone' },
{ value: 'dingbat', display: 'Ding Bat' },
{ value: 'carrotNumberOne', display: 'Number One Carrot' },
{ value: 'bananagram', display: 'Zerk' },
]);
});

it('always uses display name for focused user', () => {
fakeStore.allAnnotations.returns(annotationFixtures());
fakeStore.isFeatureEnabled.withArgs('client_display_names').returns(false);
fakeStore.getFocusFilters.returns({
user: { value: 'carrotNumberOne', display: 'Numero Uno Zanahoria' },
});

mount(<DummyComponent />);

assert.deepEqual(lastUserOptions, [
{ value: 'abalone', display: 'abalone' },
{ value: 'bananagram', display: 'bananagram' },
{ value: 'dingbat', display: 'dingbat' },
{ value: 'carrotNumberOne', display: 'Numero Uno Zanahoria' },
]);
});
});
51 changes: 51 additions & 0 deletions src/sidebar/components/hooks/use-filter-options.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useMemo } from 'preact/hooks';

import { useStoreProxy } from '../../store/use-store';
import { username } from '../../util/account-id';

/** @typedef {import('../../store/modules/filters').FilterOption} FilterOption */

/**
* Generate a list of users for filtering annotations; update when set of
* annotations or filter state changes meaningfully.
*
* @return {FilterOption[]}
*/
export function useUserFilterOptions() {
const store = useStoreProxy();
const annotations = store.allAnnotations();
const focusFilters = store.getFocusFilters();
const showDisplayNames = store.isFeatureEnabled('client_display_names');

return useMemo(() => {
// Determine unique users (authors) in annotation collection
const users = {};
annotations.forEach(annotation => {
const username_ = username(annotation.user);
const displayValue =
showDisplayNames && annotation.user_info?.display_name
? annotation.user_info.display_name
: username_;
users[username_] = displayValue;
});

// If user-focus is configured (even if not applied) add a filter
// option for that user. Note that this always respects the display
// value, even if `client_display_names` feature flags is not enabled:
// this matches current implementation of focus mode.
if (focusFilters.user) {
const username_ =
username(focusFilters.user.value) || focusFilters.user.value;
users[username_] = focusFilters.user.display;
}

// Convert to `FilterOption` objects
const userOptions = Object.keys(users).map(user => {
return { display: users[user], value: user };
});

userOptions.sort((a, b) => a.display.localeCompare(b.display));

return userOptions;
}, [annotations, focusFilters, showDisplayNames]);
}
35 changes: 35 additions & 0 deletions src/sidebar/components/notebook-filters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { createElement } from 'preact';

import { useStoreProxy } from '../store/use-store';
import { useUserFilterOptions } from './hooks/use-filter-options';

import FilterSelect from './filter-select';

/**
* @typedef {import('../store/modules/filters').FilterOption} FilterOption
*/

/**
* Filters for the Notebook
*/
function NotebookFilters() {
const store = useStoreProxy();

const userFilter = store.getFilter('user');
const userFilterOptions = useUserFilterOptions();

return (
<FilterSelect
defaultOption={{ value: '', display: 'Everybody' }}
icon="profile"
onSelect={userFilter => store.setFilter('user', userFilter)}
options={userFilterOptions}
selectedOption={userFilter}
title="Filter by user"
/>
);
}

NotebookFilters.propTypes = {};

export default NotebookFilters;
55 changes: 55 additions & 0 deletions src/sidebar/components/notebook-result-count.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { createElement } from 'preact';

import useRootThread from './hooks/use-root-thread';
import { useStoreProxy } from '../store/use-store';
import { countVisible } from '../util/thread';

/**
* Render count of annotations (or filtered results) visible in the notebook view
*
* There are three possible overall states:
* - No results (regardless of whether annotations are filtered): "No results"
* - Annotations are unfiltered: "X threads (Y annotations)"
* - Annotations are filtered: "X results [(and Y more)]"
*/
function NotebookResultCount() {
const store = useStoreProxy();
const forcedVisibleCount = store.forcedVisibleAnnotations().length;
const hasAppliedFilter = store.hasAppliedFilter();
const rootThread = useRootThread();
const visibleCount = countVisible(rootThread);

const hasResults = rootThread.children.length > 0;

const hasForcedVisible = forcedVisibleCount > 0;
const matchCount = visibleCount - forcedVisibleCount;
const threadCount = rootThread.children.length;

return (
<span className="notebook-result-count">
{!hasResults && <h2>No results</h2>}
{hasResults && hasAppliedFilter && (
<span>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the <span> element is not styled in any way then perhaps a Fragment could be used instead.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you help me understand the tradeoffs of using a <Fragment> versus using a containing element?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main benefit is that it avoids adding clutter to the DOM tree that doesn't serve any purpose for semantic or styling purposes. It's only a small benefit in many cases though.

<h2>
{matchCount} {matchCount === 1 ? 'result' : 'results'}
</h2>
{hasForcedVisible && <em> (and {forcedVisibleCount} more)</em>}
</span>
)}
{hasResults && !hasAppliedFilter && (
<span>
<h2>
{threadCount} {threadCount === 1 ? 'thread' : 'threads'}
</h2>{' '}
<em>
({visibleCount} {visibleCount === 1 ? 'annotation' : 'annotations'})
</em>
</span>
)}
</span>
);
}

NotebookResultCount.propTypes = {};

export default NotebookResultCount;
25 changes: 6 additions & 19 deletions src/sidebar/components/notebook-view.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { withServices } from '../util/service-context';
import useRootThread from './hooks/use-root-thread';
import { useStoreProxy } from '../store/use-store';

import NotebookFilters from './notebook-filters';
import NotebookResultCount from './notebook-result-count';
import ThreadList from './thread-list';

/**
Expand Down Expand Up @@ -38,31 +40,16 @@ function NotebookView({ loadAnnotationsService }) {
const rootThread = useRootThread();
const groupName = focusedGroup?.name ?? '…';

const hasResults = rootThread.totalChildren > 0;
const threadCount =
rootThread.totalChildren === 1
? '1 thread'
: `${rootThread.totalChildren} threads`;
const annotationCount =
rootThread.replyCount === 1
? '1 annotation'
: `${rootThread.replyCount} annotations`;

return (
<div className="notebook-view">
<header className="notebook-view__heading">
<h1>{groupName}</h1>
</header>
<div className="notebook-view__filters">
<NotebookFilters />
</div>
<div className="notebook-view__results">
{hasResults ? (
<span>
<h2>{threadCount}</h2> ({annotationCount})
</span>
) : (
<span>
<h2>No results</h2>
</span>
)}
<NotebookResultCount />
</div>
<div className="notebook-view__items">
<ThreadList thread={rootThread} />
Expand Down
Loading