Skip to content

Commit

Permalink
chore: 删除无用code
Browse files Browse the repository at this point in the history
  • Loading branch information
lareinayanyu committed Nov 6, 2024
1 parent 5e85740 commit d684e9d
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 162 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { warn } from '@mpxjs/utils'
interface Message {
id?: string
type: string
Expand Down Expand Up @@ -34,7 +35,7 @@ export default class Bus {
if (handler) {
handler(message)
} else {
console.warn('Received unexpected message', message)
warn(`Received unexpected message: ${message}`)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const PROPERTIES = {
}

const METHODS = [
// draw、createCircularGradient、setFillStyle、 setFontSize、 setGlobalAlpha、 setLineCap、setLineJoin、setLineWidth、setMiterLimit、setShadow、setStrokeStyle、 setTextAlign、setTextBaseline 不支持
'arc',
'arcTo',
'beginPath',
Expand Down Expand Up @@ -58,10 +59,11 @@ const METHODS = [
]

export function useContext2D (canvas: any) {
const contextRef = useWebviewBinding(
'context2D',
PROPERTIES,
METHODS
const contextRef = useWebviewBinding({
targetName: 'context2D',
properties: PROPERTIES,
methods: METHODS
}
)

useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,40 +247,6 @@ function handleMessage(_a) {
targets[target][key] = populateRefs(value);
break;
}
case "construct": {
var constructor = payload.constructor, target = payload.id, _d = payload.args, args = _d === void 0 ? [] : _d;
var newArgs = createObjectsFromArgs(args);
var object = void 0;
try {
object = new ((_c = constructors[constructor]).bind.apply(_c, __spreadArray([void 0], newArgs, false)))();
}
catch (error) {
throw new Error("Error while constructing ".concat(constructor, " ").concat(error.message));
}
object.__constructorName__ = constructor;
var message = toMessage({});
targets[target] = object;
window.ReactNativeWebView.postMessage(JSON.stringify(__assign({ id: id }, message)));
break;
}
case "listen": {
var types = payload.types, target_1 = payload.target;
for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
var eventType = types_1[_i];
targets[target_1].addEventListener(eventType, function (e) {
var _a;
var message = toMessage({
type: "event",
payload: {
type: e.type,
target: __assign(__assign({}, flattenObject(targets[target_1])), (_a = {}, _a[WEBVIEW_TARGET] = target_1, _a)),
},
});
window.ReactNativeWebView.postMessage(JSON.stringify(__assign({ id: id }, message)));
});
}
break;
}
}
}
var handleError = function (err, message) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
/**
* ✘ type
* ✘ canvas-id
* ✘ disable-scroll
* ✔ bindtouchstart
* ✔ bindtouchmove
* ✔ bindtouchend
* ✔ bindtouchcancel
* ✔ bindlongtap
* ✔ binderror
*/
import React, { useRef, useState, useCallback, useEffect, forwardRef, JSX, TouchEvent } from 'react'
import { View, Platform, StyleSheet, NativeSyntheticEvent } from 'react-native'
import { WebView } from 'react-native-webview'
import useNodesRef, { HandlerRef } from '../useNodesRef'
import { useLayout, useTransformStyle } from '../utils'
import useInnerProps from '../getInnerListeners'
import useInnerProps, { getCustomEvent } from '../getInnerListeners'
import Bus from './Bus'
import {
useWebviewBinding,
constructors,
WEBVIEW_TARGET
useWebviewBinding
} from './utils'
import { useContext2D } from './canvasRenderingContext2D'
import html from './index.html'
Expand Down Expand Up @@ -48,15 +57,13 @@ const _Canvas = forwardRef<HandlerRef<CanvasProps & View, CanvasProps>, CanvasPr
const { style = {}, originWhitelist = ['*'], 'enable-var': enableVar, 'external-var-context': externalVarContext, 'parent-font-size': parentFontSize, 'parent-width': parentWidth, 'parent-height': parentHeight } = props
const { width, height } = style
const [isLoaded, setIsLoaded] = useState(false)
const listenersRef = useRef([])
const nodeRef = useRef(null)

const canvasRef = useWebviewBinding(
'canvas',
{ width, height },
['toDataURL'],
[]
)
const canvasRef = useWebviewBinding({
targetName: 'canvas',
properties: { width, height },
methods: ['toDataURL']
})

const {
normalStyle,
Expand Down Expand Up @@ -84,33 +91,24 @@ const _Canvas = forwardRef<HandlerRef<CanvasProps & View, CanvasProps>, CanvasPr

// 初始化bus和context2D
useEffect(() => {
const webviewPostMessage = (message) => {
if (canvasRef.current.webview) {
canvasRef.current.webview.postMessage(JSON.stringify(message))
}
const webviewPostMessage = (message) => {
if (canvasRef.current.webview) {
canvasRef.current.webview.postMessage(JSON.stringify(message))
}
}

// 设置bus
canvasRef.current.bus = new Bus(webviewPostMessage)
canvasRef.current.bus.pause()

// 设置listeners数组
canvasRef.current.listeners = []

// 设置addMessageListener方法
canvasRef.current.addMessageListener = addMessageListener

// 设置removeMessageListener方法
canvasRef.current.removeMessageListener = removeMessageListener
// 设置bus
canvasRef.current.bus = new Bus(webviewPostMessage)
canvasRef.current.bus.pause()

// 设置context2D
canvasRef.current.context2D = context2D
// 设置context2D
canvasRef.current.context2D = context2D

// 设置getContext方法
canvasRef.current.getContext = getContext
// 设置getContext方法
canvasRef.current.getContext = getContext

// 设置postMessage方法
canvasRef.current.postMessage = postMessage
// 设置postMessage方法
canvasRef.current.postMessage = postMessage
}, [])

const getContext = useCallback((contextType: string) => {
Expand All @@ -120,32 +118,26 @@ const _Canvas = forwardRef<HandlerRef<CanvasProps & View, CanvasProps>, CanvasPr
return null
}, [])

const addMessageListener = useCallback((listener) => {
listenersRef.current.push(listener)
return () => removeMessageListener(listener)
}, [])

const removeMessageListener = useCallback((listener) => {
const index = listenersRef.current.indexOf(listener)
if (index > -1) {
listenersRef.current.splice(index, 1)
}
}, [])

const postMessage = useCallback(async (message) => {
if (!canvasRef.current?.bus) return

const { stack } = new Error()
const { type, payload } = await canvasRef.current.bus.post({
id: Math.random(),
...message
})

switch (type) {
case 'error': {
const error = new Error(payload.message)
error.stack = stack
throw error
const { binderror } = props
binderror &&
binderror(
getCustomEvent('error', {}, {
detail: {
errMsg: payload.message
},
layoutRef
}, props)
)
break
}
case 'json': {
return payload
Expand All @@ -156,39 +148,29 @@ const _Canvas = forwardRef<HandlerRef<CanvasProps & View, CanvasProps>, CanvasPr
}
}, [])

const handleMessage = useCallback((e) => {

let data = JSON.parse(e.nativeEvent.data)
const onMessage = useCallback((e) => {
const data = JSON.parse(e.nativeEvent.data)
switch (data.type) {
case 'log': {
console.log(...data.payload)
break
}
case 'error': {
throw new Error(data.payload.message)
const { binderror } = props
binderror &&
binderror(
getCustomEvent('error', e, {
detail: {
errMsg: data.payload.message
},
layoutRef
}, props)
)
break
}
default: {
if (data.payload) {
const constructor = constructors[data.meta?.constructor]
if (constructor) {
const { args, payload } = data
const object = constructor.constructLocally(canvasRef.current, ...args)
Object.assign(object, payload, {
[WEBVIEW_TARGET]: data.meta.target
})
data = {
...data,
payload: object
}
}
canvasRef.current.listeners.forEach(listener => listener(data.payload))
}
canvasRef.current.bus.handle(data)
}
}
}, [])

const handleLoad = useCallback(() => {
const onLoad = useCallback(() => {
setIsLoaded(true)
if (canvasRef.current?.bus) {
canvasRef.current.bus.resume()
Expand All @@ -215,8 +197,8 @@ const _Canvas = forwardRef<HandlerRef<CanvasProps & View, CanvasProps>, CanvasPr
]}
source={{ html }}
originWhitelist={originWhitelist}
onMessage={handleMessage}
onLoad={handleLoad}
onMessage={onMessage}
onLoad={onLoad}
overScrollMode="never"
mixedContentMode="always"
scalesPageToFit={false}
Expand All @@ -242,8 +224,8 @@ const _Canvas = forwardRef<HandlerRef<CanvasProps & View, CanvasProps>, CanvasPr
style={[stylesheet.webview, { height, width }]}
source={{ html }}
originWhitelist={originWhitelist}
onMessage={handleMessage}
onLoad={handleLoad}
onMessage={onMessage}
onLoad={onLoad}
scrollEnabled={false}
/>
</View>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useEffect, useRef } from 'react'

export const WEBVIEW_TARGET = '@@WEBVIEW_TARGET'

export const constructors: Record<string, any> = {}
export const constructors = {}

interface WebviewInstance {
[WEBVIEW_TARGET]: string
Expand Down Expand Up @@ -75,58 +75,26 @@ const setupWebviewMethods = (instance: WebviewInstance, methods: string[]): void
})
}

const setupWebviewEvents = (instance: WebviewInstance, eventTypes: string[]): void => {
if (eventTypes.length > 0) {
instance.postMessage({
type: 'listen',
payload: {
types: eventTypes,
target: instance[WEBVIEW_TARGET]
}
})

instance.addEventListener = function (type: string, callback: (event: any) => void) {
this.addMessageListener((message: WebviewMessage) => {
if (
message &&
message.type === 'event' &&
message.payload.target &&
typeof message.payload.target === 'object' &&
message.payload.target[WEBVIEW_TARGET] === this[WEBVIEW_TARGET] &&
message.payload.type === type
) {
for (const key in message.payload.target) {
const value = message.payload.target[key]
if (key in this && this[key] !== value) {
this[key] = value
}
}
callback({
...message.payload,
target: this
})
}
})
}
}
}

export const useWebviewBinding = (
targetName: string,
properties: Record<string, any> = {},
methods: string[] = [],
eventTypes: string[] = []
) => {
export const useWebviewBinding = ({
targetName,
properties = {},
methods = [],
constructorName = ''
}: {
targetName: string;
properties?: Record<string, any>;
methods?: string[];
constructorName?: string
}) => {
const instanceRef = useRef<WebviewInstance>({})

useEffect(() => {
if (instanceRef.current) {
setupWebviewTarget(instanceRef.current, targetName)
setupWebviewProperties(instanceRef.current, properties)
setupWebviewMethods(instanceRef.current, methods)
setupWebviewEvents(instanceRef.current, eventTypes)
}
}, [targetName, properties, methods, eventTypes])
}, [targetName, properties, methods])

return instanceRef
}

0 comments on commit d684e9d

Please sign in to comment.