Coder Social home page Coder Social logo

raxjs / universal-api Goto Github PK

View Code? Open in Web Editor NEW
258.0 18.0 63.0 7.78 MB

Universal apis for web and miniapps.

Home Page: https://universal-api.js.org/

JavaScript 10.21% TypeScript 89.79%
universal-apis miniapp wechat wechat-mini-program mini-program rax

universal-api's Introduction

Rax

Uni API 是一套支持小程序和 Web 容器的跨端 API 解决方案。


🎉 多容器支持 目前支持 Web、微信小程序、头条小程序、阿里小程序、百度小程序、快手小程序

🐂 API 丰富 覆盖 90+ API 实现

😯 文档完善 提供双语文档、丰富样例

0️⃣ 无框架依赖 无框架依赖,纯原生实现,可以兼容任意框架

🚀 极致体积 支持按需加载,按环境剔除无用代码

👍🏻 简易使用,快速接入 提供完善的 TypeScript 声明,让你可以摆脱文档,沉浸编程

快速使用

以 @uni/toast 为例

$ npm install @uni/toast
import { showToast } from '@uni/toast';

// string
showToast('Hi');

// object
showToast({
  content: 'hello',
  type: 'success',
  duration: 1000,
  success: () => {
    console.log('toast')
  }
});

// promise
showToast({
  content: 'hello',
  type: 'success',
  duration: 1000,
}).then(() => {});

文档

官方站点:https://universal-api.js.org/

示例

微信小程序 支付宝小程序

贡献代码

请首先阅读 Rax 贡献代码指南,了解基础的规范。

起步

$ git clone [email protected]:raxjs/universal-api.git
$ yarn
$ yarn build

调试 API

$ yarn demo:init
$ yarn demo:dev

然后使用小程序 IDE 即可开始调试:

更新版本

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

module.exports = {
  toast: {
    path: 'src/packages/interactive/toast/src/index.ts',
    pkgInfo: [
      {
        version: '1.0.5',
        name: '@uni/toast',
      },
    ],
  },
}
参数 含义 默认值
path 在源文件的路径 -
pkgInfo npm包的属性(同packagejson写法) -
needCommonUtil 是否需要公共utils true
unNeedSplit 是否需要安环境分包 false

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

协议

BSD License

universal-api's People

Contributors

balloonzzq avatar boiawang avatar brightcd avatar broven avatar chenjun1011 avatar chriscindy avatar cipengxu avatar dearice avatar fyangstudio avatar laolaolulu avatar lovesong avatar oklam avatar owops avatar peakchen90 avatar solojiang avatar sylingd avatar wanglijie avatar wssgcg1213 avatar yacheng avatar yuanyan avatar yuysmile avatar zhuangzaiqian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

universal-api's Issues

rax工程 导入 uni/apis 运行报错

image
image
image
image

主包es目录下,引入未打包组件’animation‘组件,导致运行报错。
目前个人解决方案,去掉对应限制,编译之后,再替换本地的包。
希望修复下

@uni/env能否支持判断isRax吗?

背景

  • web页面跳转
  • rax或者react/vue都是用自己的api进行跳转,因为用@uni/navigate跳转会刷新页面(毕竟直接调用的是history)
  • 所以希望可以在env里判断当前环境是不是isRax,这样就能判断使用了

需求

  • isRax判断是否是rax环境

universal-animation: formatBezier returns error value

According to BindingX Doc,

In particular, the cubicBezier function is used to customize the Bessel curve, which is defined as follows:

  • cubicBezier(t, begin, changeBy, duration, controlX1, controlY1, controlX2, controlY2)
    • input parameter:
      • t: time of animation execution
      • begin: attribute starting value
      • changeBy: attribute change value (end - start)
      • duration: duration of animation
      • controlX1: x coordinates of The first control point
      • controlY1: y coordinates of The first control point
      • controlX2: x coordinates of The second control point
      • controlY2: y coordinates of The second control point
    • return:
      • Void

the cubicBezier function's last 4 parameters are controlX1, controlY1, controlX2, controlY2.

In this animation implementation, we get the return value of formatBezier function, and join the result with ',' so that we pass it as the last 4 parameters for the cubicBezier function.

let bezier = formatBezier(prop.easing || easing);
let expression = bezier && bezier.length === 4 ?
`cubicBezier(t-${prop.delay},${start},${prop.end - start},${prop.duration},${bezier.join(',')})`
: `${prop.easing || easing}(t-${prop.delay},${start},${prop.end - start},${prop.duration})`;

However, the formatBezier function returns [m[1], m[4], m[3], m[4]] -- in my opinion, it means controlX1, controlY2, controlX2, controlY2.

export default function formatBezier(easing) {
if (easing) {
let m = easing.match(/cubicBezier\((.+),(.+),(.+),(.+)\)/);
return m && [m[1], m[4], m[3], m[4]];
}
}

