Commit 10a3ba96 authored by mqf_0707's avatar mqf_0707

分包加载优化

parent 10bc6224
No preview for this file type
```
taobao-mini-template
├─ .git
│ ├─ HEAD
│ ├─ config
│ ├─ description
│ ├─ hooks
│ │ ├─ applypatch-msg.sample
│ │ ├─ commit-msg.sample
│ │ ├─ fsmonitor-watchman.sample
│ │ ├─ post-update.sample
│ │ ├─ pre-applypatch.sample
│ │ ├─ pre-commit.sample
│ │ ├─ pre-merge-commit.sample
│ │ ├─ pre-push.sample
│ │ ├─ pre-rebase.sample
│ │ ├─ pre-receive.sample
│ │ ├─ prepare-commit-msg.sample
│ │ └─ update.sample
│ ├─ index
│ ├─ info
│ │ └─ exclude
│ ├─ logs
│ │ ├─ HEAD
│ │ └─ refs
│ │ ├─ heads
│ │ │ ├─ c_client_taro
│ │ │ └─ c_client_taro-pack
│ │ └─ remotes
│ │ └─ origin
│ │ └─ HEAD
│ ├─ objects
│ │ ├─ 2f
│ │ │ └─ 487f1f6678c0c8bdff4a4ca7e6891b282eda72
│ │ ├─ 69
│ │ │ └─ 2acc5b9d5055c47f8001b5e83553250e9cc0e7
│ │ ├─ 7a
│ │ │ └─ 1b61452a5b4e4d862338bb0519f2bfe0cf87b5
│ │ ├─ dd
│ │ │ └─ 3c8846e63fc1b968d5bca773e602109867e68f
│ │ ├─ e7
│ │ │ └─ f2857af41856483bb0663296756783671ebfaa
│ │ ├─ f0
│ │ │ └─ bc0499211ef47d6fe7687fd7108696e0446b67
│ │ ├─ info
│ │ └─ pack
│ │ ├─ pack-dcbf00005b3c8d9f7cd0a2991c1c6ff5e61496b9.idx
│ │ └─ pack-dcbf00005b3c8d9f7cd0a2991c1c6ff5e61496b9.pack
│ ├─ packed-refs
│ └─ refs
│ ├─ heads
│ │ ├─ c_client_taro
│ │ └─ c_client_taro-pack
│ ├─ remotes
│ │ └─ origin
│ │ └─ HEAD
│ └─ tags
├─ .gitignore
├─ ask.js
└─ c_client
├─ .editorconfig
├─ .eslintrc.js
├─ .gitignore
├─ babel.config.js
├─ config
│ ├─ default.js
│ ├─ dev.js
│ ├─ index.js
│ └─ prod.js
├─ jsconfig.json
├─ minigame
│ ├─ package-lock.json
│ ├─ package.json
│ └─ yarn.lock
├─ package-lock.json
├─ package.json
├─ plugin
│ ├─ changeAppJsonPlugin.js
│ └─ changeCompRoot.js
├─ project.config.json
├─ src
│ ├─ api.js
│ ├─ app.config.js
│ ├─ app.js
│ ├─ app.less
│ ├─ components
│ │ ├─ _base
│ │ │ ├─ Modal
│ │ │ │ ├─ Modal.config.js
│ │ │ │ ├─ Modal.jsx
│ │ │ │ └─ Modal.module.less
│ │ │ ├─ Overlay
│ │ │ │ ├─ OverLay.module.less
│ │ │ │ └─ Overlay.jsx
│ │ │ └─ Popup
│ │ │ ├─ Popup.jsx
│ │ │ └─ Popup.module.less
│ │ ├─ _miniprogram
│ │ │ ├─ game
│ │ │ │ ├─ game.acss
│ │ │ │ ├─ game.axml
│ │ │ │ ├─ game.js
│ │ │ │ ├─ game.json
│ │ │ │ ├─ output.js
│ │ │ │ └─ utils.js
│ │ │ ├─ lottieAnimation
│ │ │ │ ├─ lottieAnimation.acss
│ │ │ │ ├─ lottieAnimation.axml
│ │ │ │ ├─ lottieAnimation.js
│ │ │ │ └─ lottieAnimation.json
│ │ │ ├─ lottieBlank
│ │ │ │ ├─ lottieBlank.acss
│ │ │ │ ├─ lottieBlank.axml
│ │ │ │ ├─ lottieBlank.js
│ │ │ │ └─ lottieBlank.json
│ │ │ └─ memberModal
│ │ │ ├─ memberModal.acss
│ │ │ ├─ memberModal.axml
│ │ │ ├─ memberModal.js
│ │ │ └─ memberModal.json
│ │ ├─ _tb_comps
│ │ │ ├─ CountDown
│ │ │ │ ├─ CountDown.jsx
│ │ │ │ └─ CountDown.less
│ │ │ └─ Input
│ │ ├─ _tb_custom
│ │ └─ _tb_modal
│ │ ├─ DeliveryModal
│ │ │ ├─ DeliveryModal.jsx
│ │ │ └─ DeliveryModal.less
│ │ ├─ DoHelpModal
│ │ │ ├─ DoHelpModal.jsx
│ │ │ └─ DoHelpModal.module.less
│ │ ├─ GoodsPage
│ │ │ ├─ GoodsPage.jsx
│ │ │ └─ GoodsPage.less
│ │ ├─ RuleModal
│ │ │ ├─ RuleModal.jsx
│ │ │ └─ RuleModal.module.less
│ │ └─ TasksModal
│ │ ├─ TasksModal.config.js
│ │ ├─ TasksModal.jsx
│ │ └─ TasksModal.less
│ ├─ config.js
│ ├─ const.js
│ ├─ hooks
│ │ ├─ useAuth.js
│ │ ├─ useDebounce.js
│ │ ├─ useLogin.js
│ │ ├─ useRequest.js
│ │ ├─ useTasks.js
│ │ └─ useThrottle.js
│ ├─ index.html
│ ├─ lottie
│ │ ├─ index.js
│ │ └─ lottieData.json
│ ├─ pages
│ │ ├─ index
│ │ │ ├─ index.config.js
│ │ │ ├─ index.jsx
│ │ │ └─ index.module.less
│ │ ├─ packageGame
│ │ │ └─ game
│ │ │ ├─ game.config.js
│ │ │ ├─ game.jsx
│ │ │ └─ game.module.less
│ │ ├─ packageGood
│ │ │ ├─ browseGoods
│ │ │ │ ├─ browseGoods.config.js
│ │ │ │ ├─ browseGoods.jsx
│ │ │ │ └─ browseGoods.less
│ │ │ ├─ collectGoods
│ │ │ │ ├─ collectGoods.config.js
│ │ │ │ └─ collectGoods.jsx
│ │ │ └─ orderGoods
│ │ │ ├─ orderGoods.config.js
│ │ │ └─ orderGoods.jsx
│ │ └─ packagePrize
│ │ └─ myPrize
│ │ ├─ myPrize.config.js
│ │ ├─ myPrize.jsx
│ │ └─ myPrize.less
│ ├─ store
│ │ ├─ activityInfo.js
│ │ ├─ index.js
│ │ └─ loginInfo.js
│ ├─ styles
│ │ ├─ animate.less
│ │ ├─ border.less
│ │ ├─ flex.less
│ │ ├─ form.less
│ │ ├─ gap.less
│ │ ├─ image.less
│ │ ├─ index.less
│ │ ├─ layout.less
│ │ ├─ others.less
│ │ ├─ position.less
│ │ ├─ text.less
│ │ ├─ utils.less
│ │ └─ var.less
│ ├─ taro-ui.scss
│ └─ utils
│ ├─ date.js
│ ├─ mdProxy.js
│ └─ util.js
└─ yarn.lock
```
\ No newline at end of file
1.安装依赖
```
npm install
```
2.运行项目(淘宝环境)
```
npm run dev:alipay
```
3.使用淘宝IDE打开dist文件夹关联相应小程序
4.生产环境打包
```
npm run build:alipay
```
5.使用IDE上传版本
export default {
hasGameModule:false, // 是否开启游戏模块自动注入dist
hasLottieAnimation: false,// 使用Lottie动画
hasCanvas: false, // 是否开启游戏模块自动注入dist
defaultPlugins: [
[
'@pluve/taro-plugin-mars', // taro暂时未支持阿里小程序自定义插件 需要引用插件的页面需配置
{
usingComponents: {// 原生组件引入
enable: true,
include: [ 'pages/index/index', 'pages/myPrize/myPrize' ]
enable: true,
include: [ 'pages/index/index', 'pages/packagePrize/myPrize/myPrize','pages/packageGame/game/game']
}
}
]
],
addPages: ['pages/games/games'],// 游戏页面(自动注入app.json)'pages/games/games'
gamePages: [// 拷贝相关页面和依赖到dist目录
{ from: 'src/pages/games', to: 'dist/pages/games' },
{ from: 'minigame/node_modules', to: 'dist/node_modules'},
{ from: 'src/components/_miniprogram/taskModal', to: 'dist/components/taskModal'},
// { from: 'src/lottie', to: 'dist/lottie'},
// { from: 'src/components/_miniprogram/lottieAnimation', to: 'dist/components/lottieAnimation'}
],
lottiePages: [
canvasPages: [
// {'root': 'pages/index/index.json', 'comRoot': 'components/_miniprogram/game/game'},
{'root': 'pages/packageGame/game/game.json', 'comRoot': 'components/_miniprogram/game/game'}
],// 引入cavas组件页面(更改canvas引用路径)
canvasComps: [// 拷贝相关页面和依赖到dist目录
{ from: 'minigame/node_modules', to: 'dist/node_modules'},
{ from: 'src/lottie', to: 'dist/lottie'},
{ from: 'src/components/_miniprogram/lottieAnimation', to: 'dist/components/lottieAnimation'}
{ from: 'src/components/_miniprogram/game', to: 'dist/components/_miniprogram/game'},
{ from: 'src/components/_miniprogram/lottieAnimation', to: 'dist/components/_miniprogram/lottieAnimation'}
]
}
\ No newline at end of file
// eslint-disable-next-line import/no-commonjs
const path = require('path')
const { hasGameModule, defaultPlugins, addPages, gamePages, hasLottieAnimation, lottiePages } = require('./default').default
const { hasCanvas, defaultPlugins, canvasComps } = require('./default').default
const config = {
projectName: 'taro-test',
......@@ -16,22 +16,22 @@ const config = {
alias: {
'@': path.resolve(__dirname, '..', 'src/')
},
plugins: hasGameModule || hasLottieAnimation ? [...defaultPlugins,[ // 是否开启原生页面自动注入
path.resolve(__dirname,'..')+'/plugin/changeAppJsonPlugin.js',
{
hasGameModule,
hasLottieAnimation
}
]] : defaultPlugins,
plugins: hasCanvas ? [...defaultPlugins,[ // 是否开启原生页面自动注入
path.resolve(__dirname,'..')+'/plugin/changeAppJsonPlugin.js'
]
] : defaultPlugins,
defineConstants: {
},
copy: {
patterns: hasGameModule ? gamePages : hasLottieAnimation ? lottiePages : [],
patterns: hasCanvas ? canvasComps : [],
options: {
}
},
framework: 'react',
mini: {
compile: {
exclude: []
},
postcss: {
pxtransform: {
enable: true,
......
......@@ -4,7 +4,7 @@
"requires": true,
"dependencies": {
"fyge": {
"version": "2.0.23",
"version": "2.0.31",
"resolved": "https://registry.npmjs.org/fyge/-/fyge-2.0.23.tgz",
"integrity": "sha512-5EA6FHrwpp9sAMyctuyE+gyUH10uGT5PPp1O1gZfohJNx1/bkCPcUomnXApa8367tJ5UiPhiVi3dZeqUdJiZVQ=="
}
......
......@@ -4,6 +4,6 @@
"main": "",
"license": "MIT",
"dependencies": {
"fyge": "*"
"fyge": "2.0.31"
}
}
......@@ -2,20 +2,7 @@
# yarn lockfile v1
duiba-utils@^1.0.0:
version "1.0.9"
resolved "http://npm.dui88.com:80/duiba-utils/-/duiba-utils-1.0.9.tgz#7a1e09e08a8754a1563b18aa6b117cb270f76877"
integrity sha512-3YB5w05gNruS4yyN0cx2Qktr0vG0AXYOumfV6WYlzlMx3kGX3AihBLT2/PouERtkLfFk2q4cIikSkgwramHTmg==
fyge@*:
version "2.0.23"
resolved "http://npm.dui88.com:80/fyge/-/fyge-2.0.23.tgz#36550f93d9578cd3b02ae9772f93aa94730abd25"
integrity sha512-nNUD5HAPyknIMKdxxa50HzriLuBFmk4XLnZw5CgiX3mH7ROJzsh/ToRMTKXcxwH3r3ICid95cgEo0iCPIHSIsQ==
dependencies:
duiba-utils "^1.0.0"
tslib "^2.1.0"
tslib@^2.1.0:
version "2.2.0"
resolved "http://npm.dui88.com:80/tslib/-/tslib-2.2.0.tgz#fb2c475977e35e241311ede2693cee1ec6698f5c"
integrity sha1-+yxHWXfjXiQTEe3iaTzuHsZpj1w=
fyge@2.0.31:
version "2.0.31"
resolved "https://registry.yarnpkg.com/fyge/-/fyge-2.0.31.tgz#49afcdfef92e23b53e42bef6a93f3b2211af281e"
integrity sha512-HIt26NvgQ5udlI5jJwYgVSqBdfy1qX0+L1TseJNuyUVWgzkNGjQy2rGnXXA2yuWoSgWoDGtKfL94CC9FCAsNyg==
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -43,14 +43,16 @@
"@tarojs/react": "v3.2.0-canary.9",
"@tarojs/runtime": "v3.2.0-canary.9",
"@tarojs/taro": "v3.2.0-canary.9",
"@tbminiapp/lottie-miniapp": "^0.0.4",
"@tbmp/mp-cloud-sdk": "^1.4.2",
"classnames": "^2.2.6",
"fyge": "2.0.31",
"hox": "^1.1.2",
"lodash": "4.17.15",
"react": "^16.10.0",
"react-dom": "^16.10.0",
"taro-ui": "^3.0.0-alpha.3",
"tbcc-sdk-ts": "^1.0.5"
"tbcc-sdk-ts": "^1.0.6"
},
"devDependencies": {
"@babel/core": "^7.8.0",
......
const fs = require('fs');
const path = require('path')
const { addPages } = require('../config/default').default
const { canvasPages, hasCanvas } = require('../config/default').default
export default (ctx, options) => {
// plugin 主体
const { hasGameModule = false, hasLottieAnimation = false } = options
ctx.onBuildStart(() => {
// console.log('编译开始!')
})
ctx.onBuildFinish(() => {
if(hasGameModule) {
const dirUrl = path.resolve(__dirname,'..')+'/dist/app.json'
const rawdata = fs.readFileSync(dirUrl);
const { pages, ...ext } = JSON.parse(rawdata);
let new_pages = [...pages,...addPages]
const _new_info = {
...ext,
pages: new_pages
}
fs.writeFileSync(dirUrl, JSON.stringify(_new_info));
}
if(hasLottieAnimation) {
const dirUrl = path.resolve(__dirname,'..')+'/dist/pages/index/index.json'
const rawdata = fs.readFileSync(dirUrl);
const { usingComponents, ...ext } = JSON.parse(rawdata);
const new_info = {
...ext,
usingComponents: {
...usingComponents,
"lottie-modal":"/components/lottieAnimation/lottieAnimation"
if(hasCanvas) {
for(let i = 0; i < canvasPages.length; i++) {
const itm = canvasPages[i]
const dirUrl = path.resolve(__dirname,'..')+`/dist/${itm.root}`
const rawdata = fs.readFileSync(dirUrl);
const { usingComponents, ...ext } = JSON.parse(rawdata);
const new_info = {
...ext,
usingComponents: {
...usingComponents,
"canvas-comp": `/${itm.comRoot}`
}
}
fs.writeFileSync(dirUrl, JSON.stringify(new_info));
}
fs.writeFileSync(dirUrl, JSON.stringify(new_info));
}
console.log('文件写入成功!');
//ctx.writeFileToDist({ filePath: string, content: string })
......
......@@ -11,7 +11,6 @@ const request = tbccRequest({
cloudName,
requestType
})
/**
const defaultConfig = {
method: 'GET',
......@@ -43,6 +42,6 @@ const apiList = {
// 生成API
const API = generateAPI(apiList, request)
API.fn = capiFn(apiList, request)
API.Fn = capiFn(apiList, request)
export default API
export default {
pages: [
'pages/index/index',
'pages/myPrize/myPrize',
'pages/browseGoods/browseGoods',
'pages/collectGoods/collectGoods',
'pages/orderGoods/orderGoods'
'pages/index/index'
],
subPackages: [
{
"root": "pages/packagePrize",
"pages": [
'myPrize/myPrize'
]
},
{
"root": "pages/packageGood",
"pages": [
'browseGoods/browseGoods',
'collectGoods/collectGoods',
'orderGoods/orderGoods'
]
},
{
"root": "pages/packageGame",
"pages": [
'game/game'
]
}
],
window: {
enableSkia: 'true',
allowsBounceVertical: 'NO',
navigationBarTitleText: '活动名称'
navigationBarTitleText: '活动名称',
navigationBarForceEnable: true
},
plugins: {
cemMember: {
......
......@@ -6,7 +6,7 @@
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%) scale(0);
transform: translate(-50%, -50%);
z-index: 22;
}
......
.canvas {
width:100%;
height:100vh;
flex: 1;
display: flex;
flex-direction: column;
background: #f5cccd;
}
.test-btn-box {
position: absolute;
top: 320rpx;
background-color: #000;
}
\ No newline at end of file
<view class="page-game">
<canvas id="canvas" type="2d" class="canvas" disable-scroll="true"
onTouchStart="onMouseEvent"
onTouchMove="onMouseEvent"
onTouchEnd="onMouseEvent"
onReady="onCanvasReady"
></canvas>
</view>
<task-modal />
\ No newline at end of file
<view class="farmer-container-plants canvas">
<canvas id="canvas" type="2d" class="canvas" disable-scroll="true"
onTouchStart="onMouseEvent"
onTouchMove="onMouseEvent"
onTouchEnd="onMouseEvent"
onReady="onCanvasReady"
></canvas>
</view>
\ No newline at end of file
import { Main } from './output';
/**
* 直接取,app
*/
const app = getApp()
Component({
isUpdateFlag: true,
data: {
needDataInCanvas: {}
},
didMount(query) {
},
didUpdate(preProps,preData) {
// 实时监听数据更新
const { updateFlag, netName, updateData } = this.props
if(updateFlag !== 1 && updateFlag !== preProps.updateFlag) {
// this.postMessage(netName, updateData)
console.warn('数据更新了')
}
},
methods: {
onCanvasReady() {
console.log("进canvas了")
// 创建Main,授权登录完后才创建
this.createMain();
},
//创建引入的Main
createMain() {
const self = this;
my.createCanvas({
id: 'canvas',
success: (ccc) => {
const dpr = my.getSystemInfoSync().pixelRatio
const windowWidth = my.getSystemInfoSync().windowWidth;
const windowHeight = my.getSystemInfoSync().windowHeight;
ccc.width = windowWidth * dpr + dpr;//重新修改会有误差
ccc.height = windowHeight * dpr + dpr;
// console.log(Main)
console.log(ccc.width, ccc.height)
if (!this.main) {
try {
this.main = new Main(ccc)
//添加事件,为了和main里的通信
this.main.addGlobalEvent("onMessage", self.onMessage, self)
} catch (err) {
console.error(err)
}
}
}
})
},
//和main通信的方法,接收main的信息
onMessage(e) {
//接口名字
let netName = e.data.netName;
//接口参数
let parameter = e.data.parameter;
//暂时发现3个需要用户操作的接口
//定制的授权
if (netName == "mine.authorize") {
this.getAuth()
}
//获取地址
else if (netName == "mine.getUserAddress") {
this.getUserAddress(parameter.prizeId)
}
//关注店铺的操作
else if (netName == "mine.favorShop") {
this.doFavorShop()
}
//领养名字,有弹框的
else if (netName == "mine.getAdoptName") {
this.setData({ "adoptModalVisible": true, type: parameter.type })
}
//打开详情页,还有成功失败
else if (netName == "mine.openDetail") {
openDetail(parameter.itemId).then(
() => {
this.postMessage(netName, { success: true })
},
() => {
this.postMessage(netName, { success: false })
}
)
}
//前端同步接口
else if (netName.indexOf("mine") == 0) {
var data = { success: true }
switch (netName) {
case "mine.getAppData"://获取信息
data = {
success: true,
data: {
activityId: app.activityId,//|| "5e7c40e98564b57d7fb95812",
nickName: app.nickName,
avatar: app.avatar,
openId: app.openId,
inviteId: this.inviteId,//判断是否要发助力用
isFollow: app.isFollow,
needDataInCanvas:app.needDataInCanvas,
activityInfo:this.activityInfo,
userInfo:this.userInfo,
newUser: this.newUser,
remainTimes: this.remainTimes,
firstLoginToday: this.firstLoginToday,
}
}
break;
case "mine.navigateToOutside"://跳转小程序外的页面
my.call("navigateToOutside", {
url: parameter.url
}, (res) => {
// my.alert({ content: "success - " + JSON.stringify(res)})
})
console.log(parameter.url)
break;
case "mine.navigateTo"://跳转小程序内的页面
my.navigateTo({
url: parameter.url
})
break;
case "mine.navigateBack"://返回页面
my.navigateBack({
delta: parameter.delta || 1
})
break;
case "mine.showSharePanel"://分享
//多一个参数
this.openId = parameter.openId;
my.showSharePanel()
break;
case "mine.reportAnalytics": ////淘宝自定义埋点
reportAnalytics(parameter.logkey);
break;
case "mine.openMusic": //音频
playBgMusic(parameter.isOn, this.musicUrl);
break;
case "mine.openTask": //打开任务
this.setData({ taskModalVisible: true });
break;
case "mine.openMember": //打开入会
this.setData({ expend: true, });
break;
}
this.postMessage(netName, data)
} else {
//获取后端接口
const { function: fc } = app.cloud;
//处理下带上activityId
if (!parameter) parameter = {};
parameter.activityId = app.activityId;
//netName得分割下
fc.invoke(netName.split(".")[0], parameter, netName.split(".")[1])
.then(res => {
// console.log("返回数据" + JSON.stringify(res));
//发送消息
this.postMessage(netName, res || { success: false })
}, (err) => {
//网络异常,返回失败
this.postMessage(netName, { success: false })
})
}
},
//和main通信的方法,接收main的信息
onMessage2(e) {
// this.props.onPostMessage({
// type: 'postMessage',
// target: {
// id: this.props.id
// },
// data: e.data
// })
},
postMessage(netName, data) {
// this.main.dispatchGlobalEvent(netName, data)
this.main && this.main.dispatchGlobalEvent({ type: netName }, data)//以防复用事件event串了,就用这种方式
},
//鼠标事件
onMouseEvent(e) {
if (this.main) this.main.stage.onMouseEvent(e)
},
// 发送数据
onPostMessage() {
this.props.onPostMessage({
type: 'postMessage',
target: {
id: this.props.id
},
data: {
a: 222,
b: 33
}
})
}
}
});
{
"component": true
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
/**
* 通用toast
* @param {string} content toast内容
* @param {number} duration 显示时长
*/
export const commonToast = (content, duration = 3000) => {
my.showToast({
content: content || '换个姿势再试一次~',
duration
});
};
/**
* 获取授权用户信息
* @returns {object} 用户登录信息
*/
export const getAuthUserInfo = () => {
return new Promise((resolve, reject) => {
my.authorize({
scopes: 'scope.userInfo',
success: res => {
my.getAuthUserInfo({
success: userInfo => { resolve(userInfo); }
});
},
fail: err => {
reject(err);
}
});
});
};
/**
* 获取系统信息
* @returns {object} 小程序系统信息
*/
export const getSystemInfo = () => {
return new Promise((resolve, reject) => {
my.getSystemInfo({
success: res => { resolve(res); },
fail: err => { reject(err); }
});
});
};
/**
* 执行关注店铺
* @param {number} sellerId 店铺归属的卖家Id
* @returns {boolean} 关注状态
*/
export const favorShop = sellerId => {
return new Promise((resolve, reject) => {
my.tb.favorShop({
id: sellerId,
success: res => {
console.log(res, '关注店铺');
resolve(res);
},
fail: err => {
console.log(err, '关注店铺失败');
// error code 11 为用户取消操作不认作失败场景
// if (err.error !== 11) {
reject(err);
// }
}
});
})
};
/**
* 判断是否关注店铺
* @param {number} sellerId 店铺归属的卖家Id
* @returns {boolean} 关注状态
*/
export const checkShopFavoredStatus = sellerId => {
return new Promise((resolve, reject) => {
my.tb.checkShopFavoredStatus({
id: sellerId,
success: res => {
resolve(res.isFavor);
},
fail: err => {
reject(err);
}
});
});
};
/**
* 跳转到外部链接
* @param {string} url 跳转链接
*/
export const navigateToOutside = url => my.call("navigateToOutside", { url });
/**
* 跳转到内部链接(新开窗口)
* @param {string} url 跳转链接
*/
export const navigateTo = url => my.navigateTo({ url });
/**
* 跳转到内部链接(不新开窗口)
* @param {string} url 跳转链接
*/
export const redirectTo = url => my.redirectTo({ url });
/**
* 获取服务器时间
* @returns {number} 服务器时间戳
*/
export const getServerTime = () => {
return new Promise((resolve, reject) => {
my.getServerTime({
success: (res) => {
resolve(res.time);
},
fail: err => {
reject(err);
}
});
});
};
/**
* 收藏商品
* @param {number} 商品id
* @returns {object} 收藏结果
*/
export const collectGoods = id => {
return new Promise((resolve, reject) => {
my.tb.collectGoods({
id,
success: res => {
resolve(res);
},
fail: err => {
if (err.errorMessage === '该商品已收藏') {
// 已收藏没有给到errorCode,只能通过message判断
// 返回收藏成功,并且给到标记代表是已收藏的
resolve({ success: true, hasCollected: true, errorMessage: err.errorMessage });
} else if (err.error !== 11) {
// error code 11 为用户取消操作不认作失败场景
reject(err);
}
}
});
});
};
/**
* 查询商品收藏状态
* @param {number} 商品id
* @returns {boolean} 商品收场状态
*/
export const checkGoodsCollectedStatus = id => {
return new Promise((resolve) => {
my.tb.checkGoodsCollectedStatus({
id,
success: res => {
resolve(res.isCollect);
}
});
});
};
/**
* 时间格式化
* @param date 接收可以被new Date()方法转换的内容
* @param format 字符串,需要的格式例如:'yyyy-MM-dd hh:mm:ss'
* @returns {String}
*/
export const dateFormatter = (date, format = 'yyyy-MM-dd') => {
if (!date) return '-';
date = new Date(typeof date === 'string' && isNaN(date) ? date.replace(/-/g, '/') : date);
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'q+': Math.floor((date.getMonth() + 3) / 3),
'S': date.getMilliseconds()
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return format;
};
/**
* 创建音频类
*/
class AudioModel {
constructor(opts = {}) {
const { src } = opts;
if (!src) {
console.error('请输入音频链接');
return false;
}
try {
const innerAudioContext = my.createInnerAudioContext();
Object.keys(opts).forEach(item => {
innerAudioContext[item] = opts[item];
});
return innerAudioContext;
} catch(e) {
console.error('当前版本不支持音频');
}
}
};
/**
* 创建音频实例
* @param {object} opts 配置对象 例 { src: '音频链接', autoplay: false }
*/
export const createAudio = opts => {
const audioInstance = new AudioModel(opts)
return audioInstance;
};
//暂时只有一个音乐,临时处理
let bgMusic
export const playBgMusic = (isOn,src) => {//待测试
if (isOn) {
if (!bgMusic) {
bgMusic = createAudio({
src: src||"https://yun.duiba.com.cn/db_games/activity/babycare_xiaoxiao/bgm_babycare.mp3",
autoplay: true,
loop: true//暂时无效?
});
//监听结束,因为loop无效
bgMusic.onEnded(() => {
// bgMusic.seek(0);
bgMusic.play();
})
console.log(src)
} else {
bgMusic.play();
}
} else {
if (bgMusic) {
// bgMusic.pause();
bgMusic.stop();
// bgMusic.seek(0);
}
}
}
/**
* 版本比较
* @param {string} cur 当前版本
* @param {string} compare 比较版本
*/
export const versionCompare = (cur, compare) => {
const _cur = cur.split('.');
const _compare = compare.split('.');
if (+_cur[0] < +_compare[0]) {
return false;
} else if ( +_cur[0] === +_compare[0] && +_cur[1] < +_compare[1] ) {
return false;
} else if (+_cur[0] === +_compare[0] && +_cur[1] === +_compare[1] && +_cur[2] < +_compare[2]) {
return false;
}
return true;
}
//暂时只有一个音乐,临时处理
// let bgMusic;
// let gameMusic;
let bgs = {
}
export const playBgMusic1 = (isOn, src) => {//待测试
for (let k in bgs) {
if (bgs[k].isOn) {
bgs[k].stop();
}
// bgs[k].isOn = false; /// TODO 自己记一个开关,因为淘宝的玩意stop之后虽然听不到,但还是在播放,会触发loop播放和onEnded事件
}
const key = src;
if (isOn) {
if (!bgs[key]) {
bgs[key] = createAudio({
src: src,
autoplay: true,
loop: false /// TODO 暂时无效?2020.08.12 目前有效,但stop后还会跑数据,导致到音频结束到时间又自动播放
});
bgs[key].onPlay(() => {
bgs[key].isOn = true;
});
bgs[key].onStop(() => {
bgs[key].isOn = false;
});
/// TODO监听结束,因为loop无效 2020.08.12 loop有效,这个操作是为了解决stop之后还会跑音频数据的问题
bgs[key].onEnded(() => {
if (bgs[key].isOn) { // 判断自己记录的开关
bgs[key].play();
// bgs[key].isOn = true;
}
});
bgs[key].play(); // 安卓有时候autoplay好像莫得用
// console.log(src)
// bgs[key].isOn = true; /// TODO 自己记一个开关,因为淘宝的玩意stop之后虽然听不到,但还是在播放,会触发loop播放和onEnded事件
} else {
bgs[key].play();
// bgs[key].isOn = true; /// TODO 自己记一个开关,因为淘宝的玩意stop之后虽然听不到,但还是在播放,会触发loop播放和onEnded事件
}
} else {
if (bgs[key]) {
// bgs[key].pause(); /// pause 垃圾,不能用
bgs[key].stop();
// bgs[key].isOn = false; /// TODO 自己记一个开关,因为淘宝的玩意stop之后虽然听不到,但还是在播放,会触发loop播放和onEnded事件
}
}
}
// TODO: 确认天猫是否也是9.3.0以下有问题
export const checkSystem = async ()=> {
const { version, app } = await getSystemInfo();
console.log('version', version);
return versionCompare(version, '9.3.0');
}
/**
* 获取淘宝用户收货地址
*/
export const getUserAddress = async (opts = {}) => {
let defaults = {
addAddress: 'show',
searchAddress: 'hide',
locateAddress: 'hide',
joinTag: '' // 分割收货地址符号(淘宝商家有特定发货需求)
};
const isValidVersion = await checkSystem();
if(!isValidVersion) {
commonToast('当前版本不支持选择收货地址,请升级到最新版本');
return;
}
let _opts = Object.assign({}, defaults, opts);
return new Promise((resolve, reject) => {
my.authorize({
scopes: 'scope.addressList',
success: () => {
const { addAddress, searchAddress, locateAddress, joinTag } = _opts;
if (!my.tb.chooseAddress) {
reject({ support: false, errorMessage: '当前版本不支持选择收货地址,请升级到最新版本' });
return false;
}
my.tb.chooseAddress({
addAddress,
searchAddress,
locateAddress
}, res => {
const { error, provinceName, countyName, cityName, streetName, detailInfo, name, telNumber } = res;
// 如果有error为用户取消操作不做操作
if (error) {
resolve(false);
} else {
resolve({
...res,
duibaAddress: {
name,
phone: telNumber,
address: [provinceName, cityName, countyName, streetName, detailInfo].join(joinTag)
}
});
}
}, res => {
reject(res);
})
},
});
});
};
/**
* 打开详情页
* @param {string} itemId
*/
export const openDetail = (itemId) => {
return new Promise((resolve, reject) => {
my.tb.openDetail({
itemId,
success: (res) => {
resolve(res)
},
fail: (res) => {
reject(res)
},
});
})
}
/**
* 自定义埋点的方法
* @param {string}} logkey
*/
export const reportAnalytics = (logkey) => {
my.reportAnalytics('click', {
// 标志某一类事件,方便数据分析进行分组
'logkey': logkey
})
}
export const cloudRequest = async (_cloudName, params, handle, loading = false) => {
const { cloud } = getApp();
loading && my.showLoading()
return new Promise((resolve, reject) => {
cloud.function.invoke(_cloudName, params, handle).then(res => {
console.log(`调用${handle}接口返回结果`, res)
loading && my.hideLoading()
if (res && res.success) {
resolve(res);
} else {
reject(res);
}
return res;
}).catch(() => {
loading && my.hideLoading()
reject();
});
});
}
export const checkMember = async () => {
// @ts-ignore
const memberPlugin = requirePlugin("cemMember");
return new Promise((resolve,reject) => {
memberPlugin.checkMember({
// sellerId,
success: (res) => {
let isMember = !!res.data.isMember && res.data.isMember === 'true'
resolve(isMember)
},
fail: (res) => {
reject(res)
}
})
})
}
\ No newline at end of file
......@@ -26,6 +26,7 @@ Component({
my.createCanvas({
id: 'canvas',
success: (ccc) => {
console.warn(JSON.stringify(ccc))
this.canvas = ccc;
const dpr = my.getSystemInfoSync().pixelRatio
//显示尺寸
......@@ -37,7 +38,7 @@ Component({
//兼容小程序
fyge.initedByCanvas(ccc)
var stage = this.stage = new fyge.Stage(ccc, 750, 1624, windowWidth, windowHeight,1);
var stage = this.stage = new fyge.Stage(ccc, 750, 1624, windowWidth, windowHeight);
//加载
console.warn(lottieData[type])
var l = stage.addChild(new fyge.Lottie(lottieData[type]))
......
.dialog-container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 20;
}
.dialog-modal__shade {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.75);
}
.dialog-modal__container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.dialog-modal__container-bottom {
animation: bottom-up 1s linear forwards;
}
.dialog-modal__close {
position: absolute;
right: 20rpx;
top: -80rpx;
height: 48rpx;
width: 48rpx;
background: url('//yun.dui88.com/taobaomini/clientCTest/modal_close_btn.png') center center no-repeat;
background-size: 48rpx 48rpx;
}
@keyframes bottom-up {
from {
transform: translate(0,100vh);
}
to {
transform: translate(0,0);
}
}
.task-modal-container {
width: 100%;
height: 700rpx;
position: absolute;
bottom: 0;
left: 0;
background-color: #ffffff;
}
.task-modal-content__title {
text-align: center;
margin: 30rpx 0;
}
.task-modal-content__list {
width: 100%;
height: 600rpx;
padding: 0 16rpx;
}
.task-modal-content__scroll {
width: 100%;
height: 100%;
}
.task-modal-content-item {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16rpx;
padding: 16rpx;
border: 1rpx solid #eee;
}
.task-modal-content-item__left {
width: 120rpx;
height: 120rpx;
display: flex;
justify-content: center;
align-items: center;
background-color: #eee;
}
.task-modal-content-item__left image {
width: 80rpx;
}
.task-modal-content-item__left-label {
flex: 1;
flex-direction: column;
align-items: center;
margin: 0 16rpx;
}
.task-modal-content-item__left-title {
}
.task-modal-content-item__left-reward {
margin-top: 10rpx;
}
.task-modal-content__list-item__right {
display: flex;
justify-content: center;
align-items: center;
width: 150rpx;
height: 60rpx;
background-color: #eee;
border-radius: 30rpx;
}
.task-item__status-1 {
}
.task-item__status-2 {
}
.task-item__status-3 {
}
\ No newline at end of file
<view class="dialog-container">
<view class="dialog-modal__shade modal-animate-fade-in" />
<view class="dialog-modal__container {{ 'dialog-modal__container-bottom'}} ">
<view class="task-modal-container">
<view class="dialog-modal__close" onTap="onModalClose" />
<view class="task-modal-content">
<view class="task-modal-content__title">任务模块</view>
<view class="task-modal-content__list">
<scroll-view scroll-y="{{true}}" class="task-modal-content__scroll">
<view class="task-modal-content-item" a:for="{{taskList}}">
<view class="task-modal-content-item__left">
<image src="{{taskIcon[item.taskType]}}" mode="widthFix" />
</view>
<view class="task-modal-content-item__left-label">
<view class="task-modal-content-item__left-title">{{item.title}}</view>
<view class="task-modal-content-item__left-reward">抽盒次数+{{item.rewards}}</view>
</view>
<view class="task-modal-content__list-item__right {{'task-item__status-'+item.status}}" data-item="{{item}}" onTap="handleTapItem">
{{
item.status == 1 ? doTaskTxt[item.taskType] : commonTaskTxt[taskType]
}}
</view>
</view>
</scroll-view>
</view>
</view>
</view>
</view>
</view>
<member-shop
a:if="{{memberShopVisible}}"
expend="{{memberShopVisible}}"
onSuccess="onSuccess"
onFail="closeCommonModal"
onClose="closeCommonModal" />
\ No newline at end of file
import { cloudRequest, throttleHandle, commonToast, favorShop, navigateTo, navigateToOutside, showSharePanel } from './utils';
const app = getApp();
const taskConfig = {
taskStatus: { // 任务状态
1: '//yun.duiba.com.cn/baicaoweiFarmer/task_btn_01.png',
2: '//yun.duiba.com.cn/baicaoweiFarmer/task_btn_02.png',
3: '//yun.duiba.com.cn/baicaoweiFarmer/task_btn_03.png'
},
taskIcon: {// 任务图标
follow: '//yun.duiba.com.cn/baicaoweiFarmer/follow.png',
member: '//yun.duiba.com.cn/baicaoweiFarmer/memberStar1.png',
invites: '//yun.duiba.com.cn/baicaoweiFarmer/invites.png',
jumpLink: '//yun.duiba.com.cn/baicaoweiFarmer/browseGoodsLink.png',
browseGoods: '//yun.duiba.com.cn/baicaoweiFarmer/browseGoods.png',
orderGoods: '//yun.duiba.com.cn/baicaoweiFarmer/orderGoods.png',
collectGoods: '//yun.duiba.com.cn/baicaoweiFarmer/orderGoods.png',
sign: '//yun.duiba.com.cn/baicaoweiFarmer/orderGoods.png',
},
commonTaskTxt: {
1: '去完成',
2: '待领取',
3: '已完成'
},
doTaskTxt: {
follow: '立即关注',
invites: '去邀请',
member: '1秒入会',
sign: '立即签到',
jumpLink: '去完成',
browseGoods: '去完成',
orderGoods: '去完成',
collectGoods: '去完成',
},
browseType: 1, // 1 跳转即算完成 2 跳转浏览15s 才算完成
browseTime: 15, // 浏览时间
}
const cloudName = 'luolai'
const GO_TO_INVITE = 2 // 数据埋点
const SELLER_ID = 2374579403 // 商家sellerId
Component({
mixins: [],
data: {
taskStatus: taskConfig.taskStatus,
taskIcon: taskConfig.taskIcon,
commonTaskTxt: taskConfig.commonTaskTxt,
doTaskTxt: taskConfig.doTaskTxt,
taskList: [
{
taskType: 'follow',
title: '关注店铺',
taskRateType: 1,
times: 1,
completeTimes: 0,
status: 1,
rewards: 1
},
{
taskType: 'member',
title: '加入会员',
taskRateType: 1,
times: 1,
completeTimes: 0,
status: 1,
rewards: 1
},
{
taskType: 'invites',
title: '邀请好友入会',
taskRateType: 1,
times: 3,
completeTimes: 0,
status: 1,
rewards: 1
},
{
taskType: 'jumpLink',
title: '浏览店铺15s',
taskRateType: 2,
times: 1,
completeTimes: 0,
status: 1,
rewards: 1
},
{
taskType: 'browseGoods',
title: '浏览商品',
taskRateType: 2,
times: 1,
completeTimes: 0,
status: 1,
rewards: 1
},
{
taskType: 'orderGoods',
title: '下单任务',
taskRateType: 2,
times: 1,
completeTimes: 0,
status: 1,
rewards: 1
},
{
taskType: 'collectGoods',
title: '收藏商品',
taskRateType: 2,
times: 1,
todayCompleteTimes: 0,
status: 1,
rewards: 1
},
{
taskType: 'sign',
title: '每日签到',
taskRateType: 2,
times: 1,
todayCompleteTimes: 0,
status: 1,
rewards: 1
}
],
memberShopVisible: false,
currentTaskType: null,
preBrowseTime: null
},
props: {
taskFlag: 1,
dataName: '',
onModalClose: () => {},
onUpdate: () => {}
},
didMount() {
this.getTaskList()
},
didUpdate(preProps,preData) {
const { taskFlag } = this.props
const { isFlashTask = false } = app
const { browseTime } = taskConfig
const { preBrowseTime, currentTaskType } = this.data
if(preProps.taskFlag !== taskFlag && isFlashTask) {
// console.log((Date.now() - preBrowseTime)/1000)
if(preBrowseTime && ((Date.now() - preBrowseTime) / 1000) >= browseTime) {
this.doCompleteTask(currentTaskType,true)
}
else {
if(currentTaskType === 'jumpLink') {
this.setData({ preBrowseTime: null, currentTaskType: null})
}
this.getTaskList(true)
}
}
},
didUnmount() {
},
methods: {
// 关闭弹窗
onModalClose() {
const { onModalClose, dataName } = this.props;
onModalClose && onModalClose(dataName);
},
// 按钮
handleTapItem: throttleHandle(async function(e) {
const { activityId } = app
const { status, taskType, url, rewards, itemIds, keepTime } = e.target.dataset.item
if(status == 3) return;
if(status == 2) {
const { success, data } = await cloudRequest(cloudName,{ activityId, taskType }, 'receiveTaskRewards').catch(res => {
commonToast(res && res.message);
}) || {};
if (success && data) {
const { rewards, receiveTimes } = data
let message = taskType == 'invites' ?
`成功邀请${receiveTimes}名好友,抽盒次数+${rewards}`:`抽盒次数+${rewards}`
commonToast(message)
this.getTaskList()
this.props.onUpdate()
}
}
else {
this.goToComplete(taskType,url,itemIds,keepTime)
}
},2000),
// 做任务
async goToComplete(taskType,url,itemIds,keepTime) {
const { activityId } = app
const { browseType } = taskConfig
switch(taskType) {
case 'member':
// 去加入会员
this.setData({ memberShopVisible: true })
break;
case 'follow':
let isFollow = await favorShop(SELLER_ID)
if(isFollow) {
this.doCompleteTask(taskType)
}
break;
case 'invites':
// 邀请好友
showSharePanel();
await cloudRequest(cloudName,{ activityId, type: GO_TO_INVITE }, 'addStat')
break;
case 'jumpLink':
// 跳转任务
navigateToOutside(url || 'https://www.feizhu.com')
if(browseType === 1) {
this.doCompleteTask(taskType)
}
else {
app.isFlashTask = true
this.setData({ preBrowseTime: Date.now(), currentTaskType: taskType})
}
break;
case 'browseGoods':
// 跳转浏览页面
app.isFlashTask = true
navigateTo(`/pages/browseGoods/browseGoods?itemIds=${itemIds}&keepTime=${keepTime}`)
break;
case 'orderGoods':
// 跳转下单页面
app.isFlashTask = true
navigateTo(`/pages/orderGoods/orderGoods?itemIds=${itemIds}`)
break;
case 'collectGoods':
// 跳转收藏页面
app.isFlashTask = true
navigateTo(`/pages/collectGoods/collectGoods?itemIds=${itemIds}`)
break;
case 'sign':
// 签到
this.doCompleteTask(taskType)
break;
}
},
// 完成任务
async doCompleteTask(taskType, flag) {
const { activityId } = app
let { success, data } = await cloudRequest(cloudName,{ activityId, taskType }, 'doCompleteTask') || {}
if(success) {
this.getTaskList()
flag && this.setData({ preBrowseTime: null })
}
},
// 获取任务列表
async getTaskList(flag) {
const { activityId } = app
const { success, data } = await cloudRequest(cloudName,{ activityId }, 'getTaskList').catch(res => {
commonToast(res && res.message);
}) || {};
if (success && data) {
const { list } = data
app.isFlashTask = flag ? false : true
// this.setData({ taskList: list })
}
},
// 关闭入会组件
closeCommonModal() {
this.setData({ memberShopVisible: false })
},
// 入会成功
onSuccess() {
this.getTaskList()
this.setData({ memberShopVisible: false })
}
},
});
{
"component": true,
"usingComponents": {
"member-shop":"/components/_miniprogram/memberModal/memberModal"
}
}
\ No newline at end of file
/**
* 获取任务数据
* @param {*} _cloudName
* @param {*} params
* @param {*} loading
*/
export const cloudRequest = async (_cloudName, params, handle, loading = false) => {
const { cloud } = getApp();
loading && my.showLoading()
return new Promise((resolve, reject) => {
cloud.function.invoke(_cloudName, params, handle).then(res => {
console.log(`调用${handle}接口返回结果`, res)
loading && my.hideLoading()
if (res && res.success) {
resolve(res);
} else {
reject(res);
}
return res;
}).catch(() => {
loading && my.hideLoading()
reject();
});
});
}
/**
* 函数节流,普通防连点
* @param {fun} fun 函数
* @param {delay} delay 时间
*/
export const throttleHandle = (fun, delay = 1000) => {
let last, deferTimer;
return function () {
let now = +new Date();
if (last && now < last + delay) {
clearTimeout(deferTimer);
deferTimer = setTimeout(() => {
last = now;
}, delay);
} else {
last = now;
fun.apply(this, arguments);
}
};
}
/**
* toast
* @param {*} content
* @param {*} duration
* @param {*} successCb
*/
export const commonToast = (content, duration, successCb) => {
my.showToast({
content: content || '换个姿势再试一次~',
duration: duration || 3000,
success: successCb
})
};
/**
* 执行关注店铺
* @param {number} sellerId 店铺归属的卖家Id
* @returns {boolean} 关注状态
*/
export const favorShop = async (sellerId) => {
if (!sellerId) {
return false;
}
return new Promise((resolve, reject) => {
// @ts-ignore
my.tb.favorShop({
id: +sellerId,
success: res => {
if(res.error === 11) resolve(true)
resolve(res)
},
fail: err => {
reject(err)
}
})
})
};
/**
* 跳转到外部链接
* @param {string} url 跳转链接
*/
export const navigateToOutside = url => {
if (!url) {
console.error('navigateToOutside: 请传入url');
return false;
}
my.call('navigateToOutside',{ url });
};
/**
* 跳转到内部链接(新开窗口)
* @param {string} url 跳转链接
*/
export const navigateTo = url => {
if (!url) {
console.error('navigateTo: 请传入url');
return false;
}
my.navigateTo({ url });
};
/**
* 调起分享面板
*/
export const showSharePanel = async () => {
my.showSharePanel();
}
\ No newline at end of file
......@@ -23,6 +23,7 @@ export default function GoodsPage(props) {
},
color: '#181818'
},
collectFlag = false,
onOpenDetail,
onCompleteTask
} = props
......@@ -40,6 +41,11 @@ export default function GoodsPage(props) {
const goToCollectGoods = async(item) => {
const { itemId, collected } = item
const { taskType } = task
// 今日是否已收藏过
if(collectFlag) {
commonToast('任务已完成,请明日再来')
return;
}
if (collected) {
commonToast('您已收藏过该商品了')
return
......
const testLottie = require('./lottieData')
const testLottie = require('./lottieData.json')
export default {
1: testLottie
......
.canvas {
width:100%;
height:100%;
}
.page-game {
width:100%;
height:100vh;
flex: 1;
display: flex;
flex-direction: column;
background: #f5cccd;
}
import { Main } from './output';
import { getUserAddress, favorShop, getAuthUserInfo, checkShopFavoredStatus, openDetail, reportAnalytics, commonToast, playBgMusic, getSystemInfo } from './utils';
//这种方式/表示client下面的路径
// import { getSystemInfo } from '/utils/utils';
//检查版本号
const checkSystem = async () => {
const { version } = await getSystemInfo();
console.log('version', version);
return versionCompare(version, '9.10.0');
}
//对比版本号
const versionCompare = (cur, compare) => {
const _cur = cur.split('.');
const _compare = compare.split('.');
if (+_cur[0] < +_compare[0]) {
return false;
} else if (+_cur[0] === +_compare[0] && +_cur[1] < +_compare[1]) {
return false;
} else if (+_cur[0] === +_compare[0] && +_cur[1] === +_compare[1] && +_cur[2] < +_compare[2]) {
return false;
}
return true;
}
/**
* 直接取,app
*/
const app = getApp()
/**
* 分享信息
*/
const SHARE_CONFIG = {//待写
title: 'babycare欢乐城!',
desc: '赢TF彩妆礼盒',
imageUrl: "https://yun.duiba.com.cn/db_games/activity/pacman/share.jpg",
path: 'pages/index/index'
}
Page({
//暂时先不用吧,有问题
data: {},
onLoad(query) {
// 页面加载
console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
//带参数的取链接参数
if (query.inviteId) this.inviteId = query.inviteId;
//版本提示
checkSystem().then(r => {
if (!r) {
my.showToast({
content: "请升级最新版本的淘宝体验",
duration: 5000
});
}
});
},
onReady() {
},
onCanvasReady() {
console.log("进canvas了")
//版本检查
checkSystem().then(r => {
if (r) {//检查通过开始授权
this.getAuth();
}
});
},
//创建引入的Main
createMain() {
var self = this;
my.createCanvas({
id: 'canvas',
success: (ccc) => {
const dpr = my.getSystemInfoSync().pixelRatio
const windowWidth = my.getSystemInfoSync().windowWidth;
const windowHeight = my.getSystemInfoSync().windowHeight;
ccc.width = windowWidth * dpr + dpr;//重新修改会有误差
ccc.height = windowHeight * dpr + dpr;
// console.log(Main)
console.log(ccc.width, ccc.height)
if (!this.main) {
try {
this.main = new Main(ccc)
//添加事件,为了和main里的通信
this.main.addGlobalEvent("onMessage", self.onMessage, self)
} catch (err) {
console.error(err)
}
}
}
})
},
//授权
async getAuth() {
const userInfo = await getAuthUserInfo().catch(() => {
commonToast('未授权成功');
this.postMessage('mine.authorize', { success: false })
})
//未授权成功不进入活动
if (!userInfo) return
const { nickName, avatar } = userInfo
app.nickName = nickName;
app.avatar = avatar;
//检查是否关注的
const isFollow = await checkShopFavoredStatus(app.sellerId).catch(() => { })
app.isFollow = this.isFollow = isFollow;//app上也挂一个
//创建Main,授权登录完后才创建,也可定制在游戏内授权
this.createMain();
//分享图片,TODO,注释打开替换
const result1 = await app.cloud.file.getTempFileURL({ fileId: 'cloud://2D60DC04FC1888AF6F865B88F0B2EBCC//share.png' });
if (result1[0]) SHARE_CONFIG.imageUrl = result1[0].url
//音乐路径
const resultSrc = await app.cloud.file.getTempFileURL({ fileId: 'cloud://293F2E7D0C6799617660563A322DEE55//bgm_babycare.mp3' });
if (resultSrc[0]) this.musicUrl = resultSrc[0].url;
},
/**
* 获取及选择用户收货地址
* @param {*} prizeId
*/
async getUserAddress(prizeId) {
const userAddress = await getUserAddress().catch(res => {
commonToast(res.errorMessage)
this.postMessage('mine.getUserAddress', { success: false })
})
if (userAddress) {//格式需要修改具体
const { name, phone, address } = userAddress.duibaAddress
const { provinceName, cityName, countyName } = userAddress;
my.confirm({
title: '提示',
content: '确认使用该收货地址:' + name + phone + address,
confirmButtonText: '确定',
cancelButtonText: '取消',
success: (result) => {
const { confirm } = result
if (confirm) {
//发接口提交地址
const { cloud, activityId, cloudName } = app
cloud.function.invoke(cloudName, {//定制
activityId,
id: prizeId,
_id: prizeId,
// address,
name,
phone,
addressdetail: address,
provice: provinceName,
city: cityName,
area: countyName,
// address: JSON.stringify(userAddress.duibaAddress)
}, "receiveObjectPrize")
.then(res => {
if (res && res.success) {
//确认发送成功信息
this.postMessage('mine.getUserAddress', { success: true })
} else {
//新增失败0514
this.postMessage('mine.getUserAddress', { success: false })
}
})
.catch(() => {
//新增失败0514
this.postMessage('mine.getUserAddress', { success: false })
})
} else {
//新增失败0514
this.postMessage('mine.getUserAddress', { success: false })
}
},
})
}
},
/**
* 关注店铺
*/
async doFavorShop() {
const { sellerId } = getApp()
const success = await favorShop(sellerId).catch(err => {
// commonToast(err.errorMessage || '活动太火爆,请稍后重试')
//这个包括用户取消的,所以下面不用判断success了;
this.postMessage('mine.favorShop', { success: false })
// console.log("啊啊啊请问请问")
})
// console.log("asdasd",success)
if (success) {
this.postMessage('mine.favorShop', { success: true })
}
// else {
// // console.log("飒飒飒飒大苏打")
// this.postMessage('mine.favorShop', { success: false })
// }
},
//和main通信的方法,接收main的信息
onMessage(e) {
//接口名字
let netName = e.data.netName;
//接口参数
let parameter = e.data.parameter;
//暂时发现3个需要用户操作的接口
//定制的授权
if (netName == "mine.authorize") {
this.getAuth()
}
//获取地址
else if (netName == "mine.getUserAddress") {
this.getUserAddress(parameter.prizeId)
}
//关注店铺的操作
else if (netName == "mine.favorShop") {
this.doFavorShop()
}
//领养名字,有弹框的
else if (netName == "mine.getAdoptName") {
this.setData({ "adoptModalVisible": true, type: parameter.type })
}
//打开详情页,还有成功失败
else if (netName == "mine.openDetail") {
openDetail(parameter.itemId).then(
() => {
this.postMessage(netName, { success: true })
},
() => {
this.postMessage(netName, { success: false })
}
)
}
//前端同步接口
else if (netName.indexOf("mine") == 0) {
var data = { success: true }
switch (netName) {
case "mine.getAppData"://获取信息
data = {
success: true,
data: {
activityId: app.activityId,//|| "5e7c40e98564b57d7fb95812",
nickName: app.nickName,
avatar: app.avatar,
openId: app.openId,
inviteId: this.inviteId,//判断是否要发助力用
isFollow: app.isFollow
}
}
break;
case "mine.navigateToOutside"://跳转小程序外的页面
my.call("navigateToOutside", {
url: parameter.url
}, (res) => {
// my.alert({ content: "success - " + JSON.stringify(res)})
})
console.log(parameter.url)
break;
case "mine.navigateTo"://跳转小程序内的页面
my.navigateTo({
url: parameter.url
})
break;
case "mine.navigateBack"://返回页面
my.navigateBack({
delta: parameter.delta || 1
})
break;
case "mine.showSharePanel"://分享
//多一个参数
this.openId = parameter.openId;
my.showSharePanel()
break;
case "mine.reportAnalytics": ////淘宝自定义埋点
reportAnalytics(parameter.logkey);
break;
case "mine.openMusic": //音频
playBgMusic(parameter.isOn, this.musicUrl);
break;
case "mine.openRankPanel": //打开排行榜
this.setData({ "expRankModalVisible": true });
break;
}
this.postMessage(netName, data)
} else {
//获取后端接口
const { function: fc } = app.cloud;
//处理下带上activityId
if (!parameter) parameter = {};
parameter.activityId = app.activityId;
//netName得分割下
fc.invoke(netName.split(".")[0], parameter, netName.split(".")[1])
.then(res => {
// console.log("返回数据" + JSON.stringify(res));
//发送消息
this.postMessage(netName, res || { success: false })
}, (err) => {
//网络异常,返回失败
this.postMessage(netName, { success: false })
})
}
},
postMessage(netName, data) {
// this.main.dispatchGlobalEvent(netName, data)
this.main && this.main.dispatchGlobalEvent({ type: netName }, data)//以防复用事件event串了,就用这种方式
},
onShow() {
// 页面显示
this.main && this.main.run();
},
onHide() {
// 页面隐藏
this.main && this.main.pause();
},
onUnload() {
// 页面被关闭
this.main && this.main.destroy();
},
onTitleClick() {
// 标题被点击
},
onPullDownRefresh() {
// 页面被下拉
},
onReachBottom() {
// 页面被拉到底部
},
/**
* 分享参数处理
*/
onShareAppMessage() {
// 返回自定义分享信息
// const { activityId, openId } = app
// 发送分享记录,记录数据用
// API.getShareId({ activityId });
let { path, ...rest } = SHARE_CONFIG
if (this.openId) {
path = path + '?inviteId=' + this.openId
this.openId = null//用完清掉
}
console.log(path)
return {
...rest,
path
}
},
//鼠标事件
onMouseEvent(e) {
if (this.main) this.main.stage.onMouseEvent(e)
},
});
{
"disableScroll": "true",
"usingComponents": {
"task-modal": "/components/taskModal/taskModal"
}
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
/**
* 通用toast
* @param {string} content toast内容
* @param {number} duration 显示时长
*/
export const commonToast = (content, duration = 3000) => {
my.showToast({
content: content || '换个姿势再试一次~',
duration
});
};
/**
* 获取授权用户信息
* @returns {object} 用户登录信息
*/
export const getAuthUserInfo = () => {
return new Promise((resolve, reject) => {
my.authorize({
scopes: 'scope.userInfo',
success: res => {
my.getAuthUserInfo({
success: userInfo => { resolve(userInfo); }
});
},
fail: err => {
reject(err);
}
});
});
};
/**
* 获取系统信息
* @returns {object} 小程序系统信息
*/
export const getSystemInfo = () => {
return new Promise((resolve, reject) => {
my.getSystemInfo({
success: res => { resolve(res); },
fail: err => { reject(err); }
});
});
};
/**
* 执行关注店铺
* @param {number} sellerId 店铺归属的卖家Id
* @returns {boolean} 关注状态
*/
export const favorShop = sellerId => {
return new Promise((resolve, reject) => {
my.tb.favorShop({
id: sellerId,
success: res => {
console.log(res, '关注店铺');
resolve(res);
},
fail: err => {
console.log(err, '关注店铺失败');
// error code 11 为用户取消操作不认作失败场景
// if (err.error !== 11) {
reject(err);
// }
}
});
})
};
/**
* 判断是否关注店铺
* @param {number} sellerId 店铺归属的卖家Id
* @returns {boolean} 关注状态
*/
export const checkShopFavoredStatus = sellerId => {
return new Promise((resolve, reject) => {
my.tb.checkShopFavoredStatus({
id: sellerId,
success: res => {
resolve(res.isFavor);
},
fail: err => {
reject(err);
}
});
});
};
/**
* 跳转到外部链接
* @param {string} url 跳转链接
*/
export const navigateToOutside = url => my.call("navigateToOutside", { url });
/**
* 跳转到内部链接(新开窗口)
* @param {string} url 跳转链接
*/
export const navigateTo = url => my.navigateTo({ url });
/**
* 跳转到内部链接(不新开窗口)
* @param {string} url 跳转链接
*/
export const redirectTo = url => my.redirectTo({ url });
/**
* 获取服务器时间
* @returns {number} 服务器时间戳
*/
export const getServerTime = () => {
return new Promise((resolve, reject) => {
my.getServerTime({
success: (res) => {
resolve(res.time);
},
fail: err => {
reject(err);
}
});
});
};
/**
* 收藏商品
* @param {number} 商品id
* @returns {object} 收藏结果
*/
export const collectGoods = id => {
return new Promise((resolve, reject) => {
my.tb.collectGoods({
id,
success: res => {
resolve(res);
},
fail: err => {
if (err.errorMessage === '该商品已收藏') {
// 已收藏没有给到errorCode,只能通过message判断
// 返回收藏成功,并且给到标记代表是已收藏的
resolve({ success: true, hasCollected: true, errorMessage: err.errorMessage });
} else if (err.error !== 11) {
// error code 11 为用户取消操作不认作失败场景
reject(err);
}
}
});
});
};
/**
* 查询商品收藏状态
* @param {number} 商品id
* @returns {boolean} 商品收场状态
*/
export const checkGoodsCollectedStatus = id => {
return new Promise((resolve) => {
my.tb.checkGoodsCollectedStatus({
id,
success: res => {
resolve(res.isCollect);
}
});
});
};
/**
* 时间格式化
* @param date 接收可以被new Date()方法转换的内容
* @param format 字符串,需要的格式例如:'yyyy-MM-dd hh:mm:ss'
* @returns {String}
*/
export const dateFormatter = (date, format = 'yyyy-MM-dd') => {
if (!date) return '-';
date = new Date(typeof date === 'string' && isNaN(date) ? date.replace(/-/g, '/') : date);
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'q+': Math.floor((date.getMonth() + 3) / 3),
'S': date.getMilliseconds()
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return format;
};
/**
* 创建音频类
*/
class AudioModel {
constructor(opts = {}) {
const { src } = opts;
if (!src) {
console.error('请输入音频链接');
return false;
}
try {
const innerAudioContext = my.createInnerAudioContext();
Object.keys(opts).forEach(item => {
innerAudioContext[item] = opts[item];
});
return innerAudioContext;
} catch(e) {
console.error('当前版本不支持音频');
}
}
};
/**
* 创建音频实例
* @param {object} opts 配置对象 例 { src: '音频链接', autoplay: false }
*/
export const createAudio = opts => {
const audioInstance = new AudioModel(opts)
return audioInstance;
};
//暂时只有一个音乐,临时处理
let bgMusic
export const playBgMusic = (isOn,src) => {//待测试
if (isOn) {
if (!bgMusic) {
bgMusic = createAudio({
src: src||"https://yun.duiba.com.cn/db_games/activity/babycare_xiaoxiao/bgm_babycare.mp3",
autoplay: true,
loop: true//暂时无效?
});
//监听结束,因为loop无效
bgMusic.onEnded(() => {
// bgMusic.seek(0);
bgMusic.play();
})
console.log(src)
} else {
bgMusic.play();
}
} else {
if (bgMusic) {
// bgMusic.pause();
bgMusic.stop();
// bgMusic.seek(0);
}
}
}
/**
* 版本比较
* @param {string} cur 当前版本
* @param {string} compare 比较版本
*/
export const versionCompare = (cur, compare) => {
const _cur = cur.split('.');
const _compare = compare.split('.');
if (+_cur[0] < +_compare[0]) {
return false;
} else if ( +_cur[0] === +_compare[0] && +_cur[1] < +_compare[1] ) {
return false;
} else if (+_cur[0] === +_compare[0] && +_cur[1] === +_compare[1] && +_cur[2] < +_compare[2]) {
return false;
}
return true;
}
//暂时只有一个音乐,临时处理
// let bgMusic;
// let gameMusic;
let bgs = {
}
export const playBgMusic1 = (isOn, src) => {//待测试
for (let k in bgs) {
if (bgs[k].isOn) {
bgs[k].stop();
}
// bgs[k].isOn = false; /// TODO 自己记一个开关,因为淘宝的玩意stop之后虽然听不到,但还是在播放,会触发loop播放和onEnded事件
}
const key = src;
if (isOn) {
if (!bgs[key]) {
bgs[key] = createAudio({
src: src,
autoplay: true,
loop: false /// TODO 暂时无效?2020.08.12 目前有效,但stop后还会跑数据,导致到音频结束到时间又自动播放
});
bgs[key].onPlay(() => {
bgs[key].isOn = true;
});
bgs[key].onStop(() => {
bgs[key].isOn = false;
});
/// TODO监听结束,因为loop无效 2020.08.12 loop有效,这个操作是为了解决stop之后还会跑音频数据的问题
bgs[key].onEnded(() => {
if (bgs[key].isOn) { // 判断自己记录的开关
bgs[key].play();
// bgs[key].isOn = true;
}
});
bgs[key].play(); // 安卓有时候autoplay好像莫得用
// console.log(src)
// bgs[key].isOn = true; /// TODO 自己记一个开关,因为淘宝的玩意stop之后虽然听不到,但还是在播放,会触发loop播放和onEnded事件
} else {
bgs[key].play();
// bgs[key].isOn = true; /// TODO 自己记一个开关,因为淘宝的玩意stop之后虽然听不到,但还是在播放,会触发loop播放和onEnded事件
}
} else {
if (bgs[key]) {
// bgs[key].pause(); /// pause 垃圾,不能用
bgs[key].stop();
// bgs[key].isOn = false; /// TODO 自己记一个开关,因为淘宝的玩意stop之后虽然听不到,但还是在播放,会触发loop播放和onEnded事件
}
}
}
// TODO: 确认天猫是否也是9.3.0以下有问题
export const checkSystem = async ()=> {
const { version, app } = await getSystemInfo();
console.log('version', version);
return versionCompare(version, '9.3.0');
}
/**
* 获取淘宝用户收货地址
*/
export const getUserAddress = async (opts = {}) => {
let defaults = {
addAddress: 'show',
searchAddress: 'hide',
locateAddress: 'hide',
joinTag: '' // 分割收货地址符号(淘宝商家有特定发货需求)
};
const isValidVersion = await checkSystem();
if(!isValidVersion) {
commonToast('当前版本不支持选择收货地址,请升级到最新版本');
return;
}
let _opts = Object.assign({}, defaults, opts);
return new Promise((resolve, reject) => {
my.authorize({
scopes: 'scope.addressList',
success: () => {
const { addAddress, searchAddress, locateAddress, joinTag } = _opts;
if (!my.tb.chooseAddress) {
reject({ support: false, errorMessage: '当前版本不支持选择收货地址,请升级到最新版本' });
return false;
}
my.tb.chooseAddress({
addAddress,
searchAddress,
locateAddress
}, res => {
const { error, provinceName, countyName, cityName, streetName, detailInfo, name, telNumber } = res;
// 如果有error为用户取消操作不做操作
if (error) {
resolve(false);
} else {
resolve({
...res,
duibaAddress: {
name,
phone: telNumber,
address: [provinceName, cityName, countyName, streetName, detailInfo].join(joinTag)
}
});
}
}, res => {
reject(res);
})
},
});
});
};
/**
* 打开详情页
* @param {string} itemId
*/
export const openDetail = (itemId) => {
return new Promise((resolve, reject) => {
my.tb.openDetail({
itemId,
success: (res) => {
resolve(res)
},
fail: (res) => {
reject(res)
},
});
})
}
/**
* 自定义埋点的方法
* @param {string}} logkey
*/
export const reportAnalytics = (logkey) => {
my.reportAnalytics('click', {
// 标志某一类事件,方便数据分析进行分组
'logkey': logkey
})
}
\ No newline at end of file
......@@ -4,7 +4,6 @@ export default {
allowsBounceVertical: 'NO',
enableShareAppMessage: true,
usingComponents: {
'member-modal': '../../components/_miniprogram/memberModal/memberModal',
'lottie-modal': '../../components/_miniprogram/lottieBlank/lottieBlank'
'member-modal': '../../components/_miniprogram/memberModal/memberModal'
}
}
import React, { useState } from 'react'
import { View } from '@tarojs/components'
import { View, Image } from '@tarojs/components'
import Taro, { useShareAppMessage, useDidShow } from '@tarojs/taro'
import classnames from 'classnames'
import { SHARE_CONFIG } from '@/const.js'
import { useLogin, useLoginFromShare } from '@/hooks/useLogin'
import { useActivityInfoModel, useLoginInfoModel } from '@/store'
import API from '@/api'
import RuleModal from '@/components/RuleModal/RuleModal'
import DoHelpModal from '@/components/DoHelpModal/DoHelpModal'
import TasksModal from '@/components/TasksModal/TasksModal'
import CountDown from '@/components/CountDown/CountDown'
import RuleModal from '@/components/_tb_modal/RuleModal/RuleModal'
import DoHelpModal from '@/components/_tb_modal/DoHelpModal/DoHelpModal'
import TasksModal from '@/components/_tb_modal/TasksModal/TasksModal'
import CountDown from '@/components/_tb_comps/CountDown/CountDown'
import styles from './index.module.less'
import tbcc from 'tbcc-sdk-ts'
const { navigateTo } = tbcc.tb
const { getImgShareUrl } = tbcc.utils
import { useEffect } from 'react'
const { navigateTo, openDetail, showSharePanel } = tbcc.tb
const { getImgShareUrl, checkIsMember, validateActivityStatus } = tbcc.utils
const INDEX_CONFIG = {
bg: '', // 背景 cloud://C4015B7CEC23CF013A78247E2852524F//火箭待机小球抖动.json
......@@ -31,11 +32,17 @@ function Index() {
const [ doHelpModalVisible, setDoHelpModalVisible ] = useState(false)
const [ ruleModalVisible, setRuleModalVisible ] = useState(false)
const [ tasksModalVisible, setTasksModalVisible ] = useState(false)
const [updateFlag, setUpdateFlag] = useState(1)
const fetchActivityInfo = async() => {
const { success, data } = await API.getActivityBaseInfoById()
success && setActivityInfoAndStatus(data)
}
useEffect(() =>{
checkIsMember().then(isVip => {
console.warn(isVip)
})
})
// 授权登录完成
useLogin(async () => {
fetchActivityInfo()
......@@ -65,8 +72,14 @@ function Index() {
setMemberVisible(false)
}
const onShare = () => my.showSharePanel()
const onGoMyPrizePage = () => navigateTo('/pages/myPrize/myPrize')
const onShare = () => {
// console.warn(222)
showSharePanel()
// openDetail('652334795450')
}
const onGoMyPrizePage = () =>{
my.navigateTo({url: '/pages/packagePrize/myPrize/myPrize'})
}
const homeStyle = classnames(styles.container,{
[`${styles['content_fixed']}`]: ruleModalVisible
......@@ -83,12 +96,12 @@ function Index() {
{/* <View className={styles.countTime}>
<CountDown endTime={(Date.now() + 3 * 60 * 60 * 1000)} fontSize={'20rpx'} color={'#1B5F7F'} onUpdate={() => updateFlash()} />
</View> */}
{ true && <lottie-modal />}
{/* <Image src={testImg}></Image> */}
<View className={styles.rule} style={{ backgroundImage: `url(${INDEX_CONFIG.ruleButton})` }} onTap={() => setRuleModalVisible(true)}>活动规则</View>
<View className={styles.my_prize} style={{ backgroundImage: `url(${INDEX_CONFIG.myPrizeButton})` }} onTap={onGoMyPrizePage}>我的奖品</View>
<View className={styles.share} style={{ backgroundImage: `url(${INDEX_CONFIG.shareButton})` }} onTap={onShare}>分享</View>
<View className={styles.tasks} style={{ backgroundImage: `url(${INDEX_CONFIG.taskButton})` }} onTap={() => setTasksModalVisible(true)}>任务</View>
<View className={styles.games} style={{ backgroundImage: `url(${INDEX_CONFIG.taskButton})` }} onTap={() => navigateTo('/pages/games/games')}>游戏</View>
<View className={styles.games} style={{ backgroundImage: `url(${INDEX_CONFIG.taskButton})` }} onTap={() => navigateTo('/pages/packageGame/game/game')}>游戏</View>
<View className={styles.bemember} onTap={() => setMemberVisible(true)}>入会</View>
{
......
export default {
navigationBarTitleText: '游戏页面',
enableSkia: 'true',
allowsBounceVertical: 'NO',
enableShareAppMessage: true,
usingComponents: {
'member-modal': '../../../components/_miniprogram/memberModal/memberModal',
'canvas-comp': '../../../components/_miniprogram/lottieBlank/lottieBlank'
}
}
\ No newline at end of file
import React, { useEffect, useState, useRef } from 'react'
import { View, Canvas } from '@tarojs/components'
import { useDidShow, useRouter, useDidHide } from '@tarojs/taro'
import API from '@/api'
import { TASK_CONFIG } from '@/const'
import { useLogin, useLoginFromShare } from '@/hooks/useLogin'
import { useActivityInfoModel, useLoginInfoModel } from '@/store'
import {
commonToast,
getSystemInfo,
navigateToOutside,
navigateBack,
showSharePanel,
navigateTo,
openDetail
} from 'tbcc-sdk-ts/lib/core/tb'
import { versionCompare, getImgShareUrl } from 'tbcc-sdk-ts/lib/utils'
import styles from './game.module.less'
function GamePage(props) {
const { activityInfo, setActivityInfoAndStatus } = useActivityInfoModel()
const { loginInfo } = useLoginInfoModel()
const [canvasData,setCanvasData] = useState({})
const [ taskModalVisible, setTaskModalVisible] = useState(false)
const [ memberVisible,setMemberVisible] = useState(false)
const [updateFlag, setUpdateFlag] = useState(1)
const compRef = useRef(null)
useEffect(() =>{
// getImgShareUrl('cloud://2D60DC04FC1888AF6F865B88F0B2EBCC//share.png').then(res => {
// console.log(res)
// })
},[])
useDidShow(() =>{
// canvasMain.run();
})
useDidHide(() =>{
// canvasMain.pause();
})
//检查版本号
const checkSystem = async () => {
const { version } = await getSystemInfo();
console.log('version', version);
return versionCompare(version, '9.10.0');
}
const getAuth = () => {
console.log('getAuth')
}
const getUserAddress = () => {
}
const doFavorShop = () => {
console.log('doFavorShop')
}
//和main通信的方法,接收main的信息
const onMessage = (e)=> {
// 接口名字 参数
const { netName, parameter } = e.mpEvent.data
//定制的授权
if (netName == "mine.authorize") {
this.getAuth()
}
//获取地址
else if (netName == "mine.getUserAddress") {
this.getUserAddress(parameter.prizeId)
}
//关注店铺的操作
else if (netName == "mine.favorShop") {
this.doFavorShop()
}
//领养名字,有弹框的
else if (netName == "mine.getAdoptName") {
this.setData({ "adoptModalVisible": true, type: parameter.type })
}
//打开详情页,还有成功失败
else if (netName == "mine.openDetail") {
openDetail(parameter.itemId)
}
//前端同步接口
else if (netName.indexOf("mine") == 0) {
var data = { success: true }
switch (netName) {
case "mine.getAppData"://获取信息
data = {
success: true,
data: {
activityId: app.activityId,//|| "5e7c40e98564b57d7fb95812",
nickName: app.nickName,
avatar: app.avatar,
openId: app.openId,
inviteId: this.inviteId,//判断是否要发助力用
isFollow: app.isFollow,
needDataInCanvas:app.needDataInCanvas,
activityInfo:this.activityInfo,
userInfo:this.userInfo,
newUser: this.newUser,
remainTimes: this.remainTimes,
firstLoginToday: this.firstLoginToday,
}
}
break;
case "mine.navigateToOutside"://跳转小程序外的页面
navigateToOutside(parameter.url)
console.log(parameter.url)
break;
case "mine.navigateTo"://跳转小程序内的页面
navigateTo(parameter.url)
console.warn('navigateTo:'+parameter.url)
break;
case "mine.navigateBack"://返回页面
navigateBack()
break;
case "mine.showSharePanel"://分享
//多一个参数
showSharePanel()
break;
case "mine.reportAnalytics": ////淘宝自定义埋点
reportAnalytics(parameter.logkey);
break;
case "mine.openMusic": //音频
playBgMusic(parameter.isOn, this.musicUrl);
break;
case "mine.openTask": //打开任务
setTaskModalVisible(true)
break;
case "mine.openMember": //打开入会
setMemberVisible(true)
break;
}
} else {
//获取后端接口
const { function: fc } = app.cloud;
//处理下带上activityId
if (!parameter) parameter = {};
parameter.activityId = app.activityId;
//netName得分割下
fc.invoke(netName.split(".")[0], parameter, netName.split(".")[1])
.then(res => {
// console.log("返回数据" + JSON.stringify(res));
//发送消息
this.postMessage(netName, res || { success: false })
}, (err) => {
//网络异常,返回失败
this.postMessage(netName, { success: false })
})
}
}
const postMessageEvent = () => {
console.log('222222')
}
const onClose = () => {
console.warn(1111)
setMemberVisible(false)
}
const onAuthSuccess = () => {
setMemberVisible(false)
}
const onAuthFail = () => {
setMemberVisible(false)
}
const onTestHandle = () => {
setMemberVisible(true)
}
return(
<View>
{ true && <canvas-comp canvasData={canvasData} onPostMessage={onMessage} updateFlag={updateFlag} />}
<View className={styles['test-box']} onClick={(e) => onTestHandle(e)}>入会按钮</View>
{memberVisible && <member-modal onClose={onClose} onAuthFail={onAuthFail} onAuthSuccess={onAuthSuccess} />}
</View>
)
}
export default GamePage
\ No newline at end of file
.page-game {
width:100%;
height:100vh;
flex: 1;
display: flex;
flex-direction: column;
// background: #f5cccd;
}
.test-box {
position: absolute;
top: 200px;
width: 200px;
height: 50px;
background-color: aqua;
}
\ No newline at end of file
import React, { useEffect, useState } from 'react'
import { View } from '@tarojs/components'
import GoodsPage from '@/components/GoodsPage/GoodsPage'
import GoodsPage from '@/components/_tb_modal/GoodsPage/GoodsPage'
import { useDidShow, useRouter, useDidHide } from '@tarojs/taro'
import API from '@/api'
import { TASK_CONFIG } from '@/const'
......
import React, { useState, useEffect } from 'react'
import { View } from '@tarojs/components'
import GoodsPage from '@/components/GoodsPage/GoodsPage'
import GoodsPage from '@/components/_tb_modal/GoodsPage/GoodsPage'
import { useRouter } from '@tarojs/taro'
import tbccTs from 'tbcc-sdk-ts'
import API from '@/api'
......@@ -26,6 +26,8 @@ function CollectGoodsPage() {
const router = useRouter()
const [goodsList, setGoodsList] = useState([])
const { itemIds } = router?.params
// 收藏状态
const [collectflag, setCollectFlag ] = useState(false)
useEffect(() => {
getGoodsList()
......@@ -39,6 +41,7 @@ function CollectGoodsPage() {
const onCompleteTask = useThrottle(async(taskType, itemId) => {
const { success } = await API.doCompleteTask({ taskType, itemId })
if (success) {
setCollectFlag(true)
getGoodsList()
commonToast('收藏成功')
}
......@@ -46,7 +49,7 @@ function CollectGoodsPage() {
return (
<View>
<GoodsPage goodsList={goodsList} task={browseConfig} onCompleteTask={() => onCompleteTask} />
<GoodsPage goodsList={goodsList} collectFlag={collectflag} task={browseConfig} onCompleteTask={() => onCompleteTask} />
</View>
)
}
......
import React, { useEffect, useState } from 'react'
import { View } from '@tarojs/components'
import GoodsPage from '@/components/GoodsPage/GoodsPage'
import GoodsPage from '@/components/_tb_modal/GoodsPage/GoodsPage'
import { useRequest } from '@/hooks/useRequest'
import { useRouter } from '@tarojs/taro'
import API from '@/api'
......
......@@ -4,6 +4,6 @@ export default {
allowsBounceVertical: 'NO',
enableShareAppMessage: true,
usingComponents: {
'member-modal': '../../components/_miniprogram/memberModal/memberModal'
'member-modal': '../../../components/_miniprogram/memberModal/memberModal'
}
}
......@@ -2,15 +2,16 @@ import React, { useState, useEffect } from 'react'
import { Image, ScrollView, View } from '@tarojs/components'
import API from '@/api'
import { DRAW_STATUS, PRIZE_TYPE } from '@/const'
import DeliveryModal from '@/components/DeliveryModal/DeliveryModal'
import DeliveryModal from '@/components/_tb_modal/DeliveryModal/DeliveryModal'
import tbccTs from 'tbcc-sdk-ts'
import { useThrottle } from '@/hooks/useThrottle'
import { checkIsMember } from 'tbcc-sdk-ts/lib/utils'
import { dateFormatter } from '@/utils/date'
import './myPrize.less'
import { getApp } from '@tarojs/taro'
const { commonToast, getUserAddress, navigateToOutside, setClipboard } = tbccTs.tb
const { getMyPrizeList, receiveEnamePrize, receiveObjectPrize } = API
const { getMyPrizeList } = API
// 我的奖品配置项
const prizeConfig = {
......@@ -50,6 +51,7 @@ function Empty(blankTxt) {
}
function MyPrizeList() {
const app = getApp()
const [ myPrizeList, setMyPrizeList ] = useState([])
const [ expiredTime, setExpiredTime ] = useState('')
const [ currentPrize, setCurrentPrize ] = useState({})
......@@ -78,19 +80,19 @@ function MyPrizeList() {
// 优惠券
async function handleGetEquity(id) {
const { success, data } = await receiveEnamePrize({ id })
if (success && data) {
const { activityId } = app
const result = await API.Fn.receiveEnamePrize({ id, activityId })
if (result) {
commonToast('领取成功')
}
fetchMyPriceList()
}
// 领取实物
async function handleReceiveObjectPrize(params) {
const { success, data } = await receiveObjectPrize(params).catch(res => {
commonToast(res && res.message)
}) || {}
if (success && data) {
async function handleReceiveObjectPrize(id) {
const { activityId } = app
const result = await API.Fn.receiveObjectPrize({ id, activityId })
if (result) {
commonToast('领取成功')
}
fetchMyPriceList()
......@@ -104,11 +106,7 @@ function MyPrizeList() {
commonToast('需加入会员才能领取成功哦', 2000, () => { setMemberVisible(true) })
return
}
const { success, data } = await receiveEnamePrize({ id })
if (success && data) {
commonToast('领取成功')
}
fetchMyPriceList()
handleGetEquity(id)
}
// 领取实物前询问
......@@ -167,7 +165,7 @@ function MyPrizeList() {
const prizeId = id || _id
if (type === PRIZE_TYPE.ENAME) return handleGetEquity(prizeId)
// 领取实物
if (type === PRIZE_TYPE.OBJECT) return handleChooseAddress(prizeId)
if (type === PRIZE_TYPE.OBJECT) return handleReceiveObjectPrize(prizeId)
// 领取积分
if (type === PRIZE_TYPE.CREDITS) return handleGetCredits(prizeId)
}, 2000)
......
......@@ -9,3 +9,4 @@
@import "./text.less";
@import "./utils.less";
@import "./image.less";
@import "./page.less";
.page-container {
position: relative;
top: 0;
right: 0;
left: 0;
width: 100vw;
height: 100vh;
min-height: 100vh;
}
.page-container__content {
position: absolute;
width: 100vw;
height: 1624px;
left: 0;
right: 0;
top: 50%;
transform: translate(0,-50%);
}
\ No newline at end of file
export const noopFn = () => { }
export const createCanvas = async (canvasId) => {
return new Promise((resolve,reject) => {
my.createCanvas({
id: canvasId,
success: (ccc) => {
resolve(ccc)
}
})
})
}
......@@ -2027,6 +2027,11 @@
webpack-dev-server "3.11.0"
webpack-format-messages "2.0.3"
"@tbminiapp/lottie-miniapp@^0.0.4":
version "0.0.4"
resolved "https://registry.yarnpkg.com/@tbminiapp/lottie-miniapp/-/lottie-miniapp-0.0.4.tgz#60137da714d96b69b1ce60d043a6b9c1fe850391"
integrity sha512-CB3+1AG4uQ/Joq+U3kZcUA8UNUxnboZvzxqcLd2ieTR72sA/ZZO3BVepLvvjzJ2LIE0kjA+i+ZCu0NOOKVJDMw==
"@tbmp/mp-cloud-sdk@^1.4.2":
version "1.4.2"
resolved "http://npm.dui88.com:80/@tbmp%2fmp-cloud-sdk/-/mp-cloud-sdk-1.4.2.tgz#ff8f41b5d0da349e87f7e7fd0c304c3e0b7f05b4"
......@@ -7241,6 +7246,11 @@ functional-red-black-tree@^1.0.1:
resolved "http://npm.dui88.com:80/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327"
integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=
fyge@2.0.8:
version "2.0.8"
resolved "https://registry.yarnpkg.com/fyge/-/fyge-2.0.8.tgz#131aa5dd8b94d5a86c906f64f24e79b500eace87"
integrity sha512-Rd8KjdWLmYtdrbanc4MfgJv9C25Q6JQ/VyX4PRTtQ0Wu4JUpCr/HFswMAVkJJZLmn7bH+IBkR6hx8jE0aEVqVw==
gauge@~2.7.3:
version "2.7.4"
resolved "http://npm.dui88.com:80/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment