Bump @justinribeiro/lite-youtube from 0.9.0 to 0.9.1 in /build/javascript (#273)

* Commit updated Javascript packages

* Bump preact from 10.5.4 to 10.5.5 in /build/javascript (#265)

* Trying a new github workflow to install javascript packages

* Bump tailwindcss from 1.9.2 to 1.9.4 in /build/javascript (#266)

Bumps [tailwindcss](https://github.com/tailwindlabs/tailwindcss) from 1.9.2 to 1.9.4.
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/master/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/compare/v1.9.2...v1.9.4)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Commit updated Javascript packages

* Bump preact from 10.5.4 to 10.5.5 in /build/javascript

Bumps [preact](https://github.com/preactjs/preact) from 10.5.4 to 10.5.5.
- [Release notes](https://github.com/preactjs/preact/releases)
- [Commits](https://github.com/preactjs/preact/compare/10.5.4...10.5.5)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Gabe Kangas <gabek@real-ity.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Owncast <owncast@owncast.online>

* Bump @justinribeiro/lite-youtube in /build/javascript

Bumps [@justinribeiro/lite-youtube](https://github.com/justinribeiro/lite-youtube) from 0.9.0 to 0.9.1.
- [Release notes](https://github.com/justinribeiro/lite-youtube/releases)
- [Commits](https://github.com/justinribeiro/lite-youtube/commits)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Owncast <owncast@owncast.online>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Gabe Kangas <gabek@real-ity.com>
This commit is contained in:
dependabot[bot]
2020-10-20 15:15:56 -07:00
committed by GitHub
parent fb4a822cd8
commit dab7914eab
6133 changed files with 546543 additions and 1108 deletions

View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2019 Federico Zivolo
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.

362
build/javascript/node_modules/@popperjs/core/README.md generated vendored Normal file
View File

@@ -0,0 +1,362 @@
<!-- <HEADER> // IGNORE IT -->
<p align="center">
<img src="https://rawcdn.githack.com/popperjs/popper-core/8805a5d7599e14619c9e7ac19a3713285d8e5d7f/docs/src/images/popper-logo-outlined.svg" alt="Popper" height="300px"/>
</p>
<div align="center">
<h1>Tooltip & Popover Positioning Engine</h1>
</div>
<p align="center">
<a href="https://www.npmjs.com/package/@popperjs/core">
<img src="https://img.shields.io/npm/v/@popperjs/core?style=for-the-badge" alt="npm version" />
</a>
<a href="https://www.npmjs.com/package/@popperjs/core">
<img src="https://img.shields.io/endpoint?style=for-the-badge&url=https://runkit.io/fezvrasta/combined-npm-downloads/1.0.0?packages=popper.js,@popperjs/core" alt="npm downloads per month (popper.js + @popperjs/core)" />
</a>
<a href="https://rollingversions.com/popperjs/popper-core">
<img src="https://img.shields.io/badge/Rolling%20Versions-Enabled-brightgreen?style=for-the-badge" alt="Rolling Versions" />
</a>
</p>
<br />
<!-- </HEADER> // NOW BEGINS THE README -->
**Positioning tooltips and popovers is difficult. Popper is here to help!**
Given an element, such as a button, and a tooltip element describing it, Popper
will automatically put the tooltip in the right place near the button.
It will position _any_ UI element that "pops out" from the flow of your document
and floats near a target element. The most common example is a tooltip, but it
also includes popovers, drop-downs, and more. All of these can be generically
described as a "popper" element.
## Demo
[![Popper visualized](https://i.imgur.com/F7qWsmV.jpg)](https://popper.js.org)
## Docs
- [v2.x (latest)](https://popper.js.org/docs/v2/)
- [v1.x](https://popper.js.org/docs/v1/)
We've created a
[Migration Guide](https://popper.js.org/docs/v2/migration-guide/) to help you
migrate from Popper 1 to Popper 2.
To contribute to the Popper website and documentation, please visit the [dedicated repository](https://github.com/popperjs/website).
## Why not use pure CSS?
CSS tooltips have accessibility and usability problems:
- **Clipping and overflow issues**: CSS tooltips will not be prevented from
overflowing clipping boundaries, such as the viewport. The tooltip gets
partially cut off or overflows if it's near the edge since there is no dynamic
positioning logic. When using Popper, your tooltip will always be positioned
in the right place.
- **No flipping**: CSS tooltips will not flip to a different placement to fit
better in view if necessary. Popper automatically flips the tooltip to make it
fit in view as best as possible for the user.
- **Using HTML**: Popovers containing interactive HTML are difficult or not
possible to create without UX issues using pure CSS. Popper positions any HTML
element no pseudo-elements are used.
- **No virtual positioning**: CSS tooltips cannot follow the mouse cursor or be
used as a context menu. Popper allows you to position your tooltip relative to
any coordinates you desire.
- **Lack of extensibility**: CSS tooltips cannot be easily extended to fit any
arbitrary use case you may need to adjust for. Popper is built with
extensibility in mind.
## Why Popper?
With the CSS drawbacks out of the way, we now move on to Popper in the
JavaScript space itself.
Naive JavaScript tooltip implementations usually have the following problems:
- **Scrolling containers**: They don't ensure the tooltip stays with the
reference element while scrolling when inside any number of scrolling
containers.
- **DOM context**: They often require the tooltip move outside of its original
DOM context because they don't handle `offsetParent` contexts.
- **Configurability**: They often lack advanced configurability to suit any
possible use case.
- **Size**: They are usually relatively large in size, or require an ancient
jQuery dependency.
- **Performance**: They often have runtime performance issues and update the
tooltip position too slowly.
**Popper solves all of these key problems in an elegant, performant manner.** It
is a lightweight ~3 kB library that aims to provide a reliable and extensible
positioning engine you can use to ensure all your popper elements are positioned
in the right place.
When you start writing your own popper implementation, you'll quickly run into
all of the problems mentioned above. These widgets are incredibly common in our
UIs; we've done the hard work figuring this out so you don't need to spend hours
fixing and handling numerous edge cases that we already ran into while building
the library!
Popper is used in popular libraries like Bootstrap, Foundation, Material UI, and
more. It's likely you've already used popper elements on the web positioned by
Popper at some point in the past few years.
Since we write UIs using powerful abstraction libraries such as React or Angular
nowadays, you'll also be glad to know Popper can fully integrate with them and
be a good citizen together with your other components. Check out `react-popper`
for the official Popper wrapper for React.
## Installation
### 1. Package Manager
```bash
# With npm
npm i @popperjs/core
# With Yarn
yarn add @popperjs/core
```
### 2. CDN
```html
<!-- Development version -->
<script src="https://unpkg.com/@popperjs/core@2/dist/umd/popper.js"></script>
<!-- Production version -->
<script src="https://unpkg.com/@popperjs/core@2"></script>
```
### 3. Direct Download?
Managing dependencies by "directly downloading" them and placing them into your
source code is not recommended for a variety of reasons, including missing out
on feat/fix updates easily. Please use a versioning management system like a CDN
or npm/Yarn.
## Usage
The most straightforward way to get started is to import Popper from the `unpkg`
CDN, which includes all of its features. You can call the `Popper.createPopper`
constructor to create new popper instances.
Here is a complete example:
```html
<!DOCTYPE html>
<title>Popper example</title>
<style>
#tooltip {
background-color: #333;
color: white;
padding: 5px 10px;
border-radius: 4px;
font-size: 13px;
}
</style>
<button id="button" aria-describedby="tooltip">I'm a button</button>
<div id="tooltip" role="tooltip">I'm a tooltip</div>
<script src="https://unpkg.com/@popperjs/core@^2.0.0"></script>
<script>
const button = document.querySelector('#button');
const tooltip = document.querySelector('#tooltip');
// Pass the button, the tooltip, and some options, and Popper will do the
// magic positioning for you:
Popper.createPopper(button, tooltip, {
placement: 'right',
});
</script>
```
Visit the [tutorial](https://popper.js.org/docs/v2/tutorial/) for an example of
how to build your own tooltip from scratch using Popper.
### Module bundlers
You can import the `createPopper` constructor from the fully-featured file:
```js
import { createPopper } from '@popperjs/core';
const button = document.querySelector('#button');
const tooltip = document.querySelector('#tooltip');
// Pass the button, the tooltip, and some options, and Popper will do the
// magic positioning for you:
createPopper(button, tooltip, {
placement: 'right',
});
```
All the modifiers listed in the docs menu will be enabled and "just work", so
you don't need to think about setting Popper up. The size of Popper including
all of its features is about 5 kB minzipped, but it may grow a bit in the
future.
#### Popper Lite (tree-shaking)
If bundle size is important, you'll want to take advantage of tree-shaking. The
library is built in a modular way to allow to import only the parts you really
need.
```js
import { createPopperLite as createPopper } from "@popperjs/core";
```
The Lite version includes the most necessary modifiers that will compute the
offsets of the popper, compute and add the positioning styles, and add event
listeners. This is close in bundle size to pure CSS tooltip libraries, and
behaves somewhat similarly.
However, this does not include the features that makes Popper truly useful.
The two most useful modifiers not included in Lite are `preventOverflow` and
`flip`:
```js
import { createPopperLite as createPopper, preventOverflow, flip } from "@popperjs/core";
const button = document.querySelector('#button');
const tooltip = document.querySelector('#tooltip');
createPopper(button, tooltip, {
modifiers: [preventOverflow, flip],
});
```
As you make more poppers, you may be finding yourself needing other modifiers
provided by the library.
See [tree-shaking](https://popper.js.org/docs/v2/tree-shaking/) for more
information.
## Distribution targets
Popper is distributed in 3 different versions, in 3 different file formats.
The 3 file formats are:
- `esm` (works with `import` syntax — **recommended**)
- `umd` (works with `<script>` tags or RequireJS)
- `cjs` (works with `require()` syntax)
There are two different `esm` builds, one for bundler consumers (e.g. webpack,
Rollup, etc..), which is located under `/lib`, and one for browsers with native
support for ES Modules, under `/dist/esm`. The only difference within the two,
is that the browser-compatible version doesn't make use of
`process.env.NODE_ENV` to run development checks.
The 3 versions are:
- `popper`: includes all the modifiers (features) in one file (**default**);
- `popper-lite`: includes only the minimum amount of modifiers to provide the
basic functionality;
- `popper-base`: doesn't include any modifier, you must import them separately;
Below you can find the size of each version, minified and compressed with the
[Brotli compression algorithm](https://medium.com/groww-engineering/enable-brotli-compression-in-webpack-with-fallback-to-gzip-397a57cf9fc6):
<!-- Don't change the labels to use hyphens, it breaks, even when encoded -->
![](https://badge-size.now.sh/https://unpkg.com/@popperjs/core/dist/umd/popper.min.js?compression=brotli&label=popper)
![](https://badge-size.now.sh/https://unpkg.com/@popperjs/core/dist/umd/popper-lite.min.js?compression=brotli&label=popper%20lite)
![](https://badge-size.now.sh/https://unpkg.com/@popperjs/core/dist/umd/popper-base.min.js?compression=brotli&label=popper%20base)
## Hacking the library
If you want to play with the library, implement new features, fix a bug you
found, or simply experiment with it, this section is for you!
First of all, make sure to have
[Yarn installed](https://yarnpkg.com/lang/en/docs/install).
Install the development dependencies:
```bash
yarn install
```
And run the development environment:
```bash
yarn dev
```
Then, simply open one the development server web page:
```bash
# macOS and Linux
open localhost:5000
# Windows
start localhost:5000
```
From there, you can open any of the examples (`.html` files) to fiddle with
them.
Now any change you will made to the source code, will be automatically compiled,
you just need to refresh the page.
If the page is not working properly, try to go in _"Developer Tools >
Application > Clear storage"_ and click on "_Clear site data_".
To run the examples you need a browser with
[JavaScript modules via script tag support](https://caniuse.com/#feat=es6-module).
## Test Suite
Popper is currently tested with unit tests, and functional tests. Both of them
are run by Jest.
### Unit Tests
The unit tests use JSDOM to provide a primitive document object API, they are
used to ensure the utility functions behave as expected in isolation.
### Functional Tests
The functional tests run with Puppeteer, to take advantage of a complete browser
environment. They are currently running on Chromium, and Firefox.
You can run them with `yarn test:functional`. Set the `PUPPETEER_BROWSER`
environment variable to `firefox` to run them on the Mozilla browser.
The assertions are written in form of image snapshots, so that it's easy to
assert for the correct Popper behavior without having to write a lot of offsets
comparisons manually.
You can mark a `*.test.js` file to run in the Puppeteer environment by
prepending a `@jest-environment puppeteer` JSDoc comment to the interested file.
Here's an example of a basic functional test:
```js
/**
* @jest-environment puppeteer
* @flow
*/
import { screenshot } from '../utils/puppeteer.js';
it('should position the popper on the right', async () => {
const page = await browser.newPage();
await page.goto(`${TEST_URL}/basic.html`);
expect(await screenshot(page)).toMatchImageSnapshot();
});
```
You can find the complete
[`jest-puppeteer` documentation here](https://github.com/smooth-code/jest-puppeteer#api),
and the
[`jest-image-snapshot` documentation here](https://github.com/americanexpress/jest-image-snapshot#%EF%B8%8F-api).
## License
MIT

View File

@@ -0,0 +1 @@
export * from './lib';

View File

@@ -0,0 +1,9 @@
import { OptionsGeneric, Modifier, Instance, VirtualElement } from "./types";
import detectOverflow from "./utils/detectOverflow";
declare type PopperGeneratorArgs = {
defaultModifiers?: Array<Modifier<any, any>>;
defaultOptions?: Partial<OptionsGeneric<any>>;
};
export declare function popperGenerator(generatorOptions?: PopperGeneratorArgs): <TModifier extends Partial<Modifier<any, any>>>(reference: Element | VirtualElement, popper: HTMLElement, options?: Partial<OptionsGeneric<TModifier>>) => Instance;
export declare const createPopper: <TModifier extends Partial<Modifier<any, any>>>(reference: Element | VirtualElement, popper: HTMLElement, options?: Partial<OptionsGeneric<TModifier>>) => Instance;
export { detectOverflow };

View File

@@ -0,0 +1,258 @@
import getCompositeRect from "./dom-utils/getCompositeRect.js";
import getLayoutRect from "./dom-utils/getLayoutRect.js";
import listScrollParents from "./dom-utils/listScrollParents.js";
import getOffsetParent from "./dom-utils/getOffsetParent.js";
import getComputedStyle from "./dom-utils/getComputedStyle.js";
import orderModifiers from "./utils/orderModifiers.js";
import debounce from "./utils/debounce.js";
import validateModifiers from "./utils/validateModifiers.js";
import uniqueBy from "./utils/uniqueBy.js";
import getBasePlacement from "./utils/getBasePlacement.js";
import mergeByName from "./utils/mergeByName.js";
import detectOverflow from "./utils/detectOverflow.js";
import { isElement } from "./dom-utils/instanceOf.js";
import { auto } from "./enums.js";
var INVALID_ELEMENT_ERROR = 'Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.';
var INFINITE_LOOP_ERROR = 'Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.';
var DEFAULT_OPTIONS = {
placement: 'bottom',
modifiers: [],
strategy: 'absolute'
};
function areValidElements() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return !args.some(function (element) {
return !(element && typeof element.getBoundingClientRect === 'function');
});
}
export function popperGenerator(generatorOptions) {
if (generatorOptions === void 0) {
generatorOptions = {};
}
var _generatorOptions = generatorOptions,
_generatorOptions$def = _generatorOptions.defaultModifiers,
defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
_generatorOptions$def2 = _generatorOptions.defaultOptions,
defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
return function createPopper(reference, popper, options) {
if (options === void 0) {
options = defaultOptions;
}
var state = {
placement: 'bottom',
orderedModifiers: [],
options: Object.assign(Object.assign({}, DEFAULT_OPTIONS), defaultOptions),
modifiersData: {},
elements: {
reference: reference,
popper: popper
},
attributes: {},
styles: {}
};
var effectCleanupFns = [];
var isDestroyed = false;
var instance = {
state: state,
setOptions: function setOptions(options) {
cleanupModifierEffects();
state.options = Object.assign(Object.assign(Object.assign({}, defaultOptions), state.options), options);
state.scrollParents = {
reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
popper: listScrollParents(popper)
}; // Orders the modifiers based on their dependencies and `phase`
// properties
var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers
state.orderedModifiers = orderedModifiers.filter(function (m) {
return m.enabled;
}); // Validate the provided modifiers so that the consumer will get warned
// if one of the modifiers is invalid for any reason
if (process.env.NODE_ENV !== "production") {
var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function (_ref) {
var name = _ref.name;
return name;
});
validateModifiers(modifiers);
if (getBasePlacement(state.options.placement) === auto) {
var flipModifier = state.orderedModifiers.find(function (_ref2) {
var name = _ref2.name;
return name === 'flip';
});
if (!flipModifier) {
console.error(['Popper: "auto" placements require the "flip" modifier be', 'present and enabled to work.'].join(' '));
}
}
var _getComputedStyle = getComputedStyle(popper),
marginTop = _getComputedStyle.marginTop,
marginRight = _getComputedStyle.marginRight,
marginBottom = _getComputedStyle.marginBottom,
marginLeft = _getComputedStyle.marginLeft; // We no longer take into account `margins` on the popper, and it can
// cause bugs with positioning, so we'll warn the consumer
if ([marginTop, marginRight, marginBottom, marginLeft].some(function (margin) {
return parseFloat(margin);
})) {
console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', 'between the popper and its reference element or boundary.', 'To replicate margin, use the `offset` modifier, as well as', 'the `padding` option in the `preventOverflow` and `flip`', 'modifiers.'].join(' '));
}
}
runModifierEffects();
return instance.update();
},
// Sync update it will always be executed, even if not necessary. This
// is useful for low frequency updates where sync behavior simplifies the
// logic.
// For high frequency updates (e.g. `resize` and `scroll` events), always
// prefer the async Popper#update method
forceUpdate: function forceUpdate() {
if (isDestroyed) {
return;
}
var _state$elements = state.elements,
reference = _state$elements.reference,
popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
// anymore
if (!areValidElements(reference, popper)) {
if (process.env.NODE_ENV !== "production") {
console.error(INVALID_ELEMENT_ERROR);
}
return;
} // Store the reference and popper rects to be read by modifiers
state.rects = {
reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
popper: getLayoutRect(popper)
}; // Modifiers have the ability to reset the current update cycle. The
// most common use case for this is the `flip` modifier changing the
// placement, which then needs to re-run all the modifiers, because the
// logic was previously ran for the previous placement and is therefore
// stale/incorrect
state.reset = false;
state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
// is filled with the initial data specified by the modifier. This means
// it doesn't persist and is fresh on each update.
// To ensure persistent data, use `${name}#persistent`
state.orderedModifiers.forEach(function (modifier) {
return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
});
var __debug_loops__ = 0;
for (var index = 0; index < state.orderedModifiers.length; index++) {
if (process.env.NODE_ENV !== "production") {
__debug_loops__ += 1;
if (__debug_loops__ > 100) {
console.error(INFINITE_LOOP_ERROR);
break;
}
}
if (state.reset === true) {
state.reset = false;
index = -1;
continue;
}
var _state$orderedModifie = state.orderedModifiers[index],
fn = _state$orderedModifie.fn,
_state$orderedModifie2 = _state$orderedModifie.options,
_options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
name = _state$orderedModifie.name;
if (typeof fn === 'function') {
state = fn({
state: state,
options: _options,
name: name,
instance: instance
}) || state;
}
}
},
// Async and optimistically optimized update it will not be executed if
// not necessary (debounced to run at most once-per-tick)
update: debounce(function () {
return new Promise(function (resolve) {
instance.forceUpdate();
resolve(state);
});
}),
destroy: function destroy() {
cleanupModifierEffects();
isDestroyed = true;
}
};
if (!areValidElements(reference, popper)) {
if (process.env.NODE_ENV !== "production") {
console.error(INVALID_ELEMENT_ERROR);
}
return instance;
}
instance.setOptions(options).then(function (state) {
if (!isDestroyed && options.onFirstUpdate) {
options.onFirstUpdate(state);
}
}); // Modifiers have the ability to execute arbitrary code before the first
// update cycle runs. They will be executed in the same order as the update
// cycle. This is useful when a modifier adds some persistent data that
// other modifiers need to use, but the modifier is run after the dependent
// one.
function runModifierEffects() {
state.orderedModifiers.forEach(function (_ref3) {
var name = _ref3.name,
_ref3$options = _ref3.options,
options = _ref3$options === void 0 ? {} : _ref3$options,
effect = _ref3.effect;
if (typeof effect === 'function') {
var cleanupFn = effect({
state: state,
name: name,
instance: instance,
options: options
});
var noopFn = function noopFn() {};
effectCleanupFns.push(cleanupFn || noopFn);
}
});
}
function cleanupModifierEffects() {
effectCleanupFns.forEach(function (fn) {
return fn();
});
effectCleanupFns = [];
}
return instance;
};
}
export var createPopper = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules
export { detectOverflow };

View File

@@ -0,0 +1,291 @@
// @flow
import type {
State,
OptionsGeneric,
Modifier,
Instance,
VirtualElement,
} from './types';
import getCompositeRect from './dom-utils/getCompositeRect';
import getLayoutRect from './dom-utils/getLayoutRect';
import listScrollParents from './dom-utils/listScrollParents';
import getOffsetParent from './dom-utils/getOffsetParent';
import getComputedStyle from './dom-utils/getComputedStyle';
import orderModifiers from './utils/orderModifiers';
import debounce from './utils/debounce';
import validateModifiers from './utils/validateModifiers';
import uniqueBy from './utils/uniqueBy';
import getBasePlacement from './utils/getBasePlacement';
import mergeByName from './utils/mergeByName';
import detectOverflow from './utils/detectOverflow';
import { isElement } from './dom-utils/instanceOf';
import { auto } from './enums';
const INVALID_ELEMENT_ERROR =
'Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.';
const INFINITE_LOOP_ERROR =
'Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.';
const DEFAULT_OPTIONS: OptionsGeneric<any> = {
placement: 'bottom',
modifiers: [],
strategy: 'absolute',
};
type PopperGeneratorArgs = {
defaultModifiers?: Array<Modifier<any, any>>,
defaultOptions?: $Shape<OptionsGeneric<any>>,
};
function areValidElements(...args: Array<any>): boolean {
return !args.some(
(element) =>
!(element && typeof element.getBoundingClientRect === 'function')
);
}
export function popperGenerator(generatorOptions: PopperGeneratorArgs = {}) {
const {
defaultModifiers = [],
defaultOptions = DEFAULT_OPTIONS,
} = generatorOptions;
return function createPopper<TModifier: $Shape<Modifier<any, any>>>(
reference: Element | VirtualElement,
popper: HTMLElement,
options: $Shape<OptionsGeneric<TModifier>> = defaultOptions
): Instance {
let state: $Shape<State> = {
placement: 'bottom',
orderedModifiers: [],
options: { ...DEFAULT_OPTIONS, ...defaultOptions },
modifiersData: {},
elements: {
reference,
popper,
},
attributes: {},
styles: {},
};
let effectCleanupFns: Array<() => void> = [];
let isDestroyed = false;
const instance = {
state,
setOptions(options) {
cleanupModifierEffects();
state.options = {
// $FlowFixMe
...defaultOptions,
...state.options,
...options,
};
state.scrollParents = {
reference: isElement(reference)
? listScrollParents(reference)
: reference.contextElement
? listScrollParents(reference.contextElement)
: [],
popper: listScrollParents(popper),
};
// Orders the modifiers based on their dependencies and `phase`
// properties
const orderedModifiers = orderModifiers(
mergeByName([...defaultModifiers, ...state.options.modifiers])
);
// Strip out disabled modifiers
state.orderedModifiers = orderedModifiers.filter((m) => m.enabled);
// Validate the provided modifiers so that the consumer will get warned
// if one of the modifiers is invalid for any reason
if (false) {
const modifiers = uniqueBy(
[...orderedModifiers, ...state.options.modifiers],
({ name }) => name
);
validateModifiers(modifiers);
if (getBasePlacement(state.options.placement) === auto) {
const flipModifier = state.orderedModifiers.find(
({ name }) => name === 'flip'
);
if (!flipModifier) {
console.error(
[
'Popper: "auto" placements require the "flip" modifier be',
'present and enabled to work.',
].join(' ')
);
}
}
const {
marginTop,
marginRight,
marginBottom,
marginLeft,
} = getComputedStyle(popper);
// We no longer take into account `margins` on the popper, and it can
// cause bugs with positioning, so we'll warn the consumer
if (
[marginTop, marginRight, marginBottom, marginLeft].some((margin) =>
parseFloat(margin)
)
) {
console.warn(
[
'Popper: CSS "margin" styles cannot be used to apply padding',
'between the popper and its reference element or boundary.',
'To replicate margin, use the `offset` modifier, as well as',
'the `padding` option in the `preventOverflow` and `flip`',
'modifiers.',
].join(' ')
);
}
}
runModifierEffects();
return instance.update();
},
// Sync update it will always be executed, even if not necessary. This
// is useful for low frequency updates where sync behavior simplifies the
// logic.
// For high frequency updates (e.g. `resize` and `scroll` events), always
// prefer the async Popper#update method
forceUpdate() {
if (isDestroyed) {
return;
}
const { reference, popper } = state.elements;
// Don't proceed if `reference` or `popper` are not valid elements
// anymore
if (!areValidElements(reference, popper)) {
if (false) {
console.error(INVALID_ELEMENT_ERROR);
}
return;
}
// Store the reference and popper rects to be read by modifiers
state.rects = {
reference: getCompositeRect(
reference,
getOffsetParent(popper),
state.options.strategy === 'fixed'
),
popper: getLayoutRect(popper),
};
// Modifiers have the ability to reset the current update cycle. The
// most common use case for this is the `flip` modifier changing the
// placement, which then needs to re-run all the modifiers, because the
// logic was previously ran for the previous placement and is therefore
// stale/incorrect
state.reset = false;
state.placement = state.options.placement;
// On each update cycle, the `modifiersData` property for each modifier
// is filled with the initial data specified by the modifier. This means
// it doesn't persist and is fresh on each update.
// To ensure persistent data, use `${name}#persistent`
state.orderedModifiers.forEach(
(modifier) =>
(state.modifiersData[modifier.name] = {
...modifier.data,
})
);
let __debug_loops__ = 0;
for (let index = 0; index < state.orderedModifiers.length; index++) {
if (false) {
__debug_loops__ += 1;
if (__debug_loops__ > 100) {
console.error(INFINITE_LOOP_ERROR);
break;
}
}
if (state.reset === true) {
state.reset = false;
index = -1;
continue;
}
const { fn, options = {}, name } = state.orderedModifiers[index];
if (typeof fn === 'function') {
state = fn({ state, options, name, instance }) || state;
}
}
},
// Async and optimistically optimized update it will not be executed if
// not necessary (debounced to run at most once-per-tick)
update: debounce<$Shape<State>>(
() =>
new Promise<$Shape<State>>((resolve) => {
instance.forceUpdate();
resolve(state);
})
),
destroy() {
cleanupModifierEffects();
isDestroyed = true;
},
};
if (!areValidElements(reference, popper)) {
if (false) {
console.error(INVALID_ELEMENT_ERROR);
}
return instance;
}
instance.setOptions(options).then((state) => {
if (!isDestroyed && options.onFirstUpdate) {
options.onFirstUpdate(state);
}
});
// Modifiers have the ability to execute arbitrary code before the first
// update cycle runs. They will be executed in the same order as the update
// cycle. This is useful when a modifier adds some persistent data that
// other modifiers need to use, but the modifier is run after the dependent
// one.
function runModifierEffects() {
state.orderedModifiers.forEach(({ name, options = {}, effect }) => {
if (typeof effect === 'function') {
const cleanupFn = effect({ state, name, instance, options });
const noopFn = () => {};
effectCleanupFns.push(cleanupFn || noopFn);
}
});
}
function cleanupModifierEffects() {
effectCleanupFns.forEach((fn) => fn());
effectCleanupFns = [];
}
return instance;
};
}
export const createPopper = popperGenerator();
// eslint-disable-next-line import/no-unused-modules
export { detectOverflow };

View File

@@ -0,0 +1 @@
export default function contains(parent: Element, child: Element): boolean;

View File

@@ -0,0 +1,23 @@
import { isShadowRoot } from "./instanceOf.js";
export default function contains(parent, child) {
var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method
if (parent.contains(child)) {
return true;
} // then fallback to custom implementation with Shadow DOM support
else if (isShadowRoot(rootNode)) {
var next = child;
do {
if (next && parent.isSameNode(next)) {
return true;
} // $FlowFixMe: need a better way to handle this...
next = next.parentNode || next.host;
} while (next);
} // Give up, the result is false
return false;
}

View File

@@ -0,0 +1,25 @@
// @flow
import { isShadowRoot } from './instanceOf';
export default function contains(parent: Element, child: Element) {
const rootNode = child.getRootNode && child.getRootNode();
// First, attempt with faster native method
if (parent.contains(child)) {
return true;
}
// then fallback to custom implementation with Shadow DOM support
else if (isShadowRoot(rootNode)) {
let next = child;
do {
if (next && parent.isSameNode(next)) {
return true;
}
// $FlowFixMe: need a better way to handle this...
next = next.parentNode || next.host;
} while (next);
}
// Give up, the result is false
return false;
}

View File

@@ -0,0 +1,2 @@
import { ClientRectObject, VirtualElement } from "../types";
export default function getBoundingClientRect(element: Element | VirtualElement): ClientRectObject;

View File

@@ -0,0 +1,13 @@
export default function getBoundingClientRect(element) {
var rect = element.getBoundingClientRect();
return {
width: rect.width,
height: rect.height,
top: rect.top,
right: rect.right,
bottom: rect.bottom,
left: rect.left,
x: rect.left,
y: rect.top
};
}

View File

@@ -0,0 +1,19 @@
// @flow
import type { ClientRectObject, VirtualElement } from '../types';
export default function getBoundingClientRect(
element: Element | VirtualElement
): ClientRectObject {
const rect = element.getBoundingClientRect();
return {
width: rect.width,
height: rect.height,
top: rect.top,
right: rect.right,
bottom: rect.bottom,
left: rect.left,
x: rect.left,
y: rect.top,
};
}

View File

@@ -0,0 +1,3 @@
import { ClientRectObject } from "../types";
import { Boundary, RootBoundary } from "../enums";
export default function getClippingRect(element: Element, boundary: Boundary, rootBoundary: RootBoundary): ClientRectObject;

View File

@@ -0,0 +1,69 @@
import { viewport } from "../enums.js";
import getViewportRect from "./getViewportRect.js";
import getDocumentRect from "./getDocumentRect.js";
import listScrollParents from "./listScrollParents.js";
import getOffsetParent from "./getOffsetParent.js";
import getDocumentElement from "./getDocumentElement.js";
import getComputedStyle from "./getComputedStyle.js";
import { isElement, isHTMLElement } from "./instanceOf.js";
import getBoundingClientRect from "./getBoundingClientRect.js";
import getParentNode from "./getParentNode.js";
import contains from "./contains.js";
import getNodeName from "./getNodeName.js";
import rectToClientRect from "../utils/rectToClientRect.js";
function getInnerBoundingClientRect(element) {
var rect = getBoundingClientRect(element);
rect.top = rect.top + element.clientTop;
rect.left = rect.left + element.clientLeft;
rect.bottom = rect.top + element.clientHeight;
rect.right = rect.left + element.clientWidth;
rect.width = element.clientWidth;
rect.height = element.clientHeight;
rect.x = rect.left;
rect.y = rect.top;
return rect;
}
function getClientRectFromMixedType(element, clippingParent) {
return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isHTMLElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
} // A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`
function getClippingParents(element) {
var clippingParents = listScrollParents(getParentNode(element));
var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;
var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
if (!isElement(clipperElement)) {
return [];
} // $FlowFixMe: https://github.com/facebook/flow/issues/1414
return clippingParents.filter(function (clippingParent) {
return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
});
} // Gets the maximum area that the element is visible in due to any number of
// clipping parents
export default function getClippingRect(element, boundary, rootBoundary) {
var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
var firstClippingParent = clippingParents[0];
var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
var rect = getClientRectFromMixedType(element, clippingParent);
accRect.top = Math.max(rect.top, accRect.top);
accRect.right = Math.min(rect.right, accRect.right);
accRect.bottom = Math.min(rect.bottom, accRect.bottom);
accRect.left = Math.max(rect.left, accRect.left);
return accRect;
}, getClientRectFromMixedType(element, firstClippingParent));
clippingRect.width = clippingRect.right - clippingRect.left;
clippingRect.height = clippingRect.bottom - clippingRect.top;
clippingRect.x = clippingRect.left;
clippingRect.y = clippingRect.top;
return clippingRect;
}

View File

@@ -0,0 +1,100 @@
// @flow
import type { ClientRectObject } from '../types';
import type { Boundary, RootBoundary } from '../enums';
import { viewport } from '../enums';
import getViewportRect from './getViewportRect';
import getDocumentRect from './getDocumentRect';
import listScrollParents from './listScrollParents';
import getOffsetParent from './getOffsetParent';
import getDocumentElement from './getDocumentElement';
import getComputedStyle from './getComputedStyle';
import { isElement, isHTMLElement } from './instanceOf';
import getBoundingClientRect from './getBoundingClientRect';
import getParentNode from './getParentNode';
import contains from './contains';
import getNodeName from './getNodeName';
import rectToClientRect from '../utils/rectToClientRect';
function getInnerBoundingClientRect(element: Element) {
const rect = getBoundingClientRect(element);
rect.top = rect.top + element.clientTop;
rect.left = rect.left + element.clientLeft;
rect.bottom = rect.top + element.clientHeight;
rect.right = rect.left + element.clientWidth;
rect.width = element.clientWidth;
rect.height = element.clientHeight;
rect.x = rect.left;
rect.y = rect.top;
return rect;
}
function getClientRectFromMixedType(
element: Element,
clippingParent: Element | RootBoundary
): ClientRectObject {
return clippingParent === viewport
? rectToClientRect(getViewportRect(element))
: isHTMLElement(clippingParent)
? getInnerBoundingClientRect(clippingParent)
: rectToClientRect(getDocumentRect(getDocumentElement(element)));
}
// A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`
function getClippingParents(element: Element): Array<Element> {
const clippingParents = listScrollParents(getParentNode(element));
const canEscapeClipping =
['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;
const clipperElement =
canEscapeClipping && isHTMLElement(element)
? getOffsetParent(element)
: element;
if (!isElement(clipperElement)) {
return [];
}
// $FlowFixMe: https://github.com/facebook/flow/issues/1414
return clippingParents.filter(
(clippingParent) =>
isElement(clippingParent) &&
contains(clippingParent, clipperElement) &&
getNodeName(clippingParent) !== 'body'
);
}
// Gets the maximum area that the element is visible in due to any number of
// clipping parents
export default function getClippingRect(
element: Element,
boundary: Boundary,
rootBoundary: RootBoundary
): ClientRectObject {
const mainClippingParents =
boundary === 'clippingParents'
? getClippingParents(element)
: [].concat(boundary);
const clippingParents = [...mainClippingParents, rootBoundary];
const firstClippingParent = clippingParents[0];
const clippingRect = clippingParents.reduce((accRect, clippingParent) => {
const rect = getClientRectFromMixedType(element, clippingParent);
accRect.top = Math.max(rect.top, accRect.top);
accRect.right = Math.min(rect.right, accRect.right);
accRect.bottom = Math.min(rect.bottom, accRect.bottom);
accRect.left = Math.max(rect.left, accRect.left);
return accRect;
}, getClientRectFromMixedType(element, firstClippingParent));
clippingRect.width = clippingRect.right - clippingRect.left;
clippingRect.height = clippingRect.bottom - clippingRect.top;
clippingRect.x = clippingRect.left;
clippingRect.y = clippingRect.top;
return clippingRect;
}

View File

@@ -0,0 +1,2 @@
import { Rect, VirtualElement, Window } from "../types";
export default function getCompositeRect(elementOrVirtualElement: Element | VirtualElement, offsetParent: Element | Window, isFixed?: boolean): Rect;

View File

@@ -0,0 +1,48 @@
import getBoundingClientRect from "./getBoundingClientRect.js";
import getNodeScroll from "./getNodeScroll.js";
import getNodeName from "./getNodeName.js";
import { isHTMLElement } from "./instanceOf.js";
import getWindowScrollBarX from "./getWindowScrollBarX.js";
import getDocumentElement from "./getDocumentElement.js";
import isScrollParent from "./isScrollParent.js"; // Returns the composite rect of an element relative to its offsetParent.
// Composite means it takes into account transforms as well as layout.
export default function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
if (isFixed === void 0) {
isFixed = false;
}
var documentElement = getDocumentElement(offsetParent);
var rect = getBoundingClientRect(elementOrVirtualElement);
var isOffsetParentAnElement = isHTMLElement(offsetParent);
var scroll = {
scrollLeft: 0,
scrollTop: 0
};
var offsets = {
x: 0,
y: 0
};
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
isScrollParent(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isHTMLElement(offsetParent)) {
offsets = getBoundingClientRect(offsetParent);
offsets.x += offsetParent.clientLeft;
offsets.y += offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX(documentElement);
}
}
return {
x: rect.left + scroll.scrollLeft - offsets.x,
y: rect.top + scroll.scrollTop - offsets.y,
width: rect.width,
height: rect.height
};
}

View File

@@ -0,0 +1,49 @@
// @flow
import type { Rect, VirtualElement, Window } from '../types';
import getBoundingClientRect from './getBoundingClientRect';
import getNodeScroll from './getNodeScroll';
import getNodeName from './getNodeName';
import { isHTMLElement } from './instanceOf';
import getWindowScrollBarX from './getWindowScrollBarX';
import getDocumentElement from './getDocumentElement';
import isScrollParent from './isScrollParent';
// Returns the composite rect of an element relative to its offsetParent.
// Composite means it takes into account transforms as well as layout.
export default function getCompositeRect(
elementOrVirtualElement: Element | VirtualElement,
offsetParent: Element | Window,
isFixed: boolean = false
): Rect {
const documentElement = getDocumentElement(offsetParent);
const rect = getBoundingClientRect(elementOrVirtualElement);
const isOffsetParentAnElement = isHTMLElement(offsetParent);
let scroll = { scrollLeft: 0, scrollTop: 0 };
let offsets = { x: 0, y: 0 };
if (isOffsetParentAnElement || (!isOffsetParentAnElement && !isFixed)) {
if (
getNodeName(offsetParent) !== 'body' ||
// https://github.com/popperjs/popper-core/issues/1078
isScrollParent(documentElement)
) {
scroll = getNodeScroll(offsetParent);
}
if (isHTMLElement(offsetParent)) {
offsets = getBoundingClientRect(offsetParent);
offsets.x += offsetParent.clientLeft;
offsets.y += offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX(documentElement);
}
}
return {
x: rect.left + scroll.scrollLeft - offsets.x,
y: rect.top + scroll.scrollTop - offsets.y,
width: rect.width,
height: rect.height,
};
}

View File

@@ -0,0 +1 @@
export default function getComputedStyle(element: Element): CSSStyleDeclaration;

View File

@@ -0,0 +1,4 @@
import getWindow from "./getWindow.js";
export default function getComputedStyle(element) {
return getWindow(element).getComputedStyle(element);
}

View File

@@ -0,0 +1,8 @@
// @flow
import getWindow from './getWindow';
export default function getComputedStyle(
element: Element
): CSSStyleDeclaration {
return getWindow(element).getComputedStyle(element);
}

View File

@@ -0,0 +1,2 @@
import { Window } from "../types";
export default function getDocumentElement(element: Element | Window): HTMLElement;

View File

@@ -0,0 +1,5 @@
import { isElement } from "./instanceOf.js";
export default function getDocumentElement(element) {
// $FlowFixMe: assume body is always available
return ((isElement(element) ? element.ownerDocument : element.document) || window.document).documentElement;
}

View File

@@ -0,0 +1,11 @@
// @flow
import { isElement } from './instanceOf';
import type { Window } from '../types';
export default function getDocumentElement(
element: Element | Window
): HTMLElement {
// $FlowFixMe: assume body is always available
return ((isElement(element) ? element.ownerDocument : element.document) || window.document)
.documentElement;
}

View File

@@ -0,0 +1,2 @@
import { Rect } from "../types";
export default function getDocumentRect(element: HTMLElement): Rect;

View File

@@ -0,0 +1,26 @@
import getDocumentElement from "./getDocumentElement.js";
import getComputedStyle from "./getComputedStyle.js";
import getWindowScrollBarX from "./getWindowScrollBarX.js";
import getWindowScroll from "./getWindowScroll.js"; // Gets the entire size of the scrollable document area, even extending outside
// of the `<html>` and `<body>` rect bounds if horizontally scrollable
export default function getDocumentRect(element) {
var html = getDocumentElement(element);
var winScroll = getWindowScroll(element);
var body = element.ownerDocument.body;
var width = Math.max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
var height = Math.max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
var y = -winScroll.scrollTop;
if (getComputedStyle(body || html).direction === 'rtl') {
x += Math.max(html.clientWidth, body ? body.clientWidth : 0) - width;
}
return {
width: width,
height: height,
x: x,
y: y
};
}

View File

@@ -0,0 +1,36 @@
// @flow
import type { Rect } from '../types';
import getDocumentElement from './getDocumentElement';
import getComputedStyle from './getComputedStyle';
import getWindowScrollBarX from './getWindowScrollBarX';
import getWindowScroll from './getWindowScroll';
// Gets the entire size of the scrollable document area, even extending outside
// of the `<html>` and `<body>` rect bounds if horizontally scrollable
export default function getDocumentRect(element: HTMLElement): Rect {
const html = getDocumentElement(element);
const winScroll = getWindowScroll(element);
const body = element.ownerDocument.body;
const width = Math.max(
html.scrollWidth,
html.clientWidth,
body ? body.scrollWidth : 0,
body ? body.clientWidth : 0
);
const height = Math.max(
html.scrollHeight,
html.clientHeight,
body ? body.scrollHeight : 0,
body ? body.clientHeight : 0
);
let x = -winScroll.scrollLeft + getWindowScrollBarX(element);
const y = -winScroll.scrollTop;
if (getComputedStyle(body || html).direction === 'rtl') {
x += Math.max(html.clientWidth, body ? body.clientWidth : 0) - width;
}
return { width, height, x, y };
}

View File

@@ -0,0 +1,4 @@
export default function getHTMLElementScroll(element: HTMLElement): {
scrollLeft: number;
scrollTop: number;
};

View File

@@ -0,0 +1,6 @@
export default function getHTMLElementScroll(element) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}

View File

@@ -0,0 +1,8 @@
// @flow
export default function getHTMLElementScroll(element: HTMLElement) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop,
};
}

View File

@@ -0,0 +1,2 @@
import { Rect } from "../types";
export default function getLayoutRect(element: HTMLElement): Rect;

View File

@@ -0,0 +1,10 @@
// Returns the layout rect of an element relative to its offsetParent. Layout
// means it doesn't take into account transforms.
export default function getLayoutRect(element) {
return {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
}

View File

@@ -0,0 +1,13 @@
// @flow
import type { Rect } from '../types';
// Returns the layout rect of an element relative to its offsetParent. Layout
// means it doesn't take into account transforms.
export default function getLayoutRect(element: HTMLElement): Rect {
return {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight,
};
}

View File

@@ -0,0 +1,2 @@
import { Window } from "../types";
export default function getNodeName(element: (Node | null | undefined) | Window): string | null | undefined;

View File

@@ -0,0 +1,3 @@
export default function getNodeName(element) {
return element ? (element.nodeName || '').toLowerCase() : null;
}

View File

@@ -0,0 +1,6 @@
// @flow
import type { Window } from '../types';
export default function getNodeName(element: ?Node | Window): ?string {
return element ? (element.nodeName || '').toLowerCase() : null;
}

View File

@@ -0,0 +1,2 @@
import { Window } from "../types";
export default function getNodeScroll(node: Node | Window): any;

View File

@@ -0,0 +1,11 @@
import getWindowScroll from "./getWindowScroll.js";
import getWindow from "./getWindow.js";
import { isHTMLElement } from "./instanceOf.js";
import getHTMLElementScroll from "./getHTMLElementScroll.js";
export default function getNodeScroll(node) {
if (node === getWindow(node) || !isHTMLElement(node)) {
return getWindowScroll(node);
} else {
return getHTMLElementScroll(node);
}
}

View File

@@ -0,0 +1,14 @@
// @flow
import getWindowScroll from './getWindowScroll';
import getWindow from './getWindow';
import { isHTMLElement } from './instanceOf';
import getHTMLElementScroll from './getHTMLElementScroll';
import type { Window } from '../types';
export default function getNodeScroll(node: Node | Window) {
if (node === getWindow(node) || !isHTMLElement(node)) {
return getWindowScroll(node);
} else {
return getHTMLElementScroll(node);
}
}

View File

@@ -0,0 +1 @@
export default function getOffsetParent(element: Element): any;

View File

@@ -0,0 +1,62 @@
import getWindow from "./getWindow.js";
import getNodeName from "./getNodeName.js";
import getComputedStyle from "./getComputedStyle.js";
import { isHTMLElement } from "./instanceOf.js";
import isTableElement from "./isTableElement.js";
import getParentNode from "./getParentNode.js";
import getDocumentElement from "./getDocumentElement.js";
function getTrueOffsetParent(element) {
if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
getComputedStyle(element).position === 'fixed') {
return null;
}
var offsetParent = element.offsetParent;
if (offsetParent) {
var html = getDocumentElement(offsetParent);
if (getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static' && getComputedStyle(html).position !== 'static') {
return html;
}
}
return offsetParent;
} // `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block
function getContainingBlock(element) {
var currentNode = getParentNode(element);
while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that
// create a containing block.
if (css.transform !== 'none' || css.perspective !== 'none' || css.willChange && css.willChange !== 'auto') {
return currentNode;
} else {
currentNode = currentNode.parentNode;
}
}
return null;
} // Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.
export default function getOffsetParent(element) {
var window = getWindow(element);
var offsetParent = getTrueOffsetParent(element);
while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {
offsetParent = getTrueOffsetParent(offsetParent);
}
if (offsetParent && getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static') {
return window;
}
return offsetParent || getContainingBlock(element) || window;
}

View File

@@ -0,0 +1,87 @@
// @flow
import getWindow from './getWindow';
import getNodeName from './getNodeName';
import getComputedStyle from './getComputedStyle';
import { isHTMLElement } from './instanceOf';
import isTableElement from './isTableElement';
import getParentNode from './getParentNode';
import getDocumentElement from './getDocumentElement';
function getTrueOffsetParent(element: Element): ?Element {
if (
!isHTMLElement(element) ||
// https://github.com/popperjs/popper-core/issues/837
getComputedStyle(element).position === 'fixed'
) {
return null;
}
const offsetParent = element.offsetParent;
if (offsetParent) {
const html = getDocumentElement(offsetParent);
if (
getNodeName(offsetParent) === 'body' &&
getComputedStyle(offsetParent).position === 'static' &&
getComputedStyle(html).position !== 'static'
) {
return html;
}
}
return offsetParent;
}
// `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block
function getContainingBlock(element: Element) {
let currentNode = getParentNode(element);
while (
isHTMLElement(currentNode) &&
['html', 'body'].indexOf(getNodeName(currentNode)) < 0
) {
const css = getComputedStyle(currentNode);
// This is non-exhaustive but covers the most common CSS properties that
// create a containing block.
if (
css.transform !== 'none' ||
css.perspective !== 'none' ||
(css.willChange && css.willChange !== 'auto')
) {
return currentNode;
} else {
currentNode = currentNode.parentNode;
}
}
return null;
}
// Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.
export default function getOffsetParent(element: Element) {
const window = getWindow(element);
let offsetParent = getTrueOffsetParent(element);
while (
offsetParent &&
isTableElement(offsetParent) &&
getComputedStyle(offsetParent).position === 'static'
) {
offsetParent = getTrueOffsetParent(offsetParent);
}
if (
offsetParent &&
getNodeName(offsetParent) === 'body' &&
getComputedStyle(offsetParent).position === 'static'
) {
return window;
}
return offsetParent || getContainingBlock(element) || window;
}

View File

@@ -0,0 +1 @@
export default function getParentNode(element: Node | ShadowRoot): Node;

View File

@@ -0,0 +1,17 @@
import getNodeName from "./getNodeName.js";
import getDocumentElement from "./getDocumentElement.js";
export default function getParentNode(element) {
if (getNodeName(element) === 'html') {
return element;
}
return (// $FlowFixMe: this is a quicker (but less type safe) way to save quite some bytes from the bundle
element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
element.parentNode || // DOM Element detected
// $FlowFixMe: need a better way to handle this...
element.host || // ShadowRoot detected
// $FlowFixMe: HTMLElement is a Node
getDocumentElement(element) // fallback
);
}

View File

@@ -0,0 +1,19 @@
// @flow
import getNodeName from './getNodeName';
import getDocumentElement from './getDocumentElement';
export default function getParentNode(element: Node | ShadowRoot): Node {
if (getNodeName(element) === 'html') {
return element;
}
return (
// $FlowFixMe: this is a quicker (but less type safe) way to save quite some bytes from the bundle
element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
element.parentNode || // DOM Element detected
// $FlowFixMe: need a better way to handle this...
element.host || // ShadowRoot detected
// $FlowFixMe: HTMLElement is a Node
getDocumentElement(element) // fallback
);
}

View File

@@ -0,0 +1 @@
export default function getScrollParent(node: Node): HTMLElement;

View File

@@ -0,0 +1,16 @@
import getParentNode from "./getParentNode.js";
import isScrollParent from "./isScrollParent.js";
import getNodeName from "./getNodeName.js";
import { isHTMLElement } from "./instanceOf.js";
export default function getScrollParent(node) {
if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
// $FlowFixMe: assume body is always available
return node.ownerDocument.body;
}
if (isHTMLElement(node) && isScrollParent(node)) {
return node;
}
return getScrollParent(getParentNode(node));
}

View File

@@ -0,0 +1,18 @@
// @flow
import getParentNode from './getParentNode';
import isScrollParent from './isScrollParent';
import getNodeName from './getNodeName';
import { isHTMLElement } from './instanceOf';
export default function getScrollParent(node: Node): HTMLElement {
if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
// $FlowFixMe: assume body is always available
return node.ownerDocument.body;
}
if (isHTMLElement(node) && isScrollParent(node)) {
return node;
}
return getScrollParent(getParentNode(node));
}

View File

@@ -0,0 +1,6 @@
export default function getViewportRect(element: Element): {
width: number;
height: number;
x: number;
y: number;
};

View File

@@ -0,0 +1,40 @@
import getWindow from "./getWindow.js";
import getDocumentElement from "./getDocumentElement.js";
import getWindowScrollBarX from "./getWindowScrollBarX.js";
export default function getViewportRect(element) {
var win = getWindow(element);
var html = getDocumentElement(element);
var visualViewport = win.visualViewport;
var width = html.clientWidth;
var height = html.clientHeight;
var x = 0;
var y = 0; // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper
// can be obscured underneath it.
// Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even
// if it isn't open, so if this isn't available, the popper will be detected
// to overflow the bottom of the screen too early.
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height; // Uses Layout Viewport (like Chrome; Safari does not currently)
// In Chrome, it returns a value very close to 0 (+/-) but contains rounding
// errors due to floating point numbers, so we need to check precision.
// Safari returns a number <= 0, usually < -1 when pinch-zoomed
// Feature detection fails in mobile emulation mode in Chrome.
// Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) <
// 0.001
// Fallback here: "Not Safari" userAgent
if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width: width,
height: height,
x: x + getWindowScrollBarX(element),
y: y
};
}

View File

@@ -0,0 +1,46 @@
// @flow
import getWindow from './getWindow';
import getDocumentElement from './getDocumentElement';
import getWindowScrollBarX from './getWindowScrollBarX';
export default function getViewportRect(element: Element) {
const win = getWindow(element);
const html = getDocumentElement(element);
const visualViewport = win.visualViewport;
let width = html.clientWidth;
let height = html.clientHeight;
let x = 0;
let y = 0;
// NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper
// can be obscured underneath it.
// Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even
// if it isn't open, so if this isn't available, the popper will be detected
// to overflow the bottom of the screen too early.
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height;
// Uses Layout Viewport (like Chrome; Safari does not currently)
// In Chrome, it returns a value very close to 0 (+/-) but contains rounding
// errors due to floating point numbers, so we need to check precision.
// Safari returns a number <= 0, usually < -1 when pinch-zoomed
// Feature detection fails in mobile emulation mode in Chrome.
// Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) <
// 0.001
// Fallback here: "Not Safari" userAgent
if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width,
height,
x: x + getWindowScrollBarX(element),
y,
};
}

View File

@@ -0,0 +1 @@
export default function getWindow(node: any): any;

View File

@@ -0,0 +1,11 @@
/*:: import type { Window } from '../types'; */
/*:: declare function getWindow(node: Node | Window): Window; */
export default function getWindow(node) {
if (node.toString() !== '[object Window]') {
var ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}

View File

@@ -0,0 +1,12 @@
// @flow
/*:: import type { Window } from '../types'; */
/*:: declare function getWindow(node: Node | Window): Window; */
export default function getWindow(node) {
if (node.toString() !== '[object Window]') {
const ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}

View File

@@ -0,0 +1,5 @@
import { Window } from "../types";
export default function getWindowScroll(node: Node | Window): {
scrollLeft: any;
scrollTop: any;
};

View File

@@ -0,0 +1,10 @@
import getWindow from "./getWindow.js";
export default function getWindowScroll(node) {
var win = getWindow(node);
var scrollLeft = win.pageXOffset;
var scrollTop = win.pageYOffset;
return {
scrollLeft: scrollLeft,
scrollTop: scrollTop
};
}

View File

@@ -0,0 +1,14 @@
// @flow
import getWindow from './getWindow';
import type { Window } from '../types';
export default function getWindowScroll(node: Node | Window) {
const win = getWindow(node);
const scrollLeft = win.pageXOffset;
const scrollTop = win.pageYOffset;
return {
scrollLeft,
scrollTop,
};
}

View File

@@ -0,0 +1 @@
export default function getWindowScrollBarX(element: Element): number;

View File

@@ -0,0 +1,13 @@
import getBoundingClientRect from "./getBoundingClientRect.js";
import getDocumentElement from "./getDocumentElement.js";
import getWindowScroll from "./getWindowScroll.js";
export default function getWindowScrollBarX(element) {
// If <html> has a CSS width greater than the viewport, then this will be
// incorrect for RTL.
// Popper 1 is broken in this case and never had a bug report so let's assume
// it's not an issue. I don't think anyone ever specifies width on <html>
// anyway.
// Browsers where the left scrollbar doesn't cause an issue report `0` for
// this (e.g. Edge 2019, IE11, Safari)
return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}

View File

@@ -0,0 +1,18 @@
// @flow
import getBoundingClientRect from './getBoundingClientRect';
import getDocumentElement from './getDocumentElement';
import getWindowScroll from './getWindowScroll';
export default function getWindowScrollBarX(element: Element): number {
// If <html> has a CSS width greater than the viewport, then this will be
// incorrect for RTL.
// Popper 1 is broken in this case and never had a bug report so let's assume
// it's not an issue. I don't think anyone ever specifies width on <html>
// anyway.
// Browsers where the left scrollbar doesn't cause an issue report `0` for
// this (e.g. Edge 2019, IE11, Safari)
return (
getBoundingClientRect(getDocumentElement(element)).left +
getWindowScroll(element).scrollLeft
);
}

View File

@@ -0,0 +1,4 @@
declare function isElement(node: any): boolean;
declare function isHTMLElement(node: any): boolean;
declare function isShadowRoot(node: any): boolean;
export { isElement, isHTMLElement, isShadowRoot };

View File

@@ -0,0 +1,26 @@
import getWindow from "./getWindow.js";
/*:: declare function isElement(node: mixed): boolean %checks(node instanceof
Element); */
function isElement(node) {
var OwnElement = getWindow(node).Element;
return node instanceof OwnElement || node instanceof Element;
}
/*:: declare function isHTMLElement(node: mixed): boolean %checks(node instanceof
HTMLElement); */
function isHTMLElement(node) {
var OwnElement = getWindow(node).HTMLElement;
return node instanceof OwnElement || node instanceof HTMLElement;
}
/*:: declare function isShadowRoot(node: mixed): boolean %checks(node instanceof
ShadowRoot); */
function isShadowRoot(node) {
var OwnElement = getWindow(node).ShadowRoot;
return node instanceof OwnElement || node instanceof ShadowRoot;
}
export { isElement, isHTMLElement, isShadowRoot };

View File

@@ -0,0 +1,28 @@
// @flow
import getWindow from './getWindow';
/*:: declare function isElement(node: mixed): boolean %checks(node instanceof
Element); */
function isElement(node) {
const OwnElement = getWindow(node).Element;
return node instanceof OwnElement || node instanceof Element;
}
/*:: declare function isHTMLElement(node: mixed): boolean %checks(node instanceof
HTMLElement); */
function isHTMLElement(node) {
const OwnElement = getWindow(node).HTMLElement;
return node instanceof OwnElement || node instanceof HTMLElement;
}
/*:: declare function isShadowRoot(node: mixed): boolean %checks(node instanceof
ShadowRoot); */
function isShadowRoot(node) {
const OwnElement = getWindow(node).ShadowRoot;
return node instanceof OwnElement || node instanceof ShadowRoot;
}
export { isElement, isHTMLElement, isShadowRoot };

View File

@@ -0,0 +1 @@
export default function isScrollParent(element: HTMLElement): boolean;

View File

@@ -0,0 +1,10 @@
import getComputedStyle from "./getComputedStyle.js";
export default function isScrollParent(element) {
// Firefox wants us to check `-x` and `-y` variations as well
var _getComputedStyle = getComputedStyle(element),
overflow = _getComputedStyle.overflow,
overflowX = _getComputedStyle.overflowX,
overflowY = _getComputedStyle.overflowY;
return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}

View File

@@ -0,0 +1,8 @@
// @flow
import getComputedStyle from './getComputedStyle';
export default function isScrollParent(element: HTMLElement): boolean {
// Firefox wants us to check `-x` and `-y` variations as well
const { overflow, overflowX, overflowY } = getComputedStyle(element);
return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}

View File

@@ -0,0 +1 @@
export default function isTableElement(element: Element): boolean;

View File

@@ -0,0 +1,4 @@
import getNodeName from "./getNodeName.js";
export default function isTableElement(element) {
return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
}

View File

@@ -0,0 +1,6 @@
// @flow
import getNodeName from './getNodeName';
export default function isTableElement(element: Element): boolean {
return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
}

View File

@@ -0,0 +1,2 @@
import { Window, VisualViewport } from "../types";
export default function listScrollParents(element: Node, list?: Array<Element | Window>): Array<Element | Window | VisualViewport>;

View File

@@ -0,0 +1,25 @@
import getScrollParent from "./getScrollParent.js";
import getParentNode from "./getParentNode.js";
import getNodeName from "./getNodeName.js";
import getWindow from "./getWindow.js";
import isScrollParent from "./isScrollParent.js";
/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/
export default function listScrollParents(element, list) {
if (list === void 0) {
list = [];
}
var scrollParent = getScrollParent(element);
var isBody = getNodeName(scrollParent) === 'body';
var win = getWindow(scrollParent);
var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
var updatedList = list.concat(target);
return isBody ? updatedList : // $FlowFixMe: isBody tells us target will be an HTMLElement here
updatedList.concat(listScrollParents(getParentNode(target)));
}

View File

@@ -0,0 +1,34 @@
// @flow
import getScrollParent from './getScrollParent';
import getParentNode from './getParentNode';
import getNodeName from './getNodeName';
import getWindow from './getWindow';
import type { Window, VisualViewport } from '../types';
import isScrollParent from './isScrollParent';
/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/
export default function listScrollParents(
element: Node,
list: Array<Element | Window> = []
): Array<Element | Window | VisualViewport> {
const scrollParent = getScrollParent(element);
const isBody = getNodeName(scrollParent) === 'body';
const win = getWindow(scrollParent);
const target = isBody
? [win].concat(
win.visualViewport || [],
isScrollParent(scrollParent) ? scrollParent : []
)
: scrollParent;
const updatedList = list.concat(target);
return isBody
? updatedList
: // $FlowFixMe: isBody tells us target will be an HTMLElement here
updatedList.concat(listScrollParents(getParentNode(target)));
}

View File

@@ -0,0 +1,34 @@
export declare const top: "top";
export declare const bottom: "bottom";
export declare const right: "right";
export declare const left: "left";
export declare const auto: "auto";
export declare type BasePlacement = typeof top | typeof bottom | typeof right | typeof left;
export declare const basePlacements: Array<BasePlacement>;
export declare const start: "start";
export declare const end: "end";
export declare type Variation = typeof start | typeof end;
export declare const clippingParents: "clippingParents";
export declare const viewport: "viewport";
export declare type Boundary = HTMLElement | Array<HTMLElement> | typeof clippingParents;
export declare type RootBoundary = typeof viewport | "document";
export declare const popper: "popper";
export declare const reference: "reference";
export declare type Context = typeof popper | typeof reference;
export declare type VariationPlacement = "top-start" | "top-end" | "bottom-start" | "bottom-end" | "right-start" | "right-end" | "left-start" | "left-end";
export declare type AutoPlacement = "auto" | "auto-start" | "auto-end";
export declare type ComputedPlacement = VariationPlacement | BasePlacement;
export declare type Placement = AutoPlacement | BasePlacement | VariationPlacement;
export declare const variationPlacements: Array<VariationPlacement>;
export declare const placements: Array<Placement>;
export declare const beforeRead: "beforeRead";
export declare const read: "read";
export declare const afterRead: "afterRead";
export declare const beforeMain: "beforeMain";
export declare const main: "main";
export declare const afterMain: "afterMain";
export declare const beforeWrite: "beforeWrite";
export declare const write: "write";
export declare const afterWrite: "afterWrite";
export declare const modifierPhases: Array<ModifierPhases>;
export declare type ModifierPhases = typeof beforeRead | typeof read | typeof afterRead | typeof beforeMain | typeof main | typeof afterMain | typeof beforeWrite | typeof write | typeof afterWrite;

View File

@@ -0,0 +1,31 @@
export var top = 'top';
export var bottom = 'bottom';
export var right = 'right';
export var left = 'left';
export var auto = 'auto';
export var basePlacements = [top, bottom, right, left];
export var start = 'start';
export var end = 'end';
export var clippingParents = 'clippingParents';
export var viewport = 'viewport';
export var popper = 'popper';
export var reference = 'reference';
export var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
export var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []); // modifiers that need to read the DOM
export var beforeRead = 'beforeRead';
export var read = 'read';
export var afterRead = 'afterRead'; // pure-logic modifiers
export var beforeMain = 'beforeMain';
export var main = 'main';
export var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)
export var beforeWrite = 'beforeWrite';
export var write = 'write';
export var afterWrite = 'afterWrite';
export var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];

View File

@@ -0,0 +1,94 @@
// @flow
export const top: 'top' = 'top';
export const bottom: 'bottom' = 'bottom';
export const right: 'right' = 'right';
export const left: 'left' = 'left';
export const auto: 'auto' = 'auto';
export type BasePlacement =
| typeof top
| typeof bottom
| typeof right
| typeof left;
export const basePlacements: Array<BasePlacement> = [top, bottom, right, left];
export const start: 'start' = 'start';
export const end: 'end' = 'end';
export type Variation = typeof start | typeof end;
export const clippingParents: 'clippingParents' = 'clippingParents';
export const viewport: 'viewport' = 'viewport';
export type Boundary =
| HTMLElement
| Array<HTMLElement>
| typeof clippingParents;
export type RootBoundary = typeof viewport | 'document';
export const popper: 'popper' = 'popper';
export const reference: 'reference' = 'reference';
export type Context = typeof popper | typeof reference;
export type VariationPlacement =
| 'top-start'
| 'top-end'
| 'bottom-start'
| 'bottom-end'
| 'right-start'
| 'right-end'
| 'left-start'
| 'left-end';
export type AutoPlacement = 'auto' | 'auto-start' | 'auto-end';
export type ComputedPlacement = VariationPlacement | BasePlacement;
export type Placement = AutoPlacement | BasePlacement | VariationPlacement;
export const variationPlacements: Array<VariationPlacement> = basePlacements.reduce(
(acc: Array<VariationPlacement>, placement: BasePlacement) =>
acc.concat([(`${placement}-${start}`: any), (`${placement}-${end}`: any)]),
[]
);
export const placements: Array<Placement> = [...basePlacements, auto].reduce(
(
acc: Array<Placement>,
placement: BasePlacement | typeof auto
): Array<Placement> =>
acc.concat([
placement,
(`${placement}-${start}`: any),
(`${placement}-${end}`: any),
]),
[]
);
// modifiers that need to read the DOM
export const beforeRead: 'beforeRead' = 'beforeRead';
export const read: 'read' = 'read';
export const afterRead: 'afterRead' = 'afterRead';
// pure-logic modifiers
export const beforeMain: 'beforeMain' = 'beforeMain';
export const main: 'main' = 'main';
export const afterMain: 'afterMain' = 'afterMain';
// modifier with the purpose to write to the DOM (or write into a framework state)
export const beforeWrite: 'beforeWrite' = 'beforeWrite';
export const write: 'write' = 'write';
export const afterWrite: 'afterWrite' = 'afterWrite';
export const modifierPhases: Array<ModifierPhases> = [
beforeRead,
read,
afterRead,
beforeMain,
main,
afterMain,
beforeWrite,
write,
afterWrite,
];
export type ModifierPhases =
| typeof beforeRead
| typeof read
| typeof afterRead
| typeof beforeMain
| typeof main
| typeof afterMain
| typeof beforeWrite
| typeof write
| typeof afterWrite;

View File

@@ -0,0 +1,6 @@
export * from "./types";
export * from "./enums";
export * from "./modifiers";
export { popperGenerator, detectOverflow, createPopper as createPopperBase } from "./createPopper";
export { createPopper } from "./popper";
export { createPopper as createPopperLite } from "./popper-lite";

View File

@@ -0,0 +1,8 @@
export * from "./enums.js";
export * from "./modifiers/index.js"; // eslint-disable-next-line import/no-unused-modules
export { popperGenerator, detectOverflow, createPopper as createPopperBase } from "./createPopper.js"; // eslint-disable-next-line import/no-unused-modules
export { createPopper } from "./popper.js"; // eslint-disable-next-line import/no-unused-modules
export { createPopper as createPopperLite } from "./popper-lite.js";

View File

@@ -0,0 +1,13 @@
// @flow
export type * from './types';
export * from './enums';
export * from './modifiers';
// eslint-disable-next-line import/no-unused-modules
export { popperGenerator, detectOverflow, createPopper as createPopperBase } from './createPopper';
// eslint-disable-next-line import/no-unused-modules
export { createPopper } from './popper';
// eslint-disable-next-line import/no-unused-modules
export { createPopper as createPopperLite } from './popper-lite';

View File

@@ -0,0 +1,4 @@
import { Modifier } from "../types";
export declare type ApplyStylesModifier = Modifier<"applyStyles", {}>;
declare const _default: Modifier<"applyStyles", {}>;
export default _default;

View File

@@ -0,0 +1,86 @@
import getNodeName from "../dom-utils/getNodeName.js";
import { isHTMLElement } from "../dom-utils/instanceOf.js"; // This modifier takes the styles prepared by the `computeStyles` modifier
// and applies them to the HTMLElements such as popper and arrow
function applyStyles(_ref) {
var state = _ref.state;
Object.keys(state.elements).forEach(function (name) {
var style = state.styles[name] || {};
var attributes = state.attributes[name] || {};
var element = state.elements[name]; // arrow is optional + virtual elements
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
} // Flow doesn't support to extend this property, but it's the most
// effective way to apply styles to an HTMLElement
// $FlowFixMe
Object.assign(element.style, style);
Object.keys(attributes).forEach(function (name) {
var value = attributes[name];
if (value === false) {
element.removeAttribute(name);
} else {
element.setAttribute(name, value === true ? '' : value);
}
});
});
}
function effect(_ref2) {
var state = _ref2.state;
var initialStyles = {
popper: {
position: state.options.strategy,
left: '0',
top: '0',
margin: '0'
},
arrow: {
position: 'absolute'
},
reference: {}
};
Object.assign(state.elements.popper.style, initialStyles.popper);
if (state.elements.arrow) {
Object.assign(state.elements.arrow.style, initialStyles.arrow);
}
return function () {
Object.keys(state.elements).forEach(function (name) {
var element = state.elements[name];
var attributes = state.attributes[name] || {};
var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them
var style = styleProperties.reduce(function (style, property) {
style[property] = '';
return style;
}, {}); // arrow is optional + virtual elements
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
} // Flow doesn't support to extend this property, but it's the most
// effective way to apply styles to an HTMLElement
// $FlowFixMe
Object.assign(element.style, style);
Object.keys(attributes).forEach(function (attribute) {
element.removeAttribute(attribute);
});
});
};
} // eslint-disable-next-line import/no-unused-modules
export default {
name: 'applyStyles',
enabled: true,
phase: 'write',
fn: applyStyles,
effect: effect,
requires: ['computeStyles']
};

View File

@@ -0,0 +1,100 @@
// @flow
import type { Modifier, ModifierArguments } from '../types';
import getNodeName from '../dom-utils/getNodeName';
import { isHTMLElement } from '../dom-utils/instanceOf';
// This modifier takes the styles prepared by the `computeStyles` modifier
// and applies them to the HTMLElements such as popper and arrow
function applyStyles({ state }: ModifierArguments<{||}>) {
Object.keys(state.elements).forEach(name => {
const style = state.styles[name] || {};
const attributes = state.attributes[name] || {};
const element = state.elements[name];
// arrow is optional + virtual elements
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
}
// Flow doesn't support to extend this property, but it's the most
// effective way to apply styles to an HTMLElement
// $FlowFixMe
Object.assign(element.style, style);
Object.keys(attributes).forEach(name => {
const value = attributes[name];
if (value === false) {
element.removeAttribute(name);
} else {
element.setAttribute(name, value === true ? '' : value);
}
});
});
}
function effect({ state }: ModifierArguments<{||}>) {
const initialStyles = {
popper: {
position: state.options.strategy,
left: '0',
top: '0',
margin: '0',
},
arrow: {
position: 'absolute',
},
reference: {},
};
Object.assign(state.elements.popper.style, initialStyles.popper);
if (state.elements.arrow) {
Object.assign(state.elements.arrow.style, initialStyles.arrow);
}
return () => {
Object.keys(state.elements).forEach(name => {
const element = state.elements[name];
const attributes = state.attributes[name] || {};
const styleProperties = Object.keys(
state.styles.hasOwnProperty(name)
? state.styles[name]
: initialStyles[name]
);
// Set all values to an empty string to unset them
const style = styleProperties.reduce((style, property) => {
style[property] = '';
return style;
}, {});
// arrow is optional + virtual elements
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
}
// Flow doesn't support to extend this property, but it's the most
// effective way to apply styles to an HTMLElement
// $FlowFixMe
Object.assign(element.style, style);
Object.keys(attributes).forEach(attribute => {
element.removeAttribute(attribute);
});
});
};
}
// eslint-disable-next-line import/no-unused-modules
export type ApplyStylesModifier = Modifier<'applyStyles', {||}>;
export default ({
name: 'applyStyles',
enabled: true,
phase: 'write',
fn: applyStyles,
effect,
requires: ['computeStyles'],
}: ApplyStylesModifier);

View File

@@ -0,0 +1,8 @@
import { Modifier, Padding } from "../types";
export declare type Options = {
element: HTMLElement | string | null;
padding: Padding;
};
export declare type ArrowModifier = Modifier<"arrow", Options>;
declare const _default: Modifier<"arrow", Options>;
export default _default;

View File

@@ -0,0 +1,99 @@
import getBasePlacement from "../utils/getBasePlacement.js";
import getLayoutRect from "../dom-utils/getLayoutRect.js";
import contains from "../dom-utils/contains.js";
import getOffsetParent from "../dom-utils/getOffsetParent.js";
import getMainAxisFromPlacement from "../utils/getMainAxisFromPlacement.js";
import within from "../utils/within.js";
import mergePaddingObject from "../utils/mergePaddingObject.js";
import expandToHashMap from "../utils/expandToHashMap.js";
import { left, right, basePlacements, top, bottom } from "../enums.js";
import { isHTMLElement } from "../dom-utils/instanceOf.js"; // eslint-disable-next-line import/no-unused-modules
function arrow(_ref) {
var _state$modifiersData$;
var state = _ref.state,
name = _ref.name;
var arrowElement = state.elements.arrow;
var popperOffsets = state.modifiersData.popperOffsets;
var basePlacement = getBasePlacement(state.placement);
var axis = getMainAxisFromPlacement(basePlacement);
var isVertical = [left, right].indexOf(basePlacement) >= 0;
var len = isVertical ? 'height' : 'width';
if (!arrowElement || !popperOffsets) {
return;
}
var paddingObject = state.modifiersData[name + "#persistent"].padding;
var arrowRect = getLayoutRect(arrowElement);
var minProp = axis === 'y' ? top : left;
var maxProp = axis === 'y' ? bottom : right;
var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
var startDiff = popperOffsets[axis] - state.rects.reference[axis];
var arrowOffsetParent = getOffsetParent(arrowElement);
var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
// outside of the popper bounds
var min = paddingObject[minProp];
var max = clientSize - arrowRect[len] - paddingObject[maxProp];
var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
var offset = within(min, center, max); // Prevents breaking syntax highlighting...
var axisProp = axis;
state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
}
function effect(_ref2) {
var state = _ref2.state,
options = _ref2.options,
name = _ref2.name;
var _options$element = options.element,
arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element,
_options$padding = options.padding,
padding = _options$padding === void 0 ? 0 : _options$padding;
if (arrowElement == null) {
return;
} // CSS selector
if (typeof arrowElement === 'string') {
arrowElement = state.elements.popper.querySelector(arrowElement);
if (!arrowElement) {
return;
}
}
if (process.env.NODE_ENV !== "production") {
if (!isHTMLElement(arrowElement)) {
console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).', 'To use an SVG arrow, wrap it in an HTMLElement that will be used as', 'the arrow.'].join(' '));
}
}
if (!contains(state.elements.popper, arrowElement)) {
if (process.env.NODE_ENV !== "production") {
console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', 'element.'].join(' '));
}
return;
}
state.elements.arrow = arrowElement;
state.modifiersData[name + "#persistent"] = {
padding: mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements))
};
} // eslint-disable-next-line import/no-unused-modules
export default {
name: 'arrow',
enabled: true,
phase: 'main',
fn: arrow,
effect: effect,
requires: ['popperOffsets'],
requiresIfExists: ['preventOverflow']
};

View File

@@ -0,0 +1,129 @@
// @flow
import type { Modifier, ModifierArguments, Padding } from '../types';
import getBasePlacement from '../utils/getBasePlacement';
import getLayoutRect from '../dom-utils/getLayoutRect';
import contains from '../dom-utils/contains';
import getOffsetParent from '../dom-utils/getOffsetParent';
import getMainAxisFromPlacement from '../utils/getMainAxisFromPlacement';
import within from '../utils/within';
import mergePaddingObject from '../utils/mergePaddingObject';
import expandToHashMap from '../utils/expandToHashMap';
import { left, right, basePlacements, top, bottom } from '../enums';
import { isHTMLElement } from '../dom-utils/instanceOf';
// eslint-disable-next-line import/no-unused-modules
export type Options = {
element: HTMLElement | string | null,
padding: Padding,
};
function arrow({ state, name }: ModifierArguments<Options>) {
const arrowElement = state.elements.arrow;
const popperOffsets = state.modifiersData.popperOffsets;
const basePlacement = getBasePlacement(state.placement);
const axis = getMainAxisFromPlacement(basePlacement);
const isVertical = [left, right].indexOf(basePlacement) >= 0;
const len = isVertical ? 'height' : 'width';
if (!arrowElement || !popperOffsets) {
return;
}
const paddingObject = state.modifiersData[`${name}#persistent`].padding;
const arrowRect = getLayoutRect(arrowElement);
const minProp = axis === 'y' ? top : left;
const maxProp = axis === 'y' ? bottom : right;
const endDiff =
state.rects.reference[len] +
state.rects.reference[axis] -
popperOffsets[axis] -
state.rects.popper[len];
const startDiff = popperOffsets[axis] - state.rects.reference[axis];
const arrowOffsetParent = getOffsetParent(arrowElement);
const clientSize = arrowOffsetParent
? axis === 'y'
? arrowOffsetParent.clientHeight || 0
: arrowOffsetParent.clientWidth || 0
: 0;
const centerToReference = endDiff / 2 - startDiff / 2;
// Make sure the arrow doesn't overflow the popper if the center point is
// outside of the popper bounds
const min = paddingObject[minProp];
const max = clientSize - arrowRect[len] - paddingObject[maxProp];
const center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
const offset = within(min, center, max);
// Prevents breaking syntax highlighting...
const axisProp: string = axis;
state.modifiersData[name] = {
[axisProp]: offset,
centerOffset: offset - center,
};
}
function effect({ state, options, name }: ModifierArguments<Options>) {
let { element: arrowElement = '[data-popper-arrow]', padding = 0 } = options;
if (arrowElement == null) {
return;
}
// CSS selector
if (typeof arrowElement === 'string') {
arrowElement = state.elements.popper.querySelector(arrowElement);
if (!arrowElement) {
return;
}
}
if (false) {
if (!isHTMLElement(arrowElement)) {
console.error(
[
'Popper: "arrow" element must be an HTMLElement (not an SVGElement).',
'To use an SVG arrow, wrap it in an HTMLElement that will be used as',
'the arrow.',
].join(' ')
);
}
}
if (!contains(state.elements.popper, arrowElement)) {
if (false) {
console.error(
[
'Popper: "arrow" modifier\'s `element` must be a child of the popper',
'element.',
].join(' ')
);
}
return;
}
state.elements.arrow = arrowElement;
state.modifiersData[`${name}#persistent`] = {
padding: mergePaddingObject(
typeof padding !== 'number'
? padding
: expandToHashMap(padding, basePlacements)
),
};
}
// eslint-disable-next-line import/no-unused-modules
export type ArrowModifier = Modifier<'arrow', Options>;
export default ({
name: 'arrow',
enabled: true,
phase: 'main',
fn: arrow,
effect,
requires: ['popperOffsets'],
requiresIfExists: ['preventOverflow'],
}: ArrowModifier);

View File

@@ -0,0 +1,29 @@
import { PositioningStrategy, Modifier, Rect } from "../types";
import { BasePlacement } from "../enums";
export declare type Options = {
gpuAcceleration: boolean;
adaptive: boolean;
};
export declare function mapToStyles({ popper, popperRect, placement, offsets, position, gpuAcceleration, adaptive }: {
popper: HTMLElement;
popperRect: Rect;
placement: BasePlacement;
offsets: Partial<{
x: number;
y: number;
centerOffset: number;
}>;
position: PositioningStrategy;
gpuAcceleration: boolean;
adaptive: boolean;
}): {
transform: string;
top: string;
right: string;
bottom: string;
left: string;
position: PositioningStrategy;
};
export declare type ComputeStylesModifier = Modifier<"computeStyles", Options>;
declare const _default: Modifier<"computeStyles", Options>;
export default _default;

View File

@@ -0,0 +1,138 @@
import { top, left, right, bottom } from "../enums.js";
import getOffsetParent from "../dom-utils/getOffsetParent.js";
import getWindow from "../dom-utils/getWindow.js";
import getDocumentElement from "../dom-utils/getDocumentElement.js";
import getComputedStyle from "../dom-utils/getComputedStyle.js";
import getBasePlacement from "../utils/getBasePlacement.js"; // eslint-disable-next-line import/no-unused-modules
var unsetSides = {
top: 'auto',
right: 'auto',
bottom: 'auto',
left: 'auto'
}; // Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.
function roundOffsets(_ref) {
var x = _ref.x,
y = _ref.y;
var win = window;
var dpr = win.devicePixelRatio || 1;
return {
x: Math.round(x * dpr) / dpr || 0,
y: Math.round(y * dpr) / dpr || 0
};
}
export function mapToStyles(_ref2) {
var _Object$assign2;
var popper = _ref2.popper,
popperRect = _ref2.popperRect,
placement = _ref2.placement,
offsets = _ref2.offsets,
position = _ref2.position,
gpuAcceleration = _ref2.gpuAcceleration,
adaptive = _ref2.adaptive;
var _roundOffsets = roundOffsets(offsets),
x = _roundOffsets.x,
y = _roundOffsets.y;
var hasX = offsets.hasOwnProperty('x');
var hasY = offsets.hasOwnProperty('y');
var sideX = left;
var sideY = top;
var win = window;
if (adaptive) {
var offsetParent = getOffsetParent(popper);
if (offsetParent === getWindow(popper)) {
offsetParent = getDocumentElement(popper);
} // $FlowFixMe: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
/*:: offsetParent = (offsetParent: Element); */
if (placement === top) {
sideY = bottom;
y -= offsetParent.clientHeight - popperRect.height;
y *= gpuAcceleration ? 1 : -1;
}
if (placement === left) {
sideX = right;
x -= offsetParent.clientWidth - popperRect.width;
x *= gpuAcceleration ? 1 : -1;
}
}
var commonStyles = Object.assign({
position: position
}, adaptive && unsetSides);
if (gpuAcceleration) {
var _Object$assign;
return Object.assign(Object.assign({}, commonStyles), {}, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) < 2 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
}
return Object.assign(Object.assign({}, commonStyles), {}, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}
function computeStyles(_ref3) {
var state = _ref3.state,
options = _ref3.options;
var _options$gpuAccelerat = options.gpuAcceleration,
gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
_options$adaptive = options.adaptive,
adaptive = _options$adaptive === void 0 ? true : _options$adaptive;
if (process.env.NODE_ENV !== "production") {
var transitionProperty = getComputedStyle(state.elements.popper).transitionProperty || '';
if (adaptive && ['transform', 'top', 'right', 'bottom', 'left'].some(function (property) {
return transitionProperty.indexOf(property) >= 0;
})) {
console.warn(['Popper: Detected CSS transitions on at least one of the following', 'CSS properties: "transform", "top", "right", "bottom", "left".', '\n\n', 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', 'for smooth transitions, or remove these properties from the CSS', 'transition declaration on the popper element if only transitioning', 'opacity or background-color for example.', '\n\n', 'We recommend using the popper element as a wrapper around an inner', 'element that can have any CSS property transitioned for animations.'].join(' '));
}
}
var commonStyles = {
placement: getBasePlacement(state.placement),
popper: state.elements.popper,
popperRect: state.rects.popper,
gpuAcceleration: gpuAcceleration
};
if (state.modifiersData.popperOffsets != null) {
state.styles.popper = Object.assign(Object.assign({}, state.styles.popper), mapToStyles(Object.assign(Object.assign({}, commonStyles), {}, {
offsets: state.modifiersData.popperOffsets,
position: state.options.strategy,
adaptive: adaptive
})));
}
if (state.modifiersData.arrow != null) {
state.styles.arrow = Object.assign(Object.assign({}, state.styles.arrow), mapToStyles(Object.assign(Object.assign({}, commonStyles), {}, {
offsets: state.modifiersData.arrow,
position: 'absolute',
adaptive: false
})));
}
state.attributes.popper = Object.assign(Object.assign({}, state.attributes.popper), {}, {
'data-popper-placement': state.placement
});
} // eslint-disable-next-line import/no-unused-modules
export default {
name: 'computeStyles',
enabled: true,
phase: 'beforeWrite',
fn: computeStyles,
data: {}
};

View File

@@ -0,0 +1,195 @@
// @flow
import type {
PositioningStrategy,
Offsets,
Modifier,
ModifierArguments,
Rect,
Window,
} from '../types';
import { type BasePlacement, top, left, right, bottom } from '../enums';
import getOffsetParent from '../dom-utils/getOffsetParent';
import getWindow from '../dom-utils/getWindow';
import getDocumentElement from '../dom-utils/getDocumentElement';
import getComputedStyle from '../dom-utils/getComputedStyle';
import getBasePlacement from '../utils/getBasePlacement';
// eslint-disable-next-line import/no-unused-modules
export type Options = {
gpuAcceleration: boolean,
adaptive: boolean,
};
const unsetSides = {
top: 'auto',
right: 'auto',
bottom: 'auto',
left: 'auto',
};
// Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.
function roundOffsets({ x, y }): Offsets {
const win: Window = window;
const dpr = win.devicePixelRatio || 1;
return {
x: Math.round(x * dpr) / dpr || 0,
y: Math.round(y * dpr) / dpr || 0,
};
}
export function mapToStyles({
popper,
popperRect,
placement,
offsets,
position,
gpuAcceleration,
adaptive,
}: {
popper: HTMLElement,
popperRect: Rect,
placement: BasePlacement,
offsets: $Shape<{ x: number, y: number, centerOffset: number }>,
position: PositioningStrategy,
gpuAcceleration: boolean,
adaptive: boolean,
}) {
let { x, y } = roundOffsets(offsets);
const hasX = offsets.hasOwnProperty('x');
const hasY = offsets.hasOwnProperty('y');
let sideX: string = left;
let sideY: string = top;
const win: Window = window;
if (adaptive) {
let offsetParent = getOffsetParent(popper);
if (offsetParent === getWindow(popper)) {
offsetParent = getDocumentElement(popper);
}
// $FlowFixMe: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
/*:: offsetParent = (offsetParent: Element); */
if (placement === top) {
sideY = bottom;
y -= offsetParent.clientHeight - popperRect.height;
y *= gpuAcceleration ? 1 : -1;
}
if (placement === left) {
sideX = right;
x -= offsetParent.clientWidth - popperRect.width;
x *= gpuAcceleration ? 1 : -1;
}
}
const commonStyles = {
position,
...(adaptive && unsetSides),
};
if (gpuAcceleration) {
return {
...commonStyles,
[sideY]: hasY ? '0' : '',
[sideX]: hasX ? '0' : '',
// Layer acceleration can disable subpixel rendering which causes slightly
// blurry text on low PPI displays, so we want to use 2D transforms
// instead
transform:
(win.devicePixelRatio || 1) < 2
? `translate(${x}px, ${y}px)`
: `translate3d(${x}px, ${y}px, 0)`,
};
}
return {
...commonStyles,
[sideY]: hasY ? `${y}px` : '',
[sideX]: hasX ? `${x}px` : '',
transform: '',
};
}
function computeStyles({ state, options }: ModifierArguments<Options>) {
const { gpuAcceleration = true, adaptive = true } = options;
if (false) {
const transitionProperty =
getComputedStyle(state.elements.popper).transitionProperty || '';
if (
adaptive &&
['transform', 'top', 'right', 'bottom', 'left'].some(
property => transitionProperty.indexOf(property) >= 0
)
) {
console.warn(
[
'Popper: Detected CSS transitions on at least one of the following',
'CSS properties: "transform", "top", "right", "bottom", "left".',
'\n\n',
'Disable the "computeStyles" modifier\'s `adaptive` option to allow',
'for smooth transitions, or remove these properties from the CSS',
'transition declaration on the popper element if only transitioning',
'opacity or background-color for example.',
'\n\n',
'We recommend using the popper element as a wrapper around an inner',
'element that can have any CSS property transitioned for animations.',
].join(' ')
);
}
}
const commonStyles = {
placement: getBasePlacement(state.placement),
popper: state.elements.popper,
popperRect: state.rects.popper,
gpuAcceleration,
};
if (state.modifiersData.popperOffsets != null) {
state.styles.popper = {
...state.styles.popper,
...mapToStyles({
...commonStyles,
offsets: state.modifiersData.popperOffsets,
position: state.options.strategy,
adaptive,
}),
};
}
if (state.modifiersData.arrow != null) {
state.styles.arrow = {
...state.styles.arrow,
...mapToStyles({
...commonStyles,
offsets: state.modifiersData.arrow,
position: 'absolute',
adaptive: false,
}),
};
}
state.attributes.popper = {
...state.attributes.popper,
'data-popper-placement': state.placement,
};
}
// eslint-disable-next-line import/no-unused-modules
export type ComputeStylesModifier = Modifier<'computeStyles', Options>;
export default ({
name: 'computeStyles',
enabled: true,
phase: 'beforeWrite',
fn: computeStyles,
data: {},
}: ComputeStylesModifier);

View File

@@ -0,0 +1,8 @@
import { Modifier } from "../types";
export declare type Options = {
scroll: boolean;
resize: boolean;
};
export declare type EventListenersModifier = Modifier<"eventListeners", Options>;
declare const _default: Modifier<"eventListeners", Options>;
export default _default;

View File

@@ -0,0 +1,49 @@
import getWindow from "../dom-utils/getWindow.js"; // eslint-disable-next-line import/no-unused-modules
var passive = {
passive: true
};
function effect(_ref) {
var state = _ref.state,
instance = _ref.instance,
options = _ref.options;
var _options$scroll = options.scroll,
scroll = _options$scroll === void 0 ? true : _options$scroll,
_options$resize = options.resize,
resize = _options$resize === void 0 ? true : _options$resize;
var window = getWindow(state.elements.popper);
var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.addEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.addEventListener('resize', instance.update, passive);
}
return function () {
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.removeEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.removeEventListener('resize', instance.update, passive);
}
};
} // eslint-disable-next-line import/no-unused-modules
export default {
name: 'eventListeners',
enabled: true,
phase: 'write',
fn: function fn() {},
effect: effect,
data: {}
};

View File

@@ -0,0 +1,54 @@
// @flow
import type { ModifierArguments, Modifier } from '../types';
import getWindow from '../dom-utils/getWindow';
// eslint-disable-next-line import/no-unused-modules
export type Options = {
scroll: boolean,
resize: boolean,
};
const passive = { passive: true };
function effect({ state, instance, options }: ModifierArguments<Options>) {
const { scroll = true, resize = true } = options;
const window = getWindow(state.elements.popper);
const scrollParents = [
...state.scrollParents.reference,
...state.scrollParents.popper,
];
if (scroll) {
scrollParents.forEach(scrollParent => {
scrollParent.addEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.addEventListener('resize', instance.update, passive);
}
return () => {
if (scroll) {
scrollParents.forEach(scrollParent => {
scrollParent.removeEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.removeEventListener('resize', instance.update, passive);
}
};
}
// eslint-disable-next-line import/no-unused-modules
export type EventListenersModifier = Modifier<'eventListeners', Options>;
export default ({
name: 'eventListeners',
enabled: true,
phase: 'write',
fn: () => {},
effect,
data: {},
}: EventListenersModifier);

View File

@@ -0,0 +1,16 @@
import { Placement, Boundary, RootBoundary } from "../enums";
import { Modifier, Padding } from "../types";
export declare type Options = {
mainAxis: boolean;
altAxis: boolean;
fallbackPlacements: Array<Placement>;
padding: Padding;
boundary: Boundary;
rootBoundary: RootBoundary;
altBoundary: boolean;
flipVariations: boolean;
allowedAutoPlacements: Array<Placement>;
};
export declare type FlipModifier = Modifier<"flip", Options>;
declare const _default: Modifier<"flip", Options>;
export default _default;

View File

@@ -0,0 +1,147 @@
import getOppositePlacement from "../utils/getOppositePlacement.js";
import getBasePlacement from "../utils/getBasePlacement.js";
import getOppositeVariationPlacement from "../utils/getOppositeVariationPlacement.js";
import detectOverflow from "../utils/detectOverflow.js";
import computeAutoPlacement from "../utils/computeAutoPlacement.js";
import { bottom, top, start, right, left, auto } from "../enums.js";
import getVariation from "../utils/getVariation.js"; // eslint-disable-next-line import/no-unused-modules
function getExpandedFallbackPlacements(placement) {
if (getBasePlacement(placement) === auto) {
return [];
}
var oppositePlacement = getOppositePlacement(placement);
return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
var state = _ref.state,
options = _ref.options,
name = _ref.name;
if (state.modifiersData[name]._skip) {
return;
}
var _options$mainAxis = options.mainAxis,
checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
_options$altAxis = options.altAxis,
checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
specifiedFallbackPlacements = options.fallbackPlacements,
padding = options.padding,
boundary = options.boundary,
rootBoundary = options.rootBoundary,
altBoundary = options.altBoundary,
_options$flipVariatio = options.flipVariations,
flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
allowedAutoPlacements = options.allowedAutoPlacements;
var preferredPlacement = state.options.placement;
var basePlacement = getBasePlacement(preferredPlacement);
var isBasePlacement = basePlacement === preferredPlacement;
var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding,
flipVariations: flipVariations,
allowedAutoPlacements: allowedAutoPlacements
}) : placement);
}, []);
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var checksMap = new Map();
var makeFallbackChecks = true;
var firstFittingPlacement = placements[0];
for (var i = 0; i < placements.length; i++) {
var placement = placements[i];
var _basePlacement = getBasePlacement(placement);
var isStartVariation = getVariation(placement) === start;
var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
var len = isVertical ? 'width' : 'height';
var overflow = detectOverflow(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
altBoundary: altBoundary,
padding: padding
});
var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
if (referenceRect[len] > popperRect[len]) {
mainVariationSide = getOppositePlacement(mainVariationSide);
}
var altVariationSide = getOppositePlacement(mainVariationSide);
var checks = [];
if (checkMainAxis) {
checks.push(overflow[_basePlacement] <= 0);
}
if (checkAltAxis) {
checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
}
if (checks.every(function (check) {
return check;
})) {
firstFittingPlacement = placement;
makeFallbackChecks = false;
break;
}
checksMap.set(placement, checks);
}
if (makeFallbackChecks) {
// `2` may be desired in some cases research later
var numberOfChecks = flipVariations ? 3 : 1;
var _loop = function _loop(_i) {
var fittingPlacement = placements.find(function (placement) {
var checks = checksMap.get(placement);
if (checks) {
return checks.slice(0, _i).every(function (check) {
return check;
});
}
});
if (fittingPlacement) {
firstFittingPlacement = fittingPlacement;
return "break";
}
};
for (var _i = numberOfChecks; _i > 0; _i--) {
var _ret = _loop(_i);
if (_ret === "break") break;
}
}
if (state.placement !== firstFittingPlacement) {
state.modifiersData[name]._skip = true;
state.placement = firstFittingPlacement;
state.reset = true;
}
} // eslint-disable-next-line import/no-unused-modules
export default {
name: 'flip',
enabled: true,
phase: 'main',
fn: flip,
requiresIfExists: ['offset'],
data: {
_skip: false
}
};

View File

@@ -0,0 +1,177 @@
// @flow
import type { Placement, Boundary, RootBoundary } from '../enums';
import type { ModifierArguments, Modifier, Padding } from '../types';
import getOppositePlacement from '../utils/getOppositePlacement';
import getBasePlacement from '../utils/getBasePlacement';
import getOppositeVariationPlacement from '../utils/getOppositeVariationPlacement';
import detectOverflow from '../utils/detectOverflow';
import computeAutoPlacement from '../utils/computeAutoPlacement';
import { bottom, top, start, right, left, auto } from '../enums';
import getVariation from '../utils/getVariation';
// eslint-disable-next-line import/no-unused-modules
export type Options = {
mainAxis: boolean,
altAxis: boolean,
fallbackPlacements: Array<Placement>,
padding: Padding,
boundary: Boundary,
rootBoundary: RootBoundary,
altBoundary: boolean,
flipVariations: boolean,
allowedAutoPlacements: Array<Placement>,
};
function getExpandedFallbackPlacements(placement: Placement): Array<Placement> {
if (getBasePlacement(placement) === auto) {
return [];
}
const oppositePlacement = getOppositePlacement(placement);
return [
getOppositeVariationPlacement(placement),
oppositePlacement,
getOppositeVariationPlacement(oppositePlacement),
];
}
function flip({ state, options, name }: ModifierArguments<Options>) {
if (state.modifiersData[name]._skip) {
return;
}
const {
mainAxis: checkMainAxis = true,
altAxis: checkAltAxis = true,
fallbackPlacements: specifiedFallbackPlacements,
padding,
boundary,
rootBoundary,
altBoundary,
flipVariations = true,
allowedAutoPlacements,
} = options;
const preferredPlacement = state.options.placement;
const basePlacement = getBasePlacement(preferredPlacement);
const isBasePlacement = basePlacement === preferredPlacement;
const fallbackPlacements =
specifiedFallbackPlacements ||
(isBasePlacement || !flipVariations
? [getOppositePlacement(preferredPlacement)]
: getExpandedFallbackPlacements(preferredPlacement));
const placements = [preferredPlacement, ...fallbackPlacements].reduce(
(acc, placement) => {
return acc.concat(
getBasePlacement(placement) === auto
? computeAutoPlacement(state, {
placement,
boundary,
rootBoundary,
padding,
flipVariations,
allowedAutoPlacements,
})
: placement
);
},
[]
);
const referenceRect = state.rects.reference;
const popperRect = state.rects.popper;
const checksMap = new Map();
let makeFallbackChecks = true;
let firstFittingPlacement = placements[0];
for (let i = 0; i < placements.length; i++) {
const placement = placements[i];
const basePlacement = getBasePlacement(placement);
const isStartVariation = getVariation(placement) === start;
const isVertical = [top, bottom].indexOf(basePlacement) >= 0;
const len = isVertical ? 'width' : 'height';
const overflow = detectOverflow(state, {
placement,
boundary,
rootBoundary,
altBoundary,
padding,
});
let mainVariationSide: any = isVertical
? isStartVariation
? right
: left
: isStartVariation
? bottom
: top;
if (referenceRect[len] > popperRect[len]) {
mainVariationSide = getOppositePlacement(mainVariationSide);
}
const altVariationSide: any = getOppositePlacement(mainVariationSide);
const checks = [];
if (checkMainAxis) {
checks.push(overflow[basePlacement] <= 0);
}
if (checkAltAxis) {
checks.push(
overflow[mainVariationSide] <= 0,
overflow[altVariationSide] <= 0
);
}
if (checks.every((check) => check)) {
firstFittingPlacement = placement;
makeFallbackChecks = false;
break;
}
checksMap.set(placement, checks);
}
if (makeFallbackChecks) {
// `2` may be desired in some cases research later
const numberOfChecks = flipVariations ? 3 : 1;
for (let i = numberOfChecks; i > 0; i--) {
const fittingPlacement = placements.find((placement) => {
const checks = checksMap.get(placement);
if (checks) {
return checks.slice(0, i).every((check) => check);
}
});
if (fittingPlacement) {
firstFittingPlacement = fittingPlacement;
break;
}
}
}
if (state.placement !== firstFittingPlacement) {
state.modifiersData[name]._skip = true;
state.placement = firstFittingPlacement;
state.reset = true;
}
}
// eslint-disable-next-line import/no-unused-modules
export type FlipModifier = Modifier<'flip', Options>;
export default ({
name: 'flip',
enabled: true,
phase: 'main',
fn: flip,
requiresIfExists: ['offset'],
data: { _skip: false },
}: FlipModifier);

View File

@@ -0,0 +1,4 @@
import { Modifier } from "../types";
export declare type HideModifier = Modifier<"hide", {}>;
declare const _default: Modifier<"hide", {}>;
export default _default;

View File

@@ -0,0 +1,61 @@
import { top, bottom, left, right } from "../enums.js";
import detectOverflow from "../utils/detectOverflow.js";
function getSideOffsets(overflow, rect, preventedOffsets) {
if (preventedOffsets === void 0) {
preventedOffsets = {
x: 0,
y: 0
};
}
return {
top: overflow.top - rect.height - preventedOffsets.y,
right: overflow.right - rect.width + preventedOffsets.x,
bottom: overflow.bottom - rect.height + preventedOffsets.y,
left: overflow.left - rect.width - preventedOffsets.x
};
}
function isAnySideFullyClipped(overflow) {
return [top, right, bottom, left].some(function (side) {
return overflow[side] >= 0;
});
}
function hide(_ref) {
var state = _ref.state,
name = _ref.name;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var preventedOffsets = state.modifiersData.preventOverflow;
var referenceOverflow = detectOverflow(state, {
elementContext: 'reference'
});
var popperAltOverflow = detectOverflow(state, {
altBoundary: true
});
var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
state.modifiersData[name] = {
referenceClippingOffsets: referenceClippingOffsets,
popperEscapeOffsets: popperEscapeOffsets,
isReferenceHidden: isReferenceHidden,
hasPopperEscaped: hasPopperEscaped
};
state.attributes.popper = Object.assign(Object.assign({}, state.attributes.popper), {}, {
'data-popper-reference-hidden': isReferenceHidden,
'data-popper-escaped': hasPopperEscaped
});
} // eslint-disable-next-line import/no-unused-modules
export default {
name: 'hide',
enabled: true,
phase: 'main',
requiresIfExists: ['preventOverflow'],
fn: hide
};

View File

@@ -0,0 +1,76 @@
// @flow
import type {
ModifierArguments,
Modifier,
Rect,
SideObject,
Offsets,
} from '../types';
import { top, bottom, left, right } from '../enums';
import detectOverflow from '../utils/detectOverflow';
function getSideOffsets(
overflow: SideObject,
rect: Rect,
preventedOffsets: Offsets = { x: 0, y: 0 }
): SideObject {
return {
top: overflow.top - rect.height - preventedOffsets.y,
right: overflow.right - rect.width + preventedOffsets.x,
bottom: overflow.bottom - rect.height + preventedOffsets.y,
left: overflow.left - rect.width - preventedOffsets.x,
};
}
function isAnySideFullyClipped(overflow: SideObject): boolean {
return [top, right, bottom, left].some((side) => overflow[side] >= 0);
}
function hide({ state, name }: ModifierArguments<{||}>) {
const referenceRect = state.rects.reference;
const popperRect = state.rects.popper;
const preventedOffsets = state.modifiersData.preventOverflow;
const referenceOverflow = detectOverflow(state, {
elementContext: 'reference',
});
const popperAltOverflow = detectOverflow(state, {
altBoundary: true,
});
const referenceClippingOffsets = getSideOffsets(
referenceOverflow,
referenceRect
);
const popperEscapeOffsets = getSideOffsets(
popperAltOverflow,
popperRect,
preventedOffsets
);
const isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
const hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
state.modifiersData[name] = {
referenceClippingOffsets,
popperEscapeOffsets,
isReferenceHidden,
hasPopperEscaped,
};
state.attributes.popper = {
...state.attributes.popper,
'data-popper-reference-hidden': isReferenceHidden,
'data-popper-escaped': hasPopperEscaped,
};
}
// eslint-disable-next-line import/no-unused-modules
export type HideModifier = Modifier<'hide', {||}>;
export default ({
name: 'hide',
enabled: true,
phase: 'main',
requiresIfExists: ['preventOverflow'],
fn: hide,
}: HideModifier);

View File

@@ -0,0 +1,9 @@
export { default as applyStyles } from "./applyStyles";
export { default as arrow } from "./arrow";
export { default as computeStyles } from "./computeStyles";
export { default as eventListeners } from "./eventListeners";
export { default as flip } from "./flip";
export { default as hide } from "./hide";
export { default as offset } from "./offset";
export { default as popperOffsets } from "./popperOffsets";
export { default as preventOverflow } from "./preventOverflow";

View File

@@ -0,0 +1,9 @@
export { default as applyStyles } from "./applyStyles.js";
export { default as arrow } from "./arrow.js";
export { default as computeStyles } from "./computeStyles.js";
export { default as eventListeners } from "./eventListeners.js";
export { default as flip } from "./flip.js";
export { default as hide } from "./hide.js";
export { default as offset } from "./offset.js";
export { default as popperOffsets } from "./popperOffsets.js";
export { default as preventOverflow } from "./preventOverflow.js";

View File

@@ -0,0 +1,10 @@
// @flow
export { default as applyStyles } from './applyStyles';
export { default as arrow } from './arrow';
export { default as computeStyles } from './computeStyles';
export { default as eventListeners } from './eventListeners';
export { default as flip } from './flip';
export { default as hide } from './hide';
export { default as offset } from './offset';
export { default as popperOffsets } from './popperOffsets';
export { default as preventOverflow } from './preventOverflow';

View File

@@ -0,0 +1,18 @@
import { Placement } from "../enums";
import { Modifier, Rect, Offsets } from "../types";
declare type OffsetsFunction = (arg0: {
popper: Rect;
reference: Rect;
placement: Placement;
}) => [number | null | undefined, number | null | undefined];
declare type Offset = OffsetsFunction | [number | null | undefined, number | null | undefined];
export declare type Options = {
offset: Offset;
};
export declare function distanceAndSkiddingToXY(placement: Placement, rects: {
popper: Rect;
reference: Rect;
}, offset: Offset): Offsets;
export declare type OffsetModifier = Modifier<"offset", Options>;
declare const _default: Modifier<"offset", Options>;
export default _default;

Some files were not shown because too many files have changed in this diff Show More