@rimori/react-client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/.prettierignore +35 -0
  2. package/LICENSE +201 -0
  3. package/README copy.md +1216 -0
  4. package/README.md +1 -0
  5. package/dist/components/MarkdownEditor.d.ts +8 -0
  6. package/dist/components/MarkdownEditor.js +48 -0
  7. package/dist/components/Spinner.d.ts +8 -0
  8. package/dist/components/Spinner.js +4 -0
  9. package/dist/components/ai/Assistant.d.ts +9 -0
  10. package/dist/components/ai/Assistant.js +58 -0
  11. package/dist/components/ai/Avatar.d.ts +14 -0
  12. package/dist/components/ai/Avatar.js +59 -0
  13. package/dist/components/ai/EmbeddedAssistent/AudioInputField.d.ts +7 -0
  14. package/dist/components/ai/EmbeddedAssistent/AudioInputField.js +37 -0
  15. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.d.ts +8 -0
  16. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +79 -0
  17. package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.d.ts +19 -0
  18. package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.js +91 -0
  19. package/dist/components/ai/EmbeddedAssistent/TTS/Player.d.ts +27 -0
  20. package/dist/components/ai/EmbeddedAssistent/TTS/Player.js +185 -0
  21. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.d.ts +11 -0
  22. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.js +95 -0
  23. package/dist/components/ai/utils.d.ts +6 -0
  24. package/dist/components/ai/utils.js +13 -0
  25. package/dist/components/audio/Playbutton.d.ts +15 -0
  26. package/dist/components/audio/Playbutton.js +80 -0
  27. package/dist/components/components/ContextMenu.d.ts +10 -0
  28. package/dist/components/components/ContextMenu.js +135 -0
  29. package/dist/hooks/I18nHooks.d.ts +11 -0
  30. package/dist/hooks/I18nHooks.js +25 -0
  31. package/dist/hooks/UseChatHook.d.ts +10 -0
  32. package/dist/hooks/UseChatHook.js +29 -0
  33. package/dist/providers/PluginProvider.d.ts +11 -0
  34. package/dist/providers/PluginProvider.js +142 -0
  35. package/dist/react-client/plugin/ThemeSetter.d.ts +2 -0
  36. package/dist/react-client/plugin/ThemeSetter.js +19 -0
  37. package/dist/react-client/src/components/ContextMenu.d.ts +10 -0
  38. package/dist/react-client/src/components/ContextMenu.js +135 -0
  39. package/dist/react-client/src/components/MarkdownEditor.d.ts +8 -0
  40. package/dist/react-client/src/components/MarkdownEditor.js +48 -0
  41. package/dist/react-client/src/components/Spinner.d.ts +8 -0
  42. package/dist/react-client/src/components/Spinner.js +4 -0
  43. package/dist/react-client/src/components/ai/Assistant.d.ts +9 -0
  44. package/dist/react-client/src/components/ai/Assistant.js +58 -0
  45. package/dist/react-client/src/components/ai/Avatar.d.ts +14 -0
  46. package/dist/react-client/src/components/ai/Avatar.js +59 -0
  47. package/dist/react-client/src/components/ai/EmbeddedAssistent/AudioInputField.d.ts +7 -0
  48. package/dist/react-client/src/components/ai/EmbeddedAssistent/AudioInputField.js +37 -0
  49. package/dist/react-client/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.d.ts +8 -0
  50. package/dist/react-client/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +79 -0
  51. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/MessageSender.d.ts +19 -0
  52. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/MessageSender.js +91 -0
  53. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/Player.d.ts +27 -0
  54. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/Player.js +185 -0
  55. package/dist/react-client/src/components/ai/EmbeddedAssistent/VoiceRecoder.d.ts +11 -0
  56. package/dist/react-client/src/components/ai/EmbeddedAssistent/VoiceRecoder.js +95 -0
  57. package/dist/react-client/src/components/ai/utils.d.ts +6 -0
  58. package/dist/react-client/src/components/ai/utils.js +13 -0
  59. package/dist/react-client/src/components/audio/Playbutton.d.ts +15 -0
  60. package/dist/react-client/src/components/audio/Playbutton.js +82 -0
  61. package/dist/react-client/src/components/components/ContextMenu.d.ts +10 -0
  62. package/dist/react-client/src/components/components/ContextMenu.js +135 -0
  63. package/dist/react-client/src/hooks/I18nHooks.d.ts +11 -0
  64. package/dist/react-client/src/hooks/I18nHooks.js +25 -0
  65. package/dist/react-client/src/hooks/UseChatHook.d.ts +10 -0
  66. package/dist/react-client/src/hooks/UseChatHook.js +29 -0
  67. package/dist/react-client/src/plugin/ThemeSetter.d.ts +2 -0
  68. package/dist/react-client/src/plugin/ThemeSetter.js +19 -0
  69. package/dist/react-client/src/providers/PluginProvider.d.ts +12 -0
  70. package/dist/react-client/src/providers/PluginProvider.js +142 -0
  71. package/dist/react-client/src/utils/FullscreenUtils.d.ts +2 -0
  72. package/dist/react-client/src/utils/FullscreenUtils.js +23 -0
  73. package/dist/react-client/src/utils/PluginUtils.d.ts +2 -0
  74. package/dist/react-client/src/utils/PluginUtils.js +23 -0
  75. package/dist/rimori-client/src/cli/types/DatabaseTypes.d.ts +103 -0
  76. package/dist/rimori-client/src/cli/types/DatabaseTypes.js +2 -0
  77. package/dist/rimori-client/src/controller/AIController.d.ts +15 -0
  78. package/dist/rimori-client/src/controller/AIController.js +255 -0
  79. package/dist/rimori-client/src/controller/AccomplishmentController.d.ts +38 -0
  80. package/dist/rimori-client/src/controller/AccomplishmentController.js +112 -0
  81. package/dist/rimori-client/src/controller/AudioController.d.ts +37 -0
  82. package/dist/rimori-client/src/controller/AudioController.js +68 -0
  83. package/dist/rimori-client/src/controller/ExerciseController.d.ts +54 -0
  84. package/dist/rimori-client/src/controller/ExerciseController.js +74 -0
  85. package/dist/rimori-client/src/controller/ObjectController.d.ts +42 -0
  86. package/dist/rimori-client/src/controller/ObjectController.js +76 -0
  87. package/dist/rimori-client/src/controller/SettingsController.d.ts +79 -0
  88. package/dist/rimori-client/src/controller/SettingsController.js +118 -0
  89. package/dist/rimori-client/src/controller/SharedContentController.d.ts +106 -0
  90. package/dist/rimori-client/src/controller/SharedContentController.js +285 -0
  91. package/dist/rimori-client/src/controller/TranslationController.d.ts +38 -0
  92. package/dist/rimori-client/src/controller/TranslationController.js +106 -0
  93. package/dist/rimori-client/src/controller/VoiceController.d.ts +9 -0
  94. package/dist/rimori-client/src/controller/VoiceController.js +37 -0
  95. package/dist/rimori-client/src/fromRimori/EventBus.d.ts +101 -0
  96. package/dist/rimori-client/src/fromRimori/EventBus.js +263 -0
  97. package/dist/rimori-client/src/fromRimori/PluginTypes.d.ts +174 -0
  98. package/dist/rimori-client/src/fromRimori/PluginTypes.js +1 -0
  99. package/dist/rimori-client/src/index.d.ts +11 -0
  100. package/dist/rimori-client/src/index.js +10 -0
  101. package/dist/rimori-client/src/plugin/CommunicationHandler.d.ts +48 -0
  102. package/dist/rimori-client/src/plugin/CommunicationHandler.js +234 -0
  103. package/dist/rimori-client/src/plugin/Logger.d.ts +73 -0
  104. package/dist/rimori-client/src/plugin/Logger.js +308 -0
  105. package/dist/rimori-client/src/plugin/RimoriClient.d.ts +258 -0
  106. package/dist/rimori-client/src/plugin/RimoriClient.js +375 -0
  107. package/dist/rimori-client/src/plugin/StandaloneClient.d.ts +17 -0
  108. package/dist/rimori-client/src/plugin/StandaloneClient.js +115 -0
  109. package/dist/rimori-client/src/utils/difficultyConverter.d.ts +4 -0
  110. package/dist/rimori-client/src/utils/difficultyConverter.js +10 -0
  111. package/dist/rimori-client/src/utils/endpoint.d.ts +2 -0
  112. package/dist/rimori-client/src/utils/endpoint.js +2 -0
  113. package/dist/style.css +110 -0
  114. package/dist/style.css.map +1 -0
  115. package/dist/utils/PluginUtils.d.ts +2 -0
  116. package/dist/utils/PluginUtils.js +23 -0
  117. package/eslint.config.js +53 -0
  118. package/index.ts +6 -0
  119. package/package.json +47 -0
  120. package/prettier.config.js +8 -0
  121. package/src/components/ContextMenu.tsx +177 -0
  122. package/src/components/MarkdownEditor.tsx +144 -0
  123. package/src/components/Spinner.tsx +29 -0
  124. package/src/components/ai/Assistant.tsx +96 -0
  125. package/src/components/ai/Avatar.tsx +99 -0
  126. package/src/components/ai/EmbeddedAssistent/AudioInputField.tsx +73 -0
  127. package/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.tsx +107 -0
  128. package/src/components/ai/EmbeddedAssistent/TTS/MessageSender.ts +96 -0
  129. package/src/components/ai/EmbeddedAssistent/TTS/Player.ts +197 -0
  130. package/src/components/ai/EmbeddedAssistent/VoiceRecoder.tsx +129 -0
  131. package/src/components/ai/utils.ts +21 -0
  132. package/src/components/audio/Playbutton.tsx +126 -0
  133. package/src/hooks/I18nHooks.ts +33 -0
  134. package/src/hooks/UseChatHook.ts +38 -0
  135. package/src/plugin/ThemeSetter.ts +23 -0
  136. package/src/providers/PluginProvider.tsx +197 -0
  137. package/src/style.scss +136 -0
  138. package/src/utils/FullscreenUtils.ts +22 -0
  139. package/tsconfig.json +23 -0
