Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support cell data decoding #267

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"@ckb-lumos/base": "0.21.0-next.1",
"@microlink/react-json-view": "1.23.0",
"@nervosnetwork/ckb-sdk-utils": "0.109.1",
"@radix-ui/react-select": "^2.0.0",
"@sentry/react": "7.94.1",
"@sentry/tracing": "7.94.1",
"@spore-sdk/core": "0.2.0-beta.3",
Expand Down Expand Up @@ -39,6 +40,7 @@
"react-router-dom": "5.3.4",
"react-scripts": "5.0.1",
"sass": "1.70.0",
"selection-popover": "^0.3.0",
"styled-components": "5.3.11"
},
"devDependencies": {
Expand Down Expand Up @@ -97,7 +99,7 @@
"stylelint-config-standard": "^35.0.0",
"stylelint-config-standard-scss": "^12.0.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-no-unsupported-browser-features": "7.0.0",
"stylelint-no-unsupported-browser-features": "8.0.1",
"stylelint-processor-styled-components": "^1.10.0",
"timezone-mock": "^1.1.4",
"ts-jest": "29.1.2",
Expand Down
7 changes: 5 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { DefaultTheme, ThemeProvider } from 'styled-components'
import Routers from './routes'
import Toast from './components/Toast'
import { SelectionParser } from './components/SelectionParser'
import { isMainnet } from './utils/chain'
import { DASQueryContextProvider } from './hooks/useDASAccount'
import { getPrimaryColor, getSecondaryColor } from './constants/common'
Expand All @@ -29,8 +30,10 @@ const App = () => {
<div style={appStyle} data-net={isMainnet() ? 'mainnet' : 'testnet'}>
<QueryClientProvider client={queryClient}>
<DASQueryContextProvider>
<Routers />
<Toast />
<SelectionParser>
<Routers />
<Toast />
</SelectionParser>
</DASQueryContextProvider>
</QueryClientProvider>
</div>
Expand Down
43 changes: 43 additions & 0 deletions src/components/SelectionParser/Select.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import React from 'react'
import * as Select from '@radix-ui/react-select'
import classnames from 'classnames'

import styles from './select.module.scss'

interface MySelectProps extends Select.SelectProps {
options: { value: string; label: string }[]
placeholder?: string
container?: Select.PortalProps['container']
}

const MySelect = ({ placeholder, options, container, ...props }: MySelectProps) => (
<Select.Root {...props}>
<Select.Trigger className={styles.selectTrigger} aria-label="Food">
<Select.Value placeholder={placeholder} />
<Select.Icon className={styles.selectIcon} />
</Select.Trigger>
<Select.Portal container={container}>
<Select.Content position="popper" className={styles.selectContent}>
<Select.ScrollUpButton className={styles.SelectScrollButton} />
<Select.Viewport className={styles.selectViewport}>
{options.map(option => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</Select.Viewport>
<Select.ScrollDownButton className={styles.selectScrollButton} />
</Select.Content>
</Select.Portal>
</Select.Root>
)

const SelectItem: React.FC<React.PropsWithChildren<Select.SelectItemProps>> = ({ children, className, ...props }) => {
return (
<Select.Item className={classnames(styles.selectItem, className)} {...props}>
<Select.ItemText>{children}</Select.ItemText>
</Select.Item>
)
}

export default MySelect
139 changes: 139 additions & 0 deletions src/components/SelectionParser/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/* eslint-disable import/no-extraneous-dependencies */
import React, { ComponentProps, useEffect, useMemo, useRef, useState, createContext } from 'react'
import { useTranslation } from 'react-i18next'
import { Root, Trigger, Portal, Content } from 'selection-popover'
import Select from './Select'
import styles from './styles.module.scss'

const DECODER = {
utf8: 'UTF-8',
number: 'Number',
// todo: support decode address & Big-Endian
// bigend: 'Big-Endian',
}

type ContextValue = {
container?: HTMLElement | null
}

const SelectionParserContext = createContext<ContextValue>({
container: undefined,
})

export const SelectionParserProvider = SelectionParserContext.Provider

interface Props extends ComponentProps<'div'> {}

export const SelectionParser: React.FC<React.PropsWithChildren<Props>> = ({ children, ...props }) => {
const { t } = useTranslation()
const ref = useRef(null)
const wrapperRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const [decoderOpen, setDecoderOpen] = useState(false)
const [selectedText, setSelectedText] = useState('')
const [anchorElement, setAnchorElement] = useState<HTMLElement | undefined>(undefined)
const [decoder, setDecoder] = useState<keyof typeof DECODER>(Object.keys(DECODER)[0] as keyof typeof DECODER)

const prefix0x = (hex: string) => {
if (hex.startsWith('0x')) {
return hex
}

if (hex.startsWith('x')) {
return `0${hex}`
}

return `0x${hex}`
}

const onSelectionChanged = (e: Event) => {
e.stopPropagation()
e.preventDefault()

const selection = window.getSelection()

if (!selection) {
setDecoderOpen(false)
return
}

if (selection.anchorNode !== selection.focusNode) {
setDecoderOpen(false)
return
}

const min = Math.min(selection.anchorOffset ?? 0, selection.focusOffset ?? 0)
const max = Math.max(selection.anchorOffset ?? 0, selection.focusOffset ?? 0)
const text = (selection.anchorNode?.textContent ?? '').slice(min, max)

setSelectedText(text)
setAnchorElement(selection.anchorNode?.parentElement ?? undefined)
}

useEffect(() => {
window.document.addEventListener('selectionchange', onSelectionChanged)
return () => window.document.removeEventListener('selectionchange', onSelectionChanged)
}, [])

const handleOpenChange = (open: boolean) => {
if (!open) {
setDecoderOpen(false)
return false
}

const selection = window.getSelection()
if (!selection) {
setDecoderOpen(false)
return false
}

if (selection.anchorNode !== selection.focusNode) {
setDecoderOpen(false)
return false
}

setDecoderOpen(true)
return true
}

const decodedText = useMemo(() => {
try {
if (decoder === 'utf8') {
const bytes = [...selectedText.matchAll(/[0-9a-f]{2}/g)].map(a => parseInt(a[0], 16))
return new TextDecoder().decode(new Uint8Array(bytes))
}

if (decoder === 'number') {
if (!selectedText) return ''
return BigInt(prefix0x(selectedText)).toString()
}
} catch {
return `Unable to parse ${selectedText} to ${decoder}`
}
}, [decoder, selectedText])

return (
<div ref={wrapperRef} {...props}>
<Root whileSelect openDelay={100} open={decoderOpen} onOpenChange={handleOpenChange}>
<Trigger ref={ref}>{children}</Trigger>
<Portal container={anchorElement}>
<Content ref={contentRef} side="bottom" className={styles.selectionPopover}>
<div className={styles.selectionPopoverHeader}>
{t('transaction.view_data_as')}
<Select
container={contentRef.current}
value={decoder}
onValueChange={e => setDecoder(e as keyof typeof DECODER)}
options={Object.keys(DECODER).map(key => ({
value: key,
label: DECODER[key as keyof typeof DECODER],
}))}
/>
</div>
<div className={styles.selectionPopoverContent}>{decodedText}</div>
</Content>
</Portal>
</Root>
</div>
)
}
63 changes: 63 additions & 0 deletions src/components/SelectionParser/select.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
button {
all: unset;
}

.selectTrigger {
display: inline-flex;
cursor: pointer;
align-items: center;
justify-content: center;
border-radius: 4px;
padding: 0 15px;
line-height: 1;
gap: 5px;
background-color: white;
color: var(--primary-color);
}

.selectIcon {
font-size: 12px;
}

.selectContent {
width: 100%;
overflow: hidden;
background-color: white;
border-radius: 6px;
box-shadow: 0 10px 38px -10px rgb(22 23 24 / 35%), 0 10px 20px -15px rgb(22 23 24 / 20%);
z-index: 3;
}

.selectViewport {
padding: 12px 8px;
gap: 8px;
display: flex;
flex-direction: column;
}

.selectItem {
cursor: pointer;
border-radius: 3px;
display: flex;
align-items: center;

// padding: 0 35px 0 25px;
position: relative;
user-select: none;
font-weight: 500;
font-size: 1rem;
line-height: 1.5rem;

&:hover {
color: var(--primary-color);
}
}

.selectScrollButton {
display: flex;
align-items: center;
justify-content: center;
height: 25px;
background-color: white;
cursor: default;
}
45 changes: 45 additions & 0 deletions src/components/SelectionParser/styles.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
@import '../../styles/variables.module';

.selectionPopover {
background-color: #fff;
border-radius: 4px;
box-shadow: 0 2px 10px #eee;
transform-origin: var(--selection-popover-content-transform-origin);
animation: scale-in 500ms cubic-bezier(0.16, 1, 0.3, 1);
max-width: 400px;
word-wrap: break-word;
z-index: 2;
}

.selectionPopoverHeader {
padding: 16px;
border-bottom: 1px solid #e5e5e5;
font-size: 1rem;
font-weight: 500;
text-align: start;
}

.selectionPopoverContent {
padding: 16px;
font-size: 0.875rem;
font-weight: 600;
color: #666;
line-height: 1.5rem;
text-align: start;
}

@keyframes scale-in {
from {
opacity: 0;
transform: scale(0);
}

to {
opacity: 1;
transform: scale(1);
}
}

.notSelect {
user-select: none;
}
1 change: 1 addition & 0 deletions src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,7 @@
"lock_script": "Lock Script",
"type_script": "Type Script",
"data": "Data",
"view_data_as": "View Data As",
"base_reward": "Base Reward",
"secondary_reward": "Secondary Reward",
"commit_reward": "Commit Reward",
Expand Down
1 change: 1 addition & 0 deletions src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,7 @@
"lock_script": "Lock Script",
"type_script": "Type Script",
"data": "Data",
"view_data_as": "data 解码为",
"base_reward": "基础奖励",
"secondary_reward": "二级奖励",
"commit_reward": "提交奖励",
Expand Down
12 changes: 8 additions & 4 deletions src/pages/Transaction/TransactionCellScript/index.tsx
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these update still necessary when the selection is listened globally

Copy link
Author

@PainterPuppets PainterPuppets Mar 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These code is to make the component look the same as the design, I'll remove it if our plan to update it later.

Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,8 @@ const CellInfoValueRender = ({ content }: { content: CellInfoValue }) => {
return <JSONKeyValueView title="null" />
}

const CellInfoValueJSONView = ({ content, state }: { content: CellInfoValue; state: CellInfo }) => (
<TransactionCellInfoValuePanel isData={state === CellInfo.DATA}>
const CellInfoValueJSONView = ({ content }: { content: CellInfoValue }) => (
<TransactionCellInfoValuePanel>
<span>{'{'}</span>
<CellInfoValueRender content={content} />
<span>{'}'}</span>
Expand Down Expand Up @@ -293,7 +293,7 @@ export default ({ cell, onClose }: TransactionCellScriptProps) => {
<img src={CloseIcon} alt="close icon" tabIndex={-1} onKeyDown={() => {}} onClick={() => onClose()} />
</div>
}
tabBarStyle={{ fontSize: '10px' }}
tabBarStyle={{ fontSize: '10px', padding: '0 20px' }}
onTabClick={key => {
const state = parseInt(key, 10)
if (state && !Number.isNaN(state)) {
Expand Down Expand Up @@ -338,7 +338,11 @@ export default ({ cell, onClose }: TransactionCellScriptProps) => {
<TransactionDetailPanel>
{isFetched ? (
<div className="transactionDetailContent">
<CellInfoValueJSONView content={content} state={selectedInfo} />
{selectedInfo === CellInfo.DATA && isCellData(content) ? (
<div className={styles.dataView}>{content.data}</div>
) : (
<CellInfoValueJSONView content={content} />
)}
</div>
) : (
<div className="transactionDetailLoading">{!isFetched ? <SmallLoading /> : null}</div>
Expand Down
Loading