feat: Allow configurable context menus (#2894)

* feat: Context menu

feat: Custom context menu

Adding documentation

PR updates

* fix: Capture tool exception

* PR updates

* Add fully worked out examples in the basic test mode/extension

* Fix the menu display

* fix: Make the commands on clicks much more configurable

* Wait for load before double clicking

* docs

* PR changes - nothing functional, just moving things endlessly

* PR comments

* PR changes - rename the default context menu

* Renamed the cornerstoneContextMenu to measurementsContextMenu

* Add chevron right to the sub-menus
This commit is contained in:
Bill Wallace authored and GitHub committed 2023-03-22 17:45:28 -04:00
1 parent 4e94b588a7
commit bc642fd2b6
40 files changed
+1472 -280

No files matched your search

+1 -1
View File
@@ -106,7 +106,7 @@ export class CommandsManager {
* @param {String} commandName - Command to find
* @param {String} [contextName] - Specific command to look in. Defaults to current activeContexts
*/
getCommand = (commandName, contextName) => {
getCommand = (commandName: string, contextName?: string) => {
const contexts = [];
if (contextName) {
@@ -36,7 +36,10 @@ export interface ExtensionParams extends ExtensionConstructor {
*/
export interface Extension {
id: string;
preRegistration?: (p: ExtensionParams) => void;
preRegistration?: (p: ExtensionParams) => Promise<void> | void;
onModeExit?: () => void;
getHangingProtocolModule?: (p: ExtensionParams) => unknown;
getCommandsModule?: (p: ExtensionParams) => CommandsModule;
}
export type ExtensionRegister = {
@@ -44,6 +47,12 @@ export type ExtensionRegister = {
create: (p: ExtensionParams) => Extension;
};
export type CommandsModule = {
actions: Record<string, unknown>;
definitions: Record<string, unknown>;
defaultContext?: string;
};
export default class ExtensionManager {
private _commandsManager: CommandsManager;
private _servicesManager: ServicesManager;
@@ -331,7 +340,7 @@ export default class ExtensionManager {
}
try {
const extensionModule = getModuleFn({
const extensionModule = extension[getModuleFnName]({
appConfig: this._appConfig,
commandsManager: this._commandsManager,
servicesManager: this._servicesManager,
@@ -348,6 +357,7 @@ export default class ExtensionManager {
return extensionModule;
} catch (ex) {
console.log(ex);
throw new Error(
`Exception thrown while trying to call ${getModuleFnName} for the ${extensionId} extension`
);
@@ -123,7 +123,7 @@ export default class CustomizationService extends PubSubService {
* may have been extended with any customizationType extensions provided,
* so you cannot just use `|| defaultValue`
* @return A customization to use if one is found, or the default customization,
* both enhanced with any customizationType inheritance (see applyType)
* both enhanced with any customizationType inheritance (see transform)
*/
public getCustomization(
customizationId: string,
@@ -145,7 +145,7 @@ export default class CustomizationService extends PubSubService {
this.globalCustomizations[customizationId] ??
this.modeCustomizations[customizationId] ??
defaultValue;
return this.applyType(customization);
return this.transform(customization);
}
public hasModeCustomization(customizationId: string) {
@@ -154,6 +154,16 @@ export default class CustomizationService extends PubSubService {
this.modeCustomizations[customizationId]
);
}
/**
* get is an alias for getModeCustomization, as it is the generic getter
* which will return both mode and global customizations, and should be
* used generally.
* Note that the second parameter, defaultValue, will be expanded to include
* any customizationType values defined in it, so it is not the same as doing:
* `customizationService.get('key') || defaultValue`
* unless the defaultValue does not contain any customizationType definitions.
*/
public get = this.getModeCustomization;
/**
* Applies any inheritance due to UI Type customization.
@@ -161,14 +171,16 @@ export default class CustomizationService extends PubSubService {
* and if that is found, will assign all iterable values from that
* type into the new type, allowing default behaviour to be configured.
*/
public applyType(customization: Customization): Customization {
public transform(customization: Customization): Customization {
if (!customization) return customization;
const { customizationType } = customization;
if (!customizationType) return customization;
const parent = this.getCustomization(customizationType);
return parent
const result = parent
? Object.assign(Object.create(parent), customization)
: customization;
// Execute an nested type information
return result.transform?.(this) || result;
}
public addModeCustomizations(modeCustomizations): void {
@@ -195,7 +207,7 @@ export default class CustomizationService extends PubSubService {
id: string,
defaultValue?: Customization
): Customization | void {
return this.applyType(this.globalCustomizations[id] ?? defaultValue);
return this.transform(this.globalCustomizations[id] ?? defaultValue);
}
setGlobalCustomization(id: string, value: Customization): void {
@@ -235,7 +247,7 @@ export default class CustomizationService extends PubSubService {
const extensionValue = this.findExtensionValue(value);
// The child of a reference is only a set of references when an array,
// so call the addReference direct. It could be a secondary reference perhaps
this.addReference(extensionValue);
this.addReference(extensionValue.value, isGlobal, extensionValue.name);
} else if (Array.isArray(value)) {
this.addReferences(value, isGlobal);
} else {
+2 -4
View File
@@ -4,9 +4,7 @@ export interface Command {
context?: string;
}
/**
* This is the format used within many items for multiple commands
*/
/** A set of commands, typically contained in a tool item or other configuration */
export interface Commands {
commands: [];
commands: Commands[];
}
@@ -210,8 +210,8 @@ example (this example comes from the context menu customizations as that one
uses commands lists):
```ts
cornerstoneContextMenu = uiConfigurationService.getModeCustomization("cornerstoneContextMenu", defaultMenu);
uiConfigurationService.recordInteraction(cornerstoneContextMenu, extraProps);
cornerstoneContextMenu = uiConfigurationService.get("cornerstoneContextMenu", defaultMenu);
commandsManager.run(cornerstoneContextMenu, extraProps);
```
### Global Customizations
@@ -229,7 +229,7 @@ This allows for having strong typing when declaring customizations, for example:
```ts
import { Types } from '@ohif/ui';
const customContextMenu: Types.UIContextMenu =
const customContextMenu: Types.ContextMenu.Menu =
{
id: 'cornerstoneContextMenu',
customizationType: 'ohif.contextMenu',
@@ -260,7 +260,7 @@ getCustomizationModule = () => ([
```
defines an overlay item which has a React content object as the render value.
This can then be used by specifying a customizationType of `ohif.overlayItem`, for example:
This can then be used by specifying a `customizationType` of `ohif.overlayItem`, for example:
```js
const overlayItem: Types.UIOverlayItem = {
@@ -275,7 +275,6 @@ const overlayItem: Types.UIOverlayItem = {
This section can be used to specify various customization capabilities.
## Text color for StudyBrowser tabs
This is the recommended pattern for deep customization of class attributes,
@@ -478,6 +477,29 @@ window.config = {
<img src="../../../assets/img/customizable-overlay.png" />
## Context Menus
Context menus can be created by defining the menu structure and click
interaction, as defined in the `ContextMenu/types`. There are examples
below specific to the cornerstone context, because the actual click
handler and attributes used to decide when and how to display the menu
are specific to the context used for where the menu is displayed.
## Cornerstone Context Menu
The default cornerstone context menu can be customized by setting the
`cornerstoneContextMenu`. For a full example, see `findingsContextMenu`.
## Customizeable Cornerstone Viewport Click Behaviour
The behaviour on clicking on the cornerstone viewport can be customized
by setting the `cornerstoneViewportClickCommands`. This is intended to
support both the cornerstone 3D internal commands as well as things like
context menus. Currently it supports buttons 1-3, as well as modifier keys
by associated a commands list with the button to click. See `initContextMenu`
for more details.
## Please add additional customizations above this section
> 3rd Party implementers may be added to this table via pull requests.
<!--
@@ -1,20 +1,32 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Typography } from '../';
import Typography from '../Typography';
import Icon from '../Icon';
const ContextMenu = ({ items }) => {
const ContextMenu = ({ items, ...props }) => {
if (!items) {
console.warn('No items for context menu');
return null;
}
return (
<div
data-cy="context-menu"
className="relative bg-secondary-dark rounded z-50 block w-48"
onContextMenu={e => e.preventDefault()}
>
{items.map((item, index) => (
<div
key={index}
onClick={() => item.action(item)}
data-cy="context-menu-item"
onClick={() => item.action(item, props)}
className="flex px-4 py-3 cursor-pointer items-center transition duration-300 hover:bg-primary-dark border-b border-primary-dark last:border-b-0"
>
<Typography>{item.label}</Typography>
<Typography>
{item.label}
{item.iconRight && (
<Icon name={item.iconRight} className="inline" />
)}
</Typography>
</div>
))}
</div>
@@ -25,7 +37,6 @@ ContextMenu.propTypes = {
items: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.string.isRequired,
actionType: PropTypes.string.isRequired,
action: PropTypes.func.isRequired,
})
).isRequired,
@@ -1,44 +0,0 @@
import { ContextMenu } from '../';
import PropTypes from 'prop-types';
import React from 'react';
const ContextMenuMeasurements = ({
onGetMenuItems,
onSetLabel,
onClose,
onDelete,
}) => {
const defaultMenuItems = [
{
label: 'Delete measurement',
actionType: 'Delete',
action: item => {
onDelete(item);
onClose();
},
value: {},
},
{
label: 'Add Label',
actionType: 'setLabel',
action: item => {
onSetLabel(item);
onClose();
},
value: {},
},
];
const menuItems = onGetMenuItems(defaultMenuItems);
return <ContextMenu items={menuItems} />;
};
ContextMenuMeasurements.propTypes = {
onClose: PropTypes.func.isRequired,
onSetLabel: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onGetMenuItems: PropTypes.func.isRequired,
};
export default ContextMenuMeasurements;
@@ -1 +0,0 @@
export { default } from './ContextMenuMeasurements';
+31 -15
View File
@@ -1,36 +1,52 @@
import React from 'react';
import React, { ReactNode } from 'react';
import PropTypes from 'prop-types';
import { useTranslation } from 'react-i18next';
import classNames from 'classnames';
import { NavBar, Svg, Icon, IconButton, Dropdown } from '../';
function Header({ children, menuOptions, isReturnEnabled, onClickReturnButton, isSticky, WhiteLabeling }) {
function Header({
children,
menuOptions,
isReturnEnabled,
onClickReturnButton,
isSticky,
WhiteLabeling,
...props
}): ReactNode {
const { t } = useTranslation('Header');
// TODO: this should be passed in as a prop instead and the react-router-dom
// dependency should be dropped
const onClickReturn = () => {
if (isReturnEnabled && onClickReturnButton) {
onClickReturnButton()
onClickReturnButton();
}
};
const CustomLogo = (React) => {
return WhiteLabeling.createLogoComponentFn(React)
}
return (
<NavBar className='justify-between border-b-4 border-black' isSticky={isSticky}>
<NavBar
className="justify-between border-b-4 border-black"
isSticky={isSticky}
>
<div className="flex justify-between flex-1">
<div className="flex items-center">
{/* // TODO: Should preserve filter/sort
// Either injected service? Or context (like react router's `useLocation`?) */}
<div
className={classNames("inline-flex items-center mr-3", isReturnEnabled && 'cursor-pointer')}
className={classNames(
'inline-flex items-center mr-3',
isReturnEnabled && 'cursor-pointer'
)}
onClick={onClickReturn}
>
{isReturnEnabled && <Icon name="chevron-left" className="w-8 text-primary-active" />}
<div className="ml-4">{WhiteLabeling ? CustomLogo(React) : <Svg name="logo-ohif" />}</div>
{isReturnEnabled && (
<Icon name="chevron-left" className="w-8 text-primary-active" />
)}
<div className="ml-4">
{WhiteLabeling?.createLogoComponentFn?.(React, props) || (
<Svg name="logo-ohif" />
)}
</div>
</div>
</div>
<div className="flex items-center">{children}</div>
@@ -40,7 +56,7 @@ function Header({ children, menuOptions, isReturnEnabled, onClickReturnButton, i
</span>
<Dropdown id="options" showDropdownIcon={false} list={menuOptions}>
<IconButton
id={"options-settings-icon"}
id={'options-settings-icon'}
variant="text"
color="inherit"
size="initial"
@@ -49,7 +65,7 @@ function Header({ children, menuOptions, isReturnEnabled, onClickReturnButton, i
<Icon name="settings" />
</IconButton>
<IconButton
id={"options-chevron-down-icon"}
id={'options-chevron-down-icon'}
variant="text"
color="inherit"
size="initial"
@@ -76,12 +92,12 @@ Header.propTypes = {
isReturnEnabled: PropTypes.bool,
isSticky: PropTypes.bool,
onClickReturnButton: PropTypes.func,
WhiteLabeling: PropTypes.element,
WhiteLabeling: PropTypes.object,
};
Header.defaultProps = {
isReturnEnabled: true,
isSticky: false
isSticky: false,
};
export default Header;
-2
View File
@@ -48,7 +48,6 @@ import ThumbnailNoImage from './ThumbnailNoImage';
import ThumbnailTracked from './ThumbnailTracked';
import ThumbnailList from './ThumbnailList';
import ToolbarButton from './ToolbarButton';
import ContextMenuMeasurements from './ContextMenuMeasurements';
import ExpandableToolbarButton from './ExpandableToolbarButton';
import ListMenu from './ListMenu';
import Tooltip from './Tooltip';
@@ -134,7 +133,6 @@ export {
ThumbnailTracked,
ThumbnailList,
ToolbarButton,
ContextMenuMeasurements,
Tooltip,
TooltipClipboard,
Typography,
-1
View File
@@ -94,7 +94,6 @@ export {
ThumbnailTracked,
ThumbnailList,
ToolbarButton,
ContextMenuMeasurements,
Tooltip,
TooltipClipboard,
Typography,
+7
View File
@@ -0,0 +1,7 @@
export type ContextMenuItem = {
// A label to show for the item.
label: string;
// An icon to show the on right of the text - typically used for submenus
iconRight?: string;
action: (item, component) => void;
};
+1
View File
@@ -0,0 +1 @@
export type Predicate = (props: Record<string, unknown>) => boolean;
+3
View File
@@ -4,6 +4,9 @@ import { PresentationIds } from '../contextProviders/getPresentationIds';
// A few miscellaneous types declared inline here.
export * from './Predicate';
export * from './ContextMenuItem';
/**
* StringNumber often comes back from DICOMweb for integer valued items.
*/
@@ -0,0 +1,42 @@
describe('OHIF Context Menu', function () {
beforeEach(function () {
cy.checkStudyRouteInViewer(
'1.2.840.113619.2.5.1762583153.215519.978957063.78'
);
cy.expectMinimumThumbnails(3);
cy.initCommonElementsAliases();
cy.initCornerstoneToolsAliases();
cy.resetViewport().wait(50);
});
it('checks context menu customization', function () {
// Add length measurement
cy.addLengthMeasurement();
cy.get('[data-cy="prompt-begin-tracking-yes"]').click();
cy.get('[data-cy="measurement-item"]').click();
const [x1, y1] = [150, 100];
cy.get('@viewport')
.trigger('mousedown', x1, y1, {
which: 3,
})
.trigger('mouseup', x1, y1, {
which: 3,
});
// Contextmenu is visible
cy.get('[data-cy="context-menu"]').should('be.visible');
// Click "Finding" subMenu
cy.get('[data-cy="context-menu-item"]')
.contains('Finding')
.click();
// Click "Finding" subMenu
cy.get('[data-cy="context-menu-item"]')
.contains('Aortic insufficiency')
.click();
cy.get('[data-cy="measurement-item"]').contains('Aortic insufficiency');
});
});
@@ -52,7 +52,7 @@ describe('OHIF Study Viewer Page', function() {
it('performs double-click to load thumbnail in active viewport', () => {
// Have to finish rendering the image before this works
cy.wait(250);
cy.wait(350);
cy.get('[data-cy="study-browser-thumbnail"]:nth-child(2)').dblclick();
//cy.get('@viewportInfoBottomLeft').should('contains.text', expectedText);