Skip to content

Commit 844c079

Browse files
committed
refactor: CodeMirror - remove redundant reducer state, remove unnecessary logic, optimized code
1 parent 4393fa9 commit 844c079

File tree

8 files changed

+152
-195
lines changed

8 files changed

+152
-195
lines changed

src/Common/CodeMirror/CodeEditor.components.tsx

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,36 +27,36 @@ import { useCodeEditorContext } from './CodeEditor.context'
2727
import { CodeEditorHeaderProps, CodeEditorStatusBarProps } from './types'
2828

2929
const SplitPane = () => {
30-
const { state, dispatch, readOnly } = useCodeEditorContext()
30+
const { diffMode, setDiffMode, readOnly } = useCodeEditorContext()
3131

3232
const handleToggle = () => {
3333
if (readOnly) {
3434
return
3535
}
36-
dispatch({ type: 'setDiff', value: !state.diffMode })
36+
setDiffMode(!diffMode)
3737
}
3838

3939
return (
4040
<div className="code-editor__split-pane flex pointer cn-7 fcn-7 ml-auto" onClick={handleToggle}>
4141
<ICCompare className="icon-dim-20 mr-4" />
42-
{state.diffMode ? 'Hide comparison' : 'Compare with default'}
42+
{diffMode ? 'Hide comparison' : 'Compare with default'}
4343
</div>
4444
)
4545
}
4646

4747
export const Header = ({ children, className, hideDefaultSplitHeader }: CodeEditorHeaderProps) => {
48-
const { state, hasCodeEditorContainer, theme } = useCodeEditorContext()
48+
const { diffMode, lhsValue, hasCodeEditorContainer, theme } = useCodeEditorContext()
4949

5050
return (
5151
<div className={`${getComponentSpecificThemeClass(theme)} flexbox w-100 border__primary--bottom`}>
5252
<div
5353
data-code-editor-header
54-
className={`${hasCodeEditorContainer ? 'dc__top-radius-4' : ''} code-editor__header flex-grow-1 bg__secondary ${className || 'px-16 pt-6 pb-5'} ${state.diffMode ? 'dc__grid-half vertical-divider' : ''}`}
54+
className={`${hasCodeEditorContainer ? 'dc__top-radius-4' : ''} code-editor__header flex-grow-1 bg__secondary ${className || 'px-16 pt-6 pb-5'} ${diffMode ? 'dc__grid-half vertical-divider' : ''}`}
5555
>
5656
{children}
57-
{!hideDefaultSplitHeader && state.lhsCode && <SplitPane />}
57+
{!hideDefaultSplitHeader && lhsValue && <SplitPane />}
5858
</div>
59-
{state.diffMode ? <div className="bg__secondary px-5 dc__align-self-stretch" /> : null}
59+
{diffMode ? <div className="bg__secondary px-5 dc__align-self-stretch" /> : null}
6060
</div>
6161
)
6262
}
@@ -90,9 +90,9 @@ export const Information = ({ className, children, text }: CodeEditorStatusBarPr
9090
)
9191

9292
export const Clipboard = () => {
93-
const { state } = useCodeEditorContext()
93+
const { value } = useCodeEditorContext()
9494

95-
return <ClipboardButton content={state.code} iconSize={16} />
95+
return <ClipboardButton content={value} iconSize={16} />
9696
}
9797

