Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
10 changes: 8 additions & 2 deletions src/library-authoring/component-info/ComponentInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ import ComponentManagement from './ComponentManagement';
import ComponentPreview from './ComponentPreview';
import messages from './messages';
import { getBlockType } from '../../generic/key-utils';
import { useLibraryBlockMetadata, usePublishComponent } from '../data/apiHooks';
import { useComponentsFromSearchIndex, useLibraryBlockMetadata, usePublishComponent } from '../data/apiHooks';
import { ToastContext } from '../../generic/toast-context';
import PublishConfirmationModal from '../components/PublishConfirmationModal';
import { type ContentHit } from '../../search-manager';

const AddComponentWidget = () => {
const intl = useIntl();
Expand Down Expand Up @@ -146,6 +147,8 @@ const ComponentInfo = () => {
const canPublish = (new Date(componentMetadata?.modified ?? 0)) > (new Date(componentMetadata?.lastPublished ?? 0));
const { showToast } = React.useContext(ToastContext);

const { hits: componentHit } = useComponentsFromSearchIndex([usageKey]);

const publish = React.useCallback(() => {
closePublishConfirmation();
publishComponent.mutateAsync()
Expand Down Expand Up @@ -189,7 +192,10 @@ const ComponentInfo = () => {
>
{intl.formatMessage(messages.publishComponentButtonTitle)}
</Button>
<ComponentMenu usageKey={usageKey} />
<ComponentMenu
usageKey={usageKey}
unitsData={(componentHit as ContentHit[])?.[0]?.units}
/>

@navinkarkera navinkarkera May 7, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@ChrisChV It would be simpler to call useComponentsFromSearchIndex inside of ComponentMenu or ComponentDeleter (preferably former) component instead of passing through props.

Edit: Ahh, I missed the comment from @rpenido above.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Refactored here: 6291f67

</div>
)}
<AddComponentWidget />
Expand Down
13 changes: 2 additions & 11 deletions src/library-authoring/component-info/ComponentUsage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { useUnpaginatedEntityLinks } from '../../course-libraries/data/apiHooks'

import AlertError from '../../generic/alert-error';
import Loading from '../../generic/Loading';
import { useContentSearchConnection, useContentSearchResults } from '../../search-manager';
import messages from './messages';
import { useComponentsFromSearchIndex } from '../data/apiHooks';

interface ComponentUsageProps {
usageKey: string;
Expand Down Expand Up @@ -41,21 +41,12 @@ export const ComponentUsage = ({ usageKey }: ComponentUsageProps) => {
[dataDownstreamLinks],
);

const { client, indexName } = useContentSearchConnection();
const {
hits: downstreamHits,
isError: isErrorIndexDocuments,
error: errorIndexDocuments,
isLoading: isLoadingIndexDocuments,
} = useContentSearchResults({
client,
indexName,
searchKeywords: '',
extraFilter: [`usage_key IN ["${downstreamKeys.join('","')}"]`],
limit: downstreamKeys.length,
enabled: !!downstreamKeys.length,
skipBlockTypeFetch: true,
});
} = useComponentsFromSearchIndex(downstreamKeys);

if (isErrorDownstreamLinks || isErrorIndexDocuments) {
return <AlertError error={errorDownstreamLinks || errorIndexDocuments} />;
Expand Down
1 change: 1 addition & 0 deletions src/library-authoring/components/ComponentCard.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const contentHit: ContentHit = {
modified: 1722434322294,
lastPublished: null,
collections: {},
units: {},
publishStatus: PublishStatus.Published,
};

Expand Down
3 changes: 2 additions & 1 deletion src/library-authoring/components/ComponentCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const ComponentCard = ({ hit }: ComponentCardProps) => {
tags,
usageKey,
publishStatus,
units,
} = hit;
const componentDescription: string = (
showOnlyPublished ? formatted.published?.description : formatted.description
Expand Down Expand Up @@ -55,7 +56,7 @@ const ComponentCard = ({ hit }: ComponentCardProps) => {
{componentPickerMode ? (
<AddComponentWidget usageKey={usageKey} blockType={blockType} />
) : (
<ComponentMenu usageKey={usageKey} />
<ComponentMenu usageKey={usageKey} unitsData={units} />
)}
</ActionRow>
)}
Expand Down
48 changes: 48 additions & 0 deletions src/library-authoring/components/ComponentDeleter.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,52 @@ describe('<ComponentDeleter />', () => {
expect(mockShowToast).toHaveBeenCalledWith('Undo successful');
});
});

it('should show units message if `unitsData` is set with one unit', async () => {
const mockCancel = jest.fn();
render(
<ComponentDeleter
usageKey={usageKey}
isConfirmingDelete
cancelDelete={mockCancel}
unitsData={{
displayName: ['Unit 1'],
key: ['unit1'],
}}
/>,
renderArgs,
);

const modal = screen.getByRole('dialog', { name: 'Delete Component' });
expect(modal).toBeVisible();

expect(screen.getByText(
/by deleting this component, you will also be deleting it from in this library\./i,
)).toBeInTheDocument();
expect(screen.getByText(/unit 1/i)).toBeInTheDocument();
});

it('should show units message if `unitsData` is set with multiple units', async () => {
const mockCancel = jest.fn();
render(
<ComponentDeleter
usageKey={usageKey}
isConfirmingDelete
cancelDelete={mockCancel}
unitsData={{
displayName: ['Unit 1', 'Unit 2'],
key: ['unit1', 'unit2'],
}}
/>,
renderArgs,
);

const modal = screen.getByRole('dialog', { name: 'Delete Component' });
expect(modal).toBeVisible();

expect(screen.getByText(
/by deleting this component, you will also be deleting it from in this library\./i,
)).toBeInTheDocument();
expect(screen.getByText(/2 units/i)).toBeInTheDocument();
});
});
50 changes: 40 additions & 10 deletions src/library-authoring/components/ComponentDeleter.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useCallback, useContext } from 'react';
import { FormattedMessage, useIntl } from '@edx/frontend-platform/i18n';
import { Warning } from '@openedx/paragon/icons';
import { Icon } from '@openedx/paragon';
import { Info, Warning } from '@openedx/paragon/icons';

