RichText.js 27.6 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 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
/**
 * @ # 文本加载 显示全文特性加载
 */
import React, {Component} from "react";
import {Text, View, TouchableOpacity, Image,NativeModules,Clipboard} from "react-native";
import Cheerio from "cheerio-without-node-native";
import {NoDoublePress,xnToast} from "../utils/utils";
import _ from "lodash";
import {scaleHeight, setSpText} from "../utils/ScreenUtil";
import Toast from "react-native-root-toast";

const defaultImg = require("../img/photo_blue.png");

export default class RichText extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            linesArr:[],
            currentLength:0,
            kMaxLength:200,
            isOver:false,
        };
        this.currentLength = 0;
        // 卡控200位,如果有换行,作为一整行处理
        //this.kMaxLength = 200;
        this.kMaxLength = 200;
        // 单行字数
        this.kMaxLineLength = 67;
        // 行数数组
        this.linesArr = [];
        // 是否已经达到最大字数,处理完成
        this.isOver = false;
        // ...颜色
        this.kDotColor = "rgba(0,0,0,0.85)";
        // "全文"颜色
        this.kZenbuColor = "#406599";
        // 字号
        this.kFontSize = setSpText(17);
        // 最终显示的文字,用于在不超长的情况下复制
        this.textString = "";
    }

    //跳到个人中心页面
    toPersonal(idStr) {
        NoDoublePress.onPress(() => {
            //先去掉空格再替换掉id
            let id = idStr.replace(/\s/gi, "").replace("id=", "");
            // console.log("---------", id);
            if (id == global.userId) {
                //自己
                this.props.nav.navigate("MyPage", {id: id});
                return;
            }
            this.props.nav.navigate("PersonalHomePage", {userId: id});
        })
    }

    toImg(idStr){
        if(!!!idStr || idStr == ''){
            xnToast("图片链接失效");
            return;
        }
        NoDoublePress.onPress(()=>{
            //先去掉空格再替换掉id
            let url = idStr.replace(/\s/gi, "").replace("url=", "");
            NativeModules.system.showPhotoWithUrl(url)
        })
    }

    //跳到话题页面
    toTopicPage(idStr) {
        NoDoublePress.onPress(() => {
            //先去掉空格再替换掉id
            let id = idStr.replace(/\s/gi, "").replace("id=", "");
            this.props.nav.navigate("TopicBoard", {id: id});
        })
    }

    //跳到Web页面
    toWebPage(href) {
        NoDoublePress.onPress(() => {
            this.props.nav.navigate("WebController", {url: href.replace(/\s/gi, "")});
        })
    }

    renderColumnText() {
        this.textString = '';
        // 结果集合
        let data = this.props.item;
        if (data == undefined){
            return;
        }
        //let data = '↵funew↵呵呵哒↵funew↵哈哈↵funew↵第一行↵newline↵第二行↵newline↵第三行↵newline↵第四行';
        // 去除开头的<div> 结尾的</div>
        data = data.replace("<div>", "");
        data = data.replace("</div>", "");
        // 以下是一些防呆处理,RN端去除后台设置的特殊区切符号重新设置(小程序和RN解析富文本不一致)
        // 去除"↵funew↵"与后面的"<"之间有个空格的情况
        data = data.replace(new RegExp('↵funew↵ <','gm'),'↵funew↵<');
        data = data.replace(new RegExp('↵funew↵','gm'),'');
        data = data.replace(new RegExp('<a','gm'),'↵funew↵<a');
        // 按照"↵funew↵"分割,需要保证<a>标签在数组元素中位于第一位
        let temp = data.split("↵funew↵");
        // linesArr里存放的是根据硬回车分割的行数记录
        //let linesArr = [];
        // rowArr里存放的是每一行的记录
        let rowArr = [];
        // 遍历将回车内容分割开,这块内容还在完善中,不要放开,by qianjun
        let rowIndex = -1;
        temp.map((item, index) => {
            // 换行符替换为特殊字符用于区分
            item=item.replace(/\n/g,"↵newline↵");
            // 根据上一步替换的特殊字符来创建数组
            let tempItems = item.split("↵newline↵");
            tempItems.map((itemA, index) => {
                // 没有硬回车,继续往当前行里添加内容
                if(tempItems.length == 1){
                    rowArr.push(itemA);
                }else{
                    rowIndex  = rowIndex +1;
                    rowArr.push(itemA);
                    this.linesArr[rowIndex] = [];
                    this.linesArr[rowIndex] = rowArr;
                    rowArr = [];
                }
            });
        });
        if(rowIndex == -1){
            this.linesArr[0] = rowArr;
        }
        //console.log('linesArr = '+ linesArr);
        this.currentLength = 0;
        return this.linesArr;
    }

    render() {
        return (<View style={{
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'flex-start',
            alignItems: 'flex-start',
            flexWrap: 'wrap',
        }}>
            {
                this.renderColumnText() !=undefined &&  this.renderColumnText().map((item,index)=>{
                    return(
                        <View style={{
                            display: 'flex',
                            flexDirection: 'row',
                            justifyContent: 'flex-start',
                            alignItems: 'flex-start',
                            flexWrap: 'wrap',
                        }}>
                            {this.renderRowText(item,index)}
                        </View>
                    );
                })
            }
            {
                this.state.isOver?(<Text>
                    <Text style={{
                    color: this.kZenbuColor,
                    fontSize: this.kFontSize,
                    //height: kLineHeight
                }}>...</Text><Text style={{
                    color: this.kZenbuColor,
                    fontSize: this.kFontSize,
                    //height: kLineHeight
                }}>查看全文</Text></Text>):null
            }
        </View>);
    }

    renderRowText(rowItem,index){
        // console.log('rowItem = '+ rowItem);
        /* 以10个字符作为最大长度的限制(测试),如果超过了10个字符,显示"...全文",裁剪是先取加下一个内容的长度再判断的,可能会比手动计算
           的短一点,可以判断下一个内容是不是纯文本,如果是纯文本还是可以截字的,但@#【图片】是不能截取的必须全部显示
         */
        // 内容计算
        let kMaxLength = this.kMaxLength;
        // 是否需要行数控制 true 清除行数控制 ,false :不清除行数控制
        let kClearNumberOfLine = this.props.clearNumberOfLine;
        let content = this.currentLength;
        // 输出的控件数组
        let textArr = [];
        // 字号
        let kFontSize = setSpText(17);
        // 已读颜色
        let kReadColor = "#999";
        // 未读颜色
        let kUnReadColor = "rgba(0,0,0,0.85)";
        // "查看原图"颜色
        let kImgColor = "#406599";
        // @和#颜色
        let kAtAndTopicColor = "#406599";
        // 行高
        let kLineHeight = scaleHeight(24);
        // 是否已读
        let kHasBeenRead = !!!this.props.hasBeenRead ? false : this.props.hasBeenRead;
        //data = "↵funew↵&lt;a class=&quot;#&quot; href= &quot;id = 1066929428594036736&quot; title = &quot;#今天吃什么#&quot;/&gt;↵funew↵泉屋↵funew↵&lt;a class=&quot;#&quot; href= &quot;id = 1066929428594036736&quot; title = &quot;#今天吃什么#&quot;/&gt;↵funew↵"
        // let isOver = false;
        // 富文本区切数组
        let spliteArr = [];
        // 分割字符串
        spliteArr = Array.from(rowItem);
        // 当存在回车换行的时候,如果一行计算的字数< 最大字数/最多行数,将统计数字撑满
        if (this.linesArr.length > 0 && index > 0) {
            if (this.currentLength < this.kMaxLineLength * (index) && this.currentLength < this.kMaxLength) {
                this.currentLength = this.kMaxLineLength * (index);
                console.log("有回车,撑满一行:" + this.currentLength);
            }
        }
        // 数组处理
        spliteArr.map((item, index) => {
            //content += item;
            // 如果想要替换所有指定的字符串,可以用while循环
            while (item.indexOf('&nbsp;') >= 0) {
                item = item.replace('&nbsp;', ' ');
            }
            if (content >= kMaxLength && (!!!kClearNumberOfLine || !kClearNumberOfLine)) {
                console.log("达到最大长度,不再处理22222");
                this.isOver = true;
                if (!this.state.isOver) {
                    this.setState({
                        isOver: true,
                    });
                }
                return;
            } else {
                // 过滤掉空值<统一不过滤,换行后的空行需要显示>
                // if(item.trim().length != 0){
                if (1 == 1) {
                    // 判定是不是标签
                    if (item.indexOf("<") != -1) {
                        // 标签
                        // 套入<div>中
                        item = "<div>" + item;
                        item = item + "</div>";
                        // 解析
                        let $ = Cheerio.load(item);
                        let markArr = $("div").find("a");
                        markArr.each((index, item) => {
                            //content += item;
                            let aTag = $(item);
                            // 区分图片还是话题艾特用户
                            if (aTag.attr("class") == "img") {
                                // 查看原图+图片小图标当做5个字符来处理
                                content += 5;
                                if (content > kMaxLength && (!!!kClearNumberOfLine || !kClearNumberOfLine)) {
                                    if (!this.isOver) {
                                        // textArr.push(<Text>
                                        //     <Text style={{
                                        //         color: kDotColor,
                                        //         fontSize: kFontSize,
                                        //         //height: kLineHeight
                                        //     }}>...</Text>
                                        //     <Text style={{
                                        //         color: kZenbuColor,
                                        //         fontSize: kFontSize,
                                        //         //height: kLineHeight
                                        //     }}>全文</Text>
                                        // </Text>);
                                    }
                                    this.isOver = true;
                                    if (!this.state.isOver) {
                                        this.setState({
                                            isOver: true,
                                        });
                                    }
                                    return;
                                } else {
                                    textArr.push(<TouchableOpacity style={{
                                        flexDirection: 'row',
                                        alignItems: 'center',
                                        justifyContent: 'center'
                                    }} onPress={() => {
                                        this.toImg(aTag.attr("href"));
                                    }}>
                                        <View style={{
                                            width: 2,
                                            //height: kLineHeight
                                        }}/>
                                        <Image source={defaultImg} style={{
                                            width: 18,
                                            //height: kLineHeight-2,
                                        }} resizeMode='contain'/>
                                        <Text style={{
                                            color: kImgColor,
                                            fontSize: kFontSize,
                                            // backgroundColor: 'green',
                                            //height: kLineHeight
                                        }}  onLongPress={() => {
                                            this.copy();
                                        }} suppressHighlighting={true}>查看原图
                                        </Text>
                                    </TouchableOpacity>);
                                    // 拼接到文本字符串中
                                    this.textString = this.textString + '【查看原图('+aTag.attr("href")+')】';
                                }
                            } else {
                                let showContent = null;
                                let markAText = $("a").text();
                                if (!_.isEmpty(markAText)) {
                                    showContent = $("a").text();
                                }else if(!!aTag.attr("title") && !_.isEmpty(aTag.attr("title"))){
                                    // 尝试取title
                                        showContent = aTag.attr("title");
                                }else if(!!aTag.attr("href") && !_.isEmpty(aTag.attr("href"))){
                                    // a标签既没有内容也没有title的情况下,取href内容
                                    showContent = aTag.attr("herf");
                                }else{
                                    // 这种情况下,无法显示,最终跳过
                                    showContent = null;
                                }
                                if(!_.isEmpty(showContent)){
                                    content += showContent.length;
                                    if (content > kMaxLength && (!!!kClearNumberOfLine || !kClearNumberOfLine)) {
                                        if (!this.isOver) {
                                            // textArr.push(<Text>
                                            //     <Text style={{
                                            //         color: kDotColor,
                                            //         fontSize: kFontSize,
                                            //         //height: kLineHeight
                                            //     }}>...</Text>
                                            //     <Text style={{
                                            //         color: kZenbuColor,
                                            //         fontSize: kFontSize,
                                            //         //height: kLineHeight
                                            //     }}>全文</Text>
                                            // </Text>);
                                        }
                                        this.isOver = true;
                                        if (!this.state.isOver) {
                                            this.setState({
                                                isOver: true,
                                            });
                                        }
                                        return;
                                    } else {
                                        textArr.push(<Text style={{
                                            color: kAtAndTopicColor,
                                            fontSize: kFontSize,
                                            // backgroundColor: 'green',
                                            //height: kLineHeight
                                        }} onPress={() => {
                                            if (aTag.attr("class") == "@") {
                                                this.toPersonal(aTag.attr("href"));
                                                return;
                                            }else if(aTag.attr("class") == "#"){
                                                this.toTopicPage(aTag.attr("href"));
                                            }else{
                                                // 显示网页
                                                this.toWebPage(aTag.attr("href"));
                                            }
                                        }}  onLongPress={() => {
                                            this.copy();
                                        }} suppressHighlighting={true}>
                                            {showContent}
                                        </Text>);
                                        // 拼接到文本字符串中
                                        this.textString = this.textString + showContent;
                                    }
                                }
                            }
                        });
                        /* 这段逻辑是为了处理之前因为标签的结尾">"后面没有跟上区切字符,导致的可能出现">"还有纯文本的情况,现在已经添
                           加了结束标签的区切字符,这里保留以兼容以前的老数据
                        */
                        // 过滤掉a标签与标签之间的内容,Cheerio的text方法会包含child元素的text一起输出
                        let removedAItem = item.replace(/\<a.*?>(.*?)<\/a>/g,"");
                        let $1 = Cheerio.load(removedAItem);
                        let markAText = $1("div").text();

                            if (!_.isEmpty(markAText)) {
                                // 文本
                                var tempContent = content;
                                content += markAText.length;
                                // 超长判断
                                if (content > kMaxLength && (!!!kClearNumberOfLine || !kClearNumberOfLine)) {
                                    // 超长
                                    if (!this.isOver) {
                                        // 文本可以尝试截位
                                        if (tempContent < kMaxLength) {
                                            markAText = markAText.toString().substring(0, kMaxLength - tempContent);
                                            textArr.push(<Text style={kHasBeenRead
                                                ? {
                                                    color: kReadColor,
                                                    fontSize: kFontSize,
                                                    //height: kLineHeight
                                                    // backgroundColor: 'green',
                                                }
                                                : {
                                                    color: kUnReadColor,
                                                    fontSize: kFontSize,
                                                    //height: kLineHeight
                                                    // backgroundColor: 'green',
                                                }
                                            }>
                                                {markAText}
                                            </Text>);
                                        }
                                        // textArr.push(<Text>
                                        //     <Text style={{
                                        //         color: kDotColor,
                                        //         fontSize: kFontSize,
                                        //         //height: kLineHeight
                                        //     }}>...</Text>
                                        //     <Text style={{
                                        //         color: kZenbuColor,
                                        //         fontSize: kFontSize,
                                        //         //height: kLineHeight
                                        //     }}>全文</Text>
                                        // </Text>);
                                    }
                                    this.isOver = true;
                                    if (!this.state.isOver) {
                                        this.setState({
                                            isOver: true,
                                        });
                                    }
                                    return;
                                } else {
                                    // 正常显示
                                    textArr.push(<Text style={kHasBeenRead
                                        ? {
                                            color: kReadColor,
                                            fontSize: kFontSize,
                                            //height: kLineHeight
                                            // backgroundColor: 'green',
                                        }
                                        : {
                                            color: kUnReadColor,
                                            fontSize: kFontSize,
                                            //height: kLineHeight
                                            // backgroundColor: 'green',
                                        }
                                    }  onLongPress={() => {
                                        this.copy();
                                    }} suppressHighlighting={true}>
                                        {markAText}
                                    </Text>);
                                    // 拼接到文本字符串中
                                    this.textString = this.textString + markAText;
                                }
                            }
                        // }
                    } else {
                        // 纯文本
                        var tempContent = content;
                        content += item.length;
                        // 超长判断
                        if (content > kMaxLength && (!!!kClearNumberOfLine || !kClearNumberOfLine)) {
                            // 超长
                            //if(!this.isOver){
                            if (1 == 1) {
                                // 文本可以尝试截位
                                if (tempContent < kMaxLength) {
                                    item = item.toString().substring(0, kMaxLength - tempContent);
                                    textArr.push(<Text style={kHasBeenRead
                                        ? {
                                            color: kReadColor,
                                            fontSize: kFontSize,
                                            // backgroundColor: 'green',
                                            //height: kLineHeight
                                        }
                                        : {
                                            color: kUnReadColor,
                                            fontSize: kFontSize,
                                            // backgroundColor: 'green',
                                            //height: kLineHeight
                                        }
                                    }>
                                        {item}
                                    </Text>);
                                }
                                // textArr.push(<Text>
                                //     <Text style={{
                                //         color: kDotColor,
                                //         fontSize: kFontSize,
                                //         //height: kLineHeight
                                //     }}>...</Text>
                                //     <Text style={{
                                //         color: kZenbuColor,
                                //         fontSize: kFontSize,
                                //         //height: kLineHeight
                                //     }}>全文</Text>
                                // </Text>);
                            }
                            this.isOver = true;
                            if (!this.state.isOver) {
                                this.setState({
                                    isOver: true,
                                });
                            }
                            return;
                        } else {
                            // 正常显示
                            textArr.push(<Text style={kHasBeenRead
                                ? {
                                    color: kReadColor,
                                    fontSize: kFontSize,
                                    //height: kLineHeight
                                    //backgroundColor: 'yellow',
                                }
                                : {
                                    color: kUnReadColor,
                                    fontSize: kFontSize,
                                    //height: kLineHeight
                                    // backgroundColor: 'yellow',
                                }
                            } onLongPress={() => {
                                this.copy();
                            }} suppressHighlighting={true}>
                                {item}
                            </Text>);
                            // 拼接到文本字符串中
                            this.textString = this.textString + item;
                        }
                    }
                }
            }
        });
        // console.log(textArr);
        this.currentLength += content;
        return textArr;
    }
    // 以下四个是用来进行代码重构的方法
    // 处理文本
    _dealWithText(item,currentLength){

    }
    // 处理<a>标签
    _dealWithATag(item){

    }
    // 创建一个用于显示纯文本的Text组件
    _createTextObjectForString(item){

    }
    // 创建一个用于显示<a>标签内容(@,#,[图片])的Text组件
    _createTextObjectForTag(item){

    }

    // 创建一个用于显示"...全文"的Text组件
    _createTextObjectForZenbu(item){

    }

            // 实现复制功能
    async copy(){
        if (this.state.isOver){
            console.log('内容显示不全,不复制');
            // xnToast('内容显示不全,不复制');
            return;
        }
        let kClearNumberOfLine = this.props.clearNumberOfLine;
        let content = this.textString;
        if (content == undefined || content.length == 0){
            console.log('没有取得可以复制的内容');
            // xnToast('没有取得可以复制的内容');
            return;
        }
        try {
            // 验证以下剪贴板内容是否与先前拷贝的一致以确定是否复制成功
            Clipboard.setString(content);
            let  str = await Clipboard.getString();
            if(str == content){
                xnToast('内容已复制到剪贴板');
            }else{
                console.log('复制失败');
                // xnToast('复制失败');
            }
        }catch (e) {
            console.log('复制失败,捕捉到了异常');
            // xnToast('复制失败,捕捉到了异常');
        }
    }
}