RichTextRenderer.vue
9.75 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
<template>
<view :id="containerId" class="rich-text-renderer" v-html="processedContent"></view>
</template>
<script setup>
import { ref, watch, nextTick, onBeforeUnmount } from 'vue'
import Taro from '@tarojs/taro'
import { $ } from '@tarojs/extend'
const props = defineProps({
content: {
type: String,
default: '',
},
enableTransform: {
type: Boolean,
default: true,
},
})
const emit = defineEmits(['image-preview', 'file-click', 'link-copy'])
const processedContent = ref('')
const containerId = `rich-text-renderer-${Math.random().toString(36).slice(-8)}`
const containerSelector = `#${containerId}`
const previousTransformElement = Taro.options.html?.transformElement
const decodeHtmlEntities = html => {
if (!html) {
return ''
}
if (process.env.TARO_ENV === 'h5' && typeof document !== 'undefined') {
try {
const textArea = document.createElement('textarea')
textArea.innerHTML = html
const decoded = textArea.value
if (decoded !== html) {
return decoded
}
} catch (error) {
console.warn('[RichTextRenderer] DOM 解码失败,改用映射表', error)
}
}
const entityMap = {
' ': '\u00A0',
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
'©': '©',
'®': '®',
'™': '™',
'—': '—',
'–': '–',
'…': '…',
'«': '«',
'»': '»',
'‘': '\u2018',
'’': '\u2019',
'“': '"',
'”': '"',
}
let result = html
result = result.replace(/&#(\d+);/g, (_match, dec) => String.fromCharCode(dec))
result = result.replace(/&#x([0-9a-fA-F]+);/g, (_match, hex) =>
String.fromCharCode(parseInt(hex, 16))
)
Object.entries(entityMap).forEach(([entity, char]) => {
result = result.split(entity).join(char)
})
return result
}
const replaceAnchorTags = html => {
let content = html
// 小程序 rich-text 对原生 a 标签交互能力有限,统一替换成可绑定事件的块级节点。
content = content.replace(/<a\s+/g, '<div class="rich-text-link" ')
content = content.replace(/href=/g, 'data-href=')
content = content.replace(/<\/a>/g, '</div>')
return content
}
const processContent = raw => {
if (!raw) {
processedContent.value = ''
return
}
let processed = raw
processed = decodeHtmlEntities(processed)
processed = replaceAnchorTags(processed)
processedContent.value = processed
}
const isImageUrl = (url = '') => /\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?.*)?$/i.test(url)
const getFileNameFromUrl = (url = '') => {
const cleanUrl = url.split('?')[0]
const segments = cleanUrl.split('/')
return segments[segments.length - 1] || 'document.pdf'
}
const copyLink = (url, fileName = '链接') => {
Taro.setClipboardData({
data: url,
success: () => {
Taro.showToast({
title: '链接已复制',
icon: 'success',
duration: 2000,
})
emit('link-copy', { url, fileName })
},
fail: error => {
console.error('[RichTextRenderer] 复制链接失败:', error)
Taro.showToast({
title: '复制失败',
icon: 'none',
})
},
})
}
const openFileLink = async (url, fileName) => {
emit('file-click', { url, fileName })
if (isImageUrl(url)) {
Taro.previewImage({
urls: [url],
current: url,
indicator: 'default',
loop: false,
})
return
}
Taro.showLoading({ title: '文件打开中...' })
try {
const downloadResult = await Taro.downloadFile({
url,
})
if (downloadResult.statusCode !== 200 || !downloadResult.tempFilePath) {
throw new Error(`下载失败: ${downloadResult.statusCode}`)
}
await Taro.openDocument({
filePath: downloadResult.tempFilePath,
showMenu: true,
})
} catch (error) {
console.error('[RichTextRenderer] 文件打开失败:', error)
Taro.showModal({
title: '打开失败',
content: '当前文件无法直接预览,是否复制链接后用其他应用打开?',
confirmText: '复制链接',
cancelText: '取消',
success: res => {
if (res.confirm) {
copyLink(url, fileName)
}
},
})
} finally {
Taro.hideLoading()
}
}
const setupTransformElement = () => {
if (!props.enableTransform) {
Taro.options.html.transformElement = previousTransformElement
return
}
Taro.options.html.transformElement = element => {
const transformed = previousTransformElement ? previousTransformElement(element) : element
const nodeName = transformed?.nodeName?.toLowerCase() || ''
const tagName = transformed?.tagName?.toLowerCase() || ''
const isImg =
nodeName === 'img' || tagName === 'img' || nodeName === 'image' || tagName === 'image'
if (!isImg) {
return transformed
}
// 统一兜底图片样式,避免后端富文本里的宽高写死后撑坏小程序布局。
if (transformed?.setAttribute) {
transformed.setAttribute('mode', 'widthFix')
transformed.setAttribute('data-rich-image', 'true')
transformed.setAttribute(
'style',
'width:100%!important;max-width:100%!important;height:auto!important;display:block;margin:24rpx 0;border-radius:16rpx;'
)
}
return transformed
}
}
const bindImageEvents = () => {
nextTick(() => {
const container = $(containerSelector)
const imgs = container.find('.h5-img')
imgs.forEach(img => {
const $img = $(img)
$img.off('longpress')
$img.on('longpress', () => {
const src = $img.attr('src')
if (!src) {
return
}
Taro.previewImage({
urls: [src],
current: src,
indicator: 'default',
loop: false,
success: () => {
emit('image-preview', { src })
},
})
})
})
})
}
const bindFileLinkEvents = () => {
nextTick(() => {
const container = $(containerSelector)
const richTextLinks = container.find('.rich-text-link')
const fileLinks = container.find('._file_list')
let allLinks = []
if (richTextLinks.length > 0) {
allLinks = allLinks.concat(richTextLinks.toArray())
}
if (fileLinks.length > 0) {
allLinks = allLinks.concat(fileLinks.toArray())
}
allLinks.forEach(el => {
const $el = $(el)
const dataHref = $el.attr('data-href') || $el.attr('href')
if (!dataHref) {
return
}
$el.off('tap')
$el.on('tap', async () => {
const fileName =
$el.find('span span span').first().text() ||
$el.text().trim().substring(0, 50) ||
getFileNameFromUrl(dataHref)
await openFileLink(dataHref, fileName)
})
})
})
}
const bindLinkLongPressEvents = () => {
nextTick(() => {
const container = $(containerSelector)
const richTextLinks = container.find('.rich-text-link')
const anchorLinks = container.find('a[href]')
const fileLinks = container.find('._file_list')
let allLinks = []
if (richTextLinks.length > 0) {
allLinks = allLinks.concat(richTextLinks.toArray())
}
if (anchorLinks.length > 0) {
allLinks = allLinks.concat(anchorLinks.toArray())
}
if (fileLinks.length > 0) {
allLinks = allLinks.concat(fileLinks.toArray())
}
allLinks.forEach(el => {
const $el = $(el)
const dataHref = $el.attr('data-href') || $el.attr('href')
if (!dataHref) {
return
}
$el.off('longpress')
$el.on('longpress', () => {
const fileName =
$el.find('span span span').first().text() ||
$el.text().trim().substring(0, 30) ||
getFileNameFromUrl(dataHref)
copyLink(dataHref, fileName)
})
})
})
}
const handleContentChange = () => {
processContent(props.content)
nextTick(() => {
// 富文本每次重渲染都会替换节点,需要重新挂载图片预览和链接交互事件。
bindImageEvents()
bindFileLinkEvents()
bindLinkLongPressEvents()
})
}
watch(() => props.content, handleContentChange, { immediate: true })
watch(() => props.enableTransform, setupTransformElement, { immediate: true })
onBeforeUnmount(() => {
Taro.options.html.transformElement = previousTransformElement
})
</script>
<style lang="less">
#rich-text-renderer,
.rich-text-renderer {
color: #4b5563;
font-size: 30rpx;
line-height: 1.8;
word-break: break-word;
.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;
margin-bottom: 12rpx;
}
.h5-head {
display: none;
}
.h5-p,
.h5-div,
.h5-blockquote,
.h5-ul,
.h5-ol {
margin: 0 0 20rpx;
}
.h5-ul,
.h5-ol {
padding-left: 36rpx;
}
.h5-img,
img {
width: 100%;
max-width: 100%;
height: auto;
display: block;
margin: 24rpx 0;
border-radius: 16rpx;
}
.rich-text-link,
.h5-a,
a,
._file_list {
color: #2563eb;
text-decoration: underline;
word-break: break-all;
}
.rich-text-link *,
._file_list * {
pointer-events: none;
}
.h5-b,
.h5-strong {
font-weight: bolder;
}
.h5-i,
.h5-em {
font-style: italic;
}
.h5-table {
display: table;
width: 100%;
border-spacing: 2px;
margin: 20rpx 0;
}
.h5-tr {
display: table-row;
}
.h5-td,
.h5-th {
display: table-cell;
padding: 12rpx;
border: 1rpx solid #d1d5db;
vertical-align: top;
}
.h5-th {
font-weight: bolder;
background: #f9fafb;
}
}
</style>