Skip to content

Commit

Permalink
feat: allow async functions as args transform parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
lmestel committed Feb 27, 2024
1 parent 67931a5 commit ce201f4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
19 changes: 12 additions & 7 deletions src/components/SchemaEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useMemo } from "react";
import React, { useEffect, useRef, useState } from "react";
import type { IRange, editor } from "monaco-editor";
import type { Args } from "@storybook/types";
import Editor, { useMonaco, OnMount, OnValidate } from "@monaco-editor/react";
Expand All @@ -12,8 +12,8 @@ type SchemaEditorProps = {
schema: JsonSchema;
setValidationResults: (marker: editor.IMarker[]) => void;
selectedValidationRange?: IRange;
fromArgs?: (args: Args) => Record<string, any>;
toArgs?: (obj: Record<string, any>) => Args;
fromArgs?: (args: Args) => Record<string, any> | Promise<Record<string, any>>;
toArgs?: (obj: Record<string, any>) => Args | Promise<Args>;
};

const editorPreamble = `
Expand All @@ -32,16 +32,15 @@ export const SchemaEditor: React.FC<SchemaEditorProps> = ({
const editorRef = useRef<editor.IStandaloneCodeEditor>(null);
const monaco = useMonaco();
const [storybookArgs = {}, updateArgs] = useArgs();

const initialContent = useMemo(() => fromArgs(storybookArgs), [schema]);
const [initialContent, setInitialContent] = useState<Record<string, any>>({});

const handleEditorDidMount: OnMount = (editor, monaco) => {
editorRef.current = editor;
};

const handleChange = (value: string) => {
const handleChange = async (value: string) => {
try {
updateArgs(toArgs(JSON.parse(decomment(value))));
updateArgs(await toArgs(JSON.parse(decomment(value))));
} catch (e) {}
};

Expand All @@ -52,6 +51,12 @@ export const SchemaEditor: React.FC<SchemaEditorProps> = ({
}
};

useEffect(() => {
const update = async (args: Args) =>
setInitialContent(await fromArgs(args));
update(storybookArgs).catch(console.error);
}, [schema]);

useEffect(() => {
monaco?.languages.json.jsonDefaults.setDiagnosticsOptions({
validate: true,
Expand Down
11 changes: 9 additions & 2 deletions stories/header/Header.stories.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
pack,
unpack,
unpackDecorator,
getArgsShared,
} from "@kickstartds/core/lib/storybook";
Expand All @@ -16,7 +15,15 @@ export default {
argTypes,
parameters: {
layout: "fullscreen",
jsonschema: { schema, toArgs: pack, fromArgs: unpack },
jsonschema: {
schema,
async toArgs(obj) {
return (await import("@kickstartds/core/lib/storybook")).pack(obj);
},
async fromArgs(args) {
return (await import("@kickstartds/core/lib/storybook")).unpack(args);
},
},
},
decorators: [unpackDecorator],
};
Expand Down

0 comments on commit ce201f4

Please sign in to comment.