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

feat: Save PVM selection #262

Merged
merged 8 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from 7 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
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"react-redux": "^9.1.2",
"react-router": "^7.0.2",
"react-toastify": "^10.0.6",
"redux-persist": "^6.0.0",
"tailwind-merge": "^2.4.0",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.1",
Expand Down
111 changes: 56 additions & 55 deletions src/components/PvmSelect/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,14 @@ import { useDebuggerActions } from "@/hooks/useDebuggerActions";
import classNames from "classnames";
import { ErrorWarningTooltip } from "../ErrorWarningTooltip";
import { isSerializedError } from "@/store/utils";

const PVMS_TO_LOAD_ON_START = [
{
value: AvailablePvms.POLKAVM,
url: "https://todr.me/polkavm/pvm-metadata.json",
lang: SupportedLangs.Rust,
},
{
value: AvailablePvms.ANANAS,
url: "https://todr.me/anan-as/pvm-metadata.json",
lang: SupportedLangs.AssemblyScript,
},
];
import { useAppDispatch, useAppSelector } from "@/store/hooks.ts";
import {
selectAllAvailablePvms,
selectSelectedPvms,
setPvmOptions,
setSelectedPvms,
} from "@/store/debugger/debuggerSlice.ts";
import { SerializedFile, serializeFile } from "@/lib/utils.ts";

