@selfhelp/shared 1.14.13 → 1.14.15

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';
@@ -16,6 +16,9 @@ import type {
16
16
  } from '../mantine/common';
17
17
  import type { TMantineIconSize } from './typography';
18
18
 
19
+ /** Mantine `Anchor` `underline` behaviour. */
20
+ export type TMantineAnchorUnderline = 'always' | 'hover' | 'never';
21
+
19
22
  export interface IButtonStyle extends IStyleWithSpacing {
20
23
  style_name: 'button';
21
24
  shared_variant?: IContentField<TMantineVariant>;
@@ -43,6 +46,10 @@ export interface ILinkStyle extends IStyleWithSpacing {
43
46
  label?: IContentField<string>;
44
47
  url?: IContentField<string>;
45
48
  open_in_new_tab?: IContentField<string>;
49
+ shared_color?: IContentField<TMantineColor>;
50
+ web_link_underline?: IContentField<TMantineAnchorUnderline>;
51
+ web_left_icon?: IContentField<string>;
52
+ web_right_icon?: IContentField<string>;
46
53
  }
47
54
 
48
55
  export interface IActionIconStyle extends IStyleWithSpacing {
@@ -56,7 +63,9 @@ export interface IActionIconStyle extends IStyleWithSpacing {
56
63
  is_link?: IContentField<string>;
57
64
  page_keyword?: IContentField<string>;
58
65
  open_in_new_tab?: IContentField<string>;
59
- disabled?: IContentField<string>;}
66
+ disabled?: IContentField<string>;
67
+ /** Accessible name for the icon-only control (screen readers). */
68
+ aria_label?: IContentField<string>;}
60
69
 
61
70
  export interface IAlertStyle extends IStyleWithSpacing {
62
71
  style_name: 'alert';
@@ -19,24 +19,41 @@ export interface IImageStyle extends IStyleWithSpacing {
19
19
  web_image_fit?: IContentField<TMantineImageFit>;
20
20
  web_width?: IContentField<TMantineWidth>;
21
21
  web_height?: IContentField<TMantineHeight>;
22
- shared_radius?: IContentField<TMantineRadius>;}
22
+ shared_radius?: IContentField<TMantineRadius>;
23
+ /** Image shown when the main source fails to load (Mantine Image fallbackSrc). */
24
+ fallback_src?: IContentField<string>;}
23
25
 
24
- export interface IVideoStyle extends IBaseStyle {
26
+ export interface IVideoStyle extends IStyleWithSpacing {
25
27
  style_name: 'video';
26
28
  is_fluid?: IContentField<string>;
27
29
  alt?: IContentField<string>;
28
- sources?: IContentField<unknown[]>;
30
+ video_src?: IContentField<string>;
31
+ /** Poster image shown before playback. */
32
+ poster_src?: IContentField<string>;
33
+ /** Cross-platform playback toggles ('0' | '1'). */
34
+ has_controls?: IContentField<string>;
35
+ media_loop?: IContentField<string>;
36
+ media_autoplay?: IContentField<string>;
37
+ media_muted?: IContentField<string>;
29
38
  }
30
39
 
31
- export interface IAudioStyle extends IBaseStyle {
40
+ export interface IAudioStyle extends IStyleWithSpacing {
32
41
  style_name: 'audio';
42
+ alt?: IContentField<string>;
33
43
  sources?: IContentField<unknown[]>;
44
+ /** Cross-platform playback toggles ('0' | '1'). */
45
+ has_controls?: IContentField<string>;
46
+ media_loop?: IContentField<string>;
47
+ media_autoplay?: IContentField<string>;
34
48
  }
35
49
 
36
50
  export interface IFigureStyle extends IBaseStyle {
37
51
  style_name: 'figure';
38
52
  caption_title?: IContentField<string>;
39
53
  caption?: IContentField<string>;
54
+ /** Optional built-in image so a figure needs no child image section. */
55
+ img_src?: IContentField<string>;
56
+ alt?: IContentField<string>;
40
57
  }
41
58
 
42
59
  export interface ICarouselStyle extends IStyleWithSpacing {
@@ -72,7 +72,8 @@ export interface IHighlightStyle extends IStyleWithSpacing {
72
72
 
73
73
  export interface IBlockquoteStyle extends IStyleWithSpacing {
74
74
  style_name: 'blockquote';
75
- content?: IContentField<string>;
75
+ /** Quote body. Dedicated markdown-inline field (not the generic `content`) so authors can bold/italic/link inside the quote without affecting the `code` style. */
76
+ blockquote_content?: IContentField<string>;
76
77
  cite?: IContentField<string>;
77
78
  web_left_icon?: IContentField<string>;
78
79
  web_icon_size?: IContentField<TMantineIconSize>;
@@ -104,4 +105,6 @@ export interface ISpoilerStyle extends IStyleWithSpacing {
104
105
  style_name: 'spoiler';
105
106
  web_height?: IContentField<TMantineSpoilerMaxHeight>;
106
107
  spoiler_show_label?: IContentField<string>;
107
- spoiler_hide_label?: IContentField<string>;}
108
+ spoiler_hide_label?: IContentField<string>;
109
+ /** Color of the show/hide control link. */
110
+ shared_color?: IContentField<TMantineColor>;}