Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(utils): add utils package #268

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ showToast({
type: 'success',
duration: 1000,
success: () => {
console.log('toast')
}
console.log('toast');
},
});

// promise
Expand All @@ -60,9 +60,9 @@ showToast({

## 示例

|微信小程序|支付宝小程序|
|--------|----------|
|<img src="https://img.alicdn.com/imgextra/i1/O1CN01upA1bP1CxpGb8qLPp_!!6000000000148-0-tps-662-662.jpg" width="200" height="200" />|<img src="https://gw.alicdn.com/imgextra/i3/O1CN01Ca6t2Q2AEpIXh4r0u_!!6000000008172-0-tps-1540-1906.jpg" width="200" height="250" />|
| 微信小程序 | 支付宝小程序 |
| ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| <img src="https://img.alicdn.com/imgextra/i1/O1CN01upA1bP1CxpGb8qLPp_!!6000000000148-0-tps-662-662.jpg" width="200" height="200" /> | <img src="https://gw.alicdn.com/imgextra/i3/O1CN01Ca6t2Q2AEpIXh4r0u_!!6000000008172-0-tps-1540-1906.jpg" width="200" height="250" /> |

## 贡献代码

Expand All @@ -89,7 +89,7 @@ $ yarn demo:dev

### 更新版本

API package 版本统一维护在根目录下的api-config.js,以 @uni/toast 为例:
API package 版本统一维护在根目录下的 api-config.js,以 @uni/toast 为例:

```js
module.exports = {
Expand All @@ -102,15 +102,16 @@ module.exports = {
},
],
},
}
};
```

| 参数 | 含义 | 默认值 |
|----|----|----|
|path| 在源文件的路径| -|
|pkgInfo| npm包的属性(同packagejson写法)| -|
|needCommonUtil| 是否需要公共utils| true|
|unNeedSplit| 是否需要安环境分包| false|
| 参数 | 含义 | 默认值 |
| -------------- | ----------------------------------- | ------ |
| path | 在源文件的路径 | - |
| pkgInfo | npm 包的属性(同 packagejson 写法) | - |
| needCommonUtil | 是否需要公共 utils | true |
| unNeedSplit | 是否需要安环境分包 | false |
| exportMain | 是否需要导出到大包中 | true |

大包版本需要更新根目录下的 package.json 的 version

Expand Down
13 changes: 13 additions & 0 deletions api-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -381,4 +381,17 @@ module.exports = {
},
],
},
utils: {
path: 'src/packages/utils/src/index.ts',
unNeedSplit: true,
needCommonUtil: false,
exportMain: false,
pkgInfo: [
{
version: '1.0.0',
name: '@uni/utils',
exports: '',
},
],
},
};
69 changes: 69 additions & 0 deletions migrate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
const glob = require('glob');
const fs = require('fs-extra');
const babelParser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const types = require('@babel/types');
const generate = require('@babel/generator').default;


function parse(file) {
const source = fs.readFileSync(file, { encoding: 'utf8' });
let ast;
try {
ast = babelParser.parse(source, {
sourceType: 'module',
plugins: [
'typescript',
'classProperties',
'objectRestSpread',
'optionalCatchBinding',
'dynamicImport',
'decorators-legacy',
'asyncGenerators',
'exportDefaultFrom',
'exportNamespaceFrom',
'optionalCatchBinding',
'throwExpressions',
'optionalChaining',
'nullishCoalescingOperator',
],
});
} catch (e) {
console.error('error', file);
return;
}

if (!ast) {
console.error('error', file);
return;
}
let changed = false;
traverse(ast, {
Program(path) {
const { body } = path.node;
let specifiers = [];
const indexs = [];
body.forEach((n, index) => {
if (types.isImportDeclaration(n) && n.source.value.startsWith('@utils')) {
specifiers = specifiers.concat(n.specifiers);
indexs.push(index);
}
});

if (indexs.length > 0) {
indexs.reverse().forEach(i => body.splice(i, 1));
changed = true;
body.unshift(types.importDeclaration(specifiers, types.stringLiteral('@uni/utils')));
}
},
});
if (changed) {
fs.writeFileSync(file, generate(ast, {}, source).code);
}
}