Should it return [m[1], m[2], m[3], m[4]] rather than [m[1], m[4], m[3], m[4]]?

@uni/request

背景:
request({}) 设置了headers但没有设置'Content-Type': 'application/json', Content-Type的默认值为Content-Type: text/plain;charset=UTF-8

希望:
在自定义headers时,没有设置Content-type时默认值也还是'application/json'

isWeb 环境判断建议与 isMiniApp 互斥

各个api的env判断中web环境判断条件都是最前置的。
但是在支付宝小程序开发过程中,IDE调试时,env.isWeb = true,导致后续逻辑都不正确。
同时env.isMiniApp = true,建议web环境判断更严谨些。

import uni from '@uni/apis';
console.log(uni.application.getApp(), uni.env.isWeb);

打印结果:
image

正确应该是返回 getApp()
image

运行环境:支付宝小程序

// mini.project.json
{
  "format": 2,
  "miniprogramRoot": "src",
  "compileOptions": {
    "component2": true,
    "typescript": true,
    "less": true,
    "enableNodeModuleBabelTransform": true
  }
}

[Feature] @uni/pull-down-refresh Web下增加关闭 PullDownRefresh 的方法

问题

在 Web 下, @uni/pull-down-refresh 提供了 onPullDownRefresh

现有代码对下拉处理不是全局单实例的,看起来目前只能开启全局的下拉和增加监听,无法移除下拉和删除监听
https://github.com/raxjs/universal-api/blob/master/src/packages/interactive/pullDownRefresh/src/web/onPullDownRefresh.ts#L184-L190

期望

  1. 期望支持关闭页面下拉功能
  2. 期望支持移除下拉监听事件功能

TS 下类型校验

