1
0
Fork 0
mirror of https://github.com/mealie-recipes/mealie.git synced 2025-08-05 13:35:23 +02:00

Refactor/composables-folder (#787)

* move api clients and rename

* organize recipes composables

* rewrite useRecipeContext

* refactor(frontend): ♻️ abstract common ingredient functionality.

* feat(frontend):  add scale, and back to recipe button + hide ingredients if none

* update regex to mach 11. instead of just 1.

* minor UX improvements

Co-authored-by: Hayden K <hay-kot@pm.me>
This commit is contained in:
Hayden 2021-11-06 11:28:47 -08:00 committed by GitHub
parent 095d3bda3f
commit 788e176b16
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
68 changed files with 330 additions and 245 deletions

View file

@ -0,0 +1,7 @@
export { useFraction } from "./use-fraction";
export { useRecipe } from "./use-recipe";
export { useFoods } from "./use-recipe-foods";
export { useUnits } from "./use-recipe-units";
export { useRecipes, recentRecipes, allRecipes, useLazyRecipes, useSorter } from "./use-recipes";
export { useTags, useCategories, allCategories, allTags } from "./use-tags-categories";
export { parseIngredientText } from "./use-recipe-ingredients";

View file

@ -0,0 +1,76 @@
/* frac.js (C) 2012-present SheetJS -- http://sheetjs.com */
/* https://developer.aliyun.com/mirror/npm/package/frac/v/0.3.0 Apache license */
function frac(x: number, D: number, mixed: Boolean) {
let n1 = Math.floor(x);
let d1 = 1;
let n2 = n1 + 1;
let d2 = 1;
if (x !== n1)
while (d1 <= D && d2 <= D) {
const m = (n1 + n2) / (d1 + d2);
if (x === m) {
if (d1 + d2 <= D) {
d1 += d2;
n1 += n2;
d2 = D + 1;
} else if (d1 > d2) d2 = D + 1;
else d1 = D + 1;
break;
} else if (x < m) {
n2 = n1 + n2;
d2 = d1 + d2;
} else {
n1 = n1 + n2;
d1 = d1 + d2;
}
}
if (d1 > D) {
d1 = d2;
n1 = n2;
}
if (!mixed) return [0, n1, d1];
const q = Math.floor(n1 / d1);
return [q, n1 - q * d1, d1];
}
function cont(x: number, D: number, mixed: Boolean) {
const sgn = x < 0 ? -1 : 1;
let B = x * sgn;
let P_2 = 0;
let P_1 = 1;
let P = 0;
let Q_2 = 1;
let Q_1 = 0;
let Q = 0;
let A = Math.floor(B);
while (Q_1 < D) {
A = Math.floor(B);
P = A * P_1 + P_2;
Q = A * Q_1 + Q_2;
if (B - A < 0.00000005) break;
B = 1 / (B - A);
P_2 = P_1;
P_1 = P;
Q_2 = Q_1;
Q_1 = Q;
}
if (Q > D) {
if (Q_1 > D) {
Q = Q_2;
P = P_2;
} else {
Q = Q_1;
P = P_1;
}
}
if (!mixed) return [0, sgn * P, Q];
const q = Math.floor((sgn * P) / Q);
return [q, sgn * P - q * Q, Q];
}
export const useFraction = function () {
return {
frac,
cont,
};
};

View file

@ -0,0 +1,99 @@
import { useAsync, ref, reactive, Ref } from "@nuxtjs/composition-api";
import { useAsyncKey } from "../use-utils";
import { useUserApi } from "~/composables/api";
import { Food } from "~/api/class-interfaces/recipe-foods";
let foodStore: Ref<Food[] | null> | null = null;
export const useFoods = function () {
const api = useUserApi();
const loading = ref(false);
const deleteTargetId = ref(0);
const validForm = ref(true);
const workingFoodData = reactive({
id: 0,
name: "",
description: "",
});
const actions = {
getAll() {
loading.value = true;
const units = useAsync(async () => {
const { data } = await api.foods.getAll();
return data;
}, useAsyncKey());
loading.value = false;
return units;
},
async refreshAll() {
loading.value = true;
const { data } = await api.foods.getAll();
if (data && foodStore) {
foodStore.value = data;
}
loading.value = false;
},
async createOne(domForm: VForm | null = null) {
if (domForm && !domForm.validate()) {
validForm.value = false;
return;
}
loading.value = true;
const { data } = await api.foods.createOne(workingFoodData);
if (data && foodStore?.value) {
foodStore.value.push(data);
return data;
} else {
this.refreshAll();
}
domForm?.reset();
validForm.value = true;
this.resetWorking();
loading.value = false;
},
async updateOne() {
if (!workingFoodData.id) {
return;
}
loading.value = true;
const { data } = await api.foods.updateOne(workingFoodData.id, workingFoodData);
if (data && foodStore?.value) {
this.refreshAll();
}
loading.value = false;
},
async deleteOne(id: string | number) {
loading.value = true;
const { data } = await api.foods.deleteOne(id);
if (data && foodStore?.value) {
this.refreshAll();
}
},
resetWorking() {
workingFoodData.id = 0;
workingFoodData.name = "";
workingFoodData.description = "";
},
setWorking(item: Food) {
workingFoodData.id = item.id;
workingFoodData.name = item.name;
workingFoodData.description = item.description;
},
flushStore() {
foodStore = null;
},
};
if (!foodStore) {
foodStore = actions.getAll();
}
return { foods: foodStore, workingFoodData, deleteTargetId, actions, validForm };
};

View file

@ -0,0 +1,28 @@
import { useFraction } from "./use-fraction";
import { RecipeIngredient } from "~/types/api-types/recipe";
const { frac } = useFraction();
export function parseIngredientText(ingredient: RecipeIngredient, disableAmount: boolean, scale: number = 1): string {
if (disableAmount) {
return ingredient.note;
}
const { quantity, food, unit, note } = ingredient;
let returnQty = "";
if (unit?.fraction) {
const fraction = frac(quantity * scale, 10, true);
if (fraction[0] !== undefined && fraction[0] > 0) {
returnQty += fraction[0];
}
if (fraction[1] > 0) {
returnQty += ` <sup>${fraction[1]}</sup>&frasl;<sub>${fraction[2]}</sub>`;
}
} else {
returnQty = (quantity * scale).toString();
}
return `${returnQty} ${unit?.name || " "} ${food?.name || " "} ${note}`.replace(/ {2,}/g, " ");
}

View file

@ -0,0 +1,103 @@
import { useAsync, ref, reactive, Ref } from "@nuxtjs/composition-api";
import { useAsyncKey } from "../use-utils";
import { useUserApi } from "~/composables/api";
import { Unit } from "~/api/class-interfaces/recipe-units";
let unitStore: Ref<Unit[] | null> | null = null;
export const useUnits = function () {
const api = useUserApi();
const loading = ref(false);
const deleteTargetId = ref(0);
const validForm = ref(true);
const workingUnitData = reactive({
id: 0,
name: "",
fraction: true,
abbreviation: "",
description: "",
});
const actions = {
getAll() {
loading.value = true;
const units = useAsync(async () => {
const { data } = await api.units.getAll();
return data;
}, useAsyncKey());
loading.value = false;
return units;
},
async refreshAll() {
loading.value = true;
const { data } = await api.units.getAll();
if (data && unitStore) {
unitStore.value = data;
}
loading.value = false;
},
async createOne(domForm: VForm | null = null) {
if (domForm && !domForm.validate()) {
validForm.value = false;
return;
}
loading.value = true;
const { data } = await api.units.createOne(workingUnitData);
if (data && unitStore?.value) {
unitStore.value.push(data);
} else {
this.refreshAll();
}
domForm?.reset();
validForm.value = true;
this.resetWorking();
loading.value = false;
},
async updateOne() {
if (!workingUnitData.id) {
return;
}
loading.value = true;
const { data } = await api.units.updateOne(workingUnitData.id, workingUnitData);
if (data && unitStore?.value) {
this.refreshAll();
}
loading.value = false;
},
async deleteOne(id: string | number) {
loading.value = true;
const { data } = await api.units.deleteOne(id);
if (data && unitStore?.value) {
this.refreshAll();
}
},
resetWorking() {
workingUnitData.id = 0;
workingUnitData.name = "";
workingUnitData.abbreviation = "";
workingUnitData.description = "";
},
setWorking(item: Unit) {
workingUnitData.id = item.id;
workingUnitData.name = item.name;
workingUnitData.fraction = item.fraction;
workingUnitData.abbreviation = item.abbreviation;
workingUnitData.description = item.description;
},
flushStore() {
unitStore = null;
},
};
if (!unitStore) {
unitStore = actions.getAll();
}
return { units: unitStore, workingUnitData, deleteTargetId, actions, validForm };
};

View file

@ -0,0 +1,47 @@
import { ref, onMounted } from "@nuxtjs/composition-api";
import { useUserApi } from "~/composables/api";
import { Recipe } from "~/types/api-types/recipe";
export const useRecipe = function (slug: string, eager: boolean = true) {
const api = useUserApi();
const loading = ref(false);
const recipe = ref<Recipe | null>(null);
async function fetchRecipe() {
loading.value = true;
const { data } = await api.recipes.getOne(slug);
loading.value = false;
if (data) {
recipe.value = data;
}
}
async function deleteRecipe() {
loading.value = true;
const { data } = await api.recipes.deleteOne(slug);
loading.value = false;
return data;
}
async function updateRecipe(recipe: Recipe) {
loading.value = true;
const { data } = await api.recipes.updateOne(slug, recipe);
loading.value = false;
return data;
}
onMounted(() => {
if (eager) {
fetchRecipe();
}
});
return {
recipe,
loading,
fetchRecipe,
deleteRecipe,
updateRecipe,
};
};

View file

@ -0,0 +1,122 @@
import { useAsync, ref } from "@nuxtjs/composition-api";
import { set } from "@vueuse/core";
import { useAsyncKey } from "../use-utils";
import { useUserApi } from "~/composables/api";
import { Recipe } from "~/types/api-types/recipe";
export const allRecipes = ref<Recipe[] | null>([]);
export const recentRecipes = ref<Recipe[] | null>([]);
const rand = (n: number) => Math.floor(Math.random() * n);
function swap(t: Array<any>, i: number, j: number) {
const q = t[i];
t[i] = t[j];
t[j] = q;
return t;
}
export const useSorter = () => {
function sortAToZ(list: Array<Recipe>) {
list.sort((a, b) => {
const textA = a.name.toUpperCase();
const textB = b.name.toUpperCase();
return textA < textB ? -1 : textA > textB ? 1 : 0;
});
}
function sortByCreated(list: Array<Recipe>) {
list.sort((a, b) => (a.dateAdded > b.dateAdded ? -1 : 1));
}
function sortByUpdated(list: Array<Recipe>) {
list.sort((a, b) => (a.dateUpdated > b.dateUpdated ? -1 : 1));
}
function sortByRating(list: Array<Recipe>) {
list.sort((a, b) => (a.rating > b.rating ? -1 : 1));
}
function randomRecipe(list: Array<Recipe>): Recipe {
return list[Math.floor(Math.random() * list.length)];
}
function shuffle(list: Array<Recipe>) {
let last = list.length;
let n;
while (last > 0) {
n = rand(last);
swap(list, n, --last);
}
}
return {
sortAToZ,
sortByCreated,
sortByUpdated,
sortByRating,
randomRecipe,
shuffle,
};
};
export const useLazyRecipes = function () {
const api = useUserApi();
const recipes = ref<Recipe[] | null>([]);
async function fetchMore(start: number, limit: number) {
const { data } = await api.recipes.getAll(start, limit);
if (data) {
data.forEach((recipe) => {
recipes.value?.push(recipe);
});
}
}
return {
recipes,
fetchMore,
};
};
export const useRecipes = (all = false, fetchRecipes = true) => {
const api = useUserApi();
// recipes is non-reactive!!
const { recipes, start, end } = (() => {
if (all) {
return {
recipes: allRecipes,
start: 0,
end: 9999,
};
} else {
return {
recipes: recentRecipes,
start: 0,
end: 30,
};
}
})();
async function refreshRecipes() {
const { data } = await api.recipes.getAll(start, end);
if (data) {
set(recipes, data);
}
}
function getAllRecipes() {
useAsync(async () => {
await refreshRecipes();
}, useAsyncKey());
}
function assignSorted(val: Array<Recipe>) {
recipes.value = val;
}
if (fetchRecipes) {
getAllRecipes();
}
return { getAllRecipes, assignSorted, refreshRecipes };
};

View file

@ -0,0 +1,60 @@
import { Ref, ref, useAsync } from "@nuxtjs/composition-api";
import { useUserApi } from "../api";
import { useAsyncKey } from "../use-utils";
import { CategoriesAPI, Category } from "~/api/class-interfaces/categories";
import { Tag, TagsAPI } from "~/api/class-interfaces/tags";
export const allCategories = ref<Category[] | null>([]);
export const allTags = ref<Tag[] | null>([]);
function baseTagsCategories(reference: Ref<Category[] | null> | Ref<Tag[] | null>, api: TagsAPI | CategoriesAPI) {
function useAsyncGetAll() {
useAsync(async () => {
await refreshItems();
}, useAsyncKey());
}
async function refreshItems() {
const { data } = await api.getAll();
reference.value = data;
}
async function createOne(payload: { name: string }) {
const { data } = await api.createOne(payload);
if (data) {
refreshItems();
}
}
async function deleteOne(slug: string) {
const { data } = await api.deleteOne(slug);
if (data) {
refreshItems();
}
}
async function updateOne(slug: string, payload: { name: string }) {
// @ts-ignore // TODO: Fix Typescript Issue - Unsure how to fix this while also keeping mixins
const { data } = await api.updateOne(slug, payload);
if (data) {
refreshItems();
}
}
return { useAsyncGetAll, refreshItems, createOne, deleteOne, updateOne };
}
export const useTags = function () {
const api = useUserApi();
return {
allTags,
...baseTagsCategories(allTags, api.tags),
};
};
export const useCategories = function () {
const api = useUserApi();
return {
allCategories,
...baseTagsCategories(allCategories, api.categories),
};
};