@object-ui/react 0.5.0 → 3.0.0

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.
Files changed (144) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/dist/LazyPluginLoader.d.ts +44 -0
  4. package/dist/LazyPluginLoader.js +92 -3
  5. package/dist/SchemaRenderer.d.ts +20 -1
  6. package/dist/SchemaRenderer.js +76 -13
  7. package/dist/components/form/FieldFactory.js +44 -40
  8. package/dist/components/form/FormRenderer.js +45 -3
  9. package/dist/context/ActionContext.d.ts +76 -0
  10. package/dist/context/ActionContext.js +139 -0
  11. package/dist/context/DndContext.d.ts +135 -0
  12. package/dist/context/DndContext.js +120 -0
  13. package/dist/context/NotificationContext.d.ts +113 -0
  14. package/dist/context/NotificationContext.js +130 -0
  15. package/dist/context/ThemeContext.d.ts +94 -0
  16. package/dist/context/ThemeContext.js +215 -0
  17. package/dist/context/index.d.ts +4 -0
  18. package/dist/context/index.js +4 -0
  19. package/dist/hooks/index.d.ts +22 -0
  20. package/dist/hooks/index.js +22 -0
  21. package/dist/hooks/useActionRunner.d.ts +21 -7
  22. package/dist/hooks/useActionRunner.js +27 -7
  23. package/dist/hooks/useAnimation.d.ts +46 -0
  24. package/dist/hooks/useAnimation.js +59 -0
  25. package/dist/hooks/useClientNotifications.d.ts +53 -0
  26. package/dist/hooks/useClientNotifications.js +190 -0
  27. package/dist/hooks/useColumnSummary.d.ts +38 -0
  28. package/dist/hooks/useColumnSummary.js +54 -0
  29. package/dist/hooks/useCrudShortcuts.d.ts +39 -0
  30. package/dist/hooks/useCrudShortcuts.js +96 -0
  31. package/dist/hooks/useDensityMode.d.ts +48 -0
  32. package/dist/hooks/useDensityMode.js +60 -0
  33. package/dist/hooks/useDiscovery.d.ts +78 -0
  34. package/dist/hooks/useDiscovery.js +96 -0
  35. package/dist/hooks/useDynamicApp.d.ts +70 -0
  36. package/dist/hooks/useDynamicApp.js +92 -0
  37. package/dist/hooks/useETagCache.d.ts +75 -0
  38. package/dist/hooks/useETagCache.js +306 -0
  39. package/dist/hooks/useFocusManagement.d.ts +89 -0
  40. package/dist/hooks/useFocusManagement.js +188 -0
  41. package/dist/hooks/useFocusTrap.d.ts +41 -0
  42. package/dist/hooks/useFocusTrap.js +103 -0
  43. package/dist/hooks/useKeyboardShortcuts.d.ts +49 -0
  44. package/dist/hooks/useKeyboardShortcuts.js +86 -0
  45. package/dist/hooks/useNavigationOverlay.d.ts +78 -0
  46. package/dist/hooks/useNavigationOverlay.js +112 -0
  47. package/dist/hooks/useOffline.d.ts +96 -0
  48. package/dist/hooks/useOffline.js +185 -0
  49. package/dist/hooks/usePageTransition.d.ts +60 -0
  50. package/dist/hooks/usePageTransition.js +111 -0
  51. package/dist/hooks/usePageVariables.d.ts +67 -0
  52. package/dist/hooks/usePageVariables.js +109 -0
  53. package/dist/hooks/usePerformance.d.ts +87 -0
  54. package/dist/hooks/usePerformance.js +165 -0
  55. package/dist/hooks/usePerformanceBudget.d.ts +78 -0
  56. package/dist/hooks/usePerformanceBudget.js +209 -0
  57. package/dist/hooks/useReducedMotion.d.ts +28 -0
  58. package/dist/hooks/useReducedMotion.js +48 -0
  59. package/dist/hooks/useSchemaPersistence.d.ts +87 -0
  60. package/dist/hooks/useSchemaPersistence.js +173 -0
  61. package/dist/hooks/useViewData.d.ts +73 -0
  62. package/dist/hooks/useViewData.js +135 -0
  63. package/dist/hooks/useViewSharing.d.ts +57 -0
  64. package/dist/hooks/useViewSharing.js +74 -0
  65. package/dist/hooks/useViewTransition.d.ts +54 -0
  66. package/dist/hooks/useViewTransition.js +83 -0
  67. package/dist/index.d.ts +1 -0
  68. package/dist/index.js +2 -0
  69. package/dist/utils/i18n.d.ts +10 -0
  70. package/dist/utils/i18n.js +12 -0
  71. package/package.json +7 -5
  72. package/src/LazyPluginLoader.tsx +129 -7
  73. package/src/SchemaRenderer.tsx +122 -13
  74. package/src/__tests__/LazyPluginLoader.test.tsx +97 -1
  75. package/src/__tests__/SchemaRenderer.aria.test.tsx +118 -0
  76. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +114 -0
  77. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +132 -0
  78. package/src/__tests__/ThemeProvider.test.tsx +451 -0
  79. package/src/__tests__/useNavigationOverlay.test.ts +416 -0
  80. package/src/__tests__/useOffline.test.ts +198 -0
  81. package/src/__tests__/usePageTransition.test.ts +214 -0
  82. package/src/__tests__/usePageVariables.test.tsx +334 -0
  83. package/src/__tests__/usePerformance.test.ts +137 -0
  84. package/src/__tests__/useViewData.test.tsx +422 -0
  85. package/src/__tests__/view-switching.test.tsx +456 -0
  86. package/src/components/form/FieldFactory.tsx +51 -46
  87. package/src/components/form/FormRenderer.test.tsx +145 -0
  88. package/src/components/form/FormRenderer.tsx +52 -3
  89. package/src/context/ActionContext.tsx +213 -0
  90. package/src/context/DndContext.tsx +260 -0
  91. package/src/context/NotificationContext.tsx +280 -0
  92. package/src/context/ThemeContext.tsx +325 -0
  93. package/src/context/__tests__/ActionContext.test.tsx +174 -0
  94. package/src/context/__tests__/DndContext.test.tsx +150 -0
  95. package/src/context/__tests__/NotificationContext.test.tsx +176 -0
  96. package/src/context/index.ts +4 -0
  97. package/src/hooks/__tests__/useActionRunner.test.ts +153 -0
  98. package/src/hooks/__tests__/useAnimation.test.ts +82 -0
  99. package/src/hooks/__tests__/useColumnSummary.test.ts +93 -0
  100. package/src/hooks/__tests__/useDensityMode.test.ts +81 -0
  101. package/src/hooks/__tests__/useDiscovery.test.tsx +149 -0
  102. package/src/hooks/__tests__/useDynamicApp.test.ts +161 -0
  103. package/src/hooks/__tests__/useETagCache.test.ts +153 -0
  104. package/src/hooks/__tests__/useExpression.test.ts +86 -0
  105. package/src/hooks/__tests__/useFocusTrap.test.ts +47 -0
  106. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +144 -0
  107. package/src/hooks/__tests__/usePerformanceBudget.test.ts +157 -0
  108. package/src/hooks/__tests__/useSchemaPersistence.test.ts +220 -0
  109. package/src/hooks/__tests__/useViewSharing.test.ts +121 -0
  110. package/src/hooks/__tests__/useViewTransition.test.ts +61 -0
  111. package/src/hooks/index.ts +22 -1
  112. package/src/hooks/useActionRunner.ts +49 -11
  113. package/src/hooks/useAnimation.ts +117 -0
  114. package/src/hooks/useClientNotifications.ts +251 -0
  115. package/src/hooks/useColumnSummary.ts +87 -0
  116. package/src/hooks/useCrudShortcuts.ts +126 -0
  117. package/src/hooks/useDensityMode.ts +102 -0
  118. package/src/hooks/useDiscovery.ts +141 -0
  119. package/src/hooks/useDynamicApp.ts +142 -0
  120. package/src/hooks/useETagCache.ts +404 -0
  121. package/src/hooks/useFocusManagement.ts +248 -0
  122. package/src/hooks/useFocusTrap.ts +138 -0
  123. package/src/hooks/useKeyboardShortcuts.ts +119 -0
  124. package/src/hooks/useNavigationOverlay.ts +180 -0
  125. package/src/hooks/useOffline.ts +301 -0
  126. package/src/hooks/usePageTransition.ts +187 -0
  127. package/src/hooks/usePageVariables.tsx +157 -0
  128. package/src/hooks/usePerformance.ts +246 -0
  129. package/src/hooks/usePerformanceBudget.ts +313 -0
  130. package/src/hooks/useReducedMotion.ts +53 -0
  131. package/src/hooks/useSchemaPersistence.ts +222 -0
  132. package/src/hooks/useViewData.ts +201 -0
  133. package/src/hooks/useViewSharing.ts +140 -0
  134. package/src/hooks/useViewTransition.ts +144 -0
  135. package/src/index.ts +21 -0
  136. package/src/utils/i18n.ts +10 -0
  137. package/tsconfig.json +1 -0
  138. package/tsconfig.tsbuildinfo +1 -1
  139. package/dist/__tests__/LazyPluginLoader.test.d.ts +0 -8
  140. package/dist/__tests__/LazyPluginLoader.test.js +0 -49
  141. package/dist/components/form/FormRenderer.test.d.ts +0 -8
  142. package/dist/components/form/FormRenderer.test.js +0 -534
  143. package/dist/index.test.d.ts +0 -8
  144. package/dist/index.test.js +0 -13
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@object-ui/react",
3
- "version": "0.5.0",
3
+ "version": "3.0.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "React bindings and SchemaRenderer component for Object UI",
@@ -23,17 +23,19 @@
23
23
  }
