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

feat: allow filtering library by publish status #1570

Merged
merged 17 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from 12 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
68 changes: 67 additions & 1 deletion src/library-authoring/LibraryAuthoringPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ describe('<LibraryAuthoringPage />', () => {
// Validate clear filters
fireEvent.click(problemMenu);

const clearFitlersButton = screen.getByRole('button', { name: /clear filters/i });
const clearFitlersButton = screen.getByText('Clear Filters');
fireEvent.click(clearFitlersButton);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
Expand Down Expand Up @@ -713,6 +713,72 @@ describe('<LibraryAuthoringPage />', () => {
});
});

it('filters by publish status', async () => {
await renderLibraryPage();

// Open the publish status filter dropdown
const filterButton = screen.getByRole('button', { name: /publish status/i });
fireEvent.click(filterButton);

// Test each publish status filter option
const publishedCheckbox = screen.getByRole('checkbox', { name: /^published \d+$/i });
const modifiedCheckbox = screen.getByRole('checkbox', { name: /^modified since publish \d+$/i });
const neverPublishedCheckbox = screen.getByRole('checkbox', { name: /^never published \d+$/i });

// Verify initial state - no clear filters button
expect(screen.queryByRole('button', { name: /clear filters/i })).not.toBeInTheDocument();

// Test Published filter
fireEvent.click(publishedCheckbox);

// Wait for both the API call and the UI update
await waitFor(() => {
// Check that the API was called with the correct filter
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining('"publish_status = published"'),
method: 'POST',
headers: expect.anything(),
});
});

// Wait for the clear filters button to appear
await waitFor(() => {
const clearFiltersButton = screen.getByText('Clear Filters');
expect(clearFiltersButton).toBeInTheDocument();
});

// Test Modified filter
fireEvent.click(modifiedCheckbox);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining('"publish_status = modified"'),
method: 'POST',
headers: expect.anything(),
});
});

// Test Never Published filter
fireEvent.click(neverPublishedCheckbox);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining('"publish_status = never"'),
method: 'POST',
headers: expect.anything(),
});
});

// Test clearing filters
const clearFiltersButton = screen.getByText('Clear Filters');
fireEvent.click(clearFiltersButton);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining('"filter":[[],'), // Empty filter array
method: 'POST',
headers: expect.anything(),
});
});
});

