summaryrefslogtreecommitdiff
path: root/app/routes/list-edit.tsx
blob: 5d477370e85bb1dc995722f35b897a0b9ad788b9 (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
import { useState } from "react";
import { data, Form, Link, redirect, useActionData, useLoaderData } from "react-router";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import {
  getBandListById,
  getListEntries,
  getIpAddress,
  updateBandList,
  type ListEntryInput,
} from "~/lib/db.server";

export async function loader({ params }: LoaderFunctionArgs) {
  const list = getBandListById(params.uuid!);
  if (!list) throw data("Not found", { status: 404 });
  const entries = getListEntries(list.id);
  return { list, entries };
}

export async function action({ params, request }: ActionFunctionArgs) {
  const list = getBandListById(params.uuid!);
  if (!list) throw data("Not found", { status: 404 });

  const fd = await request.formData();
  const title = (fd.get("title") as string).trim();
  const slug = (fd.get("slug") as string).trim();
  const description = (fd.get("description") as string).trim();
  const message = (fd.get("message") as string).trim();
  const entries: ListEntryInput[] = JSON.parse((fd.get("entries") as string) || "[]");

  const errors: Record<string, string> = {};
  if (!title) errors.title = "必須です";
  if (!slug) errors.slug = "必須です";
  if (!message) errors.message = "必須です";
  if (Object.keys(errors).length > 0) return { errors };

  try {
    updateBandList(list.id, { slug, title, description, entries, message, ip_address: getIpAddress(request) });
  } catch (e) {
    if (e instanceof Error && e.message.includes("UNIQUE constraint failed: lists.slug")) {
      return { errors: { slug: "このslugは既に使用されています" } };
    }
    throw e;
  }
  return redirect(`/lists/of/${list.id}`);
}

type EntryRow = { key: string; band_name: string; note: string };

export default function ListEdit() {
  const { list, entries: initEntries } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const errors = actionData?.errors ?? {};

  const [title, setTitle] = useState(list.title);
  const [slug, setSlug] = useState(list.slug);
  const [description, setDescription] = useState(list.description);
  const [entries, setEntries] = useState<EntryRow[]>(
    initEntries.map((e) => ({ key: crypto.randomUUID(), band_name: e.band_name, note: e.note }))
  );

  function addEntry() {
    setEntries((prev) => [...prev, { key: crypto.randomUUID(), band_name: "", note: "" }]);
  }

  function removeEntry(key: string) {
    setEntries((prev) => prev.filter((e) => e.key !== key));
  }

  function updateEntry(key: string, field: "band_name" | "note", value: string) {
    setEntries((prev) => prev.map((e) => e.key === key ? { ...e, [field]: value } : e));
  }

  return (
    <main>
      <div className="page-header">
        <Link to={`/lists/of/${list.id}`} className="back">←</Link>
        <h1>{list.title} — 編集</h1>
      </div>

      <Form method="post">
        <input type="hidden" name="entries" value={JSON.stringify(entries.map(({ band_name, note }) => ({ band_name, note })))} />

        <div>
          <label>タイトル <span className="req">*</span></label>
          <input name="title" value={title} onChange={(e) => setTitle(e.target.value)} />
          {errors.title && <p className="error">{errors.title}</p>}
        </div>

        <div>
          <label>Slug <span className="req">*</span></label>
          <input name="slug" value={slug} onChange={(e) => setSlug(e.target.value)} className="mono" />
          {errors.slug && <p className="error">{errors.slug}</p>}
        </div>

        <div>
          <label>説明</label>
          <input name="description" value={description} onChange={(e) => setDescription(e.target.value)} />
        </div>

        <div>
          <label>エントリ</label>
          <div>
            {entries.map((entry) => (
              <div key={entry.key} className="entry-row">
                <input
                  className="band-input"
                  value={entry.band_name}
                  onChange={(e) => updateEntry(entry.key, "band_name", e.target.value)}
                  placeholder="バンド名"
                />
                <input
                  className="note-input"
                  value={entry.note}
                  onChange={(e) => updateEntry(entry.key, "note", e.target.value)}
                  placeholder="メモ"
                />
                <button type="button" className="btn-icon" onClick={() => removeEntry(entry.key)}>×</button>
              </div>
            ))}
          </div>
          <button type="button" className="btn-text" onClick={addEntry}>+ エントリを追加</button>
        </div>

        <div>
          <label>更新メッセージ <span className="req">*</span></label>
          <input name="message" placeholder="例: エントリ追加" />
          {errors.message && <p className="error">{errors.message}</p>}
        </div>

        <div className="actions">
          <button type="submit">保存</button>
          <Link to={`/lists/of/${list.id}`} className="btn">キャンセル</Link>
        </div>
      </Form>
    </main>
  );
}