Continue converting to composition api

This commit is contained in:
Dan Elbert 2024-10-02 14:34:50 -05:00
parent 0d35f50dbf
commit 67c23015ab
39 changed files with 1013 additions and 1324 deletions

View File

@ -42,8 +42,18 @@ class ApplicationController < ActionController::Base
if owner
yield if block_given?
else
flash[:warning] = "Operation Not Permitted"
redirect_to root_path
respond_to do |format|
format.html do
flash[:warning] = "Operation Not Permitted"
redirect_to root_path
end
format.json do
render json: { error: "Operation Not Permitted" }, status: current_user.nil? ? :unauthorized : :forbidden
end
end
end
end

View File

@ -34,8 +34,10 @@ class CalculatorController < ApplicationController
begin
input_unit = UnitConversion.parse(input)
input_unit.unitwise
rescue UnitConversion::UnparseableUnitError => e
data[:errors][:input] << 'invalid string'
data[:errors][:input] << e.message
input_unit = nil
end
if !input_unit.nil?

View File

@ -50,7 +50,7 @@ class UsersController < ApplicationController
if @user.save
set_current_user(@user)
format.html { redirect_to root_path, notice: 'User created.' }
format.json { render :show, status: :created, location: @user }
format.json { render json: UserSerializer.for(@user), status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
@ -68,7 +68,7 @@ class UsersController < ApplicationController
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to root_path, notice: 'User updated.' }
format.json { render :show, status: :created, location: @user }
format.json { render json: UserSerializer.for(@user) , status: :created, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }

View File

@ -145,7 +145,7 @@
emit("update:modelValue", newValue);
if (newValue.length >= Math.max(1, props.minLength)) {
this.updateOptions(newValue);
updateOptions(newValue);
} else {
isListOpen.value = false;
}

View File