glob('./src/packages/**/src/**/*.ts', function(err, files) {
files.forEach(file => {
parse(file);
});
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "@uni/apis",
"private": true,
"version": "1.1.10",
"sideEffects": false,
"scripts": {
"setup": "rm -rf node_modules && yarn install --no-lockfile",
"lint": "eslint --ext .js --ext .jsx --ext .ts --ext .tsx ./src/packages/**/src --fix",
Expand Down
8 changes: 7 additions & 1 deletion scripts/build-plugin/buildMain.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@ const path = require('path');
const needRename = {
location: '_location'
}
module.exports = (rootDir, sourceMap) => {
module.exports = (rootDir, originSourceMap) => {
const sourceMap = Object.keys(originSourceMap).reduce((prev, cur) => {
if (originSourceMap[cur].exportMain !== false) {
prev[cur] = originSourceMap[cur];
}
return prev;
}, {});
const defaultContent = '\r\n\r\nexport default {\r\n' + Object.entries(sourceMap).map(([key, value]) => {
if (needRename[key]) {
return ` ${key}: ${needRename[key]},`;
Expand Down
36 changes: 18 additions & 18 deletions scripts/build-plugin/gulp/conf/babel.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,26 +33,26 @@ module.exports = (isEs, isMain, aliasEntries) => {
* resolvePath: ...,
* }
*/
const oriUtilsPath = '@utils';
let newUtilsPath = '_utils';
let pathLv = 0;
if (sourcePath.indexOf(oriUtilsPath) !== -1) {
if (isMain) {
newUtilsPath = 'utils'
pathLv = currentFile
.match(/(src\/packages\/.*\.ts)/)[1]
.split('/').length - 2;
} else {
pathLv = currentFile
.replace('/src/packages', '')
.match(/(src\/.*\.ts)/)[1]
.split('/').length - 2;
}
// const oriUtilsPath = '@utils';
// let newUtilsPath = '_utils';
// let pathLv = 0;
// if (sourcePath.indexOf(oriUtilsPath) !== -1) {
// if (isMain) {
// newUtilsPath = 'utils'
// pathLv = currentFile
// .match(/(src\/packages\/.*\.ts)/)[1]
// .split('/').length - 2;
// } else {
// pathLv = currentFile
// .replace('/src/packages', '')
// .match(/(src\/.*\.ts)/)[1]
// .split('/').length - 2;
// }

const pointRelative = pathLv === 0 ? '.' : Array.from({length: pathLv}).map(i => '..').join('/');
// const pointRelative = pathLv === 0 ? '.' : Array.from({length: pathLv}).map(i => '..').join('/');

return sourcePath.replace(oriUtilsPath, pointRelative + '/' + newUtilsPath);
}
// return sourcePath.replace(oriUtilsPath, pointRelative + '/' + newUtilsPath);
// }

// 替换内部依赖,加入index.js

Expand Down
2 changes: 1 addition & 1 deletion scripts/build-plugin/gulp/gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const tsProject = ts.createProject({
// "@types/*": ["types/*"],
// "types/interface": ["./interface"],
"@/*": ["src/*"],
"@utils/*": ["src/utils/*"],
// "@utils/*": ["src/utils/*"],
}
});

Expand Down
4 changes: 4 additions & 0 deletions scripts/build-plugin/initPkg.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ const buildPkgJson = async (packageInfo, outputPath, isMain = false) => {
}
if (isMain || packageInfo.name == '@uni/env') {
delete packageJson.dependencies['@uni/env'];
cryzzchen marked this conversation as resolved.
Show resolved Hide resolved
delete packageJson.dependencies['@uni/utils'];
}
if (packageInfo.name === '@uni/utils') {
delete packageJson.dependencies['@uni/utils'];
}
if (isMain) {
packageJson.typings = 'types/main/index.d.ts';
Expand Down
1 change: 1 addition & 0 deletions scripts/build-plugin/source/package-tpl.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ module.exports = {
},
'dependencies': {
'@uni/env': '^1.0.0',
'@uni/utils': "^1.0.0"
},
"repository": {
"type": "git",
Expand Down
48 changes: 35 additions & 13 deletions src/packages/canvas/src/ali-miniapp/createContext.ts
Original file line number Diff line number Diff line change
@@ -1,74 +1,96 @@
import { CONTAINER_NAME } from '@uni/utils';
import { CanvasContext, Options } from '../types';
import { normalize } from '../common';
import { CONTAINER_NAME } from '@utils/constant';
import { isLessThanVersion } from '@utils/tools';

const createContext = normalize((canvasOptions: Options): Promise<CanvasContext> => {
const { canvasId, type = '2d' } = canvasOptions;
const {
canvasId,
type = '2d',
} = canvasOptions;

if (isLessThanVersion(my.SDKVersion, '2.7.0')) {
return new Promise((resolve) => {
const canvasContext = my.createCanvasContext(canvasId);
const _clearRect = canvasContext.clearRect;

canvasContext.clearRect = (...args) => {
_clearRect.apply(canvasContext, args);

canvasContext.draw(true);
};

const _fill = canvasContext.fill;

canvasContext.fill = (...args) => {
_fill.apply(canvasContext, args);

canvasContext.draw(true);
};

const _fillRect = canvasContext.fillRect;

canvasContext.fillRect = (...args) => {
_fillRect.apply(canvasContext, args);

canvasContext.draw(true);
};

const _fillText = canvasContext.fillText;

canvasContext.fillText = (...args) => {
_fillText.apply(canvasContext, args);

canvasContext.draw(true);
};

const _stroke = canvasContext.stroke;

canvasContext.stroke = (...args) => {
_stroke.apply(canvasContext, args);

canvasContext.draw(true);
};

const _strokeRect = canvasContext.strokeRect;

canvasContext.strokeRect = (...args) => {
_strokeRect.apply(canvasContext, args);

canvasContext.draw(true);
};

const _strokeText = canvasContext.strokeText;

canvasContext.strokeText = (...args) => {
_strokeText.apply(canvasContext, args);

canvasContext.draw(true);
};

Object.defineProperty(canvasContext, 'fillStyle', {
get() {
return canvasContext.setFillStyle;
},

set(value) {
canvasContext.setFillStyle(value);
},

});
resolve(canvasContext);
});
} else {
// 仅 2.7.0+ 基础库版本支持
return new Promise((resolve, reject) => {
const query = my.createSelectorQuery();
query
.select(`#${canvasId}`)
.node()
.exec((res) => {
if (!res[0] || !res[0].node) reject(new Error('The canvas node may not exist.'));
const canvasNode: HTMLCanvasElement = res[0].node;
const canvasContext: CanvasContext = canvasNode.getContext(type);

resolve(canvasContext);
});
query.select(`#${canvasId}`).node().exec((res) => {
if (!res[0] || !res[0].node) reject(new Error('The canvas node may not exist.'));
const canvasNode: HTMLCanvasElement = res[0].node;
const canvasContext: CanvasContext = canvasNode.getContext(type);
resolve(canvasContext);
});
});
}
}, CONTAINER_NAME.ALIPAY);

export default createContext;
Loading