import { useSidebarContext } from '../common/context/SidebarContext';
import { useDeleteLibraryBlock, useLibraryBlockMetadata, useRestoreLibraryBlock } from '../data/apiHooks';
Expand All @@ -27,6 +28,7 @@ interface Props {
/** If true, show a confirmation modal that asks the user if they want to delete this component. */
isConfirmingDelete: boolean;
cancelDelete: () => void;
unitsData?: { displayName?: string[], key?: string[] };
}

const ComponentDeleter = ({ usageKey, ...props }: Props) => {
Expand Down Expand Up @@ -66,6 +68,16 @@ const ComponentDeleter = ({ usageKey, ...props }: Props) => {
return null;
}

let unitsMessage;
const unitsLength = props.unitsData?.displayName?.length ?? 0;
if (props.unitsData?.displayName && unitsLength > 0) {
if (props.unitsData.displayName.length === 1) {
[unitsMessage] = props.unitsData.displayName;
} else {
unitsMessage = `${unitsLength} units`;
}
}
Comment thread
ChrisChV marked this conversation as resolved.
Resolved

return (
<DeleteModal
isOpen
Expand All @@ -74,15 +86,33 @@ const ComponentDeleter = ({ usageKey, ...props }: Props) => {
title={intl.formatMessage(messages.deleteComponentWarningTitle)}
icon={Warning}
description={(
<FormattedMessage
{...messages.deleteComponentConfirm}
values={{
componentName: (
<strong><BlockName usageKey={usageKey} /></strong>
),
}}
/>
)}
<>
<FormattedMessage
{...messages.deleteComponentConfirm}
values={{
componentName: (
<strong><BlockName usageKey={usageKey} /></strong>
),
message: unitsLength
? intl.formatMessage(messages.deleteComponentConfirmCourseSmall)
: intl.formatMessage(messages.deleteComponentConfirmCourse),
}}
/>
{unitsMessage && (
<div className="d-flex mt-3 small text-danger-900">
<Icon className="mr-2 mt-2" src={Info} />
<div>
<FormattedMessage
{...messages.deleteComponentConfirmUnits}
values={{
unit: <strong>{unitsMessage}</strong>,
}}
/>
</div>
</div>
)}
</>
)}
onDeleteSubmit={doDelete}
/>
);
Expand Down
14 changes: 12 additions & 2 deletions src/library-authoring/components/ComponentMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@ import { canEditComponent } from './ComponentEditorModal';
import ComponentDeleter from './ComponentDeleter';
import messages from './messages';

