Compare commits
1 Commits
feat/json-
...
feature/re
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ed97d2873 |
@@ -18,7 +18,7 @@ import {
|
|||||||
DialogTrigger,
|
DialogTrigger,
|
||||||
} from "./Dialog";
|
} from "./Dialog";
|
||||||
import { css } from "../stitches.config";
|
import { css } from "../stitches.config";
|
||||||
import { Input, Label } from "./Input";
|
import { Input } from "./Input";
|
||||||
import truncate from "../utils/truncate";
|
import truncate from "../utils/truncate";
|
||||||
|
|
||||||
const labelStyle = css({
|
const labelStyle = css({
|
||||||
@@ -491,7 +491,7 @@ const ImportAccountDialog = () => {
|
|||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogTitle>Import account</DialogTitle>
|
<DialogTitle>Import account</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
<Label>Add account secret</Label>
|
<label>Add account secret</label>
|
||||||
<Input
|
<Input
|
||||||
name="secret"
|
name="secret"
|
||||||
type="password"
|
type="password"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { blackA } from "@radix-ui/colors";
|
import { blackA } from "@radix-ui/colors";
|
||||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
|
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
|
||||||
import { styled, keyframes } from "../../stitches.config";
|
import { styled, keyframes } from "../stitches.config";
|
||||||
|
|
||||||
const overlayShow = keyframes({
|
const overlayShow = keyframes({
|
||||||
"0%": { opacity: 0 },
|
"0%": { opacity: 0 },
|
||||||
@@ -75,7 +75,7 @@ const StyledDescription = styled(AlertDialogPrimitive.Description, {
|
|||||||
marginBottom: 20,
|
marginBottom: 20,
|
||||||
color: "$mauve11",
|
color: "$mauve11",
|
||||||
lineHeight: 1.5,
|
lineHeight: 1.5,
|
||||||
fontSize: "$md",
|
fontSize: "$sm",
|
||||||
});
|
});
|
||||||
|
|
||||||
// Exports
|
// Exports
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
import { FC, ReactNode } from "react";
|
|
||||||
import { proxy, useSnapshot } from "valtio";
|
|
||||||
import Button from "../Button";
|
|
||||||
import Flex from "../Flex";
|
|
||||||
import {
|
|
||||||
AlertDialog,
|
|
||||||
AlertDialogAction,
|
|
||||||
AlertDialogCancel,
|
|
||||||
AlertDialogContent,
|
|
||||||
AlertDialogDescription,
|
|
||||||
AlertDialogTitle,
|
|
||||||
} from "./primitive";
|
|
||||||
|
|
||||||
export interface AlertState {
|
|
||||||
isOpen: boolean;
|
|
||||||
title?: string;
|
|
||||||
body?: ReactNode;
|
|
||||||
cancelText?: string;
|
|
||||||
confirmText?: string;
|
|
||||||
confirmPrefix?: ReactNode;
|
|
||||||
onConfirm?: () => any;
|
|
||||||
onCancel?: () => any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const alertState = proxy<AlertState>({
|
|
||||||
isOpen: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
const Alert: FC = () => {
|
|
||||||
const {
|
|
||||||
title = "Are you sure?",
|
|
||||||
isOpen,
|
|
||||||
body,
|
|
||||||
cancelText,
|
|
||||||
confirmText = "Ok",
|
|
||||||
confirmPrefix,
|
|
||||||
onCancel,
|
|
||||||
onConfirm,
|
|
||||||
} = useSnapshot(alertState);
|
|
||||||
return (
|
|
||||||
<AlertDialog
|
|
||||||
open={isOpen}
|
|
||||||
onOpenChange={value => (alertState.isOpen = value)}
|
|
||||||
>
|
|
||||||
<AlertDialogContent>
|
|
||||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
|
||||||
<AlertDialogDescription>{body}</AlertDialogDescription>
|
|
||||||
<Flex css={{ justifyContent: "flex-end", gap: "$3" }}>
|
|
||||||
{(cancelText || onCancel) && (
|
|
||||||
<AlertDialogCancel asChild>
|
|
||||||
<Button css={{ minWidth: "$16" }} outline onClick={onCancel}>
|
|
||||||
{cancelText || "Cancel"}
|
|
||||||
</Button>
|
|
||||||
</AlertDialogCancel>
|
|
||||||
)}
|
|
||||||
<AlertDialogAction asChild>
|
|
||||||
<Button
|
|
||||||
css={{ minWidth: "$16" }}
|
|
||||||
variant="primary"
|
|
||||||
onClick={async () => {
|
|
||||||
await onConfirm?.();
|
|
||||||
alertState.isOpen = false;
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{confirmPrefix}
|
|
||||||
{confirmText}
|
|
||||||
</Button>
|
|
||||||
</AlertDialogAction>
|
|
||||||
</Flex>
|
|
||||||
</AlertDialogContent>
|
|
||||||
</AlertDialog>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Alert;
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useCallback, useEffect } from "react";
|
import { useCallback, useEffect } from "react";
|
||||||
import { proxy, ref, useSnapshot } from "valtio";
|
import { proxy, ref, useSnapshot } from "valtio";
|
||||||
import { Select } from ".";
|
import { Select } from ".";
|
||||||
import state, { ILog, transactionsState } from "../state";
|
import state, { ILog } from "../state";
|
||||||
import { extractJSON } from "../utils/json";
|
import { extractJSON } from "../utils/json";
|
||||||
import LogBox from "./LogBox";
|
import LogBox from "./LogBox";
|
||||||
|
|
||||||
@@ -10,26 +10,17 @@ interface ISelect<T = string> {
|
|||||||
value: T;
|
value: T;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IStreamState {
|
const streamState = proxy({
|
||||||
selectedAccount: ISelect | null;
|
|
||||||
status: "idle" | "opened" | "closed";
|
|
||||||
statusChangeTimestamp?: number;
|
|
||||||
logs: ILog[];
|
|
||||||
socket?: WebSocket;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const streamState = proxy<IStreamState>({
|
|
||||||
selectedAccount: null as ISelect | null,
|
selectedAccount: null as ISelect | null,
|
||||||
status: "idle",
|
|
||||||
logs: [] as ILog[],
|
logs: [] as ILog[],
|
||||||
|
socket: undefined as WebSocket | undefined,
|
||||||
});
|
});
|
||||||
|
|
||||||
const DebugStream = () => {
|
const DebugStream = () => {
|
||||||
const { selectedAccount, logs, socket } = useSnapshot(streamState);
|
const { selectedAccount, logs, socket } = useSnapshot(streamState);
|
||||||
const { activeHeader: activeTxTab } = useSnapshot(transactionsState);
|
|
||||||
const { accounts } = useSnapshot(state);
|
const { accounts } = useSnapshot(state);
|
||||||
|
|
||||||
const accountOptions = accounts.map(acc => ({
|
const accountOptions = accounts.map((acc) => ({
|
||||||
label: acc.name,
|
label: acc.name,
|
||||||
value: acc.address,
|
value: acc.address,
|
||||||
}));
|
}));
|
||||||
@@ -42,12 +33,39 @@ const DebugStream = () => {
|
|||||||
options={accountOptions}
|
options={accountOptions}
|
||||||
hideSelectedOptions
|
hideSelectedOptions
|
||||||
value={selectedAccount}
|
value={selectedAccount}
|
||||||
onChange={acc => (streamState.selectedAccount = acc as any)}
|
onChange={(acc) => (streamState.selectedAccount = acc as any)}
|
||||||
css={{ width: "100%" }}
|
css={{ width: "100%" }}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const prepareLog = useCallback((str: any): ILog => {
|
||||||
|
if (typeof str !== "string") throw Error("Unrecognized debug log stream!");
|
||||||
|
|
||||||
|
const match = str.match(/([\s\S]+(?:UTC|ISO|GMT[+|-]\d+))\ ?([\s\S]*)/m);
|
||||||
|
const [_, tm, msg] = match || [];
|
||||||
|
|
||||||
|
const extracted = extractJSON(msg);
|
||||||
|
const timestamp = isNaN(Date.parse(tm || ""))
|
||||||
|
? tm
|
||||||
|
: new Date(tm).toLocaleTimeString();
|
||||||
|
|
||||||
|
const message = !extracted
|
||||||
|
? msg
|
||||||
|
: msg.slice(0, extracted.start) + msg.slice(extracted.end + 1);
|
||||||
|
|
||||||
|
const jsonData = extracted
|
||||||
|
? JSON.stringify(extracted.result, null, 2)
|
||||||
|
: undefined;
|
||||||
|
return {
|
||||||
|
type: "log",
|
||||||
|
message,
|
||||||
|
timestamp,
|
||||||
|
jsonData,
|
||||||
|
defaultCollapsed: true,
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const account = selectedAccount?.value;
|
const account = selectedAccount?.value;
|
||||||
if (account && (!socket || !socket.url.endsWith(account))) {
|
if (account && (!socket || !socket.url.endsWith(account))) {
|
||||||
@@ -63,50 +81,6 @@ const DebugStream = () => {
|
|||||||
}
|
}
|
||||||
}, [selectedAccount?.value, socket]);
|
}, [selectedAccount?.value, socket]);
|
||||||
|
|
||||||
const onMount = useCallback(async () => {
|
|
||||||
// deliberately using `proxy` values and not the `useSnapshot` ones to have no dep list
|
|
||||||
const acc = streamState.selectedAccount;
|
|
||||||
const status = streamState.status;
|
|
||||||
|
|
||||||
if (status === "opened" && acc) {
|
|
||||||
// fetch the missing ones
|
|
||||||
try {
|
|
||||||
const url = `https://${process.env.NEXT_PUBLIC_DEBUG_STREAM_URL}/recent/${acc?.value}`;
|
|
||||||
|
|
||||||
// TODO Remove after api sets cors properly
|
|
||||||
const res = await fetch("/api/proxy", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ url }),
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!res.ok) return;
|
|
||||||
|
|
||||||
const body = await res.json();
|
|
||||||
|
|
||||||
if (!body?.logs) return;
|
|
||||||
|
|
||||||
const start = streamState.statusChangeTimestamp || 0;
|
|
||||||
streamState.logs = [];
|
|
||||||
pushLog(`Debug stream opened for account ${acc.value}`, {
|
|
||||||
type: "success",
|
|
||||||
});
|
|
||||||
|
|
||||||
const logs = Object.entries(body.logs).filter(([tm]) => +tm >= start);
|
|
||||||
|
|
||||||
logs.forEach(([tm, log]) => pushLog(log));
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
onMount();
|
|
||||||
}, [onMount]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const account = selectedAccount?.value;
|
const account = selectedAccount?.value;
|
||||||
const socket = streamState.socket;
|
const socket = streamState.socket;
|
||||||
@@ -114,27 +88,37 @@ const DebugStream = () => {
|
|||||||
|
|
||||||
const onOpen = () => {
|
const onOpen = () => {
|
||||||
streamState.logs = [];
|
streamState.logs = [];
|
||||||
streamState.status = "opened";
|
streamState.logs.push({
|
||||||
streamState.statusChangeTimestamp = Date.now();
|
|
||||||
pushLog(`Debug stream opened for account ${account}`, {
|
|
||||||
type: "success",
|
type: "success",
|
||||||
|
message: `Debug stream opened for account ${account}`,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
const onError = () => {
|
const onError = () => {
|
||||||
pushLog("Something went wrong! Check your connection and try again.", {
|
streamState.logs.push({
|
||||||
type: "error",
|
type: "error",
|
||||||
|
message: "Something went wrong! Check your connection and try again.",
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
const onClose = (e: CloseEvent) => {
|
const onClose = (e: CloseEvent) => {
|
||||||
pushLog(`Connection was closed. [code: ${e.code}]`, {
|
streamState.logs.push({
|
||||||
type: "error",
|
type: "error",
|
||||||
|
message: `Connection was closed. [code: ${e.code}]`,
|
||||||
});
|
});
|
||||||
streamState.selectedAccount = null;
|
streamState.selectedAccount = null;
|
||||||
streamState.status = "closed";
|
|
||||||
streamState.statusChangeTimestamp = Date.now();
|
|
||||||
};
|
};
|
||||||
const onMessage = (event: any) => {
|
const onMessage = (event: any) => {
|
||||||
pushLog(event.data);
|
if (!event.data) return;
|
||||||
|
const log = prepareLog(event.data);
|
||||||
|
// Filter out account_info and account_objects requests
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(log.jsonData);
|
||||||
|
if (parsed?.id?._Request?.includes("hooks-builder-req")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Lets just skip if we cannot parse the message
|
||||||
|
}
|
||||||
|
return streamState.logs.push(log);
|
||||||
};
|
};
|
||||||
|
|
||||||
socket.addEventListener("open", onOpen);
|
socket.addEventListener("open", onOpen);
|
||||||
@@ -148,70 +132,16 @@ const DebugStream = () => {
|
|||||||
socket.removeEventListener("message", onMessage);
|
socket.removeEventListener("message", onMessage);
|
||||||
socket.removeEventListener("error", onError);
|
socket.removeEventListener("error", onError);
|
||||||
};
|
};
|
||||||
}, [selectedAccount?.value, socket]);
|
}, [prepareLog, selectedAccount?.value, socket]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const account = transactionsState.transactions.find(
|
|
||||||
tx => tx.header === activeTxTab
|
|
||||||
)?.state.selectedAccount;
|
|
||||||
|
|
||||||
if (account && account.value !== streamState.selectedAccount?.value)
|
|
||||||
streamState.selectedAccount = account;
|
|
||||||
}, [activeTxTab]);
|
|
||||||
|
|
||||||
const clearLog = () => {
|
|
||||||
streamState.logs = [];
|
|
||||||
streamState.statusChangeTimestamp = Date.now();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<LogBox
|
<LogBox
|
||||||
enhanced
|
enhanced
|
||||||
renderNav={renderNav}
|
renderNav={renderNav}
|
||||||
title="Debug stream"
|
title="Debug stream"
|
||||||
logs={logs}
|
logs={logs}
|
||||||
clearLog={clearLog}
|
clearLog={() => (streamState.logs = [])}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default DebugStream;
|
export default DebugStream;
|
||||||
|
|
||||||
export const pushLog = (
|
|
||||||
str: any,
|
|
||||||
opts: Partial<Pick<ILog, "type">> = {}
|
|
||||||
): ILog | undefined => {
|
|
||||||
if (!str) return;
|
|
||||||
if (typeof str !== "string") throw Error("Unrecognized debug log stream!");
|
|
||||||
|
|
||||||
const match = str.match(/([\s\S]+(?:UTC|ISO|GMT[+|-]\d+))?\ ?([\s\S]*)/m);
|
|
||||||
const [_, tm, msg] = match || [];
|
|
||||||
|
|
||||||
const timestamp = Date.parse(tm || "") || undefined;
|
|
||||||
const timestring = !timestamp ? tm : new Date(timestamp).toLocaleTimeString();
|
|
||||||
|
|
||||||
const extracted = extractJSON(msg);
|
|
||||||
const message = !extracted
|
|
||||||
? msg
|
|
||||||
: msg.slice(0, extracted.start) + msg.slice(extracted.end + 1);
|
|
||||||
|
|
||||||
const jsonData = extracted
|
|
||||||
? JSON.stringify(extracted.result, null, 2)
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
if (extracted?.result?.id?._Request?.includes("hooks-builder-req")) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { type = "log" } = opts;
|
|
||||||
const log: ILog = {
|
|
||||||
type,
|
|
||||||
message,
|
|
||||||
timestring,
|
|
||||||
jsonData,
|
|
||||||
defaultCollapsed: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (log) streamState.logs.push(log);
|
|
||||||
return log;
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -47,11 +47,18 @@ import {
|
|||||||
} from "./Dialog";
|
} from "./Dialog";
|
||||||
import Flex from "./Flex";
|
import Flex from "./Flex";
|
||||||
import Stack from "./Stack";
|
import Stack from "./Stack";
|
||||||
import { Input, Label } from "./Input";
|
import Input from "./Input";
|
||||||
import Text from "./Text";
|
import Text from "./Text";
|
||||||
import Tooltip from "./Tooltip";
|
import Tooltip from "./Tooltip";
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogAction,
|
||||||
|
} from "./AlertDialog";
|
||||||
import { styled } from "../stitches.config";
|
import { styled } from "../stitches.config";
|
||||||
import { showAlert } from "../state/actions/showAlert";
|
|
||||||
|
|
||||||
const ErrorText = styled(Text, {
|
const ErrorText = styled(Text, {
|
||||||
color: "$error",
|
color: "$error",
|
||||||
@@ -61,6 +68,7 @@ const ErrorText = styled(Text, {
|
|||||||
|
|
||||||
const EditorNavigation = ({ showWat }: { showWat?: boolean }) => {
|
const EditorNavigation = ({ showWat }: { showWat?: boolean }) => {
|
||||||
const snap = useSnapshot(state);
|
const snap = useSnapshot(state);
|
||||||
|
const [createNewAlertOpen, setCreateNewAlertOpen] = useState(false);
|
||||||
const [editorSettingsOpen, setEditorSettingsOpen] = useState(false);
|
const [editorSettingsOpen, setEditorSettingsOpen] = useState(false);
|
||||||
const [isNewfileDialogOpen, setIsNewfileDialogOpen] = useState(false);
|
const [isNewfileDialogOpen, setIsNewfileDialogOpen] = useState(false);
|
||||||
const [newfileError, setNewfileError] = useState<string | null>(null);
|
const [newfileError, setNewfileError] = useState<string | null>(null);
|
||||||
@@ -79,29 +87,13 @@ const EditorNavigation = ({ showWat }: { showWat?: boolean }) => {
|
|||||||
setNewfileError(null);
|
setNewfileError(null);
|
||||||
}, [filename, setNewfileError]);
|
}, [filename, setNewfileError]);
|
||||||
|
|
||||||
const showNewGistAlert = () => {
|
|
||||||
showAlert("Are you sure?", {
|
|
||||||
body: (
|
|
||||||
<>
|
|
||||||
This action will create new <strong>public</strong> Github Gist from
|
|
||||||
your current saved files. You can delete gist anytime from your GitHub
|
|
||||||
Gists page.
|
|
||||||
</>
|
|
||||||
),
|
|
||||||
cancelText: "Cancel",
|
|
||||||
confirmText: "Create new Gist",
|
|
||||||
confirmPrefix: <FilePlus size="15px" />,
|
|
||||||
onConfirm: () => syncToGist(session, true),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const validateFilename = useCallback(
|
const validateFilename = useCallback(
|
||||||
(filename: string): { error: string | null } => {
|
(filename: string): { error: string | null } => {
|
||||||
// check if filename already exists
|
// check if filename already exists
|
||||||
if (!filename) {
|
if (!filename) {
|
||||||
return { error: "You need to add filename" };
|
return { error: "You need to add filename" };
|
||||||
}
|
}
|
||||||
if (snap.files.find(file => file.name === filename)) {
|
if (snap.files.find((file) => file.name === filename)) {
|
||||||
return { error: "Filename already exists." };
|
return { error: "Filename already exists." };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,11 +222,11 @@ const EditorNavigation = ({ showWat }: { showWat?: boolean }) => {
|
|||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogTitle>Create new file</DialogTitle>
|
<DialogTitle>Create new file</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
<Label>Filename</Label>
|
<label>Filename</label>
|
||||||
<Input
|
<Input
|
||||||
value={filename}
|
value={filename}
|
||||||
onChange={e => setFilename(e.target.value)}
|
onChange={(e) => setFilename(e.target.value)}
|
||||||
onKeyPress={e => {
|
onKeyPress={(e) => {
|
||||||
if (e.key === "Enter") {
|
if (e.key === "Enter") {
|
||||||
handleConfirm();
|
handleConfirm();
|
||||||
}
|
}
|
||||||
@@ -424,7 +416,7 @@ const EditorNavigation = ({ showWat }: { showWat?: boolean }) => {
|
|||||||
if (snap.gistOwner === session?.user.username) {
|
if (snap.gistOwner === session?.user.username) {
|
||||||
syncToGist(session);
|
syncToGist(session);
|
||||||
} else {
|
} else {
|
||||||
showNewGistAlert();
|
setCreateNewAlertOpen(true);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -474,7 +466,7 @@ const EditorNavigation = ({ showWat }: { showWat?: boolean }) => {
|
|||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
disabled={status !== "authenticated"}
|
disabled={status !== "authenticated"}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
showNewGistAlert();
|
setCreateNewAlertOpen(true);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<FilePlus size="16px" /> Create as a new Gist
|
<FilePlus size="16px" /> Create as a new Gist
|
||||||
@@ -494,6 +486,34 @@ const EditorNavigation = ({ showWat }: { showWat?: boolean }) => {
|
|||||||
) : null}
|
) : null}
|
||||||
</Container>
|
</Container>
|
||||||
</Flex>
|
</Flex>
|
||||||
|
<AlertDialog
|
||||||
|
open={createNewAlertOpen}
|
||||||
|
onOpenChange={(value) => setCreateNewAlertOpen(value)}
|
||||||
|
>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogTitle>Are you sure?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
This action will create new <strong>public</strong> Github Gist from
|
||||||
|
your current saved files. You can delete gist anytime from your
|
||||||
|
GitHub Gists page.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
<Flex css={{ justifyContent: "flex-end", gap: "$3" }}>
|
||||||
|
<AlertDialogCancel asChild>
|
||||||
|
<Button outline>Cancel</Button>
|
||||||
|
</AlertDialogCancel>
|
||||||
|
<AlertDialogAction asChild>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={() => {
|
||||||
|
syncToGist(session, true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FilePlus size="15px" /> Create new Gist
|
||||||
|
</Button>
|
||||||
|
</AlertDialogAction>
|
||||||
|
</Flex>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
|
||||||
<Dialog open={editorSettingsOpen} onOpenChange={setEditorSettingsOpen}>
|
<Dialog open={editorSettingsOpen} onOpenChange={setEditorSettingsOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
@@ -504,13 +524,13 @@ const EditorNavigation = ({ showWat }: { showWat?: boolean }) => {
|
|||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogTitle>Editor settings</DialogTitle>
|
<DialogTitle>Editor settings</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
<Label>Tab size</Label>
|
<label>Tab size</label>
|
||||||
<Input
|
<Input
|
||||||
type="number"
|
type="number"
|
||||||
min="1"
|
min="1"
|
||||||
value={editorSettings.tabSize}
|
value={editorSettings.tabSize}
|
||||||
onChange={e =>
|
onChange={(e) =>
|
||||||
setEditorSettings(curr => ({
|
setEditorSettings((curr) => ({
|
||||||
...curr,
|
...curr,
|
||||||
tabSize: Number(e.target.value),
|
tabSize: Number(e.target.value),
|
||||||
}))
|
}))
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { styled } from "../stitches.config";
|
import { styled } from "../stitches.config";
|
||||||
import * as LabelPrim from '@radix-ui/react-label';
|
|
||||||
|
|
||||||
export const Input = styled("input", {
|
export const Input = styled("input", {
|
||||||
// Reset
|
// Reset
|
||||||
@@ -159,11 +158,3 @@ const ReffedInput = React.forwardRef<
|
|||||||
>((props, ref) => <Input {...props} ref={ref} />);
|
>((props, ref) => <Input {...props} ref={ref} />);
|
||||||
|
|
||||||
export default ReffedInput;
|
export default ReffedInput;
|
||||||
|
|
||||||
|
|
||||||
const LabelRoot = (props: LabelPrim.LabelProps) => <LabelPrim.Root {...props} />
|
|
||||||
|
|
||||||
export const Label = styled(LabelRoot, {
|
|
||||||
display: 'inline-block',
|
|
||||||
mb: '$1'
|
|
||||||
})
|
|
||||||
@@ -147,7 +147,7 @@ const LogBox: FC<ILogBox> = ({
|
|||||||
|
|
||||||
export const Log: FC<ILog> = ({
|
export const Log: FC<ILog> = ({
|
||||||
type,
|
type,
|
||||||
timestring,
|
timestamp: timestamp,
|
||||||
message: _message,
|
message: _message,
|
||||||
link,
|
link,
|
||||||
linkText,
|
linkText,
|
||||||
@@ -186,17 +186,8 @@ export const Log: FC<ILog> = ({
|
|||||||
},
|
},
|
||||||
[accounts]
|
[accounts]
|
||||||
);
|
);
|
||||||
|
_message = _message.trim().replace(/\n /gi, "\n");
|
||||||
let message: ReactNode;
|
const message = enrichAccounts(_message);
|
||||||
|
|
||||||
if (typeof _message === 'string') {
|
|
||||||
_message = _message.trim().replace(/\n /gi, "\n");
|
|
||||||
message = enrichAccounts(_message)
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
message = _message
|
|
||||||
}
|
|
||||||
|
|
||||||
const jsonData = enrichAccounts(_jsonData);
|
const jsonData = enrichAccounts(_jsonData);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -206,9 +197,9 @@ export const Log: FC<ILog> = ({
|
|||||||
activeAccountAddress={dialogAccount}
|
activeAccountAddress={dialogAccount}
|
||||||
/>
|
/>
|
||||||
<LogText variant={type}>
|
<LogText variant={type}>
|
||||||
{timestring && (
|
{timestamp && (
|
||||||
<Text muted monospace>
|
<Text muted monospace>
|
||||||
{timestring}{" "}
|
{timestamp}{" "}
|
||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
<Pre>{message} </Pre>
|
<Pre>{message} </Pre>
|
||||||
|
|||||||
@@ -52,7 +52,6 @@ const Select = forwardRef<any, Props>((props, ref) => {
|
|||||||
control: (provided, state) => {
|
control: (provided, state) => {
|
||||||
return {
|
return {
|
||||||
...provided,
|
...provided,
|
||||||
minHeight: 0,
|
|
||||||
border: "0px",
|
border: "0px",
|
||||||
backgroundColor: colors.mauve4,
|
backgroundColor: colors.mauve4,
|
||||||
boxShadow: `0 0 0 1px ${
|
boxShadow: `0 0 0 1px ${
|
||||||
@@ -119,6 +118,32 @@ const Select = forwardRef<any, Props>((props, ref) => {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
|
// theme={(theme) => ({
|
||||||
|
// ...theme,
|
||||||
|
// spacing: {
|
||||||
|
// ...theme.spacing,
|
||||||
|
// controlHeight: 30,
|
||||||
|
// },
|
||||||
|
// colors: {
|
||||||
|
// primary: colors.selected,
|
||||||
|
// primary25: colors.active,
|
||||||
|
// primary50: colors.primary,
|
||||||
|
// primary75: colors.primary,
|
||||||
|
// danger: colors.primary,
|
||||||
|
// dangerLight: colors.primary,
|
||||||
|
// neutral0: colors.background,
|
||||||
|
// neutral5: colors.primary,
|
||||||
|
// neutral10: colors.primary,
|
||||||
|
// neutral20: colors.outline,
|
||||||
|
// neutral30: colors.primary,
|
||||||
|
// neutral40: colors.primary,
|
||||||
|
// neutral50: colors.placeholder,
|
||||||
|
// neutral60: colors.primary,
|
||||||
|
// neutral70: colors.primary,
|
||||||
|
// neutral80: colors.searchText,
|
||||||
|
// neutral90: colors.primary,
|
||||||
|
// },
|
||||||
|
// })}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
DialogClose,
|
DialogClose,
|
||||||
DialogTrigger,
|
DialogTrigger,
|
||||||
} from "./Dialog";
|
} from "./Dialog";
|
||||||
import { Input, Label } from "./Input";
|
import { Input } from "./Input";
|
||||||
import {
|
import {
|
||||||
Controller,
|
Controller,
|
||||||
SubmitHandler,
|
SubmitHandler,
|
||||||
@@ -132,7 +132,7 @@ export const SetHookDialog: React.FC<{ account: IAccount }> = ({ account }) => {
|
|||||||
<DialogDescription as="div">
|
<DialogDescription as="div">
|
||||||
<Stack css={{ width: "100%", flex: 1 }}>
|
<Stack css={{ width: "100%", flex: 1 }}>
|
||||||
<Box css={{ width: "100%" }}>
|
<Box css={{ width: "100%" }}>
|
||||||
<Label>Invoke on transactions</Label>
|
<label>Invoke on transactions</label>
|
||||||
<Controller
|
<Controller
|
||||||
name="Invoke"
|
name="Invoke"
|
||||||
control={control}
|
control={control}
|
||||||
@@ -151,7 +151,7 @@ export const SetHookDialog: React.FC<{ account: IAccount }> = ({ account }) => {
|
|||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
<Box css={{ width: "100%" }}>
|
<Box css={{ width: "100%" }}>
|
||||||
<Label>Hook Namespace Seed</Label>
|
<label>Hook Namespace Seed</label>
|
||||||
<Input
|
<Input
|
||||||
{...register("HookNamespace", { required: true })}
|
{...register("HookNamespace", { required: true })}
|
||||||
autoComplete={"off"}
|
autoComplete={"off"}
|
||||||
@@ -165,14 +165,14 @@ export const SetHookDialog: React.FC<{ account: IAccount }> = ({ account }) => {
|
|||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
<Box css={{ mt: "$3" }}>
|
<Box css={{ mt: "$3" }}>
|
||||||
<Label>Hook Namespace (sha256)</Label>
|
<label>Hook Namespace (sha256)</label>
|
||||||
<Input readOnly value={hashedNamespace} />
|
<Input readOnly value={hashedNamespace} />
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
<Box css={{ width: "100%" }}>
|
<Box css={{ width: "100%" }}>
|
||||||
<Label style={{ marginBottom: "10px", display: "block" }}>
|
<label style={{ marginBottom: "10px", display: "block" }}>
|
||||||
Hook parameters
|
Hook parameters
|
||||||
</Label>
|
</label>
|
||||||
<Stack>
|
<Stack>
|
||||||
{fields.map((field, index) => (
|
{fields.map((field, index) => (
|
||||||
<Stack key={field.id}>
|
<Stack key={field.id}>
|
||||||
@@ -184,7 +184,7 @@ export const SetHookDialog: React.FC<{ account: IAccount }> = ({ account }) => {
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
placeholder="Parameter value"
|
placeholder="Value (hex-quoted)"
|
||||||
{...register(
|
{...register(
|
||||||
`HookParameters.${index}.HookParameter.HookParameterValue`
|
`HookParameters.${index}.HookParameter.HookParameterValue`
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import React, {
|
|||||||
useCallback,
|
useCallback,
|
||||||
} from "react";
|
} from "react";
|
||||||
import type { ReactNode, ReactElement } from "react";
|
import type { ReactNode, ReactElement } from "react";
|
||||||
import { Box, Button, Flex, Input, Label, Stack, Text } from ".";
|
import { Box, Button, Flex, Input, Stack, Text } from ".";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogTrigger,
|
DialogTrigger,
|
||||||
@@ -29,7 +29,7 @@ interface TabProps {
|
|||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO customise messages shown
|
// TODO customise strings shown
|
||||||
interface Props {
|
interface Props {
|
||||||
activeIndex?: number;
|
activeIndex?: number;
|
||||||
activeHeader?: string;
|
activeHeader?: string;
|
||||||
@@ -40,7 +40,6 @@ interface Props {
|
|||||||
forceDefaultExtension?: boolean;
|
forceDefaultExtension?: boolean;
|
||||||
onCreateNewTab?: (name: string) => any;
|
onCreateNewTab?: (name: string) => any;
|
||||||
onCloseTab?: (index: number, header?: string) => any;
|
onCloseTab?: (index: number, header?: string) => any;
|
||||||
onChangeActive?: (index: number, header?: string) => any;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Tab = (props: TabProps) => null;
|
export const Tab = (props: TabProps) => null;
|
||||||
@@ -53,12 +52,11 @@ export const Tabs = ({
|
|||||||
keepAllAlive = false,
|
keepAllAlive = false,
|
||||||
onCreateNewTab,
|
onCreateNewTab,
|
||||||
onCloseTab,
|
onCloseTab,
|
||||||
onChangeActive,
|
|
||||||
defaultExtension = "",
|
defaultExtension = "",
|
||||||
forceDefaultExtension,
|
forceDefaultExtension,
|
||||||
}: Props) => {
|
}: Props) => {
|
||||||
const [active, setActive] = useState(activeIndex || 0);
|
const [active, setActive] = useState(activeIndex || 0);
|
||||||
const tabs: TabProps[] = children.map(elem => elem.props);
|
const tabs: TabProps[] = children.map((elem) => elem.props);
|
||||||
|
|
||||||
const [isNewtabDialogOpen, setIsNewtabDialogOpen] = useState(false);
|
const [isNewtabDialogOpen, setIsNewtabDialogOpen] = useState(false);
|
||||||
const [tabname, setTabname] = useState("");
|
const [tabname, setTabname] = useState("");
|
||||||
@@ -70,9 +68,8 @@ export const Tabs = ({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (activeHeader) {
|
if (activeHeader) {
|
||||||
const idx = tabs.findIndex(tab => tab.header === activeHeader);
|
const idx = tabs.findIndex((tab) => tab.header === activeHeader);
|
||||||
if (idx !== -1) setActive(idx);
|
setActive(idx);
|
||||||
else setActive(0);
|
|
||||||
}
|
}
|
||||||
}, [activeHeader, tabs]);
|
}, [activeHeader, tabs]);
|
||||||
|
|
||||||
@@ -83,7 +80,7 @@ export const Tabs = ({
|
|||||||
|
|
||||||
const validateTabname = useCallback(
|
const validateTabname = useCallback(
|
||||||
(tabname: string): { error: string | null } => {
|
(tabname: string): { error: string | null } => {
|
||||||
if (tabs.find(tab => tab.header === tabname)) {
|
if (tabs.find((tab) => tab.header === tabname)) {
|
||||||
return { error: "Name already exists." };
|
return { error: "Name already exists." };
|
||||||
}
|
}
|
||||||
return { error: null };
|
return { error: null };
|
||||||
@@ -91,14 +88,6 @@ export const Tabs = ({
|
|||||||
[tabs]
|
[tabs]
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleActiveChange = useCallback(
|
|
||||||
(idx: number, header?: string) => {
|
|
||||||
setActive(idx);
|
|
||||||
onChangeActive?.(idx, header);
|
|
||||||
},
|
|
||||||
[onChangeActive]
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleCreateTab = useCallback(() => {
|
const handleCreateTab = useCallback(() => {
|
||||||
// add default extension in case omitted
|
// add default extension in case omitted
|
||||||
let _tabname = tabname.includes(".") ? tabname : tabname + defaultExtension;
|
let _tabname = tabname.includes(".") ? tabname : tabname + defaultExtension;
|
||||||
@@ -114,20 +103,11 @@ export const Tabs = ({
|
|||||||
|
|
||||||
setIsNewtabDialogOpen(false);
|
setIsNewtabDialogOpen(false);
|
||||||
setTabname("");
|
setTabname("");
|
||||||
|
// switch to new tab?
|
||||||
|
setActive(tabs.length);
|
||||||
|
|
||||||
onCreateNewTab?.(_tabname);
|
onCreateNewTab?.(_tabname);
|
||||||
|
}, [tabname, defaultExtension, validateTabname, onCreateNewTab, tabs.length]);
|
||||||
// switch to new tab?
|
|
||||||
handleActiveChange(tabs.length, _tabname);
|
|
||||||
}, [
|
|
||||||
tabname,
|
|
||||||
defaultExtension,
|
|
||||||
forceDefaultExtension,
|
|
||||||
validateTabname,
|
|
||||||
onCreateNewTab,
|
|
||||||
handleActiveChange,
|
|
||||||
tabs.length,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const handleCloseTab = useCallback(
|
const handleCloseTab = useCallback(
|
||||||
(idx: number) => {
|
(idx: number) => {
|
||||||
@@ -148,7 +128,7 @@ export const Tabs = ({
|
|||||||
gap: "$3",
|
gap: "$3",
|
||||||
flex: 1,
|
flex: 1,
|
||||||
flexWrap: "nowrap",
|
flexWrap: "nowrap",
|
||||||
marginBottom: "$2",
|
marginBottom: "-1px",
|
||||||
width: "100%",
|
width: "100%",
|
||||||
overflow: "auto",
|
overflow: "auto",
|
||||||
}}
|
}}
|
||||||
@@ -158,8 +138,8 @@ export const Tabs = ({
|
|||||||
key={tab.header}
|
key={tab.header}
|
||||||
role="tab"
|
role="tab"
|
||||||
tabIndex={idx}
|
tabIndex={idx}
|
||||||
onClick={() => handleActiveChange(idx, tab.header)}
|
onClick={() => setActive(idx)}
|
||||||
onKeyPress={() => handleActiveChange(idx, tab.header)}
|
onKeyPress={() => setActive(idx)}
|
||||||
outline={active !== idx}
|
outline={active !== idx}
|
||||||
size="sm"
|
size="sm"
|
||||||
css={{
|
css={{
|
||||||
@@ -212,11 +192,11 @@ export const Tabs = ({
|
|||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogTitle>Create new tab</DialogTitle>
|
<DialogTitle>Create new tab</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
<Label>Tabname</Label>
|
<label>Tabname</label>
|
||||||
<Input
|
<Input
|
||||||
value={tabname}
|
value={tabname}
|
||||||
onChange={e => setTabname(e.target.value)}
|
onChange={(e) => setTabname(e.target.value)}
|
||||||
onKeyPress={e => {
|
onKeyPress={(e) => {
|
||||||
if (e.key === "Enter") {
|
if (e.key === "Enter") {
|
||||||
handleCreateTab();
|
handleCreateTab();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,184 +0,0 @@
|
|||||||
import { Play } from "phosphor-react";
|
|
||||||
import { FC, useCallback, useEffect, useMemo } from "react";
|
|
||||||
import { useSnapshot } from "valtio";
|
|
||||||
import state from "../../state";
|
|
||||||
import {
|
|
||||||
modifyTransaction,
|
|
||||||
prepareState,
|
|
||||||
prepareTransaction,
|
|
||||||
TransactionState,
|
|
||||||
} from "../../state/transactions";
|
|
||||||
import { sendTransaction } from "../../state/actions";
|
|
||||||
import Box from "../Box";
|
|
||||||
import Button from "../Button";
|
|
||||||
import Flex from "../Flex";
|
|
||||||
import { TxJson } from "./json";
|
|
||||||
import { TxUI } from "./ui";
|
|
||||||
|
|
||||||
export interface TransactionProps {
|
|
||||||
header: string;
|
|
||||||
state: TransactionState;
|
|
||||||
}
|
|
||||||
|
|
||||||
const Transaction: FC<TransactionProps> = ({
|
|
||||||
header,
|
|
||||||
state: txState,
|
|
||||||
...props
|
|
||||||
}) => {
|
|
||||||
const { accounts, editorSettings } = useSnapshot(state);
|
|
||||||
const {
|
|
||||||
selectedAccount,
|
|
||||||
selectedTransaction,
|
|
||||||
txIsDisabled,
|
|
||||||
txIsLoading,
|
|
||||||
viewType,
|
|
||||||
editorSavedValue,
|
|
||||||
editorValue,
|
|
||||||
} = txState;
|
|
||||||
|
|
||||||
const setState = useCallback(
|
|
||||||
(pTx?: Partial<TransactionState>) => {
|
|
||||||
return modifyTransaction(header, pTx);
|
|
||||||
},
|
|
||||||
[header]
|
|
||||||
);
|
|
||||||
|
|
||||||
const prepareOptions = useCallback(
|
|
||||||
(state: TransactionState = txState) => {
|
|
||||||
const {
|
|
||||||
selectedTransaction,
|
|
||||||
selectedDestAccount,
|
|
||||||
selectedAccount,
|
|
||||||
txFields,
|
|
||||||
} = state;
|
|
||||||
|
|
||||||
const TransactionType = selectedTransaction?.value || null;
|
|
||||||
const Destination =
|
|
||||||
selectedDestAccount?.value ||
|
|
||||||
("Destination" in txFields ? null : undefined);
|
|
||||||
const Account = selectedAccount?.value || null;
|
|
||||||
|
|
||||||
return prepareTransaction({
|
|
||||||
...txFields,
|
|
||||||
TransactionType,
|
|
||||||
Destination,
|
|
||||||
Account,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
[txState]
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const transactionType = selectedTransaction?.value;
|
|
||||||
const account = selectedAccount?.value;
|
|
||||||
if (!account || !transactionType || txIsLoading) {
|
|
||||||
setState({ txIsDisabled: true });
|
|
||||||
} else {
|
|
||||||
setState({ txIsDisabled: false });
|
|
||||||
}
|
|
||||||
}, [selectedAccount?.value, selectedTransaction?.value, setState, txIsLoading]);
|
|
||||||
|
|
||||||
const submitTest = useCallback(async () => {
|
|
||||||
let st: TransactionState | undefined;
|
|
||||||
if (viewType === "json") {
|
|
||||||
// save the editor state first
|
|
||||||
const pst = prepareState(editorValue || '', txState);
|
|
||||||
if (!pst) return;
|
|
||||||
|
|
||||||
st = setState(pst);
|
|
||||||
}
|
|
||||||
|
|
||||||
const account = accounts.find(
|
|
||||||
acc => acc.address === selectedAccount?.value
|
|
||||||
);
|
|
||||||
if (txIsDisabled) return;
|
|
||||||
|
|
||||||
setState({ txIsLoading: true });
|
|
||||||
const logPrefix = header ? `${header.split(".")[0]}: ` : undefined;
|
|
||||||
try {
|
|
||||||
if (!account) {
|
|
||||||
throw Error("Account must be selected from imported accounts!");
|
|
||||||
}
|
|
||||||
const options = prepareOptions(st);
|
|
||||||
|
|
||||||
if (options.Destination === null) {
|
|
||||||
throw Error("Destination account cannot be null")
|
|
||||||
}
|
|
||||||
|
|
||||||
await sendTransaction(account, options, { logPrefix });
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
if (error instanceof Error) {
|
|
||||||
state.transactionLogs.push({
|
|
||||||
type: "error",
|
|
||||||
message: `${logPrefix}${error.message}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setState({ txIsLoading: false });
|
|
||||||
}, [viewType, accounts, txIsDisabled, setState, header, editorValue, txState, selectedAccount?.value, prepareOptions]);
|
|
||||||
|
|
||||||
const resetState = useCallback(() => {
|
|
||||||
modifyTransaction(header, { viewType }, { replaceState: true });
|
|
||||||
}, [header, viewType]);
|
|
||||||
|
|
||||||
const jsonValue = useMemo(
|
|
||||||
() =>
|
|
||||||
editorSavedValue ||
|
|
||||||
JSON.stringify(prepareOptions?.() || {}, null, editorSettings.tabSize),
|
|
||||||
[editorSavedValue, editorSettings.tabSize, prepareOptions]
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box css={{ position: "relative", height: "calc(100% - 28px)" }} {...props}>
|
|
||||||
{viewType === "json" ? (
|
|
||||||
<TxJson
|
|
||||||
value={jsonValue}
|
|
||||||
header={header}
|
|
||||||
state={txState}
|
|
||||||
setState={setState}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<TxUI state={txState} setState={setState} />
|
|
||||||
)}
|
|
||||||
<Flex
|
|
||||||
row
|
|
||||||
css={{
|
|
||||||
justifyContent: "space-between",
|
|
||||||
position: "absolute",
|
|
||||||
left: 0,
|
|
||||||
bottom: 0,
|
|
||||||
width: "100%",
|
|
||||||
mb: "$1",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Button
|
|
||||||
onClick={() => {
|
|
||||||
if (viewType === "ui") {
|
|
||||||
setState({ editorSavedValue: null, viewType: "json" });
|
|
||||||
} else setState({ viewType: "ui" });
|
|
||||||
}}
|
|
||||||
outline
|
|
||||||
>
|
|
||||||
{viewType === "ui" ? "EDIT AS JSON" : "EXIT JSON MODE"}
|
|
||||||
</Button>
|
|
||||||
<Flex row>
|
|
||||||
<Button onClick={resetState} outline css={{ mr: "$3" }}>
|
|
||||||
RESET
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
onClick={submitTest}
|
|
||||||
isLoading={txIsLoading}
|
|
||||||
disabled={txIsDisabled}
|
|
||||||
>
|
|
||||||
<Play weight="bold" size="16px" />
|
|
||||||
RUN TEST
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
</Flex>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Transaction;
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
import Editor, { loader, useMonaco } from "@monaco-editor/react";
|
|
||||||
import { FC, useCallback, useEffect, useState } from "react";
|
|
||||||
import { useTheme } from "next-themes";
|
|
||||||
|
|
||||||
import dark from "../../theme/editor/amy.json";
|
|
||||||
import light from "../../theme/editor/xcode_default.json";
|
|
||||||
import { useSnapshot } from "valtio";
|
|
||||||
import state, {
|
|
||||||
prepareState,
|
|
||||||
transactionsData,
|
|
||||||
TransactionState,
|
|
||||||
} from "../../state";
|
|
||||||
import Text from "../Text";
|
|
||||||
import Flex from "../Flex";
|
|
||||||
import { Link } from "..";
|
|
||||||
import { showAlert } from "../../state/actions/showAlert";
|
|
||||||
import { parseJSON } from "../../utils/json";
|
|
||||||
import { extractSchemaProps } from "../../utils/schema";
|
|
||||||
import amountSchema from "../../content/amount-schema.json";
|
|
||||||
|
|
||||||
loader.config({
|
|
||||||
paths: {
|
|
||||||
vs: "https://cdn.jsdelivr.net/npm/monaco-editor@0.30.1/min/vs",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
interface JsonProps {
|
|
||||||
value?: string;
|
|
||||||
header?: string;
|
|
||||||
setState: (pTx?: Partial<TransactionState> | undefined) => void;
|
|
||||||
state: TransactionState;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const TxJson: FC<JsonProps> = ({
|
|
||||||
value = "",
|
|
||||||
state: txState,
|
|
||||||
header,
|
|
||||||
setState,
|
|
||||||
}) => {
|
|
||||||
const { editorSettings, accounts } = useSnapshot(state);
|
|
||||||
const { editorValue = value, selectedTransaction } = txState;
|
|
||||||
const { theme } = useTheme();
|
|
||||||
const [hasUnsaved, setHasUnsaved] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setState({ editorValue: value });
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [value]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (editorValue === value) setHasUnsaved(false);
|
|
||||||
else setHasUnsaved(true);
|
|
||||||
}, [editorValue, value]);
|
|
||||||
|
|
||||||
const saveState = (value: string, txState: TransactionState) => {
|
|
||||||
const tx = prepareState(value, txState);
|
|
||||||
if (tx) setState(tx);
|
|
||||||
};
|
|
||||||
|
|
||||||
const discardChanges = () => {
|
|
||||||
showAlert("Confirm", {
|
|
||||||
body: "Are you sure to discard these changes?",
|
|
||||||
confirmText: "Yes",
|
|
||||||
onConfirm: () => setState({ editorValue: value }),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const onExit = (value: string) => {
|
|
||||||
const options = parseJSON(value);
|
|
||||||
if (options) {
|
|
||||||
saveState(value, txState);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
showAlert("Error!", {
|
|
||||||
body: `Malformed Transaction in ${header}, would you like to discard these changes?`,
|
|
||||||
confirmText: "Discard",
|
|
||||||
onConfirm: () => setState({ editorValue: value }),
|
|
||||||
onCancel: () => setState({ viewType: "json", editorSavedValue: value }),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const path = `file:///${header}`;
|
|
||||||
const monaco = useMonaco();
|
|
||||||
|
|
||||||
const getSchemas = useCallback((): any[] => {
|
|
||||||
const tt = selectedTransaction?.value;
|
|
||||||
const txObj = transactionsData.find(td => td.TransactionType === tt);
|
|
||||||
|
|
||||||
let genericSchemaProps: any;
|
|
||||||
if (txObj) {
|
|
||||||
genericSchemaProps = extractSchemaProps(txObj);
|
|
||||||
} else {
|
|
||||||
genericSchemaProps = transactionsData.reduce(
|
|
||||||
(cumm, td) => ({
|
|
||||||
...cumm,
|
|
||||||
...extractSchemaProps(td),
|
|
||||||
}),
|
|
||||||
{}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
uri: "file:///main-schema.json", // id of the first schema
|
|
||||||
fileMatch: ["**.json"], // associate with our model
|
|
||||||
schema: {
|
|
||||||
title: header,
|
|
||||||
type: "object",
|
|
||||||
required: ["TransactionType", "Account"],
|
|
||||||
properties: {
|
|
||||||
...genericSchemaProps,
|
|
||||||
TransactionType: {
|
|
||||||
title: "Transaction Type",
|
|
||||||
enum: transactionsData.map(td => td.TransactionType),
|
|
||||||
},
|
|
||||||
Account: {
|
|
||||||
$ref: "file:///account-schema.json",
|
|
||||||
},
|
|
||||||
Destination: {
|
|
||||||
anyOf: [
|
|
||||||
{
|
|
||||||
$ref: "file:///account-schema.json",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "string",
|
|
||||||
title: "Destination Account",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
Amount: {
|
|
||||||
$ref: "file:///amount-schema.json",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
uri: "file:///account-schema.json",
|
|
||||||
schema: {
|
|
||||||
type: "string",
|
|
||||||
title: "Account type",
|
|
||||||
enum: accounts.map(acc => acc.address),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
...amountSchema,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}, [accounts, header, selectedTransaction?.value]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!monaco) return;
|
|
||||||
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
|
|
||||||
validate: true,
|
|
||||||
schemas: getSchemas(),
|
|
||||||
});
|
|
||||||
}, [getSchemas, monaco]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Flex
|
|
||||||
fluid
|
|
||||||
column
|
|
||||||
css={{ height: "calc(100% - 45px)", position: "relative" }}
|
|
||||||
>
|
|
||||||
<Editor
|
|
||||||
className="hooks-editor"
|
|
||||||
language={"json"}
|
|
||||||
path={path}
|
|
||||||
height="100%"
|
|
||||||
beforeMount={monaco => {
|
|
||||||
monaco.editor.defineTheme("dark", dark as any);
|
|
||||||
monaco.editor.defineTheme("light", light as any);
|
|
||||||
}}
|
|
||||||
value={editorValue}
|
|
||||||
onChange={val => setState({ editorValue: val })}
|
|
||||||
onMount={(editor, monaco) => {
|
|
||||||
editor.updateOptions({
|
|
||||||
minimap: { enabled: false },
|
|
||||||
glyphMargin: true,
|
|
||||||
tabSize: editorSettings.tabSize,
|
|
||||||
dragAndDrop: true,
|
|
||||||
fontSize: 14,
|
|
||||||
});
|
|
||||||
|
|
||||||
// register onExit cb
|
|
||||||
const model = editor.getModel();
|
|
||||||
model?.onWillDispose(() => onExit(model.getValue()));
|
|
||||||
|
|
||||||
// set json defaults
|
|
||||||
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
|
|
||||||
validate: true,
|
|
||||||
schemas: getSchemas(),
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
theme={theme === "dark" ? "dark" : "light"}
|
|
||||||
/>
|
|
||||||
{hasUnsaved && (
|
|
||||||
<Text muted small css={{ position: "absolute", bottom: 0, right: 0 }}>
|
|
||||||
This file has unsaved changes.{" "}
|
|
||||||
<Link onClick={() => saveState(editorValue, txState)}>save</Link>{" "}
|
|
||||||
<Link onClick={discardChanges}>discard</Link>
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Flex>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -1,213 +0,0 @@
|
|||||||
import { FC } from "react";
|
|
||||||
import Container from "../Container";
|
|
||||||
import Flex from "../Flex";
|
|
||||||
import Input from "../Input";
|
|
||||||
import Select from "../Select";
|
|
||||||
import Text from "../Text";
|
|
||||||
import {
|
|
||||||
SelectOption,
|
|
||||||
TransactionState,
|
|
||||||
transactionsData,
|
|
||||||
TxFields,
|
|
||||||
} from "../../state/transactions";
|
|
||||||
import { useSnapshot } from "valtio";
|
|
||||||
import state from "../../state";
|
|
||||||
import { streamState } from "../DebugStream";
|
|
||||||
|
|
||||||
interface UIProps {
|
|
||||||
setState: (pTx?: Partial<TransactionState> | undefined) => void;
|
|
||||||
state: TransactionState;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const TxUI: FC<UIProps> = ({ state: txState, setState }) => {
|
|
||||||
const { accounts } = useSnapshot(state);
|
|
||||||
const {
|
|
||||||
selectedAccount,
|
|
||||||
selectedDestAccount,
|
|
||||||
selectedTransaction,
|
|
||||||
txFields,
|
|
||||||
} = txState;
|
|
||||||
|
|
||||||
const transactionsOptions = transactionsData.map(tx => ({
|
|
||||||
value: tx.TransactionType,
|
|
||||||
label: tx.TransactionType,
|
|
||||||
}));
|
|
||||||
|
|
||||||
const accountOptions: SelectOption[] = accounts.map(acc => ({
|
|
||||||
label: acc.name,
|
|
||||||
value: acc.address,
|
|
||||||
}));
|
|
||||||
|
|
||||||
const destAccountOptions: SelectOption[] = accounts
|
|
||||||
.map(acc => ({
|
|
||||||
label: acc.name,
|
|
||||||
value: acc.address,
|
|
||||||
}))
|
|
||||||
.filter(acc => acc.value !== selectedAccount?.value);
|
|
||||||
|
|
||||||
const resetOptions = (tt: string) => {
|
|
||||||
const txFields: TxFields | undefined = transactionsData.find(
|
|
||||||
tx => tx.TransactionType === tt
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!txFields) return setState({ txFields: {} });
|
|
||||||
|
|
||||||
const _txFields = Object.keys(txFields)
|
|
||||||
.filter(key => !["TransactionType", "Account", "Sequence"].includes(key))
|
|
||||||
.reduce<TxFields>(
|
|
||||||
(tf, key) => ((tf[key as keyof TxFields] = (txFields as any)[key]), tf),
|
|
||||||
{}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!_txFields.Destination) setState({ selectedDestAccount: null });
|
|
||||||
setState({ txFields: _txFields });
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSetAccount = (acc: SelectOption) => {
|
|
||||||
setState({ selectedAccount: acc });
|
|
||||||
streamState.selectedAccount = acc;
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleChangeTxType = (tt: SelectOption) => {
|
|
||||||
setState({ selectedTransaction: tt });
|
|
||||||
resetOptions(tt.value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const specialFields = ["TransactionType", "Account", "Destination"];
|
|
||||||
|
|
||||||
const otherFields = Object.keys(txFields).filter(
|
|
||||||
k => !specialFields.includes(k)
|
|
||||||
) as [keyof TxFields];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Container
|
|
||||||
css={{
|
|
||||||
p: "$3 01",
|
|
||||||
fontSize: "$sm",
|
|
||||||
height: "calc(100% - 45px)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Flex column fluid css={{ height: "100%", overflowY: "auto" }}>
|
|
||||||
<Flex
|
|
||||||
row
|
|
||||||
fluid
|
|
||||||
css={{
|
|
||||||
justifyContent: "flex-end",
|
|
||||||
alignItems: "center",
|
|
||||||
mb: "$3",
|
|
||||||
mt: "1px",
|
|
||||||
pr: "1px",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Text muted css={{ mr: "$3" }}>
|
|
||||||
Transaction type:{" "}
|
|
||||||
</Text>
|
|
||||||
<Select
|
|
||||||
instanceId="transactionsType"
|
|
||||||
placeholder="Select transaction type"
|
|
||||||
options={transactionsOptions}
|
|
||||||
hideSelectedOptions
|
|
||||||
css={{ width: "70%" }}
|
|
||||||
value={selectedTransaction}
|
|
||||||
onChange={(tt: any) => handleChangeTxType(tt)}
|
|
||||||
/>
|
|
||||||
</Flex>
|
|
||||||
<Flex
|
|
||||||
row
|
|
||||||
fluid
|
|
||||||
css={{
|
|
||||||
justifyContent: "flex-end",
|
|
||||||
alignItems: "center",
|
|
||||||
mb: "$3",
|
|
||||||
pr: "1px",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Text muted css={{ mr: "$3" }}>
|
|
||||||
Account:{" "}
|
|
||||||
</Text>
|
|
||||||
<Select
|
|
||||||
instanceId="from-account"
|
|
||||||
placeholder="Select your account"
|
|
||||||
css={{ width: "70%" }}
|
|
||||||
options={accountOptions}
|
|
||||||
value={selectedAccount}
|
|
||||||
onChange={(acc: any) => handleSetAccount(acc)} // TODO make react-select have correct types for acc
|
|
||||||
/>
|
|
||||||
</Flex>
|
|
||||||
{txFields.Destination !== undefined && (
|
|
||||||
<Flex
|
|
||||||
row
|
|
||||||
fluid
|
|
||||||
css={{
|
|
||||||
justifyContent: "flex-end",
|
|
||||||
alignItems: "center",
|
|
||||||
mb: "$3",
|
|
||||||
pr: "1px",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Text muted css={{ mr: "$3" }}>
|
|
||||||
Destination account:{" "}
|
|
||||||
</Text>
|
|
||||||
<Select
|
|
||||||
instanceId="to-account"
|
|
||||||
placeholder="Select the destination account"
|
|
||||||
css={{ width: "70%" }}
|
|
||||||
options={destAccountOptions}
|
|
||||||
value={selectedDestAccount}
|
|
||||||
isClearable
|
|
||||||
onChange={(acc: any) => setState({ selectedDestAccount: acc })}
|
|
||||||
/>
|
|
||||||
</Flex>
|
|
||||||
)}
|
|
||||||
{otherFields.map(field => {
|
|
||||||
let _value = txFields[field];
|
|
||||||
|
|
||||||
let value: string | undefined;
|
|
||||||
if (typeof _value === "object") {
|
|
||||||
if (_value.$type === "json" && typeof _value.$value === "object") {
|
|
||||||
value = JSON.stringify(_value.$value);
|
|
||||||
} else {
|
|
||||||
value = _value.$value.toString();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
value = _value?.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
let isXrp = typeof _value === "object" && _value.$type === "xrp";
|
|
||||||
return (
|
|
||||||
<Flex
|
|
||||||
key={field}
|
|
||||||
row
|
|
||||||
fluid
|
|
||||||
css={{
|
|
||||||
justifyContent: "flex-end",
|
|
||||||
alignItems: "center",
|
|
||||||
mb: "$3",
|
|
||||||
pr: "1px",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Text muted css={{ mr: "$3" }}>
|
|
||||||
{field + (isXrp ? " (XRP)" : "")}:{" "}
|
|
||||||
</Text>
|
|
||||||
<Input
|
|
||||||
value={value}
|
|
||||||
onChange={e => {
|
|
||||||
setState({
|
|
||||||
txFields: {
|
|
||||||
...txFields,
|
|
||||||
[field]:
|
|
||||||
typeof _value === "object"
|
|
||||||
? { ..._value, $value: e.target.value }
|
|
||||||
: e.target.value,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
css={{ width: "70%", flex: "inherit" }}
|
|
||||||
/>
|
|
||||||
</Flex>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Flex>
|
|
||||||
</Container>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -4,10 +4,10 @@ export { default as Container } from "./Container";
|
|||||||
export { default as Heading } from "./Heading";
|
export { default as Heading } from "./Heading";
|
||||||
export { default as Stack } from "./Stack";
|
export { default as Stack } from "./Stack";
|
||||||
export { default as Text } from "./Text";
|
export { default as Text } from "./Text";
|
||||||
export { default as Input, Label } from "./Input";
|
export { default as Input } from "./Input";
|
||||||
export { default as Select } from "./Select";
|
export { default as Select } from "./Select";
|
||||||
export * from "./Tabs";
|
export * from "./Tabs";
|
||||||
export * from "./AlertDialog/primitive";
|
export * from "./AlertDialog";
|
||||||
export { default as Box } from "./Box";
|
export { default as Box } from "./Box";
|
||||||
export { default as Button } from "./Button";
|
export { default as Button } from "./Button";
|
||||||
export { default as Pre } from "./Pre";
|
export { default as Pre } from "./Pre";
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
{
|
|
||||||
"uri": "file:///amount-schema.json",
|
|
||||||
"title": "Amount",
|
|
||||||
"description": "Specify xrp in drops and tokens as objects.",
|
|
||||||
"schema": {
|
|
||||||
"anyOf": [
|
|
||||||
{
|
|
||||||
"type": [
|
|
||||||
"number",
|
|
||||||
"string"
|
|
||||||
],
|
|
||||||
"exclusiveMinimum": 0,
|
|
||||||
"maximum": "100000000000000000"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"currency": {
|
|
||||||
"description": "Arbitrary currency code for the token. Cannot be XRP."
|
|
||||||
},
|
|
||||||
"value": {
|
|
||||||
"type": [
|
|
||||||
"string",
|
|
||||||
"number"
|
|
||||||
],
|
|
||||||
"description": "Quoted decimal representation of the amount of the token."
|
|
||||||
},
|
|
||||||
"issuer": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "Generally, the account that issues this token. In special cases, this can refer to the account that holds the token instead."
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"defaultSnippets": [
|
|
||||||
{
|
|
||||||
"label": "Xrp",
|
|
||||||
"body": "1000000"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"label": "Token",
|
|
||||||
"body": {
|
|
||||||
"currency": "${1:13.1}",
|
|
||||||
"value": "${2:FOO}",
|
|
||||||
"description": "${3:rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpns}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -27,8 +27,8 @@
|
|||||||
"Account": "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy",
|
"Account": "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy",
|
||||||
"TransactionType": "CheckCash",
|
"TransactionType": "CheckCash",
|
||||||
"Amount": {
|
"Amount": {
|
||||||
"$value": "100",
|
"value": "100",
|
||||||
"$type": "xrp"
|
"type": "currency"
|
||||||
},
|
},
|
||||||
"CheckID": "838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334",
|
"CheckID": "838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334",
|
||||||
"Fee": "12"
|
"Fee": "12"
|
||||||
@@ -61,8 +61,8 @@
|
|||||||
"Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
|
"Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
|
||||||
"TransactionType": "EscrowCreate",
|
"TransactionType": "EscrowCreate",
|
||||||
"Amount": {
|
"Amount": {
|
||||||
"$value": "100",
|
"value": "100",
|
||||||
"$type": "xrp"
|
"type": "currency"
|
||||||
},
|
},
|
||||||
"Destination": "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW",
|
"Destination": "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW",
|
||||||
"CancelAfter": 533257958,
|
"CancelAfter": 533257958,
|
||||||
@@ -99,8 +99,8 @@
|
|||||||
"Account": "rs8jBmmfpwgmrSPgwMsh7CvKRmRt1JTVSX",
|
"Account": "rs8jBmmfpwgmrSPgwMsh7CvKRmRt1JTVSX",
|
||||||
"TokenID": "000100001E962F495F07A990F4ED55ACCFEEF365DBAA76B6A048C0A200000007",
|
"TokenID": "000100001E962F495F07A990F4ED55ACCFEEF365DBAA76B6A048C0A200000007",
|
||||||
"Amount": {
|
"Amount": {
|
||||||
"$value": "100",
|
"value": "100",
|
||||||
"$type": "xrp"
|
"type": "currency"
|
||||||
},
|
},
|
||||||
"Flags": 1
|
"Flags": 1
|
||||||
},
|
},
|
||||||
@@ -122,8 +122,8 @@
|
|||||||
"Sequence": 8,
|
"Sequence": 8,
|
||||||
"TakerGets": "6000000",
|
"TakerGets": "6000000",
|
||||||
"Amount": {
|
"Amount": {
|
||||||
"$value": "100",
|
"value": "100",
|
||||||
"$type": "xrp"
|
"type": "currency"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -131,8 +131,8 @@
|
|||||||
"Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
|
"Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
|
||||||
"Destination": "ra5nK24KXen9AHvsdFTKHSANinZseWnPcX",
|
"Destination": "ra5nK24KXen9AHvsdFTKHSANinZseWnPcX",
|
||||||
"Amount": {
|
"Amount": {
|
||||||
"$value": "100",
|
"value": "100",
|
||||||
"$type": "xrp"
|
"type": "currency"
|
||||||
},
|
},
|
||||||
"Fee": "12",
|
"Fee": "12",
|
||||||
"Flags": 2147483648,
|
"Flags": 2147483648,
|
||||||
@@ -142,8 +142,8 @@
|
|||||||
"Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
|
"Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
|
||||||
"TransactionType": "PaymentChannelCreate",
|
"TransactionType": "PaymentChannelCreate",
|
||||||
"Amount": {
|
"Amount": {
|
||||||
"$value": "100",
|
"value": "100",
|
||||||
"$type": "xrp"
|
"type": "currency"
|
||||||
},
|
},
|
||||||
"Destination": "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW",
|
"Destination": "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW",
|
||||||
"SettleDelay": 86400,
|
"SettleDelay": 86400,
|
||||||
@@ -157,8 +157,8 @@
|
|||||||
"TransactionType": "PaymentChannelFund",
|
"TransactionType": "PaymentChannelFund",
|
||||||
"Channel": "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198",
|
"Channel": "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198",
|
||||||
"Amount": {
|
"Amount": {
|
||||||
"$value": "200",
|
"value": "200",
|
||||||
"$type": "xrp"
|
"type": "currency"
|
||||||
},
|
},
|
||||||
"Expiration": 543171558
|
"Expiration": 543171558
|
||||||
},
|
},
|
||||||
@@ -176,8 +176,8 @@
|
|||||||
"Fee": "12",
|
"Fee": "12",
|
||||||
"SignerQuorum": 3,
|
"SignerQuorum": 3,
|
||||||
"SignerEntries": {
|
"SignerEntries": {
|
||||||
"$type": "json",
|
"type": "json",
|
||||||
"$value": [
|
"value": [
|
||||||
{
|
{
|
||||||
"SignerEntry": {
|
"SignerEntry": {
|
||||||
"Account": "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW",
|
"Account": "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW",
|
||||||
@@ -213,8 +213,8 @@
|
|||||||
"Flags": 262144,
|
"Flags": 262144,
|
||||||
"LastLedgerSequence": 8007750,
|
"LastLedgerSequence": 8007750,
|
||||||
"Amount": {
|
"Amount": {
|
||||||
"$value": "100",
|
"value": "100",
|
||||||
"$type": "xrp"
|
"type": "currency"
|
||||||
},
|
},
|
||||||
"Sequence": 12
|
"Sequence": 12
|
||||||
}
|
}
|
||||||
|
|||||||
12057
package-lock.json
generated
12057
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -19,7 +19,6 @@
|
|||||||
"@radix-ui/react-dialog": "^0.1.1",
|
"@radix-ui/react-dialog": "^0.1.1",
|
||||||
"@radix-ui/react-dropdown-menu": "^0.1.1",
|
"@radix-ui/react-dropdown-menu": "^0.1.1",
|
||||||
"@radix-ui/react-id": "^0.1.1",
|
"@radix-ui/react-id": "^0.1.1",
|
||||||
"@radix-ui/react-label": "^0.1.5",
|
|
||||||
"@radix-ui/react-tooltip": "^0.1.7",
|
"@radix-ui/react-tooltip": "^0.1.7",
|
||||||
"@stitches/react": "^1.2.6-0",
|
"@stitches/react": "^1.2.6-0",
|
||||||
"base64-js": "^1.5.1",
|
"base64-js": "^1.5.1",
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import state from "../state";
|
|||||||
import TimeAgo from "javascript-time-ago";
|
import TimeAgo from "javascript-time-ago";
|
||||||
import en from "javascript-time-ago/locale/en.json";
|
import en from "javascript-time-ago/locale/en.json";
|
||||||
import { useSnapshot } from "valtio";
|
import { useSnapshot } from "valtio";
|
||||||
import Alert from '../components/AlertDialog';
|
|
||||||
|
|
||||||
TimeAgo.setDefaultLocale(en.locale);
|
TimeAgo.setDefaultLocale(en.locale);
|
||||||
TimeAgo.addLocale(en);
|
TimeAgo.addLocale(en);
|
||||||
@@ -141,7 +140,6 @@ function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
|
|||||||
})(),
|
})(),
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Alert />
|
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</SessionProvider>
|
</SessionProvider>
|
||||||
</IdProvider>
|
</IdProvider>
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
|
||||||
|
|
||||||
export default async function handler(
|
|
||||||
req: NextApiRequest,
|
|
||||||
res: NextApiResponse
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const { url, opts } = req.body
|
|
||||||
const r = await fetch(url, opts);
|
|
||||||
if (!r.ok) throw (r.statusText)
|
|
||||||
|
|
||||||
const data = await r.json()
|
|
||||||
return res.json(data)
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(error)
|
|
||||||
return res.status(500).json({ message: "Something went wrong!" })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,23 @@
|
|||||||
import dynamic from "next/dynamic";
|
import dynamic from "next/dynamic";
|
||||||
|
import { Play } from "phosphor-react";
|
||||||
|
import { FC, useCallback, useEffect, useState } from "react";
|
||||||
import Split from "react-split";
|
import Split from "react-split";
|
||||||
import { useSnapshot } from "valtio";
|
import { useSnapshot } from "valtio";
|
||||||
import { Box, Container, Flex, Tab, Tabs } from "../../components";
|
import {
|
||||||
import Transaction from "../../components/Transaction";
|
Box,
|
||||||
|
Button,
|
||||||
|
Container,
|
||||||
|
Flex,
|
||||||
|
Input,
|
||||||
|
Select,
|
||||||
|
Tab,
|
||||||
|
Tabs,
|
||||||
|
Text,
|
||||||
|
} from "../../components";
|
||||||
|
import transactionsData from "../../content/transactions.json";
|
||||||
import state from "../../state";
|
import state from "../../state";
|
||||||
|
import { sendTransaction } from "../../state/actions";
|
||||||
import { getSplit, saveSplit } from "../../state/actions/persistSplits";
|
import { getSplit, saveSplit } from "../../state/actions/persistSplits";
|
||||||
import { transactionsState, modifyTransaction } from "../../state";
|
|
||||||
|
|
||||||
const DebugStream = dynamic(() => import("../../components/DebugStream"), {
|
const DebugStream = dynamic(() => import("../../components/DebugStream"), {
|
||||||
ssr: false,
|
ssr: false,
|
||||||
@@ -18,10 +30,344 @@ const Accounts = dynamic(() => import("../../components/Accounts"), {
|
|||||||
ssr: false,
|
ssr: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// type SelectOption<T> = { value: T, label: string };
|
||||||
|
type TxFields = Omit<
|
||||||
|
typeof transactionsData[0],
|
||||||
|
"Account" | "Sequence" | "TransactionType"
|
||||||
|
>;
|
||||||
|
type OtherFields = (keyof Omit<TxFields, "Destination">)[];
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
header?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Transaction: FC<Props> = ({ header, ...props }) => {
|
||||||
|
const snap = useSnapshot(state);
|
||||||
|
|
||||||
|
const transactionsOptions = transactionsData.map((tx) => ({
|
||||||
|
value: tx.TransactionType,
|
||||||
|
label: tx.TransactionType,
|
||||||
|
}));
|
||||||
|
const [selectedTransaction, setSelectedTransaction] = useState<
|
||||||
|
typeof transactionsOptions[0] | null
|
||||||
|
>(null);
|
||||||
|
|
||||||
|
const accountOptions = snap.accounts.map((acc) => ({
|
||||||
|
label: acc.name,
|
||||||
|
value: acc.address,
|
||||||
|
}));
|
||||||
|
const [selectedAccount, setSelectedAccount] = useState<
|
||||||
|
typeof accountOptions[0] | null
|
||||||
|
>(null);
|
||||||
|
|
||||||
|
const destAccountOptions = snap.accounts
|
||||||
|
.map((acc) => ({
|
||||||
|
label: acc.name,
|
||||||
|
value: acc.address,
|
||||||
|
}))
|
||||||
|
.filter((acc) => acc.value !== selectedAccount?.value);
|
||||||
|
const [selectedDestAccount, setSelectedDestAccount] = useState<
|
||||||
|
typeof destAccountOptions[0] | null
|
||||||
|
>(null);
|
||||||
|
|
||||||
|
const [txIsLoading, setTxIsLoading] = useState(false);
|
||||||
|
const [txIsDisabled, setTxIsDisabled] = useState(false);
|
||||||
|
const [txFields, setTxFields] = useState<TxFields>({});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const transactionType = selectedTransaction?.value;
|
||||||
|
const account = snap.accounts.find(
|
||||||
|
(acc) => acc.address === selectedAccount?.value
|
||||||
|
);
|
||||||
|
if (!account || !transactionType || txIsLoading) {
|
||||||
|
setTxIsDisabled(true);
|
||||||
|
} else {
|
||||||
|
setTxIsDisabled(false);
|
||||||
|
}
|
||||||
|
}, [txIsLoading, selectedTransaction, selectedAccount, snap.accounts]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let _txFields: TxFields | undefined = transactionsData.find(
|
||||||
|
(tx) => tx.TransactionType === selectedTransaction?.value
|
||||||
|
);
|
||||||
|
if (!_txFields) return setTxFields({});
|
||||||
|
_txFields = { ..._txFields } as TxFields;
|
||||||
|
|
||||||
|
setSelectedDestAccount(null);
|
||||||
|
// @ts-ignore
|
||||||
|
delete _txFields.TransactionType;
|
||||||
|
// @ts-ignore
|
||||||
|
delete _txFields.Account;
|
||||||
|
// @ts-ignore
|
||||||
|
delete _txFields.Sequence;
|
||||||
|
setTxFields(_txFields);
|
||||||
|
}, [selectedTransaction, setSelectedDestAccount]);
|
||||||
|
|
||||||
|
const submitTest = useCallback(async () => {
|
||||||
|
const account = snap.accounts.find(
|
||||||
|
(acc) => acc.address === selectedAccount?.value
|
||||||
|
);
|
||||||
|
const TransactionType = selectedTransaction?.value;
|
||||||
|
if (!account || !TransactionType || txIsDisabled) return;
|
||||||
|
|
||||||
|
setTxIsLoading(true);
|
||||||
|
// setTxIsError(null)
|
||||||
|
try {
|
||||||
|
let options = { ...txFields };
|
||||||
|
|
||||||
|
options.Destination = selectedDestAccount?.value;
|
||||||
|
(Object.keys(options) as (keyof TxFields)[]).forEach((field) => {
|
||||||
|
let _value = options[field];
|
||||||
|
// convert currency
|
||||||
|
if (typeof _value === "object" && _value.type === "currency") {
|
||||||
|
if (+_value.value) {
|
||||||
|
options[field] = (+_value.value * 1000000 + "") as any;
|
||||||
|
} else {
|
||||||
|
options[field] = undefined; // 👇 💀
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// handle type: `json`
|
||||||
|
if (typeof _value === "object" && _value.type === "json") {
|
||||||
|
if (typeof _value.value === "object") {
|
||||||
|
options[field] = _value.value as any;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
options[field] = JSON.parse(_value.value);
|
||||||
|
} catch (error) {
|
||||||
|
const message = `Input error for json field '${field}': ${
|
||||||
|
error instanceof Error ? error.message : ""
|
||||||
|
}`;
|
||||||
|
throw Error(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// delete unneccesary fields
|
||||||
|
if (!options[field]) {
|
||||||
|
delete options[field];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const logPrefix = header ? `${header.split(".")[0]}: ` : undefined;
|
||||||
|
await sendTransaction(
|
||||||
|
account,
|
||||||
|
{
|
||||||
|
TransactionType,
|
||||||
|
...options,
|
||||||
|
},
|
||||||
|
{ logPrefix }
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
if (error instanceof Error) {
|
||||||
|
state.transactionLogs.push({ type: "error", message: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setTxIsLoading(false);
|
||||||
|
}, [
|
||||||
|
header,
|
||||||
|
selectedAccount?.value,
|
||||||
|
selectedDestAccount?.value,
|
||||||
|
selectedTransaction?.value,
|
||||||
|
snap.accounts,
|
||||||
|
txFields,
|
||||||
|
txIsDisabled,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const resetState = useCallback(() => {
|
||||||
|
setSelectedAccount(null);
|
||||||
|
setSelectedDestAccount(null);
|
||||||
|
setSelectedTransaction(null);
|
||||||
|
setTxFields({});
|
||||||
|
setTxIsDisabled(false);
|
||||||
|
setTxIsLoading(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const usualFields = ["TransactionType", "Amount", "Account", "Destination"];
|
||||||
|
const otherFields = Object.keys(txFields).filter(
|
||||||
|
(k) => !usualFields.includes(k)
|
||||||
|
) as OtherFields;
|
||||||
|
return (
|
||||||
|
<Box css={{ position: "relative", height: "calc(100% - 28px)" }} {...props}>
|
||||||
|
<Container
|
||||||
|
css={{
|
||||||
|
p: "$3 01",
|
||||||
|
fontSize: "$sm",
|
||||||
|
height: "calc(100% - 45px)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Flex column fluid css={{ height: "100%", overflowY: "auto" }}>
|
||||||
|
<Flex
|
||||||
|
row
|
||||||
|
fluid
|
||||||
|
css={{
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
alignItems: "center",
|
||||||
|
mb: "$3",
|
||||||
|
mt: "1px",
|
||||||
|
pr: "1px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text muted css={{ mr: "$3" }}>
|
||||||
|
Transaction type:{" "}
|
||||||
|
</Text>
|
||||||
|
<Select
|
||||||
|
instanceId="transactionsType"
|
||||||
|
placeholder="Select transaction type"
|
||||||
|
options={transactionsOptions}
|
||||||
|
hideSelectedOptions
|
||||||
|
css={{ width: "70%" }}
|
||||||
|
value={selectedTransaction}
|
||||||
|
onChange={(tt) => setSelectedTransaction(tt as any)}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
<Flex
|
||||||
|
row
|
||||||
|
fluid
|
||||||
|
css={{
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
alignItems: "center",
|
||||||
|
mb: "$3",
|
||||||
|
pr: "1px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text muted css={{ mr: "$3" }}>
|
||||||
|
Account:{" "}
|
||||||
|
</Text>
|
||||||
|
<Select
|
||||||
|
instanceId="from-account"
|
||||||
|
placeholder="Select your account"
|
||||||
|
css={{ width: "70%" }}
|
||||||
|
options={accountOptions}
|
||||||
|
value={selectedAccount}
|
||||||
|
onChange={(acc) => setSelectedAccount(acc as any)}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
{txFields.Amount !== undefined && (
|
||||||
|
<Flex
|
||||||
|
row
|
||||||
|
fluid
|
||||||
|
css={{
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
alignItems: "center",
|
||||||
|
mb: "$3",
|
||||||
|
pr: "1px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text muted css={{ mr: "$3" }}>
|
||||||
|
Amount (XRP):{" "}
|
||||||
|
</Text>
|
||||||
|
<Input
|
||||||
|
value={txFields.Amount.value}
|
||||||
|
onChange={(e) =>
|
||||||
|
setTxFields({
|
||||||
|
...txFields,
|
||||||
|
Amount: { type: "currency", value: e.target.value },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
css={{ width: "70%", flex: "inherit", height: "$9" }}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
{txFields.Destination !== undefined && (
|
||||||
|
<Flex
|
||||||
|
row
|
||||||
|
fluid
|
||||||
|
css={{
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
alignItems: "center",
|
||||||
|
mb: "$3",
|
||||||
|
pr: "1px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text muted css={{ mr: "$3" }}>
|
||||||
|
Destination account:{" "}
|
||||||
|
</Text>
|
||||||
|
<Select
|
||||||
|
instanceId="to-account"
|
||||||
|
placeholder="Select the destination account"
|
||||||
|
css={{ width: "70%" }}
|
||||||
|
options={destAccountOptions}
|
||||||
|
value={selectedDestAccount}
|
||||||
|
isClearable
|
||||||
|
onChange={(acc) => setSelectedDestAccount(acc as any)}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
{otherFields.map((field) => {
|
||||||
|
let _value = txFields[field];
|
||||||
|
let value = typeof _value === "object" ? _value.value : _value;
|
||||||
|
value =
|
||||||
|
typeof value === "object"
|
||||||
|
? JSON.stringify(value)
|
||||||
|
: value?.toLocaleString();
|
||||||
|
let isCurrency =
|
||||||
|
typeof _value === "object" && _value.type === "currency";
|
||||||
|
return (
|
||||||
|
<Flex
|
||||||
|
key={field}
|
||||||
|
row
|
||||||
|
fluid
|
||||||
|
css={{
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
alignItems: "center",
|
||||||
|
mb: "$3",
|
||||||
|
pr: "1px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text muted css={{ mr: "$3" }}>
|
||||||
|
{field + (isCurrency ? " (XRP)" : "")}:{" "}
|
||||||
|
</Text>
|
||||||
|
<Input
|
||||||
|
value={value}
|
||||||
|
onChange={(e) =>
|
||||||
|
setTxFields({
|
||||||
|
...txFields,
|
||||||
|
[field]:
|
||||||
|
typeof _value === "object"
|
||||||
|
? { ..._value, value: e.target.value }
|
||||||
|
: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
css={{ width: "70%", flex: "inherit", height: "$9" }}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Flex>
|
||||||
|
</Container>
|
||||||
|
<Flex
|
||||||
|
row
|
||||||
|
css={{
|
||||||
|
justifyContent: "space-between",
|
||||||
|
position: "absolute",
|
||||||
|
left: 0,
|
||||||
|
bottom: 0,
|
||||||
|
width: "100%",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button outline>VIEW AS JSON</Button>
|
||||||
|
<Flex row>
|
||||||
|
<Button onClick={resetState} outline css={{ mr: "$3" }}>
|
||||||
|
RESET
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={submitTest}
|
||||||
|
isLoading={txIsLoading}
|
||||||
|
disabled={txIsDisabled}
|
||||||
|
>
|
||||||
|
<Play weight="bold" size="16px" />
|
||||||
|
RUN TEST
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const Test = () => {
|
const Test = () => {
|
||||||
const { transactionLogs } = useSnapshot(state);
|
const { transactionLogs } = useSnapshot(state);
|
||||||
const { transactions, activeHeader } = useSnapshot(transactionsState);
|
const [tabHeaders, setTabHeaders] = useState<string[]>(["test1.json"]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container css={{ px: 0 }}>
|
<Container css={{ px: 0 }}>
|
||||||
<Split
|
<Split
|
||||||
@@ -30,7 +376,7 @@ const Test = () => {
|
|||||||
gutterSize={4}
|
gutterSize={4}
|
||||||
gutterAlign="center"
|
gutterAlign="center"
|
||||||
style={{ height: "calc(100vh - 60px)" }}
|
style={{ height: "calc(100vh - 60px)" }}
|
||||||
onDragEnd={e => saveSplit("testVertical", e)}
|
onDragEnd={(e) => saveSplit("testVertical", e)}
|
||||||
>
|
>
|
||||||
<Flex
|
<Flex
|
||||||
row
|
row
|
||||||
@@ -52,29 +398,23 @@ const Test = () => {
|
|||||||
width: "100%",
|
width: "100%",
|
||||||
height: "100%",
|
height: "100%",
|
||||||
}}
|
}}
|
||||||
onDragEnd={e => saveSplit("testHorizontal", e)}
|
onDragEnd={(e) => saveSplit("testHorizontal", e)}
|
||||||
>
|
>
|
||||||
<Box css={{ width: "55%", px: "$2" }}>
|
<Box css={{ width: "55%", px: "$2" }}>
|
||||||
<Tabs
|
<Tabs
|
||||||
activeHeader={activeHeader}
|
|
||||||
// TODO make header a required field
|
|
||||||
onChangeActive={(idx, header) => {
|
|
||||||
if (header) transactionsState.activeHeader = header;
|
|
||||||
}}
|
|
||||||
keepAllAlive
|
keepAllAlive
|
||||||
forceDefaultExtension
|
forceDefaultExtension
|
||||||
defaultExtension=".json"
|
defaultExtension=".json"
|
||||||
onCreateNewTab={header => modifyTransaction(header, {})}
|
onCreateNewTab={(name) =>
|
||||||
onCloseTab={(idx, header) =>
|
setTabHeaders(tabHeaders.concat(name))
|
||||||
header && modifyTransaction(header, undefined)
|
}
|
||||||
|
onCloseTab={(index) =>
|
||||||
|
setTabHeaders(tabHeaders.filter((_, idx) => idx !== index))
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{transactions.map(({ header, state }) => (
|
{tabHeaders.map((header) => (
|
||||||
<Tab key={header} header={header}>
|
<Tab key={header} header={header}>
|
||||||
<Transaction
|
<Transaction header={header} />
|
||||||
state={state}
|
|
||||||
header={header}
|
|
||||||
/>
|
|
||||||
</Tab>
|
</Tab>
|
||||||
))}
|
))}
|
||||||
</Tabs>
|
</Tabs>
|
||||||
|
|||||||
@@ -4,21 +4,19 @@ import toast from "react-hot-toast";
|
|||||||
import state, { IAccount } from "../index";
|
import state, { IAccount } from "../index";
|
||||||
import calculateHookOn, { TTS } from "../../utils/hookOnCalculator";
|
import calculateHookOn, { TTS } from "../../utils/hookOnCalculator";
|
||||||
import { SetHookData } from "../../components/SetHookDialog";
|
import { SetHookData } from "../../components/SetHookDialog";
|
||||||
import { Link } from "../../components";
|
|
||||||
import { ref } from "valtio";
|
|
||||||
|
|
||||||
export const sha256 = async (string: string) => {
|
export const sha256 = async (string: string) => {
|
||||||
const utf8 = new TextEncoder().encode(string);
|
const utf8 = new TextEncoder().encode(string);
|
||||||
const hashBuffer = await crypto.subtle.digest("SHA-256", utf8);
|
const hashBuffer = await crypto.subtle.digest('SHA-256', utf8);
|
||||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||||
const hashHex = hashArray
|
const hashHex = hashArray
|
||||||
.map(bytes => bytes.toString(16).padStart(2, "0"))
|
.map((bytes) => bytes.toString(16).padStart(2, '0'))
|
||||||
.join("");
|
.join('');
|
||||||
return hashHex;
|
return hashHex;
|
||||||
};
|
}
|
||||||
|
|
||||||
function toHex(str: string) {
|
function toHex(str: string) {
|
||||||
var result = "";
|
var result = '';
|
||||||
for (var i = 0; i < str.length; i++) {
|
for (var i = 0; i < str.length; i++) {
|
||||||
result += str.charCodeAt(i).toString(16);
|
result += str.charCodeAt(i).toString(16);
|
||||||
}
|
}
|
||||||
@@ -53,10 +51,7 @@ function arrayBufferToHex(arrayBuffer?: ArrayBuffer | null) {
|
|||||||
* hex string, signs the transaction and deploys it to
|
* hex string, signs the transaction and deploys it to
|
||||||
* Hooks testnet.
|
* Hooks testnet.
|
||||||
*/
|
*/
|
||||||
export const deployHook = async (
|
export const deployHook = async (account: IAccount & { name?: string }, data: SetHookData) => {
|
||||||
account: IAccount & { name?: string },
|
|
||||||
data: SetHookData
|
|
||||||
) => {
|
|
||||||
if (
|
if (
|
||||||
!state.files ||
|
!state.files ||
|
||||||
state.files.length === 0 ||
|
state.files.length === 0 ||
|
||||||
@@ -74,15 +69,7 @@ export const deployHook = async (
|
|||||||
const HookNamespace = (await sha256(data.HookNamespace)).toUpperCase();
|
const HookNamespace = (await sha256(data.HookNamespace)).toUpperCase();
|
||||||
const hookOnValues: (keyof TTS)[] = data.Invoke.map(tt => tt.value);
|
const hookOnValues: (keyof TTS)[] = data.Invoke.map(tt => tt.value);
|
||||||
const { HookParameters } = data;
|
const { HookParameters } = data;
|
||||||
const filteredHookParameters = HookParameters.filter(
|
const filteredHookParameters = HookParameters.filter(hp => hp.HookParameter.HookParameterName && hp.HookParameter.HookParameterValue)?.map(aa => ({ HookParameter: { HookParameterName: toHex(aa.HookParameter.HookParameterName || ''), HookParameterValue: aa.HookParameter.HookParameterValue || '' } }));
|
||||||
hp =>
|
|
||||||
hp.HookParameter.HookParameterName && hp.HookParameter.HookParameterValue
|
|
||||||
)?.map(aa => ({
|
|
||||||
HookParameter: {
|
|
||||||
HookParameterName: toHex(aa.HookParameter.HookParameterName || ""),
|
|
||||||
HookParameterValue: toHex(aa.HookParameter.HookParameterValue || ""),
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
// const filteredHookGrants = HookGrants.filter(hg => hg.HookGrant.Authorize || hg.HookGrant.HookHash).map(hg => {
|
// const filteredHookGrants = HookGrants.filter(hg => hg.HookGrant.Authorize || hg.HookGrant.HookHash).map(hg => {
|
||||||
// return {
|
// return {
|
||||||
// HookGrant: {
|
// HookGrant: {
|
||||||
@@ -110,18 +97,16 @@ export const deployHook = async (
|
|||||||
HookApiVersion: 0,
|
HookApiVersion: 0,
|
||||||
Flags: 1,
|
Flags: 1,
|
||||||
// ...(filteredHookGrants.length > 0 && { HookGrants: filteredHookGrants }),
|
// ...(filteredHookGrants.length > 0 && { HookGrants: filteredHookGrants }),
|
||||||
...(filteredHookParameters.length > 0 && {
|
...(filteredHookParameters.length > 0 && { HookParameters: filteredHookParameters }),
|
||||||
HookParameters: filteredHookParameters,
|
}
|
||||||
}),
|
}
|
||||||
},
|
]
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const keypair = derive.familySeed(account.secret);
|
const keypair = derive.familySeed(account.secret);
|
||||||
const { signedTransaction } = sign(tx, keypair);
|
const { signedTransaction } = sign(tx, keypair);
|
||||||
const currentAccount = state.accounts.find(
|
const currentAccount = state.accounts.find(
|
||||||
acc => acc.address === account.address
|
(acc) => acc.address === account.address
|
||||||
);
|
);
|
||||||
if (currentAccount) {
|
if (currentAccount) {
|
||||||
currentAccount.isLoading = true;
|
currentAccount.isLoading = true;
|
||||||
@@ -140,28 +125,12 @@ export const deployHook = async (
|
|||||||
});
|
});
|
||||||
state.deployLogs.push({
|
state.deployLogs.push({
|
||||||
type: "success",
|
type: "success",
|
||||||
message: ref(
|
message: `[${submitRes.engine_result}] ${submitRes.engine_result_message} Validated ledger index: ${submitRes.validated_ledger_index}`,
|
||||||
<>
|
|
||||||
[{submitRes.engine_result}] {submitRes.engine_result_message}{" "}
|
|
||||||
Validated ledger index:{" "}
|
|
||||||
<Link
|
|
||||||
as="a"
|
|
||||||
href={`https://${process.env.NEXT_PUBLIC_EXPLORER_URL}/${submitRes.validated_ledger_index}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
>
|
|
||||||
{submitRes.validated_ledger_index}
|
|
||||||
</Link>
|
|
||||||
</>
|
|
||||||
),
|
|
||||||
// message: `[${submitRes.engine_result}] ${submitRes.engine_result_message} Validated ledger index: ${submitRes.validated_ledger_index}`,
|
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
state.deployLogs.push({
|
state.deployLogs.push({
|
||||||
type: "error",
|
type: "error",
|
||||||
message: `[${submitRes.engine_result || submitRes.error}] ${
|
message: `[${submitRes.engine_result || submitRes.error}] ${submitRes.engine_result_message || submitRes.error_exception}`,
|
||||||
submitRes.engine_result_message || submitRes.error_exception
|
|
||||||
}`,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -183,10 +152,10 @@ export const deleteHook = async (account: IAccount & { name?: string }) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const currentAccount = state.accounts.find(
|
const currentAccount = state.accounts.find(
|
||||||
acc => acc.address === account.address
|
(acc) => acc.address === account.address
|
||||||
);
|
);
|
||||||
if (currentAccount?.isLoading || !currentAccount?.hooks.length) {
|
if (currentAccount?.isLoading || !currentAccount?.hooks.length) {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (typeof window !== "undefined") {
|
if (typeof window !== "undefined") {
|
||||||
const tx = {
|
const tx = {
|
||||||
@@ -199,9 +168,9 @@ export const deleteHook = async (account: IAccount & { name?: string }) => {
|
|||||||
Hook: {
|
Hook: {
|
||||||
CreateCode: "",
|
CreateCode: "",
|
||||||
Flags: 1,
|
Flags: 1,
|
||||||
},
|
}
|
||||||
},
|
}
|
||||||
],
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const keypair = derive.familySeed(account.secret);
|
const keypair = derive.familySeed(account.secret);
|
||||||
@@ -219,7 +188,7 @@ export const deleteHook = async (account: IAccount & { name?: string }) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (submitRes.engine_result === "tesSUCCESS") {
|
if (submitRes.engine_result === "tesSUCCESS") {
|
||||||
toast.success("Hook deleted successfully ✅", { id: toastId });
|
toast.success('Hook deleted successfully ✅', { id: toastId })
|
||||||
state.deployLogs.push({
|
state.deployLogs.push({
|
||||||
type: "success",
|
type: "success",
|
||||||
message: "Hook deleted successfully ✅",
|
message: "Hook deleted successfully ✅",
|
||||||
@@ -230,20 +199,15 @@ export const deleteHook = async (account: IAccount & { name?: string }) => {
|
|||||||
});
|
});
|
||||||
currentAccount.hooks = [];
|
currentAccount.hooks = [];
|
||||||
} else {
|
} else {
|
||||||
toast.error(
|
toast.error(`${submitRes.engine_result_message || submitRes.error_exception}`, { id: toastId })
|
||||||
`${submitRes.engine_result_message || submitRes.error_exception}`,
|
|
||||||
{ id: toastId }
|
|
||||||
);
|
|
||||||
state.deployLogs.push({
|
state.deployLogs.push({
|
||||||
type: "error",
|
type: "error",
|
||||||
message: `[${submitRes.engine_result || submitRes.error}] ${
|
message: `[${submitRes.engine_result || submitRes.error}] ${submitRes.engine_result_message || submitRes.error_exception}`,
|
||||||
submitRes.engine_result_message || submitRes.error_exception
|
|
||||||
}`,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
toast.error("Error occured while deleting hoook", { id: toastId });
|
toast.error('Error occured while deleting hoook', { id: toastId })
|
||||||
state.deployLogs.push({
|
state.deployLogs.push({
|
||||||
type: "error",
|
type: "error",
|
||||||
message: "Error occured while deleting hook",
|
message: "Error occured while deleting hook",
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
import { ref } from 'valtio';
|
|
||||||
import { AlertState, alertState } from "../../components/AlertDialog";
|
|
||||||
|
|
||||||
export const showAlert = (title: string, opts: Omit<Partial<AlertState>, 'title' | 'isOpen'> = {}) => {
|
|
||||||
const { body: _body, confirmPrefix: _confirmPrefix, ...rest } = opts
|
|
||||||
const body = (_body && typeof _body === 'object') ? ref(_body) : _body
|
|
||||||
const confirmPrefix = (_confirmPrefix && typeof _confirmPrefix === 'object') ? ref(_confirmPrefix) : _confirmPrefix
|
|
||||||
|
|
||||||
const nwState: AlertState = {
|
|
||||||
isOpen: true,
|
|
||||||
title,
|
|
||||||
body,
|
|
||||||
confirmPrefix,
|
|
||||||
cancelText: undefined,
|
|
||||||
confirmText: undefined,
|
|
||||||
onCancel: undefined,
|
|
||||||
onConfirm: undefined,
|
|
||||||
...rest,
|
|
||||||
}
|
|
||||||
Object.entries(nwState).forEach(([key, value]) => {
|
|
||||||
(alertState as any)[key] = value
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -39,10 +39,9 @@ export interface IAccount {
|
|||||||
|
|
||||||
export interface ILog {
|
export interface ILog {
|
||||||
type: "error" | "warning" | "log" | "success";
|
type: "error" | "warning" | "log" | "success";
|
||||||
message: string | JSX.Element;
|
message: string;
|
||||||
key?: string;
|
|
||||||
jsonData?: any,
|
jsonData?: any,
|
||||||
timestring?: string;
|
timestamp?: string;
|
||||||
link?: string;
|
link?: string;
|
||||||
linkText?: string;
|
linkText?: string;
|
||||||
defaultCollapsed?: boolean
|
defaultCollapsed?: boolean
|
||||||
@@ -160,5 +159,3 @@ if (typeof window !== "undefined") {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
export default state
|
export default state
|
||||||
|
|
||||||
export * from './transactions'
|
|
||||||
|
|||||||
@@ -1,225 +0,0 @@
|
|||||||
import { proxy } from 'valtio';
|
|
||||||
import { deepEqual } from '../utils/object';
|
|
||||||
import transactionsData from "../content/transactions.json";
|
|
||||||
import state from '.';
|
|
||||||
import { showAlert } from "../state/actions/showAlert";
|
|
||||||
import { parseJSON } from '../utils/json';
|
|
||||||
|
|
||||||
export type SelectOption = {
|
|
||||||
value: string;
|
|
||||||
label: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface TransactionState {
|
|
||||||
selectedTransaction: SelectOption | null;
|
|
||||||
selectedAccount: SelectOption | null;
|
|
||||||
selectedDestAccount: SelectOption | null;
|
|
||||||
txIsLoading: boolean;
|
|
||||||
txIsDisabled: boolean;
|
|
||||||
txFields: TxFields;
|
|
||||||
viewType: 'json' | 'ui',
|
|
||||||
editorSavedValue: null | string,
|
|
||||||
editorValue?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export type TxFields = Omit<
|
|
||||||
typeof transactionsData[0],
|
|
||||||
"Account" | "Sequence" | "TransactionType"
|
|
||||||
>;
|
|
||||||
|
|
||||||
export const defaultTransaction: TransactionState = {
|
|
||||||
selectedTransaction: null,
|
|
||||||
selectedAccount: null,
|
|
||||||
selectedDestAccount: null,
|
|
||||||
txIsLoading: false,
|
|
||||||
txIsDisabled: false,
|
|
||||||
txFields: {},
|
|
||||||
viewType: 'ui',
|
|
||||||
editorSavedValue: null
|
|
||||||
};
|
|
||||||
|
|
||||||
export const transactionsState = proxy({
|
|
||||||
transactions: [
|
|
||||||
{
|
|
||||||
header: "test1.json",
|
|
||||||
state: defaultTransaction,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
activeHeader: "test1.json"
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Simple transaction state changer
|
|
||||||
* @param header Unique key and tab name for the transaction tab
|
|
||||||
* @param partialTx partial transaction state, `undefined` deletes the transaction
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
export const modifyTransaction = (
|
|
||||||
header: string,
|
|
||||||
partialTx?: Partial<TransactionState>,
|
|
||||||
opts: { replaceState?: boolean } = {}
|
|
||||||
) => {
|
|
||||||
const tx = transactionsState.transactions.find(tx => tx.header === header);
|
|
||||||
|
|
||||||
if (partialTx === undefined) {
|
|
||||||
transactionsState.transactions = transactionsState.transactions.filter(
|
|
||||||
tx => tx.header !== header
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!tx) {
|
|
||||||
const state = {
|
|
||||||
...defaultTransaction,
|
|
||||||
...partialTx,
|
|
||||||
}
|
|
||||||
transactionsState.transactions.push({
|
|
||||||
header,
|
|
||||||
state,
|
|
||||||
});
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (opts.replaceState) {
|
|
||||||
const repTx: TransactionState = {
|
|
||||||
...defaultTransaction,
|
|
||||||
...partialTx,
|
|
||||||
}
|
|
||||||
tx.state = repTx
|
|
||||||
return repTx
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.keys(partialTx).forEach(k => {
|
|
||||||
// Typescript mess here, but is definetly safe!
|
|
||||||
const s = tx.state as any;
|
|
||||||
const p = partialTx as any;
|
|
||||||
if (!deepEqual(s[k], p[k])) s[k] = p[k];
|
|
||||||
});
|
|
||||||
|
|
||||||
return tx.state
|
|
||||||
};
|
|
||||||
|
|
||||||
// state to tx options
|
|
||||||
export const prepareTransaction = (data: any) => {
|
|
||||||
let options = { ...data };
|
|
||||||
|
|
||||||
(Object.keys(options)).forEach(field => {
|
|
||||||
let _value = options[field];
|
|
||||||
// convert xrp
|
|
||||||
if (_value && typeof _value === "object" && _value.$type === "xrp") {
|
|
||||||
if (+_value.$value) {
|
|
||||||
options[field] = (+_value.$value * 1000000 + "") as any;
|
|
||||||
} else {
|
|
||||||
options[field] = undefined; // 👇 💀
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// handle type: `json`
|
|
||||||
if (_value && typeof _value === "object" && _value.$type === "json") {
|
|
||||||
if (typeof _value.$value === "object") {
|
|
||||||
options[field] = _value.$value as any;
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
options[field] = JSON.parse(_value.$value);
|
|
||||||
} catch (error) {
|
|
||||||
const message = `Input error for json field '${field}': ${error instanceof Error ? error.message : ""
|
|
||||||
}`;
|
|
||||||
console.error(message)
|
|
||||||
options[field] = _value.$value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// delete unneccesary fields
|
|
||||||
if (options[field] === undefined) {
|
|
||||||
delete options[field];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
|
|
||||||
// editor value to state
|
|
||||||
export const prepareState = (value: string, txState: TransactionState) => {
|
|
||||||
const options = parseJSON(value);
|
|
||||||
if (!options) {
|
|
||||||
showAlert("Error!", {
|
|
||||||
body: "Cannot save editor with malformed transaction."
|
|
||||||
})
|
|
||||||
return
|
|
||||||
};
|
|
||||||
|
|
||||||
const { Account, TransactionType, Destination, ...rest } = options;
|
|
||||||
let tx: Partial<TransactionState> = {};
|
|
||||||
const { txFields } = txState
|
|
||||||
|
|
||||||
if (Account) {
|
|
||||||
const acc = state.accounts.find(acc => acc.address === Account);
|
|
||||||
if (acc) {
|
|
||||||
tx.selectedAccount = {
|
|
||||||
label: acc.name,
|
|
||||||
value: acc.address,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
tx.selectedAccount = {
|
|
||||||
label: Account,
|
|
||||||
value: Account,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
tx.selectedAccount = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (TransactionType) {
|
|
||||||
tx.selectedTransaction = {
|
|
||||||
label: TransactionType,
|
|
||||||
value: TransactionType,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
tx.selectedTransaction = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (txFields.Destination !== undefined) {
|
|
||||||
const dest = state.accounts.find(acc => acc.address === Destination);
|
|
||||||
rest.Destination = null
|
|
||||||
if (dest) {
|
|
||||||
tx.selectedDestAccount = {
|
|
||||||
label: dest.name,
|
|
||||||
value: dest.address,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
else if (Destination) {
|
|
||||||
tx.selectedDestAccount = {
|
|
||||||
label: Destination,
|
|
||||||
value: Destination,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
tx.selectedDestAccount = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.keys(rest).forEach(field => {
|
|
||||||
const value = rest[field];
|
|
||||||
const origValue = txFields[field as keyof TxFields]
|
|
||||||
const isXrp = typeof value !== 'object' && origValue && typeof origValue === 'object' && origValue.$type === 'xrp'
|
|
||||||
if (isXrp) {
|
|
||||||
rest[field] = {
|
|
||||||
$type: "xrp",
|
|
||||||
$value: +value / 1000000, // TODO maybe use bigint?
|
|
||||||
};
|
|
||||||
} else if (typeof value === "object") {
|
|
||||||
rest[field] = {
|
|
||||||
$type: "json",
|
|
||||||
$value: value,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
tx.txFields = rest;
|
|
||||||
tx.editorSavedValue = null;
|
|
||||||
|
|
||||||
return tx
|
|
||||||
}
|
|
||||||
|
|
||||||
export { transactionsData }
|
|
||||||
@@ -18,14 +18,4 @@ export const extractJSON = (str?: string) => {
|
|||||||
} while (firstClose > firstOpen);
|
} while (firstClose > firstOpen);
|
||||||
firstOpen = str.indexOf('{', firstOpen + 1);
|
firstOpen = str.indexOf('{', firstOpen + 1);
|
||||||
} while (firstOpen != -1);
|
} while (firstOpen != -1);
|
||||||
}
|
|
||||||
|
|
||||||
export const parseJSON = (str?: string | null): any | undefined => {
|
|
||||||
if (!str) return undefined
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(str);
|
|
||||||
return typeof parsed === "object" ? parsed : undefined;
|
|
||||||
} catch (error) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
export const deepEqual = (object1: any, object2: any) => {
|
|
||||||
if (!isObject(object1) || !isObject(object2)) return object1 === object2
|
|
||||||
|
|
||||||
const keys1 = Object.keys(object1);
|
|
||||||
const keys2 = Object.keys(object2);
|
|
||||||
if (keys1.length !== keys2.length) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
for (const key of keys1) {
|
|
||||||
const val1 = object1[key];
|
|
||||||
const val2 = object2[key];
|
|
||||||
const areObjects = isObject(val1) && isObject(val2);
|
|
||||||
if (
|
|
||||||
areObjects && !deepEqual(val1, val2) ||
|
|
||||||
!areObjects && val1 !== val2
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
export const isObject = (object: any) => {
|
|
||||||
return object != null && typeof object === 'object';
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
export const extractSchemaProps = <O extends object>(obj: O) =>
|
|
||||||
Object.entries(obj).reduce((prev, [key, val]) => {
|
|
||||||
const typeOf = <T>(arg: T) =>
|
|
||||||
arg instanceof Array
|
|
||||||
? "array"
|
|
||||||
: arg === null
|
|
||||||
? "undefined"
|
|
||||||
: typeof arg;
|
|
||||||
|
|
||||||
const value = (typeOf(val) === "object" && '$type' in val && '$value' in val) ? val?.$value : val;
|
|
||||||
const type = typeOf(value);
|
|
||||||
|
|
||||||
let schema: any = {
|
|
||||||
title: key,
|
|
||||||
type,
|
|
||||||
default: value,
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeOf(value) === 'array') {
|
|
||||||
const item = value[0] // TODO merge other item schema's into one
|
|
||||||
if (typeOf(item) !== 'object') {
|
|
||||||
schema.items = {
|
|
||||||
type: 'object',
|
|
||||||
properties: extractSchemaProps(item),
|
|
||||||
default: item
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// TODO support primitive-value arrays
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeOf(value) === "object") {
|
|
||||||
schema.properties = extractSchemaProps(value)
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...prev,
|
|
||||||
[key]: schema,
|
|
||||||
};
|
|
||||||
}, {} as any);
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user