Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import type * as React from "react";
import { useState } from "react";
import { Link } from "react-router-dom";
import type { APIDataset, APIDatasetCompact } from "types/api_types";
import { getReadableURLPart } from "viewer/model/accessors/dataset_accessor";
import { getReadableURLPart, getViewDatasetURL } from "viewer/model/accessors/dataset_accessor";
import { getNoActionsAvailableMenu } from "viewer/view/context_menu";

const disabledStyle: React.CSSProperties = {
Expand Down Expand Up @@ -259,11 +259,7 @@ function DatasetActionView(props: Props) {
onShowCreateExplorativeModal={() => setIsCreateExplorativeModalVisible(true)}
onCloseCreateExplorativeModal={() => setIsCreateExplorativeModalVisible(false)}
/>
<LinkWithDisabled
to={`/datasets/${getReadableURLPart(dataset)}/view`}
title="View Dataset"
disabled={isReloading}
>
<LinkWithDisabled to={getViewDatasetURL(dataset)} title="View Dataset" disabled={isReloading}>
<EyeOutlined className="icon-margin-right" />
View
</LinkWithDisabled>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,10 @@ export function getReadableURLPart(
return `${getURLSanitizedName(dataset)}-${dataset.id}`;
}

export function getViewDatasetURL(dataset: APIDataset | APIDatasetCompact) {
return `/datasets/${getReadableURLPart(dataset)}/view`;
}

export function getDatasetIdOrNameFromReadableURLPart(datasetNameAndId: string) {
const datasetIdOrName = datasetNameAndId.split("-").pop();
const isId = /^[a-f0-9]{24}$/.test(datasetIdOrName || "");
Expand Down
172 changes: 159 additions & 13 deletions frontend/javascripts/viewer/view/components/command_palette.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import { updateSelectedThemeOfUser } from "admin/rest_api";
import { getDatasets, getReadableAnnotations, updateSelectedThemeOfUser } from "admin/rest_api";
import type { ItemType } from "antd/lib/menu/interface";
import { formatHash } from "libs/format_utils";
import { useWkSelector } from "libs/react_hooks";
import Toast from "libs/toast";
import { capitalize, getPhraseFromCamelCaseString } from "libs/utils";
import * as Utils from "libs/utils";
import _ from "lodash";
import { getAdministrationSubMenu } from "navbar";
import { useMemo } from "react";
import { useCallback, useMemo, useState } from "react";
import type { Command } from "react-command-palette";
import ReactCommandPalette from "react-command-palette";
import { getSystemColorTheme, getThemeFromUser } from "theme";
import { WkDevFlags } from "viewer/api/wk_dev";
import { ViewModeValues } from "viewer/constants";
import { getViewDatasetURL } from "viewer/model/accessors/dataset_accessor";
import { AnnotationTool } from "viewer/model/accessors/tool_accessor";
import { Toolkits } from "viewer/model/accessors/tool_accessor";
import { updateUserSettingAction } from "viewer/model/actions/settings_actions";
import { setViewModeAction, updateUserSettingAction } from "viewer/model/actions/settings_actions";
import { setThemeAction, setToolAction } from "viewer/model/actions/ui_actions";
import { setActiveUserAction } from "viewer/model/actions/user_actions";
import { Store } from "viewer/singletons";
Expand All @@ -22,12 +26,17 @@
useTracingViewMenuItems,
} from "../action-bar/use_tracing_view_menu_items";
import { viewDatasetMenu } from "../action-bar/view_dataset_actions_view";
import { LayoutEvents, layoutEmitter } from "../layouting/layout_persistence";
import { commandPaletteDarkTheme, commandPaletteLightTheme } from "./command_palette_theme";

type CommandWithoutId = Omit<Command, "id">;

const commandEntryColor = "#5660ff";

enum DynamicCommands {
viewDataset = "> View Dataset...",
viewAnnotation = "> View Annotation...",
}

const getLabelForAction = (action: NonNullable<ItemType>) => {
if ("title" in action && action.title != null) {
return action.title;
Expand Down Expand Up @@ -57,7 +66,13 @@
const getLabelForPath = (key: string) =>
getPhraseFromCamelCaseString(capitalize(key.split("/")[1])) || key;

//clean most html except <b> tags (for highlighting)
const cleanStringOfMostHTML = (dirtyString: string | undefined) =>
dirtyString?.replace(/<(?!\/?b>)|[^<>\w\/ ]+/g, "");

export const CommandPalette = ({ label }: { label: string | JSX.Element | null }) => {
console.log("Rendering Command Palette");

const userConfig = useWkSelector((state) => state.userConfiguration);
const isViewMode = useWkSelector((state) => state.temporaryConfiguration.controlMode === "VIEW");
const isInTracingView = useWkSelector((state) => state.uiInformation.isInAnnotationView);
Expand Down Expand Up @@ -99,6 +114,72 @@
return commands;
};

const handleSelect = useCallback(async (command: Record<string, unknown>) => {
console.log("h");
if (typeof command === "string") {
return;
}

if (command.name === DynamicCommands.viewDataset) {
const items = await getDatasetItems();
if (items.length > 0) {
setCommands(items);
} else {
Toast.info("No datasets available.");
}
return;
}

if (command.name === DynamicCommands.viewAnnotation) {
const items = await getAnnotationItems();
if (items.length > 0) {
setCommands(items);
} else {
Toast.info("No annotations available.");
}
return;
}

closePalette();
}, []);

const getDatasetItems = useCallback(async () => {
const datasets = await getDatasets();
return datasets.map((dataset) => ({
name: `View dataset: ${dataset.name}`,
command: () => {
window.location.href = getViewDatasetURL(dataset);
},
color: commandEntryColor,
id: dataset.id,
}));
}, []);

const viewDatasetsItem = {
name: DynamicCommands.viewDataset,
command: () => {},
color: commandEntryColor,
};

const getAnnotationItems = useCallback(async () => {
const annotations = await getReadableAnnotations(false);
const sortedAnnotations = _.sortBy(annotations, (a) => a.modified).reverse();
return sortedAnnotations.map((annotation) => ({
name: `View annotation: ${annotation.name.length > 0 ? annotation.name : formatHash(annotation.id)}`,
command: () => {
window.location.href = `/annotations/${annotation.id}`;
},
color: commandEntryColor,
id: annotation.id,
}));
}, []);

const viewAnnotationItems = {
name: DynamicCommands.viewAnnotation,
command: () => {},
color: commandEntryColor,
};

const getSuperUserItems = (): CommandWithoutId[] => {
if (!activeUser?.isSuperUser) {
return [];
Expand Down Expand Up @@ -185,6 +266,36 @@
return commands;
};

const getViewModeEntries = () => {
if (!isInTracingView) return [];
const commands = ViewModeValues.map((mode) => ({
name: `Switch to ${mode} mode`,
command: () => {
Store.dispatch(setViewModeAction(mode));
},
color: commandEntryColor,
}));
commands.push({
name: "Reset layout",
command: () => layoutEmitter.emit(LayoutEvents.resetLayout),
color: commandEntryColor,
});
return commands;
};

const shortCutDictForTools: Record<string, string> = {
[AnnotationTool.MOVE.id]: "Ctrl + K, M",
[AnnotationTool.SKELETON.id]: "Ctrl + K, S",
[AnnotationTool.BRUSH.id]: "Ctrl + K, B",
[AnnotationTool.ERASE_BRUSH.id]: "Ctrl + K, E",
[AnnotationTool.TRACE.id]: "Ctrl + K, L",
[AnnotationTool.ERASE_TRACE.id]: "Ctrl + K, R",
[AnnotationTool.VOXEL_PIPETTE.id]: "Ctrl + K, P",
[AnnotationTool.QUICK_SELECT.id]: "Ctrl + K, Q",
[AnnotationTool.BOUNDING_BOX.id]: "Ctrl + K, X",
[AnnotationTool.PROOFREAD.id]: "Ctrl + K, O",
};

const getToolEntries = () => {
if (!isInTracingView) return [];
const commands: CommandWithoutId[] = [];
Expand All @@ -196,6 +307,7 @@
commands.push({
name: `Switch to ${tool.readableName}`,
command: () => Store.dispatch(setToolAction(tool)),
shortcut: shortCutDictForTools[tool.id] || "",

Check failure on line 310 in frontend/javascripts/viewer/view/components/command_palette.tsx

View workflow job for this annotation

GitHub Actions / backend-tests

Object literal may only specify known properties, and 'shortcut' does not exist in type 'CommandWithoutId'.

Check failure on line 310 in frontend/javascripts/viewer/view/components/command_palette.tsx

View workflow job for this annotation

GitHub Actions / frontend-tests

Object literal may only specify known properties, and 'shortcut' does not exist in type 'CommandWithoutId'.
color: commandEntryColor,
});
});
Expand All @@ -212,28 +324,62 @@
return tracingMenuItems;
}, [isInTracingView, isViewMode, tracingMenuItems]);

const allCommands = [
const allStaticCommands = [
viewDatasetsItem,
viewAnnotationItems,
...getNavigationEntries(),
...getThemeEntries(),
...getToolEntries(),
...getViewModeEntries(),
...mapMenuActionsToCommands(menuActions),
...getTabsAndSettingsMenuItems(),
...getSuperUserItems(),
];

const [commands, setCommands] = useState<CommandWithoutId[]>(allStaticCommands);
const [paletteKey, setPaletteKey] = useState(0);

const closePalette = () => {
setPaletteKey((prevKey) => prevKey + 1);
};

const commandsWithIds = useMemo(() => {
return commands.map((command, index) => {
return { id: index, ...command };
});
}, [commands]);

return (
<ReactCommandPalette
commands={allCommands.map((command, counter) => {
return {
...command,
id: counter,
};
})}
commands={commandsWithIds}
key={paletteKey}
hotKeys={["ctrl+p", "command+p"]}
trigger={label}
closeOnSelect
resetInputOnOpen
maxDisplayed={100}
theme={theme === "light" ? commandPaletteLightTheme : commandPaletteDarkTheme}
onSelect={handleSelect}
showSpinnerOnSelect={false}
resetInputOnOpen
onRequestClose={() => setCommands(allStaticCommands)}
closeOnSelect={false}
renderCommand={(command) => {
const { name, shortcut, highlight: maybeDirtyString } = command;

Check failure on line 366 in frontend/javascripts/viewer/view/components/command_palette.tsx

View workflow job for this annotation

GitHub Actions / backend-tests

Property 'highlight' does not exist on type 'Command'.

Check failure on line 366 in frontend/javascripts/viewer/view/components/command_palette.tsx

View workflow job for this annotation

GitHub Actions / backend-tests

Property 'shortcut' does not exist on type 'Command'.

Check failure on line 366 in frontend/javascripts/viewer/view/components/command_palette.tsx

View workflow job for this annotation

GitHub Actions / frontend-tests

Property 'highlight' does not exist on type 'Command'.

Check failure on line 366 in frontend/javascripts/viewer/view/components/command_palette.tsx

View workflow job for this annotation

GitHub Actions / frontend-tests

Property 'shortcut' does not exist on type 'Command'.
const cleanString = cleanStringOfMostHTML(maybeDirtyString);
return (
<div
className="item"
style={{ display: "flex", justifyContent: "space-between", width: "100%" }}
>
{cleanString ? (
// biome-ignore lint/security/noDangerouslySetInnerHtml: modified from https://github.com/asabaylus/react-command-palette/blob/main/src/default-command.js
<span dangerouslySetInnerHTML={{ __html: cleanString }} />
) : (
<span>{name}</span>
)}
<span>{shortcut}</span>
</div>
);
}}
/>
);
};
Loading