Recipes phase 2
This commit is contained in:
+27
-1
@@ -4,10 +4,11 @@ from django.core.files.uploadedfile import UploadedFile
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from food.models import FoodProduct
|
||||
from .models import Recipe, RecipeIngredient
|
||||
from .models import Recipe, RecipeIngredient, RecipeSubrecipe
|
||||
|
||||
|
||||
class RecipeForm(forms.ModelForm):
|
||||
markdown_revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput)
|
||||
tags_text = forms.CharField(required=False, label='Tags',
|
||||
help_text='Separate tags with commas.')
|
||||
remove_photo = forms.BooleanField(required=False, label='Remove current photo')
|
||||
@@ -32,6 +33,7 @@ class RecipeForm(forms.ModelForm):
|
||||
|
||||
def __init__(self, *args, user, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['markdown_revision'].initial = self.instance.markdown_revision
|
||||
self.fields['parent'].queryset = Recipe.objects.filter(owner=user).exclude(pk=self.instance.pk)
|
||||
if self.instance.pk:
|
||||
self.fields['tags_text'].initial = ', '.join(self.instance.tags)
|
||||
@@ -94,3 +96,27 @@ RecipeIngredientFormSet = inlineformset_factory(
|
||||
Recipe, RecipeIngredient, form=RecipeIngredientForm,
|
||||
formset=OwnedIngredientFormSet, extra=2, can_delete=True,
|
||||
)
|
||||
|
||||
|
||||
class RecipeSubrecipeForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = RecipeSubrecipe
|
||||
fields = ('component', 'quantity', 'unit', 'note', 'display_order')
|
||||
widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
|
||||
'display_order': forms.NumberInput(attrs={'min': 0})}
|
||||
|
||||
|
||||
class OwnedSubrecipeFormSet(BaseInlineFormSet):
|
||||
def __init__(self, *args, user, **kwargs):
|
||||
self.user = user
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def add_fields(self, form, index):
|
||||
super().add_fields(form, index)
|
||||
form.fields['component'].queryset = Recipe.objects.filter(owner=self.user).exclude(pk=self.instance.pk)
|
||||
|
||||
|
||||
RecipeSubrecipeFormSet = inlineformset_factory(
|
||||
Recipe, RecipeSubrecipe, form=RecipeSubrecipeForm,
|
||||
formset=OwnedSubrecipeFormSet, fk_name='recipe', extra=1, can_delete=True,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-11 23:40
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('recipes', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='recipe',
|
||||
name='markdown_revision',
|
||||
field=models.PositiveIntegerField(default=0),
|
||||
),
|
||||
]
|
||||
@@ -22,6 +22,7 @@ class Recipe(models.Model):
|
||||
description = models.TextField(blank=True)
|
||||
instructions_markdown = models.TextField(blank=True)
|
||||
notes_markdown = models.TextField(blank=True)
|
||||
markdown_revision = models.PositiveIntegerField(default=0)
|
||||
photo = models.ImageField(upload_to='recipes/%Y/%m/', blank=True)
|
||||
preparation_minutes = models.PositiveIntegerField(default=0)
|
||||
cooking_minutes = models.PositiveIntegerField(default=0)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/* Keep the rest of the recipe form independent of TOAST UI's API. */
|
||||
(() => {
|
||||
window.createMarkdownEditor = (element, options = {}) => {
|
||||
const editor = new toastui.Editor({
|
||||
el: element,
|
||||
height: options.height || '340px',
|
||||
initialEditType: 'wysiwyg',
|
||||
previewStyle: window.matchMedia('(max-width: 767px)').matches ? 'tab' : 'vertical',
|
||||
initialValue: options.value || '',
|
||||
usageStatistics: false,
|
||||
toolbarItems: [
|
||||
['heading', 'bold', 'italic', 'strike'],
|
||||
['hr', 'quote'],
|
||||
['ul', 'ol', 'task'],
|
||||
['link', 'code', 'codeblock'],
|
||||
],
|
||||
});
|
||||
const name = element.getAttribute('aria-label') || 'Markdown editor';
|
||||
const labelInputs = () => {
|
||||
element.querySelectorAll('[contenteditable="true"], .CodeMirror textarea').forEach((input) => {
|
||||
input.setAttribute('aria-label', name);
|
||||
});
|
||||
element.querySelectorAll('.toastui-editor-mode-switch .tab-item, .toastui-editor-md-tab-container .tab-item').forEach((tab) => {
|
||||
tab.removeAttribute('aria-role');
|
||||
tab.removeAttribute('aria-selected');
|
||||
tab.setAttribute('role', 'button');
|
||||
tab.setAttribute('tabindex', '0');
|
||||
tab.setAttribute('aria-pressed', String(tab.classList.contains('active')));
|
||||
if (!tab.dataset.keyboardReady) {
|
||||
tab.dataset.keyboardReady = 'true';
|
||||
tab.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
tab.click();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
labelInputs();
|
||||
const observer = new MutationObserver(labelInputs);
|
||||
observer.observe(element, {childList: true, subtree: true, attributes: true,
|
||||
attributeFilter: ['class']});
|
||||
return {
|
||||
getMarkdown: () => editor.getMarkdown(),
|
||||
setMarkdown: (value) => editor.setMarkdown(value),
|
||||
onChange: (callback) => editor.on('change', callback),
|
||||
destroy: () => { observer.disconnect(); editor.destroy(); },
|
||||
};
|
||||
};
|
||||
})();
|
||||
@@ -1,17 +1,156 @@
|
||||
(() => {
|
||||
const button = document.querySelector('[data-add-ingredient]');
|
||||
const container = document.querySelector('[data-ingredient-forms]');
|
||||
const template = document.querySelector('#recipe-empty-ingredient');
|
||||
const total = document.querySelector('#id_ingredients-TOTAL_FORMS');
|
||||
if (!button || !container || !template || !total) return;
|
||||
button.addEventListener('click', () => {
|
||||
const index = Number(total.value);
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.innerHTML = template.innerHTML.replaceAll('__prefix__', String(index));
|
||||
const row = wrapper.firstElementChild;
|
||||
if (!row) return;
|
||||
container.appendChild(row);
|
||||
total.value = String(index + 1);
|
||||
row.querySelector('input[name$="-name"]')?.focus();
|
||||
const form = document.querySelector('[data-recipe-form]');
|
||||
if (!form) return;
|
||||
|
||||
const addRow = (buttonSelector, containerSelector, templateSelector, totalSelector, focusSelector) => {
|
||||
const button = form.querySelector(buttonSelector);
|
||||
const container = form.querySelector(containerSelector);
|
||||
const template = document.querySelector(templateSelector);
|
||||
const total = form.querySelector(totalSelector);
|
||||
if (!button || !container || !template || !total) return;
|
||||
button.addEventListener('click', () => {
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.innerHTML = template.innerHTML.replaceAll('__prefix__', total.value);
|
||||
const row = wrapper.firstElementChild;
|
||||
if (!row) return;
|
||||
container.appendChild(row);
|
||||
total.value = String(Number(total.value) + 1);
|
||||
row.querySelector(focusSelector)?.focus();
|
||||
});
|
||||
};
|
||||
addRow('[data-add-ingredient]', '[data-ingredient-forms]', '#recipe-empty-ingredient',
|
||||
'#id_ingredients-TOTAL_FORMS', 'input[name$="-name"]');
|
||||
addRow('[data-add-subrecipe]', '[data-subrecipe-forms]', '#recipe-empty-subrecipe',
|
||||
'#id_subrecipes-TOTAL_FORMS', 'select[name$="-component"]');
|
||||
|
||||
const status = form.querySelector('[data-save-status]');
|
||||
const revision = form.querySelector('#id_markdown_revision');
|
||||
const editors = [];
|
||||
let markdownDirty = false;
|
||||
let formDirty = false;
|
||||
let saving = false;
|
||||
let submitting = false;
|
||||
let failed = false;
|
||||
let timer;
|
||||
let changeNumber = 0;
|
||||
|
||||
const report = (message, state) => {
|
||||
if (!status) return;
|
||||
status.textContent = message;
|
||||
status.dataset.state = state;
|
||||
};
|
||||
const sync = () => {
|
||||
editors.forEach(({ field, editor }) => { field.value = editor.getMarkdown(); });
|
||||
};
|
||||
const schedule = () => {
|
||||
clearTimeout(timer);
|
||||
if (form.dataset.autosaveUrl && !saving && !failed) timer = setTimeout(save, 900);
|
||||
};
|
||||
const save = async () => {
|
||||
if (!markdownDirty || saving || !form.dataset.autosaveUrl) return;
|
||||
if (!form.elements.title.value.trim()) {
|
||||
report('Add a title to start autosave.', 'unsaved');
|
||||
return;
|
||||
}
|
||||
sync();
|
||||
const submittedChange = changeNumber;
|
||||
const body = {
|
||||
revision: Number(revision.value),
|
||||
title: form.elements.title.value,
|
||||
instructions_markdown: form.elements.instructions_markdown.value,
|
||||
notes_markdown: form.elements.notes_markdown.value,
|
||||
};
|
||||
if (form.dataset.draftId) body.draft_id = form.dataset.draftId;
|
||||
saving = true;
|
||||
report('Saving…', 'saving');
|
||||
try {
|
||||
const response = await fetch(form.dataset.autosaveUrl, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json', 'X-CSRFToken': form.elements.csrfmiddlewaretoken.value},
|
||||
body: JSON.stringify(body),
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error || 'Could not save. Try again.');
|
||||
revision.value = result.revision;
|
||||
if (result.edit_url) {
|
||||
form.action = result.edit_url;
|
||||
form.dataset.autosaveUrl = result.autosave_url;
|
||||
delete form.dataset.draftId;
|
||||
form.elements.draft_id?.remove();
|
||||
window.history.replaceState(null, '', result.edit_url);
|
||||
const heading = document.querySelector('.recipes-form-header h1');
|
||||
if (heading) heading.textContent = 'Edit recipe';
|
||||
document.title = `Edit ${body.title} · Tasknest`;
|
||||
}
|
||||
markdownDirty = changeNumber !== submittedChange;
|
||||
failed = false;
|
||||
report(markdownDirty || formDirty ? 'Unsaved changes' : 'Saved', markdownDirty || formDirty ? 'unsaved' : 'saved');
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
report(error.message || 'Could not save. Try again.', 'error');
|
||||
} finally {
|
||||
saving = false;
|
||||
if (markdownDirty && !failed) schedule();
|
||||
if (failed) submitting = false;
|
||||
if (submitting && !failed) {
|
||||
submitting = false;
|
||||
form.requestSubmit();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
form.querySelectorAll('[data-markdown-editor]').forEach((host) => {
|
||||
const field = form.elements[host.dataset.markdownEditor];
|
||||
if (!field || !window.createMarkdownEditor || !window.toastui?.Editor) return;
|
||||
try {
|
||||
const editor = window.createMarkdownEditor(host, {value: field.value,
|
||||
height: host.dataset.markdownEditor === 'notes_markdown' ? '260px' : '360px'});
|
||||
field.hidden = true;
|
||||
editors.push({field, editor});
|
||||
editor.onChange(() => {
|
||||
if (editor.getMarkdown() === field.value) return;
|
||||
changeNumber += 1;
|
||||
markdownDirty = true;
|
||||
failed = false;
|
||||
report('Unsaved changes', 'unsaved');
|
||||
schedule();
|
||||
});
|
||||
} catch (error) {
|
||||
host.hidden = true;
|
||||
report('Editor unavailable. You can still edit Markdown in the text box.', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
const markOtherChange = (event) => {
|
||||
if (event.target.closest('.toastui-editor-defaultUI') || event.target.matches('[hidden]')) return;
|
||||
if (event.target.name === 'title') {
|
||||
changeNumber += 1;
|
||||
markdownDirty = true;
|
||||
failed = false;
|
||||
report('Unsaved changes', 'unsaved');
|
||||
schedule();
|
||||
return;
|
||||
}
|
||||
formDirty = true;
|
||||
report('Unsaved changes', 'unsaved');
|
||||
};
|
||||
form.addEventListener('input', markOtherChange);
|
||||
form.addEventListener('change', markOtherChange);
|
||||
form.addEventListener('submit', (event) => {
|
||||
clearTimeout(timer);
|
||||
sync();
|
||||
if (saving) {
|
||||
event.preventDefault();
|
||||
submitting = true;
|
||||
return;
|
||||
}
|
||||
submitting = true;
|
||||
});
|
||||
window.addEventListener('beforeunload', (event) => {
|
||||
if (!submitting && (markdownDirty || formDirty || saving)) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -12,3 +12,8 @@ body[data-theme=dark] .recipes-layout{--recipe-surface:#222b25;--recipe-line:#43
|
||||
@media(max-width:991px){.recipes-layout:not(.recipes-layout--form){grid-template-columns:minmax(0,1fr)}.recipes-browser,.recipes-detail,.recipes-info{grid-column:1}.recipes-list{grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-hero{grid-template-columns:minmax(170px,38%) minmax(0,1fr)}.recipes-info{grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-info .recipes-panel:last-child{grid-column:auto}}
|
||||
@media(max-width:767px){.page-content.recipes-page-content{padding-top:25px}.recipes-layout--list .recipes-detail,.recipes-layout--list .recipes-info{display:none}.recipes-layout--detail .recipes-browser{display:none}.recipes-browser__heading h1{font-size:2.4rem}.recipes-detail{padding:16px}.recipes-hero{grid-template-columns:1fr;gap:15px}.recipes-hero>img,.recipes-photo-placeholder{height:230px}.recipes-hero h2{font-size:2rem}.recipes-content-grid,.recipes-info{grid-template-columns:1fr}.recipes-list{grid-template-columns:1fr}.recipes-form-grid{grid-template-columns:1fr}.recipes-field--title,.recipes-field--description,.recipes-field--instructions_markdown,.recipes-field--notes_markdown,.recipes-field--photo,.recipes-field--remove_photo{grid-column:auto}.recipes-ingredient-form__main{grid-template-columns:minmax(0,1fr) minmax(90px,1fr)}.recipes-ingredient-form__main .recipes-field:first-child{grid-column:1/-1}.recipes-edit-card{padding:18px}.recipes-section-heading{align-items:flex-start;flex-wrap:wrap}.recipes-section-heading button{width:100%}}
|
||||
@media(max-width:400px){.recipes-browser__heading{display:block}.recipes-new{margin-top:12px}.recipes-filter-grid{grid-template-columns:1fr}.recipes-detail__top{flex-wrap:wrap}.recipes-ingredient-form__main{grid-template-columns:1fr 1fr}}
|
||||
.recipes-markdown-source>*:first-child{margin-top:0}.recipes-markdown-source>*:last-child{margin-bottom:0}.recipes-markdown-source h1,.recipes-markdown-source h2,.recipes-markdown-source h3{line-height:1.3}.recipes-markdown-source h1{font-size:1.35rem}.recipes-markdown-source h2{font-size:1.2rem}.recipes-markdown-source h3{font-size:1.05rem}.recipes-markdown-source ul,.recipes-markdown-source ol{padding-left:1.3rem}.recipes-markdown-source li{margin:.3rem 0}.recipes-markdown-source a{color:var(--recipe-accent);text-decoration:underline}.recipes-markdown-source blockquote{margin:1rem 0;padding:.2rem 0 .2rem 1rem;border-left:3px solid var(--recipe-accent);color:var(--recipe-muted)}.recipes-markdown-source pre{max-width:100%;overflow:auto;padding:.8rem;border-radius:8px;background:var(--recipe-soft)}.recipes-markdown-source code{overflow-wrap:anywhere}.recipes-markdown-source input[type=checkbox]{margin-right:.45rem;accent-color:var(--recipe-accent)}
|
||||
.recipes-field [hidden],.recipes-markdown-editor[hidden]{display:none!important}.recipes-markdown-editor{max-width:100%;min-width:0}.recipes-markdown-editor .toastui-editor-defaultUI{border-color:var(--recipe-line);border-radius:9px;overflow:hidden}.recipes-markdown-editor .toastui-editor-defaultUI-toolbar,.recipes-markdown-editor .toastui-editor-mode-switch{background:var(--recipe-soft)}.recipes-markdown-editor .toastui-editor-defaultUI button:focus-visible,.recipes-markdown-editor .toastui-editor-defaultUI .tab-item:focus-visible{outline:3px solid #77b68b;outline-offset:2px}.recipes-save-status{margin-left:auto;color:var(--recipe-muted);font-size:.8rem}.recipes-save-status[data-state=unsaved]{color:#a86a1e}.recipes-save-status[data-state=error]{color:#b6413b}.recipes-save-status[data-state=saving]{color:var(--recipe-accent)}.recipes-action-form{margin:0}.recipes-action-form button{width:100%;border:0;border-bottom:1px solid var(--recipe-line);background:none;color:inherit;text-align:left;cursor:pointer}.recipes-action-form button:hover{color:var(--recipe-accent)}
|
||||
body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI-toolbar,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-main{border-color:var(--recipe-line);background:var(--recipe-surface);color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-container,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-ww-container,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-preview{background:var(--recipe-surface);color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .ProseMirror,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-contents,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-container .CodeMirror{color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-contents *{color:inherit}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-toolbar-icons{filter:invert(.85)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI-toolbar button:hover{background:#405347}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch .tab-item{color:var(--recipe-muted)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch .tab-item.active{background:var(--recipe-surface);color:var(--recipe-ink)}
|
||||
@media(max-width:767px){.recipes-markdown-editor .toastui-editor-defaultUI-toolbar{overflow-x:auto}.recipes-markdown-editor .toastui-editor-toolbar-group{flex:none}.recipes-form-actions{flex-wrap:wrap}.recipes-save-status{width:100%;margin-left:0}}
|
||||
.recipes-related-component{padding:7px 0;border-top:1px solid var(--recipe-line)}.recipes-related-component summary{color:var(--recipe-accent);font-size:.79rem;cursor:pointer}.recipes-related-component .recipes-markdown-source{margin-top:9px;padding:9px;border-radius:8px;background:var(--recipe-soft)}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 NHN Cloud Corp.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,11 +1,13 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}{% if creating %}New recipe{% else %}Edit {{ recipe.title }}{% endif %} · Tasknest{% endblock %}
|
||||
{% block page_class %}recipes-page-content{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}">
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'recipes/vendor/toastui-editor.min.css' %}"><link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=3">
|
||||
<div class="recipes-layout recipes-layout--form"><header class="recipes-form-header"><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">← Back to recipes</a><h1>{% if creating %}New recipe{% else %}Edit recipe{% endif %}</h1><p>Keep ingredients structured and instructions in Markdown.</p></header>
|
||||
<form method="post" enctype="multipart/form-data" class="recipes-edit-card" data-recipe-form>{% csrf_token %}
|
||||
<form method="post" enctype="multipart/form-data" class="recipes-edit-card" data-recipe-form data-autosave-url="{% if creating %}{% url 'recipes:autosave-new' %}{% else %}{% url 'recipes:autosave' recipe.api_id %}{% endif %}"{% if creating %} data-draft-id="{{ new_draft_id }}"{% endif %}>{% csrf_token %}
|
||||
{% if creating %}<input type="hidden" name="draft_id" value="{{ new_draft_id }}">{% endif %}
|
||||
{% if form.non_field_errors %}<div class="recipes-form-error" role="alert">{{ form.non_field_errors }}</div>{% endif %}
|
||||
<section><h2>Recipe details</h2><div class="recipes-form-grid">{% for field in form %}{% if field.name != 'remove_photo' %}<div class="recipes-field recipes-field--{{ field.name }}"><label for="{{ field.id_for_label }}">{{ field.label }}</label>{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{% if field.errors %}<div class="recipes-form-error" role="alert">{{ field.errors }}</div>{% endif %}</div>{% endif %}{% endfor %}{% if recipe.photo %}<div class="recipes-field recipes-field--remove_photo"><img src="{% url 'recipes:photo' recipe.api_id %}" alt="Current recipe photo" class="recipes-current-photo"><label class="recipes-checkbox">{{ form.remove_photo }} Remove current photo</label></div>{% endif %}</div></section>
|
||||
<section><h2>Recipe details</h2><div class="recipes-form-grid">{% for field in form %}{% if field.name == 'markdown_revision' %}{{ field }}{% elif field.name != 'remove_photo' %}<div class="recipes-field recipes-field--{{ field.name }}"><label for="{{ field.id_for_label }}">{{ field.label }}</label>{{ field }}{% if field.name == 'instructions_markdown' or field.name == 'notes_markdown' %}<div class="recipes-markdown-editor" data-markdown-editor="{{ field.name }}" aria-label="{{ field.label }} editor"></div>{% endif %}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{% if field.errors %}<div class="recipes-form-error" role="alert">{{ field.errors }}</div>{% endif %}</div>{% endif %}{% endfor %}{% if recipe.photo %}<div class="recipes-field recipes-field--remove_photo"><img src="{% url 'recipes:photo' recipe.api_id %}" alt="Current recipe photo" class="recipes-current-photo"><label class="recipes-checkbox">{{ form.remove_photo }} Remove current photo</label></div>{% endif %}</div></section>
|
||||
<section><div class="recipes-section-heading"><div><h2>Ingredients</h2><p>Add measured ingredients now; product matching can be refined later.</p></div><button type="button" class="recipes-outline-button" data-add-ingredient>+ Add ingredient</button></div>{{ ingredients.management_form }}{% if ingredients.non_form_errors %}<div class="recipes-form-error" role="alert">{{ ingredients.non_form_errors }}</div>{% endif %}<div class="recipes-ingredient-forms" data-ingredient-forms>{% for ingredient in ingredients %}{% include 'recipes/ingredient_row.html' %}{% endfor %}</div><template id="recipe-empty-ingredient">{% with ingredient=ingredients.empty_form %}{% include 'recipes/ingredient_row.html' %}{% endwith %}</template></section>
|
||||
<div class="recipes-form-actions"><button type="submit" class="button">Save recipe</button><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">Cancel</a></div>
|
||||
</form></div><script defer src="{% static 'recipes/form.js' %}"></script>{% endblock %}
|
||||
<section><div class="recipes-section-heading"><div><h2>Subrecipes</h2><p>Include an independently editable recipe as a component.</p></div><button type="button" class="recipes-outline-button" data-add-subrecipe>+ Add subrecipe</button></div>{{ subrecipes.management_form }}{% if subrecipes.non_form_errors %}<div class="recipes-form-error" role="alert">{{ subrecipes.non_form_errors }}</div>{% endif %}<div class="recipes-ingredient-forms" data-subrecipe-forms>{% for subrecipe in subrecipes %}{% include 'recipes/subrecipe_row.html' %}{% endfor %}</div><template id="recipe-empty-subrecipe">{% with subrecipe=subrecipes.empty_form %}{% include 'recipes/subrecipe_row.html' %}{% endwith %}</template></section>
|
||||
<div class="recipes-form-actions"><button type="submit" class="button">Save recipe</button><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">Cancel</a><span class="recipes-save-status" data-save-status role="status" aria-live="polite">{% if creating %}Add a title to start autosave.{% else %}Saved{% endif %}</span></div>
|
||||
</form></div><script defer src="{% static 'recipes/vendor/toastui-editor-all.min.js' %}"></script><script defer src="{% static 'recipes/editor-adapter.js' %}?v=4"></script><script defer src="{% static 'recipes/form.js' %}?v=5"></script>{% endblock %}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% extends 'planner/base.html' %}{% load static recipe_markdown %}
|
||||
{% block title %}Recipes · Tasknest{% endblock %}
|
||||
{% block page_class %}recipes-page-content{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}">
|
||||
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=3">
|
||||
<div class="recipes-layout {% if explicit_detail %}recipes-layout--detail{% else %}recipes-layout--list{% endif %}">
|
||||
<aside class="recipes-browser" aria-label="Recipe browser">
|
||||
<div class="recipes-browser__heading">
|
||||
@@ -41,7 +41,7 @@
|
||||
</div>
|
||||
<div class="recipes-content-grid">
|
||||
<section class="recipes-panel" aria-labelledby="recipe-ingredients-heading"><h3 id="recipe-ingredients-heading">Ingredients</h3><ul class="recipes-ingredient-list">{% for ingredient in selected.ingredients.all %}<li><span>{{ ingredient.name }}{% if ingredient.preparation_note %}<small>{{ ingredient.preparation_note }}</small>{% endif %}</span><strong>{{ ingredient.quantity|floatformat:-3 }} {{ ingredient.unit }}</strong>{% if ingredient.is_optional %}<em>Optional</em>{% endif %}</li>{% empty %}<li class="recipes-muted">No ingredients added yet.</li>{% endfor %}</ul></section>
|
||||
<div class="recipes-content-stack"><section class="recipes-panel" aria-labelledby="recipe-instructions-heading"><h3 id="recipe-instructions-heading">Instructions</h3>{% if selected.instructions_markdown %}<div class="recipes-markdown-source">{{ selected.instructions_markdown|linebreaksbr }}</div>{% else %}<p class="recipes-muted">No instructions added yet.</p>{% endif %}</section>{% if selected.notes_markdown %}<section class="recipes-panel" aria-labelledby="recipe-notes-heading"><h3 id="recipe-notes-heading">Notes</h3><div class="recipes-markdown-source">{{ selected.notes_markdown|linebreaksbr }}</div></section>{% endif %}</div>
|
||||
<div class="recipes-content-stack"><section class="recipes-panel" aria-labelledby="recipe-instructions-heading"><h3 id="recipe-instructions-heading">Instructions</h3>{% if selected.instructions_markdown %}<div class="recipes-markdown-source">{{ selected.instructions_markdown|recipe_markdown }}</div>{% else %}<p class="recipes-muted">No instructions added yet.</p>{% endif %}</section>{% if selected.notes_markdown %}<section class="recipes-panel" aria-labelledby="recipe-notes-heading"><h3 id="recipe-notes-heading">Notes</h3><div class="recipes-markdown-source">{{ selected.notes_markdown|recipe_markdown }}</div></section>{% endif %}</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="recipes-empty-detail"><h2>Make room for something delicious.</h2><p>Save a recipe to see its ingredients and instructions here.</p><a class="button" href="{% url 'recipes:create' %}">Create your first recipe</a></div>
|
||||
@@ -50,8 +50,8 @@
|
||||
|
||||
{% if selected %}<aside class="recipes-info" aria-label="Recipe information">
|
||||
<section class="recipes-panel"><h3>At a glance</h3><dl class="recipes-facts"><div><dt>Servings</dt><dd>{{ selected.default_servings|floatformat:-2 }}</dd></div><div><dt>Preparation</dt><dd>{{ selected.preparation_minutes }} min</dd></div><div><dt>Cooking</dt><dd>{{ selected.cooking_minutes }} min</dd></div><div><dt>Status</dt><dd>{{ selected.get_status_display }}</dd></div></dl></section>
|
||||
{% if selected.parent or selected.variations.all or selected.subrecipes.all %}<section class="recipes-panel"><h3>Related recipes</h3>{% if selected.parent %}<p>Variation of <a href="{% url 'recipes:detail' selected.parent.api_id %}">{{ selected.parent.title }}</a></p>{% endif %}{% for variation in selected.variations.all %}<p><a href="{% url 'recipes:detail' variation.api_id %}">{{ variation.title }}</a></p>{% endfor %}{% for item in selected.subrecipes.all %}<p>{{ item.quantity|floatformat:-3 }} {{ item.unit }} of <a href="{% url 'recipes:detail' item.component.api_id %}">{{ item.component.title }}</a></p>{% endfor %}</section>{% endif %}
|
||||
<section class="recipes-panel"><h3>Actions</h3><a class="recipes-action" href="{% url 'recipes:edit' selected.api_id %}">Edit recipe</a><a class="recipes-action recipes-action--danger" href="{% url 'recipes:delete' selected.api_id %}">Delete recipe</a></section>
|
||||
{% if selected.parent or selected.variations.all or selected.subrecipes.all %}<section class="recipes-panel"><h3>Related recipes</h3>{% if selected.parent %}<p>Variation of <a href="{% url 'recipes:detail' selected.parent.api_id %}">{{ selected.parent.title }}</a></p>{% endif %}{% for variation in selected.variations.all %}<p><a href="{% url 'recipes:detail' variation.api_id %}">{{ variation.title }}</a></p>{% endfor %}{% for item in selected.subrecipes.all %}<div class="recipes-related-component"><p>{{ item.quantity|floatformat:-3 }} {{ item.unit }} of <a href="{% url 'recipes:detail' item.component.api_id %}">{{ item.component.title }}</a></p>{% if item.component.instructions_markdown %}<details><summary>Show {{ item.component.title }} instructions</summary><div class="recipes-markdown-source">{{ item.component.instructions_markdown|recipe_markdown }}</div></details>{% endif %}</div>{% endfor %}</section>{% endif %}
|
||||
<section class="recipes-panel"><h3>Actions</h3><a class="recipes-action" href="{% url 'recipes:edit' selected.api_id %}">Edit recipe</a><form method="post" action="{% url 'recipes:create-variation' selected.api_id %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Create variation</button></form><a class="recipes-action recipes-action--danger" href="{% url 'recipes:delete' selected.api_id %}">Delete recipe</a></section>
|
||||
</aside>{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<div class="recipes-ingredient-form"><div class="recipes-ingredient-form__main"><div class="recipes-field"><label for="{{ subrecipe.component.id_for_label }}">Component recipe</label>{{ subrecipe.component }}{{ subrecipe.id }}{% if subrecipe.component.errors %}<div class="recipes-form-error" role="alert">{{ subrecipe.component.errors }}</div>{% endif %}</div><div class="recipes-field"><label for="{{ subrecipe.quantity.id_for_label }}">Quantity</label>{{ subrecipe.quantity }}{% if subrecipe.quantity.errors %}<div class="recipes-form-error" role="alert">{{ subrecipe.quantity.errors }}</div>{% endif %}</div><div class="recipes-field"><label for="{{ subrecipe.unit.id_for_label }}">Unit</label>{{ subrecipe.unit }}{% if subrecipe.unit.errors %}<div class="recipes-form-error" role="alert">{{ subrecipe.unit.errors }}</div>{% endif %}</div></div><details class="recipes-ingredient-form__more"><summary>More options</summary><div class="recipes-form-grid"><div class="recipes-field"><label for="{{ subrecipe.note.id_for_label }}">Note</label>{{ subrecipe.note }}</div><div class="recipes-field"><label for="{{ subrecipe.display_order.id_for_label }}">Order</label>{{ subrecipe.display_order }}</div>{% if subrecipe.DELETE %}<div class="recipes-field"><label class="recipes-checkbox">{{ subrecipe.DELETE }} Remove component</label></div>{% endif %}</div></details>{% if subrecipe.non_field_errors %}<div class="recipes-form-error" role="alert">{{ subrecipe.non_field_errors }}</div>{% endif %}</div>
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Render user-authored recipe Markdown with a narrow HTML allowlist."""
|
||||
|
||||
import re
|
||||
|
||||
import markdown
|
||||
import nh3
|
||||
from django import template
|
||||
from django.utils.safestring import mark_safe
|
||||
|
||||
register = template.Library()
|
||||
|
||||
TAGS = {'p', 'br', 'h1', 'h2', 'h3', 'h4', 'strong', 'em', 'del', 'ul', 'ol',
|
||||
'li', 'blockquote', 'pre', 'code', 'a', 'hr'}
|
||||
|
||||
|
||||
@register.filter
|
||||
def recipe_markdown(value):
|
||||
html = markdown.markdown(value or '', extensions=['extra', 'sane_lists'])
|
||||
clean = nh3.clean(html, tags=TAGS, attributes={'a': {'href', 'title'}},
|
||||
url_schemes={'http', 'https', 'mailto'}, link_rel='noopener noreferrer')
|
||||
clean = re.sub(r'<li>\s*\[([ xX])\]\s*',
|
||||
lambda match: '<li><input type="checkbox" disabled'
|
||||
+ (' checked' if match.group(1).lower() == 'x' else '') + '> ', clean)
|
||||
return mark_safe(clean)
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
from decimal import Decimal
|
||||
from io import BytesIO
|
||||
from tempfile import TemporaryDirectory
|
||||
@@ -11,6 +12,7 @@ from django.urls import reverse
|
||||
from PIL import Image
|
||||
|
||||
from .models import Recipe, RecipeIngredient, RecipeSubrecipe
|
||||
from .templatetags.recipe_markdown import recipe_markdown
|
||||
|
||||
|
||||
class RecipeWebTests(TestCase):
|
||||
@@ -26,10 +28,13 @@ class RecipeWebTests(TestCase):
|
||||
'preparation_minutes': '10', 'cooking_minutes': '15',
|
||||
'default_servings': '2', 'status': 'draft', 'tags_text': 'Asian, Quick',
|
||||
'instructions_markdown': 'Cook the noodles.', 'notes_markdown': '',
|
||||
'markdown_revision': '0',
|
||||
'ingredients-TOTAL_FORMS': '1', 'ingredients-INITIAL_FORMS': '0',
|
||||
'ingredients-MIN_NUM_FORMS': '0', 'ingredients-MAX_NUM_FORMS': '1000',
|
||||
'ingredients-0-name': 'Noodles', 'ingredients-0-quantity': '250',
|
||||
'ingredients-0-unit': 'g', 'ingredients-0-display_order': '0',
|
||||
'subrecipes-TOTAL_FORMS': '0', 'subrecipes-INITIAL_FORMS': '0',
|
||||
'subrecipes-MIN_NUM_FORMS': '0', 'subrecipes-MAX_NUM_FORMS': '1000',
|
||||
}
|
||||
data.update(changes)
|
||||
return data
|
||||
@@ -93,3 +98,132 @@ class RecipeWebTests(TestCase):
|
||||
self.assertEqual(self.client.get(photo_url).status_code, 200)
|
||||
self.client.force_login(self.other)
|
||||
self.assertEqual(self.client.get(photo_url).status_code, 404)
|
||||
|
||||
def test_markdown_round_trip_and_safe_rendering(self):
|
||||
source = '# Dinner\n\n- [x] Prepare\n- [ ] Cook\n\n**Ready** <script>alert(1)</script> [bad](javascript:alert(1))'
|
||||
recipe = Recipe.objects.create(owner=self.user, title='Dinner', instructions_markdown=source)
|
||||
response = self.client.get(reverse('recipes:detail', args=[recipe.api_id]))
|
||||
self.assertContains(response, '<h1>Dinner</h1>', html=True)
|
||||
self.assertContains(response, '<strong>Ready</strong>', html=True)
|
||||
self.assertNotContains(response, '<script>')
|
||||
self.assertNotContains(response, 'href="javascript:')
|
||||
self.assertEqual(Recipe.objects.get(pk=recipe.pk).instructions_markdown, source)
|
||||
self.assertIn('type="checkbox"', recipe_markdown(source))
|
||||
|
||||
def test_autosave_rejects_stale_revision_and_other_owner(self):
|
||||
recipe = Recipe.objects.create(owner=self.user, title='Dinner')
|
||||
url = reverse('recipes:autosave', args=[recipe.api_id])
|
||||
payload = {'revision': 0, 'title': 'Dinner',
|
||||
'instructions_markdown': '# First', 'notes_markdown': 'Notes'}
|
||||
response = self.client.post(url, json.dumps(payload), content_type='application/json')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()['revision'], 1)
|
||||
stale = self.client.post(url, json.dumps({**payload, 'instructions_markdown': '# Stale'}),
|
||||
content_type='application/json')
|
||||
self.assertEqual(stale.status_code, 409)
|
||||
recipe.refresh_from_db()
|
||||
self.assertEqual(recipe.instructions_markdown, '# First')
|
||||
self.client.force_login(self.other)
|
||||
self.assertEqual(self.client.post(url, json.dumps(payload), content_type='application/json').status_code, 404)
|
||||
|
||||
def test_new_draft_autosave_is_idempotent(self):
|
||||
import uuid
|
||||
draft_id = str(uuid.uuid4())
|
||||
payload = {'draft_id': draft_id, 'title': 'Quick lunch',
|
||||
'instructions_markdown': '# Start', 'notes_markdown': ''}
|
||||
url = reverse('recipes:autosave-new')
|
||||
first = self.client.post(url, json.dumps(payload), content_type='application/json')
|
||||
second = self.client.post(url, json.dumps(payload), content_type='application/json')
|
||||
self.assertEqual(first.status_code, 200)
|
||||
self.assertEqual(second.status_code, 200)
|
||||
self.assertEqual(Recipe.objects.filter(owner=self.user).count(), 1)
|
||||
recipe = Recipe.objects.get(owner=self.user)
|
||||
self.assertEqual(recipe.markdown_revision, 1)
|
||||
self.assertEqual(first.json()['edit_url'], reverse('recipes:edit', args=[recipe.api_id]))
|
||||
changed = self.client.post(url, json.dumps({**payload, 'instructions_markdown': 'Stale'}),
|
||||
content_type='application/json')
|
||||
self.assertEqual(changed.status_code, 409)
|
||||
resumed = self.data('Quick lunch finished', draft_id=draft_id)
|
||||
self.assertEqual(self.client.post(reverse('recipes:create'), resumed).status_code, 302)
|
||||
self.assertEqual(Recipe.objects.filter(owner=self.user).count(), 1)
|
||||
recipe.refresh_from_db()
|
||||
self.assertEqual(recipe.title, 'Quick lunch finished')
|
||||
self.client.force_login(self.other)
|
||||
self.assertEqual(self.client.post(url, json.dumps(payload), content_type='application/json').status_code, 404)
|
||||
|
||||
def test_manual_create_retry_uses_same_draft(self):
|
||||
import uuid
|
||||
data = self.data(draft_id=str(uuid.uuid4()))
|
||||
url = reverse('recipes:create')
|
||||
self.assertEqual(self.client.post(url, data).status_code, 302)
|
||||
self.assertEqual(self.client.post(url, data).status_code, 302)
|
||||
self.assertEqual(Recipe.objects.filter(owner=self.user).count(), 1)
|
||||
|
||||
def test_variation_copies_independent_content(self):
|
||||
parent = Recipe.objects.create(owner=self.user, title='Dinner', instructions_markdown='Original')
|
||||
RecipeIngredient.objects.create(recipe=parent, name='Noodles', quantity=Decimal('250'), unit='g')
|
||||
component = Recipe.objects.create(owner=self.user, title='Sauce')
|
||||
RecipeSubrecipe.objects.create(recipe=parent, component=component)
|
||||
response = self.client.post(reverse('recipes:create-variation', args=[parent.api_id]))
|
||||
self.assertEqual(response.status_code, 302)
|
||||
variation = Recipe.objects.get(parent=parent)
|
||||
self.assertNotEqual(variation.pk, parent.pk)
|
||||
self.assertEqual(variation.ingredients.get().quantity, Decimal('250'))
|
||||
self.assertEqual(variation.subrecipes.get().component, component)
|
||||
edit_data = self.data('Spicy dinner', **{
|
||||
'instructions_markdown': '# Spicy steps',
|
||||
'ingredients-INITIAL_FORMS': '1',
|
||||
'ingredients-0-id': str(variation.ingredients.get().pk),
|
||||
'ingredients-0-quantity': '300',
|
||||
'subrecipes-TOTAL_FORMS': '1',
|
||||
'subrecipes-INITIAL_FORMS': '1',
|
||||
'subrecipes-0-id': str(variation.subrecipes.get().pk),
|
||||
'subrecipes-0-component': str(component.pk),
|
||||
'subrecipes-0-quantity': '1',
|
||||
'subrecipes-0-unit': 'servings',
|
||||
'subrecipes-0-display_order': '0',
|
||||
})
|
||||
self.assertEqual(self.client.post(reverse('recipes:edit', args=[variation.api_id]), edit_data).status_code, 302)
|
||||
variation.refresh_from_db()
|
||||
self.assertEqual(variation.title, 'Spicy dinner')
|
||||
self.assertEqual(variation.instructions_markdown, '# Spicy steps')
|
||||
self.assertEqual(variation.ingredients.get().quantity, Decimal('300'))
|
||||
self.assertEqual(parent.ingredients.get().quantity, Decimal('250'))
|
||||
parent.instructions_markdown = 'Changed original'
|
||||
parent.save()
|
||||
variation.refresh_from_db()
|
||||
self.assertEqual(variation.instructions_markdown, '# Spicy steps')
|
||||
self.client.force_login(self.other)
|
||||
self.assertEqual(self.client.post(reverse('recipes:create-variation', args=[parent.api_id])).status_code, 404)
|
||||
|
||||
def test_subrecipe_form_rejects_cycle_and_foreign_component(self):
|
||||
main = Recipe.objects.create(owner=self.user, title='Main')
|
||||
sauce = Recipe.objects.create(owner=self.user, title='Sauce')
|
||||
foreign = Recipe.objects.create(owner=self.other, title='Foreign')
|
||||
component_data = {
|
||||
'subrecipes-TOTAL_FORMS': '1', 'subrecipes-0-component': str(sauce.pk),
|
||||
'subrecipes-0-quantity': '2', 'subrecipes-0-unit': 'servings',
|
||||
'subrecipes-0-display_order': '0',
|
||||
}
|
||||
url = reverse('recipes:edit', args=[main.api_id])
|
||||
self.assertEqual(self.client.post(url, self.data(**component_data)).status_code, 302)
|
||||
self.assertEqual(main.subrecipes.get().component, sauce)
|
||||
cycle_data = {**component_data, 'subrecipes-0-component': str(main.pk)}
|
||||
response = self.client.post(reverse('recipes:edit', args=[sauce.api_id]), self.data(**cycle_data))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertFalse(sauce.subrecipes.exists())
|
||||
foreign_data = {**component_data, 'subrecipes-0-component': str(foreign.pk)}
|
||||
response = self.client.post(reverse('recipes:edit', args=[sauce.api_id]), self.data(**foreign_data))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertFalse(sauce.subrecipes.exists())
|
||||
|
||||
def test_full_form_rejects_stale_markdown_revision(self):
|
||||
recipe = Recipe.objects.create(owner=self.user, title='Original')
|
||||
recipe.instructions_markdown = 'Newer Markdown'
|
||||
recipe.markdown_revision = 1
|
||||
recipe.save()
|
||||
response = self.client.post(reverse('recipes:edit', args=[recipe.api_id]), self.data('Stale title'))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
recipe.refresh_from_db()
|
||||
self.assertEqual(recipe.title, 'Original')
|
||||
self.assertEqual(recipe.instructions_markdown, 'Newer Markdown')
|
||||
|
||||
@@ -7,8 +7,11 @@ app_name = 'recipes'
|
||||
urlpatterns = [
|
||||
path('', views.library, name='list'),
|
||||
path('new/', views.create, name='create'),
|
||||
path('new/autosave/', views.autosave_new, name='autosave-new'),
|
||||
path('<uuid:identifier>/', views.detail, name='detail'),
|
||||
path('<uuid:identifier>/edit/', views.edit, name='edit'),
|
||||
path('<uuid:identifier>/autosave/', views.autosave, name='autosave'),
|
||||
path('<uuid:identifier>/variations/new/', views.create_variation, name='create-variation'),
|
||||
path('<uuid:identifier>/delete/', views.delete, name='delete'),
|
||||
path('<uuid:identifier>/favourite/', views.toggle_favourite, name='favourite'),
|
||||
path('<uuid:identifier>/photo/', views.photo, name='photo'),
|
||||
|
||||
+136
-20
@@ -1,15 +1,18 @@
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.http import FileResponse
|
||||
from django.http import FileResponse, Http404, HttpResponseBadRequest, JsonResponse
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.urls import reverse
|
||||
from django.views.decorators.http import require_http_methods, require_POST
|
||||
from PIL import Image
|
||||
|
||||
from .forms import RecipeForm, RecipeIngredientFormSet
|
||||
from .models import Recipe
|
||||
from .forms import RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet
|
||||
from .models import Recipe, RecipeIngredient, RecipeSubrecipe
|
||||
|
||||
|
||||
def _owned(user):
|
||||
@@ -59,37 +62,59 @@ def detail(request, identifier):
|
||||
return _library(request, recipe)
|
||||
|
||||
|
||||
def _edit(request, recipe=None):
|
||||
creating = recipe is None
|
||||
def _edit(request, recipe=None, allow_draft_resume=False):
|
||||
creating = recipe is None or recipe.pk is None
|
||||
recipe = recipe or Recipe(owner=request.user)
|
||||
old_photo = recipe.photo.name if recipe.pk and recipe.photo else ''
|
||||
form = RecipeForm(request.POST or None, request.FILES or None,
|
||||
instance=recipe, user=request.user)
|
||||
ingredients = RecipeIngredientFormSet(request.POST or None, instance=recipe,
|
||||
prefix='ingredients', user=request.user)
|
||||
if request.method == 'POST' and form.is_valid() and ingredients.is_valid():
|
||||
subrecipes = RecipeSubrecipeFormSet(request.POST or None, instance=recipe,
|
||||
prefix='subrecipes', user=request.user)
|
||||
if request.method == 'POST' and form.is_valid() and ingredients.is_valid() and subrecipes.is_valid():
|
||||
with transaction.atomic():
|
||||
recipe = form.save(commit=False)
|
||||
recipe.owner = request.user
|
||||
if form.cleaned_data['remove_photo']:
|
||||
recipe.photo = ''
|
||||
recipe.full_clean()
|
||||
recipe.save()
|
||||
ingredients.instance = recipe
|
||||
ingredients.save()
|
||||
if old_photo and old_photo != recipe.photo.name:
|
||||
transaction.on_commit(lambda: recipe.photo.storage.delete(old_photo))
|
||||
messages.success(request, 'Recipe saved.')
|
||||
return redirect('recipes:detail', identifier=recipe.api_id)
|
||||
current = Recipe.objects.select_for_update().get(pk=recipe.pk) if not creating else None
|
||||
if (current and current.markdown_revision != form.cleaned_data['markdown_revision'] and
|
||||
not (allow_draft_resume and current.markdown_revision == 1 and
|
||||
form.cleaned_data['markdown_revision'] == 0)):
|
||||
form.add_error(None, 'This recipe changed in another tab. Reload before saving your changes.')
|
||||
else:
|
||||
recipe = form.save(commit=False)
|
||||
recipe.owner = request.user
|
||||
if form.cleaned_data['remove_photo']:
|
||||
recipe.photo = ''
|
||||
if current:
|
||||
recipe.markdown_revision = current.markdown_revision + 1
|
||||
recipe.full_clean()
|
||||
recipe.save()
|
||||
ingredients.instance = recipe
|
||||
ingredients.save()
|
||||
subrecipes.instance = recipe
|
||||
subrecipes.save()
|
||||
if old_photo and old_photo != recipe.photo.name:
|
||||
transaction.on_commit(lambda: recipe.photo.storage.delete(old_photo))
|
||||
messages.success(request, 'Recipe saved.')
|
||||
return redirect('recipes:detail', identifier=recipe.api_id)
|
||||
return render(request, 'recipes/form.html', {
|
||||
'form': form, 'ingredients': ingredients, 'recipe': recipe,
|
||||
'creating': creating,
|
||||
'form': form, 'ingredients': ingredients, 'subrecipes': subrecipes, 'recipe': recipe,
|
||||
'creating': creating, 'new_draft_id': recipe.api_id if creating else None,
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def create(request):
|
||||
if request.method == 'POST' and request.POST.get('draft_id'):
|
||||
try:
|
||||
draft_id = uuid.UUID(request.POST['draft_id'])
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
return HttpResponseBadRequest('Invalid draft ID.')
|
||||
existing = Recipe.objects.filter(api_id=draft_id).first()
|
||||
if existing and existing.owner_id != request.user.pk:
|
||||
raise Http404
|
||||
return _edit(request, existing or Recipe(owner=request.user, api_id=draft_id),
|
||||
allow_draft_resume=bool(existing))
|
||||
return _edit(request)
|
||||
|
||||
|
||||
@@ -99,6 +124,97 @@ def edit(request, identifier):
|
||||
return _edit(request, get_object_or_404(_owned(request.user), api_id=identifier))
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def autosave(request, identifier):
|
||||
try:
|
||||
payload = json.loads(request.body)
|
||||
revision = payload['revision']
|
||||
instructions = payload['instructions_markdown']
|
||||
notes = payload['notes_markdown']
|
||||
title = payload['title']
|
||||
except (ValueError, TypeError, KeyError):
|
||||
return JsonResponse({'error': 'Invalid Markdown data.'}, status=400)
|
||||
if (type(revision) is not int or revision < 0 or
|
||||
not isinstance(instructions, str) or not isinstance(notes, str) or
|
||||
not isinstance(title, str) or not title.strip() or len(title) > 180 or
|
||||
len(instructions) > 100_000 or len(notes) > 100_000):
|
||||
return JsonResponse({'error': 'Invalid Markdown data.'}, status=400)
|
||||
with transaction.atomic():
|
||||
recipe = get_object_or_404(_owned(request.user).select_for_update(), api_id=identifier)
|
||||
if recipe.markdown_revision != revision:
|
||||
return JsonResponse({'error': 'This recipe changed in another tab. Reload to continue.',
|
||||
'revision': recipe.markdown_revision}, status=409)
|
||||
recipe.instructions_markdown = instructions
|
||||
recipe.notes_markdown = notes
|
||||
recipe.title = title.strip()
|
||||
recipe.markdown_revision += 1
|
||||
recipe.save(update_fields=('title', 'instructions_markdown', 'notes_markdown',
|
||||
'markdown_revision', 'updated_at'))
|
||||
return JsonResponse({'revision': recipe.markdown_revision})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def autosave_new(request):
|
||||
try:
|
||||
payload = json.loads(request.body)
|
||||
draft_id = uuid.UUID(payload['draft_id'])
|
||||
title = payload['title']
|
||||
instructions = payload['instructions_markdown']
|
||||
notes = payload['notes_markdown']
|
||||
except (ValueError, TypeError, KeyError, AttributeError):
|
||||
return JsonResponse({'error': 'Invalid draft data.'}, status=400)
|
||||
if (not isinstance(title, str) or not title.strip() or len(title) > 180 or
|
||||
not isinstance(instructions, str) or not isinstance(notes, str) or
|
||||
len(instructions) > 100_000 or len(notes) > 100_000):
|
||||
return JsonResponse({'error': 'Invalid draft data.'}, status=400)
|
||||
with transaction.atomic():
|
||||
recipe = Recipe.objects.select_for_update().filter(api_id=draft_id).first()
|
||||
if recipe is None:
|
||||
recipe = Recipe.objects.create(owner=request.user, api_id=draft_id,
|
||||
title=title.strip(), instructions_markdown=instructions,
|
||||
notes_markdown=notes, markdown_revision=1)
|
||||
elif recipe.owner_id != request.user.pk:
|
||||
return JsonResponse({'error': 'Draft not found.'}, status=404)
|
||||
elif (recipe.title != title.strip() or recipe.instructions_markdown != instructions or
|
||||
recipe.notes_markdown != notes):
|
||||
return JsonResponse({'error': 'This draft changed. Reload to continue.'}, status=409)
|
||||
return JsonResponse({'revision': recipe.markdown_revision,
|
||||
'edit_url': reverse('recipes:edit', args=[recipe.api_id]),
|
||||
'autosave_url': reverse('recipes:autosave', args=[recipe.api_id])})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def create_variation(request, identifier):
|
||||
parent = get_object_or_404(_owned(request.user).prefetch_related('ingredients', 'subrecipes'),
|
||||
api_id=identifier)
|
||||
with transaction.atomic():
|
||||
variation = Recipe.objects.create(
|
||||
owner=request.user, parent=parent, title=f'{parent.title[:160]} variation',
|
||||
description=parent.description, instructions_markdown=parent.instructions_markdown,
|
||||
notes_markdown=parent.notes_markdown, preparation_minutes=parent.preparation_minutes,
|
||||
cooking_minutes=parent.cooking_minutes, default_servings=parent.default_servings,
|
||||
category=parent.category, tags=list(parent.tags), status=Recipe.Status.DRAFT,
|
||||
)
|
||||
RecipeIngredient.objects.bulk_create([
|
||||
RecipeIngredient(recipe=variation, name=item.name, quantity=item.quantity,
|
||||
unit=item.unit, display_order=item.display_order,
|
||||
inventory_product=item.inventory_product,
|
||||
nutrition_product=item.nutrition_product,
|
||||
preparation_note=item.preparation_note, is_optional=item.is_optional)
|
||||
for item in parent.ingredients.all()
|
||||
])
|
||||
RecipeSubrecipe.objects.bulk_create([
|
||||
RecipeSubrecipe(recipe=variation, component=item.component, quantity=item.quantity,
|
||||
unit=item.unit, display_order=item.display_order, note=item.note)
|
||||
for item in parent.subrecipes.all()
|
||||
])
|
||||
messages.success(request, 'Variation created. Edit it to make it your own.')
|
||||
return redirect('recipes:edit', identifier=variation.api_id)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def delete(request, identifier):
|
||||
|
||||
@@ -5,4 +5,6 @@ Pillow==12.3.0
|
||||
django-oauth-toolkit==3.4.1
|
||||
mcp==2.3.0
|
||||
h3==4.5.0
|
||||
Markdown==3.10.2
|
||||
nh3==0.3.3
|
||||
sqlparse==0.6.0
|
||||
|
||||
Reference in New Issue
Block a user