Skip to content
Open
Show file tree
Hide file tree
Changes from 20 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 @@ -32,7 +32,7 @@ import type { APIDataLayer, APIDataset, APITeam, LayerLink } from "types/api_typ
import { syncValidator } from "types/validation";
import { WkDevFlags } from "viewer/api/wk_dev";
import type { Vector3 } from "viewer/constants";
import { getReadableURLPart } from "viewer/model/accessors/dataset_accessor";
import { getReadableURLPart, getViewDatasetURL } from "viewer/model/accessors/dataset_accessor";
import { flatToNestedMatrix } from "viewer/model/accessors/dataset_layer_transformation_accessor";
import { checkLandmarksForThinPlateSpline } from "viewer/model/helpers/transformation_helpers";
import type { WizardComponentProps } from "./common";
Expand Down Expand Up @@ -372,7 +372,7 @@ function LinkedLayerForm({
info="This is the layer which will be linked into the new dataset."
>
<a
href={`/datasets/${getReadableURLPart({ name: datasetName, id: datasetId })}/view`}
href={getViewDatasetURL({ name: datasetName, id: datasetId })}
target="_blank"
rel="noreferrer"
>
Expand Down
6 changes: 2 additions & 4 deletions frontend/javascripts/admin/dataset/dataset_add_view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useWkSelector } from "libs/react_hooks";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import type { APIDataStore } from "types/api_types";
import { getReadableURLPart } from "viewer/model/accessors/dataset_accessor";
import { getReadableURLPart, getViewDatasetURL } from "viewer/model/accessors/dataset_accessor";
import DatasetAddComposeView from "./dataset_add_compose_view";

const { Content, Sider } = Layout;
Expand Down Expand Up @@ -306,9 +306,7 @@ const getPostUploadModal = (
<Button
type="primary"
onClick={() =>
navigate(
`/datasets/${getReadableURLPart({ name: uploadedDatasetName, id: datasetId })}/view`,
)
navigate(getViewDatasetURL({ name: uploadedDatasetName, id: datasetId }))
}
>
View the Dataset
Expand Down
4 changes: 2 additions & 2 deletions frontend/javascripts/admin/job/job_list_view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import type * as React from "react";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { type APIJob, APIJobType, type APIUserBase } from "types/api_types";
import { getReadableURLPart } from "viewer/model/accessors/dataset_accessor";
import { getViewDatasetURL } from "viewer/model/accessors/dataset_accessor";

// Unfortunately, the twoToneColor (nor the style) prop don't support
// CSS variables.
Expand Down Expand Up @@ -164,7 +164,7 @@ function JobListView() {
function getLinkToDataset(job: APIJob) {
// prefer updated link over legacy link.
if (job.datasetId != null)
return `/datasets/${getReadableURLPart({ name: job.datasetName || "unknown_name", id: job.datasetId })}/view`;
return getViewDatasetURL({ name: job.datasetName || "unknown_name", id: job.datasetId });
if (job.organizationId != null && (job.datasetName != null || job.datasetDirectoryName != null))
return `/datasets/${job.organizationId}/${job.datasetDirectoryName || job.datasetName}/view`;
return null;
Expand Down
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 Expand Up @@ -319,7 +315,7 @@ export function getDatasetActionContextMenu({
key: "view",
label: "View",
onClick: () => {
window.location.href = `/datasets/${getReadableURLPart(dataset)}/view`;
window.location.href = getViewDatasetURL(dataset);
},
}
: null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import { Link } from "react-router-dom";
import type { APIDatasetCompact, APIMaybeUnimportedDataset, FolderItem } from "types/api_types";
import type { EmptyObject } from "types/globals";
import { Unicode } from "viewer/constants";
import { getReadableURLPart } from "viewer/model/accessors/dataset_accessor";
import { getViewDatasetURL } from "viewer/model/accessors/dataset_accessor";
import CategorizationLabel from "viewer/view/components/categorization_label";
import EditableTextIcon from "viewer/view/components/editable_text_icon";
import {
Expand Down Expand Up @@ -333,7 +333,7 @@ class DatasetRenderer {

return (
<>
<Link to={`/datasets/${getReadableURLPart(this.data)}/view`} title="View Dataset">
<Link to={getViewDatasetURL(this.data)} title="View Dataset">
<img
src={imgSrc}
className={`dataset-table-thumbnail ${iconClassName}`}
Expand All @@ -343,7 +343,7 @@ class DatasetRenderer {
</Link>
<div className="dataset-table-name-container">
<Link
to={`/datasets/${getReadableURLPart(this.data)}/view`}
to={getViewDatasetURL(this.data)}
title="View Dataset"
className="incognito-link dataset-table-name"
>
Expand Down Expand Up @@ -803,7 +803,7 @@ class DatasetTable extends React.PureComponent<Props, State> {
},
onDoubleClick: () => {
if (isADataset) {
window.location.href = `/datasets/${getReadableURLPart(data)}/view`;
window.location.href = getViewDatasetURL(data);
} else {
context.setActiveFolderId(data.key);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,12 @@ export function getReadableURLPart(
return `${getURLSanitizedName(dataset)}-${dataset.id}`;
}

export function getViewDatasetURL(
dataset: APIDataset | APIDatasetCompact | { name: string; id: string },
) {
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
184 changes: 171 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 DOMPurify from "dompurify";
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,11 +26,18 @@
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";

const commandEntryColor = "#5660ff";

// duplicate fields because otherwise, optional fields of Command yield errors
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) {
Expand Down Expand Up @@ -57,6 +68,11 @@
const getLabelForPath = (key: string) =>
getPhraseFromCamelCaseString(capitalize(key.split("/")[1])) || key;

const cleanStringOfMostHTML = (dirtyString: string | undefined) => {
if (dirtyString == null) return null;
return DOMPurify.sanitize(dirtyString, { ALLOWED_TAGS: ["b"] });
};

export const CommandPalette = ({ label }: { label: string | JSX.Element | null }) => {
const userConfig = useWkSelector((state) => state.userConfiguration);
const isViewMode = useWkSelector((state) => state.temporaryConfiguration.controlMode === "VIEW");
Expand Down Expand Up @@ -99,6 +115,83 @@
return commands;
};

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

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

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

closePalette();
}, []);

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

const viewDatasetsItem = {
name: DynamicCommands.viewDataset,
command: () => {},
shortcut: "Enter to show list",
color: commandEntryColor,
};

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

const viewAnnotationItems = {
name: DynamicCommands.viewAnnotation,
shortcut: "Enter to show list",
command: () => {},
color: commandEntryColor,
};

const getSuperUserItems = (): CommandWithoutId[] => {
if (!activeUser?.isSuperUser) {
return [];
Expand Down Expand Up @@ -185,6 +278,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 +319,7 @@
commands.push({
name: `Switch to ${tool.readableName}`,
command: () => Store.dispatch(setToolAction(tool)),
shortcut: shortCutDictForTools[tool.id] || "",

Check failure on line 322 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 322 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 +336,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 { shortcut, highlight: maybeDirtyString, name } = command;

Check failure on line 378 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 378 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 378 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 378 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'.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@philippotto do you have any idea why this fails and how to fix it? no matter if use the import form command_palette.d.ts or whether I redefine the type in the module, this error occurs. Furthermore, it only occurs in the pipeline, not locally when running yarn typecheck.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

image

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
Loading