From 5fe357f46efa3e718c25eb0b0e3d49b4b5b88358 Mon Sep 17 00:00:00 2001 From: shangqunfeng Date: Thu, 7 Nov 2024 22:38:57 +0800 Subject: [PATCH 01/76] feat(component): add rich text component. --- .../template/wx/component-config/rich-text.js | 8 ++ .../wx/component-config/unsupported.js | 2 +- .../components/react/mpx-rich-text.tsx | 134 ++++++++++++++++++ 3 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text.tsx diff --git a/packages/webpack-plugin/lib/platform/template/wx/component-config/rich-text.js b/packages/webpack-plugin/lib/platform/template/wx/component-config/rich-text.js index f1372e600c..0fe38178a2 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/component-config/rich-text.js +++ b/packages/webpack-plugin/lib/platform/template/wx/component-config/rich-text.js @@ -12,6 +12,14 @@ module.exports = function ({ print }) { el.isBuiltIn = true return 'mpx-rich-text' }, + ios (tag, { el }) { + el.isBuiltIn = true + return 'mpx-rich-text' + }, + android (tag, { el }) { + el.isBuiltIn = true + return 'mpx-rich-text' + }, props: [ { test: /^(space)$/, diff --git a/packages/webpack-plugin/lib/platform/template/wx/component-config/unsupported.js b/packages/webpack-plugin/lib/platform/template/wx/component-config/unsupported.js index 3a05d72fad..00c615a0dc 100644 --- a/packages/webpack-plugin/lib/platform/template/wx/component-config/unsupported.js +++ b/packages/webpack-plugin/lib/platform/template/wx/component-config/unsupported.js @@ -11,7 +11,7 @@ const JD_UNSUPPORTED_TAG_NAME_ARR = ['functional-page-navigator', 'live-pusher', // 快应用不支持的标签集合 const QA_UNSUPPORTED_TAG_NAME_ARR = ['movable-view', 'movable-area', 'open-data', 'official-account', 'editor', 'functional-page-navigator', 'live-player', 'live-pusher', 'ad', 'cover-image'] // RN不支持的标签集合 -const RN_UNSUPPORTED_TAG_NAME_ARR = ['open-data', 'official-account', 'editor', 'functional-page-navigator', 'live-player', 'live-pusher', 'ad', 'progress', 'rich-text', 'slider', 'audio', 'camera', 'video', 'canvas', 'match-media', 'page-container', 'editor', 'keyboard-accessory', 'map'] +const RN_UNSUPPORTED_TAG_NAME_ARR = ['open-data', 'official-account', 'editor', 'functional-page-navigator', 'live-player', 'live-pusher', 'ad', 'progress', 'slider', 'audio', 'camera', 'video', 'canvas', 'match-media', 'page-container', 'editor', 'keyboard-accessory', 'map'] /** * @param {function(object): function} print diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text.tsx new file mode 100644 index 0000000000..d4948f682f --- /dev/null +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text.tsx @@ -0,0 +1,134 @@ + +/** + * ✔ nodes + */ +import { View, ViewProps, ViewStyle } from 'react-native' +import { useRef, forwardRef, JSX, useState } from 'react' +import useInnerProps from './getInnerListeners' +import useNodesRef, { HandlerRef } from './useNodesRef' // 引入辅助函数 +import { useTransformStyle, useLayout } from './utils' +import { WebView, WebViewMessageEvent } from 'react-native-webview' + +type Node = { + type: 'node' | 'text' + name?: string + attrs?: any + children?: Array + text: string +} + +interface _RichTextProps extends ViewProps { + style?: ViewStyle + nodes: string | Array + 'enable-var'?: boolean + 'external-var-context'?: Record + 'parent-font-size'?: number + 'parent-width'?: number + 'parent-height'?: number +} + +function jsonToHtmlStr (elements: Array) { + let htmlStr = '' + + for (const element of elements) { + if (element.type === 'text') { + htmlStr += element.text + return htmlStr + } + + const { name, attrs = {}, children = [] } = element + + let attrStr = '' + for (const [key, value] of Object.entries(attrs)) attrStr += ` ${key}="${value}"` + + let childrenStr = '' + for (const child of children) childrenStr += jsonToHtmlStr([child]) + + htmlStr += `<${name}${attrStr}>${childrenStr}` + } + + return htmlStr +} + +const _RichText = forwardRef, _RichTextProps>((props, ref): JSX.Element => { + const { + style = {}, + nodes, + 'enable-var': enableVar, + 'external-var-context': externalVarContext, + 'parent-font-size': parentFontSize, + 'parent-width': parentWidth, + 'parent-height': parentHeight + } = props + + const webview = useRef(null) + const nodeRef = useRef(null) + const [webViewHeight, setWebViewHeight] = useState(0) + + const { + normalStyle, + hasSelfPercent, + setWidth, + setHeight + } = useTransformStyle(Object.assign({ + width: '100%', + height: webViewHeight + }, style), { + enableVar, + externalVarContext, + parentFontSize, + parentWidth, + parentHeight + }) + + const { + layoutRef, + layoutStyle, + layoutProps + } = useLayout({ props, hasSelfPercent, setWidth, setHeight, nodeRef }) + + useNodesRef(props, ref, nodeRef, { + layoutRef + }) + + const innerProps = useInnerProps(props, { + ref: nodeRef, + style: { ...normalStyle, ...layoutStyle }, + ...layoutProps + }, [], { + layoutRef + }) + + const html: string = typeof nodes === 'string' ? nodes : jsonToHtmlStr(nodes) + + return ( + + ' + html }} + onMessage={(event: WebViewMessageEvent) => + setWebViewHeight(+event.nativeEvent.data) + } + // https://github.com/react-native-webview/react-native-webview/issues/341 + injectedJavaScript={` + document.documentElement.style.padding = 0; + document.documentElement.style.margin = 0; + document.body.style.padding = 0; + document.body.style.margin = 0; + window.ReactNativeWebView.postMessage(document.body.scrollHeight); + true; + `} + onLoadEnd={() => webview.current?.injectJavaScript('window.ReactNativeWebView.postMessage(document.body.scrollHeight);') // android + } + > + + + ) +}) + +_RichText.displayName = 'mpx-rich-text' + +export default _RichText From a452b5ea92defb591ac481aa5b4cc0a893dbdc2d Mon Sep 17 00:00:00 2001 From: shangqunfeng Date: Fri, 22 Nov 2024 10:44:15 +0800 Subject: [PATCH 02/76] fix(*): add html tpl. --- .../components/react/mpx-rich-text/html.ts | 40 +++++++++++++++++++ .../index.tsx} | 27 ++++--------- 2 files changed, 47 insertions(+), 20 deletions(-) create mode 100644 packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/html.ts rename packages/webpack-plugin/lib/runtime/components/react/{mpx-rich-text.tsx => mpx-rich-text/index.tsx} (71%) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/html.ts b/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/html.ts new file mode 100644 index 0000000000..034baa57c2 --- /dev/null +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/html.ts @@ -0,0 +1,40 @@ + +export const generateHTML = (html: string) => { + return ` + + + +
${html}
+ +` +} diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/index.tsx similarity index 71% rename from packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text.tsx rename to packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/index.tsx index d4948f682f..db6097df5d 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/index.tsx @@ -4,10 +4,11 @@ */ import { View, ViewProps, ViewStyle } from 'react-native' import { useRef, forwardRef, JSX, useState } from 'react' -import useInnerProps from './getInnerListeners' -import useNodesRef, { HandlerRef } from './useNodesRef' // 引入辅助函数 -import { useTransformStyle, useLayout } from './utils' +import useInnerProps from '../getInnerListeners' +import useNodesRef, { HandlerRef } from '../useNodesRef' // 引入辅助函数 +import { useTransformStyle, useLayout } from '../utils' import { WebView, WebViewMessageEvent } from 'react-native-webview' +import { generateHTML } from './html' type Node = { type: 'node' | 'text' @@ -61,7 +62,6 @@ const _RichText = forwardRef, _RichTextProps>(( 'parent-height': parentHeight } = props - const webview = useRef(null) const nodeRef = useRef(null) const [webViewHeight, setWebViewHeight] = useState(0) @@ -104,25 +104,12 @@ const _RichText = forwardRef, _RichTextProps>(( return ( ' + html }} - onMessage={(event: WebViewMessageEvent) => + source={{ html: generateHTML(html) }} + onMessage={(event: WebViewMessageEvent) => { setWebViewHeight(+event.nativeEvent.data) - } - // https://github.com/react-native-webview/react-native-webview/issues/341 - injectedJavaScript={` - document.documentElement.style.padding = 0; - document.documentElement.style.margin = 0; - document.body.style.padding = 0; - document.body.style.margin = 0; - window.ReactNativeWebView.postMessage(document.body.scrollHeight); - true; - `} - onLoadEnd={() => webview.current?.injectJavaScript('window.ReactNativeWebView.postMessage(document.body.scrollHeight);') // android - } + }} > From 05bd07d58c84a112c7b805b40194271539b62325 Mon Sep 17 00:00:00 2001 From: shangqunfeng Date: Fri, 22 Nov 2024 13:35:56 +0800 Subject: [PATCH 03/76] fix(*): typo --- .../lib/runtime/components/react/mpx-rich-text/html.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/html.ts b/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/html.ts index 034baa57c2..222797da33 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/html.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-rich-text/html.ts @@ -31,7 +31,7 @@ export const generateHTML = (html: string) => { From 01a1bccafef47a8321de27f28cc4df1ad05befed Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Wed, 27 Nov 2024 19:18:02 +0800 Subject: [PATCH 04/76] =?UTF-8?q?=E8=A1=A5=E5=85=85title=E9=80=BB=E8=BE=91?= =?UTF-8?q?&=E5=B9=B2=E6=8E=89=E6=97=A0=E7=94=A8=E7=9A=84seturl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/components/react/mpx-web-view.tsx | 23 +++++++++++-------- .../components/react/types/global.d.ts | 3 ++- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 01ede3e3ec..3221f2fb20 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -1,5 +1,5 @@ import { forwardRef, JSX, useEffect, useRef, useContext, useMemo } from 'react' -import { noop, warn } from '@mpxjs/utils' +import { noop, warn, getFocusedNavigation } from '@mpxjs/utils' import { Portal } from '@ant-design/react-native' import { getCustomEvent } from './getInnerListeners' import { promisify, redirectTo, navigateTo, navigateBack, reLaunch, switchTab } from '@mpxjs/api-proxy' @@ -48,6 +48,8 @@ interface FormRef { postMessage: (value: any) => void; } +const navigation = getFocusedNavigation() + const _WebView = forwardRef, WebViewProps>((props, ref): JSX.Element => { const { src = '', bindmessage = noop, bindload = noop, binderror = noop } = props if (props.style) { @@ -80,12 +82,6 @@ const _WebView = forwardRef, WebViewProps>((pr })) } - useEffect(() => { - if (currentPage) { - currentPage.__webViewUrl = src - } - }, [src, currentPage]) - useEffect(() => { // 组件卸载时执行 return () => { @@ -112,9 +108,18 @@ const _WebView = forwardRef, WebViewProps>((pr } binderror(result) } + + const webViewTitle = useRef('') + const webViewUrl = useRef('') const _changeUrl = function (navState: WebViewNavigation) { - if (currentPage) { - currentPage.__webViewUrl = navState.url + if (navState.navigationType) { // navigationType这个事件在页面开始加载时和页面加载完成时都会被触发所以判断这个避免其他无效触发执行该逻辑 + if (webViewTitle.current !== navState.title) { + navigation && navigation.setOptions({ headerTitle: navState.title }) + } + if (currentPage && webViewUrl.current !== navState.url) { + webViewUrl.current = navState.url + currentPage.__webViewUrl = navState.url + } } } const _message = function (res: WebViewMessageEvent) { diff --git a/packages/webpack-plugin/lib/runtime/components/react/types/global.d.ts b/packages/webpack-plugin/lib/runtime/components/react/types/global.d.ts index 93eed03767..8e177b4549 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/types/global.d.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/types/global.d.ts @@ -34,7 +34,8 @@ declare module '@mpxjs/utils' { bottom: number left: number right: number - } + }, + setOptions: (params: Record) => void } | undefined } From bcee9b661c654b92998ef071b548e6dd66172a81 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 28 Nov 2024 15:46:02 +0800 Subject: [PATCH 05/76] =?UTF-8?q?=E6=94=B9=E9=80=A0webview=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/components/react/mpx-web-view.tsx | 24 +++++-------------- 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 3221f2fb20..28b0dd0206 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -71,23 +71,6 @@ const _WebView = forwardRef, WebViewProps>((pr defaultStyle: defaultWebViewStyle }) - const _messageList = useRef([]) - const handleUnload = () => { - // 这里是 WebView 销毁前执行的逻辑 - bindmessage(getCustomEvent('messsage', {}, { - detail: { - data: _messageList.current - }, - layoutRef: webViewRef - })) - } - - useEffect(() => { - // 组件卸载时执行 - return () => { - handleUnload() - } - }, []) const _load = function (res: WebViewNavigationEvent) { const result = { type: 'load', @@ -137,7 +120,12 @@ const _WebView = forwardRef, WebViewProps>((pr const postData: PayloadData = data.payload || {} switch (data.type) { case 'postMessage': - _messageList.current.push(postData.data) + bindmessage(getCustomEvent('messsage', {}, { // RN组件销毁顺序与小程序不一致,所以改成和支付宝消息一致 + detail: { + data: postData.data + }, + layoutRef: webViewRef + })) asyncCallback = Promise.resolve({ errMsg: 'invokeWebappApi:ok' }) From 2d310487394b967e2ff27f1fe4a04b4ec385817b Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Thu, 28 Nov 2024 19:43:55 +0800 Subject: [PATCH 06/76] =?UTF-8?q?fix=20font-family=20=E6=94=AF=E6=8C=81=20?= =?UTF-8?q?css=20var?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webpack-plugin/lib/platform/style/wx/index.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/style/wx/index.js b/packages/webpack-plugin/lib/platform/style/wx/index.js index f654b35481..c8037d1bea 100644 --- a/packages/webpack-plugin/lib/platform/style/wx/index.js +++ b/packages/webpack-plugin/lib/platform/style/wx/index.js @@ -398,7 +398,7 @@ module.exports = function getSpec ({ warn, error }) { break case 'matrix': case 'matrix3d': - transform.push({ [key]: val.split(',').map(val => +val) }) + transform.push({ [key]: parseValues(val, ',').map(val => +val) }) break case 'translate': case 'scale': @@ -409,7 +409,7 @@ module.exports = function getSpec ({ warn, error }) { { // 2 个以上的值处理 key = key.replace('3d', '') - const vals = val.split(',', key === 'rotate' ? 4 : 3) + const vals = parseValues(val, ',').splice(0, key === 'rotate' ? 4 : 3) // scale(.5) === scaleX(.5) scaleY(.5) if (vals.length === 1 && key === 'scale') { vals.push(vals[0]) @@ -456,7 +456,7 @@ module.exports = function getSpec ({ warn, error }) { const formatFlex = ({ prop, value, selector }) => { let values = parseValues(value) if (values.length > 3) { - error(`Value of [flex] in ${selector} supports up to three values, received [${value}], please check again!`) + warn(`Value of [flex] in ${selector} supports up to three values, received [${value}], please check again!`) values = values.splice(0, 3) } const cssMap = [] @@ -477,7 +477,7 @@ module.exports = function getSpec ({ warn, error }) { } // 最后一个值是flexBasis 的有效值(auto或者有单位百分比、px等) // flex 0 1 auto flex auto flex 1 auto flex 1 30px flex 1 10% flex 1 1 auto - if (!isNumber(lastOne) || !cssVariableExp.test(value)) { + if (!isNumber(lastOne) || cssVariableExp.test(value)) { // 添加 grow 和 shrink // 在设置 flex basis 有效值的场景下,如果没有设置 grow 和 shrink,则默认为1 // 单值 flex: 1 1 @@ -514,7 +514,7 @@ module.exports = function getSpec ({ warn, error }) { const formatFontFamily = ({ prop, value, selector }) => { // 去掉引号 取逗号分隔后的第一个 const newVal = value.replace(/"|'/g, '').trim() - const values = newVal.split(',').filter(i => i) + const values = parseValues(newVal, ',') if (!newVal || !values.length) { error(`Value of [${prop}] is invalid in ${selector}, received [${value}], please check again!`) return false From 8be6d98753efb7130bbde2e11077eba111f4a52e Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Thu, 28 Nov 2024 20:06:00 +0800 Subject: [PATCH 07/76] flex var --- .../webpack-plugin/lib/platform/style/wx/index.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/style/wx/index.js b/packages/webpack-plugin/lib/platform/style/wx/index.js index c8037d1bea..6432bd0046 100644 --- a/packages/webpack-plugin/lib/platform/style/wx/index.js +++ b/packages/webpack-plugin/lib/platform/style/wx/index.js @@ -460,6 +460,11 @@ module.exports = function getSpec ({ warn, error }) { values = values.splice(0, 3) } const cssMap = [] + // 复合属性不支持单个css var(css var可以接收单个值可以是复合值,复合值运行时不处理,这里前置提示一下) + if (values.length === 1 && cssVariableExp.test(value)) { + error(`Property ${prop} in ${selector} is abbreviated property and does not support a single CSS var`) + return { prop, value } + } const lastOne = values[values.length - 1] const isAuto = lastOne === 'auto' // 枚举值 none initial @@ -483,11 +488,13 @@ module.exports = function getSpec ({ warn, error }) { // 单值 flex: 1 1 // 双值 flex: 1 // 三值 flex: + let isUsed = false for (let i = 0; i < 2; i++) { - const item = getIntegersFlex({ prop: AbbreviationMap[prop][i], value: isNumber(values[i]) || cssVariableExp.test(value) ? values[i] : 1 }) + isUsed = isNumber(values[i]) || cssVariableExp.test(values[i]) + const item = getIntegersFlex({ prop: AbbreviationMap[prop][i], value: isUsed ? values[i] : 1 }) item && cssMap.push(item) } - if (!isAuto) { + if (!isAuto && !isUsed) { // 有单位(百分比、px等) 的 value 赋值 flexBasis,auto 不处理 cssMap.push({ prop: 'flexBasis', From fab3d3407a13a758932b170cbf853fa2b0720e8e Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Thu, 28 Nov 2024 20:08:04 +0800 Subject: [PATCH 08/76] del log --- packages/webpack-plugin/lib/platform/style/wx/index.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/style/wx/index.js b/packages/webpack-plugin/lib/platform/style/wx/index.js index 6432bd0046..b14881906c 100644 --- a/packages/webpack-plugin/lib/platform/style/wx/index.js +++ b/packages/webpack-plugin/lib/platform/style/wx/index.js @@ -460,9 +460,7 @@ module.exports = function getSpec ({ warn, error }) { values = values.splice(0, 3) } const cssMap = [] - // 复合属性不支持单个css var(css var可以接收单个值可以是复合值,复合值运行时不处理,这里前置提示一下) if (values.length === 1 && cssVariableExp.test(value)) { - error(`Property ${prop} in ${selector} is abbreviated property and does not support a single CSS var`) return { prop, value } } const lastOne = values[values.length - 1] From f20033abfc591fb4a07b941dd8507d324bbd9d5c Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Fri, 29 Nov 2024 14:32:06 +0800 Subject: [PATCH 09/76] add log --- packages/webpack-plugin/lib/platform/style/wx/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/style/wx/index.js b/packages/webpack-plugin/lib/platform/style/wx/index.js index b14881906c..22df8d3a49 100644 --- a/packages/webpack-plugin/lib/platform/style/wx/index.js +++ b/packages/webpack-plugin/lib/platform/style/wx/index.js @@ -489,7 +489,7 @@ module.exports = function getSpec ({ warn, error }) { let isUsed = false for (let i = 0; i < 2; i++) { isUsed = isNumber(values[i]) || cssVariableExp.test(values[i]) - const item = getIntegersFlex({ prop: AbbreviationMap[prop][i], value: isUsed ? values[i] : 1 }) + const item = getIntegersFlex({ prop: AbbreviationMap[prop][i], value: isUsed ? values[i] : 1, selector }) item && cssMap.push(item) } if (!isAuto && !isUsed) { @@ -510,7 +510,7 @@ module.exports = function getSpec ({ warn, error }) { } // 循环赋值 for (let i = 0; i < values.length; i++) { - const item = getIntegersFlex({ prop: AbbreviationMap[prop][i], value: values[i] }) + const item = getIntegersFlex({ prop: AbbreviationMap[prop][i], value: values[i], selector }) item && cssMap.push(item) } return cssMap From 808e591ac33bd5f84cf5f29747424bf9fe6e8fde Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Mon, 2 Dec 2024 20:02:35 +0800 Subject: [PATCH 10/76] =?UTF-8?q?=E8=A1=A5=E5=85=85=E9=83=A8=E5=88=86api?= =?UTF-8?q?=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/platform/api/set-navigation-bar/index.ali.js | 7 ++++++- .../src/platform/api/set-navigation-bar/index.ios.js | 7 +++++-- .../api-proxy/src/platform/api/set-navigation-bar/index.js | 5 ++++- .../src/platform/api/set-navigation-bar/index.web.js | 7 +++++-- 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/packages/api-proxy/src/platform/api/set-navigation-bar/index.ali.js b/packages/api-proxy/src/platform/api/set-navigation-bar/index.ali.js index 67ebfd1f5c..a71a31e5bf 100644 --- a/packages/api-proxy/src/platform/api/set-navigation-bar/index.ali.js +++ b/packages/api-proxy/src/platform/api/set-navigation-bar/index.ali.js @@ -17,7 +17,12 @@ function setNavigationBarColor (options = {}) { return ENV_OBJ.setNavigationBar(options) } +function hideHomeButton (options = {}) { + return ENV_OBJ.hideBackHome(options) +} + export { setNavigationBarTitle, - setNavigationBarColor + setNavigationBarColor, + hideHomeButton } diff --git a/packages/api-proxy/src/platform/api/set-navigation-bar/index.ios.js b/packages/api-proxy/src/platform/api/set-navigation-bar/index.ios.js index 3f83c65f34..e8cf914abd 100644 --- a/packages/api-proxy/src/platform/api/set-navigation-bar/index.ios.js +++ b/packages/api-proxy/src/platform/api/set-navigation-bar/index.ios.js @@ -1,4 +1,4 @@ -import { successHandle, failHandle, getFocusedNavigation } from '../../../common/js' +import { successHandle, failHandle, getFocusedNavigation, envError } from '../../../common/js' import { nextTick } from '../next-tick' function setNavigationBarTitle (options = {}) { const { title = '', success, fail, complete } = options @@ -31,7 +31,10 @@ function setNavigationBarColor (options = {}) { } } +const hideHomeButton = envError('hideHomeButton') + export { setNavigationBarTitle, - setNavigationBarColor + setNavigationBarColor, + hideHomeButton } diff --git a/packages/api-proxy/src/platform/api/set-navigation-bar/index.js b/packages/api-proxy/src/platform/api/set-navigation-bar/index.js index dcfc49d1e1..a13f7acc26 100644 --- a/packages/api-proxy/src/platform/api/set-navigation-bar/index.js +++ b/packages/api-proxy/src/platform/api/set-navigation-bar/index.js @@ -4,7 +4,10 @@ const setNavigationBarTitle = ENV_OBJ.setNavigationBarTitle || envError('setNavi const setNavigationBarColor = ENV_OBJ.setNavigationBarColor || envError('setNavigationBarColor') +const hideHomeButton = ENV_OBJ.hideHomeButton || envError('hideHomeButton') + export { setNavigationBarTitle, - setNavigationBarColor + setNavigationBarColor, + hideHomeButton } diff --git a/packages/api-proxy/src/platform/api/set-navigation-bar/index.web.js b/packages/api-proxy/src/platform/api/set-navigation-bar/index.web.js index 487912e1d4..198ac4b945 100644 --- a/packages/api-proxy/src/platform/api/set-navigation-bar/index.web.js +++ b/packages/api-proxy/src/platform/api/set-navigation-bar/index.web.js @@ -1,4 +1,4 @@ -import { isBrowser, throwSSRWarning, successHandle } from '../../../common/js' +import { isBrowser, envError, throwSSRWarning, successHandle } from '../../../common/js' function setNavigationBarTitle (options = {}) { if (!isBrowser) { @@ -26,7 +26,10 @@ function setNavigationBarColor (options = {}) { successHandle({ errMsg: 'setNavigationBarColor:ok' }, success, complete) } +const hideHomeButton = envError('hideHomeButton') + export { setNavigationBarTitle, - setNavigationBarColor + setNavigationBarColor, + hideHomeButton } From e0d0ba48a90187648509e51e7c8b307e490b01fb Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Mon, 2 Dec 2024 20:54:04 +0800 Subject: [PATCH 11/76] =?UTF-8?q?fix=20toVal=3D0=20=E8=A2=AB=20undefined?= =?UTF-8?q?=20=E8=A6=86=E7=9B=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/runtime/components/react/useAnimationHooks.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts index 9eb2d97cc5..4e3e902cca 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts @@ -218,11 +218,14 @@ export default function useAnimationHooks (props: _ViewProps) { } // 添加每个key的多次step动画 animatedKeys.forEach(key => { - let toVal = (rules.get(key) || transform.get(key)) // key不存在,第一轮取shareValMap[key]value,非第一轮取上一轮的 - if (toVal === undefined) { - toVal = index > 0 ? lastValueMap[key] : shareValMap[key].value - } + let toVal = rules.get(key) !== undefined + ? rules.get(key) + : transform.get(key) !== undefined + ? transform.get(key) + : index > 0 + ? lastValueMap[key] + : shareValMap[key].value const animation = getAnimation({ key, value: toVal }, { delay, duration, easing }, needSetCallback ? setTransformOrigin : undefined) needSetCallback = false if (!sequence[key]) { From bda6bbb591a8c246b7fb0f89a6f6b56c8ef8b047 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Mon, 2 Dec 2024 21:04:23 +0800 Subject: [PATCH 12/76] =?UTF-8?q?=E8=A1=A5=E5=85=85=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/platform/api/setting/index.js | 19 +++++++++++++++++++ packages/api-proxy/src/platform/index.js | 3 +++ 2 files changed, 22 insertions(+) create mode 100644 packages/api-proxy/src/platform/api/setting/index.js diff --git a/packages/api-proxy/src/platform/api/setting/index.js b/packages/api-proxy/src/platform/api/setting/index.js new file mode 100644 index 0000000000..5ab739177f --- /dev/null +++ b/packages/api-proxy/src/platform/api/setting/index.js @@ -0,0 +1,19 @@ +import { ENV_OBJ, envError } from '../../../common/js' + +const getSetting = ENV_OBJ.getSetting || envError('getSetting') + +const openSetting = ENV_OBJ.openSetting || envError('openSetting') + +const enableAlertBeforeUnload = ENV_OBJ.enableAlertBeforeUnload || envError('enableAlertBeforeUnload') + +const disableAlertBeforeUnload = ENV_OBJ.disableAlertBeforeUnload || envError('disableAlertBeforeUnload') + +const getMenuButtonBoundingClientRect = ENV_OBJ.getMenuButtonBoundingClientRect || envError('getMenuButtonBoundingClientRect') + +export { + getSetting, + openSetting, + enableAlertBeforeUnload, + disableAlertBeforeUnload, + getMenuButtonBoundingClientRect +} diff --git a/packages/api-proxy/src/platform/index.js b/packages/api-proxy/src/platform/index.js index dda41337d6..af1382d62a 100644 --- a/packages/api-proxy/src/platform/index.js +++ b/packages/api-proxy/src/platform/index.js @@ -116,3 +116,6 @@ export * from './api/vibrate' // onKeyboardHeightChange, offKeyboardHeightChange, hideKeyboard export * from './api/keyboard' + +// getSetting, openSetting, enableAlertBeforeUnload, disableAlertBeforeUnload, getMenuButtonBoundingClientRect +export * from './api/setting' From 386c2b80ab10de6a57670217a8589ffcb9c79964 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Mon, 2 Dec 2024 21:05:52 +0800 Subject: [PATCH 13/76] =?UTF-8?q?=E4=BF=AE=E6=94=B9navigation=E5=8F=96?= =?UTF-8?q?=E5=80=BC=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/runtime/components/react/mpx-web-view.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 28b0dd0206..5efd577537 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -48,8 +48,6 @@ interface FormRef { postMessage: (value: any) => void; } -const navigation = getFocusedNavigation() - const _WebView = forwardRef, WebViewProps>((props, ref): JSX.Element => { const { src = '', bindmessage = noop, bindload = noop, binderror = noop } = props if (props.style) { @@ -97,6 +95,7 @@ const _WebView = forwardRef, WebViewProps>((pr const _changeUrl = function (navState: WebViewNavigation) { if (navState.navigationType) { // navigationType这个事件在页面开始加载时和页面加载完成时都会被触发所以判断这个避免其他无效触发执行该逻辑 if (webViewTitle.current !== navState.title) { + const navigation = getFocusedNavigation() navigation && navigation.setOptions({ headerTitle: navState.title }) } if (currentPage && webViewUrl.current !== navState.url) { From acbd41e5b68ea2e36bdc24b03eb576d665b01b2e Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Mon, 2 Dec 2024 21:29:20 +0800 Subject: [PATCH 14/76] add wx:key=index --- .../src/platform/builtInMixins/directiveHelperMixin.ios.js | 5 ++++- packages/webpack-plugin/lib/template-compiler/compiler.js | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/core/src/platform/builtInMixins/directiveHelperMixin.ios.js b/packages/core/src/platform/builtInMixins/directiveHelperMixin.ios.js index 2183bd03d0..d5ced280f9 100644 --- a/packages/core/src/platform/builtInMixins/directiveHelperMixin.ios.js +++ b/packages/core/src/platform/builtInMixins/directiveHelperMixin.ios.js @@ -1,7 +1,10 @@ export default function directiveHelperMixin () { return { methods: { - __getWxKey (item, key) { + __getWxKey (item, key, index) { + if (key === 'index') { + return index + } return key === '*this' ? item : item[key] } } diff --git a/packages/webpack-plugin/lib/template-compiler/compiler.js b/packages/webpack-plugin/lib/template-compiler/compiler.js index ae34bfb3ce..4be8742655 100644 --- a/packages/webpack-plugin/lib/template-compiler/compiler.js +++ b/packages/webpack-plugin/lib/template-compiler/compiler.js @@ -1922,7 +1922,7 @@ function postProcessFor (el) { function postProcessForReact (el) { if (el.for) { if (el.for.key) { - addExp(el, `this.__getWxKey(${el.for.item || 'item'}, ${stringify(el.for.key)})`, false, 'key') + addExp(el, `this.__getWxKey(${el.for.item || 'item'}, ${stringify(el.for.key)}, ${el.for.index || 'index'})`, false, 'key') addAttrs(el, [{ name: 'key', value: el.for.key From 9f5819a299e64dbfd6ed745e19737339f2649698 Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Mon, 2 Dec 2024 21:32:13 +0800 Subject: [PATCH 15/76] fix ts error --- .../lib/runtime/components/react/useAnimationHooks.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts index 4e3e902cca..b8a4bd9e76 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts @@ -226,7 +226,7 @@ export default function useAnimationHooks (props: _ViewProps) { : index > 0 ? lastValueMap[key] : shareValMap[key].value - const animation = getAnimation({ key, value: toVal }, { delay, duration, easing }, needSetCallback ? setTransformOrigin : undefined) + const animation = getAnimation({ key, value: toVal! }, { delay, duration, easing }, needSetCallback ? setTransformOrigin : undefined) needSetCallback = false if (!sequence[key]) { sequence[key] = [animation] @@ -234,7 +234,7 @@ export default function useAnimationHooks (props: _ViewProps) { sequence[key].push(animation) } // 更新一下 lastValueMap - lastValueMap[key] = toVal + lastValueMap[key] = toVal! }) // 赋值驱动动画 animatedKeys.forEach((key) => { From 7dfd0d173d360c28d64b26ff206f8e4812212b28 Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Mon, 2 Dec 2024 21:35:58 +0800 Subject: [PATCH 16/76] fix eslint --- .../lib/runtime/components/react/useAnimationHooks.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts index b8a4bd9e76..e59c846b60 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts @@ -219,7 +219,7 @@ export default function useAnimationHooks (props: _ViewProps) { // 添加每个key的多次step动画 animatedKeys.forEach(key => { // key不存在,第一轮取shareValMap[key]value,非第一轮取上一轮的 - let toVal = rules.get(key) !== undefined + const toVal = rules.get(key) !== undefined ? rules.get(key) : transform.get(key) !== undefined ? transform.get(key) From 7928037185226b81b45501d6738056c9605db640 Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Wed, 4 Dec 2024 21:57:53 +0800 Subject: [PATCH 17/76] =?UTF-8?q?fix=20style=E6=9B=B4=E6=96=B0=20=E5=8A=A8?= =?UTF-8?q?=E7=94=BBhooks=E6=B2=A1=E5=90=8C=E6=AD=A5=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/runtime/components/react/mpx-view.tsx | 11 ++++--- .../components/react/useAnimationHooks.ts | 30 ++++++++++++++++--- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx index 49124d76b9..e7e2dd7c50 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx @@ -789,10 +789,13 @@ const _View = forwardRef, _ViewProps>((viewProps, r throw new Error('[Mpx runtime error]: animation use should be stable in the component lifecycle, or you can set [enable-animation] with true.') } const finalStyle = enableAnimation - ? useAnimationHooks({ - animation, - style: viewStyle - }) + ? [ + viewStyle, + useAnimationHooks({ + animation, + style: viewStyle + }) + ] : viewStyle const innerProps = useInnerProps(props, { diff --git a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts index e59c846b60..55ee776db5 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts @@ -83,9 +83,31 @@ const InitialValue: ExtendedViewStyle = Object.assign({ const TransformOrigin = 'transformOrigin' // transform const isTransform = (key: string) => Object.keys(TransformInitial).includes(key) +// 多value解析 +const parseValues = (str: string, char = ' ') => { + let stack = 0 + let temp = '' + const result = [] + for (let i = 0; i < str.length; i++) { + if (str[i] === '(') { + stack++ + } else if (str[i] === ')') { + stack-- + } + // 非括号内 或者 非分隔字符且非空 + if (stack !== 0 || (str[i] !== char && str[i] !== ' ')) { + temp += str[i] + } + if ((stack === 0 && str[i] === char) || i === str.length - 1) { + result.push(temp) + temp = '' + } + } + return result +} // parse string transform, eg: transform: 'rotateX(45deg) rotateZ(0.785398rad)' const parseTransform = (transformStr: string) => { - const values = transformStr.trim().split(/\s+/) + const values = parseValues(transformStr) const transform: {[propName: string]: string|number|number[]}[] = [] values.forEach(item => { const match = item.match(/([/\w]+)\(([^)]+)\)/) @@ -109,7 +131,7 @@ const parseTransform = (transformStr: string) => { break case 'matrix': case 'matrix3d': - transform.push({ [key]: val.split(',').map(val => +val) }) + transform.push({ [key]: parseValues(val, ',').map(val => +val) }) break case 'translate': case 'scale': @@ -120,8 +142,8 @@ const parseTransform = (transformStr: string) => { { // 2 个以上的值处理 key = key.replace('3d', '') - const vals = val.split(',', key === 'rotate' ? 4 : 3) - // scale(.5) === scaleX(.5) scaleY(.5) 这里处理一下 + const vals = parseValues(val, ',').splice(0, key === 'rotate' ? 4 : 3) + // scale(.5) === scaleX(.5) scaleY(.5) if (vals.length === 1 && key === 'scale') { vals.push(vals[0]) } From 6c15df56fca54b1c5718986641976ada8920d3c5 Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Wed, 4 Dec 2024 22:03:53 +0800 Subject: [PATCH 18/76] fix eslint --- .../lib/runtime/components/react/mpx-view.tsx | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx index e7e2dd7c50..e294bfcf52 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx @@ -789,13 +789,10 @@ const _View = forwardRef, _ViewProps>((viewProps, r throw new Error('[Mpx runtime error]: animation use should be stable in the component lifecycle, or you can set [enable-animation] with true.') } const finalStyle = enableAnimation - ? [ - viewStyle, - useAnimationHooks({ + ? [viewStyle, useAnimationHooks({ animation, style: viewStyle - }) - ] + })] : viewStyle const innerProps = useInnerProps(props, { From 155b8afdd3841e89621c934037dc63f636542d0c Mon Sep 17 00:00:00 2001 From: "huajingwen@didiglobal.com" Date: Thu, 5 Dec 2024 14:29:27 +0800 Subject: [PATCH 19/76] del useAnimationHooks originalStyle --- .../lib/runtime/components/react/useAnimationHooks.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts index 55ee776db5..77d1ac0503 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/useAnimationHooks.ts @@ -352,6 +352,6 @@ export default function useAnimationHooks (props: _ViewProps) { styles[key] = shareValMap[key].value } return styles - }, Object.assign({}, originalStyle) as ExtendedViewStyle) + }, {} as ExtendedViewStyle) }) } From 5df00e1fd73eeec7f977bf5e4954470b5a8ea3df Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Thu, 5 Dec 2024 20:35:30 +0800 Subject: [PATCH 20/76] =?UTF-8?q?chore:=E4=BC=98=E5=8C=96=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E7=94=9F=E6=88=90=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/react/getInnerListeners.ts | 275 +++++++++--------- 1 file changed, 138 insertions(+), 137 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts index 4fa7410b33..900530b3d5 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts @@ -1,4 +1,4 @@ -import { useRef } from 'react' +import { useRef, useMemo } from 'react' import { hasOwn, collectDataset } from '@mpxjs/utils' import { omit, extendObject } from './utils' import eventConfigMap from './event.config' @@ -141,160 +141,161 @@ const useInnerProps = ( } } - if (!(Object.keys(eventConfig).length) || config.disableTouch) { + const rawEventKeys = Object.keys(eventConfig) + const sortEventKeys = [...rawEventKeys].sort().join(',') + + if (!rawEventKeys.length || config.disableTouch) { return omit(propsRef.current, removeProps) } - - function handleEmitEvent ( - events: string[], - type: string, - oe: NativeTouchEvent - ) { - events.forEach(event => { - if (propsRef.current[event]) { - const match = /^(catch|capture-catch):?(.*?)(?:\.(.*))?$/.exec(event) - if (match) { - oe.stopPropagation() - } - propsRef.current[event](getTouchEvent(type, oe, propsRef.current, config)) + const events = useMemo(() => { + const touchEventList = [{ + eventName: 'onTouchStart', + handler: (e: NativeTouchEvent) => { + handleTouchstart(e, 'bubble') } - }) - } + }, { + eventName: 'onTouchMove', + handler: (e: NativeTouchEvent) => { + handleTouchmove(e, 'bubble') + } + }, { + eventName: 'onTouchEnd', + handler: (e: NativeTouchEvent) => { + handleTouchend(e, 'bubble') + } + }, { + eventName: 'onTouchCancel', + handler: (e: NativeTouchEvent) => { + handleTouchcancel(e, 'bubble') + } + }, { + eventName: 'onTouchStartCapture', + handler: (e: NativeTouchEvent) => { + handleTouchstart(e, 'capture') + } + }, { + eventName: 'onTouchMoveCapture', + handler: (e: NativeTouchEvent) => { + handleTouchmove(e, 'capture') + } + }, { + eventName: 'onTouchEndCapture', + handler: (e: NativeTouchEvent) => { + handleTouchend(e, 'capture') + } + }, { + eventName: 'onTouchCancelCapture', + handler: (e: NativeTouchEvent) => { + handleTouchcancel(e, 'capture') + } + }] - function checkIsNeedPress (e: NativeTouchEvent, type: 'bubble' | 'capture') { - const tapDetailInfo = ref.current.mpxPressInfo.detail || { x: 0, y: 0 } - const nativeEvent = e.nativeEvent - const currentPageX = nativeEvent.changedTouches[0].pageX - const currentPageY = nativeEvent.changedTouches[0].pageY - if (Math.abs(currentPageX - tapDetailInfo.x) > 1 || Math.abs(currentPageY - tapDetailInfo.y) > 1) { - ref.current.needPress[type] = false - ref.current.startTimer[type] && clearTimeout(ref.current.startTimer[type] as SetTimeoutReturnType) - ref.current.startTimer[type] = null + function handleEmitEvent ( + events: string[], + type: string, + oe: NativeTouchEvent + ) { + events.forEach(event => { + if (propsRef.current[event]) { + const match = /^(catch|capture-catch):?(.*?)(?:\.(.*))?$/.exec(event) + if (match) { + oe.stopPropagation() + } + propsRef.current[event](getTouchEvent(type, oe, propsRef.current, config)) + } + }) } - } - function handleTouchstart (e: NativeTouchEvent, type: 'bubble' | 'capture') { - e.persist() - const bubbleTouchEvent = ['catchtouchstart', 'bindtouchstart'] - const bubblePressEvent = ['catchlongpress', 'bindlongpress'] - const captureTouchEvent = ['capture-catchtouchstart', 'capture-bindtouchstart'] - const capturePressEvent = ['capture-catchlongpress', 'capture-bindlongpress'] - ref.current.startTimer[type] = null - ref.current.needPress[type] = true - const nativeEvent = e.nativeEvent - ref.current.mpxPressInfo.detail = { - x: nativeEvent.changedTouches[0].pageX, - y: nativeEvent.changedTouches[0].pageY - } - const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent - const currentPressEvent = type === 'bubble' ? bubblePressEvent : capturePressEvent - handleEmitEvent(currentTouchEvent, 'touchstart', e) - const { catchlongpress, bindlongpress, 'capture-catchlongpress': captureCatchlongpress, 'capture-bindlongpress': captureBindlongpress } = propsRef.current - if (catchlongpress || bindlongpress || captureCatchlongpress || captureBindlongpress) { - ref.current.startTimer[type] = setTimeout(() => { + function checkIsNeedPress (e: NativeTouchEvent, type: 'bubble' | 'capture') { + const tapDetailInfo = ref.current.mpxPressInfo.detail || { x: 0, y: 0 } + const nativeEvent = e.nativeEvent + const currentPageX = nativeEvent.changedTouches[0].pageX + const currentPageY = nativeEvent.changedTouches[0].pageY + if (Math.abs(currentPageX - tapDetailInfo.x) > 1 || Math.abs(currentPageY - tapDetailInfo.y) > 1) { ref.current.needPress[type] = false - handleEmitEvent(currentPressEvent, 'longpress', e) - }, 350) + ref.current.startTimer[type] && clearTimeout(ref.current.startTimer[type] as SetTimeoutReturnType) + ref.current.startTimer[type] = null + } } - } - function handleTouchmove (e: NativeTouchEvent, type: 'bubble' | 'capture') { - const bubbleTouchEvent = ['catchtouchmove', 'bindtouchmove'] - const captureTouchEvent = ['capture-catchtouchmove', 'capture-bindtouchmove'] - const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent - handleEmitEvent(currentTouchEvent, 'touchmove', e) - checkIsNeedPress(e, type) - } - - function handleTouchend (e: NativeTouchEvent, type: 'bubble' | 'capture') { - // move event may not be triggered - checkIsNeedPress(e, type) - const bubbleTouchEvent = ['catchtouchend', 'bindtouchend'] - const bubbleTapEvent = ['catchtap', 'bindtap'] - const captureTouchEvent = ['capture-catchtouchend', 'capture-bindtouchend'] - const captureTapEvent = ['capture-catchtap', 'capture-bindtap'] - const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent - const currentTapEvent = type === 'bubble' ? bubbleTapEvent : captureTapEvent - ref.current.startTimer[type] && clearTimeout(ref.current.startTimer[type] as SetTimeoutReturnType) - ref.current.startTimer[type] = null - handleEmitEvent(currentTouchEvent, 'touchend', e) - if (ref.current.needPress[type]) { - if (type === 'bubble' && config.disableTap) { - return + function handleTouchstart (e: NativeTouchEvent, type: 'bubble' | 'capture') { + e.persist() + const bubbleTouchEvent = ['catchtouchstart', 'bindtouchstart'] + const bubblePressEvent = ['catchlongpress', 'bindlongpress'] + const captureTouchEvent = ['capture-catchtouchstart', 'capture-bindtouchstart'] + const capturePressEvent = ['capture-catchlongpress', 'capture-bindlongpress'] + ref.current.startTimer[type] = null + ref.current.needPress[type] = true + const nativeEvent = e.nativeEvent + ref.current.mpxPressInfo.detail = { + x: nativeEvent.changedTouches[0].pageX, + y: nativeEvent.changedTouches[0].pageY + } + const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent + const currentPressEvent = type === 'bubble' ? bubblePressEvent : capturePressEvent + handleEmitEvent(currentTouchEvent, 'touchstart', e) + const { catchlongpress, bindlongpress, 'capture-catchlongpress': captureCatchlongpress, 'capture-bindlongpress': captureBindlongpress } = propsRef.current + if (catchlongpress || bindlongpress || captureCatchlongpress || captureBindlongpress) { + ref.current.startTimer[type] = setTimeout(() => { + ref.current.needPress[type] = false + handleEmitEvent(currentPressEvent, 'longpress', e) + }, 350) } - handleEmitEvent(currentTapEvent, 'tap', e) } - } - function handleTouchcancel (e: NativeTouchEvent, type: 'bubble' | 'capture') { - const bubbleTouchEvent = ['catchtouchcancel', 'bindtouchcancel'] - const captureTouchEvent = ['capture-catchtouchcancel', 'capture-bindtouchcancel'] - const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent - ref.current.startTimer[type] && clearTimeout(ref.current.startTimer[type] as SetTimeoutReturnType) - ref.current.startTimer[type] = null - handleEmitEvent(currentTouchEvent, 'touchcancel', e) - } - - const touchEventList = [{ - eventName: 'onTouchStart', - handler: (e: NativeTouchEvent) => { - handleTouchstart(e, 'bubble') - } - }, { - eventName: 'onTouchMove', - handler: (e: NativeTouchEvent) => { - handleTouchmove(e, 'bubble') - } - }, { - eventName: 'onTouchEnd', - handler: (e: NativeTouchEvent) => { - handleTouchend(e, 'bubble') - } - }, { - eventName: 'onTouchCancel', - handler: (e: NativeTouchEvent) => { - handleTouchcancel(e, 'bubble') - } - }, { - eventName: 'onTouchStartCapture', - handler: (e: NativeTouchEvent) => { - handleTouchstart(e, 'capture') - } - }, { - eventName: 'onTouchMoveCapture', - handler: (e: NativeTouchEvent) => { - handleTouchmove(e, 'capture') + function handleTouchmove (e: NativeTouchEvent, type: 'bubble' | 'capture') { + const bubbleTouchEvent = ['catchtouchmove', 'bindtouchmove'] + const captureTouchEvent = ['capture-catchtouchmove', 'capture-bindtouchmove'] + const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent + handleEmitEvent(currentTouchEvent, 'touchmove', e) + checkIsNeedPress(e, type) } - }, { - eventName: 'onTouchEndCapture', - handler: (e: NativeTouchEvent) => { - handleTouchend(e, 'capture') - } - }, { - eventName: 'onTouchCancelCapture', - handler: (e: NativeTouchEvent) => { - handleTouchcancel(e, 'capture') - } - }] - - const events: Record void> = {} - let transformedEventKeys: string[] = [] - for (const key in eventConfig) { - if (propsRef.current[key]) { - transformedEventKeys = transformedEventKeys.concat(eventConfig[key]) + function handleTouchend (e: NativeTouchEvent, type: 'bubble' | 'capture') { + // move event may not be triggered + checkIsNeedPress(e, type) + const bubbleTouchEvent = ['catchtouchend', 'bindtouchend'] + const bubbleTapEvent = ['catchtap', 'bindtap'] + const captureTouchEvent = ['capture-catchtouchend', 'capture-bindtouchend'] + const captureTapEvent = ['capture-catchtap', 'capture-bindtap'] + const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent + const currentTapEvent = type === 'bubble' ? bubbleTapEvent : captureTapEvent + ref.current.startTimer[type] && clearTimeout(ref.current.startTimer[type] as SetTimeoutReturnType) + ref.current.startTimer[type] = null + handleEmitEvent(currentTouchEvent, 'touchend', e) + if (ref.current.needPress[type]) { + if (type === 'bubble' && config.disableTap) { + return + } + handleEmitEvent(currentTapEvent, 'tap', e) + } } - } - const finalEventKeys = [...new Set(transformedEventKeys)] - - touchEventList.forEach(item => { - if (finalEventKeys.includes(item.eventName)) { - events[item.eventName] = item.handler + function handleTouchcancel (e: NativeTouchEvent, type: 'bubble' | 'capture') { + const bubbleTouchEvent = ['catchtouchcancel', 'bindtouchcancel'] + const captureTouchEvent = ['capture-catchtouchcancel', 'capture-bindtouchcancel'] + const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent + ref.current.startTimer[type] && clearTimeout(ref.current.startTimer[type] as SetTimeoutReturnType) + ref.current.startTimer[type] = null + handleEmitEvent(currentTouchEvent, 'touchcancel', e) } - }) + const transformedEventKeys = rawEventKeys.reduce((acc: string[], key) => { + if (propsRef.current[key]) { + return acc.concat(eventConfig[key]) + } + return acc + }, []) + const finalEventKeys = [...new Set(transformedEventKeys)] + const events: Record void> = {} - const rawEventKeys = Object.keys(eventConfig) + touchEventList.forEach(item => { + if (finalEventKeys.includes(item.eventName)) { + events[item.eventName] = item.handler + } + }) + + return events + }, [sortEventKeys]) return extendObject( {}, From efa51b6c37c16be483e43370cd34c63f6ad1027c Mon Sep 17 00:00:00 2001 From: mater Date: Fri, 6 Dec 2024 17:21:52 +0800 Subject: [PATCH 21/76] fix: docs --- docs-vuepress/api/compile.md | 2 +- docs-vuepress/guide/advance/platform.md | 2 +- docs-vuepress/guide/platform/index.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs-vuepress/api/compile.md b/docs-vuepress/api/compile.md index f9eca8aee3..201c4fada2 100644 --- a/docs-vuepress/api/compile.md +++ b/docs-vuepress/api/compile.md @@ -88,7 +88,7 @@ mode 为 Mpx 编译的目标平台, 目前支持的有微信小程序(wx)\支 // 项目 package.json { "script": { - "build:cross": "mpx-cli-service build:mp --targets=wx,ali" + "build:cross": "mpx-cli-service build --targets=wx,ali" } } ``` diff --git a/docs-vuepress/guide/advance/platform.md b/docs-vuepress/guide/advance/platform.md index d7994f77a5..b1e7b7783c 100644 --- a/docs-vuepress/guide/advance/platform.md +++ b/docs-vuepress/guide/advance/platform.md @@ -65,7 +65,7 @@ new MpxwebpackPlugin({ // 项目 package.json { "script": { - "build:cross": "mpx-cli-service build:mp --targets=wx,ali" + "build:cross": "mpx-cli-service build --targets=wx,ali" } } ``` diff --git a/docs-vuepress/guide/platform/index.md b/docs-vuepress/guide/platform/index.md index 7a2507b61a..290c3407c1 100644 --- a/docs-vuepress/guide/platform/index.md +++ b/docs-vuepress/guide/platform/index.md @@ -22,7 +22,7 @@ new MpxwebpackPlugin({ // 项目 package.json { "script": { - "build:cross": "mpx-cli-service build:mp --targets=wx,ali,ios,android" + "build:cross": "mpx-cli-service build --targets=wx,ali,ios,android" } } ``` From 0ab7c6569be4b42df011866cc077bb4f9639efe2 Mon Sep 17 00:00:00 2001 From: mater Date: Fri, 6 Dec 2024 17:26:11 +0800 Subject: [PATCH 22/76] fix: docs --- docs-vuepress/guide/basic/start.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs-vuepress/guide/basic/start.md b/docs-vuepress/guide/basic/start.md index 9812f5726b..541a2b72e9 100644 --- a/docs-vuepress/guide/basic/start.md +++ b/docs-vuepress/guide/basic/start.md @@ -5,6 +5,8 @@ npm i -g @mpxjs/cli ``` +> @mpxjs/cli文档 https://github.com/mpx-ecology/mpx-cli + ## 创建项目安装依赖 在当前目录下创建mpx项目。 @@ -29,7 +31,7 @@ npm install ## 编译构建 -使用npm script执行mpx的编译构建,在开发模式下我们执行watch命令,将项目源码构建输出到`dist/${平台目录}`下,并且监听源码的改动进行重新编译。 +使用npm script执行mpx的编译构建,在开发模式下我们执行serve命令,将项目源码构建输出到`dist/${平台目录}`下,并且监听源码的改动进行重新编译。 ```shell npm run serve From d4a617c93bbec48839fd4531938d5588d3b8a9bb Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Mon, 9 Dec 2024 15:13:48 +0800 Subject: [PATCH 23/76] =?UTF-8?q?chore:=20=E4=BF=AE=E6=94=B9sortEventKeys?= =?UTF-8?q?=E7=94=9F=E6=88=90=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/components/react/event.config.ts | 51 +++++++++---------- .../components/react/getInnerListeners.ts | 9 ++-- 2 files changed, 31 insertions(+), 29 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/event.config.ts b/packages/webpack-plugin/lib/runtime/components/react/event.config.ts index b3f4633ad2..534475f3bf 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/event.config.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/event.config.ts @@ -2,31 +2,30 @@ interface EventConfig { [key: string]: string[]; } -const eventConfigMap: EventConfig = { - bindtap: ['onTouchStart', 'onTouchMove', 'onTouchEnd'], - bindlongpress: ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'], - bindtouchstart: ['onTouchStart'], - bindtouchmove: ['onTouchMove'], - bindtouchend: ['onTouchEnd'], - bindtouchcancel: ['onTouchCancel'], - catchtap: ['onTouchStart', 'onTouchMove', 'onTouchEnd'], - catchlongpress: ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'], - catchtouchstart: ['onTouchStart'], - catchtouchmove: ['onTouchMove'], - catchtouchend: ['onTouchEnd'], - catchtouchcancel: ['onTouchCancel'], - 'capture-bindtap': ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture'], - 'capture-bindlongpress': ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture', 'onTouchCancelCapture'], - 'capture-bindtouchstart': ['onTouchStartCapture'], - 'capture-bindtouchmove': ['onTouchMoveCapture'], - 'capture-bindtouchend': ['onTouchEndCapture'], - 'capture-bindtouchcancel': ['onTouchCancelCapture'], - 'capture-catchtap': ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture'], - 'capture-catchlongpress': ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture', 'onTouchCancelCapture'], - 'capture-catchtouchstart': ['onTouchStartCapture'], - 'capture-catchtouchmove': ['onTouchMoveCapture'], - 'capture-catchtouchend': ['onTouchEndCapture'], - 'capture-catchtouchcancel': ['onTouchCancelCapture'] +const eventConfigMap: { [key: string]: { bitFlag: string; events: string[] } } = { + bindtap: { bitFlag: '000001', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd'] }, + bindlongpress: { bitFlag: '000010', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'] }, + bindtouchstart: { bitFlag: '000011', events: ['onTouchStart'] }, + bindtouchmove: { bitFlag: '000100', events: ['onTouchMove'] }, + bindtouchend: { bitFlag: '000101', events: ['onTouchEnd'] }, + bindtouchcancel: { bitFlag: '000110', events: ['onTouchCancel'] }, + catchtap: { bitFlag: '000111', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd'] }, + catchlongpress: { bitFlag: '001000', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'] }, + catchtouchstart: { bitFlag: '001001', events: ['onTouchStart'] }, + catchtouchmove: { bitFlag: '001010', events: ['onTouchMove'] }, + catchtouchend: { bitFlag: '001011', events: ['onTouchEnd'] }, + catchtouchcancel: { bitFlag: '001100', events: ['onTouchCancel'] }, + 'capture-bindtap': { bitFlag: '001101', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture'] }, + 'capture-bindlongpress': { bitFlag: '001110', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture', 'onTouchCancelCapture'] }, + 'capture-bindtouchstart': { bitFlag: '001111', events: ['onTouchStartCapture'] }, + 'capture-bindtouchmove': { bitFlag: '010000', events: ['onTouchMoveCapture'] }, + 'capture-bindtouchend': { bitFlag: '010001', events: ['onTouchEndCapture'] }, + 'capture-bindtouchcancel': { bitFlag: '010010', events: ['onTouchCancelCapture'] }, + 'capture-catchtap': { bitFlag: '010011', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture'] }, + 'capture-catchlongpress': { bitFlag: '010100', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture', 'onTouchCancelCapture'] }, + 'capture-catchtouchstart': { bitFlag: '010101', events: ['onTouchStartCapture'] }, + 'capture-catchtouchmove': { bitFlag: '010110', events: ['onTouchMoveCapture'] }, + 'capture-catchtouchend': { bitFlag: '010111', events: ['onTouchEndCapture'] }, + 'capture-catchtouchcancel': { bitFlag: '011000', events: ['onTouchCancelCapture'] } } - export default eventConfigMap diff --git a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts index 900530b3d5..782b15465f 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts @@ -135,14 +135,17 @@ const useInnerProps = ( propsRef.current = extendObject({}, props, additionalProps) + let sortEventKeys = '' for (const key in eventConfigMap) { if (hasOwn(propsRef.current, key)) { - eventConfig[key] = eventConfigMap[key] + eventConfig[key] = eventConfigMap[key].events + sortEventKeys = sortEventKeys + eventConfigMap[key].bitFlag + '|' } } - const rawEventKeys = Object.keys(eventConfig) - const sortEventKeys = [...rawEventKeys].sort().join(',') + const rawEventKeys = useMemo(() => { + return Object.keys(eventConfig) + }, [sortEventKeys]) if (!rawEventKeys.length || config.disableTouch) { return omit(propsRef.current, removeProps) From 86b7b4338ece7776c6ccf98ae6e7cc790c93e8bc Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Mon, 9 Dec 2024 16:22:23 +0800 Subject: [PATCH 24/76] =?UTF-8?q?chore:=20=E9=9D=99=E6=80=81=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=8A=BD=E7=A6=BBhook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/react/getInnerListeners.ts | 362 ++++++++++-------- 1 file changed, 207 insertions(+), 155 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts index 782b15465f..633204ebd7 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts @@ -1,4 +1,4 @@ -import { useRef, useMemo } from 'react' +import { useRef, useMemo, RefObject } from 'react' import { hasOwn, collectDataset } from '@mpxjs/utils' import { omit, extendObject } from './utils' import eventConfigMap from './event.config' @@ -20,26 +20,16 @@ const getTouchEvent = ( config: UseInnerPropsConfig ) => { const nativeEvent = event.nativeEvent - const { - timestamp, - pageX, - pageY, - touches, - changedTouches - } = nativeEvent + const { timestamp, pageX, pageY, touches, changedTouches } = nativeEvent const { id } = props const { layoutRef } = config - const currentTarget = extendObject( - {}, - event.currentTarget, - { - id: id || '', - dataset: collectDataset(props), - offsetLeft: layoutRef?.current?.offsetLeft || 0, - offsetTop: layoutRef?.current?.offsetTop || 0 - } - ) + const currentTarget = extendObject({}, event.currentTarget, { + id: id || '', + dataset: collectDataset(props), + offsetLeft: layoutRef?.current?.offsetLeft || 0, + offsetTop: layoutRef?.current?.offsetTop || 0 + }) return extendObject({}, event, { type, @@ -49,7 +39,7 @@ const getTouchEvent = ( x: pageX, y: pageY }, - touches: touches.map(item => { + touches: touches.map((item) => { return { identifier: item.identifier, pageX: item.pageX, @@ -58,7 +48,7 @@ const getTouchEvent = ( clientY: item.locationY } }), - changedTouches: changedTouches.map(item => { + changedTouches: changedTouches.map((item) => { return { identifier: item.identifier, pageX: item.pageX, @@ -76,7 +66,10 @@ const getTouchEvent = ( export const getCustomEvent = ( type = '', oe: any = {}, - { detail = {}, layoutRef }: { detail?: Record; layoutRef: LayoutRef }, + { + detail = {}, + layoutRef + }: { detail?: Record; layoutRef: LayoutRef }, props: Props = {} ) => { const targetInfo = extendObject({}, oe.target, { @@ -95,6 +88,191 @@ export const getCustomEvent = ( }) } +const touchEventList = [ + { + eventName: 'onTouchStart', + handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { + handleTouchstart(e, 'bubble', ref, propsRef, config) + } + }, + { + eventName: 'onTouchMove', + handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { + handleTouchmove(e, 'bubble', ref, propsRef, config) + } + }, + { + eventName: 'onTouchEnd', + handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { + handleTouchend(e, 'bubble', ref, propsRef, config) + } + }, + { + eventName: 'onTouchCancel', + handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { + handleTouchcancel(e, 'bubble', ref, propsRef, config) + } + }, + { + eventName: 'onTouchStartCapture', + handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { + handleTouchstart(e, 'capture', ref, propsRef, config) + } + }, + { + eventName: 'onTouchMoveCapture', + handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { + handleTouchmove(e, 'capture', ref, propsRef, config) + } + }, + { + eventName: 'onTouchEndCapture', + handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { + handleTouchend(e, 'capture', ref, propsRef, config) + } + }, + { + eventName: 'onTouchCancelCapture', + handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { + handleTouchcancel(e, 'capture', ref, propsRef, config) + } + } +] + +function handleEmitEvent ( + events: string[], + type: string, + oe: NativeTouchEvent, + propsRef: Record, + config: UseInnerPropsConfig +) { + events.forEach((event) => { + if (propsRef.current[event]) { + const match = /^(catch|capture-catch):?(.*?)(?:\.(.*))?$/.exec(event) + if (match) { + oe.stopPropagation() + } + propsRef.current[event]( + getTouchEvent(type, oe, propsRef.current, config) + ) + } + }) +} + +function checkIsNeedPress (e: NativeTouchEvent, type: 'bubble' | 'capture', ref: RefObject) { + const tapDetailInfo = ref.current!.mpxPressInfo.detail || { x: 0, y: 0 } + const nativeEvent = e.nativeEvent + const currentPageX = nativeEvent.changedTouches[0].pageX + const currentPageY = nativeEvent.changedTouches[0].pageY + if ( + Math.abs(currentPageX - tapDetailInfo.x) > 1 || + Math.abs(currentPageY - tapDetailInfo.y) > 1 + ) { + ref.current!.needPress[type] = false + ref.current!.startTimer[type] && + clearTimeout(ref.current!.startTimer[type] as SetTimeoutReturnType) + ref.current!.startTimer[type] = null + } +} + +function handleTouchstart (e: NativeTouchEvent, type: 'bubble' | 'capture', ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) { + e.persist() + const bubbleTouchEvent = ['catchtouchstart', 'bindtouchstart'] + const bubblePressEvent = ['catchlongpress', 'bindlongpress'] + const captureTouchEvent = [ + 'capture-catchtouchstart', + 'capture-bindtouchstart' + ] + const capturePressEvent = [ + 'capture-catchlongpress', + 'capture-bindlongpress' + ] + ref.current!.startTimer[type] = null + ref.current!.needPress[type] = true + const nativeEvent = e.nativeEvent + ref.current!.mpxPressInfo.detail = { + x: nativeEvent.changedTouches[0].pageX, + y: nativeEvent.changedTouches[0].pageY + } + const currentTouchEvent = + type === 'bubble' ? bubbleTouchEvent : captureTouchEvent + const currentPressEvent = + type === 'bubble' ? bubblePressEvent : capturePressEvent + handleEmitEvent(currentTouchEvent, 'touchstart', e, propsRef, config) + const { + catchlongpress, + bindlongpress, + 'capture-catchlongpress': captureCatchlongpress, + 'capture-bindlongpress': captureBindlongpress + } = propsRef.current + if ( + catchlongpress || + bindlongpress || + captureCatchlongpress || + captureBindlongpress + ) { + ref.current!.startTimer[type] = setTimeout(() => { + ref.current!.needPress[type] = false + handleEmitEvent(currentPressEvent, 'longpress', e, propsRef, config) + }, 350) + } +} + +function handleTouchmove (e: NativeTouchEvent, type: 'bubble' | 'capture', ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) { + const bubbleTouchEvent = ['catchtouchmove', 'bindtouchmove'] + const captureTouchEvent = [ + 'capture-catchtouchmove', + 'capture-bindtouchmove' + ] + const currentTouchEvent = + type === 'bubble' ? bubbleTouchEvent : captureTouchEvent + handleEmitEvent(currentTouchEvent, 'touchmove', e, propsRef, config) + checkIsNeedPress(e, type, ref) +} + +function handleTouchend (e: NativeTouchEvent, type: 'bubble' | 'capture', ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) { + // move event may not be triggered + checkIsNeedPress(e, type, ref) + const bubbleTouchEvent = ['catchtouchend', 'bindtouchend'] + const bubbleTapEvent = ['catchtap', 'bindtap'] + const captureTouchEvent = [ + 'capture-catchtouchend', + 'capture-bindtouchend' + ] + const captureTapEvent = ['capture-catchtap', 'capture-bindtap'] + const currentTouchEvent = + type === 'bubble' ? bubbleTouchEvent : captureTouchEvent + const currentTapEvent = + type === 'bubble' ? bubbleTapEvent : captureTapEvent + ref.current!.startTimer[type] && + clearTimeout(ref.current!.startTimer[type] as SetTimeoutReturnType) + ref.current!.startTimer[type] = null + handleEmitEvent(currentTouchEvent, 'touchend', e, propsRef, config) + if (ref.current!.needPress[type]) { + if (type === 'bubble' && config.disableTap) { + return + } + handleEmitEvent(currentTapEvent, 'tap', e, propsRef, config) + } +} + +function handleTouchcancel ( + e: NativeTouchEvent, + type: 'bubble' | 'capture', + ref: RefObject, propsRef: Record, config: UseInnerPropsConfig +) { + const bubbleTouchEvent = ['catchtouchcancel', 'bindtouchcancel'] + const captureTouchEvent = [ + 'capture-catchtouchcancel', + 'capture-bindtouchcancel' + ] + const currentTouchEvent = + type === 'bubble' ? bubbleTouchEvent : captureTouchEvent + ref.current!.startTimer[type] && + clearTimeout(ref.current!.startTimer[type] as SetTimeoutReturnType) + ref.current!.startTimer[type] = null + handleEmitEvent(currentTouchEvent, 'touchcancel', e, propsRef, config) +} const useInnerProps = ( props: Props = {}, additionalProps: AdditionalProps = {}, @@ -120,7 +298,11 @@ const useInnerProps = ( const propsRef = useRef>({}) const eventConfig: { [key: string]: string[] } = {} - const config = rawConfig || { layoutRef: { current: {} }, disableTouch: false, disableTap: false } + const config = rawConfig || { + layoutRef: { current: {} }, + disableTouch: false, + disableTap: false + } const removeProps = [ 'children', 'enable-background', @@ -151,137 +333,6 @@ const useInnerProps = ( return omit(propsRef.current, removeProps) } const events = useMemo(() => { - const touchEventList = [{ - eventName: 'onTouchStart', - handler: (e: NativeTouchEvent) => { - handleTouchstart(e, 'bubble') - } - }, { - eventName: 'onTouchMove', - handler: (e: NativeTouchEvent) => { - handleTouchmove(e, 'bubble') - } - }, { - eventName: 'onTouchEnd', - handler: (e: NativeTouchEvent) => { - handleTouchend(e, 'bubble') - } - }, { - eventName: 'onTouchCancel', - handler: (e: NativeTouchEvent) => { - handleTouchcancel(e, 'bubble') - } - }, { - eventName: 'onTouchStartCapture', - handler: (e: NativeTouchEvent) => { - handleTouchstart(e, 'capture') - } - }, { - eventName: 'onTouchMoveCapture', - handler: (e: NativeTouchEvent) => { - handleTouchmove(e, 'capture') - } - }, { - eventName: 'onTouchEndCapture', - handler: (e: NativeTouchEvent) => { - handleTouchend(e, 'capture') - } - }, { - eventName: 'onTouchCancelCapture', - handler: (e: NativeTouchEvent) => { - handleTouchcancel(e, 'capture') - } - }] - - function handleEmitEvent ( - events: string[], - type: string, - oe: NativeTouchEvent - ) { - events.forEach(event => { - if (propsRef.current[event]) { - const match = /^(catch|capture-catch):?(.*?)(?:\.(.*))?$/.exec(event) - if (match) { - oe.stopPropagation() - } - propsRef.current[event](getTouchEvent(type, oe, propsRef.current, config)) - } - }) - } - - function checkIsNeedPress (e: NativeTouchEvent, type: 'bubble' | 'capture') { - const tapDetailInfo = ref.current.mpxPressInfo.detail || { x: 0, y: 0 } - const nativeEvent = e.nativeEvent - const currentPageX = nativeEvent.changedTouches[0].pageX - const currentPageY = nativeEvent.changedTouches[0].pageY - if (Math.abs(currentPageX - tapDetailInfo.x) > 1 || Math.abs(currentPageY - tapDetailInfo.y) > 1) { - ref.current.needPress[type] = false - ref.current.startTimer[type] && clearTimeout(ref.current.startTimer[type] as SetTimeoutReturnType) - ref.current.startTimer[type] = null - } - } - - function handleTouchstart (e: NativeTouchEvent, type: 'bubble' | 'capture') { - e.persist() - const bubbleTouchEvent = ['catchtouchstart', 'bindtouchstart'] - const bubblePressEvent = ['catchlongpress', 'bindlongpress'] - const captureTouchEvent = ['capture-catchtouchstart', 'capture-bindtouchstart'] - const capturePressEvent = ['capture-catchlongpress', 'capture-bindlongpress'] - ref.current.startTimer[type] = null - ref.current.needPress[type] = true - const nativeEvent = e.nativeEvent - ref.current.mpxPressInfo.detail = { - x: nativeEvent.changedTouches[0].pageX, - y: nativeEvent.changedTouches[0].pageY - } - const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent - const currentPressEvent = type === 'bubble' ? bubblePressEvent : capturePressEvent - handleEmitEvent(currentTouchEvent, 'touchstart', e) - const { catchlongpress, bindlongpress, 'capture-catchlongpress': captureCatchlongpress, 'capture-bindlongpress': captureBindlongpress } = propsRef.current - if (catchlongpress || bindlongpress || captureCatchlongpress || captureBindlongpress) { - ref.current.startTimer[type] = setTimeout(() => { - ref.current.needPress[type] = false - handleEmitEvent(currentPressEvent, 'longpress', e) - }, 350) - } - } - - function handleTouchmove (e: NativeTouchEvent, type: 'bubble' | 'capture') { - const bubbleTouchEvent = ['catchtouchmove', 'bindtouchmove'] - const captureTouchEvent = ['capture-catchtouchmove', 'capture-bindtouchmove'] - const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent - handleEmitEvent(currentTouchEvent, 'touchmove', e) - checkIsNeedPress(e, type) - } - - function handleTouchend (e: NativeTouchEvent, type: 'bubble' | 'capture') { - // move event may not be triggered - checkIsNeedPress(e, type) - const bubbleTouchEvent = ['catchtouchend', 'bindtouchend'] - const bubbleTapEvent = ['catchtap', 'bindtap'] - const captureTouchEvent = ['capture-catchtouchend', 'capture-bindtouchend'] - const captureTapEvent = ['capture-catchtap', 'capture-bindtap'] - const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent - const currentTapEvent = type === 'bubble' ? bubbleTapEvent : captureTapEvent - ref.current.startTimer[type] && clearTimeout(ref.current.startTimer[type] as SetTimeoutReturnType) - ref.current.startTimer[type] = null - handleEmitEvent(currentTouchEvent, 'touchend', e) - if (ref.current.needPress[type]) { - if (type === 'bubble' && config.disableTap) { - return - } - handleEmitEvent(currentTapEvent, 'tap', e) - } - } - - function handleTouchcancel (e: NativeTouchEvent, type: 'bubble' | 'capture') { - const bubbleTouchEvent = ['catchtouchcancel', 'bindtouchcancel'] - const captureTouchEvent = ['capture-catchtouchcancel', 'capture-bindtouchcancel'] - const currentTouchEvent = type === 'bubble' ? bubbleTouchEvent : captureTouchEvent - ref.current.startTimer[type] && clearTimeout(ref.current.startTimer[type] as SetTimeoutReturnType) - ref.current.startTimer[type] = null - handleEmitEvent(currentTouchEvent, 'touchcancel', e) - } const transformedEventKeys = rawEventKeys.reduce((acc: string[], key) => { if (propsRef.current[key]) { return acc.concat(eventConfig[key]) @@ -291,9 +342,10 @@ const useInnerProps = ( const finalEventKeys = [...new Set(transformedEventKeys)] const events: Record void> = {} - touchEventList.forEach(item => { + touchEventList.forEach((item) => { if (finalEventKeys.includes(item.eventName)) { - events[item.eventName] = item.handler + events[item.eventName] = (e: NativeTouchEvent) => + item.handler(e, ref, propsRef, config) } }) From 99ee2adb4923646d9ffdfb42717c82dfaaf9f065 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Mon, 9 Dec 2024 17:33:09 +0800 Subject: [PATCH 25/76] =?UTF-8?q?chore:=20=E4=BC=98=E5=8C=96=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/react/getInnerListeners.ts | 80 +++++++------------ 1 file changed, 29 insertions(+), 51 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts index 633204ebd7..468f3aaa40 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts @@ -88,57 +88,6 @@ export const getCustomEvent = ( }) } -const touchEventList = [ - { - eventName: 'onTouchStart', - handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { - handleTouchstart(e, 'bubble', ref, propsRef, config) - } - }, - { - eventName: 'onTouchMove', - handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { - handleTouchmove(e, 'bubble', ref, propsRef, config) - } - }, - { - eventName: 'onTouchEnd', - handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { - handleTouchend(e, 'bubble', ref, propsRef, config) - } - }, - { - eventName: 'onTouchCancel', - handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { - handleTouchcancel(e, 'bubble', ref, propsRef, config) - } - }, - { - eventName: 'onTouchStartCapture', - handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { - handleTouchstart(e, 'capture', ref, propsRef, config) - } - }, - { - eventName: 'onTouchMoveCapture', - handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { - handleTouchmove(e, 'capture', ref, propsRef, config) - } - }, - { - eventName: 'onTouchEndCapture', - handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { - handleTouchend(e, 'capture', ref, propsRef, config) - } - }, - { - eventName: 'onTouchCancelCapture', - handler: (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { - handleTouchcancel(e, 'capture', ref, propsRef, config) - } - } -] - function handleEmitEvent ( events: string[], type: string, @@ -273,6 +222,34 @@ function handleTouchcancel ( ref.current!.startTimer[type] = null handleEmitEvent(currentTouchEvent, 'touchcancel', e, propsRef, config) } + +function createTouchEventHandler (eventName: 'onTouchStart'|'onTouchMove'|'onTouchEnd'|'onTouchCancel', type: 'bubble' | 'capture') { + return (e: NativeTouchEvent, ref: RefObject, propsRef: Record, config: UseInnerPropsConfig) => { + const handlerMap = { + onTouchStart: handleTouchstart, + onTouchMove: handleTouchmove, + onTouchEnd: handleTouchend, + onTouchCancel: handleTouchcancel + } + + const handler = handlerMap[eventName] + if (handler) { + handler(e, type, ref, propsRef, config) + } + } +} + +const touchEventList = [ + { eventName: 'onTouchStart', handler: createTouchEventHandler('onTouchStart', 'bubble') }, + { eventName: 'onTouchMove', handler: createTouchEventHandler('onTouchMove', 'bubble') }, + { eventName: 'onTouchEnd', handler: createTouchEventHandler('onTouchEnd', 'bubble') }, + { eventName: 'onTouchCancel', handler: createTouchEventHandler('onTouchCancel', 'bubble') }, + { eventName: 'onTouchStartCapture', handler: createTouchEventHandler('onTouchStart', 'capture') }, + { eventName: 'onTouchMoveCapture', handler: createTouchEventHandler('onTouchMove', 'capture') }, + { eventName: 'onTouchEndCapture', handler: createTouchEventHandler('onTouchEnd', 'capture') }, + { eventName: 'onTouchCancelCapture', handler: createTouchEventHandler('onTouchCancel', 'capture') } +] + const useInnerProps = ( props: Props = {}, additionalProps: AdditionalProps = {}, @@ -332,6 +309,7 @@ const useInnerProps = ( if (!rawEventKeys.length || config.disableTouch) { return omit(propsRef.current, removeProps) } + const events = useMemo(() => { const transformedEventKeys = rawEventKeys.reduce((acc: string[], key) => { if (propsRef.current[key]) { From 9a2337972370c269e8db0a4f7a95784436259fb7 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Mon, 9 Dec 2024 20:01:22 +0800 Subject: [PATCH 26/76] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A0=87=E9=A2=98?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/components/react/mpx-web-view.tsx | 54 ++++++++++++------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 559d058f2a..4574e583c5 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -36,13 +36,14 @@ interface PayloadData { type MessageData = { payload?: PayloadData, type?: string, - callbackId?: number + callbackId?: number, + _documentTitle?: string } -const _WebView = forwardRef, WebViewProps>((props, ref): JSX.Element|null => { +const _WebView = forwardRef, WebViewProps>((props, ref): JSX.Element | null => { const { src, bindmessage, bindload, binderror } = props if (!src) { - return (null) + return null } if (props.style) { warn('The web-view component does not support the style prop.') @@ -83,19 +84,28 @@ const _WebView = forwardRef, WebViewProps>((pr } binderror(result) } - - const webViewTitle = useRef('') - const webViewUrl = useRef('') + const injectedJavaScript = ` + if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) { + var _documentTitle = document.title; + window.ReactNativeWebView.postMessage(JSON.stringify({ + _documentTitle: _documentTitle + })) + Object.defineProperty(document, 'title', { + set (val) { + _documentTitle = val + window.ReactNativeWebView.postMessage(JSON.stringify({ + _documentTitle: _documentTitle + })) + }, + get () { + return _documentTitle + } + }); + } + ` const _changeUrl = function (navState: WebViewNavigation) { if (navState.navigationType) { // navigationType这个事件在页面开始加载时和页面加载完成时都会被触发所以判断这个避免其他无效触发执行该逻辑 - if (webViewTitle.current !== navState.title) { - const navigation = getFocusedNavigation() - navigation && navigation.setOptions({ headerTitle: navState.title }) - } - if (currentPage && webViewUrl.current !== navState.url) { - webViewUrl.current = navState.url - currentPage.__webViewUrl = navState.url - } + currentPage.__webViewUrl = navState.url } } const _message = function (res: WebViewMessageEvent) { @@ -110,10 +120,15 @@ const _WebView = forwardRef, WebViewProps>((pr } catch (e) { data = {} } + const title = data._documentTitle + if (title) { + const navigation = getFocusedNavigation() + navigation && navigation.setOptions({ title }) + } const postData: PayloadData = data.payload || {} switch (data.type) { case 'postMessage': - bindmessage(getCustomEvent('messsage', {}, { // RN组件销毁顺序与小程序不一致,所以改成和支付宝消息一致 + bindmessage && bindmessage(getCustomEvent('messsage', {}, { // RN组件销毁顺序与小程序不一致,所以改成和支付宝消息一致 detail: { data: postData.data }, @@ -163,11 +178,9 @@ const _WebView = forwardRef, WebViewProps>((pr onError: _error }) } - if (bindmessage) { - extendObject(events, { - onMessage: _message - }) - } + extendObject(events, { + onMessage: _message + }) return ( , WebViewProps>((pr ref={webViewRef} {...events} onNavigationStateChange={_changeUrl} + injectedJavaScript={injectedJavaScript} javaScriptEnabled={true} > ) From af3d7c2e03a230f3c4cb36c0f4745dcb7fc8fd35 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Wed, 11 Dec 2024 11:17:16 +0800 Subject: [PATCH 27/76] =?UTF-8?q?=E6=8B=89=E9=BD=90=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/components/react/mpx-web-view.tsx | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 4574e583c5..13a54a193d 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -36,8 +36,7 @@ interface PayloadData { type MessageData = { payload?: PayloadData, type?: string, - callbackId?: number, - _documentTitle?: string + callbackId?: number } const _WebView = forwardRef, WebViewProps>((props, ref): JSX.Element | null => { @@ -88,13 +87,23 @@ const _WebView = forwardRef, WebViewProps>((pr if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) { var _documentTitle = document.title; window.ReactNativeWebView.postMessage(JSON.stringify({ - _documentTitle: _documentTitle + type: 'setTitle', + payload: { + data: { + _documentTitle: _documentTitle + } + } })) Object.defineProperty(document, 'title', { set (val) { _documentTitle = val window.ReactNativeWebView.postMessage(JSON.stringify({ - _documentTitle: _documentTitle + type: 'setTitle', + payload: { + data: { + _documentTitle: _documentTitle + } + } })) }, get () { @@ -120,13 +129,17 @@ const _WebView = forwardRef, WebViewProps>((pr } catch (e) { data = {} } - const title = data._documentTitle - if (title) { - const navigation = getFocusedNavigation() - navigation && navigation.setOptions({ title }) - } const postData: PayloadData = data.payload || {} switch (data.type) { + case 'setTitle': + { // case下不允许直接声明,包个块解决该问题 + const title = postData.data?._documentTitle + if (title) { + const navigation = getFocusedNavigation() + navigation && navigation.setOptions({ title }) + } + } + break case 'postMessage': bindmessage && bindmessage(getCustomEvent('messsage', {}, { // RN组件销毁顺序与小程序不一致,所以改成和支付宝消息一致 detail: { From 3b9d81faf5f28e63af473a082b4f346c2e13ef92 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Wed, 11 Dec 2024 11:50:41 +0800 Subject: [PATCH 28/76] =?UTF-8?q?chore:=20=E4=BC=98=E5=8C=96jsx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/components/react/mpx-button.tsx | 23 +++---- .../components/react/mpx-canvas/index.tsx | 35 +++++----- .../components/react/mpx-checkbox-group.tsx | 28 ++++---- .../runtime/components/react/mpx-checkbox.tsx | 66 +++++++++++++------ 4 files changed, 84 insertions(+), 68 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-button.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-button.tsx index 74d95812ff..004afef42c 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-button.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-button.tsx @@ -34,7 +34,7 @@ * ✘ bindagreeprivacyauthorization * ✔ bindtap */ -import { useEffect, useRef, useState, ReactNode, forwardRef, useContext, JSX } from 'react' +import { createElement, useEffect, useRef, useState, ReactNode, forwardRef, useContext, JSX } from 'react' import { View, StyleSheet, @@ -442,21 +442,16 @@ const Button = forwardRef, ButtonProps>((buttonPro } ) - return ( - - {loading && } + return createElement(View, innerProps, loading && createElement(Loading, { alone: !children }), + wrapChildren( + props, { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current, - textStyle, - textProps - } - ) + hasVarDec, + varContext: varContextRef.current, + textStyle, + textProps } - + ) ) }) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-canvas/index.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-canvas/index.tsx index 69075d99c5..47385974e1 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-canvas/index.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-canvas/index.tsx @@ -9,7 +9,7 @@ * ✔ bindlongtap * ✔ binderror */ -import React, { useRef, useState, useCallback, useEffect, forwardRef, JSX, TouchEvent, MutableRefObject } from 'react' +import React, { createElement, useRef, useState, useCallback, useEffect, forwardRef, JSX, TouchEvent, MutableRefObject } from 'react' import { View, Platform, StyleSheet, NativeSyntheticEvent } from 'react-native' import { WebView } from 'react-native-webview' import useNodesRef, { HandlerRef } from '../useNodesRef' @@ -277,26 +277,21 @@ const _Canvas = forwardRef, CanvasPr ) } - return ( - - { - if (canvasRef.current) { - canvasRef.current.webview = element - } - }} - style={[stylesheet.webview, { height, width }]} - source={{ html }} - originWhitelist={originWhitelist} - onMessage={onMessage} - onLoad={onLoad} - scrollEnabled={false} - /> - - ) + return createElement(View, innerProps, createElement(WebView, { + ref: (element) => { + if (canvasRef.current) { + canvasRef.current.webview = element + } + }, + style: [stylesheet.webview, { height, width }], + source: { html }, + originWhitelist: originWhitelist, + onMessage: onMessage, + onLoad: onLoad, + scrollEnabled: false + })) }) + _Canvas.displayName = 'mpxCanvas' export default _Canvas diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox-group.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox-group.tsx index fcdffee350..5c59d52f50 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox-group.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox-group.tsx @@ -8,7 +8,8 @@ import { ReactNode, useContext, useMemo, - useEffect + useEffect, + createElement } from 'react' import { View, @@ -156,20 +157,21 @@ const CheckboxGroup = forwardRef< notifyChange } }, []) - return ( - - + + return createElement( + View, + innerProps, + createElement( + CheckboxGroupContext.Provider, + { value: contextValue }, + wrapChildren( + props, { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current - } - ) + hasVarDec, + varContext: varContextRef.current } - - + ) + ) ) }) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox.tsx index 48aa98d273..53b796ef98 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox.tsx @@ -13,7 +13,8 @@ import { ReactNode, useContext, Dispatch, - SetStateAction + SetStateAction, + createElement } from 'react' import { View, @@ -206,28 +207,51 @@ const Checkbox = forwardRef, CheckboxProps>( } }, [checked]) - return ( - - - - + // return ( + // + // + // + // + // { + // wrapChildren( + // props, + // { + // hasVarDec, + // varContext: varContextRef.current, + // textStyle, + // textProps + // } + // ) + // } + // + // ) + return createElement( + View, + innerProps, + createElement( + View, + { style: defaultStyle }, // 内部 View 的样式 + createElement(Icon, { + type: 'success_no_circle', + size: 18, + color: disabled ? '#ADADAD' : color, + style: isChecked ? styles.iconChecked : styles.icon + }) + ), + wrapChildren( + props, { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current, - textStyle, - textProps - } - ) + hasVarDec, + varContext: varContextRef.current, + textStyle, + textProps } - + ) ) } ) From 147b32451eeddcea9b629bc03835468fcc4add85 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Wed, 11 Dec 2024 16:06:42 +0800 Subject: [PATCH 29/76] =?UTF-8?q?chore:=20=E4=BC=98=E5=8C=96jsx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/components/react/mpx-checkbox.tsx | 29 +-------- .../lib/runtime/components/react/mpx-form.tsx | 35 +++++----- .../lib/runtime/components/react/mpx-icon.tsx | 4 +- .../runtime/components/react/mpx-image.tsx | 56 ++++++++-------- .../runtime/components/react/mpx-input.tsx | 54 +++++++-------- .../runtime/components/react/mpx-label.tsx | 26 ++++---- .../components/react/mpx-movable-area.tsx | 26 +++----- .../components/react/mpx-movable-view.tsx | 65 ++++++++++++------- .../components/react/mpx-navigator.tsx | 10 +-- .../components/react/mpx-radio-group.tsx | 28 ++++---- .../runtime/components/react/mpx-radio.tsx | 44 ++++++------- .../components/react/mpx-root-portal.tsx | 8 +-- .../components/react/mpx-scroll-view.tsx | 46 ++++++------- .../runtime/components/react/mpx-switch.tsx | 34 +++++----- .../lib/runtime/components/react/mpx-text.tsx | 24 +++---- .../runtime/components/react/mpx-textarea.tsx | 21 +++--- .../lib/runtime/components/react/mpx-view.tsx | 15 ++--- .../runtime/components/react/mpx-web-view.tsx | 20 +++--- 18 files changed, 239 insertions(+), 306 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox.tsx index 53b796ef98..3da976c34f 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-checkbox.tsx @@ -207,35 +207,10 @@ const Checkbox = forwardRef, CheckboxProps>( } }, [checked]) - // return ( - // - // - // - // - // { - // wrapChildren( - // props, - // { - // hasVarDec, - // varContext: varContextRef.current, - // textStyle, - // textProps - // } - // ) - // } - // - // ) - return createElement( - View, - innerProps, + return createElement(View, innerProps, createElement( View, - { style: defaultStyle }, // 内部 View 的样式 + { style: defaultStyle }, createElement(Icon, { type: 'success_no_circle', size: 18, diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-form.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-form.tsx index defda9083f..100a321eae 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-form.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-form.tsx @@ -5,7 +5,7 @@ * ✔ bindreset */ import { View } from 'react-native' -import { JSX, useRef, forwardRef, ReactNode, useMemo, useCallback } from 'react' +import { JSX, useRef, forwardRef, ReactNode, useMemo, createElement } from 'react' import useNodesRef, { HandlerRef } from './useNodesRef' import useInnerProps, { getCustomEvent } from './getInnerListeners' import { FormContext } from './context' @@ -102,25 +102,20 @@ const _Form = forwardRef, FormProps>((fromProps: For reset } }, []) - return ( - - - { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current, - textStyle, - textProps - } - ) - } - - - ) + + return createElement(View, innerProps, createElement( + FormContext.Provider, + { value: contextValue }, + wrapChildren( + props, + { + hasVarDec, + varContext: varContextRef.current, + textStyle, + textProps + } + ) + )) }) _Form.displayName = 'MpxForm' diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-icon.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-icon.tsx index e26d89558b..d1a4edeceb 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-icon.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-icon.tsx @@ -3,7 +3,7 @@ * ✔ size * ✔ color */ -import { JSX, forwardRef, useRef } from 'react' +import { JSX, forwardRef, useRef, createElement } from 'react' import { Text, TextStyle, Image } from 'react-native' import useInnerProps from './getInnerListeners' import useNodesRef, { HandlerRef } from './useNodesRef' @@ -93,7 +93,7 @@ const Icon = forwardRef, IconProps>( } ) - return + return createElement(Image, innerProps) } ) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-image.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-image.tsx index 85d815a4f7..12d83640ff 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-image.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-image.tsx @@ -10,7 +10,7 @@ * ✔ bindtap * ✔ DEFAULT_SIZE */ -import { useEffect, useMemo, useState, useRef, forwardRef } from 'react' +import { useEffect, useMemo, useState, useRef, forwardRef, createElement } from 'react' import { Image as RNImage, View, @@ -359,35 +359,31 @@ const Image = forwardRef, ImageProps>((props, re } ) - return ( - - { - isSvg - ? - : - } - + return createElement(View, innerProps, + isSvg + ? createElement(SvgCssUri, { + uri: src, + onLayout: onSvgLoad, + onError: binderror && onSvgError, + style: extendObject( + { transformOrigin: 'top left' }, + modeStyle + ) + }) + : createElement(RNImage, { + source: { uri: src }, + resizeMode: resizeMode, + onLoad: bindload && onImageLoad, + onError: binderror && onImageError, + style: extendObject( + { + transformOrigin: 'top left', + width: isCropMode ? imageWidth : '100%', + height: isCropMode ? imageHeight : '100%' + }, + isCropMode ? modeStyle : {} + ) + }) ) }) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-input.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-input.tsx index e8a466affd..71196c3e13 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-input.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-input.tsx @@ -37,7 +37,7 @@ * ✘ bind:keyboardcompositionend * ✘ bind:onkeyboardheightchange */ -import { JSX, forwardRef, useMemo, useRef, useState, useContext, useEffect } from 'react' +import { JSX, forwardRef, useMemo, useRef, useState, useContext, useEffect, createElement } from 'react' import { KeyboardTypeOptions, Platform, @@ -405,7 +405,22 @@ const Input = forwardRef, FinalInputProps { ref: nodeRef, style: extendObject({}, normalStyle, layoutStyle), - allowFontScaling + allowFontScaling, + keyboardType: keyboardType, + secureTextEntry: !!password, + defaultValue: defaultValue, + value: inputValue, + maxLength: maxlength === -1 ? undefined : maxlength, + editable: !disabled, + autoFocus: !!autoFocus || !!focus, + returnKeyType: confirmType, + selection: selection, + selectionColor: cursorColor, + blurOnSubmit: !multiline && !confirmHold, + underlineColorAndroid: 'rgba(0,0,0,0)', + textAlignVertical: textAlignVertical, + placeholderTextColor: placeholderTextColor, + multiline: !!multiline }, layoutProps, { @@ -413,16 +428,17 @@ const Input = forwardRef, FinalInputProps onBlur: bindblur && onInputBlur, onKeyPress: bindconfirm && onKeyPress, onSubmitEditing: bindconfirm && multiline && onSubmitEditing, - onSelectionChange: bindselectionchange && onSelectionChange + onSelectionChange: bindselectionchange && onSelectionChange, + onTextInput: onTextInput, + onChange: onChange, + onContentSizeChange: onContentSizeChange } ), [ 'type', - 'keyboardType', 'password', 'placeholder-style', 'disabled', - 'maxlength', 'auto-focus', 'focus', 'confirm-type', @@ -430,37 +446,13 @@ const Input = forwardRef, FinalInputProps 'cursor', 'cursor-color', 'selection-start', - 'selection-end', - 'multiline' + 'selection-end' ], { layoutRef } ) - - return ( - - ) + return createElement(TextInput, innerProps) }) Input.displayName = 'MpxInput' diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-label.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-label.tsx index 4c4eb5879c..4ef3fe16ae 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-label.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-label.tsx @@ -1,7 +1,7 @@ /** * ✘ for */ -import { JSX, useRef, forwardRef, ReactNode, useCallback } from 'react' +import { JSX, useRef, forwardRef, ReactNode, useCallback, createElement } from 'react' import { View, ViewStyle, NativeSyntheticEvent } from 'react-native' import { noop, warn } from '@mpxjs/utils' import useInnerProps, { getCustomEvent } from './getInnerListeners' @@ -92,21 +92,19 @@ const Label = forwardRef, LabelProps>( } ) - return - + return createElement(View, innerProps, createElement( + LabelContext.Provider, + { value: contextRef }, + wrapChildren( + props, { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current, - textStyle, - textProps - } - ) + hasVarDec, + varContext: varContextRef.current, + textStyle, + textProps } - - + ) + )) } ) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-area.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-area.tsx index b354fc3591..3e937be817 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-area.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-area.tsx @@ -3,7 +3,7 @@ */ import { View } from 'react-native' -import { JSX, forwardRef, ReactNode, useRef, useMemo } from 'react' +import { JSX, forwardRef, ReactNode, useRef, useMemo, createElement } from 'react' import useNodesRef, { HandlerRef } from './useNodesRef' import useInnerProps from './getInnerListeners' import { MovableAreaContext } from './context' @@ -51,23 +51,17 @@ const _MovableArea = forwardRef, MovableAreaP ref: movableViewRef }, layoutProps), [], { layoutRef }) - return ( - - + return createElement(MovableAreaContext.Provider, { value: contextValue }, createElement( + View, + innerProps, + wrapChildren( + props, { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current - } - ) + hasVarDec, + varContext: varContextRef.current } - - - ) + ) + )) }) _MovableArea.displayName = 'MpxMovableArea' diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-view.tsx index a5b29a9a37..0243b04c68 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-view.tsx @@ -17,12 +17,12 @@ * ✔ htouchmove * ✔ vtouchmove */ -import { useEffect, forwardRef, ReactNode, useContext, useCallback, useRef, useMemo } from 'react' +import { useEffect, forwardRef, ReactNode, useContext, useCallback, useRef, useMemo, createElement } from 'react' import { StyleSheet, NativeSyntheticEvent, View, LayoutChangeEvent } from 'react-native' import { getCustomEvent } from './getInnerListeners' import useNodesRef, { HandlerRef } from './useNodesRef' import { MovableAreaContext } from './context' -import { useTransformStyle, splitProps, splitStyle, HIDDEN_STYLE, wrapChildren, GestureHandler, flatGesture } from './utils' +import { useTransformStyle, splitProps, splitStyle, HIDDEN_STYLE, wrapChildren, GestureHandler, flatGesture, extendObject } from './utils' import { GestureDetector, Gesture, GestureTouchEvent, GestureStateChangeEvent, PanGestureHandlerEventPayload, PanGesture } from 'react-native-gesture-handler' import Animated, { useSharedValue, @@ -518,28 +518,45 @@ const _MovableView = forwardRef, MovableViewP const catchEventHandlers = injectCatchEvent(props) const layoutStyle = !hasLayoutRef.current && hasSelfPercent ? HIDDEN_STYLE : {} - return ( - - - { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current, - textStyle, - textProps - } - ) - } - - - ) + // return ( + // + // + // { + // wrapChildren( + // props, + // { + // hasVarDec, + // varContext: varContextRef.current, + // textStyle, + // textProps + // } + // ) + // } + // + // + // ) + return createElement(GestureDetector, { gesture: gesture }, createElement( + Animated.View, + extendObject({ + ref: nodeRef, + onLayout: onLayout, + style: [innerStyle, animatedStyles, layoutStyle] + }, catchEventHandlers), + wrapChildren( + props, + { + hasVarDec, + varContext: varContextRef.current, + textStyle, + textProps + } + ) + )) }) _MovableView.displayName = 'MpxMovableView' diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-navigator.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-navigator.tsx index 90d3465f44..3de5cfd553 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-navigator.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-navigator.tsx @@ -8,7 +8,7 @@ * ✔ delta */ import { View } from 'react-native' -import { useCallback, forwardRef, JSX } from 'react' +import { useCallback, forwardRef, JSX, createElement } from 'react' import useInnerProps from './getInnerListeners' import { redirectTo, navigateTo, navigateBack, reLaunch, switchTab } from '@mpxjs/api-proxy' @@ -53,13 +53,7 @@ const _Navigator = forwardRef((props, ref): JSX.Element = bindtap: handleClick }) - return ( - - {children} - - ) + return createElement(MpxView, innerProps, children) }) _Navigator.displayName = 'MpxNavigator' diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-radio-group.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-radio-group.tsx index 5ded44937e..2c1c35db03 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-radio-group.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-radio-group.tsx @@ -8,7 +8,8 @@ import { ReactNode, useContext, useMemo, - useEffect + useEffect, + createElement } from 'react' import { View, @@ -154,20 +155,17 @@ const radioGroup = forwardRef< } ) - return ( - - - { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current - } - ) - } - - + return createElement(View, innerProps, createElement( + RadioGroupContext.Provider, + { value: contextValue }, + wrapChildren( + props, + { + hasVarDec, + varContext: varContextRef.current + } + ) + ) ) }) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-radio.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-radio.tsx index c1662f5cc8..dd760fcec0 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-radio.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-radio.tsx @@ -4,7 +4,7 @@ * ✔ checked * ✔ color */ -import { JSX, useRef, useState, forwardRef, useEffect, ReactNode, useContext, Dispatch, SetStateAction } from 'react' +import { JSX, useRef, useState, forwardRef, useEffect, ReactNode, useContext, Dispatch, SetStateAction, createElement } from 'react' import { View, StyleSheet, ViewStyle, NativeSyntheticEvent } from 'react-native' import { warn } from '@mpxjs/utils' import { LabelContext, RadioGroupContext } from './context' @@ -193,32 +193,26 @@ const Radio = forwardRef, RadioProps>( } }, [checked]) - return ( - - - - + return createElement(View, innerProps, + createElement( + View, + { style: defaultStyle }, + createElement(Icon, { + type: 'success', + size: 24, + color: disabled ? '#E1E1E1' : color, + style: extendObject({}, styles.icon, isChecked && styles.iconChecked, disabled && styles.iconDisabled) + }) + ), + wrapChildren( + props, { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current, - textStyle, - textProps - } - ) + hasVarDec, + varContext: varContextRef.current, + textStyle, + textProps } - + ) ) } ) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-root-portal.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-root-portal.tsx index 46827be068..7c5d53769d 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-root-portal.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-root-portal.tsx @@ -1,7 +1,7 @@ /** * ✔ enable */ -import { ReactNode } from 'react' +import { ReactNode, createElement, Fragment } from 'react' import { Portal } from '@ant-design/react-native' import { warn } from '@mpxjs/utils' interface RootPortalProps { @@ -16,10 +16,8 @@ const _RootPortal = (props: RootPortalProps) => { warn('The root-portal component does not support the style prop.') } return enable - ? - {children} - - : <>{children} + ? createElement(Portal, null, children) + : createElement(Fragment, null, children) } _RootPortal.displayName = 'MpxRootPortal' diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx index 17f45a6e41..c52dc960ff 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx @@ -33,7 +33,7 @@ */ import { ScrollView } from 'react-native-gesture-handler' import { View, RefreshControl, NativeSyntheticEvent, NativeScrollEvent, LayoutChangeEvent, ViewStyle } from 'react-native' -import { JSX, ReactNode, RefObject, useRef, useState, useEffect, forwardRef, useContext } from 'react' +import { JSX, ReactNode, RefObject, useRef, useState, useEffect, forwardRef, useContext, createElement } from 'react' import { useAnimatedRef } from 'react-native-reanimated' import { warn } from '@mpxjs/utils' import useInnerProps, { getCustomEvent } from './getInnerListeners' @@ -491,32 +491,26 @@ const _ScrollView = forwardRef, S white: ['#fff'] } - return ( - - ) - : undefined} - > - { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current, - textStyle, - textProps - } - ) + return createElement( + ScrollView, + extendObject({}, innerProps, { + refreshControl: refresherEnabled + ? createElement(RefreshControl, extendObject({ + progressBackgroundColor: refresherBackground, + refreshing: refreshing, + onRefresh: onRefresh + }, (refresherDefaultStyle && refresherDefaultStyle !== 'none' ? { colors: refreshColor[refresherDefaultStyle] } : null))) + : undefined + }), + wrapChildren( + props, + { + hasVarDec, + varContext: varContextRef.current, + textStyle, + textProps } - + ) ) }) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-switch.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-switch.tsx index 026424c30c..7a1c008071 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-switch.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-switch.tsx @@ -5,7 +5,7 @@ * ✔ color */ import { Switch, SwitchProps, ViewStyle, NativeSyntheticEvent } from 'react-native' -import { useRef, useEffect, forwardRef, JSX, useState, useContext } from 'react' +import { useRef, useEffect, forwardRef, JSX, useState, useContext, createElement } from 'react' import { warn } from '@mpxjs/utils' import useNodesRef, { HandlerRef } from './useNodesRef' // 引入辅助函数 import useInnerProps, { getCustomEvent } from './getInnerListeners' @@ -136,22 +136,26 @@ const _Switch = forwardRef, _SwitchProps>((prop }) if (type === 'checkbox') { - return + return createElement( + CheckBox, + extendObject({}, innerProps, { + color: color, + style: normalStyle, + checked: isChecked + }) + ) } - return + return createElement( + Switch, + extendObject({}, innerProps, { + style: normalStyle, + value: isChecked, + trackColor: { false: '#FFF', true: color }, + thumbColor: isChecked ? '#FFF' : '#f4f3f4', + ios_backgroundColor: '#FFF' + }) + ) }) _Switch.displayName = 'MpxSwitch' diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-text.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-text.tsx index 6962dc9657..e3364de844 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-text.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-text.tsx @@ -5,7 +5,7 @@ * ✘ decode */ import { Text, TextStyle, TextProps } from 'react-native' -import { useRef, forwardRef, ReactNode, JSX } from 'react' +import { useRef, forwardRef, ReactNode, JSX, createElement } from 'react' import useInnerProps from './getInnerListeners' import useNodesRef, { HandlerRef } from './useNodesRef' // 引入辅助函数 import { useTransformStyle, wrapChildren } from './utils' @@ -65,21 +65,13 @@ const _Text = forwardRef, _TextProps>((props, ref): layoutRef }) - return ( - - { - wrapChildren( - props, - { - hasVarDec, - varContext: varContextRef.current - } - ) - } - - ) + return createElement(Text, innerProps, wrapChildren( + props, + { + hasVarDec, + varContext: varContextRef.current + } + )) }) _Text.displayName = 'MpxText' diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-textarea.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-textarea.tsx index 35bb8403e5..24e5907be5 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-textarea.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-textarea.tsx @@ -9,10 +9,10 @@ * ✘ show-confirm-bar * ✔ bindlinechange: No `heightRpx` info. */ -import { JSX, forwardRef } from 'react' +import { JSX, forwardRef, createElement } from 'react' import { Keyboard, TextInput } from 'react-native' import Input, { InputProps, PrivateInputProps } from './mpx-input' -import { omit } from './utils' +import { omit, extendObject } from './utils' import { HandlerRef } from './useNodesRef' export type TextareProps = Omit< @@ -29,14 +29,15 @@ const Textarea = forwardRef, TextareProps>( 'multiline', 'confirm-hold' ]) - return ( - Keyboard.dismiss()} - {...restProps} - /> + + return createElement( + Input, + extendObject({ + ref: ref, + multiline: true, + confirmType: 'next', + bindblur: () => Keyboard.dismiss() + }, restProps) ) } ) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx index 42b9d0a077..e419c7314c 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx @@ -5,7 +5,7 @@ * ✔ hover-stay-time */ import { View, TextStyle, NativeSyntheticEvent, ViewProps, ImageStyle, StyleSheet, Image, LayoutChangeEvent } from 'react-native' -import { useRef, useState, useEffect, forwardRef, ReactNode, JSX } from 'react' +import { useRef, useState, useEffect, forwardRef, ReactNode, JSX, createElement } from 'react' import useInnerProps from './getInnerListeners' import Animated from 'react-native-reanimated' import useAnimationHooks from './useAnimationHooks' @@ -814,17 +814,10 @@ const _View = forwardRef, _ViewProps>((viewProps, r innerStyle, enableFastImage }) + return enableAnimation - ? ( - {childNode} - ) - : ( - {childNode} - ) + ? createElement(Animated.View, innerProps, childNode) + : createElement(View, innerProps, childNode) }) _View.displayName = 'MpxView' diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 79038d756a..d205fdc4e3 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -1,4 +1,4 @@ -import { forwardRef, JSX, useEffect, useRef, useContext, useMemo } from 'react' +import { forwardRef, JSX, useEffect, useRef, useContext, useMemo, createElement } from 'react' import { noop, warn } from '@mpxjs/utils' import { View } from 'react-native' import { Portal } from '@ant-design/react-native' @@ -177,16 +177,14 @@ const _WebView = forwardRef, WebViewProps>((pr onMessage: _message }) } - return ( - - ) + + return createElement(Portal, null, createElement(WebView, extendObject({ + style: defaultWebViewStyle, + source: { uri: src }, + ref: webViewRef, + javaScriptEnabled: true, + onNavigationStateChange: _changeUrl + }, events))) }) _WebView.displayName = 'MpxWebview' From 241a85e9891f7c7e1015a5e2a97d9de4f0a78cc6 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 12 Dec 2024 14:42:33 +0800 Subject: [PATCH 30/76] =?UTF-8?q?=E5=85=88=E6=94=B9=E4=B8=80=E7=89=88?= =?UTF-8?q?=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/runtime/components/react/mpx-web-view.tsx | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 13a54a193d..b1e1425283 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -30,7 +30,7 @@ interface WebViewProps { } interface PayloadData { - data?: Record + [x: string]: any } type MessageData = { @@ -89,9 +89,7 @@ const _WebView = forwardRef, WebViewProps>((pr window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'setTitle', payload: { - data: { - _documentTitle: _documentTitle - } + _documentTitle: _documentTitle } })) Object.defineProperty(document, 'title', { @@ -100,9 +98,7 @@ const _WebView = forwardRef, WebViewProps>((pr window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'setTitle', payload: { - data: { - _documentTitle: _documentTitle - } + _documentTitle: _documentTitle } })) }, @@ -133,7 +129,7 @@ const _WebView = forwardRef, WebViewProps>((pr switch (data.type) { case 'setTitle': { // case下不允许直接声明,包个块解决该问题 - const title = postData.data?._documentTitle + const title = postData._documentTitle if (title) { const navigation = getFocusedNavigation() navigation && navigation.setOptions({ title }) From 00ca1dff40a7a7f0ba310c9d9ee049ee591b5c6a Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 12 Dec 2024 18:21:56 +0800 Subject: [PATCH 31/76] =?UTF-8?q?=E4=BF=AE=E6=94=B9web=E5=92=8Crn=E7=9A=84?= =?UTF-8?q?webview=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/mpx-webview/H5/webviewbridge.min.js | 4 +- .../runtime/components/react/mpx-web-view.tsx | 20 +++++- .../runtime/components/web/mpx-web-view.vue | 62 ++++++++----------- .../dist/webviewbridge.esm.browser.js | 19 +----- .../dist/webviewbridge.esm.browser.min.js | 4 +- .../webview-bridge/dist/webviewbridge.esm.js | 18 +----- packages/webview-bridge/dist/webviewbridge.js | 18 +----- .../webview-bridge/dist/webviewbridge.min.js | 4 +- packages/webview-bridge/src/index.js | 17 +---- 9 files changed, 60 insertions(+), 106 deletions(-) diff --git a/examples/mpx-webview/H5/webviewbridge.min.js b/examples/mpx-webview/H5/webviewbridge.min.js index b94c23c965..9dac705da4 100644 --- a/examples/mpx-webview/H5/webviewbridge.min.js +++ b/examples/mpx-webview/H5/webviewbridge.min.js @@ -1,6 +1,6 @@ /** - * mpxjs webview bridge v2.9.53 + * mpxjs webview bridge v2.9.58 * (c) 2024 @mpxjs team * @license Apache */ -var e,t;e=this,t=function(){"use strict";function e(e,t,o){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var n=o.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function t(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,n)}return o}var o,n,a,r,i=function(o){for(var n=1;n-1&&g.indexOf("MiniProgram")>-1?c="my":g.toLowerCase().indexOf("miniprogram")>-1?c=g.indexOf("QQ")>-1?"qq":"wx":g.indexOf("swan/")>-1?c="swan":g.indexOf("toutiao")>-1?c="tt":(c="web",window.addEventListener("message",(function(e){var t=e.data,o=t;try{"string"==typeof t&&(o=JSON.parse(t))}catch(e){}var n=o,a=n.callbackId,r=n.error,i=n.result;void 0!==a&&d[a]&&(r?d[a](r):d[a](null,i),delete d[a])}),!1));var u=!1;function w(e){u?e():o.then((function(){u=!0,e()}))}var l={config:function(e){"wx"===c?w((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function f(e){if("[object Object]"!==Object.prototype.toString.call(e))return e;var t={};for(var o in e)"function"!=typeof e[o]&&(t[o]=e[o]);return t}function m(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("getEnv"!==e){var o=++s;d[o]=function(e,n){e?(t.fail&&t.fail(e),t.complete&&t.complete(e)):(t.success&&t.success(n),t.complete&&t.complete(n)),delete d[o]};var n={type:e,callbackId:s,payload:f(t)};void 0!==p&&(n.clientUid=p),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(n)):window.parent.postMessage&&window.parent.postMessage(n,"*")}else t({webapp:!0})}var v=function(){var e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[c]||{},t={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation"],tt:[]}[c]||[];(e.api||[]).forEach((function(t){l[t]=function(){for(var o=arguments.length,n=new Array(o),a=0;a1&&void 0!==arguments[1]?arguments[1]:{},o=t.time,n=void 0===o?5e3:o,a=t.crossOrigin,r=void 0!==a&&a;function i(){return new Promise((function(t,o){var n=document.createElement("script");n.type="text/javascript",n.async="async",r&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(t(),n.onload=n.onreadystatechange=null)},n.onerror=function(){o(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(t,o){setTimeout((function(){o(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([i(),c()])}(i[c].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),v(),l},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).mpx=t(); \ No newline at end of file +var e,t;e=this,t=function(){"use strict";function e(e,t,o){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var n=o.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function t(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,n)}return o}var o,n,a,r,i=function(o){for(var n=1;n-1&&g.indexOf("MiniProgram")>-1?c="my":g.toLowerCase().indexOf("miniprogram")>-1?c=g.indexOf("QQ")>-1?"qq":"wx":g.indexOf("swan/")>-1?c="swan":g.indexOf("toutiao")>-1?c="tt":(c="web",window.addEventListener("message",(function(e){var t=e.data,o=t;try{"string"==typeof t&&(o=JSON.parse(t))}catch(e){}var n=o,a=n.callbackId,r=n.error,i=n.result;void 0!==a&&d[a]&&(r?d[a](r):d[a](null,i),delete d[a])}),!1));var w=!1;function u(e){w?e():o.then((function(){w=!0,e()}))}var l={config:function(e){"wx"===c?u((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function f(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("getEnv"!==e){var o=++s;d[o]=function(e,n){e?(t.fail&&t.fail(e),t.complete&&t.complete(e)):(t.success&&t.success(n),t.complete&&t.complete(n)),delete d[o]};var n={type:e,callbackId:s,payload:t};void 0!==p&&(n.clientUid=p),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(n)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(n),"*")}else t({webapp:!0})}var m=function(){var e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[c]||{},t={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation"],tt:[]}[c]||[];(e.api||[]).forEach((function(t){l[t]=function(){for(var o=arguments.length,n=new Array(o),a=0;a1&&void 0!==arguments[1]?arguments[1]:{},o=t.time,n=void 0===o?5e3:o,a=t.crossOrigin,r=void 0!==a&&a;function i(){return new Promise((function(t,o){var n=document.createElement("script");n.type="text/javascript",n.async="async",r&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(t(),n.onload=n.onreadystatechange=null)},n.onerror=function(){o(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(t,o){setTimeout((function(){o(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([i(),c()])}(i[c].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),m(),l},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).mpx=t(); \ No newline at end of file diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index b1e1425283..7e0c17d01e 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -41,6 +41,7 @@ type MessageData = { const _WebView = forwardRef, WebViewProps>((props, ref): JSX.Element | null => { const { src, bindmessage, bindload, binderror } = props + const mpx = global.__mpx if (!src) { return null } @@ -126,7 +127,8 @@ const _WebView = forwardRef, WebViewProps>((pr data = {} } const postData: PayloadData = data.payload || {} - switch (data.type) { + const type = data.type + switch (type) { case 'setTitle': { // case下不允许直接声明,包个块解决该问题 const title = postData._documentTitle @@ -162,12 +164,26 @@ const _WebView = forwardRef, WebViewProps>((pr case 'reLaunch': asyncCallback = navObj.reLaunch(postData) break + default: + if (type) { + const commonMethod = mpx.config.webviewConfig.apiImplementations && mpx.config.webviewConfig.apiImplementations[type] + if (commonMethod) { + const result = commonMethod() + asyncCallback = Promise.resolve(result) + } else { + /* eslint-disable prefer-promise-reject-errors */ + asyncCallback = Promise.reject({ + errMsg: `未在apiImplementations中配置${type}方法` + }) + } + } + break } asyncCallback && asyncCallback.then((res: any) => { if (webViewRef.current?.postMessage) { const test = JSON.stringify({ - type: data.type, + type: type, callbackId: data.callbackId, result: res }) diff --git a/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue b/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue index ed83d5efd0..0a10455b37 100644 --- a/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue +++ b/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue @@ -72,37 +72,17 @@ immediate: true } }, - beforeCreate () { - this.messageList = [] - }, mounted () { window.addEventListener('message', this.messageCallback) }, - deactivated () { - if (!this.messageList.length) { - return - } - let data = { - type: 'message', - data: this.messageList - } - this.$emit(eventMessage, getCustomEvent(eventMessage, data, this)) - }, - destroyed () { - window.removeEventListener('message', this.messageCallback) - if (!this.messageList.length) { - return - } - let data = { - type: 'message', - data: this.messageList - } - this.$emit(eventMessage, getCustomEvent(eventMessage, data, this)) - }, methods: { messageCallback (event) { const hostValidate = this.hostValidate(event.origin) - const data = event.data + let data = {} + try { + const eventData = event.data + data = typeof eventData === 'string' ? JSON.parse(eventData) : eventData + } catch(e){} // 判断number类型,防止undefined导致触发return逻辑 if (data.clientUid !== undefined && +data.clientUid !== this._uid) { return @@ -112,9 +92,14 @@ return } let asyncCallback = null - switch (data.type) { + const type = data.type + switch (type) { case 'postMessage': - this.messageList.push(value.data || value) + let data = { + type: 'message', + data: value.data || value + } + this.$emit(eventMessage, getCustomEvent(eventMessage, data, this)) asyncCallback = Promise.resolve({ errMsg: 'invokeWebappApi:ok' }) @@ -134,26 +119,29 @@ case 'reLaunch': asyncCallback = navObj.reLaunch(value) break - case 'getLocation': - const getLocation = mpx.config.webviewConfig.apiImplementations && mpx.config.webviewConfig.apiImplementations.getLocation - if (getLocation) { - asyncCallback = getLocation() - } else { - asyncCallback = Promise.reject({ - errMsg: '未在apiImplementations中配置getLocation方法' - }) + default: + if (type) { + const commonMethod = mpx.config.webviewConfig.apiImplementations && mpx.config.webviewConfig.apiImplementations[type] + if (commonMethod) { + const result = commonMethod() + asyncCallback = Promise.resolve(result) + } else { + asyncCallback = Promise.reject({ + errMsg: `未在apiImplementations中配置${data.type}方法` + }) + } } break } asyncCallback && asyncCallback.then((res) => { this.mpxIframe && this.mpxIframe.contentWindow && this.mpxIframe.contentWindow.postMessage && this.mpxIframe.contentWindow.postMessage({ - type: data.type, + type: type, callbackId: data.callbackId, result: res }, event.origin) }).catch((error) => { this.mpxIframe && this.mpxIframe.contentWindow && this.mpxIframe.contentWindow.postMessage && this.mpxIframe.contentWindow.postMessage({ - type: data.type, + type: type, callbackId: data.callbackId, error }, event.origin) diff --git a/packages/webview-bridge/dist/webviewbridge.esm.browser.js b/packages/webview-bridge/dist/webviewbridge.esm.browser.js index 903ba156fa..3ad4a9e63e 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.browser.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.browser.js @@ -1,5 +1,5 @@ /** - * mpxjs webview bridge v2.9.53 + * mpxjs webview bridge v2.9.58 * (c) 2024 @mpxjs team * @license Apache */ @@ -141,19 +141,6 @@ const webviewBridge = { } }; -function filterData (data) { - if (Object.prototype.toString.call(data) !== '[object Object]') { - return data - } - const newData = {}; - for (const item in data) { - if (typeof data[item] !== 'function') { - newData[item] = data[item]; - } - } - return newData -} - function postMessage (type, data = {}) { if (type !== 'getEnv') { const currentCallbackId = ++callbackId; @@ -170,7 +157,7 @@ function postMessage (type, data = {}) { const postParams = { type, callbackId, - payload: filterData(data) + payload: data }; if (clientUid !== undefined) { postParams.clientUid = clientUid; @@ -178,7 +165,7 @@ function postMessage (type, data = {}) { if (window.ReactNativeWebView) { window.ReactNativeWebView.postMessage && window.ReactNativeWebView.postMessage(JSON.stringify(postParams)); } else { - window.parent.postMessage && window.parent.postMessage(postParams, '*'); + window.parent.postMessage && window.parent.postMessage(JSON.stringify(postParams), '*'); } } else { data({ diff --git a/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js b/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js index f707ba49bf..019f5df46b 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js @@ -1,6 +1,6 @@ /** - * mpxjs webview bridge v2.9.53 + * mpxjs webview bridge v2.9.58 * (c) 2024 @mpxjs team * @license Apache */ -let e;const o={wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"},...window.sdkUrlMap};let t=null,a=0;const n=function(){const e=location.href,o=/mpx_webview_id=(\d+)/g.exec(e);let t;return o&&o[1]&&(t=+o[1]),t}(),i={},s=navigator.userAgent;s.indexOf("AlipayClient")>-1&&s.indexOf("MiniProgram")>-1?t="my":s.toLowerCase().indexOf("miniprogram")>-1?t=s.indexOf("QQ")>-1?"qq":"wx":s.indexOf("swan/")>-1?t="swan":s.indexOf("toutiao")>-1?t="tt":(t="web",window.addEventListener("message",e=>{const o=e.data;let t=o;try{"string"==typeof o&&(t=JSON.parse(o))}catch(e){}const{callbackId:a,error:n,result:s}=t;void 0!==a&&i[a]&&(n?i[a](n):i[a](null,s),delete i[a])},!1));let r=!1;function c(o){r?o():e.then(()=>{r=!0,o()})}const d={config(e){"wx"===t?c(()=>{window.wx&&window.wx.config(e)}):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function w(e){if("[object Object]"!==Object.prototype.toString.call(e))return e;const o={};for(const t in e)"function"!=typeof e[t]&&(o[t]=e[t]);return o}const g=()=>{const e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[t]||{},o={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation"],tt:[]}[t]||[];(e.api||[]).forEach(o=>{d[o]=(...a)=>{c(()=>{window[t][e.keyName][o](...a)})}}),o.forEach(e=>{d[e]=(...o)=>{"web"===t?function(e,o={}){if("getEnv"!==e){const t=++a;i[t]=(e,a)=>{e?(o.fail&&o.fail(e),o.complete&&o.complete(e)):(o.success&&o.success(a),o.complete&&o.complete(a)),delete i[t]};const s={type:e,callbackId:a,payload:w(o)};void 0!==n&&(s.clientUid=n),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(s)):window.parent.postMessage&&window.parent.postMessage(s,"*")}else o({webapp:!0})}(e,...o):c("wx"===t?()=>{window[t]&&window[t].ready(()=>{window[t][e](...o)})}:()=>{window[t][e](...o)})}})};e="web"!==t?o[t].url?function(e,{time:o=5e3,crossOrigin:t=!1}={}){return Promise.race([new Promise((o,a)=>{const n=document.createElement("script");n.type="text/javascript",n.async="async",t&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){a(new Error(`load ${e} error`)),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}),new Promise((t,a)=>{setTimeout(()=>{a(new Error(`load ${e} timeout`))},o)})])}(o[t].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),g();export default d; \ No newline at end of file +let e;const o={wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"},...window.sdkUrlMap};let a=null,t=0;const n=function(){const e=location.href,o=/mpx_webview_id=(\d+)/g.exec(e);let a;return o&&o[1]&&(a=+o[1]),a}(),i={},s=navigator.userAgent;s.indexOf("AlipayClient")>-1&&s.indexOf("MiniProgram")>-1?a="my":s.toLowerCase().indexOf("miniprogram")>-1?a=s.indexOf("QQ")>-1?"qq":"wx":s.indexOf("swan/")>-1?a="swan":s.indexOf("toutiao")>-1?a="tt":(a="web",window.addEventListener("message",e=>{const o=e.data;let a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}const{callbackId:t,error:n,result:s}=a;void 0!==t&&i[t]&&(n?i[t](n):i[t](null,s),delete i[t])},!1));let r=!1;function c(o){r?o():e.then(()=>{r=!0,o()})}const d={config(e){"wx"===a?c(()=>{window.wx&&window.wx.config(e)}):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};const w=()=>{const e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[a]||{},o={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation"],tt:[]}[a]||[];(e.api||[]).forEach(o=>{d[o]=(...t)=>{c(()=>{window[a][e.keyName][o](...t)})}}),o.forEach(e=>{d[e]=(...o)=>{"web"===a?function(e,o={}){if("getEnv"!==e){const a=++t;i[a]=(e,t)=>{e?(o.fail&&o.fail(e),o.complete&&o.complete(e)):(o.success&&o.success(t),o.complete&&o.complete(t)),delete i[a]};const s={type:e,callbackId:t,payload:o};void 0!==n&&(s.clientUid=n),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(s)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(s),"*")}else o({webapp:!0})}(e,...o):c("wx"===a?()=>{window[a]&&window[a].ready(()=>{window[a][e](...o)})}:()=>{window[a][e](...o)})}})};e="web"!==a?o[a].url?function(e,{time:o=5e3,crossOrigin:a=!1}={}){return Promise.race([new Promise((o,t)=>{const n=document.createElement("script");n.type="text/javascript",n.async="async",a&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){t(new Error(`load ${e} error`)),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}),new Promise((a,t)=>{setTimeout(()=>{t(new Error(`load ${e} timeout`))},o)})])}(o[a].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),w();export default d; \ No newline at end of file diff --git a/packages/webview-bridge/dist/webviewbridge.esm.js b/packages/webview-bridge/dist/webviewbridge.esm.js index c45b54c0b5..d53778bd49 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.js @@ -1,5 +1,5 @@ /** - * mpxjs webview bridge v2.9.53 + * mpxjs webview bridge v2.9.58 * (c) 2024 @mpxjs team * @license Apache */ @@ -182,18 +182,6 @@ var webviewBridge = { }); } }; -function filterData(data) { - if (Object.prototype.toString.call(data) !== '[object Object]') { - return data; - } - var newData = {}; - for (var item in data) { - if (typeof data[item] !== 'function') { - newData[item] = data[item]; - } - } - return newData; -} function postMessage(type) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (type !== 'getEnv') { @@ -211,7 +199,7 @@ function postMessage(type) { var postParams = { type: type, callbackId: callbackId, - payload: filterData(data) + payload: data }; if (clientUid !== undefined) { postParams.clientUid = clientUid; @@ -219,7 +207,7 @@ function postMessage(type) { if (window.ReactNativeWebView) { window.ReactNativeWebView.postMessage && window.ReactNativeWebView.postMessage(JSON.stringify(postParams)); } else { - window.parent.postMessage && window.parent.postMessage(postParams, '*'); + window.parent.postMessage && window.parent.postMessage(JSON.stringify(postParams), '*'); } } else { data({ diff --git a/packages/webview-bridge/dist/webviewbridge.js b/packages/webview-bridge/dist/webviewbridge.js index 13c40824a5..e49ba87440 100644 --- a/packages/webview-bridge/dist/webviewbridge.js +++ b/packages/webview-bridge/dist/webviewbridge.js @@ -1,5 +1,5 @@ /** - * mpxjs webview bridge v2.9.53 + * mpxjs webview bridge v2.9.58 * (c) 2024 @mpxjs team * @license Apache */ @@ -188,18 +188,6 @@ }); } }; - function filterData(data) { - if (Object.prototype.toString.call(data) !== '[object Object]') { - return data; - } - var newData = {}; - for (var item in data) { - if (typeof data[item] !== 'function') { - newData[item] = data[item]; - } - } - return newData; - } function postMessage(type) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (type !== 'getEnv') { @@ -217,7 +205,7 @@ var postParams = { type: type, callbackId: callbackId, - payload: filterData(data) + payload: data }; if (clientUid !== undefined) { postParams.clientUid = clientUid; @@ -225,7 +213,7 @@ if (window.ReactNativeWebView) { window.ReactNativeWebView.postMessage && window.ReactNativeWebView.postMessage(JSON.stringify(postParams)); } else { - window.parent.postMessage && window.parent.postMessage(postParams, '*'); + window.parent.postMessage && window.parent.postMessage(JSON.stringify(postParams), '*'); } } else { data({ diff --git a/packages/webview-bridge/dist/webviewbridge.min.js b/packages/webview-bridge/dist/webviewbridge.min.js index b94c23c965..9dac705da4 100644 --- a/packages/webview-bridge/dist/webviewbridge.min.js +++ b/packages/webview-bridge/dist/webviewbridge.min.js @@ -1,6 +1,6 @@ /** - * mpxjs webview bridge v2.9.53 + * mpxjs webview bridge v2.9.58 * (c) 2024 @mpxjs team * @license Apache */ -var e,t;e=this,t=function(){"use strict";function e(e,t,o){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var n=o.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function t(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,n)}return o}var o,n,a,r,i=function(o){for(var n=1;n-1&&g.indexOf("MiniProgram")>-1?c="my":g.toLowerCase().indexOf("miniprogram")>-1?c=g.indexOf("QQ")>-1?"qq":"wx":g.indexOf("swan/")>-1?c="swan":g.indexOf("toutiao")>-1?c="tt":(c="web",window.addEventListener("message",(function(e){var t=e.data,o=t;try{"string"==typeof t&&(o=JSON.parse(t))}catch(e){}var n=o,a=n.callbackId,r=n.error,i=n.result;void 0!==a&&d[a]&&(r?d[a](r):d[a](null,i),delete d[a])}),!1));var u=!1;function w(e){u?e():o.then((function(){u=!0,e()}))}var l={config:function(e){"wx"===c?w((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function f(e){if("[object Object]"!==Object.prototype.toString.call(e))return e;var t={};for(var o in e)"function"!=typeof e[o]&&(t[o]=e[o]);return t}function m(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("getEnv"!==e){var o=++s;d[o]=function(e,n){e?(t.fail&&t.fail(e),t.complete&&t.complete(e)):(t.success&&t.success(n),t.complete&&t.complete(n)),delete d[o]};var n={type:e,callbackId:s,payload:f(t)};void 0!==p&&(n.clientUid=p),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(n)):window.parent.postMessage&&window.parent.postMessage(n,"*")}else t({webapp:!0})}var v=function(){var e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[c]||{},t={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation"],tt:[]}[c]||[];(e.api||[]).forEach((function(t){l[t]=function(){for(var o=arguments.length,n=new Array(o),a=0;a1&&void 0!==arguments[1]?arguments[1]:{},o=t.time,n=void 0===o?5e3:o,a=t.crossOrigin,r=void 0!==a&&a;function i(){return new Promise((function(t,o){var n=document.createElement("script");n.type="text/javascript",n.async="async",r&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(t(),n.onload=n.onreadystatechange=null)},n.onerror=function(){o(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(t,o){setTimeout((function(){o(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([i(),c()])}(i[c].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),v(),l},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).mpx=t(); \ No newline at end of file +var e,t;e=this,t=function(){"use strict";function e(e,t,o){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var n=o.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function t(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,n)}return o}var o,n,a,r,i=function(o){for(var n=1;n-1&&g.indexOf("MiniProgram")>-1?c="my":g.toLowerCase().indexOf("miniprogram")>-1?c=g.indexOf("QQ")>-1?"qq":"wx":g.indexOf("swan/")>-1?c="swan":g.indexOf("toutiao")>-1?c="tt":(c="web",window.addEventListener("message",(function(e){var t=e.data,o=t;try{"string"==typeof t&&(o=JSON.parse(t))}catch(e){}var n=o,a=n.callbackId,r=n.error,i=n.result;void 0!==a&&d[a]&&(r?d[a](r):d[a](null,i),delete d[a])}),!1));var w=!1;function u(e){w?e():o.then((function(){w=!0,e()}))}var l={config:function(e){"wx"===c?u((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function f(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("getEnv"!==e){var o=++s;d[o]=function(e,n){e?(t.fail&&t.fail(e),t.complete&&t.complete(e)):(t.success&&t.success(n),t.complete&&t.complete(n)),delete d[o]};var n={type:e,callbackId:s,payload:t};void 0!==p&&(n.clientUid=p),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(n)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(n),"*")}else t({webapp:!0})}var m=function(){var e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[c]||{},t={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation"],tt:[]}[c]||[];(e.api||[]).forEach((function(t){l[t]=function(){for(var o=arguments.length,n=new Array(o),a=0;a1&&void 0!==arguments[1]?arguments[1]:{},o=t.time,n=void 0===o?5e3:o,a=t.crossOrigin,r=void 0!==a&&a;function i(){return new Promise((function(t,o){var n=document.createElement("script");n.type="text/javascript",n.async="async",r&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(t(),n.onload=n.onreadystatechange=null)},n.onerror=function(){o(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(t,o){setTimeout((function(){o(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([i(),c()])}(i[c].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),m(),l},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).mpx=t(); \ No newline at end of file diff --git a/packages/webview-bridge/src/index.js b/packages/webview-bridge/src/index.js index a3b9fd6ce6..6250c9937b 100644 --- a/packages/webview-bridge/src/index.js +++ b/packages/webview-bridge/src/index.js @@ -97,19 +97,6 @@ const webviewBridge = { } } -function filterData (data) { - if (Object.prototype.toString.call(data) !== '[object Object]') { - return data - } - const newData = {} - for (const item in data) { - if (typeof data[item] !== 'function') { - newData[item] = data[item] - } - } - return newData -} - function postMessage (type, data = {}) { if (type !== 'getEnv') { const currentCallbackId = ++callbackId @@ -126,7 +113,7 @@ function postMessage (type, data = {}) { const postParams = { type, callbackId, - payload: filterData(data) + payload: data } if (clientUid !== undefined) { postParams.clientUid = clientUid @@ -134,7 +121,7 @@ function postMessage (type, data = {}) { if (window.ReactNativeWebView) { window.ReactNativeWebView.postMessage && window.ReactNativeWebView.postMessage(JSON.stringify(postParams)) } else { - window.parent.postMessage && window.parent.postMessage(postParams, '*') + window.parent.postMessage && window.parent.postMessage(JSON.stringify(postParams), '*') } } else { data({ From 9b0507981bfc7a75894fa0dceb358bceed9fd0ea Mon Sep 17 00:00:00 2001 From: wenwen Date: Thu, 12 Dec 2024 18:57:06 +0800 Subject: [PATCH 32/76] add transform css var --- packages/webpack-plugin/lib/platform/style/wx/index.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/platform/style/wx/index.js b/packages/webpack-plugin/lib/platform/style/wx/index.js index 22df8d3a49..17c02988f7 100644 --- a/packages/webpack-plugin/lib/platform/style/wx/index.js +++ b/packages/webpack-plugin/lib/platform/style/wx/index.js @@ -373,7 +373,8 @@ module.exports = function getSpec ({ warn, error }) { // transform 转换 const formatTransform = ({ prop, value, selector }, { mode }) => { - if (Array.isArray(value)) return { prop, value } + // css var & 数组直接返回 + if (Array.isArray(value) || calcExp.test(value)) return { prop, value } const values = parseValues(value) const transform = [] values.forEach(item => { From bb7d9cf63e4b52fcb93629c34b447dbec7649549 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 12 Dec 2024 21:04:47 +0800 Subject: [PATCH 33/76] =?UTF-8?q?=E5=B9=B2=E6=8E=89=E4=BC=A0=E9=80=92?= =?UTF-8?q?=E7=9A=84data?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../webpack-plugin/lib/runtime/components/web/mpx-web-view.vue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue b/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue index 8fa232c3fe..64b3258534 100644 --- a/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue +++ b/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue @@ -122,7 +122,7 @@ export default { case 'postMessage': let data = { type: 'message', - data: value.data || value + data: value.data } this.$emit(eventMessage, getCustomEvent(eventMessage, data, this)) asyncCallback = Promise.resolve({ From 7326b25d1c7f8278bbf09c9eeca5fefec9ab2c53 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Thu, 12 Dec 2024 21:09:46 +0800 Subject: [PATCH 34/76] =?UTF-8?q?chore:=20=E4=BF=AE=E6=94=B9bitFlag?= =?UTF-8?q?=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/components/react/event.config.ts | 48 +++++++++---------- .../components/react/getInnerListeners.ts | 8 ++-- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/event.config.ts b/packages/webpack-plugin/lib/runtime/components/react/event.config.ts index 534475f3bf..b1356b7ed9 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/event.config.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/event.config.ts @@ -3,29 +3,29 @@ interface EventConfig { } const eventConfigMap: { [key: string]: { bitFlag: string; events: string[] } } = { - bindtap: { bitFlag: '000001', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd'] }, - bindlongpress: { bitFlag: '000010', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'] }, - bindtouchstart: { bitFlag: '000011', events: ['onTouchStart'] }, - bindtouchmove: { bitFlag: '000100', events: ['onTouchMove'] }, - bindtouchend: { bitFlag: '000101', events: ['onTouchEnd'] }, - bindtouchcancel: { bitFlag: '000110', events: ['onTouchCancel'] }, - catchtap: { bitFlag: '000111', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd'] }, - catchlongpress: { bitFlag: '001000', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'] }, - catchtouchstart: { bitFlag: '001001', events: ['onTouchStart'] }, - catchtouchmove: { bitFlag: '001010', events: ['onTouchMove'] }, - catchtouchend: { bitFlag: '001011', events: ['onTouchEnd'] }, - catchtouchcancel: { bitFlag: '001100', events: ['onTouchCancel'] }, - 'capture-bindtap': { bitFlag: '001101', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture'] }, - 'capture-bindlongpress': { bitFlag: '001110', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture', 'onTouchCancelCapture'] }, - 'capture-bindtouchstart': { bitFlag: '001111', events: ['onTouchStartCapture'] }, - 'capture-bindtouchmove': { bitFlag: '010000', events: ['onTouchMoveCapture'] }, - 'capture-bindtouchend': { bitFlag: '010001', events: ['onTouchEndCapture'] }, - 'capture-bindtouchcancel': { bitFlag: '010010', events: ['onTouchCancelCapture'] }, - 'capture-catchtap': { bitFlag: '010011', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture'] }, - 'capture-catchlongpress': { bitFlag: '010100', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture', 'onTouchCancelCapture'] }, - 'capture-catchtouchstart': { bitFlag: '010101', events: ['onTouchStartCapture'] }, - 'capture-catchtouchmove': { bitFlag: '010110', events: ['onTouchMoveCapture'] }, - 'capture-catchtouchend': { bitFlag: '010111', events: ['onTouchEndCapture'] }, - 'capture-catchtouchcancel': { bitFlag: '011000', events: ['onTouchCancelCapture'] } + bindtap: { bitFlag: '0', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd'] }, + bindlongpress: { bitFlag: '1', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'] }, + bindtouchstart: { bitFlag: '2', events: ['onTouchStart'] }, + bindtouchmove: { bitFlag: '3', events: ['onTouchMove'] }, + bindtouchend: { bitFlag: '4', events: ['onTouchEnd'] }, + bindtouchcancel: { bitFlag: '5', events: ['onTouchCancel'] }, + catchtap: { bitFlag: '6', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd'] }, + catchlongpress: { bitFlag: '7', events: ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'] }, + catchtouchstart: { bitFlag: '8', events: ['onTouchStart'] }, + catchtouchmove: { bitFlag: '9', events: ['onTouchMove'] }, + catchtouchend: { bitFlag: 'a', events: ['onTouchEnd'] }, + catchtouchcancel: { bitFlag: 'b', events: ['onTouchCancel'] }, + 'capture-bindtap': { bitFlag: 'c', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture'] }, + 'capture-bindlongpress': { bitFlag: 'd', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture', 'onTouchCancelCapture'] }, + 'capture-bindtouchstart': { bitFlag: 'e', events: ['onTouchStartCapture'] }, + 'capture-bindtouchmove': { bitFlag: 'f', events: ['onTouchMoveCapture'] }, + 'capture-bindtouchend': { bitFlag: 'g', events: ['onTouchEndCapture'] }, + 'capture-bindtouchcancel': { bitFlag: 'h', events: ['onTouchCancelCapture'] }, + 'capture-catchtap': { bitFlag: 'i', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture'] }, + 'capture-catchlongpress': { bitFlag: 'j', events: ['onTouchStartCapture', 'onTouchMoveCapture', 'onTouchEndCapture', 'onTouchCancelCapture'] }, + 'capture-catchtouchstart': { bitFlag: 'k', events: ['onTouchStartCapture'] }, + 'capture-catchtouchmove': { bitFlag: 'l', events: ['onTouchMoveCapture'] }, + 'capture-catchtouchend': { bitFlag: 'm', events: ['onTouchEndCapture'] }, + 'capture-catchtouchcancel': { bitFlag: 'n', events: ['onTouchCancelCapture'] } } export default eventConfigMap diff --git a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts index 468f3aaa40..60d28c591c 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts @@ -294,17 +294,17 @@ const useInnerProps = ( propsRef.current = extendObject({}, props, additionalProps) - let sortEventKeys = '' + let hashEventKey = '' for (const key in eventConfigMap) { if (hasOwn(propsRef.current, key)) { eventConfig[key] = eventConfigMap[key].events - sortEventKeys = sortEventKeys + eventConfigMap[key].bitFlag + '|' + hashEventKey = hashEventKey + eventConfigMap[key].bitFlag } } const rawEventKeys = useMemo(() => { return Object.keys(eventConfig) - }, [sortEventKeys]) + }, [hashEventKey]) if (!rawEventKeys.length || config.disableTouch) { return omit(propsRef.current, removeProps) @@ -328,7 +328,7 @@ const useInnerProps = ( }) return events - }, [sortEventKeys]) + }, [hashEventKey]) return extendObject( {}, From 0aa4588bea761dc60c70a13f012aa871e83f1257 Mon Sep 17 00:00:00 2001 From: wenwen Date: Thu, 12 Dec 2024 21:13:22 +0800 Subject: [PATCH 35/76] =?UTF-8?q?=E4=BC=98=E5=8C=96flex=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/platform/style/wx/index.js | 61 ++++++++----------- 1 file changed, 26 insertions(+), 35 deletions(-) diff --git a/packages/webpack-plugin/lib/platform/style/wx/index.js b/packages/webpack-plugin/lib/platform/style/wx/index.js index 17c02988f7..8a8cc97e3d 100644 --- a/packages/webpack-plugin/lib/platform/style/wx/index.js +++ b/packages/webpack-plugin/lib/platform/style/wx/index.js @@ -456,17 +456,17 @@ module.exports = function getSpec ({ warn, error }) { const formatFlex = ({ prop, value, selector }) => { let values = parseValues(value) + // 值大于3 去前三 if (values.length > 3) { warn(`Value of [flex] in ${selector} supports up to three values, received [${value}], please check again!`) values = values.splice(0, 3) } const cssMap = [] + // 单个css var 直接设置 flex 属性 if (values.length === 1 && cssVariableExp.test(value)) { return { prop, value } } - const lastOne = values[values.length - 1] - const isAuto = lastOne === 'auto' - // 枚举值 none initial + // 包含枚举值 none initial if (values.includes('initial') || values.includes('none')) { // css flex: initial ===> flex: 0 1 ===> rn flex 0 1 // css flex: none ===> css flex: 0 0 ===> rn flex 0 0 @@ -479,40 +479,31 @@ module.exports = function getSpec ({ warn, error }) { } return cssMap } - // 最后一个值是flexBasis 的有效值(auto或者有单位百分比、px等) - // flex 0 1 auto flex auto flex 1 auto flex 1 30px flex 1 10% flex 1 1 auto - if (!isNumber(lastOne) || cssVariableExp.test(value)) { - // 添加 grow 和 shrink - // 在设置 flex basis 有效值的场景下,如果没有设置 grow 和 shrink,则默认为1 - // 单值 flex: 1 1 - // 双值 flex: 1 - // 三值 flex: - let isUsed = false - for (let i = 0; i < 2; i++) { - isUsed = isNumber(values[i]) || cssVariableExp.test(values[i]) - const item = getIntegersFlex({ prop: AbbreviationMap[prop][i], value: isUsed ? values[i] : 1, selector }) + // 只有1-2个值且最后的值是flexBasis 的有效值(auto或者有单位百分比、px等) + // 在设置 flex basis 有效值的场景下,如果没有设置 grow 和 shrink,则默认为1 + // 单值 flex: 1 1 + // 双值 flex: 1 + // 三值 flex: + for (let i = 0; i < 3; i++) { + if (i < 2) { + // 添加 grow 和 shrink + const isValid = isNumber(values[0]) || cssVariableExp.test(values[0]) + // 兜底 1 + const val = isValid ? values[0] : 1 + const item = getIntegersFlex({ prop: AbbreviationMap[prop][i], value: val, selector }) item && cssMap.push(item) + isValid && values.shift() + } else { + // 添加 flexBasis + // 有单位(百分比、px等) 的 value 赋值 flexBasis,auto 不处理,兜底 0 + const val = values[0] || 0 + if (val !== 'auto') { + cssMap.push({ + prop: 'flexBasis', + value: val + }) + } } - if (!isAuto && !isUsed) { - // 有单位(百分比、px等) 的 value 赋值 flexBasis,auto 不处理 - cssMap.push({ - prop: 'flexBasis', - value: lastOne - }) - } - return cssMap - } - // 纯数值:value 按flex-grow flex-shrink flex-basis 顺序赋值 - // 兜底 shrink & basis - if (values.length === 1) { - values.push(...[1, 0]) - } else if (values.length === 2) { - values.push(0) - } - // 循环赋值 - for (let i = 0; i < values.length; i++) { - const item = getIntegersFlex({ prop: AbbreviationMap[prop][i], value: values[i], selector }) - item && cssMap.push(item) } return cssMap } From 9aabd0884d626bfc49fd07e5910b2ebaf15941b1 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Mon, 16 Dec 2024 15:51:13 +0800 Subject: [PATCH 36/76] chore: del comment --- .../components/react/mpx-movable-view.tsx | 23 +------------------ 1 file changed, 1 insertion(+), 22 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-view.tsx index 0243b04c68..3a0a330251 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-movable-view.tsx @@ -518,28 +518,7 @@ const _MovableView = forwardRef, MovableViewP const catchEventHandlers = injectCatchEvent(props) const layoutStyle = !hasLayoutRef.current && hasSelfPercent ? HIDDEN_STYLE : {} - // return ( - // - // - // { - // wrapChildren( - // props, - // { - // hasVarDec, - // varContext: varContextRef.current, - // textStyle, - // textProps - // } - // ) - // } - // - // - // ) + return createElement(GestureDetector, { gesture: gesture }, createElement( Animated.View, extendObject({ From 4b8a2832f8d8e1ff63546d6da3a9d19d4d422849 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Mon, 16 Dec 2024 18:49:54 +0800 Subject: [PATCH 37/76] =?UTF-8?q?fix:=20=E8=BF=9E=E7=BB=AD=E8=A7=A6?= =?UTF-8?q?=E5=8F=91scrollToView=E4=BA=A4=E4=BA=92=E4=B8=8D=E7=AC=A6?= =?UTF-8?q?=E5=90=88=E9=A2=84=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/react/mpx-scroll-view.tsx | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx index 17f45a6e41..6d29734fbb 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx @@ -222,18 +222,16 @@ const _ScrollView = forwardRef, S useEffect(() => { if (scrollIntoView && __selectRef && snapScrollIntoView.current !== scrollIntoView) { snapScrollIntoView.current = scrollIntoView || '' - setTimeout(() => { - const refs = __selectRef(`#${scrollIntoView}`, 'node') - if (refs) { - const { nodeRef } = refs.getNodeInstance() - nodeRef.current?.measureLayout( - scrollViewRef.current, - (left: number, top:number) => { - scrollToOffset(left, top) - } - ) - } - }) + const refs = __selectRef(`#${scrollIntoView}`, 'node') + if (refs) { + const { nodeRef } = refs.getNodeInstance() + nodeRef.current?.measureLayout( + scrollViewRef.current, + (left: number, top:number) => { + scrollToOffset(left, top) + } + ) + } } }, [scrollIntoView]) From 20b30b1b94eae4f688901cddaf269bc4c90bd6a5 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Mon, 16 Dec 2024 20:08:17 +0800 Subject: [PATCH 38/76] =?UTF-8?q?chore:=20=E4=BC=98=E5=8C=96scroll-into-vi?= =?UTF-8?q?ew=E8=A7=A6=E5=8F=91=E6=97=B6=E6=9C=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/react/mpx-scroll-view.tsx | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx index 6d29734fbb..a2c474b453 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx @@ -219,22 +219,34 @@ const _ScrollView = forwardRef, S } }, [refresherTriggered]) + useEffect(() => { + if (scrollIntoView && __selectRef) { + snapScrollIntoView.current = scrollIntoView || '' + setTimeout(() => { + handleScrollIntoView() + }) + } + }, []) + useEffect(() => { if (scrollIntoView && __selectRef && snapScrollIntoView.current !== scrollIntoView) { snapScrollIntoView.current = scrollIntoView || '' - const refs = __selectRef(`#${scrollIntoView}`, 'node') - if (refs) { - const { nodeRef } = refs.getNodeInstance() - nodeRef.current?.measureLayout( - scrollViewRef.current, - (left: number, top:number) => { - scrollToOffset(left, top) - } - ) - } + handleScrollIntoView() } }, [scrollIntoView]) + function handleScrollIntoView () { + const refs = __selectRef!(`#${scrollIntoView}`, 'node') + if (!refs) return + const { nodeRef } = refs.getNodeInstance() + nodeRef.current?.measureLayout( + scrollViewRef.current, + (left: number, top:number) => { + scrollToOffset(left, top) + } + ) + } + function selectLength (size: { height: number; width: number }) { return !scrollX ? size.height : size.width } From 08f019276d39d102488eaf0072ff2d6a6f0097ed Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Tue, 17 Dec 2024 12:12:13 +0800 Subject: [PATCH 39/76] =?UTF-8?q?fix=20action-sheet=E5=92=8Cmodal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../api/action-sheet/rnActionSheet.jsx | 144 ++++++++---------- .../src/platform/api/modal/rnModal.jsx | 15 +- 2 files changed, 70 insertions(+), 89 deletions(-) diff --git a/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx b/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx index 4e68c19bca..570bdb65da 100644 --- a/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx +++ b/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx @@ -1,38 +1,14 @@ -import { View, TouchableHighlight, Text, StyleSheet, Button, Animated } from 'react-native' +import { View, TouchableHighlight, Text, StyleSheet, TouchableOpacity } from 'react-native' import { successHandle, failHandle } from '../../../common/js' import { Portal } from '@ant-design/react-native' +import Animated, { + useSharedValue, + useAnimatedStyle, + withTiming +} from 'react-native-reanimated' function showActionSheet (options = {}) { const { alertText, itemList = [], itemColor = '#000000', success, fail, complete } = options - let actionSheetKey - const slideAnim = new Animated.Value(500) - const slideIn = () => { - // Will change fadeAnim value to 1 in 5 seconds - Animated.timing(slideAnim, { - toValue: 0, - duration: 200, - useNativeDriver: true, - }).start() - } - const slideOut = () => { - // Will change fadeAnim value to 1 in 5 seconds - Animated.timing(slideAnim, { - toValue: 500, - duration: 200, - useNativeDriver: true, - }).start(() => { - }) - } - if (itemList.length === 0 || itemList.length > 6) { - const result = { - errMsg: 'showActionSheet:fail parameter error: itemList should not be large than 6' - } - if (itemList.length === 0) { - result.errno = 1001 - result.errMsg = 'showActionSheet:fail parameter error: parameter.itemList should have at least 1 item;' - } - failHandle(result, fail, complete) - return - } + let actionSheetKey = null const styles = StyleSheet.create({ actionActionMask: { left: 0, @@ -44,16 +20,13 @@ function showActionSheet (options = {}) { zIndex: 1000 }, actionSheetContent: { - left: 0, - right: 0, - position: 'absolute', - bottom: 0, backgroundColor: '#ffffff', borderTopLeftRadius: 10, borderTopRightRadius: 10, - transform: [{ - translateY: -500 - }] + position: 'absolute', + bottom: 0, + left: 0, + right: 0 }, itemStyle: { paddingTop: 15, @@ -73,53 +46,62 @@ function showActionSheet (options = {}) { paddingBottom: 10 } }) - const remove = function () { - if (actionSheetKey) { - slideOut() - setTimeout(() => { - Portal.remove(actionSheetKey) - actionSheetKey = null - }, 200) + function ActionSheet () { + const offset = useSharedValue(1000); + + const animatedStyles = useAnimatedStyle(() => ({ + transform: [{ translateY: offset.value }], + })) + + const slideOut = () => { + // Will change fadeAnim value to 1 in 5 seconds + offset.value = withTiming(1000) } - } - const selectAction = function (index) { - const result = { - errMsg: 'showActionSheet:ok', - tapIndex: index + + offset.value = withTiming(0) + + const selectAction = function (index) { + const result = { + errMsg: 'showActionSheet:ok', + tapIndex: index + } + successHandle(result, success, complete) + remove() } - successHandle(result, success, complete) - remove() - } - const cancelAction = function () { - const result = { - errMsg: 'showActionSheet:fail cancel' + + const remove = function () { + if (actionSheetKey) { + slideOut() + setTimeout(() => { + Portal.remove(actionSheetKey) + actionSheetKey = null + }, 200) + } } - failHandle(result, fail, complete) - remove() - } - let alertTextList = [] - if (alertText) { - alertTextList = [alertText] + + const cancelAction = function () { + const result = { + errMsg: 'showActionSheet:fail cancel' + } + failHandle(result, fail, complete) + remove() + } + return ( + + + { alertText ? {alertText} : null } + { itemList.map((item, index) => selectAction(index)} style={ [styles.itemStyle, itemList.length -1 === index ? { + borderBottomWidth: 6, + borderBottomStyle: 'solid', + borderBottomColor: '#f7f7f7' + } : {}] }>{item}) } + 取消 + + + ) } - const ActionSheetView = - - { alertTextList.map((item, index) => {item}) } - { itemList.map((item, index) => selectAction(index)} style={ [styles.itemStyle, itemList.length -1 === index ? { - borderBottomWidth: 6, - borderBottomStyle: 'solid', - borderBottomColor: '#f7f7f7' - } : {}] }>{item}) } - - - - actionSheetKey = Portal.add(ActionSheetView) - slideIn() + + actionSheetKey = Portal.add() } export { diff --git a/packages/api-proxy/src/platform/api/modal/rnModal.jsx b/packages/api-proxy/src/platform/api/modal/rnModal.jsx index 11060afae0..afc8ec1251 100644 --- a/packages/api-proxy/src/platform/api/modal/rnModal.jsx +++ b/packages/api-proxy/src/platform/api/modal/rnModal.jsx @@ -17,7 +17,7 @@ const showModal = function (options = {}) { fail, complete } = options - const modalWidth = width - 60 + const modalWidth = width * 0.8 const styles = StyleSheet.create({ modalTask: { left: 0, @@ -53,7 +53,8 @@ const showModal = function (options = {}) { lineHeight: 26, color: '#808080', paddingLeft: 20, - paddingRight: 20 + paddingRight: 20, + textAlign: 'center' }, modalBtnBox: { borderTopWidth: StyleSheet.hairlineWidth, @@ -67,8 +68,8 @@ const showModal = function (options = {}) { modalBtn: { flex: 1, textAlign: 'center', - paddingTop: 10, - paddingBottom: 10, + paddingTop: width * 0.04, + paddingBottom: width * 0.04, }, modalButton: { width: '100%', @@ -88,9 +89,8 @@ const showModal = function (options = {}) { let editableContent = [] let modalButton = [{ text: confirmText, - confirmColor, type: 'confirm', - color: 'rgb(87, 107, 149)' + color: confirmColor }] let contentText = content const onChangeText = function (text) { @@ -128,10 +128,9 @@ const showModal = function (options = {}) { if (showCancel) { modalButton.unshift({ text: cancelText, - cancelColor, type: 'cancel', style: styles.cancelStyle, - color: '#000000' + color: cancelColor }) } ModalView = From 1a454025e8ab14ad7cf610a6f7562535ef1c0533 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Tue, 17 Dec 2024 15:30:10 +0800 Subject: [PATCH 40/76] =?UTF-8?q?chore:=20=E4=BC=98=E5=8C=96jsx=E6=89=A9?= =?UTF-8?q?=E5=B1=95=E8=BF=90=E7=AE=97=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/react/mpx-canvas/index.tsx | 49 +++++++++---------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-canvas/index.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-canvas/index.tsx index 47385974e1..b5b31cc3d1 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-canvas/index.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-canvas/index.tsx @@ -249,31 +249,30 @@ const _Canvas = forwardRef, CanvasPr if (Platform.OS === 'android') { const isAndroid9 = Platform.Version >= 28 - return ( - - { - if (canvasRef.current) { - canvasRef.current.webview = element - } - }} - style={[ - isAndroid9 ? stylesheet.webviewAndroid9 : stylesheet.webview, - { height, width } - ]} - source={{ html }} - originWhitelist={originWhitelist} - onMessage={onMessage} - onLoad={onLoad} - overScrollMode="never" - mixedContentMode="always" - scalesPageToFit={false} - javaScriptEnabled - domStorageEnabled - thirdPartyCookiesEnabled - allowUniversalAccessFromFileURLs - /> - + return createElement(View, innerProps, createElement( + WebView, + { + ref: (element) => { + if (canvasRef.current) { + canvasRef.current.webview = element + } + }, + style: [ + isAndroid9 ? stylesheet.webviewAndroid9 : stylesheet.webview, + { height, width } + ], + source: { html }, + originWhitelist: originWhitelist, + onMessage: onMessage, + onLoad: onLoad, + overScrollMode: 'never', + mixedContentMode: 'always', + scalesPageToFit: false, + javaScriptEnabled: true, + domStorageEnabled: true, + thirdPartyCookiesEnabled: true, + allowUniversalAccessFromFileURLs: true + }) ) } From 2f7a8dfe377780299517fa8ba209bfba0f62dd07 Mon Sep 17 00:00:00 2001 From: WX-DongXing Date: Tue, 17 Dec 2024 22:09:40 +0800 Subject: [PATCH 41/76] feat: adapt onContentSizeChange event --- .../webpack-plugin/lib/runtime/components/react/mpx-input.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-input.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-input.tsx index e8a466affd..8ac3894c4c 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-input.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-input.tsx @@ -187,7 +187,7 @@ const Input = forwardRef, FinalInputProps { padding: 0, backgroundColor: '#fff' }, style, multiline && autoHeight - ? { height: Math.max((style as any)?.minHeight || 35, contentHeight) } + ? { minHeight: Math.max((style as any)?.minHeight || 35, contentHeight) } : {} ) From b1b2650c675a0f422c291fa54162021f91145139 Mon Sep 17 00:00:00 2001 From: WX-DongXing Date: Tue, 17 Dec 2024 22:11:34 +0800 Subject: [PATCH 42/76] fix: remove unnecessary keyboard handling --- packages/core/src/platform/patch/getDefaultOptions.ios.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/core/src/platform/patch/getDefaultOptions.ios.js b/packages/core/src/platform/patch/getDefaultOptions.ios.js index a794fe4160..56f7641f70 100644 --- a/packages/core/src/platform/patch/getDefaultOptions.ios.js +++ b/packages/core/src/platform/patch/getDefaultOptions.ios.js @@ -560,10 +560,7 @@ export function getDefaultOptions ({ type, rawOptions = {}, currentInject }) { backgroundColor: pageConfig.backgroundColor || '#ffffff' }, ref: rootRef, - onLayout, - onTouchStart: () => { - ReactNative.Keyboard.isVisible() && ReactNative.Keyboard.dismiss() - } + onLayout }, createElement(RouteContext.Provider, { From 7b6d50eab8d0345d37ed108911d3a832a0f2a040 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Wed, 18 Dec 2024 15:18:17 +0800 Subject: [PATCH 43/76] =?UTF-8?q?=E8=A1=A5=E5=85=85actionsheet=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E8=B7=9D=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/platform/api/action-sheet/rnActionSheet.jsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx b/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx index 570bdb65da..280d04b0d6 100644 --- a/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx +++ b/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx @@ -1,6 +1,7 @@ import { View, TouchableHighlight, Text, StyleSheet, TouchableOpacity } from 'react-native' import { successHandle, failHandle } from '../../../common/js' import { Portal } from '@ant-design/react-native' +import { getWindowInfo } from '../system/rnSystem' import Animated, { useSharedValue, useAnimatedStyle, @@ -8,6 +9,8 @@ import Animated, { } from 'react-native-reanimated' function showActionSheet (options = {}) { const { alertText, itemList = [], itemColor = '#000000', success, fail, complete } = options + const windowInfo = getWindowInfo() + const bottom = windowInfo.screenHeight - windowInfo.safeArea.bottom let actionSheetKey = null const styles = StyleSheet.create({ actionActionMask: { @@ -26,7 +29,8 @@ function showActionSheet (options = {}) { position: 'absolute', bottom: 0, left: 0, - right: 0 + right: 0, + paddingBottom: bottom }, itemStyle: { paddingTop: 15, From ced2af83ff2fa4c0f84d598d395cf947476e2cbf Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Wed, 18 Dec 2024 17:29:27 +0800 Subject: [PATCH 44/76] fix rn&web errorHandling --- .../src/platform/api/app/index.web.js | 37 ++++-- packages/core/package.json | 6 +- packages/core/src/core/proxy.js | 2 +- packages/core/src/external/vue.js | 1 - packages/core/src/external/vue.web.js | 6 - packages/core/src/index.js | 17 +-- packages/core/src/platform/createApp.ios.js | 9 +- packages/core/src/platform/createApp.js | 10 +- packages/core/src/platform/env/event.js | 108 ++++++++++++++++++ packages/core/src/platform/env/index.ios.js | 51 +++++++++ packages/core/src/platform/env/index.js | 8 ++ packages/core/src/platform/env/index.web.js | 48 ++++++++ .../{external => platform/env}/vuePlugin.js | 2 +- packages/core/src/platform/export/index.js | 2 +- .../export/{apiInject.js => inject.js} | 0 .../{apiInject.web.js => inject.web.js} | 0 packages/utils/src/errorHandling.js | 2 +- packages/utils/src/log.js | 6 +- .../lib/runtime/components/web/event.js | 105 ----------------- .../lib/runtime/optionProcessor.js | 22 ---- 20 files changed, 264 insertions(+), 178 deletions(-) delete mode 100644 packages/core/src/external/vue.js delete mode 100644 packages/core/src/external/vue.web.js create mode 100644 packages/core/src/platform/env/event.js create mode 100644 packages/core/src/platform/env/index.ios.js create mode 100644 packages/core/src/platform/env/index.js create mode 100644 packages/core/src/platform/env/index.web.js rename packages/core/src/{external => platform/env}/vuePlugin.js (98%) rename packages/core/src/platform/export/{apiInject.js => inject.js} (100%) rename packages/core/src/platform/export/{apiInject.web.js => inject.web.js} (100%) delete mode 100644 packages/webpack-plugin/lib/runtime/components/web/event.js diff --git a/packages/api-proxy/src/platform/api/app/index.web.js b/packages/api-proxy/src/platform/api/app/index.web.js index 2be7f32689..571fa27485 100644 --- a/packages/api-proxy/src/platform/api/app/index.web.js +++ b/packages/api-proxy/src/platform/api/app/index.web.js @@ -3,8 +3,27 @@ import { isBrowser, isReact } from '@mpxjs/utils' global.__mpxAppCbs = global.__mpxAppCbs || { show: [], hide: [], - error: [] + error: [], + rejection: [] +} + +function off (cbs, cb) { + if (cb) { + const idx = cbs.indexOf(cb) + if (idx > -1) cbs.splice(idx, 1) + } else { + cbs.length = 0 + } +} + +function onUnhandledRejection (callback) { + if (isBrowser || isReact) { + global.__mpxAppCbs.rejection.push(callback) + } +} +function offUnhandledRejection (callback) { + off(global.__mpxAppCbs.rejection, callback) } function onError (callback) { @@ -14,9 +33,7 @@ function onError (callback) { } function offError (callback) { - const cbs = global.__mpxAppCbs.error - const index = cbs.indexOf(callback) - if (index > -1) cbs.splice(index, 1) + off(global.__mpxAppCbs.error, callback) } function onAppShow (callback) { @@ -26,9 +43,7 @@ function onAppShow (callback) { } function offAppShow (callback) { - const cbs = global.__mpxAppCbs.show - const index = cbs.indexOf(callback) - if (index > -1) cbs.splice(index, 1) + off(global.__mpxAppCbs.show, callback) } function onAppHide (callback) { @@ -38,9 +53,7 @@ function onAppHide (callback) { } function offAppHide (callback) { - const cbs = global.__mpxAppCbs.hide - const index = cbs.indexOf(callback) - if (index > -1) cbs.splice(index, 1) + off(global.__mpxAppCbs.hide, callback) } export { @@ -49,5 +62,7 @@ export { offAppShow, offAppHide, onError, - offError + offError, + onUnhandledRejection, + offUnhandledRejection } diff --git a/packages/core/package.json b/packages/core/package.json index eee049452c..5e0a073d0d 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -32,6 +32,7 @@ "@react-navigation/stack": "^7.0.4", "react": "*", "react-native": "*", + "promise": "^8.3.0", "react-native-gesture-handler": "^2.19.0", "react-native-linear-gradient": "^2.8.3", "react-native-safe-area-context": "^4.14.0", @@ -61,6 +62,9 @@ "react-native": { "optional": true }, + "promise": { + "optional": true + }, "@react-navigation/native": { "optional": true }, @@ -106,4 +110,4 @@ }, "sideEffects": false, "gitHead": "2d37697869b9bdda3efab92dda8c910b68fd05c0" -} +} \ No newline at end of file diff --git a/packages/core/src/core/proxy.js b/packages/core/src/core/proxy.js index bbbe68759a..54d4603f55 100644 --- a/packages/core/src/core/proxy.js +++ b/packages/core/src/core/proxy.js @@ -51,7 +51,7 @@ import { } from './innerLifecycle' import contextMap from '../dynamic/vnode/context' import { getAst } from '../dynamic/astCache' -import { inject, provide } from '../platform/export/apiInject' +import { inject, provide } from '../platform/export/inject' let uid = 0 diff --git a/packages/core/src/external/vue.js b/packages/core/src/external/vue.js deleted file mode 100644 index b1c6ea436a..0000000000 --- a/packages/core/src/external/vue.js +++ /dev/null @@ -1 +0,0 @@ -export default {} diff --git a/packages/core/src/external/vue.web.js b/packages/core/src/external/vue.web.js deleted file mode 100644 index 1ff878300e..0000000000 --- a/packages/core/src/external/vue.web.js +++ /dev/null @@ -1,6 +0,0 @@ -import Vue from 'vue' -import install from './vuePlugin' - -Vue.use(install) - -export default Vue diff --git a/packages/core/src/index.js b/packages/core/src/index.js index 1ee8bcef3b..95fbcea821 100644 --- a/packages/core/src/index.js +++ b/packages/core/src/index.js @@ -1,8 +1,7 @@ -import Vue from './external/vue' + import { error, diffAndCloneA, hasOwn, makeMap } from '@mpxjs/utils' import { APIs, InstanceAPIs } from './platform/export/api' - -import { createI18n } from './platform/builtInMixins/i18nMixin' +import { init } from './platform/env/index' export * from './platform/export/index' @@ -123,10 +122,6 @@ function factory () { Object.assign(Mpx, APIs) Object.assign(Mpx.prototype, InstanceAPIs) - // 输出web时在mpx上挂载Vue对象 - if (__mpx_mode__ === 'web') { - Mpx.__vue = Vue - } return Mpx } @@ -156,12 +151,6 @@ Mpx.config = { rnConfig: {} } -global.__mpx = Mpx - -if (__mpx_mode__ !== 'web') { - if (global.i18n) { - Mpx.i18n = createI18n(global.i18n) - } -} +init(Mpx) export default Mpx diff --git a/packages/core/src/platform/createApp.ios.js b/packages/core/src/platform/createApp.ios.js index 0d7f98aa60..5fae55fa0b 100644 --- a/packages/core/src/platform/createApp.ios.js +++ b/packages/core/src/platform/createApp.ios.js @@ -81,12 +81,6 @@ export default function createApp (option, config = {}) { } } - global.__mpxAppCbs = global.__mpxAppCbs || { - show: [], - hide: [], - error: [] - } - global.__mpxAppLaunched = false global.__mpxAppFocusedState = ref('show') @@ -137,6 +131,9 @@ export default function createApp (option, config = {}) { if (defaultOptions.onError) { global.__mpxAppCbs.error.push(defaultOptions.onError.bind(instance)) } + if (defaultOptions.onUnhandledRejection) { + global.__mpxAppCbs.rejection.push(defaultOptions.onUnhandledRejection.bind(instance)) + } const changeSubscription = ReactNative.AppState.addEventListener('change', (currentState) => { if (currentState === 'active') { diff --git a/packages/core/src/platform/createApp.js b/packages/core/src/platform/createApp.js index b22bab336d..0f35cf97e5 100644 --- a/packages/core/src/platform/createApp.js +++ b/packages/core/src/platform/createApp.js @@ -5,7 +5,7 @@ import { makeMap, spreadProp, isBrowser } from '@mpxjs/utils' import { mergeLifecycle } from '../convertor/mergeLifecycle' import { LIFECYCLE } from '../platform/patch/lifecycle/index' import Mpx from '../index' -import { initAppProvides } from './export/apiInject' +import { initAppProvides } from './export/inject' const appHooksMap = makeMap(mergeLifecycle(LIFECYCLE).app) @@ -47,11 +47,6 @@ export default function createApp (option, config = {}) { } global.__mpxEnterOptions = options this.$options.onLaunch && this.$options.onLaunch.call(this, options) - global.__mpxAppCbs = global.__mpxAppCbs || { - show: [], - hide: [], - error: [] - } if (isBrowser) { if (this.$options.onShow) { this.$options.onShow.call(this, options) @@ -63,6 +58,9 @@ export default function createApp (option, config = {}) { if (this.$options.onError) { global.__mpxAppCbs.error.push(this.$options.onError.bind(this)) } + if (this.$options.onUnhandledRejection) { + global.__mpxAppCbs.rejection.push(this.$options.onUnhandledRejection.bind(this)) + } } } }) diff --git a/packages/core/src/platform/env/event.js b/packages/core/src/platform/env/event.js new file mode 100644 index 0000000000..82cb7bf77a --- /dev/null +++ b/packages/core/src/platform/env/event.js @@ -0,0 +1,108 @@ +import { isBrowser } from '@mpxjs/utils' + +function extendEvent (e, extendObj = {}) { + Object.keys(extendObj).forEach((key) => { + Object.defineProperty(e, key, { + value: extendObj[key], + enumerable: true, + configurable: true, + writable: true + }) + }) +} + +function MpxEvent (layer) { + this.targetElement = null + this.touches = [] + this.touchStartX = 0 + this.touchStartY = 0 + this.startTimer = null + this.needTap = true + this.isTouchDevice = document && ('ontouchstart' in document.documentElement) + + this.onTouchStart = (event) => { + if (event.targetTouches?.length > 1) { + return true + } + this.touches = event.targetTouches + this.targetElement = event.target + this.needTap = true + this.startTimer = null + this.touchStartX = this.touches[0].pageX + this.touchStartY = this.touches[0].pageY + this.startTimer = setTimeout(() => { + this.needTap = false + this.sendEvent(this.targetElement, 'longpress', event) + this.sendEvent(this.targetElement, 'longtap', event) + }, 350) + } + + this.onTouchMove = (event) => { + const touch = event.changedTouches[0] + if (Math.abs(touch.pageX - this.touchStartX) > 1 || Math.abs(touch.pageY - this.touchStartY) > 1) { + this.needTap = false + this.startTimer && clearTimeout(this.startTimer) + this.startTimer = null + } + } + + this.onTouchEnd = (event) => { + if (event.targetTouches?.length > 1) { + return true + } + this.startTimer && clearTimeout(this.startTimer) + this.startTimer = null + if (this.needTap) { + this.sendEvent(this.targetElement, 'tap', event) + } + } + + this.onClick = (event) => { + this.targetElement = event.target + this.sendEvent(this.targetElement, 'tap', event) + } + this.sendEvent = (targetElement, type, event) => { + const touchEvent = new CustomEvent(type, { + bubbles: true, + cancelable: true + }) + const changedTouches = event.changedTouches || [] + extendEvent(touchEvent, { + timeStamp: event.timeStamp, + changedTouches, + touches: changedTouches, + detail: { + // pc端点击事件可能没有changedTouches,所以直接从 event中取 + x: changedTouches[0]?.pageX || event.pageX || 0, + y: changedTouches[0]?.pageY || event.pageY || 0 + } + }) + targetElement && targetElement.dispatchEvent(touchEvent) + } + + this.addListener = () => { + if (this.isTouchDevice) { + layer.addEventListener('touchstart', this.onTouchStart, true) + layer.addEventListener('touchmove', this.onTouchMove, true) + layer.addEventListener('touchend', this.onTouchEnd, true) + } else { + layer.addEventListener('click', this.onClick, true) + } + } + this.addListener() +} + +export function initEvent () { + if (isBrowser && !global.__mpxCreatedEvent) { + global.__mpxCreatedEvent = true + if (document.readyState === 'complete' || document.readyState === 'interactive') { + // eslint-disable-next-line no-new + new MpxEvent(document.body) + } else { + document.addEventListener('DOMContentLoaded', function () { + // eslint-disable-next-line no-new + new MpxEvent(document.body) + }, false) + } + } +} diff --git a/packages/core/src/platform/env/index.ios.js b/packages/core/src/platform/env/index.ios.js new file mode 100644 index 0000000000..f18fcbcf4c --- /dev/null +++ b/packages/core/src/platform/env/index.ios.js @@ -0,0 +1,51 @@ +import { createI18n } from '../builtInMixins/i18nMixin' + +export function init (Mpx) { + global.__mpx = Mpx + global.__mpxAppCbs = global.__mpxAppCbs || { + show: [], + hide: [], + error: [], + rejection: [] + } + if (global.i18n) { + Mpx.i18n = createI18n(global.i18n) + } + initGlobalErrorHandling() +} + +function initGlobalErrorHandling () { + if (global.ErrorUtils) { + const defaultHandler = global.ErrorUtils.getGlobalHandler() + global.ErrorUtils.setGlobalHandler((error, isFatal) => { + if (global.__mpxAppCbs && global.__mpxAppCbs.error && global.__mpxAppCbs.error.length) { + global.__mpxAppCbs.error.forEach((cb) => { + cb(error) + }) + } else if (defaultHandler) { + defaultHandler(error, isFatal) + } else { + console.error(`${error.name}: ${error.message}\n`) + } + }) + } + + const rejectionTrackingOptions = { + allRejections: true, + onUnhandled (id, error) { + if (global.__mpxAppCbs && global.__mpxAppCbs.rejection && global.__mpxAppCbs.rejection.length) { + global.__mpxAppCbs.rejection.forEach((cb) => { + cb(error, id) + }) + } else { + console.warn(`UNHANDLED PROMISE REJECTION (id: ${id}): ${error}\n`) + } + } + } + + if (global?.HermesInternal?.hasPromise?.()) { + global.HermesInternal?.enablePromiseRejectionTracker?.(rejectionTrackingOptions) + } else { + require('promise/setimmediate/rejection-tracking').enable(rejectionTrackingOptions) + } +} diff --git a/packages/core/src/platform/env/index.js b/packages/core/src/platform/env/index.js new file mode 100644 index 0000000000..3382486e17 --- /dev/null +++ b/packages/core/src/platform/env/index.js @@ -0,0 +1,8 @@ +import { createI18n } from '../builtInMixins/i18nMixin' + +export function init (Mpx) { + global.__mpx = Mpx + if (global.i18n) { + Mpx.i18n = createI18n(global.i18n) + } +} diff --git a/packages/core/src/platform/env/index.web.js b/packages/core/src/platform/env/index.web.js new file mode 100644 index 0000000000..58dccf2d03 --- /dev/null +++ b/packages/core/src/platform/env/index.web.js @@ -0,0 +1,48 @@ +import Vue from 'vue' +import install from './vuePlugin' +import { isBrowser, error, warn } from '@mpxjs/utils' +import { initEvent } from './event' + +export function init (Mpx) { + global.__mpx = Mpx + global.__mpxAppCbs = global.__mpxAppCbs || { + show: [], + hide: [], + error: [], + rejection: [] + } + Mpx.__vue = Vue + Vue.use(install) + initEvent() + initGlobalErrorHandling() +} + +function initGlobalErrorHandling () { + Vue.config.errorHandler = (e, vm, info) => { + error(`Unhandled error occurs${info ? ` during execution of [${info}]` : ''}!`, vm?.__mpxProxy?.options.mpxFileResource, e) + } + Vue.config.warnHandler = (msg, vm, trace) => { + warn(msg, vm?.__mpxProxy?.options.mpxFileResource, trace) + } + + if (isBrowser) { + window.addEventListener('error', (event) => { + if (global.__mpxAppCbs && global.__mpxAppCbs.error && global.__mpxAppCbs.error.length) { + global.__mpxAppCbs.error.forEach((cb) => { + cb(event.error) + }) + } else { + console.error(`${event.type}: ${event.message}\n`) + } + }) + window.addEventListener('unhandledrejection', (event) => { + if (global.__mpxAppCbs && global.__mpxAppCbs.rejection && global.__mpxAppCbs.rejection.length) { + global.__mpxAppCbs.rejection.forEach((cb) => { + cb(event.reason, event.promise) + }) + } else { + console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}\n`) + } + }) + } +} diff --git a/packages/core/src/external/vuePlugin.js b/packages/core/src/platform/env/vuePlugin.js similarity index 98% rename from packages/core/src/external/vuePlugin.js rename to packages/core/src/platform/env/vuePlugin.js index f83b9f0734..4ed365d986 100644 --- a/packages/core/src/external/vuePlugin.js +++ b/packages/core/src/platform/env/vuePlugin.js @@ -1,7 +1,7 @@ import { walkChildren, parseSelector, error, hasOwn, collectDataset } from '@mpxjs/utils' import { createSelectorQuery, createIntersectionObserver } from '@mpxjs/api-proxy' import { EffectScope } from 'vue' -import { PausedState } from '../helper/const' +import { PausedState } from '../../helper/const' const hackEffectScope = () => { EffectScope.prototype.pause = function () { diff --git a/packages/core/src/platform/export/index.js b/packages/core/src/platform/export/index.js index 75b59133bb..bf570a7994 100644 --- a/packages/core/src/platform/export/index.js +++ b/packages/core/src/platform/export/index.js @@ -46,4 +46,4 @@ export { export { provide, inject -} from './apiInject' +} from './inject' diff --git a/packages/core/src/platform/export/apiInject.js b/packages/core/src/platform/export/inject.js similarity index 100% rename from packages/core/src/platform/export/apiInject.js rename to packages/core/src/platform/export/inject.js diff --git a/packages/core/src/platform/export/apiInject.web.js b/packages/core/src/platform/export/inject.web.js similarity index 100% rename from packages/core/src/platform/export/apiInject.web.js rename to packages/core/src/platform/export/inject.web.js diff --git a/packages/utils/src/errorHandling.js b/packages/utils/src/errorHandling.js index 29ded07c64..b356d9596d 100644 --- a/packages/utils/src/errorHandling.js +++ b/packages/utils/src/errorHandling.js @@ -2,7 +2,7 @@ import { isFunction, isPromise } from './base' import { error } from './log' function handleError (e, instance, info) { - error(`Unhandled error occurs${info ? ` during execution of [${info}]` : ''}!`, instance?.options?.mpxFileResource, e) + error(`Unhandled error occurs${info ? ` during execution of [${info}]` : ''}!`, instance?.options.mpxFileResource, e) } export function callWithErrorHandling (fn, instance, info, args) { diff --git a/packages/utils/src/log.js b/packages/utils/src/log.js index eba7143ff3..72fb7aed90 100644 --- a/packages/utils/src/log.js +++ b/packages/utils/src/log.js @@ -18,8 +18,9 @@ export function warn (msg, location, e) { const warnHandler = global.__mpx?.config.warnHandler if (isFunction(warnHandler)) { warnHandler(msg, location, e) + } else { + log('warn', msg, location, e) } - return log('warn', msg, location, e) } } @@ -27,8 +28,9 @@ export function error (msg, location, e) { const errorHandler = global.__mpx?.config.errorHandler if (isFunction(errorHandler)) { errorHandler(msg, location, e) + } else { + log('error', msg, location, e) } - return log('error', msg, location, e) } function log (type, msg, location, e) { diff --git a/packages/webpack-plugin/lib/runtime/components/web/event.js b/packages/webpack-plugin/lib/runtime/components/web/event.js deleted file mode 100644 index 41b6d9d5aa..0000000000 --- a/packages/webpack-plugin/lib/runtime/components/web/event.js +++ /dev/null @@ -1,105 +0,0 @@ -import { extendEvent } from './getInnerListeners' -import { isBrowser } from '../../env' - -function MpxEvent (layer) { - this.targetElement = null - - this.touches = [] - - this.touchStartX = 0 - - this.touchStartY = 0 - - this.startTimer = null - - this.needTap = true - - this.isTouchDevice = document && ('ontouchstart' in document.documentElement) - - this.onTouchStart = (event) => { - if (event.targetTouches?.length > 1) { - return true - } - - this.touches = event.targetTouches - this.targetElement = event.target - this.needTap = true - this.startTimer = null - this.touchStartX = this.touches[0].pageX - this.touchStartY = this.touches[0].pageY - this.startTimer = setTimeout(() => { - this.needTap = false - this.sendEvent(this.targetElement, 'longpress', event) - this.sendEvent(this.targetElement, 'longtap', event) - }, 350) - } - - this.onTouchMove = (event) => { - const touch = event.changedTouches[0] - if (Math.abs(touch.pageX - this.touchStartX) > 1 || Math.abs(touch.pageY - this.touchStartY) > 1) { - this.needTap = false - this.startTimer && clearTimeout(this.startTimer) - this.startTimer = null - } - } - - this.onTouchEnd = (event) => { - if (event.targetTouches?.length > 1) { - return true - } - this.startTimer && clearTimeout(this.startTimer) - this.startTimer = null - if (this.needTap) { - this.sendEvent(this.targetElement, 'tap', event) - } - } - - this.onClick = (event) => { - this.targetElement = event.target - this.sendEvent(this.targetElement, 'tap', event) - } - this.sendEvent = (targetElement, type, event) => { - const touchEvent = new CustomEvent(type, { - bubbles: true, - cancelable: true - }) - const changedTouches = event.changedTouches || [] - extendEvent(touchEvent, { - timeStamp: event.timeStamp, - changedTouches, - touches: changedTouches, - detail: { - // pc端点击事件可能没有changedTouches,所以直接从 event中取 - x: changedTouches[0]?.pageX || event.pageX || 0, - y: changedTouches[0]?.pageY || event.pageY || 0 - } - }) - targetElement && targetElement.dispatchEvent(touchEvent) - } - - this.addListener = () => { - if (this.isTouchDevice) { - layer.addEventListener('touchstart', this.onTouchStart, true) - layer.addEventListener('touchmove', this.onTouchMove, true) - layer.addEventListener('touchend', this.onTouchEnd, true) - } else { - layer.addEventListener('click', this.onClick, true) - } - } - this.addListener() -} - -export function createEvent () { - if (isBrowser && !global.__mpxCreatedEvent) { - global.__mpxCreatedEvent = true - if (document.readyState === 'complete' || document.readyState === 'interactive') { - // eslint-disable-next-line no-new - new MpxEvent(document.body) - } else { - document.addEventListener('DOMContentLoaded', function () { - // eslint-disable-next-line no-new - new MpxEvent(document.body) - }, false) - } - } -} diff --git a/packages/webpack-plugin/lib/runtime/optionProcessor.js b/packages/webpack-plugin/lib/runtime/optionProcessor.js index b1949f04cc..bb9ffa9d6c 100644 --- a/packages/webpack-plugin/lib/runtime/optionProcessor.js +++ b/packages/webpack-plugin/lib/runtime/optionProcessor.js @@ -2,9 +2,6 @@ import { hasOwn, isEmptyObject, extend } from './utils' import { isBrowser } from './env' import transRpxStyle from './transRpxStyle' import animation from './animation' -import { createEvent } from './components/web/event' - -createEvent() export function processComponentOption ( { @@ -309,25 +306,6 @@ function createApp ({ componentsMap, Vue, pagesMap, firstPage, VueRouter, App, t }) // 处理visibilitychange时触发当前活跃页面组件的onshow/onhide if (isBrowser) { - const errorHandler = function (args, fromVue) { - if (global.__mpxAppCbs && global.__mpxAppCbs.error && global.__mpxAppCbs.error.length) { - global.__mpxAppCbs.error.forEach((cb) => { - cb.apply(null, args) - }) - console.error(...args) - } else if (fromVue) { - throw args[0] - } - } - Vue.config.errorHandler = (...args) => { - return errorHandler(args, true) - } - window.addEventListener('error', (event) => { - return errorHandler([event.error, event]) - }) - window.addEventListener('unhandledrejection', (event) => { - return errorHandler([event.reason, event]) - }) document.addEventListener('visibilitychange', function () { const vnode = global.__mpxRouter && global.__mpxRouter.__mpxActiveVnode if (vnode && vnode.componentInstance) { From 244d3032302b68b936d53757cb2ae39a8d68f23c Mon Sep 17 00:00:00 2001 From: xuegan Date: Wed, 18 Dec 2024 18:10:32 +0800 Subject: [PATCH 45/76] =?UTF-8?q?feat:=20=E4=BF=AE=E5=A4=8D=E8=BE=93?= =?UTF-8?q?=E5=87=BAH5=20scoped=20:deep=20=E8=AF=AD=E6=B3=95=E4=B8=8D?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/style-compiler/plugins/scope-id.js | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js b/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js index 3c2745fcca..10831c1662 100644 --- a/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js +++ b/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js @@ -1,6 +1,8 @@ const selectorParser = require('postcss-selector-parser') // scope-id - +function isSpaceCombinator(node) { + return node.type === "combinator" && /^\s+$/.test(node.value); +} module.exports = ({ id }) => { return { postcssPlugin: 'scope-id', @@ -31,6 +33,32 @@ module.exports = ({ id }) => { n.spaces.before = n.spaces.after = '' return false } + if (n.type === 'pseudo' && n.value === ':deep') { + if (n.nodes.length) { + let last = n; + n.nodes[0].each((ss) => { + selector.insertAfter(last, ss); + last = ss; + }); + const prev = selector.at(selector.index(n) - 1); + if (!prev || !isSpaceCombinator(prev)) { + selector.insertAfter( + n, + selectorParser.combinator({ + value: " " + }) + ); + } + selector.removeChild(n); + } else { + const prev = selector.at(selector.index(n) - 1); + if (prev && isSpaceCombinator(prev)) { + selector.removeChild(prev); + } + selector.removeChild(n); + } + return false + } // /deep/ alias for >>>, since >>> doesn't work in SASS if (n.type === 'tag' && n.value === '/deep/') { const prev = n.prev() From 751f8525d3995ea2de55110564bcae5dd0ea113b Mon Sep 17 00:00:00 2001 From: xuegan Date: Wed, 18 Dec 2024 18:14:28 +0800 Subject: [PATCH 46/76] fix: eslint error --- .../lib/style-compiler/plugins/scope-id.js | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js b/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js index 10831c1662..80d6557afc 100644 --- a/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js +++ b/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js @@ -1,7 +1,7 @@ const selectorParser = require('postcss-selector-parser') // scope-id -function isSpaceCombinator(node) { - return node.type === "combinator" && /^\s+$/.test(node.value); +function isSpaceCombinator (node) { + return node.type === 'combinator' && /^\s+$/.test(node.value) } module.exports = ({ id }) => { return { @@ -35,27 +35,27 @@ module.exports = ({ id }) => { } if (n.type === 'pseudo' && n.value === ':deep') { if (n.nodes.length) { - let last = n; + let last = n n.nodes[0].each((ss) => { - selector.insertAfter(last, ss); - last = ss; - }); - const prev = selector.at(selector.index(n) - 1); + selector.insertAfter(last, ss) + last = ss + }) + const prev = selector.at(selector.index(n) - 1) if (!prev || !isSpaceCombinator(prev)) { selector.insertAfter( n, selectorParser.combinator({ - value: " " + value: ' ' }) - ); + ) } - selector.removeChild(n); + selector.removeChild(n) } else { - const prev = selector.at(selector.index(n) - 1); + const prev = selector.at(selector.index(n) - 1) if (prev && isSpaceCombinator(prev)) { - selector.removeChild(prev); + selector.removeChild(prev) } - selector.removeChild(n); + selector.removeChild(n) } return false } From 189caf2aebbc290bba474f6c40548de4470d7991 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Wed, 18 Dec 2024 18:47:28 +0800 Subject: [PATCH 47/76] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=B8=80=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/platform/api/image/index.ios.js | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 packages/api-proxy/src/platform/api/image/index.ios.js diff --git a/packages/api-proxy/src/platform/api/image/index.ios.js b/packages/api-proxy/src/platform/api/image/index.ios.js new file mode 100644 index 0000000000..da1dd03c71 --- /dev/null +++ b/packages/api-proxy/src/platform/api/image/index.ios.js @@ -0,0 +1,33 @@ +import { envError } from '../../../common/js' +import { Image } from 'react-native' + +const previewImage = envError('previewImage') + +const compressImage = envError('compressImage') + +const getImageInfo = function(options = {}) { + const { src, success, fail, complete } = options + let getImage + if (src !== undefined) { + result = { + errMsg: 'getImageInfo:fail parameter error: parameter.src should be String instead of Undefined;', + errno: 1001 + } + fail(result) + complete(result) + } + if (src === '') { + return + } + Image.getSize(src, function(res) { + console.log(res, 'test') + }, function (err) { + console.log(err, '=====') + }) +} + +export { + previewImage, + compressImage, + getImageInfo +} From 9cd53dadb8351dca66f4ea81feeb98f6b318a301 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Wed, 18 Dec 2024 20:32:38 +0800 Subject: [PATCH 48/76] =?UTF-8?q?chore:=20=E4=BC=98=E5=8C=96rawEventKeys?= =?UTF-8?q?=E7=94=9F=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/runtime/components/react/getInnerListeners.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts index 60d28c591c..67b13da734 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts @@ -295,17 +295,16 @@ const useInnerProps = ( propsRef.current = extendObject({}, props, additionalProps) let hashEventKey = '' + const rawEventKeys: Array = [] + for (const key in eventConfigMap) { if (hasOwn(propsRef.current, key)) { eventConfig[key] = eventConfigMap[key].events hashEventKey = hashEventKey + eventConfigMap[key].bitFlag + rawEventKeys.push(key) } } - const rawEventKeys = useMemo(() => { - return Object.keys(eventConfig) - }, [hashEventKey]) - if (!rawEventKeys.length || config.disableTouch) { return omit(propsRef.current, removeProps) } From 07c65e69dde794b43c718281680c53cda9bbae05 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Wed, 18 Dec 2024 20:39:29 +0800 Subject: [PATCH 49/76] =?UTF-8?q?=E6=94=AF=E6=8C=81invoke?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/mpx-webview/H5/webviewbridge.min.js | 2 +- .../runtime/components/react/mpx-web-view.tsx | 13 ++-- .../dist/webviewbridge.esm.browser.js | 30 +++++--- .../dist/webviewbridge.esm.browser.min.js | 2 +- .../webview-bridge/dist/webviewbridge.esm.js | 74 +++++-------------- packages/webview-bridge/dist/webviewbridge.js | 74 +++++-------------- .../webview-bridge/dist/webviewbridge.min.js | 2 +- packages/webview-bridge/src/index.js | 23 ++++-- 8 files changed, 81 insertions(+), 139 deletions(-) diff --git a/examples/mpx-webview/H5/webviewbridge.min.js b/examples/mpx-webview/H5/webviewbridge.min.js index 9dac705da4..0c7cf98677 100644 --- a/examples/mpx-webview/H5/webviewbridge.min.js +++ b/examples/mpx-webview/H5/webviewbridge.min.js @@ -3,4 +3,4 @@ * (c) 2024 @mpxjs team * @license Apache */ -var e,t;e=this,t=function(){"use strict";function e(e,t,o){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var n=o.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function t(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,n)}return o}var o,n,a,r,i=function(o){for(var n=1;n-1&&g.indexOf("MiniProgram")>-1?c="my":g.toLowerCase().indexOf("miniprogram")>-1?c=g.indexOf("QQ")>-1?"qq":"wx":g.indexOf("swan/")>-1?c="swan":g.indexOf("toutiao")>-1?c="tt":(c="web",window.addEventListener("message",(function(e){var t=e.data,o=t;try{"string"==typeof t&&(o=JSON.parse(t))}catch(e){}var n=o,a=n.callbackId,r=n.error,i=n.result;void 0!==a&&d[a]&&(r?d[a](r):d[a](null,i),delete d[a])}),!1));var w=!1;function u(e){w?e():o.then((function(){w=!0,e()}))}var l={config:function(e){"wx"===c?u((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function f(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("getEnv"!==e){var o=++s;d[o]=function(e,n){e?(t.fail&&t.fail(e),t.complete&&t.complete(e)):(t.success&&t.success(n),t.complete&&t.complete(n)),delete d[o]};var n={type:e,callbackId:s,payload:t};void 0!==p&&(n.clientUid=p),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(n)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(n),"*")}else t({webapp:!0})}var m=function(){var e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[c]||{},t={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation"],tt:[]}[c]||[];(e.api||[]).forEach((function(t){l[t]=function(){for(var o=arguments.length,n=new Array(o),a=0;a1&&void 0!==arguments[1]?arguments[1]:{},o=t.time,n=void 0===o?5e3:o,a=t.crossOrigin,r=void 0!==a&&a;function i(){return new Promise((function(t,o){var n=document.createElement("script");n.type="text/javascript",n.async="async",r&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(t(),n.onload=n.onreadystatechange=null)},n.onerror=function(){o(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(t,o){setTimeout((function(){o(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([i(),c()])}(i[c].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),m(),l},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).mpx=t(); \ No newline at end of file +var e,o;e=this,o=function(){"use strict";var e,o,a,n,t=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(a=location.href,(n=/mpx_webview_id=(\d+)/g.exec(a))&&n[1]&&(o=+n[1]),o),s={},d=navigator.userAgent;d.indexOf("AlipayClient")>-1&&d.indexOf("MiniProgram")>-1?i="my":d.toLowerCase().indexOf("miniprogram")>-1?i=d.indexOf("QQ")>-1?"qq":"wx":d.indexOf("swan/")>-1?i="swan":d.indexOf("toutiao")>-1?i="tt":(i="web",window.addEventListener("message",(function(e){var o=e.data,a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}var n=a,t=n.callbackId,i=n.error,r=n.result;void 0!==t&&s[t]&&(i?s[t](i):s[t](null,r),delete s[t])}),!1));var g=!1;function p(o){g?o():e.then((function(){g=!0,o()}))}var w={config:function(e){"wx"===i?p((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function l(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),n=1;n1&&void 0!==arguments[1]?arguments[1]:{},a=o.time,n=void 0===a?5e3:a,t=o.crossOrigin,i=void 0!==t&&t;function r(){return new Promise((function(o,a){var n=document.createElement("script");n.type="text/javascript",n.async="async",i&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){a(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(o,a){setTimeout((function(){a(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([r(),c()])}(t[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),v(),w},"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e=e||self).mpx=o(); \ No newline at end of file diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 282aa035fd..0362bc2117 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -42,15 +42,12 @@ type MessageData = { const _WebView = forwardRef, WebViewProps>((props, ref): JSX.Element | null => { const { src, bindmessage, bindload, binderror } = props const mpx = global.__mpx - if (!src) { - return null - } if (props.style) { warn('The web-view component does not support the style prop.') } const pageId = useContext(RouteContext) const currentPage = useMemo(() => getCurrentPage(pageId), [pageId]) - + const webViewRef = useRef(null) const defaultWebViewStyle = { position: 'absolute' as 'absolute' | 'relative' | 'static', left: 0 as number, @@ -59,11 +56,14 @@ const _WebView = forwardRef, WebViewProps>((pr bottom: 0 as number } - const webViewRef = useRef(null) useNodesRef(props, ref, webViewRef, { style: defaultWebViewStyle }) + if (!src) { + return null + } + const _load = function (res: WebViewNavigationEvent) { const result = { type: 'load', @@ -167,7 +167,8 @@ const _WebView = forwardRef, WebViewProps>((pr if (type) { const implement = mpx.config.webviewConfig.apiImplementations && mpx.config.webviewConfig.apiImplementations[type] if (isFunction(implement)) { - asyncCallback = Promise.resolve(implement()) + const params = type === 'invoke' && Array.isArray(postData) ? postData : [postData] + asyncCallback = Promise.resolve(implement(...params)) } else { /* eslint-disable prefer-promise-reject-errors */ asyncCallback = Promise.reject({ diff --git a/packages/webview-bridge/dist/webviewbridge.esm.browser.js b/packages/webview-bridge/dist/webviewbridge.esm.browser.js index 3ad4a9e63e..07f9c1031e 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.browser.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.browser.js @@ -44,7 +44,7 @@ function loadScript (url, { time = 5000, crossOrigin = false } = {}) { } let sdkReady; -const SDK_URL_MAP = { +const SDK_URL_MAP = Object.assign({ wx: { url: 'https://res.wx.qq.com/open/js/jweixin-1.3.2.js' }, @@ -59,9 +59,8 @@ const SDK_URL_MAP = { }, tt: { url: 'https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js' - }, - ...window.sdkUrlMap -}; + } +}, window.sdkUrlMap); function getMpxWebViewId () { const href = location.href; const reg = /mpx_webview_id=(\d+)/g; @@ -141,7 +140,11 @@ const webviewBridge = { } }; -function postMessage (type, data = {}) { +function postMessage (type, ...extraData) { + let data = extraData[0] || {}; + if (type === 'invoke') { + data = extraData[1] || {}; + } if (type !== 'getEnv') { const currentCallbackId = ++callbackId; callbacks[currentCallbackId] = (err, res) => { @@ -157,7 +160,7 @@ function postMessage (type, data = {}) { const postParams = { type, callbackId, - payload: data + payload: type === 'invoke' ? extraData : data }; if (clientUid !== undefined) { postParams.clientUid = clientUid; @@ -185,7 +188,8 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'postMessage', - 'getEnv' + 'getEnv', + 'invoke' ] }, tt: { @@ -206,7 +210,8 @@ const getWebviewApi = () => { 'uploadFile', 'getNetworkType', 'openLocation', - 'getLocation' + 'getLocation', + 'invoke' ] }, swan: { @@ -218,7 +223,8 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'getEnv', - 'postMessage' + 'postMessage', + 'invoke' ] }, qq: { @@ -230,7 +236,8 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'getEnv', - 'postMessage' + 'postMessage', + 'invoke' ] } }; @@ -304,7 +311,8 @@ const getWebviewApi = () => { 'getEnv', 'postMessage', 'getLoadError', - 'getLocation' + 'getLocation', + 'invoke' ], tt: [] }; diff --git a/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js b/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js index 019f5df46b..78546b7526 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js @@ -3,4 +3,4 @@ * (c) 2024 @mpxjs team * @license Apache */ -let e;const o={wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"},...window.sdkUrlMap};let a=null,t=0;const n=function(){const e=location.href,o=/mpx_webview_id=(\d+)/g.exec(e);let a;return o&&o[1]&&(a=+o[1]),a}(),i={},s=navigator.userAgent;s.indexOf("AlipayClient")>-1&&s.indexOf("MiniProgram")>-1?a="my":s.toLowerCase().indexOf("miniprogram")>-1?a=s.indexOf("QQ")>-1?"qq":"wx":s.indexOf("swan/")>-1?a="swan":s.indexOf("toutiao")>-1?a="tt":(a="web",window.addEventListener("message",e=>{const o=e.data;let a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}const{callbackId:t,error:n,result:s}=a;void 0!==t&&i[t]&&(n?i[t](n):i[t](null,s),delete i[t])},!1));let r=!1;function c(o){r?o():e.then(()=>{r=!0,o()})}const d={config(e){"wx"===a?c(()=>{window.wx&&window.wx.config(e)}):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};const w=()=>{const e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[a]||{},o={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation"],tt:[]}[a]||[];(e.api||[]).forEach(o=>{d[o]=(...t)=>{c(()=>{window[a][e.keyName][o](...t)})}}),o.forEach(e=>{d[e]=(...o)=>{"web"===a?function(e,o={}){if("getEnv"!==e){const a=++t;i[a]=(e,t)=>{e?(o.fail&&o.fail(e),o.complete&&o.complete(e)):(o.success&&o.success(t),o.complete&&o.complete(t)),delete i[a]};const s={type:e,callbackId:t,payload:o};void 0!==n&&(s.clientUid=n),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(s)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(s),"*")}else o({webapp:!0})}(e,...o):c("wx"===a?()=>{window[a]&&window[a].ready(()=>{window[a][e](...o)})}:()=>{window[a][e](...o)})}})};e="web"!==a?o[a].url?function(e,{time:o=5e3,crossOrigin:a=!1}={}){return Promise.race([new Promise((o,t)=>{const n=document.createElement("script");n.type="text/javascript",n.async="async",a&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){t(new Error(`load ${e} error`)),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}),new Promise((a,t)=>{setTimeout(()=>{t(new Error(`load ${e} timeout`))},o)})])}(o[a].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),w();export default d; \ No newline at end of file +let e;const o=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap);let a=null,t=0;const n=function(){const e=location.href,o=/mpx_webview_id=(\d+)/g.exec(e);let a;return o&&o[1]&&(a=+o[1]),a}(),i={},s=navigator.userAgent;s.indexOf("AlipayClient")>-1&&s.indexOf("MiniProgram")>-1?a="my":s.toLowerCase().indexOf("miniprogram")>-1?a=s.indexOf("QQ")>-1?"qq":"wx":s.indexOf("swan/")>-1?a="swan":s.indexOf("toutiao")>-1?a="tt":(a="web",window.addEventListener("message",e=>{const o=e.data;let a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}const{callbackId:t,error:n,result:s}=a;void 0!==t&&i[t]&&(n?i[t](n):i[t](null,s),delete i[t])},!1));let r=!1;function c(o){r?o():e.then(()=>{r=!0,o()})}const d={config(e){"wx"===a?c(()=>{window.wx&&window.wx.config(e)}):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};const w=()=>{const e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv","invoke"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation","invoke"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","invoke"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","invoke"]}}[a]||{},o={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation","invoke"],tt:[]}[a]||[];(e.api||[]).forEach(o=>{d[o]=(...t)=>{c(()=>{window[a][e.keyName][o](...t)})}}),o.forEach(e=>{d[e]=(...o)=>{"web"===a?function(e,...o){let a=o[0]||{};if("invoke"===e&&(a=o[1]||{}),"getEnv"!==e){const s=++t;i[s]=(e,o)=>{e?(a.fail&&a.fail(e),a.complete&&a.complete(e)):(a.success&&a.success(o),a.complete&&a.complete(o)),delete i[s]};const r={type:e,callbackId:t,payload:"invoke"===e?o:a};void 0!==n&&(r.clientUid=n),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(r)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(r),"*")}else a({webapp:!0})}(e,...o):c("wx"===a?()=>{window[a]&&window[a].ready(()=>{window[a][e](...o)})}:()=>{window[a][e](...o)})}})};e="web"!==a?o[a].url?function(e,{time:o=5e3,crossOrigin:a=!1}={}){return Promise.race([new Promise((o,t)=>{const n=document.createElement("script");n.type="text/javascript",n.async="async",a&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){t(new Error(`load ${e} error`)),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}),new Promise((a,t)=>{setTimeout(()=>{t(new Error(`load ${e} timeout`))},o)})])}(o[a].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),w();export default d; \ No newline at end of file diff --git a/packages/webview-bridge/dist/webviewbridge.esm.js b/packages/webview-bridge/dist/webviewbridge.esm.js index d53778bd49..622afc4dae 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.js @@ -3,50 +3,6 @@ * (c) 2024 @mpxjs team * @license Apache */ -function _defineProperty(e, r, t) { - return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { - value: t, - enumerable: !0, - configurable: !0, - writable: !0 - }) : e[r] = t, e; -} -function ownKeys(e, r) { - var t = Object.keys(e); - if (Object.getOwnPropertySymbols) { - var o = Object.getOwnPropertySymbols(e); - r && (o = o.filter(function (r) { - return Object.getOwnPropertyDescriptor(e, r).enumerable; - })), t.push.apply(t, o); - } - return t; -} -function _objectSpread2(e) { - for (var r = 1; r < arguments.length; r++) { - var t = null != arguments[r] ? arguments[r] : {}; - r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { - _defineProperty(e, r, t[r]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { - Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); - }); - } - return e; -} -function _toPrimitive(t, r) { - if ("object" != typeof t || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r || "default"); - if ("object" != typeof i) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); -} -function _toPropertyKey(t) { - var i = _toPrimitive(t, "string"); - return "symbol" == typeof i ? i : i + ""; -} - function loadScript(url) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$time = _ref.time, @@ -88,7 +44,7 @@ function loadScript(url) { } var sdkReady; -var SDK_URL_MAP = _objectSpread2({ +var SDK_URL_MAP = Object.assign({ wx: { url: 'https://res.wx.qq.com/open/js/jweixin-1.3.2.js' }, @@ -183,7 +139,13 @@ var webviewBridge = { } }; function postMessage(type) { - var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + for (var _len = arguments.length, extraData = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + extraData[_key - 1] = arguments[_key]; + } + var data = extraData[0] || {}; + if (type === 'invoke') { + data = extraData[1] || {}; + } if (type !== 'getEnv') { var currentCallbackId = ++callbackId; callbacks[currentCallbackId] = function (err, res) { @@ -199,7 +161,7 @@ function postMessage(type) { var postParams = { type: type, callbackId: callbackId, - payload: data + payload: type === 'invoke' ? extraData : data }; if (clientUid !== undefined) { postParams.clientUid = clientUid; @@ -219,26 +181,26 @@ var getWebviewApi = function getWebviewApi() { var multiApiMap = { wx: { keyName: 'miniProgram', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'postMessage', 'getEnv'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'postMessage', 'getEnv', 'invoke'] }, tt: { keyName: 'miniProgram', - api: ['redirectTo', 'navigateTo', 'switchTab', 'reLaunch', 'navigateBack', 'setSwipeBackModeSync', 'postMessage', 'getEnv', 'checkJsApi', 'chooseImage', 'compressImage', 'previewImage', 'uploadFile', 'getNetworkType', 'openLocation', 'getLocation'] + api: ['redirectTo', 'navigateTo', 'switchTab', 'reLaunch', 'navigateBack', 'setSwipeBackModeSync', 'postMessage', 'getEnv', 'checkJsApi', 'chooseImage', 'compressImage', 'previewImage', 'uploadFile', 'getNetworkType', 'openLocation', 'getLocation', 'invoke'] }, swan: { keyName: 'webView', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'invoke'] }, qq: { keyName: 'miniProgram', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'invoke'] } }; var singleApiMap = { wx: ['checkJSApi', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'startSearchBeacons', 'stopSearchBeacons', 'onSearchBeacons', 'scanQRCode', 'chooseCard', 'addCard', 'openCard'], my: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'chooseImage', 'previewImage', 'getLocation', 'openLocation', 'alert', 'showLoading', 'hideLoading', 'getNetworkType', 'startShare', 'tradePay', 'postMessage', 'onMessage', 'getEnv'], swan: ['makePhoneCall', 'setClipboardData', 'getNetworkType', 'openLocation', 'getLocation', 'chooseLocation', 'chooseImage', 'previewImage', 'openShare', 'navigateToSmartProgram'], - web: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'getLoadError', 'getLocation'], + web: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'getLoadError', 'getLocation', 'invoke'], tt: [] }; var multiApi = multiApiMap[env] || {}; @@ -246,8 +208,8 @@ var getWebviewApi = function getWebviewApi() { var multiApiLists = multiApi.api || []; multiApiLists.forEach(function (item) { webviewBridge[item] = function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; } runWebviewApiMethod(function () { var _window$env$multiApi$; @@ -257,8 +219,8 @@ var getWebviewApi = function getWebviewApi() { }); singleApi.forEach(function (item) { webviewBridge[item] = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; } if (env === 'web') { postMessage.apply(void 0, [item].concat(args)); diff --git a/packages/webview-bridge/dist/webviewbridge.js b/packages/webview-bridge/dist/webviewbridge.js index e49ba87440..0cb2705262 100644 --- a/packages/webview-bridge/dist/webviewbridge.js +++ b/packages/webview-bridge/dist/webviewbridge.js @@ -9,50 +9,6 @@ (global = global || self, global.mpx = factory()); }(this, (function () { 'use strict'; - function _defineProperty(e, r, t) { - return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { - value: t, - enumerable: !0, - configurable: !0, - writable: !0 - }) : e[r] = t, e; - } - function ownKeys(e, r) { - var t = Object.keys(e); - if (Object.getOwnPropertySymbols) { - var o = Object.getOwnPropertySymbols(e); - r && (o = o.filter(function (r) { - return Object.getOwnPropertyDescriptor(e, r).enumerable; - })), t.push.apply(t, o); - } - return t; - } - function _objectSpread2(e) { - for (var r = 1; r < arguments.length; r++) { - var t = null != arguments[r] ? arguments[r] : {}; - r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { - _defineProperty(e, r, t[r]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { - Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); - }); - } - return e; - } - function _toPrimitive(t, r) { - if ("object" != typeof t || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r || "default"); - if ("object" != typeof i) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); - } - function _toPropertyKey(t) { - var i = _toPrimitive(t, "string"); - return "symbol" == typeof i ? i : i + ""; - } - function loadScript(url) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$time = _ref.time, @@ -94,7 +50,7 @@ } var sdkReady; - var SDK_URL_MAP = _objectSpread2({ + var SDK_URL_MAP = Object.assign({ wx: { url: 'https://res.wx.qq.com/open/js/jweixin-1.3.2.js' }, @@ -189,7 +145,13 @@ } }; function postMessage(type) { - var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + for (var _len = arguments.length, extraData = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + extraData[_key - 1] = arguments[_key]; + } + var data = extraData[0] || {}; + if (type === 'invoke') { + data = extraData[1] || {}; + } if (type !== 'getEnv') { var currentCallbackId = ++callbackId; callbacks[currentCallbackId] = function (err, res) { @@ -205,7 +167,7 @@ var postParams = { type: type, callbackId: callbackId, - payload: data + payload: type === 'invoke' ? extraData : data }; if (clientUid !== undefined) { postParams.clientUid = clientUid; @@ -225,26 +187,26 @@ var multiApiMap = { wx: { keyName: 'miniProgram', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'postMessage', 'getEnv'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'postMessage', 'getEnv', 'invoke'] }, tt: { keyName: 'miniProgram', - api: ['redirectTo', 'navigateTo', 'switchTab', 'reLaunch', 'navigateBack', 'setSwipeBackModeSync', 'postMessage', 'getEnv', 'checkJsApi', 'chooseImage', 'compressImage', 'previewImage', 'uploadFile', 'getNetworkType', 'openLocation', 'getLocation'] + api: ['redirectTo', 'navigateTo', 'switchTab', 'reLaunch', 'navigateBack', 'setSwipeBackModeSync', 'postMessage', 'getEnv', 'checkJsApi', 'chooseImage', 'compressImage', 'previewImage', 'uploadFile', 'getNetworkType', 'openLocation', 'getLocation', 'invoke'] }, swan: { keyName: 'webView', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'invoke'] }, qq: { keyName: 'miniProgram', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'invoke'] } }; var singleApiMap = { wx: ['checkJSApi', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'startSearchBeacons', 'stopSearchBeacons', 'onSearchBeacons', 'scanQRCode', 'chooseCard', 'addCard', 'openCard'], my: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'chooseImage', 'previewImage', 'getLocation', 'openLocation', 'alert', 'showLoading', 'hideLoading', 'getNetworkType', 'startShare', 'tradePay', 'postMessage', 'onMessage', 'getEnv'], swan: ['makePhoneCall', 'setClipboardData', 'getNetworkType', 'openLocation', 'getLocation', 'chooseLocation', 'chooseImage', 'previewImage', 'openShare', 'navigateToSmartProgram'], - web: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'getLoadError', 'getLocation'], + web: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'getLoadError', 'getLocation', 'invoke'], tt: [] }; var multiApi = multiApiMap[env] || {}; @@ -252,8 +214,8 @@ var multiApiLists = multiApi.api || []; multiApiLists.forEach(function (item) { webviewBridge[item] = function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; } runWebviewApiMethod(function () { var _window$env$multiApi$; @@ -263,8 +225,8 @@ }); singleApi.forEach(function (item) { webviewBridge[item] = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; } if (env === 'web') { postMessage.apply(void 0, [item].concat(args)); diff --git a/packages/webview-bridge/dist/webviewbridge.min.js b/packages/webview-bridge/dist/webviewbridge.min.js index 9dac705da4..0c7cf98677 100644 --- a/packages/webview-bridge/dist/webviewbridge.min.js +++ b/packages/webview-bridge/dist/webviewbridge.min.js @@ -3,4 +3,4 @@ * (c) 2024 @mpxjs team * @license Apache */ -var e,t;e=this,t=function(){"use strict";function e(e,t,o){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var n=o.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function t(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,n)}return o}var o,n,a,r,i=function(o){for(var n=1;n-1&&g.indexOf("MiniProgram")>-1?c="my":g.toLowerCase().indexOf("miniprogram")>-1?c=g.indexOf("QQ")>-1?"qq":"wx":g.indexOf("swan/")>-1?c="swan":g.indexOf("toutiao")>-1?c="tt":(c="web",window.addEventListener("message",(function(e){var t=e.data,o=t;try{"string"==typeof t&&(o=JSON.parse(t))}catch(e){}var n=o,a=n.callbackId,r=n.error,i=n.result;void 0!==a&&d[a]&&(r?d[a](r):d[a](null,i),delete d[a])}),!1));var w=!1;function u(e){w?e():o.then((function(){w=!0,e()}))}var l={config:function(e){"wx"===c?u((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function f(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("getEnv"!==e){var o=++s;d[o]=function(e,n){e?(t.fail&&t.fail(e),t.complete&&t.complete(e)):(t.success&&t.success(n),t.complete&&t.complete(n)),delete d[o]};var n={type:e,callbackId:s,payload:t};void 0!==p&&(n.clientUid=p),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(n)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(n),"*")}else t({webapp:!0})}var m=function(){var e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[c]||{},t={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation"],tt:[]}[c]||[];(e.api||[]).forEach((function(t){l[t]=function(){for(var o=arguments.length,n=new Array(o),a=0;a1&&void 0!==arguments[1]?arguments[1]:{},o=t.time,n=void 0===o?5e3:o,a=t.crossOrigin,r=void 0!==a&&a;function i(){return new Promise((function(t,o){var n=document.createElement("script");n.type="text/javascript",n.async="async",r&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(t(),n.onload=n.onreadystatechange=null)},n.onerror=function(){o(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(t,o){setTimeout((function(){o(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([i(),c()])}(i[c].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),m(),l},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).mpx=t(); \ No newline at end of file +var e,o;e=this,o=function(){"use strict";var e,o,a,n,t=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(a=location.href,(n=/mpx_webview_id=(\d+)/g.exec(a))&&n[1]&&(o=+n[1]),o),s={},d=navigator.userAgent;d.indexOf("AlipayClient")>-1&&d.indexOf("MiniProgram")>-1?i="my":d.toLowerCase().indexOf("miniprogram")>-1?i=d.indexOf("QQ")>-1?"qq":"wx":d.indexOf("swan/")>-1?i="swan":d.indexOf("toutiao")>-1?i="tt":(i="web",window.addEventListener("message",(function(e){var o=e.data,a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}var n=a,t=n.callbackId,i=n.error,r=n.result;void 0!==t&&s[t]&&(i?s[t](i):s[t](null,r),delete s[t])}),!1));var g=!1;function p(o){g?o():e.then((function(){g=!0,o()}))}var w={config:function(e){"wx"===i?p((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function l(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),n=1;n1&&void 0!==arguments[1]?arguments[1]:{},a=o.time,n=void 0===a?5e3:a,t=o.crossOrigin,i=void 0!==t&&t;function r(){return new Promise((function(o,a){var n=document.createElement("script");n.type="text/javascript",n.async="async",i&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){a(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(o,a){setTimeout((function(){a(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([r(),c()])}(t[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),v(),w},"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e=e||self).mpx=o(); \ No newline at end of file diff --git a/packages/webview-bridge/src/index.js b/packages/webview-bridge/src/index.js index 52ad187706..c538e21da6 100644 --- a/packages/webview-bridge/src/index.js +++ b/packages/webview-bridge/src/index.js @@ -96,7 +96,11 @@ const webviewBridge = { } } -function postMessage (type, data = {}) { +function postMessage (type, ...extraData) { + let data = extraData[0] || {} + if (type === 'invoke') { + data = extraData[1] || {} + } if (type !== 'getEnv') { const currentCallbackId = ++callbackId callbacks[currentCallbackId] = (err, res) => { @@ -112,7 +116,7 @@ function postMessage (type, data = {}) { const postParams = { type, callbackId, - payload: data + payload: type === 'invoke' ? extraData : data } if (clientUid !== undefined) { postParams.clientUid = clientUid @@ -140,7 +144,8 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'postMessage', - 'getEnv' + 'getEnv', + 'invoke' ] }, tt: { @@ -161,7 +166,8 @@ const getWebviewApi = () => { 'uploadFile', 'getNetworkType', 'openLocation', - 'getLocation' + 'getLocation', + 'invoke' ] }, swan: { @@ -173,7 +179,8 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'getEnv', - 'postMessage' + 'postMessage', + 'invoke' ] }, qq: { @@ -185,7 +192,8 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'getEnv', - 'postMessage' + 'postMessage', + 'invoke' ] } } @@ -259,7 +267,8 @@ const getWebviewApi = () => { 'getEnv', 'postMessage', 'getLoadError', - 'getLocation' + 'getLocation', + 'invoke' ], tt: [] } From bfc910b31492df4c54dd942f585b8aaa5b4c5b86 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Wed, 18 Dec 2024 21:07:15 +0800 Subject: [PATCH 50/76] =?UTF-8?q?chore:=20=E4=BC=98=E5=8C=96=E5=A4=84?= =?UTF-8?q?=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/react/mpx-scroll-view.tsx | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx index a2c474b453..e6a44ea82c 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx @@ -165,7 +165,7 @@ const _ScrollView = forwardRef, S const initialTimeout = useRef | null>(null) const intersectionObservers = useContext(IntersectionObserverContext) - const snapScrollIntoView = useRef('') + const firstScrollIntoViewChange = useRef(false) const { normalStyle, @@ -221,18 +221,15 @@ const _ScrollView = forwardRef, S useEffect(() => { if (scrollIntoView && __selectRef) { - snapScrollIntoView.current = scrollIntoView || '' - setTimeout(() => { + if (!firstScrollIntoViewChange.current) { + setTimeout(() => { + handleScrollIntoView() + }) + } else { handleScrollIntoView() - }) - } - }, []) - - useEffect(() => { - if (scrollIntoView && __selectRef && snapScrollIntoView.current !== scrollIntoView) { - snapScrollIntoView.current = scrollIntoView || '' - handleScrollIntoView() + } } + firstScrollIntoViewChange.current = true }, [scrollIntoView]) function handleScrollIntoView () { From 31cf1413352d175142c8c2eed22ce1451c33e4ea Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Wed, 18 Dec 2024 21:07:36 +0800 Subject: [PATCH 51/76] =?UTF-8?q?=E4=BF=AE=E6=AD=A3toast=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/api-proxy/@types/index.d.ts | 6 ++++++ packages/api-proxy/src/platform/api/toast/rnToast.jsx | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/api-proxy/@types/index.d.ts b/packages/api-proxy/@types/index.d.ts index b3f325b2c8..aca227ee4b 100644 --- a/packages/api-proxy/@types/index.d.ts +++ b/packages/api-proxy/@types/index.d.ts @@ -110,6 +110,12 @@ export const createVideoContext: WechatMiniprogram.Wx['createVideoContext'] export const onWindowResize: WechatMiniprogram.Wx['onWindowResize'] export const offWindowResize: WechatMiniprogram.Wx['offWindowResize'] export const createAnimation: WechatMiniprogram.Wx['createAnimation'] +export const vibrateShort: WechatMiniprogram.Wx['vibrateShort'] +export const vibrateLong: WechatMiniprogram.Wx['vibrateLong'] +export const getExtConfig: WechatMiniprogram.Wx['getExtConfig'] +export const getExtConfigSync: WechatMiniprogram.Wx['getExtConfigSync'] +export const openLocation: WechatMiniprogram.Wx['openLocation'] +export const chooseLocation: WechatMiniprogram.Wx['chooseLocation'] declare const install: (...args: any) => any diff --git a/packages/api-proxy/src/platform/api/toast/rnToast.jsx b/packages/api-proxy/src/platform/api/toast/rnToast.jsx index e780ffb556..45f98fa9e6 100644 --- a/packages/api-proxy/src/platform/api/toast/rnToast.jsx +++ b/packages/api-proxy/src/platform/api/toast/rnToast.jsx @@ -14,8 +14,8 @@ const styles = StyleSheet.create({ backgroundColor: 'rgba(20, 20, 20, 0.7)', paddingTop: 15, paddingBottom: 15, - paddingLeft: 10, - paddingRight: 10, + paddingLeft: 20, + paddingRight: 20, borderRadius: 5, display: 'flex', flexDirection: 'column', From 401b4a9c85c90e5a9c696440e8baea811b0d9fb8 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Wed, 18 Dec 2024 21:26:47 +0800 Subject: [PATCH 52/76] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8E=A5=E6=94=B6?= =?UTF-8?q?=E5=8F=82=E6=95=B0=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/components/react/mpx-web-view.tsx | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 0362bc2117..f94dbf6f0c 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -35,6 +35,7 @@ interface PayloadData { type MessageData = { payload?: PayloadData, + args?: Array, type?: string, callbackId?: number } @@ -126,7 +127,9 @@ const _WebView = forwardRef, WebViewProps>((pr } catch (e) { data = {} } + const args = data.args const postData: PayloadData = data.payload || {} + const params = args !== undefined ? args : [postData] const type = data.type switch (type) { case 'setTitle': @@ -141,7 +144,7 @@ const _WebView = forwardRef, WebViewProps>((pr case 'postMessage': bindmessage && bindmessage(getCustomEvent('messsage', {}, { // RN组件销毁顺序与小程序不一致,所以改成和支付宝消息一致 detail: { - data: postData.data + data: params[0]?.data } })) asyncCallback = Promise.resolve({ @@ -149,25 +152,24 @@ const _WebView = forwardRef, WebViewProps>((pr }) break case 'navigateTo': - asyncCallback = navObj.navigateTo(postData) + asyncCallback = navObj.navigateTo(...params) break case 'navigateBack': - asyncCallback = navObj.navigateBack(postData) + asyncCallback = navObj.navigateBack(...params) break case 'redirectTo': - asyncCallback = navObj.redirectTo(postData) + asyncCallback = navObj.redirectTo(...params) break case 'switchTab': - asyncCallback = navObj.switchTab(postData) + asyncCallback = navObj.switchTab(...params) break case 'reLaunch': - asyncCallback = navObj.reLaunch(postData) + asyncCallback = navObj.reLaunch(...params) break default: if (type) { const implement = mpx.config.webviewConfig.apiImplementations && mpx.config.webviewConfig.apiImplementations[type] if (isFunction(implement)) { - const params = type === 'invoke' && Array.isArray(postData) ? postData : [postData] asyncCallback = Promise.resolve(implement(...params)) } else { /* eslint-disable prefer-promise-reject-errors */ From 370dcbe0d7198a9ad3c63525384a5bba66463343 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 19 Dec 2024 11:13:07 +0800 Subject: [PATCH 53/76] =?UTF-8?q?=E5=B9=B2=E6=8E=89=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/platform/api/image/index.ios.js | 33 ------------------- 1 file changed, 33 deletions(-) delete mode 100644 packages/api-proxy/src/platform/api/image/index.ios.js diff --git a/packages/api-proxy/src/platform/api/image/index.ios.js b/packages/api-proxy/src/platform/api/image/index.ios.js deleted file mode 100644 index da1dd03c71..0000000000 --- a/packages/api-proxy/src/platform/api/image/index.ios.js +++ /dev/null @@ -1,33 +0,0 @@ -import { envError } from '../../../common/js' -import { Image } from 'react-native' - -const previewImage = envError('previewImage') - -const compressImage = envError('compressImage') - -const getImageInfo = function(options = {}) { - const { src, success, fail, complete } = options - let getImage - if (src !== undefined) { - result = { - errMsg: 'getImageInfo:fail parameter error: parameter.src should be String instead of Undefined;', - errno: 1001 - } - fail(result) - complete(result) - } - if (src === '') { - return - } - Image.getSize(src, function(res) { - console.log(res, 'test') - }, function (err) { - console.log(err, '=====') - }) -} - -export { - previewImage, - compressImage, - getImageInfo -} From 009929906f4f55e237e7fc13bc9c68c4210e10c3 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 19 Dec 2024 11:26:58 +0800 Subject: [PATCH 54/76] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=88=A4=E6=96=AD?= =?UTF-8?q?=E6=9D=A1=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/runtime/components/react/mpx-web-view.tsx | 2 +- .../webpack-plugin/lib/runtime/components/web/mpx-web-view.vue | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index 68dfa102bf..f289306808 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -129,7 +129,7 @@ const _WebView = forwardRef, WebViewProps>((pr } const args = data.args const postData: PayloadData = data.payload || {} - const params = args !== undefined ? args : [postData] + const params = Array.isArray(args) ? args : [postData] const type = data.type switch (type) { case 'setTitle': diff --git a/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue b/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue index 83a3f7b683..0e1ff52a63 100644 --- a/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue +++ b/packages/webpack-plugin/lib/runtime/components/web/mpx-web-view.vue @@ -114,7 +114,7 @@ export default { } let value = data.payload const args = data.args - const params = args !== undefined && Array.isArray(args) ? args : [value] + const params = Array.isArray(args) ? args : [value] if (!hostValidate) { return } From 95925978438fa79fc6b6b6b88ed8a508a5c154cb Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 19 Dec 2024 11:33:39 +0800 Subject: [PATCH 55/76] =?UTF-8?q?=E5=8E=BB=E6=8E=89=E6=97=A0=E7=94=A8?= =?UTF-8?q?=E7=9A=84=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/mpx-webview/H5/webviewbridge.min.js | 2 +- .../dist/webviewbridge.esm.browser.js | 19 ++++++++----------- .../dist/webviewbridge.esm.browser.min.js | 2 +- .../webview-bridge/dist/webviewbridge.esm.js | 15 ++++++++------- packages/webview-bridge/dist/webviewbridge.js | 15 ++++++++------- .../webview-bridge/dist/webviewbridge.min.js | 2 +- packages/webview-bridge/src/index.js | 12 ++++-------- 7 files changed, 31 insertions(+), 36 deletions(-) diff --git a/examples/mpx-webview/H5/webviewbridge.min.js b/examples/mpx-webview/H5/webviewbridge.min.js index 0c7cf98677..7ac85a8e78 100644 --- a/examples/mpx-webview/H5/webviewbridge.min.js +++ b/examples/mpx-webview/H5/webviewbridge.min.js @@ -3,4 +3,4 @@ * (c) 2024 @mpxjs team * @license Apache */ -var e,o;e=this,o=function(){"use strict";var e,o,a,n,t=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(a=location.href,(n=/mpx_webview_id=(\d+)/g.exec(a))&&n[1]&&(o=+n[1]),o),s={},d=navigator.userAgent;d.indexOf("AlipayClient")>-1&&d.indexOf("MiniProgram")>-1?i="my":d.toLowerCase().indexOf("miniprogram")>-1?i=d.indexOf("QQ")>-1?"qq":"wx":d.indexOf("swan/")>-1?i="swan":d.indexOf("toutiao")>-1?i="tt":(i="web",window.addEventListener("message",(function(e){var o=e.data,a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}var n=a,t=n.callbackId,i=n.error,r=n.result;void 0!==t&&s[t]&&(i?s[t](i):s[t](null,r),delete s[t])}),!1));var g=!1;function p(o){g?o():e.then((function(){g=!0,o()}))}var w={config:function(e){"wx"===i?p((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function l(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),n=1;n1&&void 0!==arguments[1]?arguments[1]:{},a=o.time,n=void 0===a?5e3:a,t=o.crossOrigin,i=void 0!==t&&t;function r(){return new Promise((function(o,a){var n=document.createElement("script");n.type="text/javascript",n.async="async",i&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){a(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(o,a){setTimeout((function(){a(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([r(),c()])}(t[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),v(),w},"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e=e||self).mpx=o(); \ No newline at end of file +var e,o;e=this,o=function(){"use strict";var e,o,a,t,n=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(a=location.href,(t=/mpx_webview_id=(\d+)/g.exec(a))&&t[1]&&(o=+t[1]),o),s={},d=navigator.userAgent;d.indexOf("AlipayClient")>-1&&d.indexOf("MiniProgram")>-1?i="my":d.toLowerCase().indexOf("miniprogram")>-1?i=d.indexOf("QQ")>-1?"qq":"wx":d.indexOf("swan/")>-1?i="swan":d.indexOf("toutiao")>-1?i="tt":(i="web",window.addEventListener("message",(function(e){var o=e.data,a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}var t=a,n=t.callbackId,i=t.error,r=t.result;void 0!==n&&s[n]&&(i?s[n](i):s[n](null,r),delete s[n])}),!1));var g=!1;function w(o){g?o():e.then((function(){g=!0,o()}))}var p={config:function(e){"wx"===i?w((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function l(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),t=1;t1&&void 0!==arguments[1]?arguments[1]:{},a=o.time,t=void 0===a?5e3:a,n=o.crossOrigin,i=void 0!==n&&n;function r(){return new Promise((function(o,a){var t=document.createElement("script");t.type="text/javascript",t.async="async",i&&(t.crossOrigin="anonymous"),t.onload=t.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),t.onload=t.onreadystatechange=null)},t.onerror=function(){a(new Error("load ".concat(e," error"))),t.onerror=null},t.src=e,document.getElementsByTagName("head")[0].appendChild(t)}))}function c(){return new Promise((function(o,a){setTimeout((function(){a(new Error("load ".concat(e," timeout")))}),t)}))}return Promise.race([r(),c()])}(n[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),m(),p},"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e=e||self).mpx=o(); \ No newline at end of file diff --git a/packages/webview-bridge/dist/webviewbridge.esm.browser.js b/packages/webview-bridge/dist/webviewbridge.esm.browser.js index 07f9c1031e..e8b97d2f10 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.browser.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.browser.js @@ -141,10 +141,11 @@ const webviewBridge = { }; function postMessage (type, ...extraData) { - let data = extraData[0] || {}; if (type === 'invoke') { - data = extraData[1] || {}; + type = extraData[0]; + extraData = extraData.slice(1); } + const data = extraData[0]; if (type !== 'getEnv') { const currentCallbackId = ++callbackId; callbacks[currentCallbackId] = (err, res) => { @@ -160,7 +161,7 @@ function postMessage (type, ...extraData) { const postParams = { type, callbackId, - payload: type === 'invoke' ? extraData : data + args: extraData }; if (clientUid !== undefined) { postParams.clientUid = clientUid; @@ -188,8 +189,7 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'postMessage', - 'getEnv', - 'invoke' + 'getEnv' ] }, tt: { @@ -210,8 +210,7 @@ const getWebviewApi = () => { 'uploadFile', 'getNetworkType', 'openLocation', - 'getLocation', - 'invoke' + 'getLocation' ] }, swan: { @@ -223,8 +222,7 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'getEnv', - 'postMessage', - 'invoke' + 'postMessage' ] }, qq: { @@ -236,8 +234,7 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'getEnv', - 'postMessage', - 'invoke' + 'postMessage' ] } }; diff --git a/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js b/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js index 78546b7526..efbeb4cfac 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js @@ -3,4 +3,4 @@ * (c) 2024 @mpxjs team * @license Apache */ -let e;const o=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap);let a=null,t=0;const n=function(){const e=location.href,o=/mpx_webview_id=(\d+)/g.exec(e);let a;return o&&o[1]&&(a=+o[1]),a}(),i={},s=navigator.userAgent;s.indexOf("AlipayClient")>-1&&s.indexOf("MiniProgram")>-1?a="my":s.toLowerCase().indexOf("miniprogram")>-1?a=s.indexOf("QQ")>-1?"qq":"wx":s.indexOf("swan/")>-1?a="swan":s.indexOf("toutiao")>-1?a="tt":(a="web",window.addEventListener("message",e=>{const o=e.data;let a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}const{callbackId:t,error:n,result:s}=a;void 0!==t&&i[t]&&(n?i[t](n):i[t](null,s),delete i[t])},!1));let r=!1;function c(o){r?o():e.then(()=>{r=!0,o()})}const d={config(e){"wx"===a?c(()=>{window.wx&&window.wx.config(e)}):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};const w=()=>{const e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv","invoke"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation","invoke"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","invoke"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","invoke"]}}[a]||{},o={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation","invoke"],tt:[]}[a]||[];(e.api||[]).forEach(o=>{d[o]=(...t)=>{c(()=>{window[a][e.keyName][o](...t)})}}),o.forEach(e=>{d[e]=(...o)=>{"web"===a?function(e,...o){let a=o[0]||{};if("invoke"===e&&(a=o[1]||{}),"getEnv"!==e){const s=++t;i[s]=(e,o)=>{e?(a.fail&&a.fail(e),a.complete&&a.complete(e)):(a.success&&a.success(o),a.complete&&a.complete(o)),delete i[s]};const r={type:e,callbackId:t,payload:"invoke"===e?o:a};void 0!==n&&(r.clientUid=n),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(r)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(r),"*")}else a({webapp:!0})}(e,...o):c("wx"===a?()=>{window[a]&&window[a].ready(()=>{window[a][e](...o)})}:()=>{window[a][e](...o)})}})};e="web"!==a?o[a].url?function(e,{time:o=5e3,crossOrigin:a=!1}={}){return Promise.race([new Promise((o,t)=>{const n=document.createElement("script");n.type="text/javascript",n.async="async",a&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){t(new Error(`load ${e} error`)),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}),new Promise((a,t)=>{setTimeout(()=>{t(new Error(`load ${e} timeout`))},o)})])}(o[a].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),w();export default d; \ No newline at end of file +let e;const o=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap);let a=null,t=0;const n=function(){const e=location.href,o=/mpx_webview_id=(\d+)/g.exec(e);let a;return o&&o[1]&&(a=+o[1]),a}(),i={},s=navigator.userAgent;s.indexOf("AlipayClient")>-1&&s.indexOf("MiniProgram")>-1?a="my":s.toLowerCase().indexOf("miniprogram")>-1?a=s.indexOf("QQ")>-1?"qq":"wx":s.indexOf("swan/")>-1?a="swan":s.indexOf("toutiao")>-1?a="tt":(a="web",window.addEventListener("message",e=>{const o=e.data;let a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}const{callbackId:t,error:n,result:s}=a;void 0!==t&&i[t]&&(n?i[t](n):i[t](null,s),delete i[t])},!1));let r=!1;function c(o){r?o():e.then(()=>{r=!0,o()})}const d={config(e){"wx"===a?c(()=>{window.wx&&window.wx.config(e)}):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};const g=()=>{const e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[a]||{},o={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation","invoke"],tt:[]}[a]||[];(e.api||[]).forEach(o=>{d[o]=(...t)=>{c(()=>{window[a][e.keyName][o](...t)})}}),o.forEach(e=>{d[e]=(...o)=>{"web"===a?function(e,...o){"invoke"===e&&(e=o[0],o=o.slice(1));const a=o[0];if("getEnv"!==e){const s=++t;i[s]=(e,o)=>{e?(a.fail&&a.fail(e),a.complete&&a.complete(e)):(a.success&&a.success(o),a.complete&&a.complete(o)),delete i[s]};const r={type:e,callbackId:t,args:o};void 0!==n&&(r.clientUid=n),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(r)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(r),"*")}else a({webapp:!0})}(e,...o):c("wx"===a?()=>{window[a]&&window[a].ready(()=>{window[a][e](...o)})}:()=>{window[a][e](...o)})}})};e="web"!==a?o[a].url?function(e,{time:o=5e3,crossOrigin:a=!1}={}){return Promise.race([new Promise((o,t)=>{const n=document.createElement("script");n.type="text/javascript",n.async="async",a&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){t(new Error(`load ${e} error`)),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}),new Promise((a,t)=>{setTimeout(()=>{t(new Error(`load ${e} timeout`))},o)})])}(o[a].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),g();export default d; \ No newline at end of file diff --git a/packages/webview-bridge/dist/webviewbridge.esm.js b/packages/webview-bridge/dist/webviewbridge.esm.js index 622afc4dae..f7c3d3d28d 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.js @@ -142,10 +142,11 @@ function postMessage(type) { for (var _len = arguments.length, extraData = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { extraData[_key - 1] = arguments[_key]; } - var data = extraData[0] || {}; if (type === 'invoke') { - data = extraData[1] || {}; + type = extraData[0]; + extraData = extraData.slice(1); } + var data = extraData[0]; if (type !== 'getEnv') { var currentCallbackId = ++callbackId; callbacks[currentCallbackId] = function (err, res) { @@ -161,7 +162,7 @@ function postMessage(type) { var postParams = { type: type, callbackId: callbackId, - payload: type === 'invoke' ? extraData : data + args: extraData }; if (clientUid !== undefined) { postParams.clientUid = clientUid; @@ -181,19 +182,19 @@ var getWebviewApi = function getWebviewApi() { var multiApiMap = { wx: { keyName: 'miniProgram', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'postMessage', 'getEnv', 'invoke'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'postMessage', 'getEnv'] }, tt: { keyName: 'miniProgram', - api: ['redirectTo', 'navigateTo', 'switchTab', 'reLaunch', 'navigateBack', 'setSwipeBackModeSync', 'postMessage', 'getEnv', 'checkJsApi', 'chooseImage', 'compressImage', 'previewImage', 'uploadFile', 'getNetworkType', 'openLocation', 'getLocation', 'invoke'] + api: ['redirectTo', 'navigateTo', 'switchTab', 'reLaunch', 'navigateBack', 'setSwipeBackModeSync', 'postMessage', 'getEnv', 'checkJsApi', 'chooseImage', 'compressImage', 'previewImage', 'uploadFile', 'getNetworkType', 'openLocation', 'getLocation'] }, swan: { keyName: 'webView', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'invoke'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage'] }, qq: { keyName: 'miniProgram', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'invoke'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage'] } }; var singleApiMap = { diff --git a/packages/webview-bridge/dist/webviewbridge.js b/packages/webview-bridge/dist/webviewbridge.js index 0cb2705262..e1a097571e 100644 --- a/packages/webview-bridge/dist/webviewbridge.js +++ b/packages/webview-bridge/dist/webviewbridge.js @@ -148,10 +148,11 @@ for (var _len = arguments.length, extraData = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { extraData[_key - 1] = arguments[_key]; } - var data = extraData[0] || {}; if (type === 'invoke') { - data = extraData[1] || {}; + type = extraData[0]; + extraData = extraData.slice(1); } + var data = extraData[0]; if (type !== 'getEnv') { var currentCallbackId = ++callbackId; callbacks[currentCallbackId] = function (err, res) { @@ -167,7 +168,7 @@ var postParams = { type: type, callbackId: callbackId, - payload: type === 'invoke' ? extraData : data + args: extraData }; if (clientUid !== undefined) { postParams.clientUid = clientUid; @@ -187,19 +188,19 @@ var multiApiMap = { wx: { keyName: 'miniProgram', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'postMessage', 'getEnv', 'invoke'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'postMessage', 'getEnv'] }, tt: { keyName: 'miniProgram', - api: ['redirectTo', 'navigateTo', 'switchTab', 'reLaunch', 'navigateBack', 'setSwipeBackModeSync', 'postMessage', 'getEnv', 'checkJsApi', 'chooseImage', 'compressImage', 'previewImage', 'uploadFile', 'getNetworkType', 'openLocation', 'getLocation', 'invoke'] + api: ['redirectTo', 'navigateTo', 'switchTab', 'reLaunch', 'navigateBack', 'setSwipeBackModeSync', 'postMessage', 'getEnv', 'checkJsApi', 'chooseImage', 'compressImage', 'previewImage', 'uploadFile', 'getNetworkType', 'openLocation', 'getLocation'] }, swan: { keyName: 'webView', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'invoke'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage'] }, qq: { keyName: 'miniProgram', - api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'invoke'] + api: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage'] } }; var singleApiMap = { diff --git a/packages/webview-bridge/dist/webviewbridge.min.js b/packages/webview-bridge/dist/webviewbridge.min.js index 0c7cf98677..7ac85a8e78 100644 --- a/packages/webview-bridge/dist/webviewbridge.min.js +++ b/packages/webview-bridge/dist/webviewbridge.min.js @@ -3,4 +3,4 @@ * (c) 2024 @mpxjs team * @license Apache */ -var e,o;e=this,o=function(){"use strict";var e,o,a,n,t=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(a=location.href,(n=/mpx_webview_id=(\d+)/g.exec(a))&&n[1]&&(o=+n[1]),o),s={},d=navigator.userAgent;d.indexOf("AlipayClient")>-1&&d.indexOf("MiniProgram")>-1?i="my":d.toLowerCase().indexOf("miniprogram")>-1?i=d.indexOf("QQ")>-1?"qq":"wx":d.indexOf("swan/")>-1?i="swan":d.indexOf("toutiao")>-1?i="tt":(i="web",window.addEventListener("message",(function(e){var o=e.data,a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}var n=a,t=n.callbackId,i=n.error,r=n.result;void 0!==t&&s[t]&&(i?s[t](i):s[t](null,r),delete s[t])}),!1));var g=!1;function p(o){g?o():e.then((function(){g=!0,o()}))}var w={config:function(e){"wx"===i?p((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function l(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),n=1;n1&&void 0!==arguments[1]?arguments[1]:{},a=o.time,n=void 0===a?5e3:a,t=o.crossOrigin,i=void 0!==t&&t;function r(){return new Promise((function(o,a){var n=document.createElement("script");n.type="text/javascript",n.async="async",i&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){a(new Error("load ".concat(e," error"))),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}))}function c(){return new Promise((function(o,a){setTimeout((function(){a(new Error("load ".concat(e," timeout")))}),n)}))}return Promise.race([r(),c()])}(t[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),v(),w},"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e=e||self).mpx=o(); \ No newline at end of file +var e,o;e=this,o=function(){"use strict";var e,o,a,t,n=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(a=location.href,(t=/mpx_webview_id=(\d+)/g.exec(a))&&t[1]&&(o=+t[1]),o),s={},d=navigator.userAgent;d.indexOf("AlipayClient")>-1&&d.indexOf("MiniProgram")>-1?i="my":d.toLowerCase().indexOf("miniprogram")>-1?i=d.indexOf("QQ")>-1?"qq":"wx":d.indexOf("swan/")>-1?i="swan":d.indexOf("toutiao")>-1?i="tt":(i="web",window.addEventListener("message",(function(e){var o=e.data,a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}var t=a,n=t.callbackId,i=t.error,r=t.result;void 0!==n&&s[n]&&(i?s[n](i):s[n](null,r),delete s[n])}),!1));var g=!1;function w(o){g?o():e.then((function(){g=!0,o()}))}var p={config:function(e){"wx"===i?w((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function l(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),t=1;t1&&void 0!==arguments[1]?arguments[1]:{},a=o.time,t=void 0===a?5e3:a,n=o.crossOrigin,i=void 0!==n&&n;function r(){return new Promise((function(o,a){var t=document.createElement("script");t.type="text/javascript",t.async="async",i&&(t.crossOrigin="anonymous"),t.onload=t.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),t.onload=t.onreadystatechange=null)},t.onerror=function(){a(new Error("load ".concat(e," error"))),t.onerror=null},t.src=e,document.getElementsByTagName("head")[0].appendChild(t)}))}function c(){return new Promise((function(o,a){setTimeout((function(){a(new Error("load ".concat(e," timeout")))}),t)}))}return Promise.race([r(),c()])}(n[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),m(),p},"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e=e||self).mpx=o(); \ No newline at end of file diff --git a/packages/webview-bridge/src/index.js b/packages/webview-bridge/src/index.js index d2978deab3..054b022d22 100644 --- a/packages/webview-bridge/src/index.js +++ b/packages/webview-bridge/src/index.js @@ -145,8 +145,7 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'postMessage', - 'getEnv', - 'invoke' + 'getEnv' ] }, tt: { @@ -167,8 +166,7 @@ const getWebviewApi = () => { 'uploadFile', 'getNetworkType', 'openLocation', - 'getLocation', - 'invoke' + 'getLocation' ] }, swan: { @@ -180,8 +178,7 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'getEnv', - 'postMessage', - 'invoke' + 'postMessage' ] }, qq: { @@ -193,8 +190,7 @@ const getWebviewApi = () => { 'reLaunch', 'redirectTo', 'getEnv', - 'postMessage', - 'invoke' + 'postMessage' ] } } From 5ffd1e7012f07e9f28492773297c5121771fdae8 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 19 Dec 2024 13:13:31 +0800 Subject: [PATCH 56/76] =?UTF-8?q?=E8=A1=A5=E5=85=85=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/runtime/components/react/mpx-web-view.tsx | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx index f289306808..b645d05094 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-web-view.tsx @@ -124,9 +124,7 @@ const _WebView = forwardRef, WebViewProps>((pr if (typeof nativeEventData === 'string') { data = JSON.parse(nativeEventData) } - } catch (e) { - data = {} - } + } catch (e) {} const args = data.args const postData: PayloadData = data.payload || {} const params = Array.isArray(args) ? args : [postData] @@ -190,6 +188,15 @@ const _WebView = forwardRef, WebViewProps>((pr }) webViewRef.current.postMessage(test) } + }).catch((error: any) => { + if (webViewRef.current?.postMessage) { + const test = JSON.stringify({ + type, + callbackId: data.callbackId, + error + }) + webViewRef.current.postMessage(test) + } }) } const events = {} From 238ded090a413735ea02756b71368b1cf07f7561 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Thu, 19 Dec 2024 14:40:26 +0800 Subject: [PATCH 57/76] fix: cr --- .../lib/runtime/components/react/mpx-scroll-view.tsx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx index b49540d228..b058e622dc 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-scroll-view.tsx @@ -222,9 +222,7 @@ const _ScrollView = forwardRef, S useEffect(() => { if (scrollIntoView && __selectRef) { if (!firstScrollIntoViewChange.current) { - setTimeout(() => { - handleScrollIntoView() - }) + setTimeout(handleScrollIntoView) } else { handleScrollIntoView() } From 8a04d91cc597a82cd3c1b2b340aed21a4d8df29f Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 19 Dec 2024 15:43:38 +0800 Subject: [PATCH 58/76] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=89=E5=8D=93?= =?UTF-8?q?=E6=B2=A1=E6=9C=89=E6=8B=89=E9=BD=90=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/api-proxy/src/platform/api/system/rnSystem.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/api-proxy/src/platform/api/system/rnSystem.js b/packages/api-proxy/src/platform/api/system/rnSystem.js index 2284971c9b..acf3965ed9 100644 --- a/packages/api-proxy/src/platform/api/system/rnSystem.js +++ b/packages/api-proxy/src/platform/api/system/rnSystem.js @@ -10,8 +10,8 @@ const getWindowInfo = function () { const insets = Object.assign(initialWindowMetricsInset, navigationInsets) let safeArea = {} const { top = 0, bottom = 0, left = 0, right = 0 } = insets - const screenHeight = dimensionsScreen.height - const screenWidth = dimensionsScreen.width + const screenHeight = __mpx_mode__ === 'ios' ? dimensionsScreen.height : dimensionsScreen.height - bottom // 解决安卓开启屏幕内三建导航安卓把安全区计算进去后产生的影响 + const screenWidth = __mpx_mode__ === 'ios' ? dimensionsScreen.width : dimensionsScreen.width - right const layout = navigation.layout || {} const layoutHeight = layout.height || 0 const layoutWidth = layout.width || 0 From eab401f4e9ce957387dfc3454374cf9ded9f7468 Mon Sep 17 00:00:00 2001 From: xuegan Date: Thu, 19 Dec 2024 16:05:26 +0800 Subject: [PATCH 59/76] =?UTF-8?q?feat:=20=E4=BF=AE=E6=94=B9scoped-id?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/style-compiler/plugins/scope-id.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js b/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js index 80d6557afc..a0c52dc59a 100644 --- a/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js +++ b/packages/webpack-plugin/lib/style-compiler/plugins/scope-id.js @@ -40,7 +40,7 @@ module.exports = ({ id }) => { selector.insertAfter(last, ss) last = ss }) - const prev = selector.at(selector.index(n) - 1) + const prev = n.prev() if (!prev || !isSpaceCombinator(prev)) { selector.insertAfter( n, @@ -49,20 +49,20 @@ module.exports = ({ id }) => { }) ) } - selector.removeChild(n) + n.remove() } else { - const prev = selector.at(selector.index(n) - 1) + const prev = n.prev() if (prev && isSpaceCombinator(prev)) { - selector.removeChild(prev) + prev.remove() } - selector.removeChild(n) + n.remove() } return false } // /deep/ alias for >>>, since >>> doesn't work in SASS if (n.type === 'tag' && n.value === '/deep/') { const prev = n.prev() - if (prev && prev.type === 'combinator' && prev.value === ' ') { + if (prev && isSpaceCombinator(prev)) { prev.remove() } n.remove() From 7b34d473e7097ed2a2ef29c6b92ba2d96fb6d892 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 19 Dec 2024 21:26:15 +0800 Subject: [PATCH 60/76] =?UTF-8?q?=E8=A1=A5=E5=85=85getImageInfo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/api-proxy/@types/index.d.ts | 7 +++ .../src/platform/api/image/index.ali.js | 5 ++- .../api-proxy/src/platform/api/image/index.js | 5 ++- .../src/platform/api/image/index.web.js | 44 ++++++++++++++++++- packages/api-proxy/src/platform/index.js | 2 +- 5 files changed, 58 insertions(+), 5 deletions(-) diff --git a/packages/api-proxy/@types/index.d.ts b/packages/api-proxy/@types/index.d.ts index b3f325b2c8..1f14f8587e 100644 --- a/packages/api-proxy/@types/index.d.ts +++ b/packages/api-proxy/@types/index.d.ts @@ -110,6 +110,13 @@ export const createVideoContext: WechatMiniprogram.Wx['createVideoContext'] export const onWindowResize: WechatMiniprogram.Wx['onWindowResize'] export const offWindowResize: WechatMiniprogram.Wx['offWindowResize'] export const createAnimation: WechatMiniprogram.Wx['createAnimation'] +export const hideHomeButton: WechatMiniprogram.Wx['hideHomeButton'] +export const getSetting: WechatMiniprogram.Wx['getSetting'] +export const openSetting: WechatMiniprogram.Wx['openSetting'] +export const enableAlertBeforeUnload: WechatMiniprogram.Wx['enableAlertBeforeUnload'] +export const disableAlertBeforeUnload: WechatMiniprogram.Wx['disableAlertBeforeUnload'] +export const getMenuButtonBoundingClientRect: WechatMiniprogram.Wx['getMenuButtonBoundingClientRect'] +export const getImageInfo: WechatMiniprogram.Wx['getImageInfo'] declare const install: (...args: any) => any diff --git a/packages/api-proxy/src/platform/api/image/index.ali.js b/packages/api-proxy/src/platform/api/image/index.ali.js index 1c24c8c2b2..4c64e5d4d9 100644 --- a/packages/api-proxy/src/platform/api/image/index.ali.js +++ b/packages/api-proxy/src/platform/api/image/index.ali.js @@ -30,7 +30,10 @@ function compressImage (options = {}) { return ENV_OBJ.compressImage(opts) } +const getImageInfo = ENV_OBJ.getImageInfo + export { previewImage, - compressImage + compressImage, + getImageInfo } diff --git a/packages/api-proxy/src/platform/api/image/index.js b/packages/api-proxy/src/platform/api/image/index.js index 2bdd9a104e..5a94edd980 100644 --- a/packages/api-proxy/src/platform/api/image/index.js +++ b/packages/api-proxy/src/platform/api/image/index.js @@ -4,7 +4,10 @@ const previewImage = ENV_OBJ.previewImage || envError('previewImage') const compressImage = ENV_OBJ.compressImage || envError('compressImage') +const getImageInfo = ENV_OBJ.getImageInfo || envError('getImageInfo') + export { previewImage, - compressImage + compressImage, + getImageInfo } diff --git a/packages/api-proxy/src/platform/api/image/index.web.js b/packages/api-proxy/src/platform/api/image/index.web.js index a8fea9b762..883293080c 100644 --- a/packages/api-proxy/src/platform/api/image/index.web.js +++ b/packages/api-proxy/src/platform/api/image/index.web.js @@ -1,5 +1,5 @@ import Preview from './Preview' -import { isBrowser, throwSSRWarning, envError } from '../../../common/js' +import { isBrowser, throwSSRWarning, envError, defineUnsupportedProps, successHandle, failHandle } from '../../../common/js' let preview = null @@ -15,9 +15,49 @@ const previewImage = (options) => { if (!preview) preview = new Preview() preview.show(options) } + const compressImage = envError('compressImage') +const getImageInfo = function (options = {}) { + const { src, success, fail, complete } = options + + if (src === undefined) { + const result = { + errMsg: 'getImageInfo:fail parameter error: parameter.src should be String instead of Undefined;', + errno: 1001 + } + failHandle(result, fail, complete) + return + } + if (src === '') { + return + } + + const img = new Image() + img.src = src + + img.onload = function () { + const width = img.width + const height = img.height + const result = { + errMsg: 'getImageInfo:ok', + width, + height + } + defineUnsupportedProps(result, ['path', 'orientation', 'type']) + successHandle(result, success, complete) + } + + img.onerror = function () { + const result = { + errMsg: 'getImageInfo:fail download image fail. ' + } + failHandle(result, fail, complete) + } +} + export { previewImage, - compressImage + compressImage, + getImageInfo } diff --git a/packages/api-proxy/src/platform/index.js b/packages/api-proxy/src/platform/index.js index af1382d62a..67f2d93a10 100644 --- a/packages/api-proxy/src/platform/index.js +++ b/packages/api-proxy/src/platform/index.js @@ -43,7 +43,7 @@ export * from './api/file' // getUserInfo export * from './api/get-user-info' -// previewImage, compressImage +// previewImage, compressImage, getImageInfo export * from './api/image' // login From 0a0a39918117f88b5351dd3674516ebe286354d0 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 19 Dec 2024 21:26:46 +0800 Subject: [PATCH 61/76] =?UTF-8?q?=E8=A1=A5=E5=85=85=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/platform/api/image/index.ios.js | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 packages/api-proxy/src/platform/api/image/index.ios.js diff --git a/packages/api-proxy/src/platform/api/image/index.ios.js b/packages/api-proxy/src/platform/api/image/index.ios.js new file mode 100644 index 0000000000..adc09a7407 --- /dev/null +++ b/packages/api-proxy/src/platform/api/image/index.ios.js @@ -0,0 +1,41 @@ +import { envError, defineUnsupportedProps, successHandle, failHandle } from '../../../common/js' +import { Image } from 'react-native' + +const previewImage = envError('previewImage') + +const compressImage = envError('compressImage') + +const getImageInfo = function (options = {}) { + const { src, success, fail, complete } = options + if (src === undefined) { + const result = { + errMsg: 'getImageInfo:fail parameter error: parameter.src should be String instead of Undefined;', + errno: 1001 + } + failHandle(result, fail, complete) + return + } + if (src === '') { + return + } + Image.getSize(src, (width, height) => { + const result = { + errMsg: 'getImageInfo:ok', + width, + height + } + defineUnsupportedProps(result, ['path', 'orientation', 'type']) + successHandle(result, success, complete) + }, (err) => { + const result = { + errMsg: 'getImageInfo:fail download image fail. reason: ' + err + } + failHandle(result, fail, complete) + }) +} + +export { + previewImage, + compressImage, + getImageInfo +} From af720abe009c4047109ac82eac7dfab22dc0d205 Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Thu, 19 Dec 2024 21:37:10 +0800 Subject: [PATCH 62/76] =?UTF-8?q?=E8=A1=A5=E5=85=85=E6=B2=A1=E6=9C=89url?= =?UTF-8?q?=E7=9A=84=E6=83=85=E5=86=B5=E4=B8=8B=E8=BF=94=E5=9B=9E=E6=95=B0?= =?UTF-8?q?=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/api-proxy/src/platform/api/image/index.ios.js | 4 ++++ packages/api-proxy/src/platform/api/image/index.web.js | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/packages/api-proxy/src/platform/api/image/index.ios.js b/packages/api-proxy/src/platform/api/image/index.ios.js index adc09a7407..4ed1ca50fa 100644 --- a/packages/api-proxy/src/platform/api/image/index.ios.js +++ b/packages/api-proxy/src/platform/api/image/index.ios.js @@ -16,6 +16,10 @@ const getImageInfo = function (options = {}) { return } if (src === '') { + const result = { + errMsg: 'getImageInfo:fail image not found' + } + failHandle(result, fail, complete) return } Image.getSize(src, (width, height) => { diff --git a/packages/api-proxy/src/platform/api/image/index.web.js b/packages/api-proxy/src/platform/api/image/index.web.js index 883293080c..19bbc0489f 100644 --- a/packages/api-proxy/src/platform/api/image/index.web.js +++ b/packages/api-proxy/src/platform/api/image/index.web.js @@ -30,6 +30,10 @@ const getImageInfo = function (options = {}) { return } if (src === '') { + const result = { + errMsg: 'getImageInfo:fail image not found' + } + failHandle(result, fail, complete) return } From 62157468d4b389af6cce3f3f4398da51b5f7c64a Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Fri, 20 Dec 2024 11:10:50 +0800 Subject: [PATCH 63/76] =?UTF-8?q?fix=20actionsheet=E9=80=8F=E6=98=8E?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx b/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx index 280d04b0d6..e28b212dcf 100644 --- a/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx +++ b/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx @@ -91,7 +91,7 @@ function showActionSheet (options = {}) { remove() } return ( - + { alertText ? {alertText} : null } { itemList.map((item, index) => selectAction(index)} style={ [styles.itemStyle, itemList.length -1 === index ? { From 639e3f06bff2b411fdfeba33c25ab7ed52fbd2a3 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Fri, 20 Dec 2024 18:09:43 +0800 Subject: [PATCH 64/76] rn: add render function error catch --- packages/core/src/platform/patch/getDefaultOptions.ios.js | 4 ++-- packages/utils/src/errorHandling.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/src/platform/patch/getDefaultOptions.ios.js b/packages/core/src/platform/patch/getDefaultOptions.ios.js index 56f7641f70..1f44e346f6 100644 --- a/packages/core/src/platform/patch/getDefaultOptions.ios.js +++ b/packages/core/src/platform/patch/getDefaultOptions.ios.js @@ -3,7 +3,7 @@ import * as ReactNative from 'react-native' import { ReactiveEffect } from '../../observer/effect' import { watch } from '../../observer/watch' import { reactive, set, del } from '../../observer/reactive' -import { hasOwn, isFunction, noop, isObject, isArray, getByPath, collectDataset, hump2dash, wrapMethodsWithErrorHandling } from '@mpxjs/utils' +import { hasOwn, isFunction, noop, isObject, isArray, getByPath, collectDataset, hump2dash, callWithErrorHandling, wrapMethodsWithErrorHandling } from '@mpxjs/utils' import MpxProxy from '../../core/proxy' import { BEFOREUPDATE, ONLOAD, UPDATED, ONSHOW, ONHIDE, ONRESIZE, REACTHOOKSEXEC } from '../../core/innerLifecycle' import mergeOptions from '../../core/mergeOptions' @@ -52,7 +52,7 @@ function createEffect (proxy, components) { proxy.effect = new ReactiveEffect(() => { // reset instance proxy.target.__resetInstance() - return proxy.target.__injectedRender(innerCreateElement, getComponent) + return callWithErrorHandling(proxy.target.__injectedRender.bind(proxy.target), proxy, 'render function', [innerCreateElement, getComponent]) }, () => queueJob(update), proxy.scope) // render effect允许自触发 proxy.toggleRecurse(true) diff --git a/packages/utils/src/errorHandling.js b/packages/utils/src/errorHandling.js index b356d9596d..442705cbfc 100644 --- a/packages/utils/src/errorHandling.js +++ b/packages/utils/src/errorHandling.js @@ -21,7 +21,7 @@ export function callWithErrorHandling (fn, instance, info, args) { } export function wrapMethodsWithErrorHandling (methods, instance) { - if (process.env.NODE_ENV === 'production') return methods + // if (process.env.NODE_ENV === 'production') return methods const newMethods = {} Object.keys(methods).forEach((key) => { if (isFunction(methods[key])) { From 0fd875ff99ee3fbb13517fc3b06f6d7ef94ad691 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Fri, 20 Dec 2024 18:45:09 +0800 Subject: [PATCH 65/76] fix mpx-view throw --- .../lib/runtime/components/react/mpx-view.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx b/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx index 28e62b1cd3..cdc8c02aef 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/mpx-view.tsx @@ -13,6 +13,7 @@ import type { AnimationProp } from './useAnimationHooks' import { ExtendedViewStyle } from './types/common' import useNodesRef, { HandlerRef } from './useNodesRef' import { parseUrl, PERCENT_REGEX, splitStyle, splitProps, useTransformStyle, wrapChildren, useLayout, renderImage, pickStyle, extendObject } from './utils' +import { error } from '@mpxjs/utils' import LinearGradient from 'react-native-linear-gradient' export interface _ViewProps extends ViewProps { @@ -716,7 +717,7 @@ const _View = forwardRef, _ViewProps>((viewProps, r enableBackground = enableBackground || !!backgroundStyle const enableBackgroundRef = useRef(enableBackground) if (enableBackgroundRef.current !== enableBackground) { - throw new Error('[Mpx runtime error]: background use should be stable in the component lifecycle, or you can set [enable-background] with true.') + error('[Mpx runtime error]: background use should be stable in the component lifecycle, or you can set [enable-background] with true.') } const nodeRef = useRef(null) @@ -774,9 +775,9 @@ const _View = forwardRef, _ViewProps>((viewProps, r enableAnimation = enableAnimation || !!animation const enableAnimationRef = useRef(enableAnimation) if (enableAnimationRef.current !== enableAnimation) { - throw new Error('[Mpx runtime error]: animation use should be stable in the component lifecycle, or you can set [enable-animation] with true.') + error('[Mpx runtime error]: animation use should be stable in the component lifecycle, or you can set [enable-animation] with true.') } - const finalStyle = enableAnimation + const finalStyle = enableAnimationRef.current ? [viewStyle, useAnimationHooks({ animation, style: viewStyle From 7cac0f98ad4f4d542118f93bb555dde45c194c85 Mon Sep 17 00:00:00 2001 From: human Date: Sun, 22 Dec 2024 19:55:27 +0800 Subject: [PATCH 66/76] =?UTF-8?q?fix:=20bugfix=E7=9B=B8=E4=BA=A4&nav?= =?UTF-8?q?=E5=8A=A8=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../api/create-intersection-observer/rnIntersectionObserver.js | 2 +- packages/core/src/platform/createApp.ios.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/api-proxy/src/platform/api/create-intersection-observer/rnIntersectionObserver.js b/packages/api-proxy/src/platform/api/create-intersection-observer/rnIntersectionObserver.js index 059ae453b0..038b67099b 100644 --- a/packages/api-proxy/src/platform/api/create-intersection-observer/rnIntersectionObserver.js +++ b/packages/api-proxy/src/platform/api/create-intersection-observer/rnIntersectionObserver.js @@ -96,7 +96,7 @@ class RNIntersectionObserver { const windowRect = { top: navigationLayout.y + this.margins.top, - left: navigationLayout.x + this.margins.left, + left: this.margins.left, right: navigationLayout.width - this.margins.right, bottom: navigationLayout.y + navigationLayout.height - this.margins.bottom } diff --git a/packages/core/src/platform/createApp.ios.js b/packages/core/src/platform/createApp.ios.js index 5fae55fa0b..cd11268bcc 100644 --- a/packages/core/src/platform/createApp.ios.js +++ b/packages/core/src/platform/createApp.ios.js @@ -191,7 +191,8 @@ export default function createApp (option, config = {}) { // 7.x替换headerBackTitleVisible // headerBackButtonDisplayMode: 'minimal', headerBackTitleVisible: false, - headerMode: 'float' + // 安卓上会出现回退的时,如果设置为flat的话 navigator出现右滑退出,screen部分是fade的方式,交互效果不佳 + headerMode: 'screen' } if (headerBackImageProps) { navScreenOpts.headerBackImage = () => { From 2306880055e9d47e09d6c176bf6d8d431eebee60 Mon Sep 17 00:00:00 2001 From: human Date: Sun, 22 Dec 2024 21:20:41 +0800 Subject: [PATCH 67/76] =?UTF-8?q?fix:=20navigtion=20=E5=AE=89=E5=8D=93?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E9=97=AA=E7=8E=B0=E5=AF=BC=E8=88=AA?= =?UTF-8?q?=E6=9D=A1=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/platform/createApp.ios.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/core/src/platform/createApp.ios.js b/packages/core/src/platform/createApp.ios.js index cd11268bcc..dbcee86aa4 100644 --- a/packages/core/src/platform/createApp.ios.js +++ b/packages/core/src/platform/createApp.ios.js @@ -192,7 +192,9 @@ export default function createApp (option, config = {}) { // headerBackButtonDisplayMode: 'minimal', headerBackTitleVisible: false, // 安卓上会出现回退的时,如果设置为flat的话 navigator出现右滑退出,screen部分是fade的方式,交互效果不佳 - headerMode: 'screen' + headerMode: 'screen', + // 安卓上会出现初始化时闪现导航条的问题 + headerShown: false } if (headerBackImageProps) { navScreenOpts.headerBackImage = () => { From cb6492a834a4e8e1137b8974adc5c71faad1234f Mon Sep 17 00:00:00 2001 From: human Date: Sun, 22 Dec 2024 21:25:42 +0800 Subject: [PATCH 68/76] =?UTF-8?q?fix:=20=E6=96=87=E6=A1=88=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E4=B8=80=E4=B8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/platform/createApp.ios.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/platform/createApp.ios.js b/packages/core/src/platform/createApp.ios.js index dbcee86aa4..e775a9d9be 100644 --- a/packages/core/src/platform/createApp.ios.js +++ b/packages/core/src/platform/createApp.ios.js @@ -191,7 +191,7 @@ export default function createApp (option, config = {}) { // 7.x替换headerBackTitleVisible // headerBackButtonDisplayMode: 'minimal', headerBackTitleVisible: false, - // 安卓上会出现回退的时,如果设置为flat的话 navigator出现右滑退出,screen部分是fade的方式,交互效果不佳 + // 安卓上回退时,如果设置为float的话 navigator出现右滑退出,screen其实是fade的方式退出,交互不匹配,体验差,另外float模式会导致偶现状态栏透出native部分 headerMode: 'screen', // 安卓上会出现初始化时闪现导航条的问题 headerShown: false From 6104de2bc4d981ddb04c589a30020a868505a9cd Mon Sep 17 00:00:00 2001 From: human Date: Mon, 23 Dec 2024 11:41:07 +0800 Subject: [PATCH 69/76] =?UTF-8?q?fix:=20headerMode=E9=87=87=E7=94=A8stack?= =?UTF-8?q?=E7=9A=84=E9=BB=98=E8=AE=A4=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/platform/createApp.ios.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/core/src/platform/createApp.ios.js b/packages/core/src/platform/createApp.ios.js index e775a9d9be..2b15210bcb 100644 --- a/packages/core/src/platform/createApp.ios.js +++ b/packages/core/src/platform/createApp.ios.js @@ -191,8 +191,6 @@ export default function createApp (option, config = {}) { // 7.x替换headerBackTitleVisible // headerBackButtonDisplayMode: 'minimal', headerBackTitleVisible: false, - // 安卓上回退时,如果设置为float的话 navigator出现右滑退出,screen其实是fade的方式退出,交互不匹配,体验差,另外float模式会导致偶现状态栏透出native部分 - headerMode: 'screen', // 安卓上会出现初始化时闪现导航条的问题 headerShown: false } From 6f66760a3c70e3dafc6d1d57f87be3cde8969cb6 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Mon, 23 Dec 2024 12:16:59 +0800 Subject: [PATCH 70/76] fix app onhide in android --- packages/core/src/platform/createApp.ios.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/platform/createApp.ios.js b/packages/core/src/platform/createApp.ios.js index 5fae55fa0b..5857165c63 100644 --- a/packages/core/src/platform/createApp.ios.js +++ b/packages/core/src/platform/createApp.ios.js @@ -156,7 +156,7 @@ export default function createApp (option, config = {}) { if (navigation && hasOwn(global.__mpxPageStatusMap, navigation.pageId)) { global.__mpxPageStatusMap[navigation.pageId] = 'show' } - } else if (currentState === 'inactive') { + } else if (currentState === 'inactive' || currentState === 'background') { global.__mpxAppCbs.hide.forEach((cb) => { cb() }) From b51a7297a4baf1f6dc72ea248428ef23720b45b9 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Mon, 23 Dec 2024 17:15:15 +0800 Subject: [PATCH 71/76] =?UTF-8?q?fix:=20=E4=BA=8B=E4=BB=B6=E9=92=A9?= =?UTF-8?q?=E5=AD=90=E6=89=A7=E8=A1=8C=E4=B8=8D=E7=A8=B3=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/runtime/components/react/getInnerListeners.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts index 4a8b5c0677..2bd4da644d 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts @@ -317,11 +317,10 @@ const useInnerProps = ( } } - if (!rawEventKeys.length || config.disableTouch) { - return omit(propsRef.current, removeProps) - } - const events = useMemo(() => { + if (!rawEventKeys.length || config.disableTouch) { + return {} + } const transformedEventKeys = rawEventKeys.reduce((acc: string[], key) => { if (propsRef.current[key]) { return acc.concat(eventConfig[key]) @@ -339,7 +338,7 @@ const useInnerProps = ( }) return events - }, [hashEventKey]) + }, [hashEventKey, config.disableTouch]) return extendObject( {}, From 06dfc2f17238195c214b29abc9630d13298338d8 Mon Sep 17 00:00:00 2001 From: lareinayanyu Date: Mon, 23 Dec 2024 19:30:34 +0800 Subject: [PATCH 72/76] =?UTF-8?q?chore:=20=E4=B8=8B=E7=BA=BFdisableTouch?= =?UTF-8?q?=E7=9A=84=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/runtime/components/react/getInnerListeners.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts index 2bd4da644d..10f0ae1301 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts +++ b/packages/webpack-plugin/lib/runtime/components/react/getInnerListeners.ts @@ -289,7 +289,6 @@ const useInnerProps = ( const eventConfig: { [key: string]: string[] } = {} const config = rawConfig || { layoutRef: { current: {} }, - disableTouch: false, disableTap: false } const removeProps = [ @@ -318,7 +317,7 @@ const useInnerProps = ( } const events = useMemo(() => { - if (!rawEventKeys.length || config.disableTouch) { + if (!rawEventKeys.length) { return {} } const transformedEventKeys = rawEventKeys.reduce((acc: string[], key) => { @@ -338,7 +337,7 @@ const useInnerProps = ( }) return events - }, [hashEventKey, config.disableTouch]) + }, [hashEventKey]) return extendObject( {}, From a310c491f6e728b459a44d66aa6b6077ef0edb75 Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Tue, 24 Dec 2024 18:56:01 +0800 Subject: [PATCH 73/76] adjust parseAppProps returns --- packages/core/src/platform/createApp.ios.js | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/packages/core/src/platform/createApp.ios.js b/packages/core/src/platform/createApp.ios.js index 02f5cc5439..226894d9fc 100644 --- a/packages/core/src/platform/createApp.ios.js +++ b/packages/core/src/platform/createApp.ios.js @@ -1,6 +1,6 @@ import transferOptions from '../core/transferOptions' import builtInKeysMap from './patch/builtInKeysMap' -import { makeMap, spreadProp, parseUrlQuery, getFocusedNavigation, hasOwn, extend } from '@mpxjs/utils' +import { makeMap, spreadProp, getFocusedNavigation, hasOwn, extend } from '@mpxjs/utils' import { mergeLifecycle } from '../convertor/mergeLifecycle' import { LIFECYCLE } from '../platform/patch/lifecycle/index' import Mpx from '../index' @@ -96,14 +96,10 @@ export default function createApp (option, config = {}) { }) if (!global.__mpxAppLaunched) { - const parsed = Mpx.config.rnConfig.parseAppProps?.(props) || {} - if (parsed.url) { - const { path, queryObj } = parseUrlQuery(parsed.url) - Object.assign(initialRouteRef.current, { - initialRouteName: path.startsWith('/') ? path.slice(1) : path, - initialParams: queryObj - }) - } + const { initialRouteName, initialParams } = Mpx.config.rnConfig.parseAppProps?.(props) || {} + initialRouteRef.current.initialRouteName = initialRouteName || initialRouteRef.current.initialRouteName + initialRouteRef.current.initialParams = initialParams || initialRouteRef.current.initialParams + global.__mpxAppOnLaunch = (navigation) => { global.__mpxAppLaunched = true const state = navigation.getState() From c98c741cb96dab54edf1db1e58daaa1fa386e446 Mon Sep 17 00:00:00 2001 From: WX-DongXing Date: Fri, 27 Dec 2024 17:19:01 +0800 Subject: [PATCH 74/76] fix: use default gesture config --- packages/core/src/platform/createApp.ios.js | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/core/src/platform/createApp.ios.js b/packages/core/src/platform/createApp.ios.js index 226894d9fc..b3ef722394 100644 --- a/packages/core/src/platform/createApp.ios.js +++ b/packages/core/src/platform/createApp.ios.js @@ -183,7 +183,6 @@ export default function createApp (option, config = {}) { const { initialRouteName, initialParams } = initialRouteRef.current const headerBackImageProps = Mpx.config.rnConfig.headerBackImageProps || null const navScreenOpts = { - gestureEnabled: true, // 7.x替换headerBackTitleVisible // headerBackButtonDisplayMode: 'minimal', headerBackTitleVisible: false, From efb3a643f577810909c79cd58bbc44bf5fd4f35c Mon Sep 17 00:00:00 2001 From: hiyuki <674883329@qq.com> Date: Tue, 31 Dec 2024 18:18:08 +0800 Subject: [PATCH 75/76] optimize useTransformStyle with memo & adjust host props inherit & support unocss var --- .../builtInMixins/styleHelperMixin.ios.js | 2 +- .../platform/patch/getDefaultOptions.ios.js | 15 +- .../lib/runtime/components/react/utils.tsx | 148 +++++++++++------- 3 files changed, 97 insertions(+), 68 deletions(-) diff --git a/packages/core/src/platform/builtInMixins/styleHelperMixin.ios.js b/packages/core/src/platform/builtInMixins/styleHelperMixin.ios.js index 28fbe08a4a..3566007f75 100644 --- a/packages/core/src/platform/builtInMixins/styleHelperMixin.ios.js +++ b/packages/core/src/platform/builtInMixins/styleHelperMixin.ios.js @@ -181,7 +181,7 @@ export default function styleHelperMixin () { } else if (appClassMap[className]) { // todo 全局样式在每个页面和组件中生效,以支持全局原子类,后续支持样式模块复用后可考虑移除 Object.assign(result, appClassMap[className]) - } else if (this.__props[className] && isObject(this.__props[className])) { + } else if (isObject(this.__props[className])) { // externalClasses必定以对象形式传递下来 Object.assign(result, this.__props[className]) } diff --git a/packages/core/src/platform/patch/getDefaultOptions.ios.js b/packages/core/src/platform/patch/getDefaultOptions.ios.js index 1f44e346f6..ac4c5c7561 100644 --- a/packages/core/src/platform/patch/getDefaultOptions.ios.js +++ b/packages/core/src/platform/patch/getDefaultOptions.ios.js @@ -3,7 +3,7 @@ import * as ReactNative from 'react-native' import { ReactiveEffect } from '../../observer/effect' import { watch } from '../../observer/watch' import { reactive, set, del } from '../../observer/reactive' -import { hasOwn, isFunction, noop, isObject, isArray, getByPath, collectDataset, hump2dash, callWithErrorHandling, wrapMethodsWithErrorHandling } from '@mpxjs/utils' +import { hasOwn, isFunction, noop, isObject, isArray, getByPath, collectDataset, hump2dash, dash2hump, callWithErrorHandling, wrapMethodsWithErrorHandling } from '@mpxjs/utils' import MpxProxy from '../../core/proxy' import { BEFOREUPDATE, ONLOAD, UPDATED, ONSHOW, ONHIDE, ONRESIZE, REACTHOOKSEXEC } from '../../core/innerLifecycle' import mergeOptions from '../../core/mergeOptions' @@ -58,14 +58,12 @@ function createEffect (proxy, components) { proxy.toggleRecurse(true) } -function getRootProps (props) { +function getRootProps (props, validProps) { const rootProps = {} for (const key in props) { - if (hasOwn(props, key)) { - const match = /^(bind|catch|capture-bind|capture-catch|style|enable-var):?(.*?)(?:\.(.*))?$/.exec(key) - if (match) { - rootProps[key] = props[key] - } + const altKey = dash2hump(key) + if (!hasOwn(validProps, key) && !hasOwn(validProps, altKey) && key !== 'children') { + rootProps[key] = props[key] } } return rootProps @@ -474,7 +472,8 @@ export function getDefaultOptions ({ type, rawOptions = {}, currentInject }) { const root = useMemo(() => proxy.effect.run(), [finalMemoVersion]) if (root && root.props.ishost) { - const rootProps = getRootProps(props) + // 对于组件未注册的属性继承到host节点上,如事件、样式和其他属性等 + const rootProps = getRootProps(props, validProps) rootProps.style = Object.assign({}, root.props.style, rootProps.style) // update root props return cloneElement(root, rootProps) diff --git a/packages/webpack-plugin/lib/runtime/components/react/utils.tsx b/packages/webpack-plugin/lib/runtime/components/react/utils.tsx index a00bb771ea..99a171d7ec 100644 --- a/packages/webpack-plugin/lib/runtime/components/react/utils.tsx +++ b/packages/webpack-plugin/lib/runtime/components/react/utils.tsx @@ -18,8 +18,10 @@ export const HIDDEN_STYLE = { opacity: 0 } -const varDecRegExp = /^--.*/ +const varDecRegExp = /^--/ const varUseRegExp = /var\(/ +const unoVarDecRegExp = /^--un-/ +const unoVarUseRegExp = /var\(--un-/ const calcUseRegExp = /calc\(/ const envUseRegExp = /env\(/ @@ -37,7 +39,7 @@ function getSafeAreaInset (name: string) { } export function omit (obj: T, fields: K[]): Omit { - const shallowCopy: any = Object.assign({}, obj) + const shallowCopy: any = extendObject({}, obj) for (let i = 0; i < fields.length; i += 1) { const key = fields[i] delete shallowCopy[key] @@ -77,7 +79,7 @@ export const parseInlineStyle = (inlineStyle = ''): Record => { const [k, v, ...rest] = style.split(':') if (rest.length || !v || !k) return styleObj const key = k.trim().replace(/-./g, c => c.substring(1).toUpperCase()) - return Object.assign(styleObj, { [key]: global.__formatValue(v.trim()) }) + return extendObject(styleObj, { [key]: global.__formatValue(v.trim()) }) }, {}) } @@ -286,11 +288,15 @@ interface TransformStyleConfig { export function useTransformStyle (styleObj: Record = {}, { enableVar, externalVarContext, parentFontSize, parentWidth, parentHeight }: TransformStyleConfig) { const varStyle: Record = {} + const unoVarStyle: Record = {} const normalStyle: Record = {} + const normalStyleRef = useRef>({}) + const normalStyleChangedRef = useRef(false) let hasVarDec = false let hasVarUse = false let hasSelfPercent = false const varKeyPaths: Array> = [] + const unoVarKeyPaths: Array> = [] const percentKeyPaths: Array> = [] const calcKeyPaths: Array> = [] const envKeyPaths: Array> = [] @@ -299,7 +305,9 @@ export function useTransformStyle (styleObj: Record = {}, { enableV function varVisitor ({ key, value, keyPath }: VisitorArg) { if (keyPath.length === 1) { - if (varDecRegExp.test(key)) { + if (unoVarDecRegExp.test(key)) { + unoVarStyle[key] = value + } else if (varDecRegExp.test(key)) { hasVarDec = true varStyle[key] = value } else { @@ -308,25 +316,31 @@ export function useTransformStyle (styleObj: Record = {}, { enableV } } // 对于var定义中使用的var无需替换值,可以通过resolveVar递归解析出值 - if (!varDecRegExp.test(key) && varUseRegExp.test(value)) { - hasVarUse = true - varKeyPaths.push(keyPath.slice()) + if (!varDecRegExp.test(key)) { + // 一般情况下一个样式属性中不会混用unocss var和普通css var,可分开进行互斥处理 + if (unoVarUseRegExp.test(value)) { + unoVarKeyPaths.push(keyPath.slice()) + } else if (varUseRegExp.test(value)) { + hasVarUse = true + varKeyPaths.push(keyPath.slice()) + } } } - // traverse var + // traverse var & generate normalStyle traverseStyle(styleObj, [varVisitor]) + hasVarDec = hasVarDec || !!externalVarContext enableVar = enableVar || hasVarDec || hasVarUse const enableVarRef = useRef(enableVar) if (enableVarRef.current !== enableVar) { error('css variable use/declare should be stable in the component lifecycle, or you can set [enable-var] with true.') } - // apply var + // apply css var const varContextRef = useRef({}) if (enableVarRef.current) { const varContext = useContext(VarContext) - const newVarContext = Object.assign({}, varContext, externalVarContext, varStyle) + const newVarContext = extendObject({}, varContext, externalVarContext, varStyle) // 缓存比较newVarContext是否发生变化 if (diffAndCloneA(varContextRef.current, newVarContext).diff) { varContextRef.current = newVarContext @@ -334,70 +348,86 @@ export function useTransformStyle (styleObj: Record = {}, { enableV transformVar(normalStyle, varKeyPaths, varContextRef.current) } - function envVisitor ({ value, keyPath }: VisitorArg) { - if (envUseRegExp.test(value)) { - envKeyPaths.push(keyPath.slice()) - } + // apply unocss var + if (unoVarKeyPaths.length) { + transformVar(normalStyle, unoVarKeyPaths, unoVarStyle) } - function calcVisitor ({ value, keyPath }: VisitorArg) { - if (calcUseRegExp.test(value)) { - calcKeyPaths.push(keyPath.slice()) - } + const { clone, diff } = diffAndCloneA(normalStyle, normalStyleRef.current) + if (diff) { + normalStyleRef.current = clone + normalStyleChangedRef.current = !normalStyleChangedRef.current } - function percentVisitor ({ key, value, keyPath }: VisitorArg) { - if (hasOwn(selfPercentRule, key) && PERCENT_REGEX.test(value)) { - hasSelfPercent = true - percentKeyPaths.push(keyPath.slice()) - } else if ((key === 'fontSize' || key === 'lineHeight') && PERCENT_REGEX.test(value)) { - percentKeyPaths.push(keyPath.slice()) + const memoResult = useMemo(() => { + // transform can be memoized + function envVisitor ({ value, keyPath }: VisitorArg) { + if (envUseRegExp.test(value)) { + envKeyPaths.push(keyPath.slice()) + } } - } - // traverse env & calc & percent - traverseStyle(normalStyle, [envVisitor, percentVisitor, calcVisitor]) + function calcVisitor ({ value, keyPath }: VisitorArg) { + if (calcUseRegExp.test(value)) { + calcKeyPaths.push(keyPath.slice()) + } + } - const percentConfig = { - width, - height, - fontSize: normalStyle.fontSize, - parentWidth, - parentHeight, - parentFontSize - } + function percentVisitor ({ key, value, keyPath }: VisitorArg) { + if (hasOwn(selfPercentRule, key) && PERCENT_REGEX.test(value)) { + hasSelfPercent = true + percentKeyPaths.push(keyPath.slice()) + } else if ((key === 'fontSize' || key === 'lineHeight') && PERCENT_REGEX.test(value)) { + percentKeyPaths.push(keyPath.slice()) + } + } - // apply env - transformEnv(normalStyle, envKeyPaths) - // apply percent - transformPercent(normalStyle, percentKeyPaths, percentConfig) - // apply calc - transformCalc(normalStyle, calcKeyPaths, (value: string, key: string) => { - if (PERCENT_REGEX.test(value)) { - const resolved = resolvePercent(value, key, percentConfig) - return typeof resolved === 'number' ? resolved : 0 - } else { - const formatted = global.__formatValue(value) - if (typeof formatted === 'number') { - return formatted + // traverse env & calc & percent + traverseStyle(normalStyle, [envVisitor, percentVisitor, calcVisitor]) + + const percentConfig = { + width, + height, + fontSize: normalStyle.fontSize, + parentWidth, + parentHeight, + parentFontSize + } + + // apply env + transformEnv(normalStyle, envKeyPaths) + // apply percent + transformPercent(normalStyle, percentKeyPaths, percentConfig) + // apply calc + transformCalc(normalStyle, calcKeyPaths, (value: string, key: string) => { + if (PERCENT_REGEX.test(value)) { + const resolved = resolvePercent(value, key, percentConfig) + return typeof resolved === 'number' ? resolved : 0 } else { - warn('calc() only support number, px, rpx, % temporarily.') - return 0 + const formatted = global.__formatValue(value) + if (typeof formatted === 'number') { + return formatted + } else { + warn('calc() only support number, px, rpx, % temporarily.') + return 0 + } } + }) + // transform number enum stringify + transformStringify(normalStyle) + + return { + normalStyle, + hasSelfPercent } - }) - // transform number enum stringify - transformStringify(normalStyle) + }, [normalStyleChangedRef.current, width, height, parentWidth, parentHeight, parentFontSize]) - return { - normalStyle, - hasSelfPercent, + return extendObject({ hasVarDec, - enableVarRef, varContextRef, setWidth, setHeight - } + }, memoResult) } export interface VisitorArg { @@ -565,7 +595,7 @@ export const useStableCallback = ( } export const usePrevious = (value: T): T | undefined => { - const ref = useRef(undefined) + const ref = useRef() const prev = ref.current ref.current = value return prev From ca1fab6ff2f734dec3a7684655a3d0daa1b0dd33 Mon Sep 17 00:00:00 2001 From: human Date: Thu, 2 Jan 2025 18:02:23 +0800 Subject: [PATCH 76/76] fix: update docs --- docs-vuepress/guide/platform/rn.md | 33 ++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/docs-vuepress/guide/platform/rn.md b/docs-vuepress/guide/platform/rn.md index 9abfe43e3d..88d44c79ea 100644 --- a/docs-vuepress/guide/platform/rn.md +++ b/docs-vuepress/guide/platform/rn.md @@ -941,15 +941,44 @@ text-shadow: 1rpx 3rpx 0 #2E0C02; | ---- | ---- | ---- | | entryPagePath | 支持 | 无| | pages | 支持 | 无 | +| window | 子属性部分支持 | 参考下面window配置部分 | | tabbar | 暂未支持 | 无 | | networkTimeout | 支持 | 无 | | subpackages | 支持 | 分包在RN下暂未进行拆包处理,仅能正常打包在一起,分包能力待后续支持 | | usingComponents | 支持 | | | vw | 支持 | 无 | -#### 路由能力 - +##### window配置 +app里面的window配置,参考[微信内window配置说明](https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html#window) +| 配置项 | 支持情况 | 特殊说明 | +| ---- | ---- | ---- | +| navigationBarBackgroundColor | 支持 | 无| +| navigationBarTextStyle | 支持 | 无 | +| navigationStyle | 支持 | 无 | +| backgroundColor | 支持 | 无 | +#### 页面配置 +页面配置内可配置页面级别的属性,参考[微信页面配置说明](https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/page.html) +| 配置项 | 支持情况 | 特殊说明 | +| ---- | ---- | ---- | +| navigationBarBackgroundColor | 支持 | 无| +| navigationBarTextStyle | 支持 | 无 | +| navigationStyle | 支持 | 无 | +| backgroundColor | 支持 | 无 | +| usingComponents | 支持 | 无 | +| disableScroll | 不支持 | RN下默认页面不支持滚动,如需滚动需要使用可滚动的元素包裹 | + +#### 状态管理 +##### pinia +暂未支持 +##### store +已支持 +#### i18n +支持 +#### 原子类能力 +开发中,暂未支持 +#### 依赖注入(Provide/Inject) +开发中,暂未支持 ### 环境API