Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

7.3 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { Color } from '../../types';

export interface TextSegment {
    type: 'text';
    text: string;
    bold: boolean;
    italic: boolean;
    color: Color | null;
    fontSize: number | null;
}

export type ImageValign = 'baseline' | 'middle' | 'top' | 'bottom';

export interface ImageSegment {
    type: 'image';
    src: string;
    width: number;
    height: number;
    valign: ImageValign;
    offsetX: number;
    offsetY: number;
    scale: number;
    tint: Color | null;
}

export type RichTextRun = TextSegment | ImageSegment;

export interface TextRun extends TextSegment {}

interface StyleFrame {
    bold: boolean;
    italic: boolean;
    color: Color | null;
    fontSize: number | null;
}

const TAG_COLOR_RE = /^color=(#[0-9a-fA-F]{6,8})$/;
const TAG_FONT_SIZE_RE = /^font\s+size=(?:"(\d+)"|(\d+))$/;
/** `<size=24>`: the same as `<font size=24>`, in the spelling Cocos Creator's rich text uses. */
const TAG_SIZE_RE = /^size=(?:"(\d+)"|'(\d+)'|(\d+))$/;
/** `<color=red>`: a colour by name, as well as by hex. */
const TAG_COLOR_NAME_RE = /^color=(?:"([a-zA-Z]+)"|'([a-zA-Z]+)'|([a-zA-Z]+))$/;
/** Tags that mark text this renderer cannot style (underline, strike, outline) or react to (`<on click>`): the tag is consumed and its text kept. */
const TAG_INERT_OPEN_RE = /^(?:u|s|outline(?:\s[^>]*)?|on(?:\s[^>]*)?)$/;
const TAG_INERT_CLOSE = new Set(['/u', '/s', '/outline', '/on']);

const NAMED_COLORS: Readonly<Record<string, string>> = {
    black: '#000000', white: '#ffffff', red: '#ff0000', green: '#00ff00', blue: '#0000ff', yellow: '#ffff00', cyan: '#00ffff',
    magenta: '#ff00ff', orange: '#ffa500', gray: '#808080', grey: '#808080', purple: '#800080', pink: '#ffc0cb', brown: '#a52a2a',
};

function parseHexColor(hex: string): Color | null {
    if (hex.length !== 7 && hex.length !== 9) return null;
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    const a = hex.length === 9 ? parseInt(hex.slice(7, 9), 16) : 255;
    if (isNaN(r) || isNaN(g) || isNaN(b) || isNaN(a)) return null;
    return { r: r / 255, g: g / 255, b: b / 255, a: a / 255 };
}

function emitTextRun(runs: RichTextRun[], text: string, style: StyleFrame): void {
    if (text.length === 0) return;
    runs.push({ type: 'text', text, bold: style.bold, italic: style.italic, color: style.color, fontSize: style.fontSize });
}

const IMG_ATTR_RE = /(\w+)\s*=\s*(?:"([^"]*)"|(\S+))/g;
const VALID_VALIGNS = new Set<ImageValign>(['baseline', 'middle', 'top', 'bottom']);

function parseImgTag(tagContent: string): ImageSegment | null {
    const attrs = new Map<string, string>();
    let m: RegExpExecArray | null;
    IMG_ATTR_RE.lastIndex = 0;
    while ((m = IMG_ATTR_RE.exec(tagContent)) !== null) {
        attrs.set(m[1], m[2] ?? m[3]);
    }
    const src = attrs.get('src');
    if (!src) return null;
    const w = parseInt(attrs.get('width') ?? '0', 10);
    const h = parseInt(attrs.get('height') ?? '0', 10);
    const rawValign = attrs.get('valign') as ImageValign | undefined;
    const valign = rawValign && VALID_VALIGNS.has(rawValign) ? rawValign : 'baseline';
    const ox = parseFloat(attrs.get('offsetX') ?? '0');
    const oy = parseFloat(attrs.get('offsetY') ?? '0');
    const scale = parseFloat(attrs.get('scale') ?? '1');
    const tintStr = attrs.get('tint');
    const tint = tintStr ? parseHexColor(tintStr) : null;
    return {
        type: 'image', src,
        width: isNaN(w) ? 0 : w, height: isNaN(h) ? 0 : h,
        valign,
        offsetX: isNaN(ox) ? 0 : ox,
        offsetY: isNaN(oy) ? 0 : oy,
        scale: isNaN(scale) || scale <= 0 ? 1 : scale,
        tint,
    };
}