在 Typescript 下调试示例代码(https://rax.js.org/docs/api/request#%E7%A4%BA%E4%BE%8B ):

import request from 'universal-request';

request({
  url: 'https://alibaba.github.io/rax/',
  method: 'POST',
  data: {
    from: 'Rax',
  },
  dataType: 'json' // ts error
}).then(response => {})
  .catch(error => {});

dataType 处有错误提示

Type '"json"' is not assignable to type 'DATA_TYPE'.ts(2322)

storage/getStorage返回的类型都是any

背景

  const res = getStorageSync({
      key: 'openid',
    });

返回的res的类型是any

但是实际上至少是

{
 data: any
}

data这层我看文档是固定有的,所以为什么是any

[Question]@uni/request Web端为什么失败也会触发success

背景

request({
  url: 'https://alibaba.github.io/rax/',
  method: 'POST',
  data: {
    from: 'Rax',
  },
  dataType: 'json',
  success: (res) => {
    console.log('success', res);
  },
  fail: (res) => {
    console.log('fail', res);
  },
  complete: (res) => {
    console.log('complete', res);
  },
});
  • 会返回失败

预期:

  • 只触发fail和complete

但实际

  • 触发success、fail、complete

然后我看源码
https://github.com/raxjs/universal-api/blob/master/src/packages/network/request/src/web/index.ts

image

这里遇到错误并没有return掉

【BUG】pageScrollTo方法在h5可能造成页面卡顿

image
Element.scrollTop接受的是一个整数,如果赋值带有小数,会截取整数部分,如下图
image

造成卡顿的原因:
当speed是一个比较小的值时,nextTop得出的结果与top绝对值小于1,此时设置rootElement.scrollTop后实际没变化,极端情况会在同一个值循环,导致页面卡顿。

另外,同一个元素多次触发pageScrollTo方法时是否应该先清除上一次的requestAnimationFrame?

希望 universal-device 这个包能完全使用 ESM

我们尝试在 Remax 里使用依赖 @rax-ui 的小程序组件时,发现 universal-device 这个包会根据条件去 require 对应平台的模块,但是由于 remax-cli 使用的 rollup 不能很好地处理这种按条件引用的方式,希望能把 universal-device 改成纯粹的 ES module。

这个改动应该不会对现有依赖 universal-device 项目产生影响。

[Enhance] 包体积优化

  • src/utils 发成 npm 包
    原因:在构建产物中 promisify 代码重复出现了很多次,在仓库中尝试搜索 utils/promisify 可以发现 20+ 处引用

rax安装后提示'These dependencies were not found:'

  • yarn add @uni/apis
  • 显示
 ERROR  Failed to compile with 5 errors 5:29:07 ├F10: PM┤

These dependencies were not found:

* @uni/action-sheet/lib/ali-miniapp in ./node_modules/@uni/apis/es/packages/media/video/src/ali-miniapp/chooseMedia.js
* @uni/confirm/lib/web in ./node_modules/@uni/apis/es/packages/interactive/alert/src/web/index.js
* @uni/system-info in ./node_modules/@uni/apis/es/packages/base/unit-tool/src/index.js
* @uni/video/lib/web/chooseMedia in ./node_modules/@uni/apis/es/packages/media/image/src/web/chooseImage.js, ./node_modules/@uni/apis/es/packages/media/video/src/web/chooseVideo.js

To install them, you can run: npm install --save @uni/action-sheet/lib/ali-miniapp @uni/confirm/lib/web @uni/system-info @uni/video/lib/web/chooseMedia

[QUESTION]previewImage图片显示补全怎么办

image

上下两边被裁掉了

因为img的外层的样式

.__universal_preview_image_item {
    max-height: 70%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-shrink: 0;
    width: 100%;
    position: relative;
    transition-property: transform;
    overflow: hidden;
}

最大高度是70%

[Question]chooseImage在web端拿到的接口在upload不能直接用感觉有点麻烦

chooseImage({
  count: 1,
  sourceType: ['album', 'camera']
}).then(res => {
  const tempFilePaths = res.tempFilePaths
});

在web端 path 是 blob URL blob://xxxx

const task = upload({
  url: 'http://httpbin.org/post',
  fileType: 'image',
  fileName: 'file',
  filePath: '**filePath**',
  success: res => {
    console.log('upload success');
  },
  fail: res => {
    console.log('upload fail');
  },
});

然后upload这里并不能传blob URL

导致得手动转成file

const imgBlob = await fetch(tempFilePath).then((r) => r.blob());
const file = new File([imgBlob], fileName);

感觉很麻烦

然后

  • web虽然res对象里file数组,但是还是希望和其他端统一拿到的是path

需求

  • web端 chooseImage那到的内容upload能直接使用

[bug] @uni/clipboard使用chrome浏览器模拟iphone,setClipboard未生效

这个问题在我很多同事的电脑上都出现,应该不是偶现

系统:mac | window(我同事是window)
chrome 版本99

使用控制台的手机模拟器,选择任意iphone机型,走到关于IOS的判断里,是没有起作用的

···
if (isOS()) {
range = document.createRange();
range.selectNodeContents(textArea);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textArea.setSelectionRange(0, 999999);
} else {
textArea.select();
}
···

判断微信小程序环境应该与 web 环境互斥

微信小程序环境判断:
export const isWeChatMiniProgram = !isByteDanceMicroApp && typeof wx !== 'undefined' && wx !== null && (typeof wx.request !== 'undefined' || typeof wx.miniProgram !== 'undefined');

web 环境判断:
export const isWeb = typeof window !== 'undefined' && 'onload' in window;

情景是:如果在微信小程序中打开 H5 页面,并且需要用到一些 jweixin 的 API,就会在 window 对象添加一个 wx 属性,从而命中 isWeChatMiniProgram 环境判断:
<script type=\"text/javascript\" src=\"https://res.wx.qq.com/open/js/jweixin-1.3.2.js\"></script>

建议微信小程序环境判断改为:
export const isWeChatMiniProgram = !isWeb && !isByteDanceMicroApp && typeof wx !== 'undefined' && wx !== null && (typeof wx.request !== 'undefined' || typeof wx.miniProgram !== 'undefined');

[Bug] RecorderManager在web端如果没有监听onFrameRecorded,stop的时候文件就是空白的

const recorderManager = getRecorderManager();
recorderManager.onStart((e)=>{
  console.log('start',e)
})
recorderManager.onStop((e)=>{
  console.log('stop',e)
})
recorderManager.start({  
})
   setTimeout(() => {
       recorderManager.stop();
 }, 3000);

上面的代码输出的文件是空的

{
duration: 2000,
fileSize: 0,
tempFilePath: "blob:http://localhost:8989/7474aafc-53b1-4147-9158-44c4c228f156"}

但是如果加了

 recorderManager.onFrameRecorded((e)=>{
   console.log('onFrameRecorded',e)
 })

就正常

然后我们看到源文件https://github.com/raxjs/universal-api/blob/286d77035e/src/packages/media/recorder/src/web/index.ts#L114
这个确实是只有我们调用onFrameRecorded才会开始监听ondataavailable,才有切片

JSONP 解码失败

使用@uni/request做jsonp请求的时候,JSONP请求返回异常如下:
image

找到抛出异常的代码如下:
image

从上面看出,抛出异常的一定是line:130 JSON.parse方法,然后看下异常返回的详细信息如下:
image

从上图可以会导致代码冲突的,就是返回的“;”没有被替换掉。
那么,line: 129这种解码方式是有问题的,看下源码:

const content = res?.data?.replace(`${jsonpCallback}(`, '').replace(')', '');

这里只是将)替换掉了,没有考虑到 ); 结尾的情况,并且使用replace的字符串替换是不严谨的,可能导致返回的数据里面本身的相同字符串被替换,应该使用正则匹配替换,代码如下:

const reg = new RegExp(`(^${jsonpCallback}\\(|(\\)|\\);)$)`, 'gm');

const content = res?.data?.replace(reg, '');

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.