Skip to content

Commit

Permalink
fix: Cleaner and easier to understand logic on updating tags
Browse files Browse the repository at this point in the history
  • Loading branch information
luandro committed Feb 11, 2021
1 parent 2860c6a commit deb874b
Showing 1 changed file with 29 additions and 43 deletions.
72 changes: 29 additions & 43 deletions src/frontend/screens/CategoryChooser.js
Expand Up @@ -71,55 +71,41 @@ const Item = React.memo(
const CategoryChooser = ({ navigation }: { navigation: NavigationProp }) => {
const [{ presets }] = useContext(ConfigContext);
const [{ value: draftValue }, { updateDraft }] = useDraftObservation();

const presetsList = Array.from(presets.values())
// Sort presets by sort property and then by name, then filter only point presets
.sort(presetCompare)
// Only show presets where the geometry property includes "point"
.filter(p => p.geometry.includes("point"));
const handleSelectPreset = (selectedPreset: Preset) => {
if (draftValue && Object.keys(draftValue.tags).length > 0) {
// We're updating an observation
// Tags from current preset
const currentDraftTags = draftValue.tags;
// Tags from previous preset
const prevPresetTags =
(Object.fromEntries(presets)[currentDraftTags.categoryId] || {}).tags ||
{};
// Create object with new tags only
const draftTags = Object.keys(currentDraftTags).reduce(
(previous, current) => {
// Check if tag belongs to previous preset
const tagIsFromPrevPreset =
typeof currentDraftTags[current] !== "undefined" &&
currentDraftTags[current] === prevPresetTags[current];
// If belongs to previous preset, ignore it
if (tagIsFromPrevPreset) return;
// Else, include in new object
return {
...previous,
[current]: currentDraftTags[current],
};
},
{}
);
updateDraft({
tags: {
...selectedPreset.tags,
...draftTags,
categoryId: selectedPreset.id,
},
});
} else {
// Creating a new observation
updateDraft({
tags: {
...selectedPreset.tags,
...(draftValue || {}).tags,
categoryId: selectedPreset.id,
},
});
}
// Tags from current preset
const currentDraftTags = (draftValue || {}).tags || {};
// Tags from previous preset
const prevPresetTags =
(presets.get(currentDraftTags.categoryId) || {}).tags || {};
// Create object with new tags only
const draftTags = Object.keys(currentDraftTags).reduce(
(previous, current) => {
// Check if tag belongs to previous preset
const tagIsFromPrevPreset =
typeof currentDraftTags[current] !== "undefined" &&
currentDraftTags[current] === prevPresetTags[current];
// If belongs to previous preset, ignore it
if (tagIsFromPrevPreset) return previous;
// Else, include in new object
return {
...previous,
[current]: currentDraftTags[current],
};
},
{}
);
updateDraft({
tags: {
...selectedPreset.tags,
...(draftTags || (draftValue || {}).tags),
categoryId: selectedPreset.id,
},
});
navigation.navigate("ObservationEdit");
};

Expand Down

0 comments on commit deb874b

Please sign in to comment.