deploy: v0.12 fix 存档key名

This commit is contained in:
2026-06-24 03:09:02 +00:00
parent 7a08d49fe3
commit e0a5281119
58743 changed files with 7297269 additions and 39505 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Cody Olsen
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.
+135
View File
@@ -0,0 +1,135 @@
[![npm stat](https://img.shields.io/npm/dm/compute-scroll-into-view.svg?style=flat-square)](https://npm-stat.com/charts.html?package=compute-scroll-into-view)
[![npm version](https://img.shields.io/npm/v/compute-scroll-into-view.svg?style=flat-square)](https://www.npmjs.com/package/compute-scroll-into-view)
[![gzip size][gzip-badge]][unpkg-dist]
[![size][size-badge]][unpkg-dist]
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)](https://github.com/semantic-release/semantic-release)
![compute-scroll-into-view](https://user-images.githubusercontent.com/81981/43024153-a2cc212c-8c6d-11e8-913b-b4d62efcf105.png)
Lower level API that is used by the [ponyfill](https://ponyfill.com) [scroll-into-view-if-needed](https://github.com/scroll-into-view/scroll-into-view-if-needed) to compute where (if needed) elements should scroll based on [options defined in the spec](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) and the [`scrollMode: "if-needed"` draft spec proposal](https://github.com/w3c/csswg-drafts/pull/1805).
Use this if you want the smallest possible bundlesize and is ok with implementing the actual scrolling yourself.
Scrolling SVG elements are supported, as well as Shadow DOM elements. The [VisualViewport](https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport) API is also supported, ensuring scrolling works properly on modern devices. Quirksmode is also supported as long as you polyfill [`document.scrollingElement`](https://developer.mozilla.org/en-US/docs/Web/API/document/scrollingElement).
- [Install](#install)
- [Usage](#usage)
- [API](#api)
- [compute(target, options)](#computetarget-options)
- [options](#options)
- [block](#block)
- [inline](#inline)
- [scrollMode](#scrollmode)
- [boundary](#boundary)
- [skipOverflowHiddenElements](#skipoverflowhiddenelements)
# Install
```bash
npm i compute-scroll-into-view
```
You can also use it from a CDN:
```js
const { default: compute } = await import(
'https://esm.sh/compute-scroll-into-view'
)
```
# Usage
```js
import compute from 'compute-scroll-into-view'
const node = document.getElementById('hero')
// same behavior as Element.scrollIntoView({block: "nearest", inline: "nearest"})
// see: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
const actions = compute(node, {
scrollMode: 'if-needed',
block: 'nearest',
inline: 'nearest',
})
// same behavior as Element.scrollIntoViewIfNeeded(true)
// see: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded
const actions = compute(node, {
scrollMode: 'if-needed',
block: 'center',
inline: 'center',
})
// Then perform the scrolling, use scroll-into-view-if-needed if you don't want to implement this part
actions.forEach(({ el, top, left }) => {
el.scrollTop = top
el.scrollLeft = left
})
```
# API
## compute(target, options)
## options
Type: `Object`
### [block](https://scroll-into-view.dev/#scroll-alignment)
Type: `'start' | 'center' | 'end' | 'nearest'`<br> Default: `'center'`
Control the logical scroll position on the y-axis. The spec states that the `block` direction is related to the [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode), but this is not implemented yet in this library.
This means that `block: 'start'` aligns to the top edge and `block: 'end'` to the bottom.
### [inline](https://scroll-into-view.dev/#scroll-alignment)
Type: `'start' | 'center' | 'end' | 'nearest'`<br> Default: `'nearest'`
Like `block` this is affected by the [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode). In left-to-right pages `inline: 'start'` will align to the left edge. In right-to-left it should be flipped. This will be supported in a future release.
### [scrollMode](https://scroll-into-view.dev/#scrolling-if-needed)
Type: `'always' | 'if-needed'`<br> Default: `'always'`
This is a proposed addition to the spec that you can track here: https://github.com/w3c/csswg-drafts/pull/5677
This library will be updated to reflect any changes to the spec and will provide a migration path.
To be backwards compatible with `Element.scrollIntoViewIfNeeded` if something is not 100% visible it will count as "needs scrolling". If you need a different visibility ratio your best option would be to implement an [Intersection Observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
### [boundary](https://scroll-into-view.dev/#limit-propagation)
Type: `Element | Function`
By default there is no boundary. All the parent elements of your target is checked until it reaches the viewport ([`document.scrollingElement`](https://developer.mozilla.org/en-US/docs/Web/API/document/scrollingElement)) when calculating layout and what to scroll.
By passing a boundary you can short-circuit this loop depending on your needs:
- Prevent the browser window from scrolling.
- Scroll elements into view in a list, without scrolling container elements.
You can also pass a function to do more dynamic checks to override the scroll scoping:
```js
const actions = compute(target, {
boundary: (parent) => {
// By default `overflow: hidden` elements are allowed, only `overflow: visible | clip` is skipped as
// this is required by the CSSOM spec
if (getComputedStyle(parent)['overflow'] === 'hidden') {
return false
}
return true
},
})
```
### skipOverflowHiddenElements
Type: `Boolean`<br> Default: `false`
By default the [spec](https://drafts.csswg.org/cssom-view/#scrolling-box) states that `overflow: hidden` elements should be scrollable because it has [been used to allow programatic scrolling](https://drafts.csswg.org/css-overflow-3/#valdef-overflow-hidden). This behavior can sometimes lead to [scrolling issues](https://github.com/scroll-into-view/scroll-into-view-if-needed/pull/225#issue-186419520) when you have a node that is a child of an `overflow: hidden` node.
This package follows the convention [adopted by Firefox](https://hg.mozilla.org/integration/fx-team/rev/c48c3ec05012#l7.18) of setting a boolean option to _not_ scroll all nodes with `overflow: hidden` set.
[gzip-badge]: https://img.shields.io/bundlephobia/minzip/compute-scroll-into-view?label=gzip%20size&style=flat-square
[size-badge]: https://img.shields.io/bundlephobia/min/compute-scroll-into-view?label=size&style=flat-square
[unpkg-dist]: https://unpkg.com/compute-scroll-into-view/dist/
+1
View File
@@ -0,0 +1 @@
"use strict";let e=e=>"object"==typeof e&&null!=e&&1===e.nodeType,t=(e,t)=>(!t||"hidden"!==e)&&("visible"!==e&&"clip"!==e),n=(e,n)=>{if(e.clientHeight<e.scrollHeight||e.clientWidth<e.scrollWidth){let l=getComputedStyle(e,null);return t(l.overflowY,n)||t(l.overflowX,n)||(e=>{let t=(e=>{if(!e.ownerDocument||!e.ownerDocument.defaultView)return null;try{return e.ownerDocument.defaultView.frameElement}catch(e){return null}})(e);return!!t&&(t.clientHeight<e.scrollHeight||t.clientWidth<e.scrollWidth)})(e)}return!1},l=(e,t,n,l,i,o,r,d)=>o<e&&r>t||o>e&&r<t?0:o<=e&&d<=n||r>=t&&d>=n?o-e-l:r>t&&d<n||o<e&&d>n?r-t+i:0,i=e=>{let t=e.parentElement;return null==t?e.getRootNode().host||null:t};module.exports=(t,o)=>{var r,d,h,f,u,s;if("undefined"==typeof document)return[];let{scrollMode:c,block:a,inline:g,boundary:m,skipOverflowHiddenElements:p}=o,w="function"==typeof m?m:e=>e!==m;if(!e(t))throw new TypeError("Invalid target");let W=document.scrollingElement||document.documentElement,H=[],b=t;for(;e(b)&&w(b);){if(b=i(b),b===W){H.push(b);break}null!=b&&b===document.body&&n(b)&&!n(document.documentElement)||null!=b&&n(b,p)&&H.push(b)}let v=null!=(d=null==(r=window.visualViewport)?void 0:r.width)?d:innerWidth,y=null!=(f=null==(h=window.visualViewport)?void 0:h.height)?f:innerHeight,E=null!=(u=window.scrollX)?u:pageXOffset,M=null!=(s=window.scrollY)?s:pageYOffset,{height:x,width:I,top:C,right:R,bottom:T,left:V}=t.getBoundingClientRect(),k="start"===a||"nearest"===a?C:"end"===a?T:C+x/2,B="center"===g?V+I/2:"end"===g?R:V,D=[];for(let e=0;e<H.length;e++){let t=H[e],{height:n,width:i,top:o,right:r,bottom:d,left:h}=t.getBoundingClientRect();if("if-needed"===c&&C>=0&&V>=0&&T<=y&&R<=v&&C>=o&&T<=d&&V>=h&&R<=r)return D;let f=getComputedStyle(t),u=parseInt(f.borderLeftWidth,10),s=parseInt(f.borderTopWidth,10),m=parseInt(f.borderRightWidth,10),p=parseInt(f.borderBottomWidth,10),w=0,b=0,O="offsetWidth"in t?t.offsetWidth-t.clientWidth-u-m:0,X="offsetHeight"in t?t.offsetHeight-t.clientHeight-s-p:0,Y="offsetWidth"in t?0===t.offsetWidth?0:i/t.offsetWidth:0,L="offsetHeight"in t?0===t.offsetHeight?0:n/t.offsetHeight:0;if(W===t)w="start"===a?k:"end"===a?k-y:"nearest"===a?l(M,M+y,y,s,p,M+k,M+k+x,x):k-y/2,b="start"===g?B:"center"===g?B-v/2:"end"===g?B-v:l(E,E+v,v,u,m,E+B,E+B+I,I),w=Math.max(0,w+M),b=Math.max(0,b+E);else{w="start"===a?k-o-s:"end"===a?k-d+p+X:"nearest"===a?l(o,d,n,s,p+X,k,k+x,x):k-(o+n/2)+X/2,b="start"===g?B-h-u:"center"===g?B-(h+i/2)+O/2:"end"===g?B-r+m+O:l(h,r,i,u,m+O,B,B+I,I);let{scrollLeft:e,scrollTop:f}=t;w=Math.max(0,Math.min(f+w/L,t.scrollHeight-n/L+X)),b=Math.max(0,Math.min(e+b/Y,t.scrollWidth-i/Y+O)),k+=f-w,B+=e-b}D.push({el:t,top:w,left:b})}return D};//# sourceMappingURL=index.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
+73
View File
@@ -0,0 +1,73 @@
/** @public */
declare const _default: (target: Element, options: Options) => ScrollAction[]
export default _default
/** @public */
export declare interface Options {
/**
* Control the logical scroll position on the y-axis. The spec states that the `block` direction is related to the [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode), but this is not implemented yet in this library.
* This means that `block: 'start'` aligns to the top edge and `block: 'end'` to the bottom.
* @defaultValue 'center'
*/
block?: ScrollLogicalPosition
/**
* Like `block` this is affected by the [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode). In left-to-right pages `inline: 'start'` will align to the left edge. In right-to-left it should be flipped. This will be supported in a future release.
* @defaultValue 'nearest'
*/
inline?: ScrollLogicalPosition
/**
* This is a proposed addition to the spec that you can track here: https://github.com/w3c/csswg-drafts/pull/5677
*
* This library will be updated to reflect any changes to the spec and will provide a migration path.
* To be backwards compatible with `Element.scrollIntoViewIfNeeded` if something is not 100% visible it will count as "needs scrolling". If you need a different visibility ratio your best option would be to implement an [Intersection Observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
* @defaultValue 'always'
*/
scrollMode?: ScrollMode
/**
* By default there is no boundary. All the parent elements of your target is checked until it reaches the viewport ([`document.scrollingElement`](https://developer.mozilla.org/en-US/docs/Web/API/document/scrollingElement)) when calculating layout and what to scroll.
* By passing a boundary you can short-circuit this loop depending on your needs:
*
* - Prevent the browser window from scrolling.
* - Scroll elements into view in a list, without scrolling container elements.
*
* You can also pass a function to do more dynamic checks to override the scroll scoping:
*
* ```js
* let actions = compute(target, {
* boundary: (parent) => {
* // By default `overflow: hidden` elements are allowed, only `overflow: visible | clip` is skipped as
* // this is required by the CSSOM spec
* if (getComputedStyle(parent)['overflow'] === 'hidden') {
* return false
* }
* return true
* },
* })
* ```
* @defaultValue null
*/
boundary?: Element | ((parent: Element) => boolean) | null
/**
* New option that skips auto-scrolling all nodes with overflow: hidden set
* See FF implementation: https://hg.mozilla.org/integration/fx-team/rev/c48c3ec05012#l7.18
* @defaultValue false
* @public
*/
skipOverflowHiddenElements?: boolean
}
/** @public */
export declare interface ScrollAction {
el: Element
top: number
left: number
}
/**
* This new option is tracked in this PR, which is the most likely candidate at the time: https://github.com/w3c/csswg-drafts/pull/1805
* @public
*/
export declare type ScrollMode = 'always' | 'if-needed'
export {}
+1
View File
@@ -0,0 +1 @@
let e=e=>"object"==typeof e&&null!=e&&1===e.nodeType,t=(e,t)=>(!t||"hidden"!==e)&&("visible"!==e&&"clip"!==e),n=(e,n)=>{if(e.clientHeight<e.scrollHeight||e.clientWidth<e.scrollWidth){let l=getComputedStyle(e,null);return t(l.overflowY,n)||t(l.overflowX,n)||(e=>{let t=(e=>{if(!e.ownerDocument||!e.ownerDocument.defaultView)return null;try{return e.ownerDocument.defaultView.frameElement}catch(e){return null}})(e);return!!t&&(t.clientHeight<e.scrollHeight||t.clientWidth<e.scrollWidth)})(e)}return!1},l=(e,t,n,l,i,o,r,d)=>o<e&&r>t||o>e&&r<t?0:o<=e&&d<=n||r>=t&&d>=n?o-e-l:r>t&&d<n||o<e&&d>n?r-t+i:0,i=e=>{let t=e.parentElement;return null==t?e.getRootNode().host||null:t};var o=(t,o)=>{var r,d,h,f,u,s;if("undefined"==typeof document)return[];let{scrollMode:a,block:c,inline:g,boundary:m,skipOverflowHiddenElements:p}=o,w="function"==typeof m?m:e=>e!==m;if(!e(t))throw new TypeError("Invalid target");let W=document.scrollingElement||document.documentElement,H=[],b=t;for(;e(b)&&w(b);){if(b=i(b),b===W){H.push(b);break}null!=b&&b===document.body&&n(b)&&!n(document.documentElement)||null!=b&&n(b,p)&&H.push(b)}let v=null!=(d=null==(r=window.visualViewport)?void 0:r.width)?d:innerWidth,y=null!=(f=null==(h=window.visualViewport)?void 0:h.height)?f:innerHeight,E=null!=(u=window.scrollX)?u:pageXOffset,M=null!=(s=window.scrollY)?s:pageYOffset,{height:x,width:I,top:C,right:R,bottom:T,left:V}=t.getBoundingClientRect(),k="start"===c||"nearest"===c?C:"end"===c?T:C+x/2,B="center"===g?V+I/2:"end"===g?R:V,D=[];for(let e=0;e<H.length;e++){let t=H[e],{height:n,width:i,top:o,right:r,bottom:d,left:h}=t.getBoundingClientRect();if("if-needed"===a&&C>=0&&V>=0&&T<=y&&R<=v&&C>=o&&T<=d&&V>=h&&R<=r)return D;let f=getComputedStyle(t),u=parseInt(f.borderLeftWidth,10),s=parseInt(f.borderTopWidth,10),m=parseInt(f.borderRightWidth,10),p=parseInt(f.borderBottomWidth,10),w=0,b=0,O="offsetWidth"in t?t.offsetWidth-t.clientWidth-u-m:0,X="offsetHeight"in t?t.offsetHeight-t.clientHeight-s-p:0,Y="offsetWidth"in t?0===t.offsetWidth?0:i/t.offsetWidth:0,L="offsetHeight"in t?0===t.offsetHeight?0:n/t.offsetHeight:0;if(W===t)w="start"===c?k:"end"===c?k-y:"nearest"===c?l(M,M+y,y,s,p,M+k,M+k+x,x):k-y/2,b="start"===g?B:"center"===g?B-v/2:"end"===g?B-v:l(E,E+v,v,u,m,E+B,E+B+I,I),w=Math.max(0,w+M),b=Math.max(0,b+E);else{w="start"===c?k-o-s:"end"===c?k-d+p+X:"nearest"===c?l(o,d,n,s,p+X,k,k+x,x):k-(o+n/2)+X/2,b="start"===g?B-h-u:"center"===g?B-(h+i/2)+O/2:"end"===g?B-r+m+O:l(h,r,i,u,m+O,B,B+I,I);let{scrollLeft:e,scrollTop:f}=t;w=Math.max(0,Math.min(f+w/L,t.scrollHeight-n/L+X)),b=Math.max(0,Math.min(e+b/Y,t.scrollWidth-i/Y+O)),k+=f-w,B+=e-b}D.push({el:t,top:w,left:b})}return D};export{o as default};//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
+81
View File
@@ -0,0 +1,81 @@
{
"name": "compute-scroll-into-view",
"version": "2.0.4",
"description": "The engine that powers scroll-into-view-if-needed",
"keywords": [
"if-needed",
"scroll",
"scroll-into-view",
"scroll-into-view-if-needed",
"scrollIntoView",
"scrollIntoViewIfNeeded",
"scrollMode",
"typescript"
],
"homepage": "https://scroll-into-view.dev",
"repository": {
"type": "git",
"url": "git+https://github.com/scroll-into-view/compute-scroll-into-view.git"
},
"license": "MIT",
"author": "Cody Olsen",
"sideEffects": false,
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"source": "./src/index.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"typings": "./dist/index.d.ts",
"files": [
"dist",
"src"
],
"scripts": {
"prebuild": "npx rimraf 'dist'",
"build": "pkg build --strict",
"prepublishOnly": "npm run build",
"test": "npx cross-env JEST_PUPPETEER_CONFIG='jest-puppeteer.config.cjs' jest -c integration/jest.config.cjs",
"typecheck": "tsc"
},
"browserslist": [
"> 0.2% and supports es6-module and supports es6-module-dynamic-import and not dead and not IE 11",
"maintained node versions"
],
"prettier": {
"semi": false,
"singleQuote": true
},
"devDependencies": {
"@sanity/pkg-utils": "^2.1.1",
"@sanity/semantic-release-preset": "^3.0.0",
"@types/expect-puppeteer": "^5.0.2",
"@types/jest": "^29.2.5",
"@types/jest-environment-puppeteer": "^5.0.3",
"@types/puppeteer": "^7.0.4",
"cross-env": "^7.0.3",
"jest": "^29.3.1",
"jest-junit": "^15.0.0",
"jest-puppeteer": "^6.2.0",
"prettier": "^2.8.2",
"prettier-plugin-packagejson": "^2.3.0",
"puppeteer": "^19.4.1",
"rimraf": "^3.0.2",
"serve": "^14.1.2",
"typescript": "^4.9.4"
},
"bundlesize": [
{
"path": "./dist/index.js",
"maxSize": "3 kB",
"compression": "none"
}
]
}
+546
View File
@@ -0,0 +1,546 @@
// Compute what scrolling needs to be done on required scrolling boxes for target to be in view
// The type names here are named after the spec to make it easier to find more information around what they mean:
// To reduce churn and reduce things that need be maintained things from the official TS DOM library is used here
// https://drafts.csswg.org/cssom-view/
// For a definition on what is "block flow direction" exactly, check this: https://drafts.csswg.org/css-writing-modes-4/#block-flow-direction
/**
* This new option is tracked in this PR, which is the most likely candidate at the time: https://github.com/w3c/csswg-drafts/pull/1805
* @public
*/
export type ScrollMode = 'always' | 'if-needed'
/** @public */
export interface Options {
/**
* Control the logical scroll position on the y-axis. The spec states that the `block` direction is related to the [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode), but this is not implemented yet in this library.
* This means that `block: 'start'` aligns to the top edge and `block: 'end'` to the bottom.
* @defaultValue 'center'
*/
block?: ScrollLogicalPosition
/**
* Like `block` this is affected by the [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode). In left-to-right pages `inline: 'start'` will align to the left edge. In right-to-left it should be flipped. This will be supported in a future release.
* @defaultValue 'nearest'
*/
inline?: ScrollLogicalPosition
/**
* This is a proposed addition to the spec that you can track here: https://github.com/w3c/csswg-drafts/pull/5677
*
* This library will be updated to reflect any changes to the spec and will provide a migration path.
* To be backwards compatible with `Element.scrollIntoViewIfNeeded` if something is not 100% visible it will count as "needs scrolling". If you need a different visibility ratio your best option would be to implement an [Intersection Observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
* @defaultValue 'always'
*/
scrollMode?: ScrollMode
/**
* By default there is no boundary. All the parent elements of your target is checked until it reaches the viewport ([`document.scrollingElement`](https://developer.mozilla.org/en-US/docs/Web/API/document/scrollingElement)) when calculating layout and what to scroll.
* By passing a boundary you can short-circuit this loop depending on your needs:
*
* - Prevent the browser window from scrolling.
* - Scroll elements into view in a list, without scrolling container elements.
*
* You can also pass a function to do more dynamic checks to override the scroll scoping:
*
* ```js
* let actions = compute(target, {
* boundary: (parent) => {
* // By default `overflow: hidden` elements are allowed, only `overflow: visible | clip` is skipped as
* // this is required by the CSSOM spec
* if (getComputedStyle(parent)['overflow'] === 'hidden') {
* return false
* }
* return true
* },
* })
* ```
* @defaultValue null
*/
boundary?: Element | ((parent: Element) => boolean) | null
/**
* New option that skips auto-scrolling all nodes with overflow: hidden set
* See FF implementation: https://hg.mozilla.org/integration/fx-team/rev/c48c3ec05012#l7.18
* @defaultValue false
* @public
*/
skipOverflowHiddenElements?: boolean
}
/** @public */
export interface ScrollAction {
el: Element
top: number
left: number
}
// @TODO better shadowdom test, 11 = document fragment
let isElement = (el: any): el is Element =>
typeof el === 'object' && el != null && el.nodeType === 1
let canOverflow = (
overflow: string | null,
skipOverflowHiddenElements?: boolean
) => {
if (skipOverflowHiddenElements && overflow === 'hidden') {
return false
}
return overflow !== 'visible' && overflow !== 'clip'
}
let getFrameElement = (el: Element) => {
if (!el.ownerDocument || !el.ownerDocument.defaultView) {
return null
}
try {
return el.ownerDocument.defaultView.frameElement
} catch (e) {
return null
}
}
let isHiddenByFrame = (el: Element): boolean => {
let frame = getFrameElement(el)
if (!frame) {
return false
}
return (
frame.clientHeight < el.scrollHeight || frame.clientWidth < el.scrollWidth
)
}
let isScrollable = (el: Element, skipOverflowHiddenElements?: boolean) => {
if (el.clientHeight < el.scrollHeight || el.clientWidth < el.scrollWidth) {
let style = getComputedStyle(el, null)
return (
canOverflow(style.overflowY, skipOverflowHiddenElements) ||
canOverflow(style.overflowX, skipOverflowHiddenElements) ||
isHiddenByFrame(el)
)
}
return false
}
/**
* Find out which edge to align against when logical scroll position is "nearest"
* Interesting fact: "nearest" works similarily to "if-needed", if the element is fully visible it will not scroll it
*
* Legends:
* ┌────────┐ ┏ ━ ━ ━ ┓
* │ target │ frame
* └────────┘ ┗ ━ ━ ━ ┛
*/
let alignNearest = (
scrollingEdgeStart: number,
scrollingEdgeEnd: number,
scrollingSize: number,
scrollingBorderStart: number,
scrollingBorderEnd: number,
elementEdgeStart: number,
elementEdgeEnd: number,
elementSize: number
) => {
/**
* If element edge A and element edge B are both outside scrolling box edge A and scrolling box edge B
*
* ┌──┐
* ┏━│━━│━┓
* │ │
* ┃ │ │ ┃ do nothing
* │ │
* ┗━│━━│━┛
* └──┘
*
* If element edge C and element edge D are both outside scrolling box edge C and scrolling box edge D
*
* ┏ ━ ━ ━ ━ ┓
* ┌───────────┐
* │┃ ┃│ do nothing
* └───────────┘
* ┗ ━ ━ ━ ━ ┛
*/
if (
(elementEdgeStart < scrollingEdgeStart &&
elementEdgeEnd > scrollingEdgeEnd) ||
(elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd)
) {
return 0
}
/**
* If element edge A is outside scrolling box edge A and element height is less than scrolling box height
*
* ┌──┐
* ┏━│━━│━┓ ┏━┌━━┐━┓
* └──┘ │ │
* from ┃ ┃ to ┃ └──┘ ┃
*
* ┗━ ━━ ━┛ ┗━ ━━ ━┛
*
* If element edge B is outside scrolling box edge B and element height is greater than scrolling box height
*
* ┏━ ━━ ━┓ ┏━┌━━┐━┓
* │ │
* from ┃ ┌──┐ ┃ to ┃ │ │ ┃
* │ │ │ │
* ┗━│━━│━┛ ┗━│━━│━┛
* │ │ └──┘
* │ │
* └──┘
*
* If element edge C is outside scrolling box edge C and element width is less than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───┐ ┌───┐
* │ ┃ │ ┃ ┃ │ ┃
* └───┘ └───┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*
* If element edge D is outside scrolling box edge D and element width is greater than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───────────┐ ┌───────────┐
* ┃ │ ┃ │ ┃ ┃ │
* └───────────┘ └───────────┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*/
if (
(elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize) ||
(elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize)
) {
return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart
}
/**
* If element edge B is outside scrolling box edge B and element height is less than scrolling box height
*
* ┏━ ━━ ━┓ ┏━ ━━ ━┓
*
* from ┃ ┃ to ┃ ┌──┐ ┃
* ┌──┐ │ │
* ┗━│━━│━┛ ┗━└━━┘━┛
* └──┘
*
* If element edge A is outside scrolling box edge A and element height is greater than scrolling box height
*
* ┌──┐
* │ │
* │ │ ┌──┐
* ┏━│━━│━┓ ┏━│━━│━┓
* │ │ │ │
* from ┃ └──┘ ┃ to ┃ │ │ ┃
* │ │
* ┗━ ━━ ━┛ ┗━└━━┘━┛
*
* If element edge C is outside scrolling box edge C and element width is greater than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───────────┐ ┌───────────┐
* │ ┃ │ ┃ │ ┃ ┃
* └───────────┘ └───────────┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*
* If element edge D is outside scrolling box edge D and element width is less than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───┐ ┌───┐
* ┃ │ ┃ │ ┃ │ ┃
* └───┘ └───┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*
*/
if (
(elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize) ||
(elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize)
) {
return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd
}
return 0
}
let getParentElement = (element: Node): Element | null => {
let parent = element.parentElement
if (parent == null) {
return (element.getRootNode() as ShadowRoot).host || null
}
return parent
}
/** @public */
export default (target: Element, options: Options): ScrollAction[] => {
if (typeof document === 'undefined') {
// If there's no DOM we assume it's not in a browser environment
return []
}
let { scrollMode, block, inline, boundary, skipOverflowHiddenElements } =
options
// Allow using a callback to check the boundary
// The default behavior is to check if the current target matches the boundary element or not
// If undefined it'll check that target is never undefined (can happen as we recurse up the tree)
let checkBoundary =
typeof boundary === 'function' ? boundary : (node: any) => node !== boundary
if (!isElement(target)) {
throw new TypeError('Invalid target')
}
// Used to handle the top most element that can be scrolled
let scrollingElement = document.scrollingElement || document.documentElement
// Collect all the scrolling boxes, as defined in the spec: https://drafts.csswg.org/cssom-view/#scrolling-box
let frames: Element[] = []
let cursor: Element | null = target
while (isElement(cursor) && checkBoundary(cursor)) {
// Move cursor to parent
cursor = getParentElement(cursor)
// Stop when we reach the viewport
if (cursor === scrollingElement) {
frames.push(cursor)
break
}
// Skip document.body if it's not the scrollingElement and documentElement isn't independently scrollable
if (
cursor != null &&
cursor === document.body &&
isScrollable(cursor) &&
!isScrollable(document.documentElement)
) {
continue
}
// Now we check if the element is scrollable, this code only runs if the loop haven't already hit the viewport or a custom boundary
if (cursor != null && isScrollable(cursor, skipOverflowHiddenElements)) {
frames.push(cursor)
}
}
// Support pinch-zooming properly, making sure elements scroll into the visual viewport
// Browsers that don't support visualViewport will report the layout viewport dimensions on document.documentElement.clientWidth/Height
// and viewport dimensions on window.innerWidth/Height
// https://www.quirksmode.org/mobile/viewports2.html
// https://bokand.github.io/viewport/index.html
let viewportWidth = window.visualViewport?.width ?? innerWidth
let viewportHeight = window.visualViewport?.height ?? innerHeight
// Newer browsers supports scroll[X|Y], page[X|Y]Offset is
let viewportX = window.scrollX ?? pageXOffset
let viewportY = window.scrollY ?? pageYOffset
let {
height: targetHeight,
width: targetWidth,
top: targetTop,
right: targetRight,
bottom: targetBottom,
left: targetLeft,
} = target.getBoundingClientRect()
// These values mutate as we loop through and generate scroll coordinates
let targetBlock: number =
block === 'start' || block === 'nearest'
? targetTop
: block === 'end'
? targetBottom
: targetTop + targetHeight / 2 // block === 'center
let targetInline: number =
inline === 'center'
? targetLeft + targetWidth / 2
: inline === 'end'
? targetRight
: targetLeft // inline === 'start || inline === 'nearest
// Collect new scroll positions
let computations: ScrollAction[] = []
// In chrome there's no longer a difference between caching the `frames.length` to a var or not, so we don't in this case (size > speed anyways)
for (let index = 0; index < frames.length; index++) {
let frame = frames[index]
// @TODO add a shouldScroll hook here that allows userland code to take control
let { height, width, top, right, bottom, left } =
frame.getBoundingClientRect()
// If the element is already visible we can end it here
// @TODO targetBlock and targetInline should be taken into account to be compliant with https://github.com/w3c/csswg-drafts/pull/1805/files#diff-3c17f0e43c20f8ecf89419d49e7ef5e0R1333
if (
scrollMode === 'if-needed' &&
targetTop >= 0 &&
targetLeft >= 0 &&
targetBottom <= viewportHeight &&
targetRight <= viewportWidth &&
targetTop >= top &&
targetBottom <= bottom &&
targetLeft >= left &&
targetRight <= right
) {
// Break the loop and return the computations for things that are not fully visible
return computations
}
let frameStyle = getComputedStyle(frame)
let borderLeft = parseInt(frameStyle.borderLeftWidth as string, 10)
let borderTop = parseInt(frameStyle.borderTopWidth as string, 10)
let borderRight = parseInt(frameStyle.borderRightWidth as string, 10)
let borderBottom = parseInt(frameStyle.borderBottomWidth as string, 10)
let blockScroll: number = 0
let inlineScroll: number = 0
// The property existance checks for offfset[Width|Height] is because only HTMLElement objects have them, but any Element might pass by here
// @TODO find out if the "as HTMLElement" overrides can be dropped
let scrollbarWidth =
'offsetWidth' in frame
? (frame as HTMLElement).offsetWidth -
(frame as HTMLElement).clientWidth -
borderLeft -
borderRight
: 0
let scrollbarHeight =
'offsetHeight' in frame
? (frame as HTMLElement).offsetHeight -
(frame as HTMLElement).clientHeight -
borderTop -
borderBottom
: 0
let scaleX =
'offsetWidth' in frame
? (frame as HTMLElement).offsetWidth === 0
? 0
: width / (frame as HTMLElement).offsetWidth
: 0
let scaleY =
'offsetHeight' in frame
? (frame as HTMLElement).offsetHeight === 0
? 0
: height / (frame as HTMLElement).offsetHeight
: 0
if (scrollingElement === frame) {
// Handle viewport logic (document.documentElement or document.body)
if (block === 'start') {
blockScroll = targetBlock
} else if (block === 'end') {
blockScroll = targetBlock - viewportHeight
} else if (block === 'nearest') {
blockScroll = alignNearest(
viewportY,
viewportY + viewportHeight,
viewportHeight,
borderTop,
borderBottom,
viewportY + targetBlock,
viewportY + targetBlock + targetHeight,
targetHeight
)
} else {
// block === 'center' is the default
blockScroll = targetBlock - viewportHeight / 2
}
if (inline === 'start') {
inlineScroll = targetInline
} else if (inline === 'center') {
inlineScroll = targetInline - viewportWidth / 2
} else if (inline === 'end') {
inlineScroll = targetInline - viewportWidth
} else {
// inline === 'nearest' is the default
inlineScroll = alignNearest(
viewportX,
viewportX + viewportWidth,
viewportWidth,
borderLeft,
borderRight,
viewportX + targetInline,
viewportX + targetInline + targetWidth,
targetWidth
)
}
// Apply scroll position offsets and ensure they are within bounds
// @TODO add more test cases to cover this 100%
blockScroll = Math.max(0, blockScroll + viewportY)
inlineScroll = Math.max(0, inlineScroll + viewportX)
} else {
// Handle each scrolling frame that might exist between the target and the viewport
if (block === 'start') {
blockScroll = targetBlock - top - borderTop
} else if (block === 'end') {
blockScroll = targetBlock - bottom + borderBottom + scrollbarHeight
} else if (block === 'nearest') {
blockScroll = alignNearest(
top,
bottom,
height,
borderTop,
borderBottom + scrollbarHeight,
targetBlock,
targetBlock + targetHeight,
targetHeight
)
} else {
// block === 'center' is the default
blockScroll = targetBlock - (top + height / 2) + scrollbarHeight / 2
}
if (inline === 'start') {
inlineScroll = targetInline - left - borderLeft
} else if (inline === 'center') {
inlineScroll = targetInline - (left + width / 2) + scrollbarWidth / 2
} else if (inline === 'end') {
inlineScroll = targetInline - right + borderRight + scrollbarWidth
} else {
// inline === 'nearest' is the default
inlineScroll = alignNearest(
left,
right,
width,
borderLeft,
borderRight + scrollbarWidth,
targetInline,
targetInline + targetWidth,
targetWidth
)
}
let { scrollLeft, scrollTop } = frame
// Ensure scroll coordinates are not out of bounds while applying scroll offsets
blockScroll = Math.max(
0,
Math.min(
scrollTop + blockScroll / scaleY,
frame.scrollHeight - height / scaleY + scrollbarHeight
)
)
inlineScroll = Math.max(
0,
Math.min(
scrollLeft + inlineScroll / scaleX,
frame.scrollWidth - width / scaleX + scrollbarWidth
)
)
// Cache the offset so that parent frames can scroll this into view correctly
targetBlock += scrollTop - blockScroll
targetInline += scrollLeft - inlineScroll
}
computations.push({ el: frame, top: blockScroll, left: inlineScroll })
}
return computations
}