summaryrefslogtreecommitdiff
path: root/app/routes/band-edit.tsx
blob: 2e292776d1f9005735f059d213d13728de9a07a0 (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
257
258
259
260
261
262
263
264
265
import { useState } from "react";
import { data, Form, Link, redirect, useActionData, useLoaderData } from "react-router";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import {
  getBandArtists,
  getBandById,
  getBandLinks,
  getIpAddress,
  listArtists,
  updateBand,
} from "~/lib/db.server";
import { ARTIST_ROLES, LINK_TYPES } from "~/lib/constants";

export async function loader({ params }: LoaderFunctionArgs) {
  const band = getBandById(params.uuid!);
  if (!band) throw data("Not found", { status: 404 });
  const links = getBandLinks(band.id);
  const bandArtists = getBandArtists(band.id);
  const allArtists = listArtists();
  return { band, links, bandArtists, allArtists };
}

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

  const fd = await request.formData();
  const name = (fd.get("name") as string).trim();
  const slug = (fd.get("slug") as string).trim();
  const area = (fd.get("area") as string).trim() || null;
  const description = (fd.get("description") as string).trim() || null;
  const status = (fd.get("status") as string) || "active";
  const message = (fd.get("message") as string).trim();
  const links: { label: string; url: string }[] = JSON.parse(
    (fd.get("links") as string) || "[]"
  );
  const artists: { id: string; role: string | null }[] = JSON.parse(
    (fd.get("artists") as string) || "[]"
  );

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

  try {
    updateBand(band.id, { slug, name, area, description, status, links, artists, message, ip_address: getIpAddress(request) });
  } catch (e) {
    if (e instanceof Error && e.message.includes("UNIQUE constraint failed: bands.slug")) {
      return { errors: { slug: "このslugは既に使用されています" } };
    }
    throw e;
  }
  return redirect(`/bands/of/${band.id}`);
}

function toSlug(s: string) {
  return s.trim().toLowerCase().replace(/\s+/g, "-").replace(/[^\w぀-ヿ一-鿿＀-￯-]/g, "").replace(/^-+|-+$/g, "");
}

type PickedArtist = { id: string; name: string; roles: string[] };
type PendingRole = { type: string; custom: string };
const DEFAULT_PENDING: PendingRole = { type: ARTIST_ROLES[0], custom: "" };

