Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

taro convert 报错 SyntaxError: Expecting Unicode escape sequence #3913

Closed
ChimingPhang opened this issue Jul 22, 2019 · 1 comment
Closed

Comments

@ChimingPhang
Copy link

ChimingPhang commented Jul 22, 2019

问题描述
taro convert 报错 SyntaxError: Expecting Unicode escape sequence

复现步骤

var app = getApp(),
    util = require('../../common/util.js'),
    api = require('../../common/api.js'),
    regeneratorRuntime = require('../../common/regenerator-runtime/runtime.js');
var user = app.appData.user, //用户信息
    shareConfig = null; //分享配置信息
const MPID = 'wps_vip';
// 小程序appid
const miniapps = {
    // pdf转word
    pdf2word: 'wx13cd99d542d17123',
    // 会员日
    vipDay: 'wx863a6a6449197123',
    // 全文翻译
    translate: 'wx1b1b02ba43784123',
    // 会议群发
    groupSend: 'wxe5f87d6a233b5123',
    // 图片小程序
    ocr: 'wxe66629a225dbd123',
}
// 打卡开始时间
const START_TIME = 6
// 打卡结束时间
const END_TIME = 13

Page({
    /**
     * 页面的初始数据
     */
    data: {
        sid: util.getStorageSync('sid'), //从本地缓存拿sid
        status: '', // [参与成功, 打卡成功, 我的战绩]
        showFollowPopon: false, // 关注弹窗
        showTaskPopon: false, // 任务说明弹窗
        mask_rule: false, // 规则弹窗
        isClockIn: false, // 今日是否打卡
        clockYesterday: false,
        isSignUp: false, // 今日是否参与活动
        isSignUpYesterday: false, // 昨日是否参与活动
        actStatus: null, // 活动状态
        finishedTasks: [], // 已完成任务
        today_extra_reward: 0, // 今日额外奖励
        yesterday_extra_reward: 0, // 昨日额外奖励
        tipsTime: '',  // 今日 || 明日
        ruleContent: '', // 规则文本
        activity_type: 'WPS', // 打卡类型
        // 任务列表
        taskList: [{
                name: 'inviteFriend',
                title: '邀请好友',
                titleLabel: `今日已邀请XX位好友`,
                label: '邀请1位好友可得1天,每日最多10天',
                icon: 'images/icon-invite.png',
                btnText: '去邀请',
                finished: false,
                finishedTxt: '继续邀请'
            },
            {
                name: 'vip_day',
                title: '赚积分换好礼',
                label: '每日可领积分,可兑换会员、实物等',
                icon: 'images/icon-score.png',
                btnText: '赚积分',
                finishedTxt: '赚积分',
                action: `miniapp:${miniapps.vipDay}`
            },
            {
                name: 'pdf2word',
                title: '使用PDF转Word',
                label: '体验后多得1天',
                icon: 'images/icon-pdf2word.png',
                btnText: '去完成',
                finishedTxt: '继续使用',
                finished: false,
                hasFinishedTag: true,
                action: `miniapp:${miniapps.pdf2word}`
            },
            {
                name: 'img2text',
                title: '使用图片转文字',
                label: '体验后多得1天',
                icon: 'images/icon-ocr.png',
                btnText: '去完成',
                finishedTxt: '继续使用',
                finished: false,
                hasFinishedTag: true,
                action: {
                    type: 'miniapp',
                    target: {
                        appId: miniapps.ocr,
                        path: 'pages/img2any/img2any?fromType=img2text'
                    }
                }
            },
            {
                name: 'sent_notify',
                title: '使用微信群发通知',
                label: '体验后多得1天',
                icon: 'images/icon-wechat.png',
                btnText: '去完成',
                finished: false,
                hasFinishedTag: true,
                finishedTxt: '继续使用',
                action: `miniapp:${miniapps.groupSend}`
            },
            {
                name: 'translate',
                title: '使用全文翻译',
                label: '体验后多得1天',
                icon: 'images/icon-translate.png',
                btnText: '去完成',
                finished: false,
                finishedTxt: '继续使用',
                hasFinishedTag: true,
                action: `miniapp:${miniapps.translate}`
            },
            {
                name: 'add_watermark',
                title: '使用图片加水印',
                label: '体验后多得1天',
                icon: 'images/icon-watermark.png',
                btnText: '去完成',
                finished: false,
                finishedTxt: '继续使用',
                hasFinishedTag: true,
                action: {
                    type: 'miniapp',
                    target: {
                        appId: miniapps.ocr,
                        path: 'pages/img2any/img2any?fromType=watermark'
                    }
                }
            },

            {
                name: 'sub_wps',
                title: '关注WPS会员公众号',
                label: '体验后多得1天',
                icon: 'images/icon-wechat.png',
                btnText: '去完成',
                finishedTxt: '已完成',
                finished: false,
                hasFinishedTag: true,
                action: `self:followWechat`
            },
        ]
    },

    /**
     * 设置弹窗
     * @param event
     */
    setValue(event) {
        var dataset = event.currentTarget.dataset,
            action = dataset.action,
            collectData = dataset.co,
            coArr = [];
        if (collectData) {
            coArr = collectData.split(',');
        }
        // 收集
        coArr[0] && co.collect(coArr[0])
        try {
            this.setData(JSON.parse(action), function(e) {
                // 收集
                coArr[1] && co.collect(coArr[1])
            });
        } catch (e) {
            console.error('字符串格式错误!');
            console.error('示例: data-action=\'{"mask_rule": true}\'');
        }
    },

    /** 
     * 设置邀请人数
     */
    setInviteCount() {
        this.setTaskList('inviteFriend', 'titleLabel', `今日已邀请${app.globalData.clockInfo.invite_count}位好友`)
    },
    
    // 设置打卡提示日期 '明日|今日'
    getTipsTime() {
        const { isClockIn, isSignUp, isSignUpYesterday, clockYesterday, superInfo } = this.data
        const isInTime = this.isInTime()
        const isAfterTime = this.isAfterTime()
        const isBeforeTime = this.isBeforeTime()

        if ((isSignUpYesterday || clockYesterday) && (isBeforeTime || isInTime)) {
            return '今日'
        }

        return '明日'
    },

    /**
     * 生命周期函数--监听页面显示
     */
    async onShow(options) {
        const {
            search
        } = app.globalData;

        if (search) {
            this.setData({ ...search
            });
            switch (search.status) {
                case 'score':
                    this.collect('我的战绩页面-展示')
                    break;
                case 'sign':
                    this.collect('参与成功页面-展示')
                    break;
                case 'clock':
                    this.collect('打卡成功页面-展示')
                    break;
                default:
            }
        } else {
            this.setData({
                status: null
            });

            this.collect('任务中心-做任务界面展示(仅做任务界面)')
        }

        this.setInviteCount();
        this.hasFollowedWps();
        await this.getActInfo();
        this.getTaskList();
        // 设置打卡提示日期 '明日|今日'
        this.setData({
            tipsTime: this.getTipsTime()
        })
    },

    /**
     * 检验时间是否在打卡时间前
     */
    isBeforeTime() {
        var now = new Date().getHours();
        return now < START_TIME;
    },

    /**
     * 检验时间是否在打卡时间后
     */
    isAfterTime() {
        var now = new Date().getHours();
        return now >= END_TIME;
    },

    /**
     * 获取基本活动信息
     */
    async getActInfo() {
        await this.refreshActInfo();
        const act_info = app.globalData.clockInfo;
        const { is_sign_up_yesterday, is_clock_in_yesterday, is_sign_up } = act_info
        /** 
         * 昨天未打卡
         * 未报名
         * 昨天未报名
         * 不是报名成功状态
         * 首次展示
         */
        if (!is_sign_up_yesterday && !is_clock_in_yesterday && !is_sign_up || (this.data.status !== 'sign' && !util.getStorageSync('showTaskPopon_once'))) {
            this.setData({
                showTaskPopon: true
            })
        }
    },

    /**
     * 刷新数据
     */
    refreshActInfo() {
        var _this = this;
        return new Promise((resolve, reject) => {
            wx.request({
                url: `https://api/get_data?member=${app.globalData.member}`,
                method: 'GET',
                header: {
                    'sid': util.getStorageSync('sid'),
                },
                success: function(res) {
                    if (res.errMsg === 'request:ok') {
                        // 初始化活动数据
                        var act_info = res.data;
                        app.globalData.clockInfo = res.data;
                        this.changeData(act_info);
                        shareConfig = act_info.share_setting || false;
                    } else {
                        console.log('获取基本活动信息失败');
                        wx.showToast({
                            title: '网络繁忙,请重新进入!',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                    resolve()
                    wx.stopPullDownRefresh()
                }.bind(this),
                fail: function(res) {
                    wx.hideLoading();
                    wx.hideNavigationBarLoading() //完成停止加载
                    wx.stopPullDownRefresh() //停止下拉刷新
                    wx.showToast({
                        title: '网络繁忙,请重新进入!',
                        icon: 'none',
                        duration: 2000
                    });
                    co.collect('无法获取活动信息');
                    reject()
                }.bind(this)
            })
        })

    },

    /** 
     * 下拉刷新
     */
    onPullDownRefresh() {
        this.refreshActInfo()
    },

    /**
     * 更新活动数据,并且重新初始化
     * @param act_info 活动数据
     */
    changeData(act_info) {
        if (act_info.result === 'error') {
            wx.hideLoading();

            wx.showToast({
                title: act_info.msg,
                icon: 'none',
                duration: 3000
            })

            return
        }
        this.setData({
            showCoupon: util.getStorageSync('showCoupon'),
            ruleContent: (act_info.share_setting.rule && this.escape2Html(act_info.share_setting.rule.data.toString())) || '',
            pool_day: util.numFix(act_info.pool_day, 0),
            is_company: !!act_info.is_company,
            show_today: !!act_info.show_today,
            isClockIn: !!act_info.is_clock_in,
            clockYesterday: !!act_info.is_clock_in_yesterday,
            isSignUp: !!act_info.is_sign_up,
            today_extra_reward: act_info.today_extra_reward,
            yesterday_extra_reward: act_info.yesterday_extra_reward,
            avatarList: act_info.avatar_list || [],
            isSignUpYesterday: !!act_info.is_sign_up_yesterday,
            statistics: act_info.statistics,
            superInfo: act_info.superman,
            times: act_info.times,
            award_list: act_info.award_list,
            getAwardDay: act_info.total_add_day,
            getLastAwardDay: act_info.award_list && act_info.award_list[0] && act_info.award_list[0].add_day || 0,
            hasBindPhone: !!act_info.bind_phone,
            ranking_list: act_info.ranking_list,
            coupon_url: act_info.share_setting.window_pic && act_info.share_setting.window_pic.url || 'https://cation/views/wxapp/clock/test.png',
            clock_before: !!act_info.clock_before,
            winActivity: act_info.share_setting.window_config ? act_info.share_setting.window_config : this.data.winActivity
        }, () => {
            wx.hideLoading();
        });
    },

    /**
     * 检验时间是否在某一段时间内
     * @param start 开始时间
     * @param end 结束时间
     * @return {boolean}
     */
    isInTime(start = 6, end = 13) {
        var now = new Date().getHours();
        return now >= start && now < end;
    },



    /**
     * 判断是否已经关注了公众号
     */
    hasFollowedWps() {
        wx.request({
            url: `https://v1/mp/subscribe/${MPID}`,
            method: 'GET',
            header: {
                'sid': util.getStorageSync('sid'),
            },
            success: (res) => {
                if (res.errMsg === 'request:ok') {
                    var {
                        result
                    } = res.data;
                    if (result === 'ok') {
                        this.setTaskList('sub_wps', 'finished', true);
                    }
                }
            }
        })
    },

    /**
     * 关闭关注弹窗
     * @param {object} e
     */
    bindClosePopon(e) {
        const {
            key,
            once
        } = e.currentTarget.dataset
        if (once) {
            wx.setStorageSync(`${once}_once`, true)
        }
        this.setData({
            [key]: false
        })
    },

    /** 
     * 返回首页参与活动
     */
    gotoSign() {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },


    /**
     * 设置任务列表状态
     *
     * @param {*} name
     * @param {string} [key='finished']
     * @param {*} value
     * @param {function} cb
     */
    setTaskList(name, key = 'finished', value, cb) {
        const index = this.data.taskList.findIndex(item => item.name === name);
        const changeKey = `taskList[${index}].${key}`
        this.setData({
            [changeKey]: value
        }, function() {
            cb && cb()
        });
    },


    /**
     * 点击任务右侧按钮
     *
     * @param {*} e
     */
    tapButton(e) {
        const {
            action,
            name,
            title
        } = e.currentTarget.dataset;
        let [type, target] = [null, null];
        if (typeof action === 'string') {
            [type, target] = action.split(':');
        } else {
            type = action.type;
            target = action.target;
        }
        // 埋点
        this.collect(`任务中心-点击${title}`)
        switch (type) {
            case 'self':
                this[target]();
                break;
            case 'miniapp':
                if (typeof target === 'string') {
                    wx.navigateToMiniProgram({
                        appId: target,
                        success: () => {
                            this.finishTask(name)
                        }
                    })
                } else {
                    wx.navigateToMiniProgram({
                        success: () => {
                            this.finishTask(name)
                        },
                        ...target
                    })
                }

        }
    },

    /** 
     * 关注公众号
     */
    followWechat() {
        this.setData({
            showFollowPopon: true
        })
    },

    /** 
     * 信息收集
     */ 
    collect(event) {
        var co = null
        if (typeof event === 'string') {
            co = event
        } else {
            co = event.currentTarget.dataset.co
        }
        co && app.aldstat.sendEvent(co);
    },

    /**
     * 获取分享设置
     * @param type
     * @return {*}
     */
    getShareConfig(type) {
        var _this = this;
        var userid = this.data.user && this.data.user.userid || 0;
        var userName = this.data.user && this.data.user.nickname || '';
    
        if (shareConfig && shareConfig[type]) {
            var _title = shareConfig[type].title.replace('nickname', userName);
            return {
                title: _title,
                path: `/pages/index/index?sid=${userid}&type=${type}&member=${_this.data.member}&invite=1&userid=` + app.appData.user.userid,
                imageUrl: shareConfig[type].icon,
                success: function () {
                    _this.notify(3);
                }
            }
        } else {
            return {
                title: `[有人@我]${userName}送你一份${_this.data.activity_type}会员奖励`,
                path: `/pages/index/index?sid=${userid}&member=${_this.data.member}&invite=1&userid=` + app.appData.user.userid,
                imageUrl: 'https:///2018-06-14/091043/share1.png',
                success: function () {
                    _this.notify(3);
                }
            }
        }
    },


    /**
     * 分享
     * @param res
     * @return {{}}
     */
    onShareAppMessage(res) {
        const defaultConfig = this.getShareConfig('default')
        defaultConfig.path = 'pages/index/index?invite=1&userid=' + app.appData.user.userid
        // 右上角点击转发
        if (res.from === 'menu') {
            return defaultConfig;
        }


        const { status, getAwardDay } = this.data
        const { type } = res.target.dataset
        const activity_type = app.globalData.member === 'wps' ? 'WPS' : '稻壳'
        let imageUrl = ''

        if (getAwardDay > 0 && getAwardDay <= 25) {
            imageUrl = `https://v1_4/share/${getAwardDay}.png`
        } else {
            imageUrl = `https://v1_4/share/normal.png`
        }
        const SHARE_CONFIG = {
            invite: defaultConfig,
            show: {
                title: getAwardDay == 0 ? '在吗?给你发免费的WPS会员了,记得领啊拜托帮我点一下!我们一起领免费的WPS会员' : `我领了${getAwardDay}${activity_type}会员!快来和我一起免费领!`,
                path: 'pages/index/index?invite=1&userid=' + app.appData.user.userid,
                imageUrl
            }
        }
        const shareConfig = type ? SHARE_CONFIG[type] : SHARE_CONFIG['invite']
        return shareConfig;
    },

    /**
     * 根据接口返回已完成任务更新本地任务列表
     */
    mapTaskList(arr) {
        const newList = this.data.taskList.map((item) => {
            if (arr.includes(item.name)) {
                item.finished = true
            }
            return item
        })
        return newList
    },

    /**
     * 获取已完成任务列表
     */
    async getTaskList() {
        const {
            data
        } = await api.getMissions()
        this.setData({
            finishedTasks: data,
            taskList: this.mapTaskList(data)
        })
    },

    /**
     * 完成任务
     * @param name 任务字段
     */
    async finishTask(name = 'pdf2word') {
        // 已完成任务
        if (this.data.finishedTasks.includes(name)) {
            return
        }
        const res = await api.finishedMission(name)
        this.setTaskList(name, 'finished', true, () => {
            this.refreshActInfo()
        })
    },

    /** 
     * 页面隐藏时
    */
    onHide() {
        /** 
         * 分享弹窗会出发onHide, onHide当前页面
         * 如不在当前页面了就把顶部任务状态清空
         * */
        setTimeout(() => {
            const page = getCurrentPages().pop()
            page.route !== 'pages/task/task' && (app.globalData.search = null)
        }, 0)

    },

    /** 
     * 页面离开时
    */
    onUnload() {
        app.globalData.search = null;
    },

    /** 
     * 富文本转义
    */
    escape2Html(str) {
        var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
        return str.replace(/{{activity_type}}/g, this.data.activity_type).replace(/view/g, 'div').replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; });
    },

    /** 
     * 返回首页
    */
    handleBackHome() {
        wx.switchTab({
            url: '/pages/index/index',
        })
    }
})

```html

<view class="activity-container">

    <!-- status -->
    <w-status bg-color="#fff" />

    <!-- title -->
    <w-title showBack="{{true}}" bindback="handleBackHome">
        <view class="page-title activity-title">任务中心</view>
    </w-title>

    <!-- 顶部状态-start -->
    <include src="status.wxml" wx:if="{{status}}" />
    <!-- 顶部状态-end -->

    <!-- 任务列表-start -->
    <include src="tasklist.wxml" />
    <!-- 任务列表-end -->

    <!-- 活动规则按钮-start -->
    <view class="btn-show-rule" bindtap="setValue" data-action='{"mask_rule": true}'>
        <text>活动规则</text>
    </view>
    <!-- 活动规则按钮-end -->

    <!-- 关注公众号弹窗-start -->
    <w-popon class="follow-popon" visible="{{showFollowPopon}}" data-key="showFollowPopon" bindclose="bindClosePopon">
        <view>
            <image src="images/img-follow.gif" style="width:301rpx;height:500rpx;"></image>
            <button class="popon-button" style="margin-top:30rpx;" open-type="contact" send-message-title="点击下方消息关注公众号" show-message-card="{{true}}" send-message-img="https://dl.op.wpscdn.cn/odimg/web/2019-06-28/085749/follow-share.png">去关注</button>
            <view style="color:#666666;font-size:25rpx;margin-top:30rpx;">点击按钮后,请如上图操作马上关注</view>
        </view>
    </w-popon>
    <!-- 关注公众号弹窗-end -->

    <!-- 做任务提示-start -->
    <w-popon class="task-popon" lock="{{ true }}" title="做任务领更多会员" showClose="{{false}}" visible="{{showTaskPopon}}" data-key="showTaskPopon" bindclose="bindClosePopon">
        <view>
            <view style='text-align:left;font-size:29rpx;color:#666;line-height:42rpx;'>
                <view>1.参与打卡活动</view>
                <view>2.完成任务</view>
                <view>3.次日打卡获取奖励天数</view>
            </view>
            <button wx:if="{{isSignUp || isSignUpYesterday || clockYesterday}}" class="popon-button" style="margin-top:30rpx;" data-once="showTaskPopon" data-key="showTaskPopon" bindtap='bindClosePopon'>我知道了</button>
            <button wx:else class="popon-button" style="margin-top:30rpx;" bindtap='gotoSign'>立即参与</button>
        </view>
    </w-popon>
    <!-- 做任务提示-start -->

    <!-- 活动规则弹窗-start -->
    <include  src="mask_rule.wxml" />
    <!-- 活动规则弹窗-end -->
</view>

期望行为
期望转换成功

报错信息
image

系统信息

  • 操作系统: mac os
  • Taro 版本 v1.3.10
  • Node.js 版本 v10.14.0
  • 报错平台 weapp(原生转taro)

补充信息
会不会是中文字符?

@taro-bot
Copy link

taro-bot bot commented Jul 22, 2019

欢迎提交 Issue~

如果你提交的是 bug 报告,请务必遵循 Issue 模板的规范,尽量用简洁的语言描述你的问题,最好能提供一个稳定简单的复现。🙏🙏🙏

如果你的信息提供过于模糊或不足,或者已经其他 issue 已经存在相关内容,你的 issue 有可能会被关闭。

Good luck and happy coding~

@yuche yuche added the taroize label Jul 22, 2019
@yuche yuche closed this as completed in a1913f5 Jul 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants