-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProjectProvider.tsx
More file actions
83 lines (74 loc) · 2.43 KB
/
Copy pathProjectProvider.tsx
File metadata and controls
83 lines (74 loc) · 2.43 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
import React from 'react';
import { ProjectContext } from '@renderer/hooks/useProject';
import { useQueryNoError } from '@renderer/hooks/useQueryNoError';
import { useUser } from '@renderer/hooks/useUser';
import queryOptions from '@renderer/queries/options';
import type { SupportedLanguage } from '@elek-io/core';
export interface TranslateContentProps {
key: string;
// This mirrors the shape of Core's partialTranslatableStringSchema and also accepts the nullable per-language
// content of Value types (string | null), which is treated as missing below.
record: Partial<Record<SupportedLanguage, string | null>>;
}
export function ProjectProvider({
projectId,
children,
}: {
projectId: string;
children: React.ReactNode;
}): React.JSX.Element {
const { userQuery, formatDatetime } = useUser();
const projectQuery = useQueryNoError(
queryOptions.projects.read({ id: projectId })
);
/**
* Returns given TranslatableString in the language of the current user
*
* Used to translate user defined content of Collections and Entries.
*
* If the current users translation is not available,
* it shows it in the default language of the project.
* If this is not available either, show the 'en' value.
* If this is also not available, show the key instead along with a note,
* that a translation should be added.
*/
const translateContent = React.useCallback(
({ key, record }: TranslateContentProps) => {
if (userQuery.isPending === false && userQuery.data !== null) {
const toUserLanguage = record[userQuery.data.language];
if (toUserLanguage !== undefined && toUserLanguage !== null) {
return toUserLanguage;
}
}
if (projectQuery.isPending === false) {
const toProjectsDefaultLanguage =
record[projectQuery.data.settings.language.default];
if (
toProjectsDefaultLanguage !== undefined &&
toProjectsDefaultLanguage !== null
) {
return toProjectsDefaultLanguage;
}
}
const toEnglish = record['en'];
if (toEnglish !== undefined && toEnglish !== null) {
return toEnglish;
}
return key;
},
[userQuery, projectQuery]
);
return (
<ProjectContext.Provider
value={{
projectId,
userQuery,
projectQuery,
formatDatetime,
translateContent,
}}
>
{children}
</ProjectContext.Provider>
);
}