Skip to content

Commit

Permalink
feat: add example for valueTypes
Browse files Browse the repository at this point in the history
  • Loading branch information
himself65 committed Sep 18, 2022
1 parent fdf9962 commit 9daf70c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
12 changes: 12 additions & 0 deletions examples/basic/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import {
import type React from 'react'
import { useCallback, useEffect, useState } from 'react'

// this url is copied from: https://beta.reactjs.org/learn/passing-props-to-a-component
const avatar = 'https://i.imgur.com/1bX5QH6.jpg'

function aPlusB (a: number, b: number) {
return a + b
}
Expand Down Expand Up @@ -45,6 +48,7 @@ const example = {
fn: aPlusB,
string_number: '1234',
timer: 0,
avatar,
date: new Date('Tue Sep 13 2022 14:07:44 GMT-0500 (Central Daylight Time)')
}

Expand Down Expand Up @@ -100,6 +104,14 @@ const IndexPage: React.FC = () => {
indentWidth={indent}
groupArraysAfterLength={groupArraysAfterLength}
keyRenderer={KeyRenderer}
valueTypes={[
{
is: (value): value is string => typeof value === 'string' && value.startsWith('https://i.imgur.com'),
Component: (props) => {
return <img height='50px' src={props.value} alt={props.value}/>
}
}
]}
onChange={
useCallback<JsonViewerOnChange>(
(path, oldValue, newValue) => {
Expand Down
9 changes: 8 additions & 1 deletion src/stores/typeRegistry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,19 @@ export function registerType<Value> (type: DataType<Value>) {
}

export function matchTypeComponents<Value> (value: Value): DataType<Value> {
let potential: DataType<Value> | undefined
for (const T of typeRegistry) {
if (T.is(value)) {
potential = T
}
if (typeof value === 'object' && value === null) {
return T
}
}
throw new DevelopmentError('this is not possible')
if (potential === undefined) {
throw new DevelopmentError('this is not possible')
}
return potential
}

export function useTypeComponents (value: unknown) {
Expand Down

0 comments on commit 9daf70c

Please sign in to comment.