forked from nextcloud/cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecipeEdit.vue
772 lines (747 loc) · 27.4 KB
/
RecipeEdit.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
<template>
<div class="wrapper">
<div class="overlay" :class="{ hidden: !overlayVisible }" />
<EditInputField
v-model="recipe['name']"
:field-type="'text'"
:field-label="t('cookbook', 'Name')"
/>
<EditInputField
v-model="recipe['description']"
:field-type="'markdown'"
:field-label="t('cookbook', 'Description')"
:reference-popup-enabled="true"
/>
<EditInputField
v-model="recipe['url']"
:field-type="'url'"
:field-label="t('cookbook', 'URL')"
/>
<EditImageField
v-model="recipe['image']"
:field-label="t('cookbook', 'Image')"
/>
<EditTimeField
v-model="prepTime"
:field-label="t('cookbook', 'Preparation time (hours:minutes)')"
/>
<EditTimeField
v-model="cookTime"
:field-label="t('cookbook', 'Cooking time (hours:minutes)')"
/>
<EditTimeField
v-model="totalTime"
:field-label="t('cookbook', 'Total time (hours:minutes)')"
/>
<EditMultiselect
v-model="recipe['recipeCategory']"
:field-label="t('cookbook', 'Category')"
:placeholder="t('cookbook', 'Choose category')"
:options="allCategories"
:taggable="true"
:multiple="false"
:loading="isFetchingCategories"
@tag="addCategory"
/>
<EditMultiselect
v-model="selectedKeywords"
:field-label="t('cookbook', 'Keywords')"
:placeholder="t('cookbook', 'Choose keywords')"
:options="allKeywords"
:taggable="true"
:multiple="true"
:tag-width="60"
:loading="isFetchingKeywords"
@tag="addKeyword"
/>
<EditInputField
v-model="recipe['recipeYield']"
:field-type="'number'"
:field-label="t('cookbook', 'Servings')"
/>
<EditMultiselectInputGroup
v-model="recipe['nutrition']"
:field-label="t('cookbook', 'Nutrition Information')"
:options="availableNutritionFields"
:label-select-placeholder="t('cookbook', 'Pick option')"
/>
<EditInputGroup
v-model="recipe['tool']"
:field-name="'tool'"
:field-type="'text'"
:field-label="t('cookbook', 'Tools')"
:create-fields-on-newlines="true"
:reference-popup-enabled="true"
/>
<EditInputGroup
v-model="recipe['recipeIngredient']"
:field-name="'recipeIngredient'"
:field-type="'text'"
:field-label="t('cookbook', 'Ingredients')"
:create-fields-on-newlines="true"
:reference-popup-enabled="true"
/>
<EditInputGroup
v-model="recipe['recipeInstructions']"
:field-name="'recipeInstructions'"
:field-type="'textarea'"
:field-label="t('cookbook', 'Instructions')"
:create-fields-on-newlines="true"
:show-step-number="true"
:reference-popup-enabled="true"
/>
<div class="cookbook-footer">
<button class="button" @click="save()">
<span
:class="
$store.state.savingRecipe
? 'icon-loading-small'
: 'icon-checkmark'
"
></span>
{{ t("cookbook", "Save changes") }}
</button>
</div>
<edit-multiselect-popup
ref="referencesPopup"
class="references-popup"
:class="{ visible: referencesPopupFocused }"
:options="allRecipeOptions"
track-by="recipe_id"
label="title"
:loading="loadingRecipeReferences"
:focused="referencesPopupFocused"
/>
</div>
</template>
<script>
import axios from "@nextcloud/axios"
import Vue from "vue"
import EditImageField from "./EditImageField.vue"
import EditInputField from "./EditInputField.vue"
import EditInputGroup from "./EditInputGroup.vue"
import EditMultiselect from "./EditMultiselect.vue"
import EditMultiselectInputGroup from "./EditMultiselectInputGroup.vue"
import EditMultiselectPopup from "./EditMultiselectPopup.vue"
import EditTimeField from "./EditTimeField.vue"
export default {
name: "RecipeEdit",
components: {
EditImageField,
EditInputField,
EditInputGroup,
EditMultiselect,
EditTimeField,
EditMultiselectInputGroup,
EditMultiselectPopup,
},
// We can check if the user has browsed from the same recipe's view to this
// edit and save some time by not reloading the recipe data, leading to a
// more seamless experience.
// This assumes that the data has not been changed some other way between
// loading the view component and loading this edit component. If that is
// the case, the user can always manually reload by clicking the breadcrumb.
beforeRouteEnter(to, from, next) {
if (window.isSameItemInstance(from.fullPath, to.fullPath)) {
next((vm) => {
vm.setup()
})
} else if (to.params && to.params.id) {
next((vm) => {
vm.loadRecipeData()
})
} else {
next((vm) => {
vm.setup()
})
}
},
/**
* This is one tricky feature of Vue router. If different paths lead to
* the same component (such as '/recipe/create' and '/recipe/xxx/edit
* or /recipe/xxx/edit and /recipe/yyy/edit)', the view will not automatically
* reload. So we have to check for these conditions and reload manually.
* This can also be used to confirm that the user wants to leave the page
* if there are unsaved changes.
*/
beforeRouteLeave(to, from, next) {
// beforeRouteLeave is called when the static route changes.
// Cancel the navigation, if the form has unsaved edits and the user did not
// confirm leave. This prevents accidentally losing changes
if (this.confirmStayInEditedForm()) {
next(false)
} else {
// We have to check if the target component stays the same and reload.
// However, we should not reload if the component changes; otherwise
// reloaded data may overwrite the data loaded at the target component
// which will at the very least result in incorrect breadcrumb path!
next()
}
// Check if we should reload the component content
if (this.$window.shouldReloadContent(from.fullPath, to.fullPath)) {
this.setup()
}
},
beforeRouteUpdate(to, from, next) {
// beforeRouteUpdate is called when the static route stays the same
next()
// Check if we should reload the component content
if (this.$window.shouldReloadContent(from.fullPath, to.fullPath)) {
this.setup()
}
},
props: {
id: {
type: String,
default: "",
},
},
data() {
return {
// Initialize the recipe schema, otherwise v-models in child components may not work
recipe: {
id: 0,
name: null,
description: "",
url: "",
image: "",
prepTime: "",
cookTime: "",
totalTime: "",
recipeCategory: "",
keywords: "",
recipeYield: "",
tool: [],
recipeIngredient: [],
recipeInstructions: [],
nutrition: {},
},
// This will hold the above configuration after recipe is loaded, so we don't have to
// keep it up to date in multiple places if it changes later
recipeInit: null,
// ==========================
// These are helper variables
// Changes have been made to the initial values of the form
formDirty: false,
// the save button has been clicked
savingRecipe: false,
prepTime: { time: [0, 0], paddedTime: "" },
cookTime: { time: [0, 0], paddedTime: "" },
totalTime: { time: [0, 0], paddedTime: "" },
allCategories: [],
isFetchingCategories: true,
isFetchingKeywords: true,
allKeywords: [],
selectedKeywords: [],
allRecipes: [],
availableNutritionFields: [
{
key: "calories",
label: t("cookbook", "Calories"),
// prettier-ignore
placeholder: t("cookbook","E.g.: 450 kcal (amount & unit)"),
},
{
key: "carbohydrateContent",
label: t("cookbook", "Carbohydrate content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
{
key: "cholesterolContent",
label: t("cookbook", "Cholesterol content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
{
key: "fatContent",
label: t("cookbook", "Fat content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
{
key: "fiberContent",
label: t("cookbook", "Fiber content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
{
key: "proteinContent",
label: t("cookbook", "Protein content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
{
key: "saturatedFatContent",
label: t("cookbook", "Saturated-fat content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
{
key: "servingSize",
label: t("cookbook", "Serving size"),
// prettier-ignore
placeholder: t("cookbook","Enter serving size (volume or mass)"),
},
{
key: "sodiumContent",
label: t("cookbook", "Sodium content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
{
key: "sugarContent",
label: t("cookbook", "Sugar content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
{
key: "transFatContent",
label: t("cookbook", "Trans-fat content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
{
key: "unsaturatedFatContent",
label: t("cookbook", "Unsaturated-fat content"),
placeholder: t("cookbook", "E.g.: 2 g (amount & unit)"),
},
],
referencesPopupFocused: false,
popupContext: undefined,
loadingRecipeReferences: true,
}
},
computed: {
allRecipeOptions() {
return this.allRecipes.map((r) => ({
recipe_id: r.recipe_id,
title: `${r.recipe_id}: ${r.name}`,
}))
},
categoryUpdating() {
return this.$store.state.categoryUpdating
},
overlayVisible() {
return (
this.$store.state.loadingRecipe ||
this.$store.state.reloadingRecipe ||
(this.$store.state.categoryUpdating &&
this.$store.state.categoryUpdating ===
this.recipe.recipeCategory)
)
},
},
watch: {
prepTime: {
handler() {
this.recipe.prepTime = this.prepTime.paddedTime
},
deep: true,
},
cookTime: {
handler() {
this.recipe.cookTime = this.cookTime.paddedTime
},
deep: true,
},
totalTime: {
handler() {
this.recipe.totalTime = this.totalTime.paddedTime
},
deep: true,
},
selectedKeywords: {
deep: true,
handler() {
// convert keyword array to comma-separated string
this.recipe.keywords = this.selectedKeywords.join()
},
},
recipe: {
deep: true,
handler() {
this.formDirty = true
},
},
},
mounted() {
const $this = this
// Store the initial recipe configuration for possible later use
if (this.recipeInit === null) {
this.recipeInit = this.recipe
}
// Register save method hook for access from the controls components
// The event hookmust first be destroyed to avoid it from firing multiple
// times if the same component is loaded again
this.$root.$off("saveRecipe")
this.$root.$on("saveRecipe", () => {
this.save()
})
// Register data load method hook for access from the controls components
this.$root.$off("reloadRecipeEdit")
this.$root.$on("reloadRecipeEdit", () => {
this.loadRecipeData()
})
this.$root.$off("categoryRenamed")
this.$root.$on("categoryRenamed", (val) => {
// Update selectable categories
const idx = this.allCategories.findIndex((c) => c === val[1])
if (idx >= 0) {
Vue.set(this.allCategories, idx, val[0])
// this.allCategories[idx] = val[0]
}
// Update selected category if the currently selected was renamed
if (this.recipe.recipeCategory === val[1]) {
// eslint-disable-next-line prefer-destructuring
this.recipe.recipeCategory = val[0]
}
})
// Register recipe-reference selection hook for showing popup when requested
// from a child element
this.$off("showRecipeReferencesPopup")
this.$on("showRecipeReferencesPopup", (val) => {
this.referencesPopupFocused = true
this.popupContext = val
})
// Register hook when recipe reference has been selected in popup
this.$off("ms-popup-selected")
this.$on("ms-popup-selected", (opt) => {
this.referencesPopupFocused = false
this.popupContext.context.pasteString(`r/${opt.recipe_id} `)
})
// Register hook when recipe reference has been selected in popup
this.$off("ms-popup-selection-canceled")
this.$on("ms-popup-selection-canceled", () => {
this.referencesPopupFocused = false
this.popupContext.context.pasteCanceled()
})
this.savingRecipe = false
// Load data for all recipes to be used in recipe-reference popup suggestions
axios
.get(`${this.$window.baseUrl}/api/recipes`)
.then((response) => {
$this.allRecipes = response.data
})
.catch((e) => {
// eslint-disable-next-line no-console
console.log(e)
})
.then(() => {
// finally
$this.loadingRecipeReferences = false
})
},
beforeDestroy() {
window.removeEventListener("beforeunload", this.beforeWindowUnload)
},
created() {
window.addEventListener("beforeunload", this.beforeWindowUnload)
},
methods: {
/**
* Add newly created category and set as selected.
*/
addCategory(newCategory) {
this.allCategories.push(newCategory)
this.recipe.recipeCategory = newCategory
},
/**
* Add newly created keyword.
*/
addKeyword(newKeyword) {
this.allKeywords.push(newKeyword)
this.selectedKeywords.push(newKeyword)
},
addEntry(field, index, content = "") {
this.recipe[field].splice(index, 0, content)
},
beforeWindowUnload(e) {
if (this.confirmStayInEditedForm()) {
// Cancel the window unload event
e.preventDefault()
e.returnValue = ""
}
},
confirmLeavingPage() {
// eslint-disable-next-line no-alert
return window.confirm(
// prettier-ignore
t("cookbook", "You have unsaved changes! Do you still want to leave?")
)
},
confirmStayInEditedForm() {
return (
!this.savingRecipe &&
this.formDirty &&
!this.confirmLeavingPage()
)
},
deleteEntry(field, index) {
this.recipe[field].splice(index, 1)
},
/**
* Fetch and display recipe categories
*/
fetchCategories() {
const $this = this
axios
.get(`${this.$window.baseUrl}/categories`)
.then((response) => {
const json = response.data || []
$this.allCategories = []
for (let i = 0; i < json.length; i++) {
if (json[i].name !== "*") {
$this.allCategories.push(json[i].name)
}
}
$this.isFetchingCategories = false
})
.catch((e) => {
// eslint-disable-next-line no-alert
alert(t("cookbook", "Failed to fetch categories"))
if (e && e instanceof Error) {
throw e
}
})
},
/**
* Fetch and display recipe keywords
*/
fetchKeywords() {
const $this = this
axios
.get(`${this.$window.baseUrl}/keywords`)
.then((response) => {
const json = response.data || []
if (json) {
$this.allKeywords = []
for (let i = 0; i < json.length; i++) {
if (json[i].name !== "*") {
$this.allKeywords.push(json[i].name)
}
}
}
$this.isFetchingKeywords = false
})
.catch((e) => {
// eslint-disable-next-line no-alert
alert(t("cookbook", "Failed to fetch keywords"))
if (e && e instanceof Error) {
throw e
}
})
},
loadRecipeData() {
if (!this.$store.state.recipe) {
// Make the control row show that a recipe is loading
this.$store.dispatch("setLoadingRecipe", {
recipe: -1,
})
} else if (
this.$store.state.recipe.id ===
parseInt(this.$route.params.id, 10)
) {
// Make the control row show that the recipe is reloading
this.$store.dispatch("setReloadingRecipe", {
recipe: this.$route.params.id,
})
}
const $this = this
axios
.get(
`${this.$window.baseUrl}/api/recipes/${this.$route.params.id}`
)
.then((response) => {
const recipe = response.data
$this.$store.dispatch("setRecipe", { recipe })
$this.setup()
})
.catch(() => {
// eslint-disable-next-line no-alert
alert(t("cookbook", "Loading recipe failed"))
// Disable loading indicator
if ($this.$store.state.loadingRecipe) {
$this.$store.dispatch("setLoadingRecipe", { recipe: 0 })
} else if ($this.$store.state.reloadingRecipe) {
$this.$store.dispatch("setReloadingRecipe", {
recipe: 0,
})
}
// Browse to new recipe creation
$this.$window.goTo("/recipe/create")
})
},
save() {
this.savingRecipe = true
this.$store.dispatch("setSavingRecipe", { saving: true })
const $this = this
const request = (() => {
if (this.recipe_id) {
return this.$store.dispatch("updateRecipe", {
recipe: this.recipe,
})
}
return this.$store.dispatch("createRecipe", {
recipe: this.recipe,
})
})()
request
.then((response) => {
$this.$window.goTo(`/recipe/${response.data}`)
})
.catch((e) => {
// error
if (e.response) {
// Non 2xx state returned
switch (e.response.status) {
case 409:
// eslint-disable-next-line no-alert
alert(e.response.data.msg)
break
default:
// eslint-disable-next-line no-alert
alert(
// prettier-ignore
t("cookbook","Unknown answer returned from server. See logs.")
)
// eslint-disable-next-line no-console
console.log(e.response)
}
} else if (e.request) {
// eslint-disable-next-line no-alert
alert(
t("cookbook", "No answer for request was received.")
)
// eslint-disable-next-line no-console
console.log(e)
} else {
// eslint-disable-next-line no-alert
alert(
// prettier-ignore
t("cookbook","Could not start request to save recipe.")
)
// eslint-disable-next-line no-console
console.log(e)
}
})
.then(() => {
// finally
$this.$store.dispatch("setSavingRecipe", {
saving: false,
})
$this.savingRecipe = false
})
},
setup() {
this.fetchCategories()
this.fetchKeywords()
if (this.$route.params.id) {
// Load the recipe from store and make edits to a local copy first
this.recipe = { ...this.$store.state.recipe }
// Parse time values
let timeComps = this.recipe.prepTime
? this.recipe.prepTime.match(/PT(\d+?)H(\d+?)M/)
: null
this.prepTime = {
time: timeComps ? [timeComps[1], timeComps[2]] : [0, 0],
paddedTime: this.recipe.prepTime,
}
timeComps = this.recipe.cookTime
? this.recipe.cookTime.match(/PT(\d+?)H(\d+?)M/)
: null
this.cookTime = {
time: timeComps ? [timeComps[1], timeComps[2]] : [0, 0],
paddedTime: this.recipe.cookTime,
}
timeComps = this.recipe.totalTime
? this.recipe.totalTime.match(/PT(\d+?)H(\d+?)M/)
: null
this.totalTime = {
time: timeComps ? [timeComps[1], timeComps[2]] : [0, 0],
paddedTime: this.recipe.totalTime,
}
this.selectedKeywords = this.recipe.keywords
.split(",")
.map((kw) => kw.trim())
// Remove any empty keywords
// If the response from the server is just an empty
// string, split will create an array of a single empty
// string
.filter((kw) => kw !== "")
// fallback if fetching all keywords fails
this.selectedKeywords.forEach((kw) => {
if (!this.allKeywords.includes(kw)) {
this.allKeywords.push(kw)
}
})
// fallback if fetching all categories fails
if (!this.allCategories.includes(this.recipe.recipeCategory)) {
this.allCategories.push(this.recipe.recipeCategory)
}
// Always set the active page last!
this.$store.dispatch("setPage", { page: "edit" })
} else {
this.initEmptyRecipe()
this.$store.dispatch("setPage", { page: "create" })
}
this.recipeInit = JSON.parse(JSON.stringify(this.recipe))
this.$nextTick(function markDirty() {
this.formDirty = false
})
},
initEmptyRecipe() {
this.prepTime = { time: [0, 0], paddedTime: "" }
this.cookTime = { time: [0, 0], paddedTime: "" }
this.totalTime = { time: [0, 0], paddedTime: "" }
this.nutrition = {}
this.recipe = {
id: 0,
name: null,
description: "",
url: "",
image: "",
prepTime: "",
cookTime: "",
totalTime: "",
recipeCategory: "",
keywords: "",
recipeYield: "",
tool: [],
recipeIngredient: [],
recipeInstructions: [],
nutrition: {},
}
this.formDirty = false
},
},
}
</script>
<style scoped>
.wrapper {
width: 100%;
padding: 1rem;
}
.overlay {
position: absolute;
z-index: 1000;
top: 0;
left: 0;
display: block;
width: 100%;
height: 100%;
background-color: var(--color-main-background);
opacity: 0.75;
}
.overlay.hidden {
display: none;
}
/* This is not used anywhere at the moment, but left here for future reference
form fieldset ul label input[type="checkbox"] {
margin-left: 1em;
vertical-align: middle;
cursor: pointer;
} */
.references-popup {
position: fixed;
display: none;
}
.references-popup.visible {
display: block;
}
.cookbook-footer {
margin-top: 3.5em;
text-align: end;
}
</style>