1
- import { useCallback , useContext , useEffect , useState } from 'react' ;
1
+ import { useCallback , useContext , useEffect , useRef , useState } from 'react' ;
2
+ import { throttle } from 'lodash' ;
3
+ import dynamic from 'next/dynamic' ;
4
+ import { useRouter } from 'next/router' ;
2
5
import { Button , Grid , makeStyles , TextField } from '@material-ui/core' ;
3
6
import { Post } from '@zoonk/models' ;
7
+ import { searchPost } from '@zoonk/services' ;
4
8
import { appLanguage , GlobalContext } from '@zoonk/utils' ;
5
9
import FormattingTips from './FormattingTips' ;
6
10
import FormBase from './FormBase' ;
@@ -9,6 +13,8 @@ import LinkFormField from './LinkFormField';
9
13
import PostPreview from './PostPreview' ;
10
14
import TopicSelector from './TopicSelector' ;
11
15
16
+ const PostSelector = dynamic ( ( ) => import ( './PostSelector' ) ) ;
17
+
12
18
const useStyles = makeStyles ( ( theme ) => ( {
13
19
column : {
14
20
'& > *' : {
@@ -42,6 +48,8 @@ const PostForm = ({
42
48
onSubmit,
43
49
} : PostFormProps ) => {
44
50
const { translate } = useContext ( GlobalContext ) ;
51
+ const { query } = useRouter ( ) ;
52
+ const category = String ( query . category ) as Post . Category ;
45
53
const classes = useStyles ( ) ;
46
54
const [ preview , setPreview ] = useState < boolean > ( false ) ;
47
55
const [ content , setContent ] = useState < string > ( data ?. content || '' ) ;
@@ -50,7 +58,23 @@ const PostForm = ({
50
58
const [ links , setLinks ] = useState < string [ ] > (
51
59
data && data . links && data . links . length > 0 ? data . links : [ '' ] ,
52
60
) ;
61
+ const [ search , setSearch ] = useState < ReadonlyArray < Post . Index > > ( [ ] ) ;
53
62
const valid = content . length > 0 && title . length > 0 && topics . length > 0 ;
63
+ const lessonCategories = [ 'examples' , 'lessons' ] ;
64
+ const isLesson = lessonCategories . includes ( category ) ;
65
+
66
+ const throttled = useRef (
67
+ throttle ( ( searchTerm : string ) => {
68
+ searchPost ( searchTerm , category ) . then ( setSearch ) ;
69
+ } , 1000 ) ,
70
+ ) ;
71
+
72
+ // Search existing posts when creating a new one.
73
+ useEffect ( ( ) => {
74
+ if ( ! data && isLesson && title . length > 3 ) {
75
+ throttled . current ( title ) ;
76
+ }
77
+ } , [ data , isLesson , title ] ) ;
54
78
55
79
// Add the current topicId when adding a new item.
56
80
useEffect ( ( ) => {
@@ -122,6 +146,8 @@ const PostForm = ({
122
146
type = "text"
123
147
/>
124
148
149
+ { isLesson && < PostSelector posts = { search } /> }
150
+
125
151
< TextField
126
152
required
127
153
value = { content }
0 commit comments