bring EditCodec component
Co-authored-by: Josep M Sobrepere <jm.sobrepere@gmail.com> Co-authored-by: Carlo Sala <carlosalag@protonmail.com> Co-authored-by: Hannah Redler <hannahjredler@gmail.com>
This commit is contained in:
co-authored by
Josep M Sobrepere
Carlo Sala
Hannah Redler
parent
f3ab886f63
commit
34099eaafb
@@ -0,0 +1,183 @@
|
||||
import { NOTIN } from "@codec-components"
|
||||
import { Binary } from "@polkadot-api/substrate-bindings"
|
||||
import { FileUp } from "lucide-react"
|
||||
import { FC, useState } from "react"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { TextInputField } from "./TextInputField"
|
||||
import { useGenericSynchronizeInput } from "./useSynchroniseInput"
|
||||
|
||||
export const BinaryInput: React.FC<{
|
||||
encodedValue: Binary | NOTIN
|
||||
onValueChanged: (newValue: Binary | NOTIN) => boolean
|
||||
len?: number
|
||||
}> = ({ encodedValue, onValueChanged, len }) => {
|
||||
const [localInput, setLocalInput] = useGenericSynchronizeInput(
|
||||
encodedValue,
|
||||
onValueChanged,
|
||||
(value) => validate(parseValue(value), len),
|
||||
"" as string | Binary,
|
||||
serializeValue,
|
||||
checkEqualInputBinary,
|
||||
)
|
||||
const [uploadError, setUploadError] = useState("")
|
||||
|
||||
const inputValue = typeof localInput === "string" ? localInput : ""
|
||||
const placeholder =
|
||||
typeof localInput === "string"
|
||||
? "Enter text or hex" + (len ? ` (${len.toLocaleString()} bytes)` : "")
|
||||
: "(value is too long to display)"
|
||||
|
||||
const validateFile = (file: File) => {
|
||||
if (file.size > 512 * 1024 * 1024) {
|
||||
setUploadError("File size can't exceed 512MB")
|
||||
return false
|
||||
}
|
||||
if (len && file.size !== len) {
|
||||
setUploadError(
|
||||
`Field requires exactly ${len} bytes, uploaded file is ${file.size} bytes instead`,
|
||||
)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const parsed = parseValue(inputValue)
|
||||
const length = parsed === NOTIN ? null : parsed.asBytes().length
|
||||
|
||||
const oddHexLength =
|
||||
typeof localInput === "string" &&
|
||||
localInput.startsWith("0x") &&
|
||||
localInput.length % 2 === 1
|
||||
|
||||
const warn = oddHexLength
|
||||
? "Hex length is odd"
|
||||
: len && length && length !== len
|
||||
? `Field requires ${len} bytes, got ${length} instead.`
|
||||
: false
|
||||
|
||||
return (
|
||||
<TextInputField
|
||||
value={inputValue}
|
||||
onChange={(v) => {
|
||||
setUploadError("")
|
||||
setLocalInput(v)
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
className="min-w-80 border-none p-0 outline-none bg-transparent flex-1"
|
||||
warn={warn}
|
||||
error={uploadError}
|
||||
>
|
||||
{(input) => (
|
||||
<div
|
||||
className={twMerge(
|
||||
"border rounded p-2 border-polkadot-200 leading-tight text-white focus-within:outline focus-within:outline-1 flex items-center gap-2",
|
||||
warn ? "border-orange-400" : null,
|
||||
uploadError ? "border-red-600" : null,
|
||||
)}
|
||||
>
|
||||
{input}
|
||||
<label title="Load from file" className="text-slate-200">
|
||||
<FileUp size={16} />
|
||||
<BinaryFileInput
|
||||
validate={validateFile}
|
||||
onLoaded={(binary) => {
|
||||
setLocalInput(serializeValue(binary))
|
||||
setUploadError("")
|
||||
}}
|
||||
onError={() => setUploadError("Error while loading file")}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</TextInputField>
|
||||
)
|
||||
}
|
||||
|
||||
export const BinaryFileInput: FC<{
|
||||
validate: (file: File) => boolean
|
||||
onLoaded: (value: Binary) => void
|
||||
onError: () => void
|
||||
}> = ({ validate, onLoaded, onError }) => {
|
||||
const loadFile = async (file: File) => {
|
||||
if (!validate(file)) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result as ArrayBuffer)
|
||||
reader.onerror = reject
|
||||
reader.readAsArrayBuffer(file)
|
||||
})
|
||||
onLoaded(Binary.fromBytes(new Uint8Array(buffer)))
|
||||
} catch (ex) {
|
||||
console.error(ex)
|
||||
onError()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<input
|
||||
type="file"
|
||||
onChange={(e) => {
|
||||
const file = e.currentTarget.files?.[0]
|
||||
if (file) loadFile(file)
|
||||
}}
|
||||
className="hidden"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const validate = (value: Binary | NOTIN, len?: number): Binary | NOTIN => {
|
||||
if (!len || value === NOTIN) return value
|
||||
return value.asBytes().length !== len ? NOTIN : value
|
||||
}
|
||||
|
||||
const parseValue = (value: string | Binary): Binary | NOTIN => {
|
||||
if (value instanceof Binary) return value
|
||||
|
||||
if (value.trim() === "") return Binary.fromText("")
|
||||
|
||||
if (value.startsWith("0x")) {
|
||||
try {
|
||||
return Binary.fromHex(value)
|
||||
} catch (_) {
|
||||
return NOTIN
|
||||
}
|
||||
}
|
||||
|
||||
return Binary.fromText(value)
|
||||
}
|
||||
|
||||
const textDecoder = new TextDecoder("utf-8", { fatal: true })
|
||||
const serializeValue = (value: Binary): string | Binary => {
|
||||
const bytes = value.asBytes()
|
||||
if (bytes.length === 0) return ""
|
||||
if (bytes.length > 5 * 1024 * 1024) return value
|
||||
|
||||
try {
|
||||
return textDecoder.decode(bytes)
|
||||
} catch (_) {
|
||||
return value.asHex()
|
||||
}
|
||||
}
|
||||
|
||||
export const checkEqualInputBinary = (
|
||||
input: string | Binary,
|
||||
value: Binary | typeof NOTIN,
|
||||
) => {
|
||||
const parsed = parseValue(input)
|
||||
if (parsed === NOTIN || value === NOTIN) return true
|
||||
const inputBytes = parsed.asBytes()
|
||||
const valueBytes = value.asBytes()
|
||||
|
||||
if (inputBytes.length !== valueBytes.length) {
|
||||
return false
|
||||
}
|
||||
for (let i = 0; i < inputBytes.length; i++) {
|
||||
if (inputBytes[i] !== valueBytes[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { CheckCircle, Copy } from "lucide-react"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
export const CopyText: React.FC<{ text: string; disabled?: boolean }> = ({
|
||||
text,
|
||||
disabled = false,
|
||||
}) => {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const copy = async () => {
|
||||
if (disabled) return
|
||||
|
||||
await navigator.clipboard.writeText(text)
|
||||
setCopied(true)
|
||||
}
|
||||
useEffect(() => {
|
||||
if (copied) {
|
||||
setTimeout(() => setCopied(false), 1000)
|
||||
}
|
||||
}, [copied])
|
||||
|
||||
return (
|
||||
<button
|
||||
disabled={disabled || copied}
|
||||
className={disabled ? "opacity-50" : ""}
|
||||
onClick={copy}
|
||||
>
|
||||
{copied ? (
|
||||
<CheckCircle size={16} className="text-green-300" />
|
||||
) : (
|
||||
<Copy size={16} />
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { FC } from "react"
|
||||
import { ChevronRight } from "lucide-react"
|
||||
import { twMerge as clsx } from "tailwind-merge"
|
||||
|
||||
export const ExpandBtn: FC<{
|
||||
expanded: boolean
|
||||
}> = ({ expanded }) => (
|
||||
<ChevronRight
|
||||
size={16}
|
||||
className={clsx("transition-transform mt-[1px]", expanded && "rotate-90")}
|
||||
/>
|
||||
)
|
||||
@@ -0,0 +1,63 @@
|
||||
import { ReactSVG, Props } from "react-svg"
|
||||
import focusSvg from "./icons/focus.svg"
|
||||
import enumSvg from "./icons/enum.svg"
|
||||
import binarySvg from "./icons/binary.svg"
|
||||
import { useEffect, useRef } from "react"
|
||||
import { Ban, Binary, Braces, CircleHelp, Hash, List, User } from "lucide-react"
|
||||
import { LookupEntry } from "@polkadot-api/metadata-builders"
|
||||
|
||||
const customIcon =
|
||||
(url: string) =>
|
||||
({ size = 16, ...props }: Omit<Props, "ref" | "src"> & { size?: number }) => {
|
||||
const ref = useRef<SVGSVGElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref.current) return
|
||||
ref.current.setAttribute("width", String(size))
|
||||
ref.current.setAttribute("height", String(size))
|
||||
}, [size])
|
||||
|
||||
return (
|
||||
<ReactSVG
|
||||
{...props}
|
||||
src={url}
|
||||
beforeInjection={(svg) => {
|
||||
ref.current = svg
|
||||
svg.setAttribute("width", String(size))
|
||||
svg.setAttribute("height", String(size))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Focus = customIcon(focusSvg)
|
||||
export const Enum = customIcon(enumSvg)
|
||||
export const BinaryEdit = customIcon(binarySvg)
|
||||
|
||||
export const TypeIcons = {
|
||||
list: List,
|
||||
enum: Enum,
|
||||
primitive: Hash,
|
||||
binary: Binary,
|
||||
account: User,
|
||||
object: Braces,
|
||||
maybe: CircleHelp,
|
||||
void: Ban,
|
||||
}
|
||||
export type TypeIcon = keyof typeof TypeIcons
|
||||
|
||||
export const lookupToType: Record<LookupEntry["type"], TypeIcon> = {
|
||||
primitive: "primitive",
|
||||
void: "void",
|
||||
compact: "primitive",
|
||||
bitSequence: "binary",
|
||||
AccountId32: "account",
|
||||
AccountId20: "account",
|
||||
tuple: "list",
|
||||
struct: "object",
|
||||
sequence: "list",
|
||||
array: "list",
|
||||
option: "maybe",
|
||||
result: "maybe",
|
||||
enum: "enum",
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { XSquare } from "lucide-react"
|
||||
import {
|
||||
FC,
|
||||
PropsWithChildren,
|
||||
ReactNode,
|
||||
createContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react"
|
||||
import { Portal } from "react-portal"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import "./modal.css"
|
||||
|
||||
export type ModalProps = PropsWithChildren<{
|
||||
title?: ReactNode
|
||||
open?: boolean
|
||||
// On some cases you have to disable this (e.g. when using non-native select boxes, those popups will go under the native dialog)
|
||||
useNative?: boolean
|
||||
onClose?: () => void
|
||||
className?: string
|
||||
}>
|
||||
|
||||
export const ModalRefContext = createContext<HTMLElement | null>(null)
|
||||
|
||||
export const Modal: FC<ModalProps> = ({
|
||||
title,
|
||||
open,
|
||||
children,
|
||||
useNative = true,
|
||||
onClose,
|
||||
className,
|
||||
}) => {
|
||||
const [ref, setRef] = useState<HTMLDialogElement | null>(null)
|
||||
const isDialogCompatible =
|
||||
useNative &&
|
||||
Boolean(typeof window === "undefined" || globalThis.HTMLDialogElement)
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref) return
|
||||
if (ref.open && !open) {
|
||||
ref.close()
|
||||
} else if (!ref.open && open) {
|
||||
ref.showModal()
|
||||
}
|
||||
}, [open, ref])
|
||||
|
||||
usePreventBodyScroll(open)
|
||||
const showContent = usePersistOpen(open)
|
||||
|
||||
const content = showContent ? (
|
||||
<ModalContent title={title} onClose={onClose} className={className}>
|
||||
{children}
|
||||
</ModalContent>
|
||||
) : null
|
||||
|
||||
if (isDialogCompatible) {
|
||||
return (
|
||||
<dialog
|
||||
className="modal rounded backdrop:backdrop-blur-[2px] backdrop:backdrop-contrast-75 flex flex-col overflow-hidden text-polkadot-100 border-polkadot-100"
|
||||
ref={setRef}
|
||||
onClose={onClose}
|
||||
>
|
||||
<ModalRefContext.Provider value={ref}>
|
||||
{content}
|
||||
</ModalRefContext.Provider>
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Portal node={document.body}>
|
||||
<ModalPolyfill open={open} onClose={onClose}>
|
||||
{content}
|
||||
</ModalPolyfill>
|
||||
</Portal>
|
||||
)
|
||||
}
|
||||
|
||||
const ModalPolyfill: FC<ModalProps> = ({ open, children, onClose }) => {
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (evt: KeyboardEvent) => {
|
||||
if (evt.key === "Escape") onClose?.()
|
||||
}
|
||||
document.addEventListener("keydown", handleKeyDown)
|
||||
return () => document.removeEventListener("keydown", handleKeyDown)
|
||||
}, [onClose])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="z-50 fixed left-0 top-0 w-full h-full backdrop-blur-[1px] bg-opacity-10 bg-slate-950 flex items-center justify-center overflow-hidden"
|
||||
onScroll={(evt) => {
|
||||
evt.stopPropagation()
|
||||
evt.preventDefault()
|
||||
}}
|
||||
>
|
||||
<div className="modal rounded bg-polkadot-900 flex flex-col overflow-hidden">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ModalContent: FC<
|
||||
PropsWithChildren<{
|
||||
title?: ReactNode
|
||||
onClose?: () => void
|
||||
className?: string
|
||||
}>
|
||||
> = ({ title, onClose, children, className }) => (
|
||||
<>
|
||||
<div className="px-2 py-1 border-b flex overflow-hidden min-w-[10rem] flex-shrink-0">
|
||||
<div className="flex-1 flex font-bold">{title}</div>
|
||||
<button
|
||||
type="button"
|
||||
className="flex-shrink-0 text-white hover:text-polkadot-300"
|
||||
onClick={onClose}
|
||||
>
|
||||
<XSquare />
|
||||
</button>
|
||||
</div>
|
||||
<div className={twMerge("p-2 flex flex-col overflow-auto", className)}>
|
||||
{children}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
|
||||
const usePreventBodyScroll = (open?: boolean) =>
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
document.body.style.overflow = "hidden"
|
||||
return () => {
|
||||
document.body.style.overflow = ""
|
||||
}
|
||||
}
|
||||
}, [open])
|
||||
|
||||
// Persists the `open` property to let the modal animate out before removing the children.
|
||||
const usePersistOpen = (open?: boolean) => {
|
||||
const [persist, setPersist] = useState(Boolean(open))
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setPersist(true)
|
||||
} else {
|
||||
const token = setTimeout(() => setPersist(false), 500)
|
||||
return () => clearTimeout(token)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
return open || persist
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useState } from "react"
|
||||
import { twMerge as clsx } from "tailwind-merge"
|
||||
import { ChevronDown, CheckIcon } from "lucide-react"
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
ComboboxOption,
|
||||
ComboboxOptions,
|
||||
ComboboxButton,
|
||||
} from "@headlessui/react"
|
||||
|
||||
export const SearchableSelect = <T,>({
|
||||
value,
|
||||
setValue,
|
||||
options,
|
||||
}: {
|
||||
value: T
|
||||
setValue: (val: T | null) => void
|
||||
options: { value: T; text: string }[]
|
||||
}) => {
|
||||
const [query, setQuery] = useState("")
|
||||
|
||||
const filteredOptions =
|
||||
query === ""
|
||||
? options
|
||||
: options.filter((option) => {
|
||||
return option.text.toLowerCase().includes(query.toLowerCase())
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Combobox
|
||||
value={value}
|
||||
onChange={(value) => setValue(value)}
|
||||
onClose={() => setQuery("")}
|
||||
>
|
||||
<div className="flex flex-row p-2 rounded border border-polkadot-200 text-white bg-black">
|
||||
<ComboboxInput
|
||||
className="text-ellipsis overflow-hidden whitespace-nowrap focus:outline-none"
|
||||
displayValue={(option: T) =>
|
||||
options.find((_option) => _option.value === option)?.text ?? ""
|
||||
}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Select"
|
||||
/>
|
||||
<ComboboxButton className="group">
|
||||
<ChevronDown className="size-4 " />
|
||||
</ComboboxButton>
|
||||
</div>
|
||||
|
||||
<ComboboxOptions
|
||||
anchor="bottom start"
|
||||
transition
|
||||
className={clsx(
|
||||
"max-h-96 rounded bg-black p-1 empty:invisible mt-2 -ml-4",
|
||||
"transition duration-100 ease-in data-[leave]:data-[closed]:opacity-0",
|
||||
)}
|
||||
>
|
||||
{filteredOptions
|
||||
.sort((a, b) => a.text.localeCompare(b.text))
|
||||
.map((option, idx) => (
|
||||
<ComboboxOption
|
||||
key={idx}
|
||||
value={option.value}
|
||||
className="group flex cursor-default items-center gap-2 rounded py-1.5 px-3 select-none data-[focus]:bg-white/10"
|
||||
>
|
||||
<CheckIcon className="invisible size-4 group-data-[selected]:visible" />
|
||||
<div className="text-sm text-white">{option.text}</div>
|
||||
</ComboboxOption>
|
||||
))}
|
||||
</ComboboxOptions>
|
||||
</Combobox>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { FC, ReactNode, useState } from "react"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export const TextInputField: FC<{
|
||||
className?: string
|
||||
error?: string | boolean | null
|
||||
softError?: string | boolean | null
|
||||
warn?: string | boolean | null
|
||||
placeholder?: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
children?: (inputElement: ReactNode) => ReactNode
|
||||
}> = ({
|
||||
className,
|
||||
error,
|
||||
softError,
|
||||
warn,
|
||||
value,
|
||||
placeholder,
|
||||
onChange,
|
||||
children = (v) => v,
|
||||
}) => {
|
||||
const [hasBlurred, blur] = useState(false)
|
||||
|
||||
return (
|
||||
<div className="flex gap-1 items-center">
|
||||
{children(
|
||||
<input
|
||||
className={twMerge(
|
||||
"text-sm border rounded p-2 border-polkadot-200 leading-tight text-white",
|
||||
warn ? "border-orange-400" : null,
|
||||
error ? "border-red-600" : null,
|
||||
className,
|
||||
)}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={(evt) => onChange(evt.target.value)}
|
||||
onFocus={() => blur(false)}
|
||||
onBlur={() => blur(true)}
|
||||
/>,
|
||||
)}
|
||||
{(hasBlurred || error) &&
|
||||
(typeof (error || softError) === "string" ? (
|
||||
<span className="text-red-600 text-sm">{error || softError}</span>
|
||||
) : typeof warn === "string" ? (
|
||||
<span className="text-orange-400 text-sm">{warn}</span>
|
||||
) : null)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as Toggle from "@radix-ui/react-toggle"
|
||||
|
||||
const SliderToggle: React.FC<{
|
||||
isToggled: boolean
|
||||
toggle: () => void
|
||||
}> = ({ isToggled, toggle }) => {
|
||||
return (
|
||||
<Toggle.Root
|
||||
pressed={isToggled}
|
||||
onPressedChange={() => toggle()}
|
||||
className={`relative w-8 h-5 rounded-full p-1 transition-colors
|
||||
${isToggled ? "bg-polkadot-400" : "bg-gray-400"}`}
|
||||
aria-label="Toggle"
|
||||
>
|
||||
<span
|
||||
className={`block w-3 h-3 bg-white rounded-full shadow-md transform transition-transform
|
||||
${isToggled ? "translate-x-3" : "translate-x-0"}`}
|
||||
/>
|
||||
</Toggle.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export default SliderToggle
|
||||
@@ -0,0 +1,4 @@
|
||||
<svg width="33" height="21" viewBox="0 0 33 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="0.75" y="1.25" width="31.5" height="18.5" rx="3.25" stroke="currentColor" stroke-width="1.5"/>
|
||||
<path d="M8.888 15.708C8.072 15.708 7.35467 15.5133 6.736 15.124C6.12267 14.7347 5.64533 14.148 5.304 13.364C4.96267 12.58 4.792 11.5933 4.792 10.404C4.792 9.22 4.96267 8.236 5.304 7.452C5.64533 6.668 6.12267 6.084 6.736 5.7C7.35467 5.316 8.072 5.124 8.888 5.124C9.69867 5.124 10.4107 5.316 11.024 5.7C11.6373 6.084 12.1147 6.668 12.456 7.452C12.8027 8.236 12.976 9.22 12.976 10.404C12.976 11.5933 12.8027 12.58 12.456 13.364C12.1147 14.148 11.6373 14.7347 11.024 15.124C10.4107 15.5133 9.69867 15.708 8.888 15.708ZM8.888 14.308C9.69867 14.308 10.32 13.972 10.752 13.3C11.1893 12.6227 11.408 11.6573 11.408 10.404C11.408 9.156 11.1893 8.19333 10.752 7.516C10.32 6.83867 9.69867 6.5 8.888 6.5C8.07733 6.5 7.45333 6.83867 7.016 7.516C6.584 8.19333 6.368 9.156 6.368 10.404C6.368 11.6573 6.584 12.6227 7.016 13.3C7.45333 13.972 8.07733 14.308 8.888 14.308ZM14.1096 15.5L17.0616 11.66L14.1096 7.78H15.9736L18.0456 10.508L20.0216 7.78H21.8776L18.9256 11.66L21.8696 15.5H20.0136L17.9336 12.764L15.9736 15.5H14.1096ZM22.6744 14.604C22.6744 14.3053 22.7757 14.052 22.9784 13.844C23.1864 13.636 23.4477 13.532 23.7624 13.532C24.077 13.532 24.3437 13.636 24.5624 13.844C24.781 14.052 24.8904 14.3053 24.8904 14.604C24.8904 14.8973 24.781 15.1453 24.5624 15.348C24.3437 15.5453 24.077 15.644 23.7624 15.644C23.4477 15.644 23.1864 15.5427 22.9784 15.34C22.7757 15.1373 22.6744 14.892 22.6744 14.604ZM25.7838 14.604C25.7838 14.3053 25.8851 14.052 26.0878 13.844C26.2958 13.636 26.5571 13.532 26.8718 13.532C27.1864 13.532 27.4531 13.636 27.6718 13.844C27.8904 14.052 27.9998 14.3053 27.9998 14.604C27.9998 14.8973 27.8904 15.1453 27.6718 15.348C27.4531 15.5453 27.1864 15.644 26.8718 15.644C26.5571 15.644 26.2958 15.5427 26.0878 15.34C25.8851 15.1373 25.7838 14.892 25.7838 14.604Z" fill="currentColor"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
@@ -0,0 +1,8 @@
|
||||
<svg width="24" height="22" viewBox="0 0 24 22" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<line x1="20.3398" y1="1.5" x2="2.33984" y2="1.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
<line x1="20.6719" y1="3.5" x2="20.6719" y2="1.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
<line x1="20.6719" y1="20.5" x2="20.6719" y2="18.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
<line x1="1.67188" y1="1.5" x2="1.67188" y2="20.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
<line x1="2.33984" y1="20.5" x2="20.3398" y2="20.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
<path d="M18.3398 15.5L14.0097 8L22.67 8L18.3398 15.5Z" fill="currentColor"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 756 B |
@@ -0,0 +1,5 @@
|
||||
<svg width="23" height="22" viewBox="0 0 23 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M0.591721 13.3593C0.201197 13.7498 0.201197 14.383 0.591721 14.7735L6.95568 21.1375C7.34621 21.528 7.97937 21.528 8.3699 21.1375C8.76042 20.7469 8.76042 20.1138 8.3699 19.7233L2.71304 14.0664L8.3699 8.40955C8.76042 8.01903 8.76042 7.38586 8.3699 6.99534C7.97937 6.60481 7.34621 6.60481 6.95568 6.99534L0.591721 13.3593ZM21.2988 13.0664L1.29883 13.0664V15.0664L21.2988 15.0664V13.0664Z" fill="currentColor"/>
|
||||
<path d="M13.7969 1.93359H21.2969" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
<line x1="21.4609" y1="2" x2="21.4609" y2="14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 730 B |
@@ -0,0 +1,48 @@
|
||||
/* standarize native modal */
|
||||
.modal {
|
||||
max-width: calc(100% - 6px - 2em);
|
||||
max-height: calc(100% - 6px - 2em);
|
||||
}
|
||||
|
||||
dialog.modal[open] {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
dialog.modal {
|
||||
opacity: 0;
|
||||
transform: translateY(30px);
|
||||
transition:
|
||||
opacity 0.3s ease-out,
|
||||
transform 0.3s ease-out,
|
||||
overlay 0.3s ease-out allow-discrete,
|
||||
display 0.3s ease-out allow-discrete;
|
||||
}
|
||||
|
||||
@starting-style {
|
||||
dialog.modal[open] {
|
||||
opacity: 0;
|
||||
transform: translateY(30px);
|
||||
}
|
||||
}
|
||||
|
||||
/* Transition the :backdrop when the dialog modal is promoted to the top layer */
|
||||
dialog.modal::backdrop {
|
||||
opacity: 0;
|
||||
transition:
|
||||
display 0.1s allow-discrete,
|
||||
overlay 0.1s allow-discrete,
|
||||
opacity 0.1s;
|
||||
}
|
||||
|
||||
dialog.modal[open]::backdrop {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* This starting-style rule cannot be nested inside the above selector
|
||||
because the nesting selector cannot represent pseudo-elements. */
|
||||
@starting-style {
|
||||
dialog.modal[open]::backdrop {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useRefEffect } from "./useRefEffect"
|
||||
|
||||
export const useHeightObserver = (onChange: (height: number) => void) =>
|
||||
useRefEffect<HTMLElement>(
|
||||
(element) => {
|
||||
const observer = new ResizeObserver((cb) => {
|
||||
onChange(cb[0]?.borderBoxSize[0]?.blockSize ?? 0)
|
||||
})
|
||||
|
||||
observer.observe(element)
|
||||
return () => {
|
||||
observer.unobserve(element)
|
||||
observer.disconnect()
|
||||
}
|
||||
},
|
||||
[onChange],
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useCallback, useEffect, useRef } from "react"
|
||||
|
||||
export const useRefEffect = <T extends any>(
|
||||
effect: (value: T) => () => void,
|
||||
deps: any[] = [],
|
||||
) => {
|
||||
const ref = useRef<[(() => void) | null, T] | null>(null)
|
||||
const setRef = useCallback((value: T | null) => {
|
||||
if (ref.current?.[0]) {
|
||||
ref.current?.[0]()
|
||||
}
|
||||
ref.current = value ? [effect(value), value] : null
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (ref.current && !ref.current[0]) {
|
||||
ref.current[0] = effect(ref.current[1])
|
||||
}
|
||||
return () => {
|
||||
if (ref.current) {
|
||||
ref.current[0]?.()
|
||||
ref.current[0] = null
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, deps)
|
||||
|
||||
return setRef
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { NOTIN } from "@codec-components"
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react"
|
||||
|
||||
export const useGenericSynchronizeInput = <T extends unknown, R>(
|
||||
value: T | NOTIN,
|
||||
onValueChanged: (value: T | NOTIN) => void,
|
||||
parseValue: (value: R) => T | NOTIN,
|
||||
defaultValue: R,
|
||||
serializeValue: (value: T) => R,
|
||||
eqFn: (input: R, value: T | NOTIN) => boolean,
|
||||
) => {
|
||||
const [inputValue, setInputValue] = useState<R>(defaultValue)
|
||||
const values = useRef({
|
||||
editor: value,
|
||||
input: inputValue,
|
||||
})
|
||||
|
||||
useLayoutEffect(() => {
|
||||
values.current.editor = value
|
||||
if (!eqFn(values.current.input, value)) {
|
||||
setInputValue(value === NOTIN ? defaultValue : serializeValue(value))
|
||||
}
|
||||
}, [value])
|
||||
|
||||
useEffect(() => {
|
||||
values.current.input = inputValue
|
||||
const parsed = parseValue(inputValue)
|
||||
if (parsed !== values.current.editor) {
|
||||
onValueChanged(parsed)
|
||||
}
|
||||
}, [inputValue])
|
||||
|
||||
return [inputValue, setInputValue] as const
|
||||
}
|
||||
|
||||
export const useSynchronizeInput = <T extends unknown>(
|
||||
value: T | NOTIN,
|
||||
onValueChanged: (value: T | NOTIN) => void,
|
||||
parseValue: (value: string) => T | NOTIN,
|
||||
) =>
|
||||
useGenericSynchronizeInput(
|
||||
value,
|
||||
onValueChanged,
|
||||
parseValue,
|
||||
"",
|
||||
String,
|
||||
(input, value) => parseValue(input) === value,
|
||||
)
|
||||
@@ -1,3 +1,18 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
input, dialog {
|
||||
@apply bg-black
|
||||
}
|
||||
|
||||
|
||||
.visible_when_parent_hover {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: 0.2s opacity;
|
||||
}
|
||||
*:hover > .visible_when_parent_hover {
|
||||
opacity: 1;
|
||||
pointer-events: all;
|
||||
}
|
||||
|
||||
@@ -369,7 +369,7 @@ export function getViewCodecComponent(
|
||||
switch (entry.type) {
|
||||
case "compact": {
|
||||
ResultComponent = entry.isBig ? CBigNumber : CNumber
|
||||
type = (entry as any).size
|
||||
type = (entry as any).size ?? "u128"
|
||||
break
|
||||
}
|
||||
case "primitive": {
|
||||
@@ -833,7 +833,7 @@ export function getCodecComponent(
|
||||
switch (entry.type) {
|
||||
case "compact": {
|
||||
ResultComponent = entry.isBig ? CBigNumber : CNumber
|
||||
type = (entry as any).size
|
||||
type = (entry as any).size ?? "u128"
|
||||
break
|
||||
}
|
||||
case "primitive": {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Binary } from "@polkadot-api/substrate-bindings"
|
||||
import { Download, FileUp } from "lucide-react"
|
||||
import { FC, useState } from "react"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { useGenericSynchronizeInput } from "@/components/useSynchroniseInput"
|
||||
import { NOTIN } from "@codec-components"
|
||||
import {
|
||||
BinaryFileInput,
|
||||
checkEqualInputBinary,
|
||||
} from "@/components/BinaryInput"
|
||||
import { Modal } from "@/components/Modal"
|
||||
// @ts-expect-error save-as typings not available
|
||||
import { saveAs } from "save-as"
|
||||
import { BinaryStatus } from "./EditCodec/Tree/codec-components"
|
||||
|
||||
export const BinaryEditModal: FC<{
|
||||
status: BinaryStatus
|
||||
open: boolean
|
||||
path: string
|
||||
onClose: () => void
|
||||
}> = ({ status, path, open, onClose }) => (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="Edit Binary"
|
||||
className="gap-2 text-xs min-w-96 max-w-xl"
|
||||
>
|
||||
<span className="overflow-hidden text-ellipsis whitespace-nowrap">
|
||||
{path}
|
||||
</span>
|
||||
<BinaryEditModalContent path={path} status={status} onClose={onClose} />
|
||||
</Modal>
|
||||
)
|
||||
|
||||
const MAX_DISPLAY_SIZE = 5 * 1024 * 1024
|
||||
const BinaryEditModalContent: FC<{
|
||||
path: string
|
||||
status: BinaryStatus
|
||||
onClose: () => void
|
||||
}> = ({ path, status, onClose }) => {
|
||||
const [value, setValue] = useState(status.encodedValue ?? new Uint8Array())
|
||||
const [error, setError] = useState("")
|
||||
const [inputValue, setInputValue] = useGenericSynchronizeInput(
|
||||
value,
|
||||
setValue as any,
|
||||
(input) => parseInput(input).asBytes(),
|
||||
"" as string | Uint8Array,
|
||||
(value) => {
|
||||
if (value.length > MAX_DISPLAY_SIZE) return ""
|
||||
return Binary.fromBytes(value).asHex()
|
||||
},
|
||||
(input, value) =>
|
||||
checkEqualInputBinary(
|
||||
parseInput(input),
|
||||
value === NOTIN ? NOTIN : Binary.fromBytes(value),
|
||||
),
|
||||
)
|
||||
|
||||
const placeholder =
|
||||
value.length > MAX_DISPLAY_SIZE ? "(value is too long to display)" : ""
|
||||
const isValid = status.decode(value) !== NOTIN
|
||||
const textareaValue = inputValue instanceof Uint8Array ? "" : inputValue
|
||||
|
||||
const submit = () => {
|
||||
if (status.decode(value) !== NOTIN) {
|
||||
status.onValueChanged(status.decode(value))
|
||||
onClose()
|
||||
} else {
|
||||
// Shouldn't happen, but it's better than just swallowing that it failed.
|
||||
setError("Couldn't set the binary data 😢")
|
||||
}
|
||||
}
|
||||
|
||||
const validateFile = (file: File) => {
|
||||
if (file.size > 512 * 1024 * 1024) {
|
||||
setError("File size can't exceed 512MB")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const downloadDisabled = value.length === 0
|
||||
const download = () => {
|
||||
saveAs(
|
||||
new Blob([value], {
|
||||
type: "application/octet-stream",
|
||||
}),
|
||||
`${path.replace(/\./g, "__") || "root"}.dat`,
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex gap-4 text-white">
|
||||
<div className="flex-1 flex gap-2">
|
||||
<button
|
||||
disabled={downloadDisabled}
|
||||
className={twMerge(
|
||||
"flex items-center gap-1 hover:text-polkadot-300",
|
||||
downloadDisabled && "opacity-50 pointer-events-none",
|
||||
)}
|
||||
onClick={download}
|
||||
>
|
||||
<Download size={16} />
|
||||
Download
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<label className="flex items-center gap-1 hover:text-polkadot-300 cursor-pointer">
|
||||
Load file
|
||||
<FileUp size={16} />
|
||||
<BinaryFileInput
|
||||
validate={validateFile}
|
||||
onError={() => setError("Error loading file")}
|
||||
onLoaded={(value) => setValue(value.asBytes())}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-slate-400">Hex data</div>
|
||||
<textarea
|
||||
className={twMerge(
|
||||
"bg-white rounded w-full min-h-20 text-slate-950 p-1 tabular-nums border-2 border-transparent",
|
||||
!isValid && "border-red-600 outline-none",
|
||||
)}
|
||||
value={textareaValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
className={twMerge(
|
||||
"border rounded p-1 text-white",
|
||||
!isValid && "opacity-50",
|
||||
)}
|
||||
onClick={submit}
|
||||
>
|
||||
OK
|
||||
</button>
|
||||
{error && <p className="text-red-600">{error}</p>}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const parseInput = (value: string | Uint8Array) =>
|
||||
value instanceof Uint8Array
|
||||
? Binary.fromBytes(value)
|
||||
: Binary.fromHex(value.startsWith("0x") ? value : `0x${value}`)
|
||||
@@ -0,0 +1,41 @@
|
||||
import {
|
||||
SS58String,
|
||||
getSs58AddressInfo,
|
||||
} from "@polkadot-api/substrate-bindings"
|
||||
import { EditAccountId, NOTIN } from "@codec-components"
|
||||
import { TextInputField } from "./codec-components"
|
||||
import { useSynchronizeInput } from "@/components/useSynchroniseInput"
|
||||
|
||||
export const CAccountId: EditAccountId = ({ value, onValueChanged }) => {
|
||||
const [localInput, setLocalInput] = useSynchronizeInput(
|
||||
value,
|
||||
onValueChanged,
|
||||
parseValue,
|
||||
)
|
||||
|
||||
const invalid = getValidationError(localInput)
|
||||
return (
|
||||
<TextInputField
|
||||
value={localInput ?? ""}
|
||||
className="min-w-96"
|
||||
onChange={setLocalInput}
|
||||
placeholder="AccountId"
|
||||
warn={localInput === ""}
|
||||
softError={invalid}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const getValidationError = (value: string) => {
|
||||
if (value === "") return null
|
||||
const info = getSs58AddressInfo(value)
|
||||
return info.isValid &&
|
||||
(info.publicKey.length === 32 || info.publicKey.length === 32)
|
||||
? null
|
||||
: "Invalid address"
|
||||
}
|
||||
const parseValue = (value: string): SS58String | NOTIN => {
|
||||
if (value.trim() === "") return NOTIN
|
||||
if (getValidationError(value)) return NOTIN
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { EditBytes } from "@codec-components"
|
||||
import { BinaryInput } from "@/components/BinaryInput"
|
||||
|
||||
export const CBytes: EditBytes = ({ value, onValueChanged, len }) => (
|
||||
<BinaryInput encodedValue={value} onValueChanged={onValueChanged} len={len} />
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
import { SearchableSelect } from "@/components/Select"
|
||||
import { isEnumComplex, isEnumVoid } from "@/utils/shape"
|
||||
import { EditEnum, NOTIN } from "@codec-components"
|
||||
import { Marker } from "../common/Markers"
|
||||
import { useSubtreeFocus } from "../common/SubtreeFocus"
|
||||
|
||||
export const CEnum: EditEnum = ({
|
||||
type,
|
||||
value,
|
||||
tags,
|
||||
inner,
|
||||
shape,
|
||||
onValueChanged,
|
||||
path,
|
||||
}) => {
|
||||
const focus = useSubtreeFocus()
|
||||
const sub = focus.getNextPath(path)
|
||||
if (sub) {
|
||||
return inner
|
||||
}
|
||||
|
||||
const options = tags.map((t) => t.tag).sort()
|
||||
const getOptionType = (option: string) => {
|
||||
const innerType = shape.value[option]
|
||||
if (innerType.type !== "lookupEntry") return ""
|
||||
switch (innerType.value.type) {
|
||||
case "primitive":
|
||||
return ` (${innerType.value.value})`
|
||||
case "compact":
|
||||
return ` (${(innerType.value as any).size ?? "u128"})`
|
||||
case "AccountId20":
|
||||
case "AccountId32":
|
||||
return ` (${innerType.value.type})`
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
const isComplexShape = type !== "blank" && isEnumComplex(shape, value.type)
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
{value === NOTIN ? null : <Marker id={[...path, value.type]} />}
|
||||
<div className="flex flex-row flex-wrap text-sm items-center gap-2">
|
||||
<SearchableSelect
|
||||
setValue={(selected: string | null) => {
|
||||
if (selected && options.includes(selected)) {
|
||||
const value = isEnumVoid(shape, selected) ? null : NOTIN
|
||||
onValueChanged({ type: selected, value })
|
||||
}
|
||||
}}
|
||||
value={value === NOTIN ? "" : value.type + getOptionType(value.type)}
|
||||
options={options.map((option) => ({ text: option, value: option }))}
|
||||
/>
|
||||
{!isComplexShape && inner}
|
||||
</div>
|
||||
{isComplexShape && <div className="flex flex-col pt-1 ">{inner}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { EditSequence, NOTIN } from "@codec-components"
|
||||
import { CirclePlus } from "lucide-react"
|
||||
import { twMerge as clsx } from "tailwind-merge"
|
||||
import { useSubtreeFocus } from "../common/SubtreeFocus"
|
||||
import { ListItem } from "./ListItem"
|
||||
|
||||
export const CSequence: EditSequence = ({
|
||||
innerComponents,
|
||||
value,
|
||||
onValueChanged,
|
||||
path,
|
||||
}) => {
|
||||
const focus = useSubtreeFocus()
|
||||
const sub = focus.getNextPath(path)
|
||||
if (sub) {
|
||||
return innerComponents[Number(sub)]
|
||||
}
|
||||
|
||||
const addItem = () => {
|
||||
const curr = value !== NOTIN ? value.slice() : []
|
||||
|
||||
curr.push(NOTIN)
|
||||
onValueChanged([...curr])
|
||||
}
|
||||
|
||||
const removeItem = (idx: number) => {
|
||||
const curr = value !== NOTIN ? value.slice() : []
|
||||
curr.splice(idx, 1)
|
||||
onValueChanged([...curr])
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<ul>
|
||||
{innerComponents.map((item, idx) => (
|
||||
<ListItem
|
||||
key={idx}
|
||||
idx={idx}
|
||||
onDelete={() => {
|
||||
removeItem(idx)
|
||||
}}
|
||||
path={[...path, String(idx)]}
|
||||
>
|
||||
{item}
|
||||
</ListItem>
|
||||
))}
|
||||
</ul>
|
||||
<button
|
||||
className={clsx(
|
||||
"flex flex-row gap-2 border rounded-2xl py-1 px-3 mt-3",
|
||||
"hover:border-polkadot-400 hover:text-polkadot-400 hover:cursor-pointer",
|
||||
)}
|
||||
onClick={addItem}
|
||||
>
|
||||
add item <CirclePlus strokeWidth="1" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { withDefault } from "@/utils/default"
|
||||
import { EditStr } from "@codec-components"
|
||||
|
||||
export const CStr: EditStr = ({ value, onValueChanged }) => {
|
||||
return (
|
||||
<div>
|
||||
<input
|
||||
className="bg-gray-700 border-none hover:border-none outline-none text-right min-w-96"
|
||||
value={withDefault(value, "")}
|
||||
onChange={(evt) => {
|
||||
onValueChanged(evt.target.value)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { ExpandBtn } from "@/components/Expand"
|
||||
import { getFinalType } from "@/utils/shape"
|
||||
import { EditStruct } from "@codec-components"
|
||||
import { useStateObservable } from "@react-rxjs/core"
|
||||
import React from "react"
|
||||
import { twMerge as clsx, twMerge } from "tailwind-merge"
|
||||
import { Marker } from "../common/Markers"
|
||||
import { useSubtreeFocus } from "../common/SubtreeFocus"
|
||||
import {
|
||||
isActive$,
|
||||
isCollapsed$,
|
||||
setHovered,
|
||||
toggleCollapsed,
|
||||
} from "../common/paths.state"
|
||||
|
||||
const StructItem: React.FC<{
|
||||
name: string
|
||||
children: React.ReactNode
|
||||
path: string[]
|
||||
type?: string
|
||||
}> = ({ name, children, path, type }) => {
|
||||
const pathStr = path.join(".")
|
||||
const isActive = useStateObservable(isActive$(pathStr))
|
||||
const isExpanded = !useStateObservable(isCollapsed$(pathStr))
|
||||
|
||||
return (
|
||||
<li
|
||||
className={twMerge(
|
||||
"flex flex-col transition-all duration-300",
|
||||
isActive && "backdrop-brightness-150",
|
||||
)}
|
||||
onMouseEnter={() => setHovered({ id: pathStr, hover: true })}
|
||||
onMouseLeave={() => setHovered({ id: pathStr, hover: false })}
|
||||
>
|
||||
<Marker id={path} />
|
||||
<span
|
||||
onClick={() => toggleCollapsed(pathStr)}
|
||||
className="cursor-pointer flex select-none items-center py-1 gap-1"
|
||||
>
|
||||
<ExpandBtn expanded={isExpanded} />
|
||||
{name}
|
||||
{type && (
|
||||
<div className="ml-1">
|
||||
<span className="text-slate-400 text-xs">({type})</span>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
<div
|
||||
className={clsx(
|
||||
"flex flex-row pl-4 pr-2 pb-2",
|
||||
isExpanded ? "" : "hidden",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
export const CStruct: EditStruct = ({ innerComponents, path, shape }) => {
|
||||
const focus = useSubtreeFocus()
|
||||
const sub = focus.getNextPath(path)
|
||||
if (sub) {
|
||||
const field = Object.entries(innerComponents).find(([key]) => key === sub)
|
||||
return field?.[1]
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col text-left">
|
||||
<ul className="flex flex-col">
|
||||
{Object.entries(innerComponents).map(([name, jsx]) => (
|
||||
<StructItem
|
||||
name={name}
|
||||
key={name}
|
||||
path={[...path, name]}
|
||||
type={getFinalType(shape, name)}
|
||||
>
|
||||
{jsx}
|
||||
</StructItem>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useSubtreeFocus } from "../common/SubtreeFocus"
|
||||
import { EditTuple } from "@codec-components"
|
||||
|
||||
export const CTuple: EditTuple = ({ innerComponents, path }) => {
|
||||
const focus = useSubtreeFocus()
|
||||
const sub = focus.getNextPath(path)
|
||||
if (sub) {
|
||||
return innerComponents[Number(sub)]
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<span>Tuple</span>
|
||||
<ul className="flex flex-col ml-5">
|
||||
{innerComponents.map((jsx, idx) => (
|
||||
<li key={idx}>{jsx}</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/* eslint-disable react-hooks/rules-of-hooks */
|
||||
import { FC } from "react"
|
||||
import {
|
||||
EditBigNumber,
|
||||
EditBigNumberInterface,
|
||||
EditNumber,
|
||||
EditNumberInterface,
|
||||
NOTIN,
|
||||
} from "@codec-components"
|
||||
import { TextInputField } from "./codec-components"
|
||||
import { useSynchronizeInput } from "@/components/useSynchroniseInput"
|
||||
|
||||
const NumericEdit =
|
||||
<T extends number | bigint>(
|
||||
parseValue: (value: string) => T | NOTIN,
|
||||
): FC<T extends bigint ? EditBigNumberInterface : EditNumberInterface> =>
|
||||
({ value, onValueChanged, numType }) => {
|
||||
const getValidation = (value: string) => {
|
||||
const sign = numType.substring(0, 1)
|
||||
const size = Number(numType.substring(1))
|
||||
|
||||
const maxValue = sign === "i" ? 2 ** size / 2 - 1 : 2 ** size - 1
|
||||
const minValue = sign === "i" ? -(2 ** size / 2) : 0
|
||||
|
||||
const parsed = parseValue(value)
|
||||
if (parsed === NOTIN) return null
|
||||
if (parsed > maxValue) return "Too high. Max is " + maxValue
|
||||
if (parsed < minValue) return "Too low. Min is " + minValue
|
||||
return null
|
||||
}
|
||||
|
||||
const [inputValue, setInputValue] = useSynchronizeInput(
|
||||
value as any,
|
||||
onValueChanged as any,
|
||||
(v) => (getValidation(v) ? NOTIN : parseValue(v)),
|
||||
)
|
||||
|
||||
return (
|
||||
<TextInputField
|
||||
value={inputValue}
|
||||
onChange={setInputValue}
|
||||
placeholder={numType}
|
||||
warn={parseValue(inputValue) === NOTIN}
|
||||
error={getValidation(inputValue)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const CNumber: EditNumber = NumericEdit((value: string) => {
|
||||
const parsed = Number(value)
|
||||
return value.trim() === "" || Number.isSafeInteger(parsed) ? NOTIN : parsed
|
||||
})
|
||||
export const CBigNumber: EditBigNumber = NumericEdit((value: string) => {
|
||||
try {
|
||||
return value.trim() === "" ? NOTIN : BigInt(value)
|
||||
} catch (_) {
|
||||
return NOTIN
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { ExpandBtn } from "@/components/Expand"
|
||||
import { useStateObservable } from "@react-rxjs/core"
|
||||
import { Trash2 } from "lucide-react"
|
||||
import { twMerge as clsx } from "tailwind-merge"
|
||||
import { Marker } from "../common/Markers"
|
||||
import { isCollapsed$, toggleCollapsed } from "../common/paths.state"
|
||||
|
||||
export const ListItem: React.FC<{
|
||||
idx: number
|
||||
children: React.ReactNode
|
||||
path: string[]
|
||||
onDelete?: () => void
|
||||
}> = ({ idx, onDelete, children, path }) => {
|
||||
const pathStr = path.join(".")
|
||||
const isCollapsed = useStateObservable(isCollapsed$(pathStr))
|
||||
|
||||
return (
|
||||
<li className="flex flex-col mb-1">
|
||||
<div className="flex items-stretch">
|
||||
<Marker id={path} />
|
||||
<span
|
||||
className="cursor-pointer flex items-center py-1 gap-1"
|
||||
onClick={() => toggleCollapsed(pathStr)}
|
||||
>
|
||||
<ExpandBtn expanded={!isCollapsed} />
|
||||
Item {idx + 1}.
|
||||
</span>
|
||||
{onDelete ? (
|
||||
<button
|
||||
className="cursor-pointer text-gray-200 ml-2 hover:text-polkadot-400"
|
||||
onClick={() => onDelete()}
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
className={clsx(
|
||||
"flex-row p-2 items-center border border-polkadot-700 rounded ",
|
||||
isCollapsed ? "hidden" : "",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Enum } from "@/components/Icons"
|
||||
import { isComplex } from "@/utils/shape"
|
||||
import { EditEnum, NOTIN } from "@codec-components"
|
||||
import { useContext, useLayoutEffect, useState } from "react"
|
||||
import { Portal } from "react-portal"
|
||||
import { scrollToMarker } from "../../common/scroll"
|
||||
import { useSubtreeFocus } from "../../common/SubtreeFocus"
|
||||
import {
|
||||
ChildrenProviders,
|
||||
ItemTitle,
|
||||
TitleContext,
|
||||
useReportBinaryStatus,
|
||||
} from "./codec-components"
|
||||
|
||||
export const CEnum: EditEnum = ({
|
||||
value,
|
||||
inner,
|
||||
path,
|
||||
shape,
|
||||
type,
|
||||
encodedValue,
|
||||
onValueChanged,
|
||||
decode,
|
||||
}) => {
|
||||
const className =
|
||||
"text-polkadot-200 hover:text-polkadot-400 cursor-pointer whitespace-nowrap [&:not(:first-child)]:ml-1"
|
||||
|
||||
const titleContainer = useContext(TitleContext)
|
||||
const titleElement = useAppendTitle(titleContainer, className)
|
||||
useReportBinaryStatus(type, encodedValue, onValueChanged, decode)
|
||||
// We create a title element for the children below if we don't have a parent.
|
||||
const [newElement, setNewElement] = useState<HTMLElement | null>(null)
|
||||
const focus = useSubtreeFocus()
|
||||
const sub = focus.getNextPath(path)
|
||||
if (sub) {
|
||||
return inner
|
||||
}
|
||||
|
||||
if (value === NOTIN) return null
|
||||
|
||||
const innerPath = [...path, value.type]
|
||||
if (titleContainer) {
|
||||
return (
|
||||
<>
|
||||
{titleElement ? (
|
||||
<Portal node={titleElement}>
|
||||
<span onClick={() => scrollToMarker(innerPath)}>
|
||||
/ {value.type}
|
||||
</span>
|
||||
</Portal>
|
||||
) : null}
|
||||
<ChildrenProviders
|
||||
titleElement={titleContainer ?? newElement}
|
||||
onValueChange={() => {}}
|
||||
>
|
||||
{inner}
|
||||
</ChildrenProviders>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const innerShape = shape.value[value.type]
|
||||
const innerEntry =
|
||||
innerShape.type === "lookupEntry" ? innerShape.value : innerShape
|
||||
const innerIsComplex = isComplex(innerEntry.type)
|
||||
return (
|
||||
<div className="border-l border-polkadot-700">
|
||||
<ItemTitle
|
||||
icon={Enum}
|
||||
path={innerPath.join(".")}
|
||||
titleRef={setNewElement}
|
||||
onNavigate={() => scrollToMarker(innerPath)}
|
||||
onZoom={innerIsComplex ? () => focus.setFocus(innerPath) : undefined}
|
||||
binaryStatus={{
|
||||
encodedValue,
|
||||
onValueChanged,
|
||||
decode,
|
||||
type,
|
||||
}}
|
||||
>
|
||||
{value.type}
|
||||
</ItemTitle>
|
||||
<ChildrenProviders
|
||||
titleElement={titleContainer ?? newElement}
|
||||
onValueChange={() => {}}
|
||||
>
|
||||
<div className="pl-6">{inner}</div>
|
||||
</ChildrenProviders>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const useAppendTitle = (container: HTMLElement | null, className: string) => {
|
||||
const [element, setElement] = useState<HTMLElement | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!container) return
|
||||
|
||||
const element = document.createElement("span")
|
||||
container.appendChild(element)
|
||||
setElement(element)
|
||||
|
||||
return () => element.remove()
|
||||
}, [container])
|
||||
useLayoutEffect(() => {
|
||||
if (!element) return
|
||||
element.className = className ?? ""
|
||||
}, [element, className])
|
||||
|
||||
return element
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { lookupToType, TypeIcon, TypeIcons } from "@/components/Icons"
|
||||
import { isComplex } from "@/utils/shape"
|
||||
import { EditStruct } from "@codec-components"
|
||||
import { useStateObservable } from "@react-rxjs/core"
|
||||
import { FC, PropsWithChildren, useState } from "react"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { isCollapsedRoot$ } from "../../common/paths.state"
|
||||
import { scrollToMarker } from "../../common/scroll"
|
||||
import { useSubtreeFocus } from "../../common/SubtreeFocus"
|
||||
import {
|
||||
BinaryStatus,
|
||||
ChildrenProviders,
|
||||
ItemTitle,
|
||||
useReportBinaryStatus,
|
||||
} from "./codec-components"
|
||||
|
||||
const StructField: FC<
|
||||
PropsWithChildren<{
|
||||
label: string
|
||||
path: string
|
||||
icon: (typeof TypeIcons)[TypeIcon]
|
||||
onZoom?: () => void
|
||||
onNavigate?: () => void
|
||||
}>
|
||||
> = ({ label, children, onZoom, onNavigate, path, icon: Icon }) => {
|
||||
const [titleElement, setTitleElement] = useState<HTMLElement | null>(null)
|
||||
const [binaryStatus, setBinaryStatus] = useState<BinaryStatus>()
|
||||
const isCollapsed = useStateObservable(isCollapsedRoot$(path))
|
||||
|
||||
return (
|
||||
<div className="flex flex-col text-left border-l border-polkadot-700">
|
||||
<ItemTitle
|
||||
icon={Icon}
|
||||
path={path}
|
||||
onNavigate={onNavigate}
|
||||
titleRef={setTitleElement}
|
||||
onZoom={onZoom}
|
||||
binaryStatus={binaryStatus}
|
||||
className={isCollapsed ? "opacity-65" : ""}
|
||||
>
|
||||
{label}
|
||||
</ItemTitle>
|
||||
<div
|
||||
className={twMerge(
|
||||
"pl-6 transition-opacity",
|
||||
isCollapsed && "opacity-65",
|
||||
)}
|
||||
>
|
||||
<ChildrenProviders
|
||||
titleElement={titleElement}
|
||||
onValueChange={setBinaryStatus}
|
||||
>
|
||||
{children}
|
||||
</ChildrenProviders>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const CStruct: EditStruct = ({
|
||||
innerComponents,
|
||||
shape,
|
||||
path,
|
||||
type,
|
||||
encodedValue,
|
||||
onValueChanged,
|
||||
decode,
|
||||
}) => {
|
||||
const focus = useSubtreeFocus()
|
||||
useReportBinaryStatus(type, encodedValue, onValueChanged, decode)
|
||||
|
||||
const sub = focus.getNextPath(path)
|
||||
if (sub) {
|
||||
const field = Object.entries(innerComponents).find(([key]) => key === sub)
|
||||
return field?.[1]
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col text-left">
|
||||
{Object.entries(innerComponents).map(([key, jsx]) => {
|
||||
const innerShape = shape.value[key]
|
||||
const isComplexShape = isComplex(innerShape.type)
|
||||
const innerPath = [...path, key]
|
||||
|
||||
return (
|
||||
<StructField
|
||||
key={key}
|
||||
label={key}
|
||||
onZoom={
|
||||
isComplexShape || innerShape.type === "option"
|
||||
? () => focus.setFocus(innerPath)
|
||||
: undefined
|
||||
}
|
||||
onNavigate={() => scrollToMarker(innerPath)}
|
||||
path={innerPath.join(".")}
|
||||
icon={
|
||||
isComplexShape
|
||||
? TypeIcons.object
|
||||
: TypeIcons[lookupToType[innerShape.type]]
|
||||
}
|
||||
>
|
||||
{jsx}
|
||||
</StructField>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
import { TypeIcons } from "@/components/Icons"
|
||||
import { useHeightObserver } from "@/components/useHeightObserver"
|
||||
import {
|
||||
EditArray,
|
||||
EditComplexCodecComponentProps,
|
||||
EditSequence,
|
||||
EditTuple,
|
||||
NOTIN,
|
||||
} from "@codec-components"
|
||||
import { useStateObservable } from "@react-rxjs/core"
|
||||
import { GripVertical, Trash2 } from "lucide-react"
|
||||
import React, {
|
||||
FC,
|
||||
PropsWithChildren,
|
||||
ReactNode,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { isCollapsedRoot$ } from "../../common/paths.state"
|
||||
import { scrollToMarker } from "../../common/scroll"
|
||||
import { useSubtreeFocus } from "../../common/SubtreeFocus"
|
||||
import {
|
||||
BinaryStatus,
|
||||
ChildrenProviders,
|
||||
ItemTitle,
|
||||
useReportBinaryStatus,
|
||||
} from "./codec-components"
|
||||
|
||||
export const CSequence: EditSequence = (props) => (
|
||||
<ListDisplay {...props} rearrange />
|
||||
)
|
||||
|
||||
export const CArray: EditArray = (props) => (
|
||||
<ListDisplay {...props} fixedLength rearrange />
|
||||
)
|
||||
|
||||
export const CTuple: EditTuple = (props) => (
|
||||
<ListDisplay {...props} fixedLength />
|
||||
)
|
||||
|
||||
interface DragProps {
|
||||
onMeasure: (height: number) => void
|
||||
onDragStart: () => void
|
||||
onDragMove: (offset: number) => void
|
||||
onDragEnd: (offset: number) => void
|
||||
rearranging: boolean
|
||||
translation: number
|
||||
}
|
||||
|
||||
export const ListDisplay: React.FC<
|
||||
EditComplexCodecComponentProps<unknown[]> & {
|
||||
innerComponents: ReactNode[]
|
||||
fixedLength?: boolean
|
||||
rearrange?: boolean
|
||||
}
|
||||
> = (props) => {
|
||||
const {
|
||||
innerComponents,
|
||||
fixedLength,
|
||||
type,
|
||||
onValueChanged,
|
||||
value,
|
||||
path,
|
||||
encodedValue,
|
||||
decode,
|
||||
rearrange = false,
|
||||
} = props
|
||||
const drag = useDrag(rearrange, props)
|
||||
const focus = useSubtreeFocus()
|
||||
useReportBinaryStatus(type, encodedValue, onValueChanged, decode)
|
||||
const sub = focus.getNextPath(path)
|
||||
if (sub) {
|
||||
return innerComponents[Number(sub)]
|
||||
}
|
||||
|
||||
const onDelete = (idx: number) => {
|
||||
if (value === NOTIN) return
|
||||
onValueChanged(value.filter((_, i) => i !== idx))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-l border-polkadot-700">
|
||||
{innerComponents.map((component, idx) => {
|
||||
const innerPath = [...path, String(idx)]
|
||||
|
||||
return (
|
||||
<ListItem
|
||||
key={idx}
|
||||
idx={idx}
|
||||
path={innerPath.join(".")}
|
||||
onDelete={fixedLength ? undefined : () => onDelete(idx)}
|
||||
editable={type !== "blank"}
|
||||
drag={drag?.(idx)}
|
||||
onZoom={() => focus.setFocus(innerPath)}
|
||||
onNavigate={() => scrollToMarker(innerPath)}
|
||||
>
|
||||
{component}
|
||||
</ListItem>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const noop = () => {}
|
||||
const ListItem: FC<
|
||||
PropsWithChildren<{
|
||||
idx: number
|
||||
path: string
|
||||
editable?: boolean
|
||||
onDelete?: () => void
|
||||
onZoom?: () => void
|
||||
onNavigate?: () => void
|
||||
drag?: DragProps
|
||||
}>
|
||||
> = ({
|
||||
idx,
|
||||
children,
|
||||
path,
|
||||
editable = true,
|
||||
onDelete,
|
||||
drag,
|
||||
onZoom,
|
||||
onNavigate,
|
||||
}) => {
|
||||
const [titleElement, setTitleElement] = useState<HTMLElement | null>(null)
|
||||
const [binaryStatus, setBinaryStatus] = useState<BinaryStatus>()
|
||||
const ref = useHeightObserver(drag?.onMeasure ?? noop)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const isCollapsed = useStateObservable(isCollapsedRoot$(path))
|
||||
|
||||
const startDrag = (evt: React.MouseEvent) => {
|
||||
if (!drag || isDragging) return
|
||||
|
||||
setIsDragging(true)
|
||||
drag.onDragStart()
|
||||
|
||||
const start = evt.pageY
|
||||
const mouseMoveHandler = (evt: MouseEvent) => {
|
||||
drag.onDragMove(evt.pageY - start)
|
||||
}
|
||||
const mouseUpHandler = (evt: MouseEvent) => {
|
||||
document.removeEventListener("mouseup", mouseUpHandler)
|
||||
document.removeEventListener("mousemove", mouseMoveHandler)
|
||||
drag.onDragEnd(evt.pageY - start)
|
||||
setIsDragging(false)
|
||||
}
|
||||
document.addEventListener("mousemove", mouseMoveHandler)
|
||||
document.addEventListener("mouseup", mouseUpHandler)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={drag ? ref : undefined}
|
||||
className={twMerge(
|
||||
"hover:bg-[#100c35]",
|
||||
drag?.rearranging && "relative",
|
||||
isDragging && "none select-none z-10 bg-[#100c35]",
|
||||
!isDragging && drag?.rearranging && "transition-transform",
|
||||
)}
|
||||
style={{
|
||||
transform: drag?.translation
|
||||
? `translateY(${drag.translation}px)`
|
||||
: undefined,
|
||||
}}
|
||||
>
|
||||
<ItemTitle
|
||||
path={path}
|
||||
icon={TypeIcons.list}
|
||||
titleRef={setTitleElement}
|
||||
onZoom={onZoom}
|
||||
onNavigate={onNavigate}
|
||||
binaryStatus={binaryStatus}
|
||||
className={isCollapsed ? "opacity-65" : ""}
|
||||
actions={
|
||||
<>
|
||||
{onDelete && (
|
||||
<button
|
||||
className={editable ? "cursor-pointer" : "opacity-50"}
|
||||
disabled={!editable}
|
||||
onClick={onDelete}
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
)}
|
||||
{drag && (
|
||||
<div
|
||||
className={
|
||||
editable
|
||||
? isDragging
|
||||
? "cursor-grabbing"
|
||||
: "cursor-grab"
|
||||
: "opacity-50"
|
||||
}
|
||||
onMouseDown={startDrag}
|
||||
>
|
||||
<GripVertical size={16} />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{idx + 1}
|
||||
</ItemTitle>
|
||||
<div
|
||||
className={twMerge(
|
||||
"pl-6 pb-1 transition-opacity",
|
||||
isCollapsed && "opacity-65",
|
||||
)}
|
||||
>
|
||||
<ChildrenProviders
|
||||
titleElement={titleElement}
|
||||
onValueChange={setBinaryStatus}
|
||||
>
|
||||
{children}
|
||||
</ChildrenProviders>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const useDrag = (
|
||||
rearrange: boolean,
|
||||
props: EditComplexCodecComponentProps<unknown[]>,
|
||||
): ((idx: number) => DragProps) | undefined => {
|
||||
const itemHeights = useRef<number[]>([])
|
||||
const [translations, setTranslations] = useState<number[]>([])
|
||||
|
||||
// react stuff... We don't want to keep recreating ResizeObservers on each render, so we prefer having a stable reference.
|
||||
const measureCallbacks = useRef<Array<(height: number) => void>>([])
|
||||
const onMeasure = (idx: number) =>
|
||||
(measureCallbacks.current[idx] ??= (height) =>
|
||||
(itemHeights.current[idx] = height))
|
||||
|
||||
if (!rearrange) {
|
||||
return undefined
|
||||
}
|
||||
if (props.value === NOTIN) {
|
||||
// The component might give us "NOTIN" temporarily while it's initializing.
|
||||
// if we return undefined, then we will miss the "onMeasure" callback of when
|
||||
// each item is initialized, so we just return the function to capture measurements
|
||||
return (idx: number) => ({
|
||||
onDragEnd() {},
|
||||
onDragMove() {},
|
||||
onDragStart() {},
|
||||
onMeasure: onMeasure(idx),
|
||||
translation: translations[idx] ?? 0,
|
||||
rearranging: translations.some((t) => t !== 0),
|
||||
})
|
||||
}
|
||||
if (props.value.length <= 1) return undefined
|
||||
|
||||
const getHeightSums = () =>
|
||||
itemHeights.current.reduce(
|
||||
(acc: number[], height, idx) => [...acc, (acc[idx - 1] ?? 0) + height],
|
||||
[],
|
||||
)
|
||||
|
||||
const getNewIdx = (idx: number, yOffset: number) => {
|
||||
const heights = itemHeights.current
|
||||
const heightSums = getHeightSums()
|
||||
|
||||
// What feels most natural is for the element to switch when the top edge
|
||||
// reaches the mid of the previous one, and the bottom edge reaches the
|
||||
// mid of the second one
|
||||
const relevantEdge = heightSums[yOffset >= 0 ? idx : idx - 1] ?? 0
|
||||
const mids = props.value.map(
|
||||
(_, idx) => (heightSums[idx - 1] ?? 0) + heights[idx] / 2,
|
||||
)
|
||||
|
||||
const movedEdge = relevantEdge + yOffset
|
||||
const _biggerIdx = mids.findIndex((sum) => sum >= movedEdge)
|
||||
const biggerIdx = _biggerIdx < 0 ? props.value.length : _biggerIdx
|
||||
|
||||
return yOffset >= 0 ? biggerIdx - 1 : biggerIdx
|
||||
}
|
||||
|
||||
return (idx: number) => ({
|
||||
onDragEnd(yOffset) {
|
||||
const newIdx = getNewIdx(idx, yOffset)
|
||||
if (newIdx !== idx) {
|
||||
const newValue = [...props.value]
|
||||
const [element] = newValue.splice(idx, 1)
|
||||
newValue.splice(newIdx, 0, element)
|
||||
const result = newValue.filter((v) => v !== null)
|
||||
|
||||
props.onValueChanged(result)
|
||||
}
|
||||
setTranslations(props.value.map(() => 0))
|
||||
},
|
||||
onDragMove(yOffset) {
|
||||
const newIdx = getNewIdx(idx, yOffset)
|
||||
const currentHeight = itemHeights.current[idx]
|
||||
|
||||
const translations = props.value.map((_, otherIdx) => {
|
||||
if (otherIdx === idx) {
|
||||
const heightSums = getHeightSums()
|
||||
|
||||
return Math.min(
|
||||
Math.max(-(heightSums[idx - 1] ?? 0), yOffset),
|
||||
heightSums[heightSums.length - 1] - heightSums[idx],
|
||||
)
|
||||
}
|
||||
if (otherIdx < idx) {
|
||||
return otherIdx < newIdx ? 0 : currentHeight
|
||||
}
|
||||
return otherIdx > newIdx ? 0 : -currentHeight
|
||||
})
|
||||
setTranslations(translations)
|
||||
},
|
||||
onDragStart() {},
|
||||
onMeasure: onMeasure(idx),
|
||||
translation: translations[idx] ?? 0,
|
||||
rearranging: translations.some((t) => t !== 0),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import { BinaryEdit, Focus, TypeIcon, TypeIcons } from "@/components/Icons"
|
||||
import {
|
||||
EditAccountId,
|
||||
EditBigNumber,
|
||||
EditBool,
|
||||
EditBytes,
|
||||
EditEthAccount,
|
||||
EditNumber,
|
||||
EditOption,
|
||||
EditPrimitiveComponentProps,
|
||||
EditResult,
|
||||
EditStr,
|
||||
EditVoid,
|
||||
NOTIN,
|
||||
} from "@codec-components"
|
||||
import { HexString } from "@polkadot-api/substrate-bindings"
|
||||
import { useStateObservable } from "@react-rxjs/core"
|
||||
import { Circle } from "lucide-react"
|
||||
import {
|
||||
createContext,
|
||||
FC,
|
||||
PropsWithChildren,
|
||||
ReactElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { BinaryEditModal } from "../../BinaryEditModal"
|
||||
import { isActive$, setHovered } from "../../common/paths.state"
|
||||
|
||||
export const CVoid: EditVoid = () => null
|
||||
|
||||
const CPrimitive: FC<EditPrimitiveComponentProps<any>> = ({
|
||||
type,
|
||||
encodedValue,
|
||||
onValueChanged,
|
||||
decode,
|
||||
}) => {
|
||||
useReportBinaryStatus(type, encodedValue, onValueChanged, decode)
|
||||
return null
|
||||
}
|
||||
export const CBool: EditBool = CPrimitive
|
||||
export const CStr: EditStr = CPrimitive
|
||||
export const CEthAccount: EditEthAccount = CPrimitive
|
||||
export const CBigNumber: EditBigNumber = CPrimitive
|
||||
export const CNumber: EditNumber = CPrimitive
|
||||
export const CAccountId: EditAccountId = CPrimitive
|
||||
export const CBytes: EditBytes = CPrimitive
|
||||
|
||||
export const COption: EditOption = ({
|
||||
value,
|
||||
inner,
|
||||
type,
|
||||
encodedValue,
|
||||
onValueChanged,
|
||||
decode,
|
||||
}) => {
|
||||
useReportBinaryStatus(type, encodedValue, onValueChanged, decode)
|
||||
|
||||
return value === undefined ? null : (
|
||||
<BinaryStatusContext.Provider value={() => {}}>
|
||||
{inner}
|
||||
</BinaryStatusContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const CResult: EditResult = ({ value, inner }) => (
|
||||
<>
|
||||
{value !== NOTIN && (value.success ? "ok" : "ko")}-{inner}
|
||||
</>
|
||||
)
|
||||
|
||||
export const ItemMarker = () => (
|
||||
<span className="text-polkadot-700 translate-y-[-1.5px]">-</span>
|
||||
)
|
||||
|
||||
export const TitleContext = createContext<HTMLElement | null>(null)
|
||||
|
||||
export type BinaryStatus = {
|
||||
type: "blank" | "partial" | "complete"
|
||||
encodedValue: Uint8Array | undefined
|
||||
onValueChanged: (value: any | NOTIN) => boolean
|
||||
decode: (value: Uint8Array | HexString) => any | NOTIN
|
||||
}
|
||||
export const BinaryStatusContext = createContext<
|
||||
(status: BinaryStatus) => void
|
||||
>(() => {})
|
||||
|
||||
export const useReportBinaryStatus = (
|
||||
type: "blank" | "partial" | "complete",
|
||||
encodedValue: Uint8Array | undefined,
|
||||
onValueChanged: (value: any | NOTIN) => boolean,
|
||||
decode: (value: Uint8Array | HexString) => any | NOTIN,
|
||||
) => {
|
||||
const onBinChange = useContext(BinaryStatusContext)
|
||||
useLayoutEffect(
|
||||
() => onBinChange({ type, encodedValue, onValueChanged, decode }),
|
||||
[type, encodedValue, onValueChanged, decode, onBinChange],
|
||||
)
|
||||
}
|
||||
|
||||
export const ChildrenProviders: FC<
|
||||
PropsWithChildren<{
|
||||
onValueChange: (status: BinaryStatus) => void
|
||||
titleElement: HTMLElement | null
|
||||
}>
|
||||
> = ({ onValueChange, titleElement, children }) => (
|
||||
<TitleContext.Provider value={titleElement}>
|
||||
<BinaryStatusContext.Provider value={onValueChange}>
|
||||
{children}
|
||||
</BinaryStatusContext.Provider>
|
||||
</TitleContext.Provider>
|
||||
)
|
||||
|
||||
export const ItemTitle: FC<
|
||||
PropsWithChildren<{
|
||||
path: string
|
||||
icon: (typeof TypeIcons)[TypeIcon]
|
||||
binaryStatus?: BinaryStatus
|
||||
onNavigate?: () => void
|
||||
titleRef?: (element: HTMLDivElement) => void
|
||||
onZoom?: () => void
|
||||
actions?: ReactElement
|
||||
className?: string
|
||||
}>
|
||||
> = ({
|
||||
children,
|
||||
path,
|
||||
icon: Icon,
|
||||
binaryStatus,
|
||||
titleRef,
|
||||
onNavigate,
|
||||
onZoom,
|
||||
actions,
|
||||
className,
|
||||
}) => {
|
||||
const [binaryOpen, setBinaryOpen] = useState(false)
|
||||
const isActive = useStateObservable(isActive$(path))
|
||||
|
||||
// react listeners don't work across portals, we need native listeners
|
||||
const ref = useRef<HTMLDivElement | null>(null)
|
||||
useEffect(() => {
|
||||
if (!ref.current) return
|
||||
const element = ref.current
|
||||
const onMouseEnter = () => setHovered({ id: path, hover: true })
|
||||
const onMouseLeave = () => setHovered({ id: path, hover: false })
|
||||
|
||||
element.addEventListener("mouseenter", onMouseEnter)
|
||||
element.addEventListener("mouseleave", onMouseLeave)
|
||||
return () => {
|
||||
element.removeEventListener("mouseenter", onMouseEnter)
|
||||
element.removeEventListener("mouseleave", onMouseLeave)
|
||||
onMouseLeave()
|
||||
}
|
||||
}, [path])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
ref={ref}
|
||||
className={twMerge(
|
||||
"flex items-center",
|
||||
isActive && "bg-polkadot-600 bg-opacity-20",
|
||||
className,
|
||||
)}
|
||||
data-marker={`marker-${path}`}
|
||||
>
|
||||
<span
|
||||
className={twMerge(
|
||||
"hover:text-polkadot-400 flex-shrink-0 flex items-center",
|
||||
onNavigate && "cursor-pointer",
|
||||
)}
|
||||
onClick={onNavigate}
|
||||
>
|
||||
<ItemMarker />
|
||||
<Circle
|
||||
size={8}
|
||||
strokeWidth={4}
|
||||
className={twMerge(
|
||||
"mr-1",
|
||||
binaryStatus?.type === "blank" && "text-red-600",
|
||||
binaryStatus?.type === "partial" && "text-orange-600",
|
||||
binaryStatus?.type === "complete" && "text-green-600",
|
||||
binaryStatus === undefined && "text-slate-600",
|
||||
)}
|
||||
/>
|
||||
<Icon size={16} className="text-polkadot-600 mr-1" />
|
||||
{children}
|
||||
</span>
|
||||
<div
|
||||
ref={titleRef}
|
||||
className="flex flex-1 ml-1 flex-wrap leading-none"
|
||||
/>
|
||||
<div className="visible_when_parent_hover px-1 flex gap-1 items-center">
|
||||
{onZoom && binaryStatus && (
|
||||
<BinaryEdit
|
||||
size={18}
|
||||
className={twMerge("cursor-pointer hover:text-polkadot-300")}
|
||||
onClick={() => setBinaryOpen(true)}
|
||||
/>
|
||||
)}
|
||||
{onZoom && (
|
||||
<Focus
|
||||
className="cursor-pointer hover:text-polkadot-300"
|
||||
onClick={onZoom}
|
||||
/>
|
||||
)}
|
||||
{actions}
|
||||
</div>
|
||||
</div>
|
||||
{binaryStatus && (
|
||||
<BinaryEditModal
|
||||
status={binaryStatus}
|
||||
open={binaryOpen}
|
||||
path={path}
|
||||
onClose={() => setBinaryOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from "./CEnum"
|
||||
export * from "./CStruct"
|
||||
export * from "./codec-components"
|
||||
export * from "./ListComponents"
|
||||
@@ -0,0 +1,5 @@
|
||||
import { getCodecComponent } from "@codec-components"
|
||||
|
||||
import * as treeComponents from "./components"
|
||||
|
||||
export const TreeCodec = getCodecComponent(treeComponents)
|
||||
@@ -0,0 +1,144 @@
|
||||
import SliderToggle from "@/components/Toggle"
|
||||
import { withDefault } from "@/utils/default"
|
||||
import {
|
||||
EditArray,
|
||||
EditBool,
|
||||
EditEthAccount,
|
||||
EditOption,
|
||||
EditResult,
|
||||
EditVoid,
|
||||
NOTIN,
|
||||
} from "@codec-components"
|
||||
import { FC, ReactNode, useState } from "react"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { useSubtreeFocus } from "../common/SubtreeFocus"
|
||||
import { ListItem } from "./ListItem"
|
||||
|
||||
export const CBool: EditBool = ({ value, onValueChanged, path }) => {
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
<label>
|
||||
<input
|
||||
className="mr-1"
|
||||
type="radio"
|
||||
value="Yes"
|
||||
name={path.join(".")}
|
||||
checked={value === true}
|
||||
onChange={() => onValueChanged(true)}
|
||||
/>
|
||||
Yes
|
||||
</label>
|
||||
<label>
|
||||
<input
|
||||
className="mr-1"
|
||||
type="radio"
|
||||
value="No"
|
||||
name={path.join(".")}
|
||||
checked={value === false}
|
||||
onChange={() => onValueChanged(false)}
|
||||
/>
|
||||
No
|
||||
</label>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const CVoid: EditVoid = () => null
|
||||
|
||||
export const CEthAccount: EditEthAccount = ({ value }) => (
|
||||
<span>{withDefault(value, "")}</span>
|
||||
)
|
||||
|
||||
export const CArray: EditArray = ({ innerComponents, path }) => {
|
||||
const focus = useSubtreeFocus()
|
||||
const sub = focus.getNextPath(path)
|
||||
if (sub) {
|
||||
return innerComponents[Number(sub)]
|
||||
}
|
||||
|
||||
return (
|
||||
<ul>
|
||||
{innerComponents.map((jsx, idx) => (
|
||||
<ListItem key={idx} idx={idx} path={[...path, String(idx)]}>
|
||||
{jsx}
|
||||
</ListItem>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
export const COption: EditOption = ({ value, inner, onValueChanged }) => {
|
||||
const selected = value !== undefined
|
||||
return (
|
||||
<div>
|
||||
<label className="flex items-center gap-2 text-slate-300 py-1 mb-1">
|
||||
<SliderToggle
|
||||
isToggled={selected}
|
||||
toggle={() =>
|
||||
!selected ? onValueChanged(NOTIN) : onValueChanged(undefined)
|
||||
}
|
||||
/>
|
||||
<span className="text-sm">
|
||||
{selected ? "selected" : "not selected"}
|
||||
</span>
|
||||
</label>
|
||||
{inner}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const CResult: EditResult = ({ value, inner, type }) => {
|
||||
return type === "blank" ? null : (
|
||||
<>
|
||||
{value.success ? "ok" : "ko"}-{inner}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export const TextInputField: FC<{
|
||||
className?: string
|
||||
error?: string | boolean | null
|
||||
softError?: string | boolean | null
|
||||
warn?: string | boolean | null
|
||||
placeholder?: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
children?: (inputElement: ReactNode) => ReactNode
|
||||
}> = ({
|
||||
className,
|
||||
error,
|
||||
softError,
|
||||
warn,
|
||||
value,
|
||||
placeholder,
|
||||
onChange,
|
||||
children = (v) => v,
|
||||
}) => {
|
||||
const [hasBlurred, blur] = useState(false)
|
||||
|
||||
return (
|
||||
<div className="flex gap-1 items-center">
|
||||
{children(
|
||||
<input
|
||||
className={twMerge(
|
||||
"text-sm border rounded p-2 border-polkadot-200 leading-tight text-white",
|
||||
warn ? "border-orange-400" : null,
|
||||
error ? "border-red-600" : null,
|
||||
className,
|
||||
)}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={(evt) => onChange(evt.target.value)}
|
||||
onFocus={() => blur(false)}
|
||||
onBlur={() => blur(true)}
|
||||
/>,
|
||||
)}
|
||||
{(hasBlurred || error) &&
|
||||
(typeof (error || softError) === "string" ? (
|
||||
<span className="text-red-600 text-sm">{error || softError}</span>
|
||||
) : typeof warn === "string" ? (
|
||||
<span className="text-orange-400 text-sm">{warn}</span>
|
||||
) : null)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export * from "./CAccountId"
|
||||
export * from "./CEnum"
|
||||
export * from "./EditNumber"
|
||||
export * from "./CBytes"
|
||||
export * from "./CStruct"
|
||||
export * from "./CSequence"
|
||||
export * from "./CTuple"
|
||||
export * from "./CStr"
|
||||
export * from "./codec-components"
|
||||
@@ -0,0 +1,4 @@
|
||||
import { getCodecComponent } from "@codec-components"
|
||||
import * as editComponents from "./components"
|
||||
|
||||
export const EditCodec = getCodecComponent(editComponents)
|
||||
@@ -0,0 +1,149 @@
|
||||
import { FC, useEffect, useRef, useState } from "react"
|
||||
import { metadata, Binary, HexString } from "@polkadot-api/substrate-bindings"
|
||||
import { EditCodec } from "./EditCodec"
|
||||
import { TreeCodec } from "./EditCodec/Tree/index"
|
||||
import {
|
||||
CodecComponentValue,
|
||||
CodecComponentType,
|
||||
CodecComponentUpdate,
|
||||
MetadataType,
|
||||
} from "@codec-components"
|
||||
import { SubtreeFocus } from "./common/SubtreeFocus"
|
||||
import { Circle } from "lucide-react"
|
||||
import { synchronizeScroll } from "./common/scroll"
|
||||
import { MarkersContextProvider, VisibleWindow } from "./common/Markers"
|
||||
import { CopyText } from "@/components/Copy"
|
||||
import { FocusPath } from "./FocusPath"
|
||||
|
||||
export const EditMode: React.FC<{
|
||||
codecType: number
|
||||
metadata: MetadataType
|
||||
initialValue?: HexString
|
||||
}> = ({ codecType, initialValue, metadata: metadataDecoded }) => {
|
||||
const treeRef = useRef<HTMLDivElement | null>(null)
|
||||
const listRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!listRef.current || !treeRef.current) return
|
||||
return synchronizeScroll(listRef.current, treeRef.current)
|
||||
}, [])
|
||||
|
||||
// interior X1 AccountId doesn't mark as valid??
|
||||
|
||||
const [innerValue, setInnerValue] = useState<CodecComponentValue>({
|
||||
type: CodecComponentType.Initial,
|
||||
value: initialValue,
|
||||
})
|
||||
const [focusingSubtree, setFocusingSubtree] = useState<string[] | null>(null)
|
||||
|
||||
const props = {
|
||||
metadata: metadataDecoded as any,
|
||||
codecType: codecType,
|
||||
value: innerValue,
|
||||
onUpdate: (value: CodecComponentUpdate) => {
|
||||
setInnerValue({ type: CodecComponentType.Updated, value })
|
||||
},
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setInnerValue({
|
||||
type: CodecComponentType.Initial,
|
||||
value: initialValue,
|
||||
})
|
||||
}, [metadata, codecType])
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-start w-full max-w-screen-lg h-screen text-polkadot-100 overflow-hidden bg-polkadot-900">
|
||||
<BinaryDisplay
|
||||
value={
|
||||
(innerValue.type === CodecComponentType.Initial
|
||||
? innerValue.value
|
||||
: innerValue.value.empty
|
||||
? null
|
||||
: innerValue.value.encoded) ?? null
|
||||
}
|
||||
/>
|
||||
<FocusPath
|
||||
metadata={metadataDecoded as any}
|
||||
typeId={codecType}
|
||||
value={focusingSubtree}
|
||||
onFocus={setFocusingSubtree}
|
||||
/>
|
||||
<div className="px-2">
|
||||
{/* This element is presentational only: Adds a connecting border between the FocusPath and the tree below */}
|
||||
<div className="border-l border-polkadot-700 h-2 max-sm:border-none" />
|
||||
</div>
|
||||
<SubtreeFocus
|
||||
value={{ callback: setFocusingSubtree, path: focusingSubtree }}
|
||||
>
|
||||
<MarkersContextProvider>
|
||||
<div
|
||||
ref={listRef}
|
||||
className="flex flex-row overflow-auto w-full gap-2"
|
||||
>
|
||||
<div
|
||||
ref={treeRef}
|
||||
className="w-96 sticky top-0 pl-2 pb-16 leading-loose overflow-hidden max-sm:hidden"
|
||||
>
|
||||
<div className="relative">
|
||||
{!innerValue.value ? (
|
||||
<div className="h-14 ml-5 text-sm flex flex-col justify-center">
|
||||
{"Start by choosing a value -->"}
|
||||
</div>
|
||||
) : (
|
||||
<TreeCodec {...props} />
|
||||
)}
|
||||
<VisibleWindow />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="p-2 rounded bg-[#041424]">
|
||||
<EditCodec {...props} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</MarkersContextProvider>
|
||||
</SubtreeFocus>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const DISPLAY_MAX_LEN = 1024
|
||||
const COPY_MAX_LEN = 5 * 1024 * 1024
|
||||
const BinaryDisplay: FC<{ value: Uint8Array | HexString | null }> = ({
|
||||
value,
|
||||
}) => {
|
||||
const displayLength = DISPLAY_MAX_LEN * 2 + 2
|
||||
|
||||
const copyLength = COPY_MAX_LEN * 2 + 2
|
||||
const hex = value
|
||||
? typeof value === "string"
|
||||
? value.slice(0, copyLength)
|
||||
: Binary.fromBytes(value.slice(0, COPY_MAX_LEN)).asHex()
|
||||
: null
|
||||
const exceedsDisplayLength = hex && hex.length > displayLength
|
||||
const exceedsCopyLength = !!hex && hex.length >= COPY_MAX_LEN * 2 + 2
|
||||
|
||||
const copyDisabled = hex === null || exceedsCopyLength
|
||||
|
||||
return (
|
||||
<div className="p-2 w-full">
|
||||
<div className="px-3 py-2 gap-2 rounded flex flex-row items-center bg-polkadot-800">
|
||||
<CopyText text={hex ?? ""} disabled={copyDisabled} />
|
||||
<div className="text-sm tabular-nums max-h-12 overflow-hidden whitespace-nowrap text-ellipsis">
|
||||
{hex ? (
|
||||
hex.slice(0, displayLength) + (exceedsDisplayLength ? "…" : "")
|
||||
) : (
|
||||
<div className="flex flex-row items-center gap-1">
|
||||
<span>Cannot display hex. Complete required values shown by</span>{" "}
|
||||
<Circle size={8} strokeWidth={4} className="text-red-600" />
|
||||
(incomplete), or
|
||||
<Circle size={8} strokeWidth={4} className="text-orange-600" />
|
||||
(partially incomplete)
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,3 +1,36 @@
|
||||
import { metadata$ } from "@/chain.state"
|
||||
import { state, useStateObservable } from "@react-rxjs/core"
|
||||
import { map } from "rxjs"
|
||||
import { EditMode } from "./EditMode"
|
||||
|
||||
const extrinsicProps$ = state(
|
||||
metadata$.pipe(
|
||||
map((metadata) => ({
|
||||
metadata,
|
||||
codecType:
|
||||
"call" in metadata.extrinsic
|
||||
? metadata.extrinsic.call
|
||||
: // TODO v14 is this one?
|
||||
metadata.extrinsic.type,
|
||||
})),
|
||||
),
|
||||
null,
|
||||
)
|
||||
|
||||
export const Extrinsics = () => {
|
||||
return <div>Foo</div>
|
||||
const extrinsicProps = useStateObservable(extrinsicProps$)
|
||||
|
||||
if (!extrinsicProps) {
|
||||
return <div>Loading metadata...</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div>Extrinsics</div>
|
||||
<EditMode
|
||||
{...extrinsicProps}
|
||||
initialValue="0x630b040101010031323334353637383934353631363531363531363531363531363531353631350100000108000100002c00000000080000000000"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { lookupToType, TypeIcon, TypeIcons } from "@/components/Icons"
|
||||
import { getLookupFn, Var } from "@polkadot-api/metadata-builders"
|
||||
import { V14, V15 } from "@polkadot-api/substrate-bindings"
|
||||
import { FC, ReactElement } from "react"
|
||||
import { twMerge as clsx } from "tailwind-merge"
|
||||
|
||||
export const FocusPath: FC<{
|
||||
metadata: V14 | V15
|
||||
typeId: number
|
||||
value: string[] | null
|
||||
onFocus: (value: string[] | null) => void
|
||||
}> = ({ metadata, typeId, value, onFocus }) => {
|
||||
const breadcrumbs = getBreadcrumbs(metadata, typeId, value ?? [], onFocus)
|
||||
|
||||
return (
|
||||
<div className="flex-shrink-0 px-2">
|
||||
<div className="flex max-w-full flex-wrap gap-1 items-center border border-polkadot-700 text-sm px-2 py-1">
|
||||
{breadcrumbs.map((v, i) => (
|
||||
<span key={i} className="whitespace-nowrap flex gap-1 items-center">
|
||||
{i > 0 && <span className="text-slate-500 mx-2">></span>}
|
||||
{v.icon}
|
||||
{v.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type Breadcrumb = {
|
||||
icon?: ReactElement | null
|
||||
label: ReactElement
|
||||
}
|
||||
type BreadcrumbNode = {
|
||||
type?: TypeIcon
|
||||
label: string
|
||||
}
|
||||
|
||||
function getBreadcrumbs(
|
||||
metadata: V14 | V15,
|
||||
typeId: number,
|
||||
path: string[],
|
||||
onFocus: (value: string[] | null) => void,
|
||||
): Breadcrumb[] {
|
||||
const lookup = getLookupFn(metadata)
|
||||
const nodes: BreadcrumbNode[] = [
|
||||
{
|
||||
label: "Root",
|
||||
},
|
||||
]
|
||||
let lookupType: Var = lookup(typeId)
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
nodes.push({
|
||||
type: lookupToType[lookupType.type],
|
||||
label: path[i],
|
||||
})
|
||||
|
||||
switch (lookupType.type) {
|
||||
case "option":
|
||||
throw new Error("TODO Option breadcrumb not implemented")
|
||||
case "result":
|
||||
throw new Error("TODO Result breadcrumb not implemented")
|
||||
case "array":
|
||||
case "sequence":
|
||||
lookupType = lookupType.value
|
||||
break
|
||||
case "tuple":
|
||||
lookupType = lookupType.value[Number(path[i])]
|
||||
break
|
||||
case "enum": {
|
||||
const inner = lookupType.value[path[i]]
|
||||
lookupType = inner.type === "lookupEntry" ? inner.value : inner
|
||||
break
|
||||
}
|
||||
case "struct":
|
||||
lookupType = lookupType.value[path[i]]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const breadcrumbs: Breadcrumb[] = []
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i]
|
||||
const label =
|
||||
i === nodes.length - 1 ? (
|
||||
<span>{node.label}</span>
|
||||
) : (
|
||||
<a
|
||||
href="#"
|
||||
className={clsx("hover:text-polkadot-400", i === 0 && "font-bold")}
|
||||
onClick={(evt) => {
|
||||
evt.preventDefault()
|
||||
onFocus(i === 0 ? null : path.slice(0, i))
|
||||
}}
|
||||
>
|
||||
{node.label}
|
||||
</a>
|
||||
)
|
||||
|
||||
if (i > 0 && nodes[i - 1].type === node.type) {
|
||||
const previousBreadcrumb = breadcrumbs[breadcrumbs.length - 1]
|
||||
const previousLabel = previousBreadcrumb.label
|
||||
previousBreadcrumb.label = (
|
||||
<>
|
||||
{previousLabel}
|
||||
<span className="text-slate-500">/</span>
|
||||
{label}
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
const Icon = node.type && TypeIcons[node.type]
|
||||
breadcrumbs.push({
|
||||
icon: Icon ? <Icon size={16} className="text-polkadot-600" /> : null,
|
||||
label,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return breadcrumbs
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useHeightObserver } from "@/components/useHeightObserver"
|
||||
import { useRefEffect } from "@/components/useRefEffect"
|
||||
import {
|
||||
createContext,
|
||||
FC,
|
||||
PropsWithChildren,
|
||||
useContext,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
const MarkersContext = createContext<{
|
||||
observer: IntersectionObserver
|
||||
onMarkerRemoved: (id: string[]) => void
|
||||
range: [number, number]
|
||||
} | null>(null)
|
||||
|
||||
export const Marker: FC<{ id: string[] }> = ({ id }) => {
|
||||
const ctx = useContext(MarkersContext)
|
||||
const ref = useRefEffect<HTMLElement>(
|
||||
(element) => {
|
||||
if (!ctx) return () => {}
|
||||
ctx.observer.observe(element)
|
||||
return () => {
|
||||
ctx.onMarkerRemoved(id)
|
||||
ctx.observer.unobserve(element)
|
||||
}
|
||||
},
|
||||
[ctx?.observer, id],
|
||||
)
|
||||
|
||||
return <div id={"marker-" + id.join(".")} ref={ref} />
|
||||
}
|
||||
|
||||
export const MarkersContextProvider: FC<PropsWithChildren> = ({ children }) => {
|
||||
const positions = useConstant(
|
||||
() => new Map<string, { top: number; height: number }>(),
|
||||
)
|
||||
const [range, setRange] = useState<[number, number]>([0, 0])
|
||||
|
||||
const refreshRange = () => {
|
||||
const values = Array.from(positions.values())
|
||||
const min = values.reduce((a, b) => Math.min(a, b.top), values[0]?.top ?? 0)
|
||||
const max = values.reduce((a, b) => Math.max(a, b.top + b.height), 0)
|
||||
|
||||
setRange([min, max])
|
||||
}
|
||||
|
||||
const observer = useConstant(
|
||||
() =>
|
||||
new IntersectionObserver((cb) => {
|
||||
cb.forEach((v) => {
|
||||
if (v.isIntersecting) {
|
||||
const element = document.querySelector(
|
||||
`[data-marker="${v.target.id}"]`,
|
||||
)
|
||||
if (!element || !(element instanceof HTMLElement)) {
|
||||
return
|
||||
}
|
||||
positions.set(v.target.id, {
|
||||
top: element.offsetTop,
|
||||
height: element.offsetHeight,
|
||||
})
|
||||
} else {
|
||||
positions.delete(v.target.id)
|
||||
}
|
||||
})
|
||||
refreshRange()
|
||||
}),
|
||||
)
|
||||
|
||||
const onMarkerRemoved = (id: string[]) => {
|
||||
const key = "marker-" + id.join(".")
|
||||
if (positions.has(key)) {
|
||||
positions.delete(key)
|
||||
refreshRange()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<MarkersContext.Provider value={{ observer, range, onMarkerRemoved }}>
|
||||
{children}
|
||||
</MarkersContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const VisibleWindow = () => {
|
||||
const ctx = useContext(MarkersContext)
|
||||
const [height, setHeight] = useState<number | null>(null)
|
||||
const ref = useHeightObserver(setHeight)
|
||||
if (!ctx) return null
|
||||
|
||||
const isAllVisible = ctx.range[0] === 0 && ctx.range[1] === height // 🔫 always has been
|
||||
|
||||
const fade =
|
||||
"absolute left-0 right-0 transition-all ease-linear bg-gray-100 bg-opacity-10 backdrop-blur-[0.4px]"
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={twMerge(
|
||||
"absolute top-0 right-0 left-0 bottom-0 pointer-events-none border-x-8 border-y-4 border-gray-100 border-opacity-10 transition-all",
|
||||
isAllVisible && "border-x-0 border-y-0",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={fade}
|
||||
style={{
|
||||
top: 0,
|
||||
height: ctx.range[0],
|
||||
}}
|
||||
></div>
|
||||
<div
|
||||
className={fade}
|
||||
style={{
|
||||
top: ctx.range[1] || "100%",
|
||||
bottom: 0,
|
||||
}}
|
||||
></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const useConstant = <T extends any>(fn: () => T): T => {
|
||||
const ref = useRef<T | null>(null)
|
||||
if (!ref.current) {
|
||||
ref.current = fn()
|
||||
}
|
||||
|
||||
return ref.current
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createContext, useContext } from "react"
|
||||
|
||||
const SubtreeFocusContext = createContext<{
|
||||
callback: (path: string[]) => void
|
||||
path: null | string[]
|
||||
} | null>(null)
|
||||
|
||||
export const SubtreeFocus = SubtreeFocusContext.Provider
|
||||
|
||||
export const useSubtreeFocus = () => {
|
||||
const ctx = useContext(SubtreeFocusContext)
|
||||
if (!ctx) throw new Error("SubtreeFocus provider not found")
|
||||
return {
|
||||
setFocus: ctx.callback,
|
||||
getNextPath: (path: string[]) => {
|
||||
if (!ctx.path || path.length >= ctx.path.length) return null
|
||||
return ctx.path[path.length]
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { createSignal } from "@react-rxjs/utils"
|
||||
import { state } from "@react-rxjs/core"
|
||||
import { defer, map, scan } from "rxjs"
|
||||
|
||||
export const [collapsedToggle$, toggleCollapsed] = createSignal<string>()
|
||||
|
||||
const collapsedPaths$ = state(
|
||||
defer(() =>
|
||||
collapsedToggle$.pipe(
|
||||
scan((acc, v) => {
|
||||
if (acc.has(v)) acc.delete(v)
|
||||
else acc.add(v)
|
||||
return acc
|
||||
}, new Set<string>()),
|
||||
),
|
||||
),
|
||||
new Set(),
|
||||
)
|
||||
|
||||
export const isCollapsed$ = state(
|
||||
(path: string) => collapsedPaths$.pipe(map((v) => v.has(path))),
|
||||
false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Returns true if it's a collapsed root.
|
||||
* Same as `isCollapsed`, but returns `false` if a parent path is also collapsed.
|
||||
*/
|
||||
export const isCollapsedRoot$ = state(
|
||||
(path: string) =>
|
||||
collapsedPaths$.pipe(
|
||||
map((collapsedPaths) => {
|
||||
if (!collapsedPaths.has(path)) return false
|
||||
|
||||
return !Array.from(collapsedPaths).some(
|
||||
(otherPath) => otherPath !== path && path.startsWith(otherPath),
|
||||
)
|
||||
}),
|
||||
),
|
||||
false,
|
||||
)
|
||||
|
||||
export const [hoverChange$, setHovered] = createSignal<{
|
||||
id: string
|
||||
hover: boolean
|
||||
}>()
|
||||
|
||||
const hoverPaths$ = state(
|
||||
defer(() =>
|
||||
hoverChange$.pipe(
|
||||
scan((acc, v) => {
|
||||
if (v.hover) acc.add(v.id)
|
||||
else acc.delete(v.id)
|
||||
return acc
|
||||
}, new Set<string>()),
|
||||
),
|
||||
),
|
||||
new Set(),
|
||||
)
|
||||
|
||||
export const isActive$ = state(
|
||||
(path: string) =>
|
||||
hoverPaths$.pipe(
|
||||
map((hoverPaths) => {
|
||||
if (!hoverPaths.has(path)) return false
|
||||
|
||||
// Here it's the opposite of `isCollapsedRoot`: We don't want to highlight the root if a child is being highlighted
|
||||
return !Array.from(hoverPaths).some(
|
||||
(otherPath) => otherPath !== path && otherPath.startsWith(path),
|
||||
)
|
||||
}),
|
||||
),
|
||||
false,
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
export function synchronizeScroll(
|
||||
scrollingElement: HTMLElement,
|
||||
targetElement: HTMLElement,
|
||||
) {
|
||||
let heightCache = {
|
||||
time: 0,
|
||||
targetHeight: 0,
|
||||
}
|
||||
const onScroll = async () => {
|
||||
await Promise.resolve()
|
||||
const now = Date.now()
|
||||
heightCache =
|
||||
heightCache.time > now - 500
|
||||
? heightCache
|
||||
: {
|
||||
time: now,
|
||||
targetHeight: targetElement.getBoundingClientRect().height,
|
||||
}
|
||||
|
||||
const listScrollPos =
|
||||
scrollingElement.scrollTop / scrollingElement.scrollHeight
|
||||
targetElement.scrollTop = listScrollPos * heightCache.targetHeight
|
||||
}
|
||||
|
||||
scrollingElement.addEventListener("scroll", onScroll)
|
||||
// Used as scroll target for markers...
|
||||
// Otherwise smooth scroll with `element.scrollIntoView` gets interrupted.
|
||||
// This should be passed probably by context, but at this scale it works.
|
||||
;(window as any).scrollingElement = scrollingElement
|
||||
return () => {
|
||||
scrollingElement.removeEventListener("scroll", onScroll)
|
||||
;(window as any).scrollingElement = null
|
||||
}
|
||||
}
|
||||
|
||||
export const scrollToMarker = (id: string[]) => {
|
||||
const element = document.getElementById("marker-" + id.join("."))
|
||||
if (!element) return
|
||||
|
||||
const scrollingElement: HTMLElement = (window as any).scrollingElement
|
||||
if (scrollingElement) {
|
||||
const elementRect = element.getBoundingClientRect()
|
||||
const scrollRect = scrollingElement.getBoundingClientRect()
|
||||
|
||||
scrollingElement.scrollBy({
|
||||
top: elementRect.top - scrollRect.top - 50,
|
||||
behavior: "smooth",
|
||||
})
|
||||
} else {
|
||||
element.scrollIntoView({ behavior: "instant" })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { NOTIN } from "@codec-components"
|
||||
|
||||
export const withDefault: <T>(value: T | NOTIN, fallback: T) => T = (
|
||||
value,
|
||||
fallback,
|
||||
) => (value === NOTIN ? fallback : value)
|
||||
@@ -0,0 +1,54 @@
|
||||
import { EnumVar, StructVar } from "@polkadot-api/metadata-builders"
|
||||
|
||||
const complexTypes = new Set(["array", "sequence", "struct", "enum", "result"])
|
||||
export const isComplex = (type: string) => complexTypes.has(type)
|
||||
|
||||
export const isEnumComplex = <T extends EnumVar>(
|
||||
shape: T,
|
||||
type: keyof T["value"],
|
||||
): boolean => {
|
||||
const innerShape = shape.value[type]
|
||||
return isComplex(
|
||||
innerShape.type === "lookupEntry" ? innerShape.value.type : innerShape.type,
|
||||
)
|
||||
}
|
||||
|
||||
export const getEnumInnerType = <T extends EnumVar>(
|
||||
shape: T,
|
||||
type: keyof T["value"],
|
||||
) => {
|
||||
const innerShape = shape.value[type]
|
||||
return innerShape.type === "lookupEntry"
|
||||
? innerShape.value.type
|
||||
: innerShape.type
|
||||
}
|
||||
|
||||
export const getStructInnerType = <T extends StructVar>(
|
||||
shape: T,
|
||||
key: keyof T["value"],
|
||||
) => {
|
||||
return shape.value[key].type
|
||||
}
|
||||
|
||||
export const isEnumVoid = <T extends EnumVar>(
|
||||
shape: T,
|
||||
type: keyof T["value"],
|
||||
): boolean => {
|
||||
const innerShape = shape.value[type]
|
||||
const innerType =
|
||||
innerShape.type === "lookupEntry" ? innerShape.value.type : innerShape.type
|
||||
return innerType === "void"
|
||||
}
|
||||
|
||||
export const getFinalType = (shape: any, name: string) => {
|
||||
const innerType = shape.value[name]
|
||||
switch (innerType.type) {
|
||||
case "primitive":
|
||||
return innerType.value
|
||||
case "compact":
|
||||
return innerType.size
|
||||
case "AccountId20":
|
||||
case "AccountId32":
|
||||
return innerType.type
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user