feat: export částečných receptů

This commit is contained in:
Ondřej Anděl committed 2026-11-06 13:39:45 +01:00
1 parent 5e76c404fb
commit 8377ce2205
16 files changed
+446 -147

No files matched your search

+2
View File
@@ -10,6 +10,7 @@
"@fortawesome/free-regular-svg-icons": "^7.1.0",
"@fortawesome/free-solid-svg-icons": "^7.1.0",
"@fortawesome/react-fontawesome": "^3.1.0",
"@pdf-lib/fontkit": "1.1.1",
"@types/mdast": "4.0.4",
"@types/node": "^24.10.0",
"@types/pdfmake": "0.3.3",
@@ -18,6 +19,7 @@
"@vitejs/plugin-react": "^5.1.0",
"bootstrap": "^5.3.8",
"mdast-util-from-markdown": "2.0.3",
"pdf-lib": "1.17.1",
"pdfmake": "0.3.11",
"react": "^19.2.0",
"react-bootstrap": "^2.10.10",
+7
View File
@@ -393,6 +393,13 @@ export const normalizeSearch = (value: string): string =>
export const getMealKey = (meal: { name: string, source?: string }): string =>
`${normalizeSearch(meal.name)}|${normalizeSearch(meal.source ?? '')}`;
/**
* Úplný recept má suroviny i postup. Neúplný jde uložit taky, ale do běžného
* exportu nepatří — exportuje se jen jako PDF k doplnění.
*/
export const isRecipeComplete = (recipe: Pick<MealTemplate, 'ingredients' | 'note'>): boolean =>
recipe.ingredients.length > 0 && !!recipe.note?.trim();
/** Popíše recept jednou řádkou — zdroj a hodnoty jedné porce, co je vyplněné. */
export const describeMealTemplate = (template: MealTemplate): string => [
template.source,
+2 -1
View File
@@ -88,7 +88,8 @@ const MealTemplateForm = ({ template, meal, onSaved, onCancel }: Readonly<Props>
const ingredientWeight = filledIngredients.reduce((sum, item) => sum + (item.weight ?? 0), 0);
const prepMinutes = parseIntInput(form.prepMinutes);
const canSave = form.name.trim().length > 0 && filledIngredients.length > 0 && !busy;
// Suroviny ani postup nejsou povinné — neúplný recept se doplní později (třeba z PDF k doplnění)
const canSave = form.name.trim().length > 0 && !busy;
const save = async () => {
if (!canSave) return;
@@ -0,0 +1,49 @@
import { Button, ButtonGroup, Dropdown, Spinner } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFilePdf } from "@fortawesome/free-solid-svg-icons";
import { MealGroup, MealTemplate } from "../../../types";
import { isRecipeComplete } from "../Utils";
import { useRecipeExport } from "../useRecipeExport";
type RecipeItem = Pick<MealGroup, 'photoCount'> & { recipe: MealTemplate };
type Props = {
/** Recepty, které seznam po filtrech ukazuje */
itemList: RecipeItem[],
filtered: boolean,
loading: boolean,
};
/**
* Hromadný export receptů do PDF. Hlavní tlačítko stáhne jen úplné recepty
* (se surovinami i postupem); v nabídce je export všech včetně neúplných
* s poli k doplnění a opravě — PDF se pošle někomu, kdo recepty zná.
*/
const RecipeExportButton = ({ itemList, filtered, loading }: Readonly<Props>) => {
const { exporting, exportRecipes } = useRecipeExport();
const completeList = itemList.filter(item => isRecipeComplete(item.recipe));
const scope = filtered ? 'zobrazené' : 'všechny';
return (
<Dropdown as={ButtonGroup}>
<Button
variant="outline-secondary"
disabled={exporting || !completeList.length}
title={`Stáhnout ${scope} úplné recepty jako PDF`}
onClick={() => exportRecipes(completeList)}
>
{exporting ? <Spinner animation="border" size="sm" /> : <FontAwesomeIcon icon={faFilePdf} />}
{' '}Recepty do PDF{!loading && ` (${completeList.length})`}
</Button>
<Dropdown.Toggle split variant="outline-secondary" disabled={exporting || !itemList.length} />
<Dropdown.Menu align="end">
<Dropdown.Item onClick={() => exportRecipes(itemList, true)}>
K doplnění, včetně neúplných ({itemList.length})
<div className="small text-muted">čas, porce, hmotnost, chybějící suroviny a postup i poznámky jde dopsat přímo v PDF</div>
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
);
};
export default RecipeExportButton;
+32 -5
View File
@@ -1,5 +1,6 @@
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Button, Form, Modal } from "react-bootstrap";
import { toast } from "react-toastify";
import {
DayRecord, MealEntry, MealSuggestion, MealTemplate, MealType, UserSettings,
addMeal, getMealHistory, getMealTemplates, getSettings, updateMeal,
@@ -24,8 +25,11 @@ type Props = {
/** Upravovaný záznam. Pokud chybí, jde o založení nového. */
entry?: MealEntry,
onClose: () => void,
/** Zavolá se po uložení s přehledem dne a uloženým jídlem. */
onSaved: (day: DayRecord, saved?: MealEntry) => void,
/**
* Zavolá se po uložení s přehledem dne a uloženým jídlem. `keepOpen` značí
* uložení s pokračováním — formulář zůstává otevřený pro další jídlo.
*/
onSaved: (day: DayRecord, saved?: MealEntry, keepOpen?: boolean) => void,
};
/** Prázdný formulář pro nové jídlo v daném dni. */
@@ -93,6 +97,7 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
const [history, setHistory] = useState<MealSuggestion[]>([]);
/** Název návrhu, ze kterého se formulář naposledy vyplnil — pak už se návrhy nenabízejí. */
const [pickedSuggestion, setPickedSuggestion] = useState<string | undefined>();
const nameRef = useRef<HTMLInputElement>(null);
// Při každém otevření se formulář naplní dle toho, co se upravuje
useEffect(() => {
@@ -201,7 +206,12 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
const canSave = form.name.trim().length > 0 && !multiplierInvalid && !nutrientsInvalid && !saving;
const save = async () => {
/**
* Uloží jídlo. S `keepOpen` formulář nezavře, jen ho vyčistí pro další jídlo —
* celý den se tak zapíše bez opakovaného otevírání. Datum a chod zůstanou,
* další jídlo bývá ze stejného dne.
*/
const save = async (keepOpen = false) => {
if (!canSave) return;
setSaving(true);
const body = {
@@ -228,7 +238,13 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
const saved = entry
? response.data.entries.find(item => item.id === entry.id)
: [...response.data.entries].sort((a, b) => a.createdAt.localeCompare(b.createdAt)).pop();
onSaved(response.data, saved);
onSaved(response.data, saved, keepOpen);
if (keepOpen) {
toast.success(`Uloženo: ${body.name}`);
setForm({ ...emptyForm(form.date), mealType: form.mealType });
setPickedSuggestion(undefined);
nameRef.current?.focus();
}
}
};
@@ -242,6 +258,7 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
<Form.Group className="mb-3">
<Form.Label>Jídlo</Form.Label>
<Form.Control
ref={nameRef}
autoFocus
value={form.name}
placeholder="Např. Kuřecí gyros s hranolkami"
@@ -433,6 +450,16 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
)}
</div>
<Button variant="outline-secondary" onClick={onClose}>Zrušit</Button>
{!entry && (
<Button
variant="outline-primary"
title="Uloží jídlo a vyčistí formulář pro další"
onClick={() => save(true)}
disabled={!canSave}
>
Uložit a další
</Button>
)}
<Button onClick={() => save()} disabled={!canSave}>
{saving ? 'Ukládám…' : 'Uložit'}
</Button>
+23 -13
View File
@@ -1,6 +1,6 @@
import { fromMarkdown } from "mdast-util-from-markdown";
import type { BlockContent, DefinitionContent, ListItem, PhrasingContent, RootContent } from "mdast";
import type { Content } from "pdfmake/interfaces";
import type { Content, ContentText } from "pdfmake/interfaces";
import { applyLineBreaks } from "./markdownBreaks";
/** Barva odkazů a citací — stejná jako text vedle, jen tlumenější. */
@@ -8,31 +8,41 @@ const MUTED_COLOR = '#6b7280';
const LINK_COLOR = '#15803d';
const CODE_BACKGROUND = '#f3f4f6';
const convertInline = (nodeList: PhrasingContent[]): Content[] => nodeList.map(convertPhrasing);
/** Formátování zděděné od nadřazených uzlů (tučně uvnitř odkazu, kurzíva uvnitř tučného…). */
type InlineStyle = Pick<ContentText, 'bold' | 'italics' | 'decoration' | 'background' | 'color' | 'link'>;
const convertPhrasing = (node: PhrasingContent): Content => {
/**
* Inline obsah se skládá do plochého pole textů, každý s celým svým formátováním.
* pdfmake styl vnořeného pole `text` zahodí (bpampuch/pdfmake#1174) — tučné
* nebo kurzíva by se ztratily, jakmile je kolem ještě další úroveň, typicky
* v položce seznamu.
*/
const convertInline = (nodeList: PhrasingContent[], style: InlineStyle = {}): Content[] =>
nodeList.flatMap(node => convertPhrasing(node, style));
const convertPhrasing = (node: PhrasingContent, style: InlineStyle): Content[] => {
switch (node.type) {
case 'text':
return node.value;
return [{ ...style, text: node.value }];
case 'strong':
return { text: convertInline(node.children), bold: true };
return convertInline(node.children, { ...style, bold: true });
case 'emphasis':
return { text: convertInline(node.children), italics: true };
return convertInline(node.children, { ...style, italics: true });
case 'delete':
return { text: convertInline(node.children), decoration: 'lineThrough' };
return convertInline(node.children, { ...style, decoration: 'lineThrough' });
case 'inlineCode':
return { text: node.value, background: CODE_BACKGROUND };
return [{ ...style, text: node.value, background: CODE_BACKGROUND }];
case 'break':
return '\n';
return [{ ...style, text: '\n' }];
case 'link':
return { text: convertInline(node.children), link: node.url, color: LINK_COLOR, decoration: 'underline' };
return convertInline(node.children, { ...style, link: node.url, color: LINK_COLOR, decoration: 'underline' });
// Obrázky z internetu se do PDF nestahují, zůstane popisek
case 'image':
return node.alt ?? '';
return [{ ...style, text: node.alt ?? '' }];
case 'html':
return node.value;
return [{ ...style, text: node.value }];
default:
return 'children' in node ? convertInline(node.children as PhrasingContent[]) : '';
return 'children' in node ? convertInline(node.children as PhrasingContent[], style) : [];
}
};
+2 -2
View File
@@ -421,8 +421,8 @@ export default function DayPage() {
date={date}
entry={editedMeal}
onClose={() => setMealModalOpen(false)}
onSaved={(saved, savedEntry) => {
setMealModalOpen(false);
onSaved={(saved, savedEntry, keepOpen) => {
if (!keepOpen) setMealModalOpen(false);
const hasNutrition = savedEntry?.calories != null || !!savedEntry?.nutrientsPer100g;
setFillOfferEntry(hasNutrition ? savedEntry : undefined);
// Úprava mohla jídlo přesunout jinam — pak přepneme na jeho nový den
+3 -12
View File
@@ -2,13 +2,13 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import { Button, Form, Spinner } from "react-bootstrap";
import { useLocation } from "react-router";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBookOpen, faCircleCheck, faFilePdf } from "@fortawesome/free-solid-svg-icons";
import { faBookOpen, faCircleCheck } from "@fortawesome/free-solid-svg-icons";
import { MealGroup, MealTemplate, getMealGroups } from "../../../types";
import { MealGroupAction, RECIPE_FILTER_NAMES, RecipeFilter, SourceFilter } from "../enums";
import { getMealKey, normalizeSearch } from "../Utils";
import MealGroupRow from "../components/MealGroupRow";
import MealTemplateForm from "../components/MealTemplateForm";
import { useRecipeExport } from "../useRecipeExport";
import RecipeExportButton from "../components/RecipeExportButton";
import "./templates.scss";
import "./MealGroupsPage.scss";
@@ -75,7 +75,6 @@ const MealGroupsPage = () => {
const [opened, setOpened] = useState<{ key: string, action: MealGroupAction } | undefined>();
const [newRecipeOpen, setNewRecipeOpen] = useState(false);
const [scrollKey, setScrollKey] = useState<string | undefined>();
const { exporting, exportRecipes } = useRecipeExport();
const load = useCallback(async () => {
const response = await getMealGroups();
@@ -138,15 +137,7 @@ const MealGroupsPage = () => {
</p>
</div>
<div className="page-header-actions">
<Button
variant="outline-secondary"
disabled={exporting || !visibleRecipeList.length}
title={filtered ? 'Stáhnout zobrazené recepty jako PDF' : 'Stáhnout všechny recepty jako PDF'}
onClick={() => exportRecipes(visibleRecipeList)}
>
{exporting ? <Spinner animation="border" size="sm" /> : <FontAwesomeIcon icon={faFilePdf} />}
{' '}Recepty do PDF{!loading && ` (${visibleRecipeList.length})`}
</Button>
<RecipeExportButton itemList={visibleRecipeList} filtered={filtered} loading={loading} />
<Button variant="outline-secondary" onClick={() => setNewRecipeOpen(open => !open)}>
<FontAwesomeIcon icon={faBookOpen} /> Nový recept
</Button>
+74
View File
@@ -0,0 +1,74 @@
import type { NodeStartPosition } from "pdfmake/interfaces";
/** Formulářové pole PDF, pro které pdfmake vyhradil místo v dokumentu. */
export type PdfFormField = {
/** Jednoznačný název pole v dokumentu — bez teček, ty v PDF dělají hierarchii */
name: string,
width: number,
height: number,
multiline: boolean,
/** Předvyplněná hodnota, kterou jde v PDF přepsat */
value?: string,
};
export type PlacedPdfFormField = PdfFormField & { position: NodeStartPosition };
/** Odsazení textu od okraje pole, aby se nelepil na rámeček vykreslený pdfmake. */
const FIELD_INSET = 2;
const FIELD_FONT_SIZE = 10;
const decodeBase64 = (value: string): Uint8Array => Uint8Array.from(atob(value), char => char.charCodeAt(0));
/**
* Doplní do hotového PDF vyplnitelná textová pole. pdfmake formuláře neumí, takže
* v dokumentu jen vykreslí rámeček a pole se přes něj položí dodatečně (pdf-lib).
* Souřadnice z pdfmake počítají od horního okraje, PDF od spodního.
*
* Písmo polí je celé (ne podmnožina) Roboto — výchozí Helvetica neumí českou
* diakritiku a podmnožina by měla jen znaky, které už v dokumentu jsou.
*
* @param pdfBytes PDF vygenerované pdfmake
* @param fieldList pole s pozicí, kterou pdfmake vyhradil
* @param fontBase64 písmo pro text polí (TTF v base64, jak ho nese vfs pdfmake)
*/
export const addFormFields = async (
pdfBytes: Uint8Array, fieldList: PlacedPdfFormField[], fontBase64: string,
): Promise<Uint8Array> => {
const [{ PDFDocument }, { default: fontkit }] = await Promise.all([import("pdf-lib"), import("@pdf-lib/fontkit")]);
const pdf = await PDFDocument.load(pdfBytes);
pdf.registerFontkit(fontkit);
const font = await pdf.embedFont(decodeBase64(fontBase64), { subset: false });
const form = pdf.getForm();
for (const field of fieldList) {
const page = pdf.getPage(field.position.pageNumber - 1);
const textField = form.createTextField(field.name);
if (field.multiline) textField.enableMultiline();
textField.addToPage(page, {
x: field.position.left + FIELD_INSET,
y: page.getHeight() - field.position.top - field.height + FIELD_INSET,
width: field.width - 2 * FIELD_INSET,
height: field.height - 2 * FIELD_INSET,
font,
// Rámeček i podklad kreslí pdfmake, aby pole bylo vidět i po vytištění
borderWidth: 0,
backgroundColor: undefined,
borderColor: undefined,
});
textField.setFontSize(FIELD_FONT_SIZE);
if (field.value) textField.setText(field.value);
}
form.updateFieldAppearances(font);
return pdf.save();
};
/** Nabídne PDF ke stažení. */
export const downloadPdf = (pdfBytes: Uint8Array, fileName: string) => {
const url = URL.createObjectURL(new Blob([pdfBytes as BlobPart], { type: 'application/pdf' }));
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
// Prohlížeč si soubor převezme až po kliknutí, adresa se uvolní s odstupem
setTimeout(() => URL.revokeObjectURL(url), 10000);
};
+163 -97
View File
@@ -1,10 +1,11 @@
import type { Content, TDocumentDefinitions } from "pdfmake/interfaces";
import type { Content, ContentCanvas, Node, NodeQueries, NodeStartPosition, TDocumentDefinitions } from "pdfmake/interfaces";
import { MealGroup, MealPhoto, MealTemplate, getMealPhotos, getMealTemplates } from "../../types";
import { RECIPE_FLAVOR_NAMES, RECIPE_LINK_NAMES, RecipeLinkKind, getRecipeLinkIds } from "./enums";
import { convertMarkdownToPdf } from "./markdownPdf";
import type { PdfFormField } from "./pdfFormFields";
import {
deriveRecipe, formatCalories, formatCount, formatDate, formatDateString, formatIngredientAmount, formatPrepTime,
formatPrice, formatWeight, getIngredientCalories,
formatPrice, formatWeight, getIngredientCalories, isRecipeComplete,
} from "./Utils";
/** Recept s počtem fotek jídla — fotky se stahují jen tam, kde nějaké jsou. */
@@ -13,10 +14,24 @@ type RecipeItem = Pick<MealGroup, 'photoCount'> & { recipe: MealTemplate };
const PRIMARY_COLOR = '#156080';
const MUTED_COLOR = '#6b7280';
const BORDER_COLOR = '#e5e7eb';
const FIELD_BORDER_COLOR = '#9ca3af';
const FIELD_BACKGROUND = '#f9fafb';
/** Šířka tisknutelné plochy A4 při okrajích 40 pt. */
const CONTENT_WIDTH = 515;
const PHOTO_GAP = 8;
const SMALL_PHOTOS_PER_ROW = 3;
const PHOTO_COLUMN_WIDTH = 220;
/** Rozměry polí k doplnění v pt. */
const SHORT_FIELD_WIDTH = 160;
const SHORT_FIELD_HEIGHT = 20;
const SHORT_FIELD_GAP = 17;
/** Výšky velkých polí jsou zvolené tak, aby se recept jen s názvem vešel na jednu stránku. */
const INGREDIENTS_FIELD_HEIGHT = 150;
const NOTE_FIELD_HEIGHT = 230;
const REMARKS_FIELD_HEIGHT = 90;
/** Předpony `id` uzlů, podle kterých se v rozvržení pdfmake najdou pole a jejich popisky. */
const FIELD_ID_PREFIX = 'pole:';
const LABEL_ID_PREFIX = 'popisek:';
/** pdfmake umí jen JPEG a PNG; fotky se sice ukládají jako JPEG, API ale přijímá i WebP. */
const isSupportedImage = (photo: MealPhoto): boolean => /^data:image\/(jpeg|png)/.test(photo.image);
@@ -24,12 +39,17 @@ const isSupportedImage = (photo: MealPhoto): boolean => /^data:image\/(jpeg|png)
/** Název souboru bez znaků, které systémy v názvu nepovolí. */
const toFileName = (name: string): string => `${name.replace(/[\\/:*?"<>|]+/g, '').trim() || 'recept'}.pdf`;
const getRecipeMeta = (recipe: MealTemplate): string => {
/**
* Čas přípravy a počet porcí se v PDF k doplnění nevypisují — jsou v polích,
* kde jdou opravit, a „1 porce" by u nevyplněných porcí tvrdilo něco, co je
* teprve k doplnění.
*/
const getRecipeMeta = (recipe: MealTemplate, editable: boolean): string => {
return [
recipe.category,
RECIPE_FLAVOR_NAMES[recipe.flavor].toLowerCase(),
recipe.prepMinutes != null ? `příprava ${formatPrepTime(recipe.prepMinutes)}` : undefined,
formatCount(recipe.servings ?? 1, 'porce', 'porce', 'porcí'),
!editable && recipe.prepMinutes != null ? `příprava ${formatPrepTime(recipe.prepMinutes)}` : undefined,
!editable ? formatCount(recipe.servings ?? 1, 'porce', 'porce', 'porcí') : undefined,
recipe.weight != null ? `porce ${formatWeight(recipe.weight)}` : undefined,
recipe.calories != null ? `${formatCalories(recipe.calories)} na porci` : undefined,
recipe.price != null ? `${formatPrice(recipe.price)} za porci` : undefined,
@@ -63,21 +83,9 @@ const createLinks = (recipe: MealTemplate, recipeList: MealTemplate[], indexMap:
return [{ text: [{ text: `${RECIPE_LINK_NAMES[kind]}: `, bold: true }, ...nameList], style: 'recipeLinks' }];
});
const PHOTO_COLUMN_WIDTH = 220;
const createPhotos = (photoList: MealPhoto[]): Content[] => {
const first = photoList[0];
if (!first) {
return [];
}
return [
{
image: first.image,
width: PHOTO_COLUMN_WIDTH,
alignment: 'center',
},
];
return first ? [{ image: first.image, width: PHOTO_COLUMN_WIDTH, alignment: 'center' }] : [];
};
const createIngredients = (recipe: MealTemplate): Content[] => {
@@ -118,92 +126,129 @@ const createIngredients = (recipe: MealTemplate): Content[] => {
];
};
/**
* Místo pro vyplnitelné pole: popisek a rámeček. Samotné pole položí přes
* rámeček až `addFormFields`, pdfmake formuláře neumí. Pole se zapíše do
* `fieldList`, aby se k němu po rozvržení dohledala pozice.
*/
const createField = (fieldList: PdfFormField[], field: PdfFormField, label: Content, labelStyle: string): Content[] => {
fieldList.push(field);
// Typy pdfmake u plátna `id` nepovolují, pdfmake ho ale předá do pageBreakBefore jako u každého uzlu
const box: ContentCanvas & { id: string } = {
canvas: [{
type: 'rect', x: 0, y: 0, w: field.width, h: field.height, r: 2,
color: FIELD_BACKGROUND, lineColor: FIELD_BORDER_COLOR, lineWidth: 0.6,
}],
id: FIELD_ID_PREFIX + field.name,
margin: [0, 2, 0, 0],
};
return [{ text: label, style: labelStyle, id: LABEL_ID_PREFIX + field.name }, box as Content];
};
/**
* Pole receptu v PDF k doplnění — vyplní je ten, kdo recept zná, přímo v PDF
* a údaje se pak do aplikace přepíšou ručně. Čas, porce a hmotnost jsou vždy,
* předvyplněné tím, co recept už má, aby šly i opravit. Suroviny a postup jsou
* pole jen tam, kde chybí (jedno volné textové pole); chybu v hotových jde
* popsat v poznámkách. Energie chybí záměrně, tu si uživatel dohledá sám.
*/
const createEditableFields = (recipe: MealTemplate, index: number, fieldList: PdfFormField[]) => {
const prefix = `recept${index + 1}`;
const shortList = [
{ key: 'priprava', label: 'Čas přípravy (minuty)', value: recipe.prepMinutes },
{ key: 'porce', label: 'Počet porcí', value: recipe.servings },
{ key: 'hmotnost', label: 'Hmotnost hotového jídla (g)', value: recipe.cookedWeight },
];
const details: Content[] = [{
columns: shortList.map(item => ({
width: SHORT_FIELD_WIDTH,
stack: createField(fieldList, {
name: `${prefix}_${item.key}`, width: SHORT_FIELD_WIDTH, height: SHORT_FIELD_HEIGHT, multiline: false,
value: item.value != null ? String(item.value) : undefined,
}, item.label, 'fieldLabel'),
})),
columnGap: SHORT_FIELD_GAP,
margin: [0, 0, 0, 4],
}];
const ingredients = recipe.ingredients.length ? [] : createField(fieldList, {
name: `${prefix}_suroviny`, width: CONTENT_WIDTH, height: INGREDIENTS_FIELD_HEIGHT, multiline: true,
}, ['Suroviny', { text: ' jedna na řádek, s množstvím', style: 'fieldHint' }], 'sectionHeading');
const note = recipe.note?.trim() ? [] : createField(fieldList, {
name: `${prefix}_postup`, width: CONTENT_WIDTH, height: NOTE_FIELD_HEIGHT, multiline: true,
}, 'Postup', 'sectionHeading');
const remarks = createField(fieldList, {
name: `${prefix}_poznamky`, width: CONTENT_WIDTH, height: REMARKS_FIELD_HEIGHT, multiline: true,
}, ['Poznámky a opravy', { text: ' chyba v surovinách nebo postupu, cokoli dalšího', style: 'fieldHint' }], 'sectionHeading');
return { details, ingredients, note, remarks };
};
type RecipeContext = {
index: number,
withToc: boolean,
recipeList: MealTemplate[],
indexMap: Map<string, number>,
fieldList: PdfFormField[],
/** Všechny recepty dostanou pole k doplnění, nejen neúplné */
editable: boolean,
};
const createRecipe = (
recipe: MealTemplate, photoList: MealPhoto[], { index, withToc, recipeList, indexMap }: RecipeContext,
recipe: MealTemplate, photoList: MealPhoto[],
{ index, withToc, recipeList, indexMap, fieldList, editable }: RecipeContext,
): Content => {
const hasPhotos = photoList.length > 0;
return ({
const fields = editable || !isRecipeComplete(recipe) ? createEditableFields(recipe, index, fieldList) : undefined;
const header: Content[] = [
{ text: recipe.name, style: 'recipeTitle', id: getRecipeAnchor(index), tocItem: withToc },
...(recipe.source ? [{ text: recipe.source, style: 'recipeSource' }] : []),
{ text: getRecipeMeta(recipe, !!fields), style: 'recipeMeta' },
...(fields
? [{ text: 'Údaje v polích jde doplnit nebo opravit přímo v PDF a soubor uložit.', style: 'fieldHint', margin: [0, -8, 0, 12] as [number, number, number, number] }]
: []),
...createLinks(recipe, recipeList, indexMap),
...createIngredients(recipe),
];
return {
stack: [
...(hasPhotos
...(photoList.length
? [{
columns: [
{
width: '*',
stack: [
{
text: recipe.name,
style: 'recipeTitle',
id: getRecipeAnchor(index),
tocItem: withToc,
},
...(recipe.source
? [{ text: recipe.source, style: 'recipeSource' }]
: []),
{
text: getRecipeMeta(recipe),
style: 'recipeMeta',
},
...createLinks(recipe, recipeList, indexMap),
...createIngredients(recipe),
],
},
{
width: 220,
stack: createPhotos(photoList),
},
{ width: '*', stack: header },
{ width: PHOTO_COLUMN_WIDTH, stack: createPhotos(photoList) },
],
columnGap: 20,
}]
: [
{
text: recipe.name,
style: 'recipeTitle',
id: getRecipeAnchor(index),
tocItem: withToc,
},
...(recipe.source
? [{ text: recipe.source, style: 'recipeSource' }]
: []),
{
text: getRecipeMeta(recipe),
style: 'recipeMeta',
},
...createLinks(recipe, recipeList, indexMap),
...createIngredients(recipe),
]),
: header),
...(fields?.ingredients ?? []),
...(fields?.details ?? []),
...(recipe.note?.trim()
? [
{
text: 'Postup',
style: 'sectionHeading',
},
...convertMarkdownToPdf(recipe.note),
]
: []),
? [{ text: 'Postup', style: 'sectionHeading' }, ...convertMarkdownToPdf(recipe.note)]
: fields?.note ?? []),
...(fields?.remarks ?? []),
],
// Každý recept začíná na nové stránce, první hned za obsahem
...(index > 0 || withToc ? { pageBreak: 'before' as const } : {}),
};
};
// Každý recept začíná na nové stránce, první hned za obsahem
...(index > 0 || withToc
? { pageBreak: 'before' as const }
: {}),
});
}
/**
* Při rozvržení si zapamatuje, kde pdfmake vykreslil rámečky polí, a popisek,
* jehož pole se na stránku nevešlo, přesune na další stránku za ním. pdfmake
* jinou cestu k pozicím uzlů nemá; pozice holého uzlu (ne uvnitř `unbreakable`
* nebo tabulky) odpovídá místu vykreslení.
*/
const trackFieldPositions = (positionMap: Map<string, NodeStartPosition>) =>
(node: Node, { getFollowingNodesOnPage }: NodeQueries): boolean => {
if (node.id?.startsWith(FIELD_ID_PREFIX)) {
positionMap.set(node.id.slice(FIELD_ID_PREFIX.length), node.startPosition);
} else if (node.id?.startsWith(LABEL_ID_PREFIX)) {
const fieldId = FIELD_ID_PREFIX + node.id.slice(LABEL_ID_PREFIX.length);
return !getFollowingNodesOnPage().some(item => item.id === fieldId);
}
return false;
};
const loadPhotos = async (item: RecipeItem): Promise<MealPhoto[]> => {
if (!item.photoCount) return [];
@@ -221,17 +266,21 @@ const loadPdfMake = async () => {
const pdfMake = pdfMakeModule.default;
const vfs = vfsModule.default;
pdfMake.addVirtualFileSystem(vfs);
return pdfMake;
return { pdfMake, vfs: vfs as Record<string, string> };
};
/**
* Stáhne recepty jako PDF — suroviny, hodnoty porce, postup a fotky jídla.
* Víc receptů dostane titulní stránku s klikacím obsahem a každý recept
* začíná na nové stránce.
*
* S `editable` dostane každý recept vyplnitelná pole PDF k doplnění a opravě
* (`createEditableFields`); neúplný recept (bez surovin nebo postupu) je
* dostane vždy.
*/
export const exportRecipesPdf = async (itemList: RecipeItem[]): Promise<void> => {
export const exportRecipesPdf = async (itemList: RecipeItem[], editable = false): Promise<void> => {
const sortedList = [...itemList].sort((a, b) => a.recipe.name.localeCompare(b.recipe.name, 'cs'));
const [pdfMake, photoLists, recipeResponse] = await Promise.all([
const [{ pdfMake, vfs }, photoLists, recipeResponse] = await Promise.all([
loadPdfMake(),
Promise.all(sortedList.map(loadPhotos)),
getMealTemplates(),
@@ -240,6 +289,9 @@ export const exportRecipesPdf = async (itemList: RecipeItem[]): Promise<void> =>
const indexMap = new Map(sortedList.map((item, index) => [item.recipe.id, index]));
const withToc = sortedList.length > 1;
const title = withToc ? 'Recepty' : sortedList[0]?.recipe.name ?? 'Recept';
const fileName = withToc ? 'recepty.pdf' : toFileName(title);
const fieldList: PdfFormField[] = [];
const positionMap = new Map<string, NodeStartPosition>();
const cover: Content[] = withToc ? [
{ text: 'Recepty', style: 'coverTitle' },
@@ -253,15 +305,16 @@ export const exportRecipesPdf = async (itemList: RecipeItem[]): Promise<void> =>
},
] : [];
// Sestavením obsahu se naplní i fieldList, proto musí proběhnout před definicí
const recipeContent = sortedList.map((item, index) =>
createRecipe(item.recipe, photoLists[index], { index, withToc, recipeList, indexMap, fieldList, editable }));
const definition: TDocumentDefinitions = {
info: { title },
pageSize: 'A4',
pageMargins: [40, 40, 40, 50],
content: [
...cover,
...sortedList.map((item, index) =>
createRecipe(item.recipe, photoLists[index], { index, withToc, recipeList, indexMap })),
],
content: [...cover, ...recipeContent],
pageBreakBefore: fieldList.length ? trackFieldPositions(positionMap) : undefined,
footer: (currentPage, pageCount) => ({
text: `${currentPage} / ${pageCount}`,
alignment: 'center',
@@ -282,8 +335,21 @@ export const exportRecipesPdf = async (itemList: RecipeItem[]): Promise<void> =>
noteSubheading: { fontSize: 10.5, bold: true, margin: [0, 6, 0, 3] },
noteParagraph: { margin: [0, 0, 0, 6] },
noteList: { margin: [0, 0, 0, 6] },
fieldLabel: { fontSize: 9, bold: true, color: MUTED_COLOR, margin: [0, 6, 0, 0] },
fieldHint: { fontSize: 9, bold: false, italics: true, color: MUTED_COLOR },
},
};
await pdfMake.createPdf(definition).download(withToc ? 'recepty.pdf' : toFileName(title));
const document = pdfMake.createPdf(definition);
if (!fieldList.length) {
await document.download(fileName);
return;
}
const { addFormFields, downloadPdf } = await import("./pdfFormFields");
const pdfBytes = new Uint8Array(await document.getBuffer());
const placedList = fieldList.flatMap(field => {
const position = positionMap.get(field.name);
return position ? [{ ...field, position }] : [];
});
downloadPdf(await addFormFields(pdfBytes, placedList, vfs['Roboto-Regular.ttf']), fileName);
};
+2 -2
View File
@@ -6,11 +6,11 @@ import { exportRecipesPdf } from "./recipePdf";
export const useRecipeExport = () => {
const [exporting, setExporting] = useState(false);
const exportRecipes = async (itemList: Parameters<typeof exportRecipesPdf>[0]) => {
const exportRecipes = async (itemList: Parameters<typeof exportRecipesPdf>[0], editable = false) => {
if (exporting || !itemList.length) return;
setExporting(true);
try {
await exportRecipesPdf(itemList);
await exportRecipesPdf(itemList, editable);
} catch (error) {
console.error('Export receptů do PDF selhal', error);
toast.error('PDF se nepodařilo vytvořit.');
+37 -1
View File
@@ -479,6 +479,27 @@
"@parcel/watcher-win32-arm64" "2.6.0"
"@parcel/watcher-win32-x64" "2.6.0"
"@pdf-lib/fontkit@1.1.1":
version "1.1.1"
resolved "https://registry.yarnpkg.com/@pdf-lib/fontkit/-/fontkit-1.1.1.tgz#f18473892b65e3253eb73f4569785abd2c03b1e0"
integrity sha512-KjMd7grNapIWS/Dm0gvfHEilSyAmeLvrEGVcqLGi0VYebuqqzTbgF29efCx7tvx+IEbG3zQciRSWl3GkUSvjZg==
dependencies:
pako "^1.0.6"
"@pdf-lib/standard-fonts@^1.0.0":
version "1.0.0"
resolved "https://registry.yarnpkg.com/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz#8ba691c4421f71662ed07c9a0294b44528af2d7f"
integrity sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==
dependencies:
pako "^1.0.6"
"@pdf-lib/upng@^1.0.1":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@pdf-lib/upng/-/upng-1.0.1.tgz#7dc9c636271aca007a9df4deaf2dd7e7960280cb"
integrity sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==
dependencies:
pako "^1.0.10"
"@popperjs/core@^2.11.8":
version "2.11.8"
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.8.tgz#6b79032e760a0899cd4204710beede972a3a185f"
@@ -1751,7 +1772,7 @@ pako@^0.2.5:
resolved "https://registry.yarnpkg.com/pako/-/pako-0.2.9.tgz#f3f7522f4ef782348da8161bad9ecfd51bf83a75"
integrity sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==
pako@~1.0.5:
pako@^1.0.10, pako@^1.0.11, pako@^1.0.6, pako@~1.0.5:
version "1.0.11"
resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.11.tgz#6c9599d340d54dfd3946380252a35705a6b992bf"
integrity sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==
@@ -1769,6 +1790,16 @@ parse-entities@^4.0.0:
is-decimal "^2.0.0"
is-hexadecimal "^2.0.0"
pdf-lib@1.17.1:
version "1.17.1"
resolved "https://registry.yarnpkg.com/pdf-lib/-/pdf-lib-1.17.1.tgz#9e7dd21261a0c1fb17992580885b39e7d08f451f"
integrity sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==
dependencies:
"@pdf-lib/standard-fonts" "^1.0.0"
"@pdf-lib/upng" "^1.0.1"
pako "^1.0.11"
tslib "^1.11.1"
pdfkit@^0.19.1:
version "0.19.1"
resolved "https://registry.yarnpkg.com/pdfkit/-/pdfkit-0.19.1.tgz#633d5f031ce6f1ba6ce141325c6cf87fa6acb0a2"
@@ -2179,6 +2210,11 @@ tsconfck@^3.0.3:
resolved "https://registry.yarnpkg.com/tsconfck/-/tsconfck-3.1.6.tgz#da1f0b10d82237ac23422374b3fce1edb23c3ead"
integrity sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==
tslib@^1.11.1:
version "1.14.1"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"
integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==
tslib@^2.0.0, tslib@^2.8.0:
version "2.8.1"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f"