Compare commits

..

9 Commits

Author SHA1 Message Date
Jesse Brault
aa28f8d100 Prettier. 2026-01-29 18:11:15 -06:00
Jesse Brault
c02e78d27d More e2e of recipe upload. 2026-01-29 17:23:10 -06:00
Jesse Brault
09490514b1 Placeholder image/logo for recipes without mainImages. 2026-01-28 18:34:51 -06:00
Jesse Brault
14acdc3e83 Prettier. 2026-01-28 18:17:50 -06:00
Jesse Brault
b42971703f All steps basically working, much more todo. 2026-01-28 18:17:31 -06:00
Jesse Brault
ff9ffd9e13 Recipe upload integration with backend WIP. 2026-01-28 15:41:10 -06:00
Jesse Brault
6e6bf04541 Prettier. 2026-01-26 13:14:55 -06:00
Jesse Brault
13a282f71f Some auth route guard and link refactoring. 2026-01-25 18:17:35 -06:00
Jesse Brault
08d21631e2 Use environments for base api url; some service url refactoring. 2026-01-25 17:50:14 -06:00
49 changed files with 869 additions and 355 deletions

View File

@ -46,7 +46,13 @@
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
"sourceMap": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
]
}
},
"defaultConfiguration": "production"

View File

@ -33,7 +33,6 @@
"@fortawesome/angular-fontawesome": "^4.0.0",
"@fortawesome/free-solid-svg-icons": "^7.1.0",
"@tanstack/angular-query-experimental": "^5.90.16",
"ngx-sse-client": "^20.0.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},

View File

