-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuploadMarkdown.tsx
More file actions
90 lines (79 loc) · 2.9 KB
/
uploadMarkdown.tsx
File metadata and controls
90 lines (79 loc) · 2.9 KB
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
import { useState, useRef, useEffect } from "react";
import { Button } from "@mui/material";
import React, { InputHTMLAttributes, forwardRef } from "react";
const TEXT_FILE_ID = "textFileId";
type Props = {
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
id: InputHTMLAttributes<HTMLInputElement>["id"];
};
type MarkdownProps = {
onFileContentChange: (content: string) => void; // 親にデータを渡すためのProps
};
export default function UploadMarkdown({ onFileContentChange }: MarkdownProps) {
const [, setTextFile] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// 初回ロード時に localStorage からデータを読み込む
useEffect(() => {
const storedText = localStorage.getItem("item");
if (storedText) {
onFileContentChange(storedText); // 親コンポーネントにデータを渡す
}
}, []);
// ファイルが選択されたときの処理
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.currentTarget?.files && e.currentTarget.files[0]) {
const targetFile = e.currentTarget.files[0];
setTextFile(targetFile);
localStorage.setItem("filename", targetFile.name); // ファイル名を保存 -> ファイルを新規保存する際に使う。
// FileReaderを使ってファイルの内容を読み込む
const reader = new FileReader();
reader.onload = (event) => {
const text = event.target?.result as string; // ファイル内容を状態に保存
localStorage.setItem("item", text);
const storedText = localStorage.getItem("item") ?? "";
onFileContentChange(storedText);
console.log("Text saved:", storedText);
};
reader.readAsText(targetFile); // ファイルをテキストとして読み込む
}
};
const deleteStoredText = () => {
localStorage.removeItem("item");
onFileContentChange(""); // 削除後、親コンポーネントに空データを渡す
console.log("Stored text deleted");
};
return (
<>
<label>
テキストファイルをアップロード
{/* 見えないinput要素 */}
<InputMarkdown
ref={fileInputRef}
id={TEXT_FILE_ID}
onChange={handleFileChange}
/>
</label>
<Button onClick={() => fileInputRef.current?.click()}>
ファイルを選択
</Button>
<Button onClick={deleteStoredText}>消去する</Button>
</>
);
}
// テキストファイル用の Input コンポーネント
const InputMarkdown = forwardRef<HTMLInputElement, Props>(
({ onChange, id }, ref) => {
return (
<input
ref={ref}
id={id}
type="file"
accept=".md, text/markdown" // Markdownファイルを選択可能に
onChange={onChange}
hidden
/>
);
},
);
// displayNameを追加
InputMarkdown.displayName = "InputMarkdown";