@selfhelp/shared 1.14.12 → 1.14.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,232 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Cross-platform inline-formatting helpers for CMS content fields.
7
+ *
8
+ * ## Why
9
+ *
10
+ * CMS authors can apply lightweight inline formatting (Ctrl+B bold, Ctrl+I
11
+ * italic, Ctrl+U underline, links) to content fields whose field type allows it
12
+ * (`markdown-inline`). The editor stores that as a tiny HTML subset
13
+ * (`<strong>`/`<b>`, `<em>`/`<i>`, `<u>`, `<a>`), often wrapped in block tags
14
+ * (`<p>`, `<div>`) that markdown processing leaves behind.
15
+ *
16
+ * Web can render that subset as real inline HTML, but React Native `<Text>`
17
+ * cannot render HTML at all — so historically mobile (and several web leaf slots)
18
+ * stripped everything to plain text and the bold was lost. To carry the same
19
+ * formatting to BOTH platforms we parse the subset once, here, into a flat list
20
+ * of {@link IInlineNode} runs. Each platform then renders the runs natively:
21
+ *
22
+ * - web → a fragment of `<strong>/<em>/<u>/<a>` (see frontend `InlineRich`)
23
+ * - mobile → nested `<Text>` with `fontWeight`/`fontStyle`/`textDecorationLine`
24
+ * (see mobile `InlineText`)
25
+ *
26
+ * ## Scope (deliberately tiny + safe)
27
+ *
28
+ * Only the inline subset above survives. **Block** tags (`<p>`, `<div>`,
29
+ * `<h1>`…`<h6>`, `<ul>`/`<ol>`/`<li>`, `<blockquote>`, `<br>`) collapse to a
30
+ * single space — an inline text slot (a label, a paragraph run) cannot lay out
31
+ * block structure, and flattening matches the old strip behaviour. Any other tag
32
+ * is dropped while keeping its inner text. HTML entities are decoded.
33
+ *
34
+ * ## JSON-aware (HARD)
35
+ *
36
+ * Some content fields legitimately hold JSON (config blobs, table/segmented
37
+ * data). Those are read via `readField`, not these helpers, but as a safety net
38
+ * a value that parses as JSON is returned untouched so structured payloads are
39
+ * never mangled.
40
+ *
41
+ * This module is the canonical home the style docs refer to; the web
42
+ * `stripHtmlTags` and mobile `stripHtmlToText` local copies mirror
43
+ * {@link stripHtmlToText} and are folded into this once consumers adopt it.
44
+ */
45
+
46
+ /** A single run of text with the inline formatting that applies to it. */
47
+ export interface IInlineNode {
48
+ text: string;
49
+ bold?: boolean;
50
+ italic?: boolean;
51
+ underline?: boolean;
52
+ /** Present when the run sits inside an `<a href>`; the resolved target. */
53
+ href?: string;
54
+ }
55
+
56
+ const HTML_ENTITIES: Record<string, string> = {
57
+ '&amp;': '&',
58
+ '&lt;': '<',
59
+ '&gt;': '>',
60
+ '&quot;': '"',
61
+ '&#39;': "'",
62
+ '&apos;': "'",
63
+ '&nbsp;': ' ',
64
+ '&#x2f;': '/',
65
+ '&#47;': '/',
66
+ };
67
+
68
+ function decodeEntities(value: string): string {
69
+ if (!value.includes('&')) return value;
70
+ return value.replace(/&[a-zA-Z#0-9]+;/g, (entity) => HTML_ENTITIES[entity.toLowerCase()] ?? entity);
71
+ }
72
+
73
+ function looksLikeJson(trimmed: string): boolean {
74
+ const first = trimmed[0];
75
+ if (first !== '{' && first !== '[') return false;
76
+ try {
77
+ JSON.parse(trimmed);
78
+ return true;
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Tags whose boundaries collapse to a single space. An inline text slot cannot
86
+ * lay out blocks, so `<p>`/`<div>`/headings/lists/`<br>` become whitespace.
87
+ */
88
+ const SEPARATOR_TAGS = new Set([
89
+ 'br', 'p', 'div', 'li', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
90
+ 'blockquote', 'tr', 'section', 'article', 'header', 'footer', 'pre',
91
+ ]);
92
+
93
+ /** Quick test for "does this string carry any of the supported inline tags". */
94
+ const INLINE_TAG_RE = /<(?:b|strong|i|em|u|a)\b/i;
95
+ const TAG_RE = /<\/?([a-z][a-z0-9]*)\b([^>]*)>/gi;
96
+ const HREF_RE = /href\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
97
+
98
+ function extractHref(attrs: string): string {
99
+ const match = HREF_RE.exec(attrs);
100
+ return (match?.[1] ?? match?.[2] ?? '').trim();
101
+ }
102
+
103
+ function formatKey(node: IInlineNode): string {
104
+ return `${node.bold ? 1 : 0}|${node.italic ? 1 : 0}|${node.underline ? 1 : 0}|${node.href ?? ''}`;
105
+ }
106
+
107
+ /**
108
+ * Parse a CMS content string into a flat list of inline-formatted runs,
109
+ * preserving only the safe inline subset. Block tags + `<br>` collapse to
110
+ * spaces; entities are decoded; a JSON payload is returned as one untouched run.
111
+ * Adjacent runs that share formatting are merged and outer whitespace trimmed.
112
+ */
113
+ export function parseInlineRich(value: string | null | undefined): IInlineNode[] {
114
+ if (value == null) return [];
115
+ const str = String(value);
116
+ if (str === '') return [];
117
+
118
+ const trimmed = str.trim();
119
+ if (looksLikeJson(trimmed)) return [{ text: str }];
120
+
121
+ // Fast path: no markup at all.
122
+ if (!str.includes('<')) {
123
+ const text = decodeEntities(str);
124
+ return text === '' ? [] : [{ text }];
125
+ }
126
+
127
+ const raw: IInlineNode[] = [];
128
+ let bold = 0;
129
+ let italic = 0;
130
+ let underline = 0;
131
+ const hrefStack: string[] = [];
132
+
133
+ const pushText = (segment: string): void => {
134
+ if (segment === '') return;
135
+ raw.push({
136
+ text: segment,
137
+ ...(bold > 0 ? { bold: true } : {}),
138
+ ...(italic > 0 ? { italic: true } : {}),
139
+ ...(underline > 0 ? { underline: true } : {}),
140
+ ...(hrefStack.length > 0 ? { href: hrefStack[hrefStack.length - 1] } : {}),
141
+ });
142
+ };
143
+
144
+ let lastIndex = 0;
145
+ let match: RegExpExecArray | null;
146
+ TAG_RE.lastIndex = 0;
147
+ while ((match = TAG_RE.exec(str)) !== null) {
148
+ pushText(str.slice(lastIndex, match.index));
149
+ lastIndex = TAG_RE.lastIndex;
150
+
151
+ const isClose = match[0].charAt(1) === '/';
152
+ const tag = match[1].toLowerCase();
153
+ const attrs = match[2] ?? '';
154
+
155
+ if (tag === 'b' || tag === 'strong') {
156
+ bold = isClose ? Math.max(0, bold - 1) : bold + 1;
157
+ } else if (tag === 'i' || tag === 'em') {
158
+ italic = isClose ? Math.max(0, italic - 1) : italic + 1;
159
+ } else if (tag === 'u') {
160
+ underline = isClose ? Math.max(0, underline - 1) : underline + 1;
161
+ } else if (tag === 'a') {
162
+ if (isClose) {
163
+ hrefStack.pop();
164
+ } else {
165
+ hrefStack.push(extractHref(attrs));
166
+ }
167
+ } else if (SEPARATOR_TAGS.has(tag)) {
168
+ pushText(' ');
169
+ }
170
+ // Any other tag: drop the tag, keep the surrounding text.
171
+ }
172
+ pushText(str.slice(lastIndex));
173
+
174
+ // Merge adjacent runs that share formatting.
175
+ const merged: IInlineNode[] = [];
176
+ for (const node of raw) {
177
+ const prev = merged[merged.length - 1];
178
+ if (prev && formatKey(prev) === formatKey(node)) {
179
+ prev.text += node.text;
180
+ } else {
181
+ merged.push({ ...node });
182
+ }
183
+ }
184
+
185
+ // Decode entities + collapse whitespace, then trim the outer edges.
186
+ for (const node of merged) {
187
+ node.text = decodeEntities(node.text).replace(/\s+/g, ' ');
188
+ }
189
+ if (merged.length > 0) {
190
+ merged[0].text = merged[0].text.replace(/^\s+/, '');
191
+ merged[merged.length - 1].text = merged[merged.length - 1].text.replace(/\s+$/, '');
192
+ }
193
+ return merged.filter((node) => node.text !== '');
194
+ }
195
+
196
+ /**
197
+ * Does this value carry any of the supported inline tags? Used by renderers to
198
+ * fast-path plain strings (and to skip JSON). Cheap: no full parse.
199
+ */
200
+ export function hasInlineFormatting(value: string | null | undefined): boolean {
201
+ if (value == null) return false;
202
+ const str = String(value);
203
+ if (!str.includes('<')) return false;
204
+ if (looksLikeJson(str.trim())) return false;
205
+ return INLINE_TAG_RE.test(str);
206
+ }
207
+
208
+ /**
209
+ * Strip a content string to readable plain text: drop every tag, decode common
210
+ * entities, collapse whitespace. Block tags + `<br>` become spaces so words do
211
+ * not run together. JSON payloads and tag-free strings are returned untouched
212
+ * (apart from entity decoding), so it is safe to call on any field.
213
+ *
214
+ * This is the canonical cross-platform helper (web `stripHtmlTags` / mobile
215
+ * `stripHtmlToText` mirror it).
216
+ */
217
+ export function stripHtmlToText(value: string | null | undefined): string {
218
+ if (!value || typeof value !== 'string') return value ?? '';
219
+
220
+ const trimmed = value.trim();
221
+ if (looksLikeJson(trimmed)) return value;
222
+ if (!/[<&]/.test(value)) return value;
223
+
224
+ let out = value
225
+ .replace(/<br\s*\/?>/gi, ' ')
226
+ .replace(/<\/(p|div|li|h[1-6]|tr|blockquote)>/gi, ' ')
227
+ .replace(/<[^>]+>/g, '');
228
+
229
+ out = out.replace(/&[a-zA-Z#0-9]+;/g, (entity) => HTML_ENTITIES[entity.toLowerCase()] ?? entity);
230
+
231
+ return out.replace(/\s+/g, ' ').trim();
232
+ }
package/src/index.ts CHANGED
@@ -22,4 +22,5 @@ export * from './interpolation';
22
22
  export * from './condition';
23
23
  export * from './cms-classes';
24
24
  export * from './assets';
25
+ export * from './content';
25
26
  export * from './utils';