-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp1.tsx
More file actions
313 lines (280 loc) · 10.1 KB
/
App1.tsx
File metadata and controls
313 lines (280 loc) · 10.1 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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
//マークダウンの編集
import { useEffect, useState, SetStateAction } from "react";
import parse, { Element, HTMLReactParserOptions } from "html-react-parser";
// import Markdown from "react-markdown";
// import rehypeKatex from "rehype-katex";
// import remarkMath from "remark-math";
import Tippy from "@tippyjs/react";
// import markdownLink from "/hoge.md?url";
import { ExtractDefinitions } from "./MDToDefinitions";
import { MDToHTML } from "./MDToHTML";
import { replaceExternalSyntax } from "./external-syntax";
//import ExtractPDF from "./extractPDF";
//import pdfFile from "/chibutsu_nyumon.pdf";
import Textarea from "@mui/joy/Textarea";
import { Button } from "@mui/material";
import "./index.css";
import "katex/dist/katex.min.css";
import "tippy.js/dist/tippy.css";
import UploadMarkdown from "./uploadMarkdown";
import UploadImage from "./uploadImage";
//import styled from "@emotion/styled";
type positionInfo = null | { top: number; left: number };
export default function App1() {
const [markdown, setMarkdown] = useState("");
const [html, setHTML] = useState("");
const [dict, setDict] = useState(new Map());
const opts = { prefix: "!define", suffix: "!enddef" };
// ドラッグして直接参照できる機能の部分
const [inputPosition, setInputPosition] = useState<positionInfo>(null); // ドラッグされた位置
const [inputValue, setInputValue] = useState("");
const [isTextAreaFocused, setIsTextAreaFocused] = useState(false);
const [visualize, setVisualize] = useState(true); // テキストエリアを表示にするか非表示にするか
const [fileContent, setFileContent] = useState<string>("");
const [imageData, setImageData] = useState<string>("");
// get markdown
// useEffect(() => {
// fetch(markdownLink)
// .then((res) => res.text())
// .then((t) => setMarkdown(t))
// .catch((err) => console.error("Error fetching Hoge.md:", err));
// }, []);
useEffect(() => {
setMarkdown(fileContent);
}, [fileContent]);
useEffect(() => {
localStorage.setItem("item", markdown);
}, [markdown]); // markdownの内容が変わるたびにlocalStorageに保存。
// use markdown (separation is necessary because it's async)
useEffect(() => void insideUseEffect(), [markdown]);
async function insideUseEffect() {
// prepare dictionary
const d = ExtractDefinitions(markdown, opts.prefix, opts.suffix);
const newd = new Map<string, string>();
const promises: Promise<Map<string, string>>[] = [];
d.forEach((v, k) => {// eslint-disable-line
let md = replaceExternalSyntax(v);
md = md.replaceAll(opts.prefix, "##").replaceAll(opts.suffix, ""); // eslint-disable-line
//const p = MDToHTML(md).then((newv) => newd.set(k, newv));
//promises.push(p);
});
Promise.all(promises).then(() => setDict(newd));
// prepare HTML
let md;
try {
md = replaceExternalSyntax(markdown.replace(/!define[\s\S]*$/m, "")); // !define以下をすべて取り去る。
/* eslint @typescript-eslint/no-explicit-any: 0 */
} catch (e: any) {
md = e.toString();
}
MDToHTML(md.replaceAll(opts.prefix, "##").replaceAll(opts.suffix, ""))
.then((h) => setHTML(h))
.catch(() => console.log("MDToHTML failed"));
}
// ドラッグして直接参照できる機能の部分
useEffect(() => {
const handleSelectionChange = () => {
const selection = document.getSelection();
if (selection && selection.rangeCount > 0 && !isTextAreaFocused) {
// textareaがFocusされていないときのみ、selectionを発令する。
const range = selection.getRangeAt(0); // Range { commonAncestorContainer: #text, startContainer: #text, startOffset: 8, endContainer: #text, endOffset: 23, collapsed: true }
// 左から8文字目から23文字目であることを指している。
const rect = range.getBoundingClientRect(); // DOMRect { x: 209.56666564941406, y: 167.25, width: 130.38333129882812, height: 29, top: 167.25, right: 339.9499969482422, bottom: 196.25, left: 209.56666564941406 }
// 位置情報の取得
// setSelectedText(selection.toString()); // ...unused
if (selection.toString()) {
// console.log(selection.toString()) 選択した範囲の文字列。
setInputPosition({
top: rect.bottom + window.scrollY,
left: rect.left + window.scrollX,
});
setInputValue("!define " + selection.toString());
} else {
setInputPosition(null);
}
}
};
document.addEventListener("selectionchange", handleSelectionChange);
return () => {
document.removeEventListener("selectionchange", handleSelectionChange);
};
}, [isTextAreaFocused]);
const handleInputChange = (event: {
target: { value: SetStateAction<string> };
}) => {
setInputValue(event.target.value);
// console.log(inputValue) 入力された内容がここに入る。
};
const handleImageChange = (content: string) => {
setImageData(content);
};
const handleTextAreaFocus = () => {
setIsTextAreaFocused(true);
};
const handleTextAreaBlur = () => {
setIsTextAreaFocused(false);
};
// テキストファイルを保存する
const saveFile = () => {
const blob = new Blob([markdown], { type: ".md, text/markdown" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = localStorage.getItem("filename") ?? "hoge.md"; // localStorage上に保存したファイル名を使う。
link.click();
};
return (
<>
<div className="save_container">
<div className="upload_save">
<UploadMarkdown onFileContentChange={setFileContent} />
<Button variant="text" onClick={saveFile}>
保存
</Button>
</div>
<div className="upload_save">
<UploadImage onImageChange={handleImageChange} />
</div>
</div>
{visualize == false && (
<>
<div className="upload_save">
<Button
variant="text"
onClick={() => {
setVisualize(true);
}}
>
編集画面の表示
</Button>
</div>
<div className="wrapper_false">
<ConvertMarkdown dictionary={dict} html={html} opts={opts} />
</div>
</>
)}
<div>{imageData}</div>
{visualize == true && (
<>
<div className="upload_save">
<Button
variant="text"
onClick={() => {
setVisualize(false);
}}
>
編集画面の非表示
</Button>
</div>
<div className="wrapper_true">
<div className="convert_markdown">
<ConvertMarkdown dictionary={dict} html={html} opts={opts} />
</div>
<textarea
value={markdown}
onChange={(event) => {
setMarkdown(event.target.value);
}}
placeholder="編集画面"
/>
</div>
</>
)}
{/* ドラッグして参照する部分 */}
{inputPosition && (
<>
<Textarea
value={inputValue}
onChange={handleInputChange}
style={{
position: "absolute",
top: `${inputPosition.top}px`,
left: `${inputPosition.left}px`,
}}
onFocus={handleTextAreaFocus}
onBlur={handleTextAreaBlur}
/>
<button
onClick={() =>
setMarkdown((markdown) => markdown + "\n" + inputValue + "\n")
}
style={{
position: "absolute",
top: `${inputPosition.top - 1}px`,
left: `${inputPosition.left + 250}px`,
}}
>
送信
</button>
</>
)}
</>
);
}
// this uses given dictionary as the source to extract definition from,
// and given html to render the main note.
function ConvertMarkdown({
dictionary,
html,
}: {
dictionary: Map<string, string>;
html: string;
opts: { prefix: string; suffix: string };
}) {
const parsing = html.split("\n");
dictionary = new Map(
[...dictionary.entries()].sort((a, b) => a[0].length - b[0].length),
); // Sort dictionary entries by word length to avoid overlapping replacements
// Replace words with tooltip-enabled spans
dictionary.forEach((_def: string, word: string) => {
let idx = 0;
for (const line of parsing) {
// Skip lines that are part of the definition to avoid replacing inside the definition itself
if (!line.includes(`<h2>${word}</h2>`)) {
parsing[idx] = line.replaceAll(
word,
`<span class="${word} underline">${word}</span>`,
);
}
idx++;
}
});
const parsedHtml = parsing.join("\n");
const options: HTMLReactParserOptions = {
replace(domNode) {
if (!(domNode instanceof Element)) {
return domNode;
}
const tagName = domNode.tagName;
// Handle images
if (tagName === "img") {
const src = domNode.attribs?.src;
const alt = domNode.attribs?.alt;
return (
<img src={src} alt={alt || "image"} style={{ maxWidth: "100%" }} />
);
}
const word: string | undefined = domNode.attribs?.class?.split(" ")[0];
const newClass: string = domNode.attribs?.class
?.split(" ")
.slice(0)
.join(" ");
// Handle words that should show tooltips
if (
domNode instanceof Element &&
domNode.attribs?.class &&
dictionary.has(word)
) {
return (
<Tippy
content={parse(dictionary.get(word) || "")}
className="markdown_tippy"
>
<span className={newClass}>{word}</span>
</Tippy>
);
}
return domNode; // Return the domNode unchanged if no special handling is needed
},
};
return <>{parse(parsedHtml, options)}</>; // パースされた HTML を返す
}