feat: built-in template gallery with a DIN 5008 letter

lib/templates/: registry + one module per template, localized via t()
at build time. applyTemplate (App.svelte) reuses the extracted
resetDocumentState() from handleNew, then assigns the template's
margins, styles and fold marks; no file handle, so Save asks where.
Gallery dialog reachable from the ribbon File menu and the modern
chrome; first template is a DIN 5008 Form B business letter built from
placeholder fields, with the address field at 45mm and a 10cm info tab.
This commit is contained in:
Steffen Becker committed 2026-08-24 16:54:03 +00:00
1 parent a5c072db23
commit 0f8bca31cd
8 files changed
+381 -8

No files matched your search

+47 -7
View File
@@ -51,6 +51,8 @@
import LanguagePicker from './lib/components/LanguagePicker.svelte';
import UiLanguagePicker from './lib/components/UiLanguagePicker.svelte';
import AboutDialog from './lib/components/AboutDialog.svelte';
import TemplateGalleryDialog from './lib/components/TemplateGalleryDialog.svelte';
import type { TemplateEntry } from './lib/templates/types';
import DocPropertiesDialog from './lib/components/DocPropertiesDialog.svelte';
import CommentsPane from './lib/components/CommentsPane.svelte';
import RevisionsPane from './lib/components/RevisionsPane.svelte';
@@ -184,6 +186,7 @@
let pageDecor: PageDecor = $state(loadPageDecor());
let lineNumbering: LineNumbering = $state(loadLineNumbering());
let foldMarks = $state(loadFoldMarks());
let templateGalleryOpen = $state(false);
let autoCorrectOpen = $state(false);
let autoTextOpen = $state(false);
let thesaurusOpen = $state(false);
@@ -535,13 +538,9 @@
editor?.chain().setMeta(RECORDING, true).setContent(content).run();
}
function handleNew() {
if (!editor) return;
if (isDocNonEmpty() && !confirm(t().dialogs.confirmNew)) return;
loadContent('<p></p>'); // onUpdate fires → autosave
documentEpoch++;
resetHistory();
// Reset everything to defaults; the $effects persist these.
// Reset every document side-car to its default; the $effects persist these.
// Shared by New and New-from-template, which then assigns the template's own values.
function resetDocumentState() {
hfActive = null;
headerDoc = null;
footerDoc = null;
@@ -575,6 +574,37 @@
setNoteSettings(DEFAULT_NOTE_SETTINGS);
clearEmbeddedFonts();
void clearEmbeddedFontStore();
}
function handleNew() {
if (!editor) return;
if (isDocNonEmpty() && !confirm(t().dialogs.confirmNew)) return;
loadContent('<p></p>'); // onUpdate fires → autosave
documentEpoch++;
resetHistory();
resetDocumentState();
editor.commands.focus();
}
// A built-in template: a full reset, then the template's content and side-cars —
// the same set an .ott import adopts. No file handle, so the first Save asks where.
function applyTemplate(entry: TemplateEntry) {
if (!editor) return;
if (isDocNonEmpty() && !confirm(t().dialogs.confirmNew)) return;
const data = entry.build();
loadContent(data.content);
documentEpoch++;
resetHistory();
resetDocumentState();
if (data.margins) pageMargins = { ...data.margins };
if (data.styles?.length) {
const sheet = styleSheet();
const paragraph = { ...sheet.paragraph };
for (const s of data.styles) paragraph[s.name] = s;
setStyleSheet({ ...sheet, paragraph });
}
foldMarks = data.foldMarks === true;
documentName = entry.name();
editor.commands.focus();
}
@@ -1118,6 +1148,7 @@
{docxBusy}
{pdfBusy}
onNew={handleNew}
onNewFromTemplate={() => (templateGalleryOpen = true)}
onOpen={handleOpen}
onSave={handleSave}
onSaveAs={handleSaveAs}
@@ -1193,6 +1224,14 @@
<path d="M8 8v3.5M6.25 9.75h3.5" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
</svg>
</button>
<button class="file-action-btn" onclick={() => (templateGalleryOpen = true)} disabled={!editor} title={t().templates.title}>
<!-- Page with folded corner + text lines: new from template -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path d="M9 1.75H4.5A1.25 1.25 0 0 0 3.25 3v10A1.25 1.25 0 0 0 4.5 14.25h7A1.25 1.25 0 0 0 12.75 13V5.5L9 1.75z" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/>
<path d="M9 1.75V5.5h3.75" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/>
<path d="M5.5 8.5h5M5.5 10.5h5M5.5 12.5h3" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
</svg>
</button>
<button class="file-action-btn" onclick={handleOpen} disabled={!editor} title={`${t().app.open} (${shortcutHint('open')})`}>
<!-- Folder -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
@@ -1527,6 +1566,7 @@
</footer>
<AboutDialog bind:open={aboutOpen} />
<TemplateGalleryDialog bind:open={templateGalleryOpen} onPick={applyTemplate} />
<AutoCorrectDialog bind:open={autoCorrectOpen} />
<AutoTextDialog bind:open={autoTextOpen} editor={activeEditor} />
<ThesaurusDialog bind:open={thesaurusOpen} editor={activeEditor} />
@@ -0,0 +1,175 @@
<script lang="ts">
import { t } from '../i18n/i18n.svelte';
import { TEMPLATES } from '../templates/registry';
import type { TemplateEntry } from '../templates/types';
let { open = $bindable(false), onPick }: {
open?: boolean;
onPick?: (entry: TemplateEntry) => void;
} = $props();
let dialogEl: HTMLDialogElement | null = $state(null);
$effect(() => {
const el = dialogEl;
if (!el) return;
if (open && !el.open) el.showModal();
else if (!open && el.open) el.close();
});
function onClose() {
open = false;
}
function onClick(e: MouseEvent) {
if (e.target === dialogEl) open = false;
}
function pick(entry: TemplateEntry) {
open = false;
onPick?.(entry);
}
</script>
<dialog class="gallery" bind:this={dialogEl} onclose={onClose} onclick={onClick} aria-label={t().templates.title}>
<div class="card">
<button class="close" onclick={() => (open = false)} aria-label={t().common.close} title={t().common.close}>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
<path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
</svg>
</button>
<h2>{t().templates.title}</h2>
<div class="grid">
{#each TEMPLATES as entry (entry.id)}
<button class="tpl" onclick={() => pick(entry)}>
<!-- A stylized letter page: address block, info column, body lines. -->
<span class="thumb" aria-hidden="true">
<span class="addr"></span>
<span class="info"></span>
<span class="line l1"></span>
<span class="line l2"></span>
<span class="line l3"></span>
<span class="fold f1"></span>
<span class="fold f2"></span>
</span>
<span class="name">{entry.name()}</span>
<span class="desc">{entry.description()}</span>
</button>
{/each}
</div>
</div>
</dialog>
<style>
.gallery {
margin: auto;
padding: 0;
border: none;
background: transparent;
max-width: none;
max-height: none;
overflow: visible;
}
.gallery::backdrop {
background: rgba(0, 0, 0, 0.35);
backdrop-filter: blur(2px);
}
.card {
position: relative;
width: 440px;
max-width: 90vw;
box-sizing: border-box;
padding: 20px 22px 22px;
background: var(--color-surface);
color: var(--color-text);
border: 1px solid var(--color-border);
border-radius: var(--radius);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22);
font-family: var(--font-sans);
}
h2 {
margin: 0 0 14px;
font-size: 1rem;
}
.close {
position: absolute;
top: 8px;
right: 8px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
padding: 0;
border: none;
border-radius: var(--radius);
background: transparent;
color: var(--color-text-muted);
cursor: pointer;
}
.close:hover {
background: var(--color-btn-hover);
color: var(--color-text);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 12px;
}
.tpl {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
padding: 10px;
border: 1px solid var(--color-border);
border-radius: var(--radius);
background: transparent;
color: var(--color-text);
text-align: left;
cursor: pointer;
transition: border-color 0.12s, background 0.12s;
}
.tpl:hover {
border-color: var(--color-primary);
background: var(--color-btn-hover);
}
.thumb {
position: relative;
width: 84px;
height: 118px;
align-self: center;
background: #fff;
border: 1px solid var(--color-border);
border-radius: 2px;
}
.thumb > span {
position: absolute;
background: #b9c2cc;
}
.addr { top: 26px; left: 12px; width: 28px; height: 16px; }
.info { top: 26px; left: 52px; width: 22px; height: 16px; }
.line { left: 12px; height: 3px; }
.l1 { top: 56px; width: 40px; background: #8a94a0; }
.l2 { top: 66px; width: 60px; }
.l3 { top: 73px; width: 55px; }
.fold { left: 2px; width: 5px; height: 1px; background: #8a94a0; }
.f1 { top: 36px; }
.f2 { top: 80px; }
.name {
font-size: 0.85rem;
font-weight: 600;
}
.desc {
font-size: 0.75rem;
line-height: 1.4;
color: var(--color-text-muted);
}
</style>
+5 -1
View File
@@ -68,7 +68,7 @@
onSelectTheme,
docxBusy = false,
pdfBusy = false,
onNew, onOpen, onSave, onSaveAs, onSaveDocx, onSaveTemplate, onExportPdf, onPrintPdf, onPrint, onAbout, onDocProperties, onAutoCorrect, onAutoText, onNewComment, commentsOpen = false, onToggleComments, revisionsOpen = false, onToggleRevisions,
onNew, onNewFromTemplate, onOpen, onSave, onSaveAs, onSaveDocx, onSaveTemplate, onExportPdf, onPrintPdf, onPrint, onAbout, onDocProperties, onAutoCorrect, onAutoText, onNewComment, commentsOpen = false, onToggleComments, revisionsOpen = false, onToggleRevisions,
navigatorOpen = false, onToggleNavigator,
recentFiles = [], onOpenRecent, onForgetRecent,
}: {
@@ -108,6 +108,7 @@
docxBusy?: boolean;
pdfBusy?: boolean;
onNew?: () => void;
onNewFromTemplate?: () => void;
onOpen?: () => void;
onSave?: () => void;
onSaveAs?: () => void;
@@ -202,6 +203,9 @@
<button onclick={() => run(onNew)} disabled={!editor}>
<Icon name="newDoc" size={16} />{t().app.newDocument}
</button>
<button onclick={() => run(onNewFromTemplate)} disabled={!editor}>
<Icon name="foldMarks" size={16} />{t().templates.title}
</button>
<button onclick={() => run(onOpen)} disabled={!editor}>
<Icon name="folder" size={16} />{t().app.open}
<span class="menu-key">{shortcutHint('open')}</span>
+30
View File
@@ -674,6 +674,36 @@ const de: Messages = {
watermarkTransparency: 'Transparenz (%)',
clear: 'Alles entfernen',
},
templates: {
title: 'Neu aus Vorlage',
din5008b: {
name: 'Brief nach DIN 5008',
description: 'Geschäftsbrief (Form B): Anschriftfeld fürs Fensterkuvert, Infoblock, Falzmarken.',
},
letter: {
companyName: 'Firmenname',
returnAddress: 'Absender · Straße · PLZ Ort',
recipientCompany: 'Firma',
recipientName: 'Vorname Name',
recipientStreet: 'Straße Hausnummer',
recipientCity: 'PLZ Ort',
yourRef: 'Ihr Zeichen: ',
yourMessage: 'Ihre Nachricht vom: ',
ourRef: 'Unser Zeichen: ',
phone: 'Telefon: ',
email: 'E-Mail: ',
dateLabel: 'Datum: ',
reference: 'Zeichen',
date: 'Datum',
phoneNumber: 'Nummer',
emailAddress: 'Adresse',
subject: 'Betreff',
salutation: 'Anrede',
bodyText: 'Brieftext',
closing: 'Mit freundlichen Grüßen',
signature: 'Vorname Name',
},
},
lineNumbers: {
title: 'Zeilennummerierung',
off: 'Keine',
+30
View File
@@ -680,6 +680,36 @@ const en = {
watermarkTransparency: 'Transparency (%)',
clear: 'Remove all',
},
templates: {
title: 'New from template',
din5008b: {
name: 'DIN 5008 letter',
description: 'Business letter (Form B): address field for a window envelope, info block, fold marks.',
},
letter: {
companyName: 'Company name',
returnAddress: 'Sender · Street · Postal code City',
recipientCompany: 'Company',
recipientName: 'First name Last name',
recipientStreet: 'Street and number',
recipientCity: 'Postal code City',
yourRef: 'Your reference: ',
yourMessage: 'Your message of: ',
ourRef: 'Our reference: ',
phone: 'Phone: ',
email: 'Email: ',
dateLabel: 'Date: ',
reference: 'Reference',
date: 'Date',
phoneNumber: 'Number',
emailAddress: 'Address',
subject: 'Subject',
salutation: 'Salutation',
bodyText: 'Letter text',
closing: 'Kind regards',
signature: 'First name Last name',
},
},
lineNumbers: {
title: 'Line numbering',
off: 'None',
+69
View File
@@ -0,0 +1,69 @@
import { t } from '../i18n/i18n.svelte';
import { toDateValue, DEFAULT_DATE_FORMAT } from '../utils/dateTime';
import type { TemplateData, TemplateEntry } from './types';
// DIN 5008 Form B business letter. All vertical positions are paragraph rhythm from a
// 20mm top margin at 12pt single spacing (one line ≈ 4.87mm — Liberation Serif's
// natural line height is ~1.15em); the mm targets below are the norm's.
// Letterhead line height in pt; the space that lands the return-address line at 45mm.
const LINE_PT = 12 * 1.15;
const MM_TO_PT = 72 / 25.4;
// 45mm target − 20mm margin − one letterhead line.
const RETURN_SPACE_BEFORE_PT = Math.round((45 - 20) * MM_TO_PT - LINE_PT);
// The return-address zone is 5mm tall; its 8pt line fills ~3.25mm of it.
const RETURN_SPACE_AFTER_PT = Math.round((5 * MM_TO_PT - 8 * 1.15) * 10) / 10;
// Info block at 125mm from the paper edge = 10cm from the 25mm text margin.
const INFO_TAB = '10l';
type N = Record<string, unknown>;
const T = (text: string, ...marks: N[]): N => ({ type: 'text', text, ...(marks.length ? { marks } : {}) });
const PLH = (text: string, ...marks: N[]): N => ({ type: 'placeholderField', attrs: { text }, ...(marks.length ? { marks } : {}) });
const P = (attrs: N | null, ...content: N[]): N => ({ type: 'paragraph', ...(attrs ? { attrs } : {}), ...(content.length ? { content } : {}) });
const SMALL = { type: 'textStyle', attrs: { fontSize: '8pt' } };
const BOLD = { type: 'bold' };
function buildLetter(): TemplateData {
const L = t().templates.letter;
const addressRow = (attrs: N | null, addr: N[], info: N[]): N =>
P({ ...(attrs ?? {}), tabStops: INFO_TAB }, ...addr, T('\t'), ...info);
const date: N = { type: 'dateTimeField', attrs: { kind: 'date', format: DEFAULT_DATE_FORMAT, fixed: true, value: toDateValue(new Date()) } };
return {
margins: { top: 2, bottom: 2, left: 2.5, right: 2 },
foldMarks: true,
content: {
type: 'doc',
content: [
P(null, PLH(L.companyName, BOLD)),
// The one-line return address opens the address field at 45mm from the top.
P({ spaceBefore: RETURN_SPACE_BEFORE_PT, spaceAfter: RETURN_SPACE_AFTER_PT }, PLH(L.returnAddress, SMALL)),
addressRow(null, [PLH(L.recipientCompany)], [T(L.yourRef), PLH(L.reference)]),
addressRow(null, [PLH(L.recipientName)], [T(L.yourMessage), PLH(L.date)]),
addressRow(null, [PLH(L.recipientStreet)], [T(L.ourRef), PLH(L.reference)]),
addressRow(null, [PLH(L.recipientCity)], [T(L.phone), PLH(L.phoneNumber)]),
addressRow(null, [], [T(L.email), PLH(L.emailAddress)]),
addressRow(null, [], [T(L.dateLabel), date]),
P(null),
P(null),
P(null, PLH(L.subject, BOLD)),
P(null),
P(null, PLH(L.salutation)),
P(null),
P(null, PLH(L.bodyText)),
P(null),
P(null, T(L.closing)),
P(null),
P(null),
P(null),
P(null, PLH(L.signature)),
],
},
};
}
export const din5008b: TemplateEntry = {
id: 'din5008b',
name: () => t().templates.din5008b.name,
description: () => t().templates.din5008b.description,
build: buildLetter,
};
+4
View File
@@ -0,0 +1,4 @@
import { din5008b } from './din5008b';
import type { TemplateEntry } from './types';
export const TEMPLATES: TemplateEntry[] = [din5008b];
+21
View File
@@ -0,0 +1,21 @@
import type { Content } from '@tiptap/core';
import type { PageMargins } from '../storage/pageMargins';
import type { Style } from '../styles/styleSheet';
// What a built-in template sets besides the content; applyTemplate (App.svelte)
// resets everything first, so an absent field keeps the app default.
export interface TemplateData {
content: Content;
margins?: PageMargins;
/** Named paragraph styles the template ships, merged over the built-ins. */
styles?: Style[];
foldMarks?: boolean;
}
// name/description/build read t() at call time, so a template follows the UI locale.
export interface TemplateEntry {
id: string;
name: () => string;
description: () => string;
build: () => TemplateData;
}