@ -1,31 +1,33 @@
<template>
<app-modal :open="open" :title="message" @dismiss="runCancel">
<div class="buttons">
<button type="button" class="button is-primary" @click="runConfirm">OK</button>
<button type="button" class="button" @click="runCancel">Cancel</button>
</div>
<app-modal :open="open" :title="title" @dismiss="runCancel">
<p class="is-size-5">{{ message }}</p>
<template #footer>
<div class="buttons">
<button type="button" class="button is-primary" @click="runConfirm">OK</button>
<button type="button" class="button" @click="runCancel">Cancel</button>
</div>
</template>
</app-modal>
</template>
<script setup>
const emit = defineEmits(["cancel", "confirm"]);
const props = defineProps({
cancel: {
type: Function,
required: true
},
confirm: {
type: Function,
required: true
},
message: {
type: String,
required: false,
default: 'Are you sure?'
},
title: {
type: String,
required: false,
default: "Confirm"
},
open: {
type: Boolean,
required: true
@ -33,11 +35,11 @@ const props = defineProps({
});
function runConfirm() {
props.confirm();
emit("confirm");
}
function runCancel() {
props.cancel();
emit("cancel");
}
</script>

View File

@ -1,5 +1,5 @@
<template>
<app-text-field :value="stringValue" @input="input" :label="label" type="date"></app-text-field>
<app-text-field :value="stringValue" @update:modelValue="input" :label="label" type="date"></app-text-field>
</template>
<script setup>

View File

@ -1,6 +1,6 @@
<template>
<Teleport to="body">
<div :class="['popup', 'modal', { 'is-wide': wide, 'is-active': open && error === null }]">
<div :class="['modal', { 'is-wide': wide, 'is-active': open && error === null }]">
<div class="modal-background" @click="close"></div>
<div class="modal-card">
<header class="modal-card-head">
@ -13,6 +13,11 @@
<section class="modal-card-body">
<slot></slot>
</section>
<footer class="modal-card-foot">
<slot name="footer">
</slot>
</footer>
</div>
</div>
</Teleport>

View File

@ -1,7 +1,7 @@
<template>
<nav v-show="totalPages > 1 || showWithSinglePage" class="pagination" role="navigation" :aria-label="pagedItemName + ' page navigation'">
<a class="pagination-previous" :title="isFirstPage ? 'This is the first page' : ''" :disabled="isFirstPage" @click.prevent="changePage(currentPage - 1)">Previous</a>
<a class="pagination-next" :title="isLastPage ? 'This is the last page' : ''" :disabled="isLastPage" @click.prevent="changePage(currentPage + 1)">Next page</a>
<a :class="{'pagination-previous': true, 'is-disabled': isFirstPage}" :title="isFirstPage ? 'This is the first page' : ''" @click.prevent="changePage(currentPage - 1)">Previous</a>
<a :class="{'pagination-next': true, 'is-disabled': isLastPage}" :title="isLastPage ? 'This is the last page' : ''" @click.prevent="changePage(currentPage + 1)">Next page</a>
<ul class="pagination-list">
<li v-for="page in pageItems" :key="page">
<a v-if="page > 0" class="pagination-link" :class="{'is-current': page === currentPage}" href="#" @click.prevent="changePage(page)">{{page}}</a>

View File

@ -21,7 +21,7 @@
</div>
<div class="field-body">
<div class="field">
<app-rating readonly :value="log.rating"></app-rating>
<app-rating readonly :model-value="log.rating"></app-rating>
</div>
</div>
</div>

View File

@ -43,173 +43,155 @@
</div>
</template>
<script>
<script setup>
import { computed, ref } from "vue";
import { useMediaQueryStore } from "../stores/mediaQuery";
import RecipeEditIngredientItem from "./RecipeEditIngredientItem";
import { mapState } from "pinia";
import { useMediaQueryStore } from "../stores/mediaQuery";
const mediaQueryStore = useMediaQueryStore();
export default {
props: {
ingredients: {
required: true,
type: Array
}
},
data() {
return {
isBulkEditing: false,
bulkEditText: null
};
},
computed: {
...mapState(useMediaQueryStore, {
isMobile: store => store.mobile
}),
bulkIngredientPreview() {
if (this.bulkEditText === null) {
return [];
}
const regex = /^\s*(?:([\d\/.]+(?:\s+[\d\/]+)?)\s+)?(?:([\w-]+)(?:\s+of)?\s+)?([^,|]+?|.+\|)(?:,\s*([^|]*?))?(?:\s*\[(\d+)\]\s*)?$/i;
const magicFunc = function(str) {
if (str === "-") {
return "";
} else {
return str;
}
};
const parsed = [];
const lines = this.bulkEditText.replace("\r", "").split("\n");
for (let line of lines) {
if (line.length === 0) { continue; }
const match = line.match(regex);
if (match) {
const matchedName = match[3].replace(/\|\s*$/, "");
let item = {quantity: magicFunc(match[1]), units: magicFunc(match[2]), name: magicFunc(matchedName), preparation: magicFunc(match[4]), id: match[5] || null};
parsed.push(item);
} else {
parsed.push(null);
}
}
return parsed;
},
visibleIngredients() {
return this.ingredients.filter(i => i._destroy !== true);
}
},
methods: {
createIngredient() {
const sort_orders = this.ingredients.map(i => i.sort_order);
sort_orders.push(0);
const next_sort_order = Math.max(...sort_orders) + 5;
return {
id: null,
quantity: null,
units: null,
name: null,
preparation: null,
ingredient_id: null,
sort_order: next_sort_order
};
},
addIngredient() {
this.ingredients.push(this.createIngredient());
},
deleteFood(food) {
if (food.id) {
food._destroy = true;
} else {
const idx = this.ingredients.findIndex(i => i === food);
this.ingredients.splice(idx, 1);
}
},
bulkEditIngredients() {
this.isBulkEditing = true;
let text = [];
for (let item of this.visibleIngredients) {
text.push(
item.quantity + " " +
(item.units || "-") + " " +
(item.name.indexOf(",") >= 0 ? item.name + "|" : item.name) +
(item.preparation ? (", " + item.preparation) : "") +
(item.id ? (" [" + item.id + "]") : "")
);
}
this.bulkEditText = text.join("\n");
},
cancelBulkEditing() {
this.isBulkEditing = false;
},
saveBulkEditing() {
const parsed = this.bulkIngredientPreview.filter(i => i !== null);
const existing = [...this.ingredients];
const newList = [];
for (let parsedIngredient of parsed) {
let newIngredient = null;
if (parsedIngredient.id !== null) {
let intId = parseInt(parsedIngredient.id);
let exIdx = existing.findIndex(i => i.id === intId);
if (exIdx >= 0) {
let ex = existing[exIdx];
if (ex.name === parsedIngredient.name) {
newIngredient = ex;
existing.splice(exIdx, 1);
}
}
}
if (newIngredient === null) {
newIngredient = this.createIngredient();
}
newIngredient.quantity = parsedIngredient.quantity;
newIngredient.units = parsedIngredient.units;
newIngredient.name = parsedIngredient.name;
newIngredient.preparation = parsedIngredient.preparation;
newList.push(newIngredient);
}
for (let oldExisting of existing.filter(i => i.id !== null)) {
newList.push({id: oldExisting.id, _destroy: true});
}
this.ingredients.splice(0);
let sortIdx = 0;
for (let n of newList) {
n.sort_order = sortIdx++;
this.ingredients.push(n);
}
this.isBulkEditing = false;
}
},
components: {
RecipeEditIngredientItem
const props = defineProps({
ingredients: {
required: true,
type: Array
}
});
const isBulkEditing = ref(false);
const bulkEditText = ref(null);
const isMobile = computed(() => mediaQueryStore.mobile);
const visibleIngredients = computed(() => props.ingredients.filter(i => i._destroy !== true));
const bulkIngredientPreview = computed(() => {
if (bulkEditText.value === null || bulkEditText.value === "") {
return [];
}
const regex = /^\s*(?:([\d\/.]+(?:\s+[\d\/]+)?)\s+)?(?:([\w-]+)(?:\s+of)?\s+)?([^,|]+?|.+\|)(?:,\s*([^|]*?))?(?:\s*\[(\d+)\]\s*)?$/i;
const magicFunc = function(str) {
if (str === "-") {
return "";
} else {
return str;
}
};
const parsed = [];
const lines = bulkEditText.value.replace("\r", "").split("\n");
for (let line of lines) {
if (line.length === 0) { continue; }
const match = line.match(regex);
if (match) {
const matchedName = match[3].replace(/\|\s*$/, "");
let item = {quantity: magicFunc(match[1]), units: magicFunc(match[2]), name: magicFunc(matchedName), preparation: magicFunc(match[4]), id: match[5] || null};
parsed.push(item);
} else {
parsed.push(null);
}
}
return parsed;
});
function createIngredient() {
const sort_orders = props.ingredients.map(i => i.sort_order);
sort_orders.push(0);
const next_sort_order = Math.max(...sort_orders) + 5;
return {
id: null,
quantity: null,
units: null,
name: null,
preparation: null,
ingredient_id: null,
sort_order: next_sort_order
};
}
function addIngredient() {
props.ingredients.push(createIngredient());
}
function deleteFood(food) {
if (food.id) {
food._destroy = true;
} else {
const idx = props.ingredients.findIndex(i => i === food);
props.ingredients.splice(idx, 1);
}
}
function bulkEditIngredients() {
isBulkEditing.value = true;
let text = [];
for (let item of visibleIngredients.value) {
text.push(
item.quantity + " " +
(item.units || "-") + " " +
(item.name.indexOf(",") >= 0 ? item.name + "|" : item.name) +
(item.preparation ? (", " + item.preparation) : "") +
(item.id ? (" [" + item.id + "]") : "")
);
}
bulkEditText.value = text.join("\n");
}
function cancelBulkEditing() {
isBulkEditing.value = false;
}
function saveBulkEditing() {
const parsed = bulkIngredientPreview.value.filter(i => i !== null);
const existing = [...props.ingredients];
const newList = [];
for (let parsedIngredient of parsed) {
let newIngredient = null;
if (parsedIngredient.id !== null) {
let intId = parseInt(parsedIngredient.id);
let exIdx = existing.findIndex(i => i.id === intId);
if (exIdx >= 0) {
let ex = existing[exIdx];
if (ex.name === parsedIngredient.name) {
newIngredient = ex;
existing.splice(exIdx, 1);
}
}
}
if (newIngredient === null) {
newIngredient = createIngredient();
}
newIngredient.quantity = parsedIngredient.quantity;
newIngredient.units = parsedIngredient.units;
newIngredient.name = parsedIngredient.name;
newIngredient.preparation = parsedIngredient.preparation;
newList.push(newIngredient);
}
for (let oldExisting of existing.filter(i => i.id !== null)) {
newList.push({id: oldExisting.id, _destroy: true});
}
props.ingredients.splice(0);
let sortIdx = 0;
for (let n of newList) {
n.sort_order = sortIdx++;
props.ingredients.push(n);
}
isBulkEditing.value = false;
}
</script>

View File

@ -44,55 +44,50 @@
</div>
</template>
<script>
<script setup>
import { useTemplateRef, watch } from "vue";
import api from "../lib/Api";
export default {
props: {
ingredient: {
required: true,
type: Object
},
showLabels: {
required: false,
type: Boolean,
default: false
}
const emit = defineEmits(["deleteFood"]);
const props = defineProps({
ingredient: {
required: true,
type: Object
},
showLabels: {
required: false,
type: Boolean,
default: false
}
});
methods: {
deleteFood(ingredient) {
this.$emit("deleteFood", ingredient);
},
const autocompleteElement = useTemplateRef("autocomplete");
updateSearchItems(text) {
return api.getSearchIngredients(text);
},
watch(props.ingredient.name, (val) => {
if (props.ingredient.ingredient && props.ingredient.ingredient.name !== val) {
props.ingredient.ingredient_id = null;
props.ingredient.ingredient = null;
}
});
searchItemSelected(ingredient) {
this.ingredient.ingredient_id = ingredient.id;
this.ingredient.ingredient = ingredient;
this.ingredient.name = ingredient.name;
},
function deleteFood(ingredient) {
emit("deleteFood", ingredient);
}
nameClick() {
if (this.ingredient.ingredient_id === null && this.ingredient.name !== null && this.ingredient.name.length > 2) {
this.$refs.autocomplete.updateOptions(this.ingredient.name);
}
}
},
function updateSearchItems(text) {
return api.getSearchIngredients(text);
}
watch: {
'ingredient.name': function(val) {
if (this.ingredient.ingredient && this.ingredient.ingredient.name !== val) {
this.ingredient.ingredient_id = null;
this.ingredient.ingredient = null;
}
}
},
function searchItemSelected(ingredient) {
props.ingredient.ingredient_id = ingredient.id;
props.ingredient.ingredient = ingredient;
props.ingredient.name = ingredient.name;
}
components: {
function nameClick() {
if (props.ingredient.ingredient_id === null && props.ingredient.name !== null && props.ingredient.name.length > 2) {
autocompleteElement.updateOptions(props.ingredient.name);
}
}

View File

@ -38,7 +38,7 @@
Ingredients
<button class="button is-small is-primary" type="button" @click="showConvertDialog = true">Convert</button>
<app-dropdown :open="addToTasksMenuOpen" label="Add to list" button-class="is-small is-primary" @open="addToTasksMenuOpen = true" @close="addToTasksMenuOpen = false">
<button class="button primary" v-for="tl in taskLists" :key="tl.id" @click="addRecipeToList(tl)">
<button class="button primary" v-for="tl in taskStore.taskLists" :key="tl.id" @click="addRecipeToList(tl)">
{{tl.name}}
</button>
</app-dropdown>
@ -150,147 +150,118 @@
</div>
</template>
<script>
<script setup>
import { computed, onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import api from "../lib/Api";
import { mapActions, mapState } from "pinia";
import { useTaskStore } from "../stores/task";
export default {
props: {
recipe: {
required: true,
type: Object
}
},
const taskStore = useTaskStore();
const router = useRouter();
data() {
return {
showNutrition: false,
showConvertDialog: false,
addToTasksMenuOpen: false,
const props = defineProps({
recipe: {
required: true,
type: Object
}
});
scaleValue: '1',
systemConvertValue: "",
unitConvertValue: "",
const showNutrition = ref(false);
const showConvertDialog = ref(false);
const addToTasksMenuOpen = ref(false);
scaleOptions: [
'1/4',
'1/3',
'1/2',
'2/3',
'3/4',
'1',
'1 1/2',
'2',
'3',
'4'
]
};
},
const scaleValue = ref('1');
const systemConvertValue = ref('');
const unitConvertValue = ref('');
computed: {
...mapState(useTaskStore, [
'taskLists'
]),
const scaleOptions = [
'1/4',
'1/3',
'1/2',
'2/3',
'3/4',
'1',
'1 1/2',
'2',
'3',
'4'
];
timeDisplay() {
let a = this.formatMinutes(this.recipe.active_time);
const t = this.formatMinutes(this.recipe.total_time);
const timeDisplay = computed(() => {
let a = formatMinutes(props.recipe.active_time);
const t = formatMinutes(props.recipe.total_time);
if (a) {
a = ` (${a} active)`;
}
if (a) {
a = ` (${a} active)`;
}
return t + a;
},
return t + a;
});
sourceUrl() {
try {
return new URL(this.recipe.source);
} catch(err) {
return null;
}
},
const sourceUrl = computed(() => {
try {
return new URL(props.recipe.source);
} catch(err) {
return null;
}
});
isSourceUrl() {
return this.sourceUrl !== null;
},
const isSourceUrl = computed(() => sourceUrl.value !== null);
const sourceText = computed(() => isSourceUrl.value ? sourceUrl.value.host : props.recipe.source);
sourceText() {
if (this.isSourceUrl) {
return this.sourceUrl.host;
} else {
return this.recipe.source;
}
}
},
watch(props.recipe, (r) => {
if (r) {
scaleValue.value = r.converted_scale || '1';
systemConvertValue.value = r.converted_system;
unitConvertValue.value = r.converted_unit;
}
}, { immediate: true });
watch: {
recipe: {
handler: function(r) {
if (r) {
this.scaleValue = r.converted_scale || '1';
this.systemConvertValue = r.converted_system;
this.unitConvertValue = r.converted_unit;
}
},
immediate: true
}
},
onMounted(() => {
taskStore.ensureTaskLists();
});
methods: {
...mapActions(useTaskStore, [
'ensureTaskLists',
'setCurrentTaskList'
]),
addRecipeToList(list) {
api.addRecipeToTaskList(list.id, this.recipe.id)
function addRecipeToList(list) {
api.addRecipeToTaskList(list.id, props.recipe.id)
.then(() => {
this.setCurrentTaskList(list);
this.$router.push({name: 'task_lists'})
taskStore.setCurrentTaskList(list);
router.push({name: 'task_lists'})
});
},
}
convert() {
this.showConvertDialog = false;
this.$router.push({name: 'recipe', query: { scale: this.scaleValue, system: this.systemConvertValue, unit: this.unitConvertValue }});
},
function convert() {
showConvertDialog.value = false;
router.push({name: 'recipe', query: { scale: scaleValue.value, system: systemConvertValue.value, unit: unitConvertValue.value }});
}
roundValue(v) {
return parseFloat(v).toFixed(2);
},
function roundValue(v) {
return parseFloat(v).toFixed(2);
}
formatMinutes(min) {
if (min) {
const partUnits = [
{unit: "d", minutes: 60 * 24},
{unit: "h", minutes: 60},
{unit: "m", minutes: 1}
];
function formatMinutes(min) {
if (min) {
const partUnits = [
{unit: "d", minutes: 60 * 24},
{unit: "h", minutes: 60},
{unit: "m", minutes: 1}
];
const parts = [];
let remaining = min;
const parts = [];
let remaining = min;
for (let unit of partUnits) {
let val = Math.floor(remaining / unit.minutes);
remaining = remaining % unit.minutes;
for (let unit of partUnits) {
let val = Math.floor(remaining / unit.minutes);
remaining = remaining % unit.minutes;
if (val > 0) {
parts.push(`${val} ${unit.unit}`);
}
}
return parts.join(" ");
} else {
return "";
if (val > 0) {
parts.push(`${val} ${unit.unit}`);
}
}
},
mounted() {
this.ensureTaskLists();
return parts.join(" ");
} else {
return "";
}
}

View File

@ -24,39 +24,42 @@
</div>
</template>
<script>
<script setup>
export default {
props: {
taskItem: {
required: true,
type: Object
}
},
import { onMounted, useTemplateRef } from "vue";
methods: {
inputKeydown(evt) {
switch (evt.key) {
case "Enter":
evt.preventDefault();
this.save();
}
},
const emit = defineEmits(["save"]);
const props = defineProps({
taskItem: {
required: true,
type: Object
}
});
save() {
this.$emit("save", this.taskItem);
},
const nameElement = useTemplateRef("nameInput");
focus() {
this.$refs.nameInput.focus();
}
},
onMounted(() => focus());
mounted() {
this.focus();
function inputKeydown(evt) {
switch (evt.key) {
case "Enter":
evt.preventDefault();
save();
}
}
function save() {
emit("save", props.taskItem);
}
function focus() {
nameElement.value.focus();
}
defineExpose({
focus
});
</script>
<style lang="scss" scoped>

View File

@ -60,130 +60,100 @@
</div>
</template>
<script>
<script setup>
import { computed, ref, useTemplateRef } from "vue";
import * as Errors from '../lib/Errors';
import { mapActions } from "pinia";
import { useTaskStore } from "../stores/task";
import { useLoadResource } from "../lib/useLoadResource";
import TaskItemEdit from "./TaskItemEdit";
const newItemTemplate = function(listId) {
const { loadResource } = useLoadResource();
const taskStore = useTaskStore();
const itemEditElement = useTemplateRef("itemEdit");
const props = defineProps({
taskList: {
required: true,
type: Object
}
});
const showAddItem = ref(false);
const newItem = ref(null);
const newItemValidationErrors = ref({});
const completedTaskItems = computed(() => (props.taskList ? props.taskList.task_items : []).filter(i => i.completed));
const uncompletedTaskItems = computed(() => (props.taskList ? props.taskList.task_items : []).filter(i => !i.completed));
const completedItemCount = computed(() => completedTaskItems.value.length);
const uncompletedItemCount = computed(() => uncompletedTaskItems.value.length);
const taskItems = computed(() => uncompletedTaskItems.value.concat(completedTaskItems.value));
function newItemTemplate() {
return {
task_list_id: listId,
task_list_id: null,
name: '',
quantity: '',
completed: false
};
};
}
export default {
props: {
taskList: {
required: true,
type: Object
}
},
data() {
return {
showAddItem: false,
newItem: null,
newItemValidationErrors: {}
};
},
computed: {
completedItemCount() {
return this.taskList === null ? 0 : this.taskList.task_items.filter(i => i.completed).length;
},
uncompletedItemCount() {
return this.taskList === null ? 0 : this.taskList.task_items.filter(i => !i.completed).length;
},
completedTaskItems() {
return (this.taskList ? this.taskList.task_items : []).filter(i => i.completed);
},
uncompletedTaskItems() {
return (this.taskList ? this.taskList.task_items : []).filter(i => !i.completed);
},
taskItems() {
return this.uncompletedTaskItems.concat(this.completedTaskItems);
}
},
methods: {
...mapActions(useTaskStore, [
'createTaskItem',
'updateTaskItem',
'deleteTaskItems',
'completeTaskItems'
]),
save() {
this.loadResource(
this.createTaskItem(this.newItem)
function save() {
newItem.value.task_list_id = props.taskList.id;
loadResource(
taskStore.createTaskItem(newItem.value)
.then(() => {
this.newItem = newItemTemplate(this.taskList.id);
this.$refs.itemEdit.focus();
newItem.value = newItemTemplate();
itemEditElement.value.focus();
})
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.newItemValidationErrors = err.validationErrors()))
)
},
.catch(Errors.onlyFor(Errors.ApiValidationError, err => newItemValidationErrors.value = err.validationErrors()))
)
}
toggleItem(i) {
this.loadResource(
this.completeTaskItems({
taskList: this.taskList,
taskItems: [i],
completed: !i.completed
})
);
},
function toggleItem(i) {
loadResource(
taskStore.completeTaskItems({
taskList: props.taskList,
taskItems: [i],
completed: !i.completed
})
);
}
toggleShowAddItem() {
this.newItem = newItemTemplate(this.taskList.id);
this.showAddItem = !this.showAddItem;
},
function toggleShowAddItem() {
newItem.value = newItemTemplate();
showAddItem.value = !showAddItem.value;
}
completeAllItems() {
const toComplete = this.taskList.task_items.filter(i => !i.completed);
this.loadResource(
this.completeTaskItems({
taskList: this.taskList,
taskItems: toComplete,
completed: true
})
)
},
function completeAllItems() {
const toComplete = props.taskList.task_items.filter(i => !i.completed);
loadResource(
taskStore.completeTaskItems({
taskList: props.taskList,
taskItems: toComplete,
completed: true
})
)
}
unCompleteAllItems() {
const toUnComplete = this.taskList.task_items.filter(i => i.completed);
this.loadResource(
this.completeTaskItems({
taskList: this.taskList,
taskItems: toUnComplete,
completed: false
})
)
},
function unCompleteAllItems() {
const toUnComplete = props.taskList.task_items.filter(i => i.completed);
loadResource(
taskStore.completeTaskItems({
taskList: props.taskList,
taskItems: toUnComplete,
completed: false
})
)
}
deleteCompletedItems() {
this.loadResource(
this.deleteTaskItems({
taskList: this.taskList,
taskItems: this.taskList.task_items.filter(i => i.completed)
})
);
},
},
components: {
TaskItemEdit
}
function deleteCompletedItems() {
loadResource(
taskStore.deleteTaskItems({
taskList: props.taskList,
taskItems: props.taskList.task_items.filter(i => i.completed)
})
);
}
</script>

View File

@ -14,39 +14,35 @@
</template>
<script>
<script setup>
export default {
props: {
taskList: {
type: Object,
required: true
},
import { ref } from "vue";
active: {
type: Boolean,
required: false,
default: false
}
const emit = defineEmits(["select", "delete"]);
const props = defineProps({
taskList: {
type: Object,
required: true
},
data() {
return {
hovering: false,
confirmingDelete: false
};
},
methods: {
selectList() {
this.$emit("select", this.taskList);
},
deleteList() {
this.confirmingDelete = false;
this.$emit("delete", this.taskList);
}
active: {
type: Boolean,
required: false,
default: false
}
});
const hovering = ref(false);
const confirmingDelete = ref(false);
function selectList() {
emit("select", props.taskList);
}
function deleteList() {
confirmingDelete.value = false;
emit("delete", props.taskList);
}
</script>

View File

@ -14,34 +14,32 @@
</div>
</template>
<script>
<script setup>
export default {
props: {
taskList: {
required: true,
type: Object
},
const emit = defineEmits(["save"]);
validationErrors: {
required: false,
type: Object,
default: function() { return {}; }
}
const props = defineProps({
taskList: {
required: true,
type: Object
},
methods: {
save() {
this.$emit("save");
},
validationErrors: {
required: false,
type: Object,
default: function() { return {}; }
}
});
nameKeydownHandler(evt) {
switch (evt.key) {
case "Enter":
evt.preventDefault();
this.save();
}
}
function save() {
emit("save");
}
function nameKeydownHandler(evt) {
switch (evt.key) {
case "Enter":
evt.preventDefault();
save();
}
}

View File

@ -5,10 +5,7 @@
</div>
</template>
<script>
<script setup>
export default {
}
</script>

View File

@ -19,11 +19,7 @@
</div>
</template>
<script>
export default {
}
<script setup>
</script>

View File

@ -2,11 +2,8 @@
</template>
<script>
<script setup>
export default {
}
</script>

View File

@ -29,24 +29,21 @@
</template>
<script>
<script setup>
import { onBeforeMount, ref } from "vue";
import { useLoadResource } from "../lib/useLoadResource";
import api from "../lib/Api";
export default {
data() {
return {
userList: []
};
},
const { loadResource } = useLoadResource();
const userList = ref([]);
created() {
this.loadResource(
onBeforeMount(() => {
loadResource(
api.getAdminUserList()
.then(list => this.userList = list)
);
}
}
.then(list => userList.value = list)
);
});
</script>

View File

@ -40,93 +40,64 @@
</div>
</template>
<script>
<script setup>
import { computed, ref, watch } from "vue";
import api from "../lib/Api";
import debounce from "lodash/debounce";
import { useLoadResource } from "../lib/useLoadResource";
export default {
data() {
return {
input: '',
outputUnit: '',
ingredient_name: '',
ingredient: null,
density: '',
output: '',
errors: {}
};
},
const { loadResource } = useLoadResource();
computed: {
inputErrors() {
if (this.errors.input && this.errors.input.length > 0) {
return this.errors.input.join(", ");
} else {
return null;
}
},
const input = ref("");
const outputUnit = ref("");
const ingredient_name = ref("");
const ingredient = ref(null);
const density = ref("");
const output = ref("");
const errors = ref({});
outputUnitErrors() {
if (this.errors.output_unit && this.errors.output_unit.length > 0) {
return this.errors.output_unit.join(", ");
} else {
return null;
}
},
const inputErrors = computed(() => getErrors("input"));
const outputUnitErrors = computed(() => getErrors("output_unit"));
const densityErrors = computed(() => getErrors("density"));
densityErrors() {
if (this.errors.density && this.errors.density.length > 0) {
return this.errors.density.join(", ");
} else {
return null;
}
}
},
const updateOutput = debounce(function() {
if (input.value && input.value.length > 0) {
loadResource(api.getCalculate(input.value, outputUnit.value, ingredient.value ? ingredient.value.ingredient_id : null, density.value)
.then(data => {
output.value = data.output;
errors.value = data.errors;
})
);
}
}, 500);
methods: {
updateSearchItems(text) {
return api.getSearchIngredients(text);
},
watch(ingredient_name, function(val) {
if (ingredient.value && ingredient.value.name !== val) {
ingredient.value = null;
}
});
searchItemSelected(ingredient) {
this.ingredient = ingredient || null;
this.ingredient_name = ingredient.name || null;
this.density = ingredient.density || null;
},
watch(
[input, outputUnit, density, ingredient],
() => updateOutput()
);
updateOutput: debounce(function() {
if (this.input && this.input.length > 0) {
this.loadResource(api.getCalculate(this.input, this.outputUnit, this.ingredient ? this.ingredient.ingredient_id : null, this.density)
.then(data => {
this.output = data.output;
this.errors = data.errors;
})
);
}
}, 500)
},
function updateSearchItems(text) {
return api.getSearchIngredients(text);
}
watch: {
'ingredient_name': function(val) {
if (this.ingredient && this.ingredient.name !== val) {
this.ingredient = null;
}
}
},
function searchItemSelected(ingredient) {
ingredient.value = ingredient || null;
ingredient_name.value = ingredient.name || null;
density.value = ingredient.density || null;
}
created() {
this.$watch(
function() {
return [this.input, this.outputUnit, this.density, this.ingredient];
},
function() {
this.updateOutput();
}
)
},
components: {
function getErrors(type) {
if (errors.value[type] && errors.value[type].length > 0) {
return errors.value[type].join(", ");
} else {
return null;
}
}

View File

@ -7,40 +7,33 @@
<food-show :food="food"></food-show>
</div>
<router-link v-if="isLoggedIn" class="button" :to="{name: 'edit_food', params: { id: foodId }}">Edit</router-link>
<router-link v-if="appConfig.isLoggedIn" class="button" :to="{name: 'edit_food', params: { id: foodId }}">Edit</router-link>
<router-link class="button" to="/foods">Back</router-link>
</div>
</template>
<script>
<script setup>
import { computed, onBeforeMount, ref } from "vue";
import { useRoute } from "vue-router";
import FoodShow from "./FoodShow";
import api from "../lib/Api";
import { useLoadResource } from "../lib/useLoadResource";
import { useAppConfigStore } from "../stores/appConfig";
export default {
data: function () {
return {
food: null
}
},
const { loadResource } = useLoadResource();
const appConfig = useAppConfigStore();
const route = useRoute();
computed: {
foodId() {
return this.$route.params.id;
}
},
const food = ref(null);
const foodId = computed(() => route.params.id);
created() {
this.loadResource(
api.getFood(this.foodId)
.then(data => { this.food = data; return data; })
);
},
components: {
FoodShow
}
}
onBeforeMount(() => {
loadResource(
api.getFood(foodId.value)
.then(data => { food.value = data; return data; })
);
});
</script>

View File

@ -9,65 +9,59 @@
</div>
</template>
<script>
<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import FoodEdit from "./FoodEdit";
import api from "../lib/Api";
import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
export default {
data() {
return {
food: {
name: null,
notes: null,
ndbn: null,
density: null,
water: null,
ash: null,
protein: null,
kcal: null,
fiber: null,
sugar: null,
carbohydrates: null,
calcium: null,
iron: null,
magnesium: null,
phosphorus: null,
potassium: null,
sodium: null,
zinc: null,
copper: null,
manganese: null,
vit_c: null,
vit_b6: null,
vit_b12: null,
vit_a: null,
vit_e: null,
vit_d: null,
vit_k: null,
cholesterol: null,
lipids: null,
food_units: []
},
validationErrors: {}
}
},
const { loadResource } = useLoadResource();
const router = useRouter();
methods: {
save() {
this.validationErrors = {}
this.loadResource(
api.postFood(this.food)
.then(() => this.$router.push('/foods'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
);
}
},
const validationErrors = ref({});
const food = reactive({
name: null,
notes: null,
ndbn: null,
density: null,
water: null,
ash: null,
protein: null,
kcal: null,
fiber: null,
sugar: null,
carbohydrates: null,
calcium: null,
iron: null,
magnesium: null,
phosphorus: null,
potassium: null,
sodium: null,
zinc: null,
copper: null,
manganese: null,
vit_c: null,
vit_b6: null,
vit_b12: null,
vit_a: null,
vit_e: null,
vit_d: null,
vit_k: null,
cholesterol: null,
lipids: null,
food_units: []
});
components: {
FoodEdit
}
function save() {
validationErrors.value = {}
loadResource(
api.postFood(food)
.then(() => router.push('/foods'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
);
}
</script>

View File

@ -14,47 +14,37 @@
</div>
</template>
<script>
<script setup>
import { computed, onBeforeMount, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import FoodEdit from "./FoodEdit";
import api from "../lib/Api";
import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
export default {
data: function () {
return {
food: null,
validationErrors: {}
};
},
const { loadResource } = useLoadResource();
const router = useRouter();
const route = useRoute();
computed: {
foodId() {
return this.$route.params.id;
}
},
const food = ref(null);
const validationErrors = ref({});
const foodId = computed(() => route.params.id);
methods: {
save() {
this.validationErrors = {};
this.loadResource(
api.patchFood(this.food)
.then(() => this.$router.push({name: 'food', params: {id: this.foodId }}))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
);
}
},
onBeforeMount(() => {
loadResource(
api.getFood(foodId.value)
.then(data => { food.value = data; return data; })
);
});
created() {
this.loadResource(
api.getFood(this.foodId)
.then(data => { this.food = data; return data; })
);
},
components: {
FoodEdit
}
function save() {
validationErrors.value = {};
loadResource(
api.patchFood(food.value)
.then(() => router.push({name: 'food', params: {id: foodId.value }}))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
);
}
</script>

View File

@ -3,7 +3,7 @@
<h1 class="title">Ingredients</h1>
<div class="buttons">
<router-link v-if="isLoggedIn" :to="{name: 'new_food'}" class="button is-primary">Create Ingredient</router-link>
<router-link v-if="appConfig.isLoggedIn" :to="{name: 'new_food'}" class="button is-primary">Create Ingredient</router-link>
</div>
<app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="food" @changePage="changePage"></app-pager>
@ -35,12 +35,14 @@
<td>{{i.kcal}}</td>
<td>{{i.density}}</td>
<td>
<router-link v-if="isLoggedIn" class="button" :to="{name: 'edit_food', params: { id: i.id } }">
<app-icon icon="pencil"></app-icon>
</router-link>
<button v-if="isLoggedIn" type="button" class="button is-danger" @click="deleteFood(i)">
<app-icon icon="x"></app-icon>
</button>
<template v-if="appConfig.isLoggedIn">
<router-link class="button" :to="{name: 'edit_food', params: { id: i.id } }">
<app-icon icon="pencil"></app-icon>
</router-link>
<button type="button" class="button is-danger" @click="deleteFood(i)">
<app-icon icon="x"></app-icon>
</button>
</template>
</td>
</tr>
</transition-group>
@ -49,114 +51,80 @@
<app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="food" @changePage="changePage"></app-pager>
<div class="buttons">
<router-link v-if="isLoggedIn" :to="{name: 'new_food'}" class="button is-primary">Create Ingredient</router-link>
<router-link v-if="appConfig.isLoggedIn" :to="{name: 'new_food'}" class="button is-primary">Create Ingredient</router-link>
</div>
<app-confirm :open="showConfirmFoodDelete" :message="confirmFoodDeleteMessage" :cancel="foodDeleteCancel" :confirm="foodDeleteConfirm"></app-confirm>
<app-confirm :open="showConfirmFoodDelete" title="Delete Ingredient?" :message="confirmFoodDeleteMessage" @cancel="foodDeleteCancel" @confirm="foodDeleteConfirm"></app-confirm>
</div>
</template>
<script>
<script setup>
import { computed, reactive, ref, watch } from "vue";
import api from "../lib/Api";
import debounce from "lodash/debounce";
import { useAppConfigStore } from "../stores/appConfig";
import { useLoadResource } from "../lib/useLoadResource";
export default {
data() {
return {
foodData: null,
foodForDeletion: null,
search: {
page: 1,
per: 25,
name: null
}
};
},
const appConfig = useAppConfigStore();
const { loadResource } = useLoadResource();
computed: {
foods() {
if (this.foodData) {
return this.foodData.foods;
} else {
return [];
}
},
const foodData = ref(null);
const foodForDeletion = ref(null);
const search = reactive({
page: 1,
per: 25,
name: null
});
totalPages() {
if (this.foodData) {
return this.foodData.total_pages
}
return 0;
},
const foods = computed(() => foodData.value?.foods || []);
const totalPages = computed(() => foodData.value?.total_pages || 0);
const currentPage = computed(() => foodData.value?.current_page || 0);
const showConfirmFoodDelete = computed(() => foodForDeletion.value !== null);
const confirmFoodDeleteMessage = computed(() => {
if (foodForDeletion.value !== null) {
return `Are you sure you want to delete ${foodForDeletion.value.name}?`;
} else {
return "??";
}
});
currentPage() {
if (this.foodData) {
return this.foodData.current_page
}
return 0;
},
const getList = debounce(function() {
return loadResource(
api.getFoodList(search.page, search.per, search.name)
.then(data => foodData.value = data)
);
}, 500, {leading: true, trailing: true});
showConfirmFoodDelete() {
return this.foodForDeletion !== null;
},
confirmFoodDeleteMessage() {
if (this.foodForDeletion !== null) {
return `Are you sure you want to delete ${this.foodForDeletion.name}?`;
} else {
return "??";
}
watch(search,
() => getList(),
{
deep: true,
immediate: true
}
},
);
methods: {
changePage(idx) {
this.search.page = idx;
},
function changePage(idx) {
search.page = idx;
}
getList: debounce(function() {
return this.loadResource(
api.getFoodList(this.search.page, this.search.per, this.search.name)
.then(data => this.foodData = data)
);
}, 500, {leading: true, trailing: true}),
function deleteFood(food) {
foodForDeletion.value = food;
}
deleteFood(food) {
this.foodForDeletion = food;
},
function foodDeleteCancel() {
foodForDeletion.value = null;
}
foodDeleteCancel() {
this.foodForDeletion = null;
},
foodDeleteConfirm() {
if (this.foodForDeletion !== null) {
this.loadResource(
api.deleteFood(this.foodForDeletion.id).then(res => {
this.foodForDeletion = null;
return this.getList();
})
);
console.log("This is where the thing happens!!");
this.foodForDeletion = null;
}
}
},
created() {
this.$watch("search",
() => this.getList(),
{
deep: true,
immediate: true
}
function foodDeleteConfirm() {
if (foodForDeletion.value !== null) {
loadResource(
api.deleteFood(foodForDeletion.value.id).then(res => {
foodForDeletion.value = null;
return getList();
})
);
},
components: {
}
}

View File

@ -14,35 +14,26 @@
</div>
</template>
<script>
<script setup>
import { computed, onBeforeMount, ref } from "vue";
import { useRoute } from "vue-router";
import LogShow from "./LogShow";
import api from "../lib/Api";
import { useLoadResource } from "../lib/useLoadResource";
export default {
data: function () {
return {
log: null
}
},
const { loadResource } = useLoadResource();
const route = useRoute();
computed: {
logId() {
return this.$route.params.id;
}
},
const log = ref(null);
const logId = computed(() => route.params.id);
created() {
this.loadResource(
api.getLog(this.logId)
.then(data => { this.log = data; return data; })
);
},
components: {
LogShow
}
}
onBeforeMount(() => {
loadResource(
api.getLog(logId.value)
.then(data => { log.value = data; return data; })
);
});
</script>

View File

@ -16,53 +16,44 @@
</div>
</template>
<script>
<script setup>
import { computed, onBeforeMount, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import LogEdit from "./LogEdit";
import api from "../lib/Api";
import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
export default {
data() {
return {
validationErrors: {},
log: {
date: null,
rating: null,
notes: null,
recipe: null
}
}
},
const { loadResource } = useLoadResource();
const route = useRoute();
const router = useRouter();
computed: {
recipeId() {
return this.$route.params.recipeId;
}
},
const validationErrors = ref({});
const log = reactive({
date: null,
rating: null,
notes: null,
recipe: null
});
methods: {
save() {
this.log.original_recipe_id = this.recipeId;
this.validationErrors = {};
const recipeId = computed(() => route.params.recipeId);
this.loadResource(
api.postLog(this.log)
.then(() => this.$router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
);
}
},
onBeforeMount(() => {
loadResource(
api.getRecipe(recipeId.value, null, null, null, data => log.recipe = data)
);
});
created() {
this.loadResource(
api.getRecipe(this.recipeId, null, null, null, data => this.log.recipe = data)
);
},
function save() {
log.original_recipe_id = recipeId.value;
validationErrors.value = {};
components: {
LogEdit
}
loadResource(
api.postLog(log)
.then(() => router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
);
}
</script>

View File

@ -16,47 +16,38 @@
</div>
</template>
<script>
<script setup>
import { computed, onBeforeMount, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import api from "../lib/Api";
import * as Errors from "../lib/Errors";
import LogEdit from "./LogEdit";
import { useLoadResource } from "../lib/useLoadResource";
export default {
data() {
return {
validationErrors: {},
log: null
}
},
const { loadResource } = useLoadResource();
const route = useRoute();
const router = useRouter();
computed: {
logId() {
return this.$route.params.id;
}
},
const validationErrors = ref({});
const log = ref(null);
methods: {
save() {
this.validationErrors = {};
this.loadResource(
api.patchLog(this.log)
.then(() => this.$router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
);
}
},
const logId = computed(() => route.params.id);
created() {
this.loadResource(
api.getLog(this.logId)
.then(data => { this.log = data; return data; })
);
},
onBeforeMount(() => {
loadResource(
api.getLog(logId.value)
.then(data => { log.value = data; return data; })
);
});
components: {
LogEdit
}
function save() {
validationErrors.value = {};
loadResource(
api.patchLog(log.value)
.then(() => router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
);
}
</script>

View File

@ -18,7 +18,7 @@
<tr v-for="l in logs" :key="l.id">
<td> <router-link :to="{name: 'log', params: {id: l.id}}">{{l.recipe.name}}</router-link></td>
<td><app-date-time :date-time="l.date" :show-time="false"></app-date-time> </td>
<td><app-rating :value="l.rating" readonly></app-rating></td>
<td><app-rating :model-value="l.rating" readonly></app-rating></td>
<td>{{l.notes}}</td>
</tr>
</tbody>
@ -27,68 +27,42 @@
</div>
</template>
<script>
<script setup>
import { computed, reactive, ref, watch } from "vue";
import api from "../lib/Api";
import debounce from "lodash/debounce";
import { useLoadResource } from "../lib/useLoadResource";
export default {
data() {
return {
logData: null,
search: {
page: 1,
per: 25
}
};
},
const { loadResource } = useLoadResource();
computed: {
logs() {
if (this.logData) {
return this.logData.logs;
} else {
return [];
}
},
const logData = ref(null);
const search = reactive({
page: 1,
per: 25
});
totalPages() {
if (this.logData) {
return this.logData.total_pages
}
return 0;
},
const logs = computed(() => logData.value?.logs || []);
const totalPages = computed(() => logData.value?.total_pages || 0);
const currentPage = computed(() => logData.value?.current_page || 0);
currentPage() {
if (this.logData) {
return this.logData.current_page
}
return 0;
const getList = debounce(function() {
loadResource(
api.getLogList(search.page, search.per)
.then(data => logData.value = data)
);
}, 500, {leading: true, trailing: true});
watch(search,
() => getList(),
{
deep: true,
immediate: true
}
},
);
methods: {
changePage(idx) {
this.search.page = idx;
},
getList: debounce(function() {
this.loadResource(
api.getLogList(this.search.page, this.search.per)
.then(data => this.logData = data)
);
}, 500, {leading: true, trailing: true})
},
created() {
this.$watch("search",
() => this.getList(),
{
deep: true,
immediate: true
}
);
}
function changePage(idx) {
search.page = idx;
}
</script>

View File

@ -38,62 +38,53 @@
</template>
<script>
<script setup>
import { onBeforeMount, ref } from "vue";
import api from "../lib/Api";
import NoteEdit from "./NoteEdit";
import { useLoadResource } from "../lib/useLoadResource";
export default {
data() {
return {
notes: [],
editNote: null
};
},
const { loadResource } = useLoadResource();
const notes = ref([]);
const editNote = ref(null);
methods: {
refreshList() {
this.loadResource(
api.getNoteList()
.then(data => this.notes = data)
);
},
onBeforeMount(() => {
refreshList();
});
addNote() {
this.editNote = { id: null, content: "" };
},
function refreshList() {
loadResource(
api.getNoteList()
.then(data => notes.value = data)
);
}
saveNote() {
this.loadResource(
api.postNote(this.editNote)
function addNote() {
editNote.value = { id: null, content: "" };
}
function saveNote() {
loadResource(
api.postNote(editNote.value)
.then(() => {
this.editNote = null;
return this.refreshList();
editNote.value = null;
return refreshList();
})
);
},
);
}
cancelNote() {
this.editNote = null;
},
function cancelNote() {
editNote.value = null;
}
deleteNote(n) {
this.loadResource(
api.deleteNote(n)
function deleteNote(n) {
loadResource(
api.deleteNote(n)
.then(() => {
return this.refreshList();
return refreshList();
})
);
}
},
created() {
this.refreshList();
},
components: {
NoteEdit
}
);
}
</script>

View File

@ -22,58 +22,43 @@
</div>
</template>
<script>
<script setup>
import { computed, ref, watch } from "vue";
import { useRoute } from "vue-router";
import RecipeShow from "./RecipeShow";
import api from "../lib/Api";
import { useLoadResource } from "../lib/useLoadResource";
export default {
data: function () {
return {
recipe: null,
showNutrition: false
}
},
const route = useRoute();
const { loadResource } = useLoadResource();
const recipe = ref(null);
computed: {
recipeId() { return this.$route.params.id },
routeQuery() { return this.$route.query },
scale() { return this.$route.query.scale || null },
system() { return this.$route.query.system || null },
unit() { return this.$route.query.unit || null },
const recipeId = computed(() => route.params.id);
const scale = computed(() => route.query.scale || null);
const system = computed(() => route.query.system || null);
const unit = computed(() => route.query.unit || null);
const isScaled = computed(() => recipe.value?.converted_scale?.length !== undefined && recipe.value.converted_scale.length > 0 && recipe.value.converted_scale !== "1");
isScaled() {
return this.recipe.converted_scale !== null && this.recipe.converted_scale.length > 0 && this.recipe.converted_scale !== "1";
}
},
watch(
() => route.query,
() => refreshData(),
{ immediate: true }
);
watch: {
routeQuery() {
this.refreshData();
},
recipe(newRecipe) {
watch(
() => recipe.value?.name,
(newRecipe) => {
if (newRecipe) {
document.title = `${newRecipe.name}`;
}
}
},
)
methods: {
refreshData() {
this.loadResource(
api.getRecipe(this.recipeId, this.scale, this.system, this.unit, data => this.recipe = data)
);
}
},
created() {
this.refreshData();
},
components: {
RecipeShow
}
function refreshData() {
loadResource(
api.getRecipe(recipeId.value, scale.value, system.value, unit.value, data => recipe.value = data)
);
}
</script>

View File

@ -13,44 +13,38 @@
</div>
</template>
<script>
<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import RecipeEdit from "./RecipeEdit";
import api from "../lib/Api";
import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
export default {
data() {
return {
validationErrors: {},
recipe: {
name: null,
source: null,
description: null,
yields: null,
total_time: null,
active_time: null,
step_text: null,
tags: [],
ingredients: []
}
}
},
const router = useRouter();
const { loadResource } = useLoadResource();
methods: {
save() {
this.validationErrors = {};
this.loadResource(
api.postRecipe(this.recipe)
.then(() => this.$router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
);
}
},
const validationErrors = ref({});
const recipe = ref({
name: null,
source: null,
description: null,
yields: null,
total_time: null,
active_time: null,
step_text: null,
tags: [],
ingredients: []
});
components: {
RecipeEdit
}
function save() {
validationErrors.value = {};
loadResource(
api.postRecipe(recipe.value)
.then(() => router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
);
}
</script>

View File

@ -18,48 +18,39 @@
</div>
</template>
<script>
<script setup>
import { computed, onBeforeMount, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useLoadResource } from "../lib/useLoadResource";
import RecipeEdit from "./RecipeEdit";
import api from "../lib/Api";
import * as Errors from '../lib/Errors';
export default {
data: function () {
return {
recipe: null,
validationErrors: {}
}
},
const { loadResource } = useLoadResource();
const route = useRoute();
const router = useRouter();
const recipe = ref(null);
const validationErrors = ref({});
computed: {
recipeId() {
return this.$route.params.id;
}
},
const recipeId = computed(() => route.params.id);
methods: {
save() {
this.validationErrors = {};
this.loadResource(
api.patchRecipe(this.recipe)
.then(() => this.$router.push({name: 'recipe', params: {id: this.recipeId }}))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
);
}
},
onBeforeMount(() => {
loadResource(
api.getRecipe(recipeId.value, null, null, null, data => { recipe.value = data; return data; })
);
});
created() {
this.loadResource(
api.getRecipe(this.recipeId, null, null, null, data => { this.recipe = data; return data; })
);
},
components: {
RecipeEdit
}
function save() {
validationErrors.value = {};
loadResource(
api.patchRecipe(recipe.value)
.then(() => router.push({name: 'recipe', params: {id: recipeId.value }}))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
);
}
</script>
<style lang="scss" scoped>

View File

@ -42,7 +42,7 @@
</div>
</td>
<td>
<app-rating v-if="r.rating !== null" :value="r.rating" readonly></app-rating>
<app-rating v-if="r.rating !== null" :model-value="r.rating" readonly></app-rating>
<span v-else>--</span>
</td>
<td>{{ r.yields }}</td>
@ -85,7 +85,7 @@
</div>
<app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="recipe" @changePage="changePage"></app-pager>
<app-confirm :open="showConfirmRecipeDelete" :message="confirmRecipeDeleteMessage" :cancel="recipeDeleteCancel" :confirm="recipeDeleteConfirm"></app-confirm>
<app-confirm :open="showConfirmRecipeDelete" title="Delete Recipe?" :message="confirmRecipeDeleteMessage" @cancel="recipeDeleteCancel" @confirm="recipeDeleteConfirm"></app-confirm>
</div>
</template>

View File

@ -22,15 +22,16 @@
</div>
</template>
<script>
<script setup>
import { computed, onBeforeMount, ref } from "vue";
import * as Errors from '../lib/Errors';
import { mapActions, mapState } from "pinia";
import { useTaskStore } from "../stores/task";
import TaskListMiniForm from "./TaskListMiniForm";
import TaskListDropdownItem from "./TaskListDropdownItem";
import TaskItemList from "./TaskItemList";
import { useLoadResource } from "../lib/useLoadResource";
const newListTemplate = function() {
return {
@ -38,82 +39,52 @@
};
};
export default {
data() {
return {
showListDropdown: false,
newList: newListTemplate(),
newListValidationErrors: {}
}
},
const { loadResource } = useLoadResource();
const taskStore = useTaskStore();
computed: {
...mapState(useTaskStore, [
'taskLists',
'currentTaskList'
]),
listSelectLabel() {
if (this.currentTaskList === null) {
return "Select or Create a List";
} else {
return this.currentTaskList.name;
}
}
},
const showListDropdown = ref(false);
const newList = ref(newListTemplate());
const newListValidationErrors = ref({});
methods: {
...mapActions(useTaskStore, [
'refreshTaskLists',
'createTaskList',
'deleteTaskList',
'deleteTaskItems',
'completeTaskItems',
'setCurrentTaskList'
]),
selectList(list) {
this.setCurrentTaskList(list);
this.showListDropdown = false;
},
saveNewList() {
this.loadResource(
this.createTaskList(this.newList)
.then(() => this.showListDropdown = false)
.then(() => { this.newList = newListTemplate(); this.newListValidationErrors = {}; } )
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.newListValidationErrors = err.validationErrors()))
);
},
deleteList(list) {
this.loadResource(
this.deleteTaskList(list)
);
},
deleteAllItems() {
this.loadResource(
this.deleteTaskItems({
taskList: this.currentTaskList,
taskItems: this.currentTaskList.task_items
})
);
}
},
created() {
this.loadResource(
this.refreshTaskLists()
);
},
components: {
TaskListMiniForm,
TaskListDropdownItem,
TaskItemList
const taskLists = computed(() => taskStore.taskLists);
const currentTaskList = computed(() => taskStore.currentTaskList);
const listSelectLabel = computed(() => {
if (currentTaskList.value === null) {
return "Select or Create a List";
} else {
return currentTaskList.value.name;
}
});
onBeforeMount(() => {
loadResource(taskStore.refreshTaskLists());
});
function selectList(list) {
taskStore.setCurrentTaskList(list);
showListDropdown.value = false;
}
function saveNewList() {
loadResource(
taskStore.createTaskList(newList.value)
.then(() => showListDropdown.value = false)
.then(() => { newList.value = newListTemplate(); newListValidationErrors.value = {}; } )
.catch(Errors.onlyFor(Errors.ApiValidationError, err => newListValidationErrors.value = err.validationErrors()))
);
}
function deleteList(list) {
loadResource(taskStore.deleteTaskList(list));
}
function deleteAllItems() {
loadResource(
taskStore.deleteTaskItems({
taskList: currentTaskList.value,
taskItems: currentTaskList.value.task_items
})
);
}
</script>

View File

@ -13,41 +13,37 @@
</div>
</template>
<script>
<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import UserEdit from "./UserEdit";
import api from "../lib/Api";
import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
import { useCheckAuthentication } from "../lib/useCheckAuthentication";
export default {
data() {
return {
validationErrors: {},
userObj: {
username: '',
full_name: '',
email: '',
password: '',
password_confirmation: ''
}
}
},
const { loadResource } = useLoadResource();
const { checkAuthentication } = useCheckAuthentication(loadResource);
const router = useRouter();
methods: {
save() {
this.validationErrors = {};
this.loadResource(
api.postUser(this.userObj)
.then(() => this.checkAuthentication())
.then(() => this.$router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
);
}
},
const validationErrors = ref({});
const userObj = ref({
username: '',
full_name: '',
email: '',
password: '',
password_confirmation: ''
});
components: {
UserEdit
}
function save() {
validationErrors.value = {};
loadResource(
api.postUser(userObj.value)
.then(() => checkAuthentication())
.then(() => router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
);
}
</script>

View File

@ -13,63 +13,56 @@
</div>
</template>
<script>
<script setup>
import { ref, watch } from "vue";
import { useRouter } from "vue-router";
import UserEdit from "./UserEdit";
import api from "../lib/Api";
import * as Errors from '../lib/Errors';
import { useAppConfigStore } from "../stores/appConfig";
import { useLoadResource } from "../lib/useLoadResource";
import { useCheckAuthentication } from "../lib/useCheckAuthentication";
export default {
data() {
return {
validationErrors: {},
userObj: null
}
},
const appConfig = useAppConfigStore();
const { loadResource } = useLoadResource();
const { checkAuthentication } = useCheckAuthentication(loadResource);
const router = useRouter();
created() {
this.refreshUser();
},
const validationErrors = ref({});
const userObj = ref(null);
watch: {
user() {
this.refreshUser();
}
},
watch(
() => appConfig.user,
() => refreshUser(),
{ immediate: true });
methods: {
refreshUser() {
if (this.user) {
this.userObj = {
username: this.user.username,
full_name: this.user.full_name,
email: this.user.email,
password: '',
password_confirmation: ''
};
} else {
this.userObj = null;
}
},
save() {
this.validationErrors = {};
this.loadResource(
api.patchUser(this.userObj)
.then(() => this.checkAuthentication())
.then(() => {
this.$router.push('/');
})
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
);
}
},
components: {
UserEdit
function refreshUser() {
if (appConfig.user) {
userObj.value = {
username: appConfig.user.username,
full_name: appConfig.user.full_name,
email: appConfig.user.email,
password: '',
password_confirmation: ''
};
} else {
userObj.value = null;
}
}
function save() {
validationErrors.value = {};
loadResource(
api.patchUser(userObj.value)
.then(() => checkAuthentication())
.then(() => {
router.push('/');
})
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
);
}
</script>
<style lang="scss" scoped>

View File

@ -3,21 +3,19 @@
<app-text-field label="Username" v-model="userObj.username"></app-text-field>
<app-text-field label="Name" v-model="userObj.full_name"></app-text-field>
<app-text-field label="Email" v-model="userObj.email"></app-text-field>
<app-text-field label="Password" v-model="userObj.password"></app-text-field>
<app-text-field label="Password Confirmation" v-model="userObj.password_confirmation"></app-text-field>
<app-text-field type="password" label="Password" v-model="userObj.password"></app-text-field>
<app-text-field type="password" label="Password Confirmation" v-model="userObj.password_confirmation"></app-text-field>
</div>
</template>
<script>
<script setup>
export default {
props: {
userObj: {
required: true,
type: Object
}
const props = defineProps({
userObj: {
required: true,
type: Object
}
}
});
</script>

View File

@ -45,58 +45,44 @@
</div>
</template>
<script>
<script setup>
import { mapActions, mapState } from "pinia";
import { computed, nextTick, ref, useTemplateRef } from "vue";
import { useAppConfigStore } from "../stores/appConfig";
import { useLoadResource } from "../lib/useLoadResource";
export default {
data() {
return {
showLogin: false,
error: '',
username: '',
password: ''
};
},
const appConfig = useAppConfigStore();
const { loadResource } = useLoadResource();
computed: {
...mapState(useAppConfigStore, [
'loginMessage'
]),
enableSubmit() {
return this.username !== '' && this.password !== '' && !this.isLoading;
}
},
const userNameElement = useTemplateRef("usernameInput");
methods: {
...mapActions(useAppConfigStore, [
'login'
]),
const showLogin = ref(false);
const error = ref('');
const username = ref("");
const password = ref("");
openDialog() {
this.showLogin = true;
this.$nextTick(() => this.$refs.usernameInput.focus());
},
const loginMessage = computed(() => appConfig.loginMessage);
const enableSubmit = computed(() => username.value !== "" && password.value !== "" && !appConfig.isLoading);
performLogin() {
if (this.username !== '' && this.password !== '') {
const params = {username: this.username, password: this.password};
function openDialog() {
showLogin.value = true;
nextTick(() => {
userNameElement.value.focus();
})
}
this.loadResource(
this.login(params)
function performLogin() {
if (username.value !== '' && password.value !== '') {
const params = {username: username.value, password: password.value};
loadResource(
appConfig.login(params)
.then(data => {
console.log(data);
if (data.success) {
this.showLogin = false;
showLogin.value = false;
}
})
);
}
}
},
components: {
);
}
}