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

Stricter Parameter Meta Parsing #154

Merged
merged 2 commits into from
Jun 24, 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
20 changes: 9 additions & 11 deletions src/actions/instances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,18 +304,16 @@ export const clearParameterMidiMappingOnRemote = (id: InstanceStateRecord["id"],
const param = instance.parameters.get(paramId);
if (!param) return;

const meta = param.getParsedMeta();
if (typeof meta === "object" && !Array.isArray(meta)) {
delete meta.midi;
const message = {
address: `${param.path}/meta`,
args: [
{ type: "s", value: JSON.stringify(meta) }
]
};
const meta = param.getParsedMetaObject();
delete meta.midi;
const message = {
address: `${param.path}/meta`,
args: [
{ type: "s", value: JSON.stringify(meta) }
]
};

oscQueryBridge.sendPacket(writePacket(message));
}
oscQueryBridge.sendPacket(writePacket(message));
};

export const setInstanceMessagePortMetaOnRemote = (_instance: InstanceStateRecord, port: MessagePortRecord, value: string): AppThunk =>
Expand Down
3 changes: 3 additions & 0 deletions src/components/meta/metaEditorModal.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.textArea {
font-family: var(--mantine-font-family-monospace);
}
44 changes: 21 additions & 23 deletions src/components/meta/metaEditorModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import { useIsMobileDevice } from "../../hooks/useIsMobileDevice";
import { faCode, faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { modals } from "@mantine/modals";
import { AnyJson } from "../../lib/types";
import { JsonMap } from "../../lib/types";
import { MetadataScope } from "../../lib/constants";
import { parseParamMetaJSONString } from "../../lib/util";
import classes from "./metaEditorModal.module.css";

export type MetaEditorModalProps = {
name: string;
Expand Down Expand Up @@ -125,24 +127,23 @@ export const MetaEditorModal: FC<MetaEditorModalProps> = memo(function WrappedPa
onConfirm: () => {
setValue(meta);
setHasChanges(false);

try {
if (meta) {
JSON.parse(meta); // ensure valid
}
if (meta) parseParamMetaJSONString(meta); // ensure valid
setError(undefined);
} catch (err) {
setError(new Error("Invalid JSON."));
} catch (err: unknown) {
setError(err instanceof Error ? err : new Error("Invalid JSON format."));
}
}
});
} else {
setValue(meta);
setHasChanges(false);
try {
JSON.parse(meta); // ensure valid
parseParamMetaJSONString(meta); // ensure valid
setError(undefined);
} catch (err) {
setError(new Error("Invalid JSON."));
} catch (err: unknown) {
setError(err instanceof Error ? err : new Error("Invalid JSON format."));
}
}
}, [setValue, hasChanges, setHasChanges, meta, setError]);
Expand All @@ -151,12 +152,10 @@ export const MetaEditorModal: FC<MetaEditorModalProps> = memo(function WrappedPa
if (error) {
try {
const v = e.currentTarget.value;
if (v) {
JSON.parse(v); // ensure valid
}
if (v) parseParamMetaJSONString(v); // ensure valid
setError(undefined);
} catch (err) {
setError(new Error("Invalid JSON."));
} catch (err: unknown) {
setError(err instanceof Error ? err : new Error("Invalid JSON format."));
}
}
setValue(e.currentTarget.value);
Expand All @@ -166,25 +165,23 @@ export const MetaEditorModal: FC<MetaEditorModalProps> = memo(function WrappedPa
const onInputBlur = useCallback(() => {
try {
if (value) {
const j: AnyJson = JSON.parse(value); // ensure valid
const j: JsonMap = parseParamMetaJSONString(value); // ensure valid
setValue(JSON.stringify(j, null, 2));
}
setError(undefined);
} catch (err) {
setError(new Error("Invalid JSON."));
} catch (err: unknown) {
setError(err instanceof Error ? err : new Error("Invalid JSON format."));
}
}, [value, setError, setValue]);

const onSaveValue = useCallback((e: FormEvent) => {
e.preventDefault();
try {
if (value) {
JSON.parse(value); // ensure valid
}
if (value) parseParamMetaJSONString(value); // ensure valid
setHasChanges(false);
onSaveMeta(value);
} catch (err) {
setError(new Error("Invalid JSON."));
} catch (err: unknown) {
setError(err instanceof Error ? err : new Error("Invalid JSON format."));
}
}, [setError, setHasChanges, onSaveMeta, value]);

Expand Down Expand Up @@ -238,13 +235,14 @@ export const MetaEditorModal: FC<MetaEditorModalProps> = memo(function WrappedPa
<Stack gap="md">
<Textarea
label="Metadata"
description="Metadata in JSON format"
description="Metadata in JSON object format"
autosize
minRows={ 10 }
onChange={ onInputChange }
value={ value }
error={ error?.message }
onBlur={ onInputBlur }
classNames={{ input: classes.textArea }}
/>
<Group justify="flex-end">
<Button.Group>
Expand Down
13 changes: 11 additions & 2 deletions src/components/page/theme.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,20 @@ import { RootStateType } from "../../lib/store";
import { getAppSetting } from "../../selectors/settings";
import { AppSetting } from "../../models/settings";

export const PageTheme: FunctionComponent<PropsWithChildren & { fontFamily: string; } > = ({ children, fontFamily }) => {
export type PageThemeProps = PropsWithChildren & {
fontFamily: string;
fontFamilyMonospace: string;
};

export const PageTheme: FunctionComponent<PageThemeProps> = ({
children,
fontFamily,
fontFamilyMonospace
}) => {

const colorScheme = useAppSelector((state: RootStateType) => getAppSetting(state, AppSetting.colorScheme).value as "light" | "dark");
return (
<MantineProvider theme={{ ...rnboTheme, fontFamily }} forceColorScheme={ colorScheme } >
<MantineProvider theme={{ ...rnboTheme, fontFamily, fontFamilyMonospace }} forceColorScheme={ colorScheme } >
{ children }
</MantineProvider>
);
Expand Down
25 changes: 24 additions & 1 deletion src/lib/util.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { KeyboardEvent } from "react";
import { OSCQueryStringValueRange, OSCQueryValueRange } from "./types";
import { AnyJson, JsonMap, OSCQueryStringValueRange, OSCQueryValueRange } from "./types";

export const sleep = (t: number): Promise<void> => new Promise(resolve => setTimeout(resolve, t));

Expand Down Expand Up @@ -36,3 +36,26 @@ export const formatFileSize = (size: number): string => {
const exp = Math.floor(Math.log(size) / Math.log(1000));
return (size / Math.pow(1000, exp)).toFixed(exp >= 2 ? 2 : 0) + " " + fileSizeUnits[exp];
};

export const parseParamMetaJSONString = (v: string): JsonMap => {
if (!v?.length) return {};

let parsed: AnyJson;
try {
parsed = JSON.parse(v);
} catch (err) {
throw new Error("Invalid JSON syntax.");
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Invalid Meta JSON format. Meta is expected to be a JSON object.");

return parsed;
};

export const validateParamMetaJSONString = (v: string): boolean => {
try {
parseParamMetaJSONString(v);
return true;
} catch (err) {
return false;
}
};
13 changes: 8 additions & 5 deletions src/models/parameter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Record as ImmuRecord } from "immutable";
import { AnyJson, JsonMap, OSCQueryRNBOInstanceParameterInfo, OSCQueryRNBOInstanceParameterValue } from "../lib/types";
import { parseParamMetaJSONString } from "../lib/util";

export type ParameterRecordProps = {
enumVals: Array<string | number>;
Expand Down Expand Up @@ -96,23 +97,25 @@ export class ParameterRecord extends ImmuRecord<ParameterRecordProps>({

// get parsed meta but if it isn't a map, return an empty map
public getParsedMetaObject(): JsonMap {
const meta = this.getParsedMeta();
if (typeof meta !== "object") {
try {
return parseParamMetaJSONString(this.meta); // ensure valid
} catch (err) {
return {};
}
return meta as JsonMap;
}

public setMeta(value: string): ParameterRecord {
// detect midi mapping
let isMidiMapped = false;
let j: JsonMap = {};
try {
// detection simply looks for a 'midi' entry in the meta
const j = JSON.parse(value);
isMidiMapped = typeof j.midi === "object";
j = parseParamMetaJSONString(value);
} catch {
// ignore
}

isMidiMapped = typeof j.midi === "object";
return this.set("meta", value).set("isMidiMapped", isMidiMapped);
}

Expand Down
5 changes: 3 additions & 2 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import Head from "next/head";
import React, { useEffect } from "react";
import { Provider } from "react-redux";

import { Lato as lato } from "next/font/google";
import { Lato as lato, Ubuntu_Mono as ubuntuMono } from "next/font/google";
const latoFont = lato({ subsets: ["latin-ext"], weight: ["300", "400", "700", "900"], style: ["normal", "italic"] });
const ubuntuMonoFont = ubuntuMono({display: "block", subsets: ["latin-ext"], weight: ["400"] });


import { library } from "@fortawesome/fontawesome-svg-core";
Expand Down Expand Up @@ -49,7 +50,7 @@ function App({ Component, pageProps }: AppProps) {
</style>
<Provider store={store}>
<PageSettings>
<PageTheme fontFamily={ latoFont.style.fontFamily } >
<PageTheme fontFamily={ latoFont.style.fontFamily } fontFamilyMonospace={ ubuntuMonoFont.style.fontFamily } >
<ModalsProvider>
<Head>
<title>RNBO</title>
Expand Down
Loading