Enhance newsletter HTML generation and UI components

- Introduce helper functions `_outlook_font` and `_outlook_link` for better formatting in Outlook-compatible HTML.
- Update `create_outlook_html` to utilize new font and link functions, improving the overall appearance of the newsletter.
- Modify CSS to add styles for a new copy dialog overlay and related components.
- Refactor JavaScript to improve copy functionality and add a dialog for copying HTML content.
- Update dashboard template to enhance user instructions for copying and downloading HTML content.
This commit is contained in:
smueller
2026-07-03 13:17:11 +02:00
parent 90cdb7e922
commit df4424fdf9
4 changed files with 259 additions and 155 deletions

View File

@@ -263,6 +263,28 @@ OUTLOOK_MUTED = "#666666"
OUTLOOK_LINK = "#0563C1" OUTLOOK_LINK = "#0563C1"
OUTLOOK_HEADING = "#003366" OUTLOOK_HEADING = "#003366"
OUTLOOK_BORDER = "#DDDDDD" OUTLOOK_BORDER = "#DDDDDD"
OUTLOOK_WHITE = "#FFFFFF"
def _outlook_font(
text: str,
*,
color: str = OUTLOOK_TEXT,
size: str = "2",
bold: bool = False,
) -> str:
inner = escape(text)
if bold:
inner = f"<b>{inner}</b>"
return f'<font face="Arial" color="{color}" size="{size}">{inner}</font>'
def _outlook_link(title: str, url: str) -> str:
return (
f'<a href="{escape(url)}">'
f'<font face="Arial" color="{OUTLOOK_LINK}" size="2">{escape(title)}</font>'
f"</a>"
)
def create_outlook_html( def create_outlook_html(
@@ -271,18 +293,18 @@ def create_outlook_html(
display: DisplayOptions | None = None, display: DisplayOptions | None = None,
category: str = "", category: str = "",
) -> str: ) -> str:
"""Vereinfachtes HTML für Outlook/Word nur Tabellen und Inline-Styles.""" """Word/Outlook-kompatibles HTML mit font-Tags und bgcolor (überlebt Einfügen in Outlook)."""
display = display or DEFAULT_DISPLAY display = display or DEFAULT_DISPLAY
new_articles, edited_articles = split_articles_by_type(articles) new_articles, edited_articles = split_articles_by_type(articles)
period_start, period_end = _period_range(days) period_start, period_end = _period_range(days)
created_at = datetime.now().strftime("%d.%m.%Y %H:%M") created_at = datetime.now().strftime("%d.%m.%Y %H:%M")
intro = escape(_intro_sentence(period_start, period_end)) intro = _intro_sentence(period_start, period_end)
subject = escape(create_subject(days, category)) subject = escape(create_subject(days, category))
if not new_articles and not edited_articles: if not new_articles and not edited_articles:
body_rows = f"""<tr> body_rows = f"""<tr>
<td style="padding:12px 0;font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_MUTED};"> <td bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};padding:12px 0;">
Im gewählten Zeitraum wurden keine passenden Wiki-Änderungen gefunden. {_outlook_font("Im gewählten Zeitraum wurden keine passenden Wiki-Änderungen gefunden.", color=OUTLOOK_MUTED)}
</td> </td>
</tr>""" </tr>"""
else: else:
@@ -300,15 +322,18 @@ def create_outlook_html(
category_block = "" category_block = ""
if category.strip(): if category.strip():
category_block = f"""<p style="margin:0 0 8px;font-family:{OUTLOOK_FONT};font-size:10pt;color:{OUTLOOK_MUTED};"> category_block = (
<strong style="font-family:{OUTLOOK_FONT};color:{OUTLOOK_HEADING};">Filter:</strong> Kategorie {escape(category.strip())} f'<p style="margin:0 0 10px;">'
</p>""" f'{_outlook_font("Filter: ", color=OUTLOOK_HEADING, bold=True)}'
f'{_outlook_font(f"Kategorie {category.strip()}", color=OUTLOOK_MUTED, size="1")}'
f"</p>"
)
total = len(new_articles) + len(edited_articles) total = len(new_articles) + len(edited_articles)
summary_row = f"""<tr> summary_row = f"""<tr>
<td style="padding:16px 0 0;font-family:{OUTLOOK_FONT};font-size:10pt;color:{OUTLOOK_MUTED};border-top:1px solid {OUTLOOK_BORDER};"> <td bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};padding:16px 0 0;border-top:1px solid {OUTLOOK_BORDER};">
<strong style="font-family:{OUTLOOK_FONT};color:{OUTLOOK_HEADING};">Zusammenfassung:</strong> {_outlook_font("Zusammenfassung: ", color=OUTLOOK_HEADING, bold=True, size="1")}
{len(new_articles)} neu &middot; {len(edited_articles)} bearbeitet &middot; {total} gesamt {_outlook_font(f"{len(new_articles)} neu · {len(edited_articles)} bearbeitet · {total} gesamt", color=OUTLOOK_MUTED, size="1")}
</td> </td>
</tr>""" </tr>"""
@@ -318,48 +343,42 @@ def create_outlook_html(
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="ProgId" content="Word.Document"> <meta name="ProgId" content="Word.Document">
<meta name="Generator" content="Microsoft Word 15"> <meta name="Generator" content="Microsoft Word 15">
<meta name="color-scheme" content="light only">
<meta name="supported-color-schemes" content="light">
<title>{subject}</title> <title>{subject}</title>
<!--[if gte mso 9]>
<xml>
<w:WordDocument>
<w:View>Print</w:View>
<w:Zoom>100</w:Zoom>
<w:DoNotOptimizeForBrowser/>
</w:WordDocument>
</xml>
<![endif]-->
<!--[if mso]> <!--[if mso]>
<style type="text/css"> <style type="text/css">
body, table, td, p, a, span, strong {{ font-family: Arial, sans-serif !important; }} body, table, td, p, a, font, span, strong {{ font-family: Arial, sans-serif !important; }}
a {{ color: {OUTLOOK_LINK} !important; }}
</style> </style>
<![endif]--> <![endif]-->
</head> </head>
<body style="margin:0;padding:16px;font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_TEXT};background:#FFFFFF;"> <body bgcolor="{OUTLOOK_WHITE}" style="margin:0;padding:16px;background-color:{OUTLOOK_WHITE};">
<table width="600" cellpadding="0" cellspacing="0" border="0" align="center" style="width:600px;font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_TEXT};background:#FFFFFF;"> <table width="600" cellpadding="0" cellspacing="0" border="0" align="center" bgcolor="{OUTLOOK_WHITE}" style="width:600px;background-color:{OUTLOOK_WHITE};">
<tr> <tr>
<td style="padding:16px 20px;background:{OUTLOOK_HEADING};font-family:{OUTLOOK_FONT};"> <td bgcolor="{OUTLOOK_HEADING}" style="background-color:{OUTLOOK_HEADING};padding:16px 20px;">
<p style="margin:0;font-family:{OUTLOOK_FONT};font-size:9pt;color:#A9C6E8;text-transform:uppercase;letter-spacing:1px;">Interner Newsletter</p> {_outlook_font("Interner Newsletter", color="#A9C6E8", size="1")}<br>
<p style="margin:6px 0 0;font-family:{OUTLOOK_FONT};font-size:18pt;font-weight:bold;color:#FFFFFF;">Thomas-Krenn Wiki Update</p> {_outlook_font("Thomas-Krenn Wiki Update", color=OUTLOOK_WHITE, size="5", bold=True)}<br>
<p style="margin:4px 0 0;font-family:{OUTLOOK_FONT};font-size:11pt;color:#D9E8F8;">{escape(ORG_NAME)}</p> {_outlook_font(ORG_NAME, color="#D9E8F8", size="2")}
</td> </td>
</tr> </tr>
<tr> <tr>
<td style="padding:20px;font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_TEXT};"> <td bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};padding:20px;">
<p style="margin:0 0 8px;font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_TEXT};">Liebe Kolleginnen und Kollegen,</p> <p style="margin:0 0 8px;">{_outlook_font("Liebe Kolleginnen und Kollegen,")}</p>
<p style="margin:0 0 12px;font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_TEXT};">{intro}</p> <p style="margin:0 0 12px;">{_outlook_font(intro)}</p>
<p style="margin:0 0 16px;font-family:{OUTLOOK_FONT};font-size:9pt;color:{OUTLOOK_MUTED};">Erstellt am: {created_at}</p> <p style="margin:0 0 16px;">{_outlook_font(f"Erstellt am: {created_at}", color=OUTLOOK_MUTED, size="1")}</p>
{category_block} {category_block}
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_TEXT};"> <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};">
{body_rows} {body_rows}
{summary_row} {summary_row}
<tr> <tr>
<td style="padding:20px 0 0;font-family:{OUTLOOK_FONT};font-size:11pt;"> <td bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};padding:20px 0 0;">
<a href="{WIKI_HOME_URL}" style="font-family:{OUTLOOK_FONT};font-size:11pt;font-weight:bold;color:{OUTLOOK_LINK};">Zum Thomas-Krenn-Wiki &rarr;</a> <a href="{WIKI_HOME_URL}"><font face="Arial" color="{OUTLOOK_LINK}" size="2"><b>Zum Thomas-Krenn-Wiki →</b></font></a>
</td> </td>
</tr> </tr>
<tr> <tr>
<td style="padding:16px 0 0;font-family:{OUTLOOK_FONT};font-size:9pt;color:{OUTLOOK_MUTED};border-top:1px solid {OUTLOOK_BORDER};"> <td bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};padding:16px 0 0;border-top:1px solid {OUTLOOK_BORDER};">
Automatisch erstellter interner Newsletter &middot; Nur für den Gebrauch bei {escape(ORG_NAME)} {_outlook_font(f"Automatisch erstellter interner Newsletter · Nur für den Gebrauch bei {ORG_NAME}", color=OUTLOOK_MUTED, size="1")}
</td> </td>
</tr> </tr>
</table> </table>
@@ -385,20 +404,19 @@ def _outlook_meta_line(item: dict[str, Any], display: DisplayOptions) -> str:
def _outlook_article_rows(items: list[dict[str, Any]], display: DisplayOptions) -> str: def _outlook_article_rows(items: list[dict[str, Any]], display: DisplayOptions) -> str:
rows: list[str] = [] rows: list[str] = []
for idx, item in enumerate(items, 1): for idx, item in enumerate(items, 1):
title = escape(item.get("title", "Ohne Titel")) title = item.get("title", "Ohne Titel")
url = escape(_article_url(item.get("title", ""))) url = _article_url(item.get("title", ""))
meta = _outlook_meta_line(item, display) meta = _outlook_meta_line(item, display)
meta_html = "" meta_html = ""
if meta: if meta:
meta_html = ( meta_html = f"<br>{_outlook_font(meta, color=OUTLOOK_MUTED, size='1')}"
f'<br><span style="font-family:{OUTLOOK_FONT};font-size:9pt;color:{OUTLOOK_MUTED};">'
f"{escape(meta)}</span>"
)
rows.append( rows.append(
f"""<tr> f"""<tr>
<td width="28" valign="top" style="padding:6px 8px 10px 0;border-bottom:1px solid {OUTLOOK_BORDER};font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_TEXT};">{idx}.</td> <td width="28" valign="top" bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};padding:8px 8px 10px 0;border-bottom:1px solid {OUTLOOK_BORDER};">
<td valign="top" style="padding:6px 0 10px;border-bottom:1px solid {OUTLOOK_BORDER};font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_TEXT};"> {_outlook_font(f"{idx}.")}
<a href="{url}" style="font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_LINK};">{title}</a>{meta_html} </td>
<td valign="top" bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};padding:8px 0 10px;border-bottom:1px solid {OUTLOOK_BORDER};">
{_outlook_link(title, url)}{meta_html}
</td> </td>
</tr>""" </tr>"""
) )
@@ -412,13 +430,15 @@ def _outlook_section(
empty_text: str, empty_text: str,
) -> str: ) -> str:
header = f"""<tr> header = f"""<tr>
<td colspan="2" style="padding:18px 0 6px;font-family:{OUTLOOK_FONT};font-size:13pt;font-weight:bold;color:{OUTLOOK_HEADING};border-bottom:2px solid {OUTLOOK_HEADING};"> <td colspan="2" bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};padding:18px 0 8px;border-bottom:2px solid {OUTLOOK_HEADING};">
{escape(heading)} ({len(items)}) {_outlook_font(f"{heading} ({len(items)})", color=OUTLOOK_HEADING, size="3", bold=True)}
</td> </td>
</tr>""" </tr>"""
if not items: if not items:
return header + f"""<tr> return header + f"""<tr>
<td colspan="2" style="padding:8px 0;font-family:{OUTLOOK_FONT};font-size:11pt;color:{OUTLOOK_MUTED};font-style:italic;">{escape(empty_text)}</td> <td colspan="2" bgcolor="{OUTLOOK_WHITE}" style="background-color:{OUTLOOK_WHITE};padding:8px 0;">
{_outlook_font(empty_text, color=OUTLOOK_MUTED)}
</td>
</tr>""" </tr>"""
return header + _outlook_article_rows(items, display) return header + _outlook_article_rows(items, display)

