Skip to content

Commit 9d5c5ae

Browse files
Fixed delete and add state, added context to code preview
Co-authored: Ron Fu [email protected]
1 parent 745370f commit 9d5c5ae

File tree

4 files changed

+112
-42
lines changed

4 files changed

+112
-42
lines changed

app/src/components/right/StatePropsPanel.tsx

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -76,29 +76,30 @@ const StatePropsPanel = ({ isThemeLight }): JSX.Element => {
7676
type: inputType,
7777
};
7878
// store this newStateProp obj to our Component's stateProps array
79-
currentComponent.stateProps.push(newState);
79+
// currentComponent.stateProps.push(newState);
8080
// reset newStateProp to empty for future new state prop entries
81-
updateUseStateCodes();
81+
8282
dispatch({
83-
type: 'ADD STATE'
83+
type: 'ADD STATE',
84+
payload: {newState: newState}
8485
});
8586
clearForm();
8687
};
8788

8889
// generates React Hook code snippets for each new stateProp entry
89-
const updateUseStateCodes = () => {
90-
// array of snippets of state prop codes
91-
const localStateCode = [];
90+
// const updateUseStateCodes = () => {
91+
// // array of snippets of state prop codes
92+
// const localStateCode = [];
9293

93-
currentComponent.stateProps.forEach((stateProp) => {
94-
const useStateCode = `const [${stateProp.key}, set${
95-
stateProp.key.charAt(0).toUpperCase() + stateProp.key.slice(1)
96-
}] = useState<${stateProp.type} | undefined>(${JSON.stringify(stateProp.value)})`;
97-
localStateCode.push(useStateCode);
98-
});
99-
// store localStateCodes in global state context
100-
currentComponent.useStateCodes = localStateCode;
101-
};
94+
// currentComponent.stateProps.forEach((stateProp) => {
95+
// const useStateCode = `const [${stateProp.key}, set${
96+
// stateProp.key.charAt(0).toUpperCase() + stateProp.key.slice(1)
97+
// }] = useState<${stateProp.type} | undefined>(${JSON.stringify(stateProp.value)})`;
98+
// localStateCode.push(useStateCode);
99+
// });
100+
// // store localStateCodes in global state context
101+
// return localStateCode;
102+
// };
102103

