@selfhelp/shared 1.14.13 → 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.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,37 @@ All notable changes to `@selfhelp/shared` will be documented in this file.
9
9
 
10
10
  This project follows semantic versioning.
11
11
 
12
+ ## v1.14.14
13
+
14
+ Cross-platform **inline rich-text** keystone. CMS authors can apply lightweight
15
+ inline formatting (Ctrl+B bold, Ctrl+I italic, Ctrl+U underline, links) to
16
+ `markdown-inline` content fields. Web could already render that HTML subset, but
17
+ React Native `<Text>` cannot render HTML, so mobile (and several web leaf slots)
18
+ used to strip it and the formatting was lost. This adds the canonical parser that
19
+ turns the safe subset into a flat list of formatted runs each platform can render
20
+ natively (web → `<strong>/<em>/<u>/<a>`, mobile → nested `<Text>`).
21
+
22
+ ### Added (`content`)
23
+
24
+ - **`parseInlineRich(value)`** → `IInlineNode[]`: parses the safe inline subset
25
+ (`<strong>`/`<b>`, `<em>`/`<i>`, `<u>`, `<a href>`) into `{ text, bold?,
26
+ italic?, underline?, href? }` runs. Block tags (`<p>`, `<div>`, headings,
27
+ lists, `<blockquote>`) and `<br>` collapse to a single space (an inline text
28
+ slot cannot lay out blocks); unknown tags are dropped but their text kept;
29
+ HTML entities are decoded; adjacent same-format runs are merged.
30
+ - **`hasInlineFormatting(value)`** → `boolean`: cheap check for whether a string
31
+ carries any supported inline tag (lets renderers fast-path plain strings).
32
+ - **`stripHtmlToText(value)`**: the canonical plain-text strip (web `stripHtmlTags`
33
+ / mobile `sanitizeContent` mirror this) — drop tags, decode entities, collapse
34
+ whitespace, block tags → spaces.
35
+ - **JSON-aware (hard):** any value that parses as JSON is returned untouched, so
36
+ structured content payloads are never mangled.
37
+ - New `IInlineNode` type and `./content` re-export from the package root.
38
+
39
+ Consumers (frontend web + mobile) currently use behaviour-identical local copies
40
+ of the parser/strip (mirroring the existing `stripHtmlToText` pattern); folding
41
+ them onto this shared export is a follow-up.
42
+
12
43
  ## v1.14.13
13
44
 
14
45
  `css_mobile` Tailwind-class lockstep fix. The web CMS class dropdown
package/dist/index.d.mts CHANGED
@@ -1511,6 +1511,78 @@ interface IAssetSource {
1511
1511
  }
1512
1512
  declare function resolveAssetSources<T extends IAssetSource>(sources: T[] | undefined, baseUrl: string): T[];
1513
1513
 
