summaryrefslogtreecommitdiffhomepage
path: root/frontend/src/Sidebar/index.tsx
blob: 960d766d26dae2e2c07019093c781a1ba793db06 (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
254
255
256
import { setSidebar } from "@/modules/redux/actions";
import { useReduxAction, useReduxStore } from "@/modules/redux/hooks/base";
import { useRouteItems } from "@/Router";
import { CustomRouteObject, Route } from "@/Router/type";
import { BuildKey, pathJoin } from "@/utilities";
import { LOG } from "@/utilities/console";
import { useGotoHomepage } from "@/utilities/hooks";
import { IconDefinition } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
import {
  createContext,
  FunctionComponent,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";
import {
  Badge,
  Collapse,
  Container,
  Image,
  ListGroup,
  ListGroupItem,
} from "react-bootstrap";
import {
  matchPath,
  NavLink,
  RouteObject,
  useLocation,
  useNavigate,
} from "react-router-dom";

const Selection = createContext<{
  selection: string | null;
  select: (path: string | null) => void;
}>({
  selection: null,
  select: () => {
    LOG("error", "Selection context not initialized");
  },
});

function useSelection() {
  return useContext(Selection);
}

function useBadgeValue(route: Route.Item) {
  const { badge, children } = route;
  return useMemo(() => {
    let value = badge ?? 0;

    if (children === undefined) {
      return value;
    }

    value +=
      children.reduce((acc, child: Route.Item) => {
        if (child.badge && child.hidden !== true) {
          return acc + (child.badge ?? 0);
        }
        return acc;
      }, 0) ?? 0;

    return value === 0 ? undefined : value;
  }, [badge, children]);
}

function useIsActive(parent: string, route: RouteObject) {
  const { path, children } = route;

  const { pathname } = useLocation();
  const root = useMemo(() => pathJoin(parent, path ?? ""), [parent, path]);

  const paths = useMemo(
    () => [root, ...(children?.map((v) => pathJoin(root, v.path ?? "")) ?? [])],
    [root, children]
  );

  const selection = useSelection().selection;
  return useMemo(
    () =>
      selection?.includes(root) ||
      paths.some((path) => matchPath(path, pathname)),
    [pathname, paths, root, selection]
  );
}

// Actual sidebar
const Sidebar: FunctionComponent = () => {
  const [selection, select] = useState<string | null>(null);
  const isShow = useReduxStore((s) => s.site.showSidebar);

  const showSidebar = useReduxAction(setSidebar);

  const goHome = useGotoHomepage();

  const routes = useRouteItems();

  const { pathname } = useLocation();
  useEffect(() => {
    select(null);
  }, [pathname]);

  return (
    <Selection.Provider value={{ selection, select }}>
      <nav className={clsx("sidebar-container", { open: isShow })}>
        <Container className="sidebar-title d-flex align-items-center d-md-none">
          <Image
            alt="brand"
            src="/static/logo64.png"
            width="32"
            height="32"
            onClick={goHome}
            className="cursor-pointer"
          ></Image>
        </Container>
        <ListGroup variant="flush" style={{ paddingBottom: "16rem" }}>
          {routes.map((route, idx) => (
            <RouteItem
              key={BuildKey("nav", idx)}
              parent="/"
              route={route}
            ></RouteItem>
          ))}
        </ListGroup>
      </nav>
      <div
        className={clsx("sidebar-overlay", { open: isShow })}
        onClick={() => showSidebar(false)}
      ></div>
    </Selection.Provider>
  );
};

const RouteItem: FunctionComponent<{
  route: CustomRouteObject;
  parent: string;
}> = ({ route, parent }) => {
  const { children, name, path, icon, hidden, element } = route;

  const isValidated = useMemo(
    () =>
      element !== undefined ||
      children?.find((v) => v.index === true) !== undefined,
    [element, children]
  );

  const { select } = useSelection();

  const navigate = useNavigate();

  const link = useMemo(() => pathJoin(parent, path ?? ""), [parent, path]);

  const badge = useBadgeValue(route);

  const isOpen = useIsActive(parent, route);

  if (hidden === true) {
    return null;
  }

  // Ignore path if it is using match
  if (path === undefined || path.includes(":")) {
    return null;
  }

  if (children !== undefined) {
    const elements = children.map((child, idx) => (
      <RouteItem
        parent={link}
        key={BuildKey(link, "nav", idx)}
        route={child}
      ></RouteItem>
    ));

    if (name) {
      return (
        <div className={clsx("sidebar-collapse-box", { active: isOpen })}>
          <ListGroupItem
            action
            className={clsx("button", { active: isOpen })}
            onClick={() => {
              LOG("info", "clicked", link);

              if (isValidated) {
                navigate(link);
              }

              if (isOpen) {
                select(null);
              } else {
                select(link);
              }
            }}
          >
            <RouteItemContent
              name={name ?? link}
              icon={icon}
              badge={badge}
            ></RouteItemContent>
          </ListGroupItem>
          <Collapse in={isOpen}>
            <div className="indent">{elements}</div>
          </Collapse>
        </div>
      );
    } else {
      return <>{elements}</>;
    }
  } else {
    return (
      <NavLink
        to={link}
        className={({ isActive }) =>
          clsx("list-group-item list-group-item-action button sb-collapse", {
            active: isActive,
          })
        }
      >
        <RouteItemContent
          name={name ?? link}
          icon={icon}
          badge={badge}
        ></RouteItemContent>
      </NavLink>
    );
  }
};

interface ItemComponentProps {
  name: string;
  icon?: IconDefinition;
  badge?: number;
}

const RouteItemContent: FunctionComponent<ItemComponentProps> = ({
  icon,
  name,
  badge,
}) => {
  return (
    <>
      {icon && <FontAwesomeIcon size="1x" className="icon" icon={icon} />}
      <span className="d-flex flex-grow-1 justify-content-between">
        {name}
        <Badge variant="secondary" hidden={badge === undefined || badge === 0}>
          {badge}
        </Badge>
      </span>
    </>
  );
};

export default Sidebar;