Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(anchor): [anchor] add top-offset props #2388

Merged
merged 1 commit into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions packages/renderless/src/anchor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,11 @@ export const onItersectionObserver =
({ state, props, api, vm, emit }: Pick<IAnchorRenderlessParams, 'state' | 'props' | 'api' | 'vm' | 'emit'>) =>
() => {
const { expandLink, scrollContainer } = state
const { topOffset } = props
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add type checking and validation for topOffset.

The topOffset property is used without type checking or validation. Consider adding runtime checks to ensure it's a non-negative number.

Add validation before using topOffset:

-    const { topOffset } = props
+    const topOffset = Math.max(0, Number(props.topOffset) || 0)

Also applies to: 173-173

state.currentLink && updateSkidPosition({ vm, state, emit })
const rootMargin = topOffset ? `${-topOffset}px 0px 0px 0px` : ''
state.intersectionObserver = new IntersectionObserver(
(entries) => {
const { top } = scrollContainer.getBoundingClientRect()
const scrollStartTop = top + state.offsetTop
entries.forEach((item) => {
const key = item.target.id
state.observerLinks[key] = item
Expand All @@ -194,11 +194,7 @@ export const onItersectionObserver =
for (let key in state.observerLinks) {
if (Object.prototype.hasOwnProperty.call(state.observerLinks, key)) {
const item = state.observerLinks[key]
if (
item.isIntersecting &&
item.intersectionRatio >= 0 &&
item.target.getBoundingClientRect().top < scrollStartTop
) {
if (item.isIntersecting && item.intersectionRatio >= 0) {
const link = `#${item.target.id}`
if (!expandLink[link].children) {
api.getCurrentAnchor(link)
Expand All @@ -210,7 +206,7 @@ export const onItersectionObserver =
}
}
},
{ root: scrollContainer, threshold: [0, 0.25, 0.5, 1] }
{ root: scrollContainer, threshold: [0, 0.25, 0.5, 1], rootMargin }
)

addObserver({ props, state })
Expand All @@ -232,7 +228,11 @@ export const linkClick =

if (scrollContainer && scrollContainer !== document.body && !isChangeHash) {
const linkEl = scrollContainer.querySelector(item.link) as HTMLElement
const top = linkEl?.offsetTop - scrollContainer.offsetTop // 修复横向锚点无法滚动到顶部
const top =
linkEl?.getBoundingClientRect().top -
scrollContainer.getBoundingClientRect().top +
scrollContainer.scrollTop -
props.topOffset // 修复横向锚点无法滚动到顶部
Comment on lines +231 to +235
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add null safety and consider cross-browser compatibility.

The scroll position calculation looks correct but has the following concerns:

  1. Missing null check for linkEl before accessing getBoundingClientRect
  2. The scrollTo with smooth behavior isn't supported in all browsers

Add null safety and fallback:

-      const top =
-        linkEl?.getBoundingClientRect().top -
-        scrollContainer.getBoundingClientRect().top +
-        scrollContainer.scrollTop -
-        props.topOffset
-      const param = { top, left: 0, behavior: 'smooth' } as ScrollToOptions
-      scrollContainer?.scrollTo(param)
+      if (linkEl) {
+        const top =
+          linkEl.getBoundingClientRect().top -
+          scrollContainer.getBoundingClientRect().top +
+          scrollContainer.scrollTop -
+          (props.topOffset || 0)
+        try {
+          scrollContainer.scrollTo({ top, left: 0, behavior: 'smooth' })
+        } catch (e) {
+          // Fallback for browsers that don't support smooth scrolling
+          scrollContainer.scrollTop = top
+        }
+      }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const top =
linkEl?.getBoundingClientRect().top -
scrollContainer.getBoundingClientRect().top +
scrollContainer.scrollTop -
props.topOffset // 修复横向锚点无法滚动到顶部
if (linkEl) {
const top =
linkEl.getBoundingClientRect().top -
scrollContainer.getBoundingClientRect().top +
scrollContainer.scrollTop -
(props.topOffset || 0)
try {
scrollContainer.scrollTo({ top, left: 0, behavior: 'smooth' })
} catch (e) {
// Fallback for browsers that don't support smooth scrolling
scrollContainer.scrollTop = top
}
}

const param = { top, left: 0, behavior: 'smooth' } as ScrollToOptions
scrollContainer?.scrollTo(param)
scrollContainer?.addEventListener('scroll', api.handleScroll())
Expand Down
4 changes: 4 additions & 0 deletions packages/vue/src/anchor/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ export const anchorProps = {
type: {
type: String,
default: 'line'
},
topOffset: {
type: Number,
default: 0
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/vue/src/anchor/src/pc.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { IAnchorApi } from '@opentiny/vue-renderless/types/anchor.type'
export default defineComponent({
name: $prefix + 'Anchor',
directives: { AutoTip },
props: [...props, 'isAffix', 'links', 'containerId', 'markClass', 'type'],
props: [...props, 'isAffix', 'links', 'containerId', 'markClass', 'type', 'topOffset'],
emits: ['linkClick', 'onChange', 'change'], // deprecated v3.12.0废弃,v3.17.0移除onChange 事件
setup(props, context) {
return setup({ props, context, renderless, api }) as unknown as IAnchorApi
Expand Down
Loading