Skip to content

Commit 9daf70c

Browse files
committed
feat: add example for valueTypes
1 parent fdf9962 commit 9daf70c

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

examples/basic/pages/index.tsx

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ import {
88
import type React from 'react'
99
import { useCallback, useEffect, useState } from 'react'
1010

11+
// this url is copied from: https://beta.reactjs.org/learn/passing-props-to-a-component
12+
const avatar = 'https://i.imgur.com/1bX5QH6.jpg'
13+
1114
function aPlusB (a: number, b: number) {
1215
return a + b
1316
}
@@ -45,6 +48,7 @@ const example = {
4548
fn: aPlusB,
4649
string_number: '1234',
4750
timer: 0,
51+
avatar,
4852
date: new Date('Tue Sep 13 2022 14:07:44 GMT-0500 (Central Daylight Time)')
4953
}
5054

@@ -100,6 +104,14 @@ const IndexPage: React.FC = () => {
100104
indentWidth={indent}
101105
groupArraysAfterLength={groupArraysAfterLength}
102106
keyRenderer={KeyRenderer}
107+
valueTypes={[
108+
{
109+
is: (value): value is string => typeof value === 'string' && value.startsWith('https://i.imgur.com'),
110+
Component: (props) => {
111+
return <img height='50px' src={props.value} alt={props.value}/>
112+
}
113+
}
114+
]}
103115
onChange={
104116
useCallback<JsonViewerOnChange>(
105117
(path, oldValue, newValue) => {

src/stores/typeRegistry.tsx

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,19 @@ export function registerType<Value> (type: DataType<Value>) {
1717
}
1818

1919
export function matchTypeComponents<Value> (value: Value): DataType<Value> {
20+
let potential: DataType<Value> | undefined
2021
for (const T of typeRegistry) {
2122
if (T.is(value)) {
23+
potential = T
24+
}
25+
if (typeof value === 'object' && value === null) {
2226
return T
2327
}
2428
}
25-
throw new DevelopmentError('this is not possible')
29+
if (potential === undefined) {
30+
throw new DevelopmentError('this is not possible')
31+
}
32+
return potential
2633
}
2734

2835
export function useTypeComponents (value: unknown) {

0 commit comments

Comments
 (0)