export const ComponentMenu = ({ usageKey }: { usageKey: string }) => {
type ComponentMenuProps = {
usageKey: string,
unitsData?: { displayName?: string[], key?: string[] },
};

export const ComponentMenu = ({ usageKey, unitsData }: ComponentMenuProps) => {
const intl = useIntl();
const {
libraryId,
Expand Down Expand Up @@ -129,7 +134,12 @@ export const ComponentMenu = ({ usageKey }: { usageKey: string }) => {
</Dropdown.Item>
)}
</Dropdown.Menu>
<ComponentDeleter usageKey={usageKey} isConfirmingDelete={isConfirmingDelete} cancelDelete={cancelDelete} />
<ComponentDeleter
usageKey={usageKey}
isConfirmingDelete={isConfirmingDelete}
cancelDelete={cancelDelete}
unitsData={unitsData}
/>
</Dropdown>
);
};
Expand Down
17 changes: 16 additions & 1 deletion src/library-authoring/components/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,24 @@ const messages = defineMessages({
},
deleteComponentConfirm: {
id: 'course-authoring.library-authoring.component.delete-confirmation-text',
defaultMessage: 'Delete {componentName}? If this component has been used in a course, those copies won\'t be deleted, but they will no longer receive updates from the library.',
defaultMessage: 'Delete {componentName}? {message}',
description: 'Confirmation text to display before deleting a component',
},
deleteComponentConfirmCourse: {
id: 'course-authoring.library-authoring.component.delete-confirmation-text.course',
defaultMessage: 'If this component has been used in a course, those copies won\'t be deleted, but they will no longer receive updates from the library.',
description: 'Message text about courses when deleting a component',
},
deleteComponentConfirmCourseSmall: {
id: 'course-authoring.library-authoring.component.delete-confirmation-text.course-small',
defaultMessage: 'Any course instances will stop receiving library updates.',
description: 'Small message text about courses when deleting a component',
},
deleteComponentConfirmUnits: {
id: 'course-authoring.library-authoring.component.delete-confirmation-text.units',
defaultMessage: 'By deleting this component, you will also be deleting it from {unit} in this library.',
description: 'Message text about units when deleting a component',
},
deleteComponentCancelButton: {
id: 'course-authoring.library-authoring.component.cancel-delete-button',
defaultMessage: 'Cancel',
Expand Down
24 changes: 24 additions & 0 deletions src/library-authoring/data/apiHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { useCallback } from 'react';
import { getLibraryId } from '../../generic/key-utils';
import * as api from './api';
import { VersionSpec } from '../LibraryBlock';
import { useContentSearchConnection, useContentSearchResults } from '../../search-manager';

export const libraryQueryPredicate = (query: Query, libraryId: string): boolean => {
// Invalidate all content queries related to this library.
Expand Down Expand Up @@ -648,6 +649,13 @@ export const useAddComponentsToContainer = (containerId?: string) => {
return undefined;
},
onSettled: () => {
if (!containerId) {
return;
}
// NOTE: We invalidate the library query here because we need to update the units list
// of the added components
const libraryId = getLibraryId(containerId);
queryClient.invalidateQueries({ predicate: (query) => libraryQueryPredicate(query, libraryId) });
queryClient.invalidateQueries({ queryKey: libraryAuthoringQueryKeys.containerChildren(containerId!) });
},
});
Expand Down Expand Up @@ -737,3 +745,19 @@ export const usePublishContainer = (containerId: string) => {
},
});
};

/**
* Use this mutations to get a list of components from the search index
*/
export const useComponentsFromSearchIndex = (componentIds: string[]) => {
const { client, indexName } = useContentSearchConnection();
return useContentSearchResults({
client,
indexName,
searchKeywords: '',
extraFilter: [`usage_key IN ["${componentIds.join('","')}"]`],
limit: componentIds.length,
enabled: !!componentIds.length,
skipBlockTypeFetch: true,
});
};
Loading