View File

@@ -24,3 +24,10 @@ th, td { border-bottom: 1px solid #e6ebf4; text-align: left; padding: 0.55rem; v
.display-options legend { font-weight: 600; padding: 0 0.25rem; } .display-options legend { font-weight: 600; padding: 0 0.25rem; }
.error { color: #b42318; background: #fef3f2; border: 1px solid #fecdca; padding: 0.6rem; border-radius: 4px; margin: 0 0 0.75rem; } .error { color: #b42318; background: #fef3f2; border: 1px solid #fecdca; padding: 0.6rem; border-radius: 4px; margin: 0 0 0.75rem; }
.hint { color: #64748b; font-size: 0.92rem; margin: 0 0 0.6rem; } .hint { color: #64748b; font-size: 0.92rem; margin: 0 0 0.6rem; }
.copy-dialog-overlay { position: fixed; inset: 0; z-index: 1000; background: rgba(15, 23, 42, 0.55); display: flex; align-items: center; justify-content: center; padding: 1rem; }
.copy-dialog { width: min(900px, 100%); max-height: 90vh; background: #fff; border-radius: 8px; padding: 1rem 1.25rem; box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2); display: grid; gap: 0.75rem; }
.copy-dialog h4 { margin: 0; color: #003366; }
.copy-dialog-hint { margin: 0; color: #334155; }
.copy-dialog-textarea { width: 100%; min-height: 320px; font-family: Consolas, "Courier New", monospace; font-size: 0.85rem; line-height: 1.4; border: 1px solid #cbd5e1; border-radius: 4px; padding: 0.75rem; resize: vertical; }
.copy-dialog-actions { display: flex; gap: 0.6rem; flex-wrap: wrap; }
.textarea-actions { display: flex; gap: 0.6rem; flex-wrap: wrap; margin-bottom: 0.6rem; }

View File

@@ -8,8 +8,7 @@ function setCopyStatus(message, isError) {
function getNewsletterHtml() { function getNewsletterHtml() {
const htmlSource = document.getElementById("newsletter-html-source"); const htmlSource = document.getElementById("newsletter-html-source");
const htmlDisplay = document.getElementById("newsletter-html-display"); const htmlDisplay = document.getElementById("newsletter-html-display");
const value = htmlSource?.value.trim() || htmlDisplay?.value.trim() || ""; return htmlSource?.value.trim() || htmlDisplay?.value.trim() || "";
return value;
} }
function getNewsletterOutlookHtml() { function getNewsletterOutlookHtml() {
@@ -24,6 +23,10 @@ function getNewsletterPlain() {
return plainSource ? plainSource.value : ""; return plainSource ? plainSource.value : "";
} }
function byteLength(text) {
return new TextEncoder().encode(text).length;
}
function wrapCfHtml(html) { function wrapCfHtml(html) {
const fragmentStart = "<!--StartFragment-->"; const fragmentStart = "<!--StartFragment-->";
const fragmentEnd = "<!--EndFragment-->"; const fragmentEnd = "<!--EndFragment-->";
@@ -32,15 +35,20 @@ function wrapCfHtml(html) {
const documentHtml = `<html><body>${fragmentStart}${inner}${fragmentEnd}</body></html>`; const documentHtml = `<html><body>${fragmentStart}${inner}${fragmentEnd}</body></html>`;
const pad = (value) => String(value).padStart(10, "0"); const pad = (value) => String(value).padStart(10, "0");
const headerPlaceholder = "StartHTML:0000000000\r\nEndHTML:0000000000\r\nStartFragment:0000000000\r\nEndFragment:0000000000\r\n"; const headerTemplate =
const prefix = `Version:0.9\r\n${headerPlaceholder}`; "Version:0.9\r\n" +
const startHtml = prefix.length; "StartHTML:0000000000\r\n" +
const endHtml = startHtml + documentHtml.length; "EndHTML:0000000000\r\n" +
const startFragment = startHtml + documentHtml.indexOf(fragmentStart) + fragmentStart.length; "StartFragment:0000000000\r\n" +
const endFragment = startHtml + documentHtml.indexOf(fragmentEnd); "EndFragment:0000000000\r\n";
const startHtml = byteLength(headerTemplate);
const endHtml = startHtml + byteLength(documentHtml);
const startFragment = startHtml + byteLength(documentHtml.slice(0, documentHtml.indexOf(fragmentStart) + fragmentStart.length));
const endFragment = startHtml + byteLength(documentHtml.slice(0, documentHtml.indexOf(fragmentEnd)));
return ( return (
`Version:0.9\r\n` + "Version:0.9\r\n" +
`StartHTML:${pad(startHtml)}\r\n` + `StartHTML:${pad(startHtml)}\r\n` +
`EndHTML:${pad(endHtml)}\r\n` + `EndHTML:${pad(endHtml)}\r\n` +
`StartFragment:${pad(startFragment)}\r\n` + `StartFragment:${pad(startFragment)}\r\n` +
@@ -49,26 +57,33 @@ function wrapCfHtml(html) {
); );
} }
function copyFromTextarea(textarea) { function selectTextarea(textarea) {
if (!textarea || !textarea.value) return false; if (!textarea || !textarea.value) return false;
textarea.scrollIntoView({ behavior: "smooth", block: "center" });
const previousActive = document.activeElement;
textarea.removeAttribute("readonly");
textarea.focus({ preventScroll: true }); textarea.focus({ preventScroll: true });
textarea.select(); textarea.select();
textarea.setSelectionRange(0, textarea.value.length); textarea.setSelectionRange(0, textarea.value.length);
return true;
}
function copyFromTextarea(textarea) {
if (!textarea || !textarea.value) return false;
const wasReadonly = textarea.hasAttribute("readonly");
if (wasReadonly) textarea.removeAttribute("readonly");
selectTextarea(textarea);
let ok = false; let ok = false;
try { try {
ok = document.execCommand("copy"); ok = document.execCommand("copy");
} catch (err) { } catch (err) {
console.warn("execCommand copy from textarea failed.", err); console.warn("execCommand copy from textarea failed.", err);
ok = false;
} finally {
textarea.setAttribute("readonly", "");
if (previousActive && typeof previousActive.focus === "function") {
previousActive.focus({ preventScroll: true });
} }
if (wasReadonly) textarea.setAttribute("readonly", "");
if (!ok) {
selectTextarea(textarea);
} }
return ok; return ok;
} }
@@ -92,47 +107,118 @@ function copyTextWithFallback(text) {
const textarea = document.createElement("textarea"); const textarea = document.createElement("textarea");
textarea.value = text; textarea.value = text;
textarea.setAttribute("aria-hidden", "true"); textarea.setAttribute("aria-hidden", "true");
textarea.style.position = "fixed"; textarea.style.cssText = "position:fixed;top:0;left:0;width:2px;height:2px;opacity:0;border:none;padding:0;";
textarea.style.top = "0";
textarea.style.left = "0";
textarea.style.width = "2px";
textarea.style.height = "2px";
textarea.style.padding = "0";
textarea.style.border = "none";
textarea.style.outline = "none";
textarea.style.boxShadow = "none";
textarea.style.background = "transparent";
document.body.appendChild(textarea); document.body.appendChild(textarea);
let ok = false; let ok = false;
try { try {
textarea.focus({ preventScroll: true }); selectTextarea(textarea);
textarea.select();
textarea.setSelectionRange(0, text.length);
ok = document.execCommand("copy"); ok = document.execCommand("copy");
} catch (err) { } catch (err) {
console.warn("execCommand copy from temporary textarea failed.", err); console.warn("execCommand copy from temporary textarea failed.", err);
ok = false;
} finally { } finally {
document.body.removeChild(textarea); document.body.removeChild(textarea);
} }
return ok; return ok;
} }
let copyDialogKeyHandler = null;
function closeCopyDialog() {
const overlay = document.getElementById("copy-dialog-overlay");
if (overlay) overlay.remove();
if (copyDialogKeyHandler) {
document.removeEventListener("keydown", copyDialogKeyHandler);
copyDialogKeyHandler = null;
}
}
function showCopyDialog(text, title) {
closeCopyDialog();
const overlay = document.createElement("div");
overlay.id = "copy-dialog-overlay";
overlay.className = "copy-dialog-overlay";
overlay.innerHTML = `
<div class="copy-dialog" role="dialog" aria-modal="true" aria-labelledby="copy-dialog-title">
<h4 id="copy-dialog-title">${title}</h4>
<p class="copy-dialog-hint">Der Text ist markiert. Jetzt <strong>Strg+C</strong> drücken (Mac: <strong>Cmd+C</strong>).</p>
<textarea class="copy-dialog-textarea" spellcheck="false"></textarea>
<div class="copy-dialog-actions">
<button type="button" class="btn-secondary" id="copy-dialog-select-btn">Alles markieren</button>
<button type="button" class="btn-secondary" id="copy-dialog-close-btn">Schließen</button>
</div>
</div>
`;
document.body.appendChild(overlay);
const textarea = overlay.querySelector(".copy-dialog-textarea");
textarea.value = text;
selectTextarea(textarea);
let copied = false;
try {
copied = document.execCommand("copy");
} catch (err) {
console.warn("execCommand copy in dialog failed.", err);
}
if (copied) {
setCopyStatus("HTML-Quelltext kopiert.");
} else {
setCopyStatus("Bitte im Fenster Strg+C drücken.", true);
}
overlay.querySelector("#copy-dialog-close-btn").addEventListener("click", closeCopyDialog);
overlay.querySelector("#copy-dialog-select-btn").addEventListener("click", () => selectTextarea(textarea));
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeCopyDialog();
});
copyDialogKeyHandler = (event) => {
if (event.key === "Escape") closeCopyDialog();
};
document.addEventListener("keydown", copyDialogKeyHandler);
}
function copyViaIframe(html) {
const iframe = document.createElement("iframe");
iframe.setAttribute("aria-hidden", "true");
iframe.style.cssText = "position:fixed;width:700px;height:500px;left:-9999px;top:0;border:none;";
document.body.appendChild(iframe);
const doc = iframe.contentWindow.document;
doc.open();
doc.write(html);
doc.close();
const range = doc.createRange();
range.selectNodeContents(doc.body);
const selection = iframe.contentWindow.getSelection();
selection.removeAllRanges();
selection.addRange(range);
let ok = false;
try {
ok = doc.execCommand("copy");
} catch (err) {
console.warn("execCommand copy via iframe failed.", err);
} finally {
selection.removeAllRanges();
document.body.removeChild(iframe);
}
return ok;
}
function copyHtmlWithFallback(html) { function copyHtmlWithFallback(html) {
if (copyViaIframe(html)) return true;
const container = document.createElement("div"); const container = document.createElement("div");
container.innerHTML = html; container.innerHTML = html;
container.contentEditable = "true"; container.contentEditable = "true";
container.setAttribute("aria-hidden", "true"); container.setAttribute("aria-hidden", "true");
container.style.position = "fixed"; container.style.cssText =
container.style.left = "0"; "position:fixed;left:0;top:0;width:700px;max-height:1px;overflow:hidden;opacity:0;pointer-events:none;background:#FFFFFF;";
container.style.top = "0";
container.style.width = "600px";
container.style.height = "1px";
container.style.overflow = "hidden";
container.style.opacity = "0";
container.style.pointerEvents = "none";
container.style.background = "#FFFFFF";
document.body.appendChild(container); document.body.appendChild(container);
const range = document.createRange(); const range = document.createRange();
@@ -146,36 +232,13 @@ function copyHtmlWithFallback(html) {
ok = document.execCommand("copy"); ok = document.execCommand("copy");
} catch (err) { } catch (err) {
console.warn("execCommand HTML copy failed.", err); console.warn("execCommand HTML copy failed.", err);
ok = false;
} finally { } finally {
selection.removeAllRanges(); selection.removeAllRanges();
document.body.removeChild(container); document.body.removeChild(container);
} }
if (!ok) {
ok = copyTextWithFallback(wrapCfHtml(html));
}
return ok; return ok;
} }
async function copyText(text) {
if (!text) return false;
if (copyTextWithFallback(text)) {
return true;
}
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (err) {
console.warn("Clipboard API text copy failed.", err);
}
}
return false;
}
async function copyForOutlook() { async function copyForOutlook() {
const html = getNewsletterOutlookHtml(); const html = getNewsletterOutlookHtml();
const plain = getNewsletterPlain(); const plain = getNewsletterPlain();
@@ -185,7 +248,7 @@ async function copyForOutlook() {
} }
if (copyHtmlWithFallback(html)) { if (copyHtmlWithFallback(html)) {
setCopyStatus("Newsletter für Outlook kopiert. Mit Strg+V einfügen (ggf. „Format beibehalten“)."); setCopyStatus("Newsletter kopiert. In Outlook: Strg+V, dann ggf. Rechtsklick → „Format beibehalten“.");
return; return;
} }
@@ -198,55 +261,24 @@ async function copyForOutlook() {
"text/plain": new Blob([plain], { type: "text/plain" }), "text/plain": new Blob([plain], { type: "text/plain" }),
}), }),
]); ]);
setCopyStatus("Newsletter für Outlook kopiert. Mit Strg+V einfügen (ggf. „Format beibehalten“)."); setCopyStatus("Newsletter kopiert. In Outlook: Strg+V, dann ggf. Rechtsklick → „Format beibehalten“.");
return; return;
} catch (err) { } catch (err) {
console.warn("Clipboard API HTML copy failed.", err); console.warn("Clipboard API HTML copy failed.", err);
} }
} }
setCopyStatus("Kopieren fehlgeschlagen. Bitte „HTML herunterladen“ verwenden.", true); setCopyStatus("Bitte „Im Browser öffnen“ nutzen und dort Strg+A → Strg+C.", true);
} }
async function copyHtmlSource() { function copyHtmlSource() {
const html = getNewsletterHtml(); const html = getNewsletterHtml();
if (!html) { if (!html) {
setCopyStatus("Bitte zuerst einen Newsletter generieren.", true); setCopyStatus("Bitte zuerst einen Newsletter generieren.", true);
return; return;
} }
const displayArea = document.getElementById("newsletter-html-display"); showCopyDialog(html, "HTML-Quelltext kopieren");
const sourceArea = document.getElementById("newsletter-html-source");
const textarea = displayArea?.value ? displayArea : sourceArea;
if (textarea && copyFromTextarea(textarea)) {
setCopyStatus("HTML-Quelltext kopiert.");
return;
}
if (copyTextWithFallback(html)) {
setCopyStatus("HTML-Quelltext kopiert.");
return;
}
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(html);
setCopyStatus("HTML-Quelltext kopiert.");
return;
} catch (err) {
console.warn("Clipboard API HTML source copy failed.", err);
}
}
if (textarea) {
textarea.focus({ preventScroll: true });
textarea.select();
}
setCopyStatus(
"Automatisches Kopieren nicht möglich. HTML-Feld unten ist markiert bitte Strg+C drücken.",
true
);
} }
function downloadHtml() { function downloadHtml() {
@@ -256,9 +288,23 @@ function downloadHtml() {
return; return;
} }
const stamp = new Date().toISOString().slice(0, 10); downloadFile(html, `wiki-newsletter-${new Date().toISOString().slice(0, 10)}.html`, "text/html;charset=utf-8");
const filename = `wiki-newsletter-${stamp}.html`; setCopyStatus("Outlook-HTML heruntergeladen.");
const blob = new Blob([html], { type: "text/html;charset=utf-8" }); }
function downloadHtmlSource() {
const html = getNewsletterHtml();
if (!html) {
setCopyStatus("Bitte zuerst einen Newsletter generieren.", true);
return;
}
downloadFile(html, `wiki-newsletter-source-${new Date().toISOString().slice(0, 10)}.html`, "text/html;charset=utf-8");
setCopyStatus("HTML-Quelltext heruntergeladen.");
}
function downloadFile(content, filename, mimeType) {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const link = document.createElement("a"); const link = document.createElement("a");
link.href = url; link.href = url;
@@ -267,7 +313,26 @@ function downloadHtml() {
link.click(); link.click();
document.body.removeChild(link); document.body.removeChild(link);
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
setCopyStatus(`HTML gespeichert als ${filename}. Datei in Outlook öffnen oder Inhalt kopieren.`); }
function openOutlookInBrowser() {
const html = getNewsletterOutlookHtml();
if (!html) {
setCopyStatus("Bitte zuerst einen Newsletter generieren.", true);
return;
}
const popup = window.open("", "_blank");
if (!popup) {
setCopyStatus("Pop-up blockiert. Bitte Pop-ups erlauben oder „HTML herunterladen“ nutzen.", true);
return;
}
popup.document.open();
popup.document.write(html);
popup.document.close();
popup.document.title = "Wiki-Newsletter zum Kopieren";
setCopyStatus("Newsletter im Browser geöffnet: Strg+A → Strg+C, dann in Outlook einfügen.");
} }
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
@@ -279,7 +344,14 @@ document.addEventListener("DOMContentLoaded", () => {
frame.srcdoc = previewHtml; frame.srcdoc = previewHtml;
} }
const htmlDisplay = document.getElementById("newsletter-html-display");
htmlDisplay?.addEventListener("focus", () => selectTextarea(htmlDisplay));
htmlDisplay?.addEventListener("click", () => selectTextarea(htmlDisplay));
document.getElementById("copy-outlook-btn")?.addEventListener("click", copyForOutlook); document.getElementById("copy-outlook-btn")?.addEventListener("click", copyForOutlook);
document.getElementById("open-outlook-btn")?.addEventListener("click", openOutlookInBrowser);
document.getElementById("copy-html-source-btn")?.addEventListener("click", copyHtmlSource); document.getElementById("copy-html-source-btn")?.addEventListener("click", copyHtmlSource);
document.getElementById("copy-html-source-btn-2")?.addEventListener("click", copyHtmlSource);
document.getElementById("download-html-btn")?.addEventListener("click", downloadHtml); document.getElementById("download-html-btn")?.addEventListener("click", downloadHtml);
document.getElementById("download-html-source-btn")?.addEventListener("click", downloadHtmlSource);
}); });

