summaryrefslogtreecommitdiff
path: root/src2/components/layouts/Header.js
blob: 23fda642322655686d80869bd917f1820c1c3f64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import Image from "next/image";
import { Fragment, useCallback, useEffect, useRef, useState } from "react";
import Head from "next/head";
import { useRouter } from "next/router";
import axios from "axios";
import {
  MagnifyingGlassIcon,
  Bars3Icon,
  ShoppingCartIcon,
  ChevronRightIcon,
  Cog6ToothIcon,
  HeartIcon,
  ChevronDownIcon,
  ChevronUpIcon
} from "@heroicons/react/24/outline";

// Helpers
import { useAuth } from "@/core/utils/auth";
// Components
import Link from "../elements/Link";
// Images
import Logo from "@/images/logo.png";
import greeting from "@/core/utils/greeting";
import apiOdoo from "@/core/utils/apiOdoo";

const menus = [
  { name: 'Semua Brand', href: '/shop/brands' },
  { name: 'Blog Indoteknik', href: '/' },
  { name: 'Tentang Indoteknik', href: '/' },
  { name: 'Pusat Bantuan', href: '/' },
];

export default function Header({ title }) {
  const router = useRouter();
  const { q = '' } = router.query;
  const [searchQuery, setSearchQuery] = useState(q != '*' ? q : '');
  const [suggestions, setSuggestions] = useState([]);
  const searchQueryRef = useRef();
  const [isMenuActive, setIsMenuActive] = useState(false);
  const [auth] = useAuth();
  
  useEffect(() => {
    if (q) {
      searchQueryRef.current.blur();
      setSuggestions([]);
    };
  }, [q]);

  const clickSuggestion = (value) => {
    router.push(`/shop/search?q=${value}`, undefined, { scroll: false });
  };

  const getSuggestion = useCallback(async () => {
    if (searchQuery.trim().length > 0) {
      let result = await axios(`${process.env.SELF_HOST}/api/shop/suggest?q=${searchQuery.trim()}`);
      setSuggestions(result.data.suggest.mySuggester[searchQuery.trim()].suggestions);
    } else {
      setSuggestions([]);
    }
  }, [searchQuery]);

  useEffect(() => {
    if (document.activeElement == searchQueryRef.current) getSuggestion();
  }, [getSuggestion]);

  const openMenu = () => setIsMenuActive(true);
  const closeMenu = () => setIsMenuActive(false);

  const searchSubmit = (e) => {
    e.preventDefault();
    if (searchQuery.length > 0) {
      router.push(`/shop/search?q=${searchQuery}`, undefined, { scroll: false });
    } else {
      searchQueryRef.current.focus();
    }
  }

  const [ isOpenCategory, setOpenCategory ] = useState(false);
  const [ categories, setCategories ] = useState([]);

  useEffect(() => {
    const loadCategories = async () => {
      if (isOpenCategory && categories.length == 0) {
        let dataCategories = await apiOdoo('GET', '/api/v1/category/tree');
        dataCategories = dataCategories.map((category) => {
          category.childs = category.childs.map((child1Category) => {
            return {
              ...child1Category,
              isOpen: false
            }
          })
          return {
            ...category,
            isOpen: false
          }
        });
        setCategories(dataCategories);
      }
    }
    loadCategories();
  }, [ isOpenCategory, categories ]);
  
  const toggleCategories = (id = 0) => {
    let newCategories = categories.map((category) => {
      category.childs = category.childs.map((child1Category) => {
        return {
          ...child1Category,
          isOpen: id == child1Category.id ? !child1Category.isOpen : child1Category.isOpen
        }
      })
      return {
        ...category,
        isOpen: id == category.id ? !category.isOpen : category.isOpen
      }
    });
    setCategories(newCategories);
  }

  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <title>{title}</title>
      </Head>
      
      <div className={'menu-wrapper' + (isMenuActive ? ' active ' : '')}>
        <div className="flex gap-x-2 items-center border-b border-gray_r-6 p-4">
          { auth && (
            <Link href="/my/menu" className="w-full flex items-center text-gray_r-12" onClick={closeMenu}>
              <div>
                <p className="text-gray_r-11 text-caption-2">{ greeting() },</p>
                <h1>{auth.name}</h1>
              </div>
              <div className="ml-auto">
                <Cog6ToothIcon className="w-5" />
              </div>
            </Link>
          ) }

          { !auth && (
            <>
              <Link href="/login" onClick={closeMenu} className="w-full py-2 btn-light text-gray_r-12">Masuk</Link>
              <Link href="/register" onClick={closeMenu} className="w-full py-2 btn-yellow text-gray_r-12">Daftar</Link>
            </>
          ) }
        </div>
        <div className="flex flex-col">
          { menus.map((menu, index) => (
            <Link className="flex w-full font-normal text-gray_r-11 border-b border-gray_r-6 p-4" href={menu.href} key={index} onClick={closeMenu}>
                <span>{ menu.name }</span>
                <div className="ml-auto">
                  <ChevronRightIcon className="text-gray_r-12 w-5" />
                </div>
            </Link>
          )) }
          <div className="flex w-full font-normal text-gray_r-11 border-b border-gray_r-6 p-4" onClick={() => setOpenCategory(!isOpenCategory)}>
              <span>Kategori</span>
              <div className="ml-auto">
                { !isOpenCategory && <ChevronDownIcon className="text-gray_r-12 w-5" /> }
                { isOpenCategory && <ChevronUpIcon className="text-gray_r-12 w-5" /> }
              </div>
          </div>
          { isOpenCategory && categories.map((category) => (
            <Fragment key={category.id}>
              <div className="flex w-full text-gray_r-11 border-b border-gray_r-6 px-4 pl-8">
                <Link href={`/shop/search?category=${category.name}`} className="flex-1 font-normal text-gray_r-11 py-4">
                  { category.name }
                </Link>
                <div className="ml-4 h-full py-4" onClick={() => toggleCategories(category.id)}>
                  { !category.isOpen && <ChevronDownIcon className="text-gray_r-12 w-5" /> }
                  { category.isOpen && <ChevronUpIcon className="text-gray_r-12 w-5" /> }
                </div>
              </div>
              { category.isOpen && category.childs.map((child1Category) => (
                <Fragment key={child1Category.id}>
                  <div className={`flex w-full text-gray_r-11 border-b border-gray_r-6 p-4 pl-12 ${category.isOpen ? 'bg-gray_r-2' : ''}`}>
                    <Link href={`/shop/search?category=${child1Category.name}`} className="flex-1 font-normal text-gray_r-11">
                      { child1Category.name }
                    </Link>
                    { child1Category.childs.length > 0 && (
                      <div className="ml-4 h-full" onClick={() => toggleCategories(child1Category.id)}>
                        { !child1Category.isOpen && <ChevronDownIcon className="text-gray_r-12 w-5" /> }
                        { child1Category.isOpen && <ChevronUpIcon className="text-gray_r-12 w-5" /> }
                      </div>
                    ) }
                  </div>
                  { child1Category.isOpen && child1Category.childs.map((child2Category) => (
                    <Link key={child2Category.id} href={`/shop/search?category=${child2Category.name}`} className="flex w-full font-normal text-gray_r-11 border-b border-gray_r-6 p-4 pl-16">
                      { child2Category.name }
                    </Link>
                  )) }
                </Fragment>
              )) }
            </Fragment>
          )) }
        </div>
      </div>
      <div className={isMenuActive ? 'menu-overlay block opacity-100' : 'menu-overlay hidden opacity-0'} onClick={closeMenu}></div>

      <div className="sticky-header">
        <div className="flex justify-between items-center">
          <Link href="/" scroll={false}>
            <Image src={Logo} alt="Logo Indoteknik" width={120} height={40} />
          </Link>
          <div className="flex gap-x-4">
            <Link href="/my/wishlist">
              <HeartIcon className="w-6 text-gray_r-12" />
            </Link>
            <Link href="/shop/cart">
              <ShoppingCartIcon className="w-6 text-gray_r-12" />
            </Link>
            <button onClick={openMenu}>
              <Bars3Icon className="w-6 text-gray_r-12" />
            </button>
          </div>
        </div>
        <form onSubmit={searchSubmit} className="relative flex mt-2">
          <input 
            ref={searchQueryRef}
            type="text" 
            name="q" 
            onChange={(e) => setSearchQuery(e.target.value)} 
            onFocus={getSuggestion}
            value={searchQuery} 
            className="form-input rounded-r-none border-r-0 focus:border-gray_r-7" 
            placeholder="Ketikan nama, merek, part number"
            autoComplete="off"
          />

          <button 
            type="submit" 
            aria-label="search" 
            className="btn-light bg-transparent px-2 py-1 rounded-l-none border-l-0"
          >
            <MagnifyingGlassIcon className="w-6" />
          </button>

          {suggestions.length > 1 && (
            <div className="absolute w-full top-[50px] rounded-b bg-gray_r-2 border border-gray_r-6">
              {suggestions.map((suggestion, index) => (
                <p onClick={() => clickSuggestion(suggestion.term)} className="w-full p-2" key={index}>{suggestion.term}</p>
              ))}
            </div>
          )}
        </form>
      </div>

      {suggestions.length > 1 && (
        <div className="menu-overlay !z-40" onClick={() => setSuggestions([])}></div>
      )}
    </>
  )
}