Skip to content

client: Add tag autocomplete #1311

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

Closed
wants to merge 6 commits into from
Closed
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
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# selfoss news
## 2.20 – unreleased

### New features
- Tags are now autocompleted when editing a new source. ([#1311](https://github.com/fossar/selfoss/pull/1311), [#669](https://github.com/fossar/selfoss/issues/669))

### Bug fixes
- Configuration parser was changed to *raw* method, which relaxes the requirement to quote option values containing special characters in `config.ini`. ([#1371](https://github.com/fossar/selfoss/issues/1371))

Expand Down
4 changes: 3 additions & 1 deletion assets/js/templates/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,9 @@ function PureApp({
)}
</Route>
<Route path="/manage/sources">
<SourcesPage />
<SourcesPage
tags={tags}
/>
</Route>
<Route path="*">
<NotFound />
Expand Down
174 changes: 151 additions & 23 deletions assets/js/templates/Source.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React from 'react';
import { useRef } from 'react';
import { useMemo, useRef } from 'react';
import { Button as MenuButton, Wrapper as MenuWrapper, Menu, MenuItem } from 'react-aria-menubutton';
import { useHistory, useLocation } from 'react-router-dom';
import ReactTags from 'react-tag-autocomplete';
import { fadeOut } from '@siteparts/show-hide-effects';
import { makeEntriesLinkLocation } from '../helpers/uri';
import PropTypes from 'prop-types';
Expand Down Expand Up @@ -67,10 +68,7 @@ function handleSave({

// Make tags into a list.
const tagsList = tags
? tags
.split(',')
.map((tag) => tag.trim())
.filter((tag) => tag !== '')
? tags.map((tag) => tag.name)
: [];

const values = {
Expand Down Expand Up @@ -192,15 +190,24 @@ function handleDelete({
}

// start editing
function handleEdit({ event, source, setEditedSource }) {
function handleEdit({ event, source, tagInfo, setEditedSource }) {
event.preventDefault();

const { id, title, tags, filter, spout, params } = source;

const newTags =
tags
? tags.map(unescape).map((name) => ({
id: tagInfo[name]?.id,
name,
color: tagInfo[name]?.color,
}))
: [];

setEditedSource({
id,
title: title ? unescape(title) : '',
tags: tags ? tags.map(unescape).join(',') : '',
tags: newTags,
filter,
spout,
params
Expand Down Expand Up @@ -267,13 +274,72 @@ function daysAgo(date) {
return Math.floor((today - old) / MS_PER_DAY);
}


function ColorBox({ color }) {
return (
<span
className="color"
style={{
backgroundColor: color,
}}
/>
);
}

ColorBox.propTypes = {
color: nullable(PropTypes.string).isRequired,
};

function mkTag(tagInfo) {
function Tag({ classNames, removeButtonText, onDelete, tag }) {
return (
<button
type="button"
className={classNames.selectedTag}
title={removeButtonText}
onClick={onDelete}
>
<ColorBox color={tagInfo[tag.name]?.color ?? null} />
{' '}
<span className={classNames.selectedTagName}>{tag.name}</span>
</button>
);
}

Tag.propTypes = {
classNames: PropTypes.object.isRequired,
removeButtonText: PropTypes.string.isRequired,
onDelete: PropTypes.func.isRequired,
tag: PropTypes.object.isRequired,
};

return Tag;
}


const reactTagsClassNames = {
root: 'react-tags',
rootFocused: 'is-focused',
selected: 'react-tags-selected',
selectedTag: 'react-tags-selected-tag',
selectedTagName: 'react-tags-selected-tag-name',
search: 'react-tags-search',
searchWrapper: 'react-tags-search-wrapper',
searchInput: 'react-tags-search-input',
suggestions: 'react-tags-suggestions',
suggestionActive: 'is-active',
suggestionDisabled: 'is-disabled',
suggestionPrefix: 'react-tags-suggestion-prefix'
};

function SourceEditForm({
source,
sourceElem,
sourceError,
setSources,
spouts,
setSpouts,
tagInfo,
setEditedSource,
sourceActionLoading,
setSourceActionLoading,
Expand Down Expand Up @@ -305,8 +371,39 @@ function SourceEditForm({
[updateEditedSource]
);

const tagsOnChange = React.useCallback(
(event) => updateEditedSource({ tags: event.target.value }),
const tagsOnAddition = React.useCallback(
(input) => {
// We need to handle pasting as well.
const tagsToAdd =
typeof input.id !== 'undefined'
? [input]
: input.name
.split(',')
.map((tag) => tag.trim())
.filter((tag) => tag !== '')
.map((tag) => ({ name: tag, id: undefined }));
updateEditedSource(({ tags }) => {
const usedTagNames = tags.map(({ name }) => name);
const freshTagsToAdd = tagsToAdd.filter((tag) => !usedTagNames.includes(tag.name));
if (freshTagsToAdd.length === 0) {
// All tags already included, no change.
return {};
}

return { tags: [...tags, ...freshTagsToAdd] };
});
},
[updateEditedSource]
);

const tagsOnDelete = React.useCallback(
(index) => {
updateEditedSource(({ tags }) => {
let newTags = tags.slice(0);
newTags.splice(index, 1);
return { tags: newTags};
});
},
[updateEditedSource]
);

Expand Down Expand Up @@ -366,6 +463,15 @@ function SourceEditForm({
[source, sourceElem, setSources, setEditedSource, dirty, setDirty]
);

const tagSuggestions = useMemo(
() => Object.entries(tagInfo).map(([name, { id, color }]) => ({
id,
name,
prefix: <ColorBox color={color ?? null} />
})),
[tagInfo]
);

const _ = React.useContext(LocalizationContext);

const sourceParamsContent = (
Expand Down Expand Up @@ -403,6 +509,10 @@ function SourceEditForm({

);

const reactTags = useRef();

const tagComponent = useMemo(() => mkTag(tagInfo), [tagInfo]);

return (
<form>
<ul className="source-edit-form">
Expand Down Expand Up @@ -431,18 +541,25 @@ function SourceEditForm({
<label htmlFor={`tags-${sourceId}`}>
{_('source_tags')}
</label>
<input
id={`tags-${sourceId}`}
type="text"
name="tags"
accessKey="g"
value={source.tags ?? ''}
onChange={tagsOnChange}
<ReactTags
ref={reactTags}
tags={source.tags}
inputAttributes={{
id: `tags-${sourceId}`,
accessKey: 'g',
}}
suggestions={tagSuggestions}
onDelete={tagsOnDelete}
onAddition={tagsOnAddition}
allowNew={true}
addOnBlur={true}
minQueryLength={1}
placeholderText={_('source_tags_placeholder')}
removeButtonText={_('source_tag_remove_button_label')}
classNames={reactTagsClassNames}
delimiters={['Enter', 'Tab', ',']}
tagComponent={tagComponent}
/>
<span className="source-edit-form-help">
{' '}
{_('source_comma')}
</span>
{sourceErrors['tags'] ? (
<span className="error">{sourceErrors['tags']}</span>
) : null}
Expand Down Expand Up @@ -548,6 +665,7 @@ SourceEditForm.propTypes = {
setSources: PropTypes.func.isRequired,
spouts: PropTypes.object.isRequired,
setSpouts: PropTypes.func.isRequired,
tagInfo: PropTypes.object.isRequired,
setEditedSource: PropTypes.func.isRequired,
sourceActionLoading: PropTypes.bool.isRequired,
setSourceActionLoading: PropTypes.func.isRequired,
Expand All @@ -562,7 +680,15 @@ SourceEditForm.propTypes = {
setDirty: PropTypes.func.isRequired,
};

export default function Source({ source, setSources, spouts, setSpouts, dirty, setDirtySources }) {
export default function Source({
source,
setSources,
spouts,
setSpouts,
tagInfo,
dirty,
setDirtySources,
}) {
const isNew = !source.title;
let classes = {
source: true,
Expand Down Expand Up @@ -591,8 +717,8 @@ export default function Source({ source, setSources, spouts, setSpouts, dirty, s
}, [justSavedTimeout]);

const editOnClick = React.useCallback(
(event) => handleEdit({ event, source, setEditedSource }),
[source]
(event) => handleEdit({ event, source, tagInfo, setEditedSource }),
[source, tagInfo]
);

const setDirty = React.useCallback(
Expand Down Expand Up @@ -723,6 +849,7 @@ export default function Source({ source, setSources, spouts, setSpouts, dirty, s
setSources,
spouts,
setSpouts,
tagInfo,
setEditedSource,
sourceActionLoading,
setSourceActionLoading,
Expand Down Expand Up @@ -750,6 +877,7 @@ Source.propTypes = {
setSources: PropTypes.func.isRequired,
spouts: PropTypes.object.isRequired,
setSpouts: PropTypes.func.isRequired,
tagInfo: PropTypes.object.isRequired,
dirty: PropTypes.bool.isRequired,
setDirtySources: PropTypes.func.isRequired,
};
33 changes: 31 additions & 2 deletions assets/js/templates/SourcesPage.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import PropTypes from 'prop-types';
import React from 'react';
import { useMemo } from 'react';
import { Prompt } from 'react-router';
Expand Down Expand Up @@ -90,9 +91,28 @@ function loadSources({ abortController, location, setSpouts, setSources, setLoad
});
}

export default function SourcesPage() {

export default function SourcesPage({ tags }) {
const [spouts, setSpouts] = React.useState([]);
const [sources, setSources] = React.useState([]);
const tagInfo = useMemo(
() => {
let maxTagId = 1;
let info = {};

tags.forEach(({ tag, color }) => {
if (typeof info[tag] === 'undefined') {
info[tag] = {
id: maxTagId++,
color,
};
}
});

return info;
},
[tags]
);

const [loadingState, setLoadingState] = React.useState(LoadingState.INITIAL);

Expand All @@ -105,6 +125,11 @@ export default function SourcesPage() {
React.useEffect(() => {
const abortController = new AbortController();

if (selfoss.app.state.tags.length === 0) {
// Ensure tags are loaded.
selfoss.reloadTags();
}

loadSources({ abortController, location, setSpouts, setSources, setLoadingState })
.then(() => {
if (isAdding) {
Expand Down Expand Up @@ -183,7 +208,7 @@ export default function SourcesPage() {
<Source
key={source.id}
dirty={dirtySources[source.id] ?? false}
{...{ source, setSources, spouts, setSpouts, setDirtySources }}
{...{ source, setSources, spouts, setSpouts, setDirtySources, tagInfo }}
/>
))}
</ul>
Expand All @@ -197,3 +222,7 @@ export default function SourcesPage() {
</React.Fragment>
);
}

SourcesPage.propTypes = {
tags: PropTypes.array.isRequired,
};
2 changes: 2 additions & 0 deletions assets/locale/cs.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
"lang_source_title": "Název",
"lang_source_autotitle_hint": "Pro automatické vyplnění ponechte prázdné",
"lang_source_tags": "Štítky",
"lang_source_tags_placeholder": "Přidat nový štítek",
"lang_source_tag_remove_button_label": "Klikněte pro odstranění štítku",
"lang_source_pwd_placeholder": "Beze změny",
"lang_source_comma": "Oddělené čárkou",
"lang_source_select": "Vyberte prosím zdroj",
Expand Down
2 changes: 2 additions & 0 deletions assets/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
"lang_source_title": "Title",
"lang_source_autotitle_hint": "Leave empty to fetch title",
"lang_source_tags": "Tags",
"lang_source_tags_placeholder": "Add new tag",
"lang_source_tag_remove_button_label": "Click to remove tag",
"lang_source_pwd_placeholder": "Not changed",
"lang_source_comma": "Comma separated",
"lang_source_select": "Please select source",
Expand Down
Loading