RichTextOverflowTag:基于 HarmonyOS ArkTS 的富文本 HAR 模块项目

富文本尾随标签组件

Branch1Tags0
FilesLast commitLast update
5 months ago
5 months ago
5 months ago
4 months ago
5 months ago
5 months ago
5 months ago
5 months ago
4 months ago
5 months ago
5 months ago
5 months ago

RichTextOverflowTag

RichTextOverflowTag 是一个 HarmonyOS ArkTS 富文本 HAR 模块,提供文本、图片、内嵌标签、点击高亮、自动识别、尾部展开 token 和尾部 tag 展示能力。

当前工程包含两个模块:

  • rich_text_overflow_fag:HAR 库模块,包名 richtextoverflowtag
  • entry:Demo HAP 模块,用于验证基础富文本、话题标签、尾部 token、尾部 tag 等场景

功能特性

  • 多段文本拼接,支持统一样式和局部样式
  • 支持文本高亮、点击、长按回调
  • 支持图片 run 和组件 run,组件 run 可用于文本中的角标、引用标、徽章等
  • 支持 maxLines、TextOverflow、WordBreak、行间距、内边距
  • 支持字符串截断 token,例如 ...展开
  • 支持自定义 tailTokenBuilder,用于构建展开按钮
  • 支持自定义 tailTagBuilder,用于在文本尾部追加“继续看”“推荐”等尾部标签
  • 支持 EmText 和 HighLightText 扩展组件,便于解析强调文本和关键字高亮

接入方式

通过 ohpm 安装:

ohpm install richtextoverflowtag

或使用简写命令:

ohpm i richtextoverflowtag

本地开发调试时,也可以在业务模块的 oh-package.json5 中添加本地依赖:

{
  "dependencies": {
    "richtextoverflowtag": "file:../rich_text_overflow_fag"
  }
}

在 ArkTS 文件中引入:

import {
  RichTextComponent,
  AttributeLabelBuilder,
  AttributeLabelModel
} from 'richtextoverflowtag'

快速使用

import {
  RichTextComponent,
  AttributeLabelBuilder,
  AttributeLabelModel
} from 'richtextoverflowtag'

@ComponentV2
struct DemoText {
  @Local private model: AttributeLabelModel = { runs: [] }

  aboutToAppear(): void {
    this.model = new AttributeLabelBuilder()
      .setMaxLines(2)
      .setCommonStyle({
        fontSize: 16,
        lineHeight: 24,
        fontColor: '#1f2329'
      })
      .appendText({
        text: '这是一段用于演示的富文本,超过两行后会展示省略号。'
      })
      .build()
  }

  build() {
    RichTextComponent({
      model: this.model
    })
  }
}

RichTextComponent

RichTextComponent 是核心渲染组件。

RichTextComponent({
  model: this.model,
  maxLinesOverride: 2,
  tailTokenBuilder: this.buildTailToken,
  tailTagBuilder: this.buildTailTag
})
参数 类型 说明
model AttributeLabelModel 富文本数据模型
maxLinesOverride number 临时覆盖 model.config.maxLines;默认 -1 表示使用 model 配置
tailTokenBuilder () => void 自定义溢出 token,例如“展开”按钮
tailTagBuilder () => void 自定义尾部标签,例如“继续看”徽章

Builder 用法

推荐通过 AttributeLabelBuilder 构建 AttributeLabelModel。

const model = new AttributeLabelBuilder()
  .setMaxLines(2)
  .setInsets(0, 0, 0, 0)
  .setTruncationToken('...展开')
  .setTruncationTokenSpacing(6)
  .setTextVerticalAlign(AttributeTextVerticalAlign.CENTER)
  .setCommonStyle({
    fontSize: 16,
    lineHeight: 24,
    fontColor: '#1f2329'
  })
  .appendText({ text: '普通文本 ' })
  .appendHighlightText({
    text: '#话题#',
    key: 'topic',
    normalStyle: { fontColor: '#2f7de1' },
    onTap: (ctx) => {
      console.info(`tap ${ctx.runId}`)
    }
  })
  .appendText({ text: ' 后续正文内容' })
  .build()

常用方法:

方法 说明
setConfig(config) 批量设置配置
setMaxLines(maxLines) 设置最大行数;0 表示不限制
setInsets(top, right, bottom, left) 设置内边距
setTruncationToken(token) 设置字符串截断 token
setTruncationTokenSpacing(spacing) 设置 token/tag 与正文之间的间距
setTextVerticalAlign(align) 设置尾部区域垂直对齐方式
setCommonStyle(style) 设置通用文本样式
appendText(options) 追加文本
appendImage(options) 追加图片
appendComponent(options) 追加内嵌组件标签
appendHighlightText(options) 追加高亮文本
appendLinkText(options) 追加链接文本
appendAutoDetectedText(options) 自动识别链接、手机号等片段并高亮
bindHighlightTap(key, onTap) 绑定已有高亮 key 的点击事件
bindHighlightLongPress(key, onLongPress) 绑定已有高亮 key 的长按事件
build() 同步构建 AttributeLabelModel
buildAsync() 异步构建 AttributeLabelModel

TailToken 与 TailTag

字符串 TailToken

适合简单的“展开”文案。

this.model = new AttributeLabelBuilder()
  .setMaxLines(2)
  .setTruncationToken('...展开')
  .setTruncationTokenSpacing(0)
  .appendText({
    text: '这是一段很长的文本,超过两行后展示字符串 token。'
  })
  .build()
RichTextComponent({
  model: this.model
})

自定义 TailToken

适合需要按钮、图标或更复杂样式的展开入口。

