Skip to content

Commit

Permalink
feat(runtime-web): fields 调用和 scrollOffset,boundingClientRect 调用隔离 (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
hwaphon authored May 22, 2023
1 parent d3cd994 commit f6d23e1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 20 deletions.
46 changes: 26 additions & 20 deletions packages/runtime-web/src/api/ui/element-query/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// 节点相关查询接口
import { getRootView, updateRootView } from '../../global'
import { wait } from '../../utils'
import { isFunction, isObject, wait } from '../../utils'
import IntersectionObserver from './intersection-observer'
import { FIELD_CONFIG_METHODS_MAP, mapTarget } from './utils'

Expand All @@ -17,6 +17,7 @@ class SelectorQuery {
private target: HTMLElement | NodeListOf<HTMLElement>

private execPromises: Promise<any>[] = []
private fieldsPromise: Promise<any>[] = []

select(selector: string) {
this.target = getRootView().querySelector(selector) as HTMLElement
Expand Down Expand Up @@ -61,35 +62,40 @@ class SelectorQuery {
return this
}

fields(config) {
fields(config, callback) {
const target = this.target

this.execPromises.push(
wait().then(() => {
return mapTarget(target, (el: HTMLElement) => {
return Object.keys(config).reduce((res, key) => {
if (
config[key] &&
typeof FIELD_CONFIG_METHODS_MAP[key] === 'function'
) {
const value = FIELD_CONFIG_METHODS_MAP[key](el, config[key])

if (typeof value === 'object') res = { ...res, ...value }
else res[key] = value
}

return res
}, {})
this.fieldsPromise.push(
wait()
.then(() => {
return mapTarget(target, (el: HTMLElement) => {
return Object.keys(config).reduce((res, key) => {
if (
config[key] &&
typeof FIELD_CONFIG_METHODS_MAP[key] === 'function'
) {
const value = FIELD_CONFIG_METHODS_MAP[key](el, config[key])

if (isObject(value)) res = { ...res, ...value }
else res[key] = value
}
return res
}, {})
})
})
})
.then((res) => isFunction(callback) && callback(res))
)

return this
}

exec(callback) {
Promise.all(this.execPromises).then((res) => {
callback(res)
isFunction(callback) && callback(res)
})

if (this.fieldsPromise.length > 0) {
Promise.all(this.fieldsPromise)
}
}
}
4 changes: 4 additions & 0 deletions packages/runtime-web/src/api/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,7 @@ export const wait = (millisecond = 67) => {
setTimeout(resolve, millisecond)
})
}

export const isObject = (param) => param && typeof param === 'object'

export const isFunction = (param) => typeof param === 'function'

0 comments on commit f6d23e1

Please sign in to comment.