Skip to content

Commit

Permalink
feat: add scroll to view
Browse files Browse the repository at this point in the history
  • Loading branch information
Fog3211 committed Jun 4, 2021
1 parent 897e6f6 commit 780794f
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { default as numberParse } from './numberParse'
export { numberParse, numberMatch } from './numberParse'
export { default as scrollToView } from './scrollToView'
2 changes: 2 additions & 0 deletions src/numberParse/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const FLOAT_REGEXP = /-?\d+(\.\d+)?/g

type ParserResult<T> = T extends ('NUMBER_FLOAT' | 'NUMBER_INT') ? number : string

/** 解析字符串中的数字 */
export const numberParse = <T = 'STRING_FLOAT'>(str: string, options?: Options<T>): ParserResult<T> | undefined => {
const { digits, format = 'STRING_FLOAT', customRegexp } = options ?? {}
const isFloat = format === 'NUMBER_FLOAT' || format === 'STRING_FLOAT'
Expand Down Expand Up @@ -51,6 +52,7 @@ export const numberParse = <T = 'STRING_FLOAT'>(str: string, options?: Options<T
}
}

/** 匹配字符串中的数字 */
export const numberMatch = <T = 'STRING_FLOAT'>(str: string, options?: Options<T>): ParserResult<T>[] => {
const { digits, format = 'STRING_FLOAT', customRegexp } = options ?? {}
const isFloat = format === 'NUMBER_FLOAT' || format === 'STRING_FLOAT'
Expand Down
36 changes: 36 additions & 0 deletions src/scrollToView/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

export type Options = ScrollToOptions & {
/** 横向滚动位置偏移量,正数偏右,负数偏左 */
offsetX?: number
/** 纵向滚动位置偏移量,正数偏上,负数偏下 */
offsetY?: number
/** css选择器,用于指定滚动的dom */
selector?: string
}

/** 滚动至可视区域 */
const scrollToView = (options: Options) => {
const { top, left, offsetY = 0, offsetX = 0, selector, behavior } = options ?? {}
let elmSelector = selector
if (!elmSelector) {
// 如果未指定选择器,就从路由里面读取锚点
const matchs = window.location.hash.match(/(#\w+)/g)
if (matchs) {
elmSelector = matchs[matchs.length - 1]
}
}
if (elmSelector) {
const dom = document.querySelector(elmSelector)
if (dom) {
window.scrollTo({
behavior,
top: top ?? dom.getBoundingClientRect().top + offsetY,
left: left ?? dom.getBoundingClientRect().left + offsetX,
})
}
} else {
throw new Error('Did you forget params selector?')
}
}

export default scrollToView

0 comments on commit 780794f

Please sign in to comment.