interface WasmMetadata {
name: string;
Expand All @@ -40,12 +35,14 @@ interface WasmMetadata {

export interface SelectedPvmWithPayload {
id: string;
type: string;
type: PvmTypes | AvailablePvms;
label: string;
params?: {
file?: Blob;
file?: SerializedFile;
lang?: SupportedLangs;
url?: string;
};
removable?: boolean;
}

const fetchWasmMetadata = async (url: string): Promise<WasmMetadata | undefined> => {
Expand All @@ -71,16 +68,10 @@ export const PvmSelect = () => {
const { handlePvmTypeChange } = useDebuggerActions();
const [error, setError] = useState<string>();
const [isFileDialogOpen, setIsFileDialogOpen] = useState(false);
const [selectedPvms, setSelectedPvms] = useState<string[]>([AvailablePvms.TYPEBERRY]);
const [pvmsWithPayload, setPvmsWithPayload] = useState<SelectedPvmWithPayload[]>([
{
id: "typeberry",
type: "built-in",
},
]);
const [multiSelectOptions, setMultiSelectOptions] = useState<{ value: string; label: string }[]>([
{ value: AvailablePvms.TYPEBERRY, label: `@typeberry/pvm v${import.meta.env.TYPEBERRY_PVM_VERSION}` },
]);

const selectedPvms = useAppSelector(selectSelectedPvms);
const pvmsWithPayload = useAppSelector(selectAllAvailablePvms);
const dispatch = useAppDispatch();
const [selectedLang, setSelectedLang] = useState<SupportedLangs>(SupportedLangs.Rust);

const mapValuesToPvmWithPayload = useCallback(
Expand All @@ -100,7 +91,7 @@ export const PvmSelect = () => {
: name;
};

const handlePvmFileUpload = (file: File) => {
const handlePvmFileUpload = async (file: File) => {
const id = generatePvmId(file.name);

const newValues = [
Expand All @@ -110,13 +101,15 @@ export const PvmSelect = () => {
type: PvmTypes.WASM_FILE,
params: {
lang: selectedLang,
file,
file: await serializeFile(file),
},
label: `${id} - last modified: ${new Date(file.lastModified).toUTCString()}`,
removable: true,
},
];
setPvmsWithPayload(newValues);
setMultiSelectOptions((prevState) => [...prevState, { value: id, label: id }]);
setSelectedPvms([...selectedPvms, id]);

dispatch(setPvmOptions(newValues));
dispatch(setSelectedPvms([...selectedPvms, id]));
};

const handlePvmFileOption = () => {
Expand Down Expand Up @@ -145,39 +138,44 @@ export const PvmSelect = () => {
params: {
url: path.join(url, "../", wasmMetadata.wasmBlobUrl),
},
label: `${id} v${wasmMetadata.version}` as string,
removable: true,
},
];
setPvmsWithPayload(newValues);
setMultiSelectOptions((prevState) => [...prevState, { value: id, label: `${id} v${wasmMetadata.version}` }]);
setSelectedPvms([...selectedPvms, id]);
dispatch(setPvmOptions(newValues));
dispatch(setSelectedPvms([...selectedPvms, id]));
} else {
alert("No URL provided");
}
};

useEffect(() => {
PVMS_TO_LOAD_ON_START.forEach(({ url, value, lang }) => {
fetchWasmMetadata(url).then((metadata) => {
if (!metadata) {
throw new Error("Invalid metadata");
Promise.all(
pvmsWithPayload.map(async (pvm) => {
if (pvm.type === PvmTypes.WASM_URL) {
if (pvm.params?.url) {
const metadata = await fetchWasmMetadata(pvm.params.url);
if (!metadata) {
throw new Error("Invalid metadata");
}
return {
id: pvm.id,
type: PvmTypes.WASM_URL,
params: {
...pvmsWithPayload.find((p) => p.id === pvm.id)?.params,
url: path.join(pvm.params.url, "../", metadata.wasmBlobUrl).replace("https:/", "https://"), // TODO: check why the http protocol path is getting messed up
},
label: `${metadata.name} v${metadata.version}` as string,
};
}
}
setMultiSelectOptions((prevState) => [
...prevState,
{ value, label: `${metadata.name} v${metadata.version}` as string },
]);
setPvmsWithPayload((prevState) => [
...prevState,
{
id: value,
type: PvmTypes.WASM_URL,
params: {
url: path.join(url, "../", metadata.wasmBlobUrl),
lang,
},
},
]);
});
return pvm;
}),
).then((values) => {
dispatch(setPvmOptions(values));
});

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

useEffect(() => {
Expand All @@ -203,11 +201,14 @@ export const PvmSelect = () => {
maxCount={1}
required
className={classNames({ "border-red-500": !!error })}
options={multiSelectOptions}
options={pvmsWithPayload.map((pvm) => ({ value: pvm.id, label: pvm.label, removable: pvm.removable }))}
selectedValues={selectedPvms}
defaultValue={[AvailablePvms.TYPEBERRY]}
onValueChange={async (values) => {
setSelectedPvms(values);
dispatch(setSelectedPvms(values));
}}
removeOption={(value) => {
dispatch(setPvmOptions(pvmsWithPayload.filter((pvm) => pvm.id !== value)));
}}
>
<span className="cursor-pointer" onClick={handlePvmUrlOption}>
Expand Down
20 changes: 19 additions & 1 deletion src/components/ui/multi-select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ interface MultiSelectProps
value: string;
/** Optional icon component to display alongside the option. */
icon?: React.ComponentType<{ className?: string }>;
/** Optional removable flag. */
removable?: boolean;
}[];

/**
Expand Down Expand Up @@ -133,6 +135,11 @@ interface MultiSelectProps
* (Custom)
*/
children?: React.ReactNode;

/**
* (Custom)
*/
removeOption?: (value: string) => void;
}

export const MultiSelect = React.forwardRef<HTMLButtonElement, MultiSelectProps>(
Expand All @@ -155,6 +162,7 @@ export const MultiSelect = React.forwardRef<HTMLButtonElement, MultiSelectProps>
showOptionsAsTags,
required,
children,
removeOption,
...props
},
ref,
Expand Down Expand Up @@ -332,7 +340,17 @@ export const MultiSelect = React.forwardRef<HTMLButtonElement, MultiSelectProps>
<CheckIcon className="h-4 w-4" />
</div>
{option.icon && <option.icon className="mr-2 h-4 w-4 text-muted-foreground" />}
<span>{option.label}</span>
<span className="flex-1">{option.label}</span>
{option.removable && (
<XCircle
className="ml-2 h-4 w-4 cursor-pointer"
onClick={(event) => {
event.stopPropagation();
toggleOption(option.value);
removeOption?.(option.value);
}}
/>
)}
</CommandItem>
);
})}
Expand Down
39 changes: 39 additions & 0 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,42 @@ export const hexToRgb = (hex: string) => {
const b = bigint & 255;
return `${r}, ${g}, ${b}`;
};

export interface SerializedFile {
name: string;
size: number;
type: string;
content: string;
}

export const serializeFile = async (file: File) => {
const encodeFileToBase64 = (file: File) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
reader.readAsDataURL(file); // Encodes the file content as Base64
});
};

const base64 = await encodeFileToBase64(file);
return {
name: file.name,
size: file.size,
type: file.type,
content: base64,
};
};

export const deserializeFile = (fileData: SerializedFile) => {
const byteString = atob(fileData.content.split(",")[1]);
const mimeType = fileData.type;
const arrayBuffer = new ArrayBuffer(byteString.length);
const uint8Array = new Uint8Array(arrayBuffer);

for (let i = 0; i < byteString.length; i++) {
uint8Array[i] = byteString.charCodeAt(i);
}

return new File([uint8Array], fileData.name, { type: mimeType });
};
15 changes: 9 additions & 6 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,21 @@ import "./index.css";
import "./globals.css";
import { NumeralSystemProvider } from "@/context/NumeralSystemProvider";
import { Provider } from "react-redux";
import { store } from "./store";
import { persistor, store } from "./store";
import { HashRouter } from "react-router";
import { PersistGate } from "redux-persist/integration/react";

ReactDOM.createRoot(document.getElementById("root")!).render(
// TODO: strict mode is disabled because of the App useEffect for init being called twice
// <React.StrictMode>
<Provider store={store}>
<NumeralSystemProvider>
<HashRouter>
<App />
</HashRouter>
</NumeralSystemProvider>
<PersistGate loading={null} persistor={persistor}>
<NumeralSystemProvider>
<HashRouter>
<App />
</HashRouter>
</NumeralSystemProvider>
</PersistGate>
</Provider>,
// </React.StrictMode>,
);
8 changes: 5 additions & 3 deletions src/packages/web-worker/command-handlers/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { logger } from "@/utils/loggerService";
import { getMemorySize, loadArrayBufferAsWasm, SupportedLangs } from "../utils";
import { CommandStatus, PvmApiInterface, PvmTypes } from "../types";
import { Pvm as InternalPvmInstance } from "@typeberry/pvm-debugger-adapter";
import { deserializeFile, SerializedFile } from "@/lib/utils.ts";

export type LoadParams = { type: PvmTypes; params: { url?: string; file?: Blob; lang?: SupportedLangs } };
export type LoadParams = { type: PvmTypes; params: { url?: string; file?: SerializedFile; lang?: SupportedLangs } };
export type LoadResponse = {
pvm: PvmApiInterface | null;
memorySize: number | null;
Expand All @@ -15,11 +16,12 @@ const load = async (args: LoadParams): Promise<PvmApiInterface | null> => {
if (args.type === PvmTypes.BUILT_IN) {
return new InternalPvmInstance();
} else if (args.type === PvmTypes.WASM_FILE) {
const file = args.params.file;
if (!file) {
if (!args.params.file) {
throw new Error("No PVM file");
}

const file = deserializeFile(args.params.file);

logger.info("Load WASM from file", file);
const bytes = await file.arrayBuffer();
return await loadArrayBufferAsWasm(bytes, args.params.lang);
Expand Down
3 changes: 2 additions & 1 deletion src/packages/web-worker/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { SupportedLangs } from "./utils";
import { WasmPvmShellInterface } from "./wasmBindgenShell";
import { Pvm as InternalPvm } from "@/types/pvm";
import { bytes } from "@typeberry/jam-host-calls";
import { SerializedFile } from "@/lib/utils.ts";

type CommonWorkerResponseParams = { status: CommandStatus; error?: unknown; messageId: string };

Expand Down Expand Up @@ -48,7 +49,7 @@ type CommonWorkerRequestParams = { messageId: string };
export type CommandWorkerRequestParams =
| {
command: Commands.LOAD;
payload: { type: PvmTypes; params: { url?: string; file?: Blob; lang?: SupportedLangs } };
payload: { type: PvmTypes; params: { url?: string; file?: SerializedFile; lang?: SupportedLangs } };
}
| { command: Commands.INIT; payload: { program: Uint8Array; initialState: InitialState } }
| { command: Commands.STEP; payload: { program: Uint8Array; stepsToPerform: number } }
Expand Down
Loading
Loading