View File

@@ -98,8 +98,9 @@
<section class="card"> <section class="card">
<h3>Newsletter-Vorschau (mit Hyperlinks)</h3> <h3>Newsletter-Vorschau (mit Hyperlinks)</h3>
<p class="hint">Für Outlook „Für Outlook kopieren“ nutzen und mit <strong>Strg+V</strong> einfügen (Rechtsklick → „Format beibehalten“). Falls Kopieren nicht klappt (z. B. per HTTP/IP), „HTML herunterladen“ verwenden und die Datei in Outlook öffnen.</p> <p class="hint"><strong>Empfohlen für Outlook:</strong> „Im Browser öffnen“ → dort <strong>Strg+A</strong>, <strong>Strg+C</strong> → in Outlook <strong>Strg+V</strong>. Alternativ „Für Outlook kopieren“ und mit Rechtsklick → „Format beibehalten“ einfügen.</p>
<div class="copy-actions"> <div class="copy-actions">
<button type="button" id="open-outlook-btn" class="btn-secondary">Im Browser öffnen</button>
<button type="button" id="copy-outlook-btn" class="btn-secondary">Für Outlook kopieren</button> <button type="button" id="copy-outlook-btn" class="btn-secondary">Für Outlook kopieren</button>
<button type="button" id="copy-html-source-btn" class="btn-secondary">HTML-Quelltext kopieren</button> <button type="button" id="copy-html-source-btn" class="btn-secondary">HTML-Quelltext kopieren</button>
<button type="button" id="download-html-btn" class="btn-secondary">HTML herunterladen</button> <button type="button" id="download-html-btn" class="btn-secondary">HTML herunterladen</button>
@@ -119,7 +120,11 @@
<section class="card"> <section class="card">
<h3>Output: HTML-Quelltext</h3> <h3>Output: HTML-Quelltext</h3>
<p class="hint">Bei Problemen mit „Kopieren“: Textfeld markieren (Strg+A) und manuell kopieren (Strg+C).</p> <p class="hint">Öffnet ein Fenster mit markiertem Text dort <strong>Strg+C</strong> drücken. Funktioniert auch ohne HTTPS.</p>
<div class="textarea-actions">
<button type="button" id="copy-html-source-btn-2" class="btn-secondary">HTML-Quelltext kopieren</button>
<button type="button" id="download-html-source-btn" class="btn-secondary">HTML-Quelltext herunterladen</button>
</div>
<textarea id="newsletter-html-display" rows="12" readonly>{{ raw_html }}</textarea> <textarea id="newsletter-html-display" rows="12" readonly>{{ raw_html }}</textarea>
</section> </section>
@@ -195,5 +200,5 @@
{% endblock %} {% endblock %}
{% block scripts %} {% block scripts %}
<script src="/static/js/newsletter.js"></script> <script src="/static/js/newsletter.js?v=5"></script>
{% endblock %} {% endblock %}