@@ -0,0 +1,197 @@
1
+ export class ChunkedAudioPlayer {
2
+ private audioContext!: AudioContext;
3
+ private chunkQueue: ArrayBuffer[] = [];
4
+ private isPlaying = false;
5
+ private analyser!: AnalyserNode;
6
+ private dataArray!: Uint8Array<ArrayBuffer>;
7
+ private shouldMonitorLoudness = true;
8
+ private isMonitoring = false;
9
+ private handle = 0;
10
+ private volume = 1.0;
11
+ private loudnessCallback: (value: number) => void = () => {};
12
+ private currentIndex = 0;
13
+ private startedPlaying = false;
14
+ private onEndOfSpeech: () => void = () => {};
15
+
16
+ constructor() {
17
+ this.init();
18
+ }
19
+
20
+ private init(): void {
21
+ this.audioContext = new AudioContext();
22
+ this.analyser = this.audioContext.createAnalyser();
23
+ this.analyser.fftSize = 256; // Set the FFT size (smaller values provide faster updates, larger ones give better resolution)
24
+ const bufferLength = this.analyser.frequencyBinCount;
25
+ this.dataArray = new Uint8Array(bufferLength); // Array to hold frequency data
26
+ }
27
+
28
+ public setOnLoudnessChange(callback: (value: number) => void) {
29
+ this.loudnessCallback = callback;
30
+ }
31
+
32
+ public setVolume(volume: number) {
33
+ this.volume = volume;
34
+ }
35
+
36
+ public async addChunk(chunk: ArrayBuffer, position: number): Promise<void> {
37
+ console.log('Adding chunk', position, chunk);
38
+ this.chunkQueue[position] = chunk;
39
+ // console.log("received chunk", {
40
+ // chunkQueue: this.chunkQueue.length,
41
+ // isPlaying: this.isPlaying,
42
+ // })
43
+
44
+ if (position === 0 && !this.startedPlaying) {
45
+ this.startedPlaying = true;
46
+ this.playChunks();
47
+ }
48
+ }
49
+
50
+ private playChunks(): void {
51
+ // console.log({ isPlaying: this.isPlaying });
52
+ if (this.isPlaying) return;
53
+ if (!this.chunkQueue[this.currentIndex]) {
54
+ // wait until the correct chunk arrives
55
+ setTimeout(() => this.playChunks(), 10);
56
+ }
57
+ this.isPlaying = true;
58
+
59
+ this.playChunk(this.chunkQueue[this.currentIndex]).then(() => {
60
+ this.isPlaying = false;
61
+ this.currentIndex++;
62
+ if (this.chunkQueue[this.currentIndex]) {
63
+ this.shouldMonitorLoudness = true;
64
+ this.playChunks();
65
+ } else {
66
+ // console.log('Playback finished', { currentIndex: this.currentIndex, chunkQueue: this.chunkQueue });
67
+ setTimeout(() => {
68
+ // console.log('Check again if really playback finished', { currentIndex: this.currentIndex, chunkQueue: this.chunkQueue });
69
+ if (this.chunkQueue.length > this.currentIndex) {
70
+ this.playChunks();
71
+ } else {
72
+ this.startedPlaying = false;
73
+ this.shouldMonitorLoudness = false;
74
+ }
75
+ }, 1000);
76
+ }
77
+ });
78
+ }
79
+
80
+ public stopPlayback(): void {
81
+ // console.log('Stopping playback');
82
+ // Implement logic to stop the current playback
83
+ this.isPlaying = false;
84
+ this.chunkQueue = [];
85
+ this.startedPlaying = false;
86
+ this.shouldMonitorLoudness = false;
87
+ cancelAnimationFrame(this.handle);
88
+ }
89
+
90
+ private playChunk(chunk: ArrayBuffer): Promise<void> {
91
+ // console.log({queue: this.chunkQueue})
92
+ if (!chunk) {
93
+ return Promise.resolve();
94
+ }
95
+
96
+ // console.log('Playing chunk', chunk);
97
+ return new Promise((resolve) => {
98
+ const source = this.audioContext.createBufferSource();
99
+ this.audioContext.decodeAudioData(chunk.slice(0)).then((audioBuffer) => {
100
+ source.buffer = audioBuffer;
101
+
102
+ // Create a GainNode for volume control
103
+ const gainNode = this.audioContext.createGain();
104
+ gainNode.gain.value = this.volume;
105
+
106
+ // Connect the source to the GainNode, then to the analyser node, then to the destination (speakers)
107
+ source.connect(gainNode);
108
+ gainNode.connect(this.analyser);
109
+ this.analyser.connect(this.audioContext.destination);
110
+
111
+ source.start(0);
112
+ // console.log('Playing chunk', this.currentIndex);
113
+ gainNode.gain.value = this.volume;
114
+ source.onended = () => {
115
+ // console.log('Chunk ended');
116
+ resolve();
117
+ };
118
+
119
+ // Start monitoring loudness only once
120
+ if (!this.isMonitoring) {
121
+ this.isMonitoring = true;
122
+ this.shouldMonitorLoudness = true;
123
+ this.monitorLoudness();
124
+ }
125
+ });
126
+ });
127
+ }
128
+
129
+ async playAgain(): Promise<void> {
130
+ console.log('Playing again');
131
+ if (this.chunkQueue.length > 0 && !this.isPlaying) {
132
+ this.playChunks();
133
+ }
134
+ }
135
+
136
+ private monitorLoudness(): void {
137
+ // Stop monitoring when the flag is false
138
+ if (!this.shouldMonitorLoudness) {
139
+ // console.log('Loudness monitoring stopped.');
140
+ cancelAnimationFrame(this.handle);
141
+ this.loudnessCallback(0);
142
+ this.onEndOfSpeech();
143
+ return;
144
+ }
145
+
146
+ // Get the time domain data from the analyser (this is a snapshot of the waveform)
147
+ this.analyser.getByteTimeDomainData(this.dataArray);
148
+
149
+ // Calculate the RMS (root mean square) of the waveform values to get the perceived loudness
150
+ let sum = 0;
151
+ for (let i = 0; i < this.dataArray.length; i++) {
152
+ const value = this.dataArray[i] / 128.0 - 1.0; // Normalize between -1 and 1
153
+ sum += value * value;
154
+ }
155
+
156
+ const rms = Math.sqrt(sum / this.dataArray.length);
157
+
158
+ // Handle the case where RMS is 0 to avoid log10(0)
159
+ if (rms === 0) {
160
+ // console.log('Current loudness: Silent');
161
+ } else {
162
+ let loudnessInDb = 20 * Math.log10(rms); // Convert to dB
163
+ // console.log('Current loudness:' + loudnessInDb);
164
+ const minDb = -57;
165
+ const maxDb = -15;
166
+
167
+ if (loudnessInDb < minDb) {
168
+ loudnessInDb = minDb;
169
+ }
170
+ if (loudnessInDb > maxDb) {
171
+ loudnessInDb = maxDb;
172
+ }
173
+
174
+ const loudnessScale = ((loudnessInDb - minDb) / (maxDb - minDb)) * 100;
175
+ // console.log("root:corrent loudness", loudnessScale);
176
+
177
+ this.loudnessCallback(loudnessScale);
178
+ }
179
+
180
+ // Call this method again at regular intervals if you want continuous loudness monitoring
181
+ this.handle = requestAnimationFrame(() => this.monitorLoudness());
182
+ }
183
+ public reset() {
184
+ // console.log('Resetting player');
185
+ this.stopPlayback();
186
+ this.currentIndex = 0;
187
+ this.shouldMonitorLoudness = true;
188
+ //reset to the beginning when the class gets initialized
189
+ this.isMonitoring = false;
190
+ this.isPlaying = false;
191
+ this.init();
192
+ }
193
+
194
+ public setOnEndOfSpeech(callback: () => void) {
195
+ this.onEndOfSpeech = callback;
196
+ }
197
+ }
@@ -0,0 +1,129 @@
1
+ import { useRimori } from '../../../providers/PluginProvider';
2
+ import { FaMicrophone, FaSpinner } from 'react-icons/fa6';
3
+ import { AudioController } from '@rimori/client';
4
+ import { useState, useRef, forwardRef, useImperativeHandle, useEffect } from 'react';
5
+
6
+ interface Props {
7
+ iconSize?: string;
8
+ className?: string;
9
+ disabled?: boolean;
10
+ loading?: boolean;
11
+ enablePushToTalk?: boolean;
12
+ onRecordingStatusChange: (running: boolean) => void;
13
+ onVoiceRecorded: (message: string) => void;
14
+ }
15
+
16
+ export const VoiceRecorder = forwardRef(
17
+ (
18
+ {
19
+ onVoiceRecorded,
20
+ iconSize,
21
+ className,
22
+ disabled,
23
+ loading,
24
+ onRecordingStatusChange,
25
+ enablePushToTalk = false,
26
+ }: Props,
27
+ ref,
28
+ ) => {
29
+ const [isRecording, setIsRecording] = useState(false);
30
+ const [internalIsProcessing, setInternalIsProcessing] = useState(false);
31
+ const audioControllerRef = useRef<AudioController | null>(null);
32
+ const { ai, plugin } = useRimori();
33
+
34
+ // Ref for latest onVoiceRecorded callback
35
+ const onVoiceRecordedRef = useRef(onVoiceRecorded);
36
+ useEffect(() => {
37
+ onVoiceRecordedRef.current = onVoiceRecorded;
38
+ }, [onVoiceRecorded]);
39
+
40
+ const startRecording = async () => {
41
+ try {
42
+ if (!audioControllerRef.current) {
43
+ audioControllerRef.current = new AudioController(plugin.pluginId);
44
+ }
45
+
46
+ await audioControllerRef.current.startRecording();
47
+ setIsRecording(true);
48
+ onRecordingStatusChange(true);
49
+ } catch (error) {
50
+ console.error('Failed to start recording:', error);
51
+ // Handle permission denied or other errors
52
+ }
53
+ };
54
+
55
+ const stopRecording = async () => {
56
+ try {
57
+ if (audioControllerRef.current && isRecording) {
58
+ const audioResult = await audioControllerRef.current.stopRecording();
59
+ // console.log("audioResult: ", audioResult);
60
+
61
+ setInternalIsProcessing(true);
62
+
63
+ // Play the recorded audio from the Blob
64
+ // const blobUrl = URL.createObjectURL(audioResult.recording);
65
+ // const audioRef = new Audio(blobUrl);
66
+ // audioRef.onended = () => URL.revokeObjectURL(blobUrl);
67
+ // audioRef.play().catch((e) => console.error('Playback error:', e));
68
+
69
+ // console.log("audioBlob: ", audioResult.recording);
70
+ const text = await ai.getTextFromVoice(audioResult.recording);
71
+ // console.log("stt result", text);
72
+ // throw new Error("test");
73
+ setInternalIsProcessing(false);
74
+ onVoiceRecordedRef.current(text);
75
+ }
76
+ } catch (error) {
77
+ console.error('Failed to stop recording:', error);
78
+ } finally {
79
+ setIsRecording(false);
80
+ onRecordingStatusChange(false);
81
+ }
82
+ };
83
+
84
+ useImperativeHandle(ref, () => ({
85
+ startRecording,
86
+ stopRecording,
87
+ }));
88
+
89
+ // push to talk feature
90
+ const spacePressedRef = useRef(false);
91
+
92
+ useEffect(() => {
93
+ if (!enablePushToTalk) return;
94
+
95
+ const handleKeyDown = async (event: KeyboardEvent) => {
96
+ if (event.code === 'Space' && !spacePressedRef.current) {
97
+ spacePressedRef.current = true;
98
+ await startRecording();
99
+ }
100
+ };
101
+ const handleKeyUp = (event: KeyboardEvent) => {
102
+ if (event.code === 'Space' && spacePressedRef.current) {
103
+ spacePressedRef.current = false;
104
+ stopRecording();
105
+ }
106
+ };
107
+ window.addEventListener('keydown', handleKeyDown);
108
+ window.addEventListener('keyup', handleKeyUp);
109
+ return () => {
110
+ window.removeEventListener('keydown', handleKeyDown);
111
+ window.removeEventListener('keyup', handleKeyUp);
112
+ };
113
+ }, [enablePushToTalk]);
114
+
115
+ return (
116
+ <button
117
+ className={'flex flex-row justify-center items-center rounded-full mx-auto disabled:opacity-50 ' + className}
118
+ onClick={isRecording ? stopRecording : startRecording}
119
+ disabled={disabled || loading || internalIsProcessing}
120
+ >
121
+ {loading || internalIsProcessing ? (
122
+ <FaSpinner className="animate-spin" />
123
+ ) : (
124
+ <FaMicrophone size={iconSize} className={isRecording ? 'text-red-600' : ''} />
125
+ )}
126
+ </button>
127
+ );
128
+ },
129
+ );
@@ -0,0 +1,21 @@
1
+ export interface FirstMessages {
2
+ instructions?: string;
3
+ userMessage?: string;
4
+ assistantMessage?: string;
5
+ }
6
+
7
+ export function getFirstMessages(instructions: FirstMessages): any[] {
8
+ const messages = [];
9
+
10
+ if (instructions.instructions) {
11
+ messages.push({ id: '1', role: 'system', content: instructions.instructions });
12
+ }
13
+ if (instructions.userMessage) {
14
+ messages.push({ id: '2', role: 'user', content: instructions.userMessage });
15
+ }
16
+ if (instructions.assistantMessage) {
17
+ messages.push({ id: '3', role: 'assistant', content: instructions.assistantMessage });
18
+ }
19
+
20
+ return messages;
21
+ }
@@ -0,0 +1,126 @@
1
+ import React, { useState, useEffect } from 'react';
2
+ import { FaPlayCircle, FaStopCircle } from 'react-icons/fa';
3
+ import { useRimori } from '../../providers/PluginProvider';
4
+ import { Spinner } from '../Spinner';
5
+ import { EventBus } from '@rimori/client';
6
+
7
+ type AudioPlayerProps = {
8
+ text: string;
9
+ voice?: string;
10
+ language?: string;
11
+ hide?: boolean;
12
+ playOnMount?: boolean;
13
+ initialSpeed?: number;
14
+ enableSpeedAdjustment?: boolean;
15
+ playListenerEvent?: string;
16
+ };
17
+
18
+ export const AudioPlayOptions = [0.8, 0.9, 1.0, 1.1, 1.2, 1.5];
19
+ export type AudioPlayOptionType = 0.8 | 0.9 | 1.0 | 1.1 | 1.2 | 1.5;
20
+
21
+ let isFetchingAudio = false;
22
+
23
+ export const AudioPlayer: React.FC<AudioPlayerProps> = ({
24
+ text,
25
+ voice,
26
+ language,
27
+ hide,
28
+ playListenerEvent,
29
+ initialSpeed = 1.0,
30
+ playOnMount = false,
31
+ enableSpeedAdjustment = false,
32
+ }) => {
33
+ const [audioUrl, setAudioUrl] = useState<string | null>(null);
34
+ const [speed, setSpeed] = useState(initialSpeed);
35
+ const [isPlaying, setIsPlaying] = useState(false);
36
+ const [isLoading, setIsLoading] = useState(false);
37
+ const { ai } = useRimori();
38
+
39
+ useEffect(() => {
40
+ if (audioUrl) setAudioUrl(null);
41
+ return () => {
42
+ if (audioUrl) URL.revokeObjectURL(audioUrl);
43
+ };
44
+ }, [text]);
45
+
46
+ // Function to generate audio from text using API
47
+ const generateAudio = async () => {
48
+ setIsLoading(true);
49
+
50
+ const blob = await ai.getVoice(text, voice || (language ? 'aws_default' : 'openai_alloy'), 1, language);
51
+ setAudioUrl(URL.createObjectURL(blob));
52
+ setIsLoading(false);
53
+ };
54
+
55
+ // Effect to play audio when audioUrl changes and play state is true
56
+ useEffect(() => {
57
+ if (!audioUrl || !isPlaying) return;
58
+ const audio = new Audio(audioUrl);
59
+ audio.playbackRate = speed;
60
+ audio
61
+ .play()
62
+ .then(() => {
63
+ audio.onended = () => {
64
+ setIsPlaying(false);
65
+ isFetchingAudio = false;
66
+ };
67
+ })
68
+ .catch((e) => {
69
+ console.warn('Error playing audio:', e);
70
+ setIsPlaying(false);
71
+ });
72
+
73
+ return () => {
74
+ audio.pause();
75
+ };
76
+ }, [audioUrl, isPlaying, speed]);
77
+
78
+ const togglePlayback = () => {
79
+ if (!isPlaying && !audioUrl) {
80
+ generateAudio().then(() => setIsPlaying(true));
81
+ } else {
82
+ setIsPlaying((prev) => !prev);
83
+ }
84
+ };
85
+
86
+ useEffect(() => {
87
+ if (!playListenerEvent) return;
88
+ EventBus.on(playListenerEvent, () => togglePlayback());
89
+ }, [playListenerEvent]);
90
+
91
+ useEffect(() => {
92
+ if (!playOnMount || isFetchingAudio) return;
93
+ isFetchingAudio = true;
94
+ // console.log("playOnMount", playOnMount);
95
+ togglePlayback();
96
+ }, [playOnMount]);
97
+
98
+ return (
99
+ <div className="group relative">
100
+ <div className="flex flex-row items-end">
101
+ {!hide && (
102
+ <button className="text-gray-500" onClick={togglePlayback} disabled={isLoading}>
103
+ {isLoading ? <Spinner /> : isPlaying ? <FaStopCircle size={'25px'} /> : <FaPlayCircle size={'25px'} />}
104
+ </button>
105
+ )}
106
+ {enableSpeedAdjustment && (
107
+ <div className="ml-1 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-row text-sm text-gray-500">
108
+ <span className="pr-1">Speed: </span>
109
+ <select
110
+ value={speed}
111
+ className="appearance-none cursor-pointer pr-0 p-0 rounded shadow leading-tight focus:outline-none focus:bg-gray-800 focus:ring bg-transparent border-0"
112
+ onChange={(e) => setSpeed(parseFloat(e.target.value))}
113
+ disabled={isLoading}
114
+ >
115
+ {AudioPlayOptions.map((s) => (
116
+ <option key={s} value={s}>
117
+ {s}
118
+ </option>
119
+ ))}
120
+ </select>
121
+ </div>
122
+ )}
123
+ </div>
124
+ </div>
125
+ );
126
+ };
@@ -0,0 +1,33 @@
1
+ import { TOptions } from '@rimori/client';
2
+ import { useEffect, useState } from 'react';
3
+ import { Translator } from '@rimori/client';
4
+ import { useRimori } from '../providers/PluginProvider';
5
+
6
+ type TranslatorFn = (key: string, options?: TOptions) => string;
7
+
8
+ /**
9
+ * Custom useTranslation hook that provides a translation function and indicates readiness
10
+ * @returns An object containing the translation function (`t`) and a boolean (`ready`) indicating if the translator is initialized.
11
+ */
12
+ export function useTranslation(): { t: TranslatorFn; ready: boolean } {
13
+ const { plugin } = useRimori();
14
+ const [translatorInstance, setTranslatorInstance] = useState<Translator | null>(null);
15
+
16
+ useEffect(() => {
17
+ void plugin.getTranslator().then(setTranslatorInstance);
18
+ }, [plugin]);
19
+
20
+ const safeT = (key: string, options?: TOptions): string => {
21
+ // return zero-width space if translator is not initialized to keep text space occupied
22
+ if (!translatorInstance) return '\u200B'; // zero-width space
23
+
24
+ const result = translatorInstance.t(key, options);
25
+ if (!result) {
26
+ console.error(`Translation key not found: ${key}`);
27
+ return '\u200B'; // zero-width space
28
+ }
29
+ return result;
30
+ };
31
+
32
+ return { t: safeT, ready: translatorInstance !== null };
33
+ }
@@ -0,0 +1,38 @@
1
+ import React from 'react';
2
+ import { Tool } from '@rimori/client';
3
+ import { useRimori } from '../providers/PluginProvider';
4
+ import { Message, ToolInvocation } from '@rimori/client';
5
+
6
+ export function useChat(tools?: Tool[]) {
7
+ const [messages, setMessages] = React.useState<Message[]>([]);
8
+ const [isLoading, setIsLoading] = React.useState(false);
9
+ const { ai } = useRimori();
10
+
11
+ const append = (appendMessages: Message[]) => {
12
+ const allMessages = [...messages, ...appendMessages];
13
+ setMessages(allMessages);
14
+ ai.getSteamedText(
15
+ allMessages,
16
+ (id, message, finished: boolean, toolInvocations?: ToolInvocation[]) => {
17
+ const lastMessage = messages[messages.length - 1];
18
+ setIsLoading(!finished);
19
+
20
+ if (lastMessage?.id === id) {
21
+ lastMessage.content = message;
22
+ setMessages([...messages, lastMessage]);
23
+ } else {
24
+ setMessages([...allMessages, { id, role: 'assistant', content: message, toolCalls: toolInvocations }]);
25
+ }
26
+ },
27
+ tools,
28
+ );
29
+ };
30
+
31
+ return {
32
+ messages,
33
+ append,
34
+ isLoading,
35
+ setMessages,
36
+ lastMessage: messages[messages.length - 1] as Message | undefined,
37
+ };
38
+ }
@@ -0,0 +1,23 @@
1
+ export function setTheme(theme?: string | null) {
2
+ document.documentElement.classList.add('dark:text-gray-200');
3
+
4
+ if (isDarkTheme(theme)) {
5
+ document.documentElement.setAttribute('data-theme', 'dark');
6
+ document.documentElement.classList.add('dark', 'dark:bg-gray-950');
7
+ document.documentElement.style.background = 'hsl(var(--background))';
8
+ }
9
+ }
10
+
11
+ export function isDarkTheme(theme?: string | null): boolean {
12
+ // If no theme provided, try to get from URL as fallback (for standalone mode)
13
+ if (!theme) {
14
+ const urlParams = new URLSearchParams(window.location.search);
15
+ theme = urlParams.get('theme');
16
+ }
17
+
18
+ if (!theme || theme === 'system') {
19
+ return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
20
+ }
21
+
22
+ return theme === 'dark';
23
+ }