Skip to content

Commit 31df2da

Browse files
committed
refactor with react hooks
1 parent de24bf5 commit 31df2da

5 files changed

Lines changed: 132 additions & 146 deletions

File tree

‎src/components/NoticeLinks.js‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ function useSliderEffect(el) {
3333
useEffect(() => {
3434
const timer = setInterval(() => renderItem(el.current.children), 10000);
3535
return () => clearInterval(timer);
36-
}, []); // pass [] to run an effect and clean it up only once
36+
}, []); // run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([])
3737

3838
let active = 1;
3939
function renderItem(list) {
@@ -44,9 +44,6 @@ function useSliderEffect(el) {
4444
item.classList.remove('show');
4545
}
4646
});
47-
active++;
48-
if (active >= list.length) {
49-
active = 0;
50-
}
47+
active = (active + 1) % list.length;
5148
}
5249
}

‎src/components/SearchBar.js‎

Lines changed: 86 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from 'react';
1+
import {useEffect, useRef, useState} from 'react';
22
import {Dropdown, Icon, Input} from 'semantic-ui-react';
33

44
// http://githut.info/
@@ -28,121 +28,108 @@ const topProgramLan = [
2828
{id: 42, language: 'ActionScript'}
2929
];
3030

31-
export default class SearchBar extends React.Component {
32-
input = React.createRef();
33-
select = React.createRef();
31+
export default function SearchBar(props) {
32+
const inputEl = useRef(null);
33+
const inputSize = useInputSize('huge');
34+
const [state, setState] = useState({
35+
lang: props && props.searchLang ? props.searchLang : [],
36+
valChanged: false
37+
});
3438

35-
constructor(props) {
36-
super(props);
37-
this.state = {
38-
lang: props && props.searchLang ? props.searchLang : [],
39-
prevProps: props,
40-
inputSize: 'huge',
41-
inputChanged: false
42-
}
43-
window.addEventListener('resize', this.resizeInput, false)
39+
function updateState(vals) {
40+
setState(prevState => {
41+
return {...prevState, ...vals};
42+
});
4443
}
4544

46-
static getDerivedStateFromProps(nextProps, prevState) {
47-
// avoid calculating expensive derived data
48-
if (prevState.prevProps === nextProps) {
49-
return null
50-
}
51-
let newState = {
52-
prevProps: nextProps // prevProps memoization
53-
}
54-
// derived state from props
55-
if (prevState.prevProps.searchLang != nextProps.searchLang) {
56-
newState.lang = nextProps.searchLang;
57-
}
58-
return newState;
45+
function handleSearch() {
46+
props.onSearch(inputEl.current.inputRef.value, state.lang);
47+
inputEl.current.inputRef.blur();
48+
updateState({valChanged: false});
5949
}
6050

61-
componentDidMount() {
62-
this.resizeInput();
51+
function handleRestLang() {
52+
updateState({lang: [], valChanged: true});
6353
}
6454

65-
resizeInput = () => {
66-
this.setState({inputSize: document.body.offsetWidth < 800 ? '' : 'huge'})
55+
function handleSelectLang(id) {
56+
updateState({lang: state.lang.concat(id).sort(), valChanged: true});
6757
}
6858

69-
handleSearch = () => {
70-
this.setState({inputChanged: false});
71-
this.props.onSearch(this.input.current.inputRef.value, this.state.lang);
72-
this.input.current.inputRef.blur();
59+
function handleDeselectLang(id) {
60+
let lang = state.lang;
61+
lang.splice(state.lang.indexOf(id), 1);
62+
updateState({lang: lang.sort(), valChanged: true});
7363
}
7464

75-
handleRestLang = () => {
76-
this.setState({lang: [], inputChanged: true});
65+
function handleToggleSelectLang(id) {
66+
state.lang.indexOf(id) === -1 ? handleSelectLang(id) : handleDeselectLang(id);
7767
}
7868

79-
handleSelectLang = id => {
80-
this.setState({lang: this.state.lang.concat(id).sort(), inputChanged: true});
81-
}
69+
const langItems = topProgramLan.map(key => {
70+
const active = state.lang.indexOf(key.id) !== -1;
71+
return <Dropdown.Item key={key.id}
72+
active={active}
73+
onClick={() => handleToggleSelectLang(key.id)}>
74+
<Icon name={active ? 'check circle outline' : 'circle outline'}/>{key.language}
75+
</Dropdown.Item>;
76+
});
8277

83-
handleDeselectLang = id => {
84-
let lang = this.state.lang;
85-
lang.splice(this.state.lang.indexOf(id), 1);
86-
this.setState({lang: lang.sort(), inputChanged: true});
87-
}
78+
return (
79+
<div className='search-bar'>
80+
<div className='search-bar__desc'>
81+
Search over GitHub, Bitbucket, GitLab to find real-world usage variable names
82+
</div>
83+
<form action="javascript:void(0);">
84+
<Input ref={inputEl}
85+
onChange={() => updateState({valChanged: true})}
86+
className='search-bar__input'
87+
icon fluid placeholder={props.placeholder} size={inputSize}>
88+
<Dropdown floating text='' icon='filter' className='search-bar__dropdown'>
89+
<Dropdown.Menu>
90+
<Dropdown.Item icon='undo' text='All 90 Languages (Reset)' onClick={handleRestLang}/>
91+
<Dropdown.Menu scrolling className='fix-dropdown-menu'>
92+
{langItems}
93+
</Dropdown.Menu>
94+
</Dropdown.Menu>
95+
</Dropdown>
8896

89-
handleToggleSelectLang = id => {
90-
this.state.lang.indexOf(id) === -1 ? this.handleSelectLang(id) : this.handleDeselectLang(id);
91-
}
97+
<input type='search' name='search' defaultValue={props.searchValue}
98+
onKeyPress={e => {
99+
e.key === 'Enter' && handleSearch()
100+
}}/>
101+
<Icon name={(props.variableList.length && !state.valChanged) ? 'search plus' : 'search'}
102+
link onClick={() => handleSearch()}/>
103+
</Input>
104+
</form>
105+
<div className='search-bar__plugins'>
106+
Extensions:&nbsp;
107+
<a href='https://github.com/unbug/codelf#codelf-for-vs-code'
108+
target='_blank' rel='noopener noreferrer'>VS Code</a>,&nbsp;
109+
<a className='text-muted' href='https://atom.io/packages/codelf'
110+
target='_blank' rel='noopener noreferrer'>Atom</a>,&nbsp;
111+
<a className='text-muted' href='https://github.com/unbug/codelf#codelf-for-sublime-text'
112+
target='_blank' rel='noopener noreferrer'>Sublime</a>,&nbsp;
113+
<a href='https://github.com/unbug/codelf/issues/24'
114+
target='_blank' rel='noopener noreferrer'>WebStorm</a>,&nbsp;
115+
<a href='https://github.com/unbug/codelf/issues/63'
116+
target='_blank' rel='noopener noreferrer'>Alfred</a>
117+
</div>
118+
</div>
119+
)
120+
}
92121

93-
renderItems() {
94-
return topProgramLan.map(key => {
95-
const active = this.state.lang.indexOf(key.id) !== -1;
96-
return <Dropdown.Item key={key.id}
97-
active={active}
98-
onClick={() => this.handleToggleSelectLang(key.id)}>
99-
<Icon name={active ? 'check circle outline' : 'circle outline'}/>{key.language}
100-
</Dropdown.Item>;
101-
})
102-
}
122+
function useInputSize(val) {
123+
const [size, setSize] = useState(val);
103124

104-
render() {
105-
return (
106-
<div className='search-bar'>
107-
<div className='search-bar__desc'>
108-
Search over GitHub, Bitbucket, GitLab to find real-world usage variable names
109-
</div>
110-
<form action="javascript:void(0);">
111-
<Input ref={this.input}
112-
onChange={() => this.setState({inputChanged: true})}
113-
className='search-bar__input'
114-
icon fluid placeholder={this.props.placeholder} size={this.state.inputSize}>
115-
<Dropdown floating text='' icon='filter' className='search-bar__dropdown'>
116-
<Dropdown.Menu>
117-
<Dropdown.Item icon='undo' text='All 90 Languages (Reset)' onClick={this.handleRestLang}/>
118-
<Dropdown.Menu scrolling className='fix-dropdown-menu'>
119-
{this.renderItems()}
120-
</Dropdown.Menu>
121-
</Dropdown.Menu>
122-
</Dropdown>
125+
useEffect(() => {
126+
window.addEventListener('resize', resizeInput, false);
127+
return () => window.removeEventListener('resize', resizeInput, false);
128+
}, []);// run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([])
123129

124-
<input type='search' name='search' defaultValue={this.props.searchValue}
125-
onKeyPress={e => {
126-
e.key === 'Enter' && this.handleSearch()
127-
}}/>
128-
<Icon name={(this.props.variableList.length && !this.state.inputChanged) ? 'search plus' : 'search'}
129-
link onClick={() => this.handleSearch()}/>
130-
</Input>
131-
</form>
132-
<div className='search-bar__plugins'>
133-
Extensions:&nbsp;
134-
<a href='https://github.com/unbug/codelf#codelf-for-vs-code'
135-
target='_blank' rel='noopener noreferrer'>VS Code</a>,&nbsp;
136-
<a className='text-muted' href='https://atom.io/packages/codelf'
137-
target='_blank' rel='noopener noreferrer'>Atom</a>,&nbsp;
138-
<a className='text-muted' href='https://github.com/unbug/codelf#codelf-for-sublime-text'
139-
target='_blank' rel='noopener noreferrer'>Sublime</a>,&nbsp;
140-
<a href='https://github.com/unbug/codelf/issues/24'
141-
target='_blank' rel='noopener noreferrer'>WebStorm</a>,&nbsp;
142-
<a href='https://github.com/unbug/codelf/issues/63'
143-
target='_blank' rel='noopener noreferrer'>Alfred</a>
144-
</div>
145-
</div>
146-
)
130+
function resizeInput() {
131+
setSize(document.body.offsetWidth < 800 ? '' : val);
147132
}
133+
134+
return size;
148135
}

‎src/components/VariableItem.js‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import {Button, Label, Popup} from 'semantic-ui-react';
2+
import * as Tools from '../utils/Tools';
3+
4+
export default function VariableItem(props) {
5+
const clipboardId = `clipboardId-${Tools.uuid()}`;
6+
const variable = props.variable;
7+
let clipboard = null;
8+
9+
function handlePopOnMount() {
10+
clipboard = new ClipboardJS(`#${clipboardId}`);
11+
}
12+
13+
function handlePopUnmount() {
14+
clipboard && clipboard.destroy();
15+
}
16+
17+
return (
18+
<Popup style={{padding: '0'}}
19+
position='top center'
20+
trigger={
21+
<Label circular color={variable.color} className={props.className} style={props.style}>
22+
{variable.keyword}
23+
</Label>}
24+
onMount={handlePopOnMount}
25+
onUnmount={handlePopUnmount}
26+
hoverable={true}>
27+
<Button.Group vertical basic style={{border: 0}}>
28+
<Button compact as='a' href={`#${variable.keyword}`}>Search</Button>
29+
<Button compact as='a' href={variable.repoLink} target='_blank'>Repo</Button>
30+
<Button compact data-clipboard-text={variable.keyword} id={clipboardId}>Copy</Button>
31+
<Button compact onClick={() => props.onOpenSourceCode(variable)}>
32+
[{variable.repoLang}] Codes <Label size='mini' circular color={variable.color}>{variable.repoList.length}</Label>
33+
</Button>
34+
</Button.Group>
35+
</Popup>
36+
);
37+
}

‎src/components/VariableList.js‎

Lines changed: 4 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,15 @@
11
import {useMemo} from 'react';
2-
import {Button, Label, Popup} from 'semantic-ui-react';
32
import * as Tools from '../utils/Tools';
3+
import VariableItem from './VariableItem';
44

55
const notFound = val => val && /59ce9297fba93aeb9d693a2f61922fb6|bfd876277827a33f49d363e8857977a0/g.test(Tools.MD5(val));
66
const notFoundImg = '//user-images.githubusercontent.com/799578/50722775-1a9a1d00-110f-11e9-9bcc-efe5465a4ad5.jpg';
7-
8-
function Variable(props) {
9-
const clipboardId = `clipboardId-${Tools.uuid()}`;
10-
const variable = props.variable;
11-
let clipboard = null;
12-
13-
function handlePopOnMount() {
14-
clipboard = new ClipboardJS(`#${clipboardId}`);
15-
}
16-
17-
function handlePopUnmount() {
18-
clipboard && clipboard.destroy();
19-
}
20-
21-
return (
22-
<Popup style={{padding: '0'}}
23-
position='top center'
24-
trigger={
25-
<Label circular color={variable.color} className={props.className} style={props.style}>
26-
{variable.keyword}
27-
</Label>}
28-
onMount={handlePopOnMount}
29-
onUnmount={handlePopUnmount}
30-
hoverable={true}>
31-
<Button.Group vertical basic style={{border: 0}}>
32-
<Button compact as='a' href={`#${variable.keyword}`}>Search</Button>
33-
<Button compact as='a' href={variable.repoLink} target='_blank'>Repo</Button>
34-
<Button compact data-clipboard-text={variable.keyword} id={clipboardId}>Copy</Button>
35-
<Button compact onClick={() => props.onOpenSourceCode(variable)}>
36-
[{variable.repoLang}] Codes <Label size='mini' circular color={variable.color}>{variable.repoList.length}</Label>
37-
</Button>
38-
</Button.Group>
39-
</Popup>
40-
);
41-
}
42-
437
const animationName = Math.random() > 0.5 ? 'zoomInDown' : 'zoomInUp';
448
let lastPageLen = 0;
9+
4510
export default function VariableList(props) {
4611
const variableList = props.variableList;
47-
const list = useMemo(() => {
12+
const list = useMemo(() => { // same as "shouldComponentUpdate", only compute when "variableList" has changed
4813
const pageLen = variableList.length;
4914
let pages = [];
5015
if (notFound(props.searchValue)) {
@@ -62,7 +27,7 @@ export default function VariableList(props) {
6227
animationDuration: Math.min(duration, 0.8) + Math.random() + 's'
6328
};
6429
}
65-
return <Variable key={Tools.uuid()} variable={variable}
30+
return <VariableItem key={Tools.uuid()} variable={variable}
6631
onOpenSourceCode={props.onOpenSourceCode} style={style} className={className}/>
6732
});
6833
if (variables && variables.length) {

‎src/containers/MainContainer.js‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ export default class MainContainer extends React.Component {
6767
}
6868

6969
requestVariable = (val, lang) => {
70-
const langChanged = lang ? (lang.join(',') != this.state.searchLang.join(',')) : this.state.searchLang != lang;
70+
const langChanged = lang ? (lang.join(',') != this.state.searchLang.join(',')) : !!this.state.searchLang;
7171
val = decodeURIComponent(val);
7272
let page = this.state.page;
7373
if (val == this.state.searchValue && !langChanged) {
@@ -76,7 +76,7 @@ export default class MainContainer extends React.Component {
7676
page = 0;
7777
}
7878
this.setState({searchValue: val, requestingVariable: true});
79-
SearchCodeModel.requestVariable(val, page, lang);
79+
SearchCodeModel.requestVariable(val, page, lang || this.state.searchLang);
8080
AppModel.analytics('q=' + val);
8181
DDMSModel.postKeyWords(val);
8282
this.updateDocTitle(val);
@@ -154,7 +154,7 @@ export default class MainContainer extends React.Component {
154154
this.requestVariable(val, lang);
155155
} else {
156156
this.setState({searchLang: lang});
157-
HashHandler.set(val); // update window.location.hash
157+
setTimeout(() => HashHandler.set(val)); // update window.location.hash
158158
}
159159
}
160160

0 commit comments

Comments
 (0)