@@ -2,30 +2,77 @@ import React from 'react';
22import { Container } from 'semantic-ui-react' ;
33import SearchBar from '../components/SearchBar' ;
44import Title from '../components/Title' ;
5+ import SearchcodeModel from '../models/SearchcodeModel' ;
6+ import HashHandler from '../utils/HashHandler' ;
7+ import VariableList from '../components/VariableList' ;
58
69export default class MainContainer extends React . Component {
710 state = {
8- searchValue : null ,
11+ isSearchingVariable : false ,
12+ searchValue : SearchcodeModel . searchValue ,
13+ searchLang : SearchcodeModel . searchLang ,
14+ page : SearchcodeModel . page ,
15+ variableList : SearchcodeModel . variableList
916 }
1017
1118 constructor ( props ) {
1219 super ( props ) ;
20+ SearchcodeModel . onUpdated ( this . handleSearchcodeModelUpdate ) ;
21+ window . addEventListener ( 'hashchange' , this . handleLocationHashChanged , false ) ;
1322 }
1423
1524 componentDidUpdate ( prevProps ) {
16- if ( this . props . location !== prevProps . location ) {
17- }
25+ this . state . variableList . length && document . body . classList . add ( 'dark' ) ;
1826 }
1927
2028 componentDidMount ( ) {
21- document . body . classList . add ( 'dark' )
29+ this . handleLocationHashChanged ( ) ;
30+ }
31+
32+ handleLocationHashChanged = e => {
33+ e && e . preventDefault ( ) ;
34+ const hash = HashHandler . get ( ) ;
35+ hash && this . requestVariable ( hash . replace ( / ( \? .* ) / , '' ) ) ;
36+ }
37+
38+ handleSearchcodeModelUpdate = ( curr , prev , mutation ) => {
39+ this . setState ( {
40+ isSearchingVariable : ! mutation . variableList ,
41+ searchValue : SearchcodeModel . searchValue ,
42+ searchLang : SearchcodeModel . searchLang ,
43+ page : SearchcodeModel . page ,
44+ variableList : SearchcodeModel . variableList
45+ } ) ;
46+ }
47+
48+ handleSearch = ( val , lang ) => {
49+ this . setState ( { searchLang : lang } ) ;
50+ if ( val === null || val === undefined || this . state . isSearchingVariable ) { return ; }
51+ val = val . trim ( ) . replace ( / \s + / ig, ' ' ) ; // filter spaces
52+ if ( val . length < 1 ) { return ; }
53+ if ( val == this . state . searchValue ) {
54+ this . requestVariable ( val ) ;
55+ } else {
56+ HashHandler . set ( val ) ; // update window.location.hash
57+ }
58+ }
59+
60+ requestVariable = val => {
61+ val = decodeURIComponent ( val ) ;
62+ let page = this . state . page ;
63+ if ( val === this . state . searchValue ) {
64+ page += 1 ;
65+ }
66+ this . setState ( { isSearchingVariable : true } ) ;
67+ SearchcodeModel . requestVariable ( val , page , this . state . searchLang ) ;
2268 }
2369
2470 render ( ) {
2571 return (
2672 < Container className = 'main' >
2773 < Title { ...this . state } />
28- < SearchBar placeholder = 'AI 人工智能' { ...this . state } />
74+ < SearchBar placeholder = 'AI 人工智能' { ...this . state } onSearch = { this . handleSearch } />
75+ < VariableList { ...this . state } />
2976 </ Container >
3077 )
3178 }
0 commit comments