MCPcopy Create free account
hub / github.com/DavidHDev/react-bits / injectPropsIntoCode

Function injectPropsIntoCode

src/components/code/CodeExample.jsx:16–103  ·  view source on GitHub ↗
(usageCode, props, defaultProps, componentName, demoOnlyProps = [])

Source from the content-addressed store, hash-verified

14 * Updates changed props in place, and adds new props that don't exist yet.
15 */
16export function injectPropsIntoCode(usageCode, props, defaultProps, componentName, demoOnlyProps = []) {
17 if (!usageCode || !props || !componentName) return usageCode;
18
19 const demoOnlySet = new Set(demoOnlyProps);
20 const changedProps = {};
21 for (const [key, value] of Object.entries(props)) {
22 if (demoOnlySet.has(key)) continue;
23
24 if (JSON.stringify(value) !== JSON.stringify(defaultProps[key])) {
25 changedProps[key] = value;
26 }
27 }
28
29 if (Object.keys(changedProps).length === 0) return usageCode;
30
31 let result = usageCode;
32 const propsToAdd = [];
33
34 for (const [propName, propValue] of Object.entries(changedProps)) {
35 const formattedValue = formatPropValue(propValue, propName);
36 const newPropLine =
37 typeof propValue === 'boolean' && propValue === true ? propName : `${propName}=${formattedValue}`;
38
39 const simplePropRegex = new RegExp(
40 `(^[ \\t]*)(${propName})(?:=(?:"[^"\\n]*"|'[^'\\n]*'|\\{[^{}\\n]*\\}|[^\\s/>]+))?[ \\t]*(\\r?\\n|$)`,
41 'gm'
42 );
43
44 const hasSimpleMatch = simplePropRegex.test(result);
45 simplePropRegex.lastIndex = 0;
46
47 if (hasSimpleMatch) {
48 let seen = false;
49 result = result.replace(simplePropRegex, (_, indent, __, lineEnding) => {
50 if (seen) return '';
51 seen = true;
52 return `${indent}${newPropLine}${lineEnding}`;
53 });
54 continue;
55 }
56
57 const multiLineStart = new RegExp(`^([ \\t]*)(${propName})=\\{`, 'gm');
58 let match;
59 let updated = false;
60
61 while ((match = multiLineStart.exec(result)) !== null) {
62 const indent = match[1];
63 const startIndex = match.index;
64 const openBraceIndex = match.index + match[0].length - 1;
65
66 let braceCount = 1;
67 let i = openBraceIndex + 1;
68 while (i < result.length && braceCount > 0) {
69 if (result[i] === '{') braceCount++;
70 else if (result[i] === '}') braceCount--;
71 i++;
72 }
73

Callers 2

TabsLayoutFunction · 0.90
CodeExampleFunction · 0.85

Calls 1

formatPropValueFunction · 0.90

Tested by

no test coverage detected