11import { useMemo } from "react" ;
2+ import { atom , useAtomValue } from "jotai" ;
23import type { Expression } from "../shared" ;
3- import { error , isExpression } from "../shared" ;
4- import { evaluate } from "../evaluate/evaluate" ;
5- import { defaultScreenContext } from "../state" ;
4+ import { deepCloneAsJSON , error , isExpression } from "../shared" ;
5+ import { createBindingAtom } from "../evaluate" ;
66import { useCustomScope } from "./useCustomScope" ;
77
88export const useWidgetId = (
@@ -13,31 +13,46 @@ export const useWidgetId = (
1313 resolvedTestId : string | undefined ;
1414} => {
1515 const customScope = useCustomScope ( ) ;
16- const resolvedWidgetId = useMemo < string > ( ( ) => {
17- let workingId = id ;
18- if ( isExpression ( workingId ) ) {
19- workingId = String (
20- evaluate ( defaultScreenContext , workingId , customScope ) ,
16+
17+ const idBindingAtom = useMemo ( ( ) => {
18+ if ( isExpression ( id ) ) {
19+ return createBindingAtom (
20+ id ,
21+ deepCloneAsJSON ( customScope ) || { } ,
22+ "widgetId" ,
2123 ) ;
2224 }
23- if ( workingId && JS_ID_REGEX . test ( workingId ) ) {
25+ return atom < string | undefined > ( id ) ;
26+ } , [ customScope , id ] ) ;
27+
28+ const resolvedId = useAtomValue ( idBindingAtom ) ;
29+
30+ const resolvedWidgetId = useMemo < string > ( ( ) => {
31+ const workingId = resolvedId ;
32+ if ( typeof workingId === "string" && JS_ID_REGEX . test ( workingId ) ) {
2433 return workingId ;
2534 }
2635 if ( workingId ) {
2736 error (
28- `${ workingId } is not a valid javascript identifier. generating a random one` ,
37+ `${ String ( workingId ) } is not a valid javascript identifier. generating a random one` ,
2938 ) ;
3039 }
3140 return generateRandomString ( 6 ) ;
32- } , [ customScope , id ] ) ;
41+ } , [ resolvedId ] ) ;
3342
34- const resolvedTestId = useMemo ( ( ) => {
43+ const testIdBindingAtom = useMemo ( ( ) => {
3544 if ( isExpression ( testId ) ) {
36- return String ( evaluate ( defaultScreenContext , testId , customScope ) ) ;
45+ return createBindingAtom (
46+ testId ,
47+ deepCloneAsJSON ( customScope ) || { } ,
48+ "widgetTestId" ,
49+ ) ;
3750 }
38- return testId ;
51+ return atom < string | undefined > ( testId ) ;
3952 } , [ customScope , testId ] ) ;
4053
54+ const resolvedTestId = useAtomValue ( testIdBindingAtom ) as string | undefined ;
55+
4156 return { resolvedWidgetId, resolvedTestId } ;
4257} ;
4358
0 commit comments