1514
+ /**
1515
+ * Cross-platform inline-formatting helpers for CMS content fields.
1516
+ *
1517
+ * ## Why
1518
+ *
1519
+ * CMS authors can apply lightweight inline formatting (Ctrl+B bold, Ctrl+I
1520
+ * italic, Ctrl+U underline, links) to content fields whose field type allows it
1521
+ * (`markdown-inline`). The editor stores that as a tiny HTML subset
1522
+ * (`<strong>`/`<b>`, `<em>`/`<i>`, `<u>`, `<a>`), often wrapped in block tags
1523
+ * (`<p>`, `<div>`) that markdown processing leaves behind.
1524
+ *
1525
+ * Web can render that subset as real inline HTML, but React Native `<Text>`
1526
+ * cannot render HTML at all — so historically mobile (and several web leaf slots)
1527
+ * stripped everything to plain text and the bold was lost. To carry the same
1528
+ * formatting to BOTH platforms we parse the subset once, here, into a flat list
1529
+ * of {@link IInlineNode} runs. Each platform then renders the runs natively:
1530
+ *
1531
+ * - web → a fragment of `<strong>/<em>/<u>/<a>` (see frontend `InlineRich`)
1532
+ * - mobile → nested `<Text>` with `fontWeight`/`fontStyle`/`textDecorationLine`
1533
+ * (see mobile `InlineText`)
1534
+ *
1535
+ * ## Scope (deliberately tiny + safe)
1536
+ *
1537
+ * Only the inline subset above survives. **Block** tags (`<p>`, `<div>`,
1538
+ * `<h1>`…`<h6>`, `<ul>`/`<ol>`/`<li>`, `<blockquote>`, `<br>`) collapse to a
1539
+ * single space — an inline text slot (a label, a paragraph run) cannot lay out
1540
+ * block structure, and flattening matches the old strip behaviour. Any other tag
1541
+ * is dropped while keeping its inner text. HTML entities are decoded.
1542
+ *
1543
+ * ## JSON-aware (HARD)
1544
+ *
1545
+ * Some content fields legitimately hold JSON (config blobs, table/segmented
1546
+ * data). Those are read via `readField`, not these helpers, but as a safety net
1547
+ * a value that parses as JSON is returned untouched so structured payloads are
1548
+ * never mangled.
1549
+ *
1550
+ * This module is the canonical home the style docs refer to; the web
1551
+ * `stripHtmlTags` and mobile `stripHtmlToText` local copies mirror
1552
+ * {@link stripHtmlToText} and are folded into this once consumers adopt it.
1553
+ */
1554
+ /** A single run of text with the inline formatting that applies to it. */
1555
+ interface IInlineNode {
1556
+ text: string;
1557
+ bold?: boolean;
1558
+ italic?: boolean;
1559
+ underline?: boolean;
1560
+ /** Present when the run sits inside an `<a href>`; the resolved target. */
1561
+ href?: string;
1562
+ }
1563
+ /**
1564
+ * Parse a CMS content string into a flat list of inline-formatted runs,
1565
+ * preserving only the safe inline subset. Block tags + `<br>` collapse to
1566
+ * spaces; entities are decoded; a JSON payload is returned as one untouched run.
1567
+ * Adjacent runs that share formatting are merged and outer whitespace trimmed.
1568
+ */
1569
+ declare function parseInlineRich(value: string | null | undefined): IInlineNode[];
1570
+ /**
1571
+ * Does this value carry any of the supported inline tags? Used by renderers to
1572
+ * fast-path plain strings (and to skip JSON). Cheap: no full parse.
1573
+ */
1574
+ declare function hasInlineFormatting(value: string | null | undefined): boolean;
1575
+ /**
1576
+ * Strip a content string to readable plain text: drop every tag, decode common
1577
+ * entities, collapse whitespace. Block tags + `<br>` become spaces so words do
1578
+ * not run together. JSON payloads and tag-free strings are returned untouched
1579
+ * (apart from entity decoding), so it is safe to call on any field.
1580
+ *
1581
+ * This is the canonical cross-platform helper (web `stripHtmlTags` / mobile
1582
+ * `stripHtmlToText` mirror it).
1583
+ */
1584
+ declare function stripHtmlToText(value: string | null | undefined): string;
1585
+
1514
1586
  /**
1515
1587
  * Parse the unified `shared_spacing` field. The CMS
1516
1588
  * stores this as a JSON string with optional keys for each side:
@@ -1590,4 +1662,4 @@ declare function transformPageData(apiPage: IRawPage): IPageItem;
1590
1662
  */
1591
1663
  declare function transformPagesData(pages: IRawPage[] | null | undefined): IPageItem[];
1592
1664
 
1593
- export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, PERMISSIONS, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, type TPermission, type TPlatform, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, parseSpacing, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, transformPageData, transformPagesData };
1665
+ export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, PERMISSIONS, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, type TPermission, type TPlatform, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, parseInlineRich, parseSpacing, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
package/dist/index.d.ts CHANGED
@@ -1511,6 +1511,78 @@ interface IAssetSource {
1511
1511
  }
1512
1512
  declare function resolveAssetSources<T extends IAssetSource>(sources: T[] | undefined, baseUrl: string): T[];
1513
1513
 
