aboutsummaryrefslogtreecommitdiff
path: root/src/pages/index.tsx
blob: 674878a0a76c787184f27876d809f7ce699b3fae (plain) (blame)
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
import type { NextPage } from "next";
import Head from "next/head";
import { List } from "immutable";
import {
  Header,
  Table,
  Message,
  Container,
  Pagination,
} from "semantic-ui-react";

import styles from "../styles/Home.module.css";
import { useMemo, useState } from "react";
import AddItem from "../components/add-item";
import {
  getGetItemsQueryKey,
  useGetItems,
  usePostItemsHook,
} from "../util/pantry-item-resource";
import { PantryItem } from "../model";
import { useMutation, useQueryClient } from "@tanstack/react-query";

const ENTRIES_PER_PAGE = Number(process.env.ENTRIES_PER_PAGE ?? "10");

interface SortStateProps {
  field: keyof PantryItem;
  order: "ascending" | "descending";
}

const Home: NextPage = () => {
  const { data, error } = useGetItems();
  const postItems = usePostItemsHook();
  const queryClient = useQueryClient();
  const { mutate } = useMutation(postItems, {
    onSuccess: async (item) => {
      queryClient.setQueryData(
        getGetItemsQueryKey(),
        (data ?? []).concat(item)
      );
    },
  });
  const [activePage, setActivePage] = useState(1);
  const [sortState, setSortState] = useState<SortStateProps>({
    field: "name",
    order: "ascending",
  });

  const hasEntries = useMemo(
    () => error === null && (data === undefined || data.length > 0),
    [error, data]
  );
  const entries = useMemo(() => {
    const list = List<PantryItem>(data);
    // case insensitive sort
    const sorted = list.sortBy((item) =>
      item[sortState.field]?.toString().toUpperCase()
    );

    return sortState.order === "ascending" ? sorted : sorted.reverse();
  }, [data, sortState]);
  const handleSortChange = (field: keyof PantryItem) => {
    setSortState((state) =>
      state.field === field
        ? {
            ...state,
            order: state.order === "ascending" ? "descending" : "ascending",
          }
        : { field: field, order: "ascending" }
    );
  };

  return (
    <Container className={styles.container}>
      <Head>
        <title>Pantry</title>
        <meta
          name="description"
          content="Meal planning with inventory management"
        />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Header as="h1" className="title">
        Pantry
      </Header>

      <AddItem addItem={(newItem) => Promise.resolve(mutate(newItem))} />
      <Message error={error !== null} attached hidden={hasEntries}>
        {error !== null
          ? error.message !== undefined
            ? `Network error occurred: ${error.message}`
            : "Unknown network error occurred"
          : "Nothing's in the pantry at the moment!"}
      </Message>
      <Table sortable attached="bottom">
        <Table.Header>
          <Table.Row>
            <Table.HeaderCell
              sorted={sortState.field === "name" ? sortState.order : undefined}
              onClick={() => handleSortChange("name")}
            >
              Name
            </Table.HeaderCell>
            <Table.HeaderCell
              sorted={
                sortState.field === "description" ? sortState.order : undefined
              }
              onClick={() => handleSortChange("description")}
            >
              Description
            </Table.HeaderCell>
            <Table.HeaderCell
              sorted={
                sortState.field === "quantity" ? sortState.order : undefined
              }
              onClick={() => handleSortChange("quantity")}
            >
              Quantity
            </Table.HeaderCell>
          </Table.Row>
        </Table.Header>
        <Table.Body>
          {entries
            .valueSeq()
            .slice(
              (activePage - 1) * ENTRIES_PER_PAGE,
              activePage * ENTRIES_PER_PAGE
            )
            .map((item: PantryItem) => (
              <Table.Row key={item.id}>
                <Table.Cell>{item.name}</Table.Cell>
                <Table.Cell>
                  {item.description === "" ? "—" : item.description}
                </Table.Cell>
                <Table.Cell>
                  {item.quantity} {item.quantityUnitType}
                </Table.Cell>
              </Table.Row>
            ))}
        </Table.Body>
        <Table.Footer>
          <Table.Row>
            <Table.HeaderCell colSpan="3">
              <Pagination
                activePage={activePage}
                onPageChange={(_, { activePage }) =>
                  setActivePage(Number(activePage ?? 1))
                }
                totalPages={Math.max(
                  1,
                  Math.ceil(entries.size / ENTRIES_PER_PAGE)
                )}
              />
            </Table.HeaderCell>
          </Table.Row>
        </Table.Footer>
      </Table>
    </Container>
  );
};

export default Home;