@Builder
private buildTailToken() {
  Text('展开')
    .fontSize(14)
    .fontColor('#1677ff')
}

build() {
  RichTextComponent({
    model: this.model,
    maxLinesOverride: 2,
    tailTokenBuilder: this.buildTailToken
  })
}

自定义 TailTag

tailTagBuilder 用于在文本尾部展示标签。文本未溢出时会尽量跟随最后一行;放不下时会换到下一行。文本溢出时会根据 maxLines、剩余宽度和标签宽度决定同排展示或独占一行。

@Builder
private buildTailTag() {
  Row({ space: 4 }) {
    Text('荐')
      .fontSize(11)
      .fontWeight(FontWeight.Medium)
      .fontColor('#ffffff')
      .padding({ left: 4, right: 4, top: 1, bottom: 1 })
      .backgroundColor('#2f7de1')
      .borderRadius(6)

    Text('继续看')
      .fontSize(13)
      .fontWeight(FontWeight.Medium)
      .fontColor('#2f7de1')
  }
  .padding({ left: 8, right: 8, top: 4, bottom: 4 })
  .backgroundColor('#eef5ff')
  .borderRadius(14)
  .border({ width: 1, color: '#d7e7ff' })
}

build() {
  RichTextComponent({
    model: this.model,
    maxLinesOverride: 2,
    tailTagBuilder: this.buildTailTag
  })
}

内嵌组件标签

appendComponent 可在文本流中插入一个自绘标签,适合引用序号、徽章等轻量元素。

const model = new AttributeLabelBuilder()
  .setCommonStyle({
    fontSize: 17,
    lineHeight: 29,
    fontColor: '#1f2329'
  })
  .appendText({ text: '这段回答综合了官方文档' })
  .appendComponent({
    componentId: '1',
    style: {
      fontSize: 11,
      fontWeight: FontWeight.Medium,
      fontColor: '#2f7de1',
      backgroundColor: '#eef5ff',
      paddingLeft: 6,
      paddingRight: 6,
      paddingTop: 1,
      paddingBottom: 1,
      marginLeft: 6,
      cornerRadius: 9
    }
  })
  .appendText({ text: '以及项目内实现记录。' })
  .build()

扩展组件

EmText

EmText 用于解析强调标签,内部会转换为 RichTextComponent 渲染。

EmText({
  content: '这是一段 <em>强调文本</em>',
  textStyle: {
    fontSize: 16,
    lineHeight: 24,
    fontColor: '#1f2329'
  },
  config: {
    maxLines: 2
  },
  checkBold: true,
  forceEmTagColor: '#1677ff'
})

HighLightText

HighLightText 用于对指定关键词做高亮,也可同时解析强调和下标标签。

HighLightText({
  content: '企查查提供企业查询、风险监控等能力',
  highlightList: [
    {
      name: '企查查',
      onTap: (ctx) => {
        console.info(`tap ${ctx.text}`)
      }
    }
  ],
  highLightColor: '#1677ff',
  highLightPressedColor: '#0e5ad6',
  config: {
    maxLines: 2
  }
})

配置说明

AttributeLabelConfig:

字段 默认值 说明
maxLines 0 最大行数;0 表示不限制
textAlign TextAlign.Start 文本对齐
overflow { overflow: TextOverflow.Ellipsis } 原生文本溢出策略
wordBreak WordBreak.BREAK_WORD 换行策略
selectable false 是否允许选择
copyOptionEnabled false 是否启用复制选项
insets { top: 0, right: 0, bottom: 0, left: 0 } 组件内边距
truncationToken '...' 字符串截断 token
truncationTokenSpacing 4 token/tag 与正文间距,单位 vp
lineSpacing 0 行间距
textVerticalAlign AttributeTextVerticalAlign.CENTER 尾部 token/tag 与末行的垂直对齐方式
debugBorder false 是否显示调试边框

AttributeTextStyle 支持:

字段 说明
fontSize、fontWeight、fontColor、fontStyle 字体相关样式
lineHeight、letterSpacing、baselineOffset 排版相关样式
decorationType、decorationColor 下划线等装饰样式
backgroundColor、cornerRadius 背景和圆角
paddingLeft/right/top/bottom 组件 run 内边距
marginLeft/right/top/bottom 组件 run 外边距

目录说明

rich_text_overflow_fag/
  Index.ets
  src/main/ets/
    base/
      detect/                 # 自动识别能力
      types/                  # 基础类型
    component/
      RichTextComponent.ets   # 核心渲染组件
      builder/                # AttributeLabelBuilder
      span/                   # 内嵌组件 span
      util/                   # 文本构建、测量、tail 策略等内部实现
    extension/
      richtext/               # EmText、HighLightText 和解析器
entry/
  src/main/ets/components/    # Demo 页面

运行 Demo

  1. 使用 DevEco Studio 打开工程根目录
  2. 执行 Sync,同步本地 HAR 依赖
  3. 配置 debug 签名
  4. 运行 entry

注意事项

  • tailTokenBuilder 与 tailTagBuilder 同时传入时,溢出场景会优先保证展开 token 的可见性,并按剩余空间决定 tailTag 的展示方式。
  • tailTagBuilder 宽度较长时,组件会判断它是否需要独占一行,避免直接挤出文本区域。
  • 自定义 tailTokenBuilder 的最大可用宽度按末行宽度的 50% 控制,避免展开区域完全占满文本行。
  • maxLinesOverride 只影响当前 RichTextComponent 实例,不会修改 AttributeLabelModel 本身。

Introduction

富文本尾随标签组件

Customize your domain