1514
+ /**
1515
+ * Cross-platform inline-formatting helpers for CMS content fields.
1516
+ *
1517
+ * ## Why
1518
+ *
1519
+ * CMS authors can apply lightweight inline formatting (Ctrl+B bold, Ctrl+I
1520
+ * italic, Ctrl+U underline, links) to content fields whose field type allows it
1521
+ * (`markdown-inline`). The editor stores that as a tiny HTML subset
1522
+ * (`<strong>`/`<b>`, `<em>`/`<i>`, `<u>`, `<a>`), often wrapped in block tags
1523
+ * (`<p>`, `<div>`) that markdown processing leaves behind.
1524
+ *
1525
+ * Web can render that subset as real inline HTML, but React Native `<Text>`
1526
+ * cannot render HTML at all — so historically mobile (and several web leaf slots)
1527
+ * stripped everything to plain text and the bold was lost. To carry the same
1528
+ * formatting to BOTH platforms we parse the subset once, here, into a flat list
1529
+ * of {@link IInlineNode} runs. Each platform then renders the runs natively:
1530
+ *
1531
+ * - web → a fragment of `<strong>/<em>/<u>/<a>` (see frontend `InlineRich`)
1532
+ * - mobile → nested `<Text>` with `fontWeight`/`fontStyle`/`textDecorationLine`
1533
+ * (see mobile `InlineText`)
1534
+ *
1535
+ * ## Scope (deliberately tiny + safe)
1536
+ *
1537
+ * Only the inline subset above survives. **Block** tags (`<p>`, `<div>`,
1538
+ * `<h1>`…`<h6>`, `<ul>`/`<ol>`/`<li>`, `<blockquote>`, `<br>`) collapse to a
1539
+ * single space — an inline text slot (a label, a paragraph run) cannot lay out
1540
+ * block structure, and flattening matches the old strip behaviour. Any other tag
1541
+ * is dropped while keeping its inner text. HTML entities are decoded.
1542
+ *
1543
+ * ## JSON-aware (HARD)
1544
+ *
1545
+ * Some content fields legitimately hold JSON (config blobs, table/segmented
1546
+ * data). Those are read via `readField`, not these helpers, but as a safety net
1547
+ * a value that parses as JSON is returned untouched so structured payloads are
1548
+ * never mangled.
1549
+ *
1550
+ * This module is the canonical home the style docs refer to; the web
1551
+ * `stripHtmlTags` and mobile `stripHtmlToText` local copies mirror
1552
+ * {@link stripHtmlToText} and are folded into this once consumers adopt it.
1553
+ */
1554
+ /** A single run of text with the inline formatting that applies to it. */
1555
+ interface IInlineNode {
1556
+ text: string;
1557
+ bold?: boolean;
1558
+ italic?: boolean;
1559
+ underline?: boolean;
1560
+ /** Present when the run sits inside an `<a href>`; the resolved target. */
1561
+ href?: string;
1562
+ }
1563
+ /**
1564
+ * Parse a CMS content string into a flat list of inline-formatted runs,
1565
+ * preserving only the safe inline subset. Block tags + `<br>` collapse to
1566
+ * spaces; entities are decoded; a JSON payload is returned as one untouched run.
1567
+ * Adjacent runs that share formatting are merged and outer whitespace trimmed.
1568
+ */
1569
+ declare function parseInlineRich(value: string | null | undefined): IInlineNode[];
1570
+ /**
1571
+ * Does this value carry any of the supported inline tags? Used by renderers to
1572
+ * fast-path plain strings (and to skip JSON). Cheap: no full parse.
1573
+ */
1574
+ declare function hasInlineFormatting(value: string | null | undefined): boolean;
1575
+ /**
1576
+ * Strip a content string to readable plain text: drop every tag, decode common
1577
+ * entities, collapse whitespace. Block tags + `<br>` become spaces so words do
1578
+ * not run together. JSON payloads and tag-free strings are returned untouched
1579
+ * (apart from entity decoding), so it is safe to call on any field.
1580
+ *
1581
+ * This is the canonical cross-platform helper (web `stripHtmlTags` / mobile
1582
+ * `stripHtmlToText` mirror it).
1583
+ */
1584
+ declare function stripHtmlToText(value: string | null | undefined): string;
1585
+
1514
1586
  /**
1515
1587
  * Parse the unified `shared_spacing` field. The CMS
1516
1588
  * stores this as a JSON string with optional keys for each side:
@@ -1590,4 +1662,4 @@ declare function transformPageData(apiPage: IRawPage): IPageItem;
1590
1662
  */
1591
1663
  declare function transformPagesData(pages: IRawPage[] | null | undefined): IPageItem[];
1592
1664
 
