Repository navigation
Expand file tree
/
Copy pathcommit-translation.tsx
More file actions
237 lines (218 loc) · 8.42 KB
/
Copy pathcommit-translation.tsx
File metadata and controls
237 lines (218 loc) · 8.42 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
import { useHttp, usePage } from '@inertiajs/react';
import { Languages } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import CommitTranslationController from '@/actions/App/Http/Controllers/CommitTranslationController';
import { useCommitNotFound } from '@/hooks/use-deleted-resources';
import { signIn } from '@/lib/auth';
import { changesSince, readAt } from '@/lib/commit-changes';
import { coalesce, commitChannel, listen } from '@/lib/realtime';
import type { Commit, CommitTranslation } from '@/types';
export function useCommitTranslation(commit: Commit) {
const { auth, now: serverNow } = usePage().props;
const commitNotFound = useCommitNotFound();
const bodyRef = useRef<HTMLDivElement>(null);
const [bodyHeight, setBodyHeight] = useState<number>();
const [generated, setGenerated] = useState<{
body: string;
translation: CommitTranslation | null;
} | null>(null);
const [display, setDisplay] = useState<'original' | 'translated' | null>(
null,
);
// The reader's language, saved or from the browser, which a change saved elsewhere replaces on every page.
const language =
auth.translationLanguage ?? commit.translation?.language ?? null;
const translation =
generated?.body === commit.body &&
generated.translation?.language === language
? generated.translation
: commit.translation;
const request = useHttp<
{ language: string },
{ translation: CommitTranslation | null }
>({ language: language ?? 'en' });
const translated =
(display === 'translated' ||
(display === null && auth.automaticTranslation)) &&
translation?.translated;
const isApproved = commit.status === 'approved';
const readSince = useRef(Math.min(serverNow - 5_000, readAt()));
const isTranslated = Boolean(translation?.translated);
const isOtherLanguage =
translation !== null &&
translation !== undefined &&
translation.language !== language;
// A translation finished for someone else is read again in this reader's language; showing the original stays.
useEffect(() => {
if (!isApproved || language === null) {
return;
}
const controller = new AbortController();
const body = commit.body;
let needsRead = isOtherLanguage;
const read = coalesce(async () => {
const since = readAt();
const response = await fetch(
CommitTranslationController.show.url(commit.id, {
query: { language },
}),
{
headers: { Accept: 'application/json' },
cache: 'no-store',
signal: controller.signal,
},
);
if (response.ok) {
const fresh = (await response.json()) as {
translation: CommitTranslation | null;
};
readSince.current = since;
needsRead = false;
setGenerated({ body, translation: fresh.translation });
}
}, 500);
const refresh = () => {
needsRead = true;
read.request();
};
// A translation finished while not listening is learnt by asking, with every commit shown, what was
// translated since: joining does while none is shown yet, and reads again only those.
const catchUp = async () => {
if (needsRead) {
read.request();
return;
}
if (isTranslated) {
return;
}
const since = readSince.current;
const checkedAt = readAt();
const change = await changesSince(commit.id, since);
if (change === null || change.translated) {
refresh();
} else {
readSince.current = checkedAt;
}
};
const stop = listen(
commitChannel(commit.id),
{ translation: refresh },
() => void catchUp(),
);
// Shown in another language than the reader's: read again in theirs, keeping Show original if chosen.
if (isOtherLanguage) {
refresh();
}
return () => {
stop();
read.cancel();
controller.abort();
};
}, [
commit.id,
commit.body,
isApproved,
language,
isTranslated,
isOtherLanguage,
]);
const translate = async () => {
setBodyHeight(bodyRef.current?.getBoundingClientRect().height);
if (translation?.translated) {
setDisplay('translated');
return;
}
if (!auth.user) {
signIn();
return;
}
request.transform(() => ({ language: language ?? 'en' }));
let isNotFound = false;
let failureMessage = 'Could not translate this commit. Try again.';
try {
const response = await request.submit(
CommitTranslationController.store(commit.id),
{
onHttpException: (response) => {
isNotFound = commitNotFound(commit.id, response);
if (
response.status === 503 &&
response.headers['content-type']?.includes(
'application/json',
)
) {
const { message } = JSON.parse(response.data) as {
message: string;
};
failureMessage = message;
}
},
},
);
setGenerated({
body: commit.body,
translation: response.translation,
});
setDisplay('translated');
} catch {
if (!isNotFound) {
toast.error(failureMessage);
}
}
};
return {
bodyRef,
bodyStyle: { minHeight: bodyHeight },
segments: translated ? translated.body_segments : commit.body_segments,
previewSegments: translated
? translated.preview_segments
: commit.preview_segments,
notice: translation?.available ? (
<div className="flex min-h-5 min-w-0 items-center gap-1 text-xs text-muted-foreground">
{translated && (
<>
<span
className="truncate"
title={`Translated from ${translation.source_name}`}
>
Translated from {translation.source_name}
</span>
<span aria-hidden>·</span>
<button
type="button"
onClick={() => {
setBodyHeight(
bodyRef.current?.getBoundingClientRect()
.height,
);
setDisplay('original');
}}
className="shrink-0 text-primary hover:underline"
>
Show original
</button>
</>
)}
</div>
) : null,
button: translation?.available ? (
<button
type="button"
onClick={() => void translate()}
disabled={request.processing || Boolean(translated)}
aria-label={
request.processing
? 'Translating commit'
: 'Translate commit'
}
aria-busy={request.processing}
className="flex items-center gap-1.5 rounded-md px-2 py-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50 sm:min-w-24"
data-test="translate-commit"
>
<Languages className="size-4" aria-hidden />
<span className="sr-only sm:not-sr-only">Translate</span>
</button>
) : null,
};
}