it('Disables Type filter on Collections tab', async () => {
await renderLibraryPage();

Expand Down
2 changes: 2 additions & 0 deletions src/library-authoring/LibraryAuthoringPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
ClearFiltersButton,
FilterByBlockType,
FilterByTags,
FilterByPublished,
SearchContextProvider,
SearchKeywordsField,
SearchSortWidget,
Expand Down Expand Up @@ -266,6 +267,7 @@ const LibraryAuthoringPage = ({ returnToLibrarySelection }: LibraryAuthoringPage
<SearchKeywordsField className="mr-3" />
<FilterByTags />
{!insideCollections && <FilterByBlockType />}
<FilterByPublished />
Copy link
Contributor

Choose a reason for hiding this comment

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

Could you please add <FilterByPublished /> to the LibraryCollectionPage too?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

will do

<ClearFiltersButton />
<ActionRow.Spacer />
<SearchSortWidget />
Expand Down
21 changes: 14 additions & 7 deletions src/library-authoring/components/BaseComponentCard.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import React, { useMemo } from 'react';
import {
Badge,
Card,
Container,
Icon,
Stack,
} from '@openedx/paragon';

import { useIntl } from '@edx/frontend-platform/i18n';
import messages from './messages';
import { getItemIcon, getComponentStyleColor } from '../../generic/block-type-utils';
import TagCount from '../../generic/tag-count';
import { BlockTypeLabel, type ContentHitTags, Highlight } from '../../search-manager';

type BaseComponentCardProps = {
componentType: string,
displayName: string, description: string,
numChildren?: number,
tags: ContentHitTags,
actions: React.ReactNode,
componentType: string;
displayName: string;
description: string;
numChildren?: number;
tags: ContentHitTags;
actions: React.ReactNode;
hasUnpublishedChanges?: boolean;
onSelect: () => void
};

Expand All @@ -27,6 +31,7 @@ const BaseComponentCard = ({
tags,
actions,
onSelect,
...props
} : BaseComponentCardProps) => {
const tagCount = useMemo(() => {
if (!tags) {
Expand All @@ -37,6 +42,7 @@ const BaseComponentCard = ({
}, [tags]);

const componentIcon = getItemIcon(componentType);
const intl = useIntl();

return (
<Container className="library-component-card">
Expand Down Expand Up @@ -75,7 +81,8 @@ const BaseComponentCard = ({
<div className="text-truncate h3 mt-2">
<Highlight text={displayName} />
</div>
<Highlight text={description} />
<Highlight text={description} /><br />
{props.hasUnpublishedChanges ? <Badge variant="warning">{intl.formatMessage(messages.unpublishedChanges)}</Badge> : null}
</Card.Section>
</Card.Body>
</Card>
Expand Down
3 changes: 3 additions & 0 deletions src/library-authoring/components/ComponentCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ const ComponentCard = ({ contentHit }: ComponentCardProps) => {
formatted,
tags,
usageKey,
modified,
lastPublished,
} = contentHit;
const componentDescription: string = (
showOnlyPublished ? formatted.published?.description : formatted.description
Expand Down Expand Up @@ -228,6 +230,7 @@ const ComponentCard = ({ contentHit }: ComponentCardProps) => {
)}
</ActionRow>
)}
hasUnpublishedChanges={modified >= (lastPublished ?? 0)}
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Why not pull this from the added published_status field? I'm ok either way, but it seems like we shouldn't duplicate functionality here.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

ohh nice catch

onSelect={openComponent}
/>
);
Expand Down
6 changes: 5 additions & 1 deletion src/library-authoring/components/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,10 @@ const messages = defineMessages({
defaultMessage: 'Select',
description: 'Button title for selecting multiple components',
},
unpublishedChanges: {
id: 'course-authoring.library-authoring.component.unpublished-changes',
defaultMessage: 'Unpublished changes',
description: 'Badge text shown when a component has unpublished changes',
},
});

export default messages;
18 changes: 10 additions & 8 deletions src/search-manager/ClearFiltersButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@ const ClearFiltersButton = ({
size = 'sm',
}: ClearFiltersButtonProps) => {
const { canClearFilters, clearFilters } = useSearchContext();
if (canClearFilters) {
return (
<Button variant={variant} size={size} onClick={clearFilters}>
<FormattedMessage {...messages.clearFilters} />
</Button>
);
}
return null;
return (
<Button
variant={variant}
size={size}
onClick={clearFilters}
className={canClearFilters ? '' : 'd-none'}
>
<FormattedMessage {...messages.clearFilters} />
</Button>
);
};

export default ClearFiltersButton;
107 changes: 107 additions & 0 deletions src/search-manager/FilterByPublished.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import React from 'react';
import {
Badge,
Form,
Menu,
MenuItem,
} from '@openedx/paragon';
import { FilterList } from '@openedx/paragon/icons';
import { useIntl } from '@edx/frontend-platform/i18n';
import messages from './messages';
import SearchFilterWidget from './SearchFilterWidget';
import { useSearchContext } from './SearchManager';
import { PublishStatus, SearchSortOption } from './data/api';

/**
* A button with a dropdown that allows filtering the current search by publish status
*/
const FilterByPublished: React.FC<Record<never, never>> = () => {
const [onlyPublished, setOnlyPublished] = React.useState(false);
const intl = useIntl();
const {
publishStatus,
publishStatusFilter,
setPublishStatusFilter,
searchSortOrder,
} = useSearchContext();

const clearFilters = React.useCallback(() => {
setPublishStatusFilter([]);
}, []);
Copy link
Contributor

Choose a reason for hiding this comment

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

Selecting a Published Status filter doesn't show the "clear filters" link?

Need to modify canClearFilters.


React.useEffect(() => {
if (searchSortOrder === SearchSortOption.RECENTLY_PUBLISHED) {
setPublishStatusFilter([PublishStatus.Published, PublishStatus.Modified]);
setOnlyPublished(true);
} else {
setOnlyPublished(false);
}
}, [searchSortOrder]);

const toggleFilterMode = React.useCallback((mode: PublishStatus) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Bug: Selecting one publish_status filter clears all the others? Maybe see FilterByBlockType for how its checkbox onChange handler works.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

it was because I forgot to add the setter to the dependencies. this was somehow breaking the tags filter tests so thank you so much for finding this :)

Copy link
Contributor

Choose a reason for hiding this comment

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

Thank you for working out a simple fix! it's working great now.

setPublishStatusFilter(oldList => {
if (oldList.includes(mode)) {
return oldList.filter(m => m !== mode);
}
return [...oldList, mode];
});
}, []);
const modeToLabel = {
published: intl.formatMessage(messages.publishStatusPublished),
modified: intl.formatMessage(messages.publishStatusModified),
never: intl.formatMessage(messages.publishStatusNeverPublished),
};
const appliedFilters = publishStatusFilter.map(mode => ({ label: modeToLabel[mode] }));

return (
<SearchFilterWidget
appliedFilters={appliedFilters}
label="Publish Status"
Copy link
Contributor

Choose a reason for hiding this comment

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

Please extract "Publish Status" to a message so it can be translated.

clearFilter={clearFilters}
icon={FilterList}
>
<Form.Group className="mb-0">
<Form.CheckboxSet
name="publish-status-filter"
value={publishStatusFilter}
>
<Menu className="block-type-refinement-menu" style={{ boxShadow: 'none' }}>
<MenuItem
as={Form.Checkbox}
value={PublishStatus.Published}
onChange={() => { toggleFilterMode(PublishStatus.Published); }}
>
<div>
{intl.formatMessage(messages.publishStatusPublished)}
<Badge variant="light" pill>{publishStatus[PublishStatus.Published] ?? 0}</Badge>
</div>
</MenuItem>
<MenuItem
as={Form.Checkbox}
value={PublishStatus.Modified}
onChange={() => { toggleFilterMode(PublishStatus.Modified); }}
>
<div>
{intl.formatMessage(messages.publishStatusModified)}
<Badge variant="light" pill>{publishStatus[PublishStatus.Modified] ?? 0}</Badge>
</div>
</MenuItem>
<MenuItem
as={Form.Checkbox}
value={PublishStatus.NeverPublished}
onChange={() => { toggleFilterMode(PublishStatus.NeverPublished); }}
disabled={onlyPublished}
>
<div>
{intl.formatMessage(messages.publishStatusNeverPublished)}
<Badge variant="light" pill>{publishStatus[PublishStatus.NeverPublished] ?? 0}</Badge>
</div>
</MenuItem>
</Menu>
</Form.CheckboxSet>
</Form.Group>
</SearchFilterWidget>
);
};

export default FilterByPublished;
21 changes: 20 additions & 1 deletion src/search-manager/SearchManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import { MeiliSearch, type Filter } from 'meilisearch';
import { union } from 'lodash';

import {
CollectionHit, ContentHit, SearchSortOption, forceArray,
CollectionHit,
ContentHit,
SearchSortOption,
forceArray, PublishStatus,
} from './data/api';
import { TypesFilterData, useStateOrUrlSearchParam } from './hooks';
import { useContentSearchConnection, useContentSearchResults } from './data/apiHooks';
Expand All @@ -20,12 +23,15 @@ export interface SearchContextData {
indexName?: string;
searchKeywords: string;
setSearchKeywords: React.Dispatch<React.SetStateAction<string>>;
publishStatusFilter: PublishStatus[];
setPublishStatusFilter: React.Dispatch<React.SetStateAction<PublishStatus[]>>;
typesFilter: TypesFilterData;
setTypesFilter: React.Dispatch<React.SetStateAction<TypesFilterData>>;
tagsFilter: string[];
setTagsFilter: React.Dispatch<React.SetStateAction<string[]>>;
blockTypes: Record<string, number>;
problemTypes: Record<string, number>;
publishStatus: Record<string, number>;
extraFilter?: Filter;
canClearFilters: boolean;
clearFilters: () => void;
Expand Down Expand Up @@ -98,6 +104,14 @@ export const SearchContextProvider: React.FC<{
skipUrlUpdate,
);

const [publishStatusFilter, setPublishStatusFilter] = useStateOrUrlSearchParam<PublishStatus>(
[],
'published',
(value: string) => Object.values(PublishStatus).find((enumValue) => value === enumValue),
(value: PublishStatus) => value.toString(),
skipUrlUpdate,
);

// E.g ?usageKey=lb:OpenCraft:libA:problem:5714eb65-7c36-4eee-8ab9-a54ed5a95849
const sanitizeUsageKey = (value: string): string | undefined => {
try {
Expand Down Expand Up @@ -144,12 +158,14 @@ export const SearchContextProvider: React.FC<{
const canClearFilters = (
!typesFilter.isEmpty()
|| tagsFilter.length > 0
|| publishStatusFilter.length > 0
|| !!usageKey
);
const isFiltered = canClearFilters || (searchKeywords !== '');
const clearFilters = React.useCallback(() => {
setTypesFilter((types) => types.clear());
setTagsFilter([]);
setPublishStatusFilter([]);
if (usageKey !== '') {
setUsageKey('');
}
Expand All @@ -164,6 +180,7 @@ export const SearchContextProvider: React.FC<{
indexName,
extraFilter,
searchKeywords,
Copy link
Contributor

Choose a reason for hiding this comment

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

Some UI questions, feel free to bounce these off the UX folks if you agree :)

  1. Currently, sorting by "Recently Published" also filters out any "Never published" items, but this is entirely hidden from the user.
    Should we make this explicit force-selecting the "Published" and "Modified since publish" filters in the UI?
  2. Should the Publish Status drop-down label reveal when some filters are selected, like the Type and Tags do?
    image
    To make the drop-down more concise, I'd use "Status: Published" or whatever instead of "Published status: Published".

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@jmakowski1123 @lizc577 @sdaitzman @marcotuts any comments on this? ^

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@jmakowski1123 @lizc577 @sdaitzman @marcotuts gentle nudge on this since we're blocked waiting for a decision here.

publishStatusFilter,
blockTypesFilter: [...typesFilter.blocks],
problemTypesFilter: [...typesFilter.problems],
tagsFilter,
Expand All @@ -177,6 +194,8 @@ export const SearchContextProvider: React.FC<{
indexName,
searchKeywords,
setSearchKeywords,
publishStatusFilter,
setPublishStatusFilter,
typesFilter,
setTypesFilter,
tagsFilter,
Expand Down
Loading
Loading