9898
export const Container = ({ children, flexExpand }: { children: ReactNode; flexExpand?: boolean }) => (

src/Common/CodeMirror/CodeEditor.constants.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,4 @@ export const READ_ONLY_TOOLTIP_TIMEOUT = 2000
3131

3232
export const CODE_EDITOR_FONT_SIZE = 15
3333

34-
export const CODE_EDITOR_LINE_HEIGHT = 15
34+
export const CODE_EDITOR_LINE_HEIGHT = 1.4

src/Common/CodeMirror/CodeEditor.reducer.ts

Lines changed: 0 additions & 80 deletions
This file was deleted.

src/Common/CodeMirror/CodeEditor.tsx

Lines changed: 44 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
* limitations under the License.
1515
*/
1616

17-
import { useEffect, useMemo, useReducer, useRef, useState } from 'react'
17+
import { useEffect, useMemo, useRef, useState } from 'react'
1818
import {
1919
Extension,
2020
ReactCodeMirrorProps,
@@ -31,21 +31,23 @@ import { indentationMarkers } from '@replit/codemirror-indentation-markers'
3131

3232
import { AppThemeType, useTheme } from '@Shared/Providers'
3333
import { getUniqueId } from '@Shared/Helpers'
34-
import { cleanKubeManifest, useEffectAfterMount } from '@Common/Helper'
34+
import { cleanKubeManifest } from '@Common/Helper'
3535
import { DEFAULT_JSON_SCHEMA_URI, MODES } from '@Common/Constants'
3636

3737
import { codeEditorFindReplace, readOnlyTooltip, yamlHighlight } from './Extensions'
3838
import { openSearchPanel, openSearchPanelWithReplace, replaceAll, showReplaceFieldState } from './Commands'
3939
import { CodeEditorContextProps, CodeEditorProps } from './types'
40-
import { CodeEditorReducer, initialState, parseValueToCode } from './CodeEditor.reducer'
41-
import { getFoldGutterElement, getLanguageExtension, getValidationSchema } from './utils'
40+
import { getFoldGutterElement, getLanguageExtension, getValidationSchema, parseValueToCode } from './utils'
4241
import { CodeEditorContext } from './CodeEditor.context'
4342
import { Clipboard, Container, ErrorBar, Header, Information, Warning } from './CodeEditor.components'
4443
import { getCodeEditorTheme } from './CodeEditor.theme'
4544
import { CodeEditorRenderer } from './CodeEditorRenderer'
4645

4746
import './codeEditor.scss'
4847

48+
// CODEMIRROR CLASSES
49+
const foldingCompartment = new Compartment()
50+
4951
const CodeEditor = <DiffView extends boolean = false>({
5052
theme,
5153
value: propValue,
@@ -78,16 +80,36 @@ const CodeEditor = <DiffView extends boolean = false>({
7880
// HOOKS
7981
const { appTheme } = useTheme()
8082

83+
// REFS
84+
const codeMirrorParentDivRef = useRef<HTMLDivElement>()
85+
const codeEditorValues = useRef({ code: '', lhsCode: '' })
86+
8187
// MEMOISED VALUES
8288
// Cleaning KubeManifest
8389
const value = useMemo(() => {
8490
const _value = diffView ? modifiedValue : propValue
85-
return cleanData ? cleanKubeManifest(_value) : _value
86-
}, [propValue, modifiedValue, diffView])
87-
const lhsValue = useMemo(() => (cleanData ? cleanKubeManifest(originalValue) : originalValue), [originalValue])
91+
const updatedValue = cleanData ? cleanKubeManifest(_value) : _value
8892

89-
// REFS
90-
const codeMirrorParentDivRef = useRef<HTMLDivElement>()
93+
if (updatedValue !== codeEditorValues.current.code) {
94+
return ![MODES.JSON, MODES.YAML].includes(mode) || noParsing
95+
? updatedValue
96+
: parseValueToCode(updatedValue, mode, tabSize)
97+
}
98+
99+
return codeEditorValues.current.code
100+
}, [propValue, modifiedValue, diffView, noParsing])
101+
102+
const lhsValue = useMemo(() => {
103+
const updatedValue = cleanData ? cleanKubeManifest(originalValue) : originalValue
104+
105+
if (updatedValue !== codeEditorValues.current.lhsCode) {
106+
return ![MODES.JSON, MODES.YAML].includes(mode) || noParsing
107+
? updatedValue
108+
: parseValueToCode(updatedValue, mode, tabSize)
109+
}
110+
111+
return codeEditorValues.current.lhsCode
112+
}, [originalValue, noParsing])
91113

92114
// CONSTANTS
93115
const componentTheme = theme ?? appTheme
@@ -97,24 +119,12 @@ const CodeEditor = <DiffView extends boolean = false>({
97119
// STATES
98120
const [codemirrorMergeKey, setCodemirrorMergeKey] = useState<string>()
99121
const [hasCodeEditorContainer, setHasCodeEditorContainer] = useState(false)
100-
101-
// REDUCER
102-
const [state, dispatch] = useReducer(
103-
CodeEditorReducer,
104-
initialState({
105-
mode,
106-
value,
107-
lhsValue,
108-
noParsing,
109-
tabSize,
110-
diffView,
111-
}),
112-
)
122+
const [diffMode, setDiffMode] = useState(diffView)
113123

114124
// CONTEXT VALUE
115125
const contextValue = useMemo<CodeEditorContextProps>(
116-
() => ({ dispatch, state, height, hasCodeEditorContainer, theme: componentTheme }),
117-
[state, hasCodeEditorContainer, componentTheme],
126+
() => ({ setDiffMode, diffMode, hasCodeEditorContainer, lhsValue, value, readOnly, theme: componentTheme }),
127+
[diffMode, hasCodeEditorContainer, lhsValue, value, readOnly, componentTheme],
118128
)
119129

120130
// USE-EFFECTS
@@ -127,8 +137,8 @@ const CodeEditor = <DiffView extends boolean = false>({
127137
}, [])
128138

129139
useEffect(() => {
130-
// Toggle `state.diffMode` based on `diffView`
131-
dispatch({ type: 'setDiff', value: diffView })
140+
// Toggle `diffMode` based on `diffView`
141+
setDiffMode(diffView)
132142
}, [diffView])
133143

134144
// Re-mounting codemirror-merge is necessary because its extensions don't automatically update after being changed.
@@ -143,38 +153,20 @@ const CodeEditor = <DiffView extends boolean = false>({
143153

144154
// METHODS
145155
const setCode = (codeValue: string) => {
146-
dispatch({ type: 'setCode', value: codeValue })
147-
if (state.diffMode) {
156+
codeEditorValues.current.code = codeValue
157+
if (diffMode) {
148158
onModifiedValueChange?.(codeValue)
149159
} else {
150160
onChange?.(codeValue)
151161
}
152162
}
153163

154164
const setLhsCode = (codeValue: string) => {
155-
dispatch({ type: 'setLhsCode', value: codeValue })
165+
codeEditorValues.current.lhsCode = codeValue
156166
onOriginalValueChange?.(codeValue)
157167
}
158168

159-
useEffectAfterMount(() => {
160-
if (value === state.code) {
161-
return
162-
}
163-
164-
setCode(noParsing ? value : parseValueToCode(value, mode, tabSize))
165-
}, [value, noParsing])
166-
167-
useEffectAfterMount(() => {
168-
if (lhsValue === state.lhsCode) {
169-
return
170-
}
171-
172-
setLhsCode(noParsing ? lhsValue : parseValueToCode(lhsValue, mode, tabSize))
173-
}, [lhsValue, noParsing])
174-
175169
// CODEMIRROR PROPS
176-
const foldingCompartment = new Compartment()
177-
178170
const basicSetupOptions: BasicSetupOptions = {
179171
defaultKeymap: false,
180172
searchKeymap: false,
@@ -197,7 +189,7 @@ const CodeEditor = <DiffView extends boolean = false>({
197189
markerDOM: getFoldGutterElement,
198190
})
199191

200-
const baseExtensions: Extension[] = [
192+
const getBaseExtensions = (): Extension[] => [
201193
basicSetup(basicSetupOptions),
202194
themeExtension,
203195
keymap.of([
@@ -218,14 +210,14 @@ const CodeEditor = <DiffView extends boolean = false>({
218210
]
219211

220212
const extensions: Extension[] = [
221-
...baseExtensions,
222-
...(!state.diffMode ? getValidationSchema({ mode, schemaURI, validatorSchema }) : []),
213+
...getBaseExtensions(),
214+
...(!diffMode ? getValidationSchema({ mode, schemaURI, validatorSchema }) : []),
223215
readOnlyTooltip,
224216
]
225217

226-
const originalViewExtensions: Extension[] = [...baseExtensions, readOnlyTooltip]
218+
const originalViewExtensions: Extension[] = [...getBaseExtensions(), readOnlyTooltip]
227219

228-
const modifiedViewExtensions: Extension[] = [...baseExtensions, readOnlyTooltip]
220+
const modifiedViewExtensions: Extension[] = [...getBaseExtensions(), readOnlyTooltip]
229221

230222
const diffMinimapExtensions: Extension[] = [
231223
basicSetup({
@@ -247,7 +239,6 @@ const CodeEditor = <DiffView extends boolean = false>({
247239
codeMirrorParentDivRef={codeMirrorParentDivRef}
248240
codeEditorTheme={codeEditorTheme}
249241
theme={componentTheme}
250-
state={state}
251242
loading={loading}
252243
customLoader={customLoader}
253244
height={height}

0 commit comments

Comments
 (0)