aboutsummaryrefslogtreecommitdiff
path: root/modern/src/common
diff options
context:
space:
mode:
authorAnton Tananaev <anton@traccar.org>2022-05-08 13:16:57 -0700
committerAnton Tananaev <anton@traccar.org>2022-05-08 13:16:57 -0700
commit2cd374bb9fa941d7e2a6fd8aa5079893a158c98f (patch)
treef4ee48130592fed5de25dce7af4ac0cbeb017680 /modern/src/common
parent2352071211b61c10fa5bf5736baaff7809d18bf0 (diff)
downloadtrackermap-web-2cd374bb9fa941d7e2a6fd8aa5079893a158c98f.tar.gz
trackermap-web-2cd374bb9fa941d7e2a6fd8aa5079893a158c98f.tar.bz2
trackermap-web-2cd374bb9fa941d7e2a6fd8aa5079893a158c98f.zip
Reorganize remaining files
Diffstat (limited to 'modern/src/common')
-rw-r--r--modern/src/common/attributes/AddAttributeDialog.js89
-rw-r--r--modern/src/common/attributes/EditAttributesView.js203
-rw-r--r--modern/src/common/attributes/useCommandAttributes.js11
-rw-r--r--modern/src/common/attributes/useDeviceAttributes.js13
-rw-r--r--modern/src/common/attributes/useGeofenceAttributes.js8
-rw-r--r--modern/src/common/attributes/usePositionAttributes.js21
-rw-r--r--modern/src/common/attributes/useUserAttributes.js48
-rw-r--r--modern/src/common/components/BottomMenu.js2
-rw-r--r--modern/src/common/components/LinkField.js85
-rw-r--r--modern/src/common/components/LocalizationProvider.js165
-rw-r--r--modern/src/common/components/PositionValue.js2
-rw-r--r--modern/src/common/components/RemoveDialog.js2
-rw-r--r--modern/src/common/components/SelectField.js53
13 files changed, 699 insertions, 3 deletions
diff --git a/modern/src/common/attributes/AddAttributeDialog.js b/modern/src/common/attributes/AddAttributeDialog.js
new file mode 100644
index 00000000..37b36c76
--- /dev/null
+++ b/modern/src/common/attributes/AddAttributeDialog.js
@@ -0,0 +1,89 @@
+import React, { useState } from 'react';
+import {
+ Button, Dialog, DialogActions, DialogContent, FormControl, InputLabel, MenuItem, Select, TextField,
+} from '@material-ui/core';
+
+import { Autocomplete, createFilterOptions } from '@material-ui/lab';
+import { useTranslation } from '../components/LocalizationProvider';
+
+const AddAttributeDialog = ({ open, onResult, definitions }) => {
+ const t = useTranslation();
+
+ const filter = createFilterOptions({
+ stringify: (option) => option.name,
+ });
+
+ const options = Object.entries(definitions).map(([key, value]) => ({
+ key,
+ name: value.name,
+ type: value.type,
+ }));
+
+ const [key, setKey] = useState();
+ const [type, setType] = useState('string');
+
+ return (
+ <Dialog open={open} fullWidth maxWidth="xs">
+ <DialogContent>
+ <Autocomplete
+ onChange={(_, option) => {
+ setKey(option && typeof option === 'object' ? option.key : option);
+ if (option && option.type) {
+ setType(option.type);
+ }
+ }}
+ filterOptions={(options, params) => {
+ const filtered = filter(options, params);
+ if (params.inputValue) {
+ filtered.push({
+ key: params.inputValue,
+ name: params.inputValue,
+ });
+ }
+ return filtered;
+ }}
+ options={options}
+ getOptionLabel={(option) => (option && typeof option === 'object' ? option.name : option)}
+ renderOption={(option) => option.name}
+ freeSolo
+ renderInput={(params) => (
+ <TextField {...params} label={t('sharedAttribute')} variant="filled" margin="normal" />
+ )}
+ />
+ <FormControl
+ variant="filled"
+ margin="normal"
+ fullWidth
+ disabled={key in definitions}
+ >
+ <InputLabel>{t('sharedType')}</InputLabel>
+ <Select
+ value={type}
+ onChange={(e) => setType(e.target.value)}
+ >
+ <MenuItem value="string">{t('sharedTypeString')}</MenuItem>
+ <MenuItem value="number">{t('sharedTypeNumber')}</MenuItem>
+ <MenuItem value="boolean">{t('sharedTypeBoolean')}</MenuItem>
+ </Select>
+ </FormControl>
+ </DialogContent>
+ <DialogActions>
+ <Button
+ color="primary"
+ disabled={!key}
+ onClick={() => onResult({ key, type })}
+ >
+ {t('sharedAdd')}
+ </Button>
+ <Button
+ autoFocus
+ onClick={() => onResult(null)}
+ >
+ {t('sharedCancel')}
+ </Button>
+ </DialogActions>
+ </Dialog>
+ );
+};
+
+export default AddAttributeDialog;
diff --git a/modern/src/common/attributes/EditAttributesView.js b/modern/src/common/attributes/EditAttributesView.js
new file mode 100644
index 00000000..4bc34b19
--- /dev/null
+++ b/modern/src/common/attributes/EditAttributesView.js
@@ -0,0 +1,203 @@
+import React, { useState } from 'react';
+
+import {
+ Button, Checkbox, FilledInput, FormControl, FormControlLabel, Grid, IconButton, InputAdornment, InputLabel, makeStyles,
+} from '@material-ui/core';
+import CloseIcon from '@material-ui/icons/Close';
+import AddIcon from '@material-ui/icons/Add';
+import AddAttributeDialog from './AddAttributeDialog';
+import { useTranslation } from '../components/LocalizationProvider';
+import { useAttributePreference } from '../util/preferences';
+import {
+ distanceFromMeters, distanceToMeters, distanceUnitString, speedFromKnots, speedToKnots, speedUnitString, volumeFromLiters, volumeToLiters, volumeUnitString,
+} from '../util/converter';
+
+const useStyles = makeStyles((theme) => ({
+ addButton: {
+ marginTop: theme.spacing(2),
+ marginBottom: theme.spacing(1),
+ },
+ removeButton: {
+ marginRight: theme.spacing(1.5),
+ },
+}));
+
+const EditAttributesView = ({ attributes, setAttributes, definitions }) => {
+ const classes = useStyles();
+ const t = useTranslation();
+
+ const speedUnit = useAttributePreference('speedUnit');
+ const distanceUnit = useAttributePreference('distanceUnit');
+ const volumeUnit = useAttributePreference('volumeUnit');
+
+ const [addDialogShown, setAddDialogShown] = useState(false);
+
+ const updateAttribute = (key, value, type, subtype) => {
+ const updatedAttributes = { ...attributes };
+ switch (subtype) {
+ case 'speed':
+ updatedAttributes[key] = speedToKnots(Number(value), speedUnit);
+ break;
+ case 'distance':
+ updatedAttributes[key] = distanceToMeters(Number(value), distanceUnit);
+ break;
+ case 'volume':
+ updatedAttributes[key] = volumeToLiters(Number(value), volumeUnit);
+ break;
+ default:
+ updatedAttributes[key] = type === 'number' ? Number(value) : value;
+ break;
+ }
+ setAttributes(updatedAttributes);
+ };
+
+ const deleteAttribute = (key) => {
+ const updatedAttributes = { ...attributes };
+ delete updatedAttributes[key];
+ setAttributes(updatedAttributes);
+ };
+
+ const getAttributeName = (key, subtype) => {
+ const definition = definitions[key];
+ const name = definition ? definition.name : key;
+ switch (subtype) {
+ case 'speed':
+ return `${name} (${speedUnitString(speedUnit, t)})`;
+ case 'distance':
+ return `${name} (${distanceUnitString(distanceUnit, t)})`;
+ case 'volume':
+ return `${name} (${volumeUnitString(volumeUnit, t)})`;
+ default:
+ return name;
+ }
+ };
+
+ const getAttributeType = (value) => {
+ if (typeof value === 'number') {
+ return 'number';
+ } if (typeof value === 'boolean') {
+ return 'boolean';
+ }
+ return 'string';
+ };
+
+ const getAttributeSubtype = (key) => {
+ const definition = definitions[key];
+ return definition && definition.subtype;
+ };
+
+ const getDisplayValue = (value, subtype) => {
+ if (value) {
+ switch (subtype) {
+ case 'speed':
+ return speedFromKnots(value, speedUnit);
+ case 'distance':
+ return distanceFromMeters(value, distanceUnit);
+ case 'volume':
+ return volumeFromLiters(value, volumeUnit);
+ default:
+ return value;
+ }
+ }
+ return '';
+ };
+
+ const convertToList = (attributes) => {
+ const booleanList = [];
+ const otherList = [];
+ const excludeAttributes = ['speedUnit', 'distanceUnit', 'volumeUnit', 'timezone'];
+ Object.keys(attributes || []).filter((key) => !excludeAttributes.includes(key)).forEach((key) => {
+ const value = attributes[key];
+ const type = getAttributeType(value);
+ const subtype = getAttributeSubtype(key);
+ if (type === 'boolean') {
+ booleanList.push({
+ key, value, type, subtype,
+ });
+ } else {
+ otherList.push({
+ key, value, type, subtype,
+ });
+ }
+ });
+ return [...otherList, ...booleanList];
+ };
+
+ const handleAddResult = (definition) => {
+ setAddDialogShown(false);
+ if (definition) {
+ switch (definition.type) {
+ case 'number':
+ updateAttribute(definition.key, 0);
+ break;
+ case 'boolean':
+ updateAttribute(definition.key, false);
+ break;
+ default:
+ updateAttribute(definition.key, '');
+ break;
+ }
+ }
+ };
+
+ return (
+ <>
+ {convertToList(attributes).map(({
+ key, value, type, subtype,
+ }) => {
+ if (type === 'boolean') {
+ return (
+ <Grid container direction="row" justifyContent="space-between" key={key}>
+ <FormControlLabel
+ control={(
+ <Checkbox
+ checked={value}
+ onChange={(e) => updateAttribute(key, e.target.checked)}
+ />
+ )}
+ label={getAttributeName(key, subtype)}
+ />
+ <IconButton className={classes.removeButton} onClick={() => deleteAttribute(key)}>
+ <CloseIcon />
+ </IconButton>
+ </Grid>
+ );
+ }
+ return (
+ <FormControl variant="filled" margin="normal" key={key}>
+ <InputLabel>{getAttributeName(key, subtype)}</InputLabel>
+ <FilledInput
+ type={type === 'number' ? 'number' : 'text'}
+ value={getDisplayValue(value, subtype)}
+ onChange={(e) => updateAttribute(key, e.target.value, type, subtype)}
+ endAdornment={(
+ <InputAdornment position="end">
+ <IconButton onClick={() => deleteAttribute(key)}>
+ <CloseIcon />
+ </IconButton>
+ </InputAdornment>
+ )}
+ />
+ </FormControl>
+ );
+ })}
+ <Button
+ size="large"
+ variant="outlined"
+ color="primary"
+ onClick={() => setAddDialogShown(true)}
+ startIcon={<AddIcon />}
+ className={classes.addButton}
+ >
+ {t('sharedAdd')}
+ </Button>
+ <AddAttributeDialog
+ open={addDialogShown}
+ onResult={handleAddResult}
+ definitions={definitions}
+ />
+ </>
+ );
+};
+
+export default EditAttributesView;
diff --git a/modern/src/common/attributes/useCommandAttributes.js b/modern/src/common/attributes/useCommandAttributes.js
new file mode 100644
index 00000000..1212d283
--- /dev/null
+++ b/modern/src/common/attributes/useCommandAttributes.js
@@ -0,0 +1,11 @@
+import { useMemo } from 'react';
+
+export default (t) => useMemo(() => ({
+ custom: [
+ {
+ key: 'data',
+ name: t('commandData'),
+ type: 'string',
+ },
+ ],
+}), [t]);
diff --git a/modern/src/common/attributes/useDeviceAttributes.js b/modern/src/common/attributes/useDeviceAttributes.js
new file mode 100644
index 00000000..8a4d886c
--- /dev/null
+++ b/modern/src/common/attributes/useDeviceAttributes.js
@@ -0,0 +1,13 @@
+import { useMemo } from 'react';
+
+export default (t) => useMemo(() => ({
+ speedLimit: {
+ name: t('attributeSpeedLimit'),
+ type: 'number',
+ subtype: 'speed',
+ },
+ 'report.ignoreOdometer': {
+ name: t('attributeReportIgnoreOdometer'),
+ type: 'boolean',
+ },
+}), [t]);
diff --git a/modern/src/common/attributes/useGeofenceAttributes.js b/modern/src/common/attributes/useGeofenceAttributes.js
new file mode 100644
index 00000000..89908aa5
--- /dev/null
+++ b/modern/src/common/attributes/useGeofenceAttributes.js
@@ -0,0 +1,8 @@
+import { useMemo } from 'react';
+
+export default (t) => useMemo(() => ({
+ speedLimit: {
+ name: t('attributeSpeedLimit'),
+ type: 'string',
+ },
+}), [t]);
diff --git a/modern/src/common/attributes/usePositionAttributes.js b/modern/src/common/attributes/usePositionAttributes.js
new file mode 100644
index 00000000..7b33720a
--- /dev/null
+++ b/modern/src/common/attributes/usePositionAttributes.js
@@ -0,0 +1,21 @@
+import { useMemo } from 'react';
+
+export default (t) => useMemo(() => ({
+ raw: {
+ name: t('positionRaw'),
+ type: 'string',
+ },
+ index: {
+ name: t('positionIndex'),
+ type: 'number',
+ },
+ ignition: {
+ name: t('positionIgnition'),
+ type: 'boolean',
+ },
+ odometer: {
+ name: t('positionOdometer'),
+ type: 'number',
+ dataType: 'distance',
+ },
+}), [t]);
diff --git a/modern/src/common/attributes/useUserAttributes.js b/modern/src/common/attributes/useUserAttributes.js
new file mode 100644
index 00000000..fa6d7d8f
--- /dev/null
+++ b/modern/src/common/attributes/useUserAttributes.js
@@ -0,0 +1,48 @@
+import { useMemo } from 'react';
+
+export default (t) => useMemo(() => ({
+ notificationTokens: {
+ name: t('attributeNotificationTokens'),
+ type: 'string',
+ },
+ /* 'web.liveRouteLength': {
+ name: t('attributeWebLiveRouteLength'),
+ type: 'number',
+ },
+ 'web.selectZoom': {
+ name: t('attributeWebSelectZoom'),
+ type: 'number',
+ },
+ 'web.maxZoom': {
+ name: t('attributeWebMaxZoom'),
+ type: 'number',
+ },
+ 'ui.disableEvents': {
+ name: t('attributeUiDisableEvents'),
+ type: 'boolean',
+ },
+ 'ui.disableVehicleFetures': {
+ name: t('attributeUiDisableVehicleFetures'),
+ type: 'boolean',
+ },
+ 'ui.disableDrivers': {
+ name: t('attributeUiDisableDrivers'),
+ type: 'boolean',
+ },
+ 'ui.disableComputedAttributes': {
+ name: t('attributeUiDisableComputedAttributes'),
+ type: 'boolean',
+ },
+ 'ui.disableCalendars': {
+ name: t('attributeUiDisableCalendars'),
+ type: 'boolean',
+ },
+ 'ui.disableMaintenance': {
+ name: t('attributeUiDisableMaintenance'),
+ type: 'boolean',
+ },
+ 'ui.hidePositionAttributes': {
+ name: t('attributeUiHidePositionAttributes'),
+ type: 'string',
+ }, */
+}), [t]);
diff --git a/modern/src/common/components/BottomMenu.js b/modern/src/common/components/BottomMenu.js
index d26b4ae2..3865de29 100644
--- a/modern/src/common/components/BottomMenu.js
+++ b/modern/src/common/components/BottomMenu.js
@@ -12,7 +12,7 @@ import PersonIcon from '@material-ui/icons/Person';
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import { sessionActions } from '../../store';
-import { useTranslation } from '../../LocalizationProvider';
+import { useTranslation } from './LocalizationProvider';
import { useReadonly } from '../util/permissions';
const BottomMenu = () => {
diff --git a/modern/src/common/components/LinkField.js b/modern/src/common/components/LinkField.js
new file mode 100644
index 00000000..e11438df
--- /dev/null
+++ b/modern/src/common/components/LinkField.js
@@ -0,0 +1,85 @@
+import {
+ FormControl, InputLabel, MenuItem, Select,
+} from '@material-ui/core';
+import React, { useState } from 'react';
+import { useEffectAsync } from '../../reactHelper';
+
+const LinkField = ({
+ margin,
+ variant,
+ label,
+ endpointAll,
+ endpointLinked,
+ baseId,
+ keyBase,
+ keyLink,
+ keyGetter = (item) => item.id,
+ titleGetter = (item) => item.name,
+}) => {
+ const [items, setItems] = useState();
+ const [linked, setLinked] = useState();
+
+ useEffectAsync(async () => {
+ const response = await fetch(endpointAll);
+ if (response.ok) {
+ setItems(await response.json());
+ }
+ }, []);
+
+ useEffectAsync(async () => {
+ const response = await fetch(endpointLinked);
+ if (response.ok) {
+ const data = await response.json();
+ setLinked(data.map((it) => it.id));
+ }
+ }, []);
+
+ const createBody = (linkId) => {
+ const body = {};
+ body[keyBase] = baseId;
+ body[keyLink] = linkId;
+ return body;
+ };
+
+ const onChange = async (event) => {
+ const oldValue = linked;
+ const newValue = event.target.value;
+ const results = [];
+ newValue.filter((it) => !oldValue.includes(it)).forEach((added) => {
+ results.push(fetch('/api/permissions', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(createBody(added)),
+ }));
+ });
+ oldValue.filter((it) => !newValue.includes(it)).forEach((removed) => {
+ results.push(fetch('/api/permissions', {
+ method: 'DELETE',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(createBody(removed)),
+ }));
+ });
+ await Promise.all(results);
+ setLinked(newValue);
+ };
+
+ if (items && linked) {
+ return (
+ <FormControl margin={margin} variant={variant}>
+ <InputLabel>{label}</InputLabel>
+ <Select
+ multiple
+ value={linked}
+ onChange={onChange}
+ >
+ {items.map((item) => (
+ <MenuItem key={keyGetter(item)} value={keyGetter(item)}>{titleGetter(item)}</MenuItem>
+ ))}
+ </Select>
+ </FormControl>
+ );
+ }
+ return null;
+};
+
+export default LinkField;
diff --git a/modern/src/common/components/LocalizationProvider.js b/modern/src/common/components/LocalizationProvider.js
new file mode 100644
index 00000000..0df242dc
--- /dev/null
+++ b/modern/src/common/components/LocalizationProvider.js
@@ -0,0 +1,165 @@
+import React, { createContext, useContext, useMemo } from 'react';
+import usePersistedState from '../util/usePersistedState';
+
+import af from '../../../../web/l10n/af.json';
+import ar from '../../../../web/l10n/ar.json';
+import az from '../../../../web/l10n/az.json';
+import bg from '../../../../web/l10n/bg.json';
+import bn from '../../../../web/l10n/bn.json';
+import cs from '../../../../web/l10n/cs.json';
+import da from '../../../../web/l10n/da.json';
+import de from '../../../../web/l10n/de.json';
+import el from '../../../../web/l10n/el.json';
+import en from '../../../../web/l10n/en.json';
+import es from '../../../../web/l10n/es.json';
+import fa from '../../../../web/l10n/fa.json';
+import fi from '../../../../web/l10n/fi.json';
+import fr from '../../../../web/l10n/fr.json';
+import he from '../../../../web/l10n/he.json';
+import hi from '../../../../web/l10n/hi.json';
+import hr from '../../../../web/l10n/hr.json';
+import hu from '../../../../web/l10n/hu.json';
+import id from '../../../../web/l10n/id.json';
+import it from '../../../../web/l10n/it.json';
+import ja from '../../../../web/l10n/ja.json';
+import ka from '../../../../web/l10n/ka.json';
+import kk from '../../../../web/l10n/kk.json';
+import km from '../../../../web/l10n/km.json';
+import ko from '../../../../web/l10n/ko.json';
+import lo from '../../../../web/l10n/lo.json';
+import lt from '../../../../web/l10n/lt.json';
+import lv from '../../../../web/l10n/lv.json';
+import ml from '../../../../web/l10n/ml.json';
+import mn from '../../../../web/l10n/mn.json';
+import ms from '../../../../web/l10n/ms.json';
+import nb from '../../../../web/l10n/nb.json';
+import ne from '../../../../web/l10n/ne.json';
+import nl from '../../../../web/l10n/nl.json';
+import nn from '../../../../web/l10n/nn.json';
+import pl from '../../../../web/l10n/pl.json';
+import pt from '../../../../web/l10n/pt.json';
+import ptBR from '../../../../web/l10n/pt_BR.json';
+import ro from '../../../../web/l10n/ro.json';
+import ru from '../../../../web/l10n/ru.json';
+import si from '../../../../web/l10n/si.json';
+import sk from '../../../../web/l10n/sk.json';
+import sl from '../../../../web/l10n/sl.json';
+import sq from '../../../../web/l10n/sq.json';
+import sr from '../../../../web/l10n/sr.json';
+import sv from '../../../../web/l10n/sv.json';
+import ta from '../../../../web/l10n/ta.json';
+import th from '../../../../web/l10n/th.json';
+import tr from '../../../../web/l10n/tr.json';
+import uk from '../../../../web/l10n/uk.json';
+import uz from '../../../../web/l10n/uz.json';
+import vi from '../../../../web/l10n/vi.json';
+import zh from '../../../../web/l10n/zh.json';
+import zhTW from '../../../../web/l10n/zh_TW.json';
+
+const languages = {
+ af: { data: af, name: 'Afrikaans' },
+ ar: { data: ar, name: 'العربية' },
+ az: { data: az, name: 'Azərbaycanca' },
+ bg: { data: bg, name: 'Български' },
+ bn: { data: bn, name: 'বাংলা' },
+ cs: { data: cs, name: 'Čeština' },
+ de: { data: de, name: 'Deutsch' },
+ da: { data: da, name: 'Dansk' },
+ el: { data: el, name: 'Ελληνικά' },
+ en: { data: en, name: 'English' },
+ es: { data: es, name: 'Español' },
+ fa: { data: fa, name: 'فارسی' },
+ fi: { data: fi, name: 'Suomi' },
+ fr: { data: fr, name: 'Français' },
+ he: { data: he, name: 'עברית' },
+ hi: { data: hi, name: 'हिन्दी' },
+ hr: { data: hr, name: 'Hrvatski' },
+ hu: { data: hu, name: 'Magyar' },
+ id: { data: id, name: 'Bahasa Indonesia' },
+ it: { data: it, name: 'Italiano' },
+ ja: { data: ja, name: '日本語' },
+ ka: { data: ka, name: 'ქართული' },
+ kk: { data: kk, name: 'Қазақша' },
+ ko: { data: ko, name: '한국어' },
+ km: { data: km, name: 'ភាសាខ្មែរ' },
+ lo: { data: lo, name: 'ລາວ' },
+ lt: { data: lt, name: 'Lietuvių' },
+ lv: { data: lv, name: 'Latviešu' },
+ ml: { data: ml, name: 'മലയാളം' },
+ mn: { data: mn, name: 'Монгол хэл' },
+ ms: { data: ms, name: 'بهاس ملايو' },
+ nb: { data: nb, name: 'Norsk bokmål' },
+ ne: { data: ne, name: 'नेपाली' },
+ nl: { data: nl, name: 'Nederlands' },
+ nn: { data: nn, name: 'Norsk nynorsk' },
+ pl: { data: pl, name: 'Polski' },
+ pt: { data: pt, name: 'Português' },
+ ptBR: { data: ptBR, name: 'Português (Brasil)' },
+ ro: { data: ro, name: 'Română' },
+ ru: { data: ru, name: 'Русский' },
+ si: { data: si, name: 'සිංහල' },
+ sk: { data: sk, name: 'Slovenčina' },
+ sl: { data: sl, name: 'Slovenščina' },
+ sq: { data: sq, name: 'Shqipëria' },
+ sr: { data: sr, name: 'Srpski' },
+ sv: { data: sv, name: 'Svenska' },
+ ta: { data: ta, name: 'தமிழ்' },
+ th: { data: th, name: 'ไทย' },
+ tr: { data: tr, name: 'Türkçe' },
+ uk: { data: uk, name: 'Українська' },
+ uz: { data: uz, name: 'Oʻzbekcha' },
+ vi: { data: vi, name: 'Tiếng Việt' },
+ zh: { data: zh, name: '中文' },
+ zhTW: { data: zhTW, name: '中文 (Taiwan)' },
+};
+
+const getDefaultLanguage = () => {
+ const browserLanguages = window.navigator.languages ? window.navigator.languages.slice() : [];
+ const browserLanguage = window.navigator.userLanguage || window.navigator.language;
+ browserLanguages.push(browserLanguage);
+ browserLanguages.push(browserLanguage.substring(0, 2));
+
+ for (let i = 0; i < browserLanguages.length; i += 1) {
+ let language = browserLanguages[i].replace('-', '');
+ if (language in languages) {
+ return language;
+ }
+ if (language.length > 2) {
+ language = language.substring(0, 2);
+ if (language in languages) {
+ return language;
+ }
+ }
+ }
+ return 'en';
+};
+
+const LocalizationContext = createContext({
+ languages,
+ language: 'en',
+ setLanguage: () => {},
+});
+
+export const LocalizationProvider = ({ children }) => {
+ const [language, setLanguage] = usePersistedState('language', getDefaultLanguage());
+
+ return (
+ <LocalizationContext.Provider value={{ languages, language, setLanguage }}>
+ {children}
+ </LocalizationContext.Provider>
+ );
+};
+
+export const useLocalization = () => useContext(LocalizationContext);
+
+export const useTranslation = () => {
+ const context = useContext(LocalizationContext);
+ const { data } = context.languages[context.language];
+ return useMemo(() => (key) => data[key], [data]);
+};
+
+export const useTranslationKeys = (predicate) => {
+ const context = useContext(LocalizationContext);
+ const { data } = context.languages[context.language];
+ return Object.keys(data).filter(predicate);
+};
diff --git a/modern/src/common/components/PositionValue.js b/modern/src/common/components/PositionValue.js
index b160be34..17e7b1d2 100644
--- a/modern/src/common/components/PositionValue.js
+++ b/modern/src/common/components/PositionValue.js
@@ -5,7 +5,7 @@ import {
formatAlarm, formatBoolean, formatCoordinate, formatCourse, formatDistance, formatNumber, formatPercentage, formatSpeed, formatTime,
} from '../util/formatter';
import { useAttributePreference, usePreference } from '../util/preferences';
-import { useTranslation } from '../../LocalizationProvider';
+import { useTranslation } from './LocalizationProvider';
import { useAdministrator } from '../util/permissions';
const PositionValue = ({ position, property, attribute }) => {
diff --git a/modern/src/common/components/RemoveDialog.js b/modern/src/common/components/RemoveDialog.js
index 1b75e926..6d191d6a 100644
--- a/modern/src/common/components/RemoveDialog.js
+++ b/modern/src/common/components/RemoveDialog.js
@@ -4,7 +4,7 @@ import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
-import { useTranslation } from '../../LocalizationProvider';
+import { useTranslation } from './LocalizationProvider';
const RemoveDialog = ({
open, endpoint, itemId, onResult,
diff --git a/modern/src/common/components/SelectField.js b/modern/src/common/components/SelectField.js
new file mode 100644
index 00000000..98473b16
--- /dev/null
+++ b/modern/src/common/components/SelectField.js
@@ -0,0 +1,53 @@
+import {
+ FormControl, InputLabel, MenuItem, Select,
+} from '@material-ui/core';
+import React, { useState } from 'react';
+import { useEffectAsync } from '../../reactHelper';
+
+const SelectField = ({
+ margin,
+ variant,
+ label,
+ multiple,
+ value,
+ emptyValue = 0,
+ emptyTitle = '\u00a0',
+ onChange,
+ endpoint,
+ data,
+ keyGetter = (item) => item.id,
+ titleGetter = (item) => item.name,
+}) => {
+ const [items, setItems] = useState(data);
+
+ useEffectAsync(async () => {
+ if (endpoint) {
+ const response = await fetch(endpoint);
+ if (response.ok) {
+ setItems(await response.json());
+ }
+ }
+ }, []);
+
+ if (items) {
+ return (
+ <FormControl margin={margin} variant={variant}>
+ <InputLabel>{label}</InputLabel>
+ <Select
+ multiple={multiple}
+ value={value}
+ onChange={onChange}
+ >
+ {!multiple && emptyValue !== null
+ && <MenuItem value={emptyValue}>{emptyTitle}</MenuItem>}
+ {items.map((item) => (
+ <MenuItem key={keyGetter(item)} value={keyGetter(item)}>{titleGetter(item)}</MenuItem>
+ ))}
+ </Select>
+ </FormControl>
+ );
+ }
+ return null;
+};
+
+export default SelectField;