@ -3,6 +3,7 @@ import { RecipePage } from './pages/recipe-page/recipe-page';
import { RecipesPage } from './pages/recipes-page/recipes-page';
import { RecipesSearchPage } from './pages/recipes-search-page/recipes-search-page';
import { RecipeUploadPage } from './pages/recipe-upload-page/recipe-upload-page';
import { authGuard } from './shared/guards/auth-guard';
export const routes: Routes = [
{
@ -16,6 +17,7 @@ export const routes: Routes = [
{
path: 'recipe-upload',
component: RecipeUploadPage,
canActivate: [authGuard],
},
{
path: 'recipes/:username/:slug',

View File

@ -1,3 +1,7 @@
export const Endpoints = {
authLogin: 'auth/login',
authLogout: 'auth/logout',
authRefresh: 'auth/refresh',
recipes: 'recipes',
recipeDrafts: 'recipe-drafts',
};

View File

@ -31,14 +31,17 @@
</div>
</div>
@if (mainImageUrl.isSuccess()) {
@let maybeMainImageUrl = mainImageUrl.data();
@if (!!maybeMainImageUrl) {
<img
id="main-image"
[src]="mainImageUrl.data()"
[alt]="recipe.mainImage.alt"
[height]="recipe.mainImage.height"
[width]="recipe.mainImage.width"
[src]="maybeMainImageUrl"
[alt]="recipe.mainImage!.alt"
[height]="recipe.mainImage!.height"
[width]="recipe.mainImage!.width"
/>
}
}
<div [innerHTML]="recipe.text"></div>
<app-recipe-comments-list [recipeUsername]="recipe.owner.username" [recipeSlug]="recipe.slug" />
</article>

View File

@ -27,8 +27,8 @@ export class RecipePageContent {
protected readonly mainImageUrl = injectQuery(() => {
const recipe = this.recipeView().recipe;
return {
queryKey: ['images', recipe.mainImage.owner.username, recipe.mainImage.filename],
queryFn: () => this.imageService.getImage(recipe.mainImage.url),
queryKey: ['recipe-main-images', recipe.owner.username, recipe.slug],
queryFn: () => this.imageService.getImage(recipe.mainImage?.url),
};
});

View File

@ -1,51 +0,0 @@
#recipe-upload-container {
display: flex;
flex-direction: column;
row-gap: 5px;
}
form {
display: flex;
width: 100%;
flex-direction: column;
row-gap: 5px;
}
#recipe-upload-form {
width: 66%;
}
.action-buttons-container {
width: 100%;
display: flex;
column-gap: 5px;
}
/*button {*/
/* width: 100%;*/
/*}*/
/*input[type="text"],*/
/*textarea {*/
/* padding: 10px;*/
/* font-size: 16px;*/
/*}*/
textarea {
box-sizing: border-box;
height: auto;
overflow: hidden;
resize: none;
}
#recipe-form-and-source {
display: grid;
grid-template-columns: 1fr 1fr;
column-gap: 10px;
justify-items: flex-start;
}
#recipe-form-and-source div,
#recipe-form-and-source div img {
width: 100%;
}

View File

@ -1,65 +1,25 @@
<div id="recipe-upload-container">
<h1>Upload Recipe</h1>
<app-recipe-upload-trail
<h1>Upload Recipe</h1>
<app-recipe-upload-trail
[displayStep]="displayStep()"
[inProgressStep]="inProgressStep()"
[includeInfer]="includeInfer()"
(stepClick)="onStepClick($event)"
></app-recipe-upload-trail>
></app-recipe-upload-trail>
@if (displayStep() === RecipeUploadStep.START) {
@if (displayStep() === RecipeUploadStep.START) {
<app-ai-or-manual
[sourceFile]="sourceFile()"
(sourceFileChange)="onSourceFileChange($event)"
(submitStep)="onAiOrManualSubmit($event)"
></app-ai-or-manual>
} @else if (displayStep() === RecipeUploadStep.INFER) {
} @else if (displayStep() === RecipeUploadStep.INFER) {
<app-infer></app-infer>
} @else if (displayStep() === RecipeUploadStep.ENTER_DATA) {
<app-enter-recipe-data [model]="model()"></app-enter-recipe-data>
}
<!--
<section>
<h2>Auto-Complete Recipe (Optional)</h2>
<p>Choose a photo of a recipe from your files, and AI will fill out the form below for you.</p>
<form id="recipe-upload-form" [formGroup]="recipeUploadForm" (ngSubmit)="onFileSubmit()">
<input id="file" type="file" (change)="onFileChange($event)" />
<div class="action-buttons-container">
<button matButton="outlined" type="button" (click)="onClear()">Clear</button>
<button matButton="filled" type="submit" [disabled]="!recipeUploadForm.valid || inferenceInProgress()">
AI Auto-Complete
</button>
<app-spinner [enabled]="inferenceInProgress()"></app-spinner>
</div>
</form>
</section>
<section>
<h2>Recipe Form</h2>
<div id="recipe-form-and-source">
<form [formGroup]="recipeForm" (ngSubmit)="onRecipeSubmit()">
<mat-form-field>
<mat-label>Recipe Title</mat-label>
<input matInput id="recipe-title" type="text" formControlName="title" />
</mat-form-field>
<mat-form-field>
<mat-label>Recipe Text</mat-label>
<textarea
matInput
id="recipe-text"
formControlName="recipeText"
(input)="onRecipeTextChange($event)"
></textarea>
</mat-form-field>
<button matButton="filled" type="submit" [disabled]="!recipeForm.valid || inferenceInProgress()">Add Recipe</button>
</form>
<div>
@if (sourceRecipeImage()) {
<img [src]="sourceRecipeImage()" alt="Your source recipe image." />
}
</div>
</div>
</section>
-->
</div>
} @else if (displayStep() === RecipeUploadStep.ENTER_DATA) {
<app-enter-recipe-data
[model]="model()"
(submit)="onEnterRecipeDataSubmit($event)"
(deleteDraft)="onDeleteDraft()"
></app-enter-recipe-data>
} @else if (displayStep() === RecipeUploadStep.REVIEW) {
<app-review [draft]="model().draft!" (publish)="onPublish()"></app-review>
}

View File

@ -7,59 +7,68 @@ import { EnterRecipeData } from './steps/enter-recipe-data/enter-recipe-data';
import { RecipeUploadTrail } from './recipe-upload-trail/recipe-upload-trail';
import { ActivatedRoute, Router } from '@angular/router';
import { StepClickEvent } from './recipe-upload-trail/StepClickEvent';
import { RecipeUploadModel } from '../../shared/client-models/RecipeUploadModel';
import { RecipeUploadService } from '../../shared/services/RecipeUploadService';
import { RecipeUploadClientModel } from '../../shared/client-models/RecipeUploadClientModel';
import { RecipeDraftService } from '../../shared/services/RecipeDraftService';
import { RecipeUploadStep } from '../../shared/client-models/RecipeUploadStep';
import { FileUploadEvent } from '../../shared/components/file-upload/FileUploadEvent';
import { tryMaybeInt } from '../../shared/util';
import { from, map, switchMap, tap } from 'rxjs';
import { Review } from './steps/review/review';
import { EnterRecipeDataSubmitEvent } from './steps/enter-recipe-data/EnterRecipeDataSubmitEvent';
import { QueryClient } from '@tanstack/angular-query-experimental';
@Component({
selector: 'app-recipe-upload-page',
imports: [ReactiveFormsModule, AiOrManual, Infer, EnterRecipeData, RecipeUploadTrail],
imports: [ReactiveFormsModule, AiOrManual, Infer, EnterRecipeData, RecipeUploadTrail, Review],
templateUrl: './recipe-upload-page.html',
styleUrl: './recipe-upload-page.css',
})
export class RecipeUploadPage implements OnInit {
protected readonly model = signal<RecipeUploadModel>({
protected readonly model = signal<RecipeUploadClientModel>({
inProgressStep: RecipeUploadStep.START,
});
protected readonly displayStep = signal<number>(RecipeUploadStep.START);
protected readonly inProgressStep = computed(() => this.model().inProgressStep);
protected readonly includeInfer = signal(false);
protected readonly sourceFile = computed(() => this.model().sourceFile ?? null);
protected readonly sourceFile = computed(() => this.model().inputSourceFile ?? null);
private readonly router = inject(Router);
private readonly activatedRoute = inject(ActivatedRoute);
private readonly recipeUploadService = inject(RecipeUploadService);
private readonly recipeDraftService = inject(RecipeDraftService);
private readonly queryClient = inject(QueryClient);
private isValidStep(step: number): boolean {
if (this.model().draft?.lastInference || this.model().draft?.state === 'INFER') {
return step <= RecipeUploadStep.REVIEW;
} else {
return [0, 2, 3].includes(step);
}
}
public ngOnInit(): void {
this.activatedRoute.queryParamMap
.pipe(
map((paramMap) => {
const draftIdParam: string | null = paramMap.get('draftId');
const draftId = tryMaybeInt(draftIdParam);
const stepParam: string | null = paramMap.get('step');
const step = tryMaybeInt(stepParam);
return [draftId, step];
return [paramMap.get('draftId'), step] as const;
}),
switchMap(([draftId, step]) => {
const currentModel = this.model();
if (draftId !== null && currentModel.id !== draftId) {
return this.recipeUploadService.getRecipeUploadModel(draftId).pipe(
tap((updatedModel) => {
this.model.set(updatedModel);
if (draftId !== null) {
return this.recipeDraftService.getRecipeUploadClientModel(draftId).pipe(
tap(async (recipeUploadClientModel) => {
await this.switchModel(recipeUploadClientModel);
}),
switchMap((updatedModel) => {
if (step !== null && step <= updatedModel.inProgressStep) {
if (step !== null && this.isValidStep(step)) {
return from(this.changeDisplayStep(step));
} else {
return from(this.changeDisplayStep(updatedModel.inProgressStep));
}
}),
);
} else if (step !== null && step <= currentModel.inProgressStep) {
} else if (step !== null && this.isValidStep(step)) {
return from(this.changeDisplayStep(step));
} else {
return from(this.changeDisplayStep(RecipeUploadStep.START));
@ -69,15 +78,28 @@ export class RecipeUploadPage implements OnInit {
.subscribe();
}
private async switchModel(
model: RecipeUploadClientModel,
switchStep: boolean | RecipeUploadStep = false,
): Promise<void> {
this.model.set(model);
this.includeInfer.set(!!model.draft?.lastInference);
if (switchStep === true) {
await this.changeDisplayStep(model.inProgressStep);
} else if (typeof switchStep === 'number') {
await this.changeDisplayStep(switchStep);
}
}
private async changeDisplayStep(targetStep: number): Promise<void> {
this.displayStep.set(targetStep);
await this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
draftId: this.model().draft?.id,
step: targetStep,
draftId: this.model().id,
},
queryParamsHandling: 'merge',
queryParamsHandling: 'replace',
});
}
@ -89,124 +111,57 @@ export class RecipeUploadPage implements OnInit {
if (event._tag === 'file-add-event') {
this.model.update((model) => ({
...model,
sourceFile: event.file,
inputSourceFile: event.file,
}));
} else {
this.model.update((model) => ({
...model,
sourceFile: null,
inputSourceFile: null,
}));
}
}
protected async onAiOrManualSubmit(event: AIOrManualSubmitEvent): Promise<void> {
if (event.mode === 'manual') {
this.model.update((model) => ({
...model,
sourceFile: null,
inProgressStep: RecipeUploadStep.ENTER_DATA,
}));
await this.changeDisplayStep(RecipeUploadStep.ENTER_DATA);
this.includeInfer.set(false);
const model = await this.recipeDraftService.createManualDraft();
await this.switchModel(model, true);
} else {
this.model.update((model) => ({
...model,
sourceFile: this.sourceFile(),
inputSourceFile: this.sourceFile(),
inProgressStep: RecipeUploadStep.INFER,
}));
await this.changeDisplayStep(RecipeUploadStep.INFER);
this.includeInfer.set(true);
this.recipeUploadService.doInference(this.model()).subscribe((updatedModel) => {
this.recipeDraftService.doInference(this.model()).subscribe((updatedModel) => {
this.model.set(updatedModel);
this.changeDisplayStep(RecipeUploadStep.ENTER_DATA);
});
}
}
// private readonly sseClient = inject(SseClient);
// private readonly formBuilder = inject(FormBuilder);
//
// protected readonly sourceRecipeImage = signal<string | null>(null);
// protected readonly inferenceInProgress = signal(false);
//
// protected readonly recipeUploadForm = this.formBuilder.group({
// file: this.formBuilder.control<File | null>(null, [Validators.required]),
// });
//
// protected readonly recipeForm = new FormGroup({
// title: new FormControl('', [Validators.required]),
// recipeText: new FormControl('', Validators.required),
// });
//
// protected onClear() {
// this.recipeUploadForm.reset();
// this.sourceRecipeImage.set(null);
// }
//
// protected onFileChange(event: Event) {
// const fileInput = event.target as HTMLInputElement;
// if (fileInput.files && fileInput.files.length) {
// const file = fileInput.files[0];
// this.recipeUploadForm.controls.file.setValue(file);
// this.recipeUploadForm.controls.file.markAsTouched();
// this.recipeUploadForm.controls.file.updateValueAndValidity();
//
// // set source image
// this.sourceRecipeImage.set(URL.createObjectURL(file));
// }
// }
//
// protected onFileSubmit() {
// const rawValue = this.recipeUploadForm.getRawValue();
//
// this.inferenceInProgress.set(true);
//
// // upload form data
// const formData = new FormData();
// formData.append('recipeImageFile', rawValue.file!, rawValue.file!.name);
// this.sseClient
// .stream(
// `http://localhost:8080/inferences/recipe-extract-stream`,
// {
// keepAlive: false,
// reconnectionDelay: 1000,
// responseType: 'event',
// },
// {
// body: formData,
// },
// 'PUT',
// )
// .subscribe({
// next: (event) => {
// if (event.type === 'error') {
// const errorEvent = event as ErrorEvent;
// console.error(errorEvent.error, errorEvent.message);
// } else {
// const messageEvent = event as MessageEvent;
// const data: { delta: string } = JSON.parse(messageEvent.data);
// this.recipeForm.patchValue({
// recipeText: this.recipeForm.value.recipeText + data.delta,
// });
//
// // must do this so we auto-resize the textarea
// document.getElementById('recipe-text')?.dispatchEvent(new Event('input', { bubbles: true }));
// }
// },
// complete: () => {
// this.inferenceInProgress.set(false);
// },
// });
// }
//
// protected onRecipeSubmit() {
// console.log(this.recipeForm.value);
// }
//
// protected onRecipeTextChange(event: Event) {
// const textarea = event.target as HTMLTextAreaElement;
// textarea.style.height = 'auto';
// textarea.style.height = textarea.scrollHeight + 'px';
// }
protected async onEnterRecipeDataSubmit(event: EnterRecipeDataSubmitEvent): Promise<void> {
const model = await this.recipeDraftService.updateDraft(this.model().draft!.id, event);
await this.switchModel(model, RecipeUploadStep.REVIEW);
}
protected async onDeleteDraft(): Promise<void> {
await this.recipeDraftService.deleteDraft(this.model().draft!.id);
await this.queryClient.invalidateQueries({
queryKey: ['recipe-upload', 'in-progress-drafts'],
});
await this.switchModel(
{
inProgressStep: RecipeUploadStep.START,
},
RecipeUploadStep.START,
);
}
protected async onPublish(): Promise<void> {
const recipe = await this.recipeDraftService.publish(this.model().draft!.id);
await this.router.navigate(['recipes', recipe.owner.username, recipe.slug]);
}
protected readonly RecipeUploadStep = RecipeUploadStep;
}

View File

@ -5,7 +5,7 @@
'step-complete': step.completed,
'step-in-progress': step.inProgress,
'step-incomplete': !step.completed,
'step-displayed': displayStep() === step.index
'step-displayed': displayStep() === step.index,
}"
>
@if (step.completed || step.inProgress) {

View File

@ -34,6 +34,12 @@ export class RecipeUploadTrail {
completed: this.inProgressStep() > RecipeUploadStep.ENTER_DATA,
inProgress: this.inProgressStep() === RecipeUploadStep.ENTER_DATA,
},
{
index: RecipeUploadStep.REVIEW,
name: 'Review',
completed: this.inProgressStep() > RecipeUploadStep.REVIEW,
inProgress: this.inProgressStep() === RecipeUploadStep.REVIEW,
},
];
if (this.includeInfer()) {
base.push({

View File

@ -1,11 +1,35 @@
<section>
<h2>Start</h2>
<section>
@if (inProgressDrafts.isLoading()) {
<p>Loading drafts...</p>
} @else if (inProgressDrafts.isError()) {
<p>Could not fetch drafts!</p>
} @else if (inProgressDrafts.isSuccess() && inProgressDrafts.data().length) {
<h3>In Progress Drafts</h3>
<ul>
@for (draft of inProgressDrafts.data(); track draft.id) {
<li>
<a (click)="onInProgressDraftClick(draft)">
<fa-icon [icon]="faFilePen"></fa-icon>
{{ draft.title }}
</a>
</li>
}
</ul>
}
</section>
<section>
<h3>New Draft</h3>
<p>Either upload a photo of a recipe and AI will assist you, or enter your recipe manually.</p>
<form id="ai-or-manual-form">
<app-file-upload [files]="sourceFilesArray()" (fileChange)="onFileChange($event)"></app-file-upload>
<div id="ai-or-manual-buttons">
<button matButton="outlined" type="button" (click)="onFormSubmit('manual')">Enter Manually</button>
<button matButton="filled" type="button" [disabled]="!sourceFile()" (click)="onFormSubmit('ai-assist')">Use AI Assist</button>
<button matButton="filled" type="button" [disabled]="!sourceFile()" (click)="onFormSubmit('ai-assist')">
Use AI Assist
</button>
</div>
</form>
</section>
</section>

View File

@ -1,13 +1,19 @@
import { Component, computed, input, output } from '@angular/core';
import { Component, computed, inject, input, output } from '@angular/core';
import { MatButton } from '@angular/material/button';
import { ReactiveFormsModule } from '@angular/forms';
import { AIOrManualSubmitEvent } from './AIOrManualSubmitEvent';
import { FileUpload } from '../../../../shared/components/file-upload/file-upload';
import { FileUploadEvent } from '../../../../shared/components/file-upload/FileUploadEvent';
import { injectQuery } from '@tanstack/angular-query-experimental';
import { RecipeDraftService } from '../../../../shared/services/RecipeDraftService';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { faFilePen } from '@fortawesome/free-solid-svg-icons';
import { Router } from '@angular/router';
import { RecipeDraftViewModel } from '../../../../shared/models/RecipeDraftView.model';
@Component({
selector: 'app-ai-or-manual',
imports: [MatButton, ReactiveFormsModule, FileUpload],
imports: [MatButton, ReactiveFormsModule, FileUpload, FaIconComponent],
templateUrl: './ai-or-manual.html',
styleUrl: './ai-or-manual.css',
})
@ -16,6 +22,9 @@ export class AiOrManual {
public sourceFileChange = output<FileUploadEvent>();
public submitStep = output<AIOrManualSubmitEvent>();
private readonly recipeDraftService = inject(RecipeDraftService);
private readonly router = inject(Router);
protected readonly sourceFilesArray = computed(() => {
const maybeSourceFile = this.sourceFile();
if (maybeSourceFile) {
@ -25,6 +34,13 @@ export class AiOrManual {
}
});
protected readonly inProgressDrafts = injectQuery(() => ({
queryKey: ['recipe-upload', 'in-progress-drafts'],
queryFn: () => {
return this.recipeDraftService.getInProgressDrafts();
},
}));
protected onFileChange(event: FileUploadEvent) {
this.sourceFileChange.emit(event);
}
@ -32,4 +48,14 @@ export class AiOrManual {
protected onFormSubmit(mode: 'manual' | 'ai-assist') {
this.submitStep.emit({ mode });
}
protected async onInProgressDraftClick(draft: RecipeDraftViewModel) {
await this.router.navigate(['/recipe-upload'], {
queryParams: {
draftId: draft.id,
},
});
}
protected readonly faFilePen = faFilePen;
}

View File

@ -0,0 +1,10 @@
export interface EnterRecipeDataSubmitEvent {
title: string;
slug: string;
ingredients: Array<{
amount: string | null;
name: string;
notes: string | null;
}>;
rawText: string;
}

View File

@ -1,5 +1,25 @@
.ingredients-table {
width: 100ch;
}
.ingredient-input {
width: 100%;
}
form {
display: flex;
flex-direction: column;
width: 60ch;
}
textarea {
box-sizing: border-box;
height: auto;
overflow: hidden;
resize: none;
}
.draft-info-container {
display: flex;
column-gap: 10px;
}

View File

@ -1,15 +1,93 @@
<h2>Enter Recipe</h2>
<form [formGroup]="recipeFormGroup">
<div class="draft-info-container">
<div>
<p>Draft started: {{ model().draft!.created }}</p>
<p>Last saved: {{ model().draft!.modified }}</p>
</div>
<div>
<button matButton="text" [matMenuTriggerFor]="draftActionsMenu">
<fa-icon [icon]="faEllipsis" size="3x"></fa-icon>
</button>
<mat-menu #draftActionsMenu="matMenu">
<button mat-menu-item (click)="onDraftDelete()">Delete draft</button>
</mat-menu>
</div>
</div>
<form [formGroup]="recipeFormGroup" (submit)="onSubmit($event)">
<h3>Basic Info</h3>
<mat-form-field>
<mat-label>Title</mat-label>
<input matInput [formControl]="recipeFormGroup.controls.title">
<input matInput [formControl]="recipeFormGroup.controls.title" />
</mat-form-field>
<mat-form-field>
<mat-label>Slug</mat-label>
<input matInput [formControl]="recipeFormGroup.controls.slug">
<input matInput [formControl]="recipeFormGroup.controls.slug" />
</mat-form-field>
<h3>Ingredients</h3>
<table
class="ingredients-table"
mat-table
#ingredientsTable
[dataSource]="recipeFormGroup.controls.ingredients.controls"
>
<ng-container matColumnDef="amount">
<th mat-header-cell *matHeaderCellDef>Amount</th>
<td mat-cell *matCellDef="let row; let i = index">
<mat-form-field class="ingredient-input ingredient-amount-input">
<input
#ingredientAmount
type="text"
matInput
[formControl]="getIngredientControl(i, 'amount')"
(keydown)="onIngredientKeydown($event, i)"
/>
</mat-form-field>
</td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let row; let i = index">
<mat-form-field class="ingredient-input ingredient-name-input">
<input
type="text"
matInput
[formControl]="getIngredientControl(i, 'name')"
(keydown)="onIngredientKeydown($event, i)"
/>
</mat-form-field>
</td>
</ng-container>
<ng-container matColumnDef="notes">
<th mat-header-cell *matHeaderCellDef>Notes</th>
<td mat-cell *matCellDef="let row; let i = index">
<mat-form-field class="ingredient-input ingredient-notes-input">
<input
type="text"
matInput
[formControl]="getIngredientControl(i, 'notes')"
(keydown)="onIngredientKeydown($event, i)"
/>
</mat-form-field>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="ingredientsColumnsToDisplay"></tr>
<tr mat-row *matRowDef="let row; columns: ingredientsColumnsToDisplay"></tr>
</table>
<button matButton="outlined" (click)="addIngredient()" type="button">Add Ingredient</button>
<h3>Recipe Text</h3>
<mat-form-field>
<mat-label>Recipe Text</mat-label>
<textarea matInput [formControl]="recipeFormGroup.controls.text"></textarea>
<textarea
#recipeTextTextarea
matInput
[formControl]="recipeFormGroup.controls.text"
(input)="onRecipeTextChange($event)"
></textarea>
</mat-form-field>
<button matButton="filled" type="submit">Review</button>
</form>

View File

@ -1,29 +1,192 @@
import { Component, input, OnInit } from '@angular/core';
import { RecipeUploadModel } from '../../../../shared/client-models/RecipeUploadModel';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import {
afterNextRender,
Component,
ElementRef,
inject,
Injector,
input,
OnInit,
output,
runInInjectionContext,
viewChild,
viewChildren,
} from '@angular/core';
import { RecipeUploadClientModel } from '../../../../shared/client-models/RecipeUploadClientModel';
import { FormArray, FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatFormField, MatInput, MatLabel } from '@angular/material/input';
import { MatButton } from '@angular/material/button';
import { EnterRecipeDataSubmitEvent } from './EnterRecipeDataSubmitEvent';
import {
MatCell,
MatCellDef,
MatColumnDef,
MatHeaderCell,
MatHeaderCellDef,
MatHeaderRow,
MatHeaderRowDef,
MatRow,
MatRowDef,
MatTable,
} from '@angular/material/table';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { faEllipsis } from '@fortawesome/free-solid-svg-icons';
import { MatMenu, MatMenuItem, MatMenuTrigger } from '@angular/material/menu';
@Component({
selector: 'app-enter-recipe-data',
imports: [ReactiveFormsModule, MatFormField, MatLabel, MatInput],
imports: [
ReactiveFormsModule,
MatFormField,
MatLabel,
MatInput,
MatButton,
MatTable,
MatColumnDef,
MatHeaderCell,
MatHeaderCellDef,
MatCell,
MatCellDef,
MatHeaderRow,
MatHeaderRowDef,
MatRow,
MatRowDef,
FaIconComponent,
MatMenuTrigger,
MatMenu,
MatMenuItem,
],
templateUrl: './enter-recipe-data.html',
styleUrl: './enter-recipe-data.css',
})
export class EnterRecipeData implements OnInit {
public readonly model = input.required<RecipeUploadModel>();
public readonly model = input.required<RecipeUploadClientModel>();
public readonly submit = output<EnterRecipeDataSubmitEvent>();
public readonly deleteDraft = output<void>();
public ngOnInit(): void {
const model = this.model();
this.recipeFormGroup.patchValue({
title: model.userTitle ?? model.inferredTitle ?? '',
slug: model.userSlug ?? model.inferredSlug ?? '',
text: model.userText ?? model.inferredText ?? '',
});
}
protected recipeTextTextarea = viewChild.required<ElementRef<HTMLTextAreaElement>>('recipeTextTextarea');
protected ingredientsTable = viewChild.required<
MatTable<
FormGroup<{
amount: FormControl<string | null>;
name: FormControl<string | null>;
notes: FormControl<string | null>;
}>
>
>('ingredientsTable');
protected ingredientAmountControls = viewChildren<ElementRef<HTMLInputElement>>('ingredientAmount');
protected readonly recipeFormGroup = new FormGroup({
title: new FormControl('', Validators.required),
slug: new FormControl('', Validators.required),
ingredients: new FormArray(
[] as Array<
FormGroup<{
amount: FormControl<string | null>;
name: FormControl<string | null>;
notes: FormControl<string | null>;
}>
>,
),
text: new FormControl('', Validators.required),
});
protected readonly ingredientsColumnsToDisplay = ['amount', 'name', 'notes'];
private readonly injector = inject(Injector);
public ngOnInit(): void {
const model = this.model();
this.recipeFormGroup.patchValue({
title: model.draft?.title ?? '',
slug: model.draft?.slug ?? '',
text: model.draft?.rawText ?? '',
ingredients: model.draft?.ingredients ?? [],
});
runInInjectionContext(this.injector, () => {
afterNextRender({
mixedReadWrite: () => {
this.updateTextareaHeight(this.recipeTextTextarea().nativeElement);
},
});
});
}
private updateTextareaHeight(textarea: HTMLTextAreaElement) {
const windowScrollX = window.scrollX;
const windowScrollY = window.scrollY;
textarea.style.height = 'auto';
textarea.style.height = textarea.scrollHeight + 'px';
requestAnimationFrame(() => {
window.scrollTo(windowScrollX, windowScrollY);
});
}
protected onRecipeTextChange(event: Event): void {
this.updateTextareaHeight(event.target as HTMLTextAreaElement);
}
protected addIngredient() {
const control = new FormGroup({
amount: new FormControl(''),
name: new FormControl('', Validators.required),
notes: new FormControl(''),
});
this.recipeFormGroup.controls.ingredients.push(control);
this.ingredientsTable().renderRows();
const addedIndex = this.recipeFormGroup.controls.ingredients.length - 1;
const target = this.ingredientAmountControls()[addedIndex];
target.nativeElement.focus();
}
protected removeIngredient(index: number) {
this.recipeFormGroup.controls.ingredients.removeAt(index);
}
protected getIngredientControl(index: number, column: 'amount' | 'name' | 'notes'): FormControl {
const ingredientGroup = this.recipeFormGroup.controls.ingredients.controls[index].controls;
switch (column) {
case 'amount':
return ingredientGroup.amount;
case 'name':
return ingredientGroup.name;
case 'notes':
return ingredientGroup.notes;
}
}
protected onIngredientKeydown(event: KeyboardEvent, index: number) {
if (event.key === 'Enter') {
event.preventDefault();
this.onIngredientEnterKey(index);
}
}
private onIngredientEnterKey(index: number) {
if (index === this.recipeFormGroup.controls.ingredients.length - 1) {
// last control row
this.addIngredient();
}
}
protected onSubmit(event: SubmitEvent): void {
event.preventDefault();
const value = this.recipeFormGroup.value;
this.submit.emit({
title: value.title!,
slug: value.slug!,
ingredients:
value.ingredients?.map((ingredient) => ({
amount: ingredient.amount ?? null,
name: ingredient.name!,
notes: ingredient.notes ?? null,
})) ?? [],
rawText: value.text!,
});
}
protected onDraftDelete(): void {
this.deleteDraft.emit();
}
protected readonly faEllipsis = faEllipsis;
}

View File

@ -0,0 +1,9 @@
<section>
<h2>Review and Publish</h2>
<p>Title: {{ draft().title }}</p>
<p>Slug: {{ draft().slug }}</p>
<div>
<p>Text: todo</p>
</div>
<button matButton="filled" (click)="onPublish()">Publish</button>
</section>

View File

@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Review } from './review';
describe('Review', () => {
let component: Review;
let fixture: ComponentFixture<Review>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Review],
}).compileComponents();
fixture = TestBed.createComponent(Review);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,18 @@
import { Component, input, output } from '@angular/core';
import { RecipeDraftViewModel } from '../../../../shared/models/RecipeDraftView.model';
import { MatButton } from '@angular/material/button';
@Component({
selector: 'app-review',
imports: [MatButton],
templateUrl: './review.html',
styleUrl: './review.css',
})
export class Review {
public readonly draft = input.required<RecipeDraftViewModel>();
public readonly publish = output<void>();
protected onPublish(): void {
this.publish.emit();
}
}

View File

@ -0,0 +1,8 @@
import { RecipeUploadStep } from './RecipeUploadStep';
import { RecipeDraftViewModel } from '../models/RecipeDraftView.model';
export interface RecipeUploadClientModel {
inProgressStep: RecipeUploadStep;
inputSourceFile?: File | null;
draft?: RecipeDraftViewModel;
}

View File

@ -1,5 +0,0 @@
export interface RecipeUploadIngredientModel {
amount: string | null;
name: string;
notes: string | null;
}

View File

@ -1,19 +0,0 @@
import { RecipeUploadIngredientModel } from './RecipeUploadIngredientModel';
import { RecipeUploadStep } from './RecipeUploadStep';
export interface RecipeUploadModel {
inProgressStep: RecipeUploadStep;
id?: number | null;
sourceFile?: File | null;
inferredText?: string | null;
inferredIngredients?: RecipeUploadIngredientModel[] | null;
inferredTitle?: string | null;
inferredSlug?: string | null;
userText?: string | null;
userIngredients?: RecipeUploadIngredientModel[] | null;
userTitle?: string | null;
userSlug?: string | null;
}

View File

@ -2,4 +2,5 @@ export enum RecipeUploadStep {
START,
INFER,
ENTER_DATA,
REVIEW,
}

View File

@ -0,0 +1,13 @@
div {
width: 60px;
height: 60px;
border-radius: 10px;
background-color: var(--primary-red);
display: flex;
align-items: center;
justify-content: center;
}
.utensils {
color: var(--primary-white);
}

View File

@ -0,0 +1,3 @@
<div>
<fa-icon [icon]="faUtensils" size="2x" class="utensils"></fa-icon>
</div>

View File

@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Logo } from './logo';
describe('Logo', () => {
let component: Logo;
let fixture: ComponentFixture<Logo>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Logo],
}).compileComponents();
fixture = TestBed.createComponent(Logo);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,13 @@
import { Component } from '@angular/core';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { faUtensils } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-logo',
imports: [FaIconComponent],
templateUrl: './logo.html',
styleUrl: './logo.css',
})
export class Logo {
protected readonly faUtensils = faUtensils;
}

View File

@ -0,0 +1,5 @@
export interface NavLinkConfig {
relativeUrl: string;
title: string;
disabled?: boolean;
}

View File

@ -1,8 +1,12 @@
<nav>
<h2>Nav</h2>
<ul>
<li><a [routerLink]="'/'">Browse Recipes</a></li>
<li><a [routerLink]="'/recipes-search'">Search Recipes</a></li>
<li><a [routerLink]="'/recipe-upload'">Upload Recipe</a></li>
@for (link of links(); track link.relativeUrl) {
@if (!link.disabled) {
<li>
<a [routerLink]="link.relativeUrl">{{ link.title }}</a>
</li>
}
}
</ul>
</nav>

View File

@ -1,5 +1,7 @@
import { Component } from '@angular/core';
import { Component, computed, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { AuthService } from '../../services/AuthService';
import { NavLinkConfig } from './NavLinkConfig';
@Component({
selector: 'app-nav',
@ -7,4 +9,24 @@ import { RouterLink } from '@angular/router';
templateUrl: './nav.html',
styleUrl: './nav.css',
})
export class Nav {}
export class Nav {
private readonly authService = inject(AuthService);
protected readonly links = computed<NavLinkConfig[]>(() => {
return [
{
relativeUrl: '/',
title: 'Browse Recipes',
},
{
relativeUrl: '/recipes-search',
title: 'Search Recipes',
},
{
relativeUrl: '/recipe-upload',
title: 'Upload Recipe',
disabled: this.authService.accessToken() === null,
},
];
});
}

View File

@ -4,6 +4,15 @@
object-fit: cover;
}
.recipe-card-image-placeholder {
height: 200px;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
article {
display: flex;
flex-direction: column;

View File

@ -2,7 +2,14 @@
<article>
<a [routerLink]="recipePageLink()">
@if (mainImage.isSuccess()) {
<img [src]="mainImage.data()" id="recipe-card-image" [alt]="recipe.mainImage.alt" />
@let maybeMainImageUrl = mainImage.data();
@if (!!maybeMainImageUrl) {
<img [src]="maybeMainImageUrl" id="recipe-card-image" [alt]="recipe.mainImage!.alt" />
} @else {
<div class="recipe-card-image-placeholder">
<app-logo></app-logo>
</div>
}
}
</a>
<div id="title-and-visibility">

View File

@ -5,10 +5,11 @@ import { injectQuery } from '@tanstack/angular-query-experimental';
import { ImageService } from '../../../services/ImageService';
import { faGlobe, faLock, faStar, faUser } from '@fortawesome/free-solid-svg-icons';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { Logo } from '../../logo/logo';
@Component({
selector: 'app-recipe-card',
imports: [RouterLink, FaIconComponent],
imports: [RouterLink, FaIconComponent, Logo],
templateUrl: './recipe-card.html',
styleUrl: './recipe-card.css',
})
@ -30,8 +31,8 @@ export class RecipeCard {
protected readonly mainImage = injectQuery(() => {
const recipe = this.recipe();
return {
queryKey: ['images', recipe.mainImage.owner.username, recipe.mainImage.filename],
queryFn: () => this.imageService.getImage(recipe.mainImage.url),
queryKey: ['recipe-main-images', recipe.owner.username, recipe.slug],
queryFn: () => this.imageService.getImage(recipe.mainImage?.url),
};
});
}

View File

@ -26,7 +26,7 @@
<div>{{ addCommentMutation.variables() }}</div>
</li>
}
@for (recipeComments of commentsQuery.data()?.pages; track $index) {
@for (recipeComments of commentsQuery.data()!.pages; track $index) {
@for (recipeComment of recipeComments.content; track recipeComment.id) {
<li class="comment">
<div class="comment-username-time">

View File

@ -0,0 +1,17 @@
import { TestBed } from '@angular/core/testing';
import { CanActivateFn } from '@angular/router';
import { authGuard } from './auth-guard';
describe('authGuardGuard', () => {
const executeGuard: CanActivateFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => authGuard(...guardParameters));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it('should be created', () => {
expect(executeGuard).toBeTruthy();
});
});

View File

@ -0,0 +1,13 @@
import { CanActivateFn, RedirectCommand, Router } from '@angular/router';
import { inject } from '@angular/core';
import { AuthService } from '../services/AuthService';
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
if (authService.accessToken() === null) {
const router = inject(Router);
return new RedirectCommand(router.parseUrl('/'));
} else {
return true;
}
};

View File

@ -18,7 +18,7 @@ export interface RecipeView {
export interface Recipe {
id: number;
isPublic: boolean;
mainImage: ImageView;
mainImage?: ImageView | null;
owner: ResourceOwner;
slug: string;
starCount: number;

View File

@ -0,0 +1,31 @@
import { ResourceOwner } from './ResourceOwner.model';
import { ImageView } from './ImageView.model';
export interface RecipeDraftViewModel {
id: string;
created: Date;
modified?: Date | null;
state: 'INFER' | 'ENTER_DATA';
slug?: string | null;
title?: string | null;
preparationTime?: number | null;
cookingTime?: number | null;
totalTime?: number | null;
rawText?: string | null;
ingredients?: IngredientDraft[] | null;
owner: ResourceOwner;
mainImage?: ImageView | null;
lastInference?: RecipeDraftInferenceView | null;
}
export interface IngredientDraft {
amount?: string | null;
name: string;
notes?: string | null;
}
export interface RecipeDraftInferenceView {
inferredAt: Date;
title: string;
rawText: string;
}

View File

@ -4,6 +4,7 @@ import { LoginView } from '../models/LoginView.model';
import { firstValueFrom, Observable, tap } from 'rxjs';
import { QueryClient } from '@tanstack/angular-query-experimental';
import { Router } from '@angular/router';
import { EndpointService } from './EndpointService';
@Injectable({
providedIn: 'root',
@ -18,11 +19,12 @@ export class AuthService {
private readonly http = inject(HttpClient);
private readonly queryClient = inject(QueryClient);
private readonly router = inject(Router);
private readonly endpointService = inject(EndpointService);
public async login(username: string, password: string): Promise<LoginView> {
const loginView = await firstValueFrom(
this.http.post<LoginView>(
'http://localhost:8080/auth/login',
this.endpointService.getUrl('authLogin'),
{ username, password },
{
withCredentials: true,
@ -36,7 +38,7 @@ export class AuthService {
}
public async logout(): Promise<void> {
await firstValueFrom(this.http.post('http://localhost:8080/auth/logout', null));
await firstValueFrom(this.http.post(this.endpointService.getUrl('authLogout'), null));
this._username.set(null);
this._accessToken.set(null);
await this.router.navigate(['/']);
@ -47,7 +49,7 @@ export class AuthService {
this._accessToken.set(null);
this._username.set(null);
return this.http
.post<LoginView>('http://localhost:8080/auth/refresh', null, {
.post<LoginView>(this.endpointService.getUrl('authRefresh'), null, {
withCredentials: true,
})
.pipe(

View File

@ -1,12 +1,13 @@
import { Injectable } from '@angular/core';
import { Endpoints } from '../../endpoints';
import { QueryParams } from '../models/Query.model';
import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root',
})
export class EndpointService {
public getUrl(endpoint: keyof typeof Endpoints, pathParams?: string[], queryParams?: QueryParams): string {
public getUrl(endpoint: keyof typeof Endpoints, pathParts?: string[], queryParams?: QueryParams): string {
const urlSearchParams = new URLSearchParams();
if (queryParams?.page !== undefined) {
urlSearchParams.set('page', queryParams.page.toString());
@ -29,7 +30,7 @@ export class EndpointService {
}
});
let pathString = pathParams?.join('/') || '';
let pathString = pathParts?.join('/') || '';
if (pathString?.length) {
pathString = '/' + pathString;
}
@ -39,6 +40,6 @@ export class EndpointService {
queryString = '?' + queryString;
}
return `http://localhost:8080/${Endpoints[endpoint]}${pathString}${queryString}`;
return environment.apiBaseUrl + '/' + Endpoints[endpoint] + pathString + queryString;
}
}

View File

@ -8,7 +8,8 @@ import { firstValueFrom, map } from 'rxjs';
export class ImageService {
private readonly httpClient = inject(HttpClient);
public getImage(backendUrl: string): Promise<string> {
public getImage(backendUrl?: string | null): Promise<string | null> {
if (!!backendUrl) {
return firstValueFrom(
this.httpClient
.get(backendUrl, {
@ -16,5 +17,8 @@ export class ImageService {
})
.pipe(map((blob) => URL.createObjectURL(blob))),
);
} else {
return Promise.resolve(null);
}
}
}

View File

@ -0,0 +1,121 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { delay, firstValueFrom, map, Observable, of } from 'rxjs';
import { RecipeUploadClientModel } from '../client-models/RecipeUploadClientModel';
import { RecipeUploadStep } from '../client-models/RecipeUploadStep';
import { RecipeDraftViewModel } from '../models/RecipeDraftView.model';
import { EndpointService } from './EndpointService';
import { WithStringDates } from '../util';
import { Recipe } from '../models/Recipe.model';
@Injectable({
providedIn: 'root',
})
export class RecipeDraftService {
private readonly http = inject(HttpClient);
private readonly endpointService = inject(EndpointService);
private hydrateView(rawView: WithStringDates<RecipeDraftViewModel>): RecipeDraftViewModel {
return {
...rawView,
created: new Date(rawView.created),
modified: rawView.modified ? new Date(rawView.modified) : undefined,
lastInference: rawView.lastInference
? {
...rawView.lastInference,
inferredAt: new Date(rawView.lastInference.inferredAt),
}
: undefined,
};
}
public getInProgressDrafts(): Promise<RecipeDraftViewModel[]> {
return firstValueFrom(
this.http.get<WithStringDates<RecipeDraftViewModel>[]>(this.endpointService.getUrl('recipeDrafts')).pipe(
map((rawViews) => {
return rawViews.map((rawView) => this.hydrateView(rawView));
}),
),
);
}
public getRecipeUploadClientModel(draftId: string): Observable<RecipeUploadClientModel> {
return this.http
.get<WithStringDates<RecipeDraftViewModel>>(this.endpointService.getUrl('recipeDrafts', [draftId]))
.pipe(
map((rawDraft) => {
return this.hydrateView(rawDraft);
}),
map((draft) => {
return {
draft,
inProgressStep:
draft.state === 'ENTER_DATA' ? RecipeUploadStep.ENTER_DATA : RecipeUploadStep.INFER,
};
}),
);
}
public createManualDraft(): Promise<RecipeUploadClientModel> {
return firstValueFrom(
this.http
.post<
WithStringDates<RecipeDraftViewModel>
>(this.endpointService.getUrl('recipeDrafts', ['manual']), null)
.pipe(
map((rawDraft) => this.hydrateView(rawDraft)),
map((draft) => ({
draft,
inProgressStep: RecipeUploadStep.ENTER_DATA,
})),
),
);
}
public updateDraft(
id: string,
data: {
title?: string | null;
slug?: string | null;
ingredients?: Array<{
amount?: string | null;
name: string;
notes?: string | null;
}>;
rawText?: string | null;
},
): Promise<RecipeUploadClientModel> {
return firstValueFrom(
this.http
.put<WithStringDates<RecipeDraftViewModel>>(this.endpointService.getUrl('recipeDrafts', [id]), data)
.pipe(
map((rawView) => this.hydrateView(rawView)),
map((draft) => ({
draft,
inProgressStep: RecipeUploadStep.ENTER_DATA,
})),
),
);
}
public publish(id: string): Promise<Recipe> {
return firstValueFrom(
this.http.post<Recipe>(this.endpointService.getUrl('recipeDrafts', [id, 'publish']), null),
);
}
public deleteDraft(id: string): Promise<void> {
return firstValueFrom(this.http.delete<void>(this.endpointService.getUrl('recipeDrafts', [id])));
}
public doInference(model: RecipeUploadClientModel): Observable<RecipeUploadClientModel> {
return of({
inProgressStep: RecipeUploadStep.ENTER_DATA,
id: 16,
inferredTitle: 'Some recipe',
inferredSlug: 'some-recipe',
inferredText: 'Some text.',
inferredIngredients: [],
}).pipe(delay(5_000));
}
}

View File

@ -19,24 +19,24 @@ export class RecipeService {
public getRecipes(): Promise<Recipe[]> {
return firstValueFrom(
this.http.get<RecipeInfoViews>('http://localhost:8080/recipes').pipe(map((res) => res.content)),
this.http.get<RecipeInfoViews>(this.endpointService.getUrl('recipes')).pipe(map((res) => res.content)),
);
}
public getRecipeView(username: string, slug: string): Promise<RecipeView> {
return firstValueFrom(this.http.get<RecipeView>(`http://localhost:8080/recipes/${username}/${slug}`));
return firstValueFrom(this.http.get<RecipeView>(this.endpointService.getUrl('recipes', [username, slug])));
}
private getRecipeUrl(recipeView: RecipeView): string {
return `http://localhost:8080/recipes/${recipeView.recipe.owner.username}/${recipeView.recipe.slug}`;
private getRecipeBaseUrl(recipeView: RecipeView): string {
return this.endpointService.getUrl('recipes', [recipeView.recipe.owner.username, recipeView.recipe.slug]);
}
public async toggleStar(recipeView: RecipeView): Promise<void> {
if (this.authService.accessToken()) {
if (recipeView.isStarred) {
await lastValueFrom(this.http.delete(this.getRecipeUrl(recipeView) + '/star'));
await lastValueFrom(this.http.delete(this.getRecipeBaseUrl(recipeView) + '/star'));
} else {
await lastValueFrom(this.http.post(this.getRecipeUrl(recipeView) + '/star', null));
await lastValueFrom(this.http.post(this.getRecipeBaseUrl(recipeView) + '/star', null));
}
await this.queryClient.invalidateQueries({
queryKey: ['recipe', recipeView.recipe.owner.username, recipeView.recipe.slug],
@ -56,7 +56,7 @@ export class RecipeService {
public async addComment(username: string, slug: string, commentText: string): Promise<RecipeComment> {
const comment = await firstValueFrom(
this.http.post<RecipeComment>(`http://localhost:8080/recipes/${username}/${slug}/comments`, {
this.http.post<RecipeComment>(this.endpointService.getUrl('recipes', [username, slug, 'comments']), {
text: commentText,
}),
);

View File

@ -1,31 +0,0 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { delay, Observable, of } from 'rxjs';
import { RecipeUploadModel } from '../client-models/RecipeUploadModel';
import { RecipeUploadStep } from '../client-models/RecipeUploadStep';
@Injectable({
providedIn: 'root',
})
export class RecipeUploadService {
private readonly http = inject(HttpClient);
public getRecipeUploadModel(draftId: number): Observable<RecipeUploadModel> {
return of({
inProgressStep: RecipeUploadStep.ENTER_DATA,
id: 42
});
}
public doInference(model: RecipeUploadModel): Observable<RecipeUploadModel> {
return of({
inProgressStep: RecipeUploadStep.ENTER_DATA,
id: 16,
inferredTitle: 'Some recipe',
inferredSlug: 'some-recipe',
inferredText: 'Some text.',
inferredIngredients: []
}).pipe(delay(5_000));
}
}

View File

@ -21,3 +21,15 @@ export const tryMaybeInt = (maybeString: string | null): number | null => {
export const hasValue = <T>(value?: T | null): value is T => {
return value !== undefined && value !== null;
};
export type WithStringDates<T> = {
[K in keyof T]: T[K] extends Date
? string
: T[K] extends Date | null | undefined
? string | null | undefined
: T[K] extends Record<string, any>
? WithStringDates<T[K]>
: T[K] extends Record<string, any> | null | undefined
? WithStringDates<T[K]> | null | undefined
: T[K];
};

View File

@ -0,0 +1,3 @@
export const environment = {
apiBaseUrl: 'http://localhost:8080',
};

View File

@ -0,0 +1,3 @@
export const environment = {
apiBaseUrl: 'http://localhost:8080',
};