export function parseRichText(input: string): RichTextRun[] {
    const runs: RichTextRun[] = [];
    if (!input) return runs;

    const stack: StyleFrame[] = [{ bold: false, italic: false, color: null, fontSize: null }];
    let buffer = '';
    let i = 0;

    while (i < input.length) {
        if (input[i] !== '<') {
            buffer += input[i];
            i++;
            continue;
        }

        const closeIdx = input.indexOf('>', i + 1);
        if (closeIdx === -1) {
            buffer += input[i];
            i++;
            continue;
        }

        const tagContent = input.slice(i + 1, closeIdx);
        const current = stack[stack.length - 1];

        if (tagContent === 'b') {
            emitTextRun(runs, buffer, current);
            buffer = '';
            stack.push({ ...current, bold: true });
        } else if (tagContent === 'i') {
            emitTextRun(runs, buffer, current);
            buffer = '';
            stack.push({ ...current, italic: true });
        } else if (tagContent === '/b' || tagContent === '/i' || tagContent === '/color' || tagContent === '/font' || tagContent === '/size') {
            emitTextRun(runs, buffer, current);
            buffer = '';
            if (stack.length > 1) stack.pop();
        } else if (tagContent === 'br' || tagContent === 'br/' || tagContent === 'br /') {
            buffer += '\n';
        } else if (TAG_INERT_OPEN_RE.test(tagContent)) {
            // keep the text; the style (or the click) is not something this renderer has
            emitTextRun(runs, buffer, current);
            buffer = '';
            stack.push({ ...current });
        } else if (TAG_INERT_CLOSE.has(tagContent)) {
            emitTextRun(runs, buffer, current);
            buffer = '';
            if (stack.length > 1) stack.pop();
        } else if (tagContent.startsWith('img ') && tagContent.endsWith('/')) {
            const img = parseImgTag(tagContent.slice(0, -1));
            if (img) {
                emitTextRun(runs, buffer, current);
                buffer = '';
                runs.push(img);
            } else {
                buffer += input.slice(i, closeIdx + 1);
                i = closeIdx + 1;
                continue;
            }
        } else {
            const colorMatch = tagContent.match(TAG_COLOR_RE);
            const nameMatch = colorMatch ? null : tagContent.match(TAG_COLOR_NAME_RE);
            const named = nameMatch ? NAMED_COLORS[(nameMatch[1] ?? nameMatch[2] ?? nameMatch[3]).toLowerCase()] : undefined;
            const parsed = colorMatch ? parseHexColor(colorMatch[1]) : named ? parseHexColor(named) : null;
            const fontSizeMatch = tagContent.match(TAG_FONT_SIZE_RE);
            const sizeMatch = fontSizeMatch ? null : tagContent.match(TAG_SIZE_RE);
            const parsedSize = fontSizeMatch ? parseInt(fontSizeMatch[1] ?? fontSizeMatch[2], 10)
                : sizeMatch ? parseInt(sizeMatch[1] ?? sizeMatch[2] ?? sizeMatch[3], 10) : NaN;

            if (parsed) {
                emitTextRun(runs, buffer, current);
                buffer = '';
                stack.push({ ...current, color: parsed });
            } else if (!isNaN(parsedSize) && parsedSize > 0) {
                emitTextRun(runs, buffer, current);
                buffer = '';
                stack.push({ ...current, fontSize: parsedSize });
            } else {
                buffer += input.slice(i, closeIdx + 1);
                i = closeIdx + 1;
                continue;
            }
        }

        i = closeIdx + 1;
    }

    emitTextRun(runs, buffer, stack[stack.length - 1]);
    return runs;
}