Skip to content

Commit

Permalink
feat(reactive-react): add reactive react package
Browse files Browse the repository at this point in the history
  • Loading branch information
janryWang committed Mar 10, 2021
1 parent eb9e421 commit 7d24537
Show file tree
Hide file tree
Showing 20 changed files with 379 additions and 4 deletions.
2 changes: 1 addition & 1 deletion packages/json-schema/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export const compile = <Source = any, Scope = any>(
return source
}
if (Schema.isSchemaInstance(source)) {
return source.fromJSON(source)
return source.compile(scope)
}
if (isFn(source['toJS'])) {
return source
Expand Down
10 changes: 10 additions & 0 deletions packages/reactive-react/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
node_modules
*.log
build
dist
docs
doc-site
__tests__
.eslintrc
jest.config.js
tsconfig.json
21 changes: 21 additions & 0 deletions packages/reactive-react/.umirc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { resolve } from 'path'
export default {
mode: 'doc',
logo:
'https://img.alicdn.com/imgextra/i2/O1CN01Kq3OHU1fph6LGqjIz_!!6000000004056-55-tps-1141-150.svg',
title: 'Formily',
hash: true,
favicon:
'//img.alicdn.com/imgextra/i3/O1CN01XtT3Tv1Wd1b5hNVKy_!!6000000002810-55-tps-360-360.svg',
outputPath: './doc-site',
styles: [
`
.__dumi-default-menu-header .__dumi-default-menu-logo{
width:200px !important;
}
.__dumi-default-menu-header h1{
display:none;
}
`,
],
}
20 changes: 20 additions & 0 deletions packages/reactive-react/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2015-present, Alibaba Group Holding Limited. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 changes: 28 additions & 0 deletions packages/reactive-react/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# @formily/reactive-react

## QuikStart

```tsx
import React from 'react'
import { observable } from '@formily/reactive'
import { observer } from '@formily/reactive-react'

const obs = observable({
count: 0,
})

export default observer(() => {
return (
<div>
{obs.count}
<button
onClick={() => {
obs.count++
}}
>
Click
</button>
</div>
)
})
```
1 change: 1 addition & 0 deletions packages/reactive-react/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../../scripts/jest.base')
50 changes: 50 additions & 0 deletions packages/reactive-react/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "@formily/reactive-react",
"version": "2.0.0-beta.3",
"license": "MIT",
"main": "lib",
"module": "esm",
"umd:main": "dist/formily.reactive-react.umd.production.js",
"unpkg": "dist/formily.reactive-react.umd.production.js",
"jsdelivr": "dist/formily.reactive-react.umd.production.js",
"jsnext:main": "esm",
"repository": {
"type": "git",
"url": "git+https://github.com/alibaba/formily.git"
},
"types": "esm/index.d.ts",
"bugs": {
"url": "https://github.com/alibaba/formily/issues"
},
"homepage": "https://github.com/alibaba/formily#readme",
"engines": {
"npm": ">=3.0.0"
},
"scripts": {
"start": "dumi dev",
"build": "rimraf -rf lib esm dist && npm run build:cjs && npm run build:esm && npm run build:umd",
"build:cjs": "tsc --declaration",
"build:esm": "tsc --declaration --module es2015 --outDir esm",
"build:umd": "rollup --config",
"build:docs": "dumi build"
},
"peerDependencies": {
"@types/react": ">=16.8.0 || >=17.0.0",
"@types/react-dom": ">=16.8.0 || >=17.0.0",
"mobx": "^6.0.3",
"react": ">=16.8.0 || >=17.0.0",
"react-dom": ">=16.8.0 || >=17.0.0"
},
"devDependencies": {
"dumi": "^1.1.0-rc.8"
},
"dependencies": {
"@formily/reactive":"^2.0.0-beta.3",
"@formily/shared": "^2.0.0-beta.3",
"hoist-non-react-statics": "^3.3.2"
},
"publishConfig": {
"access": "public"
},
"gitHead": "4d068dad6183e8da294a4c899a158326c0b0b050"
}
3 changes: 3 additions & 0 deletions packages/reactive-react/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import baseConfig from '../../scripts/rollup.base.js'

export default baseConfig('formily.reactive-react', 'Formily.ReactiveReact')
8 changes: 8 additions & 0 deletions packages/reactive-react/src/gc/global.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export {}
declare global {
export class FinalizationRegistry<T> {
constructor(cleanup: (cleanupToken: T) => void)
register(object: object, cleanupToken: T): void
unregister(object: object): void
}
}
36 changes: 36 additions & 0 deletions packages/reactive-react/src/gc/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { globalThisPolyfill } from '@formily/shared'
import './global'

const registry =
globalThisPolyfill['FinalizationRegistry'] &&
new globalThisPolyfill['FinalizationRegistry']((clean: () => void) => clean())

export class GarbageCollector {
private target: object
private cleaner: () => void
private expireTime: number
private request: NodeJS.Timeout
constructor(target: object, cleaner?: () => void, expireTime = 10_000) {
this.target = target
this.cleaner = cleaner
this.expireTime = expireTime
}

open() {
if (registry) {
registry.register(this.target, () => {
this.cleaner?.()
})
}
this.request = setTimeout(() => {
this.cleaner?.()
}, this.expireTime)
}

close() {
if (registry) {
registry.unregister(this.target)
}
clearTimeout(this.request)
}
}
2 changes: 2 additions & 0 deletions packages/reactive-react/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './useForceUpdate'
export * from './useObserver'
13 changes: 13 additions & 0 deletions packages/reactive-react/src/hooks/useForceUpdate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useCallback, useState } from 'react'