1593
- export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, PERMISSIONS, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, type TPermission, type TPlatform, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, parseSpacing, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, transformPageData, transformPagesData };
1665
+ export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, PERMISSIONS, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, type TPermission, type TPlatform, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, parseInlineRich, parseSpacing, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
package/dist/index.js CHANGED
@@ -72,6 +72,7 @@ __export(index_exports, {
72
72
  getStylePlatforms: () => getStylePlatforms,
73
73
  getStylePluginId: () => getStylePluginId,
74
74
  gridSpanToReactNativeColumn: () => gridSpanToReactNativeColumn,
75
+ hasInlineFormatting: () => hasInlineFormatting,
75
76
  isKnownStyleName: () => isKnownStyleName,
76
77
  isRegisteredStyleName: () => isRegisteredStyleName,
77
78
  isStyleAllowedOnPage: () => isStyleAllowedOnPage,
@@ -93,6 +94,7 @@ __export(index_exports, {
93
94
  mapSpacingToPx: () => mapSpacingToPx,
94
95
  parseDimensionToReactNative: () => parseDimensionToReactNative,
95
96
  parseDimensionToWeb: () => parseDimensionToWeb,
97
+ parseInlineRich: () => parseInlineRich,
96
98
  parseSpacing: () => parseSpacing,
97
99
  radiusToPx: () => radiusToPx,
98
100
  replaceCalcedValues: () => replaceCalcedValues,
@@ -109,6 +111,7 @@ __export(index_exports, {
109
111
  sizeToFontPx: () => sizeToFontPx,
110
112
  spacingToClasses: () => spacingToClasses,
111
113
  spacingToPx: () => spacingToPx,
114
+ stripHtmlToText: () => stripHtmlToText,
112
115
  stylePlatformToSet: () => stylePlatformToSet,
113
116
  toHeroUiSemanticProps: () => toHeroUiSemanticProps,
114
117
  toMantineSemanticProps: () => toMantineSemanticProps,
@@ -1362,6 +1365,149 @@ function resolveAssetSources(sources, baseUrl) {
1362
1365
  return sources.map((s) => ({ ...s, src: resolveAssetUrl(s.src, baseUrl) }));
1363
1366
  }
1364
1367
 
1368
+ // src/content/inlineFormat.ts
1369
+ var HTML_ENTITIES = {
1370
+ "&amp;": "&",
1371
+ "&lt;": "<",
1372
+ "&gt;": ">",
1373
+ "&quot;": '"',
1374
+ "&#39;": "'",
1375
+ "&apos;": "'",
1376
+ "&nbsp;": " ",
1377
+ "&#x2f;": "/",
1378
+ "&#47;": "/"
1379
+ };
1380
+ function decodeEntities(value) {
1381
+ if (!value.includes("&")) return value;
1382
+ return value.replace(/&[a-zA-Z#0-9]+;/g, (entity) => HTML_ENTITIES[entity.toLowerCase()] ?? entity);
1383
+ }
1384
+ function looksLikeJson(trimmed) {
1385
+ const first = trimmed[0];
1386
+ if (first !== "{" && first !== "[") return false;
1387
+ try {
1388
+ JSON.parse(trimmed);
1389
+ return true;
1390
+ } catch {
1391
+ return false;
1392
+ }
1393
+ }
1394
+ var SEPARATOR_TAGS = /* @__PURE__ */ new Set([
1395
+ "br",
1396
+ "p",
1397
+ "div",
1398
+ "li",
1399
+ "ul",
1400
+ "ol",
1401
+ "h1",
1402
+ "h2",
1403
+ "h3",
1404
+ "h4",
1405
+ "h5",
1406
+ "h6",
1407
+ "blockquote",
1408
+ "tr",
1409
+ "section",
1410
+ "article",
1411
+ "header",
1412
+ "footer",
1413
+ "pre"
1414
+ ]);
1415
+ var INLINE_TAG_RE = /<(?:b|strong|i|em|u|a)\b/i;
1416
+ var TAG_RE = /<\/?([a-z][a-z0-9]*)\b([^>]*)>/gi;
1417
+ var HREF_RE = /href\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
1418
+ function extractHref(attrs) {
1419
+ const match = HREF_RE.exec(attrs);
1420
+ return (match?.[1] ?? match?.[2] ?? "").trim();
1421
+ }
1422
+ function formatKey(node) {
1423
+ return `${node.bold ? 1 : 0}|${node.italic ? 1 : 0}|${node.underline ? 1 : 0}|${node.href ?? ""}`;
1424
+ }
1425
+ function parseInlineRich(value) {
1426
+ if (value == null) return [];
1427
+ const str = String(value);
1428
+ if (str === "") return [];
1429
+ const trimmed = str.trim();
1430
+ if (looksLikeJson(trimmed)) return [{ text: str }];
1431
+ if (!str.includes("<")) {
1432
+ const text = decodeEntities(str);
1433
+ return text === "" ? [] : [{ text }];
1434
+ }
1435
+ const raw = [];
1436
+ let bold = 0;
1437
+ let italic = 0;
1438
+ let underline = 0;
1439
+ const hrefStack = [];
1440
+ const pushText = (segment) => {
1441
+ if (segment === "") return;
1442
+ raw.push({
1443
+ text: segment,
1444
+ ...bold > 0 ? { bold: true } : {},
1445
+ ...italic > 0 ? { italic: true } : {},
1446
+ ...underline > 0 ? { underline: true } : {},
1447
+ ...hrefStack.length > 0 ? { href: hrefStack[hrefStack.length - 1] } : {}
1448
+ });
1449
+ };
1450
+ let lastIndex = 0;
1451
+ let match;
1452
+ TAG_RE.lastIndex = 0;
1453
+ while ((match = TAG_RE.exec(str)) !== null) {
1454
+ pushText(str.slice(lastIndex, match.index));
1455
+ lastIndex = TAG_RE.lastIndex;
1456
+ const isClose = match[0].charAt(1) === "/";
1457
+ const tag = match[1].toLowerCase();
1458
+ const attrs = match[2] ?? "";
1459
+ if (tag === "b" || tag === "strong") {
1460
+ bold = isClose ? Math.max(0, bold - 1) : bold + 1;
1461
+ } else if (tag === "i" || tag === "em") {
1462
+ italic = isClose ? Math.max(0, italic - 1) : italic + 1;
1463
+ } else if (tag === "u") {
1464
+ underline = isClose ? Math.max(0, underline - 1) : underline + 1;
1465
+ } else if (tag === "a") {
1466
+ if (isClose) {
1467
+ hrefStack.pop();
1468
+ } else {
1469
+ hrefStack.push(extractHref(attrs));
1470
+ }
1471
+ } else if (SEPARATOR_TAGS.has(tag)) {
1472
+ pushText(" ");
1473
+ }
1474
+ }
1475
+ pushText(str.slice(lastIndex));
1476
+ const merged = [];
1477
+ for (const node of raw) {
1478
+ const prev = merged[merged.length - 1];
1479
+ if (prev && formatKey(prev) === formatKey(node)) {
1480
+ prev.text += node.text;
1481
+ } else {
1482
+ merged.push({ ...node });
1483
+ }
1484
+ }
1485
+ for (const node of merged) {
1486
+ node.text = decodeEntities(node.text).replace(/\s+/g, " ");
1487
+ }
1488
+ if (merged.length > 0) {
1489
+ merged[0].text = merged[0].text.replace(/^\s+/, "");
1490
+ merged[merged.length - 1].text = merged[merged.length - 1].text.replace(/\s+$/, "");
1491
+ }
1492
+ return merged.filter((node) => node.text !== "");
1493
+ }
1494
+ function hasInlineFormatting(value) {
1495
+ if (value == null) return false;
1496
+ const str = String(value);
1497
+ if (!str.includes("<")) return false;
1498
+ if (looksLikeJson(str.trim())) return false;
1499
+ return INLINE_TAG_RE.test(str);
1500
+ }
1501
+ function stripHtmlToText(value) {
1502
+ if (!value || typeof value !== "string") return value ?? "";
1503
+ const trimmed = value.trim();
1504
+ if (looksLikeJson(trimmed)) return value;
1505
+ if (!/[<&]/.test(value)) return value;
1506
+ let out = value.replace(/<br\s*\/?>/gi, " ").replace(/<\/(p|div|li|h[1-6]|tr|blockquote)>/gi, " ").replace(/<[^>]+>/g, "");
1507
+ out = out.replace(/&[a-zA-Z#0-9]+;/g, (entity) => HTML_ENTITIES[entity.toLowerCase()] ?? entity);
1508
+ return out.replace(/\s+/g, " ").trim();
1509
+ }
1510
+
1365
1511
  // src/utils/spacing.ts
1366
1512
  var ALLOWED_KEYS = ["mt", "mb", "ms", "me", "pt", "pb", "ps", "pe"];
1367
1513
  function parseSpacing(raw) {
@@ -1473,6 +1619,7 @@ function transformPagesData(pages) {
1473
1619
  getStylePlatforms,
1474
1620
  getStylePluginId,
1475
1621
  gridSpanToReactNativeColumn,
1622
+ hasInlineFormatting,
1476
1623
  isKnownStyleName,
1477
1624
  isRegisteredStyleName,
1478
1625
  isStyleAllowedOnPage,
@@ -1494,6 +1641,7 @@ function transformPagesData(pages) {
1494
1641
  mapSpacingToPx,
1495
1642
  parseDimensionToReactNative,
1496
1643
  parseDimensionToWeb,
1644
+ parseInlineRich,
1497
1645
  parseSpacing,
1498
1646
  radiusToPx,
1499
1647
  replaceCalcedValues,
@@ -1510,6 +1658,7 @@ function transformPagesData(pages) {
1510
1658
  sizeToFontPx,
1511
1659
  spacingToClasses,
1512
1660
  spacingToPx,
1661
+ stripHtmlToText,
1513
1662
  stylePlatformToSet,
1514
1663
  toHeroUiSemanticProps,
1515
1664
  toMantineSemanticProps,
package/dist/index.mjs CHANGED
@@ -1242,6 +1242,149 @@ function resolveAssetSources(sources, baseUrl) {
1242
1242
  return sources.map((s) => ({ ...s, src: resolveAssetUrl(s.src, baseUrl) }));
1243
1243
  }
1244
1244
 
1245
+ // src/content/inlineFormat.ts
1246
+ var HTML_ENTITIES = {
1247
+ "&amp;": "&",
1248
+ "&lt;": "<",
1249
+ "&gt;": ">",
1250
+ "&quot;": '"',
1251
+ "&#39;": "'",
1252
+ "&apos;": "'",
1253
+ "&nbsp;": " ",
1254
+ "&#x2f;": "/",
1255
+ "&#47;": "/"
1256
+ };
1257
+ function decodeEntities(value) {
1258
+ if (!value.includes("&")) return value;
1259
+ return value.replace(/&[a-zA-Z#0-9]+;/g, (entity) => HTML_ENTITIES[entity.toLowerCase()] ?? entity);
1260
+ }
1261
+ function looksLikeJson(trimmed) {
1262
+ const first = trimmed[0];
1263
+ if (first !== "{" && first !== "[") return false;
1264
+ try {
1265
+ JSON.parse(trimmed);
1266
+ return true;
1267
+ } catch {
1268
+ return false;
1269
+ }
1270
+ }
1271
+ var SEPARATOR_TAGS = /* @__PURE__ */ new Set([
1272
+ "br",
1273
+ "p",
1274
+ "div",
1275
+ "li",
1276
+ "ul",
1277
+ "ol",
1278
+ "h1",
1279
+ "h2",
1280
+ "h3",
1281
+ "h4",
1282
+ "h5",
1283
+ "h6",
1284
+ "blockquote",
1285
+ "tr",
1286
+ "section",
1287
+ "article",
1288
+ "header",
1289
+ "footer",
1290
+ "pre"
1291
+ ]);
1292
+ var INLINE_TAG_RE = /<(?:b|strong|i|em|u|a)\b/i;
1293
+ var TAG_RE = /<\/?([a-z][a-z0-9]*)\b([^>]*)>/gi;
1294
+ var HREF_RE = /href\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
1295
+ function extractHref(attrs) {
1296
+ const match = HREF_RE.exec(attrs);
1297
+ return (match?.[1] ?? match?.[2] ?? "").trim();
1298
+ }
1299
+ function formatKey(node) {
1300
+ return `${node.bold ? 1 : 0}|${node.italic ? 1 : 0}|${node.underline ? 1 : 0}|${node.href ?? ""}`;
1301
+ }
1302
+ function parseInlineRich(value) {
1303
+ if (value == null) return [];
1304
+ const str = String(value);
1305
+ if (str === "") return [];
1306
+ const trimmed = str.trim();
1307
+ if (looksLikeJson(trimmed)) return [{ text: str }];
1308
+ if (!str.includes("<")) {
1309
+ const text = decodeEntities(str);
1310
+ return text === "" ? [] : [{ text }];
1311
+ }
1312
+ const raw = [];
1313
+ let bold = 0;
1314
+ let italic = 0;
1315
+ let underline = 0;
1316
+ const hrefStack = [];
1317
+ const pushText = (segment) => {
1318
+ if (segment === "") return;
1319
+ raw.push({
1320
+ text: segment,
1321
+ ...bold > 0 ? { bold: true } : {},
1322
+ ...italic > 0 ? { italic: true } : {},
1323
+ ...underline > 0 ? { underline: true } : {},
1324
+ ...hrefStack.length > 0 ? { href: hrefStack[hrefStack.length - 1] } : {}
1325
+ });
1326
+ };
1327
+ let lastIndex = 0;
1328
+ let match;
1329
+ TAG_RE.lastIndex = 0;
1330
+ while ((match = TAG_RE.exec(str)) !== null) {
1331
+ pushText(str.slice(lastIndex, match.index));
1332
+ lastIndex = TAG_RE.lastIndex;
1333
+ const isClose = match[0].charAt(1) === "/";
1334
+ const tag = match[1].toLowerCase();
1335
+ const attrs = match[2] ?? "";
1336
+ if (tag === "b" || tag === "strong") {
1337
+ bold = isClose ? Math.max(0, bold - 1) : bold + 1;
1338
+ } else if (tag === "i" || tag === "em") {
1339
+ italic = isClose ? Math.max(0, italic - 1) : italic + 1;
1340
+ } else if (tag === "u") {
1341
+ underline = isClose ? Math.max(0, underline - 1) : underline + 1;
1342
+ } else if (tag === "a") {
1343
+ if (isClose) {
1344
+ hrefStack.pop();
1345
+ } else {
1346
+ hrefStack.push(extractHref(attrs));
1347
+ }
1348
+ } else if (SEPARATOR_TAGS.has(tag)) {
1349
+ pushText(" ");
1350
+ }
1351
+ }
1352
+ pushText(str.slice(lastIndex));
1353
+ const merged = [];
1354
+ for (const node of raw) {
1355
+ const prev = merged[merged.length - 1];
1356
+ if (prev && formatKey(prev) === formatKey(node)) {
1357
+ prev.text += node.text;
1358
+ } else {
1359
+ merged.push({ ...node });
1360
+ }
1361
+ }
1362
+ for (const node of merged) {
1363
+ node.text = decodeEntities(node.text).replace(/\s+/g, " ");
1364
+ }
1365
+ if (merged.length > 0) {
1366
+ merged[0].text = merged[0].text.replace(/^\s+/, "");
1367
+ merged[merged.length - 1].text = merged[merged.length - 1].text.replace(/\s+$/, "");
1368
+ }
1369
+ return merged.filter((node) => node.text !== "");
1370
+ }
1371
+ function hasInlineFormatting(value) {
1372
+ if (value == null) return false;
1373
+ const str = String(value);
1374
+ if (!str.includes("<")) return false;
1375
+ if (looksLikeJson(str.trim())) return false;
1376
+ return INLINE_TAG_RE.test(str);
1377
+ }
1378
+ function stripHtmlToText(value) {
1379
+ if (!value || typeof value !== "string") return value ?? "";
1380
+ const trimmed = value.trim();
1381
+ if (looksLikeJson(trimmed)) return value;
1382
+ if (!/[<&]/.test(value)) return value;
1383
+ let out = value.replace(/<br\s*\/?>/gi, " ").replace(/<\/(p|div|li|h[1-6]|tr|blockquote)>/gi, " ").replace(/<[^>]+>/g, "");
1384
+ out = out.replace(/&[a-zA-Z#0-9]+;/g, (entity) => HTML_ENTITIES[entity.toLowerCase()] ?? entity);
1385
+ return out.replace(/\s+/g, " ").trim();
1386
+ }
1387
+
1245
1388
  // src/utils/spacing.ts
1246
1389
  var ALLOWED_KEYS = ["mt", "mb", "ms", "me", "pt", "pb", "ps", "pe"];
1247
1390
  function parseSpacing(raw) {
@@ -1352,6 +1495,7 @@ export {
1352
1495
  getStylePlatforms,
1353
1496
  getStylePluginId,
1354
1497
  gridSpanToReactNativeColumn,
1498
+ hasInlineFormatting,
1355
1499
  isKnownStyleName,
1356
1500
  isRegisteredStyleName,
1357
1501
  isStyleAllowedOnPage,
@@ -1373,6 +1517,7 @@ export {
1373
1517
  mapSpacingToPx,
1374
1518
  parseDimensionToReactNative,
1375
1519
  parseDimensionToWeb,
1520
+ parseInlineRich,
1376
1521
  parseSpacing,
1377
1522
  radiusToPx,
1378
1523
  replaceCalcedValues,
@@ -1389,6 +1534,7 @@ export {
1389
1534
  sizeToFontPx,
1390
1535
  spacingToClasses,
1391
1536
  spacingToPx,
1537
+ stripHtmlToText,
1392
1538
  stylePlatformToSet,
1393
1539
  toHeroUiSemanticProps,
1394
1540
  toMantineSemanticProps,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selfhelp/shared",
3
- "version": "1.14.13",
3
+ "version": "1.14.14",
4
4
  "description": "Shared TypeScript package for SelfHelp web frontend and mobile app: style registry, types, API contracts, Mantine theme tokens, condition + interpolation engines, CMS class allow-list.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,116 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ import { describe, it, expect } from 'vitest';
6
+ import { parseInlineRich, hasInlineFormatting, stripHtmlToText } from '../inlineFormat';
7
+
8
+ describe('parseInlineRich', () => {
9
+ it('returns a single plain run for tag-free text', () => {
10
+ expect(parseInlineRich('hello world')).toEqual([{ text: 'hello world' }]);
11
+ });
12
+
13
+ it('returns an empty list for empty / nullish input', () => {
14
+ expect(parseInlineRich('')).toEqual([]);
15
+ expect(parseInlineRich(null)).toEqual([]);
16
+ expect(parseInlineRich(undefined)).toEqual([]);
17
+ });
18
+
19
+ it('marks <strong> and <b> as bold', () => {
20
+ expect(parseInlineRich('a <strong>bold</strong> c')).toEqual([
21
+ { text: 'a ' },
22
+ { text: 'bold', bold: true },
23
+ { text: ' c' },
24
+ ]);
25
+ expect(parseInlineRich('<b>x</b>')).toEqual([{ text: 'x', bold: true }]);
26
+ });
27
+
28
+ it('marks <em>/<i> as italic and <u> as underline (merging same-format runs)', () => {
29
+ // <em>e</em><i>i</i> are both italic and adjacent, so they merge.
30
+ expect(parseInlineRich('<em>e</em><i>i</i><u>u</u>')).toEqual([
31
+ { text: 'ei', italic: true },
32
+ { text: 'u', underline: true },
33
+ ]);
34
+ });
35
+
36
+ it('combines nested formatting into one run', () => {
37
+ expect(parseInlineRich('<strong>bold <em>both</em></strong>')).toEqual([
38
+ { text: 'bold ', bold: true },
39
+ { text: 'both', bold: true, italic: true },
40
+ ]);
41
+ });
42
+
43
+ it('captures the href on anchor runs', () => {
44
+ expect(parseInlineRich('see <a href="https://x.test">here</a>')).toEqual([
45
+ { text: 'see ' },
46
+ { text: 'here', href: 'https://x.test' },
47
+ ]);
48
+ });
49
+
50
+ it('flattens the leading <p> wrapper the editor leaves behind', () => {
51
+ // The exact "label authored as plain text but stored wrapped" case.
52
+ expect(parseInlineRich('<p class="single-line-paragraph">9 STEF</p>')).toEqual([
53
+ { text: '9 STEF' },
54
+ ]);
55
+ });
56
+
57
+ it('collapses block tags + <br> to single spaces', () => {
58
+ expect(parseInlineRich('<p>a</p><p>b</p>')).toEqual([{ text: 'a b' }]);
59
+ expect(parseInlineRich('line<br/>break')).toEqual([{ text: 'line break' }]);
60
+ });
61
+
62
+ it('keeps bold across a block boundary as separate runs', () => {
63
+ expect(parseInlineRich('<p><strong>A</strong></p><p>b</p>')).toEqual([
64
+ { text: 'A', bold: true },
65
+ { text: ' b' },
66
+ ]);
67
+ });
68
+
69
+ it('decodes HTML entities', () => {
70
+ expect(parseInlineRich('a &amp; <strong>b&nbsp;c</strong>')).toEqual([
71
+ { text: 'a & ' },
72
+ { text: 'b c', bold: true },
73
+ ]);
74
+ });
75
+
76
+ it('drops unknown tags but keeps their text', () => {
77
+ expect(parseInlineRich('<span class="x">keep</span>')).toEqual([{ text: 'keep' }]);
78
+ });
79
+
80
+ it('never touches structured JSON payloads', () => {
81
+ const json = '{"type":"array","items":["a","b"]}';
82
+ expect(parseInlineRich(json)).toEqual([{ text: json }]);
83
+ });
84
+ });
85
+
86
+ describe('hasInlineFormatting', () => {
87
+ it('is true only when a supported inline tag is present', () => {
88
+ expect(hasInlineFormatting('<strong>x</strong>')).toBe(true);
89
+ expect(hasInlineFormatting('<em>x</em>')).toBe(true);
90
+ expect(hasInlineFormatting('<a href="#">x</a>')).toBe(true);
91
+ });
92
+
93
+ it('is false for plain text, block-only markup, and JSON', () => {
94
+ expect(hasInlineFormatting('plain')).toBe(false);
95
+ expect(hasInlineFormatting('<p>plain</p>')).toBe(false);
96
+ expect(hasInlineFormatting('{"a":1}')).toBe(false);
97
+ expect(hasInlineFormatting(null)).toBe(false);
98
+ });
99
+ });
100
+
101
+ describe('stripHtmlToText', () => {
102
+ it('strips tags to readable plain text', () => {
103
+ expect(stripHtmlToText('<p>a</p><p>b</p>')).toBe('a b');
104
+ expect(stripHtmlToText('<strong>bold</strong> text')).toBe('bold text');
105
+ });
106
+
107
+ it('leaves tag-free strings and JSON untouched', () => {
108
+ expect(stripHtmlToText('plain')).toBe('plain');
109
+ const json = '{"a":1}';
110
+ expect(stripHtmlToText(json)).toBe(json);
111
+ });
112
+
113
+ it('decodes entities', () => {
114
+ expect(stripHtmlToText('a &amp; b')).toBe('a & b');
115
+ });
116
+ });
@@ -0,0 +1,5 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ export * from './inlineFormat';
@@ -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';