RichTextRenderer.vue
10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
<!--
* @Date: 2026-02-27
* @Description: 富文本渲染组件 - 基于 Taro v-html
*
* @features
* - HTML 实体自动解码
* - <a> 标签自动替换为 <div data-href="">
* - 图片长按预览
* - 文件链接点击处理
* - 可选的 transformElement 图片自动处理
*
* @example
* <RichTextRenderer
* :content="htmlContent"
* :enable-transform="true"
* @image-preview="handlePreview"
* @file-click="handleFileClick"
* />
-->
<template>
<view id="rich-text-renderer" v-html="processedContent" class="rich-text-content"></view>
</template>
<script setup>
import { ref, watch, nextTick } from 'vue'
import Taro from '@tarojs/taro'
import { $ } from '@tarojs/extend'
import { useFileOperation } from '@/composables/useFileOperation'
// 注意:不再导入全局的 @tarojs/taro/html.css
// 改为在组件内部内联完整的 html.css 样式,通过 #rich-text-renderer ID 选择器限制作用范围
/**
* 组件属性
*/
const props = defineProps({
/**
* HTML 内容字符串
*/
content: {
type: String,
default: ''
},
/**
* 是否启用 transformElement 自动处理图片
* @description 开启后会为非链接内的图片添加 mode="widthFix" 和 style="width: 100%"
* @default true
*/
enableTransform: {
type: Boolean,
default: true
}
})
/**
* 组件事件
*/
const emit = defineEmits(['image-preview', 'file-click'])
// 文件操作
const { viewFile } = useFileOperation()
// 处理后的内容
const processedContent = ref('')
// 容器 ID(用于 jQuery 选择器)
const CONTAINER_ID = '#rich-text-renderer'
/**
* HTML 实体解码
*/
const decodeHtmlEntities = (html) => {
return html
.replace(/ /g, ' ') // 空格
.replace(/&/g, '&') // &
.replace(/</g, '<') // <
.replace(/>/g, '>') // >
.replace(/"/g, '"') // "
.replace(/'/g, "'") // '
}
/**
* 替换 <a> 标签为 <div data-href="">
*/
const replaceAnchorTags = (html) => {
let content = html
// 替换 <a ... href="..."> 为 <div ... data-href="..." data-is-link="true">
content = content.replace(/<a\s+/g, '<div data-is-link="true" ')
content = content.replace(/href=/g, 'data-href=')
content = content.replace(/<\/a>/g, '</div>')
return content
}
/**
* 处理 HTML 内容
*/
const processContent = (raw) => {
if (!raw) {
processedContent.value = ''
return
}
let processed = raw
// 1. HTML 实体解码
processed = decodeHtmlEntities(processed)
// 2. 替换 <a> 标签
processed = replaceAnchorTags(processed)
processedContent.value = processed
}
/**
* 配置 transformElement
*/
const setupTransformElement = () => {
if (props.enableTransform) {
Taro.options.html.transformElement = (element) => {
const el = element
// 获取标签名(兼容大小写)
const nodeName = el.nodeName?.toLowerCase() || ''
const tagName = el.tagName?.toLowerCase() || ''
// 只处理 img/image 标签
const isImg = nodeName === 'img' || tagName === 'img' || nodeName === 'image' || tagName === 'image'
if (!isImg) {
return el
}
// 检查是否在链接内(遍历整个父元素链)
let parent = el.parentElement
let isInsideLink = false
while (parent) {
const pName = parent.nodeName?.toLowerCase() || ''
const pDataIsLink = parent.getAttribute?.('data-is-link')
const pClassList = parent.classList?.value || ''
// 检查是否在 <a> 或带有 data-is-link 或 _file_list class 的元素内
if (pName === 'a' || pDataIsLink === 'true' || pClassList.includes('_file_list')) {
isInsideLink = true
break
}
parent = parent.parentElement
}
if (isInsideLink) {
// 在链接内的 img(图标),不处理但必须返回元素
return el
}
// 在链接外的 img(内容图片),添加完整的样式
if (el.setAttribute) {
el.setAttribute('mode', 'widthFix')
// 设置完整样式,确保图片宽度100%并保持正确显示
el.setAttribute('style', 'width:100%!important;max-width:100%!important;height:auto!important;display:block;margin:24rpx 0;')
}
return el
}
} else {
Taro.options.html.transformElement = undefined
}
}
/**
* 绑定图片长按预览事件
*/
const bindImageEvents = () => {
nextTick(() => {
const imgs = $(CONTAINER_ID).children('.h5-p').children('.h5-img')
imgs.forEach(function (img) {
$(img).off('longpress') // 先解绑,避免重复
$(img).on('longpress', function () {
const src = $(img).attr('src')
Taro.previewImage({
urls: [src],
current: src,
indicator: 'default',
loop: false,
success: () => {
emit('image-preview', { src })
},
fail: () => {
// 预览失败
}
})
})
})
})
}
/**
* 绑定文件链接点击事件
*/
const bindFileLinkEvents = () => {
nextTick(() => {
const container = $(CONTAINER_ID)
const fileLinks = container.find('div[data-is-link="true"]')
// 如果找不到 data-is-link,尝试用 class 查找
const targetLinks = fileLinks.length > 0 ? fileLinks : container.find('._file_list')
targetLinks.each(function (idx, el) {
const $el = $(el)
const dataHref = $el.attr('data-href')
if (dataHref) {
$el.off('tap') // 先解绑,避免重复
$el.on('tap', function () {
// 尝试提取文件名
const fileName = $el.find('span span span').first().text() ||
$el.text().trim().substring(0, 50) ||
'document.pdf'
emit('file-click', { url: dataHref, fileName })
viewFile({ downloadUrl: dataHref, fileName })
})
}
})
})
}
/**
* 处理内容变化
*/
const handleContentChange = () => {
processContent(props.content)
// 等待 DOM 更新后绑定事件
nextTick(() => {
bindImageEvents()
bindFileLinkEvents()
})
}
/**
* 监听 props 变化
*/
// 重要:先设置 transformElement,再监听内容变化
setupTransformElement()
watch(() => props.content, handleContentChange, { immediate: true })
watch(() => props.enableTransform, () => {
setupTransformElement()
// 重新渲染当前内容
if (processedContent.value) {
const current = processedContent.value
processedContent.value = ''
nextTick(() => {
processedContent.value = current
handleContentChange()
})
}
})
/**
* 组件挂载
*/
// transformElement 已在初始化时设置,watch immediate 已处理首次渲染
</script>
<style lang="less">
// 注意:v-html 内容不受 scoped 样式影响,因此不使用 scoped
// 通过 #rich-text-renderer ID 选择器限制样式作用范围,避免污染全局
// 参考 @tarojs/taro/html.css 的完整 HTML4 样式
#rich-text-renderer {
// ========== 基础显示属性 ==========
.h5-html,
.h5-address,
.h5-blockquote,
.h5-body,
.h5-dd,
.h5-div,
.h5-dl,
.h5-dt,
.h5-fieldset,
.h5-form,
.h5-frame,
.h5-frameset,
.h5-h1,
.h5-h2,
.h5-h3,
.h5-h4,
.h5-h5,
.h5-h6,
.h5-noframes,
.h5-ol,
.h5-p,
.h5-ul,
.h5-center,
.h5-dir,
.h5-hr,
.h5-menu,
.h5-pre {
display: block;
unicode-bidi: embed;
}
.h5-li {
display: list-item;
}
.h5-head {
display: none;
}
// ========== 表格样式 ==========
.h5-table {
display: table;
border-spacing: 2px;
}
.h5-tr {
display: table-row;
}
.h5-thead {
display: table-header-group;
}
.h5-tbody {
display: table-row-group;
}
.h5-tfoot {
display: table-footer-group;
}
.h5-col {
display: table-column;
}
.h5-colgroup {
display: table-column-group;
}
.h5-td,
.h5-th {
display: table-cell;
}
.h5-caption {
display: table-caption;
text-align: center;
}
.h5-th {
text-align: center;
font-weight: bolder;
}
.h5-thead,
.h5-tbody,
.h5-tfoot {
vertical-align: middle;
}
.h5-td,
.h5-th,
.h5-tr {
vertical-align: inherit;
}
// ========== 标题样式 ==========
.h5-body {
margin: 8px;
}
.h5-h1 {
margin: 0.67em 0;
font-size: 2em;
}
.h5-h2 {
margin: 0.75em 0;
font-size: 1.5em;
}
.h5-h3 {
margin: 0.83em 0;
font-size: 1.17em;
}
.h5-h4,
.h5-p,
.h5-blockquote,
.h5-ul,
.h5-fieldset,
.h5-form,
.h5-ol,
.h5-dl,
.h5-dir,
.h5-menu {
margin: 1.12em 0;
}
.h5-h5 {
margin: 1.5em 0;
font-size: 0.83em;
}
.h5-h6 {
margin: 1.67em 0;
font-size: 0.75em;
}
.h5-h1,
.h5-h2,
.h5-h3,
.h5-h4,
.h5-h5,
.h5-h6 {
line-height: 1;
}
.h5-h1,
.h5-h2,
.h5-h3,
.h5-h4,
.h5-h5,
.h5-h6,
.h5-b,
.h5-strong {
font-weight: bolder;
}
// ========== 文本样式 ==========
.h5-blockquote {
margin-left: 40px;
margin-right: 40px;
}
.h5-i,
.h5-cite,
.h5-em,
.h5-var,
.h5-address {
font-style: italic;
}
.h5-pre,
.h5-tt,
.h5-code,
.h5-kbd,
.h5-samp {
font-family: monospace;
}
.h5-pre {
white-space: pre;
}
.h5-big {
font-size: 1.17em;
}
.h5-small,
.h5-sub,
.h5-sup {
font-size: 0.83em;
}
.h5-sub {
vertical-align: sub;
}
.h5-sup {
vertical-align: super;
}
.h5-s,
.h5-strike,
.h5-del {
text-decoration: line-through;
}
.h5-u,
.h5-ins {
text-decoration: underline;
}
.h5-center {
text-align: center;
}
// ========== 列表样式 ==========
.h5-ol,
.h5-ul,
.h5-dir,
.h5-menu,
.h5-dd {
margin-left: 40px;
}
.h5-ol {
list-style-type: decimal;
}
.h5-ol .h5-ul,
.h5-ul .h5-ol,
.h5-ul .h5-ul,
.h5-ol .h5-ol {
margin-top: 0;
margin-bottom: 0;
}
// ========== 其他元素 ==========
.h5-button,
.h5-textarea,
.h5-input,
.h5-select {
display: inline-block;
}
input[type="hidden"] {
display: none !important;
}
.h5-a {
display: inline;
}
.h5-button::after {
border: none;
}
.h5-span {
display: inline;
}
.h5-hr {
border: 1px inset;
}
.h5-br::before {
white-space: pre-line;
content: "\A";
}
// ========== 自定义补充样式 ==========
// 图片样式(transformElement 已添加 mode 和 style,这里做兜底)
.h5-img,
img {
max-width: 100%;
height: auto;
}
// 文件链接交互样式
div[data-is-link="true"] {
cursor: pointer;
transition: opacity 0.2s;
&:active {
opacity: 0.7;
}
}
}
</style>