const EMPTY_ARRAY: any[] = []

export function useForceUpdate() {
const [, setTick] = useState(0)

const update = useCallback(() => {
setTick((tick) => tick + 1)
}, EMPTY_ARRAY)

return update
}
59 changes: 59 additions & 0 deletions packages/reactive-react/src/hooks/useObserver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from 'react'
import ReactDOM from 'react-dom'
import { Tracker } from '@formily/reactive'
import { isFn } from '@formily/shared'
import { GarbageCollector } from '../gc'
import { IObserverOptions } from '../types'
import { useForceUpdate } from './useForceUpdate'

const batchUpdate =
React['batchUpdate'] ||
ReactDOM['batchUpdate'] ||
ReactDOM['unstable_batchedUpdates']

class AutoCollector {}

export const useObserver = <T extends () => any>(
view: T,
options?: IObserverOptions
): ReturnType<T> => {
const forceUpdate = useForceUpdate()
const gcRef = React.useRef<GarbageCollector>()
const tracker = React.useMemo(() => {
const updater = () => {
if (isFn(batchUpdate)) {
batchUpdate(() => forceUpdate())
} else {
forceUpdate()
}
}
return new Tracker(() => {
if (isFn(options?.scheduler)) {
options.scheduler(updater)
} else {
updater()
}
})
}, [])
//StrictMode/ConcurrentMode会导致组件无法正确触发Unmount,所以只能自己做垃圾回收
if (!gcRef.current) {
const target = new AutoCollector()
gcRef.current = new GarbageCollector(target, () => {
if (tracker) {
tracker.dispose()
}
})
gcRef.current.open()
}

React.useEffect(() => {
gcRef.current.close()
return () => {
if (tracker) {
tracker.dispose()
}
}
}, [])

return tracker.track(view)
}
65 changes: 65 additions & 0 deletions packages/reactive-react/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import React, { memo, forwardRef } from 'react'
import hoistNonReactStatics from 'hoist-non-react-statics'
import { useObserver } from './hooks'
import { IObserverOptions } from './types'

export function observer<P extends object, TRef = {}>(
baseComponent: React.ForwardRefRenderFunction<TRef, P>,
options: IObserverOptions & { forwardRef: true }
): React.MemoExoticComponent<
React.ForwardRefExoticComponent<
React.PropsWithoutRef<P> & React.RefAttributes<TRef>
>
>

export function observer<P extends object>(
baseComponent: React.FunctionComponent<P>,
options?: IObserverOptions
): React.FunctionComponent<P>

export function observer<
C extends React.FunctionComponent<any> | React.ForwardRefRenderFunction<any>,
Options extends IObserverOptions
>(
baseComponent: C,
options?: Options
): Options extends { forwardRef: true }
? C extends React.ForwardRefRenderFunction<infer P, infer TRef>
? C &
React.MemoExoticComponent<
React.ForwardRefExoticComponent<
React.PropsWithoutRef<P> & React.RefAttributes<TRef>
>
>
: never /* forwardRef set for a non forwarding component */
: C & { displayName: string }

export function observer<P extends object, TRef = {}>(
baseComponent:
| React.ForwardRefRenderFunction<TRef, P>
| React.FunctionComponent<P>,
options?: IObserverOptions
) {
const realOptions = {
forwardRef: false,
...options,
}
const wrappedComponent = (props: P, ref: React.Ref<TRef>) => {
//eslint-disable-next-line
return useObserver(() => baseComponent(props, ref))
}
let memoComponent: any
if (realOptions.forwardRef) {
memoComponent = memo(forwardRef(wrappedComponent))
} else {
memoComponent = memo(wrappedComponent)
}

hoistNonReactStatics(memoComponent, baseComponent)

if (realOptions.displayName) {
memoComponent.displayName = realOptions.displayName
}

return memoComponent
}
6 changes: 6 additions & 0 deletions packages/reactive-react/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

export interface IObserverOptions {
forwardRef?: boolean
scheduler?: (updater: () => void) => void
displayName?: string
}
13 changes: 13 additions & 0 deletions packages/reactive-react/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./lib"
},
"include": [
"./src/**/*.ts",
"./src/**/*.tsx"
],
"exclude": [
"./src/__tests__/*"
]
}
1 change: 1 addition & 0 deletions packages/reactive/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from './batch'
export * from './observable'
export * from './define'
export * from './autorun'
export * from './tracker'
export * from './observe'
export * from './shared'
export * from './types'
12 changes: 10 additions & 2 deletions packages/reactive/src/reaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ const runReactions = (target: any, key: PropertyKey) => {
PendingReactions.add(reaction)
}
} else {
reaction()
if (isFn(reaction._scheduler)) {
reaction._scheduler(reaction)
} else {
reaction()
}
}
})
}
Expand Down Expand Up @@ -218,6 +222,10 @@ export const isBatching = () => BatchCount.value > 0
export const excutePendingReactions = () => {
PendingReactions.forEach((reaction) => {
PendingReactions.delete(reaction)
reaction()
if (isFn(reaction._scheduler)) {
reaction._scheduler(reaction)
} else {
reaction()
}
})
}
Loading

0 comments on commit 7d24537

Please sign in to comment.