103104
// find table row using its id and if it exists, populate form with its details
104105
const handlerRowSelect = (table) => {
@@ -117,11 +118,15 @@ const StatePropsPanel = ({ isThemeLight }): JSX.Element => {
117118

118119
// find & delete table row using its id
119120
const handlerRowDelete = (id:any) => {
120-
console.log('handlerRowDelete invoked')
121121
// iterate and filter out stateProps with matching row id
122-
currentComponent.stateProps = currentComponent.stateProps.filter(element => element.id !== id);
123-
updateUseStateCodes();
124-
setStateProps(currentComponent.stateProps.slice());
122+
const filtered = currentComponent.stateProps.filter(element => element.id !== id);
123+
124+
dispatch({
125+
type: 'DELETE STATE',
126+
payload: {stateProps: filtered}
127+
});
128+
// updateUseStateCodes();
129+
setStateProps(filtered);
125130
};
126131

127132
return (

app/src/components/right/TableStateProps.tsx

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,12 @@ const getColumns = (props) => {
4646
renderCell: function renderCell(params:any) {
4747
const getIdRow = () => {
4848
const { api } = params;
49-
const fields = api.getAllColumns().map((c: any) => c.field).filter((c : any) => c !== '__check__' && !!c);
50-
return params.getValue(fields[0]);
49+
console.log('Line 49 params =', params);
50+
console.log('Line 50 id = ', params.id);
51+
// const fields = api.getAllColumns().map((c: any) => c.field).filter((c : any) => c !== '__check__' && !!c);
52+
return params.id;
53+
54+
// return params.getValue(fields[0]);
5155
};
5256
return (
5357
<Button style={{width:`${3}px`}}

app/src/helperFunctions/generateCode.ts

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,14 @@ const generateUnformattedCode = (
6060
referencedHTML.tag === 'ol' ||
6161
referencedHTML.tag === 'menu' ||
6262
referencedHTML.tag === 'li' ||
63-
referencedHTML.tag === 'Link' ||
63+
referencedHTML.tag === 'LinkTo' ||
6464
referencedHTML.tag === 'Switch' ||
6565
referencedHTML.tag === 'Route'
6666
) {
6767
child.children = getEnrichedChildren(child);
6868
}
69-
// when we see a Switch, import React Router
70-
if (referencedHTML.tag === 'Switch' || referencedHTML.tag === 'Link') importReactRouter = true;
69+
// when we see a Switch or LinkTo, import React Router
70+
if (referencedHTML.tag === 'Switch' || referencedHTML.tag === 'LinkTo') importReactRouter = true;
7171
return child;
7272
} else if (child.type === 'Route Link') {
7373
links = true;
@@ -142,7 +142,9 @@ const generateUnformattedCode = (
142142
} else if (childElement.tag === 'input') {
143143
return `${levelSpacer(level, 5)}<${childElement.tag}${elementTagDetails(childElement)}></${childElement.tag}>${levelSpacer(2, (3 + level))}`;
144144
} else if (childElement.tag === 'LinkTo') {
145-
return `${levelSpacer(level, 5)}<Link to="${activeLink}"${elementTagDetails(childElement)}>${innerText}</Link>${levelSpacer(2, (3 + level))}`;
145+
return `${levelSpacer(level, 5)}<Link to="${activeLink}"${elementTagDetails(childElement)}>${innerText}
146+
${tabSpacer(level)}${writeNestedElements(childElement.children, level + 1)}
147+
${tabSpacer(level - 1)}</Link>${levelSpacer(2, (3 + level))}`;
146148
} else if (nestable) {
147149
const routePath = (childElement.tag === 'Route') ? (' ' + 'exact path="' + activeLink + '"') : '';
148150
return `${levelSpacer(level, 5)}<${childElement.tag}${elementTagDetails(childElement)}${routePath}>${innerText}
@@ -212,14 +214,27 @@ const generateUnformattedCode = (
212214
const classBased = false;
213215
let importReactRouter;
214216

217+
const createState = (stateProps) => {
218+
let state = '{';
219+
220+
stateProps.forEach((ele) => {
221+
state += `${ele.key}: ${(ele.type !== 'string') ? `${ele.value}` : `"${ele.value}"`}, `;
222+
});
223+
224+
state = state.substring(0, state.length - 2) + '}';
225+
226+
return state;
227+
}
228+
229+
215230
// create final component code. component code differs between classic react, next.js, gatsby.js
216231
// classic react code
217232
if (projectType === 'Classic React') {
218233
return `
219-
${stateful && !classBased ? `import React, {useState} from 'react';` : ''}
234+
${stateful && !classBased ? `import React, { useState, createContext, useContext } from 'react';` : ''}
220235
${importReactRouter ? `import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';`: ``}
221-
${classBased ? `import React, {Component} from 'react';` : ''}
222-
${!stateful && !classBased ? `import React from 'react';` : ''}
236+
${classBased ? `import React, { Component } from 'react';` : ''}
237+
${!stateful && !classBased ? `import React, { createContext, useContext } from 'react';` : ''}
223238
${importsMapped}
224239
${
225240
classBased
@@ -228,10 +243,16 @@ const generateUnformattedCode = (
228243
}
229244
${
230245
stateful && !classBased
231-
? `const [value, setValue] = useState<any | undefined>("INITIAL VALUE")${writeStateProps(currentComponent.useStateCodes)};
246+
? `const [value, setValue] = useState<any | undefined>("INITIAL VALUE");${writeStateProps(currentComponent.useStateCodes)}
232247
`
233248
: ``
234249
}
250+
${
251+
isRoot && currentComponent.stateProps.length !== 0
252+
? `const ${currentComponent.name}Context = createContext(${createState(currentComponent.stateProps)});`
253+
: ``
254+
255+
}
235256
${
236257
classBased && stateful
237258
? `constructor(props) {
@@ -243,15 +264,19 @@ const generateUnformattedCode = (
243264
${classBased ? `render(): JSX.Element {` : ``}
244265
${!importReactRouter ?
245266
`return (
246-
<div className="${currentComponent.name}" ${formatStyles(currentComponent)}>
247-
${writeNestedElements(enrichedChildren)}
248-
</div>
249-
);` : `return (
250-
<Router>
267+
<${currentComponent.name}Context.Provider value="">
251268
<div className="${currentComponent.name}" ${formatStyles(currentComponent)}>
252269
${writeNestedElements(enrichedChildren)}
253270
</div>
254-
</Router>
271+
</${currentComponent.name}Context.Provider>
272+
);` : `return (
273+
<${currentComponent.name}Context.Provider value="">
274+
<Router>
275+
<div className="${currentComponent.name}" ${formatStyles(currentComponent)}>
276+
${writeNestedElements(enrichedChildren)}
277+
</div>
278+
</Router>
279+
</${currentComponent.name}Context.Provider>
255280
);`}
256281
${`}`}
257282
export default ${currentComponent.name};

app/src/reducers/componentReducer.ts

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import initialState from '../context/initialState';
99
import generateCode from '../helperFunctions/generateCode';
1010
import manageSeparators from '../helperFunctions/manageSeparators';
1111
import addRoute from '../helperFunctions/addRoute';
12+
import cloneDeep from '../helperFunctions/cloneDeep';
1213

1314
let separator = initialState.HTMLTypes[1];
1415

@@ -197,6 +198,20 @@ const reducer = (state: State, action: Action) => {
197198
}
198199
};
199200

201+
const updateUseStateCodes = (currentComponent) => {
202+
// array of snippets of state prop codes
203+
const localStateCode = [];
204+
205+
currentComponent.stateProps.forEach((stateProp) => {
206+
const useStateCode = `const [${stateProp.key}, set${
207+
stateProp.key.charAt(0).toUpperCase() + stateProp.key.slice(1)
208+
}] = useState<${stateProp.type} | undefined>(${JSON.stringify(stateProp.value)})`;
209+
localStateCode.push(useStateCode);
210+
});
211+
// store localStateCodes in global state context
212+
return localStateCode;
213+
};
214+
200215
switch (action.type) {
201216
case 'ADD COMPONENT': {
202217
if (
@@ -732,34 +747,55 @@ const reducer = (state: State, action: Action) => {
732747
...state
733748
};
734749
}
735-
case 'ADD STATE': {
750+
case 'ADD STATE' : {
736751
// if (!state.canvasFocus.childId) return state;
737752
// find the current component in focus
738753
const components = [...state.components];
739-
const component = findComponent(
754+
const currComponent = findComponent(
740755
components,
741756
state.canvasFocus.componentId
742757
);
743758

744-
console.log("line 744", component);
745-
746-
console.log("line 760", component.code);
759+
currComponent.stateProps.push(action.payload.newState);
760+
currComponent.useStateCodes = updateUseStateCodes(currComponent);
747761

748-
component.code = generateCode(
762+
currComponent.code = generateCode(
749763
components,
750764
state.canvasFocus.componentId,
751765
[...state.rootComponents],
752766
state.projectType,
753767
state.HTMLTypes
754768
);
769+
return { ...state, components};
770+
}
755771

756-
console.log('line 770', component.code);
772+
case 'DELETE STATE' : {
773+
const components = [...state.components];
774+
let currComponent = findComponent(
775+
components,
776+
state.canvasFocus.componentId
777+
);
778+
779+
currComponent.stateProps = action.payload.stateProps;
780+
781+
console.log(currComponent);
782+
currComponent.useStateCodes = updateUseStateCodes(currComponent);
757783

784+
currComponent.code = generateCode(
785+
components,
786+
state.canvasFocus.componentId,
787+
[...state.rootComponents],
788+
state.projectType,
789+
state.HTMLTypes
790+
);
758791
return { ...state, components};
759792
}
793+
760794
default:
761795
return state;
762796
}
797+
798+
763799
};
764800

765801
export default reducer;

0 commit comments

Comments
 (0)