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

Settings API #35

Merged
merged 7 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
35 changes: 33 additions & 2 deletions packages/suite-base/src/PanelAPI/useConfigById.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,25 @@
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/

import * as _ from "lodash-es";
import { useCallback } from "react";
import { DeepPartial } from "ts-essentials";

import { useMessagePipeline } from "@lichtblick/suite-base/components/MessagePipeline";
import {
LayoutState,
useCurrentLayoutActions,
useCurrentLayoutSelector,
} from "@lichtblick/suite-base/context/CurrentLayoutContext";
import {
getExtensionPanelSettings,
useExtensionCatalog,
} from "@lichtblick/suite-base/context/ExtensionCatalogContext";
import { SaveConfig } from "@lichtblick/suite-base/types/panels";
import { maybeCast } from "@lichtblick/suite-base/util/maybeCast";

import { getPanelTypeFromId } from "../util/layout";

/**
* Like `useConfig`, but for a specific panel id. This generally shouldn't be used by panels
* directly, but is for use in internal code that's running outside of regular context providers.
Expand All @@ -24,15 +32,38 @@ export default function useConfigById<Config extends Record<string, unknown>>(
panelId: string | undefined,
): [Config | undefined, SaveConfig<Config>] {
const { getCurrentLayoutState, savePanelConfigs } = useCurrentLayoutActions();
const extensionSettings = useExtensionCatalog(getExtensionPanelSettings);
const sortedTopics = useMessagePipeline((state) => state.sortedTopics);

const configSelector = useCallback(
(state: DeepPartial<LayoutState>) => {
if (panelId == undefined) {
return undefined;
}
return maybeCast<Config>(state.selectedLayout?.data?.configById?.[panelId]);
const stateConfig = maybeCast<Config>(state.selectedLayout?.data?.configById?.[panelId]);
const panelType = getPanelTypeFromId(panelId);
const customSettingsByTopic: Record<string, unknown> = _.merge(
{},
...sortedTopics.map(({ name: topic, schemaName }) => {
if (schemaName == undefined) {
return {};
}
const defaultConfig = extensionSettings[panelType]?.[schemaName]?.defaultConfig;
if (defaultConfig == undefined) {
return {};
}
return {
[topic]: defaultConfig,
};
}),
stateConfig?.topics,
);
if (Object.keys(customSettingsByTopic).length === 0) {
return stateConfig;
}
return maybeCast<Config>({ ...stateConfig, topics: customSettingsByTopic });
},
[panelId],
[panelId, extensionSettings, sortedTopics],
);

const config = useCurrentLayoutSelector(configSelector);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// SPDX-FileCopyrightText: Copyright (C) 2023-2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)<[email protected]>
// SPDX-License-Identifier: MPL-2.0

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/

import { getTopicToSchemaNameMap } from "@lichtblick/suite-base/components/MessagePipeline/selectors";
import { MessagePipelineContext } from "@lichtblick/suite-base/components/MessagePipeline/types";
import { PlayerPresence } from "@lichtblick/suite-base/players/types";

it("map schema names by topic name", () => {
const state: MessagePipelineContext = {
sortedTopics: [
{ name: "topic1", schemaName: "schema1" },
{ name: "topic2", schemaName: "schema2" },
],
playerState: {
presence: PlayerPresence.PRESENT,
progress: {},
capabilities: [],
profile: undefined,
playerId: "",
},
callService: jest.fn(),
datatypes: new Map(),
fetchAsset: jest.fn(),
messageEventsBySubscriberId: new Map(),
pauseFrame: jest.fn(),
publish: jest.fn(),
seekPlayback: jest.fn(),
setParameter: jest.fn(),
setPublishers: jest.fn(),
setSubscriptions: jest.fn(),
subscriptions: [],
getMetadata: jest.fn(),
};
const result = getTopicToSchemaNameMap(state);
expect(result).toEqual({
topic1: "schema1",
topic2: "schema2",
});
});
15 changes: 15 additions & 0 deletions packages/suite-base/src/components/MessagePipeline/selectors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// SPDX-FileCopyrightText: Copyright (C) 2023-2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)<[email protected]>
// SPDX-License-Identifier: MPL-2.0

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/

import * as _ from "lodash-es";

import { MessagePipelineContext } from "@lichtblick/suite-base/components/MessagePipeline/types";

export const getTopicToSchemaNameMap = (
state: MessagePipelineContext,
): Record<string, string | undefined> =>
_.mapValues(_.keyBy(state.sortedTopics, "name"), ({ schemaName }) => schemaName);
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import { fromSec, toSec } from "@foxglove/rostime";
import { useTheme } from "@mui/material";
import { produce } from "immer";
import { CSSProperties, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useLatest } from "react-use";
import { v4 as uuid } from "uuid";
Expand All @@ -20,6 +21,7 @@ import {
ParameterValue,
RenderState,
SettingsTree,
SettingsTreeAction,
Subscription,
Time,
VariableValue,
Expand All @@ -34,6 +36,7 @@ import PanelToolbar from "@lichtblick/suite-base/components/PanelToolbar";
import { useAppConfiguration } from "@lichtblick/suite-base/context/AppConfigurationContext";
import {
ExtensionCatalog,
getExtensionPanelSettings,
useExtensionCatalog,
} from "@lichtblick/suite-base/context/ExtensionCatalogContext";
import {
Expand All @@ -54,9 +57,10 @@ import {
} from "@lichtblick/suite-base/providers/PanelStateContextProvider";
import { PanelConfig, SaveConfig } from "@lichtblick/suite-base/types/panels";
import { assertNever } from "@lichtblick/suite-base/util/assertNever";
import { maybeCast } from "@lichtblick/suite-base/util/maybeCast";

import { PanelConfigVersionError } from "./PanelConfigVersionError";
import { initRenderStateBuilder } from "./renderState";
import { RenderStateConfig, initRenderStateBuilder } from "./renderState";
import { BuiltinPanelExtensionContext } from "./types";
import { useSharedPanelState } from "./useSharedPanelState";

Expand Down Expand Up @@ -115,7 +119,7 @@ function PanelExtensionAdapter(
//
// We store the config in a ref to avoid re-initializing the panel when the react config
// changes.
const initialState = useLatest(config);
const initialState = useLatest(maybeCast<RenderStateConfig>(config));

const messagePipelineContext = useMessagePipeline(selectContext);

Expand All @@ -124,7 +128,7 @@ function PanelExtensionAdapter(

const { capabilities, profile: dataSourceProfile, presence: playerPresence } = playerState;

const { openSiblingPanel, setMessagePathDropConfig } = usePanelContext();
const { openSiblingPanel, setMessagePathDropConfig, type: panelName } = usePanelContext();

const [panelId] = useState(() => uuid());
const isMounted = useSynchronousMountedState();
Expand Down Expand Up @@ -240,6 +244,7 @@ function PanelExtensionAdapter(
sortedTopics,
subscriptions: localSubscriptions,
watchedFields,
config: initialState.current,
});

if (!renderState) {
Expand Down Expand Up @@ -288,10 +293,13 @@ function PanelExtensionAdapter(
sharedPanelState,
sortedTopics,
watchedFields,
initialState,
]);

const updatePanelSettingsTree = usePanelSettingsTreeUpdate();

const extensionsSettings = useExtensionCatalog(getExtensionPanelSettings);

type PartialPanelExtensionContext = Omit<BuiltinPanelExtensionContext, "panelElement">;

const partialExtensionContext = useMemo<PartialPanelExtensionContext>(() => {
Expand All @@ -314,6 +322,21 @@ function PanelExtensionAdapter(
},
};

const extensionSettingsActionHandler = (action: SettingsTreeAction) => {
const {
payload: { path },
} = action;

saveConfig(
produce<{ topics: Record<string, unknown> }>((draft) => {
const [category, topicName] = path;
if (category === "topics" && topicName != undefined) {
extensionsSettings[panelName]?.[topicName]?.handler(action, draft.topics[topicName]);
}
}),
);
};

return {
initialState: initialState.current,

Expand Down Expand Up @@ -505,7 +528,11 @@ function PanelExtensionAdapter(
if (!isMounted()) {
return;
}
updatePanelSettingsTree(settings);
const actionHandler: typeof settings.actionHandler = (action) => {
settings.actionHandler(action);
extensionSettingsActionHandler(action);
};
updatePanelSettingsTree({ ...settings, actionHandler });
},

setDefaultPanelTitle: (title: string) => {
Expand All @@ -522,22 +549,24 @@ function PanelExtensionAdapter(
// Disable this rule because the metadata function. If used, it will break.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
capabilities,
clearHoverValue,
dataSourceProfile,
getMessagePipelineContext,
initialState,
seekPlayback,
dataSourceProfile,
setSharedPanelState,
capabilities,
isMounted,
openSiblingPanel,
panelId,
saveConfig,
seekPlayback,
setDefaultPanelTitle,
extensionsSettings,
panelName,
getMessagePipelineContext,
setGlobalVariables,
clearHoverValue,
setHoverValue,
setSharedPanelState,
setSubscriptions,
panelId,
updatePanelSettingsTree,
setDefaultPanelTitle,
setMessagePathDropConfig,
]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export function convertMessage(
message: convertedMessage,
originalMessageEvent: messageEvent,
sizeInBytes: messageEvent.sizeInBytes,
topicConfig: messageEvent.topicConfig,
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import { produce } from "immer";

import { PanelSettings } from "@lichtblick/suite";
import { PlayerPresence } from "@lichtblick/suite-base/players/types";

import { BuilderRenderStateInput, initRenderStateBuilder } from "./renderState";
Expand Down Expand Up @@ -1067,4 +1068,61 @@ describe("renderState", () => {
expect(state).toEqual(undefined);
}
});

it("should add extension settings to converter method", async () => {
const generatePanelSettings = <T>(obj: PanelSettings<T>) => obj as PanelSettings<unknown>;
const checkRenderedConfig = jest.fn();
const buildRenderState = initRenderStateBuilder();
buildRenderState({
appSettings: undefined,
playerState: undefined,
currentFrame: [
{
schemaName: "from.Schema",
topic: "myTopic",
receiveTime: { sec: 0, nsec: 0 },
message: {},
sizeInBytes: 0,
},
],
colorScheme: undefined,
globalVariables: {},
hoverValue: undefined,
sharedPanelState: undefined,
sortedTopics: [{ name: "myTopic", schemaName: "from.Schema" }],
subscriptions: [{ topic: "myTopic", convertTo: "to.Schema", preload: true }],
watchedFields: new Set(["topics", "currentFrame"]),
messageConverters: [
{
fromSchemaName: "from.Schema",
toSchemaName: "to.Schema",
converter: (msg, event) => {
checkRenderedConfig(event.topicConfig);
return msg;
},
panelSettings: {
Dummy: generatePanelSettings({
settings: (config) => ({
fields: {
test: {
input: "boolean",
value: config?.test,
label: "Nope",
},
},
}),
handler: () => {},
defaultConfig: {
test: true,
},
}),
},
},
],
config: { topics: { myTopic: { test: false } } },
});

expect(checkRenderedConfig).toHaveBeenCalled();
expect(checkRenderedConfig.mock.calls.at(-1)).toEqual([{ test: false }]);
});
});
Loading
Loading