From 22c5b28d6415e444d68ecf60669a4a22691894e4 Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 16:56:50 +0800 Subject: [PATCH 001/272] =?UTF-8?q?chore(cli):=20=E5=90=84=E5=B0=8F?= =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=B9=B3=E5=8F=B0=E6=8F=92=E4=BB=B6=E6=8B=86?= =?UTF-8?q?=E4=B8=BA=E5=8D=95=E7=8B=AC=E7=9A=84=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lerna.json | 8 +- packages/taro-cli/package.json | 6 + packages/taro-cli/src/presets/index.ts | 15 +- .../taro-cli/src/presets/platforms/alipay.ts | 150 ----------- packages/taro-cli/src/presets/platforms/jd.ts | 64 ----- packages/taro-cli/src/presets/platforms/qq.ts | 73 ------ .../src/presets/platforms/quickapp.ts | 230 ----------------- packages/taro-cli/src/presets/platforms/rn.ts | 23 -- .../taro-cli/src/presets/platforms/swan.ts | 96 ------- packages/taro-cli/src/presets/platforms/tt.ts | 58 ----- packages/taro-cli/src/presets/platforms/ui.ts | 236 ------------------ .../taro-cli/src/presets/platforms/weapp.ts | 73 ------ 12 files changed, 19 insertions(+), 1013 deletions(-) delete mode 100644 packages/taro-cli/src/presets/platforms/alipay.ts delete mode 100644 packages/taro-cli/src/presets/platforms/jd.ts delete mode 100644 packages/taro-cli/src/presets/platforms/qq.ts delete mode 100644 packages/taro-cli/src/presets/platforms/quickapp.ts delete mode 100644 packages/taro-cli/src/presets/platforms/rn.ts delete mode 100644 packages/taro-cli/src/presets/platforms/swan.ts delete mode 100644 packages/taro-cli/src/presets/platforms/tt.ts delete mode 100644 packages/taro-cli/src/presets/platforms/ui.ts delete mode 100644 packages/taro-cli/src/presets/platforms/weapp.ts diff --git a/lerna.json b/lerna.json index 0fe2b422d8e6..851214c23997 100644 --- a/lerna.json +++ b/lerna.json @@ -24,7 +24,13 @@ "packages/taro-service", "packages/taro-webpack-runner", "packages/taro-with-weapp", - "packages/taroize" + "packages/taroize", + "packages/taro-weapp", + "packages/taro-alipay", + "packages/taro-swan", + "packages/taro-tt", + "packages/taro-qq", + "packages/taro-jd" ], "command": { "publish": { diff --git a/packages/taro-cli/package.json b/packages/taro-cli/package.json index 9430b22ae25f..71e81f19cb5b 100644 --- a/packages/taro-cli/package.json +++ b/packages/taro-cli/package.json @@ -45,6 +45,12 @@ "dependencies": { "@hapi/joi": "17.1.1", "@tarojs/helper": "3.0.9", + "@tarojs/plugin-platform-alipay": "3.0.9", + "@tarojs/plugin-platform-jd": "3.0.9", + "@tarojs/plugin-platform-qq": "3.0.9", + "@tarojs/plugin-platform-swan": "3.0.9", + "@tarojs/plugin-platform-tt": "3.0.9", + "@tarojs/plugin-platform-weapp": "3.0.9", "@tarojs/service": "3.0.9", "@tarojs/shared": "3.0.9", "@tarojs/taro": "3.0.9", diff --git a/packages/taro-cli/src/presets/index.ts b/packages/taro-cli/src/presets/index.ts index f8fb3ab470fc..72cf6e582a13 100644 --- a/packages/taro-cli/src/presets/index.ts +++ b/packages/taro-cli/src/presets/index.ts @@ -4,17 +4,14 @@ export default () => { return { plugins: [ // platforms - path.resolve(__dirname, 'platforms', 'weapp.js'), - path.resolve(__dirname, 'platforms', 'tt.js'), - path.resolve(__dirname, 'platforms', 'alipay.js'), - path.resolve(__dirname, 'platforms', 'swan.js'), - path.resolve(__dirname, 'platforms', 'jd.js'), - path.resolve(__dirname, 'platforms', 'qq.js'), - // path.resolve(__dirname, 'platforms', 'quickapp.js'), + require.resolve('@tarojs/plugin-platform-weapp'), + require.resolve('@tarojs/plugin-platform-alipay'), + require.resolve('@tarojs/plugin-platform-swan'), + require.resolve('@tarojs/plugin-platform-tt'), + require.resolve('@tarojs/plugin-platform-qq'), + require.resolve('@tarojs/plugin-platform-jd'), path.resolve(__dirname, 'platforms', 'h5.js'), - // path.resolve(__dirname, 'platforms', 'rn.js'), path.resolve(__dirname, 'platforms', 'plugin.js'), - // path.resolve(__dirname, 'platforms', 'ui.js'), // commands path.resolve(__dirname, 'commands', 'build.js'), diff --git a/packages/taro-cli/src/presets/platforms/alipay.ts b/packages/taro-cli/src/presets/platforms/alipay.ts deleted file mode 100644 index 69cad57ff383..000000000000 --- a/packages/taro-cli/src/presets/platforms/alipay.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { IPluginContext } from '@tarojs/service' -import { RecursiveTemplate, capitalize, toCamelCase } from '@tarojs/shared' -import { recursiveReplaceObjectKeys, printDevelopmentTip } from '../../util' - -export class Template extends RecursiveTemplate { - exportExpr = 'export default' - supportXS = true - Adapter = { - if: 'a:if', - else: 'a:else', - elseif: 'a:elif', - for: 'a:for', - forItem: 'a:for-item', - forIndex: 'a:for-index', - key: 'a:key', - xs: 'sjs', - type: 'alipay' - } - - buildXsTemplate () { - return '' - } - - replacePropName (name, value) { - if (value === 'eh') return name.replace('bind', 'on') - return name - } - - getEvents () { - return { - onTap: 'eh', - onTouchMove: 'eh', - onTouchEnd: 'eh', - onTouchCancel: 'eh', - onLongTap: 'eh' - } - } - - buildThirdPartyAttr (attrs: Set) { - return [...attrs].reduce((str, attr) => { - if (attr.startsWith('@')) { - return str + `on${capitalize(attr.slice(1))}="eh" ` - } else if (attr.startsWith('bind')) { - return str + `${attr}="eh" ` - } else if (attr.startsWith('on')) { - return str + `${attr}="eh" ` - } - - return str + `${attr}="{{ i.${toCamelCase(attr)} }}" ` - }, '') - } - - modifyCompProps = (compName: string, target: Record) => { - if (compName === 'canvas') { - return { - ...target, - width: '', - height: '' - } - } - return target - } - - modifyLoopBody = (child: string, nodeName: string) => { - if (nodeName === 'picker-view') { - return ` - - ${child} - - ` - } - if (nodeName === 'swiper') { - return ` - - ${child} - - ` - } - return child - } - - modifyLoopContainer = (children: string, nodeName: string) => { - if (nodeName === 'picker') { - return ` - ${children} - ` - } - return children - } - - modifyTemplateResult = (res: string, nodeName: string) => { - if (nodeName === 'picker-view-column' || nodeName === 'swiper-item') return '' - return res - } -} - -export default (ctx: IPluginContext) => { - ctx.registerPlatform({ - name: 'alipay', - useConfigName: 'mini', - async fn ({ config }) { - const { appPath, nodeModulesPath, outputPath } = ctx.paths - const { npm, emptyDirectory } = ctx.helper - emptyDirectory(outputPath) - - printDevelopmentTip('alipay') - - // 准备 miniRunner 参数 - const miniRunnerOpts = { - ...config, - nodeModulesPath, - buildAdapter: config.platform, - isBuildPlugin: false, - globalObject: 'my', - fileType: { - templ: '.axml', - style: '.acss', - config: '.json', - script: '.js', - xs: '.sjs' - }, - isUseComponentBuildPage: false, - template: new Template() - } - - ctx.modifyMiniConfigs(({ configMap }) => { - const replaceKeyMap = { - navigationBarTitleText: 'defaultTitle', - navigationBarBackgroundColor: 'titleBarColor', - enablePullDownRefresh: 'pullRefresh', - list: 'items', - text: 'name', - iconPath: 'icon', - selectedIconPath: 'activeIcon', - color: 'textColor' - } - Object.keys(configMap).forEach(key => { - const item = configMap[key] - if (item.content) { - recursiveReplaceObjectKeys(item.content, replaceKeyMap) - } - }) - }) - - // build with webpack - const miniRunner = await npm.getNpmPkg('@tarojs/mini-runner', appPath) - await miniRunner(appPath, miniRunnerOpts) - } - }) -} diff --git a/packages/taro-cli/src/presets/platforms/jd.ts b/packages/taro-cli/src/presets/platforms/jd.ts deleted file mode 100644 index 30660e8c8eec..000000000000 --- a/packages/taro-cli/src/presets/platforms/jd.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { IPluginContext } from '@tarojs/service' -import { UnRecursiveTemplate } from '@tarojs/shared' -import { printDevelopmentTip } from '../../util' - -export class Template extends UnRecursiveTemplate { - supportXS = false - Adapter = { - if: 'jd:if', - else: 'jd:else', - elseif: 'jd:elif', - for: 'jd:for', - forItem: 'jd:for-item', - forIndex: 'jd:for-index', - key: 'jd:key', - type: 'jd' - } - - replacePropName (name, value) { - if (name === 'bingdlongtap') return 'bindlongpress' - if (value === 'eh') return name.toLowerCase() - return name - } -} - -export default (ctx: IPluginContext) => { - ctx.registerPlatform({ - name: 'jd', - useConfigName: 'mini', - async fn ({ config }) { - const { appPath, nodeModulesPath, outputPath } = ctx.paths - const { npm, emptyDirectory } = ctx.helper - emptyDirectory(outputPath) - - printDevelopmentTip('jd') - - // 生成 project.config.json - ctx.generateProjectConfig({ - srcConfigName: 'project.jd.json', - distConfigName: 'project.config.json' - }) - - // 准备 miniRunner 参数 - const miniRunnerOpts = { - ...config, - nodeModulesPath, - buildAdapter: config.platform, - isBuildPlugin: false, - globalObject: 'jd', - fileType: { - templ: '.jxml', - style: '.jxss', - config: '.json', - script: '.js' - }, - isUseComponentBuildPage: false, - template: new Template() - } - - // build with webpack - const miniRunner = await npm.getNpmPkg('@tarojs/mini-runner', appPath) - await miniRunner(appPath, miniRunnerOpts) - } - }) -} diff --git a/packages/taro-cli/src/presets/platforms/qq.ts b/packages/taro-cli/src/presets/platforms/qq.ts deleted file mode 100644 index e215c5fa2c63..000000000000 --- a/packages/taro-cli/src/presets/platforms/qq.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { IPluginContext } from '@tarojs/service' -import { UnRecursiveTemplate } from '@tarojs/shared' -import { printDevelopmentTip } from '../../util' - -export class Template extends UnRecursiveTemplate { - supportXS = true - Adapter = { - if: 'qq:if', - else: 'qq:else', - elseif: 'qq:elif', - for: 'qq:for', - forItem: 'qq:for-item', - forIndex: 'qq:for-index', - key: 'qq:key', - xs: 'wxs', - type: 'qq' - } - - buildXsTemplate () { - return '' - } - - replacePropName (name: string, value: string, componentName: string) { - if (value === 'eh') { - const nameLowerCase = name.toLowerCase() - if (nameLowerCase === 'bindlongtap' && componentName !== 'canvas') return 'bindlongpress' - return nameLowerCase - } - return name - } -} - -export default (ctx: IPluginContext) => { - ctx.registerPlatform({ - name: 'qq', - useConfigName: 'mini', - async fn ({ config }) { - const { appPath, nodeModulesPath, outputPath } = ctx.paths - const { npm, emptyDirectory } = ctx.helper - emptyDirectory(outputPath) - - printDevelopmentTip('qq') - - // 生成 project.config.json - ctx.generateProjectConfig({ - srcConfigName: 'project.qq.json', - distConfigName: 'project.config.json' - }) - - // 准备 miniRunner 参数 - const miniRunnerOpts = { - ...config, - nodeModulesPath, - buildAdapter: config.platform, - isBuildPlugin: false, - globalObject: 'qq', - fileType: { - templ: '.qml', - style: '.qss', - config: '.json', - script: '.js', - xs: '.wxs' - }, - isUseComponentBuildPage: true, - template: new Template() - } - - // build with webpack - const miniRunner = await npm.getNpmPkg('@tarojs/mini-runner', appPath) - await miniRunner(appPath, miniRunnerOpts) - } - }) -} diff --git a/packages/taro-cli/src/presets/platforms/quickapp.ts b/packages/taro-cli/src/presets/platforms/quickapp.ts deleted file mode 100644 index ccc6cd4f3632..000000000000 --- a/packages/taro-cli/src/presets/platforms/quickapp.ts +++ /dev/null @@ -1,230 +0,0 @@ -import * as path from 'path' -import { execSync } from 'child_process' - -import { IPluginContext } from '@tarojs/service' -import * as ora from 'ora' - -import { - recursiveReplaceObjectKeys -} from '../../util' -import { downloadGithubRepoLatestRelease } from '../../util/dowload' -import * as defaultManifestJSON from '../../config/manifest.default.json' - -export default (ctx: IPluginContext) => { - ctx.registerPlatform({ - name: 'quickapp', - useConfigName: 'mini', - async fn ({ config }) { - const { appPath, nodeModulesPath } = ctx.paths - const { - isWatch, - port, - release - } = ctx.runOpts - const { - npm, - fs, - printLog, - processTypeEnum, - chalk, - shouldUseYarn, - isWindows, - shouldUseCnpm, - unzip - } = ctx.helper - - // 读取 project.quickapp.json - const quickappJSONPath = path.join(appPath, 'project.quickapp.json') - let quickappJSON - if (fs.existsSync(quickappJSONPath)) { - quickappJSON = fs.readJSONSync(quickappJSONPath) - } else { - printLog(processTypeEnum.WARNING, '缺少配置', `检测到项目目录下未添加 ${chalk.bold('project.quickapp.json')} 文件,将使用默认配置,参考文档 https://nervjs.github.io/taro/docs/project-config.html`) - quickappJSON = defaultManifestJSON - } - - const originalOutputRoot = config.outputRoot - config.outputRoot = `${originalOutputRoot}/src` - - // 准备 miniRunner 参数 - const miniRunnerOpts = { - ...config, - nodeModulesPath, - buildAdapter: config.platform, - isBuildPlugin: false, - globalObject: 'global', - fileType: { - templ: '.ux', - style: '.css', - config: '.json', - script: '.js' - }, - isUseComponentBuildPage: false, - quickappJSON, - isBuildQuickapp: true, - templateAdapter: { - if: 'if', - else: 'else', - elseif: 'elif', - for: 'for', - forItem: 'for-item', - forIndex: 'for-index', - key: 'key', - type: 'quickapp' - }, - isSupportRecursive: true, - isSupportXS: false - } - - ctx.modifyBuildTempFileContent(({ tempFiles }) => { - const replaceKeyMap = { - navigationBarTitleText: 'titleBarText', - navigationBarBackgroundColor: 'titleBarBackgroundColor', - navigationBarTextStyle: 'titleBarTextColor', - pageOrientation: 'orientation', - backgroundTextStyle: false, - onReachBottomDistance: false, - backgroundColorBottom: false, - backgroundColorTop: false - } - Object.keys(tempFiles).forEach(key => { - const item = tempFiles[key] - if (item.config) { - recursiveReplaceObjectKeys(item.config, replaceKeyMap) - } - }) - }) - - // build with webpack - const miniRunner = await npm.getNpmPkg('@tarojs/mini-runner', appPath) - await miniRunner(appPath, miniRunnerOpts) - - const isReady = await prepareQuickAppEnvironment({ - originalOutputRoot, - fs, - appPath, - chalk, - shouldUseYarn, - isWindows, - shouldUseCnpm, - unzip - }) - if (!isReady) { - console.log() - console.log(chalk.red('快应用环境准备失败,请重试!')) - process.exit(0) - } - await runQuickApp({ - isWatch, - originalOutputRoot, - port, - release - }) - } - }) -} - -async function prepareQuickAppEnvironment ({ - originalOutputRoot, - fs, - appPath, - chalk, - shouldUseYarn, - isWindows, - shouldUseCnpm, - unzip -}) { - let isReady = false - let needDownload = false - let needInstall = false - console.log() - if (fs.existsSync(path.join(originalOutputRoot, 'sign'))) { - needDownload = false - } else { - needDownload = true - } - if (needDownload) { - const getSpinner = ora('开始下载快应用运行容器...').start() - await downloadGithubRepoLatestRelease('NervJS/quickapp-container', appPath, originalOutputRoot) - await unzip(path.join(originalOutputRoot, 'download_temp.zip')) - getSpinner.succeed('快应用运行容器下载完成') - } else { - console.log(`${chalk.green('✔ ')} 快应用容器已经准备好`) - } - process.chdir(originalOutputRoot) - console.log() - if (fs.existsSync(path.join(originalOutputRoot, 'node_modules'))) { - needInstall = false - } else { - needInstall = true - } - if (needInstall) { - let command - if (shouldUseYarn()) { - if (!isWindows) { - command = 'NODE_ENV=development yarn install' - } else { - command = 'yarn install' - } - } else if (shouldUseCnpm()) { - if (!isWindows) { - command = 'NODE_ENV=development cnpm install' - } else { - command = 'cnpm install' - } - } else { - if (!isWindows) { - command = 'NODE_ENV=development npm install' - } else { - command = 'npm install' - } - } - const installSpinner = ora('安装快应用依赖环境, 需要一会儿...').start() - try { - const stdout = execSync(command) - installSpinner.color = 'green' - installSpinner.succeed('安装成功') - console.log(`${stdout}`) - isReady = true - } catch (error) { - installSpinner.color = 'red' - installSpinner.fail(chalk.red(`快应用依赖环境安装失败,请进入 ${path.basename(originalOutputRoot)} 重新安装!`)) - console.log(`${error}`) - isReady = false - } - } else { - console.log(`${chalk.green('✔ ')} 快应用依赖已经安装好`) - isReady = true - } - return isReady -} - -async function runQuickApp ({ - isWatch, - originalOutputRoot, - port, - release -}: { - isWatch: boolean | void, - originalOutputRoot: string, - port?: number, - release?: boolean -}) { - const { compile } = require(require.resolve('hap-toolkit/lib/commands/compile', { paths: [originalOutputRoot] })) - if (isWatch) { - const { launchServer } = require(require.resolve('@hap-toolkit/server', { paths: [originalOutputRoot] })) - launchServer({ - port: port || 12306, - watch: isWatch, - clearRecords: false, - disableADB: false - }) - compile('native', 'dev', true) - } else { - if (!release) { - compile('native', 'dev', false) - } else { - compile('native', 'prod', false) - } - } -} diff --git a/packages/taro-cli/src/presets/platforms/rn.ts b/packages/taro-cli/src/presets/platforms/rn.ts deleted file mode 100644 index 514787dde0cf..000000000000 --- a/packages/taro-cli/src/presets/platforms/rn.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { IPluginContext } from '@tarojs/service' - -export default (ctx: IPluginContext) => { - ctx.registerPlatform({ - name: 'rn', - useConfigName: 'rn', - async fn ({ config }) { - const { appPath, outputPath } = ctx.paths - const { isWatch, port } = ctx.runOpts - const { emptyDirectory } = ctx.helper - const { modifyWebpackChain, modifyBuildAssets, onBuildFinish } = config - emptyDirectory(outputPath) - require('../../rn').build(appPath, { - watch: isWatch, - port - }, { - modifyWebpackChain, - modifyBuildAssets, - onBuildFinish - }) - } - }) -} diff --git a/packages/taro-cli/src/presets/platforms/swan.ts b/packages/taro-cli/src/presets/platforms/swan.ts deleted file mode 100644 index 2dc417485933..000000000000 --- a/packages/taro-cli/src/presets/platforms/swan.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { IPluginContext } from '@tarojs/service' -import { RecursiveTemplate, isArray, Shortcuts } from '@tarojs/shared' -import { printDevelopmentTip } from '../../util' - -const swanSpecialAttrs = { - 'scroll-view': ['scrollTop', 'scrollLeft', 'scrollIntoView'], - 'movable-view': ['x', 'y'], - slider: ['value'], - input: ['value'], - textarea: ['value'] -} - -export class Template extends RecursiveTemplate { - supportXS = true - Adapter = { - if: 's-if', - else: 's-else', - elseif: 's-elif', - for: 's-for', - forItem: 's-for-item', - forIndex: 's-for-index', - key: 's-key', - xs: 'sjs', - type: 'swan' - } - - buildXsTemplate () { - return '' - } - - dataKeymap (keymap: string) { - return `{ ${keymap} }` - } - - getAttrValue (value: string, key: string, nodeName: string) { - if (isArray(swanSpecialAttrs[nodeName]) && swanSpecialAttrs[nodeName].includes(key)) { - return `= ${value} =` - } - - return `{ ${value} }` - } - - modifyLoopBody = (child: string, nodeName: string) => { - if (nodeName === 'text') { - return `{{ i.${Shortcuts.Childnodes}[index].${Shortcuts.Text} }}` - } - - return child - } -} - -export default (ctx: IPluginContext) => { - ctx.registerPlatform({ - name: 'swan', - useConfigName: 'mini', - async fn ({ config }) { - const { appPath, nodeModulesPath, outputPath } = ctx.paths - const { npm, emptyDirectory } = ctx.helper - emptyDirectory(outputPath) - - // ctx.generateFrameworkInfo({ - // platform: config.platform - // }) - - printDevelopmentTip('swan') - - // 生成 project.swan.json - ctx.generateProjectConfig({ - srcConfigName: 'project.swan.json', - distConfigName: 'project.swan.json' - }) - - // 准备 miniRunner 参数 - const miniRunnerOpts = { - ...config, - nodeModulesPath, - buildAdapter: config.platform, - isBuildPlugin: false, - globalObject: 'swan', - fileType: { - templ: '.swan', - style: '.css', - config: '.json', - script: '.js', - xs: '.sjs' - }, - isUseComponentBuildPage: true, - template: new Template() - } - - // build with webpack - const miniRunner = await npm.getNpmPkg('@tarojs/mini-runner', appPath) - await miniRunner(appPath, miniRunnerOpts) - } - }) -} diff --git a/packages/taro-cli/src/presets/platforms/tt.ts b/packages/taro-cli/src/presets/platforms/tt.ts deleted file mode 100644 index d0df3e0377ba..000000000000 --- a/packages/taro-cli/src/presets/platforms/tt.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { IPluginContext } from '@tarojs/service' -import { RecursiveTemplate } from '@tarojs/shared' -import { printDevelopmentTip } from '../../util' - -export class Template extends RecursiveTemplate { - supportXS = false - Adapter = { - if: 'tt:if', - else: 'tt:else', - elseif: 'tt:elif', - for: 'tt:for', - forItem: 'tt:for-item', - forIndex: 'tt:for-index', - key: 'tt:key', - type: 'tt' - } -} - -export default (ctx: IPluginContext) => { - ctx.registerPlatform({ - name: 'tt', - useConfigName: 'mini', - async fn ({ config }) { - const { appPath, nodeModulesPath, outputPath } = ctx.paths - const { npm, emptyDirectory } = ctx.helper - emptyDirectory(outputPath) - - printDevelopmentTip('tt') - - // 生成 project.config.json - ctx.generateProjectConfig({ - srcConfigName: 'project.tt.json', - distConfigName: 'project.config.json' - }) - - // 准备 miniRunner 参数 - const miniRunnerOpts = { - ...config, - nodeModulesPath, - buildAdapter: config.platform, - isBuildPlugin: false, - globalObject: 'tt', - fileType: { - templ: '.ttml', - style: '.ttss', - config: '.json', - script: '.js' - }, - isUseComponentBuildPage: false, - template: new Template() - } - - // build with webpack - const miniRunner = await npm.getNpmPkg('@tarojs/mini-runner', appPath) - await miniRunner(appPath, miniRunnerOpts) - } - }) -} diff --git a/packages/taro-cli/src/presets/platforms/ui.ts b/packages/taro-cli/src/presets/platforms/ui.ts deleted file mode 100644 index 0146c4c0e0e2..000000000000 --- a/packages/taro-cli/src/presets/platforms/ui.ts +++ /dev/null @@ -1,236 +0,0 @@ -import * as path from 'path' - -import * as _ from 'lodash' -import { IPluginContext } from '@tarojs/service' - -export default (ctx: IPluginContext) => { - ctx.registerPlatform({ - name: 'ui', - async fn () { - const { - H5_OUTPUT_NAME, - RN_OUTPUT_NAME, - TEMP_DIR, - RN_TEMP_DIR, - WEAPP_OUTPUT_NAME, - QUICKAPP_OUTPUT_NAME, - copyFileToDist, - analyzeStyleFilesImport, - analyzeFiles - } = require('../../ui/common') - const { Compiler } = require('../../h5') - const { buildH5Script, buildForH5 } = require('../../ui/h5') - const { buildForRN } = require('../../ui/rn') - const { buildForWeapp } = require('../../ui/weapp') - const { buildForQuickapp } = require('../../ui/quickapp') - const { Compiler: RNCompiler } = require('../../rn_bak') - - const { uiIndex, isWatch } = ctx.runOpts - const { appPath, sourcePath } = ctx.paths - const { chalk, fs, resolveScriptPath, printLog, REG_STYLE, processTypeEnum, PLATFORMS, chokidar } = ctx.helper - const projectConfig = ctx.initialConfig - let entryFilePath - if (uiIndex) { - entryFilePath = resolveScriptPath(path.join(sourcePath, uiIndex)) - } else { - entryFilePath = resolveScriptPath(path.join(sourcePath, 'index')) - } - const buildData = { - appPath, - projectConfig, - sourceDirName: projectConfig.sourceRoot, - outputDirName: projectConfig.outputRoot, - sourceDir: sourcePath, - entryFilePath, - entryFileName: path.basename(entryFilePath), - tempPath: path.join(appPath, TEMP_DIR), - rnTempPath: path.join(appPath, RN_TEMP_DIR) - } - - function buildEntry (uiIndex) { - const { appPath, outputDirName } = buildData - let indexName = 'index' - if (uiIndex) { - indexName = path.basename(uiIndex, path.extname(uiIndex)) - } - - let content = '' - platforms.forEach((item, index) => { - let dir: any = item - if (item !== PLATFORMS.H5 && item !== PLATFORMS.RN && item !== PLATFORMS.QUICKAPP) { - dir = WEAPP_OUTPUT_NAME - } - content += `if (process.env.TARO_ENV === '${item}') { - module.exports = require('./${dir}/${indexName}') - module.exports.default = module.exports - }` - if (index < platforms.length - 1) { - content += ' else ' - } else { - content += ` else { - module.exports = require('./${WEAPP_OUTPUT_NAME}/${indexName}') - module.exports.default = module.exports - }` - } - }) - - const outputDir = path.join(appPath, outputDirName!) - fs.writeFileSync(path.join(outputDir, 'index.js'), content) - } - - function watchFiles () { - const { sourceDir, projectConfig, appPath, outputDirName, tempPath } = buildData - const platforms = _.get(buildData, 'projectConfig.ui.platforms') - console.log('\n', chalk.gray('监听文件修改中...'), '\n') - - const watchList = [sourceDir] - - const uiConfig = projectConfig.ui - let extraWatchFiles - if (uiConfig && Array.isArray(uiConfig.extraWatchFiles)) { - extraWatchFiles = uiConfig.extraWatchFiles - extraWatchFiles.forEach(item => { - watchList.push(path.join(appPath, item.path)) - if (typeof item.handler === 'function') item.callback = item.handler({ buildH5Script }) - }) - } - - const watcher = chokidar.watch(watchList, { - ignored: /(^|[/\\])\../, - ignoreInitial: true - }) - - function syncWeappFile (filePath) { - const outputDir = path.join(appPath, outputDirName!, WEAPP_OUTPUT_NAME) - copyFileToDist(filePath, sourceDir, outputDir, buildData) - // 依赖分析 - const extname = path.extname(filePath) - if (REG_STYLE.test(extname)) { - analyzeStyleFilesImport([filePath], sourceDir, outputDir, buildData) - } else { - analyzeFiles([filePath], sourceDir, outputDir, buildData) - } - } - - function syncQuickappFile (filePath) { - const outputDir = path.join(appPath, outputDirName!, QUICKAPP_OUTPUT_NAME) - copyFileToDist(filePath, sourceDir, outputDir, buildData) - // 依赖分析 - const extname = path.extname(filePath) - if (REG_STYLE.test(extname)) { - analyzeStyleFilesImport([filePath], sourceDir, outputDir, buildData) - } else { - analyzeFiles([filePath], sourceDir, outputDir, buildData) - } - } - - function syncH5File (filePath, compiler) { - const { sourceDir, appPath, outputDirName, tempPath } = buildData - const outputDir = path.join(appPath, outputDirName!, H5_OUTPUT_NAME) - let fileTempPath = filePath.replace(sourceDir, tempPath) - fileTempPath = fileTempPath.replace(new RegExp(`${path.extname(fileTempPath)}$`), '') - fileTempPath = resolveScriptPath(fileTempPath) - compiler.processFiles(filePath) - - if (process.env.TARO_BUILD_TYPE === 'script') { - buildH5Script(buildData) - } else { - copyFileToDist(fileTempPath, tempPath, outputDir, buildData) - // 依赖分析 - const extname = path.extname(filePath) - if (REG_STYLE.test(extname)) { - analyzeStyleFilesImport([fileTempPath], tempPath, outputDir, buildData) - } else { - analyzeFiles([fileTempPath], tempPath, outputDir, buildData) - } - } - } - - function syncRNFile (filePath, compiler) { - const { sourceDir, appPath, outputDirName, rnTempPath } = buildData - const outputDir = path.join(appPath, outputDirName!, RN_OUTPUT_NAME) - const fileTempPath = filePath.replace(sourceDir, rnTempPath) - compiler.processFiles(filePath) - - copyFileToDist(fileTempPath, tempPath, outputDir, buildData) - // 依赖分析 - const extname = path.extname(filePath) - if (REG_STYLE.test(extname)) { - analyzeStyleFilesImport([fileTempPath], tempPath, outputDir, buildData) - } else { - analyzeFiles([fileTempPath], tempPath, outputDir, buildData) - } - } - - function handleChange (filePath, type, tips) { - const relativePath = path.relative(appPath, filePath) - const compiler = new Compiler(appPath) - const rnCompiler = new RNCompiler(appPath) - printLog(type, tips, relativePath) - - let processed = false - extraWatchFiles && extraWatchFiles.forEach(item => { - if (filePath.indexOf(item.path.substr(2)) < 0) return - if (typeof item.callback === 'function') { - item.callback() - processed = true - } - }) - if (processed) return - - try { - if (platforms && Array.isArray(platforms)) { - platforms.includes(PLATFORMS.WEAPP) && syncWeappFile(filePath) - platforms.includes(PLATFORMS.QUICKAPP) && syncQuickappFile(filePath) - platforms.includes(PLATFORMS.H5) && syncH5File(filePath, compiler) - platforms.includes(PLATFORMS.RN) && syncRNFile(filePath, rnCompiler) - } else { - syncWeappFile(filePath) - syncH5File(filePath, compiler) - } - } catch (err) { - console.log(err) - } - } - - watcher - .on('add', filePath => handleChange(filePath, processTypeEnum.CREATE, '添加文件')) - .on('change', filePath => handleChange(filePath, processTypeEnum.MODIFY, '文件变动')) - .on('unlink', filePath => { - for (const path in extraWatchFiles) { - if (filePath.indexOf(path.substr(2)) > -1) return - } - - const relativePath = path.relative(appPath, filePath) - printLog(processTypeEnum.UNLINK, '删除文件', relativePath) - const weappOutputPath = path.join(appPath, outputDirName!, WEAPP_OUTPUT_NAME) - const quickappOutputPath = path.join(appPath, outputDirName!, QUICKAPP_OUTPUT_NAME) - const h5OutputPath = path.join(appPath, outputDirName!, H5_OUTPUT_NAME) - const fileTempPath = filePath.replace(sourceDir, tempPath) - const fileWeappPath = filePath.replace(sourceDir, weappOutputPath) - const fileQuickappPath = filePath.replace(sourceDir, quickappOutputPath) - const fileH5Path = filePath.replace(sourceDir, h5OutputPath) - fs.existsSync(fileTempPath) && fs.unlinkSync(fileTempPath) - fs.existsSync(fileWeappPath) && fs.unlinkSync(fileWeappPath) - fs.existsSync(fileQuickappPath) && fs.unlinkSync(fileQuickappPath) - fs.existsSync(fileH5Path) && fs.unlinkSync(fileH5Path) - }) - } - - const platforms = _.get(buildData, 'projectConfig.ui.platforms') || [PLATFORMS.WEAPP, PLATFORMS.H5] - buildEntry(uiIndex) - if (platforms && Array.isArray(platforms)) { - platforms.includes(PLATFORMS.WEAPP) && await buildForWeapp(buildData) - platforms.includes(PLATFORMS.QUICKAPP) && await buildForQuickapp(buildData) - platforms.includes(PLATFORMS.H5) && await buildForH5(uiIndex, buildData) - platforms.includes(PLATFORMS.RN) && await buildForRN(uiIndex, buildData) - } else { - await buildForWeapp(buildData) - await buildForH5(uiIndex, buildData) - } - if (isWatch) { - watchFiles() - } - } - }) -} diff --git a/packages/taro-cli/src/presets/platforms/weapp.ts b/packages/taro-cli/src/presets/platforms/weapp.ts deleted file mode 100644 index 32ead8ac0e1e..000000000000 --- a/packages/taro-cli/src/presets/platforms/weapp.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { IPluginContext } from '@tarojs/service' -import { UnRecursiveTemplate } from '@tarojs/shared' -import { printDevelopmentTip } from '../../util' - -export class Template extends UnRecursiveTemplate { - supportXS = true - Adapter = { - if: 'wx:if', - else: 'wx:else', - elseif: 'wx:elif', - for: 'wx:for', - forItem: 'wx:for-item', - forIndex: 'wx:for-index', - key: 'wx:key', - xs: 'wxs', - type: 'weapp' - } - - buildXsTemplate () { - return '' - } - - replacePropName (name: string, value: string, componentName: string) { - if (value === 'eh') { - const nameLowerCase = name.toLowerCase() - if (nameLowerCase === 'bindlongtap' && componentName !== 'canvas') return 'bindlongpress' - return nameLowerCase - } - return name - } -} - -export default (ctx: IPluginContext) => { - ctx.registerPlatform({ - name: 'weapp', - useConfigName: 'mini', - async fn ({ config }) { - const { appPath, nodeModulesPath, outputPath } = ctx.paths - const { npm, emptyDirectory } = ctx.helper - emptyDirectory(outputPath) - - printDevelopmentTip('weapp') - - // 生成 project.config.json - ctx.generateProjectConfig({ - srcConfigName: 'project.config.json', - distConfigName: 'project.config.json' - }) - - // 准备 miniRunner 参数 - const miniRunnerOpts = { - ...config, - nodeModulesPath, - buildAdapter: config.platform, - isBuildPlugin: false, - globalObject: 'wx', - fileType: { - templ: '.wxml', - style: '.wxss', - config: '.json', - script: '.js', - xs: '.wxs' - }, - isUseComponentBuildPage: true, - template: new Template() - } - - // build with webpack - const miniRunner = await npm.getNpmPkg('@tarojs/mini-runner', appPath) - await miniRunner(appPath, miniRunnerOpts) - } - }) -} From 875a7e3af26c8b527245f556cfd82c795c0259ee Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 16:59:07 +0800 Subject: [PATCH 002/272] =?UTF-8?q?chore(shared):=20=E6=8A=BD=E5=8F=96?= =?UTF-8?q?=E5=87=BA=E5=B0=8F=E7=A8=8B=E5=BA=8F=E5=B9=B3=E5=8F=B0=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E7=9A=84=E5=9F=BA=E7=B1=BB=EF=BC=8C=E6=94=BE=E5=9C=A8?= =?UTF-8?q?=20shared=20=E5=8C=85=E9=87=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/shared/package.json | 3 + packages/shared/rollup.config.js | 6 +- packages/shared/src/index.ts | 1 + packages/shared/src/platform-plugin-base.ts | 115 ++++++++++++++++++++ packages/taro-cli/src/util/index.ts | 32 ------ 5 files changed, 124 insertions(+), 33 deletions(-) create mode 100644 packages/shared/src/platform-plugin-base.ts diff --git a/packages/shared/package.json b/packages/shared/package.json index a96453def1b4..02fe0c3b31e6 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -24,5 +24,8 @@ }, "publishConfig": { "access": "public" + }, + "dependencies": { + "@tarojs/service": "3.0.9" } } diff --git a/packages/shared/rollup.config.js b/packages/shared/rollup.config.js index b2e93ba9fb79..79b297f0141a 100644 --- a/packages/shared/rollup.config.js +++ b/packages/shared/rollup.config.js @@ -22,7 +22,11 @@ const baseConfig = { } } }), - buble() + buble({ + transforms: { + asyncAwait: false + } + }) ] } const esmConfig = Object.assign({}, baseConfig, { diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 9c2c4cfa33c4..e739883c4fc0 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -3,3 +3,4 @@ export { Shortcuts } from './shortcuts' export * from './components' export * from './utils' export * from './template' +export * from './platform-plugin-base' diff --git a/packages/shared/src/platform-plugin-base.ts b/packages/shared/src/platform-plugin-base.ts new file mode 100644 index 000000000000..13e7c663a020 --- /dev/null +++ b/packages/shared/src/platform-plugin-base.ts @@ -0,0 +1,115 @@ +import type { IPluginContext } from '@tarojs/service' +import type { RecursiveTemplate, UnRecursiveTemplate } from './template' + +interface IFileType { + templ: string + style: string + config: string + script: string + xs?: string +} + +export class TaroPlatformBase { + ctx: IPluginContext + helper: IPluginContext['helper'] + config: any + platform: string + globalObject: string + fileType: IFileType + template: RecursiveTemplate | UnRecursiveTemplate + + constructor (ctx: IPluginContext, config) { + this.ctx = ctx + this.helper = ctx.helper + this.config = config + } + + /** + * 1. 清空 dist 文件夹 + * 2. 输出提示 + */ + setup () { + this.emptyOutputDir() + this.printDevelopmentTip(this.platform) + } + + emptyOutputDir () { + const { outputPath } = this.ctx.paths + this.helper.emptyDirectory(outputPath) + } + + printDevelopmentTip (platform: string) { + if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') return + + const { isWindows, chalk } = this.helper + let exampleCommand + + if (isWindows) { + exampleCommand = `$ set NODE_ENV=production && taro build --type ${platform} --watch` + } else { + exampleCommand = `$ NODE_ENV=production taro build --type ${platform} --watch` + } + + console.log(chalk.yellowBright(`Tips: 预览模式生成的文件较大,设置 NODE_ENV 为 production 可以开启压缩。 +Example: +${exampleCommand} +`)) + } + + /** + * 返回当前项目内的 @tarojs/mini-runner 包 + */ + async getRunner () { + const { appPath } = this.ctx.paths + const { npm } = this.helper + const runner = await npm.getNpmPkg('@tarojs/mini-runner', appPath) + return runner.bind(null, appPath) + } + + /** + * 准备 mini-runner 参数 + */ + getBaseOptions () { + const { ctx, config, globalObject, fileType, template } = this + + return { + ...config, + nodeModulesPath: ctx.paths.nodeModulesPath, + buildAdapter: config.platform, + globalObject, + fileType, + template + } + } + + /** + * 生成 project.config.json + * @param src 项目源码中配置文件的名称 + * @param dist 编译后配置文件的名称,默认为 'project.config.json' + */ + generateProjectConfig (src: string, dist = 'project.config.json') { + this.ctx.generateProjectConfig({ + srcConfigName: src, + distConfigName: dist + }) + } + + /** + * 递归替换对象的 key 值 + */ + recursiveReplaceObjectKeys (obj, keyMap) { + Object.keys(obj).forEach(key => { + if (keyMap[key]) { + obj[keyMap[key]] = obj[key] + if (typeof obj[key] === 'object') { + this.recursiveReplaceObjectKeys(obj[keyMap[key]], keyMap) + } + delete obj[key] + } else if (keyMap[key] === false) { + delete obj[key] + } else if (typeof obj[key] === 'object') { + this.recursiveReplaceObjectKeys(obj[key], keyMap) + } + }) + } +} diff --git a/packages/taro-cli/src/util/index.ts b/packages/taro-cli/src/util/index.ts index a9f2062c89ab..fddcd754a93d 100644 --- a/packages/taro-cli/src/util/index.ts +++ b/packages/taro-cli/src/util/index.ts @@ -1,6 +1,5 @@ import * as fs from 'fs-extra' import * as path from 'path' -import { isWindows, chalk } from '@tarojs/helper' export function getRootPath (): string { return path.resolve(__dirname, '../../') @@ -75,34 +74,3 @@ export function readDirWithFileTypes (floder: string): FileStat[] { }) return res } - -export function recursiveReplaceObjectKeys (obj, keyMap) { - Object.keys(obj).forEach(key => { - if (keyMap[key]) { - obj[keyMap[key]] = obj[key] - if (typeof obj[key] === 'object') { - recursiveReplaceObjectKeys(obj[keyMap[key]], keyMap) - } - delete obj[key] - } else if (keyMap[key] === false) { - delete obj[key] - } else if (typeof obj[key] === 'object') { - recursiveReplaceObjectKeys(obj[key], keyMap) - } - }) -} - -export function printDevelopmentTip (platform: string) { - if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') { - let exampleCommand - if (isWindows) { - exampleCommand = `$ set NODE_ENV=production && taro build --type ${platform} --watch` - } else { - exampleCommand = `$ NODE_ENV=production taro build --type ${platform} --watch` - } - console.log(chalk.yellowBright(`Tips: 预览模式生成的文件较大,设置 NODE_ENV 为 production 可以开启压缩。 -Example: -${exampleCommand} -`)) - } -} From b33630379752e63adbc9cfd4c3430ed18b1910ab Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 17:04:47 +0800 Subject: [PATCH 003/272] =?UTF-8?q?chore(shared):=20=E6=8B=86=E8=A7=A3?= =?UTF-8?q?=E5=87=BA=E6=89=80=E6=9C=89=E5=B0=8F=E7=A8=8B=E5=BA=8F=E5=85=B1?= =?UTF-8?q?=E6=9C=89=E7=9A=84=E7=BB=84=E4=BB=B6=E5=8F=8A=E5=85=B6=E5=B1=9E?= =?UTF-8?q?=E6=80=A7=E5=88=97=E8=A1=A8=EF=BC=8C=E4=B8=94=E5=8F=AF=E8=A2=AB?= =?UTF-8?q?=E5=A4=96=E9=83=A8=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/shared/src/components.ts | 343 ++++++------------------------ packages/shared/src/template.ts | 58 ++--- 2 files changed, 84 insertions(+), 317 deletions(-) diff --git a/packages/shared/src/components.ts b/packages/shared/src/components.ts index 853bb2fbc7dd..b766a2753796 100644 --- a/packages/shared/src/components.ts +++ b/packages/shared/src/components.ts @@ -9,7 +9,7 @@ export const events = { bindtap: 'eh' } -const touchEvents = { +export const touchEvents = { bindTouchStart: '', bindTouchMove: '', bindTouchEnd: '', @@ -17,6 +17,13 @@ const touchEvents = { bindLongTap: '' } +export const animationEvents = { + bindAnimationStart: '', + bindAnimationIteration: '', + bindAnimationEnd: '', + bindTransitionEnd: '' +} + export const specialEvents = new Set([ 'htouchmove', 'vtouchmove' @@ -32,11 +39,8 @@ const View = { 'hover-start-time': '50', 'hover-stay-time': '400', animation: '', - bindAnimationStart: '', - bindAnimationIteration: '', - bindAnimationEnd: '', - bindTransitionEnd: '', - ...touchEvents + ...touchEvents, + ...animationEvents } const Icon = { @@ -45,7 +49,7 @@ const Icon = { color: '' } -const Map = { +const MapComp = { longitude: '', latitude: '', scale: '16', @@ -53,52 +57,30 @@ const Map = { covers: '', polyline: '[]', circles: '[]', - controls: '', + controls: '[]', 'include-points': '[]', 'show-location': '', - polygons: '', - subkey: '', 'layer-style': '1', - rotate: '0', - skew: 'skew', - 'enable-3D': 'false', - 'show-compass': 'false', - 'show-scale': 'false', - 'enable-overlooking': 'false', - 'enable-zoom': 'true', - 'enable-scroll': 'true', - 'enable-rotate': 'false', - 'enable-satellite': 'false', - 'enable-traffic': 'false', - setting: '[]', bindMarkerTap: '', - bindLabelTap: '', bindControlTap: '', bindCalloutTap: '', bindUpdated: '', - bindRegionChange: '', - bindPoiTap: '', ...touchEvents } const Progress = { percent: '', - 'show-info': 'false', - 'border-radius': '0', - 'font-size': '16', 'stroke-width': '6', color: singleQuote('#09BB07'), activeColor: singleQuote('#09BB07'), backgroundColor: singleQuote('#EBEBEB'), active: 'false', 'active-mode': singleQuote('backwards'), - duration: '30', - bindActiveEnd: '' + 'show-info': 'false' } const RichText = { - nodes: '[]', - space: '' + nodes: '[]' } const Text = { @@ -119,30 +101,9 @@ const Button = { 'hover-stop-propagation': 'false', 'hover-start-time': '20', 'hover-stay-time': '70', - lang: 'en', - 'session-from': '', - 'send-message-title': '', - 'send-message-path': '', - 'send-message-img': '', - 'app-parameter': '', - 'show-message-card': 'false', - bindGetUserInfo: '', - bindGetAuthorize: '', - bindContact: '', - bindGetPhoneNumber: '', - bindError: '', - bindOpenSetting: '', - bindLaunchApp: '', - scope: '', name: '' } -if (process.env.TARO_ENV === 'qq') { - Button['app-packagename'] = '' - Button['app-bundleid'] = '' - Button['app-connect-id'] = '' -} - const Checkbox = { value: '', disabled: '', @@ -156,24 +117,8 @@ const CheckboxGroup = { name: '' } -const Editor = { - 'read-only': 'false', - placeholder: '', - 'show-img-size': 'false', - 'show-img-toolbar': 'false', - 'show-img-resize': 'false', - focus: 'false', - bindReady: '', - bindFocus: '', - bindBlur: '', - bindInput: '', - bindStatusChange: '', - name: '' -} - const Form = { 'report-submit': 'false', - 'report-submit-timeout': '0', bindSubmit: '', bindReset: '', name: '' @@ -189,20 +134,16 @@ const Input = { disabled: '', maxlength: '140', 'cursor-spacing': '0', - 'auto-focus': 'false', focus: 'false', 'confirm-type': singleQuote('done'), 'confirm-hold': 'false', cursor: 'i.value.length', 'selection-start': '-1', 'selection-end': '-1', - 'adjust-position': 'true', - 'hold-keyboard': 'false', bindInput: '', bindFocus: '', bindBlur: '', bindConfirm: '', - bindKeyboardHeightChange: '', name: '' } @@ -214,17 +155,17 @@ const Label = { const Picker = { mode: singleQuote('selector'), disabled: '', - bindCancel: '', range: '', 'range-key': '', value: '', - bindChange: '', - bindColumnChange: '', start: '', end: '', fields: singleQuote('day'), 'custom-item': '', - name: '' + name: '', + bindCancel: '', + bindChange: '', + bindColumnChange: '' } const PickerView = { @@ -234,8 +175,6 @@ const PickerView = { 'mask-style': '', 'mask-class': '', bindChange: '', - bindPickStart: '', - bindPickEnd: '', name: '' } @@ -262,8 +201,6 @@ const Slider = { step: '1', disabled: '', value: '0', - color: singleQuote('#e9e9e9'), - 'selected-color': singleQuote('#1aad19'), activeColor: singleQuote('#1aad19'), backgroundColor: singleQuote('#e9e9e9'), 'block-size': '28', @@ -283,12 +220,6 @@ const Switch = { name: '' } -const CoverImage = { - src: '', - bindLoad: 'eh', - bindError: 'eh' -} - const Textarea = { value: '', placeholder: '', @@ -302,35 +233,27 @@ const Textarea = { fixed: 'false', 'cursor-spacing': '0', cursor: '-1', - 'show-confirm-bar': 'true', 'selection-start': '-1', 'selection-end': '-1', - 'adjust-position': 'true', - 'hold-keyboard': 'false', bindFocus: '', bindBlur: '', bindLineChange: '', bindInput: '', bindConfirm: '', - bindKeyboardHeightChange: '', name: '' } +const CoverImage = { + src: '', + bindLoad: 'eh', + bindError: 'eh' +} + const CoverView = { 'scroll-top': 'false', ...touchEvents } -const MatchMedia = { - 'min-width': '', - 'max-width': '', - width: '', - 'min-height': '', - 'max-height': '', - height: '', - orientation: '' -} - const MovableArea = { 'scale-area': 'false' } @@ -349,14 +272,14 @@ const MovableView = { 'scale-max': '10', 'scale-value': '1', animation: 'true', - bindAnimationEnd: '', bindChange: '', bindScale: '', htouchmove: '', vtouchmove: '', width: singleQuote('10px'), height: singleQuote('10px'), - ...touchEvents + ...touchEvents, + ...animationEvents } const ScrollView = { @@ -369,34 +292,11 @@ const ScrollView = { 'scroll-into-view': '', 'scroll-with-animation': 'false', 'enable-back-to-top': 'false', - 'enable-flex': 'false', - 'scroll-anchoring': 'false', - 'refresher-enabled': 'false', - 'refresher-threshold': '45', - 'refresher-default-style': singleQuote('black'), - 'refresher-background': singleQuote('#FFF'), - 'refresher-triggered': 'false', - enhanced: 'false', - bounces: 'true', - 'show-scrollbar': 'true', - 'paging-enabled': 'false', - 'fast-deceleration': 'false', - bindRefresherPulling: '', - bindRefresherRefresh: '', - bindRefresherRestore: '', - bindRefresherAbort: '', bindScrollToUpper: '', bindScrollToLower: '', bindScroll: '', - animation: '', - bindTransitionEnd: '', - bindAnimationStart: '', - bindAnimationIteration: '', - bindAnimationEnd: '', - bindDragStart: '', - bindDragging: '', - bindDragEnd: '', - ...touchEvents + ...touchEvents, + ...animationEvents } const Swiper = { @@ -412,8 +312,6 @@ const Swiper = { 'previous-margin': '\'0px\'', 'next-margin': '\'0px\'', 'display-multiple-items': '1', - 'skip-hidden-item-layout': 'false', - 'easing-function': singleQuote('default'), bindChange: '', bindTransition: '', bindAnimationFinish: '', @@ -424,24 +322,10 @@ const SwiperItem = { 'item-id': '' } -const FunctionalPageNavigator = { - version: singleQuote('release'), - name: '', - args: '', - bindSuccess: '', - bindFail: '', - bindCancel: '' -} - const Navigator = { - target: singleQuote('self'), url: '', 'open-type': singleQuote('navigate'), delta: '1', - 'app-id': '', - path: '', - 'extra-data': '', - version: singleQuote('version'), 'hover-class': singleQuote('navigator-hover'), 'hover-stop-propagation': 'false', 'hover-start-time': '50', @@ -467,22 +351,16 @@ const Audio = { } const Camera = { - mode: singleQuote('normal'), 'device-position': singleQuote('back'), flash: singleQuote('auto'), - 'frame-size': singleQuote('medium'), bindStop: '', - bindError: '', - bindInitDone: '', - bindScanCode: '' + bindError: '' } const Image = { src: '', mode: singleQuote('scaleToFill'), - webp: 'false', 'lazy-load': 'false', - 'show-menu-by-longpress': 'false', bindError: '', bindLoad: '', ...touchEvents @@ -490,7 +368,6 @@ const Image = { const LivePlayer = { src: '', - mode: singleQuote('live'), autoplay: 'false', muted: 'false', orientation: singleQuote('vertical'), @@ -498,54 +375,10 @@ const LivePlayer = { 'background-mute': 'false', 'min-cache': '1', 'max-cache': '3', - 'sound-mode': singleQuote('speaker'), - 'auto-pause-if-navigate': 'true', - 'auto-pause-if-open-native': 'true', - 'picture-in-picture-mode': '[]', animation: '', bindStateChange: '', bindFullScreenChange: '', - bindNetStatus: '', - bindAudioVolumeNotify: '', - bindEnterPictureInPicture: '', - bindLeavePictureInPicture: '' -} - -const LivePusher = { - url: '', - mode: singleQuote('RTC'), - autopush: 'false', - muted: 'false', - 'enable-camera': 'true', - 'auto-focus': 'true', - orientation: singleQuote('vertical'), - beauty: '0', - whiteness: '0', - aspect: singleQuote('9:16'), - 'min-bitrate': '200', - 'max-bitrate': '1000', - 'audio-quality': singleQuote('high'), - 'waiting-image': '', - 'waiting-image-hash': '', - zoom: 'false', - 'device-position': singleQuote('front'), - 'background-mute': 'false', - mirror: 'false', - 'remote-mirror': 'false', - 'local-mirror': 'false', - 'audio-reverb-type': '0', - 'enable-mic': 'true', - 'enable-agc': 'false', - 'enable-ans': 'false', - 'audio-volume-type': singleQuote('voicecall'), - 'video-width': '360', - 'video-height': '640', - animation: '', - bindStateChange: '', - bindNetStatus: '', - bindBgmStart: '', - bindBgmProgress: '', - bindBgmComplete: '' + bindNetStatus: '' } const Video = { @@ -569,24 +402,6 @@ const Video = { 'object-fit': singleQuote('contain'), poster: '', 'show-mute-btn': 'false', - title: '', - 'play-btn-position': singleQuote('bottom'), - 'enable-play-gesture': 'false', - 'auto-pause-if-navigate': 'true', - 'auto-pause-if-open-native': 'true', - 'vslide-gesture': 'false', - 'vslide-gesture-in-fullscreen': 'true', - 'ad-unit-id': '', - 'poster-for-crawler': '', - 'show-casting-button': 'false', - 'picture-in-picture-mode': '[]', - // picture-in-picture-show-progress 属性先注释掉的原因如下: - // 该属性超过了 wxml 属性的长度限制,实际无法使用且导致编译报错。可等微信官方修复后再放开。 - // 参考1:https://developers.weixin.qq.com/community/develop/doc/000a429beb87f0eac07acc0fc5b400 - // 参考2: https://developers.weixin.qq.com/community/develop/doc/0006883619c48054286a4308258c00?_at=vyxqpllafi - // 'picture-in-picture-show-progress': 'false', - 'enable-auto-rotation': 'false', - 'show-screen-lock-button': 'false', animation: '', bindPlay: '', bindPause: '', @@ -594,78 +409,29 @@ const Video = { bindTimeUpdate: '', bindFullScreenChange: '', bindWaiting: '', - bindError: '', - bindProgress: '', - bindLoadedMetadata: '', - bindControlsToggle: '', - bindEnterPictureInPicture: '', - bindLeavePictureInPicture: '', - bindSeekComplete: '' + bindError: '' } const Canvas = { - type: '', 'canvas-id': '', 'disable-scroll': 'false', - bindTouchStart: '', - bindTouchMove: '', - bindTouchEnd: '', - bindTouchCancel: '', - bindLongtap: '', - bindError: '' + bindError: '', + ...touchEvents } const Ad = { 'unit-id': '', 'ad-intervals': '', - 'ad-type': singleQuote('banner'), - 'ad-theme': singleQuote('white'), bindLoad: '', bindError: '', bindClose: '' } -const OfficialAccount = { - bindLoad: '', - bindError: '' -} - -const OpenData = { - type: '', - 'open-gid': '', - lang: singleQuote('en'), - 'default-text': '', - 'default-avatar': '', - bindError: '' -} - const WebView = { src: '', bindMessage: '', - bindLoad: '' -} - -const NavigationBar = { - title: '', - loading: 'false', - 'front-color': '', - 'background-color': '', - 'color-animation-duration': '0', - 'color-animation-timing-func': singleQuote('linear') -} - -const PageMeta = { - 'background-text-style': '', - 'background-color': '', - 'background-color-top': '', - 'background-color-bottom': '', - 'scroll-top': singleQuote(''), - 'scroll-duration': '300', - 'page-style': singleQuote(''), - 'root-font-size': singleQuote(''), - bindResize: '', - bindScroll: '', - bindScrollDone: '' + bindLoad: '', + bindError: '' } const Block = {} @@ -692,7 +458,6 @@ export const internalComponents = { Button, Checkbox, CheckboxGroup, - Editor, Form, Input, Label, @@ -706,29 +471,22 @@ export const internalComponents = { CoverImage, Textarea, CoverView, - MatchMedia, MovableArea, MovableView, ScrollView, Swiper, SwiperItem, - FunctionalPageNavigator, Navigator, Audio, Camera, Image, LivePlayer, - LivePusher, Video, Canvas, Ad, - OfficialAccount, - OpenData, WebView, - NavigationBar, - PageMeta, Block, - Map, + Map: MapComp, Slot, SlotView } @@ -749,3 +507,32 @@ export const focusComponents = new Set([ 'textarea', 'editor' ]) + +export const voidElements = new Set([ + 'progress', + 'icon', + 'rich-text', + 'input', + 'textarea', + 'slider', + 'switch', + 'audio', + 'live-pusher', + 'video', + 'ad', + 'official-account', + 'open-data', + 'navigation-bar' +]) + +export const nestElements = new Map([ + ['view', -1], + ['cover-view', -1], + ['block', -1], + ['text', -1], + ['slot', 8], + ['slot-view', 8], + ['label', 6], + ['form', 4], + ['scroll-view', 4] +]) diff --git a/packages/shared/src/template.ts b/packages/shared/src/template.ts index 2b507500dae0..43b6ed3c87ca 100644 --- a/packages/shared/src/template.ts +++ b/packages/shared/src/template.ts @@ -15,6 +15,8 @@ import { internalComponents, focusComponents, + voidElements, + nestElements, styles, events, specialEvents, @@ -54,36 +56,6 @@ export interface IAdapter { export type Attributes = Record -const voidElements = new Set([ - 'progress', - 'icon', - 'rich-text', - 'input', - 'textarea', - 'slider', - 'switch', - 'audio', - 'live-player', - 'live-pusher', - 'video', - 'ad', - 'official-account', - 'open-data', - 'navigation-bar' -]) - -const nestElements = new Map([ - ['view', -1], - ['cover-view', -1], - ['block', -1], - ['text', -1], - ['slot', 8], - ['slot-view', 8], - ['label', 6], - ['form', 4], - ['scroll-view', 4] -]) - const weixinAdapter: IAdapter = { if: 'wx:if', else: 'wx:else', @@ -107,6 +79,14 @@ export class BaseTemplate { protected modifyTemplateResult?: (res: string, nodeName: string, level: number, children: string) => string public Adapter = weixinAdapter + /** 组件列表 */ + public internalComponents: Record> = internalComponents + /** 可以 focus 聚焦的组件 */ + public focusComponents: Set = focusComponents + /** 不需要渲染子节点的元素 */ + public voidElements: Set = voidElements + /** 可以递归调用自身的组件 */ + public nestElements: Map = nestElements private buildAttribute (attrs: Attributes, nodeName: string): string { return Object.keys(attrs) @@ -204,7 +184,7 @@ export class BaseTemplate { } protected buildComponentTemplate (comp: Component, level: number) { - return focusComponents.has(comp.nodeName) + return this.focusComponents.has(comp.nodeName) ? this.buildFocusComponentTemplte(comp, level) : this.buildStandardComponentTemplate(comp, level) } @@ -246,7 +226,7 @@ export class BaseTemplate { child = this.modifyLoopBody(child, comp.nodeName) } - let children = voidElements.has(comp.nodeName) + let children = this.voidElements.has(comp.nodeName) ? '' : ` @@ -402,7 +382,7 @@ export class RecursiveTemplate extends BaseTemplate { public buildTemplate = (componentConfig: ComponentConfig) => { let template = this.buildBaseTemplate() if (!this.miniComponents) { - this.miniComponents = this.createMiniComponents(internalComponents) + this.miniComponents = this.createMiniComponents(this.internalComponents) } const ZERO_FLOOR = 0 const components = Object.keys(this.miniComponents) @@ -437,7 +417,7 @@ export class UnRecursiveTemplate extends BaseTemplate { public buildTemplate = (componentConfig: ComponentConfig) => { this.componentConfig = componentConfig if (!this.miniComponents) { - this.miniComponents = this.createMiniComponents(internalComponents) + this.miniComponents = this.createMiniComponents(this.internalComponents) } const components = Object.keys(this.miniComponents) .filter(c => componentConfig.includes.size && !componentConfig.includeAll ? componentConfig.includes.has(c) : true) @@ -472,12 +452,12 @@ export class UnRecursiveTemplate extends BaseTemplate { let template = components.reduce((current, nodeName) => { if (level !== 0) { - if (!nestElements.has(nodeName)) { + if (!this.nestElements.has(nodeName)) { // 不可嵌套自身的组件只需输出一层模板 return current } else { // 部分可嵌套自身的组件实际上不会嵌套过深,这里按阈值限制层数 - const max = nestElements.get(nodeName)! + const max = this.nestElements.get(nodeName)! if (max > 0 && level >= max) { return current } @@ -496,11 +476,11 @@ export class UnRecursiveTemplate extends BaseTemplate { protected buildXSTmplName () { const comps = [ - ...Array.from(nestElements.keys()), + ...Array.from(this.nestElements.keys()), ...Array.from(this.componentConfig.thirdPartyComponents.keys()) ] const hasMaxComps: string[] = [] - nestElements.forEach((max, comp) => { + this.nestElements.forEach((max, comp) => { if (max > -1) hasMaxComps.push(comp) }) return `function (l, n, s) { @@ -523,7 +503,7 @@ export class UnRecursiveTemplate extends BaseTemplate { protected buildXSTmpExtra () { const hasMaxComps: string[] = [] - nestElements.forEach((max, comp) => { + this.nestElements.forEach((max, comp) => { if (max > -1) hasMaxComps.push(comp) }) return `f: function (l, n) { From 1516f889018dc47b391e586fe29d0f64a103f644 Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 17:06:58 +0800 Subject: [PATCH 004/272] =?UTF-8?q?chore(components):=20=E6=AD=A4=E5=8C=85?= =?UTF-8?q?=E7=9A=84React=E7=BB=84=E4=BB=B6=E5=85=A5=E5=8F=A3=E7=B2=BE?= =?UTF-8?q?=E7=AE=80=E5=87=BA=E5=85=AC=E5=85=B1=E7=BB=84=E4=BB=B6=EF=BC=8C?= =?UTF-8?q?=E5=8F=AF=E7=94=B1=E5=A4=96=E9=83=A8=E6=8F=92=E4=BB=B6=E6=8B=93?= =?UTF-8?q?=E5=B1=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/taro-components/mini/index.js | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/packages/taro-components/mini/index.js b/packages/taro-components/mini/index.js index ce815e6c9294..d697370ffdf9 100644 --- a/packages/taro-components/mini/index.js +++ b/packages/taro-components/mini/index.js @@ -6,7 +6,6 @@ export const Text = 'text' export const Button = 'button' export const Checkbox = 'checkbox' export const CheckboxGroup = 'checkbox-group' -export const Editor = 'editor' export const Form = 'form' export const Input = 'input' export const Label = 'label' @@ -20,29 +19,20 @@ export const Switch = 'switch' export const CoverImage = 'cover-image' export const Textarea = 'textarea' export const CoverView = 'cover-view' -export const MatchMedia = 'match-media' -export const MoveableArea = 'moveable-area' -export const MoveableView = 'moveable-view' +export const MovableArea = 'movable-area' +export const MovableView = 'movable-view' export const ScrollView = 'scroll-view' export const Swiper = 'swiper' export const SwiperItem = 'swiper-item' -export const FunctionalPageNavigator = 'functional-page-navigator' export const Navigator = 'navigator' export const Audio = 'audio' export const Camera = 'camera' export const Image = 'image' export const LivePlayer = 'live-player' -export const LivePusher = 'live-pusher' export const Video = 'video' -export const Map = 'map' export const Canvas = 'canvas' export const Ad = 'ad' -export const OfficialAccount = 'official-account' -export const OpenData = 'open-data' export const WebView = 'web-view' -export const NavigationBar = 'navigation-bar' -export const PageMeta = 'page-meta' export const Block = 'block' -export const MovableArea = 'movable-area' -export const MovableView = 'movable-view' +export const Map = 'map' export const Slot = 'slot' From 4c3a660ed5e5b529cb0f22b75d4763644145837c Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 17:10:43 +0800 Subject: [PATCH 005/272] =?UTF-8?q?chore(mini-runner):=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=20options=20=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 为 isBuildPlugin 提供默认值,小程序平台插件可选是否传入此参数 2. 删除过去版本遗留的 isUseComponentBuildPage 配置的类型定义 --- packages/taro-mini-runner/src/utils/types.ts | 1 - .../taro-mini-runner/src/webpack/build.conf.ts | 17 +++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/taro-mini-runner/src/utils/types.ts b/packages/taro-mini-runner/src/utils/types.ts index 0bb8be5d5ad7..5b9c562ba26f 100644 --- a/packages/taro-mini-runner/src/utils/types.ts +++ b/packages/taro-mini-runner/src/utils/types.ts @@ -50,7 +50,6 @@ export interface IBuildConfig extends IProjectBaseConfig, IMiniAppConfig { fileType: IFileType, isSupportXS: boolean, globalObject: string, - isUseComponentBuildPage: boolean, modifyWebpackChain: Function, modifyBuildAssets: Function, modifyMiniConfigs: Function, diff --git a/packages/taro-mini-runner/src/webpack/build.conf.ts b/packages/taro-mini-runner/src/webpack/build.conf.ts index b04b8926612f..119a5c5994ed 100644 --- a/packages/taro-mini-runner/src/webpack/build.conf.ts +++ b/packages/taro-mini-runner/src/webpack/build.conf.ts @@ -38,6 +38,7 @@ export default (appPath: string, mode, config: Partial): any => { globalObject = 'wx', outputRoot = 'dist', sourceRoot = 'src', + isBuildPlugin = false, designWidth = 750, deviceRatio, @@ -82,7 +83,7 @@ export default (appPath: string, mode, config: Partial): any => { const sourceDir = path.join(appPath, sourceRoot) const outputDir = path.join(appPath, outputRoot) const taroBaseReg = /@tarojs[\\/][a-z]+/ - if (config.isBuildPlugin) { + if (isBuildPlugin) { const patterns = copy ? copy.patterns : [] patterns.push({ from: path.join(sourceRoot, 'plugin', 'doc'), @@ -119,9 +120,9 @@ export default (appPath: string, mode, config: Partial): any => { const entryRes = getEntry({ sourceDir, entry, - isBuildPlugin: config.isBuildPlugin + isBuildPlugin }) - const defaultCommonChunks = config.isBuildPlugin + const defaultCommonChunks = isBuildPlugin ? ['plugin/runtime', 'plugin/vendors', 'plugin/taro', 'plugin/common'] : ['runtime', 'vendors', 'taro', 'common'] let customCommonChunks = defaultCommonChunks @@ -142,7 +143,7 @@ export default (appPath: string, mode, config: Partial): any => { quickappJSON, designWidth, pluginConfig: entryRes!.pluginConfig, - isBuildPlugin: !!config.isBuildPlugin, + isBuildPlugin: Boolean(isBuildPlugin), commonChunks: customCommonChunks, baseLevel, framework, @@ -222,7 +223,7 @@ export default (appPath: string, mode, config: Partial): any => { usedExports: true, minimizer, runtimeChunk: { - name: config.isBuildPlugin ? 'plugin/runtime' : 'runtime' + name: isBuildPlugin ? 'plugin/runtime' : 'runtime' }, splitChunks: { chunks: 'all', @@ -230,12 +231,12 @@ export default (appPath: string, mode, config: Partial): any => { minSize: 0, cacheGroups: { common: { - name: config.isBuildPlugin ? 'plugin/common' : 'common', + name: isBuildPlugin ? 'plugin/common' : 'common', minChunks: 2, priority: 1 }, vendors: { - name: config.isBuildPlugin ? 'plugin/vendors' : 'vendors', + name: isBuildPlugin ? 'plugin/vendors' : 'vendors', minChunks: 2, test: module => { return /[\\/]node_modules[\\/]/.test(module.resource) @@ -243,7 +244,7 @@ export default (appPath: string, mode, config: Partial): any => { priority: 10 }, taro: { - name: config.isBuildPlugin ? 'plugin/taro' : 'taro', + name: isBuildPlugin ? 'plugin/taro' : 'taro', test: module => { return taroBaseReg.test(module.context) }, From 4525715c74829176c73d7d2a563696e7f887a232 Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 17:11:30 +0800 Subject: [PATCH 006/272] =?UTF-8?q?chore(taro-weapp):=20=E5=88=86=E7=A6=BB?= =?UTF-8?q?=E5=87=BA=20weapp=20=E5=B9=B3=E5=8F=B0=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/taro-weapp/README.md | 3 + packages/taro-weapp/index.js | 3 + packages/taro-weapp/package.json | 33 ++ packages/taro-weapp/src/components-react.ts | 49 +++ packages/taro-weapp/src/components.ts | 281 ++++++++++++++++++ packages/taro-weapp/src/index.ts | 16 + packages/taro-weapp/src/program.ts | 54 ++++ packages/taro-weapp/src/runtime.ts | 3 + packages/taro-weapp/src/template.ts | 29 ++ packages/taro-weapp/tsconfig.json | 27 ++ .../taro-weapp/types/components-react.d.ts | 48 +++ packages/taro-weapp/types/components.d.ts | 272 +++++++++++++++++ packages/taro-weapp/types/index.d.ts | 5 + packages/taro-weapp/types/program.d.ts | 27 ++ packages/taro-weapp/types/runtime.d.ts | 1 + packages/taro-weapp/types/template.d.ts | 17 ++ 16 files changed, 868 insertions(+) create mode 100644 packages/taro-weapp/README.md create mode 100644 packages/taro-weapp/index.js create mode 100644 packages/taro-weapp/package.json create mode 100644 packages/taro-weapp/src/components-react.ts create mode 100644 packages/taro-weapp/src/components.ts create mode 100644 packages/taro-weapp/src/index.ts create mode 100644 packages/taro-weapp/src/program.ts create mode 100644 packages/taro-weapp/src/runtime.ts create mode 100644 packages/taro-weapp/src/template.ts create mode 100644 packages/taro-weapp/tsconfig.json create mode 100644 packages/taro-weapp/types/components-react.d.ts create mode 100644 packages/taro-weapp/types/components.d.ts create mode 100644 packages/taro-weapp/types/index.d.ts create mode 100644 packages/taro-weapp/types/program.d.ts create mode 100644 packages/taro-weapp/types/runtime.d.ts create mode 100644 packages/taro-weapp/types/template.d.ts diff --git a/packages/taro-weapp/README.md b/packages/taro-weapp/README.md new file mode 100644 index 000000000000..ad12c19e46c0 --- /dev/null +++ b/packages/taro-weapp/README.md @@ -0,0 +1,3 @@ +# `@tarojs/plugin-platform-weapp` + +Taro 插件。用于支持编译为微信小程序。 diff --git a/packages/taro-weapp/index.js b/packages/taro-weapp/index.js new file mode 100644 index 000000000000..771c0c5fed4c --- /dev/null +++ b/packages/taro-weapp/index.js @@ -0,0 +1,3 @@ +module.exports = require('./dist/index.js').default +module.exports.default = module.exports +module.exports.Weapp = require('./dist/index.js').Weapp diff --git a/packages/taro-weapp/package.json b/packages/taro-weapp/package.json new file mode 100644 index 000000000000..d1aa4c6af8a2 --- /dev/null +++ b/packages/taro-weapp/package.json @@ -0,0 +1,33 @@ +{ + "name": "@tarojs/plugin-platform-weapp", + "version": "3.0.9", + "description": "微信小程序平台插件", + "author": "Chen-jj", + "homepage": "https://github.com/nervjs/taro/tree/master/packages/taro-weapp#readme", + "license": "MIT", + "main": "index.js", + "keywords": [ + "taro" + ], + "files": [ + "index.js", + "dist", + "types" + ], + "types": "types/index.d.ts", + "repository": { + "type": "git", + "url": "git+https://github.com/NervJS/taro.git" + }, + "scripts": { + "build": "tsc", + "dev": "tsc -w" + }, + "bugs": { + "url": "https://github.com/NervJS/taro/issues" + }, + "dependencies": { + "@tarojs/service": "3.0.9", + "@tarojs/shared": "3.0.9" + } +} diff --git a/packages/taro-weapp/src/components-react.ts b/packages/taro-weapp/src/components-react.ts new file mode 100644 index 000000000000..41ec393b74a8 --- /dev/null +++ b/packages/taro-weapp/src/components-react.ts @@ -0,0 +1,49 @@ +// For React.createElement's type +export const View = 'view' +export const Icon = 'icon' +export const Progress = 'progress' +export const RichText = 'rich-text' +export const Text = 'text' +export const Button = 'button' +export const Checkbox = 'checkbox' +export const CheckboxGroup = 'checkbox-group' +export const Form = 'form' +export const Input = 'input' +export const Label = 'label' +export const Picker = 'picker' +export const PickerView = 'picker-view' +export const PickerViewColumn = 'picker-view-column' +export const Radio = 'radio' +export const RadioGroup = 'radio-group' +export const Slider = 'slider' +export const Switch = 'switch' +export const CoverImage = 'cover-image' +export const Textarea = 'textarea' +export const CoverView = 'cover-view' +export const MovableArea = 'movable-area' +export const MovableView = 'movable-view' +export const ScrollView = 'scroll-view' +export const Swiper = 'swiper' +export const SwiperItem = 'swiper-item' +export const Navigator = 'navigator' +export const Audio = 'audio' +export const Camera = 'camera' +export const Image = 'image' +export const LivePlayer = 'live-player' +export const Video = 'video' +export const Canvas = 'canvas' +export const Ad = 'ad' +export const WebView = 'web-view' +export const Block = 'block' +export const Map = 'map' +export const Slot = 'slot' +export const Editor = 'editor' +export const MatchMedia = 'match-media' +export const FunctionalPageNavigator = 'functional-page-navigator' +export const LivePusher = 'live-pusher' +export const OfficialAccount = 'official-account' +export const OpenData = 'open-data' +export const NavigationBar = 'navigation-bar' +export const PageMeta = 'page-meta' +export const VoipRoom = 'voip-room' +export const AdCustom = 'ad-custom' diff --git a/packages/taro-weapp/src/components.ts b/packages/taro-weapp/src/components.ts new file mode 100644 index 000000000000..06627fd1e3e0 --- /dev/null +++ b/packages/taro-weapp/src/components.ts @@ -0,0 +1,281 @@ +import { singleQuote } from '@tarojs/shared' + +export const components = { + // ======== 调整属性 ======== + Progress: { + 'border-radius': '0', + 'font-size': '16', + duration: '30', + bindActiveEnd: '' + }, + RichText: { + space: '' + }, + Text: { + 'user-select': 'false' + }, + Map: { + polygons: '[]', + subkey: '', + rotate: '0', + skew: '0', + 'enable-3D': 'false', + 'show-compass': 'false', + 'show-scale': 'false', + 'enable-overlooking': 'false', + 'enable-zoom': 'true', + 'enable-scroll': 'true', + 'enable-rotate': 'false', + 'enable-satellite': 'false', + 'enable-traffic': 'false', + setting: '[]', + bindLabelTap: '', + bindRegionChange: '', + bindPoiTap: '' + }, + Button: { + lang: 'en', + 'session-from': '', + 'send-message-title': '', + 'send-message-path': '', + 'send-message-img': '', + 'app-parameter': '', + 'show-message-card': 'false', + bindGetUserInfo: '', + bindContact: '', + bindGetPhoneNumber: '', + bindError: '', + bindOpenSetting: '', + bindLaunchApp: '' + }, + Form: { + 'report-submit-timeout': '0' + }, + Input: { + 'auto-focus': 'false', + 'always-embed': 'false', + 'adjust-position': 'true', + 'hold-keyboard': 'false', + bindKeyboardHeightChange: '' + }, + Picker: { + 'header-text': '' + }, + PickerView: { + bindPickStart: '', + bindPickEnd: '' + }, + Slider: { + color: singleQuote('#e9e9e9'), + 'selected-color': singleQuote('#1aad19') + }, + Textarea: { + 'show-confirm-bar': 'true', + 'adjust-position': 'true', + 'hold-keyboard': 'false', + 'disable-default-padding': 'false', + bindKeyboardHeightChange: '' + }, + ScrollView: { + 'enable-flex': 'false', + 'scroll-anchoring': 'false', + 'refresher-enabled': 'false', + 'refresher-threshold': '45', + 'refresher-default-style': singleQuote('black'), + 'refresher-background': singleQuote('#FFF'), + 'refresher-triggered': 'false', + enhanced: 'false', + bounces: 'true', + 'show-scrollbar': 'true', + 'paging-enabled': 'false', + 'fast-deceleration': 'false', + bindDragStart: '', + bindDragging: '', + bindDragEnd: '', + bindRefresherPulling: '', + bindRefresherRefresh: '', + bindRefresherRestore: '', + bindRefresherAbort: '' + }, + Swiper: { + 'snap-to-edge': 'false', + 'easing-function': singleQuote('default') + }, + SwiperItem: { + 'skip-hidden-item-layout': 'false' + }, + Navigator: { + target: singleQuote('self'), + 'app-id': '', + path: '', + 'extra-data': '', + version: singleQuote('version') + }, + Camera: { + mode: singleQuote('normal'), + resolution: singleQuote('medium'), + 'frame-size': singleQuote('medium'), + bindInitDone: '', + bindScanCode: '' + }, + Image: { + webp: 'false', + 'show-menu-by-longpress': 'false' + }, + LivePlayer: { + mode: singleQuote('live'), + 'sound-mode': singleQuote('speaker'), + 'auto-pause-if-navigate': 'true', + 'auto-pause-if-open-native': 'true', + 'picture-in-picture-mode': '[]', + bindAudioVolumeNotify: '', + bindEnterPictureInPicture: '', + bindLeavePictureInPicture: '' + }, + Video: { + title: '', + 'play-btn-position': singleQuote('bottom'), + 'enable-play-gesture': 'false', + 'auto-pause-if-navigate': 'true', + 'auto-pause-if-open-native': 'true', + 'vslide-gesture': 'false', + 'vslide-gesture-in-fullscreen': 'true', + 'ad-unit-id': '', + 'poster-for-crawler': '', + 'show-casting-button': 'false', + 'picture-in-picture-mode': '[]', + // picture-in-picture-show-progress 属性先注释掉的原因如下: + // 该属性超过了 wxml 属性的长度限制,实际无法使用且导致编译报错。可等微信官方修复后再放开。 + // 参考1:https://developers.weixin.qq.com/community/develop/doc/000a429beb87f0eac07acc0fc5b400 + // 参考2: https://developers.weixin.qq.com/community/develop/doc/0006883619c48054286a4308258c00?_at=vyxqpllafi + // 'picture-in-picture-show-progress': 'false', + 'enable-auto-rotation': 'false', + 'show-screen-lock-button': 'false', + bindProgress: '', + bindLoadedMetadata: '', + bindControlsToggle: '', + bindEnterPictureInPicture: '', + bindLeavePictureInPicture: '', + bindSeekComplete: '' + }, + Canvas: { + type: '' + }, + Ad: { + 'ad-type': singleQuote('banner'), + 'ad-theme': singleQuote('white') + }, + // ======== 额外组件 ======== + Editor: { + 'read-only': 'false', + placeholder: '', + 'show-img-size': 'false', + 'show-img-toolbar': 'false', + 'show-img-resize': 'false', + focus: 'false', + bindReady: '', + bindFocus: '', + bindBlur: '', + bindInput: '', + bindStatusChange: '', + name: '' + }, + MatchMedia: { + 'min-width': '', + 'max-width': '', + width: '', + 'min-height': '', + 'max-height': '', + height: '', + orientation: '' + }, + FunctionalPageNavigator: { + version: singleQuote('release'), + name: '', + args: '', + bindSuccess: '', + bindFail: '', + bindCancel: '' + }, + LivePusher: { + url: '', + mode: singleQuote('RTC'), + autopush: 'false', + muted: 'false', + 'enable-camera': 'true', + 'auto-focus': 'true', + orientation: singleQuote('vertical'), + beauty: '0', + whiteness: '0', + aspect: singleQuote('9:16'), + 'min-bitrate': '200', + 'max-bitrate': '1000', + 'audio-quality': singleQuote('high'), + 'waiting-image': '', + 'waiting-image-hash': '', + zoom: 'false', + 'device-position': singleQuote('front'), + 'background-mute': 'false', + mirror: 'false', + 'remote-mirror': 'false', + 'local-mirror': 'false', + 'audio-reverb-type': '0', + 'enable-mic': 'true', + 'enable-agc': 'false', + 'enable-ans': 'false', + 'audio-volume-type': singleQuote('voicecall'), + 'video-width': '360', + 'video-height': '640', + animation: '', + bindStateChange: '', + bindNetStatus: '', + bindBgmStart: '', + bindBgmProgress: '', + bindBgmComplete: '' + }, + OfficialAccount: { + bindLoad: '', + bindError: '' + }, + OpenData: { + type: '', + 'open-gid': '', + lang: singleQuote('en'), + 'default-text': '', + 'default-avatar': '', + bindError: '' + }, + NavigationBar: { + title: '', + loading: 'false', + 'front-color': '', + 'background-color': '', + 'color-animation-duration': '0', + 'color-animation-timing-func': singleQuote('linear') + }, + PageMeta: { + 'background-text-style': '', + 'background-color': '', + 'background-color-top': '', + 'background-color-bottom': '', + 'scroll-top': singleQuote(''), + 'scroll-duration': '300', + 'page-style': singleQuote(''), + 'root-font-size': singleQuote(''), + bindResize: '', + bindScroll: '', + bindScrollDone: '' + }, + VoipRoom: { + openid: '', + mode: singleQuote('camera'), + 'device-position': singleQuote('front'), + bindError: '' + }, + AdCustom: { + 'unit-id': '', + 'ad-intervals': '', + bindLoad: '', + bindError: '' + } +} diff --git a/packages/taro-weapp/src/index.ts b/packages/taro-weapp/src/index.ts new file mode 100644 index 000000000000..6d213aaf08cb --- /dev/null +++ b/packages/taro-weapp/src/index.ts @@ -0,0 +1,16 @@ +import Weapp from './program' +import type { IPluginContext } from '@tarojs/service' + +// 让其它平台插件可以继承此平台 +export { Weapp } + +export default (ctx: IPluginContext) => { + ctx.registerPlatform({ + name: 'weapp', + useConfigName: 'mini', + async fn ({ config }) { + const program = new Weapp(ctx, config) + program.start() + } + }) +} diff --git a/packages/taro-weapp/src/program.ts b/packages/taro-weapp/src/program.ts new file mode 100644 index 000000000000..7b75c9f41d63 --- /dev/null +++ b/packages/taro-weapp/src/program.ts @@ -0,0 +1,54 @@ +import { TaroPlatformBase } from '@tarojs/shared' +import { Template } from './template' +import { components } from './components' + +export default class Weapp extends TaroPlatformBase { + platform = 'weapp' + globalObject = 'wx' + projectConfigJson = 'project.config.json' + fileType = { + templ: '.wxml', + style: '.wxss', + config: '.json', + script: '.js', + xs: '.wxs' + } + + template = new Template() + + /** + * 调用 mini-runner 开启编译 + */ + async start () { + this.setup() + this.generateProjectConfig(this.projectConfigJson) + this.modifyComponents() + this.modifyWebpackChain() + + const runner = await this.getRunner() + const options = this.getBaseOptions() + runner(options) + } + + /** + * 增加组件或修改组件属性 + */ + modifyComponents () { + const { internalComponents } = this.template + const { recursiveMerge } = this.ctx.helper + + recursiveMerge(internalComponents, components) + + this.template.voidElements.add('voip-room') + } + + /** + * 修改 webpack 配置 + */ + modifyWebpackChain () { + this.ctx.modifyWebpackChain(({ chain }) => { + const { taroJsComponents } = this.helper + chain.resolve.alias.set(taroJsComponents + '$', '@tarojs/plugin-platform-weapp/dist/components-react.js') + }) + } +} diff --git a/packages/taro-weapp/src/runtime.ts b/packages/taro-weapp/src/runtime.ts new file mode 100644 index 000000000000..ea1e3f3fb7ff --- /dev/null +++ b/packages/taro-weapp/src/runtime.ts @@ -0,0 +1,3 @@ +export const hostConfig = { + +} diff --git a/packages/taro-weapp/src/template.ts b/packages/taro-weapp/src/template.ts new file mode 100644 index 000000000000..b7952d5ee49a --- /dev/null +++ b/packages/taro-weapp/src/template.ts @@ -0,0 +1,29 @@ +import { UnRecursiveTemplate } from '@tarojs/shared' + +export class Template extends UnRecursiveTemplate { + supportXS = true + Adapter = { + if: 'wx:if', + else: 'wx:else', + elseif: 'wx:elif', + for: 'wx:for', + forItem: 'wx:for-item', + forIndex: 'wx:for-index', + key: 'wx:key', + xs: 'wxs', + type: 'weapp' + } + + buildXsTemplate () { + return '' + } + + replacePropName (name: string, value: string, componentName: string) { + if (value === 'eh') { + const nameLowerCase = name.toLowerCase() + if (nameLowerCase === 'bindlongtap' && componentName !== 'canvas') return 'bindlongpress' + return nameLowerCase + } + return name + } +} diff --git a/packages/taro-weapp/tsconfig.json b/packages/taro-weapp/tsconfig.json new file mode 100644 index 000000000000..77fe04ab51c3 --- /dev/null +++ b/packages/taro-weapp/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "es2017", + "module": "CommonJS", + "rootDir": "./src", + "outDir": "dist", + "sourceMap": true, + "baseUrl": ".", + "noImplicitAny": false, + "noUnusedLocals": true, + "removeComments": false, + "strictNullChecks": true, + "allowSyntheticDefaultImports": true, + "experimentalDecorators": true, + "moduleResolution": "node", + "declaration": true, + "declarationDir": "types" + }, + "include": [ + "./src" + ], + "exclude": [ + "**/*.test.ts", + "**/*.spec.ts" + ], + "compileOnSave": false +} diff --git a/packages/taro-weapp/types/components-react.d.ts b/packages/taro-weapp/types/components-react.d.ts new file mode 100644 index 000000000000..7599556f3dce --- /dev/null +++ b/packages/taro-weapp/types/components-react.d.ts @@ -0,0 +1,48 @@ +export declare const View = "view"; +export declare const Icon = "icon"; +export declare const Progress = "progress"; +export declare const RichText = "rich-text"; +export declare const Text = "text"; +export declare const Button = "button"; +export declare const Checkbox = "checkbox"; +export declare const CheckboxGroup = "checkbox-group"; +export declare const Form = "form"; +export declare const Input = "input"; +export declare const Label = "label"; +export declare const Picker = "picker"; +export declare const PickerView = "picker-view"; +export declare const PickerViewColumn = "picker-view-column"; +export declare const Radio = "radio"; +export declare const RadioGroup = "radio-group"; +export declare const Slider = "slider"; +export declare const Switch = "switch"; +export declare const CoverImage = "cover-image"; +export declare const Textarea = "textarea"; +export declare const CoverView = "cover-view"; +export declare const MovableArea = "movable-area"; +export declare const MovableView = "movable-view"; +export declare const ScrollView = "scroll-view"; +export declare const Swiper = "swiper"; +export declare const SwiperItem = "swiper-item"; +export declare const Navigator = "navigator"; +export declare const Audio = "audio"; +export declare const Camera = "camera"; +export declare const Image = "image"; +export declare const LivePlayer = "live-player"; +export declare const Video = "video"; +export declare const Canvas = "canvas"; +export declare const Ad = "ad"; +export declare const WebView = "web-view"; +export declare const Block = "block"; +export declare const Map = "map"; +export declare const Slot = "slot"; +export declare const Editor = "editor"; +export declare const MatchMedia = "match-media"; +export declare const FunctionalPageNavigator = "functional-page-navigator"; +export declare const LivePusher = "live-pusher"; +export declare const OfficialAccount = "official-account"; +export declare const OpenData = "open-data"; +export declare const NavigationBar = "navigation-bar"; +export declare const PageMeta = "page-meta"; +export declare const VoipRoom = "voip-room"; +export declare const AdCustom = "ad-custom"; diff --git a/packages/taro-weapp/types/components.d.ts b/packages/taro-weapp/types/components.d.ts new file mode 100644 index 000000000000..c38e937bb79f --- /dev/null +++ b/packages/taro-weapp/types/components.d.ts @@ -0,0 +1,272 @@ +export declare const components: { + Progress: { + 'border-radius': string; + 'font-size': string; + duration: string; + bindActiveEnd: string; + }; + RichText: { + space: string; + }; + Text: { + 'user-select': string; + }; + Map: { + polygons: string; + subkey: string; + rotate: string; + skew: string; + 'enable-3D': string; + 'show-compass': string; + 'show-scale': string; + 'enable-overlooking': string; + 'enable-zoom': string; + 'enable-scroll': string; + 'enable-rotate': string; + 'enable-satellite': string; + 'enable-traffic': string; + setting: string; + bindLabelTap: string; + bindRegionChange: string; + bindPoiTap: string; + }; + Button: { + lang: string; + 'session-from': string; + 'send-message-title': string; + 'send-message-path': string; + 'send-message-img': string; + 'app-parameter': string; + 'show-message-card': string; + bindGetUserInfo: string; + bindContact: string; + bindGetPhoneNumber: string; + bindError: string; + bindOpenSetting: string; + bindLaunchApp: string; + }; + Form: { + 'report-submit-timeout': string; + }; + Input: { + 'auto-focus': string; + 'always-embed': string; + 'adjust-position': string; + 'hold-keyboard': string; + bindKeyboardHeightChange: string; + }; + Picker: { + 'header-text': string; + }; + PickerView: { + bindPickStart: string; + bindPickEnd: string; + }; + Slider: { + color: string; + 'selected-color': string; + }; + Textarea: { + 'show-confirm-bar': string; + 'adjust-position': string; + 'hold-keyboard': string; + 'disable-default-padding': string; + bindKeyboardHeightChange: string; + }; + ScrollView: { + 'enable-flex': string; + 'scroll-anchoring': string; + 'refresher-enabled': string; + 'refresher-threshold': string; + 'refresher-default-style': string; + 'refresher-background': string; + 'refresher-triggered': string; + enhanced: string; + bounces: string; + 'show-scrollbar': string; + 'paging-enabled': string; + 'fast-deceleration': string; + bindDragStart: string; + bindDragging: string; + bindDragEnd: string; + bindRefresherPulling: string; + bindRefresherRefresh: string; + bindRefresherRestore: string; + bindRefresherAbort: string; + }; + Swiper: { + 'snap-to-edge': string; + 'easing-function': string; + }; + SwiperItem: { + 'skip-hidden-item-layout': string; + }; + Navigator: { + target: string; + 'app-id': string; + path: string; + 'extra-data': string; + version: string; + }; + Camera: { + mode: string; + resolution: string; + 'frame-size': string; + bindInitDone: string; + bindScanCode: string; + }; + Image: { + webp: string; + 'show-menu-by-longpress': string; + }; + LivePlayer: { + mode: string; + 'sound-mode': string; + 'auto-pause-if-navigate': string; + 'auto-pause-if-open-native': string; + 'picture-in-picture-mode': string; + bindAudioVolumeNotify: string; + bindEnterPictureInPicture: string; + bindLeavePictureInPicture: string; + }; + Video: { + title: string; + 'play-btn-position': string; + 'enable-play-gesture': string; + 'auto-pause-if-navigate': string; + 'auto-pause-if-open-native': string; + 'vslide-gesture': string; + 'vslide-gesture-in-fullscreen': string; + 'ad-unit-id': string; + 'poster-for-crawler': string; + 'show-casting-button': string; + 'picture-in-picture-mode': string; + 'enable-auto-rotation': string; + 'show-screen-lock-button': string; + bindProgress: string; + bindLoadedMetadata: string; + bindControlsToggle: string; + bindEnterPictureInPicture: string; + bindLeavePictureInPicture: string; + bindSeekComplete: string; + }; + Canvas: { + type: string; + }; + Ad: { + 'ad-type': string; + 'ad-theme': string; + }; + Editor: { + 'read-only': string; + placeholder: string; + 'show-img-size': string; + 'show-img-toolbar': string; + 'show-img-resize': string; + focus: string; + bindReady: string; + bindFocus: string; + bindBlur: string; + bindInput: string; + bindStatusChange: string; + name: string; + }; + MatchMedia: { + 'min-width': string; + 'max-width': string; + width: string; + 'min-height': string; + 'max-height': string; + height: string; + orientation: string; + }; + FunctionalPageNavigator: { + version: string; + name: string; + args: string; + bindSuccess: string; + bindFail: string; + bindCancel: string; + }; + LivePusher: { + url: string; + mode: string; + autopush: string; + muted: string; + 'enable-camera': string; + 'auto-focus': string; + orientation: string; + beauty: string; + whiteness: string; + aspect: string; + 'min-bitrate': string; + 'max-bitrate': string; + 'audio-quality': string; + 'waiting-image': string; + 'waiting-image-hash': string; + zoom: string; + 'device-position': string; + 'background-mute': string; + mirror: string; + 'remote-mirror': string; + 'local-mirror': string; + 'audio-reverb-type': string; + 'enable-mic': string; + 'enable-agc': string; + 'enable-ans': string; + 'audio-volume-type': string; + 'video-width': string; + 'video-height': string; + animation: string; + bindStateChange: string; + bindNetStatus: string; + bindBgmStart: string; + bindBgmProgress: string; + bindBgmComplete: string; + }; + OfficialAccount: { + bindLoad: string; + bindError: string; + }; + OpenData: { + type: string; + 'open-gid': string; + lang: string; + 'default-text': string; + 'default-avatar': string; + bindError: string; + }; + NavigationBar: { + title: string; + loading: string; + 'front-color': string; + 'background-color': string; + 'color-animation-duration': string; + 'color-animation-timing-func': string; + }; + PageMeta: { + 'background-text-style': string; + 'background-color': string; + 'background-color-top': string; + 'background-color-bottom': string; + 'scroll-top': string; + 'scroll-duration': string; + 'page-style': string; + 'root-font-size': string; + bindResize: string; + bindScroll: string; + bindScrollDone: string; + }; + VoipRoom: { + openid: string; + mode: string; + 'device-position': string; + bindError: string; + }; + AdCustom: { + 'unit-id': string; + 'ad-intervals': string; + bindLoad: string; + bindError: string; + }; +}; diff --git a/packages/taro-weapp/types/index.d.ts b/packages/taro-weapp/types/index.d.ts new file mode 100644 index 000000000000..167c579ecf76 --- /dev/null +++ b/packages/taro-weapp/types/index.d.ts @@ -0,0 +1,5 @@ +import Weapp from './program'; +import type { IPluginContext } from '@tarojs/service'; +export { Weapp }; +declare const _default: (ctx: IPluginContext) => void; +export default _default; diff --git a/packages/taro-weapp/types/program.d.ts b/packages/taro-weapp/types/program.d.ts new file mode 100644 index 000000000000..28e9aaef8e9b --- /dev/null +++ b/packages/taro-weapp/types/program.d.ts @@ -0,0 +1,27 @@ +import { TaroPlatformBase } from '@tarojs/shared'; +import { Template } from './template'; +export default class Weapp extends TaroPlatformBase { + platform: string; + globalObject: string; + projectConfigJson: string; + fileType: { + templ: string; + style: string; + config: string; + script: string; + xs: string; + }; + template: Template; + /** + * 调用 mini-runner 开启编译 + */ + start(): Promise; + /** + * 增加组件或修改组件属性 + */ + modifyComponents(): void; + /** + * 修改 webpack 配置 + */ + modifyWebpackChain(): void; +} diff --git a/packages/taro-weapp/types/runtime.d.ts b/packages/taro-weapp/types/runtime.d.ts new file mode 100644 index 000000000000..0d3892e71438 --- /dev/null +++ b/packages/taro-weapp/types/runtime.d.ts @@ -0,0 +1 @@ +export declare const hostConfig: {}; diff --git a/packages/taro-weapp/types/template.d.ts b/packages/taro-weapp/types/template.d.ts new file mode 100644 index 000000000000..1c2520e3ef56 --- /dev/null +++ b/packages/taro-weapp/types/template.d.ts @@ -0,0 +1,17 @@ +import { UnRecursiveTemplate } from '@tarojs/shared'; +export declare class Template extends UnRecursiveTemplate { + supportXS: boolean; + Adapter: { + if: string; + else: string; + elseif: string; + for: string; + forItem: string; + forIndex: string; + key: string; + xs: string; + type: string; + }; + buildXsTemplate(): string; + replacePropName(name: string, value: string, componentName: string): string; +} From 13f55aa6bd98e517cfc31dafb3871ffdeb79e8ed Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 17:11:40 +0800 Subject: [PATCH 007/272] =?UTF-8?q?chore(taro-weapp):=20=E5=88=86=E7=A6=BB?= =?UTF-8?q?=E5=87=BA=20tt=20=E5=B9=B3=E5=8F=B0=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/taro-tt/README.md | 3 ++ packages/taro-tt/index.js | 3 ++ packages/taro-tt/package.json | 33 +++++++++++++++++++++ packages/taro-tt/src/components.ts | 36 +++++++++++++++++++++++ packages/taro-tt/src/index.ts | 16 +++++++++++ packages/taro-tt/src/program.ts | 40 ++++++++++++++++++++++++++ packages/taro-tt/src/runtime.ts | 5 ++++ packages/taro-tt/src/template.ts | 15 ++++++++++ packages/taro-tt/tsconfig.json | 27 +++++++++++++++++ packages/taro-tt/types/components.d.ts | 33 +++++++++++++++++++++ packages/taro-tt/types/index.d.ts | 5 ++++ packages/taro-tt/types/program.d.ts | 22 ++++++++++++++ packages/taro-tt/types/runtime.d.ts | 3 ++ packages/taro-tt/types/template.d.ts | 14 +++++++++ 14 files changed, 255 insertions(+) create mode 100644 packages/taro-tt/README.md create mode 100644 packages/taro-tt/index.js create mode 100644 packages/taro-tt/package.json create mode 100644 packages/taro-tt/src/components.ts create mode 100644 packages/taro-tt/src/index.ts create mode 100644 packages/taro-tt/src/program.ts create mode 100644 packages/taro-tt/src/runtime.ts create mode 100644 packages/taro-tt/src/template.ts create mode 100644 packages/taro-tt/tsconfig.json create mode 100644 packages/taro-tt/types/components.d.ts create mode 100644 packages/taro-tt/types/index.d.ts create mode 100644 packages/taro-tt/types/program.d.ts create mode 100644 packages/taro-tt/types/runtime.d.ts create mode 100644 packages/taro-tt/types/template.d.ts diff --git a/packages/taro-tt/README.md b/packages/taro-tt/README.md new file mode 100644 index 000000000000..843bc33d6ada --- /dev/null +++ b/packages/taro-tt/README.md @@ -0,0 +1,3 @@ +# `@tarojs/plugin-platform-tt` + +Taro 插件。用于支持编译为头条小程序。 diff --git a/packages/taro-tt/index.js b/packages/taro-tt/index.js new file mode 100644 index 000000000000..30a7c8300a51 --- /dev/null +++ b/packages/taro-tt/index.js @@ -0,0 +1,3 @@ +module.exports = require('./dist/index.js').default +module.exports.default = module.exports +module.exports.TT = require('./dist/index.js').TT diff --git a/packages/taro-tt/package.json b/packages/taro-tt/package.json new file mode 100644 index 000000000000..ed86cf16d536 --- /dev/null +++ b/packages/taro-tt/package.json @@ -0,0 +1,33 @@ +{ + "name": "@tarojs/plugin-platform-tt", + "version": "3.0.9", + "description": "头条小程序平台插件", + "author": "Chen-jj", + "homepage": "https://github.com/nervjs/taro/tree/master/packages/taro-tt#readme", + "license": "MIT", + "main": "index.js", + "keywords": [ + "taro" + ], + "files": [ + "index.js", + "dist", + "types" + ], + "types": "types/index.d.ts", + "repository": { + "type": "git", + "url": "git+https://github.com/NervJS/taro.git" + }, + "scripts": { + "build": "tsc", + "dev": "tsc -w" + }, + "bugs": { + "url": "https://github.com/NervJS/taro/issues" + }, + "dependencies": { + "@tarojs/service": "3.0.9", + "@tarojs/shared": "3.0.9" + } +} diff --git a/packages/taro-tt/src/components.ts b/packages/taro-tt/src/components.ts new file mode 100644 index 000000000000..7939fe521a63 --- /dev/null +++ b/packages/taro-tt/src/components.ts @@ -0,0 +1,36 @@ +import { singleQuote } from '@tarojs/shared' + +export const components = { + // ======== 调整属性 ======== + Icon: { + size: '24' + }, + Button: { + bindGetPhoneNumber: '' + }, + Form: { + 'report-submit-timeout': '0' + }, + Slider: { + color: singleQuote('#e9e9e9'), + 'selected-color': singleQuote('#1aad19') + }, + WebView: { + 'progressbar-color': singleQuote('#51a0d8') + }, + Video: { + 'play-btn-position': singleQuote('center'), + 'pre-roll-unit-id': '', + 'post-roll-unit-id': '', + bindAdStart: '', + bindAdEnded: '', + bindAdLoad: '', + bindAdClose: '', + bindAdError: '' + }, + Ad: { + fixed: '', + type: singleQuote('banner'), + scale: '100' + } +} diff --git a/packages/taro-tt/src/index.ts b/packages/taro-tt/src/index.ts new file mode 100644 index 000000000000..937b87023db2 --- /dev/null +++ b/packages/taro-tt/src/index.ts @@ -0,0 +1,16 @@ +import TT from './program' +import type { IPluginContext } from '@tarojs/service' + +// 让其它平台插件可以继承此平台 +export { TT } + +export default (ctx: IPluginContext) => { + ctx.registerPlatform({ + name: 'tt', + useConfigName: 'mini', + async fn ({ config }) { + const program = new TT(ctx, config) + program.start() + } + }) +} diff --git a/packages/taro-tt/src/program.ts b/packages/taro-tt/src/program.ts new file mode 100644 index 000000000000..490724ace8b1 --- /dev/null +++ b/packages/taro-tt/src/program.ts @@ -0,0 +1,40 @@ +import { TaroPlatformBase } from '@tarojs/shared' +import { Template } from './template' +import { components } from './components' + +export default class TT extends TaroPlatformBase { + platform = 'tt' + globalObject = 'tt' + projectConfigJson = 'project.tt.json' + fileType = { + templ: '.ttml', + style: '.ttss', + config: '.json', + script: '.js' + } + + template = new Template() + + /** + * 调用 mini-runner 开启编译 + */ + async start () { + this.setup() + this.generateProjectConfig(this.projectConfigJson) + this.modifyComponents() + + const runner = await this.getRunner() + const options = this.getBaseOptions() + runner(options) + } + + /** + * 增加组件或修改组件属性 + */ + modifyComponents () { + const { internalComponents } = this.template + const { recursiveMerge } = this.ctx.helper + + recursiveMerge(internalComponents, components) + } +} diff --git a/packages/taro-tt/src/runtime.ts b/packages/taro-tt/src/runtime.ts new file mode 100644 index 000000000000..93cb5c7be947 --- /dev/null +++ b/packages/taro-tt/src/runtime.ts @@ -0,0 +1,5 @@ +export const hostConfig = { + log: function () { + console.log('ok') + } +} diff --git a/packages/taro-tt/src/template.ts b/packages/taro-tt/src/template.ts new file mode 100644 index 000000000000..93611ed27aa1 --- /dev/null +++ b/packages/taro-tt/src/template.ts @@ -0,0 +1,15 @@ +import { RecursiveTemplate } from '@tarojs/shared' + +export class Template extends RecursiveTemplate { + supportXS = false + Adapter = { + if: 'tt:if', + else: 'tt:else', + elseif: 'tt:elif', + for: 'tt:for', + forItem: 'tt:for-item', + forIndex: 'tt:for-index', + key: 'tt:key', + type: 'tt' + } +} diff --git a/packages/taro-tt/tsconfig.json b/packages/taro-tt/tsconfig.json new file mode 100644 index 000000000000..77fe04ab51c3 --- /dev/null +++ b/packages/taro-tt/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "es2017", + "module": "CommonJS", + "rootDir": "./src", + "outDir": "dist", + "sourceMap": true, + "baseUrl": ".", + "noImplicitAny": false, + "noUnusedLocals": true, + "removeComments": false, + "strictNullChecks": true, + "allowSyntheticDefaultImports": true, + "experimentalDecorators": true, + "moduleResolution": "node", + "declaration": true, + "declarationDir": "types" + }, + "include": [ + "./src" + ], + "exclude": [ + "**/*.test.ts", + "**/*.spec.ts" + ], + "compileOnSave": false +} diff --git a/packages/taro-tt/types/components.d.ts b/packages/taro-tt/types/components.d.ts new file mode 100644 index 000000000000..5df28ea2a0d4 --- /dev/null +++ b/packages/taro-tt/types/components.d.ts @@ -0,0 +1,33 @@ +export declare const components: { + Icon: { + size: string; + }; + Button: { + bindGetPhoneNumber: string; + }; + Form: { + 'report-submit-timeout': string; + }; + Slider: { + color: string; + 'selected-color': string; + }; + WebView: { + 'progressbar-color': string; + }; + Video: { + 'play-btn-position': string; + 'pre-roll-unit-id': string; + 'post-roll-unit-id': string; + bindAdStart: string; + bindAdEnded: string; + bindAdLoad: string; + bindAdClose: string; + bindAdError: string; + }; + Ad: { + fixed: string; + type: string; + scale: string; + }; +}; diff --git a/packages/taro-tt/types/index.d.ts b/packages/taro-tt/types/index.d.ts new file mode 100644 index 000000000000..6bca4a8ecc92 --- /dev/null +++ b/packages/taro-tt/types/index.d.ts @@ -0,0 +1,5 @@ +import TT from './program'; +import type { IPluginContext } from '@tarojs/service'; +export { TT }; +declare const _default: (ctx: IPluginContext) => void; +export default _default; diff --git a/packages/taro-tt/types/program.d.ts b/packages/taro-tt/types/program.d.ts new file mode 100644 index 000000000000..2e9e5115e768 --- /dev/null +++ b/packages/taro-tt/types/program.d.ts @@ -0,0 +1,22 @@ +import { TaroPlatformBase } from '@tarojs/shared'; +import { Template } from './template'; +export default class TT extends TaroPlatformBase { + platform: string; + globalObject: string; + projectConfigJson: string; + fileType: { + templ: string; + style: string; + config: string; + script: string; + }; + template: Template; + /** + * 调用 mini-runner 开启编译 + */ + start(): Promise; + /** + * 增加组件或修改组件属性 + */ + modifyComponents(): void; +} diff --git a/packages/taro-tt/types/runtime.d.ts b/packages/taro-tt/types/runtime.d.ts new file mode 100644 index 000000000000..5448c1d735d7 --- /dev/null +++ b/packages/taro-tt/types/runtime.d.ts @@ -0,0 +1,3 @@ +export declare const hostConfig: { + log: () => void; +}; diff --git a/packages/taro-tt/types/template.d.ts b/packages/taro-tt/types/template.d.ts new file mode 100644 index 000000000000..517ef56c327a --- /dev/null +++ b/packages/taro-tt/types/template.d.ts @@ -0,0 +1,14 @@ +import { RecursiveTemplate } from '@tarojs/shared'; +export declare class Template extends RecursiveTemplate { + supportXS: boolean; + Adapter: { + if: string; + else: string; + elseif: string; + for: string; + forItem: string; + forIndex: string; + key: string; + type: string; + }; +} From e9f47d95567c4b84754d6af5bc8c117f4a83d51a Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 17:11:57 +0800 Subject: [PATCH 008/272] =?UTF-8?q?chore(taro-weapp):=20=E5=88=86=E7=A6=BB?= =?UTF-8?q?=E5=87=BA=20swan=20=E5=B9=B3=E5=8F=B0=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/taro-swan/README.md | 3 + packages/taro-swan/index.js | 3 + packages/taro-swan/package.json | 33 ++++ packages/taro-swan/src/components-react.ts | 47 ++++++ packages/taro-swan/src/components.ts | 153 ++++++++++++++++++ packages/taro-swan/src/index.ts | 16 ++ packages/taro-swan/src/program.ts | 54 +++++++ packages/taro-swan/src/runtime.ts | 5 + packages/taro-swan/src/template.ts | 48 ++++++ packages/taro-swan/tsconfig.json | 27 ++++ .../taro-swan/types/components-react.d.ts | 46 ++++++ packages/taro-swan/types/components.d.ts | 149 +++++++++++++++++ packages/taro-swan/types/index.d.ts | 5 + packages/taro-swan/types/program.d.ts | 27 ++++ packages/taro-swan/types/runtime.d.ts | 3 + packages/taro-swan/types/template.d.ts | 19 +++ 16 files changed, 638 insertions(+) create mode 100644 packages/taro-swan/README.md create mode 100644 packages/taro-swan/index.js create mode 100644 packages/taro-swan/package.json create mode 100644 packages/taro-swan/src/components-react.ts create mode 100644 packages/taro-swan/src/components.ts create mode 100644 packages/taro-swan/src/index.ts create mode 100644 packages/taro-swan/src/program.ts create mode 100644 packages/taro-swan/src/runtime.ts create mode 100644 packages/taro-swan/src/template.ts create mode 100644 packages/taro-swan/tsconfig.json create mode 100644 packages/taro-swan/types/components-react.d.ts create mode 100644 packages/taro-swan/types/components.d.ts create mode 100644 packages/taro-swan/types/index.d.ts create mode 100644 packages/taro-swan/types/program.d.ts create mode 100644 packages/taro-swan/types/runtime.d.ts create mode 100644 packages/taro-swan/types/template.d.ts diff --git a/packages/taro-swan/README.md b/packages/taro-swan/README.md new file mode 100644 index 000000000000..ff887efc574a --- /dev/null +++ b/packages/taro-swan/README.md @@ -0,0 +1,3 @@ +# `@tarojs/plugin-platform-swan` + +Taro 插件。用于支持编译为百度小程序。 diff --git a/packages/taro-swan/index.js b/packages/taro-swan/index.js new file mode 100644 index 000000000000..91aa64b7a516 --- /dev/null +++ b/packages/taro-swan/index.js @@ -0,0 +1,3 @@ +module.exports = require('./dist/index.js').default +module.exports.default = module.exports +module.exports.Swan = require('./dist/index.js').Swan diff --git a/packages/taro-swan/package.json b/packages/taro-swan/package.json new file mode 100644 index 000000000000..8b13ed641128 --- /dev/null +++ b/packages/taro-swan/package.json @@ -0,0 +1,33 @@ +{ + "name": "@tarojs/plugin-platform-swan", + "version": "3.0.9", + "description": "百度小程序平台插件", + "author": "Chen-jj", + "homepage": "https://github.com/nervjs/taro/tree/master/packages/taro-swan#readme", + "license": "MIT", + "main": "index.js", + "keywords": [ + "taro" + ], + "files": [ + "index.js", + "dist", + "types" + ], + "types": "types/index.d.ts", + "repository": { + "type": "git", + "url": "git+https://github.com/NervJS/taro.git" + }, + "scripts": { + "build": "tsc", + "dev": "tsc -w" + }, + "bugs": { + "url": "https://github.com/NervJS/taro/issues" + }, + "dependencies": { + "@tarojs/service": "3.0.9", + "@tarojs/shared": "3.0.9" + } +} diff --git a/packages/taro-swan/src/components-react.ts b/packages/taro-swan/src/components-react.ts new file mode 100644 index 000000000000..3f243493a6e2 --- /dev/null +++ b/packages/taro-swan/src/components-react.ts @@ -0,0 +1,47 @@ +// For React.createElement's type +export const View = 'view' +export const Icon = 'icon' +export const Progress = 'progress' +export const RichText = 'rich-text' +export const Text = 'text' +export const Button = 'button' +export const Checkbox = 'checkbox' +export const CheckboxGroup = 'checkbox-group' +export const Form = 'form' +export const Input = 'input' +export const Label = 'label' +export const Picker = 'picker' +export const PickerView = 'picker-view' +export const PickerViewColumn = 'picker-view-column' +export const Radio = 'radio' +export const RadioGroup = 'radio-group' +export const Slider = 'slider' +export const Switch = 'switch' +export const CoverImage = 'cover-image' +export const Textarea = 'textarea' +export const CoverView = 'cover-view' +export const MovableArea = 'movable-area' +export const MovableView = 'movable-view' +export const ScrollView = 'scroll-view' +export const Swiper = 'swiper' +export const SwiperItem = 'swiper-item' +export const Navigator = 'navigator' +export const Audio = 'audio' +export const Camera = 'camera' +export const Image = 'image' +export const LivePlayer = 'live-player' +export const Video = 'video' +export const Canvas = 'canvas' +export const Ad = 'ad' +export const WebView = 'web-view' +export const Block = 'block' +export const Map = 'map' +export const Slot = 'slot' +export const Tabs = 'tabs' +export const TabItem = 'tab-item' +export const AnimationVideo = 'animation-video' +export const AnimationView = 'animation-view' +export const ArCamera = 'ar-camera' +export const RtcRoom = 'rtc-room' +export const RtcRoomItem = 'rtc-room-item' +export const OpenData = 'open-data' diff --git a/packages/taro-swan/src/components.ts b/packages/taro-swan/src/components.ts new file mode 100644 index 000000000000..796ede97afdb --- /dev/null +++ b/packages/taro-swan/src/components.ts @@ -0,0 +1,153 @@ +import { singleQuote } from '@tarojs/shared' + +export const components = { + // ======== 调整属性 ======== + Progress: { + 'border-radius': '0', + 'font-size': '16', + duration: '30' + }, + RichText: { + selectable: 'false', + name: '', + attrs: '', + children: '[]', + text: '', + 'image-menu-prevent': 'false', + preview: '' + }, + Map: { + polygons: '[]', + 'enable-3D': 'false', + 'show-compass': 'false', + 'enable-overlooking': 'false', + 'enable-zoom': 'true', + 'enable-scroll': 'true', + 'enable-rotate': 'false', + bindRegionChange: '', + bindPoiTap: '' + }, + Button: { + bindGetPhoneNumber: '', + bindGetUserInfo: '', + bindOpenSetting: '', + bindContact: '', + bindChooseAddress: '', + bindChooseInvoiceTitle: '' + }, + Form: { + 'report-type': 'default', + 'template-id': '', + 'subscribe-id': '' + }, + Input: { + 'adjust-position': 'true' + }, + Textarea: { + 'confirm-type': singleQuote('default'), + 'confirm-hold': 'false', + 'show-confirm-bar': 'true', + 'adjust-position': 'true' + }, + Navigator: { + target: singleQuote('self'), + 'app-id': '', + path: '', + 'extra-data': '', + version: singleQuote('version') + }, + Image: { + webp: 'false', + 'image-menu-prevent': 'false', + preview: '', + 'original-src': '' + }, + Video: { + title: '', + 'show-no-wifi-tip': 'true', + 'vslide-gesture': 'false', + 'vslide-gesture-in-fullscreen': 'true', + 'enable-play-gesture': 'false', + 'show-rate-btn': 'false', + 'show-vslide-btn-in-fullscreen': 'true', + 'silent-play': 'false', + bindLoadedMetadata: '' + }, + Ad: { + appid: '', + apid: '', + type: singleQuote('feed'), + updatetime: '', + bindStatus: '' + }, + // ======== 额外组件 ======== + Tabs: { + 'tabs-background-color': singleQuote('#fff'), + 'tabs-active-text-color': singleQuote('#000'), + 'tabs-inactive-text-color': singleQuote('#666'), + 'tabs-underline-color': singleQuote('#333'), + 'active-name': '', + 'url-query-name': '', + 'max-tab-item-amount': '5', + bindTabChange: '' + }, + TabItem: { + label: '', + name: '', + 'badge-type': '', + 'badge-text': '' + }, + AnimationVideo: { + 'resource-width': '800', + 'resource-height': '400', + 'canvas-style': singleQuote('width:400px;height:400px'), + path: '', + loop: 'fasle', + autoplay: 'fasle', + bindStarted: '', + bindEnded: '' + }, + AnimationView: { + path: '', + loop: 'false', + autoplay: 'true', + action: singleQuote('play'), + hidden: 'true', + bindEnded: '' + }, + ArCamera: { + key: '', + type: '', + flash: singleQuote('off'), + bindError: '', + bindLoad: '', + bindMessage: '', + bindScanCode: '' + }, + RtcRoom: { + id: '', + 'enable-camera': 'true', + 'enable-auto-focus': 'true', + 'enable-zoom': 'false', + 'device-position': singleQuote('front'), + 'enable-mic': 'true', + 'enable-agc': 'false', + 'enable-ans': 'false', + bitrate: '900', + 'video-width': '360', + 'video-height': '640', + 'enable-remote-mirror': 'false', + 'local-mirror': singleQuote('auto'), + 'sound-mode': singleQuote('speaker'), + bindStateChange: '', + bindError: '' + }, + RtcRoomItem: { + id: '', + type: '', + 'user-id': '' + }, + OpenData: { + type: '' + } +} diff --git a/packages/taro-swan/src/index.ts b/packages/taro-swan/src/index.ts new file mode 100644 index 000000000000..7ca64bb57668 --- /dev/null +++ b/packages/taro-swan/src/index.ts @@ -0,0 +1,16 @@ +import Swan from './program' +import type { IPluginContext } from '@tarojs/service' + +// 让其它平台插件可以继承此平台 +export { Swan } + +export default (ctx: IPluginContext) => { + ctx.registerPlatform({ + name: 'swan', + useConfigName: 'mini', + async fn ({ config }) { + const program = new Swan(ctx, config) + program.start() + } + }) +} diff --git a/packages/taro-swan/src/program.ts b/packages/taro-swan/src/program.ts new file mode 100644 index 000000000000..e57aa78c6c5d --- /dev/null +++ b/packages/taro-swan/src/program.ts @@ -0,0 +1,54 @@ +import { TaroPlatformBase } from '@tarojs/shared' +import { Template } from './template' +import { components } from './components' + +const PROJECT_JSON = 'project.swan.json' + +export default class Swan extends TaroPlatformBase { + platform = 'swan' + globalObject = 'swan' + projectConfigJson = PROJECT_JSON + fileType = { + templ: '.swan', + style: '.css', + config: '.json', + script: '.js', + xs: '.sjs' + } + + template = new Template() + + /** + * 调用 mini-runner 开启编译 + */ + async start () { + this.setup() + this.generateProjectConfig(this.projectConfigJson, PROJECT_JSON) + this.modifyComponents() + this.modifyWebpackChain() + + const runner = await this.getRunner() + const options = this.getBaseOptions() + runner(options) + } + + /** + * 增加组件或修改组件属性 + */ + modifyComponents () { + const { internalComponents } = this.template + const { recursiveMerge } = this.ctx.helper + + recursiveMerge(internalComponents, components) + } + + /** + * 修改 webpack 配置 + */ + modifyWebpackChain () { + this.ctx.modifyWebpackChain(({ chain }) => { + const { taroJsComponents } = this.helper + chain.resolve.alias.set(taroJsComponents + '$', '@tarojs/plugin-platform-swan/dist/components-react.js') + }) + } +} diff --git a/packages/taro-swan/src/runtime.ts b/packages/taro-swan/src/runtime.ts new file mode 100644 index 000000000000..93cb5c7be947 --- /dev/null +++ b/packages/taro-swan/src/runtime.ts @@ -0,0 +1,5 @@ +export const hostConfig = { + log: function () { + console.log('ok') + } +} diff --git a/packages/taro-swan/src/template.ts b/packages/taro-swan/src/template.ts new file mode 100644 index 000000000000..f428a09a3930 --- /dev/null +++ b/packages/taro-swan/src/template.ts @@ -0,0 +1,48 @@ +import { RecursiveTemplate, isArray, Shortcuts } from '@tarojs/shared' + +const swanSpecialAttrs = { + 'scroll-view': ['scrollTop', 'scrollLeft', 'scrollIntoView'], + 'movable-view': ['x', 'y'], + slider: ['value'], + input: ['value'], + textarea: ['value'] +} + +export class Template extends RecursiveTemplate { + supportXS = true + Adapter = { + if: 's-if', + else: 's-else', + elseif: 's-elif', + for: 's-for', + forItem: 's-for-item', + forIndex: 's-for-index', + key: 's-key', + xs: 'sjs', + type: 'swan' + } + + buildXsTemplate () { + return '' + } + + dataKeymap (keymap: string) { + return `{ ${keymap} }` + } + + getAttrValue (value: string, key: string, nodeName: string) { + if (isArray(swanSpecialAttrs[nodeName]) && swanSpecialAttrs[nodeName].includes(key)) { + return `= ${value} =` + } + + return `{ ${value} }` + } + + modifyLoopBody = (child: string, nodeName: string) => { + if (nodeName === 'text') { + return `{{ i.${Shortcuts.Childnodes}[index].${Shortcuts.Text} }}` + } + + return child + } +} diff --git a/packages/taro-swan/tsconfig.json b/packages/taro-swan/tsconfig.json new file mode 100644 index 000000000000..77fe04ab51c3 --- /dev/null +++ b/packages/taro-swan/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "es2017", + "module": "CommonJS", + "rootDir": "./src", + "outDir": "dist", + "sourceMap": true, + "baseUrl": ".", + "noImplicitAny": false, + "noUnusedLocals": true, + "removeComments": false, + "strictNullChecks": true, + "allowSyntheticDefaultImports": true, + "experimentalDecorators": true, + "moduleResolution": "node", + "declaration": true, + "declarationDir": "types" + }, + "include": [ + "./src" + ], + "exclude": [ + "**/*.test.ts", + "**/*.spec.ts" + ], + "compileOnSave": false +} diff --git a/packages/taro-swan/types/components-react.d.ts b/packages/taro-swan/types/components-react.d.ts new file mode 100644 index 000000000000..f710dc94b5c2 --- /dev/null +++ b/packages/taro-swan/types/components-react.d.ts @@ -0,0 +1,46 @@ +export declare const View = "view"; +export declare const Icon = "icon"; +export declare const Progress = "progress"; +export declare const RichText = "rich-text"; +export declare const Text = "text"; +export declare const Button = "button"; +export declare const Checkbox = "checkbox"; +export declare const CheckboxGroup = "checkbox-group"; +export declare const Form = "form"; +export declare const Input = "input"; +export declare const Label = "label"; +export declare const Picker = "picker"; +export declare const PickerView = "picker-view"; +export declare const PickerViewColumn = "picker-view-column"; +export declare const Radio = "radio"; +export declare const RadioGroup = "radio-group"; +export declare const Slider = "slider"; +export declare const Switch = "switch"; +export declare const CoverImage = "cover-image"; +export declare const Textarea = "textarea"; +export declare const CoverView = "cover-view"; +export declare const MovableArea = "movable-area"; +export declare const MovableView = "movable-view"; +export declare const ScrollView = "scroll-view"; +export declare const Swiper = "swiper"; +export declare const SwiperItem = "swiper-item"; +export declare const Navigator = "navigator"; +export declare const Audio = "audio"; +export declare const Camera = "camera"; +export declare const Image = "image"; +export declare const LivePlayer = "live-player"; +export declare const Video = "video"; +export declare const Canvas = "canvas"; +export declare const Ad = "ad"; +export declare const WebView = "web-view"; +export declare const Block = "block"; +export declare const Map = "map"; +export declare const Slot = "slot"; +export declare const Tabs = "tabs"; +export declare const TabItem = "tab-item"; +export declare const AnimationVideo = "animation-video"; +export declare const AnimationView = "animation-view"; +export declare const ArCamera = "ar-camera"; +export declare const RtcRoom = "rtc-room"; +export declare const RtcRoomItem = "rtc-room-item"; +export declare const OpenData = "open-data"; diff --git a/packages/taro-swan/types/components.d.ts b/packages/taro-swan/types/components.d.ts new file mode 100644 index 000000000000..20747ff34358 --- /dev/null +++ b/packages/taro-swan/types/components.d.ts @@ -0,0 +1,149 @@ +export declare const components: { + Progress: { + 'border-radius': string; + 'font-size': string; + duration: string; + }; + RichText: { + selectable: string; + name: string; + attrs: string; + children: string; + text: string; + 'image-menu-prevent': string; + preview: string; + }; + Map: { + polygons: string; + 'enable-3D': string; + 'show-compass': string; + 'enable-overlooking': string; + 'enable-zoom': string; + 'enable-scroll': string; + 'enable-rotate': string; + bindRegionChange: string; + bindPoiTap: string; + }; + Button: { + bindGetPhoneNumber: string; + bindGetUserInfo: string; + bindOpenSetting: string; + bindContact: string; + bindChooseAddress: string; + bindChooseInvoiceTitle: string; + }; + Form: { + 'report-type': string; + 'template-id': string; + 'subscribe-id': string; + }; + Input: { + 'adjust-position': string; + }; + Textarea: { + 'confirm-type': string; + 'confirm-hold': string; + 'show-confirm-bar': string; + 'adjust-position': string; + }; + Navigator: { + target: string; + 'app-id': string; + path: string; + 'extra-data': string; + version: string; + }; + Image: { + webp: string; + 'image-menu-prevent': string; + preview: string; + 'original-src': string; + }; + Video: { + title: string; + 'show-no-wifi-tip': string; + 'vslide-gesture': string; + 'vslide-gesture-in-fullscreen': string; + 'enable-play-gesture': string; + 'show-rate-btn': string; + 'show-vslide-btn-in-fullscreen': string; + 'silent-play': string; + bindLoadedMetadata: string; + }; + Ad: { + appid: string; + apid: string; + type: string; + updatetime: string; + bindStatus: string; + }; + Tabs: { + 'tabs-background-color': string; + 'tabs-active-text-color': string; + 'tabs-inactive-text-color': string; + 'tabs-underline-color': string; + 'active-name': string; + 'url-query-name': string; + 'max-tab-item-amount': string; + bindTabChange: string; + }; + TabItem: { + label: string; + name: string; + 'badge-type': string; + 'badge-text': string; + }; + AnimationVideo: { + 'resource-width': string; + 'resource-height': string; + 'canvas-style': string; + path: string; + loop: string; + autoplay: string; + bindStarted: string; + bindEnded: string; + }; + AnimationView: { + path: string; + loop: string; + autoplay: string; + action: string; + hidden: string; + bindEnded: string; + }; + ArCamera: { + key: string; + type: string; + flash: string; + bindError: string; + bindLoad: string; + bindMessage: string; + bindScanCode: string; + }; + RtcRoom: { + id: string; + 'enable-camera': string; + 'enable-auto-focus': string; + 'enable-zoom': string; + 'device-position': string; + 'enable-mic': string; + 'enable-agc': string; + 'enable-ans': string; + bitrate: string; + 'video-width': string; + 'video-height': string; + 'enable-remote-mirror': string; + 'local-mirror': string; + 'sound-mode': string; + bindStateChange: string; + bindError: string; + }; + RtcRoomItem: { + id: string; + type: string; + 'user-id': string; + }; + OpenData: { + type: string; + }; +}; diff --git a/packages/taro-swan/types/index.d.ts b/packages/taro-swan/types/index.d.ts new file mode 100644 index 000000000000..2283e99145cd --- /dev/null +++ b/packages/taro-swan/types/index.d.ts @@ -0,0 +1,5 @@ +import Swan from './program'; +import type { IPluginContext } from '@tarojs/service'; +export { Swan }; +declare const _default: (ctx: IPluginContext) => void; +export default _default; diff --git a/packages/taro-swan/types/program.d.ts b/packages/taro-swan/types/program.d.ts new file mode 100644 index 000000000000..0cd6b10a9efc --- /dev/null +++ b/packages/taro-swan/types/program.d.ts @@ -0,0 +1,27 @@ +import { TaroPlatformBase } from '@tarojs/shared'; +import { Template } from './template'; +export default class Swan extends TaroPlatformBase { + platform: string; + globalObject: string; + projectConfigJson: string; + fileType: { + templ: string; + style: string; + config: string; + script: string; + xs: string; + }; + template: Template; + /** + * 调用 mini-runner 开启编译 + */ + start(): Promise; + /** + * 增加组件或修改组件属性 + */ + modifyComponents(): void; + /** + * 修改 webpack 配置 + */ + modifyWebpackChain(): void; +} diff --git a/packages/taro-swan/types/runtime.d.ts b/packages/taro-swan/types/runtime.d.ts new file mode 100644 index 000000000000..5448c1d735d7 --- /dev/null +++ b/packages/taro-swan/types/runtime.d.ts @@ -0,0 +1,3 @@ +export declare const hostConfig: { + log: () => void; +}; diff --git a/packages/taro-swan/types/template.d.ts b/packages/taro-swan/types/template.d.ts new file mode 100644 index 000000000000..411c94314de4 --- /dev/null +++ b/packages/taro-swan/types/template.d.ts @@ -0,0 +1,19 @@ +import { RecursiveTemplate } from '@tarojs/shared'; +export declare class Template extends RecursiveTemplate { + supportXS: boolean; + Adapter: { + if: string; + else: string; + elseif: string; + for: string; + forItem: string; + forIndex: string; + key: string; + xs: string; + type: string; + }; + buildXsTemplate(): string; + dataKeymap(keymap: string): string; + getAttrValue(value: string, key: string, nodeName: string): string; + modifyLoopBody: (child: string, nodeName: string) => string; +} From 12d35bb1831b716de633039bf0b70d6396e15396 Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 17:12:07 +0800 Subject: [PATCH 009/272] =?UTF-8?q?chore(taro-weapp):=20=E5=88=86=E7=A6=BB?= =?UTF-8?q?=E5=87=BA=20qq=20=E5=B9=B3=E5=8F=B0=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/taro-qq/README.md | 3 ++ packages/taro-qq/index.js | 2 ++ packages/taro-qq/package.json | 32 +++++++++++++++++++++ packages/taro-qq/src/components.ts | 8 ++++++ packages/taro-qq/src/index.ts | 13 +++++++++ packages/taro-qq/src/program.ts | 45 ++++++++++++++++++++++++++++++ packages/taro-qq/src/runtime.ts | 5 ++++ packages/taro-qq/tsconfig.json | 25 +++++++++++++++++ 8 files changed, 133 insertions(+) create mode 100644 packages/taro-qq/README.md create mode 100644 packages/taro-qq/index.js create mode 100644 packages/taro-qq/package.json create mode 100644 packages/taro-qq/src/components.ts create mode 100644 packages/taro-qq/src/index.ts create mode 100644 packages/taro-qq/src/program.ts create mode 100644 packages/taro-qq/src/runtime.ts create mode 100644 packages/taro-qq/tsconfig.json diff --git a/packages/taro-qq/README.md b/packages/taro-qq/README.md new file mode 100644 index 000000000000..1d71d3cf4b96 --- /dev/null +++ b/packages/taro-qq/README.md @@ -0,0 +1,3 @@ +# `@tarojs/plugin-platform-qq` + +Taro 插件。用于支持编译为 QQ 小程序。 diff --git a/packages/taro-qq/index.js b/packages/taro-qq/index.js new file mode 100644 index 000000000000..437a6d4788f4 --- /dev/null +++ b/packages/taro-qq/index.js @@ -0,0 +1,2 @@ +module.exports = require('./dist/index.js').default +module.exports.default = module.exports diff --git a/packages/taro-qq/package.json b/packages/taro-qq/package.json new file mode 100644 index 000000000000..537a295b0b85 --- /dev/null +++ b/packages/taro-qq/package.json @@ -0,0 +1,32 @@ +{ + "name": "@tarojs/plugin-platform-qq", + "version": "3.0.9", + "description": "QQ 小程序平台插件", + "author": "Chen-jj", + "homepage": "https://github.com/nervjs/taro/tree/master/packages/taro-qq#readme", + "license": "MIT", + "main": "index.js", + "keywords": [ + "taro" + ], + "files": [ + "index.js", + "dist" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/NervJS/taro.git" + }, + "scripts": { + "build": "tsc", + "dev": "tsc -w" + }, + "bugs": { + "url": "https://github.com/NervJS/taro/issues" + }, + "dependencies": { + "@tarojs/plugin-platform-weapp": "3.0.9", + "@tarojs/service": "3.0.9", + "@tarojs/shared": "3.0.9" + } +} diff --git a/packages/taro-qq/src/components.ts b/packages/taro-qq/src/components.ts new file mode 100644 index 000000000000..394a9d26ad38 --- /dev/null +++ b/packages/taro-qq/src/components.ts @@ -0,0 +1,8 @@ +export const components = { + // ======== 调整属性 ======== + Button: { + 'app-packagename': '', + 'app-bundleid': '', + 'app-connect-id': '' + } +} diff --git a/packages/taro-qq/src/index.ts b/packages/taro-qq/src/index.ts new file mode 100644 index 000000000000..17f8eaca9cb7 --- /dev/null +++ b/packages/taro-qq/src/index.ts @@ -0,0 +1,13 @@ +import QQ from './program' +import type { IPluginContext } from '@tarojs/service' + +export default (ctx: IPluginContext) => { + ctx.registerPlatform({ + name: 'qq', + useConfigName: 'mini', + async fn ({ config }) { + const program = new QQ(ctx, config) + program.start() + } + }) +} diff --git a/packages/taro-qq/src/program.ts b/packages/taro-qq/src/program.ts new file mode 100644 index 000000000000..d7156b3f38af --- /dev/null +++ b/packages/taro-qq/src/program.ts @@ -0,0 +1,45 @@ +import { Weapp } from '@tarojs/plugin-platform-weapp' +import { components } from './components' + +export default class QQ extends Weapp { + platform = 'qq' + globalObject = 'qq' + projectConfigJson = 'project.qq.json' + fileType = { + templ: '.qml', + style: '.qss', + config: '.json', + script: '.js', + xs: '.wxs' + } + + constructor (ctx, config) { + super(ctx, config) + + this.template.Adapter = { + if: 'qq:if', + else: 'qq:else', + elseif: 'qq:elif', + for: 'qq:for', + forItem: 'qq:for-item', + forIndex: 'qq:for-index', + key: 'qq:key', + xs: 'wxs', + type: 'qq' + } + } + + /** + * 增加组件或修改组件属性 + */ + modifyComponents () { + const { internalComponents } = this.template + const { recursiveMerge } = this.ctx.helper + + // 先按微信标准对齐组件 + super.modifyComponents() + + // 再处理 QQ 与微信的组件差异 + recursiveMerge(internalComponents, components) + } +} diff --git a/packages/taro-qq/src/runtime.ts b/packages/taro-qq/src/runtime.ts new file mode 100644 index 000000000000..93cb5c7be947 --- /dev/null +++ b/packages/taro-qq/src/runtime.ts @@ -0,0 +1,5 @@ +export const hostConfig = { + log: function () { + console.log('ok') + } +} diff --git a/packages/taro-qq/tsconfig.json b/packages/taro-qq/tsconfig.json new file mode 100644 index 000000000000..5bcbde76d437 --- /dev/null +++ b/packages/taro-qq/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "target": "es2017", + "module": "CommonJS", + "rootDir": "./src", + "outDir": "dist", + "sourceMap": true, + "baseUrl": ".", + "noImplicitAny": false, + "noUnusedLocals": true, + "removeComments": false, + "strictNullChecks": true, + "allowSyntheticDefaultImports": true, + "experimentalDecorators": true, + "moduleResolution": "node", + }, + "include": [ + "./src" + ], + "exclude": [ + "**/*.test.ts", + "**/*.spec.ts" + ], + "compileOnSave": false +} From 787b6a133752886ed8a9912757d940415d42e611 Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 17:12:16 +0800 Subject: [PATCH 010/272] =?UTF-8?q?chore(taro-weapp):=20=E5=88=86=E7=A6=BB?= =?UTF-8?q?=E5=87=BA=20jd=20=E5=B9=B3=E5=8F=B0=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/taro-jd/README.md | 3 +++ packages/taro-jd/index.js | 3 +++ packages/taro-jd/package.json | 33 ++++++++++++++++++++++++++++ packages/taro-jd/src/index.ts | 16 ++++++++++++++ packages/taro-jd/src/program.ts | 28 +++++++++++++++++++++++ packages/taro-jd/src/runtime.ts | 5 +++++ packages/taro-jd/src/template.ts | 21 ++++++++++++++++++ packages/taro-jd/tsconfig.json | 27 +++++++++++++++++++++++ packages/taro-jd/types/index.d.ts | 5 +++++ packages/taro-jd/types/program.d.ts | 18 +++++++++++++++ packages/taro-jd/types/runtime.d.ts | 3 +++ packages/taro-jd/types/template.d.ts | 15 +++++++++++++ 12 files changed, 177 insertions(+) create mode 100644 packages/taro-jd/README.md create mode 100644 packages/taro-jd/index.js create mode 100644 packages/taro-jd/package.json create mode 100644 packages/taro-jd/src/index.ts create mode 100644 packages/taro-jd/src/program.ts create mode 100644 packages/taro-jd/src/runtime.ts create mode 100644 packages/taro-jd/src/template.ts create mode 100644 packages/taro-jd/tsconfig.json create mode 100644 packages/taro-jd/types/index.d.ts create mode 100644 packages/taro-jd/types/program.d.ts create mode 100644 packages/taro-jd/types/runtime.d.ts create mode 100644 packages/taro-jd/types/template.d.ts diff --git a/packages/taro-jd/README.md b/packages/taro-jd/README.md new file mode 100644 index 000000000000..57d5211ca981 --- /dev/null +++ b/packages/taro-jd/README.md @@ -0,0 +1,3 @@ +# `@tarojs/plugin-platform-jd` + +Taro 插件。用于支持编译为京东小程序。 diff --git a/packages/taro-jd/index.js b/packages/taro-jd/index.js new file mode 100644 index 000000000000..d10e007191bd --- /dev/null +++ b/packages/taro-jd/index.js @@ -0,0 +1,3 @@ +module.exports = require('./dist/index.js').default +module.exports.default = module.exports +module.exports.JD = require('./dist/index.js').JD diff --git a/packages/taro-jd/package.json b/packages/taro-jd/package.json new file mode 100644 index 000000000000..72632af38de1 --- /dev/null +++ b/packages/taro-jd/package.json @@ -0,0 +1,33 @@ +{ + "name": "@tarojs/plugin-platform-jd", + "version": "3.0.9", + "description": "京东小程序平台插件", + "author": "Chen-jj", + "homepage": "https://github.com/nervjs/taro/tree/master/packages/taro-jd#readme", + "license": "MIT", + "main": "index.js", + "keywords": [ + "taro" + ], + "files": [ + "index.js", + "dist", + "types" + ], + "types": "types/index.d.ts", + "repository": { + "type": "git", + "url": "git+https://github.com/NervJS/taro.git" + }, + "scripts": { + "build": "tsc", + "dev": "tsc -w" + }, + "bugs": { + "url": "https://github.com/NervJS/taro/issues" + }, + "dependencies": { + "@tarojs/service": "3.0.9", + "@tarojs/shared": "3.0.9" + } +} diff --git a/packages/taro-jd/src/index.ts b/packages/taro-jd/src/index.ts new file mode 100644 index 000000000000..e255168243fa --- /dev/null +++ b/packages/taro-jd/src/index.ts @@ -0,0 +1,16 @@ +import JD from './program' +import type { IPluginContext } from '@tarojs/service' + +// 让其它平台插件可以继承此平台 +export { JD } + +export default (ctx: IPluginContext) => { + ctx.registerPlatform({ + name: 'jd', + useConfigName: 'mini', + async fn ({ config }) { + const program = new JD(ctx, config) + program.start() + } + }) +} diff --git a/packages/taro-jd/src/program.ts b/packages/taro-jd/src/program.ts new file mode 100644 index 000000000000..2e7b10d263fa --- /dev/null +++ b/packages/taro-jd/src/program.ts @@ -0,0 +1,28 @@ +import { TaroPlatformBase } from '@tarojs/shared' +import { Template } from './template' + +export default class JD extends TaroPlatformBase { + platform = 'jd' + globalObject = 'jd' + projectConfigJson = 'project.jd.json' + fileType = { + templ: '.jxml', + style: '.jxss', + config: '.json', + script: '.js' + } + + template = new Template() + + /** + * 调用 mini-runner 开启编译 + */ + async start () { + this.setup() + this.generateProjectConfig(this.projectConfigJson) + + const runner = await this.getRunner() + const options = this.getBaseOptions() + runner(options) + } +} diff --git a/packages/taro-jd/src/runtime.ts b/packages/taro-jd/src/runtime.ts new file mode 100644 index 000000000000..93cb5c7be947 --- /dev/null +++ b/packages/taro-jd/src/runtime.ts @@ -0,0 +1,5 @@ +export const hostConfig = { + log: function () { + console.log('ok') + } +} diff --git a/packages/taro-jd/src/template.ts b/packages/taro-jd/src/template.ts new file mode 100644 index 000000000000..e27adb2913e3 --- /dev/null +++ b/packages/taro-jd/src/template.ts @@ -0,0 +1,21 @@ +import { UnRecursiveTemplate } from '@tarojs/shared' + +export class Template extends UnRecursiveTemplate { + supportXS = false + Adapter = { + if: 'jd:if', + else: 'jd:else', + elseif: 'jd:elif', + for: 'jd:for', + forItem: 'jd:for-item', + forIndex: 'jd:for-index', + key: 'jd:key', + type: 'jd' + } + + replacePropName (name, value) { + if (name === 'bingdlongtap') return 'bindlongpress' + if (value === 'eh') return name.toLowerCase() + return name + } +} diff --git a/packages/taro-jd/tsconfig.json b/packages/taro-jd/tsconfig.json new file mode 100644 index 000000000000..77fe04ab51c3 --- /dev/null +++ b/packages/taro-jd/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "es2017", + "module": "CommonJS", + "rootDir": "./src", + "outDir": "dist", + "sourceMap": true, + "baseUrl": ".", + "noImplicitAny": false, + "noUnusedLocals": true, + "removeComments": false, + "strictNullChecks": true, + "allowSyntheticDefaultImports": true, + "experimentalDecorators": true, + "moduleResolution": "node", + "declaration": true, + "declarationDir": "types" + }, + "include": [ + "./src" + ], + "exclude": [ + "**/*.test.ts", + "**/*.spec.ts" + ], + "compileOnSave": false +} diff --git a/packages/taro-jd/types/index.d.ts b/packages/taro-jd/types/index.d.ts new file mode 100644 index 000000000000..fced9aa83114 --- /dev/null +++ b/packages/taro-jd/types/index.d.ts @@ -0,0 +1,5 @@ +import JD from './program'; +import type { IPluginContext } from '@tarojs/service'; +export { JD }; +declare const _default: (ctx: IPluginContext) => void; +export default _default; diff --git a/packages/taro-jd/types/program.d.ts b/packages/taro-jd/types/program.d.ts new file mode 100644 index 000000000000..860d24197ae1 --- /dev/null +++ b/packages/taro-jd/types/program.d.ts @@ -0,0 +1,18 @@ +import { TaroPlatformBase } from '@tarojs/shared'; +import { Template } from './template'; +export default class JD extends TaroPlatformBase { + platform: string; + globalObject: string; + projectConfigJson: string; + fileType: { + templ: string; + style: string; + config: string; + script: string; + }; + template: Template; + /** + * 调用 mini-runner 开启编译 + */ + start(): Promise; +} diff --git a/packages/taro-jd/types/runtime.d.ts b/packages/taro-jd/types/runtime.d.ts new file mode 100644 index 000000000000..5448c1d735d7 --- /dev/null +++ b/packages/taro-jd/types/runtime.d.ts @@ -0,0 +1,3 @@ +export declare const hostConfig: { + log: () => void; +}; diff --git a/packages/taro-jd/types/template.d.ts b/packages/taro-jd/types/template.d.ts new file mode 100644 index 000000000000..3fe3e05511ee --- /dev/null +++ b/packages/taro-jd/types/template.d.ts @@ -0,0 +1,15 @@ +import { UnRecursiveTemplate } from '@tarojs/shared'; +export declare class Template extends UnRecursiveTemplate { + supportXS: boolean; + Adapter: { + if: string; + else: string; + elseif: string; + for: string; + forItem: string; + forIndex: string; + key: string; + type: string; + }; + replacePropName(name: any, value: any): any; +} From cc22115eb403980c726eaea997cfe9a1242da348 Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 15 Sep 2020 17:12:27 +0800 Subject: [PATCH 011/272] =?UTF-8?q?chore(taro-weapp):=20=E5=88=86=E7=A6=BB?= =?UTF-8?q?=E5=87=BA=20alipay=20=E5=B9=B3=E5=8F=B0=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/taro-alipay/README.md | 3 + packages/taro-alipay/index.js | 3 + packages/taro-alipay/package.json | 33 +++++ packages/taro-alipay/src/components-react.ts | 42 +++++++ packages/taro-alipay/src/components.ts | 116 ++++++++++++++++++ packages/taro-alipay/src/index.ts | 16 +++ packages/taro-alipay/src/program.ts | 84 +++++++++++++ packages/taro-alipay/src/runtime.ts | 5 + packages/taro-alipay/src/template.ts | 82 +++++++++++++ packages/taro-alipay/tsconfig.json | 27 ++++ .../taro-alipay/types/components-react.d.ts | 41 +++++++ packages/taro-alipay/types/components.d.ts | 112 +++++++++++++++++ packages/taro-alipay/types/index.d.ts | 5 + packages/taro-alipay/types/program.d.ts | 34 +++++ packages/taro-alipay/types/runtime.d.ts | 3 + packages/taro-alipay/types/template.d.ts | 29 +++++ 16 files changed, 635 insertions(+) create mode 100644 packages/taro-alipay/README.md create mode 100644 packages/taro-alipay/index.js create mode 100644 packages/taro-alipay/package.json create mode 100644 packages/taro-alipay/src/components-react.ts create mode 100644 packages/taro-alipay/src/components.ts create mode 100644 packages/taro-alipay/src/index.ts create mode 100644 packages/taro-alipay/src/program.ts create mode 100644 packages/taro-alipay/src/runtime.ts create mode 100644 packages/taro-alipay/src/template.ts create mode 100644 packages/taro-alipay/tsconfig.json create mode 100644 packages/taro-alipay/types/components-react.d.ts create mode 100644 packages/taro-alipay/types/components.d.ts create mode 100644 packages/taro-alipay/types/index.d.ts create mode 100644 packages/taro-alipay/types/program.d.ts create mode 100644 packages/taro-alipay/types/runtime.d.ts create mode 100644 packages/taro-alipay/types/template.d.ts diff --git a/packages/taro-alipay/README.md b/packages/taro-alipay/README.md new file mode 100644 index 000000000000..b01c6beddda6 --- /dev/null +++ b/packages/taro-alipay/README.md @@ -0,0 +1,3 @@ +# `@tarojs/plugin-platform-alipay` + +Taro 插件。用于支持编译为支付宝小程序。 diff --git a/packages/taro-alipay/index.js b/packages/taro-alipay/index.js new file mode 100644 index 000000000000..d347cc7109f9 --- /dev/null +++ b/packages/taro-alipay/index.js @@ -0,0 +1,3 @@ +module.exports = require('./dist/index.js').default +module.exports.default = module.exports +module.exports.Alipay = require('./dist/index.js').Alipay diff --git a/packages/taro-alipay/package.json b/packages/taro-alipay/package.json new file mode 100644 index 000000000000..2ebc0fc669f4 --- /dev/null +++ b/packages/taro-alipay/package.json @@ -0,0 +1,33 @@ +{ + "name": "@tarojs/plugin-platform-alipay", + "version": "3.0.9", + "description": "支付宝小程序平台插件", + "author": "Chen-jj", + "homepage": "https://github.com/nervjs/taro/tree/master/packages/taro-alipay#readme", + "license": "MIT", + "main": "index.js", + "keywords": [ + "taro" + ], + "files": [ + "index.js", + "dist", + "types" + ], + "types": "types/index.d.ts", + "repository": { + "type": "git", + "url": "git+https://github.com/NervJS/taro.git" + }, + "scripts": { + "build": "tsc", + "dev": "tsc -w" + }, + "bugs": { + "url": "https://github.com/NervJS/taro/issues" + }, + "dependencies": { + "@tarojs/service": "3.0.9", + "@tarojs/shared": "3.0.9" + } +} diff --git a/packages/taro-alipay/src/components-react.ts b/packages/taro-alipay/src/components-react.ts new file mode 100644 index 000000000000..16956d1e75b6 --- /dev/null +++ b/packages/taro-alipay/src/components-react.ts @@ -0,0 +1,42 @@ +// For React.createElement's type +export const View = 'view' +export const Icon = 'icon' +export const Progress = 'progress' +export const RichText = 'rich-text' +export const Text = 'text' +export const Button = 'button' +export const Checkbox = 'checkbox' +export const CheckboxGroup = 'checkbox-group' +export const Form = 'form' +export const Input = 'input' +export const Label = 'label' +export const Picker = 'picker' +export const PickerView = 'picker-view' +export const PickerViewColumn = 'picker-view-column' +export const Radio = 'radio' +export const RadioGroup = 'radio-group' +export const Slider = 'slider' +export const Switch = 'switch' +export const CoverImage = 'cover-image' +export const Textarea = 'textarea' +export const CoverView = 'cover-view' +export const MovableArea = 'movable-area' +export const MovableView = 'movable-view' +export const ScrollView = 'scroll-view' +export const Swiper = 'swiper' +export const SwiperItem = 'swiper-item' +export const Navigator = 'navigator' +export const Audio = 'audio' +export const Camera = 'camera' +export const Image = 'image' +export const LivePlayer = 'live-player' +export const Video = 'video' +export const Canvas = 'canvas' +export const Ad = 'ad' +export const WebView = 'web-view' +export const Block = 'block' +export const Map = 'map' +export const Slot = 'slot' +export const Lottie = 'lottie' +export const Lifestyle = 'lifestyle' +export const ContactButton = 'contact-button' diff --git a/packages/taro-alipay/src/components.ts b/packages/taro-alipay/src/components.ts new file mode 100644 index 000000000000..5e840265c61c --- /dev/null +++ b/packages/taro-alipay/src/components.ts @@ -0,0 +1,116 @@ +import { singleQuote } from '@tarojs/shared' + +export const components = { + // ======== 调整属性 ======== + View: { + 'disable-scroll': 'false', + hidden: 'false', + bindAppear: '', + bindDisappear: '', + bindFirstAppear: '' + }, + Text: { + 'number-of-lines': '' + }, + Map: { + skew: '0', + rotate: '0', + polygon: '[]', + 'include-padding': '', + 'ground-overlays': '', + 'tile-overlay': '', + 'custom-map-style': '', + setting: '', + bindRegionChange: '', + bindPanelTap: '' + }, + Button: { + scope: '', + 'public-id': '', + bindGetAuthorize: '', + bindError: '' + }, + Checkbox: { + bindChange: '' + }, + Input: { + 'random-number': 'false', + controlled: 'false' + }, + Slider: { + 'track-size': '4', + 'handle-size': '22', + 'handle-color': singleQuote('#ffffff') + }, + Switch: { + controlled: 'false' + }, + Textarea: { + 'show-count': 'true', + controlled: 'false' + }, + MovableView: { + bindChangeEnd: '' + }, + ScrollView: { + 'scroll-animation-duration': '', + 'trap-scroll': 'false' + }, + Swiper: { + 'active-class': '', + 'changing-class': '', + acceleration: 'false', + 'disable-programmatic-animation': 'false', + 'disable-touch': 'false', + bindAnimationEnd: '' + }, + Image: { + 'default-source': '' + }, + Canvas: { + width: singleQuote('300px'), + height: singleQuote('225px') + }, + Video: { + 'poster-size': singleQuote('contain'), + 'mobilenet-hint-type': '1', + bindLoading: '', + bindUserAction: '', + bindStop: '', + bindRenderStart: '' + }, + // ======== 额外组件 ======== + Lottie: { + autoplay: 'false', + path: '', + speed: '1.0', + repeatCount: '0', + autoReverse: 'false', + assetsPath: '', + placeholder: '', + djangoId: '', + md5: '', + optimize: 'false', + bindDataReady: '', + bindDataFailed: '', + bindAnimationStart: '', + bindAnimationEnd: '', + bindAnimationRepeat: '', + bindAnimationCancel: '', + bindDataLoadReady: '' + }, + Lifestyle: { + 'public-id': '', + memo: '', + bindFollow: '' + }, + ContactButton: { + 'tnt-inst-id': '', + scene: '', + size: '25', + color: singleQuote('#00A3FF'), + icon: '', + 'alipay-card-no': '', + 'ext-info': '' + } +} diff --git a/packages/taro-alipay/src/index.ts b/packages/taro-alipay/src/index.ts new file mode 100644 index 000000000000..3206337f2934 --- /dev/null +++ b/packages/taro-alipay/src/index.ts @@ -0,0 +1,16 @@ +import Alipay from './program' +import type { IPluginContext } from '@tarojs/service' + +// 让其它平台插件可以继承此平台 +export { Alipay } + +export default (ctx: IPluginContext) => { + ctx.registerPlatform({ + name: 'alipay', + useConfigName: 'mini', + async fn ({ config }) { + const program = new Alipay(ctx, config) + program.start() + } + }) +} diff --git a/packages/taro-alipay/src/program.ts b/packages/taro-alipay/src/program.ts new file mode 100644 index 000000000000..1df5f86609a0 --- /dev/null +++ b/packages/taro-alipay/src/program.ts @@ -0,0 +1,84 @@ +import { TaroPlatformBase } from '@tarojs/shared' +import { Template } from './template' +import { components } from './components' + +export default class Alipay extends TaroPlatformBase { + platform = 'alipay' + globalObject = 'my' + fileType = { + templ: '.axml', + style: '.acss', + config: '.json', + script: '.js', + xs: '.sjs' + } + + template = new Template() + + /** + * 调用 mini-runner 开启编译 + */ + async start () { + this.setup() + this.modifyMiniConfigs() + this.modifyComponents() + this.modifyWebpackChain() + + const runner = await this.getRunner() + const options = this.getBaseOptions() + runner(options) + } + + /** + * 转换用户编写的配置(微信小程序标准)为支付宝小程序标准 + */ + modifyMiniConfigs () { + this.ctx.modifyMiniConfigs(({ configMap }) => { + const replaceKeyMap = { + navigationBarTitleText: 'defaultTitle', + navigationBarBackgroundColor: 'titleBarColor', + enablePullDownRefresh: 'pullRefresh', + list: 'items', + text: 'name', + iconPath: 'icon', + selectedIconPath: 'activeIcon', + color: 'textColor' + } + Object.keys(configMap).forEach(key => { + const item = configMap[key] + if (item.content) { + this.recursiveReplaceObjectKeys(item.content, replaceKeyMap) + } + }) + }) + } + + /** + * 增加组件或修改组件属性 + */ + modifyComponents () { + const { internalComponents } = this.template + const { recursiveMerge } = this.ctx.helper + + recursiveMerge(internalComponents, components) + this.modifySlider(internalComponents.Slider) + } + + /** + * 修改 Slider 组件属性 + */ + modifySlider (slider) { + delete slider['block-size'] + delete slider['block-color'] + } + + /** + * 修改 webpack 配置 + */ + modifyWebpackChain () { + this.ctx.modifyWebpackChain(({ chain }) => { + const { taroJsComponents } = this.helper + chain.resolve.alias.set(taroJsComponents + '$', '@tarojs/plugin-platform-alipay/dist/components-react.js') + }) + } +} diff --git a/packages/taro-alipay/src/runtime.ts b/packages/taro-alipay/src/runtime.ts new file mode 100644 index 000000000000..93cb5c7be947 --- /dev/null +++ b/packages/taro-alipay/src/runtime.ts @@ -0,0 +1,5 @@ +export const hostConfig = { + log: function () { + console.log('ok') + } +} diff --git a/packages/taro-alipay/src/template.ts b/packages/taro-alipay/src/template.ts new file mode 100644 index 000000000000..daec3fa901ec --- /dev/null +++ b/packages/taro-alipay/src/template.ts @@ -0,0 +1,82 @@ +import { RecursiveTemplate, capitalize, toCamelCase } from '@tarojs/shared' + +export class Template extends RecursiveTemplate { + exportExpr = 'export default' + supportXS = true + Adapter = { + if: 'a:if', + else: 'a:else', + elseif: 'a:elif', + for: 'a:for', + forItem: 'a:for-item', + forIndex: 'a:for-index', + key: 'a:key', + xs: 'sjs', + type: 'alipay' + } + + buildXsTemplate () { + return '' + } + + replacePropName (name, value) { + if (value === 'eh') return name.replace('bind', 'on') + return name + } + + getEvents () { + return { + onTap: 'eh', + onTouchMove: 'eh', + onTouchEnd: 'eh', + onTouchCancel: 'eh', + onLongTap: 'eh' + } + } + + buildThirdPartyAttr (attrs: Set) { + return [...attrs].reduce((str, attr) => { + if (attr.startsWith('@')) { + return str + `on${capitalize(attr.slice(1))}="eh" ` + } else if (attr.startsWith('bind')) { + return str + `${attr}="eh" ` + } else if (attr.startsWith('on')) { + return str + `${attr}="eh" ` + } + + return str + `${attr}="{{ i.${toCamelCase(attr)} }}" ` + }, '') + } + + modifyLoopBody = (child: string, nodeName: string) => { + if (nodeName === 'picker-view') { + return ` + + ${child} + + ` + } + if (nodeName === 'swiper') { + return ` + + ${child} + + ` + } + return child + } + + modifyLoopContainer = (children: string, nodeName: string) => { + if (nodeName === 'picker') { + return ` + ${children} + ` + } + return children + } + + modifyTemplateResult = (res: string, nodeName: string) => { + if (nodeName === 'picker-view-column' || nodeName === 'swiper-item') return '' + return res + } +} diff --git a/packages/taro-alipay/tsconfig.json b/packages/taro-alipay/tsconfig.json new file mode 100644 index 000000000000..77fe04ab51c3 --- /dev/null +++ b/packages/taro-alipay/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "es2017", + "module": "CommonJS", + "rootDir": "./src", + "outDir": "dist", + "sourceMap": true, + "baseUrl": ".", + "noImplicitAny": false, + "noUnusedLocals": true, + "removeComments": false, + "strictNullChecks": true, + "allowSyntheticDefaultImports": true, + "experimentalDecorators": true, + "moduleResolution": "node", + "declaration": true, + "declarationDir": "types" + }, + "include": [ + "./src" + ], + "exclude": [ + "**/*.test.ts", + "**/*.spec.ts" + ], + "compileOnSave": false +} diff --git a/packages/taro-alipay/types/components-react.d.ts b/packages/taro-alipay/types/components-react.d.ts new file mode 100644 index 000000000000..831068e20bac --- /dev/null +++ b/packages/taro-alipay/types/components-react.d.ts @@ -0,0 +1,41 @@ +export declare const View = "view"; +export declare const Icon = "icon"; +export declare const Progress = "progress"; +export declare const RichText = "rich-text"; +export declare const Text = "text"; +export declare const Button = "button"; +export declare const Checkbox = "checkbox"; +export declare const CheckboxGroup = "checkbox-group"; +export declare const Form = "form"; +export declare const Input = "input"; +export declare const Label = "label"; +export declare const Picker = "picker"; +export declare const PickerView = "picker-view"; +export declare const PickerViewColumn = "picker-view-column"; +export declare const Radio = "radio"; +export declare const RadioGroup = "radio-group"; +export declare const Slider = "slider"; +export declare const Switch = "switch"; +export declare const CoverImage = "cover-image"; +export declare const Textarea = "textarea"; +export declare const CoverView = "cover-view"; +export declare const MovableArea = "movable-area"; +export declare const MovableView = "movable-view"; +export declare const ScrollView = "scroll-view"; +export declare const Swiper = "swiper"; +export declare const SwiperItem = "swiper-item"; +export declare const Navigator = "navigator"; +export declare const Audio = "audio"; +export declare const Camera = "camera"; +export declare const Image = "image"; +export declare const LivePlayer = "live-player"; +export declare const Video = "video"; +export declare const Canvas = "canvas"; +export declare const Ad = "ad"; +export declare const WebView = "web-view"; +export declare const Block = "block"; +export declare const Map = "map"; +export declare const Slot = "slot"; +export declare const Lottie = "lottie"; +export declare const Lifestyle = "lifestyle"; +export declare const ContactButton = "contact-button"; diff --git a/packages/taro-alipay/types/components.d.ts b/packages/taro-alipay/types/components.d.ts new file mode 100644 index 000000000000..bdf380636356 --- /dev/null +++ b/packages/taro-alipay/types/components.d.ts @@ -0,0 +1,112 @@ +export declare const components: { + View: { + 'disable-scroll': string; + hidden: string; + bindAppear: string; + bindDisappear: string; + bindFirstAppear: string; + }; + Text: { + 'number-of-lines': string; + }; + Map: { + skew: string; + rotate: string; + polygon: string; + 'include-padding': string; + 'ground-overlays': string; + 'tile-overlay': string; + 'custom-map-style': string; + setting: string; + bindRegionChange: string; + bindPanelTap: string; + }; + Button: { + scope: string; + 'public-id': string; + bindGetAuthorize: string; + bindError: string; + }; + Checkbox: { + bindChange: string; + }; + Input: { + 'random-number': string; + controlled: string; + }; + Slider: { + 'track-size': string; + 'handle-size': string; + 'handle-color': string; + }; + Switch: { + controlled: string; + }; + Textarea: { + 'show-count': string; + controlled: string; + }; + MovableView: { + bindChangeEnd: string; + }; + ScrollView: { + 'scroll-animation-duration': string; + 'trap-scroll': string; + }; + Swiper: { + 'active-class': string; + 'changing-class': string; + acceleration: string; + 'disable-programmatic-animation': string; + 'disable-touch': string; + bindAnimationEnd: string; + }; + Image: { + 'default-source': string; + }; + Canvas: { + width: string; + height: string; + }; + Video: { + 'poster-size': string; + 'mobilenet-hint-type': string; + bindLoading: string; + bindUserAction: string; + bindStop: string; + bindRenderStart: string; + }; + Lottie: { + autoplay: string; + path: string; + speed: string; + repeatCount: string; + autoReverse: string; + assetsPath: string; + placeholder: string; + djangoId: string; + md5: string; + optimize: string; + bindDataReady: string; + bindDataFailed: string; + bindAnimationStart: string; + bindAnimationEnd: string; + bindAnimationRepeat: string; + bindAnimationCancel: string; + bindDataLoadReady: string; + }; + Lifestyle: { + 'public-id': string; + memo: string; + bindFollow: string; + }; + ContactButton: { + 'tnt-inst-id': string; + scene: string; + size: string; + color: string; + icon: string; + 'alipay-card-no': string; + 'ext-info': string; + }; +}; diff --git a/packages/taro-alipay/types/index.d.ts b/packages/taro-alipay/types/index.d.ts new file mode 100644 index 000000000000..04101be90a9c --- /dev/null +++ b/packages/taro-alipay/types/index.d.ts @@ -0,0 +1,5 @@ +import Alipay from './program'; +import type { IPluginContext } from '@tarojs/service'; +export { Alipay }; +declare const _default: (ctx: IPluginContext) => void; +export default _default; diff --git a/packages/taro-alipay/types/program.d.ts b/packages/taro-alipay/types/program.d.ts new file mode 100644 index 000000000000..f1373296bc0e --- /dev/null +++ b/packages/taro-alipay/types/program.d.ts @@ -0,0 +1,34 @@ +import { TaroPlatformBase } from '@tarojs/shared'; +import { Template } from './template'; +export default class Alipay extends TaroPlatformBase { + platform: string; + globalObject: string; + fileType: { + templ: string; + style: string; + config: string; + script: string; + xs: string; + }; + template: Template; + /** + * 调用 mini-runner 开启编译 + */ + start(): Promise; + /** + * 转换用户编写的配置(微信小程序标准)为支付宝小程序标准 + */ + modifyMiniConfigs(): void; + /** + * 增加组件或修改组件属性 + */ + modifyComponents(): void; + /** + * 修改 Slider 组件属性 + */ + modifySlider(slider: any): void; + /** + * 修改 webpack 配置 + */ + modifyWebpackChain(): void; +} diff --git a/packages/taro-alipay/types/runtime.d.ts b/packages/taro-alipay/types/runtime.d.ts new file mode 100644 index 000000000000..5448c1d735d7 --- /dev/null +++ b/packages/taro-alipay/types/runtime.d.ts @@ -0,0 +1,3 @@ +export declare const hostConfig: { + log: () => void; +}; diff --git a/packages/taro-alipay/types/template.d.ts b/packages/taro-alipay/types/template.d.ts new file mode 100644 index 000000000000..479877eab1c3 --- /dev/null +++ b/packages/taro-alipay/types/template.d.ts @@ -0,0 +1,29 @@ +import { RecursiveTemplate } from '@tarojs/shared'; +export declare class Template extends RecursiveTemplate { + exportExpr: string; + supportXS: boolean; + Adapter: { + if: string; + else: string; + elseif: string; + for: string; + forItem: string; + forIndex: string; + key: string; + xs: string; + type: string; + }; + buildXsTemplate(): string; + replacePropName(name: any, value: any): any; + getEvents(): { + onTap: string; + onTouchMove: string; + onTouchEnd: string; + onTouchCancel: string; + onLongTap: string; + }; + buildThirdPartyAttr(attrs: Set): string; + modifyLoopBody: (child: string, nodeName: string) => string; + modifyLoopContainer: (children: string, nodeName: string) => string; + modifyTemplateResult: (res: string, nodeName: string) => string; +} From 6f4124b5c4333cc80c14ac5e1b1ac89ac329fa2e Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Wed, 16 Sep 2020 16:48:27 +0800 Subject: [PATCH 012/272] =?UTF-8?q?chore(taro):=20=E5=90=88=E5=B9=B6=20@ta?= =?UTF-8?q?rojs/taro=20=E4=B8=8E=20@tarojs/api?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lerna.json | 1 - packages/taro-api/README.md | 3 - packages/taro-api/package.json | 34 -- packages/taro-api/rollup.config.js | 66 --- packages/taro-helper/src/constants.ts | 7 +- packages/taro/.gitignore | 1 - packages/taro/README.md | 14 +- packages/taro/apis/alipay.js | 462 ------------------ packages/taro/apis/data-cache.js | 15 - packages/taro/apis/jd.js | 255 ---------- packages/taro/apis/qq.js | 253 ---------- packages/taro/apis/swan.js | 181 ------- packages/taro/apis/tt.js | 206 -------- packages/taro/apis/utils.js | 37 -- packages/taro/apis/wx.js | 255 ---------- packages/taro/h5.js | 4 - packages/taro/index.js | 28 +- packages/taro/package.json | 16 +- packages/taro/rollup.config.js | 70 ++- packages/{taro-api => taro}/src/env.js | 0 packages/taro/src/h5-cjs.js | 16 + packages/taro/src/h5.js | 9 + packages/{taro-api => taro}/src/index.js | 33 ++ .../src/interceptor/chain.js | 0 .../src/interceptor/index.js | 0 .../src/interceptor/interceptors.js | 0 .../{taro-api => taro}/src/native-apis.js | 0 packages/{taro-api => taro}/src/polyfill.js | 0 packages/{taro-api => taro}/src/render.js | 0 29 files changed, 122 insertions(+), 1844 deletions(-) delete mode 100644 packages/taro-api/README.md delete mode 100644 packages/taro-api/package.json delete mode 100644 packages/taro-api/rollup.config.js delete mode 100644 packages/taro/.gitignore delete mode 100644 packages/taro/apis/alipay.js delete mode 100644 packages/taro/apis/data-cache.js delete mode 100644 packages/taro/apis/jd.js delete mode 100644 packages/taro/apis/qq.js delete mode 100644 packages/taro/apis/swan.js delete mode 100644 packages/taro/apis/tt.js delete mode 100644 packages/taro/apis/utils.js delete mode 100644 packages/taro/apis/wx.js delete mode 100644 packages/taro/h5.js rename packages/{taro-api => taro}/src/env.js (100%) create mode 100644 packages/taro/src/h5-cjs.js create mode 100644 packages/taro/src/h5.js rename packages/{taro-api => taro}/src/index.js (71%) rename packages/{taro-api => taro}/src/interceptor/chain.js (100%) rename packages/{taro-api => taro}/src/interceptor/index.js (100%) rename packages/{taro-api => taro}/src/interceptor/interceptors.js (100%) rename packages/{taro-api => taro}/src/native-apis.js (100%) rename packages/{taro-api => taro}/src/polyfill.js (100%) rename packages/{taro-api => taro}/src/render.js (100%) diff --git a/lerna.json b/lerna.json index 851214c23997..1af0f163fba0 100644 --- a/lerna.json +++ b/lerna.json @@ -9,7 +9,6 @@ "packages/postcss-pxtransform", "packages/shared", "packages/taro", - "packages/taro-api", "packages/taro-cli", "packages/taro-components", "packages/taro-extend", diff --git a/packages/taro-api/README.md b/packages/taro-api/README.md deleted file mode 100644 index 92eb61240df6..000000000000 --- a/packages/taro-api/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `@tarojs/api` - -暴露给 @tarojs/taro 的所有端的公有 API。`@tarojs/api` 会跨 node/浏览器/小程序/React Native 使用,不得使用/包含平台特有特性。 diff --git a/packages/taro-api/package.json b/packages/taro-api/package.json deleted file mode 100644 index 9bf3b23a88e3..000000000000 --- a/packages/taro-api/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "@tarojs/api", - "version": "3.0.9", - "description": "Taro common API", - "author": "yuche ", - "homepage": "https://github.com/nervjs/taro/tree/master/packages/api#readme", - "license": "MIT", - "main": "dist/index.js", - "module": "dist/index.esm.js", - "directories": { - "lib": "lib", - "test": "__tests__" - }, - "files": [ - "dist" - ], - "publishConfig": { - "access": "public" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/NervJS/taro.git" - }, - "scripts": { - "test": "echo \"Error: run tests from root\" && exit 1", - "build": "rollup -c rollup.config.js" - }, - "bugs": { - "url": "https://github.com/NervJS/taro/issues" - }, - "dependencies": { - "@tarojs/runtime": "3.0.9" - } -} diff --git a/packages/taro-api/rollup.config.js b/packages/taro-api/rollup.config.js deleted file mode 100644 index 054d3206144a..000000000000 --- a/packages/taro-api/rollup.config.js +++ /dev/null @@ -1,66 +0,0 @@ -const { join } = require('path') -const resolve = require('rollup-plugin-node-resolve') -const cjs = require('rollup-plugin-commonjs') -const babel = require('rollup-plugin-babel') -const cwd = __dirname - -const baseConfig = { - input: join(cwd, 'src/index.js'), - external: ['nervjs', '@tarojs/runtime'], - output: [ - { - file: join(cwd, 'dist/index.js'), - format: 'cjs', - sourcemap: true, - exports: 'named' - }, - { - file: join(cwd, 'dist/taro.js'), - format: 'umd', - name: 'Taro', - sourcemap: true, - exports: 'named' - } - ], - plugins: [ - resolve({ - preferBuiltins: false - }), - cjs(), - babel({ - babelrc: false, - presets: [ - ['@babel/preset-env', { - modules: false - }] - ], - plugins: [ - '@babel/plugin-proposal-class-properties', - '@babel/plugin-proposal-object-rest-spread', - ['@babel/plugin-transform-react-jsx', { - pragma: 'Nerv.createElement' - }] - ] - }) - ] -} -const esmConfig = Object.assign({}, baseConfig, { - output: Object.assign({}, baseConfig.output, { - sourcemap: true, - format: 'es', - file: join(cwd, 'dist/index.esm.js') - }) -}) - -function rollup () { - const target = process.env.TARGET - - if (target === 'umd') { - return baseConfig - } else if (target === 'esm') { - return esmConfig - } else { - return [baseConfig, esmConfig] - } -} -module.exports = rollup() diff --git a/packages/taro-helper/src/constants.ts b/packages/taro-helper/src/constants.ts index 3970057aeb64..4b95e4dc159d 100644 --- a/packages/taro-helper/src/constants.ts +++ b/packages/taro-helper/src/constants.ts @@ -135,7 +135,6 @@ export const UPDATE_PACKAGE_LIST = [ 'postcss-pxtransform', '@tarojs/shared', '@tarojs/taro', - '@tarojs/api', '@tarojs/cli', '@tarojs/components', '@tarojs/taro-h5', @@ -150,6 +149,12 @@ export const UPDATE_PACKAGE_LIST = [ '@tarojs/webpack-runner', '@tarojs/with-weapp', '@tarojs/taroize', + '@tarojs/plugin-platform-weapp', + '@tarojs/plugin-platform-alipay', + '@tarojs/plugin-platform-swan', + '@tarojs/plugin-platform-tt', + '@tarojs/plugin-platform-qq', + '@tarojs/plugin-platform-jd', 'nervjs', 'nerv-devtools' ] diff --git a/packages/taro/.gitignore b/packages/taro/.gitignore deleted file mode 100644 index 7951405f85a5..000000000000 --- a/packages/taro/.gitignore +++ /dev/null @@ -1 +0,0 @@ -lib \ No newline at end of file diff --git a/packages/taro/README.md b/packages/taro/README.md index 7efbdd0d0b70..49151c87b026 100644 --- a/packages/taro/README.md +++ b/packages/taro/README.md @@ -1,14 +1,14 @@ -# @tarojs/taro +# `@tarojs/api` -暴露给应用开发者的 Taro 核心 API。包含以下文件: +暴露给 @tarojs/taro 的所有端的公有 API。`@tarojs/api` 会跨 node/浏览器/小程序/React Native 使用,不得使用/包含平台特有特性。 -## index.js +## dist/index.esm.js 小程序端入口文件 -## apis +## dist/h5.esm.js -各小程序平台 API +H5 端入口文件 ## html.css @@ -17,7 +17,3 @@ W3C HTML4 的内置样式,用于 [渲染 HTML](https://taro-docs.jd.com/taro/n ## html5.css Chrome(Blink) HTML5 的内置样式,用于 [渲染 HTML](https://taro-docs.jd.com/taro/next/docs/html.html)。 - -## h5.js - -H5 端入口文件 diff --git a/packages/taro/apis/alipay.js b/packages/taro/apis/alipay.js deleted file mode 100644 index f6c5815c142d..000000000000 --- a/packages/taro/apis/alipay.js +++ /dev/null @@ -1,462 +0,0 @@ -/* eslint-disable no-console */ -import Taro from '@tarojs/api' -import { cacheDataSet, cacheDataGet } from './data-cache' -import { queryToJson, getUniqueKey } from './utils' - -const { - noPromiseApis, - onAndSyncApis, - otherApis, - initPxTransform, - Link -} = Taro - -const apiDiff = { - showActionSheet: { - options: { - change: [{ - old: 'itemList', - new: 'items' - }] - } - }, - showToast: { - options: { - change: [{ - old: 'title', - new: 'content' - }, { - old: 'icon', - new: 'type' - }] - } - }, - showLoading: { - options: { - change: [{ - old: 'title', - new: 'content' - }] - } - }, - setNavigationBarTitle: { - alias: 'setNavigationBar' - }, - setNavigationBarColor: { - alias: 'setNavigationBar' - }, - saveImageToPhotosAlbum: { - alias: 'saveImage', - options: { - change: [{ - old: 'filePath', - new: 'url' - }] - } - }, - previewImage: { - options: { - set: [{ - key: 'current', - value (options) { - return options.urls.indexOf(options.current || options.urls[0]) - } - }] - } - }, - getFileInfo: { - options: { - change: [{ - old: 'filePath', - new: 'apFilePath' - }] - } - }, - getSavedFileInfo: { - options: { - change: [{ - old: 'filePath', - new: 'apFilePath' - }] - } - }, - removeSavedFile: { - options: { - change: [{ - old: 'filePath', - new: 'apFilePath' - }] - } - }, - saveFile: { - options: { - change: [{ - old: 'tempFilePath', - new: 'apFilePath' - }] - } - }, - openLocation: { - options: { - set: [{ - key: 'latitude', - value (options) { - return String(options.latitude) - } - }, { - key: 'longitude', - value (options) { - return String(options.longitude) - } - }] - } - }, - uploadFile: { - options: { - change: [{ - old: 'name', - new: 'fileName' - }] - } - }, - getClipboardData: { - alias: 'getClipboard' - }, - setClipboardData: { - alias: 'setClipboard', - options: { - change: [{ - old: 'data', - new: 'text' - }] - } - }, - makePhoneCall: { - options: { - change: [{ - old: 'phoneNumber', - new: 'number' - }] - } - }, - scanCode: { - alias: 'scan', - options: { - change: [{ - old: 'onlyFromCamera', - new: 'hideAlbum' - }], - set: [{ - key: 'type', - value (options) { - return (options.scanType && options.scanType[0].slice(0, -4)) || 'qr' - } - }] - } - }, - setScreenBrightness: { - options: { - change: [{ - old: 'value', - new: 'brightness' - }] - } - } -} - -const nativeRequest = my.canIUse('request') ? my.request : my.httpRequest - -const RequestQueue = { - MAX_REQUEST: 5, - queue: [], - request (options) { - this.push(options) - // 返回request task - return this.run() - }, - - push (options) { - this.queue.push(options) - }, - - run () { - if (!this.queue.length) { - return - } - if (this.queue.length <= this.MAX_REQUEST) { - const options = this.queue.shift() - const completeFn = options.complete - options.complete = () => { - completeFn && completeFn.apply(options, [...arguments]) - this.run() - } - return nativeRequest(options) - } - } -} - -function taroInterceptor (chain) { - return request(chain.requestParams) -} - -const link = new Link(taroInterceptor) - -function request (options) { - options = options || {} - if (typeof options === 'string') { - options = { - url: options - } - } - const defaultHeaders = { - 'content-type': 'application/json' - } - options.headers = defaultHeaders - if (options.header) { - for (const k in options.header) { - const lowerK = k.toLocaleLowerCase() - options.headers[lowerK] = options.header[k] - } - delete options.header - } - const originSuccess = options.success - const originFail = options.fail - const originComplete = options.complete - let requestTask - const p = new Promise((resolve, reject) => { - options.success = res => { - res.statusCode = res.status - delete res.status - res.header = res.headers - delete res.headers - originSuccess && originSuccess(res) - resolve(res) - } - options.fail = res => { - originFail && originFail(res) - reject(res) - } - - options.complete = res => { - originComplete && originComplete(res) - } - - requestTask = RequestQueue.request(options) - }) - p.abort = (cb) => { - cb && cb() - if (requestTask) { - requestTask.abort() - } - return p - } - return p -} - -function processApis (taro) { - const weApis = Object.assign({ }, onAndSyncApis, noPromiseApis, otherApis) - const preloadPrivateKey = '__preload_' - const preloadInitedComponent = '$preloadComponent' - Object.keys(weApis).forEach(key => { - if (!onAndSyncApis[key] && !noPromiseApis[key]) { - taro[key] = (options, ...args) => { - const result = generateSpecialApis(key, options || {}) - const newKey = result.api - options = result.options - let task = null - const obj = Object.assign({}, options) - if (!(newKey in my)) { - console.warn(`支付宝小程序暂不支持 ${newKey}`) - return - } - if (typeof options === 'string') { - if (args.length) { - return my[newKey](options, ...args) - } - return my[newKey](options) - } - - if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { - let url = obj.url ? obj.url.replace(/^\//, '') : '' - if (url.indexOf('?') > -1) url = url.split('?')[0] - - const Component = cacheDataGet(url) - if (Component) { - const component = new Component() - if (component.componentWillPreload) { - const cacheKey = getUniqueKey() - const MarkIndex = obj.url.indexOf('?') - const hasMark = MarkIndex > -1 - const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' - const params = queryToJson(urlQueryStr) - obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` - cacheDataSet(cacheKey, component.componentWillPreload(params)) - cacheDataSet(preloadInitedComponent, component) - } - } - } - - const p = new Promise((resolve, reject) => { - ['fail', 'success', 'complete'].forEach((k) => { - obj[k] = (res) => { - if (k === 'success') { - if (newKey === 'saveFile') { - res.savedFilePath = res.apFilePath - } else if (newKey === 'downloadFile') { - res.tempFilePath = res.apFilePath - } else if (newKey === 'chooseImage') { - res.tempFilePaths = res.apFilePaths - } else if (newKey === 'getClipboard') { - res.data = res.text - } else if (newKey === 'scan') { - res.result = res.code - } else if (newKey === 'getScreenBrightness') { - res.value = res.brightness - delete res.brightness - } - } - options[k] && options[k](res) - if (k === 'success') { - resolve(res) - } else if (k === 'fail') { - reject(res) - } - } - }) - if (args.length) { - task = my[newKey](obj, ...args) - } else { - task = my[newKey](obj) - } - }) - if (newKey === 'uploadFile' || newKey === 'downloadFile') { - p.progress = cb => { - if (task) { - task.onProgressUpdate(cb) - } - return p - } - p.abort = cb => { - cb && cb() - if (task) { - task.abort() - } - return p - } - } - return p - } - } else { - taro[key] = (...args) => { - if (!(key in my)) { - console.warn(`支付宝小程序暂不支持 ${key}`) - return - } - if (key === 'getStorageSync') { - const arg1 = args[0] - if (arg1 != null) { - return my[key]({ key: arg1 }).data || my[key]({ key: arg1 }).APDataStorage || '' - } - return console.log('getStorageSync 传入参数错误') - } - if (key === 'setStorageSync') { - const arg1 = args[0] - const arg2 = args[1] - if (arg1 != null) { - return my[key]({ - key: arg1, - data: arg2 - }) - } - return console.log('setStorageSync 传入参数错误') - } - if (key === 'removeStorageSync') { - const arg1 = args[0] - if (arg1 != null) { - return my[key]({ key: arg1 }) - } - return console.log('removeStorageSync 传入参数错误') - } - if (key === 'createSelectorQuery') { - const query = my[key]() - query.in = function () { return query } - return query - } - const argsLen = args.length - const newArgs = args.concat() - const lastArg = newArgs[argsLen - 1] - if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { - newArgs.splice(argsLen - 1, 1, lastArg.$scope) - } - return my[key].apply(my, newArgs) - } - } - }) -} - -function pxTransform (size) { - const { - designWidth = 750, - deviceRatio = { - 640: 2.34 / 2, - 750: 1, - 828: 1.81 / 2 - } - } = this.config || {} - if (!(designWidth in deviceRatio)) { - throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) - } - return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' -} - -function generateSpecialApis (api, options) { - let apiAlias = api - if (api === 'showModal') { - options.cancelButtonText = options.cancelText - options.confirmButtonText = options.confirmText || '确定' - apiAlias = 'confirm' - if (options.showCancel === false) { - options.buttonText = options.confirmText || '确定' - apiAlias = 'alert' - } - } else { - Object.keys(apiDiff).forEach(item => { - const apiItem = apiDiff[item] - if (api === item) { - if (apiItem.alias) { - apiAlias = apiItem.alias - } - if (apiItem.options) { - const change = apiItem.options.change - const set = apiItem.options.set - if (change) { - change.forEach(changeItem => { - options[changeItem.new] = options[changeItem.old] - }) - } - if (set) { - set.forEach(setItem => { - options[setItem.key] = typeof setItem.value === 'function' ? setItem.value(options) : setItem.value - }) - } - } - } - }) - } - - return { - api: apiAlias, - options - } -} - -export default function initNativeApi (taro) { - processApis(taro) - taro.request = link.request.bind(link) - taro.addInterceptor = link.addInterceptor.bind(link) - taro.cleanInterceptors = link.cleanInterceptors.bind(link) - taro.getCurrentPages = getCurrentPages - taro.getApp = getApp - taro.initPxTransform = initPxTransform.bind(taro) - taro.pxTransform = pxTransform.bind(taro) -} diff --git a/packages/taro/apis/data-cache.js b/packages/taro/apis/data-cache.js deleted file mode 100644 index f11a760035da..000000000000 --- a/packages/taro/apis/data-cache.js +++ /dev/null @@ -1,15 +0,0 @@ -const data = {} - -export function cacheDataSet (key, val) { - data[key] = val -} - -export function cacheDataGet (key, delelteAfterGet) { - const temp = data[key] - delelteAfterGet && delete data[key] - return temp -} - -export function cacheDataHas (key) { - return key in data -} diff --git a/packages/taro/apis/jd.js b/packages/taro/apis/jd.js deleted file mode 100644 index 01b2d5662107..000000000000 --- a/packages/taro/apis/jd.js +++ /dev/null @@ -1,255 +0,0 @@ -import Taro from '@tarojs/api' -import { cacheDataSet, cacheDataGet } from './data-cache' -import { queryToJson, getUniqueKey } from './utils' - -const { - noPromiseApis, - onAndSyncApis, - otherApis, - initPxTransform, - Link -} = Taro - -const RequestQueue = { - MAX_REQUEST: 5, - queue: [], - request (options) { - this.push(options) - // 返回request task - return this.run() - }, - - push (options) { - this.queue.push(options) - }, - - run () { - if (!this.queue.length) { - return - } - if (this.queue.length <= this.MAX_REQUEST) { - const options = this.queue.shift() - const completeFn = options.complete - options.complete = (...args) => { - completeFn && completeFn.apply(options, args) - this.run() - } - return jd.request(options) - } - } -} - -function taroInterceptor (chain) { - return request(chain.requestParams) -} - -const link = new Link(taroInterceptor) - -function request (options) { - options = options || {} - if (typeof options === 'string') { - options = { - url: options - } - } - const originSuccess = options.success - const originFail = options.fail - const originComplete = options.complete - let requestTask - const p = new Promise((resolve, reject) => { - options.success = res => { - originSuccess && originSuccess(res) - resolve(res) - } - options.fail = res => { - originFail && originFail(res) - reject(res) - } - - options.complete = res => { - originComplete && originComplete(res) - } - - requestTask = RequestQueue.request(options) - }) - p.abort = (cb) => { - cb && cb() - if (requestTask) { - requestTask.abort() - } - return p - } - return p -} - -function processApis (taro) { - const weApis = Object.assign({ }, onAndSyncApis, noPromiseApis, otherApis) - const useDataCacheApis = { - navigateTo: true, - redirectTo: true, - reLaunch: true - } - const routerParamsPrivateKey = '__key_' - const preloadPrivateKey = '__preload_' - const preloadInitedComponent = '$preloadComponent' - Object.keys(weApis).forEach(key => { - if (!(key in jd)) { - taro[key] = () => { - console.warn(`微信小程序暂不支持 ${key}`) - } - return - } - - if (!onAndSyncApis[key] && !noPromiseApis[key]) { - taro[key] = (options, ...args) => { - options = options || {} - let task = null - const obj = Object.assign({}, options) - if (typeof options === 'string') { - if (args.length) { - return jd[key](options, ...args) - } - return jd[key](options) - } - - if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { - let url = obj.url ? obj.url.replace(/^\//, '') : '' - if (url.indexOf('?') > -1) url = url.split('?')[0] - - const Component = cacheDataGet(url) - if (Component) { - const component = new Component() - if (component.componentWillPreload) { - const cacheKey = getUniqueKey() - const MarkIndex = obj.url.indexOf('?') - const hasMark = MarkIndex > -1 - const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' - const params = queryToJson(urlQueryStr) - obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` - cacheDataSet(cacheKey, component.componentWillPreload(params)) - cacheDataSet(preloadInitedComponent, component) - } - } - } - - if (useDataCacheApis[key]) { - const url = obj.url = obj.url || '' - const MarkIndex = url.indexOf('?') - const hasMark = MarkIndex > -1 - const urlQueryStr = hasMark ? url.substring(MarkIndex + 1, url.length) : '' - const params = queryToJson(urlQueryStr) - const cacheKey = getUniqueKey() - obj.url += (hasMark ? '&' : '?') + `${routerParamsPrivateKey}=${cacheKey}` - cacheDataSet(cacheKey, params) - } - - const p = new Promise((resolve, reject) => { - ['fail', 'success', 'complete'].forEach((k) => { - obj[k] = (res) => { - options[k] && options[k](res) - if (k === 'success') { - if (key === 'connectSocket') { - resolve( - Promise.resolve().then(() => Object.assign(task, res)) - ) - } else { - resolve(res) - } - } else if (k === 'fail') { - reject(res) - } - } - }) - if (args.length) { - task = jd[key](obj, ...args) - } else { - task = jd[key](obj) - } - }) - if (key === 'uploadFile' || key === 'downloadFile') { - p.progress = cb => { - if (task) { - task.onProgressUpdate(cb) - } - return p - } - p.abort = cb => { - cb && cb() - if (task) { - task.abort() - } - return p - } - } - return p - } - } else { - taro[key] = (...args) => { - const argsLen = args.length - const newArgs = args.concat() - const lastArg = newArgs[argsLen - 1] - if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { - newArgs.splice(argsLen - 1, 1, lastArg.$scope) - } - return jd[key].apply(jd, newArgs) - } - } - }) -} - -function pxTransform (size) { - const { - designWidth = 750, - deviceRatio = { - 640: 2.34 / 2, - 750: 1, - 828: 1.81 / 2 - } - } = this.config || {} - if (!(designWidth in deviceRatio)) { - throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) - } - return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' -} - -function canIUseWebp () { - const { platform = '' } = jd.getSystemInfoSync() - const platformLower = platform.toLowerCase() - if (platformLower === 'android' || platformLower === 'devtools') { - return true - } - return false -} - -function jdCloud (taro) { - const jdC = jd.cloud || {} - const jdcloud = {} - const apiList = [ - 'init', - 'database', - 'uploadFile', - 'downloadFile', - 'getTempFileURL', - 'deleteFile', - 'callFunction', - 'CloudID' - ] - apiList.forEach(v => { - jdcloud[v] = jdC[v] - }) - taro.cloud = jdcloud -} - -export default function initNativeApi (taro) { - processApis(taro) - taro.request = link.request.bind(link) - taro.addInterceptor = link.addInterceptor.bind(link) - taro.cleanInterceptors = link.cleanInterceptors.bind(link) - taro.getCurrentPages = getCurrentPages - taro.getApp = getApp - taro.requirePlugin = requirePlugin - taro.initPxTransform = initPxTransform.bind(taro) - taro.pxTransform = pxTransform.bind(taro) - taro.canIUseWebp = canIUseWebp - jdCloud(taro) -} diff --git a/packages/taro/apis/qq.js b/packages/taro/apis/qq.js deleted file mode 100644 index abd6b7de491c..000000000000 --- a/packages/taro/apis/qq.js +++ /dev/null @@ -1,253 +0,0 @@ -import Taro from '@tarojs/api' -import { cacheDataSet, cacheDataGet } from './data-cache' -import { queryToJson, getUniqueKey } from './utils' - -const { - noPromiseApis, - onAndSyncApis, - otherApis, - initPxTransform, - Link -} = Taro - -const RequestQueue = { - MAX_REQUEST: 5, - queue: [], - request (options) { - this.push(options) - // 返回request task - return this.run() - }, - - push (options) { - this.queue.push(options) - }, - - run () { - if (!this.queue.length) { - return - } - if (this.queue.length <= this.MAX_REQUEST) { - const options = this.queue.shift() - const completeFn = options.complete - options.complete = (...args) => { - completeFn && completeFn.apply(options, args) - this.run() - } - return qq.request(options) - } - } -} - -function taroInterceptor (chain) { - return request(chain.requestParams) -} - -const link = new Link(taroInterceptor) - -function request (options) { - options = options || {} - if (typeof options === 'string') { - options = { - url: options - } - } - const originSuccess = options.success - const originFail = options.fail - const originComplete = options.complete - let requestTask - const p = new Promise((resolve, reject) => { - options.success = res => { - originSuccess && originSuccess(res) - resolve(res) - } - options.fail = res => { - originFail && originFail(res) - reject(res) - } - - options.complete = res => { - originComplete && originComplete(res) - } - - requestTask = RequestQueue.request(options) - }) - p.abort = (cb) => { - cb && cb() - if (requestTask) { - requestTask.abort() - } - return p - } - return p -} - -function processApis (taro) { - const weApis = Object.assign({ }, onAndSyncApis, noPromiseApis, otherApis) - const useDataCacheApis = { - navigateTo: true, - redirectTo: true, - reLaunch: true - } - const routerParamsPrivateKey = '__key_' - const preloadPrivateKey = '__preload_' - const preloadInitedComponent = '$preloadComponent' - Object.keys(weApis).forEach(key => { - if (!(key in qq)) { - taro[key] = () => { - console.warn(`QQ小程序暂不支持 ${key}`) - } - return - } - if (!onAndSyncApis[key] && !noPromiseApis[key]) { - taro[key] = (options, ...args) => { - options = options || {} - let task = null - const obj = Object.assign({}, options) - if (typeof options === 'string') { - if (args.length) { - return qq[key](options, ...args) - } - return qq[key](options) - } - - if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { - let url = obj.url ? obj.url.replace(/^\//, '') : '' - if (url.indexOf('?') > -1) url = url.split('?')[0] - - const Component = cacheDataGet(url) - if (Component) { - const component = new Component() - if (component.componentWillPreload) { - const cacheKey = getUniqueKey() - const MarkIndex = obj.url.indexOf('?') - const hasMark = MarkIndex > -1 - const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' - const params = queryToJson(urlQueryStr) - obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` - cacheDataSet(cacheKey, component.componentWillPreload(params)) - cacheDataSet(preloadInitedComponent, component) - } - } - } - - if (useDataCacheApis[key]) { - const url = obj.url = obj.url || '' - const MarkIndex = url.indexOf('?') - const hasMark = MarkIndex > -1 - const urlQueryStr = hasMark ? url.substring(MarkIndex + 1, url.length) : '' - const params = queryToJson(urlQueryStr) - const cacheKey = getUniqueKey() - obj.url += (hasMark ? '&' : '?') + `${routerParamsPrivateKey}=${cacheKey}` - cacheDataSet(cacheKey, params) - } - - const p = new Promise((resolve, reject) => { - ['fail', 'success', 'complete'].forEach((k) => { - obj[k] = (res) => { - options[k] && options[k](res) - if (k === 'success') { - if (key === 'connectSocket') { - resolve( - Promise.resolve().then(() => Object.assign(task, res)) - ) - } else { - resolve(res) - } - } else if (k === 'fail') { - reject(res) - } - } - }) - if (args.length) { - task = qq[key](obj, ...args) - } else { - task = qq[key](obj) - } - }) - if (key === 'uploadFile' || key === 'downloadFile') { - p.progress = cb => { - if (task) { - task.onProgressUpdate(cb) - } - return p - } - p.abort = cb => { - cb && cb() - if (task) { - task.abort() - } - return p - } - } - return p - } - } else { - taro[key] = (...args) => { - const argsLen = args.length - const newArgs = args.concat() - const lastArg = newArgs[argsLen - 1] - if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { - newArgs.splice(argsLen - 1, 1, lastArg.$scope) - } - return qq[key].apply(qq, newArgs) - } - } - }) -} - -function pxTransform (size) { - const { - designWidth = 750, - deviceRatio = { - 640: 2.34 / 2, - 750: 1, - 828: 1.81 / 2 - } - } = this.config || {} - if (!(designWidth in deviceRatio)) { - throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) - } - return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' -} - -function canIUseWebp () { - const { platform } = qq.getSystemInfoSync() - const platformLower = platform.toLowerCase() - if (platformLower === 'android' || platformLower === 'devtools') { - return true - } - return false -} - -function qqCloud (taro) { - const qqC = qq.cloud || {} - const qqcloud = {} - const apiList = [ - 'init', - 'database', - 'uploadFile', - 'downloadFile', - 'getTempFileURL', - 'deleteFile', - 'callFunction' - ] - apiList.forEach(v => { - qqcloud[v] = qqC[v] - }) - taro.cloud = qqcloud -} - -export default function initNativeApi (taro) { - processApis(taro) - taro.request = link.request.bind(link) - taro.addInterceptor = link.addInterceptor.bind(link) - taro.cleanInterceptors = link.cleanInterceptors.bind(link) - taro.getCurrentPages = getCurrentPages - taro.getApp = getApp - taro.requirePlugin = requirePlugin - taro.initPxTransform = initPxTransform.bind(taro) - taro.pxTransform = pxTransform.bind(taro) - taro.canIUseWebp = canIUseWebp - qqCloud(taro) -} diff --git a/packages/taro/apis/swan.js b/packages/taro/apis/swan.js deleted file mode 100644 index 68ece88fa115..000000000000 --- a/packages/taro/apis/swan.js +++ /dev/null @@ -1,181 +0,0 @@ -import Taro from '@tarojs/api' - -const { - noPromiseApis, - onAndSyncApis, - otherApis, - initPxTransform, - Link -} = Taro - -const RequestQueue = { - MAX_REQUEST: 5, - queue: [], - request (options) { - this.push(options) - // 返回request task - return this.run() - }, - - push (options) { - this.queue.push(options) - }, - - run () { - if (!this.queue.length) { - return - } - if (this.queue.length <= this.MAX_REQUEST) { - const options = this.queue.shift() - const completeFn = options.complete - options.complete = () => { - completeFn && completeFn.apply(options, [...arguments]) - this.run() - } - return swan.request(options) - } - } -} - -function taroInterceptor (chain) { - return request(chain.requestParams) -} - -const link = new Link(taroInterceptor) - -function request (options) { - options = options || {} - if (typeof options === 'string') { - options = { - url: options - } - } - const originSuccess = options.success - const originFail = options.fail - const originComplete = options.complete - let requestTask - const p = new Promise((resolve, reject) => { - options.success = res => { - originSuccess && originSuccess(res) - resolve(res) - } - options.fail = res => { - originFail && originFail(res) - reject(res) - } - - options.complete = res => { - originComplete && originComplete(res) - } - - requestTask = RequestQueue.request(options) - }) - p.abort = (cb) => { - cb && cb() - if (requestTask) { - requestTask.abort() - } - return p - } - return p -} - -function processApis (taro) { - const weApis = Object.assign({ }, onAndSyncApis, noPromiseApis, otherApis) - Object.keys(weApis).forEach(key => { - if (!(key in swan)) { - taro[key] = () => { - console.warn(`百度小程序暂不支持 ${key}`) - } - return - } - if (!onAndSyncApis[key] && !noPromiseApis[key]) { - taro[key] = (options, ...args) => { - options = options || {} - let task = null - const obj = Object.assign({}, options) - if (typeof options === 'string') { - if (args.length) { - return swan[key](options, ...args) - } - return swan[key](options) - } - const p = new Promise((resolve, reject) => { - ['fail', 'success', 'complete'].forEach((k) => { - obj[k] = (res) => { - options[k] && options[k](res) - if (k === 'success') { - if (key === 'connectSocket') { - resolve( - Promise.resolve().then(() => Object.assign(task, res)) - ) - } else { - resolve(res) - } - } else if (k === 'fail') { - reject(res) - } - } - }) - if (args.length) { - task = swan[key](obj, ...args) - } else { - task = swan[key](obj) - } - }) - if (key === 'uploadFile' || key === 'downloadFile') { - p.progress = cb => { - if (task) { - task.onProgressUpdate(cb) - } - return p - } - p.abort = cb => { - cb && cb() - if (task) { - task.abort() - } - return p - } - } - return p - } - } else { - taro[key] = (...args) => { - const argsLen = args.length - const newArgs = args.concat() - const lastArg = newArgs[argsLen - 1] - if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { - newArgs.splice(argsLen - 1, 1, lastArg.$scope) - } - return swan[key].apply(swan, newArgs) - } - } - }) -} - -function pxTransform (size) { - const { - designWidth = 750, - deviceRatio = { - 640: 2.34 / 2, - 750: 1, - 828: 1.81 / 2 - } - } = this.config || {} - if (!(designWidth in deviceRatio)) { - throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) - } - return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' -} - -export default function initNativeApi (taro) { - processApis(taro) - taro.request = link.request.bind(link) - taro.addInterceptor = link.addInterceptor.bind(link) - taro.cleanInterceptors = link.cleanInterceptors.bind(link) - taro.getCurrentPages = getCurrentPages - taro.getApp = getApp - taro.initPxTransform = initPxTransform.bind(taro) - taro.pxTransform = pxTransform.bind(taro) -} diff --git a/packages/taro/apis/tt.js b/packages/taro/apis/tt.js deleted file mode 100644 index 1fb5c58a093c..000000000000 --- a/packages/taro/apis/tt.js +++ /dev/null @@ -1,206 +0,0 @@ -import Taro from '@tarojs/api' -import { cacheDataSet, cacheDataGet } from './data-cache' -import { queryToJson, getUniqueKey } from './utils' - -const { - noPromiseApis, - onAndSyncApis, - otherApis, - initPxTransform, - Link -} = Taro - -const RequestQueue = { - MAX_REQUEST: 5, - queue: [], - request (options) { - this.push(options) - // 返回request task - return this.run() - }, - - push (options) { - this.queue.push(options) - }, - - run () { - if (!this.queue.length) { - return - } - if (this.queue.length <= this.MAX_REQUEST) { - const options = this.queue.shift() - const completeFn = options.complete - options.complete = () => { - completeFn && completeFn.apply(options, [...arguments]) - this.run() - } - return tt.request(options) - } - } -} - -function taroInterceptor (chain) { - return request(chain.requestParams) -} - -const link = new Link(taroInterceptor) - -function request (options) { - options = options || {} - if (typeof options === 'string') { - options = { - url: options - } - } - const originSuccess = options.success - const originFail = options.fail - const originComplete = options.complete - let requestTask - const p = new Promise((resolve, reject) => { - options.success = res => { - originSuccess && originSuccess(res) - resolve(res) - } - options.fail = res => { - originFail && originFail(res) - reject(res) - } - - options.complete = res => { - originComplete && originComplete(res) - } - - requestTask = RequestQueue.request(options) - }) - p.abort = (cb) => { - cb && cb() - if (requestTask) { - requestTask.abort() - } - return p - } - return p -} - -function processApis (taro) { - const weApis = Object.assign({ }, onAndSyncApis, noPromiseApis, otherApis) - const preloadPrivateKey = '__preload_' - const preloadInitedComponent = '$preloadComponent' - Object.keys(weApis).forEach(key => { - if (!(key in tt)) { - taro[key] = () => { - console.warn(`头条小程序暂不支持 ${key}`) - } - return - } - if (!onAndSyncApis[key] && !noPromiseApis[key]) { - taro[key] = (options, ...args) => { - options = options || {} - let task = null - const obj = Object.assign({}, options) - if (typeof options === 'string') { - if (args.length) { - return tt[key](options, ...args) - } - return tt[key](options) - } - - if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { - let url = obj.url ? obj.url.replace(/^\//, '') : '' - if (url.indexOf('?') > -1) url = url.split('?')[0] - - const Component = cacheDataGet(url) - if (Component) { - const component = new Component() - if (component.componentWillPreload) { - const cacheKey = getUniqueKey() - const MarkIndex = obj.url.indexOf('?') - const hasMark = MarkIndex > -1 - const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' - const params = queryToJson(urlQueryStr) - obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` - cacheDataSet(cacheKey, component.componentWillPreload(params)) - cacheDataSet(preloadInitedComponent, component) - } - } - } - - const p = new Promise((resolve, reject) => { - ['fail', 'success', 'complete'].forEach((k) => { - obj[k] = (res) => { - options[k] && options[k](res) - if (k === 'success') { - if (key === 'connectSocket') { - resolve( - Promise.resolve().then(() => Object.assign(task, res)) - ) - } else { - resolve(res) - } - } else if (k === 'fail') { - reject(res) - } - } - }) - if (args.length) { - task = tt[key](obj, ...args) - } else { - task = tt[key](obj) - } - }) - if (key === 'uploadFile' || key === 'downloadFile') { - p.progress = cb => { - if (task) { - task.onProgressUpdate(cb) - } - return p - } - p.abort = cb => { - cb && cb() - if (task) { - task.abort() - } - return p - } - } - return p - } - } else { - taro[key] = (...args) => { - const argsLen = args.length - const newArgs = args.concat() - const lastArg = newArgs[argsLen - 1] - if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { - newArgs.splice(argsLen - 1, 1, lastArg.$scope) - } - return tt[key].apply(tt, newArgs) - } - } - }) -} - -function pxTransform (size) { - const { - designWidth = 750, - deviceRatio = { - 640: 2.34 / 2, - 750: 1, - 828: 1.81 / 2 - } - } = this.config || {} - if (!(designWidth in deviceRatio)) { - throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) - } - return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' -} - -export default function initNativeApi (taro) { - processApis(taro) - taro.request = link.request.bind(link) - taro.addInterceptor = link.addInterceptor.bind(link) - taro.cleanInterceptors = link.cleanInterceptors.bind(link) - taro.getCurrentPages = getCurrentPages - taro.getApp = getApp - taro.initPxTransform = initPxTransform.bind(taro) - taro.pxTransform = pxTransform.bind(taro) -} diff --git a/packages/taro/apis/utils.js b/packages/taro/apis/utils.js deleted file mode 100644 index c7d05c102bd3..000000000000 --- a/packages/taro/apis/utils.js +++ /dev/null @@ -1,37 +0,0 @@ -export function queryToJson (str) { - const dec = decodeURIComponent - const qp = str.split('&') - const ret = {} - let name - let val - for (let i = 0, l = qp.length, item; i < l; ++i) { - item = qp[i] - if (item.length) { - const s = item.indexOf('=') - if (s < 0) { - name = dec(item) - val = '' - } else { - name = dec(item.slice(0, s)) - val = dec(item.slice(s + 1)) - } - if (typeof ret[name] === 'string') { // inline'd type check - ret[name] = [ret[name]] - } - - if (Array.isArray(ret[name])) { - ret[name].push(val) - } else { - ret[name] = val - } - } - } - return ret // Object -} - -let _i = 1 -const _loadTime = (new Date()).getTime().toString() - -export function getUniqueKey () { - return _loadTime + (_i++) -} diff --git a/packages/taro/apis/wx.js b/packages/taro/apis/wx.js deleted file mode 100644 index 557df0086527..000000000000 --- a/packages/taro/apis/wx.js +++ /dev/null @@ -1,255 +0,0 @@ -import Taro from '@tarojs/api' -import { cacheDataSet, cacheDataGet } from './data-cache' -import { queryToJson, getUniqueKey } from './utils' - -const { - noPromiseApis, - onAndSyncApis, - otherApis, - initPxTransform, - Link -} = Taro - -const RequestQueue = { - MAX_REQUEST: 5, - queue: [], - request (options) { - this.push(options) - // 返回request task - return this.run() - }, - - push (options) { - this.queue.push(options) - }, - - run () { - if (!this.queue.length) { - return - } - if (this.queue.length <= this.MAX_REQUEST) { - const options = this.queue.shift() - const completeFn = options.complete - options.complete = (...args) => { - completeFn && completeFn.apply(options, args) - this.run() - } - return wx.request(options) - } - } -} - -function taroInterceptor (chain) { - return request(chain.requestParams) -} - -const link = new Link(taroInterceptor) - -function request (options) { - options = options || {} - if (typeof options === 'string') { - options = { - url: options - } - } - const originSuccess = options.success - const originFail = options.fail - const originComplete = options.complete - let requestTask - const p = new Promise((resolve, reject) => { - options.success = res => { - originSuccess && originSuccess(res) - resolve(res) - } - options.fail = res => { - originFail && originFail(res) - reject(res) - } - - options.complete = res => { - originComplete && originComplete(res) - } - - requestTask = RequestQueue.request(options) - }) - p.abort = (cb) => { - cb && cb() - if (requestTask) { - requestTask.abort() - } - return p - } - return p -} - -function processApis (taro) { - const weApis = Object.assign({ }, onAndSyncApis, noPromiseApis, otherApis) - const useDataCacheApis = { - navigateTo: true, - redirectTo: true, - reLaunch: true - } - const routerParamsPrivateKey = '__key_' - const preloadPrivateKey = '__preload_' - const preloadInitedComponent = '$preloadComponent' - Object.keys(weApis).forEach(key => { - if (!(key in wx)) { - taro[key] = () => { - console.warn(`微信小程序暂不支持 ${key}`) - } - return - } - - if (!onAndSyncApis[key] && !noPromiseApis[key]) { - taro[key] = (options, ...args) => { - options = options || {} - let task = null - const obj = Object.assign({}, options) - if (typeof options === 'string') { - if (args.length) { - return wx[key](options, ...args) - } - return wx[key](options) - } - - if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { - let url = obj.url ? obj.url.replace(/^\//, '') : '' - if (url.indexOf('?') > -1) url = url.split('?')[0] - - const Component = cacheDataGet(url) - if (Component) { - const component = new Component() - if (component.componentWillPreload) { - const cacheKey = getUniqueKey() - const MarkIndex = obj.url.indexOf('?') - const hasMark = MarkIndex > -1 - const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' - const params = queryToJson(urlQueryStr) - obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` - cacheDataSet(cacheKey, component.componentWillPreload(params)) - cacheDataSet(preloadInitedComponent, component) - } - } - } - - if (useDataCacheApis[key]) { - const url = obj.url = obj.url || '' - const MarkIndex = url.indexOf('?') - const hasMark = MarkIndex > -1 - const urlQueryStr = hasMark ? url.substring(MarkIndex + 1, url.length) : '' - const params = queryToJson(urlQueryStr) - const cacheKey = getUniqueKey() - obj.url += (hasMark ? '&' : '?') + `${routerParamsPrivateKey}=${cacheKey}` - cacheDataSet(cacheKey, params) - } - - const p = new Promise((resolve, reject) => { - ['fail', 'success', 'complete'].forEach((k) => { - obj[k] = (res) => { - options[k] && options[k](res) - if (k === 'success') { - if (key === 'connectSocket') { - resolve( - Promise.resolve().then(() => Object.assign(task, res)) - ) - } else { - resolve(res) - } - } else if (k === 'fail') { - reject(res) - } - } - }) - if (args.length) { - task = wx[key](obj, ...args) - } else { - task = wx[key](obj) - } - }) - if (key === 'uploadFile' || key === 'downloadFile') { - p.progress = cb => { - if (task) { - task.onProgressUpdate(cb) - } - return p - } - p.abort = cb => { - cb && cb() - if (task) { - task.abort() - } - return p - } - } - return p - } - } else { - taro[key] = (...args) => { - const argsLen = args.length - const newArgs = args.concat() - const lastArg = newArgs[argsLen - 1] - if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { - newArgs.splice(argsLen - 1, 1, lastArg.$scope) - } - return wx[key].apply(wx, newArgs) - } - } - }) -} - -function pxTransform (size) { - const { - designWidth = 750, - deviceRatio = { - 640: 2.34 / 2, - 750: 1, - 828: 1.81 / 2 - } - } = this.config || {} - if (!(designWidth in deviceRatio)) { - throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) - } - return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' -} - -function canIUseWebp () { - const { platform } = wx.getSystemInfoSync() - const platformLower = platform.toLowerCase() - if (platformLower === 'android' || platformLower === 'devtools') { - return true - } - return false -} - -function wxCloud (taro) { - const wxC = wx.cloud || {} - const wxcloud = {} - const apiList = [ - 'init', - 'database', - 'uploadFile', - 'downloadFile', - 'getTempFileURL', - 'deleteFile', - 'callFunction', - 'CloudID' - ] - apiList.forEach(v => { - wxcloud[v] = wxC[v] - }) - taro.cloud = wxcloud -} - -export default function initNativeApi (taro) { - processApis(taro) - taro.request = link.request.bind(link) - taro.addInterceptor = link.addInterceptor.bind(link) - taro.cleanInterceptors = link.cleanInterceptors.bind(link) - taro.getCurrentPages = getCurrentPages - taro.getApp = getApp - taro.requirePlugin = requirePlugin - taro.initPxTransform = initPxTransform.bind(taro) - taro.pxTransform = pxTransform.bind(taro) - taro.canIUseWebp = canIUseWebp - wxCloud(taro) -} diff --git a/packages/taro/h5.js b/packages/taro/h5.js deleted file mode 100644 index c1c45fd281a1..000000000000 --- a/packages/taro/h5.js +++ /dev/null @@ -1,4 +0,0 @@ -import Taro from '@tarojs/taro-h5' -export * from '@tarojs/taro-h5' - -export default Taro diff --git a/packages/taro/index.js b/packages/taro/index.js index 00c2a105031e..860df4920178 100644 --- a/packages/taro/index.js +++ b/packages/taro/index.js @@ -1,28 +1,2 @@ -const Taro = require('@tarojs/api').default - -let api - -// bundler 可以自动移除不需要的 require -if (process.env.TARO_ENV === 'alipay') { - api = require('./lib/alipay') -} else if (process.env.TARO_ENV === 'jd') { - api = require('./lib/jd') -} else if (process.env.TARO_ENV === 'qq') { - api = require('./lib/qq') -} else if (process.env.TARO_ENV === 'swan') { - api = require('./lib/swan') -} else if (process.env.TARO_ENV === 'tt') { - api = require('./lib/tt') -} else if (process.env.TARO_ENV === 'weapp') { - api = require('./lib/wx') -} - -// 兼容不同工具的 import 机制,如 Jest, rollup -const initNativeAPI = api && api.default ? api.default : api -// 如果没有对应的 env type,那就啥也不干,例如 h5 -if (typeof initNativeAPI === 'function') { - initNativeAPI(Taro) -} - -module.exports = Taro +module.exports = require('./dist/index.esm').default module.exports.default = module.exports diff --git a/packages/taro/package.json b/packages/taro/package.json index 79c39d2c0e94..6ea09fe64535 100644 --- a/packages/taro/package.json +++ b/packages/taro/package.json @@ -2,24 +2,21 @@ "name": "@tarojs/taro", "version": "3.0.9", "description": "Taro framework", + "homepage": "https://github.com/nervjs/taro/tree/master/packages/taro#readme", "main": "index.js", - "main:h5": "h5.js", + "main:h5": "dist/h5.esm.js", "typings": "types/index.d.ts", "files": [ "dist", - "src", "index.js", "types", - "package.json", - "lib", "h5.js", "html.css", "html5.css" ], "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "build:api": "babel apis --out-dir lib --presets=@babel/preset-env", - "build": "babel apis --out-dir lib --presets=@babel/preset-env" + "test": "echo \"Error: run tests from root\" && exit 1", + "build": "rollup -c rollup.config.js" }, "repository": { "type": "git", @@ -31,10 +28,7 @@ "author": "O2Team", "license": "MIT", "dependencies": { - "@tarojs/api": "3.0.9", + "@tarojs/runtime": "3.0.9", "@tarojs/taro-h5": "3.0.9" - }, - "devDependencies": { - "@tarojs/runtime": "3.0.9" } } diff --git a/packages/taro/rollup.config.js b/packages/taro/rollup.config.js index 054d3206144a..b6515e35b145 100644 --- a/packages/taro/rollup.config.js +++ b/packages/taro/rollup.config.js @@ -5,23 +5,7 @@ const babel = require('rollup-plugin-babel') const cwd = __dirname const baseConfig = { - input: join(cwd, 'src/index.js'), - external: ['nervjs', '@tarojs/runtime'], - output: [ - { - file: join(cwd, 'dist/index.js'), - format: 'cjs', - sourcemap: true, - exports: 'named' - }, - { - file: join(cwd, 'dist/taro.js'), - format: 'umd', - name: 'Taro', - sourcemap: true, - exports: 'named' - } - ], + external: ['nervjs', '@tarojs/runtime', '@tarojs/taro-h5'], plugins: [ resolve({ preferBuiltins: false @@ -44,23 +28,63 @@ const baseConfig = { }) ] } -const esmConfig = Object.assign({}, baseConfig, { - output: Object.assign({}, baseConfig.output, { + +const miniUmdConfig = Object.assign({}, baseConfig, { + input: join(cwd, 'src/index.js'), + output: [ + { + file: join(cwd, 'dist/index.js'), + format: 'cjs', + sourcemap: true, + exports: 'named' + }, + { + file: join(cwd, 'dist/taro.js'), + format: 'umd', + name: 'Taro', + sourcemap: true, + exports: 'named' + } + ] +}) + +const miniEsmConfig = Object.assign({}, baseConfig, { + input: join(cwd, 'src/index.js'), + output: { sourcemap: true, format: 'es', file: join(cwd, 'dist/index.esm.js') - }) + } +}) + +const h5CjsConfig = Object.assign({}, baseConfig, { + input: join(cwd, 'src/h5-cjs.js'), + output: { + file: join(cwd, 'dist/h5.js'), + format: 'cjs', + sourcemap: true, + exports: 'named' + } +}) + +const h5EsmConfig = Object.assign({}, baseConfig, { + input: join(cwd, 'src/h5.js'), + output: { + sourcemap: true, + format: 'es', + file: join(cwd, 'dist/h5.esm.js') + } }) function rollup () { const target = process.env.TARGET if (target === 'umd') { - return baseConfig + return [miniUmdConfig, h5CjsConfig] } else if (target === 'esm') { - return esmConfig + return [miniEsmConfig, h5EsmConfig] } else { - return [baseConfig, esmConfig] + return [miniUmdConfig, miniEsmConfig, h5EsmConfig, h5CjsConfig] } } module.exports = rollup() diff --git a/packages/taro-api/src/env.js b/packages/taro/src/env.js similarity index 100% rename from packages/taro-api/src/env.js rename to packages/taro/src/env.js diff --git a/packages/taro/src/h5-cjs.js b/packages/taro/src/h5-cjs.js new file mode 100644 index 000000000000..b12ef01d1a87 --- /dev/null +++ b/packages/taro/src/h5-cjs.js @@ -0,0 +1,16 @@ +import * as H5 from '@tarojs/taro-h5' +import Taro from './index' + +const { + initNativeApi, + ...apis +} = H5 + +initNativeApi(Taro) + +const taro = Object.assign(Taro, apis) + +export default taro +export * from './index' +export * from '@tarojs/taro-h5' +export const getApp = Taro.getApp diff --git a/packages/taro/src/h5.js b/packages/taro/src/h5.js new file mode 100644 index 000000000000..d2ea2c3b7c38 --- /dev/null +++ b/packages/taro/src/h5.js @@ -0,0 +1,9 @@ +import { initNativeApi } from '@tarojs/taro-h5' +import Taro from './index' + +initNativeApi(Taro) + +export default Taro +export * from './index' +export * from '@tarojs/taro-h5' +export const getApp = Taro.getApp diff --git a/packages/taro-api/src/index.js b/packages/taro/src/index.js similarity index 71% rename from packages/taro-api/src/index.js rename to packages/taro/src/index.js index 6a8ede3d2a52..513b1115a2c8 100644 --- a/packages/taro-api/src/index.js +++ b/packages/taro/src/index.js @@ -68,3 +68,36 @@ const Taro = { } export default Taro + +export { + Events, + eventCenter, + getEnv, + ENV_TYPE, + render, + noPromiseApis, + onAndSyncApis, + otherApis, + initPxTransform, + Link, + interceptors, + Current, + getCurrentInstance, + useDidShow, + useDidHide, + usePullDownRefresh, + useReachBottom, + usePageScroll, + useResize, + useShareAppMessage, + useTabItemTap, + useTitleClick, + useOptionMenuClick, + usePullIntercept, + useShareTimeline, + useAddToFavorites, + useReady, + useRouter, + options, + nextTick +} diff --git a/packages/taro-api/src/interceptor/chain.js b/packages/taro/src/interceptor/chain.js similarity index 100% rename from packages/taro-api/src/interceptor/chain.js rename to packages/taro/src/interceptor/chain.js diff --git a/packages/taro-api/src/interceptor/index.js b/packages/taro/src/interceptor/index.js similarity index 100% rename from packages/taro-api/src/interceptor/index.js rename to packages/taro/src/interceptor/index.js diff --git a/packages/taro-api/src/interceptor/interceptors.js b/packages/taro/src/interceptor/interceptors.js similarity index 100% rename from packages/taro-api/src/interceptor/interceptors.js rename to packages/taro/src/interceptor/interceptors.js diff --git a/packages/taro-api/src/native-apis.js b/packages/taro/src/native-apis.js similarity index 100% rename from packages/taro-api/src/native-apis.js rename to packages/taro/src/native-apis.js diff --git a/packages/taro-api/src/polyfill.js b/packages/taro/src/polyfill.js similarity index 100% rename from packages/taro-api/src/polyfill.js rename to packages/taro/src/polyfill.js diff --git a/packages/taro-api/src/render.js b/packages/taro/src/render.js similarity index 100% rename from packages/taro-api/src/render.js rename to packages/taro/src/render.js From d0f11c6a4e181fd36e4e77eb756764b1aade4063 Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Wed, 16 Sep 2020 16:51:47 +0800 Subject: [PATCH 013/272] =?UTF-8?q?chore(h5):=20=E9=87=8D=E6=9E=84=20@taro?= =?UTF-8?q?js/h5=20=E7=9A=84=E6=89=93=E5=8C=85=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/taro-h5/package.json | 8 - packages/taro-h5/rollup.config.js | 5 - packages/taro-h5/src/api/api.md | 655 ------------------ .../taro-h5/src/api/customComponent/index.js | 1 - packages/taro-h5/src/api/index.js | 1 - packages/taro-h5/src/index.cjs.js | 11 - packages/taro-h5/src/index.js | 6 +- .../src/{taro/index.js => init-api.js} | 71 +- packages/taro-h5/yarn.lock | 18 +- 9 files changed, 37 insertions(+), 739 deletions(-) delete mode 100644 packages/taro-h5/src/api/api.md delete mode 100644 packages/taro-h5/src/api/customComponent/index.js delete mode 100644 packages/taro-h5/src/index.cjs.js rename packages/taro-h5/src/{taro/index.js => init-api.js} (56%) diff --git a/packages/taro-h5/package.json b/packages/taro-h5/package.json index 2f513be5a3b0..f211acc247ef 100644 --- a/packages/taro-h5/package.json +++ b/packages/taro-h5/package.json @@ -3,19 +3,12 @@ "version": "3.0.9", "description": "Taro h5 framework", "main:h5": "src/index.js", - "main": "dist/index.cjs.js", "typings": "types/index.d.ts", "files": [ "dist", "src", - "index.js", "types" ], - "sideEffects": [ - "*.scss", - "*.css", - "./src/taro/index.js" - ], "scripts": { "test": "jest", "test:dev": "jest --watch", @@ -33,7 +26,6 @@ "author": "O2Team", "license": "MIT", "dependencies": { - "@tarojs/api": "3.0.9", "@tarojs/router": "3.0.9", "@tarojs/runtime": "3.0.9", "base64-js": "^1.3.0", diff --git a/packages/taro-h5/rollup.config.js b/packages/taro-h5/rollup.config.js index 52966f35c8d7..0db911ef59f2 100644 --- a/packages/taro-h5/rollup.config.js +++ b/packages/taro-h5/rollup.config.js @@ -49,11 +49,6 @@ const variesConfig = [{ file: 'dist/taroApis.js' }, plugins: exportNameOnly() -}, { - input: 'src/index.cjs.js', - output: { - file: 'dist/index.cjs.js' - } }] export default variesConfig.map(v => { diff --git a/packages/taro-h5/src/api/api.md b/packages/taro-h5/src/api/api.md deleted file mode 100644 index e86e7eb4637d..000000000000 --- a/packages/taro-h5/src/api/api.md +++ /dev/null @@ -1,655 +0,0 @@ -## H5 API - -✅ support - -☑️ todo - -🤔 let me think - -❌ unsupport - -### 网络 - -#### 发起请求 - -✅ wx.request - -#### 上传、下载 - -☑️ wx.uploadFile - -☑️ wx.downloadFile - -#### WebSocket - -✅ wx.connectSocket - -❌ wx.onSocketOpen - -❌ wx.onSocketError - -❌ wx.sendSocketMessage - -❌ wx.onSocketMessage - -❌ wx.closeSocket - -❌ wx.onSocketClose - -✅ SocketTask - -### 媒体 - -#### 图片 - -☑️ wx.chooseImage - -☑️ wx.previewImage - -☑️ wx.getImageInfo - -🤔 wx.saveImageToPhotosAlbum - -#### 录音 - -🤔 wx.startRecord - -🤔 wx.stopRecord - -#### 录音管理 - -🤔 wx.getRecorderManager - -#### 音频播放控制 - -☑️ wx.playVoice - -☑️ wx.pauseVoice - -☑️ wx.stopVoice - -#### 音乐播放控制 - -🤔 wx.getBackgroundAudioPlayerState - -🤔 wx.playBackgroundAudio - -🤔 wx.pauseBackgroundAudio - -🤔 wx.seekBackgroundAudio - -🤔 wx.stopBackgroundAudio - -🤔 wx.onBackgroundAudioPlay - -🤔 wx.onBackgroundAudioPause - -🤔 wx.onBackgroundAudioStop - -#### 背景音频播放管理 - -🤔 wx.getBackgroundAudioManager - -#### 音频组件控制 - -☑️ wx.createAudioContext - -☑️ wx.createInnerAudioContext - -#### 视频 - -☑️ wx.chooseVideo - -🤔 wx.saveVideoToPhotosAlbum - -#### 视频组件控制 - -☑️ wx.createVideoContext - -#### 相机组件控制 - -🤔 wx.createCameraContext - -#### 实时音视频 - -🤔 wx.createLivePlayerContext - -🤔 wx.createLivePusherContext - -#### 文件 - -🤔 wx.saveFile - -☑️ wx.getFileInfo - -🤔 wx.getSavedFileList - -🤔 wx.getSavedFileInfo - -❌ wx.removeSavedFile - -❌ wx.openDocument - -#### 数据缓存 - -✅ wx.setStorage - -✅ wx.setStorageSync - -✅ wx.getStorage - -✅ wx.getStorageSync - -✅ wx.getStorageInfo - -✅ wx.getStorageInfoSync - -✅ wx.removeStorage - -✅ wx.removeStorageSync - -✅ wx.clearStorage - -✅ wx.clearStorageSync - -### 位置 - -#### 获取位置 - -🤔 wx.getLocation - -❌ wx.chooseLocation - -#### 查看位置 - -❌ wx.openLocation - -#### 地图组件控制 - -❌ wx.createMapContext - -### 设备 - -#### 系统信息 - -✅ wx.getSystemInfo - -✅️ wx.getSystemInfoSync - -☑️ wx.canIUse - -#### 网络状态 - -✅ wx.getNetworkType - -✅ wx.onNetworkStatusChange - -#### 加速度计 - -☑️ wx.onAccelerometerChange - -☑️ wx.startAccelerometer - -☑️ wx.stopAccelerometer - -#### 罗盘 - -☑️ wx.onCompassChange - -☑️ wx.startCompass - -☑️ wx.stopCompass - -#### 拨打电话 - -✅ wx.makePhoneCall - -#### 扫码 - -❌ wx.scanCode - -#### 剪贴板 - -❌ wx.setClipboardData - -❌ wx.getClipboardData - -#### 蓝牙 - -❌ wx.openBluetoothAdapter - -❌ wx.closeBluetoothAdapter - -❌ wx.getBluetoothAdapterState - -❌ wx.onBluetoothAdapterStateChange - -❌ wx.startBluetoothDevicesDiscovery - -❌ wx.stopBluetoothDevicesDiscovery - -❌ wx.getBluetoothDevices - -❌ wx.getConnectedBluetoothDevices - -❌ wx.onBluetoothDeviceFound - -❌ wx.createBLEConnection - -❌ wx.closeBLEConnection - -❌ wx.getBLEDeviceServices - -❌ wx.getBLEDeviceCharacteristics - -❌ wx.readBLECharacteristicValue - -❌ wx.writeBLECharacteristicValue - -❌ wx.notifyBLECharacteristicValueChange - -❌ wx.onBLEConnectionStateChange - -❌ wx.onBLECharacteristicValueChange - -#### iBeacon - -❌ wx.startBeaconDiscovery - -❌ wx.stopBeaconDiscovery - -❌ wx.getBeacons - -❌ wx.onBeaconUpdate - -❌ wx.onBeaconServiceChange - -#### 屏幕亮度 - -❌ wx.setScreenBrightness - -❌ wx.getScreenBrightness - -❌ wx.setKeepScreenOn - -#### 用户截屏事件 - -❌ wx.onUserCaptureScreen - -#### 振动 - -☑️ wx.vibrateLong - -☑️ wx.vibrateShort - -#### 手机联系人 - -❌ wx.addPhoneContact - -#### NFC - -❌ wx.getHCEState - -❌ wx.startHCE - -❌ wx.stopHCE - -❌ wx.onHCEMessage - -❌ wx.sendHCEMessage - -#### Wi-Fi - -❌ wx.startWifi - -❌ wx.stopWifi - -❌ wx.connectWifi - -❌ wx.getWifiList - -❌ wx.onGetWifiList - -❌ wx.setWifiList - -❌ wx.onWifiConnected - -❌ wx.getConnectedWifi - -### 界面 - -#### 交互反馈 - -✅ wx.showToast - -✅ wx.showLoading - -✅ wx.hideToast - -✅ wx.hideLoading - -✅ wx.showModal - -✅ wx.showActionSheet - -#### 设置导航条 - -❌ wx.setNavigationBarTitle - -❌ wx.showNavigationBarLoading - -❌ wx.hideNavigationBarLoading - -❌ wx.setNavigationBarColor - -#### 设置tabBar - -🤔 wx.setTabBarBadge - -🤔 wx.removeTabBarBadge - -🤔 wx.showTabBarRedDot - -🤔 wx.hideTabBarRedDot - -🤔 wx.setTabBarStyle - -🤔 wx.setTabBarItem - -🤔 wx.showTabBar - -🤔 wx.hideTabBar - -#### 设置置顶信息 - -❌ wx.setTopBarText - -#### 导航 - -✅ wx.navigateTo - -✅ wx.redirectTo - -🤔 wx.switchTab - -✅ wx.navigateBack - -🤔 wx.reLaunch - -#### 动画 - -✅ wx.createAnimation - -#### 位置 - -☑️ wx.pageScrollTo - -#### 绘图 - -☑️ wx.createCanvasContext - -☑️ wx.createContext - -☑️ wx.drawCanvas - -☑️ wx.canvasToTempFilePath - -☑️ wx.canvasGetImageData - -☑️ wx.canvasPutImageData - -☑️ setFillStyle - -☑️ setStrokeStyle - -☑️ setShadow - -☑️ createLinearGradient - -☑️ createCircularGradient - -☑️ addColorStop - -☑️ setLineWidth - -☑️ setLineCap - -☑️ setLineJoin - -☑️ setLineDash - -☑️ setMiterLimit - -☑️ rect - -☑️ fillRect - -☑️ strokeRect - -☑️ clearRect - -☑️ fill - -☑️ stroke - -☑️ beginPath - -☑️ closePath - -☑️ moveTo - -☑️ lineTo - -☑️ arc - -☑️ bezierCurveTo - -☑️ quadraticCurveTo - -☑️ scale - -☑️ rotate - -☑️ translate - -☑️ clip - -☑️ setFontSize - -☑️ fillText - -☑️ setTextAlign - -☑️ setTextBaseline - -☑️ drawImage - -☑️ setGlobalAlpha - -☑️ save - -☑️ restore - -☑️ draw - -☑️ getActions - -☑️ clearActions - -☑️ measureText - -☑️ globalCompositeOperation - -☑️ arcTo - -☑️ strokeText - -☑️ lineDashOffset - -☑️ createPattern - -☑️ shadowBlur - -☑️ shadowColor - -☑️ shadowOffsetX - -☑️ shadowOffsetY - -☑️ font - -☑️ transform - -☑️ setTransform - -#### 下拉刷新 - -🤔 Page.onPullDownRefresh - -🤔 wx.startPullDownRefresh - -🤔 wx.stopPullDownRefresh - -#### WXML节点信息 - -✅ wx.createSelectorQuery - -✅ selectorQuery.in - -✅ selectorQuery.select - -✅ selectorQuery.selectAll - -✅ selectorQuery.selectViewport - -✅ nodesRef.boundingClientRect - -✅ nodesRef.scrollOffset - -✅ nodesRef.fields - -✅ selectorQuery.exec - -#### WXML节点布局相交状态 - -🤔 wx.createIntersectionObserver - -🤔 intersectionObserver.relativeTo - -🤔 intersectionObserver.relativeToViewport - -🤔 intersectionObserver.observe - -🤔 intersectionObserver.disconnect - -### 第三方平台 - -❌ wx.getExtConfig - -❌ wx.getExtConfigSync - -### 开放接口 - -#### 登录 - -❌ wx.login - -❌ wx.checkSession - -#### 授权 - -❌ wx.authorize - -#### 用户信息 - -❌ wx.getUserInfo - -❌ getPhoneNumber - -#### 微信支付 - -❌ wx.requestPayment - -#### 模板消息 - -❌ - -#### 客服消息 - -❌ - -#### 转发 - -❌ - -#### 获取二维码 - -❌ - -#### 收货地址 - -❌ wx.chooseAddress - -#### 卡券 - -❌ wx.addCard - -❌ wx.openCard - -❌ 会员卡组件 - -#### 设置 - -❌ wx.openSetting - -❌ wx.getSetting - -#### 微信运动 - -❌ wx.getWeRunData - -#### 打开小程序 - -❌ wx.navigateToMiniProgram - -❌ wx.navigateBackMiniProgram - -#### 打开APP - -☑️ launchApp - -#### 获取发票抬头 - -❌ wx.chooseInvoiceTitle - -#### 生物认证 - -❌ wx.checkIsSupportSoterAuthentication - -❌ wx.startSoterAuthentication - -❌ wx.checkIsSoterEnrolledInDevice - -#### 附近 - -❌ - -#### 插件管理 - -❌ - -### 数据 - -❌ - -#### 更新 - -❌ wx.getUpdateManager - -#### 多线程 - -🤔 wx.createWorker - -#### 调试接口 - -❌ 打开/关闭调试 diff --git a/packages/taro-h5/src/api/customComponent/index.js b/packages/taro-h5/src/api/customComponent/index.js deleted file mode 100644 index 220f037bfb7b..000000000000 --- a/packages/taro-h5/src/api/customComponent/index.js +++ /dev/null @@ -1 +0,0 @@ -export const nextTick = Promise.resolve() diff --git a/packages/taro-h5/src/api/index.js b/packages/taro-h5/src/api/index.js index 4f1693fefd4e..2687e787595e 100644 --- a/packages/taro-h5/src/api/index.js +++ b/packages/taro-h5/src/api/index.js @@ -9,7 +9,6 @@ export * from './clipboard' export * from './compass' export * from './createAnimation' export * from './createSelectorQuery' -export * from './customComponent' export * from './deviceMotion' export * from './fileTransfer' export * from './image' diff --git a/packages/taro-h5/src/index.cjs.js b/packages/taro-h5/src/index.cjs.js deleted file mode 100644 index ede251406ec3..000000000000 --- a/packages/taro-h5/src/index.cjs.js +++ /dev/null @@ -1,11 +0,0 @@ -/* 这个入口提供给使用require的用户 */ - -import Taro from './taro/index' -import * as TaroApis from './api/index' - -export * from './taro/index' -export * from './api/index' - -Object.assign(Taro, TaroApis) - -export default Taro diff --git a/packages/taro-h5/src/index.js b/packages/taro-h5/src/index.js index bcdc00a290fc..c59699e0a258 100644 --- a/packages/taro-h5/src/index.js +++ b/packages/taro-h5/src/index.js @@ -1,6 +1,2 @@ -import Taro from './taro/index' - export * from './api/index' - -export default Taro -export * from './taro/index' +export * from './init-api' diff --git a/packages/taro-h5/src/taro/index.js b/packages/taro-h5/src/init-api.js similarity index 56% rename from packages/taro-h5/src/taro/index.js rename to packages/taro-h5/src/init-api.js index c823677b1faf..25fc21078f12 100644 --- a/packages/taro-h5/src/taro/index.js +++ b/packages/taro-h5/src/init-api.js @@ -1,27 +1,4 @@ -import Taro from '@tarojs/api' -import { history, navigateBack, navigateTo, createRouter, reLaunch, redirectTo, getCurrentPages, switchTab } from '@tarojs/router' -import { permanentlyNotSupport } from '../api/utils' - -const { - ENV_TYPE, - eventCenter, - Events, - getEnv, - initPxTransform: originalInitPxTransform, - render, - interceptors, - Current, - ...rest -} = Taro - -const taro = { - ...rest, - getEnv, - ENV_TYPE, - Events, - eventCenter, - Current, - render, +import { history, navigateBack, navigateTo, @@ -30,13 +7,10 @@ const taro = { redirectTo, getCurrentPages, switchTab -} +} from '@tarojs/router' +import { permanentlyNotSupport } from './api/utils' -const initPxTransform = originalInitPxTransform.bind(taro) const requirePlugin = permanentlyNotSupport('requirePlugin') -const getApp = function () { - return taro._$app -} /** * RouterParams @@ -60,27 +34,34 @@ const canIUseWebp = function () { return canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0 } -taro.initPxTransform = initPxTransform -taro.requirePlugin = requirePlugin -taro.getApp = getApp -taro.pxTransform = pxTransform -taro.canIUseWebp = canIUseWebp -taro.interceptors = interceptors - -export default taro +export function initNativeApi (taro) { + const getApp = function () { + return taro._$app + } + Object.assign(taro, { + // bind + initPxTransform: taro.initPxTransform.bind(taro), + // extra + requirePlugin, + getApp, + pxTransform, + canIUseWebp, + // router + history, + navigateBack, + navigateTo, + createRouter, + reLaunch, + redirectTo, + getCurrentPages, + switchTab + }) +} export { - getEnv, - ENV_TYPE, - Events, - eventCenter, - render, - initPxTransform, requirePlugin, - getApp, pxTransform, canIUseWebp, - interceptors, history, navigateBack, navigateTo, diff --git a/packages/taro-h5/yarn.lock b/packages/taro-h5/yarn.lock index 21d441f438ac..f7c7a6f66e6d 100644 --- a/packages/taro-h5/yarn.lock +++ b/packages/taro-h5/yarn.lock @@ -2,46 +2,48 @@ # yarn lockfile v1 +"@tarojs/api@3.0.9": + version "3.0.9" + resolved "https://registry.npm.taobao.org/@tarojs/api/download/@tarojs/api-3.0.9.tgz#8d76c1f2f2bb00520bd6130573b61f531e6494d8" + dependencies: + "@tarojs/runtime" "3.0.9" + +"@tarojs/runtime@3.0.9": + version "3.0.9" + resolved "https://registry.npm.taobao.org/@tarojs/runtime/download/@tarojs/runtime-3.0.9.tgz#912ed65b0845ed21a36ff272a3182f59d3063604" + base64-js@^1.3.0: version "1.3.1" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.3.1.tgz#58ece8cb75dd07e71ed08c736abc5fac4dbf8df1" - integrity sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g== jsonp-retry@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/jsonp-retry/-/jsonp-retry-1.0.3.tgz#9e6b18b02ec767a621dd44b4e99439a8a43a6419" - integrity sha512-/jmE9+shtKP+oIt2AWO9Wx+C27NTGpLCEw4QHOqpoV2X6ta374HE9C+EEdgu8r3iLKgFMx7u5j0mCwxWN8UdlA== dependencies: object-assign "^4.1.1" mobile-detect@^1.4.2: version "1.4.4" resolved "https://registry.yarnpkg.com/mobile-detect/-/mobile-detect-1.4.4.tgz#686c74e92d3cc06b09a9b3594b7b981494b137f6" - integrity sha512-vTgEjKjS89C5yHL5qWPpT6BzKuOVqABp+A3Szpbx34pIy3sngxlGaFpgHhfj6fKze1w0QKeOSDbU7SKu7wDvRQ== object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" - integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= performance-now@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" - integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns= raf@^3.4.1: version "3.4.1" resolved "https://registry.yarnpkg.com/raf/-/raf-3.4.1.tgz#0742e99a4a6552f445d73e3ee0328af0ff1ede39" - integrity sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA== dependencies: performance-now "^2.1.0" unfetch@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/unfetch/-/unfetch-4.1.0.tgz#6ec2dd0de887e58a4dee83a050ded80ffc4137db" - integrity sha512-crP/n3eAPUJxZXM9T80/yv0YhkTEx2K1D3h7D1AJM6fzsWZrxdyRuLN0JH/dkZh1LNH8LxCnBzoPFCPbb2iGpg== whatwg-fetch@^2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-2.0.4.tgz#dde6a5df315f9d39991aa17621853d720b85566f" - integrity sha512-dcQ1GWpOD/eEQ97k66aiEVpNnapVj90/+R+SXTPYGHpYBBypfKJEQjLrvMZ7YXbKm21gXd4NcuxUTjiv1YtLng== From 86f6657a3240c76a35e4c982f3e3c4aca78785ee Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Mon, 21 Sep 2020 16:01:03 +0800 Subject: [PATCH 014/272] =?UTF-8?q?chore(loader/platform/mini-runner):=20?= =?UTF-8?q?=E8=A7=A3=E8=97=95=E5=B9=B3=E5=8F=B0=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/shared/package.json | 2 +- packages/shared/src/platform-plugin-base.ts | 6 +- packages/shared/src/utils.ts | 54 ++ packages/taro-alipay/src/apis-list.ts | 61 +++ packages/taro-alipay/src/apis.ts | 489 +++++++++++++++++ packages/taro-alipay/src/program.ts | 10 +- packages/taro-alipay/src/runtime.ts | 6 +- packages/taro-alipay/types/apis-list.d.ts | 3 + packages/taro-alipay/types/apis.d.ts | 1 + packages/taro-alipay/types/program.d.ts | 2 + packages/taro-alipay/types/runtime.d.ts | 3 +- packages/taro-jd/src/apis.ts | 253 +++++++++ packages/taro-jd/src/program.ts | 7 +- packages/taro-jd/src/runtime.ts | 6 +- packages/taro-jd/types/apis.d.ts | 1 + packages/taro-jd/types/program.d.ts | 1 + packages/taro-jd/types/runtime.d.ts | 3 +- packages/taro-loader/src/app.ts | 16 + .../src/plugins/MiniPlugin.ts | 4 +- packages/taro-mini-runner/src/utils/types.ts | 1 + .../src/webpack/build.conf.ts | 4 +- packages/taro-qq/src/apis.ts | 272 ++++++++++ packages/taro-qq/src/program.ts | 3 + packages/taro-qq/src/runtime.ts | 6 +- packages/taro-runtime/package.json | 8 + packages/taro-runtime/rollup.config.js | 6 +- packages/taro-swan/src/apis-list.ts | 39 ++ packages/taro-swan/src/apis.ts | 186 +++++++ packages/taro-swan/src/program.ts | 9 +- packages/taro-swan/src/runtime.ts | 6 +- packages/taro-swan/types/apis-list.d.ts | 3 + packages/taro-swan/types/apis.d.ts | 1 + packages/taro-swan/types/program.d.ts | 2 + packages/taro-swan/types/runtime.d.ts | 3 +- packages/taro-tt/src/apis-list.ts | 14 + packages/taro-tt/src/apis.ts | 215 ++++++++ packages/taro-tt/src/program.ts | 7 +- packages/taro-tt/src/runtime.ts | 6 +- packages/taro-tt/types/apis-list.d.ts | 2 + packages/taro-tt/types/apis.d.ts | 1 + packages/taro-tt/types/program.d.ts | 1 + packages/taro-tt/types/runtime.d.ts | 3 +- packages/taro-weapp/src/apis-list.ts | 127 +++++ packages/taro-weapp/src/apis.ts | 265 +++++++++ packages/taro-weapp/src/program.ts | 10 +- packages/taro-weapp/src/runtime.ts | 4 +- packages/taro-weapp/types/apis-list.d.ts | 3 + packages/taro-weapp/types/apis.d.ts | 1 + packages/taro-weapp/types/program.d.ts | 2 + packages/taro-weapp/types/runtime.d.ts | 5 +- packages/taro/README.md | 6 +- packages/taro/index.js | 9 +- packages/taro/package.json | 1 - packages/taro/src/native-apis.js | 513 +++++++----------- 54 files changed, 2318 insertions(+), 354 deletions(-) create mode 100644 packages/taro-alipay/src/apis-list.ts create mode 100644 packages/taro-alipay/src/apis.ts create mode 100644 packages/taro-alipay/types/apis-list.d.ts create mode 100644 packages/taro-alipay/types/apis.d.ts create mode 100644 packages/taro-jd/src/apis.ts create mode 100644 packages/taro-jd/types/apis.d.ts create mode 100644 packages/taro-qq/src/apis.ts create mode 100644 packages/taro-swan/src/apis-list.ts create mode 100644 packages/taro-swan/src/apis.ts create mode 100644 packages/taro-swan/types/apis-list.d.ts create mode 100644 packages/taro-swan/types/apis.d.ts create mode 100644 packages/taro-tt/src/apis-list.ts create mode 100644 packages/taro-tt/src/apis.ts create mode 100644 packages/taro-tt/types/apis-list.d.ts create mode 100644 packages/taro-tt/types/apis.d.ts create mode 100644 packages/taro-weapp/src/apis-list.ts create mode 100644 packages/taro-weapp/src/apis.ts create mode 100644 packages/taro-weapp/types/apis-list.d.ts create mode 100644 packages/taro-weapp/types/apis.d.ts diff --git a/packages/shared/package.json b/packages/shared/package.json index 02fe0c3b31e6..571bac25e6ca 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -6,7 +6,7 @@ "homepage": "https://github.com/nervjs/taro/tree/master/packages/shared#readme", "license": "MIT", "main": "dist/index.js", - "module": "dist/index.esm.js", + "module": "dist/shared.esm.js", "types": "dist/index.d.ts", "files": [ "dist" diff --git a/packages/shared/src/platform-plugin-base.ts b/packages/shared/src/platform-plugin-base.ts index 13e7c663a020..671936cb853e 100644 --- a/packages/shared/src/platform-plugin-base.ts +++ b/packages/shared/src/platform-plugin-base.ts @@ -68,8 +68,9 @@ ${exampleCommand} /** * 准备 mini-runner 参数 + * @param extraOptions 需要额外合入 Options 的配置项 */ - getBaseOptions () { + getOptions (extraOptions = {}) { const { ctx, config, globalObject, fileType, template } = this return { @@ -78,7 +79,8 @@ ${exampleCommand} buildAdapter: config.platform, globalObject, fileType, - template + template, + ...extraOptions } } diff --git a/packages/shared/src/utils.ts b/packages/shared/src/utils.ts index bf9fdc7ae898..64463ce247fc 100644 --- a/packages/shared/src/utils.ts +++ b/packages/shared/src/utils.ts @@ -81,3 +81,57 @@ export function warn (condition: boolean, msg: string) { } } } + +export function queryToJson (str) { + const dec = decodeURIComponent + const qp = str.split('&') + const ret = {} + let name + let val + for (let i = 0, l = qp.length, item; i < l; ++i) { + item = qp[i] + if (item.length) { + const s = item.indexOf('=') + if (s < 0) { + name = dec(item) + val = '' + } else { + name = dec(item.slice(0, s)) + val = dec(item.slice(s + 1)) + } + if (typeof ret[name] === 'string') { // inline'd type check + ret[name] = [ret[name]] + } + + if (Array.isArray(ret[name])) { + ret[name].push(val) + } else { + ret[name] = val + } + } + } + return ret // Object +} + +let _uniqueId = 1 +const _loadTime = (new Date()).getTime().toString() + +export function getUniqueKey () { + return _loadTime + (_uniqueId++) +} + +const cacheData = {} + +export function cacheDataSet (key, val) { + cacheData[key] = val +} + +export function cacheDataGet (key, delelteAfterGet?) { + const temp = cacheData[key] + delelteAfterGet && delete cacheData[key] + return temp +} + +export function cacheDataHas (key) { + return key in cacheData +} diff --git a/packages/taro-alipay/src/apis-list.ts b/packages/taro-alipay/src/apis-list.ts new file mode 100644 index 000000000000..272dcb395797 --- /dev/null +++ b/packages/taro-alipay/src/apis-list.ts @@ -0,0 +1,61 @@ +export const _onAndSyncApis = new Set([ + 'offSocketClose', + 'offSocketError', + 'offSocketMessage', + 'offSocketOpen', + 'getAppIdSync' +]) + +export const _noPromiseApis = new Set([ + 'calculateRoute', + 'createWebViewContext', + 'hideAddToDesktopMenu', + 'hideAllAddToDesktopMenu', + 'hideAllFavoriteMenu', + 'hideBackHome', + 'hideFavoriteMenu', + 'openCardDetail', + 'openCardList', + 'openKBVoucherDetail', + 'openMerchantCardList', + 'openMerchantTicketList', + 'openMerchantVoucherList', + 'openTicketDetail', + 'openTicketList', + 'openVoucherDetail', + 'openVoucherList', + 'setCanPullDown', + 'setOptionMenu', + 'showSharePanel' +]) + +export const _otherApis = new Set([ + 'addCardAuth', + 'getOpenUserInfo', + 'chooseAlipayContact', + 'chooseCity', + 'chooseContact', + 'choosePhoneContact', + 'datePicker', + 'getAddress', + 'getAuthCode', + 'getPhoneNumber', + 'getRunData', + 'getRunScene', + 'getServerTime', + 'getTitleColor', + 'rsa', + 'paySignCenter', + 'tradePay', + 'isCollected', + 'multiLevelSelect', + 'onLocatedComplete', + 'optionsSelect', + 'prompt', + 'regionPicker', + 'setLocatedCity', + 'showAuthGuide', + 'textRiskIdentification', + 'vibrate', + 'watchShake' +]) diff --git a/packages/taro-alipay/src/apis.ts b/packages/taro-alipay/src/apis.ts new file mode 100644 index 000000000000..1d9713394af0 --- /dev/null +++ b/packages/taro-alipay/src/apis.ts @@ -0,0 +1,489 @@ +import { + queryToJson, + getUniqueKey, + cacheDataSet, + cacheDataGet +} from '@tarojs/shared' +import { _onAndSyncApis, _noPromiseApis, _otherApis } from './apis-list' + +declare const my: any +declare const getCurrentPages: () => any +declare const getApp: () => any + +interface ITaro { + onAndSyncApis: Set + noPromiseApis: Set + otherApis: Set + [propName: string]: any +} + +const apiDiff = { + showActionSheet: { + options: { + change: [{ + old: 'itemList', + new: 'items' + }] + } + }, + showToast: { + options: { + change: [{ + old: 'title', + new: 'content' + }, { + old: 'icon', + new: 'type' + }] + } + }, + showLoading: { + options: { + change: [{ + old: 'title', + new: 'content' + }] + } + }, + setNavigationBarTitle: { + alias: 'setNavigationBar' + }, + setNavigationBarColor: { + alias: 'setNavigationBar' + }, + saveImageToPhotosAlbum: { + alias: 'saveImage', + options: { + change: [{ + old: 'filePath', + new: 'url' + }] + } + }, + previewImage: { + options: { + set: [{ + key: 'current', + value (options) { + return options.urls.indexOf(options.current || options.urls[0]) + } + }] + } + }, + getFileInfo: { + options: { + change: [{ + old: 'filePath', + new: 'apFilePath' + }] + } + }, + getSavedFileInfo: { + options: { + change: [{ + old: 'filePath', + new: 'apFilePath' + }] + } + }, + removeSavedFile: { + options: { + change: [{ + old: 'filePath', + new: 'apFilePath' + }] + } + }, + saveFile: { + options: { + change: [{ + old: 'tempFilePath', + new: 'apFilePath' + }] + } + }, + openLocation: { + options: { + set: [{ + key: 'latitude', + value (options) { + return String(options.latitude) + } + }, { + key: 'longitude', + value (options) { + return String(options.longitude) + } + }] + } + }, + uploadFile: { + options: { + change: [{ + old: 'name', + new: 'fileName' + }] + } + }, + getClipboardData: { + alias: 'getClipboard' + }, + setClipboardData: { + alias: 'setClipboard', + options: { + change: [{ + old: 'data', + new: 'text' + }] + } + }, + makePhoneCall: { + options: { + change: [{ + old: 'phoneNumber', + new: 'number' + }] + } + }, + scanCode: { + alias: 'scan', + options: { + change: [{ + old: 'onlyFromCamera', + new: 'hideAlbum' + }], + set: [{ + key: 'type', + value (options) { + return (options.scanType && options.scanType[0].slice(0, -4)) || 'qr' + } + }] + } + }, + setScreenBrightness: { + options: { + change: [{ + old: 'value', + new: 'brightness' + }] + } + }, + onBLEConnectionStateChange: { + alias: 'onBLEConnectionStateChanged' + }, + offBLEConnectionStateChange: { + alias: 'offBLEConnectionStateChanged' + }, + createBLEConnection: { + alias: 'connectBLEDevice' + }, + closeBLEConnection: { + alias: 'disconnectBLEDevice' + } +} + +const nativeRequest = my.canIUse('request') ? my.request : my.httpRequest + +const RequestQueue = { + MAX_REQUEST: 5, + queue: [], + request (options) { + this.push(options) + // 返回request task + return this.run() + }, + + push (options) { + this.queue.push(options) + }, + + run () { + if (!this.queue.length) { + return + } + if (this.queue.length <= this.MAX_REQUEST) { + const options = this.queue.shift() + const completeFn = options.complete + options.complete = () => { + completeFn && completeFn.apply(options, [...arguments]) + this.run() + } + return nativeRequest(options) + } + } +} + +function taroInterceptor (chain) { + return request(chain.requestParams) +} + +function request (options) { + options = options || {} + if (typeof options === 'string') { + options = { + url: options + } + } + const defaultHeaders = { + 'content-type': 'application/json' + } + options.headers = defaultHeaders + if (options.header) { + for (const k in options.header) { + const lowerK = k.toLocaleLowerCase() + options.headers[lowerK] = options.header[k] + } + delete options.header + } + const originSuccess = options.success + const originFail = options.fail + const originComplete = options.complete + let requestTask + const p: any = new Promise((resolve, reject) => { + options.success = res => { + res.statusCode = res.status + delete res.status + res.header = res.headers + delete res.headers + originSuccess && originSuccess(res) + resolve(res) + } + options.fail = res => { + originFail && originFail(res) + reject(res) + } + + options.complete = res => { + originComplete && originComplete(res) + } + + requestTask = RequestQueue.request(options) + }) + p.abort = (cb) => { + cb && cb() + if (requestTask) { + requestTask.abort() + } + return p + } + return p +} + +function processApis (taro: ITaro) { + const onAndSyncApis = new Set([...taro.onAndSyncApis, ..._onAndSyncApis]) + const noPromiseApis = new Set([...taro.noPromiseApis, ..._noPromiseApis]) + const otherApis = new Set([...taro.otherApis, ..._otherApis]) + const apis = [...onAndSyncApis, ...noPromiseApis, ...otherApis] + const preloadPrivateKey = '__preload_' + const preloadInitedComponent = '$preloadComponent' + apis.forEach(key => { + if (!(key in my)) { + taro[key] = () => { + console.warn(`支付宝小程序暂不支持 ${key}`) + } + return + } + + if (otherApis.has(key)) { + taro[key] = (options, ...args) => { + const result = generateSpecialApis(key, options || {}) + const newKey = result.api + options = result.options + let task: any = null + const obj = Object.assign({}, options) + if (!(newKey in my)) { + console.warn(`支付宝小程序暂不支持 ${newKey}`) + return + } + if (typeof options === 'string') { + if (args.length) { + return my[newKey](options, ...args) + } + return my[newKey](options) + } + + if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { + let url = obj.url ? obj.url.replace(/^\//, '') : '' + if (url.indexOf('?') > -1) url = url.split('?')[0] + + const Component = cacheDataGet(url) + if (Component) { + const component = new Component() + if (component.componentWillPreload) { + const cacheKey = getUniqueKey() + const MarkIndex = obj.url.indexOf('?') + const hasMark = MarkIndex > -1 + const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' + const params = queryToJson(urlQueryStr) + obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` + cacheDataSet(cacheKey, component.componentWillPreload(params)) + cacheDataSet(preloadInitedComponent, component) + } + } + } + + const p: any = new Promise((resolve, reject) => { + ['fail', 'success', 'complete'].forEach((k) => { + obj[k] = (res) => { + if (k === 'success') { + if (newKey === 'saveFile') { + res.savedFilePath = res.apFilePath + } else if (newKey === 'downloadFile') { + res.tempFilePath = res.apFilePath + } else if (newKey === 'chooseImage') { + res.tempFilePaths = res.apFilePaths + } else if (newKey === 'getClipboard') { + res.data = res.text + } else if (newKey === 'scan') { + res.result = res.code + } else if (newKey === 'getScreenBrightness') { + res.value = res.brightness + delete res.brightness + } + } + options[k] && options[k](res) + if (k === 'success') { + resolve(res) + } else if (k === 'fail') { + reject(res) + } + } + }) + if (args.length) { + task = my[newKey](obj, ...args) + } else { + task = my[newKey](obj) + } + }) + if (newKey === 'uploadFile' || newKey === 'downloadFile') { + p.progress = cb => { + if (task) { + task.onProgressUpdate(cb) + } + return p + } + p.abort = cb => { + cb && cb() + if (task) { + task.abort() + } + return p + } + } + return p + } + } else { + taro[key] = (...args) => { + if (!(key in my)) { + console.warn(`支付宝小程序暂不支持 ${key}`) + return + } + if (key === 'getStorageSync') { + const arg1 = args[0] + if (arg1 != null) { + return my[key]({ key: arg1 }).data || my[key]({ key: arg1 }).APDataStorage || '' + } + return console.log('getStorageSync 传入参数错误') + } + if (key === 'setStorageSync') { + const arg1 = args[0] + const arg2 = args[1] + if (arg1 != null) { + return my[key]({ + key: arg1, + data: arg2 + }) + } + return console.log('setStorageSync 传入参数错误') + } + if (key === 'removeStorageSync') { + const arg1 = args[0] + if (arg1 != null) { + return my[key]({ key: arg1 }) + } + return console.log('removeStorageSync 传入参数错误') + } + if (key === 'createSelectorQuery') { + const query = my[key]() + query.in = function () { return query } + return query + } + const argsLen = args.length + const newArgs = args.concat() + const lastArg = newArgs[argsLen - 1] + if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { + newArgs.splice(argsLen - 1, 1, lastArg.$scope) + } + return my[key].apply(my, newArgs) + } + } + }) +} + +function pxTransform (size) { + const { + designWidth = 750, + deviceRatio = { + 640: 2.34 / 2, + 750: 1, + 828: 1.81 / 2 + } + } = this.config || {} + if (!(designWidth in deviceRatio)) { + throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) + } + return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' +} + +function generateSpecialApis (api, options) { + let apiAlias = api + if (api === 'showModal') { + options.cancelButtonText = options.cancelText + options.confirmButtonText = options.confirmText || '确定' + apiAlias = 'confirm' + if (options.showCancel === false) { + options.buttonText = options.confirmText || '确定' + apiAlias = 'alert' + } + } else { + Object.keys(apiDiff).forEach(item => { + const apiItem = apiDiff[item] + if (api === item) { + if (apiItem.alias) { + apiAlias = apiItem.alias + } + if (apiItem.options) { + const change = apiItem.options.change + const set = apiItem.options.set + if (change) { + change.forEach(changeItem => { + options[changeItem.new] = options[changeItem.old] + }) + } + if (set) { + set.forEach(setItem => { + options[setItem.key] = typeof setItem.value === 'function' ? setItem.value(options) : setItem.value + }) + } + } + } + }) + } + + return { + api: apiAlias, + options + } +} + +export function initNativeApi (taro) { + processApis(taro) + const link = new taro.Link(taroInterceptor) + taro.request = link.request.bind(link) + taro.addInterceptor = link.addInterceptor.bind(link) + taro.cleanInterceptors = link.cleanInterceptors.bind(link) + taro.getCurrentPages = getCurrentPages + taro.getApp = getApp + taro.initPxTransform = taro.initPxTransform.bind(taro) + taro.pxTransform = pxTransform.bind(taro) +} diff --git a/packages/taro-alipay/src/program.ts b/packages/taro-alipay/src/program.ts index 1df5f86609a0..eab4994fee7e 100644 --- a/packages/taro-alipay/src/program.ts +++ b/packages/taro-alipay/src/program.ts @@ -2,9 +2,13 @@ import { TaroPlatformBase } from '@tarojs/shared' import { Template } from './template' import { components } from './components' +const PACKAGE_NAME = '@tarojs/plugin-platform-alipay' + export default class Alipay extends TaroPlatformBase { platform = 'alipay' globalObject = 'my' + runtimePath = `${PACKAGE_NAME}/dist/runtime` + reactComponents = `${PACKAGE_NAME}/dist/components-react` fileType = { templ: '.axml', style: '.acss', @@ -25,7 +29,9 @@ export default class Alipay extends TaroPlatformBase { this.modifyWebpackChain() const runner = await this.getRunner() - const options = this.getBaseOptions() + const options = this.getOptions({ + hostConfig: this.runtimePath + }) runner(options) } @@ -78,7 +84,7 @@ export default class Alipay extends TaroPlatformBase { modifyWebpackChain () { this.ctx.modifyWebpackChain(({ chain }) => { const { taroJsComponents } = this.helper - chain.resolve.alias.set(taroJsComponents + '$', '@tarojs/plugin-platform-alipay/dist/components-react.js') + chain.resolve.alias.set(taroJsComponents + '$', this.reactComponents) }) } } diff --git a/packages/taro-alipay/src/runtime.ts b/packages/taro-alipay/src/runtime.ts index 93cb5c7be947..64a88eb4816b 100644 --- a/packages/taro-alipay/src/runtime.ts +++ b/packages/taro-alipay/src/runtime.ts @@ -1,5 +1,5 @@ +import { initNativeApi } from './apis' + export const hostConfig = { - log: function () { - console.log('ok') - } + initNativeApi } diff --git a/packages/taro-alipay/types/apis-list.d.ts b/packages/taro-alipay/types/apis-list.d.ts new file mode 100644 index 000000000000..f77285489736 --- /dev/null +++ b/packages/taro-alipay/types/apis-list.d.ts @@ -0,0 +1,3 @@ +export declare const _onAndSyncApis: Set; +export declare const _noPromiseApis: Set; +export declare const _otherApis: Set; diff --git a/packages/taro-alipay/types/apis.d.ts b/packages/taro-alipay/types/apis.d.ts new file mode 100644 index 000000000000..5738d9110523 --- /dev/null +++ b/packages/taro-alipay/types/apis.d.ts @@ -0,0 +1 @@ +export declare function initNativeApi(taro: any): void; diff --git a/packages/taro-alipay/types/program.d.ts b/packages/taro-alipay/types/program.d.ts index f1373296bc0e..955e556e2b3a 100644 --- a/packages/taro-alipay/types/program.d.ts +++ b/packages/taro-alipay/types/program.d.ts @@ -3,6 +3,8 @@ import { Template } from './template'; export default class Alipay extends TaroPlatformBase { platform: string; globalObject: string; + runtimePath: string; + reactComponents: string; fileType: { templ: string; style: string; diff --git a/packages/taro-alipay/types/runtime.d.ts b/packages/taro-alipay/types/runtime.d.ts index 5448c1d735d7..c5f1dbe0717a 100644 --- a/packages/taro-alipay/types/runtime.d.ts +++ b/packages/taro-alipay/types/runtime.d.ts @@ -1,3 +1,4 @@ +import { initNativeApi } from './apis'; export declare const hostConfig: { - log: () => void; + initNativeApi: typeof initNativeApi; }; diff --git a/packages/taro-jd/src/apis.ts b/packages/taro-jd/src/apis.ts new file mode 100644 index 000000000000..59fef1fbe8d1 --- /dev/null +++ b/packages/taro-jd/src/apis.ts @@ -0,0 +1,253 @@ +import { + queryToJson, + getUniqueKey, + cacheDataSet, + cacheDataGet +} from '@tarojs/shared' + +declare const jd: any +declare const getCurrentPages: () => any +declare const getApp: () => any + +const RequestQueue = { + MAX_REQUEST: 5, + queue: [], + request (options) { + this.push(options) + // 返回request task + return this.run() + }, + + push (options) { + this.queue.push(options) + }, + + run () { + if (!this.queue.length) { + return + } + if (this.queue.length <= this.MAX_REQUEST) { + const options = this.queue.shift() + const completeFn = options.complete + options.complete = (...args) => { + completeFn && completeFn.apply(options, args) + this.run() + } + return jd.request(options) + } + } +} + +function taroInterceptor (chain) { + return request(chain.requestParams) +} + +function request (options) { + options = options || {} + if (typeof options === 'string') { + options = { + url: options + } + } + const originSuccess = options.success + const originFail = options.fail + const originComplete = options.complete + let requestTask + const p: any = new Promise((resolve, reject) => { + options.success = res => { + originSuccess && originSuccess(res) + resolve(res) + } + options.fail = res => { + originFail && originFail(res) + reject(res) + } + + options.complete = res => { + originComplete && originComplete(res) + } + + requestTask = RequestQueue.request(options) + }) + p.abort = (cb) => { + cb && cb() + if (requestTask) { + requestTask.abort() + } + return p + } + return p +} + +function processApis (taro) { + const { onAndSyncApis, noPromiseApis, otherApis } = taro + const apis = [...onAndSyncApis, ...noPromiseApis, ...otherApis] + const useDataCacheApis = { + navigateTo: true, + redirectTo: true, + reLaunch: true + } + const routerParamsPrivateKey = '__key_' + const preloadPrivateKey = '__preload_' + const preloadInitedComponent = '$preloadComponent' + apis.forEach(key => { + if (!(key in jd)) { + taro[key] = () => { + console.warn(`京东小程序暂不支持 ${key}`) + } + return + } + + if (otherApis.has(key)) { + taro[key] = (options, ...args) => { + options = options || {} + let task: any = null + const obj = Object.assign({}, options) + if (typeof options === 'string') { + if (args.length) { + return jd[key](options, ...args) + } + return jd[key](options) + } + + if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { + let url = obj.url ? obj.url.replace(/^\//, '') : '' + if (url.indexOf('?') > -1) url = url.split('?')[0] + + const Component = cacheDataGet(url) + if (Component) { + const component = new Component() + if (component.componentWillPreload) { + const cacheKey = getUniqueKey() + const MarkIndex = obj.url.indexOf('?') + const hasMark = MarkIndex > -1 + const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' + const params = queryToJson(urlQueryStr) + obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` + cacheDataSet(cacheKey, component.componentWillPreload(params)) + cacheDataSet(preloadInitedComponent, component) + } + } + } + + if (useDataCacheApis[key]) { + const url = obj.url = obj.url || '' + const MarkIndex = url.indexOf('?') + const hasMark = MarkIndex > -1 + const urlQueryStr = hasMark ? url.substring(MarkIndex + 1, url.length) : '' + const params = queryToJson(urlQueryStr) + const cacheKey = getUniqueKey() + obj.url += (hasMark ? '&' : '?') + `${routerParamsPrivateKey}=${cacheKey}` + cacheDataSet(cacheKey, params) + } + + const p: any = new Promise((resolve, reject) => { + ['fail', 'success', 'complete'].forEach((k) => { + obj[k] = (res) => { + options[k] && options[k](res) + if (k === 'success') { + if (key === 'connectSocket') { + resolve( + Promise.resolve().then(() => Object.assign(task, res)) + ) + } else { + resolve(res) + } + } else if (k === 'fail') { + reject(res) + } + } + }) + if (args.length) { + task = jd[key](obj, ...args) + } else { + task = jd[key](obj) + } + }) + if (key === 'uploadFile' || key === 'downloadFile') { + p.progress = cb => { + if (task) { + task.onProgressUpdate(cb) + } + return p + } + p.abort = cb => { + cb && cb() + if (task) { + task.abort() + } + return p + } + } + return p + } + } else { + taro[key] = (...args) => { + const argsLen = args.length + const newArgs = args.concat() + const lastArg = newArgs[argsLen - 1] + if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { + newArgs.splice(argsLen - 1, 1, lastArg.$scope) + } + return jd[key].apply(jd, newArgs) + } + } + }) +} + +function pxTransform (size) { + const { + designWidth = 750, + deviceRatio = { + 640: 2.34 / 2, + 750: 1, + 828: 1.81 / 2 + } + } = this.config || {} + if (!(designWidth in deviceRatio)) { + throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) + } + return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' +} + +function canIUseWebp () { + const { platform = '' } = jd.getSystemInfoSync() + const platformLower = platform.toLowerCase() + if (platformLower === 'android' || platformLower === 'devtools') { + return true + } + return false +} + +function jdCloud (taro) { + const jdC = jd.cloud || {} + const jdcloud = {} + const apiList = [ + 'init', + 'database', + 'uploadFile', + 'downloadFile', + 'getTempFileURL', + 'deleteFile', + 'callFunction', + 'CloudID' + ] + apiList.forEach(v => { + jdcloud[v] = jdC[v] + }) + taro.cloud = jdcloud +} + +export function initNativeApi (taro) { + processApis(taro) + const link = new taro.Link(taroInterceptor) + taro.request = link.request.bind(link) + taro.addInterceptor = link.addInterceptor.bind(link) + taro.cleanInterceptors = link.cleanInterceptors.bind(link) + taro.getCurrentPages = getCurrentPages + taro.getApp = getApp + taro.initPxTransform = taro.initPxTransform.bind(taro) + taro.pxTransform = pxTransform.bind(taro) + taro.canIUseWebp = canIUseWebp + jdCloud(taro) +} diff --git a/packages/taro-jd/src/program.ts b/packages/taro-jd/src/program.ts index 2e7b10d263fa..7f388de61698 100644 --- a/packages/taro-jd/src/program.ts +++ b/packages/taro-jd/src/program.ts @@ -1,10 +1,13 @@ import { TaroPlatformBase } from '@tarojs/shared' import { Template } from './template' +const PACKAGE_NAME = '@tarojs/plugin-platform-jd' + export default class JD extends TaroPlatformBase { platform = 'jd' globalObject = 'jd' projectConfigJson = 'project.jd.json' + runtimePath = `${PACKAGE_NAME}/dist/runtime` fileType = { templ: '.jxml', style: '.jxss', @@ -22,7 +25,9 @@ export default class JD extends TaroPlatformBase { this.generateProjectConfig(this.projectConfigJson) const runner = await this.getRunner() - const options = this.getBaseOptions() + const options = this.getOptions({ + hostConfig: this.runtimePath + }) runner(options) } } diff --git a/packages/taro-jd/src/runtime.ts b/packages/taro-jd/src/runtime.ts index 93cb5c7be947..64a88eb4816b 100644 --- a/packages/taro-jd/src/runtime.ts +++ b/packages/taro-jd/src/runtime.ts @@ -1,5 +1,5 @@ +import { initNativeApi } from './apis' + export const hostConfig = { - log: function () { - console.log('ok') - } + initNativeApi } diff --git a/packages/taro-jd/types/apis.d.ts b/packages/taro-jd/types/apis.d.ts new file mode 100644 index 000000000000..5738d9110523 --- /dev/null +++ b/packages/taro-jd/types/apis.d.ts @@ -0,0 +1 @@ +export declare function initNativeApi(taro: any): void; diff --git a/packages/taro-jd/types/program.d.ts b/packages/taro-jd/types/program.d.ts index 860d24197ae1..0e2c6fd21040 100644 --- a/packages/taro-jd/types/program.d.ts +++ b/packages/taro-jd/types/program.d.ts @@ -4,6 +4,7 @@ export default class JD extends TaroPlatformBase { platform: string; globalObject: string; projectConfigJson: string; + runtimePath: string; fileType: { templ: string; style: string; diff --git a/packages/taro-jd/types/runtime.d.ts b/packages/taro-jd/types/runtime.d.ts index 5448c1d735d7..c5f1dbe0717a 100644 --- a/packages/taro-jd/types/runtime.d.ts +++ b/packages/taro-jd/types/runtime.d.ts @@ -1,3 +1,4 @@ +import { initNativeApi } from './apis'; export declare const hostConfig: { - log: () => void; + initNativeApi: typeof initNativeApi; }; diff --git a/packages/taro-loader/src/app.ts b/packages/taro-loader/src/app.ts index 5721ca7591b5..3d41071e900f 100644 --- a/packages/taro-loader/src/app.ts +++ b/packages/taro-loader/src/app.ts @@ -12,12 +12,28 @@ export default function (this: webpack.loader.LoaderContext) { if (typeof PRERENDER !== 'undefined') { global._prerender = inst }` + + const setReconciler = mergeHostConfig(options) + return `import { ${creator}, window } from '@tarojs/runtime' import component from ${stringify(this.request.split('!').slice(1).join('!'))} ${importFrameworkStatement} +${setReconciler} var config = ${config}; window.__taroAppConfig = config var inst = App(${creator}(component, ${frameworkArgs})) ${options.prerender ? prerender : ''} ` } + +function mergeHostConfig (options) { + if (options.hostConfig) { + return ` + import { CurrentReconciler } from '@tarojs/runtime' + import { hostConfig } from '${options.hostConfig}' + Object.assign(CurrentReconciler, hostConfig) +` + } else { + return '' + } +} diff --git a/packages/taro-mini-runner/src/plugins/MiniPlugin.ts b/packages/taro-mini-runner/src/plugins/MiniPlugin.ts index 5e05a4d54c0b..3d5fb63caa8e 100644 --- a/packages/taro-mini-runner/src/plugins/MiniPlugin.ts +++ b/packages/taro-mini-runner/src/plugins/MiniPlugin.ts @@ -49,6 +49,7 @@ interface ITaroMiniPluginOptions { template: RecursiveTemplate | UnRecursiveTemplate modifyBuildAssets?: Function modifyMiniConfigs?: Function + hostConfig?: string } export interface IComponentObj { @@ -221,7 +222,8 @@ export default class TaroMiniPlugin { options: { framework, prerender: this.prerenderPages.size > 0, - config: this.appConfig + config: this.appConfig, + hostConfig: this.options.hostConfig } }) } diff --git a/packages/taro-mini-runner/src/utils/types.ts b/packages/taro-mini-runner/src/utils/types.ts index 5b9c562ba26f..276b465b00a4 100644 --- a/packages/taro-mini-runner/src/utils/types.ts +++ b/packages/taro-mini-runner/src/utils/types.ts @@ -59,6 +59,7 @@ export interface IBuildConfig extends IProjectBaseConfig, IMiniAppConfig { baseLevel: number, prerender?: PrerenderConfig template: RecursiveTemplate | UnRecursiveTemplate + hostConfig?: string } export type AddPageChunks = ((pages: Map, pagesNames?: string[]) => void) diff --git a/packages/taro-mini-runner/src/webpack/build.conf.ts b/packages/taro-mini-runner/src/webpack/build.conf.ts index 119a5c5994ed..c2a8a8d04e38 100644 --- a/packages/taro-mini-runner/src/webpack/build.conf.ts +++ b/packages/taro-mini-runner/src/webpack/build.conf.ts @@ -39,6 +39,7 @@ export default (appPath: string, mode, config: Partial): any => { outputRoot = 'dist', sourceRoot = 'src', isBuildPlugin = false, + hostConfig, designWidth = 750, deviceRatio, @@ -151,7 +152,8 @@ export default (appPath: string, mode, config: Partial): any => { addChunkPages, modifyMiniConfigs, modifyBuildAssets, - minifyXML + minifyXML, + hostConfig }) plugin.miniCssExtractPlugin = getMiniCssExtractPlugin([{ diff --git a/packages/taro-qq/src/apis.ts b/packages/taro-qq/src/apis.ts new file mode 100644 index 000000000000..31141f9f5784 --- /dev/null +++ b/packages/taro-qq/src/apis.ts @@ -0,0 +1,272 @@ +import { + queryToJson, + getUniqueKey, + cacheDataSet, + cacheDataGet +} from '@tarojs/shared' +import { + _onAndSyncApis as wxOnAndSyncApis, + _noPromiseApis as wxNoPromiseApis, + _otherApis as wxOtherApis +} from '@tarojs/plugin-platform-weapp/dist/apis-list' + +declare const qq: any +declare const getCurrentPages: () => any +declare const getApp: () => any +declare const requirePlugin: () => void + +const _noPromiseApis = new Set([ + 'createAppBox' +]) + +const _otherApis = new Set([ + 'getQQRunData', + 'requestWxPayment', + 'setAvatar', + 'shareInvite', + 'updateBookshelfReadTime' +]) + +const RequestQueue = { + MAX_REQUEST: 5, + queue: [], + request (options) { + this.push(options) + // 返回request task + return this.run() + }, + + push (options) { + this.queue.push(options) + }, + + run () { + if (!this.queue.length) { + return + } + if (this.queue.length <= this.MAX_REQUEST) { + const options = this.queue.shift() + const completeFn = options.complete + options.complete = (...args) => { + completeFn && completeFn.apply(options, args) + this.run() + } + return qq.request(options) + } + } +} + +function taroInterceptor (chain) { + return request(chain.requestParams) +} + +function request (options) { + options = options || {} + if (typeof options === 'string') { + options = { + url: options + } + } + const originSuccess = options.success + const originFail = options.fail + const originComplete = options.complete + let requestTask + const p: any = new Promise((resolve, reject) => { + options.success = res => { + originSuccess && originSuccess(res) + resolve(res) + } + options.fail = res => { + originFail && originFail(res) + reject(res) + } + + options.complete = res => { + originComplete && originComplete(res) + } + + requestTask = RequestQueue.request(options) + }) + p.abort = (cb) => { + cb && cb() + if (requestTask) { + requestTask.abort() + } + return p + } + return p +} + +function processApis (taro) { + const onAndSyncApis = new Set([...taro.onAndSyncApis, ...wxOnAndSyncApis]) + const noPromiseApis = new Set([...taro.noPromiseApis, ...wxNoPromiseApis, ..._noPromiseApis]) + const otherApis = new Set([...taro.otherApis, ...wxOtherApis, ..._otherApis]) + const apis = [...onAndSyncApis, ...noPromiseApis, ...otherApis] + const useDataCacheApis = { + navigateTo: true, + redirectTo: true, + reLaunch: true + } + const routerParamsPrivateKey = '__key_' + const preloadPrivateKey = '__preload_' + const preloadInitedComponent = '$preloadComponent' + apis.forEach(key => { + if (!(key in qq)) { + taro[key] = () => { + console.warn(`QQ 小程序暂不支持 ${key}`) + } + return + } + if (otherApis.has(key)) { + taro[key] = (options, ...args) => { + options = options || {} + let task: any = null + const obj = Object.assign({}, options) + if (typeof options === 'string') { + if (args.length) { + return qq[key](options, ...args) + } + return qq[key](options) + } + + if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { + let url = obj.url ? obj.url.replace(/^\//, '') : '' + if (url.indexOf('?') > -1) url = url.split('?')[0] + + const Component = cacheDataGet(url) + if (Component) { + const component = new Component() + if (component.componentWillPreload) { + const cacheKey = getUniqueKey() + const MarkIndex = obj.url.indexOf('?') + const hasMark = MarkIndex > -1 + const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' + const params = queryToJson(urlQueryStr) + obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` + cacheDataSet(cacheKey, component.componentWillPreload(params)) + cacheDataSet(preloadInitedComponent, component) + } + } + } + + if (useDataCacheApis[key]) { + const url = obj.url = obj.url || '' + const MarkIndex = url.indexOf('?') + const hasMark = MarkIndex > -1 + const urlQueryStr = hasMark ? url.substring(MarkIndex + 1, url.length) : '' + const params = queryToJson(urlQueryStr) + const cacheKey = getUniqueKey() + obj.url += (hasMark ? '&' : '?') + `${routerParamsPrivateKey}=${cacheKey}` + cacheDataSet(cacheKey, params) + } + + const p: any = new Promise((resolve, reject) => { + ['fail', 'success', 'complete'].forEach((k) => { + obj[k] = (res) => { + options[k] && options[k](res) + if (k === 'success') { + if (key === 'connectSocket') { + resolve( + Promise.resolve().then(() => Object.assign(task, res)) + ) + } else { + resolve(res) + } + } else if (k === 'fail') { + reject(res) + } + } + }) + if (args.length) { + task = qq[key](obj, ...args) + } else { + task = qq[key](obj) + } + }) + if (key === 'uploadFile' || key === 'downloadFile') { + p.progress = cb => { + if (task) { + task.onProgressUpdate(cb) + } + return p + } + p.abort = cb => { + cb && cb() + if (task) { + task.abort() + } + return p + } + } + return p + } + } else { + taro[key] = (...args) => { + const argsLen = args.length + const newArgs = args.concat() + const lastArg = newArgs[argsLen - 1] + if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { + newArgs.splice(argsLen - 1, 1, lastArg.$scope) + } + return qq[key].apply(qq, newArgs) + } + } + }) +} + +function pxTransform (size) { + const { + designWidth = 750, + deviceRatio = { + 640: 2.34 / 2, + 750: 1, + 828: 1.81 / 2 + } + } = this.config || {} + if (!(designWidth in deviceRatio)) { + throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) + } + return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' +} + +function canIUseWebp () { + const { platform } = qq.getSystemInfoSync() + const platformLower = platform.toLowerCase() + if (platformLower === 'android' || platformLower === 'devtools') { + return true + } + return false +} + +function qqCloud (taro) { + const qqC = qq.cloud || {} + const qqcloud = {} + const apiList = [ + 'init', + 'database', + 'uploadFile', + 'downloadFile', + 'getTempFileURL', + 'deleteFile', + 'callFunction' + ] + apiList.forEach(v => { + qqcloud[v] = qqC[v] + }) + taro.cloud = qqcloud +} + +export function initNativeApi (taro) { + processApis(taro) + const link = new taro.Link(taroInterceptor) + taro.request = link.request.bind(link) + taro.addInterceptor = link.addInterceptor.bind(link) + taro.cleanInterceptors = link.cleanInterceptors.bind(link) + taro.getCurrentPages = getCurrentPages + taro.getApp = getApp + taro.requirePlugin = requirePlugin + taro.initPxTransform = taro.initPxTransform.bind(taro) + taro.pxTransform = pxTransform.bind(taro) + taro.canIUseWebp = canIUseWebp + qqCloud(taro) +} diff --git a/packages/taro-qq/src/program.ts b/packages/taro-qq/src/program.ts index d7156b3f38af..a09c3cd9815f 100644 --- a/packages/taro-qq/src/program.ts +++ b/packages/taro-qq/src/program.ts @@ -1,10 +1,13 @@ import { Weapp } from '@tarojs/plugin-platform-weapp' import { components } from './components' +const PACKAGE_NAME = '@tarojs/plugin-platform-qq' + export default class QQ extends Weapp { platform = 'qq' globalObject = 'qq' projectConfigJson = 'project.qq.json' + runtimePath = `${PACKAGE_NAME}/dist/runtime` fileType = { templ: '.qml', style: '.qss', diff --git a/packages/taro-qq/src/runtime.ts b/packages/taro-qq/src/runtime.ts index 93cb5c7be947..64a88eb4816b 100644 --- a/packages/taro-qq/src/runtime.ts +++ b/packages/taro-qq/src/runtime.ts @@ -1,5 +1,5 @@ +import { initNativeApi } from './apis' + export const hostConfig = { - log: function () { - console.log('ok') - } + initNativeApi } diff --git a/packages/taro-runtime/package.json b/packages/taro-runtime/package.json index 578b9ad04c47..531241f84679 100644 --- a/packages/taro-runtime/package.json +++ b/packages/taro-runtime/package.json @@ -20,5 +20,13 @@ "license": "MIT", "publishConfig": { "access": "public" + }, + "dependencies": { + "@tarojs/plugin-platform-alipay": "3.0.9", + "@tarojs/plugin-platform-jd": "3.0.9", + "@tarojs/plugin-platform-qq": "3.0.9", + "@tarojs/plugin-platform-swan": "3.0.9", + "@tarojs/plugin-platform-tt": "3.0.9", + "@tarojs/plugin-platform-weapp": "3.0.9" } } diff --git a/packages/taro-runtime/rollup.config.js b/packages/taro-runtime/rollup.config.js index 05ed72e602ef..ae12f85edc6d 100644 --- a/packages/taro-runtime/rollup.config.js +++ b/packages/taro-runtime/rollup.config.js @@ -25,7 +25,11 @@ const baseConfig = { ] }), typescript(), - buble() + buble({ + transforms: { + asyncAwait: false + } + }) ] } const esmConfig = Object.assign({}, baseConfig, { diff --git a/packages/taro-swan/src/apis-list.ts b/packages/taro-swan/src/apis-list.ts new file mode 100644 index 000000000000..3807126ec0e5 --- /dev/null +++ b/packages/taro-swan/src/apis-list.ts @@ -0,0 +1,39 @@ +export const _onAndSyncApis = new Set([ + 'getEnvInfoSync', + 'isLoginSync' + +]) + +export const _noPromiseApis = new Set([ + 'createARCameraContext', + 'createAnimationVideo', + 'createRtcRoomContext', + 'getURLQuery', + 'setURLQuery' +]) + +export const _otherApis = new Set([ + 'addEventOnCalendar', + 'chooseAlbum', + 'closeCommunityEditor', + 'getSwanId', + 'requestPolymerPayment', + 'navigateBackSmartProgram', + 'navigateToSmartProgram', + 'setPageInfo', + 'closeReplyEditor', + 'deleteBookShelf', + 'deleteEventOnCalendar', + 'getSystemRiskInfo', + 'insertBookshelf', + 'loadSubPackage', + 'openCommunityEditor', + 'openReplyEditor', + 'openShare', + 'setDocumentTitle', + 'setMetaDescription', + 'setMetaKeywords', + 'shareFile', + 'subscribeService', + 'updateBookshelfReadTime' +]) diff --git a/packages/taro-swan/src/apis.ts b/packages/taro-swan/src/apis.ts new file mode 100644 index 000000000000..d9457ec692be --- /dev/null +++ b/packages/taro-swan/src/apis.ts @@ -0,0 +1,186 @@ +import { _onAndSyncApis, _noPromiseApis, _otherApis } from './apis-list' + +declare const swan: any +declare const getCurrentPages: () => any +declare const getApp: () => any + +interface ITaro { + onAndSyncApis: Set + noPromiseApis: Set + otherApis: Set + [propName: string]: any +} + +const RequestQueue = { + MAX_REQUEST: 5, + queue: [], + request (options) { + this.push(options) + // 返回request task + return this.run() + }, + + push (options) { + this.queue.push(options) + }, + + run () { + if (!this.queue.length) { + return + } + if (this.queue.length <= this.MAX_REQUEST) { + const options = this.queue.shift() + const completeFn = options.complete + options.complete = () => { + completeFn && completeFn.apply(options, [...arguments]) + this.run() + } + return swan.request(options) + } + } +} + +function taroInterceptor (chain) { + return request(chain.requestParams) +} + +function request (options) { + options = options || {} + if (typeof options === 'string') { + options = { + url: options + } + } + const originSuccess = options.success + const originFail = options.fail + const originComplete = options.complete + let requestTask + const p: any = new Promise((resolve, reject) => { + options.success = res => { + originSuccess && originSuccess(res) + resolve(res) + } + options.fail = res => { + originFail && originFail(res) + reject(res) + } + + options.complete = res => { + originComplete && originComplete(res) + } + + requestTask = RequestQueue.request(options) + }) + p.abort = (cb) => { + cb && cb() + if (requestTask) { + requestTask.abort() + } + return p + } + return p +} + +function processApis (taro: ITaro) { + const onAndSyncApis = new Set([...taro.onAndSyncApis, ..._onAndSyncApis]) + const noPromiseApis = new Set([...taro.noPromiseApis, ..._noPromiseApis]) + const otherApis = new Set([...taro.otherApis, ..._otherApis]) + const apis = [...onAndSyncApis, ...noPromiseApis, ...otherApis] + apis.forEach(key => { + if (!(key in swan)) { + taro[key] = () => { + console.warn(`百度小程序暂不支持 ${key}`) + } + return + } + if (otherApis.has(key)) { + taro[key] = (options, ...args) => { + options = options || {} + let task: any = null + const obj = Object.assign({}, options) + if (typeof options === 'string') { + if (args.length) { + return swan[key](options, ...args) + } + return swan[key](options) + } + const p: any = new Promise((resolve, reject) => { + ['fail', 'success', 'complete'].forEach((k) => { + obj[k] = (res) => { + options[k] && options[k](res) + if (k === 'success') { + if (key === 'connectSocket') { + resolve( + Promise.resolve().then(() => Object.assign(task, res)) + ) + } else { + resolve(res) + } + } else if (k === 'fail') { + reject(res) + } + } + }) + if (args.length) { + task = swan[key](obj, ...args) + } else { + task = swan[key](obj) + } + }) + if (key === 'uploadFile' || key === 'downloadFile') { + p.progress = cb => { + if (task) { + task.onProgressUpdate(cb) + } + return p + } + p.abort = cb => { + cb && cb() + if (task) { + task.abort() + } + return p + } + } + return p + } + } else { + taro[key] = (...args) => { + const argsLen = args.length + const newArgs = args.concat() + const lastArg = newArgs[argsLen - 1] + if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { + newArgs.splice(argsLen - 1, 1, lastArg.$scope) + } + return swan[key].apply(swan, newArgs) + } + } + }) +} + +function pxTransform (size) { + const { + designWidth = 750, + deviceRatio = { + 640: 2.34 / 2, + 750: 1, + 828: 1.81 / 2 + } + } = this.config || {} + if (!(designWidth in deviceRatio)) { + throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) + } + return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' +} + +export function initNativeApi (taro) { + processApis(taro) + const link = new taro.Link(taroInterceptor) + taro.request = link.request.bind(link) + taro.addInterceptor = link.addInterceptor.bind(link) + taro.cleanInterceptors = link.cleanInterceptors.bind(link) + taro.getCurrentPages = getCurrentPages + taro.getApp = getApp + taro.initPxTransform = taro.initPxTransform.bind(taro) + taro.pxTransform = pxTransform.bind(taro) +} diff --git a/packages/taro-swan/src/program.ts b/packages/taro-swan/src/program.ts index e57aa78c6c5d..c34de416a735 100644 --- a/packages/taro-swan/src/program.ts +++ b/packages/taro-swan/src/program.ts @@ -2,12 +2,15 @@ import { TaroPlatformBase } from '@tarojs/shared' import { Template } from './template' import { components } from './components' +const PACKAGE_NAME = '@tarojs/plugin-platform-swan' const PROJECT_JSON = 'project.swan.json' export default class Swan extends TaroPlatformBase { platform = 'swan' globalObject = 'swan' projectConfigJson = PROJECT_JSON + runtimePath = `${PACKAGE_NAME}/dist/runtime` + reactComponents = `${PACKAGE_NAME}/dist/components-react` fileType = { templ: '.swan', style: '.css', @@ -28,7 +31,9 @@ export default class Swan extends TaroPlatformBase { this.modifyWebpackChain() const runner = await this.getRunner() - const options = this.getBaseOptions() + const options = this.getOptions({ + hostConfig: this.runtimePath + }) runner(options) } @@ -48,7 +53,7 @@ export default class Swan extends TaroPlatformBase { modifyWebpackChain () { this.ctx.modifyWebpackChain(({ chain }) => { const { taroJsComponents } = this.helper - chain.resolve.alias.set(taroJsComponents + '$', '@tarojs/plugin-platform-swan/dist/components-react.js') + chain.resolve.alias.set(taroJsComponents + '$', this.reactComponents) }) } } diff --git a/packages/taro-swan/src/runtime.ts b/packages/taro-swan/src/runtime.ts index 93cb5c7be947..64a88eb4816b 100644 --- a/packages/taro-swan/src/runtime.ts +++ b/packages/taro-swan/src/runtime.ts @@ -1,5 +1,5 @@ +import { initNativeApi } from './apis' + export const hostConfig = { - log: function () { - console.log('ok') - } + initNativeApi } diff --git a/packages/taro-swan/types/apis-list.d.ts b/packages/taro-swan/types/apis-list.d.ts new file mode 100644 index 000000000000..f77285489736 --- /dev/null +++ b/packages/taro-swan/types/apis-list.d.ts @@ -0,0 +1,3 @@ +export declare const _onAndSyncApis: Set; +export declare const _noPromiseApis: Set; +export declare const _otherApis: Set; diff --git a/packages/taro-swan/types/apis.d.ts b/packages/taro-swan/types/apis.d.ts new file mode 100644 index 000000000000..5738d9110523 --- /dev/null +++ b/packages/taro-swan/types/apis.d.ts @@ -0,0 +1 @@ +export declare function initNativeApi(taro: any): void; diff --git a/packages/taro-swan/types/program.d.ts b/packages/taro-swan/types/program.d.ts index 0cd6b10a9efc..6d65b246b9ed 100644 --- a/packages/taro-swan/types/program.d.ts +++ b/packages/taro-swan/types/program.d.ts @@ -4,6 +4,8 @@ export default class Swan extends TaroPlatformBase { platform: string; globalObject: string; projectConfigJson: string; + runtimePath: string; + reactComponents: string; fileType: { templ: string; style: string; diff --git a/packages/taro-swan/types/runtime.d.ts b/packages/taro-swan/types/runtime.d.ts index 5448c1d735d7..c5f1dbe0717a 100644 --- a/packages/taro-swan/types/runtime.d.ts +++ b/packages/taro-swan/types/runtime.d.ts @@ -1,3 +1,4 @@ +import { initNativeApi } from './apis'; export declare const hostConfig: { - log: () => void; + initNativeApi: typeof initNativeApi; }; diff --git a/packages/taro-tt/src/apis-list.ts b/packages/taro-tt/src/apis-list.ts new file mode 100644 index 000000000000..df64134e78d3 --- /dev/null +++ b/packages/taro-tt/src/apis-list.ts @@ -0,0 +1,14 @@ +export const _noPromiseApis = new Set([ + 'canIPutStuffOverComponent' +]) + +export const _otherApis = new Set([ + 'checkFollowState', + 'exitMiniProgram', + 'followOfficialAccount', + 'getMenuButtonLayout', + 'hideInteractionBar', + 'pay', + 'navigateToVideoView', + 'showInteractionBar' +]) diff --git a/packages/taro-tt/src/apis.ts b/packages/taro-tt/src/apis.ts new file mode 100644 index 000000000000..37739ba6a213 --- /dev/null +++ b/packages/taro-tt/src/apis.ts @@ -0,0 +1,215 @@ +import { + queryToJson, + getUniqueKey, + cacheDataSet, + cacheDataGet +} from '@tarojs/shared' +import { _noPromiseApis, _otherApis } from './apis-list' + +declare const tt: any +declare const getCurrentPages: () => any +declare const getApp: () => any + +interface ITaro { + onAndSyncApis: Set + noPromiseApis: Set + otherApis: Set + [propName: string]: any +} + +const RequestQueue = { + MAX_REQUEST: 5, + queue: [], + request (options) { + this.push(options) + // 返回request task + return this.run() + }, + + push (options) { + this.queue.push(options) + }, + + run () { + if (!this.queue.length) { + return + } + if (this.queue.length <= this.MAX_REQUEST) { + const options = this.queue.shift() + const completeFn = options.complete + options.complete = () => { + completeFn && completeFn.apply(options, [...arguments]) + this.run() + } + return tt.request(options) + } + } +} + +function taroInterceptor (chain) { + return request(chain.requestParams) +} + +function request (options) { + options = options || {} + if (typeof options === 'string') { + options = { + url: options + } + } + const originSuccess = options.success + const originFail = options.fail + const originComplete = options.complete + let requestTask + const p: any = new Promise((resolve, reject) => { + options.success = res => { + originSuccess && originSuccess(res) + resolve(res) + } + options.fail = res => { + originFail && originFail(res) + reject(res) + } + + options.complete = res => { + originComplete && originComplete(res) + } + + requestTask = RequestQueue.request(options) + }) + p.abort = (cb) => { + cb && cb() + if (requestTask) { + requestTask.abort() + } + return p + } + return p +} + +function processApis (taro: ITaro) { + const { onAndSyncApis } = taro + const noPromiseApis = new Set([...taro.noPromiseApis, ..._noPromiseApis]) + const otherApis = new Set([...taro.otherApis, ..._otherApis]) + const apis = [...onAndSyncApis, ...noPromiseApis, ...otherApis] + const preloadPrivateKey = '__preload_' + const preloadInitedComponent = '$preloadComponent' + apis.forEach(key => { + if (!(key in tt)) { + taro[key] = () => { + console.warn(`头条小程序暂不支持 ${key}`) + } + return + } + if (otherApis.has(key)) { + taro[key] = (options, ...args) => { + options = options || {} + let task: any = null + const obj = Object.assign({}, options) + if (typeof options === 'string') { + if (args.length) { + return tt[key](options, ...args) + } + return tt[key](options) + } + + if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { + let url = obj.url ? obj.url.replace(/^\//, '') : '' + if (url.indexOf('?') > -1) url = url.split('?')[0] + + const Component = cacheDataGet(url) + if (Component) { + const component = new Component() + if (component.componentWillPreload) { + const cacheKey = getUniqueKey() + const MarkIndex = obj.url.indexOf('?') + const hasMark = MarkIndex > -1 + const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' + const params = queryToJson(urlQueryStr) + obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` + cacheDataSet(cacheKey, component.componentWillPreload(params)) + cacheDataSet(preloadInitedComponent, component) + } + } + } + + const p: any = new Promise((resolve, reject) => { + ['fail', 'success', 'complete'].forEach((k) => { + obj[k] = (res) => { + options[k] && options[k](res) + if (k === 'success') { + if (key === 'connectSocket') { + resolve( + Promise.resolve().then(() => Object.assign(task, res)) + ) + } else { + resolve(res) + } + } else if (k === 'fail') { + reject(res) + } + } + }) + if (args.length) { + task = tt[key](obj, ...args) + } else { + task = tt[key](obj) + } + }) + if (key === 'uploadFile' || key === 'downloadFile') { + p.progress = cb => { + if (task) { + task.onProgressUpdate(cb) + } + return p + } + p.abort = cb => { + cb && cb() + if (task) { + task.abort() + } + return p + } + } + return p + } + } else { + taro[key] = (...args) => { + const argsLen = args.length + const newArgs = args.concat() + const lastArg = newArgs[argsLen - 1] + if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { + newArgs.splice(argsLen - 1, 1, lastArg.$scope) + } + return tt[key].apply(tt, newArgs) + } + } + }) +} + +function pxTransform (size) { + const { + designWidth = 750, + deviceRatio = { + 640: 2.34 / 2, + 750: 1, + 828: 1.81 / 2 + } + } = this.config || {} + if (!(designWidth in deviceRatio)) { + throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) + } + return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' +} + +export function initNativeApi (taro) { + processApis(taro) + const link = new taro.Link(taroInterceptor) + taro.request = link.request.bind(link) + taro.addInterceptor = link.addInterceptor.bind(link) + taro.cleanInterceptors = link.cleanInterceptors.bind(link) + taro.getCurrentPages = getCurrentPages + taro.getApp = getApp + taro.initPxTransform = taro.initPxTransform.bind(taro) + taro.pxTransform = pxTransform.bind(taro) +} diff --git a/packages/taro-tt/src/program.ts b/packages/taro-tt/src/program.ts index 490724ace8b1..1afef3d3dd3a 100644 --- a/packages/taro-tt/src/program.ts +++ b/packages/taro-tt/src/program.ts @@ -2,10 +2,13 @@ import { TaroPlatformBase } from '@tarojs/shared' import { Template } from './template' import { components } from './components' +const PACKAGE_NAME = '@tarojs/plugin-platform-tt' + export default class TT extends TaroPlatformBase { platform = 'tt' globalObject = 'tt' projectConfigJson = 'project.tt.json' + runtimePath = `${PACKAGE_NAME}/dist/runtime` fileType = { templ: '.ttml', style: '.ttss', @@ -24,7 +27,9 @@ export default class TT extends TaroPlatformBase { this.modifyComponents() const runner = await this.getRunner() - const options = this.getBaseOptions() + const options = this.getOptions({ + hostConfig: this.runtimePath + }) runner(options) } diff --git a/packages/taro-tt/src/runtime.ts b/packages/taro-tt/src/runtime.ts index 93cb5c7be947..64a88eb4816b 100644 --- a/packages/taro-tt/src/runtime.ts +++ b/packages/taro-tt/src/runtime.ts @@ -1,5 +1,5 @@ +import { initNativeApi } from './apis' + export const hostConfig = { - log: function () { - console.log('ok') - } + initNativeApi } diff --git a/packages/taro-tt/types/apis-list.d.ts b/packages/taro-tt/types/apis-list.d.ts new file mode 100644 index 000000000000..fc8256c14382 --- /dev/null +++ b/packages/taro-tt/types/apis-list.d.ts @@ -0,0 +1,2 @@ +export declare const _noPromiseApis: Set; +export declare const _otherApis: Set; diff --git a/packages/taro-tt/types/apis.d.ts b/packages/taro-tt/types/apis.d.ts new file mode 100644 index 000000000000..5738d9110523 --- /dev/null +++ b/packages/taro-tt/types/apis.d.ts @@ -0,0 +1 @@ +export declare function initNativeApi(taro: any): void; diff --git a/packages/taro-tt/types/program.d.ts b/packages/taro-tt/types/program.d.ts index 2e9e5115e768..252b8cc82ff8 100644 --- a/packages/taro-tt/types/program.d.ts +++ b/packages/taro-tt/types/program.d.ts @@ -4,6 +4,7 @@ export default class TT extends TaroPlatformBase { platform: string; globalObject: string; projectConfigJson: string; + runtimePath: string; fileType: { templ: string; style: string; diff --git a/packages/taro-tt/types/runtime.d.ts b/packages/taro-tt/types/runtime.d.ts index 5448c1d735d7..c5f1dbe0717a 100644 --- a/packages/taro-tt/types/runtime.d.ts +++ b/packages/taro-tt/types/runtime.d.ts @@ -1,3 +1,4 @@ +import { initNativeApi } from './apis'; export declare const hostConfig: { - log: () => void; + initNativeApi: typeof initNativeApi; }; diff --git a/packages/taro-weapp/src/apis-list.ts b/packages/taro-weapp/src/apis-list.ts new file mode 100644 index 000000000000..a9adfcb43948 --- /dev/null +++ b/packages/taro-weapp/src/apis-list.ts @@ -0,0 +1,127 @@ +export const _onAndSyncApis = new Set([ + 'getAccountInfoSync', + 'getEnterOptionsSync', + 'offBLEPeripheralConnectionStateChanged', + 'offBeaconServiceChange', + 'offBeaconUpdate', + 'offDeviceMotionChange', + 'offHCEMessage', + 'offKeyboardHeightChange', + 'offLocalServiceDiscoveryStop', + 'offLocalServiceFound', + 'offLocalServiceLost', + 'offLocalServiceResolveFail', + 'offLocationChange', + 'offThemeChange', + 'offVoIPChatInterrupted', + 'offVoIPChatMembersChanged', + 'offVoIPVideoMembersChanged', + 'offWifiConnected', + 'offWindowResize', + 'onBLEPeripheralConnectionStateChanged', + 'onBackgroundAudioPause', + 'onBackgroundAudioPlay', + 'onBackgroundAudioStop', + 'onBackgroundFetchData', + 'onHCEMessage', + 'onKeyboardHeightChange', + 'onLocalServiceDiscoveryStop', + 'onLocalServiceFound', + 'onLocalServiceLost', + 'onLocalServiceResolveFail', + 'onLocationChange', + 'onThemeChange', + 'onVoIPChatInterrupted', + 'onVoIPChatMembersChanged', + 'onVoIPChatSpeakersChanged', + 'onVoIPVideoMembersChanged', + 'onWifiConnected', + 'onWindowResize', + 'reportMonitor' +]) + +export const _noPromiseApis = new Set([ + 'createAudioContext', + 'createLivePusherContext', + 'createMediaContainer', + 'createMediaRecorder', + 'createOffscreenCanvas', + 'createRewardedVideoAd', + 'createUDPSocket', + 'createVideoDecoder', + 'createWorker', + 'getLogManager', + 'getNFCAdapter', + 'getPerformance', + 'getRealtimeLogManager', + 'pauseBackgroundAudio', + 'pauseVoice', + 'reportPerformance', + 'stopBackgroundAudio', + 'stopRecord', + 'stopVoice' +]) + +export const _otherApis = new Set([ + 'addCard', + 'authPrivateMessage', + 'checkIsOpenAccessibility', + 'checkIsSoterEnrolledInDevice', + 'checkIsSupportSoterAuthentication', + 'chooseInvoice', + 'chooseMedia', + 'chooseMessageFile', + 'compressVideo', + 'connectWifi', + 'createBLEPeripheralServer', + 'disableAlertBeforeUnload', + 'enableAlertBeforeUnload', + 'exitVoIPChat', + 'getBLEDeviceRSSI', + 'getBackgroundAudioPlayerState', + 'getBackgroundFetchData', + 'getBackgroundFetchToken', + 'getGroupEnterInfo', + 'getHCEState', + 'getSelectedTextRange', + 'getShareInfo', + 'getVideoInfo', + 'getWeRunData', + 'join1v1Chat', + 'joinVoIPChat', + 'makeBluetoothPair', + 'openCard', + 'openVideoEditor', + 'playBackgroundAudio', + 'playVoice', + 'previewMedia', + 'requestPayment', + 'saveFileToDisk', + 'scanItem', + 'seekBackgroundAudio', + 'sendHCEMessage', + 'setBLEMTU', + 'setBackgroundFetchToken', + 'setEnable1v1Chat', + 'setTopBarText', + 'setWifiList', + 'setWindowSize', + 'showRedPackage', + 'startGyroscope', + 'startHCE', + 'startLocalServiceDiscovery', + 'startLocationUpdate', + 'startLocationUpdateBackground', + 'startRecord', + 'startSoterAuthentication', + 'startWifi', + 'stopGyroscope', + 'stopHCE', + 'stopLocalServiceDiscovery', + 'stopLocationUpdate', + 'stopWifi', + 'subscribeVoIPVideoMembers', + 'updateShareMenu', + 'updateVoIPChatMuteConfig', + 'updateWeChatApp' +]) diff --git a/packages/taro-weapp/src/apis.ts b/packages/taro-weapp/src/apis.ts new file mode 100644 index 000000000000..932e6ed6321e --- /dev/null +++ b/packages/taro-weapp/src/apis.ts @@ -0,0 +1,265 @@ +import { + queryToJson, + getUniqueKey, + cacheDataSet, + cacheDataGet +} from '@tarojs/shared' +import { _onAndSyncApis, _noPromiseApis, _otherApis } from './apis-list' + +declare const wx: any +declare const getCurrentPages: () => any +declare const getApp: () => any +declare const requirePlugin: () => void + +interface ITaro { + onAndSyncApis: Set + noPromiseApis: Set + otherApis: Set + [propName: string]: any +} + +const RequestQueue = { + MAX_REQUEST: 5, + queue: [], + request (options) { + this.push(options) + // 返回request task + return this.run() + }, + + push (options) { + this.queue.push(options) + }, + + run () { + if (!this.queue.length) { + return + } + if (this.queue.length <= this.MAX_REQUEST) { + const options = this.queue.shift() + const completeFn = options.complete + options.complete = (...args) => { + completeFn && completeFn.apply(options, args) + this.run() + } + return wx.request(options) + } + } +} + +function taroInterceptor (chain) { + return request(chain.requestParams) +} + +function request (options) { + options = options || {} + if (typeof options === 'string') { + options = { + url: options + } + } + const originSuccess = options.success + const originFail = options.fail + const originComplete = options.complete + let requestTask + const p = new Promise((resolve, reject) => { + options.success = res => { + originSuccess && originSuccess(res) + resolve(res) + } + options.fail = res => { + originFail && originFail(res) + reject(res) + } + + options.complete = res => { + originComplete && originComplete(res) + } + + requestTask = RequestQueue.request(options) + }) + ;(p as any).abort = (cb) => { + cb && cb() + if (requestTask) { + requestTask.abort() + } + return p + } + return p +} + +function processApis (taro: ITaro) { + const onAndSyncApis = new Set([...taro.onAndSyncApis, ..._onAndSyncApis]) + const noPromiseApis = new Set([...taro.noPromiseApis, ..._noPromiseApis]) + const otherApis = new Set([...taro.otherApis, ..._otherApis]) + const apis = [...onAndSyncApis, ...noPromiseApis, ...otherApis] + const useDataCacheApis = { + navigateTo: true, + redirectTo: true, + reLaunch: true + } + const routerParamsPrivateKey = '__key_' + const preloadPrivateKey = '__preload_' + const preloadInitedComponent = '$preloadComponent' + apis.forEach(key => { + if (!(key in wx)) { + taro[key] = () => { + console.warn(`微信小程序暂不支持 ${key}`) + } + return + } + + if (otherApis.has(key)) { + taro[key] = (options, ...args) => { + options = options || {} + let task: any = null + const obj = Object.assign({}, options) + if (typeof options === 'string') { + if (args.length) { + return wx[key](options, ...args) + } + return wx[key](options) + } + + if (key === 'navigateTo' || key === 'redirectTo' || key === 'switchTab') { + let url = obj.url ? obj.url.replace(/^\//, '') : '' + if (url.indexOf('?') > -1) url = url.split('?')[0] + + const Component = cacheDataGet(url) + if (Component) { + const component = new Component() + if (component.componentWillPreload) { + const cacheKey = getUniqueKey() + const MarkIndex = obj.url.indexOf('?') + const hasMark = MarkIndex > -1 + const urlQueryStr = hasMark ? obj.url.substring(MarkIndex + 1, obj.url.length) : '' + const params = queryToJson(urlQueryStr) + obj.url += (hasMark ? '&' : '?') + `${preloadPrivateKey}=${cacheKey}` + cacheDataSet(cacheKey, component.componentWillPreload(params)) + cacheDataSet(preloadInitedComponent, component) + } + } + } + + if (useDataCacheApis[key]) { + const url = obj.url = obj.url || '' + const MarkIndex = url.indexOf('?') + const hasMark = MarkIndex > -1 + const urlQueryStr = hasMark ? url.substring(MarkIndex + 1, url.length) : '' + const params = queryToJson(urlQueryStr) + const cacheKey = getUniqueKey() + obj.url += (hasMark ? '&' : '?') + `${routerParamsPrivateKey}=${cacheKey}` + cacheDataSet(cacheKey, params) + } + + const p: any = new Promise((resolve, reject) => { + ['fail', 'success', 'complete'].forEach((k) => { + obj[k] = (res) => { + options[k] && options[k](res) + if (k === 'success') { + if (key === 'connectSocket') { + resolve( + Promise.resolve().then(() => Object.assign(task, res)) + ) + } else { + resolve(res) + } + } else if (k === 'fail') { + reject(res) + } + } + }) + if (args.length) { + task = wx[key](obj, ...args) + } else { + task = wx[key](obj) + } + }) + if (key === 'uploadFile' || key === 'downloadFile') { + p.progress = cb => { + if (task) { + task.onProgressUpdate(cb) + } + return p + } + p.abort = cb => { + cb && cb() + if (task) { + task.abort() + } + return p + } + } + return p + } + } else { + taro[key] = (...args) => { + const argsLen = args.length + const newArgs = args.concat() + const lastArg = newArgs[argsLen - 1] + if (lastArg && lastArg.isTaroComponent && lastArg.$scope) { + newArgs.splice(argsLen - 1, 1, lastArg.$scope) + } + return wx[key].apply(wx, newArgs) + } + } + }) +} + +function pxTransform (size) { + const { + designWidth = 750, + deviceRatio = { + 640: 2.34 / 2, + 750: 1, + 828: 1.81 / 2 + } + } = this.config || {} + if (!(designWidth in deviceRatio)) { + throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`) + } + return parseInt(size, 10) / deviceRatio[designWidth] + 'rpx' +} + +function canIUseWebp () { + const { platform } = wx.getSystemInfoSync() + const platformLower = platform.toLowerCase() + if (platformLower === 'android' || platformLower === 'devtools') { + return true + } + return false +} + +function wxCloud (taro) { + const wxC = wx.cloud || {} + const wxcloud = {} + const apiList = [ + 'init', + 'database', + 'uploadFile', + 'downloadFile', + 'getTempFileURL', + 'deleteFile', + 'callFunction', + 'CloudID' + ] + apiList.forEach(v => { + wxcloud[v] = wxC[v] + }) + taro.cloud = wxcloud +} + +export function initNativeApi (taro) { + processApis(taro) + const link = new taro.Link(taroInterceptor) + taro.request = link.request.bind(link) + taro.addInterceptor = link.addInterceptor.bind(link) + taro.cleanInterceptors = link.cleanInterceptors.bind(link) + taro.getCurrentPages = getCurrentPages + taro.getApp = getApp + taro.requirePlugin = requirePlugin + taro.initPxTransform = taro.initPxTransform.bind(taro) + taro.pxTransform = pxTransform.bind(taro) + taro.canIUseWebp = canIUseWebp + wxCloud(taro) +} diff --git a/packages/taro-weapp/src/program.ts b/packages/taro-weapp/src/program.ts index 7b75c9f41d63..d8ae9f88239f 100644 --- a/packages/taro-weapp/src/program.ts +++ b/packages/taro-weapp/src/program.ts @@ -2,10 +2,14 @@ import { TaroPlatformBase } from '@tarojs/shared' import { Template } from './template' import { components } from './components' +const PACKAGE_NAME = '@tarojs/plugin-platform-weapp' + export default class Weapp extends TaroPlatformBase { platform = 'weapp' globalObject = 'wx' projectConfigJson = 'project.config.json' + runtimePath = `${PACKAGE_NAME}/dist/runtime` + reactComponents = `${PACKAGE_NAME}/dist/components-react` fileType = { templ: '.wxml', style: '.wxss', @@ -26,7 +30,9 @@ export default class Weapp extends TaroPlatformBase { this.modifyWebpackChain() const runner = await this.getRunner() - const options = this.getBaseOptions() + const options = this.getOptions({ + hostConfig: this.runtimePath + }) runner(options) } @@ -48,7 +54,7 @@ export default class Weapp extends TaroPlatformBase { modifyWebpackChain () { this.ctx.modifyWebpackChain(({ chain }) => { const { taroJsComponents } = this.helper - chain.resolve.alias.set(taroJsComponents + '$', '@tarojs/plugin-platform-weapp/dist/components-react.js') + chain.resolve.alias.set(taroJsComponents + '$', this.reactComponents) }) } } diff --git a/packages/taro-weapp/src/runtime.ts b/packages/taro-weapp/src/runtime.ts index ea1e3f3fb7ff..64a88eb4816b 100644 --- a/packages/taro-weapp/src/runtime.ts +++ b/packages/taro-weapp/src/runtime.ts @@ -1,3 +1,5 @@ -export const hostConfig = { +import { initNativeApi } from './apis' +export const hostConfig = { + initNativeApi } diff --git a/packages/taro-weapp/types/apis-list.d.ts b/packages/taro-weapp/types/apis-list.d.ts new file mode 100644 index 000000000000..f77285489736 --- /dev/null +++ b/packages/taro-weapp/types/apis-list.d.ts @@ -0,0 +1,3 @@ +export declare const _onAndSyncApis: Set; +export declare const _noPromiseApis: Set; +export declare const _otherApis: Set; diff --git a/packages/taro-weapp/types/apis.d.ts b/packages/taro-weapp/types/apis.d.ts new file mode 100644 index 000000000000..5738d9110523 --- /dev/null +++ b/packages/taro-weapp/types/apis.d.ts @@ -0,0 +1 @@ +export declare function initNativeApi(taro: any): void; diff --git a/packages/taro-weapp/types/program.d.ts b/packages/taro-weapp/types/program.d.ts index 28e9aaef8e9b..80fb18cdfd8d 100644 --- a/packages/taro-weapp/types/program.d.ts +++ b/packages/taro-weapp/types/program.d.ts @@ -4,6 +4,8 @@ export default class Weapp extends TaroPlatformBase { platform: string; globalObject: string; projectConfigJson: string; + runtimePath: string; + reactComponents: string; fileType: { templ: string; style: string; diff --git a/packages/taro-weapp/types/runtime.d.ts b/packages/taro-weapp/types/runtime.d.ts index 0d3892e71438..c5f1dbe0717a 100644 --- a/packages/taro-weapp/types/runtime.d.ts +++ b/packages/taro-weapp/types/runtime.d.ts @@ -1 +1,4 @@ -export declare const hostConfig: {}; +import { initNativeApi } from './apis'; +export declare const hostConfig: { + initNativeApi: typeof initNativeApi; +}; diff --git a/packages/taro/README.md b/packages/taro/README.md index 49151c87b026..a620ddabe1a1 100644 --- a/packages/taro/README.md +++ b/packages/taro/README.md @@ -2,7 +2,7 @@ 暴露给 @tarojs/taro 的所有端的公有 API。`@tarojs/api` 会跨 node/浏览器/小程序/React Native 使用,不得使用/包含平台特有特性。 -## dist/index.esm.js +## index.js 小程序端入口文件 @@ -10,6 +10,10 @@ H5 端入口文件 +## dist/h5.js + +H5 端入口文件(当不使用 babel-plugin-transform-taroapi 时) + ## html.css W3C HTML4 的内置样式,用于 [渲染 HTML](https://taro-docs.jd.com/taro/next/docs/html.html)。 diff --git a/packages/taro/index.js b/packages/taro/index.js index 860df4920178..ecca75baa522 100644 --- a/packages/taro/index.js +++ b/packages/taro/index.js @@ -1,2 +1,9 @@ -module.exports = require('./dist/index.esm').default +const reconciler = require('@tarojs/runtime').CurrentReconciler +const taro = require('./dist/index.esm').default + +if (typeof reconciler.initNativeApi === 'function') { + reconciler.initNativeApi(taro) +} + +module.exports = taro module.exports.default = module.exports diff --git a/packages/taro/package.json b/packages/taro/package.json index 6ea09fe64535..cb4a56b01d82 100644 --- a/packages/taro/package.json +++ b/packages/taro/package.json @@ -10,7 +10,6 @@ "dist", "index.js", "types", - "h5.js", "html.css", "html5.css" ], diff --git a/packages/taro/src/native-apis.js b/packages/taro/src/native-apis.js index 14563b46b807..8cfdeb0579f4 100644 --- a/packages/taro/src/native-apis.js +++ b/packages/taro/src/native-apis.js @@ -1,319 +1,200 @@ -const onAndSyncApis = { - onSocketOpen: true, - onSocketError: true, - onSocketMessage: true, - onSocketClose: true, - onBackgroundAudioPlay: true, - onBackgroundAudioPause: true, - onBackgroundAudioStop: true, - onNetworkStatusChange: true, - onAccelerometerChange: true, - onCompassChange: true, - onBluetoothAdapterStateChange: true, - onBluetoothDeviceFound: true, - onBLEConnectionStateChange: true, - onBLECharacteristicValueChange: true, - onBeaconUpdate: true, - onBeaconServiceChange: true, - onUserCaptureScreen: true, - onHCEMessage: true, - onGetWifiList: true, - onWifiConnected: true, - onDeviceMotionChange: true, - setStorageSync: true, - getStorageSync: true, - getStorageInfoSync: true, - removeStorageSync: true, - clearStorageSync: true, - getSystemInfoSync: true, - getExtConfigSync: true, - getLogManager: true, - onMemoryWarning: true, - reportMonitor: true, - reportAnalytics: true, - navigateToSmartGameProgram: true, - // 文件 - getFileSystemManager: true, - - getLaunchOptionsSync: true, - onPageNotFound: true, - onError: true, - onAppShow: true, - onAppHide: true, - offPageNotFound: true, - offError: true, - offAppShow: true, - offAppHide: true, - onAudioInterruptionEnd: true, - onAudioInterruptionBegin: true, - onLocationChange: true, - offLocationChange: true, - - // 基础 - onUnhandledRejection: true, - offUnhandledRejection: true, - onThemeChange: true, - offThemeChange: true, - - // 界面 - onKeyboardHeightChange: true, - offKeyboardHeightChange: true -} -const noPromiseApis = { - // 媒体 - stopRecord: true, - getRecorderManager: true, - pauseVoice: true, - stopVoice: true, - pauseBackgroundAudio: true, - stopBackgroundAudio: true, - getBackgroundAudioManager: true, - createAudioContext: true, - createInnerAudioContext: true, - createVideoContext: true, - createCameraContext: true, - createLivePlayerContext: true, - createLivePusherContext: true, - - // 位置 - createMapContext: true, - - // 设备 - canIUse: true, - startAccelerometer: true, - stopAccelerometer: true, - startCompass: true, - stopCompass: true, - - // 界面 - hideToast: true, - hideLoading: true, - showNavigationBarLoading: true, - hideNavigationBarLoading: true, - createAnimation: true, - createSelectorQuery: true, - createOffscreenCanvas: true, - createCanvasContext: true, - // createContext: true, - drawCanvas: true, - hideKeyboard: true, - stopPullDownRefresh: true, - createIntersectionObserver: true, - - // 菜单 - getMenuButtonBoundingClientRect: true, - - onWindowResize: true, - offWindowResize: true, - - // 调试 - setEnableDebug: true, - getRealtimeLogManager: true, - getLogManager: true, - - // 拓展接口 - arrayBufferToBase64: true, - base64ToArrayBuffer: true, - - getAccountInfoSync: true, - getUpdateManager: true, - createWorker: true, - - // 广告 - createRewardedVideoAd: true, - createInterstitialAd: true -} -const otherApis = { - // 网络 - uploadFile: true, - downloadFile: true, - connectSocket: true, - sendSocketMessage: true, - closeSocket: true, - - // 媒体 - chooseImage: true, - chooseMessageFile: true, - previewImage: true, - getImageInfo: true, - compressImage: true, - saveImageToPhotosAlbum: true, - startRecord: true, - playVoice: true, - setInnerAudioOption: true, - getAvailableAudioSources: true, - getBackgroundAudioPlayerState: true, - playBackgroundAudio: true, - seekBackgroundAudio: true, - chooseVideo: true, - saveVideoToPhotosAlbum: true, - loadFontFace: true, - - // 文件 - saveFile: true, - getFileInfo: true, - getSavedFileList: true, - getSavedFileInfo: true, - removeSavedFile: true, - openDocument: true, - - // 数据缓存 - setStorage: true, - getStorage: true, - getStorageInfo: true, - removeStorage: true, - clearStorage: true, - - // 导航 - navigateBack: true, - navigateTo: true, - redirectTo: true, - switchTab: true, - reLaunch: true, - - // 位置 - startLocationUpdate: true, - startLocationUpdateBackground: true, - stopLocationUpdate: true, - getLocation: true, - chooseLocation: true, - openLocation: true, - - // 设备 - getSystemInfo: true, - getNetworkType: true, - makePhoneCall: true, - scanCode: true, - setClipboardData: true, - getClipboardData: true, - openBluetoothAdapter: true, - closeBluetoothAdapter: true, - getBluetoothAdapterState: true, - startBluetoothDevicesDiscovery: true, - stopBluetoothDevicesDiscovery: true, - getBluetoothDevices: true, - getConnectedBluetoothDevices: true, - createBLEConnection: true, - closeBLEConnection: true, - getBLEDeviceServices: true, - getBLEDeviceCharacteristics: true, - readBLECharacteristicValue: true, - writeBLECharacteristicValue: true, - notifyBLECharacteristicValueChange: true, - startBeaconDiscovery: true, - stopBeaconDiscovery: true, - getBeacons: true, - setScreenBrightness: true, - getScreenBrightness: true, - setKeepScreenOn: true, - vibrateLong: true, - vibrateShort: true, - addPhoneContact: true, - getHCEState: true, - startHCE: true, - stopHCE: true, - sendHCEMessage: true, - startWifi: true, - stopWifi: true, - connectWifi: true, - getWifiList: true, - setWifiList: true, - getConnectedWifi: true, - startDeviceMotionListening: true, - stopDeviceMotionListening: true, - - // 界面 - pageScrollTo: true, - showToast: true, - showLoading: true, - showModal: true, - showActionSheet: true, - setNavigationBarTitle: true, - setNavigationBarColor: true, - setTabBarBadge: true, - removeTabBarBadge: true, - showTabBarRedDot: true, - hideTabBarRedDot: true, - setTabBarStyle: true, - setTabBarItem: true, - showTabBar: true, - hideTabBar: true, - setTopBarText: true, - startPullDownRefresh: true, - canvasToTempFilePath: true, - canvasGetImageData: true, - canvasPutImageData: true, - - setBackgroundColor: true, - setBackgroundTextStyle: true, - getSelectedTextRange: true, - hideHomeButton: true, - - // 第三方平台 - getExtConfig: true, - - // 开放接口 - login: true, - checkSession: true, - authorize: true, - getUserInfo: true, - checkIsSupportFacialRecognition: true, - startFacialRecognitionVerify: true, - startFacialRecognitionVerifyAndUploadVideo: true, - faceVerifyForPay: true, - requestPayment: true, - showShareMenu: true, - hideShareMenu: true, - updateShareMenu: true, - getShareInfo: true, - chooseAddress: true, - addCard: true, - openCard: true, - openSetting: true, - getSetting: true, - getWeRunData: true, - navigateToMiniProgram: true, - navigateBackMiniProgram: true, - chooseInvoice: true, - chooseInvoiceTitle: true, - checkIsSupportSoterAuthentication: true, - startSoterAuthentication: true, - checkIsSoterEnrolledInDevice: true, - - // 订阅消息 - requestSubscribeMessage: true, - - setEnableDebug: true, - // 支付宝小程序API - getOpenUserInfo: true, - - // 百度小程序专有 API - // 百度小程序 AI 相关 - ocrIdCard: true, - ocrBankCard: true, - ocrDrivingLicense: true, - ocrVehicleLicense: true, - textReview: true, - textToAudio: true, - imageAudit: true, - advancedGeneralIdentify: true, - objectDetectIdentify: true, - carClassify: true, - dishClassify: true, - logoClassify: true, - animalClassify: true, - plantClassify: true, - setPageInfo: true, - - // 用户信息 - getSwanId: true, - // 百度收银台支付 - requestPolymerPayment: true, - // 打开小程序 - navigateToSmartProgram: true, - navigateBackSmartProgram: true, - preloadSubPackage: true -} +const onAndSyncApis = new Set([ + 'clearStorageSync', + 'getBatteryInfoSync', + 'getExtConfigSync', + 'getFileSystemManager', + 'getLaunchOptionsSync', + 'getStorageInfoSync', + 'getStorageSync', + 'getSystemInfoSync', + 'offAccelerometerChange', + 'offAppHide', + 'offAppShow', + 'offAudioInterruptionBegin', + 'offAudioInterruptionEnd', + 'offBLECharacteristicValueChange', + 'offBLEConnectionStateChange', + 'offBluetoothAdapterStateChange', + 'offBluetoothDeviceFound', + 'offCompassChange', + 'offError', + 'offGetWifiList', + 'offGyroscopeChange', + 'offMemoryWarning', + 'offNetworkStatusChange', + 'offPageNotFound', + 'offUnhandledRejection', + 'offUserCaptureScreen', + 'onAccelerometerChange', + 'onAppHide', + 'onAppShow', + 'onAudioInterruptionBegin', + 'onAudioInterruptionEnd', + 'onBLECharacteristicValueChange', + 'onBLEConnectionStateChange', + 'onBeaconServiceChange', + 'onBeaconUpdate', + 'onBluetoothAdapterStateChange', + 'onBluetoothDeviceFound', + 'onCompassChange', + 'onDeviceMotionChange', + 'onError', + 'onGetWifiList', + 'onGyroscopeChange', + 'onMemoryWarning', + 'onNetworkStatusChange', + 'onPageNotFound', + 'onSocketClose', + 'onSocketError', + 'onSocketMessage', + 'onSocketOpen', + 'onUnhandledRejection', + 'onUserCaptureScreen', + 'removeStorageSync', + 'reportAnalytics', + 'setStorageSync' +]) + +const noPromiseApis = new Set([ + 'arrayBufferToBase64', + 'base64ToArrayBuffer', + 'canIUse', + 'createAnimation', + 'createCameraContext', + 'createCanvasContext', + 'createInnerAudioContext', + 'createIntersectionObserver', + 'createInterstitialAd', + 'createLivePlayerContext', + 'createMapContext', + 'createSelectorQuery', + 'createVideoContext', + 'getBackgroundAudioManager', + 'getMenuButtonBoundingClientRect', + 'getRecorderManager', + 'getUpdateManager' +]) + +const otherApis = new Set([ + 'addPhoneContact', + 'authorize', + 'canvasGetImageData', + 'canvasPutImageData', + 'canvasToTempFilePath', + 'checkSession', + 'chooseAddress', + 'chooseImage', + 'chooseInvoiceTitle', + 'chooseLocation', + 'chooseVideo', + 'clearStorage', + 'closeBLEConnection', + 'closeBluetoothAdapter', + 'closeSocket', + 'compressImage', + 'connectSocket', + 'createBLEConnection', + 'downloadFile', + 'getAvailableAudioSources', + 'getBLEDeviceCharacteristics', + 'getBLEDeviceServices', + 'getBatteryInfo', + 'getBeacons', + 'getBluetoothAdapterState', + 'getBluetoothDevices', + 'getClipboardData', + 'getConnectedBluetoothDevices', + 'getConnectedWifi', + 'getExtConfig', + 'getFileInfo', + 'getImageInfo', + 'getLocation', + 'getNetworkType', + 'getSavedFileInfo', + 'getSavedFileList', + 'getScreenBrightness', + 'getSetting', + 'getStorage', + 'getStorageInfo', + 'getSystemInfo', + 'getUserInfo', + 'getWifiList', + 'hideHomeButton', + 'hideShareMenu', + 'hideTabBar', + 'hideTabBarRedDot', + 'loadFontFace', + 'login', + 'makePhoneCall', + 'navigateBack', + 'navigateBackMiniProgram', + 'navigateTo', + 'navigateToBookshelf', + 'navigateToMiniProgram', + 'notifyBLECharacteristicValueChange', + 'hideKeyboard', + 'hideLoading', + 'hideNavigationBarLoading', + 'hideToast', + 'openBluetoothAdapter', + 'openDocument', + 'openLocation', + 'openSetting', + 'pageScrollTo', + 'previewImage', + 'queryBookshelf', + 'reLaunch', + 'readBLECharacteristicValue', + 'redirectTo', + 'removeSavedFile', + 'removeStorage', + 'removeTabBarBadge', + 'requestSubscribeMessage', + 'saveFile', + 'saveImageToPhotosAlbum', + 'saveVideoToPhotosAlbum', + 'scanCode', + 'sendSocketMessage', + 'setBackgroundColor', + 'setBackgroundTextStyle', + 'setClipboardData', + 'setEnableDebug', + 'setInnerAudioOption', + 'setKeepScreenOn', + 'setNavigationBarColor', + 'setNavigationBarTitle', + 'setScreenBrightness', + 'setStorage', + 'setTabBarBadge', + 'setTabBarItem', + 'setTabBarStyle', + 'showActionSheet', + 'showFavoriteGuide', + 'showLoading', + 'showModal', + 'showShareMenu', + 'showTabBar', + 'showTabBarRedDot', + 'showToast', + 'startBeaconDiscovery', + 'startBluetoothDevicesDiscovery', + 'startDeviceMotionListening', + 'startPullDownRefresh', + 'stopBeaconDiscovery', + 'stopBluetoothDevicesDiscovery', + 'stopCompass', + 'startCompass', + 'startAccelerometer', + 'stopAccelerometer', + 'showNavigationBarLoading', + 'stopDeviceMotionListening', + 'stopPullDownRefresh', + 'switchTab', + 'uploadFile', + 'vibrateLong', + 'vibrateShort', + 'writeBLECharacteristicValue' +]) function initPxTransform (config) { const { From 5b2a0a17867c4292c5a5deada2d47a5492f67a27 Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 22 Sep 2020 10:25:37 +0800 Subject: [PATCH 015/272] =?UTF-8?q?chore(runtime):=20=E5=88=86=E7=A6=BB=20?= =?UTF-8?q?runtime=20=E8=80=A6=E5=90=88=E9=80=BB=E8=BE=91=E5=88=B0?= =?UTF-8?q?=E4=B8=AA=E5=B0=8F=E7=A8=8B=E5=BA=8F=E6=8F=92=E4=BB=B6=E5=8C=85?= =?UTF-8?q?=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/shared/src/components.ts | 2 +- packages/shared/src/utils.ts | 18 ++++++++++++++++++ packages/taro-alipay/src/program.ts | 2 +- packages/taro-alipay/src/runtime.ts | 17 +++++++++++++++-- packages/taro-alipay/types/runtime.d.ts | 5 +---- packages/taro-jd/src/program.ts | 2 +- packages/taro-jd/src/runtime.ts | 3 +++ packages/taro-loader/src/app.ts | 18 +++--------------- .../src/plugins/MiniPlugin.ts | 4 ++-- packages/taro-mini-runner/src/utils/types.ts | 2 +- .../src/webpack/build.conf.ts | 4 ++-- packages/taro-qq/src/runtime.ts | 5 +++++ packages/taro-runtime/rollup.config.js | 11 +---------- packages/taro-runtime/src/dom/element.ts | 5 +---- packages/taro-runtime/src/dom/node.ts | 5 ++--- packages/taro-runtime/src/dsl/react.ts | 2 +- packages/taro-runtime/src/dsl/vue.ts | 2 +- packages/taro-runtime/src/dsl/vue3.ts | 2 +- packages/taro-runtime/src/emitter/emitter.ts | 15 ++++----------- packages/taro-runtime/src/options.ts | 4 ++-- packages/taro-runtime/src/reconciler.ts | 19 +++++++++++++++++-- packages/taro-swan/src/program.ts | 2 +- packages/taro-swan/src/runtime.ts | 12 ++++++++++-- packages/taro-swan/types/runtime.d.ts | 5 +---- packages/taro-tt/src/program.ts | 2 +- packages/taro-tt/src/runtime.ts | 5 +++++ packages/taro-weapp/src/program.ts | 2 +- packages/taro-weapp/src/runtime.ts | 15 +++++++++++++-- packages/taro-weapp/types/runtime.d.ts | 5 +---- 29 files changed, 116 insertions(+), 79 deletions(-) diff --git a/packages/shared/src/components.ts b/packages/shared/src/components.ts index b766a2753796..dc2306597916 100644 --- a/packages/shared/src/components.ts +++ b/packages/shared/src/components.ts @@ -449,7 +449,7 @@ const Slot = { name: '' } -export const internalComponents = { +export const internalComponents: Record> = { View, Icon, Progress, diff --git a/packages/shared/src/utils.ts b/packages/shared/src/utils.ts index 64463ce247fc..4aa7f5edb694 100644 --- a/packages/shared/src/utils.ts +++ b/packages/shared/src/utils.ts @@ -1,9 +1,13 @@ +import { internalComponents } from './components' + export const EMPTY_OBJ: any = {} export const EMPTY_ARR = [] export const noop = (..._: unknown[]) => {} +export const defaultReconciler = {} + /** * Boxed value. * @@ -135,3 +139,17 @@ export function cacheDataGet (key, delelteAfterGet?) { export function cacheDataHas (key) { return key in cacheData } + +export function mergeInternalComponents (components) { + Object.keys(components).forEach(name => { + if (name in internalComponents) { + Object.assign(internalComponents[name], components[name]) + } else { + internalComponents[name] = components[name] + } + }) +} + +export function mergeReconciler (hostConfig) { + Object.assign(defaultReconciler, hostConfig) +} diff --git a/packages/taro-alipay/src/program.ts b/packages/taro-alipay/src/program.ts index eab4994fee7e..9083ab64c4d7 100644 --- a/packages/taro-alipay/src/program.ts +++ b/packages/taro-alipay/src/program.ts @@ -30,7 +30,7 @@ export default class Alipay extends TaroPlatformBase { const runner = await this.getRunner() const options = this.getOptions({ - hostConfig: this.runtimePath + runtimePath: this.runtimePath }) runner(options) } diff --git a/packages/taro-alipay/src/runtime.ts b/packages/taro-alipay/src/runtime.ts index 64a88eb4816b..83814a04cae2 100644 --- a/packages/taro-alipay/src/runtime.ts +++ b/packages/taro-alipay/src/runtime.ts @@ -1,5 +1,18 @@ +import { mergeReconciler, mergeInternalComponents } from '@tarojs/shared' import { initNativeApi } from './apis' +import { components } from './components' -export const hostConfig = { - initNativeApi +declare const my: any + +const hostConfig = { + initNativeApi, + getEventCenter (Events) { + if (!my.taroEventCenter) { + my.taroEventCenter = new Events() + } + return my.taroEventCenter + } } + +mergeReconciler(hostConfig) +mergeInternalComponents(components) diff --git a/packages/taro-alipay/types/runtime.d.ts b/packages/taro-alipay/types/runtime.d.ts index c5f1dbe0717a..cb0ff5c3b541 100644 --- a/packages/taro-alipay/types/runtime.d.ts +++ b/packages/taro-alipay/types/runtime.d.ts @@ -1,4 +1 @@ -import { initNativeApi } from './apis'; -export declare const hostConfig: { - initNativeApi: typeof initNativeApi; -}; +export {}; diff --git a/packages/taro-jd/src/program.ts b/packages/taro-jd/src/program.ts index 7f388de61698..892a541d65e2 100644 --- a/packages/taro-jd/src/program.ts +++ b/packages/taro-jd/src/program.ts @@ -26,7 +26,7 @@ export default class JD extends TaroPlatformBase { const runner = await this.getRunner() const options = this.getOptions({ - hostConfig: this.runtimePath + runtimePath: this.runtimePath }) runner(options) } diff --git a/packages/taro-jd/src/runtime.ts b/packages/taro-jd/src/runtime.ts index 64a88eb4816b..e10d0f049dc6 100644 --- a/packages/taro-jd/src/runtime.ts +++ b/packages/taro-jd/src/runtime.ts @@ -1,5 +1,8 @@ +import { mergeReconciler } from '@tarojs/shared' import { initNativeApi } from './apis' export const hostConfig = { initNativeApi } + +mergeReconciler(hostConfig) diff --git a/packages/taro-loader/src/app.ts b/packages/taro-loader/src/app.ts index 3d41071e900f..04bad24afcb3 100644 --- a/packages/taro-loader/src/app.ts +++ b/packages/taro-loader/src/app.ts @@ -13,27 +13,15 @@ if (typeof PRERENDER !== 'undefined') { global._prerender = inst }` - const setReconciler = mergeHostConfig(options) + const setReconciler = options.runtimePath ? `import '${options.runtimePath}'` : '' - return `import { ${creator}, window } from '@tarojs/runtime' + return `${setReconciler} +import { ${creator}, window } from '@tarojs/runtime' import component from ${stringify(this.request.split('!').slice(1).join('!'))} ${importFrameworkStatement} -${setReconciler} var config = ${config}; window.__taroAppConfig = config var inst = App(${creator}(component, ${frameworkArgs})) ${options.prerender ? prerender : ''} ` } - -function mergeHostConfig (options) { - if (options.hostConfig) { - return ` - import { CurrentReconciler } from '@tarojs/runtime' - import { hostConfig } from '${options.hostConfig}' - Object.assign(CurrentReconciler, hostConfig) -` - } else { - return '' - } -} diff --git a/packages/taro-mini-runner/src/plugins/MiniPlugin.ts b/packages/taro-mini-runner/src/plugins/MiniPlugin.ts index 3d5fb63caa8e..24e6dc0a5271 100644 --- a/packages/taro-mini-runner/src/plugins/MiniPlugin.ts +++ b/packages/taro-mini-runner/src/plugins/MiniPlugin.ts @@ -49,7 +49,7 @@ interface ITaroMiniPluginOptions { template: RecursiveTemplate | UnRecursiveTemplate modifyBuildAssets?: Function modifyMiniConfigs?: Function - hostConfig?: string + runtimePath?: string } export interface IComponentObj { @@ -223,7 +223,7 @@ export default class TaroMiniPlugin { framework, prerender: this.prerenderPages.size > 0, config: this.appConfig, - hostConfig: this.options.hostConfig + runtimePath: this.options.runtimePath } }) } diff --git a/packages/taro-mini-runner/src/utils/types.ts b/packages/taro-mini-runner/src/utils/types.ts index 276b465b00a4..6d38dc5045c8 100644 --- a/packages/taro-mini-runner/src/utils/types.ts +++ b/packages/taro-mini-runner/src/utils/types.ts @@ -59,7 +59,7 @@ export interface IBuildConfig extends IProjectBaseConfig, IMiniAppConfig { baseLevel: number, prerender?: PrerenderConfig template: RecursiveTemplate | UnRecursiveTemplate - hostConfig?: string + runtimePath?: string } export type AddPageChunks = ((pages: Map, pagesNames?: string[]) => void) diff --git a/packages/taro-mini-runner/src/webpack/build.conf.ts b/packages/taro-mini-runner/src/webpack/build.conf.ts index c2a8a8d04e38..1b33fc602edc 100644 --- a/packages/taro-mini-runner/src/webpack/build.conf.ts +++ b/packages/taro-mini-runner/src/webpack/build.conf.ts @@ -39,7 +39,7 @@ export default (appPath: string, mode, config: Partial): any => { outputRoot = 'dist', sourceRoot = 'src', isBuildPlugin = false, - hostConfig, + runtimePath, designWidth = 750, deviceRatio, @@ -153,7 +153,7 @@ export default (appPath: string, mode, config: Partial): any => { modifyMiniConfigs, modifyBuildAssets, minifyXML, - hostConfig + runtimePath }) plugin.miniCssExtractPlugin = getMiniCssExtractPlugin([{ diff --git a/packages/taro-qq/src/runtime.ts b/packages/taro-qq/src/runtime.ts index 64a88eb4816b..707e0eea86b7 100644 --- a/packages/taro-qq/src/runtime.ts +++ b/packages/taro-qq/src/runtime.ts @@ -1,5 +1,10 @@ +import { mergeReconciler, mergeInternalComponents } from '@tarojs/shared' import { initNativeApi } from './apis' +import { components } from './components' export const hostConfig = { initNativeApi } + +mergeReconciler(hostConfig) +mergeInternalComponents(components) diff --git a/packages/taro-runtime/rollup.config.js b/packages/taro-runtime/rollup.config.js index ae12f85edc6d..a270cc8a61a8 100644 --- a/packages/taro-runtime/rollup.config.js +++ b/packages/taro-runtime/rollup.config.js @@ -1,12 +1,11 @@ const { join } = require('path') const buble = require('rollup-plugin-buble') -const alias = require('rollup-plugin-alias') const typescript = require('rollup-plugin-typescript2') const cwd = __dirname const baseConfig = { input: join(cwd, 'src/index.ts'), - external: ['react', 'nervjs', 'react-dom', 'vue'], + external: ['react', 'nervjs', 'react-dom', 'vue', '@tarojs/shared'], output: [ { file: join(cwd, 'dist/index.js'), @@ -16,14 +15,6 @@ const baseConfig = { } ], plugins: [ - alias({ - entries: [ - { - find: '@tarojs/shared', - replacement: join(cwd, '../shared/dist/shared.esm') - } - ] - }), typescript(), buble({ transforms: { diff --git a/packages/taro-runtime/src/dom/element.ts b/packages/taro-runtime/src/dom/element.ts index 4a707e7dc0c7..82b5cd7d6060 100644 --- a/packages/taro-runtime/src/dom/element.ts +++ b/packages/taro-runtime/src/dom/element.ts @@ -28,10 +28,7 @@ export class TaroElement extends TaroNode { super(nodeType || NodeType.ELEMENT_NODE, nodeName) this.tagName = nodeName.toUpperCase() this.style = new Style(this) - warn( - this.tagName === 'MAP' && process.env.TARO_ENV === 'weapp', - '微信小程序 map 组件的 `setting` 属性需要传递一个默认值。详情:\n https://developers.weixin.qq.com/miniprogram/dev/component/map.html' - ) + CurrentReconciler.onTaroElementCreate?.(this.tagName, nodeType) } public get id () { diff --git a/packages/taro-runtime/src/dom/node.ts b/packages/taro-runtime/src/dom/node.ts index 38cc5e1be16b..624def9e554d 100644 --- a/packages/taro-runtime/src/dom/node.ts +++ b/packages/taro-runtime/src/dom/node.ts @@ -41,9 +41,8 @@ export class TaroNode extends TaroEventTarget { public get _path () { if (this.parentNode !== null) { - const index = process.env.TARO_ENV === 'swan' - ? this.parentNode.childNodes.indexOf(this) - : '[' + this.parentNode.childNodes.indexOf(this) + ']' + const indexOfNode = this.parentNode.childNodes.indexOf(this) + const index = CurrentReconciler.getPathIndex(indexOfNode) return `${this.parentNode._path}.${Shortcuts.Childnodes}.${index}` } diff --git a/packages/taro-runtime/src/dsl/react.ts b/packages/taro-runtime/src/dsl/react.ts index f09050991f78..720ea2ab43ad 100644 --- a/packages/taro-runtime/src/dsl/react.ts +++ b/packages/taro-runtime/src/dsl/react.ts @@ -89,7 +89,7 @@ let ReactDOM type PageComponent = React.CElement> function setReconciler () { - const hostConfig: Reconciler | React.ComponentClass> = { + const hostConfig: Partial | React.ComponentClass>> = { getLifecyle (instance, lifecycle) { if (lifecycle === 'onShow') { lifecycle = 'componentDidShow' diff --git a/packages/taro-runtime/src/dsl/vue.ts b/packages/taro-runtime/src/dsl/vue.ts index 35277a6b74b0..2000155e6ff6 100644 --- a/packages/taro-runtime/src/dsl/vue.ts +++ b/packages/taro-runtime/src/dsl/vue.ts @@ -50,7 +50,7 @@ export function connectVuePage (Vue: VueConstructor, id: string) { } function setReconciler () { - const hostConfig: Reconciler = { + const hostConfig: Partial> = { getLifecyle (instance, lifecycle) { return instance.$options[lifecycle] }, diff --git a/packages/taro-runtime/src/dsl/vue3.ts b/packages/taro-runtime/src/dsl/vue3.ts index cf416421aa27..7aaedf8e7091 100644 --- a/packages/taro-runtime/src/dsl/vue3.ts +++ b/packages/taro-runtime/src/dsl/vue3.ts @@ -49,7 +49,7 @@ function createVue3Page (h: typeof createElement, id: string) { } function setReconciler () { - const hostConfig: Reconciler = { + const hostConfig: Partial> = { getLifecyle (instance, lifecycle) { return instance.$options[lifecycle] }, diff --git a/packages/taro-runtime/src/emitter/emitter.ts b/packages/taro-runtime/src/emitter/emitter.ts index c7e19ad50562..20c2443ddcbe 100644 --- a/packages/taro-runtime/src/emitter/emitter.ts +++ b/packages/taro-runtime/src/emitter/emitter.ts @@ -1,3 +1,5 @@ +import { CurrentReconciler } from '../reconciler' + /* eslint-disable no-dupe-class-members */ type Callback1 = (arg1: T1) => any; type Callback2 = (arg1: T1, arg2: T2) => any; @@ -115,15 +117,6 @@ export class Events { } } -declare let my: any - -export let eventCenter: Events +export type EventsType = typeof Events -if (process.env.TARO_ENV === 'alipay') { - if (!my.taroEventCenter) { - my.taroEventCenter = new Events() - } - eventCenter = my.taroEventCenter -} else { - eventCenter = new Events() -} +export const eventCenter = CurrentReconciler.getEventCenter(Events) diff --git a/packages/taro-runtime/src/options.ts b/packages/taro-runtime/src/options.ts index b152196b5e7c..06355ea01683 100644 --- a/packages/taro-runtime/src/options.ts +++ b/packages/taro-runtime/src/options.ts @@ -14,7 +14,7 @@ export interface Options { transformElement?: (taroElement: TaroElement, element: Element) => TaroElement renderHTMLTag: boolean }, - reconciler: (reconciler: Reconciler) => void + reconciler: (reconciler: Partial>) => void } export const options: Options = { @@ -34,7 +34,7 @@ export const options: Options = { ]), renderHTMLTag: false }, - reconciler (reconciler: Reconciler) { + reconciler (reconciler) { Object.assign(CurrentReconciler, reconciler) } } diff --git a/packages/taro-runtime/src/reconciler.ts b/packages/taro-runtime/src/reconciler.ts index 072f497f9959..a48484828873 100644 --- a/packages/taro-runtime/src/reconciler.ts +++ b/packages/taro-runtime/src/reconciler.ts @@ -1,8 +1,11 @@ +import { defaultReconciler } from '@tarojs/shared' import type { TaroElement } from './dom/element' import type { TaroText } from './dom/text' import type { DataTree, TaroNode } from './dom/node' import type { TaroRootElement } from './dom/root' import type { Instance, PageInstance, PageProps } from './dsl/instance' +import type { NodeType } from './dom/node_types' +import type { EventsType } from './emitter/emitter' type Inst = Instance @@ -24,6 +27,12 @@ export interface Reconciler + onTaroElementCreate?(tagName: string, nodeType: NodeType): void + + getPathIndex(indexOfNode: number): void + + getEventCenter(Events: EventsType): InstanceType + // h5 createPullDownComponent?(el: Instance, path: string, framework) @@ -32,8 +41,14 @@ export interface Reconciler = { +export const CurrentReconciler: Reconciler = Object.assign({ getLifecyle (instance, lifecyle) { return instance[lifecyle] + }, + getPathIndex (indexOfNode) { + return `[${indexOfNode}]` + }, + getEventCenter (Events) { + return new Events() } -} +}, defaultReconciler) diff --git a/packages/taro-swan/src/program.ts b/packages/taro-swan/src/program.ts index c34de416a735..a9010e3f904f 100644 --- a/packages/taro-swan/src/program.ts +++ b/packages/taro-swan/src/program.ts @@ -32,7 +32,7 @@ export default class Swan extends TaroPlatformBase { const runner = await this.getRunner() const options = this.getOptions({ - hostConfig: this.runtimePath + runtimePath: this.runtimePath }) runner(options) } diff --git a/packages/taro-swan/src/runtime.ts b/packages/taro-swan/src/runtime.ts index 64a88eb4816b..895c05af015f 100644 --- a/packages/taro-swan/src/runtime.ts +++ b/packages/taro-swan/src/runtime.ts @@ -1,5 +1,13 @@ +import { mergeReconciler, mergeInternalComponents } from '@tarojs/shared' import { initNativeApi } from './apis' +import { components } from './components' -export const hostConfig = { - initNativeApi +const hostConfig = { + initNativeApi, + getPathIndex (indexOfNode) { + return indexOfNode + } } + +mergeReconciler(hostConfig) +mergeInternalComponents(components) diff --git a/packages/taro-swan/types/runtime.d.ts b/packages/taro-swan/types/runtime.d.ts index c5f1dbe0717a..cb0ff5c3b541 100644 --- a/packages/taro-swan/types/runtime.d.ts +++ b/packages/taro-swan/types/runtime.d.ts @@ -1,4 +1 @@ -import { initNativeApi } from './apis'; -export declare const hostConfig: { - initNativeApi: typeof initNativeApi; -}; +export {}; diff --git a/packages/taro-tt/src/program.ts b/packages/taro-tt/src/program.ts index 1afef3d3dd3a..9c1c5ff6bcbf 100644 --- a/packages/taro-tt/src/program.ts +++ b/packages/taro-tt/src/program.ts @@ -28,7 +28,7 @@ export default class TT extends TaroPlatformBase { const runner = await this.getRunner() const options = this.getOptions({ - hostConfig: this.runtimePath + runtimePath: this.runtimePath }) runner(options) } diff --git a/packages/taro-tt/src/runtime.ts b/packages/taro-tt/src/runtime.ts index 64a88eb4816b..707e0eea86b7 100644 --- a/packages/taro-tt/src/runtime.ts +++ b/packages/taro-tt/src/runtime.ts @@ -1,5 +1,10 @@ +import { mergeReconciler, mergeInternalComponents } from '@tarojs/shared' import { initNativeApi } from './apis' +import { components } from './components' export const hostConfig = { initNativeApi } + +mergeReconciler(hostConfig) +mergeInternalComponents(components) diff --git a/packages/taro-weapp/src/program.ts b/packages/taro-weapp/src/program.ts index d8ae9f88239f..0f2691be46dc 100644 --- a/packages/taro-weapp/src/program.ts +++ b/packages/taro-weapp/src/program.ts @@ -31,7 +31,7 @@ export default class Weapp extends TaroPlatformBase { const runner = await this.getRunner() const options = this.getOptions({ - hostConfig: this.runtimePath + runtimePath: this.runtimePath }) runner(options) } diff --git a/packages/taro-weapp/src/runtime.ts b/packages/taro-weapp/src/runtime.ts index 64a88eb4816b..75eefc008a32 100644 --- a/packages/taro-weapp/src/runtime.ts +++ b/packages/taro-weapp/src/runtime.ts @@ -1,5 +1,16 @@ +import { warn, mergeReconciler, mergeInternalComponents } from '@tarojs/shared' import { initNativeApi } from './apis' +import { components } from './components' -export const hostConfig = { - initNativeApi +const hostConfig = { + initNativeApi, + onTaroElementCreate (tagName: string) { + warn( + tagName === 'MAP', + '微信小程序 map 组件的 `setting` 属性需要传递一个默认值。详情:\n https://developers.weixin.qq.com/miniprogram/dev/component/map.html' + ) + } } + +mergeReconciler(hostConfig) +mergeInternalComponents(components) diff --git a/packages/taro-weapp/types/runtime.d.ts b/packages/taro-weapp/types/runtime.d.ts index c5f1dbe0717a..cb0ff5c3b541 100644 --- a/packages/taro-weapp/types/runtime.d.ts +++ b/packages/taro-weapp/types/runtime.d.ts @@ -1,4 +1 @@ -import { initNativeApi } from './apis'; -export declare const hostConfig: { - initNativeApi: typeof initNativeApi; -}; +export {}; From 1819da4a576245448938cce1c48c518751ba980a Mon Sep 17 00:00:00 2001 From: chenjiajian <798095202@qq.com> Date: Tue, 22 Sep 2020 16:09:42 +0800 Subject: [PATCH 016/272] =?UTF-8?q?feat(alipay):=20=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E5=AE=9D=E5=B0=8F=E7=A8=8B=E5=BA=8F=E6=94=AF=E6=8C=81=E5=BC=95?= =?UTF-8?q?=E7=94=A8=E8=87=AA=E5=AE=9A=E4=B9=89=E7=BB=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/shared/src/template.ts | 2 +- packages/taro-alipay/src/index.ts | 43 +++++++++++++++++++ .../taro-cli/src/presets/commands/build.ts | 5 ++- .../src/plugins/MiniPlugin.ts | 18 ++++---- packages/taro-service/types/index.d.ts | 2 +- 5 files changed, 58 insertions(+), 12 deletions(-) diff --git a/packages/shared/src/template.ts b/packages/shared/src/template.ts index 43b6ed3c87ca..3f53f631fd6d 100644 --- a/packages/shared/src/template.ts +++ b/packages/shared/src/template.ts @@ -331,7 +331,7 @@ export class BaseTemplate { public buildPageTemplate = (baseTempPath: string) => { const template = ` -