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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
|
"use client";
import { Spinner } from "@/components/ui/spinner";
import "../Flashcard/cards.css";
import { useState, useEffect, useTransition, useRef, useCallback } from "react";
import { WordData } from "@/zoom/logic/types";
import {
fetchWordsByToneAndSyllables,
mutateToneSelection,
} from "@/actions/tones";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton"; // For loading state
import { MutationOrder, PhoneticData, ToneQuery } from "@/lib/types/phonetics";
import { ProsodySyllable } from "@/lib/types/cards";
import { ArrowLeft, ArrowRight, Volume2, FlipHorizontal2 } from "lucide-react";
import { LLM } from "@/lib/services/llm";
function getColorByTone(tone: string): string {
if (tone === "mid") return "blue";
if (tone === "low") return "green";
if (tone === "falling") return "gold";
if (tone === "high") return "purple";
if (tone === "rising") return "black";
else return "black";
}
// Helper to display tones prominently
const ProminentToneDisplay = ({ word }: { word: any }) => {
const [isLoading, setLoading] = useState(false);
const tones: string[] = word.tone_sequence.split(",");
const syls: string[] = word.syl_seq.split(",");
const [isPending, startTransition] = useTransition();
function mutateWord(idx: number) {
console.log("changing", idx);
const mutationOrder: MutationOrder = syls.map((s, i) => {
if (idx === i) return { change: tones[idx]! };
else return { keep: syls[i]! };
});
console.log("hey hey", word);
startTransition(async () => {
const words = await mutateToneSelection(mutationOrder);
console.log({ words });
// setCurrentWord(word);
});
}
// playing audio
// const sourceRef = useRef<AudioBufferSourceNode>(null);
const audioRef = useRef<HTMLAudioElement>(null);
async function playAudio() {
setLoading(true);
// const audioContext = new (window.AudioContext ||
// (window as any).webkitAudioContext)();
// const response = await fetch(audioUrl);
// const arrayBuffer = await response.arrayBuffer();
// const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
// if (audioContext && audioBuffer) {
// setLoading(false);
// const source = audioContext.createBufferSource();
// source.buffer = audioBuffer;
// source.connect(audioContext.destination);
// source.start();
// sourceRef.current = source;
// }
const res = await fetch(`/api/tts?word=${word.spelling}&lang=thai`);
const audioBlob = await res.blob();
const audioURL = URL.createObjectURL(audioBlob);
setLoading(false);
if (audioRef.current) {
audioRef.current.src = audioURL;
audioRef.current.play();
}
}
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === " ") {
e.preventDefault();
playAudio();
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [playAudio]);
async function testLM() {
const lm = new LLM({
openai: {
url: "http://localhost:1234/v1",
apiKey: "",
model: "openai/gpt-oss-20b",
allowBrowser: true,
},
});
const res = await lm.chat("hey man something great happened to me today");
console.log("llm res", res);
}
return (
<div className="flex flex-col items-center mb-4">
<h1 className="text-6xl font-bold mb-2">
{syls.map((syl: string, idx: number) => (
<span
key={syl + idx}
onClick={() => mutateWord(idx)}
style={{ color: getColorByTone(tones[idx]!) }}
className="cursor-pointer hover:text-gray-700"
>
{syl}
</span>
))}
</h1>
<div className="mt-4 space-x-4">
<p className="ipa text-xl text-gray-700 mt-2">{word.ipa}</p>
<button
className="p-1 text-blue-500 hover:text-blue-700 transition-colors"
title="Pronounce"
onClick={playAudio}
>
<Volume2 size={20} />
</button>
{(isPending || isLoading) && <Spinner />}
<audio ref={audioRef} />
<p className="ipa text-xl text-gray-700 mt-2">{word.frequency}</p>
<p className="ipa text-xl text-gray-700 mt-2">{word.word_id}</p>
<button onClick={testLM}>Test</button>
</div>
</div>
);
};
export default function ToneSelectorClient({
initialData,
initialTones,
}: {
initialData: PhoneticData[];
initialTones: ToneQuery;
}) {
console.log({ initialData });
const [data, setData] = useState<any[]>(initialData);
const [currentIdx, setCurrentIdx] = useState(0);
const [isLoading, startTransition] = useTransition();
const [selectedTones, setTones] = useState<ToneQuery>(initialTones);
const goPrev = useCallback(() => {
setCurrentIdx((i) => (i === 0 ? 0 : i - 1));
}, []);
const goNext = useCallback(() => {
setCurrentIdx((i) => (i === data.length - 1 ? data.length - 1 : i + 1));
}, [data.length]);
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "ArrowLeft") {
e.preventDefault();
goPrev();
} else if (e.key === "ArrowRight") {
e.preventDefault();
goNext();
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [goPrev, goNext]);
const handleFetch = () => {
startTransition(async () => {
const words = await fetchWordsByToneAndSyllables(selectedTones);
setData(words);
});
};
return (
<div className="container mx-auto p-4 max-w-2xl">
<ToneForm
isLoading={isLoading}
handleFetch={handleFetch}
selectedTones={selectedTones}
setTones={setTones}
/>
<Inner
isLoading={isLoading}
currentWord={data[currentIdx]}
goPrev={goPrev}
goNext={goNext}
/>
</div>
);
}
type IProps = {
isLoading: boolean;
currentWord: PhoneticData;
goPrev: () => void;
goNext: () => void;
};
function Inner({ isLoading, currentWord, goPrev, goNext }: IProps) {
const [isFlipped, setIsFlipped] = useState(false);
const toggleFlip = () => setIsFlipped((f) => !f);
if (isLoading) {
return (
<Card>
<CardHeader>
<Skeleton className="h-12 w-3/4" />
</CardHeader>
<CardContent className="space-y-4">
<Skeleton className="h-8 w-1/2" />
<Skeleton className="h-20 w-full" />
<Skeleton className="h-6 w-full" />
</CardContent>
</Card>
);
}
if (!currentWord) {
return (
<Card>
<CardHeader>
<CardTitle className="text-center">No Word Found</CardTitle>
</CardHeader>
<CardContent>
<p className="text-center text-gray-600">
Could not find a Thai word matching your criteria. Try different
selections.
</p>
</CardContent>
</Card>
);
}
console.log({ currentWord });
return (
<div className="relative w-full max-w-2xl mx-auto h-100 perspective">
<button
type="button"
onClick={toggleFlip}
className="absolute z-20 top-2 right-2 p-2 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
title="Flip"
>
<FlipHorizontal2 size={18} />
</button>
<div
className={`relative w-full h-full rounded-xl shadow-xl transition-transform duration-700 ease-in-out transform-style-preserve-3d ${
isFlipped ? "rotate-y-180" : ""
}`}
>
{/* Front */}
<div
id="frontside"
className="absolute inset-0 bg-white dark:bg-slate-800 rounded-xl backface-hidden flex flex-col"
>
<div className="px-6 pt-6 pb-2">
<h3 className="text-center text-lg font-semibold">Current Word</h3>
</div>
<div className="flex-1 px-6 overflow-auto">
<ProminentToneDisplay word={currentWord} />
</div>
<div className="px-6 py-4 flex items-center justify-between">
<ArrowLeft onClick={goPrev} className="cursor-pointer" />
<ArrowRight onClick={goNext} className="cursor-pointer" />
</div>
</div>
{/* Back */}
<div
id="backside"
className="absolute inset-0 bg-slate-50 dark:bg-slate-700 rounded-xl backface-hidden rotate-y-180 flex flex-col"
>
<div className="px-6 pt-6 pb-2">
<h3 className="text-center text-lg font-semibold">Details</h3>
</div>
<div className="flex-1 px-6 py-2 overflow-auto text-sm text-slate-700 dark:text-slate-100">
{/* Placeholder for user-provided data */}
<pre className="whitespace-pre-wrap break-words text-xs opacity-80">
{JSON.stringify(currentWord, null, 2)}
</pre>
</div>
<div className="px-6 py-4 flex items-center justify-center text-xs opacity-60">
Back of card – replace with your data
</div>
</div>
</div>
</div>
);
}
type ToneFormProps = {
isLoading: boolean;
handleFetch: (tones: ToneQuery) => void;
selectedTones: ToneQuery;
setTones: React.Dispatch<React.SetStateAction<ToneQuery>>;
};
function ToneForm({
selectedTones,
setTones,
isLoading,
handleFetch,
}: ToneFormProps) {
const thaiTones = [
{ value: "mid", label: "1 (Mid)" },
{ value: "low", label: "2 (Low)" },
{ value: "falling", label: "3 (Falling)" },
{ value: "high", label: "4 (High)" },
{ value: "rising", label: "5 (Rising)" },
];
const [syllableCount, setSyllableCount] = useState<number>(2);
const decrSyl = useCallback(() => {
setSyllableCount((s) => (s <= 1 ? 1 : s - 1));
}, []);
const incrSyl = useCallback(() => {
setSyllableCount((s) => (s >= 5 ? 5 : s + 1));
}, []);
useEffect(() => {
// Adjust selectedTones array length when syllableCount changes
setTones((prevTones) => {
const newTones = Array(syllableCount).fill(null);
for (let i = 0; i < Math.min(prevTones.length, syllableCount); i++) {
newTones[i] = prevTones[i];
}
return newTones;
});
}, [syllableCount]);
const handleSyllableCountChange = (value: string) => {
const count = parseInt(value, 10);
if (!isNaN(count) && count > 0 && count <= 5) {
// Max 5 syllables for simplicity
setSyllableCount(count);
}
};
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "ArrowUp") {
e.preventDefault();
incrSyl();
} else if (e.key === "ArrowDown") {
e.preventDefault();
decrSyl();
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [incrSyl, decrSyl]);
const handleToneChange = (syllableIndex: number, value: string) => {
const tone = value === "any" ? null : value;
setTones((prevTones) => {
const newTones = [...prevTones];
newTones[syllableIndex] = tone;
return newTones;
});
};
return (
<Card className="mb-6">
<CardHeader>
<CardTitle>Thai Tone Explorer</CardTitle>
<CardDescription>
Select syllable count and tones to find Thai words.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="flex gap-10 justify-center">
{Array.from({ length: syllableCount }).map((_, index) => (
<div key={index} className="w-fit">
<Select
value={selectedTones[index]?.toString() || "any"}
onValueChange={(value) => handleToneChange(index, value)}
>
<SelectTrigger
id={`tone-select-${index}`}
className="w-full md:w-full mt-1"
>
<SelectValue
className="w-full"
placeholder={`Select tone for syllable ${index + 1}`}
/>
</SelectTrigger>
<SelectContent className="lolol md:w-full bg-white w-full">
<SelectItem value="any">Any Tone</SelectItem>
{thaiTones.map((tone) => (
<SelectItem key={tone.value} value={tone.value}>
{tone.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
))}
</div>
</CardContent>
<CardFooter className="justify-center gap-18">
<Button className="" onClick={decrSyl}>
-
</Button>
<Button
onClick={() => handleFetch(selectedTones)}
disabled={isLoading}
className="w-full md:w-auto"
>
{isLoading ? "Searching..." : "Fetch"}
</Button>
<Button className="" onClick={incrSyl}>
+
</Button>
</CardFooter>
</Card>
);
}
|