Skip to content

Commit 949030c

Browse files
authored
Merge pull request #6 from oslabs-beta/ron-william-changes
Fixed Add and Delete State and Added Context API to code preview
2 parents 8bc0bbf + f3b5756 commit 949030c

File tree

4 files changed

+98
-46
lines changed

4 files changed

+98
-46
lines changed

app/src/components/right/StatePropsPanel.tsx

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -75,30 +75,14 @@ const StatePropsPanel = ({ isThemeLight }): JSX.Element => {
7575
value: typeConversion(inputValue, inputType),
7676
type: inputType,
7777
};
78-
// store this newStateProp obj to our Component's stateProps array
79-
currentComponent.stateProps.push(newState);
80-
// reset newStateProp to empty for future new state prop entries
81-
updateUseStateCodes();
78+
8279
dispatch({
83-
type: 'ADD STATE'
80+
type: 'ADD STATE',
81+
payload: {newState: newState}
8482
});
8583
clearForm();
8684
};
8785

88-
// generates React Hook code snippets for each new stateProp entry
89-
const updateUseStateCodes = () => {
90-
// array of snippets of state prop codes
91-
const localStateCode = [];
92-
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-
};
10286

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

118102
// find & delete table row using its id
119103
const handlerRowDelete = (id:any) => {
120-
console.log('handlerRowDelete invoked')
121104
// 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());
105+
const filtered = currentComponent.stateProps.filter(element => element.id !== id);
106+
107+
dispatch({
108+
type: 'DELETE STATE',
109+
payload: {stateProps: filtered}
110+
});
111+
112+
setStateProps(filtered);
125113
};
126114

127115
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: 42 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,54 @@ 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+
currComponent.useStateCodes = updateUseStateCodes(currComponent);
757782

783+
currComponent.code = generateCode(
784+
components,
785+
state.canvasFocus.componentId,
786+
[...state.rootComponents],
787+
state.projectType,
788+
state.HTMLTypes
789+
);
758790
return { ...state, components};
759791
}
792+
760793
default:
761794
return state;
762795
}
796+
797+
763798
};
764799

765800
export default reducer;

0 commit comments

Comments
 (0)