File size: 9,911 Bytes
a417977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {createContext} from "@/utils/context";
import {generateUUID} from "@/utils/uuids";
import {getCurrentTimeIso8601} from "@/utils/dates";
import {useContext} from "preact/hooks";
import {Settings} from "@/contexts/settings";
import {feedPosts, feedTopic} from "@/utils/model";
import {LogAction} from "@/contexts/log";

export type Post = {
    user: string;
    date: string; // date from AI if generated by AI tokens, ISO 8601, YYYY-MM-DDTHH:MM:SS
    generationDate: string | null; //"null" means not generated by AI, ISO 8601, YYYY-MM-DDTHH:MM:SS
    content: string;
}

export type Topic = {
    id: string; // UUID
    title: string;
    posts: Post[];
}

export type TopicsContext = {
    generation: "done" | "pending" | "error";
    import: "done" | "error";
    topics: Topic[];
}

const itemKey = "topics";

export const topicsCtx = createContext({
    initialValue: () => {
        const storedTopics = localStorage.getItem(itemKey);
        return {
            generation: "done",
            import: "done",
            topics: storedTopics ? JSON.parse(storedTopics) as Topic[] : []
        } as TopicsContext;
    },
    controllers: (topicsContext: TopicsContext, setTopicsContext) => ({
        effect: () => {
            // console.log("**")
            localStorage.setItem(itemKey, JSON.stringify(topicsContext.topics));
        },
        actions: {
            reset: (): void => {
                setTopicsContext({
                    generation: "done",
                    import: "done",
                    topics: []
                });
            },
            addTopic: (user: string, title: string, text: string): string => {
                const id = generateUUID();
                setTopicsContext({
                    ...topicsContext,
                    topics: [...topicsContext.topics, {
                        id: id,
                        title,
                        posts: [{
                            user: user,
                            date: getCurrentTimeIso8601(),
                            generationDate: null,
                            content: text,
                        }]
                    }],
                });
                return id;
            },
            deleteTopic: (topicId: string): void => {
                setTopicsContext({
                    ...topicsContext,
                    topics: topicsContext.topics.filter((topic) => topic.id !== topicId)
                });
            },
            addPost: (topicId: string, user: string, text: string): void => {
                const newPost: Post = {
                    user: user,
                    date: getCurrentTimeIso8601(),
                    generationDate: null,
                    content: text,
                }
                setTopicsContext({
                    ...topicsContext,
                    topics: topicsContext.topics.map((topic) => topic.id === topicId ? {
                        ...topic,
                        posts: [...topic.posts, newPost]
                    } : topic)
                });
            },
            deletePost: (topicId: string, postIndex: number): void => {
                setTopicsContext({
                    ...topicsContext,
                    topics: topicsContext.topics.map((topic) => {
                        if (topic.id !== topicId) {
                            return topic;
                        }

                        // Delete all posts if the first is deleted
                        const posts: Post[] = postIndex === 0 ? [] : topic.posts.filter((_, index) => index !== postIndex);

                        return {
                            ...topic,
                            posts
                        };
                        // Delete topic if it has not more posts
                    }).filter((t) => t.posts.length > 0)
                });
            },
            generateTopic: async (settings: Settings, log: LogAction) => {
                const id = generateUUID();
                setTopicsContext({
                    ...topicsContext,
                    generation: "pending",
                });
                log(`Topic: ${id} -> generation start.`)
                feedTopic(settings, log, id, (topic: Topic) => {
                    if(topic.title.length < 1) return;

                    setTopicsContext((topicsContext: TopicsContext) => {
                        // console.log(topicsContext);
                        const topicIndex = topicsContext.topics.findIndex((topic) => topic.id === id);

                        // -1 if no topic found
                        if(topicIndex < 0) {
                            return {
                                ...topicsContext,
                                generation: "pending",
                                topics: [...topicsContext.topics, topic]
                            } satisfies TopicsContext
                        }

                        return {
                            ...topicsContext,
                            generation: "pending",
                            // Replace the old topic with the new one
                            topics: topicsContext.topics.map(oldTopic => oldTopic.id === id ? topic : oldTopic),
                        } satisfies TopicsContext
                    });
                    // console.log("feedTopic");
                }).then(() => {
                    // console.log("then");
                    // TODO: check if the topic has been generated
                    setTopicsContext((topicsContext: TopicsContext) => ({
                        ...topicsContext,
                        generation: "done",
                    }))
                    log(`Topic: ${id} -> generation done.`)
                }).catch((e: Error) => {
                    setTopicsContext((topicsContext: TopicsContext) => ({
                        ...topicsContext,
                        generation: "error",
                    }))
                    log(`Topic: ${id} -> generation error (${e.message}).`)
                });
            },
            generatePosts: async (settings: Settings, log: LogAction, initialTopic: Topic) => {
                setTopicsContext({
                    ...topicsContext,
                    generation: "pending",
                });
                log(`Topic: ${initialTopic.id} -> generation start.`)
                feedPosts(settings, log, initialTopic, (topic: Topic) => {
                    setTopicsContext((topicsContext: TopicsContext) => {
                        // console.log(topicsContext);
                        const topicIndex = topicsContext.topics.findIndex((topic) => topic.id === initialTopic.id);

                        // -1 if no topic found
                        if(topicIndex < 0) {
                            return {
                                ...topicsContext,
                                generation: "pending",
                                topics: [...topicsContext.topics, topic]
                            } satisfies TopicsContext
                        }

                        return {
                            ...topicsContext,
                            generation: "pending",
                            // Replace the old topic with the new one
                            topics: topicsContext.topics.map(oldTopic => oldTopic.id === initialTopic.id ? topic : oldTopic),
                        } satisfies TopicsContext
                    });
                }).then(() => {
                    setTopicsContext((topicsContext: TopicsContext) => ({
                        ...topicsContext,
                        generation: "done",
                    }))
                    log(`Topic: ${initialTopic.id} -> generation done.`)
                }).catch((e: Error) => {
                    setTopicsContext((topicsContext: TopicsContext) => ({
                        ...topicsContext,
                        generation: "error",
                    }))
                    log(`Topic: ${initialTopic.id} -> generation error (${e.message}).`)
                });
            },
            importTopic: (json: string): void => {
                const error = (message: string): void => {
                    throw new Error(message)
                }
                try {
                    const object = JSON.parse(json);
                    const id = generateUUID();
                    const topic: Topic = {
                        id: id,
                        title: typeof object.title == "string" ? object.title : error("title must be a string"),
                        posts: object.posts instanceof Array ? object.posts.map((object: unknown): Post => ({
                            user: typeof object.user == "string" ? object.user : error("posts.user must be a string"),
                            date: typeof object.date == "string" ? object.date : error("posts.date must be a string"),
                            generationDate: typeof object.generationDate == "string" || object.generationDate === null ? object.generationDate : error("posts.generationDate must be null or string"),
                            content: typeof object.content == "string" ? object.content : error("posts.content must be a string"),
                        })) : error("posts must be a string"),
                    }
                    setTopicsContext({
                        ...topicsContext,
                        topics: [...topicsContext.topics, topic],
                        import: "done",
                    });
                } catch (e) {
                    console.error(e);
                    setTopicsContext({
                        ...topicsContext,
                        import: "error",
                    });
                }
            }
        },
    })
})