Format slide texts in WhatsApp style #50

Merged
gnilebein merged 1 commits from feature/text-formatting into main 2026-11-11 14:23:30 +01:00
12 changed files with 215 additions and 8 deletions

No files matched your search

+5
View File
@@ -242,6 +242,11 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
nur solange die Abstimmung offen ist. `participate:edit` → `VoteService::editText()`, gleiche Vorbedingungen wie
`submit()`, in der Folien-Sperre, legt nie eine neue Antwort an.
- **Formatierung von Folientexten** (nur `description`, nie Eingaben von Teilnehmenden) im WhatsApp-Stil: `*fett*`,
`_kursiv_`, `~durchgestrichen~`, Aufzählung mit `- `/`* ` am Zeilenanfang, Zeilenumbrüche. Zwei gleiche Implementierungen:
`FormatHelper::text()` (PHP: Teilnehmerseite, PDF; escapt alles und erzeugt nur diese Tags) und `Format` in `plenario.js`
(Presenter/Embed; baut DOM-Knoten, kein `innerHTML`). Regeln in beiden gleich halten (Regex `INLINE`/`LIST_ITEM`),
Tests: `FormatHelperTest.php`.
- **PDF-Export** (`/admin/{token}/export.pdf`, `admin:export`, `ReportService` + `PdfView`, Dompdf): Ergebnisse aller
interaktiven Folien (Inhaltsfolien/YouTube fehlen). Standard ist die Fassung **ohne interne Inhalte**: private Folien
(`Slide::isPrivate()`) erscheinen nur mit Teilnehmerzahl. `?internal=1` = vollständige Fassung inkl.
+1
View File
@@ -37,5 +37,6 @@ class AppView extends View
*/
public function initialize(): void
{
$this->addHelper('Format');
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace App\View\Helper;
use Cake\View\Helper;
/**
* Light formatting of slide texts in WhatsApp style: *bold*, _italic_, ~strikethrough~ and
* lists with "- " or "* " at the start of a line. Everything else is plain, escaped text.
* Only for texts of the poll owner (slide descriptions), never for participant input.
* The same rules are implemented in webroot/js/plenario.js (Format) for the presentation.
*/
class FormatHelper extends Helper
{
/**
* A marker at a word boundary, text without leading/trailing space inside, within one line.
* Group 1: character before the marker, 2: marker, 3: formatted text.
*/
public const INLINE = '/(^|[^\p{L}\p{N}])([*_~])(\S|\S[^\n]*?\S)\2(?=$|[^\p{L}\p{N}])/u';
public const LIST_ITEM = '/^\s*[-*•]\s+(.*)$/u';
/**
* @var array<string, string>
*/
protected const TAGS = ['*' => 'strong', '_' => 'em', '~' => 's'];
/**
* Formats a text as HTML: lines become <br>, consecutive list lines a <ul>.
*
* @param string|null $text Text as entered
* @return string Safe HTML
*/
public function text(?string $text): string
{
$lines = preg_split('/\R/u', trim((string)$text)) ?: [];
$html = '';
$paragraph = [];
$items = [];
$flushText = function () use (&$html, &$paragraph): void {
if ($paragraph) {
$html .= implode('<br>', array_map($this->inline(...), $paragraph));
$paragraph = [];
}
};
$flushList = function () use (&$html, &$items): void {
if ($items) {
$html .= '<ul>' . implode('', array_map(fn($item) => '<li>' . $this->inline($item) . '</li>', $items)) . '</ul>';
$items = [];
}
};
foreach ($lines as $line) {
if (preg_match(self::LIST_ITEM, $line, $match)) {
$flushText();
$items[] = $match[1];
} else {
$flushList();
$paragraph[] = $line;
}
}
$flushText();
$flushList();
return $html;
}
/**
* Inline markers of one line, nested by recursion (e.g. *_bold italic_*).
*
* @param string $text Line as entered
* @return string Safe HTML
*/
public function inline(string $text): string
{
if (!preg_match(self::INLINE, $text, $match, PREG_OFFSET_CAPTURE)) {
return h($text);
}
$start = $match[0][1];
$tag = self::TAGS[$match[2][0]];
return h(substr($text, 0, $start)) . h($match[1][0])
. '<' . $tag . '>' . $this->inline($match[3][0]) . '</' . $tag . '>'
. $this->inline(substr($text, $start + strlen($match[0][0])));
}
}
+1 -1
View File
@@ -78,7 +78,7 @@ $bar = function (float $percent, bool $ok = false): string {
</p>
<h2><?= h($slide->question) ?></h2>
<?php if ($slide->description) : ?>
<p class="muted"><?= nl2br(h($slide->description)) ?></p>
<div class="muted formatted"><?= $this->Format->text($slide->description) ?></div>
<?php endif; ?>
<p class="muted"><?= __n('{0} Person hat teilgenommen', '{0} Personen haben teilgenommen', $participants, $participants) ?></p>
+1 -1
View File
@@ -36,7 +36,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);
<main class="stage__main">
<p class="stage__status" data-status></p>
<h1 class="stage__question" data-question><?= __('Lade …') ?></h1>
<p class="stage__description" data-description></p>
<div class="stage__description formatted" data-description></div>
<div class="stage__media" data-media hidden></div>
<div class="stage__results" data-results></div>
</main>
+1 -1
View File
@@ -40,7 +40,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);
<main class="stage__main">
<p class="stage__status" data-status></p>
<h1 class="stage__question" data-question><?= h($slide->question) ?></h1>
<p class="stage__description" data-description></p>
<div class="stage__description formatted" data-description></div>
<div class="stage__media" data-media hidden></div>
<div class="stage__results" data-results></div>
</main>
+3 -3
View File
@@ -66,7 +66,7 @@ $countdown = function (?int $remaining): string {
<p class="eyebrow"><?= __('Video') ?></p>
<h1><?= h($slide->question) ?></h1>
<?php if ($slide->description) : ?>
<div class="prose"><?= nl2br(h($slide->description)) ?></div>
<div class="prose formatted"><?= $this->Format->text($slide->description) ?></div>
<?php endif; ?>
<?php if ($watchUrl !== null) : ?>
<p class="video-link">
@@ -87,7 +87,7 @@ $countdown = function (?int $remaining): string {
<section class="card">
<h1><?= h($slide->question) ?></h1>
<?php if ($slide->description) : ?>
<div class="prose"><?= nl2br(h($slide->description)) ?></div>
<div class="prose formatted"><?= $this->Format->text($slide->description) ?></div>
<?php endif; ?>
</section>
@@ -95,7 +95,7 @@ $countdown = function (?int $remaining): string {
<section class="card">
<h1 class="question"><?= h($slide->question) ?></h1>
<?php if ($slide->description) : ?>
<p class="muted"><?= nl2br(h($slide->description)) ?></p>
<div class="muted formatted"><?= $this->Format->text($slide->description) ?></div>
<?php endif; ?>
<?php if ($quiz !== null) : ?>
+2
View File
@@ -111,7 +111,9 @@ $optionsError = $slide->getError('options_text');
'type' => 'textarea',
'rows' => $slide->type === 'content' ? 6 : 2,
'label' => $slide->type === 'content' ? __('Text') : __('Beschreibung (optional)'),
'aria-describedby' => 'description-format',
]) ?>
<p class="hint" id="description-format"><?= __('Formatierung wie bei WhatsApp: *fett*, _kursiv_, ~durchgestrichen~, Aufzählung mit „- “ am Zeilenanfang.') ?></p>
<?php if ($slide->type === 'choice') : ?>
<div class="input textarea<?= $optionsError ? ' error' : '' ?>">
+3
View File
@@ -48,6 +48,9 @@
.stat { font-size: 12pt; font-weight: bold; }
td.stars { color: #c27c00; letter-spacing: 1pt; }
.empty { color: #5d6280; font-style: italic; }
/* slide texts with *bold*, _italic_, ~strike~ and lists (FormatHelper) */
.formatted { margin: 0 0 2mm; }
.formatted ul { margin: 1mm 0; padding-left: 6mm; }
</style>
</head>
<body>
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\View\Helper;
use App\View\Helper\FormatHelper;
use Cake\TestSuite\TestCase;
use Cake\View\View;
/**
* WhatsApp style formatting of slide texts.
*/
class FormatHelperTest extends TestCase
{
protected FormatHelper $Format;
protected function setUp(): void
{
parent::setUp();
$this->Format = new FormatHelper(new View());
}
public function testInlineMarkers(): void
{
$this->assertSame('<strong>fett</strong>', $this->Format->text('*fett*'));
$this->assertSame('ganz <em>kursiv</em> hier', $this->Format->text('ganz _kursiv_ hier'));
$this->assertSame('<s>alt</s> neu', $this->Format->text('~alt~ neu'));
$this->assertSame('<strong>zwei Wörter</strong>, gut', $this->Format->text('*zwei Wörter*, gut'));
$this->assertSame('<strong><em>beides</em></strong>', $this->Format->text('*_beides_*'));
$this->assertSame('<strong>a</strong> und <strong>b</strong>', $this->Format->text('*a* und *b*'));
}
public function testMarkersNeedWordBoundariesAndNoInnerSpaces(): void
{
$this->assertSame('2*3*4', $this->Format->text('2*3*4'));
$this->assertSame('snake_case_name', $this->Format->text('snake_case_name'));
$this->assertSame('so * nicht fett *', $this->Format->text('so * nicht fett *'));
$this->assertSame('5 * 3 = 15', $this->Format->text('5 * 3 = 15'));
$this->assertSame('*offen', $this->Format->text('*offen'));
}
public function testLinesAndLists(): void
{
$this->assertSame('eins<br>zwei', $this->Format->text("eins\r\nzwei"));
$this->assertSame(
'Agenda:<ul><li>Bericht</li><li><strong>Wahl</strong></li></ul>Danke!',
$this->Format->text("Agenda:\n- Bericht\n* *Wahl*\nDanke!"),
);
}
public function testEverythingElseIsEscaped(): void
{
$this->assertSame(
'&lt;script&gt;x&lt;/script&gt; <strong>&lt;b&gt;</strong> &amp;',
$this->Format->text('<script>x</script> *<b>* &'),
);
$this->assertSame('', $this->Format->text(null));
}
}
+6 -1
View File
@@ -377,6 +377,11 @@ textarea { resize: vertical; }
.pulse { width: 18px; height: 18px; border-radius: 50%; background: var(--primary); margin: 0 auto 24px; animation: pulse 1.6s infinite; }
@keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(75, 63, 224, .5); } 100% { box-shadow: 0 0 0 24px rgba(75, 63, 224, 0); } }
.prose { font-size: 1.1rem; }
/* slide texts with *bold*, _italic_, ~strike~ and lists (FormatHelper / Format in plenario.js) */
.muted.formatted { margin: 1em 0; }
.formatted ul { margin: .3em 0; padding-left: 1.3em; text-align: left; }
.formatted li + li { margin-top: .15em; }
.muted.formatted strong { color: var(--text); }
/* quiz (participant) */
.choice--quiz { border-left-width: 8px; border-left-color: var(--c0); font-size: 1.1rem; }
@@ -663,7 +668,7 @@ body.present {
.stage__status:empty { display: none; }
.stage--closed .stage__status { color: var(--muted); }
.stage__question { font-size: clamp(2rem, 4.5vw, 4rem); margin-bottom: .3em; }
.stage__description { font-size: clamp(1.1rem, 2vw, 1.6rem); color: var(--muted); white-space: pre-line; margin-top: 0; }
.stage__description { font-size: clamp(1.1rem, 2vw, 1.6rem); color: var(--muted); margin: 0 0 1em; }
.stage__media { width: min(100%, calc(62vh * 16 / 9)); margin: 1vh auto 0; }
.stage--video .stage__question { font-size: clamp(1.5rem, 3vw, 2.6rem); }
.stage--video .stage__description { font-size: clamp(1rem, 1.6vw, 1.3rem); }
+47 -1
View File
@@ -42,6 +42,52 @@
return node;
}
/**
* Light formatting of slide texts in WhatsApp style, same rules as App\View\Helper\FormatHelper:
* *bold*, _italic_, ~strikethrough~, lists with "- " or "* " at the start of a line.
* Builds DOM nodes (text via textContent), never HTML strings.
*/
var Format = {
INLINE: /(^|[^\p{L}\p{N}])([*_~])(\S|\S[^\n]*?\S)\2(?=$|[^\p{L}\p{N}])/u,
LIST_ITEM: /^\s*[-*•]\s+(.*)$/u,
TAGS: { '*': 'strong', '_': 'em', '~': 's' },
render: function (container, text) {
container.textContent = '';
var lines = String(text || '').trim().split(/\r\n|\r|\n/);
var list = null;
var lineBefore = false;
lines.forEach(function (line) {
var item = Format.LIST_ITEM.exec(line);
if (item) {
if (!list) {
list = container.appendChild(el('ul'));
}
list.appendChild(el('li', {}, Format.inline(item[1])));
lineBefore = false;
return;
}
if (lineBefore) {
container.appendChild(el('br'));
}
list = null;
Format.inline(line).forEach(function (node) { container.appendChild(node); });
lineBefore = true;
});
},
inline: function (text) {
var m = Format.INLINE.exec(text);
if (!m) {
return text ? [document.createTextNode(text)] : [];
}
var before = text.slice(0, m.index) + m[1];
return (before ? [document.createTextNode(before)] : [])
.concat([el(Format.TAGS[m[2]], {}, Format.inline(m[3]))])
.concat(Format.inline(text.slice(m.index + m[0].length)));
}
};
function csrfToken() {
var meta = document.querySelector('meta[name="csrf-token"]');
return meta ? meta.getAttribute('content') : '';
@@ -1294,7 +1340,7 @@
: (qaStage ? Qa.labels[qaStage]
: (orderRevealed ? 'Auflösung' : (closed ? 'Abstimmung geschlossen' : '')));
q('[data-question]').textContent = slide.question;
q('[data-description]').textContent = slide.description;
Format.render(q('[data-description]'), slide.description);
root.classList.toggle('stage--content', !slide.isInteractive);
root.classList.toggle('stage--video', slide.type === 'youtube');
renderMedia(slide);