24
24
  },
25
25
  "dependencies": {
26
- "@objectstack/spec": "^0.9.1",
26
+ "@objectstack/spec": "^3.0.2",
27
27
  "react-hook-form": "^7.71.1",
28
- "@object-ui/core": "0.5.0"
28
+ "@object-ui/core": "3.0.0",
29
+ "@object-ui/types": "3.0.0",
30
+ "@object-ui/i18n": "3.0.0"
29
31
  },
30
32
  "peerDependencies": {
31
33
  "react": "^18.0.0 || ^19.0.0",
32
34
  "react-dom": "^18.0.0 || ^19.0.0"
33
35
  },
34
36
  "devDependencies": {
35
- "@types/react": "^19.2.10",
36
- "@types/react-dom": "^19.2.3",
37
+ "@types/react": "19.2.13",
38
+ "@types/react-dom": "19.2.3",
37
39
  "typescript": "^5.9.3"
38
40
  },
39
41
  "scripts": {
@@ -6,13 +6,83 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
 
9
- import React, { lazy, Suspense } from 'react';
9
+ import React, { lazy, Suspense, Component } from 'react';
10
10
 
11
11
  export interface LazyPluginOptions {
12
12
  /**
13
13
  * Fallback component to show while loading
14
14
  */
15
15
  fallback?: React.ReactNode;
16
+ /**
17
+ * Number of retry attempts on load failure (default: 2)
18
+ */
19
+ retries?: number;
20
+ /**
21
+ * Delay in ms between retries (default: 1000)
22
+ */
23
+ retryDelay?: number;
24
+ /**
25
+ * Custom error fallback component
26
+ */
27
+ errorFallback?: React.ComponentType<{ error: Error; retry: () => void }>;
28
+ }
29
+
30
+ /**
31
+ * Error boundary for lazy-loaded plugins
32
+ */
33
+ interface ErrorBoundaryState {
34
+ hasError: boolean;
35
+ error: Error | null;
36
+ }
37
+
38
+ class PluginErrorBoundary extends Component<
39
+ { fallback?: React.ComponentType<{ error: Error; retry: () => void }>; children: React.ReactNode },
40
+ ErrorBoundaryState
41
+ > {
42
+ state: ErrorBoundaryState = { hasError: false, error: null };
43
+
44
+ static getDerivedStateFromError(error: Error): ErrorBoundaryState {
45
+ return { hasError: true, error };
46
+ }
47
+
48
+ handleRetry = () => {
49
+ this.setState({ hasError: false, error: null });
50
+ };
51
+
52
+ render() {
53
+ if (this.state.hasError && this.state.error) {
54
+ const FallbackComponent = this.props.fallback;
55
+ if (FallbackComponent) {
56
+ return <FallbackComponent error={this.state.error} retry={this.handleRetry} />;
57
+ }
58
+ return null;
59
+ }
60
+ return this.props.children;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Create a lazy-loaded import function with retry support
66
+ */
67
+ function createRetryImport<P extends object>(
68
+ importFn: () => Promise<{ default: React.ComponentType<P> }>,
69
+ retries: number,
70
+ retryDelay: number,
71
+ ): () => Promise<{ default: React.ComponentType<P> }> {
72
+ return () => {
73
+ let attempt = 0;
74
+ const tryImport = (): Promise<{ default: React.ComponentType<P> }> =>
75
+ importFn().catch((err) => {
76
+ attempt++;
77
+ if (attempt <= retries) {
78
+ return new Promise((resolve) =>
79
+ setTimeout(() => resolve(tryImport()), retryDelay),
80
+ );
81
+ }
82
+ throw err;
83
+ });
84
+ return tryImport();
85
+ };
16
86
  }
17
87
 
18
88
  /**
@@ -34,19 +104,71 @@ export interface LazyPluginOptions {
34
104
  * () => import('@object-ui/plugin-grid'),
35
105
  * { fallback: <div>Loading grid...</div> }
36
106
  * );
107
+ *
108
+ * // With retry and error handling
109
+ * const ObjectGrid = createLazyPlugin(
110
+ * () => import('@object-ui/plugin-grid'),
111
+ * {
112
+ * retries: 3,
113
+ * errorFallback: ({ error, retry }) => (
114
+ * <div>
115
+ * <p>Failed to load: {error.message}</p>
116
+ * <button onClick={retry}>Retry</button>
117
+ * </div>
118
+ * ),
119
+ * }
120
+ * );
37
121
  * ```
38
122
  */
39
123
  export function createLazyPlugin<P extends object = any>(
40
124
  importFn: () => Promise<{ default: React.ComponentType<P> }>,
41
125
  options?: LazyPluginOptions
42
126
  ): React.ComponentType<P> {
43
- const LazyComponent = lazy(importFn);
127
+ const { retries = 2, retryDelay = 1000, errorFallback } = options || {};
128
+
129
+ const retryImport = retries > 0
130
+ ? createRetryImport(importFn, retries, retryDelay)
131
+ : importFn;
132
+
133
+ const LazyComponent = lazy(retryImport);
44
134
 
45
- const PluginWrapper: React.FC<P> = (props) => (
46
- <Suspense fallback={options?.fallback || null}>
47
- <LazyComponent {...props} />
48
- </Suspense>
49
- );
135
+ const PluginWrapper: React.FC<P> = (props) => {
136
+ const content = (
137
+ <Suspense fallback={options?.fallback || null}>
138
+ <LazyComponent {...props} />
139
+ </Suspense>
140
+ );
141
+
142
+ if (errorFallback) {
143
+ return (
144
+ <PluginErrorBoundary fallback={errorFallback}>
145
+ {content}
146
+ </PluginErrorBoundary>
147
+ );
148
+ }
149
+
150
+ return content;
151
+ };
50
152
 
51
153
  return PluginWrapper;
52
154
  }
155
+
156
+ /**
157
+ * Preload a plugin module without rendering it.
158
+ * Useful for preloading plugins that will be needed soon.
159
+ *
160
+ * @param importFn - Dynamic import function
161
+ * @returns Promise that resolves when the module is loaded
162
+ *
163
+ * @example
164
+ * ```tsx
165
+ * // Preload on hover
166
+ * const loadGrid = () => import('@object-ui/plugin-grid');
167
+ * <button onMouseEnter={() => preloadPlugin(loadGrid)}>Show Grid</button>
168
+ * ```
169
+ */
170
+ export function preloadPlugin<T = unknown>(
171
+ importFn: () => Promise<T>,
172
+ ): Promise<T> {
173
+ return importFn();
174
+ }
@@ -6,9 +6,100 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
 
9
- import React, { forwardRef, useContext, useMemo } from 'react';
10
- import { SchemaNode, ComponentRegistry, ExpressionEvaluator } from '@object-ui/core';
9
+ import React, { forwardRef, useContext, useMemo, Component } from 'react';
10
+ import {
11
+ SchemaNode,
12
+ ComponentRegistry,
13
+ ExpressionEvaluator,
14
+ isObjectUIError,
15
+ type ObjectUIError,
16
+ ERROR_CODES,
17
+ debugLog,
18
+ debugTime,
19
+ debugTimeEnd,
20
+ } from '@object-ui/core';
11
21
  import { SchemaRendererContext } from './context/SchemaRendererContext';
22
+ import { resolveI18nLabel } from './utils/i18n';
23
+
24
+ /**
25
+ * Extract AriaPropsSchema properties from a schema node and convert
26
+ * them to standard HTML ARIA attributes.
27
+ *
28
+ * @objectstack/spec AriaPropsSchema defines:
29
+ * ariaLabel: string | I18nLabel (→ aria-label)
30
+ * ariaDescribedBy: string (→ aria-describedby)
31
+ * role: string (→ role)
32
+ */
33
+ function resolveAriaProps(schema: Record<string, any>): Record<string, string | undefined> {
34
+ const aria: Record<string, string | undefined> = {};
35
+ if (schema.ariaLabel) {
36
+ aria['aria-label'] = resolveI18nLabel(schema.ariaLabel);
37
+ }
38
+ if (schema.ariaDescribedBy) {
39
+ aria['aria-describedby'] = schema.ariaDescribedBy;
40
+ }
41
+ if (schema.role) {
42
+ aria['role'] = schema.role;
43
+ }
44
+ return aria;
45
+ }
46
+
47
+ /**
48
+ * Per-component Error Boundary for SchemaRenderer.
49
+ * Catches render errors in individual components, preventing one broken
50
+ * component from crashing the entire page.
51
+ */
52
+ interface SchemaErrorBoundaryState {
53
+ hasError: boolean;
54
+ error: Error | null;
55
+ }
56
+
57
+ export class SchemaErrorBoundary extends Component<
58
+ { componentType?: string; children: React.ReactNode },
59
+ SchemaErrorBoundaryState
60
+ > {
61
+ state: SchemaErrorBoundaryState = { hasError: false, error: null };
62
+
63
+ static getDerivedStateFromError(error: Error): SchemaErrorBoundaryState {
64
+ return { hasError: true, error };
65
+ }
66
+
67
+ handleRetry = () => {
68
+ this.setState({ hasError: false, error: null });
69
+ };
70
+
71
+ render() {
72
+ if (this.state.hasError && this.state.error) {
73
+ const error = this.state.error;
74
+ const isDev = process.env.NODE_ENV !== 'production';
75
+ const objuiError = isObjectUIError(error) ? error as ObjectUIError : null;
76
+
77
+ return (
78
+ <div className="p-4 border border-orange-400 rounded bg-orange-50 text-orange-700 my-2" role="alert">
79
+ <p className="font-medium">
80
+ Component{this.props.componentType ? ` "${this.props.componentType}"` : ''} failed to render
81
+ </p>
82
+ <p className="text-sm mt-1">{error.message}</p>
83
+ {isDev && objuiError?.code && (
84
+ <p className="text-xs mt-1 text-orange-500">
85
+ Error code: {objuiError.code}
86
+ {objuiError.details?.suggestion ? (
87
+ <span className="block mt-0.5">💡 {String(objuiError.details.suggestion)}</span>
88
+ ) : null}
89
+ </p>
90
+ )}
91
+ <button
92
+ onClick={this.handleRetry}
93
+ className="mt-2 text-sm underline hover:no-underline"
94
+ >
95
+ Retry
96
+ </button>
97
+ </div>
98
+ );
99
+ }
100
+ return this.props.children;
101
+ }
102
+ }
12
103
 
13
104
  export const SchemaRenderer = forwardRef<any, { schema: SchemaNode } & Record<string, any>>(({ schema, ...props }, _ref) => {
14
105
  const context = useContext(SchemaRendererContext);
@@ -48,13 +139,20 @@ export const SchemaRenderer = forwardRef<any, { schema: SchemaNode } & Record<st
48
139
  if (!evaluatedSchema) return null;
49
140
  // If schema is just a string, render it as text
50
141
  if (typeof evaluatedSchema === 'string') return <>{evaluatedSchema}</>;
142
+
143
+ debugLog('schema', 'Rendering schema node', { type: evaluatedSchema.type, id: evaluatedSchema.id });
51
144
 
52
145
  const Component = ComponentRegistry.get(evaluatedSchema.type);
53
146
 
54
147
  if (!Component) {
148
+ debugLog('schema', 'Component not found in registry', { type: evaluatedSchema.type });
149
+ const errorInfo = ERROR_CODES['OBJUI-001'];
55
150
  return (
56
- <div className="p-4 border border-red-500 rounded text-red-500 bg-red-50 my-2">
57
- Unknown component type: <strong>{evaluatedSchema.type}</strong>
151
+ <div className="p-4 border border-red-500 rounded text-red-500 bg-red-50 my-2" role="alert">
152
+ <p className="font-medium">Unknown component type: <strong>{evaluatedSchema.type}</strong></p>
153
+ {process.env.NODE_ENV !== 'production' && (
154
+ <p className="text-xs mt-1">💡 {errorInfo.suggestion} (OBJUI-001)</p>
155
+ )}
58
156
  <pre className="text-xs mt-2 overflow-auto">{JSON.stringify(evaluatedSchema, null, 2)}</pre>
59
157
  </div>
60
158
  );
@@ -78,14 +176,25 @@ export const SchemaRenderer = forwardRef<any, { schema: SchemaNode } & Record<st
78
176
  ...componentProps
79
177
  } = evaluatedSchema;
80
178
 
81
- return React.createElement(Component, {
82
- schema: evaluatedSchema,
83
- ...componentProps, // Spread non-metadata schema properties as props
84
- ...(evaluatedSchema.props || {}), // Override with explicit props if provided
85
- className: evaluatedSchema.className,
86
- 'data-obj-id': evaluatedSchema.id,
87
- 'data-obj-type': evaluatedSchema.type,
88
- ...props
89
- });
179
+ // Extract AriaPropsSchema properties for accessibility
180
+ const ariaProps = resolveAriaProps(evaluatedSchema);
181
+
182
+ debugTime(`render:${evaluatedSchema.type}:${evaluatedSchema.id ?? 'anon'}`);
183
+ const rendered = (
184
+ <SchemaErrorBoundary componentType={evaluatedSchema.type}>
185
+ {React.createElement(Component, {
186
+ schema: evaluatedSchema,
187
+ ...componentProps, // Spread non-metadata schema properties as props
188
+ ...(evaluatedSchema.props || {}), // Override with explicit props if provided
189
+ ...ariaProps, // Inject ARIA attributes from AriaPropsSchema
190
+ className: evaluatedSchema.className,
191
+ 'data-obj-id': evaluatedSchema.id,
192
+ 'data-obj-type': evaluatedSchema.type,
193
+ ...props
194
+ })}
195
+ </SchemaErrorBoundary>
196
+ );
197
+ debugTimeEnd(`render:${evaluatedSchema.type}:${evaluatedSchema.id ?? 'anon'}`);
198
+ return rendered;
90
199
  });
91
200
  SchemaRenderer.displayName = 'SchemaRenderer';
@@ -9,7 +9,7 @@
9
9
  import { describe, it, expect, vi } from 'vitest';
10
10
  import { render, screen, waitFor } from '@testing-library/react';
11
11
  import React from 'react';
12
- import { createLazyPlugin } from '../LazyPluginLoader';
12
+ import { createLazyPlugin, preloadPlugin } from '../LazyPluginLoader';
13
13
 
14
14
  describe('createLazyPlugin', () => {
15
15
  it('should create a lazy-loaded component', async () => {
@@ -77,4 +77,100 @@ describe('createLazyPlugin', () => {
77
77
  // Restore console.error
78
78
  console.error = originalError;
79
79
  });
80
+
81
+ it('should preload a plugin without rendering', async () => {
82
+ const TestComponent = () => <div>Preloaded</div>;
83
+ const importFn = vi.fn(() => Promise.resolve({ default: TestComponent }));
84
+
85
+ const result = await preloadPlugin(importFn);
86
+
87
+ expect(importFn).toHaveBeenCalledTimes(1);
88
+ expect(result).toEqual({ default: TestComponent });
89
+ });
90
+
91
+ it('should render errorFallback when component fails to load', async () => {
92
+ const originalError = console.error;
93
+ console.error = vi.fn();
94
+
95
+ const ErrorFallback = ({ error, retry }: { error: Error; retry: () => void }) => (
96
+ <div>
97
+ <span>Error: {error.message}</span>
98
+ <button onClick={retry}>Retry</button>
99
+ </div>
100
+ );
101
+
102
+ const LazyComponent = createLazyPlugin(
103
+ () => Promise.reject(new Error('chunk failed')),
104
+ { retries: 0, errorFallback: ErrorFallback }
105
+ );
106
+
107
+ render(<LazyComponent />);
108
+
109
+ await waitFor(() => {
110
+ expect(screen.getByText('Error: chunk failed')).toBeInTheDocument();
111
+ });
112
+
113
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
114
+
115
+ console.error = originalError;
116
+ });
117
+
118
+ it('should not retry when retries=0', async () => {
119
+ const originalError = console.error;
120
+ console.error = vi.fn();
121
+
122
+ const importFn = vi.fn(() => Promise.reject(new Error('fail')));
123
+
124
+ const ErrorFallback = ({ error }: { error: Error; retry: () => void }) => (
125
+ <div>Error: {error.message}</div>
126
+ );
127
+
128
+ const LazyComponent = createLazyPlugin(importFn, {
129
+ retries: 0,
130
+ errorFallback: ErrorFallback,
131
+ });
132
+
133
+ render(<LazyComponent />);
134
+
135
+ await waitFor(() => {
136
+ expect(screen.getByText('Error: fail')).toBeInTheDocument();
137
+ });
138
+
139
+ // Called only once — no retries
140
+ expect(importFn).toHaveBeenCalledTimes(1);
141
+
142
+ console.error = originalError;
143
+ });
144
+
145
+ it('should retry on failure then succeed', async () => {
146
+ const originalError = console.error;
147
+ console.error = vi.fn();
148
+
149
+ const TestComponent = () => <div>Success after retry</div>;
150
+
151
+ let callCount = 0;
152
+ const importFn = vi.fn(() => {
153
+ callCount++;
154
+ if (callCount <= 2) {
155
+ return Promise.reject(new Error('transient error'));
156
+ }
157
+ return Promise.resolve({ default: TestComponent as React.ComponentType });
158
+ });
159
+
160
+ const LazyComponent = createLazyPlugin(importFn, {
161
+ retries: 3,
162
+ retryDelay: 10,
163
+ });
164
+
165
+ render(<LazyComponent />);
166
+
167
+ await waitFor(() => {
168
+ expect(screen.getByText('Success after retry')).toBeInTheDocument();
169
+ }, { timeout: 5000 });
170
+
171
+ // First call + 2 retries (fails) + 1 success = called 3 times
172
+ expect(importFn).toHaveBeenCalledTimes(3);
173
+
174
+ console.error = originalError;
175
+ });
80
176
  });
@@ -0,0 +1,118 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
10
+ import { render, screen } from '@testing-library/react';
11
+ import React from 'react';
12
+ import { ComponentRegistry } from '@object-ui/core';
13
+ import { SchemaRenderer } from '../SchemaRenderer';
14
+
15
+ // A simple test component that forwards ARIA attributes
16
+ const TestWidget: React.FC<any> = (props) => (
17
+ <div
18
+ data-testid="test-widget"
19
+ aria-label={props['aria-label']}
20
+ aria-describedby={props['aria-describedby']}
21
+ role={props['role']}
22
+ >
23
+ {props.content || 'Test'}
24
+ </div>
25
+ );
26
+
27
+ describe('SchemaRenderer AriaProps injection', () => {
28
+ beforeEach(() => {
29
+ ComponentRegistry.register('test-widget', TestWidget);
30
+ });
31
+
32
+ afterEach(() => {
33
+ ComponentRegistry.unregister?.('test-widget');
34
+ });
35
+
36
+ it('should inject aria-label from ariaLabel string', () => {
37
+ render(
38
+ <SchemaRenderer
39
+ schema={{
40
+ type: 'test-widget',
41
+ ariaLabel: 'Close dialog',
42
+ }}
43
+ />
44
+ );
45
+ const el = screen.getByTestId('test-widget');
46
+ expect(el).toHaveAttribute('aria-label', 'Close dialog');
47
+ });
48
+
49
+ it('should resolve ariaLabel from I18nLabel object', () => {
50
+ render(
51
+ <SchemaRenderer
52
+ schema={{
53
+ type: 'test-widget',
54
+ ariaLabel: { key: 'dialog.close', defaultValue: 'Close dialog' },
55
+ }}
56
+ />
57
+ );
58
+ const el = screen.getByTestId('test-widget');
59
+ expect(el).toHaveAttribute('aria-label', 'Close dialog');
60
+ });
61
+
62
+ it('should inject aria-describedby from ariaDescribedBy', () => {
63
+ render(
64
+ <SchemaRenderer
65
+ schema={{
66
+ type: 'test-widget',
67
+ ariaDescribedBy: 'help-text-1',
68
+ }}
69
+ />
70
+ );
71
+ const el = screen.getByTestId('test-widget');
72
+ expect(el).toHaveAttribute('aria-describedby', 'help-text-1');
73
+ });
74
+
75
+ it('should inject role from schema', () => {
76
+ render(
77
+ <SchemaRenderer
78
+ schema={{
79
+ type: 'test-widget',
80
+ role: 'navigation',
81
+ }}
82
+ />
83
+ );
84
+ const el = screen.getByTestId('test-widget');
85
+ expect(el).toHaveAttribute('role', 'navigation');
86
+ });
87
+
88
+ it('should inject all ARIA props together', () => {
89
+ render(
90
+ <SchemaRenderer
91
+ schema={{
92
+ type: 'test-widget',
93
+ ariaLabel: 'Main nav',
94
+ ariaDescribedBy: 'nav-desc',
95
+ role: 'navigation',
96
+ }}
97
+ />
98
+ );
99
+ const el = screen.getByTestId('test-widget');
100
+ expect(el).toHaveAttribute('aria-label', 'Main nav');
101
+ expect(el).toHaveAttribute('aria-describedby', 'nav-desc');
102
+ expect(el).toHaveAttribute('role', 'navigation');
103
+ });
104
+
105
+ it('should not inject ARIA attrs when not in schema', () => {
106
+ render(
107
+ <SchemaRenderer
108
+ schema={{
109
+ type: 'test-widget',
110
+ content: 'Hello',
111
+ }}
112
+ />
113
+ );
114
+ const el = screen.getByTestId('test-widget');
115
+ expect(el).not.toHaveAttribute('aria-label');
116
+ expect(el).not.toHaveAttribute('aria-describedby');
117
+ });
118
+ });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
10
+ import { render, screen, fireEvent } from '@testing-library/react';
11
+ import React from 'react';
12
+ import { ComponentRegistry } from '@object-ui/core';
13
+ import { SchemaRenderer, SchemaErrorBoundary } from '../SchemaRenderer';
14
+
15
+ // Suppress console.error from React error boundary during tests
16
+ const originalConsoleError = console.error;
17
+ beforeEach(() => {
18
+ console.error = vi.fn();
19
+ });
20
+ afterEach(() => {
21
+ console.error = originalConsoleError;
22
+ });
23
+
24
+ const CrashingWidget: React.FC = () => {
25
+ throw new Error('Widget exploded!');
26
+ };
27
+
28
+ const StableWidget: React.FC<any> = (props) => (
29
+ <div data-testid="stable-widget">{props.content || 'Stable'}</div>
30
+ );
31
+
32
+ describe('SchemaErrorBoundary', () => {
33
+ it('should render children normally when no error', () => {
34
+ render(
35
+ <SchemaErrorBoundary>
36
+ <div data-testid="child">OK</div>
37
+ </SchemaErrorBoundary>
38
+ );
39
+ expect(screen.getByTestId('child')).toBeInTheDocument();
40
+ });
41
+
42
+ it('should catch render errors and display fallback', () => {
43
+ render(
44
+ <SchemaErrorBoundary componentType="crashing-widget">
45
+ <CrashingWidget />
46
+ </SchemaErrorBoundary>
47
+ );
48
+ expect(screen.getByRole('alert')).toBeInTheDocument();
49
+ expect(screen.getByText(/failed to render/i)).toBeInTheDocument();
50
+ expect(screen.getByText(/"crashing-widget"/)).toBeInTheDocument();
51
+ expect(screen.getByText('Widget exploded!')).toBeInTheDocument();
52
+ });
53
+
54
+ it('should display retry button that resets the error', () => {
55
+ render(
56
+ <SchemaErrorBoundary>
57
+ <CrashingWidget />
58
+ </SchemaErrorBoundary>
59
+ );
60
+ expect(screen.getByRole('alert')).toBeInTheDocument();
61
+ const retryButton = screen.getByText('Retry');
62
+ expect(retryButton).toBeInTheDocument();
63
+ });
64
+
65
+ it('should work without componentType prop', () => {
66
+ render(
67
+ <SchemaErrorBoundary>
68
+ <CrashingWidget />
69
+ </SchemaErrorBoundary>
70
+ );
71
+ expect(screen.getByText(/failed to render/i)).toBeInTheDocument();
72
+ });
73
+ });
74
+
75
+ describe('SchemaRenderer error boundary integration', () => {
76
+ beforeEach(() => {
77
+ ComponentRegistry.register('crashing-widget', CrashingWidget);
78
+ ComponentRegistry.register('stable-widget', StableWidget);
79
+ });
80
+
81
+ afterEach(() => {
82
+ ComponentRegistry.unregister?.('crashing-widget');
83
+ ComponentRegistry.unregister?.('stable-widget');
84
+ });
85
+
86
+ it('should catch errors from a crashing component', () => {
87
+ render(
88
+ <SchemaRenderer schema={{ type: 'crashing-widget' }} />
89
+ );
90
+ expect(screen.getByRole('alert')).toBeInTheDocument();
91
+ expect(screen.getByText('Widget exploded!')).toBeInTheDocument();
92
+ });
93
+
94
+ it('should not affect stable components', () => {
95
+ render(
96
+ <SchemaRenderer schema={{ type: 'stable-widget', content: 'Hello' }} />
97
+ );
98
+ expect(screen.getByTestId('stable-widget')).toBeInTheDocument();
99
+ expect(screen.getByText('Hello')).toBeInTheDocument();
100
+ });
101
+
102
+ it('should isolate crashes between multiple renderers', () => {
103
+ render(
104
+ <div>
105
+ <SchemaRenderer schema={{ type: 'crashing-widget' }} />
106
+ <SchemaRenderer schema={{ type: 'stable-widget', content: 'Still works' }} />
107
+ </div>
108
+ );
109
+ // Crashing one should not affect the other
110
+ expect(screen.getByRole('alert')).toBeInTheDocument();
111
+ expect(screen.getByTestId('stable-widget')).toBeInTheDocument();
112
+ expect(screen.getByText('Still works')).toBeInTheDocument();
113
+ });
114
+ });