export default function BandEdit() {
  const { band, links: initLinks, bandArtists: initArtists, allArtists } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const errors = actionData?.errors ?? {};

  const [name, setName] = useState(band.name);
  const [slug, setSlug] = useState(band.slug);
  const [slugManual, setSlugManual] = useState(true);
  const [links, setLinks] = useState(initLinks.map((l) => ({ label: l.label, url: l.url })));
  const [picked, setPicked] = useState<PickedArtist[]>(
    initArtists.map((a) => ({
      id: a.artist_id,
      name: a.artist_name,
      roles: a.role ? a.role.split(", ").filter(Boolean) : [],
    }))
  );
  const [pending, setPending] = useState<Record<string, PendingRole>>(
    Object.fromEntries(initArtists.map((a) => [a.artist_id, { ...DEFAULT_PENDING }]))
  );

  const available = allArtists.filter((a) => !picked.some((p) => p.id === a.id));

  function addRole(artistId: string) {
    const pend = pending[artistId] ?? DEFAULT_PENDING;
    const role = pend.type === "other" ? pend.custom.trim() : pend.type;
    if (!role) return;
    setPicked((prev) => prev.map((a) => a.id === artistId ? { ...a, roles: [...a.roles, role] } : a));
  }

  function removeRole(artistId: string, idx: number) {
    setPicked((prev) => prev.map((a) => a.id === artistId ? { ...a, roles: a.roles.filter((_, i) => i !== idx) } : a));
  }

  return (
    <main>
      <div className="page-header">
        <Link to={`/bands/of/${band.id}`} className="back">←</Link>
        <h1>Edit Band</h1>
      </div>

      <Form method="post">
        <input type="hidden" name="links" value={JSON.stringify(links)} />
        <input
          type="hidden"
          name="artists"
          value={JSON.stringify(picked.map((p) => ({ id: p.id, role: p.roles.join(", ") || null })))}
        />

        <div>
          <label>バンド名 <span className="req">*</span></label>
          <input
            name="name"
            value={name}
            onChange={(e) => { setName(e.target.value); if (!slugManual) setSlug(toSlug(e.target.value)); }}
          />
          {errors.name && <p className="error">{errors.name}</p>}
        </div>

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

        <div>
          <label>活動拠点</label>
          <input name="area" defaultValue={band.area ?? ""} />
        </div>

        <div>
          <label>ステータス</label>
          <select name="status" defaultValue={band.status}>
            <option value="active">活動中</option>
            <option value="hiatus">活動休止</option>
            <option value="disbanded">解散</option>
          </select>
        </div>

        <div>
          <label>説明</label>
          <textarea name="description" rows={3} defaultValue={band.description ?? ""} />
        </div>

        <div>
          <label>リンク</label>
          <div className="links-form">
            {links.map((link, i) => (
              <div key={i} className="link-row">
                <select
                  value={link.label}
                  onChange={(e) => setLinks(links.map((l, idx) => idx === i ? { ...l, label: e.target.value } : l))}
                >
                  {LINK_TYPES.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
                </select>
                <input
                  value={link.url}
                  onChange={(e) => setLinks(links.map((l, idx) => idx === i ? { ...l, url: e.target.value } : l))}
                  placeholder="https://..."
                />
                <button type="button" className="btn-icon" onClick={() => setLinks(links.filter((_, idx) => idx !== i))}>×</button>
              </div>
            ))}
          </div>
          <button
            type="button"
            className="btn-text"
            onClick={() => setLinks([...links, { label: LINK_TYPES[0].value, url: "" }])}
          >
            + リンクを追加
          </button>
        </div>

        <div>
          <label>メンバー</label>
          {picked.length > 0 && (
            <div className="members-form">
              {picked.map((p) => {
                const pend = pending[p.id] ?? DEFAULT_PENDING;
                return (
                  <div key={p.id} className="member-card">
                    <div className="card-header">
                      <span className="card-name">{p.name}</span>
                      <button
                        type="button"
                        className="btn-icon"
                        onClick={() => setPicked(picked.filter((a) => a.id !== p.id))}
                      >
                        削除
                      </button>
                    </div>
                    {p.roles.length > 0 && (
                      <div className="badges">
                        {p.roles.map((r, ri) => (
                          <span key={ri} className="badge">
                            {r}
                            <button type="button" onClick={() => removeRole(p.id, ri)}>×</button>
                          </span>
                        ))}
                      </div>
                    )}
                    <div className="role-row">
                      <select
                        value={pend.type}
                        onChange={(e) => setPending({ ...pending, [p.id]: { ...pend, type: e.target.value } })}
                      >
                        {ARTIST_ROLES.map((r) => <option key={r} value={r}>{r}</option>)}
                        <option value="other">その他...</option>
                      </select>
                      {pend.type === "other" && (
                        <input
                          className="custom-input"
                          value={pend.custom}
                          onChange={(e) => setPending({ ...pending, [p.id]: { ...pend, custom: e.target.value } })}
                          placeholder="ロール名"
                        />
                      )}
                      <button type="button" className="btn-text" onClick={() => addRole(p.id)}>+ 追加</button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
          {available.length > 0 && (
            <select
              onChange={(e) => {
                const a = allArtists.find((x) => x.id === e.target.value);
                if (a) {
                  setPicked([...picked, { id: a.id, name: a.name, roles: [] }]);
                  setPending({ ...pending, [a.id]: { ...DEFAULT_PENDING } });
                  e.target.value = "";
                }
              }}
              defaultValue=""
            >
              <option value="">+ アーティストを追加...</option>
              {available.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
            </select>
          )}
        </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={`/bands/of/${band.id}`} className="btn">キャンセル</Link>
        </div>
      </Form>
    </main>
  );
}