Elffuss BraidHub

kikocis/continue public

main · 2.1 KiBRawPermalink
1import { JSONContent } from "@tiptap/react";
2import { useState } from "react";
3import { getLocalStorage, setLocalStorage } from "../util/localStorage";
4import useUpdatingRef from "./useUpdatingRef";
5
6const emptyJsonContent = () => ({
7 type: "doc",
8 content: [{ type: "paragraph", content: [{ type: "text", text: "" }] }],
9});
10
11const MAX_HISTORY_LENGTH = 100;
12
13export function useInputHistory(historyKey: string) {
14 const [inputHistory, setInputHistory] = useState<JSONContent[]>(
15 getLocalStorage(`inputHistory_${historyKey}`)?.slice(-MAX_HISTORY_LENGTH) ??
16 [],
17 );
18 const [pendingInput, setPendingInput] =
19 useState<JSONContent>(emptyJsonContent());
20 const [currentIndex, setCurrentIndex] = useState(inputHistory.length);
21
22 function prev(currentInput: JSONContent) {
23 let index = currentIndex;
24
25 if (index === inputHistory.length) {
26 setPendingInput(currentInput);
27 }
28
29 if (index > 0 && index <= inputHistory.length) {
30 setCurrentIndex((prevState) => prevState - 1);
31 return inputHistory[index - 1];
32 }
33 }
34
35 function next() {
36 let index = currentIndex;
37 if (index >= 0 && index < inputHistory.length) {
38 setCurrentIndex((prevState) => prevState + 1);
39 if (index === inputHistory.length - 1) {
40 return pendingInput;
41 }
42 return inputHistory[index + 1];
43 }
44 }
45
46 function add(inputValue: JSONContent) {
47 setPendingInput(emptyJsonContent());
48
49 if (
50 JSON.stringify(inputHistory[inputHistory.length - 1]) ===
51 JSON.stringify(inputValue)
52 ) {
53 setCurrentIndex(inputHistory.length);
54 return;
55 }
56
57 setCurrentIndex(inputHistory.length + 1);
58 setInputHistory((prev) => {
59 return [...prev, inputValue].slice(-MAX_HISTORY_LENGTH);
60 });
61 setLocalStorage(
62 `inputHistory_${historyKey}`,
63 [...inputHistory, inputValue].slice(-MAX_HISTORY_LENGTH),
64 );
65 }
66
67 const prevRef = useUpdatingRef(prev, [inputHistory]);
68 const nextRef = useUpdatingRef(next, [inputHistory]);
69 const addRef = useUpdatingRef(add, [inputHistory]);
70
71 return { prevRef, nextRef, addRef };
72}