forked from dpim/wf-react-app
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseFunctionCode.js
More file actions
231 lines (197 loc) · 7.5 KB
/
useFunctionCode.js
File metadata and controls
231 lines (197 loc) · 7.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { useState, useEffect } from 'react'
import examples from '../examples/examples'
const BASE_URL =
process.env.NODE_ENV === 'development'
? 'https://development--thriving-zuccutto-5ad917.netlify.app'
: 'https://main--thriving-zuccutto-5ad917.netlify.app'
// This hook is responsible for fetching and parsing function code, and extracting parameters.
export const useFunctionCode = (
selectedFunctionName,
selectedExampleCategory,
) => {
const [functionCode, setFunctionCode] = useState('')
const [parameterNames, setParameterNames] = useState([])
const [parameterTypes, setParameterTypes] = useState([])
const [functionParameters, setFunctionParameters] = useState({})
useEffect(() => {
if (selectedFunctionName && selectedExampleCategory) {
const filePath = `${BASE_URL}/examples/${selectedExampleCategory.toLowerCase()}.ts`
fetch(filePath)
.then((response) => response.text())
.then((text) => {
// Function to parse the function text and extract details
const functionMatch = parseFunctionText(
text,
selectedFunctionName,
selectedExampleCategory,
)
if (functionMatch) {
let extractedCode = functionMatch
.replace(`${selectedFunctionName}:`, '')
.replace(/,\s*$/, '')
setFunctionCode(extractedCode)
const { params, types } = extractParameters(functionMatch)
setParameterNames(params)
setParameterTypes(types)
// Initialize function parameters with empty values
setFunctionParameters(
params.reduce((acc, param) => ({ ...acc, [param]: '' }), {}),
)
} else {
setFunctionCode('Function code not found.')
setParameterNames([])
setParameterTypes([])
setFunctionParameters({})
}
})
.catch((error) => {
console.error('Failed to fetch function source:', error)
setFunctionCode('')
setParameterNames([])
setParameterTypes([])
setFunctionParameters({})
})
}
}, [selectedFunctionName, selectedExampleCategory])
return {
functionCode,
parameterNames,
parameterTypes,
functionParameters,
setParameterNames,
setFunctionParameters,
}
}
// Utility function to parse function text
const parseFunctionText = (
text,
selectedFunctionName,
selectedExampleCategory,
) => {
// First, find the top-level category (Elements, Assets, etc.)
const findMatchingBrace = (str, startIndex) => {
let braceCount = 1
let i = startIndex
while (i < str.length && braceCount > 0) {
if (str[i] === '{') braceCount++
if (str[i] === '}') braceCount--
i++
}
return i
}
// Find the start of the category
const categoryStart = text.indexOf(
`export const ${selectedExampleCategory} = {`,
)
if (categoryStart === -1) {
console.error('Top level category not found:', selectedExampleCategory)
throw new Error(`Category "${selectedExampleCategory}" not found.`)
}
// Find the matching closing brace
const contentStart =
categoryStart + `export const ${selectedExampleCategory} = {`.length
const contentEnd = findMatchingBrace(text, contentStart)
// Extract everything between the braces
let searchText = text.slice(contentStart, contentEnd)
// Handle nested function names (e.g., "elementManagement.setSelectedElement")
const [category, funcName] = selectedFunctionName.includes('.')
? selectedFunctionName.split('.')
: [null, selectedFunctionName]
// If we have a subcategory, extract that section
if (category) {
// Find the start of the subcategory
const subcategoryStart = searchText.indexOf(`${category}:`)
if (subcategoryStart === -1) {
console.error('Subcategory not found:', category)
throw new Error(`Subcategory "${category}" not found.`)
}
// Find the opening brace
const braceStart = searchText.indexOf('{', subcategoryStart)
if (braceStart === -1) {
throw new Error(`No opening brace found for subcategory "${category}"`)
}
// Find the matching closing brace using our existing helper
const subcategoryEnd = findMatchingBrace(searchText, braceStart + 1)
// Extract everything between the braces
searchText = searchText.slice(braceStart + 1, subcategoryEnd - 1)
}
// Regex to find all function definitions
const funcRegex = /(\w+):\s*(async\s*)?\(\s*.*?\)\s*=>\s*{(.*?)}/gs
// Match all function definitions in the search text
const matches = [...searchText.matchAll(funcRegex)]
// Find the match for the selected function
const selectedFunctionMatch = matches.find(
(match) => match[1] === (funcName || selectedFunctionName),
)
// If the function is not found, throw an error
if (!selectedFunctionMatch) {
throw new Error(`Function "${funcName || selectedFunctionName}" not found.`)
}
// Get the index of the selected function in the matches
const selectedFunctionIndex = matches.findIndex(
(match) => match[1] === (funcName || selectedFunctionName),
)
// Get text for the selected function and everything up to the next function
const functionText = selectedFunctionMatch[0].trim()
// If there's a next function, extract text up to it; otherwise, use the end of the text
const nextFunctionText =
selectedFunctionIndex + 1 < matches.length
? matches[selectedFunctionIndex + 1][0]
: null
// Determine the end index for extraction
const endIndex = nextFunctionText
? searchText.indexOf(nextFunctionText)
: searchText.length
// Extract everything from the function text up to the end index
let extractedText = searchText
.slice(searchText.indexOf(functionText), endIndex)
.trim()
// Remove the trailing "}" if this is the last function in the file
if (!nextFunctionText) {
extractedText = extractedText.replace(/\s*}$/, '')
}
return extractedText
}
// Utility function to extract parameters and types
const extractParameters = (functionMatch) => {
const paramsRegex = /\(\s*([^)]*?)\s*\)\s*=>/
const paramsMatch = paramsRegex.exec(functionMatch)
const params = []
const types = []
if (paramsMatch) {
const paramString = paramsMatch[1]
const individualParamRegex = /(\w+)\s*:\s*(\w+)/g
let paramMatch
while ((paramMatch = individualParamRegex.exec(paramString))) {
params.push(paramMatch[1])
types.push(paramMatch[2])
}
}
return { params, types }
}
const handleFunctionExecutionWithoutParameters = () => {
if (selectedExampleCategory && selectedFunctionName) {
// Handle nested function names (e.g., "elementManagement.setSelectedElement")
const [category, funcName] = selectedFunctionName.includes('.')
? selectedFunctionName.split('.')
: [null, selectedFunctionName]
// Get the top-level category
const topCategory = examples[selectedExampleCategory]
// Get the function to execute, handling nested categories
const funcToExecute = category
? topCategory[category][funcName] // For nested functions like elementManagement.getSelectedElement
: topCategory[selectedFunctionName] // For top-level functions
if (funcToExecute && parameterNames.length === 0) {
try {
const result = funcToExecute()
if (result && typeof result.then === 'function') {
result.catch(console.error)
} else {
console.log(result)
}
} catch (error) {
console.error('Error executing function:', error)
}
}
}
}