Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Labels Step 2 #1120

Merged
merged 49 commits into from
Jul 20, 2024
Merged
Show file tree
Hide file tree
Changes from 44 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
1b57f5e
show customized modes (used dummy data for now)
jiji14 Dec 1, 2023
cad2d7c
fix prettier issu
jiji14 Dec 1, 2023
74e2dfe
fetch post/mode
jiji14 Dec 4, 2023
0402a34
use displayErrorMsg
jiji14 Dec 4, 2023
09b56ee
Done with fetching data to server
jiji14 Dec 7, 2023
a3cb1f2
update mode - old mode and new mode
jiji14 Dec 8, 2023
abc7f8a
Change modes type to string array and call it when modal opens
jiji14 Dec 11, 2023
cb1c491
add comments
jiji14 Dec 11, 2023
0a7a4ba
change mode text in a desired format (ex) my_car => My Car
jiji14 Dec 12, 2023
8ba3fb6
add default mode & custom mode label
jiji14 Dec 13, 2023
aa18e98
noted that getModes & updateMode need to be tested after e2e testing …
jiji14 Dec 14, 2023
7548de7
reuse existing common function and delete the original function
jiji14 Dec 18, 2023
01c1afe
use dynamic color
jiji14 Dec 18, 2023
b5a63be
change logic for showing custom modes before 'other' option
jiji14 Dec 18, 2023
f64d719
change function names more descriptive
jiji14 Dec 18, 2023
14c4438
delete unnecessary variable and change variable names more intuitive
jiji14 Dec 18, 2023
447e7e2
add new translation entry
jiji14 Dec 18, 2023
0509d5e
Fetch custom modes on initial rendering to prevent unnecessary api calls
jiji14 Dec 27, 2023
23f4758
add 'custom modes' tab in Profile
jiji14 Dec 27, 2023
0ef37b4
Move customModes state to AppContext to be shared between the 'Label'…
jiji14 Dec 27, 2023
de9008f
separate the component for clean code
jiji14 Dec 27, 2023
07f4534
Add insert user custom mode feature
jiji14 Dec 29, 2023
189f79d
check if inputType is 'MODE' for custom mode label
jiji14 Jan 3, 2024
643ae90
Modify the mode functions to encompass all types of labels (purpose, …
jiji14 Jan 5, 2024
315561e
Merge branch 'customize-modes' into customize-modes-step2
jiji14 Jan 8, 2024
939480f
fix merge conflict related to LabelTabContext
jiji14 Jan 9, 2024
bf3754d
Done with "manage custom labels" in profile setting tab
jiji14 Jan 9, 2024
01a3729
fix radio button issue when 'other' option is selected
jiji14 Jan 9, 2024
8cec495
change variable names for better understanding
jiji14 Jan 9, 2024
606816b
update radio button comment
jiji14 Jan 9, 2024
2d7352b
combine replaced_mode and mode
jiji14 Jan 11, 2024
32e5708
Merge branch 'customize-modes' into customize-modes-step2
jiji14 Jan 11, 2024
5f87ab3
update merge changes
jiji14 Jan 11, 2024
d02d7aa
combine mode and replaced_mode for Label Setting
jiji14 Jan 11, 2024
f5f5551
error handling for empty label array
jiji14 Jan 12, 2024
4192269
add skipped test functions
jiji14 Jan 12, 2024
0e0569e
Change list title "edit custom labels" -> "manage custom labels""
jiji14 Jan 12, 2024
7eb31dd
Merge branch 'service_rewrite_2023' into customize-modes-step2
jiji14 Jan 12, 2024
2a1a12c
Merge branch 'customize-modes' of https://github.com/jiji14/e-mission…
JGreenlee Feb 9, 2024
0c87797
bump 'react-native-paper' to ^5.11.0
JGreenlee Feb 9, 2024
7e09923
Merge branch 'master' into customize-modes-step2
jiji14 Feb 9, 2024
ae66eff
fix label context issue after merge
jiji14 Feb 15, 2024
3453205
ignore commHelper from coverage report
jiji14 Feb 15, 2024
26264ce
delete not operator
jiji14 Feb 16, 2024
cba51b8
add comment why we need to ingnore commHelper in coverage report
jiji14 Feb 17, 2024
96386a3
delete duplicated code
jiji14 Feb 17, 2024
15c994a
show customLabel setting conditionally
jiji14 Feb 17, 2024
45bfc2d
Merge branch 'master' into customize-modes-step2
JGreenlee Mar 25, 2024
52b0fb9
Merge branch 'master' of https://github.com/e-mission/e-mission-phone…
JGreenlee Jul 12, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ module.exports = {
moduleDirectories: ["node_modules", "src"],
globals: {"__DEV__": false},
collectCoverage: true,
coveragePathIgnorePatterns: ['www/js/services/commHelper.ts']
jiji14 marked this conversation as resolved.
Show resolved Hide resolved
};
4 changes: 4 additions & 0 deletions www/__tests__/commHelper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,8 @@ it('fetches text from a URL and caches it so the next call is faster', async ()
* - updateUser
* - getUser
* - putOne
* - getUserCustomLabels
* - insertUserCustomLabel
* - updateUserCustomLabel
* - deleteUserCustomLabel
*/
8 changes: 6 additions & 2 deletions www/i18n/en.json
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added Spanish translations in e-mission/e-mission-translate@e658a1a. Still need to add Lao translations @Abby-Wheelis

Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
"trip-confirm": {
"services-please-fill-in": "Please fill in the {{text}} not listed.",
"services-cancel": "Cancel",
"services-save": "Save"
"services-save": "Save",
"custom-mode": "Custom Mode",
"custom-purpose": "Custom Purpose",
"custom-labels": "Custom Labels"
},

"control": {
Expand Down Expand Up @@ -47,7 +50,8 @@
"reminders-time-of-day": "Time of Day for Reminders ({{time}})",
"upcoming-notifications": "Upcoming Notifications",
"dummy-notification": "Dummy Notification in 5 Seconds",
"log-out": "Log Out"
"log-out": "Log Out",
"manage-custom-labels": "Manage Custom Labels"
},

"general-settings": {
Expand Down
15 changes: 15 additions & 0 deletions www/js/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { initPushNotify } from './splash/pushNotifySettings';
import { initStoreDeviceSettings } from './splash/storeDeviceSettings';
import { initRemoteNotifyHandler } from './splash/remoteNotifyHandler';
import { withErrorBoundary } from './plugin/ErrorBoundary';
import { getUserCustomLabels } from './services/commHelper';
import { initCustomDatasetHelper } from './metrics/customMetricsHelper';

const defaultRoutes = (t) => [
Expand All @@ -42,6 +43,16 @@ const defaultRoutes = (t) => [
];

export const AppContext = createContext<any>({});
const CUSTOM_LABEL_KEYS_IN_DATABASE = ['mode', 'purpose'];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JGreenlee don't we need this for replaced mode as well? Or is the expectation that the replaced mode will also share the custom labels from the regular mode?

type CustomLabelMap = {
[k: string]: string[];
};

const scenes = {
label: withErrorBoundary(LabelTab),
metrics: withErrorBoundary(MetricsTab),
control: withErrorBoundary(ProfileSettings),
};
jiji14 marked this conversation as resolved.
Show resolved Hide resolved

const scenes = {
label: withErrorBoundary(LabelTab),
Expand All @@ -54,6 +65,7 @@ const App = () => {
// will remain null while the onboarding state is still being determined
const [onboardingState, setOnboardingState] = useState<OnboardingState | null>(null);
const [permissionsPopupVis, setPermissionsPopupVis] = useState(false);
const [customLabelMap, setCustomLabelMap] = useState<CustomLabelMap>({});
const appConfig = useAppConfig();
const permissionStatus = usePermissionStatus();
const { colors } = useTheme();
Expand All @@ -79,6 +91,7 @@ const App = () => {
initPushNotify();
initStoreDeviceSettings();
initRemoteNotifyHandler();
getUserCustomLabels(CUSTOM_LABEL_KEYS_IN_DATABASE).then((res) => setCustomLabelMap(res));
initCustomDatasetHelper(appConfig);
}, [appConfig]);

Expand All @@ -90,6 +103,8 @@ const App = () => {
permissionStatus,
permissionsPopupVis,
setPermissionsPopupVis,
customLabelMap,
setCustomLabelMap,
};

console.debug('onboardingState in App', onboardingState);
Expand Down
166 changes: 166 additions & 0 deletions www/js/control/CustomLabelSettingRow.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import React, { useState, useContext } from 'react';
import SettingRow from './SettingRow';
import {
Modal,
View,
Text,
TouchableOpacity,
StyleSheet,
useWindowDimensions,
ScrollView,
} from 'react-native';
import { Icon, TextInput, Dialog, Button, useTheme, SegmentedButtons } from 'react-native-paper';
import { AppContext } from '../App';
import { useTranslation } from 'react-i18next';
import { deleteUserCustomLabel, insertUserCustomLabel } from '../services/commHelper';
import { displayErrorMsg, logDebug } from '../plugin/logger';
import { labelKeyToReadable, readableLabelToKey } from '../survey/multilabel/confirmHelper';

const CustomLabelSettingRow = () => {
const [isCustomLabelModalOpen, setIsCustomLabelModalOpen] = useState(false);
const { customLabelMap, setCustomLabelMap } = useContext(AppContext);
const [isAddLabelOn, setIsAddLabelOn] = useState(false);
const [text, setText] = useState('');
const [key, setKey] = useState('mode');

const { t } = useTranslation(); //this accesses the translations
const { colors } = useTheme(); // use this to get the theme colors instead of hardcoded #hex colors
const { height } = useWindowDimensions();

const labelKeysButton = [
{
value: 'mode',
label: t('diary.mode'),
},
{
value: 'purpose',
label: t('diary.purpose'),
},
];

const onDeleteLabel = async (label) => {
const processedLabel = readableLabelToKey(label);
try {
const res = await deleteUserCustomLabel(key, processedLabel);
if (res) {
setCustomLabelMap({
...customLabelMap,
[key]: res['label'],
});
logDebug(`Successfuly deleted custom ${key}, ${JSON.stringify(res)}`);
}
} catch (e) {
displayErrorMsg(e, 'Delete Mode Error');
}
};

const onSaveLabel = async () => {
const processedLabel = readableLabelToKey(text);
if (customLabelMap[key]?.length > 0 && customLabelMap[key].indexOf(processedLabel) > -1) {
return;
}
try {
const res = await insertUserCustomLabel(key, processedLabel);
if (res) {
setText('');
setCustomLabelMap({
...customLabelMap,
[key]: res['label'],
});
setIsAddLabelOn(false);
logDebug(`Successfuly inserted custom ${key}, ${JSON.stringify(res)}`);
}
} catch (e) {
displayErrorMsg(e, 'Create Mode Error');
}
};

return (
<>
<SettingRow
textKey="control.manage-custom-labels"
iconName="label-multiple"
action={() => setIsCustomLabelModalOpen(true)}></SettingRow>
<Modal
visible={isCustomLabelModalOpen}
onDismiss={() => setIsCustomLabelModalOpen(false)}
transparent={true}>
<Dialog visible={isCustomLabelModalOpen} onDismiss={() => setIsCustomLabelModalOpen(false)}>
<Dialog.Title>
<Text>{t('trip-confirm.custom-labels')}</Text>
<TouchableOpacity style={styles.plusIconWrapper} onPress={() => setIsAddLabelOn(true)}>
<Icon source="plus-circle" size={24} />
</TouchableOpacity>
</Dialog.Title>
<Dialog.Content>
<SegmentedButtons
style={{ marginBottom: 10 }}
value={key}
onValueChange={setKey}
buttons={labelKeysButton}
/>
{isAddLabelOn && (
<>
<TextInput
label={t('trip-confirm.services-please-fill-in', {
text: key,
})}
value={text}
onChangeText={setText}
maxLength={25}
style={{ marginTop: 10 }}
/>
<View style={styles.saveButtonWrapper}>
<Button onPress={() => setIsAddLabelOn(false)}>
{t('trip-confirm.services-cancel')}
</Button>
<Button onPress={onSaveLabel}>{t('trip-confirm.services-save')}</Button>
</View>
</>
)}
<ScrollView contentContainerStyle={{ height: height / 2 }}>
{customLabelMap[key]?.length > 0 &&
customLabelMap[key].map((label, idx) => {
return (
<View
key={label + idx}
style={[styles.itemWrapper, { borderBottomColor: colors.outline }]}>
<Text>{labelKeyToReadable(label)}</Text>
<TouchableOpacity onPress={() => onDeleteLabel(label)}>
<Icon source="trash-can" size={20} />
</TouchableOpacity>
</View>
);
})}
</ScrollView>
</Dialog.Content>
<Dialog.Actions>
<Button onPress={() => setIsCustomLabelModalOpen(false)}>
{t('trip-confirm.services-cancel')}
</Button>
</Dialog.Actions>
</Dialog>
</Modal>
</>
);
};

const styles = StyleSheet.create({
itemWrapper: {
flexDirection: 'row',
justifyContent: 'space-between',
paddingVertical: 16,
borderBottomWidth: 1,
},
saveButtonWrapper: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-end',
},
plusIconWrapper: {
position: 'absolute',
right: 0,
},
});

export default CustomLabelSettingRow;
2 changes: 2 additions & 0 deletions www/js/control/ProfileSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { storageClear } from '../plugin/storage';
import { getAppVersion } from '../plugin/clientStats';
import { getConsentDocument } from '../splash/startprefs';
import { displayError, displayErrorMsg, logDebug, logWarn } from '../plugin/logger';
import CustomLabelSettingRow from './CustomLabelSettingRow';
import { fetchOPCode, getSettings } from '../services/controlHelper';
import {
updateScheduledNotifs,
Expand Down Expand Up @@ -434,6 +435,7 @@ const ProfileSettings = () => {
desc={authSettings.opcode}
descStyle={settingStyles.monoDesc}></SettingRow>
<DemographicsSettingRow></DemographicsSettingRow>
<CustomLabelSettingRow />
jiji14 marked this conversation as resolved.
Show resolved Hide resolved
<SettingRow
textKey="control.view-privacy"
iconName="eye"
Expand Down
1 change: 0 additions & 1 deletion www/js/diary/LabelTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ const LabelTab = () => {
if (!appConfig) return;
showPlaces = appConfig.survey_info?.buttons?.['place-notes'];
getLabelOptions(appConfig).then((labelOptions) => setLabelOptions(labelOptions));

// we will show filters if 'additions' are not configured
// https://github.com/e-mission/e-mission-docs/issues/894
if (appConfig.survey_info?.buttons == undefined) {
Expand Down
5 changes: 4 additions & 1 deletion www/js/diary/LabelTabContext.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createContext } from 'react';
import { Dispatch, SetStateAction, createContext } from 'react';
import { TimelineEntry, UserInputEntry } from '../types/diaryTypes';
import { LabelOption, LabelOptions, MultilabelKey } from '../types/labelTypes';
import { EnketoUserInputEntry } from '../survey/enketo/enketoHelper';
Expand All @@ -20,6 +20,9 @@ export type TimelineLabelMap = {
export type TimelineNotesMap = {
[k: string]: UserInputEntry[];
};
export type CustomLabelMap = {
[k: string]: string[];
};

type ContextProps = {
labelOptions: LabelOptions | null;
Expand Down
74 changes: 74 additions & 0 deletions www/js/services/commHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,77 @@ export function putOne(key, data) {
throw error;
});
}

export function getUserCustomLabels(keys) {
return new Promise<any>((rs, rj) => {
window['cordova'].plugins.BEMServerComm.postUserPersonalData(
'/customlabel/get',
'keys',
keys,
rs,
rj,
);
}).catch((error) => {
error = 'While getting labels, ' + error;
throw error;
});
}

export function insertUserCustomLabel(key, newLabel) {
const insertedLabel = {
key: key,
label: newLabel,
};
return new Promise((rs, rj) => {
window['cordova'].plugins.BEMServerComm.postUserPersonalData(
'/customlabel/insert',
'inserted_label',
insertedLabel,
rs,
rj,
);
}).catch((error) => {
error = `While inserting one ${key}, ${error}`;
throw error;
});
}

export function updateUserCustomLabel(key, oldLabel, newLabel, isNewLabelMustAdded) {
const updatedLabel = {
key: key,
old_label: oldLabel,
new_label: newLabel,
is_new_label_must_added: isNewLabelMustAdded,
};
return new Promise<any>((rs, rj) => {
window['cordova'].plugins.BEMServerComm.postUserPersonalData(
'/customlabel/update',
'updated_label',
updatedLabel,
rs,
rj,
);
}).catch((error) => {
error = `While updating one ${key}, ${error}`;
throw error;
});
}

export function deleteUserCustomLabel(key, newLabel) {
const deletedLabel = {
key: key,
label: newLabel,
};
return new Promise((rs, rj) => {
window['cordova'].plugins.BEMServerComm.postUserPersonalData(
'/customlabel/delete',
'deleted_label',
deletedLabel,
rs,
rj,
);
}).catch((error) => {
error = `While deleting one ${key}, ${error}`;
throw error;
});
}
Loading
Loading