@dxos/react-ui-syntax-highlighter 0.8.4-main.f9ba587 → 0.8.4-main.fcfe5033a5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,15 +1,20 @@
1
1
  {
2
2
  "name": "@dxos/react-ui-syntax-highlighter",
3
- "version": "0.8.4-main.f9ba587",
3
+ "version": "0.8.4-main.fcfe5033a5",
4
4
  "description": "A syntax highlighter wrapper.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/dxos/dxos"
10
+ },
7
11
  "license": "MIT",
8
12
  "author": "DXOS.org",
9
- "sideEffects": true,
13
+ "sideEffects": false,
10
14
  "type": "module",
11
15
  "exports": {
12
16
  ".": {
17
+ "source": "./src/index.ts",
13
18
  "types": "./dist/types/src/index.d.ts",
14
19
  "browser": "./dist/lib/browser/index.mjs",
15
20
  "node": "./dist/lib/node-esm/index.mjs"
@@ -24,27 +29,29 @@
24
29
  "src"
25
30
  ],
26
31
  "dependencies": {
27
- "@preact-signals/safe-react": "^0.9.0",
28
- "jsonpath": "^1.1.1",
29
- "react-syntax-highlighter": "^15.5.0"
32
+ "jsonpath-plus": "^10.3.0",
33
+ "react-syntax-highlighter": "^15.6.1",
34
+ "@dxos/util": "0.8.4-main.fcfe5033a5",
35
+ "@dxos/ui-types": "0.8.4-main.fcfe5033a5"
30
36
  },
31
37
  "devDependencies": {
32
- "@types/jsonpath": "^0.2.4",
33
- "@types/react": "~18.2.0",
34
- "@types/react-dom": "~18.2.0",
38
+ "@types/react": "~19.2.7",
39
+ "@types/react-dom": "~19.2.3",
35
40
  "@types/react-syntax-highlighter": "^15.5.13",
36
- "react": "~18.2.0",
37
- "react-dom": "~18.2.0",
38
- "vite": "5.4.7",
39
- "@dxos/react-ui": "0.8.4-main.f9ba587",
40
- "@dxos/react-ui-theme": "0.8.4-main.f9ba587",
41
- "@dxos/storybook-utils": "0.8.4-main.f9ba587"
41
+ "react": "~19.2.3",
42
+ "react-dom": "~19.2.3",
43
+ "vite": "^7.1.11",
44
+ "@dxos/random": "0.8.4-main.fcfe5033a5",
45
+ "@dxos/storybook-utils": "0.8.4-main.fcfe5033a5",
46
+ "@dxos/ui-theme": "0.8.4-main.fcfe5033a5",
47
+ "@dxos/react-ui": "0.8.4-main.fcfe5033a5",
48
+ "@dxos/util": "0.8.4-main.fcfe5033a5"
42
49
  },
43
50
  "peerDependencies": {
44
- "react": "~18.2.0",
45
- "react-dom": "~18.2.0",
46
- "@dxos/react-ui": "0.8.4-main.f9ba587",
47
- "@dxos/react-ui-theme": "0.8.4-main.f9ba587"
51
+ "react": "~19.2.3",
52
+ "react-dom": "~19.2.3",
53
+ "@dxos/react-ui": "0.8.4-main.fcfe5033a5",
54
+ "@dxos/ui-theme": "0.8.4-main.fcfe5033a5"
48
55
  },
49
56
  "publishConfig": {
50
57
  "access": "public"
@@ -0,0 +1,106 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { type Meta, type StoryObj } from '@storybook/react-vite';
6
+ import React from 'react';
7
+
8
+ import { random } from '@dxos/random';
9
+ import { withLayout, withTheme } from '@dxos/react-ui/testing';
10
+
11
+ import { Json } from './Json';
12
+
13
+ random.seed(0);
14
+
15
+ const createNode = () => {
16
+ const data: Record<string, any> = {};
17
+ const keys = [...Array(random.number.int({ min: 1, max: 5 }))].map(() => random.lorem.word());
18
+ keys.forEach((key) => {
19
+ switch (random.helpers.arrayElement(['object', 'string', 'number', 'boolean', 'null'])) {
20
+ case 'object':
21
+ data[key] = createNode();
22
+ break;
23
+ case 'string':
24
+ data[key] = random.lorem.word();
25
+ break;
26
+ case 'number':
27
+ data[key] = random.number.int();
28
+ break;
29
+ case 'boolean':
30
+ data[key] = random.datatype.boolean();
31
+ break;
32
+ case 'null':
33
+ data[key] = null;
34
+ break;
35
+ }
36
+ });
37
+
38
+ return data;
39
+ };
40
+
41
+ const createData = ({ depth = 2, children = 3 } = {}): any => {
42
+ const createChildren = (root: any, d = 0) => {
43
+ if (d < depth) {
44
+ const num = random.number.int({ min: 1, max: Math.round(Math.log(depth + 1 - d) * children) });
45
+ root.children = [...new Array(num)].map(() => {
46
+ return createChildren(createNode(), d + 1);
47
+ });
48
+ }
49
+
50
+ return root;
51
+ };
52
+
53
+ return createChildren(createNode());
54
+ };
55
+
56
+ const createCycle = () => {
57
+ const data: any = {
58
+ a: 1,
59
+ b: [],
60
+ };
61
+
62
+ data.b.push(data);
63
+ return data;
64
+ };
65
+
66
+ const meta = {
67
+ title: 'ui/react-ui-syntax-highlighter/Json',
68
+ component: Json.Root,
69
+ decorators: [withTheme(), withLayout({ layout: 'column' })],
70
+ } satisfies Meta;
71
+
72
+ export default meta;
73
+
74
+ type Story = StoryObj<typeof meta>;
75
+
76
+ /** Standalone Json.Data — simplest usage. */
77
+ export const Default: Story = {
78
+ render: (args) => <Json.Data {...args} />,
79
+ args: {
80
+ data: createData(),
81
+ },
82
+ };
83
+
84
+ /** Circular reference handling. */
85
+ export const Cycle: Story = {
86
+ render: (args) => <Json.Data {...args} />,
87
+ args: {
88
+ data: createCycle(),
89
+ },
90
+ };
91
+
92
+ /** Large dataset with replacer. */
93
+ export const Filter: Story = {
94
+ render: (args) => (
95
+ <Json.Root {...args}>
96
+ <Json.Content>
97
+ <Json.Filter />
98
+ <Json.Data />
99
+ </Json.Content>
100
+ </Json.Root>
101
+ ),
102
+ args: {
103
+ data: createData({ depth: 5 }),
104
+ replacer: { maxDepth: 3, maxArrayLen: 10, maxStringLen: 10 },
105
+ },
106
+ };
package/src/Json/Json.tsx CHANGED
@@ -2,57 +2,189 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- // TODO(burdon): Move to jsonpath-plus.
6
- import jp from 'jsonpath';
7
- import React, { useEffect, useState } from 'react';
5
+ import { JSONPath } from 'jsonpath-plus';
6
+ import React, {
7
+ createContext,
8
+ type PropsWithChildren,
9
+ forwardRef,
10
+ useContext,
11
+ useEffect,
12
+ useMemo,
13
+ useState,
14
+ } from 'react';
8
15
 
9
- import { Input, type ThemedClassName } from '@dxos/react-ui';
10
- import { mx } from '@dxos/react-ui-theme';
16
+ import { Input } from '@dxos/react-ui';
17
+ import { composable, composableProps } from '@dxos/ui-theme';
18
+ import { type ComposableProps } from '@dxos/ui-types';
19
+ import { type CreateReplacerProps, createReplacer, safeStringify } from '@dxos/util';
11
20
 
12
21
  import { SyntaxHighlighter } from '../SyntaxHighlighter';
13
22
 
14
- export type JsonProps = ThemedClassName<{ data?: any; testId?: string }>;
23
+ //
24
+ // Context
25
+ //
15
26
 
16
- export const Json = ({ data, classNames, testId }: JsonProps) => {
17
- return (
18
- <SyntaxHighlighter language='json' classNames={['w-full', classNames]} data-testid={testId}>
19
- {JSON.stringify(data, null, 2)}
20
- </SyntaxHighlighter>
21
- );
27
+ type JsonContextType = {
28
+ data: any;
29
+ filteredData: any;
30
+ filterText: string;
31
+ setFilterText: (text: string) => void;
32
+ filterError: Error | null;
33
+ replacer?: CreateReplacerProps;
34
+ };
35
+
36
+ const JsonContext = createContext<JsonContextType | null>(null);
37
+
38
+ /** Require Json context (throws if used outside Json.Root). */
39
+ const useJsonContext = (consumerName: string): JsonContextType => {
40
+ const context = useContext(JsonContext);
41
+ if (!context) {
42
+ throw new Error(`\`${consumerName}\` must be used within \`Json.Root\`.`);
43
+ }
44
+ return context;
22
45
  };
23
46
 
24
- export const JsonFilter = ({ data: initialData, classNames, testId }: JsonProps) => {
25
- const [data, setData] = useState(initialData);
26
- const [text, setText] = useState('');
27
- const [error, setError] = useState<Error | null>(null);
47
+ /** Optional Json context (returns null outside Json.Root). */
48
+ const useOptionalJsonContext = (): JsonContextType | null => {
49
+ return useContext(JsonContext);
50
+ };
51
+
52
+ //
53
+ // Root
54
+ //
55
+
56
+ const JSON_ROOT_NAME = 'Json.Root';
57
+
58
+ type JsonRootProps = PropsWithChildren<{
59
+ data?: any;
60
+ replacer?: CreateReplacerProps;
61
+ }>;
62
+
63
+ /** Headless context provider for Json composite. */
64
+ const JsonRoot = forwardRef<HTMLDivElement, JsonRootProps>(({ children, data, replacer }, _forwardedRef) => {
65
+ const [filterText, setFilterText] = useState('');
66
+ const [filteredData, setFilteredData] = useState(data);
67
+ const [filterError, setFilterError] = useState<Error | null>(null);
68
+
28
69
  useEffect(() => {
29
- if (!initialData || !text.trim().length) {
30
- setData(initialData);
70
+ if (!filterText.trim().length) {
71
+ setFilteredData(data);
72
+ setFilterError(null);
31
73
  } else {
32
74
  try {
33
- setData(jp.query(initialData, text));
34
- setError(null);
75
+ setFilteredData(JSONPath({ path: filterText, json: data }));
76
+ setFilterError(null);
35
77
  } catch (err) {
36
- setData(initialData);
37
- setError(err as Error);
78
+ setFilteredData(data);
79
+ setFilterError(err as Error);
38
80
  }
39
81
  }
40
- }, [initialData, text]); // TODO(burdon): Need structural diff.
82
+ }, [data, filterText]);
83
+
84
+ const context = useMemo(
85
+ () => ({ data, filteredData, filterText, setFilterText, filterError, replacer }),
86
+ [data, filteredData, filterText, setFilterText, filterError, replacer],
87
+ );
88
+
89
+ return <JsonContext.Provider value={context}>{children}</JsonContext.Provider>;
90
+ });
91
+
92
+ JsonRoot.displayName = JSON_ROOT_NAME;
41
93
 
94
+ //
95
+ // Content
96
+ //
97
+
98
+ const JSON_CONTENT_NAME = 'Json.Content';
99
+
100
+ type JsonContentProps = ComposableProps;
101
+
102
+ /** Layout container for Json composite parts. */
103
+ const JsonContent = composable<HTMLDivElement, JsonContentProps>(({ children, ...props }, forwardedRef) => {
42
104
  return (
43
- <div className='flex flex-col grow overflow-hidden'>
44
- <Input.Root validationValence={error ? 'error' : 'success'}>
105
+ <div {...composableProps(props, { classNames: 'flex flex-col h-full min-h-0 overflow-hidden' })} ref={forwardedRef}>
106
+ {children}
107
+ </div>
108
+ );
109
+ });
110
+
111
+ JsonContent.displayName = JSON_CONTENT_NAME;
112
+
113
+ //
114
+ // Filter
115
+ //
116
+
117
+ const JSON_FILTER_NAME = 'Json.Filter';
118
+
119
+ type JsonFilterProps = ComposableProps<{
120
+ placeholder?: string;
121
+ }>;
122
+
123
+ /** JSONPath filter input. Must be used within Json.Root. */
124
+ const JsonFilter = forwardRef<HTMLInputElement, JsonFilterProps>(
125
+ ({ classNames, placeholder = 'JSONPath (e.g., $.graph.nodes)' }, forwardedRef) => {
126
+ const { filterText, setFilterText, filterError } = useJsonContext(JSON_FILTER_NAME);
127
+
128
+ return (
129
+ <Input.Root validationValence={filterError ? 'error' : 'success'}>
45
130
  <Input.TextInput
46
- classNames={mx('p-1 px-2 font-mono', error && 'border-red-500')}
131
+ classNames={['p-1 px-2 font-mono', filterError && 'border-rose-500', classNames]}
47
132
  variant='subdued'
48
- value={text}
49
- onChange={(event) => setText(event.target.value)}
50
- placeholder='JSONPath (e.g., $.graph.nodes)'
133
+ value={filterText}
134
+ placeholder={placeholder}
135
+ onChange={(event) => setFilterText(event.target.value)}
136
+ ref={forwardedRef}
51
137
  />
52
138
  </Input.Root>
53
- <SyntaxHighlighter language='json' classNames={mx('grow overflow-y-auto', classNames)} data-testid={testId}>
54
- {JSON.stringify(data, null, 2)}
139
+ );
140
+ },
141
+ );
142
+
143
+ JsonFilter.displayName = JSON_FILTER_NAME;
144
+
145
+ //
146
+ // Data
147
+ //
148
+
149
+ const JSON_DATA_NAME = 'Json.Data';
150
+
151
+ type JsonDataProps = ComposableProps<{
152
+ data?: any;
153
+ replacer?: CreateReplacerProps;
154
+ testId?: string;
155
+ }>;
156
+
157
+ /** Syntax-highlighted JSON display. Works standalone or within Json.Root. */
158
+ const JsonData = composable<HTMLDivElement, JsonDataProps>(
159
+ ({ data: dataProp, replacer: replacerProp, testId, ...props }, forwardedRef) => {
160
+ const context = useOptionalJsonContext();
161
+ const data = dataProp ?? context?.filteredData;
162
+ const replacer = replacerProp ?? context?.replacer;
163
+
164
+ return (
165
+ <SyntaxHighlighter
166
+ {...composableProps(props, { classNames: 'flex-1 min-h-0 w-full py-1 px-2 overflow-y-auto text-sm' })}
167
+ language='json'
168
+ data-testid={testId}
169
+ ref={forwardedRef}
170
+ >
171
+ {safeStringify(data, replacer && createReplacer(replacer), 2)}
55
172
  </SyntaxHighlighter>
56
- </div>
57
- );
173
+ );
174
+ },
175
+ );
176
+
177
+ JsonData.displayName = JSON_DATA_NAME;
178
+
179
+ //
180
+ // Json
181
+ //
182
+
183
+ export const Json = {
184
+ Root: JsonRoot,
185
+ Content: JsonContent,
186
+ Filter: JsonFilter,
187
+ Data: JsonData,
58
188
  };
189
+
190
+ export type { JsonRootProps, JsonContentProps, JsonFilterProps, JsonDataProps };
package/src/Json/index.ts CHANGED
@@ -2,4 +2,4 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- export * from './Json';
5
+ export { Json, type JsonRootProps, type JsonContentProps, type JsonFilterProps, type JsonDataProps } from './Json';
@@ -2,19 +2,23 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import '@dxos-theme';
6
-
7
5
  import { type Meta, type StoryObj } from '@storybook/react-vite';
8
6
 
9
- import { withTheme } from '@dxos/storybook-utils';
7
+ import { withLayout, withTheme } from '@dxos/react-ui/testing';
8
+ import { trim } from '@dxos/util';
10
9
 
10
+ // @ts-ignore - Vite raw import.
11
+ import TEXT from '../../package.json?raw';
11
12
  import { SyntaxHighlighter } from './SyntaxHighlighter';
12
13
 
13
- const meta: Meta<typeof SyntaxHighlighter> = {
14
+ const meta = {
14
15
  title: 'ui/react-ui-syntax-highlighter/SyntaxHighlighter',
15
16
  component: SyntaxHighlighter,
16
- decorators: [withTheme],
17
- };
17
+ decorators: [withTheme(), withLayout({ layout: 'column' })],
18
+ parameters: {
19
+ layout: 'fullscreen',
20
+ },
21
+ } satisfies Meta<typeof SyntaxHighlighter>;
18
22
 
19
23
  export default meta;
20
24
 
@@ -24,19 +28,21 @@ export const Default: Story = {
24
28
  args: {
25
29
  language: 'json',
26
30
  classNames: 'text-sm',
27
- children: JSON.stringify({ message: 'DXOS', initialized: true }, null, 2),
31
+ children: TEXT,
28
32
  },
29
33
  };
30
34
 
31
35
  export const Typescript: Story = {
32
36
  args: {
33
- language: 'ts',
34
- children: 'const x = 100;',
37
+ language: 'tsx',
38
+ children: trim`
39
+ import React from 'react'
40
+
41
+ const Test = () => {
42
+ return <div>Test</div>
43
+ }
44
+ `,
35
45
  },
36
46
  };
37
47
 
38
- export const Empty: Story = {
39
- args: {
40
- children: false,
41
- },
42
- };
48
+ export const Empty: Story = {};
@@ -2,48 +2,64 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import React from 'react';
6
- import { type SyntaxHighlighterProps as NativeSyntaxHighlighterProps } from 'react-syntax-highlighter';
7
- // Using `light-async` version directly from dist to avoid any chance of the heavy one being loaded.
8
- // Lightweight version will load specific language parsers asynchronously.
9
- // eslint-disable-next-line no-restricted-imports
10
- import NativeSyntaxHighlighter from 'react-syntax-highlighter/dist/esm/light-async';
11
- // eslint-disable-next-line no-restricted-imports
12
- import { github as light, a11yDark as dark } from 'react-syntax-highlighter/dist/esm/styles/hljs';
13
-
14
- import { type ThemedClassName, useThemeContext } from '@dxos/react-ui';
15
- import { mx } from '@dxos/react-ui-theme';
5
+ import React, { CSSProperties } from 'react';
6
+ import { type SyntaxHighlighterProps as NaturalSyntaxHighlighterProps } from 'react-syntax-highlighter';
7
+ import NativeSyntaxHighlighter from 'react-syntax-highlighter/dist/esm/prism-async-light';
8
+ import { coldarkDark as dark, coldarkCold as light } from 'react-syntax-highlighter/dist/esm/styles/prism';
9
+
10
+ import { ScrollArea, useThemeContext } from '@dxos/react-ui';
11
+ import { composable, composableProps } from '@dxos/ui-theme';
16
12
 
17
13
  const zeroWidthSpace = '\u200b';
18
14
 
19
- export type SyntaxHighlighterProps = ThemedClassName<
20
- NativeSyntaxHighlighterProps & {
21
- fallback?: string;
22
- }
23
- >;
15
+ const languages = {
16
+ js: 'javascript',
17
+ ts: 'typescript',
18
+ };
24
19
 
25
- light.hljs.background = '';
26
- dark.hljs.background = '';
20
+ export type SyntaxHighlighterProps = NaturalSyntaxHighlighterProps & {
21
+ fallback?: string;
22
+ };
27
23
 
28
24
  /**
25
+ * NOTE: Using `light-async` version directly from dist to avoid any chance of the heavy one being loaded.
26
+ * The lightweight version will load specific language parsers asynchronously.
27
+ *
29
28
  * https://github.com/react-syntax-highlighter/react-syntax-highlighter
29
+ * https://react-syntax-highlighter.github.io/react-syntax-highlighter/demo/prism.html
30
30
  */
31
- export const SyntaxHighlighter = ({
32
- classNames,
33
- children,
34
- fallback = zeroWidthSpace,
35
- ...props
36
- }: SyntaxHighlighterProps) => {
37
- const { themeMode } = useThemeContext();
38
-
39
- return (
40
- <NativeSyntaxHighlighter
41
- className={mx('w-full p-0 font-thin overflow-auto scrollbar-thin !text-baseText', classNames)}
42
- style={themeMode === 'dark' ? dark : light}
43
- {...props}
44
- >
45
- {/* Non-empty fallback prevents collapse. */}
46
- {children || fallback}
47
- </NativeSyntaxHighlighter>
48
- );
49
- };
31
+ export const SyntaxHighlighter = composable<HTMLDivElement, SyntaxHighlighterProps>(
32
+ (
33
+ { children, language = 'text', fallback = zeroWidthSpace, classNames, className, style, ...nativeProps },
34
+ forwardedRef,
35
+ ) => {
36
+ const { themeMode } = useThemeContext();
37
+
38
+ return (
39
+ <ScrollArea.Root {...composableProps({ classNames, className })} thin ref={forwardedRef}>
40
+ <ScrollArea.Viewport>
41
+ {/* NOTE: The div prevents NativeSyntaxHighlighter from managing scrolling. */}
42
+ <div role='none'>
43
+ <NativeSyntaxHighlighter
44
+ language={languages[language as keyof typeof languages] || language}
45
+ style={(style as { [key: string]: CSSProperties }) ?? (themeMode === 'dark' ? dark : light)}
46
+ customStyle={{
47
+ background: 'unset',
48
+ border: 'none',
49
+ boxShadow: 'none',
50
+ padding: 0,
51
+ margin: 0,
52
+ }}
53
+ {...nativeProps}
54
+ >
55
+ {/* Non-empty fallback prevents collapse. */}
56
+ {children || fallback}
57
+ </NativeSyntaxHighlighter>
58
+ </div>
59
+ </ScrollArea.Viewport>
60
+ </ScrollArea.Root>
61
+ );
62
+ },
63
+ );
64
+
65
+ SyntaxHighlighter.displayName = 'SyntaxHighlighter';