Skip to content
Merged
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
34 changes: 28 additions & 6 deletions code/core/src/preview-api/modules/store/inferArgTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ import { dedent } from 'ts-dedent';

import { combineParameters } from './parameters';

const inferType = (value: any, name: string, visited: Set<any>): SBType => {
const inferType = (
value: any,
name: string,
visited: Set<any>,
cache: Map<any, SBType>
): SBType => {
const type = typeof value;
switch (type) {
case 'boolean':
Expand All @@ -19,6 +24,12 @@ const inferType = (value: any, name: string, visited: Set<any>): SBType => {
break;
}
if (value) {
// Check cache first for previously computed results
if (cache.has(value)) {
return cache.get(value)!;
}

// Check for cycles (currently being processed in this path)
if (visited.has(value)) {
logger.warn(dedent`
We've detected a cycle in arg '${name}'. Args should be JSON-serializable.
Expand All @@ -29,25 +40,36 @@ const inferType = (value: any, name: string, visited: Set<any>): SBType => {
`);
return { name: 'other', value: 'cyclic object' };
}

visited.add(value);

let result: SBType;

if (Array.isArray(value)) {
const childType: SBType =
value.length > 0
? inferType(value[0], name, new Set(visited))
? inferType(value[0], name, visited, cache)
: { name: 'other', value: 'unknown' };
return { name: 'array', value: childType };
result = { name: 'array', value: childType };
} else {
const fieldTypes = mapValues(value, (field) => inferType(field, name, visited, cache));
result = { name: 'object', value: fieldTypes };
}
const fieldTypes = mapValues(value, (field) => inferType(field, name, new Set(visited)));
return { name: 'object', value: fieldTypes };

visited.delete(value); // Remove from current path after processing
cache.set(value, result); // Cache the result for future lookups

return result;
}
return { name: 'object', value: {} };
};

export const inferArgTypes: ArgTypesEnhancer<Renderer> = (context) => {
const { id, argTypes: userArgTypes = {}, initialArgs = {} } = context;
const cache = new Map<any, SBType>();
const argTypes = mapValues(initialArgs, (arg, key) => ({
name: key,
type: inferType(arg, `${id}.${key}`, new Set()),
type: inferType(arg, `${id}.${key}`, new Set(), cache),
}));
const userArgTypesNames = mapValues(userArgTypes, (argType, key) => ({
name: key,
Expand Down
Loading