aboutsummaryrefslogtreecommitdiff
path: root/FrontEnd/src/pages/timeline/TimelinePostCreateView.tsx
blob: 70925cd968b9bfb1d81501e0ff0b2fed11393b18 (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
266
267
268
269
270
271
272
import { useState, useEffect, ChangeEventHandler } from "react";
import { useTranslation } from "react-i18next";

import { UiLogicError } from "~src/common";

import {
  getHttpTimelineClient,
  HttpTimelineInfo,
  HttpTimelinePostInfo,
  HttpTimelinePostPostRequestData,
} from "~src/http/timeline";

import base64 from "~src/utilities/base64";

import { pushAlert } from "~src/components/alert";
import BlobImage from "~src/components/BlobImage";
import LoadingButton from "~src/components/button/LoadingButton";
import PopupMenu from "~src/components/menu/PopupMenu";
import MarkdownPostEdit from "./MarkdownPostEdit";
import TimelinePostCard from "./TimelinePostCard";
import TimelinePostContainer from "./TimelinePostContainer";
import IconButton from "~src/components/button/IconButton";

import "./TimelinePostCreateView.css";
import classNames from "classnames";

interface TimelinePostEditTextProps {
  text: string;
  disabled: boolean;
  onChange: (text: string) => void;
  className?: string;
}

function TimelinePostEditText(props: TimelinePostEditTextProps) {
  const { text, disabled, onChange, className } = props;

  return (
    <textarea
      value={text}
      disabled={disabled}
      onChange={(event) => {
        onChange(event.target.value);
      }}
      className={classNames("timeline-post-create-edit-text", className)}
    />
  );
}

interface TimelinePostEditImageProps {
  onSelect: (file: File | null) => void;
  disabled: boolean;
}

function TimelinePostEditImage(props: TimelinePostEditImageProps) {
  const { onSelect, disabled } = props;

  const { t } = useTranslation();

  const [file, setFile] = useState<File | null>(null);
  const [error, setError] = useState<boolean>(false);

  const onInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
    setError(false);
    const files = e.target.files;
    if (files == null || files.length === 0) {
      setFile(null);
      onSelect(null);
    } else {
      setFile(files[0]);
    }
  };

  useEffect(() => {
    return () => {
      onSelect(null);
    };
  }, [onSelect]);

  return (
    <>
      <input
        type="file"
        onChange={onInputChange}
        accept="image/*"
        disabled={disabled}
        className="mx-3 my-1"
      />
      {file != null && !error && (
        <BlobImage
          src={file}
          className="timeline-post-create-image"
          onLoad={() => onSelect(file)}
          onError={() => {
            onSelect(null);
            setError(true);
          }}
        />
      )}
      {error ? <div className="text-danger">{t("loadImageError")}</div> : null}
    </>
  );
}

type PostKind = "text" | "markdown" | "image";

const postKindIconMap: Record<PostKind, string> = {
  text: "fonts",
  markdown: "markdown",
  image: "image",
};

export interface TimelinePostEditProps {
  className?: string;
  timeline: HttpTimelineInfo;
  onPosted: (newPost: HttpTimelinePostInfo) => void;
}

function TimelinePostEdit(props: TimelinePostEditProps) {
  const { timeline, className, onPosted } = props;

  const { t } = useTranslation();

  const [process, setProcess] = useState<boolean>(false);

  const [kind, setKind] = useState<Exclude<PostKind, "markdown">>("text");
  const [showMarkdown, setShowMarkdown] = useState<boolean>(false);

  const [text, setText] = useState<string>("");
  const [image, setImage] = useState<File | null>(null);

  const draftTextLocalStorageKey = `timeline.${timeline.owner.username}.${timeline.nameV2}.postDraft.text`;

  useEffect(() => {
    setText(window.localStorage.getItem(draftTextLocalStorageKey) ?? "");
  }, [draftTextLocalStorageKey]);

  const canSend =
    (kind === "text" && text.length !== 0) ||
    (kind === "image" && image != null);

  const onPostError = (): void => {
    pushAlert({
      color: "danger",
      message: "timeline.sendPostFailed",
    });
  };

  const onSend = async (): Promise<void> => {
    setProcess(true);

    let requestData: HttpTimelinePostPostRequestData;
    switch (kind) {
      case "text":
        requestData = {
          contentType: "text/plain",
          data: await base64(text),
        };
        break;
      case "image":
        if (image == null) {
          throw new UiLogicError(
            "Content type is image but image blob is null.",
          );
        }
        requestData = {
          contentType: image.type,
          data: await base64(image),
        };
        break;
      default:
        throw new UiLogicError("Unknown content type.");
    }

    getHttpTimelineClient()
      .postPost(timeline.owner.username, timeline.nameV2, {
        dataList: [requestData],
      })
      .then(
        (data) => {
          if (kind === "text") {
            setText("");
            window.localStorage.removeItem(draftTextLocalStorageKey);
          }
          setProcess(false);
          setKind("text");
          onPosted(data);
        },
        () => {
          setProcess(false);
          onPostError();
        },
      );
  };

  return (
    <TimelinePostContainer
      className={classNames(className, "timeline-post-create-container")}
    >
      <TimelinePostCard className="timeline-post-create-card">
        {showMarkdown ? (
          <MarkdownPostEdit
            className="cru-fill-parent"
            onClose={() => setShowMarkdown(false)}
            owner={timeline.owner.username}
            timeline={timeline.nameV2}
            onPosted={onPosted}
            onPostError={onPostError}
          />
        ) : (
          <div className="timeline-post-create">
            <div className="timeline-post-create-edit-area">
              {(() => {
                if (kind === "text") {
                  return (
                    <TimelinePostEditText
                      className="timeline-post-create-edit-text"
                      text={text}
                      disabled={process}
                      onChange={(text) => {
                        setText(text);
                        window.localStorage.setItem(
                          draftTextLocalStorageKey,
                          text,
                        );
                      }}
                    />
                  );
                } else if (kind === "image") {
                  return (
                    <TimelinePostEditImage
                      onSelect={setImage}
                      disabled={process}
                    />
                  );
                }
              })()}
            </div>
            <div className="timeline-post-create-right-area">
              <PopupMenu
                containerClassName="timeline-post-create-kind-select"
                items={(["text", "image", "markdown"] as const).map((kind) => ({
                  type: "button",
                  text: `timeline.post.type.${kind}`,
                  iconClassName: postKindIconMap[kind],
                  onClick: () => {
                    if (kind === "markdown") {
                      setShowMarkdown(true);
                    } else {
                      setKind(kind);
                    }
                  },
                }))}
              >
                <IconButton color="primary" icon={postKindIconMap[kind]} />
              </PopupMenu>
              <LoadingButton
                onClick={() => void onSend()}
                color="primary"
                disabled={!canSend}
                loading={process}
              >
                {t("timeline.send")}
              </LoadingButton>
            </div>
          </div>
        )}
      </TimelinePostCard>
    </TimelinePostContainer>
  );
}

export default TimelinePostEdit;