ode < 4.0 var asar = require('../lib/asar') var program = require('commander') program.version('v' + packageJSON.version) .description('Manipulate asar archive files') program.command('pack ') .alias('p') .description('create asar archive') .option('--ordering ', 'path to a text file for ordering contents') .option('--unpack ', 'do not pack files matching glob ') .option('--unpack-dir ', 'do not pack dirs matching glob or starting with literal ') .option('--exclude-hidden', 'exclude hidden files') .action(function (dir, output, options) { options = { unpack: options.unpack, unpackDir: options.unpackDir, ordering: options.ordering, version: options.sv, arch: options.sa, builddir: options.sb, dot: !options.excludeHidden } asar.createPackageWithOptions(dir, output, options).catch(error => { console.error(error) process.exit(1) }) }) program.command('list ') .alias('l') .description('list files of asar archive') .option('-i, --is-pack', 'each file in the asar is pack or unpack') .action(function (archive, options) { options = { isPack: options.isPack } var files = asar.listPackage(archive, options) for (var i in files) { console.log(files[i]) } }) program.command('extract-file ') .alias('ef') .description('extract one file from archive') .action(function (archive, filename) { require('fs').writeFileSync(require('path').basename(filename), asar.extractFile(archive, filename)) }) program.command('extract ') .alias('e') .description('extract archive') .action(function (archive, dest) { asar.extractAll(archive, dest) }) program.command('*') .action(function (_cmd, args) { console.log('asar: \'%s\' is not an asar command. See \'asar --help\'.', args[0]) }) program.parse(process.argv) if (program.args.length === 0) { program.help() } "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createPackage = createPackage; exports.createPackageWithOptions = createPackageWithOptions; exports.createPackageFromFiles = createPackageFromFiles; exports.createPackageFromStreams = createPackageFromStreams; exports.statFile = statFile; exports.getRawHeader = getRawHeader; exports.listPackage = listPackage; exports.extractFile = extractFile; exports.extractAll = extractAll; exports.uncache = uncache; exports.uncacheAll = uncacheAll; const path = __importStar(require("path")); const minimatch_1 = __importDefault(require("minimatch")); const wrapped_fs_1 = __importDefault(require("./wrapped-fs")); const filesystem_1 = require("./filesystem"); const disk = __importStar(require("./disk")); const crawlfs_1 = require("./crawlfs"); /** * Whether a directory should be excluded from packing due to the `--unpack-dir" option. * * @param dirPath - directory path to check * @param pattern - literal prefix [for backward compatibility] or glob pattern * @param unpackDirs - Array of directory paths previously marked as unpacked */ function isUnpackedDir(dirPath, pattern, unpackDirs) { if (dirPath.startsWith(pattern) || (0, minimatch_1.default)(dirPath, pattern)) { if (!unpackDirs.includes(dirPath)) { unpackDirs.push(dirPath); } return true; } else { return unpackDirs.some((unpackDir) => dirPath.startsWith(unpackDir) && !path.relative(unpackDir, dirPath).startsWith('..')); } } async function createPackage(src, dest) { return createPackageWithOptions(src, dest, {}); } async function createPackageWithOptions(src, dest, options) { const globOptions = options.globOptions ? options.globOptions : {}; globOptions.dot = options.dot === undefined ? true : options.dot; const pattern = src + (options.pattern ? options.pattern : '/**/*'); const [filenames, metadata] = await (0, crawlfs_1.crawl)(pattern, globOptions); return createPackageFromFiles(src, dest, filenames, metadata, options); } /** * Create an ASAR archive from a list of filenames. * * @param src - Base path. All files are relative to this. * @param dest - Archive filename (& path). * @param filenames - List of filenames relative to src. * @param [metadata] - Object with filenames as keys and {type='directory|file|link', stat: fs.stat} as values. (Optional) * @param [options] - Options passed to `createPackageWithOptions`. */ async function createPackageFromFiles(src, dest, filenames, metadata = {}, options = {}) { src = path.normalize(src); dest = path.normalize(dest); filenames = filenames.map(function (filename) { return path.normalize(filename); }); const filesystem = new filesystem_1.Filesystem(src); const files = []; const links = []; const unpackDirs = []; let filenamesSorted = []; if (options.ordering) { const orderingFiles = (await wrapped_fs_1.default.readFile(options.ordering)) .toString() .split('\n') .map((line) => { if (line.includes(':')) { line = line.split(':').pop(); } line = line.trim(); if (line.startsWith('/')) { line = line.slice(1); } return line; }); const ordering = []; for (const file of orderingFiles) { const pathComponents = file.split(path.sep); let str = src; for (const pathComponent of pathComponents) { str = path.join(str, pathComponent); ordering.push(str); } } let missing = 0; const total = filenames.length; for (const file of ordering) { if (!filenamesSorted.includes(file) && filenames.includes(file)) { filenamesSorted.push(file); } } for (const file of filenames) { if (!filenamesSorted.includes(file)) { filenamesSorted.push(file); missing += 1; } } console.log(`Ordering file has ${((total - missing) / total) * 100}% coverage.`); } else { filenamesSorted = filenames; } const handleFile = async function (filename) { if (!metadata[filename]) { const fileType = await (0, crawlfs_1.determineFileType)(filename); if (!fileType) { throw new Error('Unknown file type for file: ' + filename); } metadata[filename] = fileType; } const file = metadata[filename]; const shouldUnpackPath = function (relativePath, unpack, unpackDir) { let shouldUnpack = false; if (unpack) { shouldUnpack = (0, minimatch_1.default)(filename, unpack, { matchBase: true }); } if (!shouldUnpack && unpackDir) { shouldUnpack = isUnpackedDir(relativePath, unpackDir, unpackDirs); } return shouldUnpack; }; let shouldUnpack; switch (file.type) { case 'directory': shouldUnpack = shouldUnpackPath(path.relative(src, filename), undefined, options.unpackDir); filesystem.insertDirectory(filename, shouldUnpack); break; case 'file': shouldUnpack = shouldUnpackPath(path.relative(src, path.dirname(filename)), options.unpack, options.unpackDir); files.push({ filename, unpack: shouldUnpack }); return filesystem.insertFile(filename, () => wrapped_fs_1.default.createReadStream(filename), shouldUnpack, file, options); case 'link': shouldUnpack = shouldUnpackPath(path.relative(src, filename), options.unpack, options.unpackDir); links.push({ filename, unpack: shouldUnpack }); filesystem.insertLink(filename, shouldUnpack); break; } return Promise.resolve(); }; const insertsDone = async function () { await wrapped_fs_1.default.mkdirp(path.dirname(dest)); return disk.writeFilesystem(dest, filesystem, { files, links }, metadata); }; const names = filenamesSorted.slice(); const next = async function (name) { if (!name) { return insertsDone(); } await handleFile(name); return next(names.shift()); }; return next(names.shift()); } /** * Create an ASAR archive from a list of streams. * * @param dest - Archive filename (& path). * @param streams - List of streams to be piped in-memory into asar filesystem. Insertion order is preserved. */ async function createPackageFromStreams(dest, streams) { // We use an ambiguous root `src` since we're piping directly from a stream and the `filePath` for the stream is already relative to the src/root const src = '.'; const filesystem = new filesystem_1.Filesystem(src); const files = []; const links = []; const handleFile = async function (stream) { const { path: destinationPath, type } = stream; const filename = path.normalize(destinationPath); switch (type) { case 'directory': filesystem.insertDirectory(filename, stream.unpacked); break; case 'file': files.push({ filename, streamGenerator: stream.streamGenerator, link: undefined, mode: stream.stat.mode, unpack: stream.unpacked, }); return filesystem.insertFile(filename, stream.streamGenerator, stream.unpacked, { type: 'file', stat: stream.stat, }); case 'link': links.push({ filename, streamGenerator: stream.streamGenerator, link: stream.symlink, mode: stream.stat.mode, unpack: stream.unpacked, }); filesystem.insertLink(filename, stream.unpacked, path.dirname(filename), stream.symlink, src); break; } return Promise.resolve(); }; const insertsDone = async function () { await wrapped_fs_1.default.mkdirp(path.dirname(dest)); return disk.streamFilesystem(dest, filesystem, { files, links }); }; const streamQueue = streams.slice(); const next = async function (stream) { if (!stream) { return insertsDone(); } await handleFile(stream); return next(streamQueue.shift()); }; return next(streamQueue.shift()); } function statFile(archivePath, filename, followLinks = true) { const filesystem = disk.readFilesystemSync(archivePath); return filesystem.getFile(filename, followLinks); } function getRawHeader(archivePath) { return disk.readArchiveHeaderSync(archivePath); } function listPackage(archivePath, options) { return disk.readFilesystemSync(archivePath).listFiles(options); } function extractFile(archivePath, filename, followLinks = true) { const filesystem = disk.readFilesystemSync(archivePath); const fileInfo = filesystem.getFile(filename, followLinks); if ('link' in fileInfo || 'files' in fileInfo) { throw new Error('Expected to find file at: ' + filename + ' but found a directory or link'); } return disk.readFileSync(filesystem, filename, fileInfo); } function extractAll(archivePath, dest) { const filesystem = disk.readFilesystemSync(archivePath); const filenames = filesystem.listFiles(); // under windows just extract links as regular files const followLinks = process.platform === 'win32'; // create destination directory wrapped_fs_1.default.mkdirpSync(dest); const extractionErrors = []; for (const fullPath of filenames) { // Remove leading slash const filename = fullPath.substr(1); const destFilename = path.join(dest, filename); const file = filesystem.getFile(filename, followLinks); if (path.relative(dest, destFilename).startsWith('..')) { throw new Error(`${fullPath}: file "${destFilename}" writes out of the package`); } if ('files' in file) { // it's a directory, create it and continue with the next entry wrapped_fs_1.default.mkdirpSync(destFilename); } else if ('link' in file) { // it's a symlink, create a symlink const linkSrcPath = path.dirname(path.join(dest, file.link)); const linkDestPath = path.dirname(destFilename); const relativePath = path.relative(linkDestPath, linkSrcPath); // try to delete output file, because we can't overwrite a link try { wrapped_fs_1.default.unlinkSync(destFilename); } catch (_a) { } const linkTo = path.join(relativePath, path.basename(file.link)); if (path.relative(dest, linkSrcPath).startsWith('..')) { throw new Error(`${fullPath}: file "${file.link}" links out of the package to "${linkSrcPath}"`); } wrapped_fs_1.default.symlinkSync(linkTo, destFilename); } else { // it's a file, try to extract it try { const content = disk.readFileSync(filesystem, filename, file); wrapped_fs_1.default.writeFileSync(destFilename, content); if (file.executable) { wrapped_fs_1.default.chmodSync(destFilename, '755'); } } catch (e) { extractionErrors.push(e); } } } if (extractionErrors.length) { throw new Error('Unable to extract some files:\n\n' + extractionErrors.map((error) => error.stack).join('\n\n')); } } function uncache(archivePath) { return disk.uncacheFilesystem(archivePath); } function uncacheAll() { disk.uncacheAll(); } // Export everything in default, too exports.default = { createPackage, createPackageWithOptions, createPackageFromFiles, createPackageFromStreams, statFile, getRawHeader, listPackage, extractFile, extractAll, uncache, uncacheAll, }; //# sourceMappingURL=asar.js.map{"version":3,"file":"asar.js","sourceRoot":"","sources":["../src/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IACX,WAAW;IACX,UAAU;IACV,OAAO;IACP,UAAU;CACX,CAAC"}"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.determineFileType = determineFileType; exports.crawl = crawl; const util_1 = require("util"); const glob_1 = require("glob"); const wrapped_fs_1 = __importDefault(require("./wrapped-fs")); const path = __importStar(require("path")); const glob = (0, util_1.promisify)(glob_1.glob); async function determineFileType(filename) { const stat = await wrapped_fs_1.default.lstat(filename); if (stat.isFile()) { return { type: 'file', stat }; } else if (stat.isDirectory()) { return { type: 'directory', stat }; } else if (stat.isSymbolicLink()) { return { type: 'link', stat }; } return null; } async function crawl(dir, options) { const metadata = {}; const crawled = await glob(dir, options); const results = await Promise.all(crawled.map(async (filename) => [filename, await determineFileType(filename)])); const links = []; const filenames = results .map(([filename, type]) => { if (type) { metadata[filename] = type; if (type.type === 'link') links.push(filename); } return filename; }) .filter((filename) => { // Newer glob can return files inside symlinked directories, to avoid // those appearing in archives we need to manually exclude theme here const exactLinkIndex = links.findIndex((link) => filename === link); return links.every((link, index) => { if (index === exactLinkIndex) { return true; } const isFileWithinSymlinkDir = filename.startsWith(link); // symlink may point outside the directory: https://github.com/electron/asar/issues/303 const relativePath = path.relative(link, path.dirname(filename)); return !isFileWithinSymlinkDir || relativePath.startsWith('..'); }); }); return [filenames, metadata]; } //# sourceMappingURL=crawlfs.js.map{"version":3,"file":"crawlfs.js","sourceRoot":"","sources":["../src/crawlfs.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,8CAUC;AAED,sBA8BC;AA7DD,+BAAiC;AACjC,+BAAqC;AAErC,8DAA8B;AAE9B,2CAA6B;AAG7B,MAAM,IAAI,GAAG,IAAA,gBAAS,EAAC,WAAK,CAAC,CAAC;AAWvB,KAAK,UAAU,iBAAiB,CAAC,QAAgB;IACtD,MAAM,IAAI,GAAG,MAAM,oBAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACtC,IAAI,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;QAClB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IAChC,CAAC;SAAM,IAAI,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;QAC9B,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC;IACrC,CAAC;SAAM,IAAI,IAAI,CAAC,cAAc,EAAE,EAAE,CAAC;QACjC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IAChC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAEM,KAAK,UAAU,KAAK,CAAC,GAAW,EAAE,OAAiB;IACxD,MAAM,QAAQ,GAAoC,EAAE,CAAC;IACrD,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACzC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAC/B,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC,QAAQ,EAAE,MAAM,iBAAiB,CAAC,QAAQ,CAAC,CAAU,CAAC,CACxF,CAAC;IACF,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,SAAS,GAAG,OAAO;SACtB,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,EAAE;QACxB,IAAI,IAAI,EAAE,CAAC;YACT,QAAQ,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC;YAC1B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM;gBAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACjD,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE;QACnB,qEAAqE;QACrE,qEAAqE;QACrE,MAAM,cAAc,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC;QACpE,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;YACjC,IAAI,KAAK,KAAK,cAAc,EAAE,CAAC;gBAC7B,OAAO,IAAI,CAAC;YACd,CAAC;YACD,MAAM,sBAAsB,GAAG,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YACzD,uFAAuF;YACvF,MAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;YACjE,OAAO,CAAC,sBAAsB,IAAI,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QAClE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IACL,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAU,CAAC;AACxC,CAAC"}"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __asyncValues = (this && this.__asyncValues) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.writeFilesystem = writeFilesystem; exports.streamFilesystem = streamFilesystem; exports.readArchiveHeaderSync = readArchiveHeaderSync; exports.readFilesystemSync = readFilesystemSync; exports.uncacheFilesystem = uncacheFilesystem; exports.uncacheAll = uncacheAll; exports.readFileSync = readFileSync; const path = __importStar(require("path")); const wrapped_fs_1 = __importDefault(require("./wrapped-fs")); const pickle_1 = require("./pickle"); const filesystem_1 = require("./filesystem"); const util_1 = require("util"); const stream = __importStar(require("stream")); const pipeline = (0, util_1.promisify)(stream.pipeline); let filesystemCache = Object.create(null); async function copyFile(dest, src, filename) { const srcFile = path.join(src, filename); const targetFile = path.join(dest, filename); const [content, stats] = await Promise.all([ wrapped_fs_1.default.readFile(srcFile), wrapped_fs_1.default.stat(srcFile), wrapped_fs_1.default.mkdirp(path.dirname(targetFile)), ]); return wrapped_fs_1.default.writeFile(targetFile, content, { mode: stats.mode }); } async function streamTransformedFile(stream, outStream) { return new Promise((resolve, reject) => { stream.pipe(outStream, { end: false }); stream.on('error', reject); stream.on('end', () => resolve()); }); } const writeFileListToStream = async function (dest, filesystem, out, lists, metadata) { const { files, links } = lists; for (const file of files) { if (file.unpack) { // the file should not be packed into archive const filename = path.relative(filesystem.getRootPath(), file.filename); await copyFile(`${dest}.unpacked`, filesystem.getRootPath(), filename); } else { const transformed = metadata[file.filename].transformed; const stream = wrapped_fs_1.default.createReadStream(transformed ? transformed.path : file.filename); await streamTransformedFile(stream, out); } } for (const file of links.filter((f) => f.unpack)) { // the symlink needs to be recreated outside in .unpacked const filename = path.relative(filesystem.getRootPath(), file.filename); const link = await wrapped_fs_1.default.readlink(file.filename); await createSymlink(dest, filename, link); } return out.end(); }; async function writeFilesystem(dest, filesystem, lists, metadata) { const out = await createFilesystemWriteStream(filesystem, dest); return writeFileListToStream(dest, filesystem, out, lists, metadata); } async function streamFilesystem(dest, filesystem, lists) { var _a, e_1, _b, _c; const out = await createFilesystemWriteStream(filesystem, dest); const { files, links } = lists; try { for (var _d = true, files_1 = __asyncValues(files), files_1_1; files_1_1 = await files_1.next(), _a = files_1_1.done, !_a; _d = true) { _c = files_1_1.value; _d = false; const file = _c; // the file should not be packed into archive if (file.unpack) { const targetFile = path.join(`${dest}.unpacked`, file.filename); await wrapped_fs_1.default.mkdirp(path.dirname(targetFile)); const writeStream = wrapped_fs_1.default.createWriteStream(targetFile, { mode: file.mode }); await pipeline(file.streamGenerator(), writeStream); } else { await streamTransformedFile(file.streamGenerator(), out); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = files_1.return)) await _b.call(files_1); } finally { if (e_1) throw e_1.error; } } for (const file of links.filter((f) => f.unpack && f.link)) { // the symlink needs to be recreated outside in .unpacked await createSymlink(dest, file.filename, file.link); } return out.end(); } function readArchiveHeaderSync(archivePath) { const fd = wrapped_fs_1.default.openSync(archivePath, 'r'); let size; let headerBuf; try { const sizeBuf = Buffer.alloc(8); if (wrapped_fs_1.default.readSync(fd, sizeBuf, 0, 8, null) !== 8) { throw new Error('Unable to read header size'); } const sizePickle = pickle_1.Pickle.createFromBuffer(sizeBuf); size = sizePickle.createIterator().readUInt32(); headerBuf = Buffer.alloc(size); if (wrapped_fs_1.default.readSync(fd, headerBuf, 0, size, null) !== size) { throw new Error('Unable to read header'); } } finally { wrapped_fs_1.default.closeSync(fd); } const headerPickle = pickle_1.Pickle.createFromBuffer(headerBuf); const header = headerPickle.createIterator().readString(); return { headerString: header, header: JSON.parse(header), headerSize: size }; } function readFilesystemSync(archivePath) { if (!filesystemCache[archivePath]) { const header = readArchiveHeaderSync(archivePath); const filesystem = new filesystem_1.Filesystem(archivePath); filesystem.setHeader(header.header, header.headerSize); filesystemCache[archivePath] = filesystem; } return filesystemCache[archivePath]; } function uncacheFilesystem(archivePath) { if (filesystemCache[archivePath]) { filesystemCache[archivePath] = undefined; return true; } return false; } function uncacheAll() { filesystemCache = {}; } function readFileSync(filesystem, filename, info) { let buffer = Buffer.alloc(info.size); if (info.size <= 0) { return buffer; } if (info.unpacked) { // it's an unpacked file, copy it. buffer = wrapped_fs_1.default.readFileSync(path.join(`${filesystem.getRootPath()}.unpacked`, filename)); } else { // Node throws an exception when reading 0 bytes into a 0-size buffer, // so we short-circuit the read in this case. const fd = wrapped_fs_1.default.openSync(filesystem.getRootPath(), 'r'); try { const offset = 8 + filesystem.getHeaderSize() + parseInt(info.offset); wrapped_fs_1.default.readSync(fd, buffer, 0, info.size, offset); } finally { wrapped_fs_1.default.closeSync(fd); } } return buffer; } async function createFilesystemWriteStream(filesystem, dest) { const headerPickle = pickle_1.Pickle.createEmpty(); headerPickle.writeString(JSON.stringify(filesystem.getHeader())); const headerBuf = headerPickle.toBuffer(); const sizePickle = pickle_1.Pickle.createEmpty(); sizePickle.writeUInt32(headerBuf.length); const sizeBuf = sizePickle.toBuffer(); const out = wrapped_fs_1.default.createWriteStream(dest); await new Promise((resolve, reject) => { out.on('error', reject); out.write(sizeBuf); return out.write(headerBuf, () => resolve()); }); return out; } async function createSymlink(dest, filepath, link) { // if symlink is within subdirectories, then we need to recreate dir structure await wrapped_fs_1.default.mkdirp(path.join(`${dest}.unpacked`, path.dirname(filepath))); // create symlink within unpacked dir await wrapped_fs_1.default.symlink(link, path.join(`${dest}.unpacked`, filepath)).catch(async (error) => { if (error.code === 'EPERM' && error.syscall === 'symlink') { throw new Error('Could not create symlinks for unpacked assets. On Windows, consider activating Developer Mode to allow non-admin users to create symlinks by following the instructions at https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development.'); } throw error; }); } //# sourceMappingURL=disk.js.map{"version":3,"file":"disk.js","sourceRoot":"","sources":["../src/disk.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsFA,0CAQC;AAED,4CAyBC;AAsBD,sDAuBC;AAED,gDAQC;AAED,8CAMC;AAED,gCAEC;AAED,oCAoBC;AAlND,2CAA6B;AAC7B,8DAA8B;AAC9B,qCAAkC;AAClC,6CAA+D;AAG/D,+BAAiC;AACjC,+CAAiC;AAEjC,MAAM,QAAQ,GAAG,IAAA,gBAAS,EAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAE5C,IAAI,eAAe,GAA2C,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAElF,KAAK,UAAU,QAAQ,CAAC,IAAY,EAAE,GAAW,EAAE,QAAgB;IACjE,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IACzC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAA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AC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACpF,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;YAC1D,MAAM,IAAI,KAAK,CACb,0QAA0Q,CAC3Q,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC"}"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Filesystem = void 0; const os = __importStar(require("os")); const path = __importStar(require("path")); const util_1 = require("util"); const stream = __importStar(require("stream")); const integrity_1 = require("./integrity"); const wrapped_fs_1 = __importDefault(require("./wrapped-fs")); const UINT32_MAX = 2 ** 32 - 1; const pipeline = (0, util_1.promisify)(stream.pipeline); class Filesystem { constructor(src) { this.src = path.resolve(src); this.header = { files: Object.create(null) }; this.headerSize = 0; this.offset = BigInt(0); } getRootPath() { return this.src; } getHeader() { return this.header; } getHeaderSize() { return this.headerSize; } setHeader(header, headerSize) { this.header = header; this.headerSize = headerSize; } searchNodeFromDirectory(p) { let json = this.header; const dirs = p.split(path.sep); for (const dir of dirs) { if (dir !== '.') { if ('files' in json) { if (!json.files[dir]) { json.files[dir] = { files: Object.create(null) }; } json = json.files[dir]; } else { throw new Error('Unexpected directory state while traversing: ' + p); } } } return json; } searchNodeFromPath(p) { p = path.relative(this.src, p); if (!p) { return this.header; } const name = path.basename(p); const node = this.searchNodeFromDirectory(path.dirname(p)); if (!node.files) { node.files = Object.create(null); } if (!node.files[name]) { node.files[name] = Object.create(null); } return node.files[name]; } insertDirectory(p, shouldUnpack) { const node = this.searchNodeFromPath(p); if (shouldUnpack) { node.unpacked = shouldUnpack; } node.files = node.files || Object.create(null); return node.files; } async insertFile(p, streamGenerator, shouldUnpack, file, options = {}) { const dirNode = this.searchNodeFromPath(path.dirname(p)); const node = this.searchNodeFromPath(p); if (shouldUnpack || dirNode.unpacked) { node.size = file.stat.size; node.unpacked = true; node.integrity = await (0, integrity_1.getFileIntegrity)(streamGenerator()); return Promise.resolve(); } let size; const transformed = options.transform && options.transform(p); if (transformed) { const tmpdir = await wrapped_fs_1.default.mkdtemp(path.join(os.tmpdir(), 'asar-')); const tmpfile = path.join(tmpdir, path.basename(p)); const out = wrapped_fs_1.default.createWriteStream(tmpfile); await pipeline(streamGenerator(), transformed, out); file.transformed = { path: tmpfile, stat: await wrapped_fs_1.default.lstat(tmpfile), }; size = file.transformed.stat.size; } else { size = file.stat.size; } // JavaScript cannot precisely present integers >= UINT32_MAX. if (size > UINT32_MAX) { throw new Error(`${p}: file size can not be larger than 4.2GB`); } node.size = size; node.offset = this.offset.toString(); node.integrity = await (0, integrity_1.getFileIntegrity)(streamGenerator()); if (process.platform !== 'win32' && file.stat.mode & 0o100) { node.executable = true; } this.offset += BigInt(size); } insertLink(p, shouldUnpack, parentPath = wrapped_fs_1.default.realpathSync(path.dirname(p)), symlink = wrapped_fs_1.default.readlinkSync(p), // /var/tmp => /private/var src = wrapped_fs_1.default.realpathSync(this.src)) { const link = this.resolveLink(src, parentPath, symlink); if (link.startsWith('..')) { throw new Error(`${p}: file "${link}" links out of the package`); } const node = this.searchNodeFromPath(p); const dirNode = this.searchNodeFromPath(path.dirname(p)); if (shouldUnpack || dirNode.unpacked) { node.unpacked = true; } node.link = link; return link; } resolveLink(src, parentPath, symlink) { const target = path.join(parentPath, symlink); const link = path.relative(src, target); return link; } listFiles(options) { const files = []; const fillFilesFromMetadata = function (basePath, metadata) { if (!('files' in metadata)) { return; } for (const [childPath, childMetadata] of Object.entries(metadata.files)) { const fullPath = path.join(basePath, childPath); const packState = 'unpacked' in childMetadata && childMetadata.unpacked ? 'unpack' : 'pack '; files.push(options && options.isPack ? `${packState} : ${fullPath}` : fullPath); fillFilesFromMetadata(fullPath, childMetadata); } }; fillFilesFromMetadata('/', this.header); return files; } getNode(p, followLinks = true) { const node = this.searchNodeFromDirectory(path.dirname(p)); const name = path.basename(p); if ('link' in node && followLinks) { return this.getNode(path.join(node.link, name)); } if (name) { return node.files[name]; } else { return node; } } getFile(p, followLinks = true) { const info = this.getNode(p, followLinks); if (!info) { throw new Error(`"${p}" was not found in this archive`); } // if followLinks is false we don't resolve symlinks if ('link' in info && followLinks) { return this.getFile(info.link, followLinks); } else { return info; } } } exports.Filesystem = Filesystem; //# sourceMappingURL=filesystem.js.map{"version":3,"file":"filesystem.js","sourceRoot":"","sources":["../src/filesystem.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAC7B,+BAAiC;AACjC,+CAAiC;AAEjC,2CAA8D;AAC9D,8DAA8B;AAG9B,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AAE/B,MAAM,QAAQ,GAAG,IAAA,gBAAS,EAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAwB5C,MAAa,UAAU;I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BAAqB,CAAC,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,CAAS,EAAE,cAAuB,IAAI;QAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3D,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC9B,IAAI,MAAM,IAAI,IAAI,IAAI,WAAW,EAAE,CAAC;YAClC,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;QAClD,CAAC;QACD,IAAI,IAAI,EAAE,CAAC;YACT,OAAQ,IAAiC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACxD,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,CAAC,CAAS,EAAE,cAAuB,IAAI;QAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC;QAE1C,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,iCAAiC,CAAC,CAAC;QAC1D,CAAC;QAED,oDAAoD;QACpD,IAAI,MAAM,IAAI,IAAI,IAAI,WAAW,EAAE,CAAC;YAClC,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QAC9C,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF;AArMD,gCAqMC"}"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getFileIntegrity = getFileIntegrity; const crypto = __importStar(require("crypto")); const stream = __importStar(require("stream")); const util_1 = require("util"); const ALGORITHM = 'SHA256'; // 4MB default block size const BLOCK_SIZE = 4 * 1024 * 1024; const pipeline = (0, util_1.promisify)(stream.pipeline); function hashBlock(block) { return crypto.createHash(ALGORITHM).update(block).digest('hex'); } async function getFileIntegrity(inputFileStream) { const fileHash = crypto.createHash(ALGORITHM); const blockHashes = []; let currentBlockSize = 0; let currentBlock = []; await pipeline(inputFileStream, new stream.PassThrough({ decodeStrings: false, transform(_chunk, encoding, callback) { fileHash.update(_chunk); function handleChunk(chunk) { const diffToSlice = Math.min(BLOCK_SIZE - currentBlockSize, chunk.byteLength); currentBlockSize += diffToSlice; currentBlock.push(chunk.slice(0, diffToSlice)); if (currentBlockSize === BLOCK_SIZE) { blockHashes.push(hashBlock(Buffer.concat(currentBlock))); currentBlock = []; currentBlockSize = 0; } if (diffToSlice < chunk.byteLength) { handleChunk(chunk.slice(diffToSlice)); } } handleChunk(_chunk); callback(); }, flush(callback) { blockHashes.push(hashBlock(Buffer.concat(currentBlock))); currentBlock = []; callback(); }, })); return { algorithm: ALGORITHM, hash: fileHash.digest('hex'), blockSize: BLOCK_SIZE, blocks: blockHashes, }; } //# sourceMappingURL=integrity.js.map{"version":3,"file":"integrity.js","sourceRoot":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AC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;oBACzD,YAAY,GAAG,EAAE,CAAC;oBAClB,gBAAgB,GAAG,CAAC,CAAC;gBACvB,CAAC;gBACD,IAAI,WAAW,GAAG,KAAK,CAAC,UAAU,EAAE,CAAC;oBACnC,WAAW,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;gBACxC,CAAC;YACH,CAAC;YACD,WAAW,CAAC,MAAM,CAAC,CAAC;YACpB,QAAQ,EAAE,CAAC;QACb,CAAC;QACD,KAAK,CAAC,QAAQ;YACZ,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;YACzD,YAAY,GAAG,EAAE,CAAC;YAClB,QAAQ,EAAE,CAAC;QACb,CAAC;KACF,CAAC,CACH,CAAC;IAEF,OAAO;QACL,SAAS,EAAE,SAAS;QACpB,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC;QAC5B,SAAS,EAAE,UAAU;QACrB,MAAM,EAAE,WAAW;KACpB,CAAC;AACJ,CAAC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Pickle = void 0; // sizeof(T). const SIZE_INT32 = 4; const SIZE_UINT32 = 4; const SIZE_INT64 = 8; const SIZE_UINT64 = 8; const SIZE_FLOAT = 4; const SIZE_DOUBLE = 8; // The allocation granularity of the payload. const PAYLOAD_UNIT = 64; // Largest JS number. const CAPACITY_READ_ONLY = 9007199254740992; // Aligns 'i' by rounding it up to the next multiple of 'alignment'. const alignInt = function (i, alignment) { return i + ((alignment - (i % alignment)) % alignment); }; // PickleIterator reads data from a Pickle. The Pickle object must remain valid // while the PickleIterator object is in use. class PickleIterator { constructor(pickle) { this.payload = pickle.getHeader(); this.payloadOffset = pickle.getHeaderSize(); this.readIndex = 0; this.endIndex = pickle.getPayloadSize(); } readBool() { return this.readInt() !== 0; } readInt() { return this.readBytes(SIZE_INT32, Buffer.prototype.readInt32LE); } readUInt32() { return this.readBytes(SIZE_UINT32, Buffer.prototype.readUInt32LE); } readInt64() { return this.readBytes(SIZE_INT64, Buffer.prototype.readBigInt64LE); } readUInt64() { return this.readBytes(SIZE_UINT64, Buffer.prototype.readBigUInt64LE); } readFloat() { return this.readBytes(SIZE_FLOAT, Buffer.prototype.readFloatLE); } readDouble() { return this.readBytes(SIZE_DOUBLE, Buffer.prototype.readDoubleLE); } readString() { return this.readBytes(this.readInt()).toString(); } readBytes(length, method) { const readPayloadOffset = this.getReadPayloadOffsetAndAdvance(length); if (method != null) { return method.call(this.payload, readPayloadOffset, length); } else { return this.payload.slice(readPayloadOffset, readPayloadOffset + length); } } getReadPayloadOffsetAndAdvance(length) { if (length > this.endIndex - this.readIndex) { this.readIndex = this.endIndex; throw new Error('Failed to read data with length of ' + length); } const readPayloadOffset = this.payloadOffset + this.readIndex; this.advance(length); return readPayloadOffset; } advance(size) { const alignedSize = alignInt(size, SIZE_UINT32); if (this.endIndex - this.readIndex < alignedSize) { this.readIndex = this.endIndex; } else { this.readIndex += alignedSize; } } } // This class provides facilities for basic binary value packing and unpacking. // // The Pickle class supports appending primitive values (ints, strings, etc.) // to a pickle instance. The Pickle instance grows its internal memory buffer // dynamically to hold the sequence of primitive values. The internal memory // buffer is exposed as the "data" of the Pickle. This "data" can be passed // to a Pickle object to initialize it for reading. // // When reading from a Pickle object, it is important for the consumer to know // what value types to read and in what order to read them as the Pickle does // not keep track of the type of data written to it. // // The Pickle's data has a header which contains the size of the Pickle's // payload. It can optionally support additional space in the header. That // space is controlled by the header_size parameter passed to the Pickle // constructor. class Pickle { constructor(buffer) { if (buffer) { this.header = buffer; this.headerSize = buffer.length - this.getPayloadSize(); this.capacityAfterHeader = CAPACITY_READ_ONLY; this.writeOffset = 0; if (this.headerSize > buffer.length) { this.headerSize = 0; } if (this.headerSize !== alignInt(this.headerSize, SIZE_UINT32)) { this.headerSize = 0; } if (this.headerSize === 0) { this.header = Buffer.alloc(0); } } else { this.header = Buffer.alloc(0); this.headerSize = SIZE_UINT32; this.capacityAfterHeader = 0; this.writeOffset = 0; this.resize(PAYLOAD_UNIT); this.setPayloadSize(0); } } static createEmpty() { return new Pickle(); } static createFromBuffer(buffer) { return new Pickle(buffer); } getHeader() { return this.header; } getHeaderSize() { return this.headerSize; } createIterator() { return new PickleIterator(this); } toBuffer() { return this.header.slice(0, this.headerSize + this.getPayloadSize()); } writeBool(value) { return this.writeInt(value ? 1 : 0); } writeInt(value) { return this.writeBytes(value, SIZE_INT32, Buffer.prototype.writeInt32LE); } writeUInt32(value) { return this.writeBytes(value, SIZE_UINT32, Buffer.prototype.writeUInt32LE); } writeInt64(value) { return this.writeBytes(BigInt(value), SIZE_INT64, Buffer.prototype.writeBigInt64LE); } writeUInt64(value) { return this.writeBytes(BigInt(value), SIZE_UINT64, Buffer.prototype.writeBigUInt64LE); } writeFloat(value) { return this.writeBytes(value, SIZE_FLOAT, Buffer.prototype.writeFloatLE); } writeDouble(value) { return this.writeBytes(value, SIZE_DOUBLE, Buffer.prototype.writeDoubleLE); } writeString(value) { const length = Buffer.byteLength(value, 'utf8'); if (!this.writeInt(length)) { return false; } return this.writeBytes(value, length); } setPayloadSize(payloadSize) { return this.header.writeUInt32LE(payloadSize, 0); } getPayloadSize() { return this.header.readUInt32LE(0); } writeBytes(data, length, method) { const dataLength = alignInt(length, SIZE_UINT32); const newSize = this.writeOffset + dataLength; if (newSize > this.capacityAfterHeader) { this.resize(Math.max(this.capacityAfterHeader * 2, newSize)); } if (method) { method.call(this.header, data, this.headerSize + this.writeOffset); } else { this.header.write(data, this.headerSize + this.writeOffset, length); } const endOffset = this.headerSize + this.writeOffset + length; this.header.fill(0, endOffset, endOffset + dataLength - length); this.setPayloadSize(newSize); this.writeOffset = newSize; return true; } resize(newCapacity) { newCapacity = alignInt(newCapacity, PAYLOAD_UNIT); this.header = Buffer.concat([this.header, Buffer.alloc(newCapacity)]); this.capacityAfterHeader = newCapacity; } } exports.Pickle = Pickle; //# sourceMappingURL=pickle.js.map{"version":3,"file":"pickle.js","sourceRoot":"","sources":["../src/pickle.ts"],"names":[],"mappings":";;;AAAA,aAAa;AACb,MAAM,UAAU,GAAG,CAAC,CAAC;AACrB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,UAAU,GAAG,CAAC,CAAC;AACrB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,UAAU,GAAG,CAAC,CAAC;AACrB,MAAM,WAAW,GAAG,CAAC,CAAC;AAEtB,6CAA6C;AAC7C,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB,qBAAqB;AACrB,MAAM,kBAAkB,GAAG,gBAAgB,CAAC;AAE5C,oEAAoE;AACpE,MAAM,QAAQ,GAAG,UAAU,CAAS,EAAE,SAAiB;IACrD,OAAO,CAAC,GAAG,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;AACzD,CAAC,CAAC;AAEF,+EAA+E;AAC/E,6CAA6C;AAC7C,MAAM,cAAc;IAMlB,YAAY,MAAc;QACxB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;QAClC,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,aAAa,EAAE,CAAC;QAC5C,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC;QACnB,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,cAAc,EAAE,CAAC;IAC1C,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;IAClE,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,CAAC,SAAS,CAAC,YAAY,CAAC,C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AAI,CAAC,mBAAmB,GAAG,WAAW,CAAC;IACzC,CAAC;CACF;AA5HD,wBA4HC"}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=glob.js.map{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/types/glob.ts"],"names":[],"mappings":""}"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fs = 'electron' in process.versions ? require('original-fs') : require('fs'); const promisifiedMethods = [ 'lstat', 'mkdtemp', 'readFile', 'stat', 'writeFile', 'symlink', 'readlink', ]; const promisified = {}; for (const method of Object.keys(fs)) { if (promisifiedMethods.includes(method)) { promisified[method] = fs.promises[method]; } else { promisified[method] = fs[method]; } } // To make it more like fs-extra promisified.mkdirp = (dir) => fs.promises.mkdir(dir, { recursive: true }); promisified.mkdirpSync = (dir) => fs.mkdirSync(dir, { recursive: true }); exports.default = promisified; //# sourceMappingURL=wrapped-fs.js.map{"version":3,"file":"wrapped-fs.js","sourceRoot":"","sources":["../src/wrapped-fs.ts"],"names":[],"mappings":";;AAAA,MAAM,EAAE,GAAG,UAAU,IAAI,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AAEnF,MAAM,kBAAkB,GAAG;IACzB,OAAO;IACP,SAAS;IACT,UAAU;IACV,MAAM;IACN,WAAW;IACX,SAAS;IACT,UAAU;CACX,CAAC;AAcF,MAAM,WAAW,GAAG,EAAY,CAAC;AAEjC,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC;IACrC,IAAI,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACvC,WAAmB,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrD,CAAC;SAAM,CAAC;QACL,WAAmB,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,CAAC;IAC5C,CAAC;AACH,CAAC;AACD,gCAAgC;AAChC,WAAW,CAAC,MAAM,GAAG,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAC1E,WAAW,CAAC,UAAU,GAAG,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAEzE,kBAAe,WAAW,CAAC"}{ "name": "@electron/asar", "description": "Creating Electron app packages", "version": "3.4.1", "main": "./lib/asar.js", "types": "./lib/asar.d.ts", "bin": { "asar": "./bin/asar.js" }, "files": [ "bin", "lib" ], "engines": { "node": ">=10.12.0" }, "license": "MIT", "homepage": "https://github.com/electron/asar", "repository": { "type": "git", "url": "git+https://github.com/electron/asar.git" }, "publishConfig": { "provenance": true }, "dependencies": { "commander": "^5.0.0", "glob": "^7.1.6", "minimatch": "^3.0.4" }, "devDependencies": { "@types/minimatch": "^3.0.5", "@types/node": "^12.0.0", "chai": "^4.5.0", "electron": "^22.0.0", "electron-mocha": "^13.0.1", "lodash": "^4.17.15", "mocha": "^10.1.0", "mocha-chai-jest-snapshot": "^1.1.6", "prettier": "^3.3.3", "rimraf": "^3.0.2", "typescript": "^5.5.4", "xvfb-maybe": "^0.2.1" } }MIT License Copyright (c) Emotion team and other contributors 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. 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var memoize = _interopDefault(require('@emotion/memoize')); var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 var index = memoize(function (prop) { return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111 /* o */ && prop.charCodeAt(1) === 110 /* n */ && prop.charCodeAt(2) < 91; } /* Z+1 */ ); exports.default = index; import memoize from '@emotion/memoize'; var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 var index = memoize(function (prop) { return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111 /* o */ && prop.charCodeAt(1) === 110 /* n */ && prop.charCodeAt(2) < 91; } /* Z+1 */ ); export default index; 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var memoize = _interopDefault(require('@emotion/memoize')); var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 var index = memoize(function (prop) { return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111 /* o */ && prop.charCodeAt(1) === 110 /* n */ && prop.charCodeAt(2) < 91; } /* Z+1 */ ); exports.default = index; 'use strict'; if (process.env.NODE_ENV === "production") { module.exports = require("./is-prop-valid.cjs.prod.js"); } else { module.exports = require("./is-prop-valid.cjs.dev.js"); } // @flow export * from "../src/index.js"; export { default } from "../src/index.js"; "use strict"; function _interopDefault(ex) { return ex && "object" == typeof ex && "default" in ex ? ex.default : ex; } Object.defineProperty(exports, "__esModule", { value: !0 }); var memoize = _interopDefault(require("@emotion/memoize")), reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/, index = memoize(function(prop) { return reactPropsRegex.test(prop) || 111 === prop.charCodeAt(0) && 110 === prop.charCodeAt(1) && prop.charCodeAt(2) < 91; }); exports.default = index; import memoize from '@emotion/memoize'; var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 var index = memoize(function (prop) { return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111 /* o */ && prop.charCodeAt(1) === 110 /* n */ && prop.charCodeAt(2) < 91; } /* Z+1 */ ); export default index; // @flow import memoize from '@emotion/memoize' declare var codegen: { require: string => RegExp } const reactPropsRegex = codegen.require('./props') // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 export default memoize( prop => reactPropsRegex.test(prop) || (prop.charCodeAt(0) === 111 /* o */ && prop.charCodeAt(1) === 110 /* n */ && prop.charCodeAt(2) < 91) /* Z+1 */ ) // @flow const props = { // react props // https://github.com/facebook/react/blob/5495a7f24aef85ba6937truetrue1ce962673ca9f5fde6/src/renderers/dom/shared/hooks/ReactDOMUnknownPropertyHook.js children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, defaultChecked: true, innerHTML: true, suppressContentEditableWarning: true, suppressHydrationWarning: true, // deprecated react prop valueLink: true, // https://github.com/facebook/react/blob/d7157651f7b72d9888ctrue123e191f9b88cd8f41e9/src/renderers/dom/shared/HTMLDOMPropertyConfig.js /** * Standard Properties */ accept: true, acceptCharset: true, accessKey: true, action: true, allow: true, allowUserMedia: true, allowPaymentRequest: true, allowFullScreen: true, allowTransparency: true, alt: true, // specifies target context for links with `preload` type // as: true, async: true, autoComplete: true, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: true, autoPlay: true, capture: true, cellPadding: true, cellSpacing: true, // keygen prop challenge: true, charSet: true, checked: true, cite: true, classID: true, className: true, cols: true, colSpan: true, content: true, contentEditable: true, contextMenu: true, controls: true, controlsList: true, coords: true, crossOrigin: true, data: true, // For `` acts as `src`. dateTime: true, decoding: true, default: true, defer: true, dir: true, disabled: true, disablePictureInPicture: true, download: true, draggable: true, encType: true, form: true, formAction: true, formEncType: true, formMethod: true, formNoValidate: true, formTarget: true, frameBorder: true, headers: true, height: true, hidden: true, high: true, href: true, hrefLang: true, htmlFor: true, httpEquiv: true, id: true, inputMode: true, integrity: true, is: true, keyParams: true, keyType: true, kind: true, label: true, lang: true, list: true, loading: true, loop: true, low: true, // manifest: true, marginHeight: true, marginWidth: true, max: true, maxLength: true, media: true, mediaGroup: true, method: true, min: true, minLength: true, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: true, muted: true, name: true, nonce: true, noValidate: true, open: true, optimum: true, pattern: true, placeholder: true, playsInline: true, poster: true, preload: true, profile: true, radioGroup: true, readOnly: true, referrerPolicy: true, rel: true, required: true, reversed: true, role: true, rows: true, rowSpan: true, sandbox: true, scope: true, scoped: true, scrolling: true, seamless: true, selected: true, shape: true, size: true, sizes: true, // support for projecting regular DOM Elements via V1 named slots ( shadow dom ) slot: true, span: true, spellCheck: true, src: true, srcDoc: true, srcLang: true, srcSet: true, start: true, step: true, style: true, summary: true, tabIndex: true, target: true, title: true, // Setting .type throws on non- tags type: true, useMap: true, value: true, width: true, wmode: true, wrap: true, /** * RDFa Properties */ about: true, datatype: true, inlist: true, prefix: true, // property is also supported for OpenGraph in meta tags. property: true, resource: true, typeof: true, vocab: true, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: true, autoCorrect: true, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: true, // color is for Safari mask-icon link color: true, // https://html.spec.whatwg.org/multipage/interaction.html#inert inert: true, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: true, itemScope: true, itemType: true, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: true, itemRef: true, // used in amp html for eventing purposes on: true, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: true, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<1true security: true, // IE-only attribute that controls focus behavior unselectable: true, // // SVG properties: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute // The following "onX" events have been omitted: // // onabort // onactivate // onbegin // onclick // onend // onerror // onfocusin // onfocusout // onload // onmousedown // onmousemove // onmouseout // onmouseover // onmouseup // onrepeat // onresize // onscroll // onunload accentHeight: true, accumulate: true, additive: true, alignmentBaseline: true, allowReorder: true, alphabetic: true, amplitude: true, arabicForm: true, ascent: true, attributeName: true, attributeType: true, autoReverse: true, azimuth: true, baseFrequency: true, baselineShift: true, baseProfile: true, bbox: true, begin: true, bias: true, by: true, calcMode: true, capHeight: true, clip: true, clipPathUnits: true, clipPath: true, clipRule: true, colorInterpolation: true, colorInterpolationFilters: true, colorProfile: true, colorRendering: true, contentScriptType: true, contentStyleType: true, cursor: true, cx: true, cy: true, d: true, decelerate: true, descent: true, diffuseConstant: true, direction: true, display: true, divisor: true, dominantBaseline: true, dur: true, dx: true, dy: true, edgeMode: true, elevation: true, enableBackground: true, end: true, exponent: true, externalResourcesRequired: true, fill: true, fillOpacity: true, fillRule: true, filter: true, filterRes: true, filterUnits: true, floodColor: true, floodOpacity: true, focusable: true, fontFamily: true, fontSize: true, fontSizeAdjust: true, fontStretch: true, fontStyle: true, fontVariant: true, fontWeight: true, format: true, from: true, fr: true, // valid SVG element but React will ask for removal fx: true, fy: true, g1: true, g2: true, glyphName: true, glyphOrientationHorizontal: true, glyphOrientationVertical: true, glyphRef: true, gradientTransform: true, gradientUnits: true, hanging: true, horizAdvX: true, horizOriginX: true, ideographic: true, imageRendering: true, in: true, in2: true, intercept: true, k: true, k1: true, k2: true, k3: true, k4: true, kernelMatrix: true, kernelUnitLength: true, kerning: true, keyPoints: true, keySplines: true, keyTimes: true, lengthAdjust: true, letterSpacing: true, lightingColor: true, limitingConeAngle: true, local: true, markerEnd: true, markerMid: true, markerStart: true, markerHeight: true, markerUnits: true, markerWidth: true, mask: true, maskContentUnits: true, maskUnits: true, mathematical: true, mode: true, numOctaves: true, offset: true, opacity: true, operator: true, order: true, orient: true, orientation: true, origin: true, overflow: true, overlinePosition: true, overlineThickness: true, panose1: true, paintOrder: true, pathLength: true, patternContentUnits: true, patternTransform: true, patternUnits: true, pointerEvents: true, points: true, pointsAtX: true, pointsAtY: true, pointsAtZ: true, preserveAlpha: true, preserveAspectRatio: true, primitiveUnits: true, r: true, radius: true, refX: true, refY: true, renderingIntent: true, repeatCount: true, repeatDur: true, requiredExtensions: true, requiredFeatures: true, restart: true, result: true, rotate: true, rx: true, ry: true, scale: true, seed: true, shapeRendering: true, slope: true, spacing: true, specularConstant: true, specularExponent: true, speed: true, spreadMethod: true, startOffset: true, stdDeviation: true, stemh: true, stemv: true, stitchTiles: true, stopColor: true, stopOpacity: true, strikethroughPosition: true, strikethroughThickness: true, string: true, stroke: true, strokeDasharray: true, strokeDashoffset: true, strokeLinecap: true, strokeLinejoin: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true, surfaceScale: true, systemLanguage: true, tableValues: true, targetX: true, targetY: true, textAnchor: true, textDecoration: true, textRendering: true, textLength: true, to: true, transform: true, u1: true, u2: true, underlinePosition: true, underlineThickness: true, unicode: true, unicodeBidi: true, unicodeRange: true, unitsPerEm: true, vAlphabetic: true, vHanging: true, vIdeographic: true, vMathematical: true, values: true, vectorEffect: true, version: true, vertAdvY: true, vertOriginX: true, vertOriginY: true, viewBox: true, viewTarget: true, visibility: true, widths: true, wordSpacing: true, writingMode: true, x: true, xHeight: true, x1: true, x2: true, xChannelSelector: true, xlinkActuate: true, xlinkArcrole: true, xlinkHref: true, xlinkRole: true, xlinkShow: true, xlinkTitle: true, xlinkType: true, xmlBase: true, xmlns: true, xmlnsXlink: true, xmlLang: true, xmlSpace: true, y: true, y1: true, y2: true, yChannelSelector: true, z: true, zoomAndPan: true, // preact for: true, class: true, autofocus: true } // eslint-disable-next-line import/no-commonjs module.exports = `/^((${Object.keys(props).join( '|' )})|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/` import isPropValid from '@emotion/is-prop-valid' isPropValid('ref') // $ExpectError isPropValid() // $ExpectError isPropValid(5) // $ExpectError isPropValid({}) // $ExpectError isPropValid('ref', 'def') { "compilerOptions": { "baseUrl": "../", "forceConsistentCasingInFileNames": true, "lib": [ "es6", "dom" ], "module": "commonjs", "noEmit": true, "noImplicitAny": true, "noImplicitThis": true, "strict": true, "strictNullChecks": true, "strictFunctionTypes": true, "target": "es5", "typeRoots": [ "../" ], "types": [] }, "include": [ "./*.ts", "./*.tsx" ] } { "extends": "dtslint/dtslint.json", "rules": { "array-type": [ true, "generic" ], "import-spacing": false, "semicolon": false, "whitespace": [ true, "check-branch", "check-decl", "check-operator", "check-module", "check-rest-spread", "check-type", "check-typecast", "check-type-operator", "check-preblock" ], "no-unnecessary-generics": false } } { "name": "@emotion/is-prop-valid", "version": "0.8.8", "description": "A function to check whether a prop is valid for HTML and SVG elements", "main": "dist/is-prop-valid.cjs.js", "module": "dist/is-prop-valid.esm.js", "types": "types/index.d.ts", "license": "MIT", "repository": "https://github.com/emotion-js/emotion/tree/master/packages/is-prop-valid", "publishConfig": { "access": "public" }, "dependencies": { "@emotion/memoize": "0.7.4" }, "devDependencies": { "dtslint": "^0.3.0" }, "files": [ "src", "dist", "types" ], "browser": { "./dist/is-prop-valid.cjs.js": "./dist/is-prop-valid.browser.cjs.js", "./dist/is-prop-valid.esm.js": "./dist/is-prop-valid.browser.esm.js" } }MIT License Copyright (c) Emotion team and other contributors 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. 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function memoize(fn) { var cache = {}; return function (arg) { if (cache[arg] === undefined) cache[arg] = fn(arg); return cache[arg]; }; } exports.default = memoize; function memoize(fn) { var cache = {}; return function (arg) { if (cache[arg] === undefined) cache[arg] = fn(arg); return cache[arg]; }; } export default memoize; 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function memoize(fn) { var cache = {}; return function (arg) { if (cache[arg] === undefined) cache[arg] = fn(arg); return cache[arg]; }; } exports.default = memoize; 'use strict'; if (process.env.NODE_ENV === "production") { module.exports = require("./memoize.cjs.prod.js"); } else { module.exports = require("./memoize.cjs.dev.js"); } // @flow export * from "../src/index.js"; export { default } from "../src/index.js"; "use strict"; function memoize(fn) { var cache = {}; return function(arg) { return void 0 === cache[arg] && (cache[arg] = fn(arg)), cache[arg]; }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.default = memoize; function memoize(fn) { var cache = {}; return function (arg) { if (cache[arg] === undefined) cache[arg] = fn(arg); return cache[arg]; }; } export default memoize; // @flow export default function memoize(fn: string => V): string => V { const cache = {} return (arg: string) => { if (cache[arg] === undefined) cache[arg] = fn(arg) return cache[arg] } } import memoize from '@emotion/memoize' // $ExpectType string[] memoize((arg: string) => [arg])('foo') // $ExpectError memoize((arg: number) => [arg]) { "compilerOptions": { "baseUrl": "../", "forceConsistentCasingInFileNames": true, "lib": [ "es6", "dom" ], "module": "commonjs", "noEmit": true, "noImplicitAny": true, "noImplicitThis": true, "strict": true, "strictNullChecks": true, "strictFunctionTypes": true, "target": "es5", "typeRoots": [ "../" ], "types": [] }, "include": [ "./*.ts", "./*.tsx" ] } { "extends": "dtslint/dtslint.json", "rules": { "array-type": [ true, "generic" ], "import-spacing": false, "semicolon": false, "whitespace": [ true, "check-branch", "check-decl", "check-operator", "check-module", "check-rest-spread", "check-type", "check-typecast", "check-type-operator", "check-preblock" ], "no-unnecessary-generics": false } } { "name": "@emotion/memoize", "version": "0.7.4", "description": "emotion's memoize utility", "main": "dist/memoize.cjs.js", "module": "dist/memoize.esm.js", "types": "types/index.d.ts", "license": "MIT", "repository": "https://github.com/emotion-js/emotion/tree/master/packages/memoize", "publishConfig": { "access": "public" }, "devDependencies": { "dtslint": "^0.3.0" }, "files": [ "src", "dist", "types" ], "browser": { "./dist/memoize.cjs.js": "./dist/memoize.browser.cjs.js", "./dist/memoize.esm.js": "./dist/memoize.browser.esm.js" } }MIT License Copyright (c) 2021-present Floating UI contributors 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. const t=["top","right","bottom","left"],e=["start","end"],n=t.reduce(((t,n)=>t.concat(n,n+"-"+e[0],n+"-"+e[1])),[]),i=Math.min,r=Math.max,o={left:"right",right:"left",bottom:"top",top:"bottom"},a={start:"end",end:"start"};function l(t,e,n){return r(t,i(e,n))}function s(t,e){return"function"==typeof t?t(e):t}function c(t){return t.split("-")[0]}function f(t){return t.split("-")[1]}function m(t){return"x"===t?"y":"x"}function u(t){return"y"===t?"height":"width"}function d(t){return["top","bottom"].includes(c(t))?"y":"x"}function g(t){return m(d(t))}function p(t,e,n){void 0===n&&(n=!1);const i=f(t),r=g(t),o=u(r);let a="x"===r?i===(n?"end":"start")?"right":"left":"start"===i?"bottom":"top";return e.reference[o]>e.floating[o]&&(a=y(a)),[a,y(a)]}function h(t){return t.replace(/start|end/g,(t=>a[t]))}function y(t){return t.replace(/left|right|bottom|top/g,(t=>o[t]))}function w(t){return"number"!=typeof t?function(t){return{top:0,right:0,bottom:0,left:0,...t}}(t):{top:t,right:t,bottom:t,left:t}}function x(t){const{x:e,y:n,width:i,height:r}=t;return{width:i,height:r,top:n,left:e,right:e+i,bottom:n+r,x:e,y:n}}function v(t,e,n){let{reference:i,floating:r}=t;const o=d(e),a=g(e),l=u(a),s=c(e),m="y"===o,p=i.x+i.width/2-r.width/2,h=i.y+i.height/2-r.height/2,y=i[l]/2-r[l]/2;let w;switch(s){case"top":w={x:p,y:i.y-r.height};break;case"bottom":w={x:p,y:i.y+i.height};break;case"right":w={x:i.x+i.width,y:h};break;case"left":w={x:i.x-r.width,y:h};break;default:w={x:i.x,y:i.y}}switch(f(e)){case"start":w[a]-=y*(n&&m?-1:1);break;case"end":w[a]+=y*(n&&m?-1:1)}return w}const b=async(t,e,n)=>{const{placement:i="bottom",strategy:r="absolute",middleware:o=[],platform:a}=n,l=o.filter(Boolean),s=await(null==a.isRTL?void 0:a.isRTL(e));let c=await a.getElementRects({reference:t,floating:e,strategy:r}),{x:f,y:m}=v(c,i,s),u=i,d={},g=0;for(let n=0;n({name:"arrow",options:t,async fn(e){const{x:n,y:r,placement:o,rects:a,platform:c,elements:m,middlewareData:d}=e,{element:p,padding:h=0}=s(t,e)||{};if(null==p)return{};const y=w(h),x={x:n,y:r},v=g(o),b=u(v),A=await c.getDimensions(p),R="y"===v,D=R?"top":"left",P=R?"bottom":"right",E=R?"clientHeight":"clientWidth",O=a.reference[b]+a.reference[v]-x[v]-a.floating[b],T=x[v]-a.reference[v],L=await(null==c.getOffsetParent?void 0:c.getOffsetParent(p));let k=L?L[E]:0;k&&await(null==c.isElement?void 0:c.isElement(L))||(k=m.floating[E]||a.floating[b]);const B=O/2-T/2,C=k/2-A[b]/2-1,H=i(y[D],C),S=i(y[P],C),F=H,M=k-A[b]-S,V=k/2-A[b]/2+B,W=l(F,V,M),j=!d.arrow&&null!=f(o)&&V!==W&&a.reference[b]/2-(Vf(e)===t)),...n.filter((e=>f(e)!==t))]:n.filter((t=>c(t)===t))).filter((n=>!t||f(n)===t||!!e&&h(n)!==n))}(y||null,x,w):w,R=await A(e,v),D=(null==(i=l.autoPlacement)?void 0:i.index)||0,P=b[D];if(null==P)return{};const E=p(P,a,await(null==u.isRTL?void 0:u.isRTL(d.floating)));if(m!==P)return{reset:{placement:b[0]}};const O=[R[c(P)],R[E[0]],R[E[1]]],T=[...(null==(r=l.autoPlacement)?void 0:r.overflows)||[],{placement:P,overflows:O}],L=b[D+1];if(L)return{data:{index:D+1,overflows:T},reset:{placement:L}};const k=T.map((t=>{const e=f(t.placement);return[t.placement,e&&g?t.overflows.slice(0,2).reduce(((t,e)=>t+e),0):t.overflows[0],t.overflows]})).sort(((t,e)=>t[1]-e[1])),B=(null==(o=k.filter((t=>t[2].slice(0,f(t[0])?2:3).every((t=>t<=0))))[0])?void 0:o[0])||k[0][0];return B!==m?{data:{index:D+1,overflows:T},reset:{placement:B}}:{}}}},P=function(t){return void 0===t&&(t={}),{name:"flip",options:t,async fn(e){var n,i;const{placement:r,middlewareData:o,rects:a,initialPlacement:l,platform:m,elements:u}=e,{mainAxis:g=!0,crossAxis:w=!0,fallbackPlacements:x,fallbackStrategy:v="bestFit",fallbackAxisSideDirection:b="none",flipAlignment:R=!0,...D}=s(t,e);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const P=c(r),E=d(l),O=c(l)===l,T=await(null==m.isRTL?void 0:m.isRTL(u.floating)),L=x||(O||!R?[y(l)]:function(t){const e=y(t);return[h(t),e,h(e)]}(l)),k="none"!==b;!x&&k&&L.push(...function(t,e,n,i){const r=f(t);let o=function(t,e,n){const i=["left","right"],r=["right","left"],o=["top","bottom"],a=["bottom","top"];switch(t){case"top":case"bottom":return n?e?r:i:e?i:r;case"left":case"right":return e?o:a;default:return[]}}(c(t),"start"===n,i);return r&&(o=o.map((t=>t+"-"+r)),e&&(o=o.concat(o.map(h)))),o}(l,R,b,T));const B=[l,...L],C=await A(e,D),H=[];let S=(null==(i=o.flip)?void 0:i.overflows)||[];if(g&&H.push(C[P]),w){const t=p(r,a,T);H.push(C[t[0]],C[t[1]])}if(S=[...S,{placement:r,overflows:H}],!H.every((t=>t<=0))){var F,M;const t=((null==(F=o.flip)?void 0:F.index)||0)+1,e=B[t];if(e){var V;const n="alignment"===w&&E!==d(e),i=(null==(V=S[0])?void 0:V.overflows[0])>0;if(!n||i)return{data:{index:t,overflows:S},reset:{placement:e}}}let n=null==(M=S.filter((t=>t.overflows[0]<=0)).sort(((t,e)=>t.overflows[1]-e.overflows[1]))[0])?void 0:M.placement;if(!n)switch(v){case"bestFit":{var W;const t=null==(W=S.filter((t=>{if(k){const e=d(t.placement);return e===E||"y"===e}return!0})).map((t=>[t.placement,t.overflows.filter((t=>t>0)).reduce(((t,e)=>t+e),0)])).sort(((t,e)=>t[1]-e[1]))[0])?void 0:W[0];t&&(n=t);break}case"initialPlacement":n=l}if(r!==n)return{reset:{placement:n}}}return{}}}};function E(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function O(e){return t.some((t=>e[t]>=0))}const T=function(t){return void 0===t&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:i="referenceHidden",...r}=s(t,e);switch(i){case"referenceHidden":{const t=E(await A(e,{...r,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:t,referenceHidden:O(t)}}}case"escaped":{const t=E(await A(e,{...r,altBoundary:!0}),n.floating);return{data:{escapedOffsets:t,escaped:O(t)}}}default:return{}}}}};function L(t){const e=i(...t.map((t=>t.left))),n=i(...t.map((t=>t.top)));return{x:e,y:n,width:r(...t.map((t=>t.right)))-e,height:r(...t.map((t=>t.bottom)))-n}}const k=function(t){return void 0===t&&(t={}),{name:"inline",options:t,async fn(e){const{placement:n,elements:o,rects:a,platform:l,strategy:f}=e,{padding:m=2,x:u,y:g}=s(t,e),p=Array.from(await(null==l.getClientRects?void 0:l.getClientRects(o.reference))||[]),h=function(t){const e=t.slice().sort(((t,e)=>t.y-e.y)),n=[];let i=null;for(let t=0;ti.height/2?n.push([r]):n[n.length-1].push(r),i=r}return n.map((t=>x(L(t))))}(p),y=x(L(p)),v=w(m);const b=await l.getElementRects({reference:{getBoundingClientRect:function(){if(2===h.length&&h[0].left>h[1].right&&null!=u&&null!=g)return h.find((t=>u>t.left-v.left&&ut.top-v.top&&g=2){if("y"===d(n)){const t=h[0],e=h[h.length-1],i="top"===c(n),r=t.top,o=e.bottom,a=i?t.left:e.left,l=i?t.right:e.right;return{top:r,bottom:o,left:a,right:l,width:l-a,height:o-r,x:a,y:r}}const t="left"===c(n),e=r(...h.map((t=>t.right))),o=i(...h.map((t=>t.left))),a=h.filter((n=>t?n.left===o:n.right===e)),l=a[0].top,s=a[a.length-1].bottom;return{top:l,bottom:s,left:o,right:e,width:e-o,height:s-l,x:o,y:l}}return y}},floating:o.floating,strategy:f});return a.reference.x!==b.reference.x||a.reference.y!==b.reference.y||a.reference.width!==b.reference.width||a.reference.height!==b.reference.height?{reset:{rects:b}}:{}}}};const B=function(t){return void 0===t&&(t=0),{name:"offset",options:t,async fn(e){var n,i;const{x:r,y:o,placement:a,middlewareData:l}=e,m=await async function(t,e){const{placement:n,platform:i,elements:r}=t,o=await(null==i.isRTL?void 0:i.isRTL(r.floating)),a=c(n),l=f(n),m="y"===d(n),u=["left","top"].includes(a)?-1:1,g=o&&m?-1:1,p=s(e,t);let{mainAxis:h,crossAxis:y,alignmentAxis:w}="number"==typeof p?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return l&&"number"==typeof w&&(y="end"===l?-1*w:w),m?{x:y*g,y:h*u}:{x:h*u,y:y*g}}(e,t);return a===(null==(n=l.offset)?void 0:n.placement)&&null!=(i=l.arrow)&&i.alignmentOffset?{}:{x:r+m.x,y:o+m.y,data:{...m,placement:a}}}}},C=function(t){return void 0===t&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:i,placement:r}=e,{mainAxis:o=!0,crossAxis:a=!1,limiter:f={fn:t=>{let{x:e,y:n}=t;return{x:e,y:n}}},...u}=s(t,e),g={x:n,y:i},p=await A(e,u),h=d(c(r)),y=m(h);let w=g[y],x=g[h];if(o){const t="y"===y?"bottom":"right";w=l(w+p["y"===y?"top":"left"],w,w-p[t])}if(a){const t="y"===h?"bottom":"right";x=l(x+p["y"===h?"top":"left"],x,x-p[t])}const v=f.fn({...e,[y]:w,[h]:x});return{...v,data:{x:v.x-n,y:v.y-i,enabled:{[y]:o,[h]:a}}}}}},H=function(t){return void 0===t&&(t={}),{options:t,fn(e){const{x:n,y:i,placement:r,rects:o,middlewareData:a}=e,{offset:l=0,mainAxis:f=!0,crossAxis:u=!0}=s(t,e),g={x:n,y:i},p=d(r),h=m(p);let y=g[h],w=g[p];const x=s(l,e),v="number"==typeof x?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(f){const t="y"===h?"height":"width",e=o.reference[h]-o.floating[t]+v.mainAxis,n=o.reference[h]+o.reference[t]-v.mainAxis;yn&&(y=n)}if(u){var b,A;const t="y"===h?"width":"height",e=["top","left"].includes(c(r)),n=o.reference[p]-o.floating[t]+(e&&(null==(b=a.offset)?void 0:b[p])||0)+(e?0:v.crossAxis),i=o.reference[p]+o.reference[t]+(e?0:(null==(A=a.offset)?void 0:A[p])||0)-(e?v.crossAxis:0);wi&&(w=i)}return{[h]:y,[p]:w}}}},S=function(t){return void 0===t&&(t={}),{name:"size",options:t,async fn(e){var n,o;const{placement:a,rects:l,platform:m,elements:u}=e,{apply:g=()=>{},...p}=s(t,e),h=await A(e,p),y=c(a),w=f(a),x="y"===d(a),{width:v,height:b}=l.floating;let R,D;"top"===y||"bottom"===y?(R=y,D=w===(await(null==m.isRTL?void 0:m.isRTL(u.floating))?"start":"end")?"left":"right"):(D=y,R="end"===w?"top":"bottom");const P=b-h.top-h.bottom,E=v-h.left-h.right,O=i(b-h[R],P),T=i(v-h[D],E),L=!e.middlewareData.shift;let k=O,B=T;if(null!=(n=e.middlewareData.shift)&&n.enabled.x&&(B=E),null!=(o=e.middlewareData.shift)&&o.enabled.y&&(k=P),L&&!w){const t=r(h.left,0),e=r(h.right,0),n=r(h.top,0),i=r(h.bottom,0);x?B=v-2*(0!==t||0!==e?t+e:r(h.left,h.right)):k=b-2*(0!==n||0!==i?n+i:r(h.top,h.bottom))}await g({...e,availableWidth:B,availableHeight:k});const C=await m.getDimensions(u.floating);return v!==C.width||b!==C.height?{reset:{rects:!0}}:{}}}};export{R as arrow,D as autoPlacement,b as computePosition,A as detectOverflow,P as flip,T as hide,k as inline,H as limitShift,B as offset,x as rectToClientRect,C as shift,S as size}; /** * Custom positioning reference element. * @see https://floating-ui.com/docs/virtual-elements */ const sides = ['top', 'right', 'bottom', 'left']; const alignments = ['start', 'end']; const placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + "-" + alignments[0], side + "-" + alignments[1]), []); const min = Math.min; const max = Math.max; const oppositeSideMap = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; const oppositeAlignmentMap = { start: 'end', end: 'start' }; function clamp(start, value, end) { return max(start, min(value, end)); } function evaluate(value, param) { return typeof value === 'function' ? value(param) : value; } function getSide(placement) { return placement.split('-')[0]; } function getAlignment(placement) { return placement.split('-')[1]; } function getOppositeAxis(axis) { return axis === 'x' ? 'y' : 'x'; } function getAxisLength(axis) { return axis === 'y' ? 'height' : 'width'; } function getSideAxis(placement) { return ['top', 'bottom'].includes(getSide(placement)) ? 'y' : 'x'; } function getAlignmentAxis(placement) { return getOppositeAxis(getSideAxis(placement)); } function getAlignmentSides(placement, rects, rtl) { if (rtl === void 0) { rtl = false; } const alignment = getAlignment(placement); const alignmentAxis = getAlignmentAxis(placement); const length = getAxisLength(alignmentAxis); let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top'; if (rects.reference[length] > rects.floating[length]) { mainAlignmentSide = getOppositePlacement(mainAlignmentSide); } return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)]; } function getExpandedPlacements(placement) { const oppositePlacement = getOppositePlacement(placement); return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)]; } function getOppositeAlignmentPlacement(placement) { return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]); } function getSideList(side, isStart, rtl) { const lr = ['left', 'right']; const rl = ['right', 'left']; const tb = ['top', 'bottom']; const bt = ['bottom', 'top']; switch (side) { case 'top': case 'bottom': if (rtl) return isStart ? rl : lr; return isStart ? lr : rl; case 'left': case 'right': return isStart ? tb : bt; default: return []; } } function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { const alignment = getAlignment(placement); let list = getSideList(getSide(placement), direction === 'start', rtl); if (alignment) { list = list.map(side => side + "-" + alignment); if (flipAlignment) { list = list.concat(list.map(getOppositeAlignmentPlacement)); } } return list; } function getOppositePlacement(placement) { return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]); } function expandPaddingObject(padding) { return { top: 0, right: 0, bottom: 0, left: 0, ...padding }; } function getPaddingObject(padding) { return typeof padding !== 'number' ? expandPaddingObject(padding) : { top: padding, right: padding, bottom: padding, left: padding }; } function rectToClientRect(rect) { const { x, y, width, height } = rect; return { width, height, top: y, left: x, right: x + width, bottom: y + height, x, y }; } function computeCoordsFromPlacement(_ref, placement, rtl) { let { reference, floating } = _ref; const sideAxis = getSideAxis(placement); const alignmentAxis = getAlignmentAxis(placement); const alignLength = getAxisLength(alignmentAxis); const side = getSide(placement); const isVertical = sideAxis === 'y'; const commonX = reference.x + reference.width / 2 - floating.width / 2; const commonY = reference.y + reference.height / 2 - floating.height / 2; const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; let coords; switch (side) { case 'top': coords = { x: commonX, y: reference.y - floating.height }; break; case 'bottom': coords = { x: commonX, y: reference.y + reference.height }; break; case 'right': coords = { x: reference.x + reference.width, y: commonY }; break; case 'left': coords = { x: reference.x - floating.width, y: commonY }; break; default: coords = { x: reference.x, y: reference.y }; } switch (getAlignment(placement)) { case 'start': coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); break; case 'end': coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); break; } return coords; } /** * Computes the `x` and `y` coordinates that will place the floating element * next to a given reference element. * * This export does not have any `platform` interface logic. You will need to * write one for the platform you are using Floating UI with. */ const computePosition = async (reference, floating, config) => { const { placement = 'bottom', strategy = 'absolute', middleware = [], platform } = config; const validMiddleware = middleware.filter(Boolean); const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); let rects = await platform.getElementRects({ reference, floating, strategy }); let { x, y } = computeCoordsFromPlacement(rects, placement, rtl); let statefulPlacement = placement; let middlewareData = {}; let resetCount = 0; for (let i = 0; i < validMiddleware.length; i++) { const { name, fn } = validMiddleware[i]; const { x: nextX, y: nextY, data, reset } = await fn({ x, y, initialPlacement: placement, placement: statefulPlacement, strategy, middlewareData, rects, platform, elements: { reference, floating } }); x = nextX != null ? nextX : x; y = nextY != null ? nextY : y; middlewareData = { ...middlewareData, [name]: { ...middlewareData[name], ...data } }; if (reset && resetCount <= 50) { resetCount++; if (typeof reset === 'object') { if (reset.placement) { statefulPlacement = reset.placement; } if (reset.rects) { rects = reset.rects === true ? await platform.getElementRects({ reference, floating, strategy }) : reset.rects; } ({ x, y } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); } i = -1; } } return { x, y, placement: statefulPlacement, strategy, middlewareData }; }; /** * Resolves with an object of overflow side offsets that determine how much the * element is overflowing a given clipping boundary on each side. * - positive = overflowing the boundary by that number of pixels * - negative = how many pixels left before it will overflow * - 0 = lies flush with the boundary * @see https://floating-ui.com/docs/detectOverflow */ async function detectOverflow(state, options) { var _await$platform$isEle; if (options === void 0) { options = {}; } const { x, y, platform, rects, elements, strategy } = state; const { boundary = 'clippingAncestors', rootBoundary = 'viewport', elementContext = 'floating', altBoundary = false, padding = 0 } = evaluate(options, state); const paddingObject = getPaddingObject(padding); const altContext = elementContext === 'floating' ? 'reference' : 'floating'; const element = elements[altBoundary ? altContext : elementContext]; const clippingClientRect = rectToClientRect(await platform.getClippingRect({ element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), boundary, rootBoundary, strategy })); const rect = elementContext === 'floating' ? { x, y, width: rects.floating.width, height: rects.floating.height } : rects.reference; const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { x: 1, y: 1 } : { x: 1, y: 1 }; const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ elements, rect, offsetParent, strategy }) : rect); return { top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x }; } /** * Provides data to position an inner element of the floating element so that it * appears centered to the reference element. * @see https://floating-ui.com/docs/arrow */ const arrow = options => ({ name: 'arrow', options, async fn(state) { const { x, y, placement, rects, platform, elements, middlewareData } = state; // Since `element` is required, we don't Partial<> the type. const { element, padding = 0 } = evaluate(options, state) || {}; if (element == null) { return {}; } const paddingObject = getPaddingObject(padding); const coords = { x, y }; const axis = getAlignmentAxis(placement); const length = getAxisLength(axis); const arrowDimensions = await platform.getDimensions(element); const isYAxis = axis === 'y'; const minProp = isYAxis ? 'top' : 'left'; const maxProp = isYAxis ? 'bottom' : 'right'; const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; const startDiff = coords[axis] - rects.reference[axis]; const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; // DOM platform can return `window` as the `offsetParent`. if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { clientSize = elements.floating[clientProp] || rects.floating[length]; } const centerToReference = endDiff / 2 - startDiff / 2; // If the padding is large enough that it causes the arrow to no longer be // centered, modify the padding so that it is centered. const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; const minPadding = min(paddingObject[minProp], largestPossiblePadding); const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); // Make sure the arrow doesn't overflow the floating element if the center // point is outside the floating element's bounds. const min$1 = minPadding; const max = clientSize - arrowDimensions[length] - maxPadding; const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; const offset = clamp(min$1, center, max); // If the reference is small enough that the arrow's padding causes it to // to point to nothing for an aligned placement, adjust the offset of the // floating element itself. To ensure `shift()` continues to take action, // a single reset is performed when this is true. const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; return { [axis]: coords[axis] + alignmentOffset, data: { [axis]: offset, centerOffset: center - offset - alignmentOffset, ...(shouldAddOffset && { alignmentOffset }) }, reset: shouldAddOffset }; } }); function getPlacementList(alignment, autoAlignment, allowedPlacements) { const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); return allowedPlacementsSortedByAlignment.filter(placement => { if (alignment) { return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); } return true; }); } /** * Optimizes the visibility of the floating element by choosing the placement * that has the most space available automatically, without needing to specify a * preferred placement. Alternative to `flip`. * @see https://floating-ui.com/docs/autoPlacement */ const autoPlacement = function (options) { if (options === void 0) { options = {}; } return { name: 'autoPlacement', options, async fn(state) { var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; const { rects, middlewareData, placement, platform, elements } = state; const { crossAxis = false, alignment, allowedPlacements = placements, autoAlignment = true, ...detectOverflowOptions } = evaluate(options, state); const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; const overflow = await detectOverflow(state, detectOverflowOptions); const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; const currentPlacement = placements$1[currentIndex]; if (currentPlacement == null) { return {}; } const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); // Make `computeCoords` start from the right place. if (placement !== currentPlacement) { return { reset: { placement: placements$1[0] } }; } const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]]; const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { placement: currentPlacement, overflows: currentOverflows }]; const nextPlacement = placements$1[currentIndex + 1]; // There are more placements to check. if (nextPlacement) { return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: nextPlacement } }; } const placementsSortedByMostSpace = allOverflows.map(d => { const alignment = getAlignment(d.placement); return [d.placement, alignment && crossAxis ? // Check along the mainAxis and main crossAxis side. d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : // Check only the mainAxis. d.overflows[0], d.overflows]; }).sort((a, b) => a[1] - b[1]); const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, // Aligned placements should not check their opposite crossAxis // side. getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; if (resetPlacement !== placement) { return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: resetPlacement } }; } return {}; } }; }; /** * Optimizes the visibility of the floating element by flipping the `placement` * in order to keep it in view when the preferred placement(s) will overflow the * clipping boundary. Alternative to `autoPlacement`. * @see https://floating-ui.com/docs/flip */ const flip = function (options) { if (options === void 0) { options = {}; } return { name: 'flip', options, async fn(state) { var _middlewareData$arrow, _middlewareData$flip; const { placement, middlewareData, rects, initialPlacement, platform, elements } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true, fallbackPlacements: specifiedFallbackPlacements, fallbackStrategy = 'bestFit', fallbackAxisSideDirection = 'none', flipAlignment = true, ...detectOverflowOptions } = evaluate(options, state); // If a reset by the arrow was caused due to an alignment offset being // added, we should skip any logic now since `flip()` has already done its // work. // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643 if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } const side = getSide(placement); const initialSideAxis = getSideAxis(initialPlacement); const isBasePlacement = getSide(initialPlacement) === initialPlacement; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none'; if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) { fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); } const placements = [initialPlacement, ...fallbackPlacements]; const overflow = await detectOverflow(state, detectOverflowOptions); const overflows = []; let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; if (checkMainAxis) { overflows.push(overflow[side]); } if (checkCrossAxis) { const sides = getAlignmentSides(placement, rects, rtl); overflows.push(overflow[sides[0]], overflow[sides[1]]); } overflowsData = [...overflowsData, { placement, overflows }]; // One or more sides is overflowing. if (!overflows.every(side => side <= 0)) { var _middlewareData$flip2, _overflowsData$filter; const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; const nextPlacement = placements[nextIndex]; if (nextPlacement) { var _overflowsData$; const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false; const hasInitialMainAxisOverflow = ((_overflowsData$ = overflowsData[0]) == null ? void 0 : _overflowsData$.overflows[0]) > 0; if (!ignoreCrossAxisOverflow || hasInitialMainAxisOverflow) { // Try next placement and re-run the lifecycle. return { data: { index: nextIndex, overflows: overflowsData }, reset: { placement: nextPlacement } }; } } // First, find the candidates that fit on the mainAxis side of overflow, // then find the placement that fits the best on the main crossAxis side. let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; // Otherwise fallback. if (!resetPlacement) { switch (fallbackStrategy) { case 'bestFit': { var _overflowsData$filter2; const placement = (_overflowsData$filter2 = overflowsData.filter(d => { if (hasFallbackAxisSideDirection) { const currentSideAxis = getSideAxis(d.placement); return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal // reading directions favoring greater width. currentSideAxis === 'y'; } return true; }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; if (placement) { resetPlacement = placement; } break; } case 'initialPlacement': resetPlacement = initialPlacement; break; } } if (placement !== resetPlacement) { return { reset: { placement: resetPlacement } }; } } return {}; } }; }; function getSideOffsets(overflow, rect) { return { top: overflow.top - rect.height, right: overflow.right - rect.width, bottom: overflow.bottom - rect.height, left: overflow.left - rect.width }; } function isAnySideFullyClipped(overflow) { return sides.some(side => overflow[side] >= 0); } /** * Provides data to hide the floating element in applicable situations, such as * when it is not in the same clipping context as the reference element. * @see https://floating-ui.com/docs/hide */ const hide = function (options) { if (options === void 0) { options = {}; } return { name: 'hide', options, async fn(state) { const { rects } = state; const { strategy = 'referenceHidden', ...detectOverflowOptions } = evaluate(options, state); switch (strategy) { case 'referenceHidden': { const overflow = await detectOverflow(state, { ...detectOverflowOptions, elementContext: 'reference' }); const offsets = getSideOffsets(overflow, rects.reference); return { data: { referenceHiddenOffsets: offsets, referenceHidden: isAnySideFullyClipped(offsets) } }; } case 'escaped': { const overflow = await detectOverflow(state, { ...detectOverflowOptions, altBoundary: true }); const offsets = getSideOffsets(overflow, rects.floating); return { data: { escapedOffsets: offsets, escaped: isAnySideFullyClipped(offsets) } }; } default: { return {}; } } } }; }; function getBoundingRect(rects) { const minX = min(...rects.map(rect => rect.left)); const minY = min(...rects.map(rect => rect.top)); const maxX = max(...rects.map(rect => rect.right)); const maxY = max(...rects.map(rect => rect.bottom)); return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; } function getRectsByLine(rects) { const sortedRects = rects.slice().sort((a, b) => a.y - b.y); const groups = []; let prevRect = null; for (let i = 0; i < sortedRects.length; i++) { const rect = sortedRects[i]; if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { groups.push([rect]); } else { groups[groups.length - 1].push(rect); } prevRect = rect; } return groups.map(rect => rectToClientRect(getBoundingRect(rect))); } /** * Provides improved positioning for inline reference elements that can span * over multiple lines, such as hyperlinks or range selections. * @see https://floating-ui.com/docs/inline */ const inline = function (options) { if (options === void 0) { options = {}; } return { name: 'inline', options, async fn(state) { const { placement, elements, rects, platform, strategy } = state; // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a // ClientRect's bounds, despite the event listener being triggered. A // padding of 2 seems to handle this issue. const { padding = 2, x, y } = evaluate(options, state); const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); const clientRects = getRectsByLine(nativeClientRects); const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); const paddingObject = getPaddingObject(padding); function getBoundingClientRect() { // There are two rects and they are disjoined. if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { // Find the first rect in which the point is fully inside. return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; } // There are 2 or more connected rects. if (clientRects.length >= 2) { if (getSideAxis(placement) === 'y') { const firstRect = clientRects[0]; const lastRect = clientRects[clientRects.length - 1]; const isTop = getSide(placement) === 'top'; const top = firstRect.top; const bottom = lastRect.bottom; const left = isTop ? firstRect.left : lastRect.left; const right = isTop ? firstRect.right : lastRect.right; const width = right - left; const height = bottom - top; return { top, bottom, left, right, width, height, x: left, y: top }; } const isLeftSide = getSide(placement) === 'left'; const maxRight = max(...clientRects.map(rect => rect.right)); const minLeft = min(...clientRects.map(rect => rect.left)); const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); const top = measureRects[0].top; const bottom = measureRects[measureRects.length - 1].bottom; const left = minLeft; const right = maxRight; const width = right - left; const height = bottom - top; return { top, bottom, left, right, width, height, x: left, y: top }; } return fallback; } const resetRects = await platform.getElementRects({ reference: { getBoundingClientRect }, floating: elements.floating, strategy }); if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { return { reset: { rects: resetRects } }; } return {}; } }; }; // For type backwards-compatibility, the `OffsetOptions` type was also // Derivable. async function convertValueToCoords(state, options) { const { placement, platform, elements } = state; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const side = getSide(placement); const alignment = getAlignment(placement); const isVertical = getSideAxis(placement) === 'y'; const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1; const crossAxisMulti = rtl && isVertical ? -1 : 1; const rawValue = evaluate(options, state); // eslint-disable-next-line prefer-const let { mainAxis, crossAxis, alignmentAxis } = typeof rawValue === 'number' ? { mainAxis: rawValue, crossAxis: 0, alignmentAxis: null } : { mainAxis: rawValue.mainAxis || 0, crossAxis: rawValue.crossAxis || 0, alignmentAxis: rawValue.alignmentAxis }; if (alignment && typeof alignmentAxis === 'number') { crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; } return isVertical ? { x: crossAxis * crossAxisMulti, y: mainAxis * mainAxisMulti } : { x: mainAxis * mainAxisMulti, y: crossAxis * crossAxisMulti }; } /** * Modifies the placement by translating the floating element along the * specified axes. * A number (shorthand for `mainAxis` or distance), or an axes configuration * object may be passed. * @see https://floating-ui.com/docs/offset */ const offset = function (options) { if (options === void 0) { options = 0; } return { name: 'offset', options, async fn(state) { var _middlewareData$offse, _middlewareData$arrow; const { x, y, placement, middlewareData } = state; const diffCoords = await convertValueToCoords(state, options); // If the placement is the same and the arrow caused an alignment offset // then we don't need to change the positioning coordinates. if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } return { x: x + diffCoords.x, y: y + diffCoords.y, data: { ...diffCoords, placement } }; } }; }; /** * Optimizes the visibility of the floating element by shifting it in order to * keep it in view when it will overflow the clipping boundary. * @see https://floating-ui.com/docs/shift */ const shift = function (options) { if (options === void 0) { options = {}; } return { name: 'shift', options, async fn(state) { const { x, y, placement } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = false, limiter = { fn: _ref => { let { x, y } = _ref; return { x, y }; } }, ...detectOverflowOptions } = evaluate(options, state); const coords = { x, y }; const overflow = await detectOverflow(state, detectOverflowOptions); const crossAxis = getSideAxis(getSide(placement)); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; if (checkMainAxis) { const minSide = mainAxis === 'y' ? 'top' : 'left'; const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; const min = mainAxisCoord + overflow[minSide]; const max = mainAxisCoord - overflow[maxSide]; mainAxisCoord = clamp(min, mainAxisCoord, max); } if (checkCrossAxis) { const minSide = crossAxis === 'y' ? 'top' : 'left'; const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; const min = crossAxisCoord + overflow[minSide]; const max = crossAxisCoord - overflow[maxSide]; crossAxisCoord = clamp(min, crossAxisCoord, max); } const limitedCoords = limiter.fn({ ...state, [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }); return { ...limitedCoords, data: { x: limitedCoords.x - x, y: limitedCoords.y - y, enabled: { [mainAxis]: checkMainAxis, [crossAxis]: checkCrossAxis } } }; } }; }; /** * Built-in `limiter` that will stop `shift()` at a certain point. */ const limitShift = function (options) { if (options === void 0) { options = {}; } return { options, fn(state) { const { x, y, placement, rects, middlewareData } = state; const { offset = 0, mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true } = evaluate(options, state); const coords = { x, y }; const crossAxis = getSideAxis(placement); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; const rawOffset = evaluate(offset, state); const computedOffset = typeof rawOffset === 'number' ? { mainAxis: rawOffset, crossAxis: 0 } : { mainAxis: 0, crossAxis: 0, ...rawOffset }; if (checkMainAxis) { const len = mainAxis === 'y' ? 'height' : 'width'; const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; if (mainAxisCoord < limitMin) { mainAxisCoord = limitMin; } else if (mainAxisCoord > limitMax) { mainAxisCoord = limitMax; } } if (checkCrossAxis) { var _middlewareData$offse, _middlewareData$offse2; const len = mainAxis === 'y' ? 'width' : 'height'; const isOriginSide = ['top', 'left'].includes(getSide(placement)); const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); if (crossAxisCoord < limitMin) { crossAxisCoord = limitMin; } else if (crossAxisCoord > limitMax) { crossAxisCoord = limitMax; } } return { [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }; } }; }; /** * Provides data that allows you to change the size of the floating element — * for instance, prevent it from overflowing the clipping boundary or match the * width of the reference element. * @see https://floating-ui.com/docs/size */ const size = function (options) { if (options === void 0) { options = {}; } return { name: 'size', options, async fn(state) { var _state$middlewareData, _state$middlewareData2; const { placement, rects, platform, elements } = state; const { apply = () => {}, ...detectOverflowOptions } = evaluate(options, state); const overflow = await detectOverflow(state, detectOverflowOptions); const side = getSide(placement); const alignment = getAlignment(placement); const isYAxis = getSideAxis(placement) === 'y'; const { width, height } = rects.floating; let heightSide; let widthSide; if (side === 'top' || side === 'bottom') { heightSide = side; widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; } else { widthSide = side; heightSide = alignment === 'end' ? 'top' : 'bottom'; } const maximumClippingHeight = height - overflow.top - overflow.bottom; const maximumClippingWidth = width - overflow.left - overflow.right; const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); const noShift = !state.middlewareData.shift; let availableHeight = overflowAvailableHeight; let availableWidth = overflowAvailableWidth; if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) { availableWidth = maximumClippingWidth; } if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) { availableHeight = maximumClippingHeight; } if (noShift && !alignment) { const xMin = max(overflow.left, 0); const xMax = max(overflow.right, 0); const yMin = max(overflow.top, 0); const yMax = max(overflow.bottom, 0); if (isYAxis) { availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); } else { availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); } } await apply({ ...state, availableWidth, availableHeight }); const nextDimensions = await platform.getDimensions(elements.floating); if (width !== nextDimensions.width || height !== nextDimensions.height) { return { reset: { rects: true } }; } return {}; } }; }; export { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, rectToClientRect, shift, size }; import { AlignedPlacement } from '@floating-ui/utils'; import { Alignment } from '@floating-ui/utils'; import { Axis } from '@floating-ui/utils'; import { ClientRectObject } from '@floating-ui/utils'; import { Coords } from '@floating-ui/utils'; import { Dimensions } from '@floating-ui/utils'; import { ElementRects } from '@floating-ui/utils'; import { Length } from '@floating-ui/utils'; import { Padding } from '@floating-ui/utils'; import { Placement } from '@floating-ui/utils'; import { Rect } from '@floating-ui/utils'; import { rectToClientRect } from '@floating-ui/utils'; import { Side } from '@floating-ui/utils'; import { SideObject } from '@floating-ui/utils'; import { Strategy } from '@floating-ui/utils'; import { VirtualElement } from '@floating-ui/utils'; export { AlignedPlacement } export { Alignment } /** * Provides data to position an inner element of the floating element so that it * appears centered to the reference element. * @see https://floating-ui.com/docs/arrow */ export declare const arrow: (options: ArrowOptions | Derivable) => Middleware; export declare interface ArrowOptions { /** * The arrow element to be positioned. * @default undefined */ element: any; /** * The padding between the arrow element and the floating element edges. * Useful when the floating element has rounded corners. * @default 0 */ padding?: Padding; } /** * Optimizes the visibility of the floating element by choosing the placement * that has the most space available automatically, without needing to specify a * preferred placement. Alternative to `flip`. * @see https://floating-ui.com/docs/autoPlacement */ export declare const autoPlacement: (options?: AutoPlacementOptions | Derivable) => Middleware; export declare interface AutoPlacementOptions extends DetectOverflowOptions { /** * The axis that runs along the alignment of the floating element. Determines * whether to check for most space along this axis. * @default false */ crossAxis?: boolean; /** * Choose placements with a particular alignment. * @default undefined */ alignment?: Alignment | null; /** * Whether to choose placements with the opposite alignment if the preferred * alignment does not fit. * @default true */ autoAlignment?: boolean; /** * Which placements are allowed to be chosen. Placements must be within the * `alignment` option if explicitly set. * @default allPlacements (variable) */ allowedPlacements?: Array; } export { Axis } export declare type Boundary = any; export { ClientRectObject } export declare type ComputePosition = (reference: unknown, floating: unknown, config: ComputePositionConfig) => Promise; /** * Computes the `x` and `y` coordinates that will place the floating element * next to a given reference element. * * This export does not have any `platform` interface logic. You will need to * write one for the platform you are using Floating UI with. */ export declare const computePosition: ComputePosition; export declare interface ComputePositionConfig { /** * Object to interface with the current platform. */ platform: Platform; /** * Where to place the floating element relative to the reference element. */ placement?: Placement; /** * The strategy to use when positioning the floating element. */ strategy?: Strategy; /** * Array of middleware objects to modify the positioning or provide data for * rendering. */ middleware?: Array; } export declare interface ComputePositionReturn extends Coords { /** * The final chosen placement of the floating element. */ placement: Placement; /** * The strategy used to position the floating element. */ strategy: Strategy; /** * Object containing data returned from all middleware, keyed by their name. */ middlewareData: MiddlewareData; } export { Coords } /** * Function option to derive middleware options from state. */ export declare type Derivable = (state: MiddlewareState) => T; /** * Resolves with an object of overflow side offsets that determine how much the * element is overflowing a given clipping boundary on each side. * - positive = overflowing the boundary by that number of pixels * - negative = how many pixels left before it will overflow * - 0 = lies flush with the boundary * @see https://floating-ui.com/docs/detectOverflow */ export declare function detectOverflow(state: MiddlewareState, options?: DetectOverflowOptions | Derivable): Promise; export declare interface DetectOverflowOptions { /** * The clipping element(s) or area in which overflow will be checked. * @default 'clippingAncestors' */ boundary?: Boundary; /** * The root clipping area in which overflow will be checked. * @default 'viewport' */ rootBoundary?: RootBoundary; /** * The element in which overflow is being checked relative to a boundary. * @default 'floating' */ elementContext?: ElementContext; /** * Whether to check for overflow using the alternate element's boundary * (`clippingAncestors` boundary only). * @default false */ altBoundary?: boolean; /** * Virtual padding for the resolved overflow detection offsets. * @default 0 */ padding?: Padding; } export { Dimensions } export declare type ElementContext = 'reference' | 'floating'; export { ElementRects } export declare interface Elements { reference: ReferenceElement; floating: FloatingElement; } /** * Optimizes the visibility of the floating element by flipping the `placement` * in order to keep it in view when the preferred placement(s) will overflow the * clipping boundary. Alternative to `autoPlacement`. * @see https://floating-ui.com/docs/flip */ export declare const flip: (options?: FlipOptions | Derivable) => Middleware; export declare interface FlipOptions extends DetectOverflowOptions { /** * The axis that runs along the side of the floating element. Determines * whether overflow along this axis is checked to perform a flip. * @default true */ mainAxis?: boolean; /** * The axis that runs along the alignment of the floating element. Determines * whether overflow along this axis is checked to perform a flip. * - `true`: Whether to check cross axis overflow for both side and alignment flipping. * - `false`: Whether to disable all cross axis overflow checking. * - `'alignment'`: Whether to check cross axis overflow for alignment flipping only. * @default true */ crossAxis?: boolean | 'alignment'; /** * Placements to try sequentially if the preferred `placement` does not fit. * @default [oppositePlacement] (computed) */ fallbackPlacements?: Array; /** * What strategy to use when no placements fit. * @default 'bestFit' */ fallbackStrategy?: 'bestFit' | 'initialPlacement'; /** * Whether to allow fallback to the perpendicular axis of the preferred * placement, and if so, which side direction along the axis to prefer. * @default 'none' (disallow fallback) */ fallbackAxisSideDirection?: 'none' | 'start' | 'end'; /** * Whether to flip to placements with the opposite alignment if they fit * better. * @default true */ flipAlignment?: boolean; } export declare type FloatingElement = any; /** * Provides data to hide the floating element in applicable situations, such as * when it is not in the same clipping context as the reference element. * @see https://floating-ui.com/docs/hide */ export declare const hide: (options?: HideOptions | Derivable) => Middleware; export declare interface HideOptions extends DetectOverflowOptions { /** * The strategy used to determine when to hide the floating element. */ strategy?: 'referenceHidden' | 'escaped'; } /** * Provides improved positioning for inline reference elements that can span * over multiple lines, such as hyperlinks or range selections. * @see https://floating-ui.com/docs/inline */ export declare const inline: (options?: InlineOptions | Derivable) => Middleware; export declare interface InlineOptions { /** * Viewport-relative `x` coordinate to choose a `ClientRect`. * @default undefined */ x?: number; /** * Viewport-relative `y` coordinate to choose a `ClientRect`. * @default undefined */ y?: number; /** * Represents the padding around a disjoined rect when choosing it. * @default 2 */ padding?: Padding; } export { Length } /** * Built-in `limiter` that will stop `shift()` at a certain point. */ export declare const limitShift: (options?: LimitShiftOptions | Derivable) => { options: any; fn: (state: MiddlewareState) => Coords; }; declare type LimitShiftOffset = number | { /** * Offset the limiting of the axis that runs along the alignment of the * floating element. */ mainAxis?: number; /** * Offset the limiting of the axis that runs along the side of the * floating element. */ crossAxis?: number; }; export declare interface LimitShiftOptions { /** * Offset when limiting starts. `0` will limit when the opposite edges of the * reference and floating elements are aligned. * - positive = start limiting earlier * - negative = start limiting later */ offset?: LimitShiftOffset | Derivable; /** * Whether to limit the axis that runs along the alignment of the floating * element. */ mainAxis?: boolean; /** * Whether to limit the axis that runs along the side of the floating element. */ crossAxis?: boolean; } export declare type Middleware = { name: string; options?: any; fn: (state: MiddlewareState) => Promisable; }; /** * @deprecated use `MiddlewareState` instead. */ export declare type MiddlewareArguments = MiddlewareState; export declare interface MiddlewareData { [key: string]: any; arrow?: Partial & { centerOffset: number; alignmentOffset?: number; }; autoPlacement?: { index?: number; overflows: Array<{ placement: Placement; overflows: Array; }>; }; flip?: { index?: number; overflows: Array<{ placement: Placement; overflows: Array; }>; }; hide?: { referenceHidden?: boolean; escaped?: boolean; referenceHiddenOffsets?: SideObject; escapedOffsets?: SideObject; }; offset?: Coords & { placement: Placement; }; shift?: Coords & { enabled: { [key in Axis]: boolean; }; }; } export declare interface MiddlewareReturn extends Partial { data?: { [key: string]: any; }; reset?: boolean | { placement?: Placement; rects?: boolean | ElementRects; }; } export declare interface MiddlewareState extends Coords { initialPlacement: Placement; placement: Placement; strategy: Strategy; middlewareData: MiddlewareData; elements: Elements; rects: ElementRects; platform: Platform; } /** * Modifies the placement by translating the floating element along the * specified axes. * A number (shorthand for `mainAxis` or distance), or an axes configuration * object may be passed. * @see https://floating-ui.com/docs/offset */ export declare const offset: (options?: OffsetOptions) => Middleware; export declare type OffsetOptions = OffsetValue | Derivable; declare type OffsetValue = number | { /** * The axis that runs along the side of the floating element. Represents * the distance (gutter or margin) between the reference and floating * element. * @default 0 */ mainAxis?: number; /** * The axis that runs along the alignment of the floating element. * Represents the skidding between the reference and floating element. * @default 0 */ crossAxis?: number; /** * The same axis as `crossAxis` but applies only to aligned placements * and inverts the `end` alignment. When set to a number, it overrides the * `crossAxis` value. * * A positive number will move the floating element in the direction of * the opposite edge to the one that is aligned, while a negative number * the reverse. * @default null */ alignmentAxis?: number | null; }; export { Padding } export { Placement } /** * Platform interface methods to work with the current platform. * @see https://floating-ui.com/docs/platform */ export declare interface Platform { getElementRects: (args: { reference: ReferenceElement; floating: FloatingElement; strategy: Strategy; }) => Promisable; getClippingRect: (args: { element: any; boundary: Boundary; rootBoundary: RootBoundary; strategy: Strategy; }) => Promisable; getDimensions: (element: any) => Promisable; convertOffsetParentRelativeRectToViewportRelativeRect?: (args: { elements?: Elements; rect: Rect; offsetParent: any; strategy: Strategy; }) => Promisable; getOffsetParent?: (element: any) => Promisable; isElement?: (value: any) => Promisable; getDocumentElement?: (element: any) => Promisable; getClientRects?: (element: any) => Promisable>; isRTL?: (element: any) => Promisable; getScale?: (element: any) => Promisable<{ x: number; y: number; }>; } declare type Promisable = T | Promise; export { Rect } export { rectToClientRect } export declare type ReferenceElement = any; export declare type RootBoundary = 'viewport' | 'document' | Rect; /** * Optimizes the visibility of the floating element by shifting it in order to * keep it in view when it will overflow the clipping boundary. * @see https://floating-ui.com/docs/shift */ export declare const shift: (options?: ShiftOptions | Derivable) => Middleware; export declare interface ShiftOptions extends DetectOverflowOptions { /** * The axis that runs along the alignment of the floating element. Determines * whether overflow along this axis is checked to perform shifting. * @default true */ mainAxis?: boolean; /** * The axis that runs along the side of the floating element. Determines * whether overflow along this axis is checked to perform shifting. * @default false */ crossAxis?: boolean; /** * Accepts a function that limits the shifting done in order to prevent * detachment. */ limiter?: { fn: (state: MiddlewareState) => Coords; options?: any; }; } export { Side } export { SideObject } /** * Provides data that allows you to change the size of the floating element — * for instance, prevent it from overflowing the clipping boundary or match the * width of the reference element. * @see https://floating-ui.com/docs/size */ export declare const size: (options?: SizeOptions | Derivable) => Middleware; export declare interface SizeOptions extends DetectOverflowOptions { /** * Function that is called to perform style mutations to the floating element * to change its size. * @default undefined */ apply?(args: MiddlewareState & { availableWidth: number; availableHeight: number; }): void | Promise; } export { Strategy } export { VirtualElement } export { } import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils'; export { rectToClientRect } from '@floating-ui/utils'; function computeCoordsFromPlacement(_ref, placement, rtl) { let { reference, floating } = _ref; const sideAxis = getSideAxis(placement); const alignmentAxis = getAlignmentAxis(placement); const alignLength = getAxisLength(alignmentAxis); const side = getSide(placement); const isVertical = sideAxis === 'y'; const commonX = reference.x + reference.width / 2 - floating.width / 2; const commonY = reference.y + reference.height / 2 - floating.height / 2; const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; let coords; switch (side) { case 'top': coords = { x: commonX, y: reference.y - floating.height }; break; case 'bottom': coords = { x: commonX, y: reference.y + reference.height }; break; case 'right': coords = { x: reference.x + reference.width, y: commonY }; break; case 'left': coords = { x: reference.x - floating.width, y: commonY }; break; default: coords = { x: reference.x, y: reference.y }; } switch (getAlignment(placement)) { case 'start': coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); break; case 'end': coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); break; } return coords; } /** * Computes the `x` and `y` coordinates that will place the floating element * next to a given reference element. * * This export does not have any `platform` interface logic. You will need to * write one for the platform you are using Floating UI with. */ const computePosition = async (reference, floating, config) => { const { placement = 'bottom', strategy = 'absolute', middleware = [], platform } = config; const validMiddleware = middleware.filter(Boolean); const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); let rects = await platform.getElementRects({ reference, floating, strategy }); let { x, y } = computeCoordsFromPlacement(rects, placement, rtl); let statefulPlacement = placement; let middlewareData = {}; let resetCount = 0; for (let i = 0; i < validMiddleware.length; i++) { const { name, fn } = validMiddleware[i]; const { x: nextX, y: nextY, data, reset } = await fn({ x, y, initialPlacement: placement, placement: statefulPlacement, strategy, middlewareData, rects, platform, elements: { reference, floating } }); x = nextX != null ? nextX : x; y = nextY != null ? nextY : y; middlewareData = { ...middlewareData, [name]: { ...middlewareData[name], ...data } }; if (reset && resetCount <= 50) { resetCount++; if (typeof reset === 'object') { if (reset.placement) { statefulPlacement = reset.placement; } if (reset.rects) { rects = reset.rects === true ? await platform.getElementRects({ reference, floating, strategy }) : reset.rects; } ({ x, y } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); } i = -1; } } return { x, y, placement: statefulPlacement, strategy, middlewareData }; }; /** * Resolves with an object of overflow side offsets that determine how much the * element is overflowing a given clipping boundary on each side. * - positive = overflowing the boundary by that number of pixels * - negative = how many pixels left before it will overflow * - 0 = lies flush with the boundary * @see https://floating-ui.com/docs/detectOverflow */ async function detectOverflow(state, options) { var _await$platform$isEle; if (options === void 0) { options = {}; } const { x, y, platform, rects, elements, strategy } = state; const { boundary = 'clippingAncestors', rootBoundary = 'viewport', elementContext = 'floating', altBoundary = false, padding = 0 } = evaluate(options, state); const paddingObject = getPaddingObject(padding); const altContext = elementContext === 'floating' ? 'reference' : 'floating'; const element = elements[altBoundary ? altContext : elementContext]; const clippingClientRect = rectToClientRect(await platform.getClippingRect({ element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), boundary, rootBoundary, strategy })); const rect = elementContext === 'floating' ? { x, y, width: rects.floating.width, height: rects.floating.height } : rects.reference; const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { x: 1, y: 1 } : { x: 1, y: 1 }; const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ elements, rect, offsetParent, strategy }) : rect); return { top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x }; } /** * Provides data to position an inner element of the floating element so that it * appears centered to the reference element. * @see https://floating-ui.com/docs/arrow */ const arrow = options => ({ name: 'arrow', options, async fn(state) { const { x, y, placement, rects, platform, elements, middlewareData } = state; // Since `element` is required, we don't Partial<> the type. const { element, padding = 0 } = evaluate(options, state) || {}; if (element == null) { return {}; } const paddingObject = getPaddingObject(padding); const coords = { x, y }; const axis = getAlignmentAxis(placement); const length = getAxisLength(axis); const arrowDimensions = await platform.getDimensions(element); const isYAxis = axis === 'y'; const minProp = isYAxis ? 'top' : 'left'; const maxProp = isYAxis ? 'bottom' : 'right'; const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; const startDiff = coords[axis] - rects.reference[axis]; const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; // DOM platform can return `window` as the `offsetParent`. if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { clientSize = elements.floating[clientProp] || rects.floating[length]; } const centerToReference = endDiff / 2 - startDiff / 2; // If the padding is large enough that it causes the arrow to no longer be // centered, modify the padding so that it is centered. const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; const minPadding = min(paddingObject[minProp], largestPossiblePadding); const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); // Make sure the arrow doesn't overflow the floating element if the center // point is outside the floating element's bounds. const min$1 = minPadding; const max = clientSize - arrowDimensions[length] - maxPadding; const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; const offset = clamp(min$1, center, max); // If the reference is small enough that the arrow's padding causes it to // to point to nothing for an aligned placement, adjust the offset of the // floating element itself. To ensure `shift()` continues to take action, // a single reset is performed when this is true. const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; return { [axis]: coords[axis] + alignmentOffset, data: { [axis]: offset, centerOffset: center - offset - alignmentOffset, ...(shouldAddOffset && { alignmentOffset }) }, reset: shouldAddOffset }; } }); function getPlacementList(alignment, autoAlignment, allowedPlacements) { const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); return allowedPlacementsSortedByAlignment.filter(placement => { if (alignment) { return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); } return true; }); } /** * Optimizes the visibility of the floating element by choosing the placement * that has the most space available automatically, without needing to specify a * preferred placement. Alternative to `flip`. * @see https://floating-ui.com/docs/autoPlacement */ const autoPlacement = function (options) { if (options === void 0) { options = {}; } return { name: 'autoPlacement', options, async fn(state) { var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; const { rects, middlewareData, placement, platform, elements } = state; const { crossAxis = false, alignment, allowedPlacements = placements, autoAlignment = true, ...detectOverflowOptions } = evaluate(options, state); const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; const overflow = await detectOverflow(state, detectOverflowOptions); const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; const currentPlacement = placements$1[currentIndex]; if (currentPlacement == null) { return {}; } const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); // Make `computeCoords` start from the right place. if (placement !== currentPlacement) { return { reset: { placement: placements$1[0] } }; } const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]]; const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { placement: currentPlacement, overflows: currentOverflows }]; const nextPlacement = placements$1[currentIndex + 1]; // There are more placements to check. if (nextPlacement) { return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: nextPlacement } }; } const placementsSortedByMostSpace = allOverflows.map(d => { const alignment = getAlignment(d.placement); return [d.placement, alignment && crossAxis ? // Check along the mainAxis and main crossAxis side. d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : // Check only the mainAxis. d.overflows[0], d.overflows]; }).sort((a, b) => a[1] - b[1]); const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, // Aligned placements should not check their opposite crossAxis // side. getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; if (resetPlacement !== placement) { return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: resetPlacement } }; } return {}; } }; }; /** * Optimizes the visibility of the floating element by flipping the `placement` * in order to keep it in view when the preferred placement(s) will overflow the * clipping boundary. Alternative to `autoPlacement`. * @see https://floating-ui.com/docs/flip */ const flip = function (options) { if (options === void 0) { options = {}; } return { name: 'flip', options, async fn(state) { var _middlewareData$arrow, _middlewareData$flip; const { placement, middlewareData, rects, initialPlacement, platform, elements } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true, fallbackPlacements: specifiedFallbackPlacements, fallbackStrategy = 'bestFit', fallbackAxisSideDirection = 'none', flipAlignment = true, ...detectOverflowOptions } = evaluate(options, state); // If a reset by the arrow was caused due to an alignment offset being // added, we should skip any logic now since `flip()` has already done its // work. // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643 if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } const side = getSide(placement); const initialSideAxis = getSideAxis(initialPlacement); const isBasePlacement = getSide(initialPlacement) === initialPlacement; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none'; if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) { fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); } const placements = [initialPlacement, ...fallbackPlacements]; const overflow = await detectOverflow(state, detectOverflowOptions); const overflows = []; let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; if (checkMainAxis) { overflows.push(overflow[side]); } if (checkCrossAxis) { const sides = getAlignmentSides(placement, rects, rtl); overflows.push(overflow[sides[0]], overflow[sides[1]]); } overflowsData = [...overflowsData, { placement, overflows }]; // One or more sides is overflowing. if (!overflows.every(side => side <= 0)) { var _middlewareData$flip2, _overflowsData$filter; const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; const nextPlacement = placements[nextIndex]; if (nextPlacement) { var _overflowsData$; const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false; const hasInitialMainAxisOverflow = ((_overflowsData$ = overflowsData[0]) == null ? void 0 : _overflowsData$.overflows[0]) > 0; if (!ignoreCrossAxisOverflow || hasInitialMainAxisOverflow) { // Try next placement and re-run the lifecycle. return { data: { index: nextIndex, overflows: overflowsData }, reset: { placement: nextPlacement } }; } } // First, find the candidates that fit on the mainAxis side of overflow, // then find the placement that fits the best on the main crossAxis side. let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; // Otherwise fallback. if (!resetPlacement) { switch (fallbackStrategy) { case 'bestFit': { var _overflowsData$filter2; const placement = (_overflowsData$filter2 = overflowsData.filter(d => { if (hasFallbackAxisSideDirection) { const currentSideAxis = getSideAxis(d.placement); return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal // reading directions favoring greater width. currentSideAxis === 'y'; } return true; }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; if (placement) { resetPlacement = placement; } break; } case 'initialPlacement': resetPlacement = initialPlacement; break; } } if (placement !== resetPlacement) { return { reset: { placement: resetPlacement } }; } } return {}; } }; }; function getSideOffsets(overflow, rect) { return { top: overflow.top - rect.height, right: overflow.right - rect.width, bottom: overflow.bottom - rect.height, left: overflow.left - rect.width }; } function isAnySideFullyClipped(overflow) { return sides.some(side => overflow[side] >= 0); } /** * Provides data to hide the floating element in applicable situations, such as * when it is not in the same clipping context as the reference element. * @see https://floating-ui.com/docs/hide */ const hide = function (options) { if (options === void 0) { options = {}; } return { name: 'hide', options, async fn(state) { const { rects } = state; const { strategy = 'referenceHidden', ...detectOverflowOptions } = evaluate(options, state); switch (strategy) { case 'referenceHidden': { const overflow = await detectOverflow(state, { ...detectOverflowOptions, elementContext: 'reference' }); const offsets = getSideOffsets(overflow, rects.reference); return { data: { referenceHiddenOffsets: offsets, referenceHidden: isAnySideFullyClipped(offsets) } }; } case 'escaped': { const overflow = await detectOverflow(state, { ...detectOverflowOptions, altBoundary: true }); const offsets = getSideOffsets(overflow, rects.floating); return { data: { escapedOffsets: offsets, escaped: isAnySideFullyClipped(offsets) } }; } default: { return {}; } } } }; }; function getBoundingRect(rects) { const minX = min(...rects.map(rect => rect.left)); const minY = min(...rects.map(rect => rect.top)); const maxX = max(...rects.map(rect => rect.right)); const maxY = max(...rects.map(rect => rect.bottom)); return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; } function getRectsByLine(rects) { const sortedRects = rects.slice().sort((a, b) => a.y - b.y); const groups = []; let prevRect = null; for (let i = 0; i < sortedRects.length; i++) { const rect = sortedRects[i]; if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { groups.push([rect]); } else { groups[groups.length - 1].push(rect); } prevRect = rect; } return groups.map(rect => rectToClientRect(getBoundingRect(rect))); } /** * Provides improved positioning for inline reference elements that can span * over multiple lines, such as hyperlinks or range selections. * @see https://floating-ui.com/docs/inline */ const inline = function (options) { if (options === void 0) { options = {}; } return { name: 'inline', options, async fn(state) { const { placement, elements, rects, platform, strategy } = state; // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a // ClientRect's bounds, despite the event listener being triggered. A // padding of 2 seems to handle this issue. const { padding = 2, x, y } = evaluate(options, state); const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); const clientRects = getRectsByLine(nativeClientRects); const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); const paddingObject = getPaddingObject(padding); function getBoundingClientRect() { // There are two rects and they are disjoined. if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { // Find the first rect in which the point is fully inside. return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; } // There are 2 or more connected rects. if (clientRects.length >= 2) { if (getSideAxis(placement) === 'y') { const firstRect = clientRects[0]; const lastRect = clientRects[clientRects.length - 1]; const isTop = getSide(placement) === 'top'; const top = firstRect.top; const bottom = lastRect.bottom; const left = isTop ? firstRect.left : lastRect.left; const right = isTop ? firstRect.right : lastRect.right; const width = right - left; const height = bottom - top; return { top, bottom, left, right, width, height, x: left, y: top }; } const isLeftSide = getSide(placement) === 'left'; const maxRight = max(...clientRects.map(rect => rect.right)); const minLeft = min(...clientRects.map(rect => rect.left)); const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); const top = measureRects[0].top; const bottom = measureRects[measureRects.length - 1].bottom; const left = minLeft; const right = maxRight; const width = right - left; const height = bottom - top; return { top, bottom, left, right, width, height, x: left, y: top }; } return fallback; } const resetRects = await platform.getElementRects({ reference: { getBoundingClientRect }, floating: elements.floating, strategy }); if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { return { reset: { rects: resetRects } }; } return {}; } }; }; // For type backwards-compatibility, the `OffsetOptions` type was also // Derivable. async function convertValueToCoords(state, options) { const { placement, platform, elements } = state; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const side = getSide(placement); const alignment = getAlignment(placement); const isVertical = getSideAxis(placement) === 'y'; const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1; const crossAxisMulti = rtl && isVertical ? -1 : 1; const rawValue = evaluate(options, state); // eslint-disable-next-line prefer-const let { mainAxis, crossAxis, alignmentAxis } = typeof rawValue === 'number' ? { mainAxis: rawValue, crossAxis: 0, alignmentAxis: null } : { mainAxis: rawValue.mainAxis || 0, crossAxis: rawValue.crossAxis || 0, alignmentAxis: rawValue.alignmentAxis }; if (alignment && typeof alignmentAxis === 'number') { crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; } return isVertical ? { x: crossAxis * crossAxisMulti, y: mainAxis * mainAxisMulti } : { x: mainAxis * mainAxisMulti, y: crossAxis * crossAxisMulti }; } /** * Modifies the placement by translating the floating element along the * specified axes. * A number (shorthand for `mainAxis` or distance), or an axes configuration * object may be passed. * @see https://floating-ui.com/docs/offset */ const offset = function (options) { if (options === void 0) { options = 0; } return { name: 'offset', options, async fn(state) { var _middlewareData$offse, _middlewareData$arrow; const { x, y, placement, middlewareData } = state; const diffCoords = await convertValueToCoords(state, options); // If the placement is the same and the arrow caused an alignment offset // then we don't need to change the positioning coordinates. if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } return { x: x + diffCoords.x, y: y + diffCoords.y, data: { ...diffCoords, placement } }; } }; }; /** * Optimizes the visibility of the floating element by shifting it in order to * keep it in view when it will overflow the clipping boundary. * @see https://floating-ui.com/docs/shift */ const shift = function (options) { if (options === void 0) { options = {}; } return { name: 'shift', options, async fn(state) { const { x, y, placement } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = false, limiter = { fn: _ref => { let { x, y } = _ref; return { x, y }; } }, ...detectOverflowOptions } = evaluate(options, state); const coords = { x, y }; const overflow = await detectOverflow(state, detectOverflowOptions); const crossAxis = getSideAxis(getSide(placement)); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; if (checkMainAxis) { const minSide = mainAxis === 'y' ? 'top' : 'left'; const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; const min = mainAxisCoord + overflow[minSide]; const max = mainAxisCoord - overflow[maxSide]; mainAxisCoord = clamp(min, mainAxisCoord, max); } if (checkCrossAxis) { const minSide = crossAxis === 'y' ? 'top' : 'left'; const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; const min = crossAxisCoord + overflow[minSide]; const max = crossAxisCoord - overflow[maxSide]; crossAxisCoord = clamp(min, crossAxisCoord, max); } const limitedCoords = limiter.fn({ ...state, [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }); return { ...limitedCoords, data: { x: limitedCoords.x - x, y: limitedCoords.y - y, enabled: { [mainAxis]: checkMainAxis, [crossAxis]: checkCrossAxis } } }; } }; }; /** * Built-in `limiter` that will stop `shift()` at a certain point. */ const limitShift = function (options) { if (options === void 0) { options = {}; } return { options, fn(state) { const { x, y, placement, rects, middlewareData } = state; const { offset = 0, mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true } = evaluate(options, state); const coords = { x, y }; const crossAxis = getSideAxis(placement); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; const rawOffset = evaluate(offset, state); const computedOffset = typeof rawOffset === 'number' ? { mainAxis: rawOffset, crossAxis: 0 } : { mainAxis: 0, crossAxis: 0, ...rawOffset }; if (checkMainAxis) { const len = mainAxis === 'y' ? 'height' : 'width'; const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; if (mainAxisCoord < limitMin) { mainAxisCoord = limitMin; } else if (mainAxisCoord > limitMax) { mainAxisCoord = limitMax; } } if (checkCrossAxis) { var _middlewareData$offse, _middlewareData$offse2; const len = mainAxis === 'y' ? 'width' : 'height'; const isOriginSide = ['top', 'left'].includes(getSide(placement)); const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); if (crossAxisCoord < limitMin) { crossAxisCoord = limitMin; } else if (crossAxisCoord > limitMax) { crossAxisCoord = limitMax; } } return { [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }; } }; }; /** * Provides data that allows you to change the size of the floating element — * for instance, prevent it from overflowing the clipping boundary or match the * width of the reference element. * @see https://floating-ui.com/docs/size */ const size = function (options) { if (options === void 0) { options = {}; } return { name: 'size', options, async fn(state) { var _state$middlewareData, _state$middlewareData2; const { placement, rects, platform, elements } = state; const { apply = () => {}, ...detectOverflowOptions } = evaluate(options, state); const overflow = await detectOverflow(state, detectOverflowOptions); const side = getSide(placement); const alignment = getAlignment(placement); const isYAxis = getSideAxis(placement) === 'y'; const { width, height } = rects.floating; let heightSide; let widthSide; if (side === 'top' || side === 'bottom') { heightSide = side; widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; } else { widthSide = side; heightSide = alignment === 'end' ? 'top' : 'bottom'; } const maximumClippingHeight = height - overflow.top - overflow.bottom; const maximumClippingWidth = width - overflow.left - overflow.right; const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); const noShift = !state.middlewareData.shift; let availableHeight = overflowAvailableHeight; let availableWidth = overflowAvailableWidth; if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) { availableWidth = maximumClippingWidth; } if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) { availableHeight = maximumClippingHeight; } if (noShift && !alignment) { const xMin = max(overflow.left, 0); const xMax = max(overflow.right, 0); const yMin = max(overflow.top, 0); const yMax = max(overflow.bottom, 0); if (isYAxis) { availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); } else { availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); } } await apply({ ...state, availableWidth, availableHeight }); const nextDimensions = await platform.getDimensions(elements.floating); if (width !== nextDimensions.width || height !== nextDimensions.height) { return { reset: { rects: true } }; } return {}; } }; }; export { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size }; import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils'; export { rectToClientRect } from '@floating-ui/utils'; function computeCoordsFromPlacement(_ref, placement, rtl) { let { reference, floating } = _ref; const sideAxis = getSideAxis(placement); const alignmentAxis = getAlignmentAxis(placement); const alignLength = getAxisLength(alignmentAxis); const side = getSide(placement); const isVertical = sideAxis === 'y'; const commonX = reference.x + reference.width / 2 - floating.width / 2; const commonY = reference.y + reference.height / 2 - floating.height / 2; const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; let coords; switch (side) { case 'top': coords = { x: commonX, y: reference.y - floating.height }; break; case 'bottom': coords = { x: commonX, y: reference.y + reference.height }; break; case 'right': coords = { x: reference.x + reference.width, y: commonY }; break; case 'left': coords = { x: reference.x - floating.width, y: commonY }; break; default: coords = { x: reference.x, y: reference.y }; } switch (getAlignment(placement)) { case 'start': coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); break; case 'end': coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); break; } return coords; } /** * Computes the `x` and `y` coordinates that will place the floating element * next to a given reference element. * * This export does not have any `platform` interface logic. You will need to * write one for the platform you are using Floating UI with. */ const computePosition = async (reference, floating, config) => { const { placement = 'bottom', strategy = 'absolute', middleware = [], platform } = config; const validMiddleware = middleware.filter(Boolean); const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); let rects = await platform.getElementRects({ reference, floating, strategy }); let { x, y } = computeCoordsFromPlacement(rects, placement, rtl); let statefulPlacement = placement; let middlewareData = {}; let resetCount = 0; for (let i = 0; i < validMiddleware.length; i++) { const { name, fn } = validMiddleware[i]; const { x: nextX, y: nextY, data, reset } = await fn({ x, y, initialPlacement: placement, placement: statefulPlacement, strategy, middlewareData, rects, platform, elements: { reference, floating } }); x = nextX != null ? nextX : x; y = nextY != null ? nextY : y; middlewareData = { ...middlewareData, [name]: { ...middlewareData[name], ...data } }; if (reset && resetCount <= 50) { resetCount++; if (typeof reset === 'object') { if (reset.placement) { statefulPlacement = reset.placement; } if (reset.rects) { rects = reset.rects === true ? await platform.getElementRects({ reference, floating, strategy }) : reset.rects; } ({ x, y } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); } i = -1; } } return { x, y, placement: statefulPlacement, strategy, middlewareData }; }; /** * Resolves with an object of overflow side offsets that determine how much the * element is overflowing a given clipping boundary on each side. * - positive = overflowing the boundary by that number of pixels * - negative = how many pixels left before it will overflow * - 0 = lies flush with the boundary * @see https://floating-ui.com/docs/detectOverflow */ async function detectOverflow(state, options) { var _await$platform$isEle; if (options === void 0) { options = {}; } const { x, y, platform, rects, elements, strategy } = state; const { boundary = 'clippingAncestors', rootBoundary = 'viewport', elementContext = 'floating', altBoundary = false, padding = 0 } = evaluate(options, state); const paddingObject = getPaddingObject(padding); const altContext = elementContext === 'floating' ? 'reference' : 'floating'; const element = elements[altBoundary ? altContext : elementContext]; const clippingClientRect = rectToClientRect(await platform.getClippingRect({ element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), boundary, rootBoundary, strategy })); const rect = elementContext === 'floating' ? { x, y, width: rects.floating.width, height: rects.floating.height } : rects.reference; const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { x: 1, y: 1 } : { x: 1, y: 1 }; const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ elements, rect, offsetParent, strategy }) : rect); return { top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x }; } /** * Provides data to position an inner element of the floating element so that it * appears centered to the reference element. * @see https://floating-ui.com/docs/arrow */ const arrow = options => ({ name: 'arrow', options, async fn(state) { const { x, y, placement, rects, platform, elements, middlewareData } = state; // Since `element` is required, we don't Partial<> the type. const { element, padding = 0 } = evaluate(options, state) || {}; if (element == null) { return {}; } const paddingObject = getPaddingObject(padding); const coords = { x, y }; const axis = getAlignmentAxis(placement); const length = getAxisLength(axis); const arrowDimensions = await platform.getDimensions(element); const isYAxis = axis === 'y'; const minProp = isYAxis ? 'top' : 'left'; const maxProp = isYAxis ? 'bottom' : 'right'; const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; const startDiff = coords[axis] - rects.reference[axis]; const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; // DOM platform can return `window` as the `offsetParent`. if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { clientSize = elements.floating[clientProp] || rects.floating[length]; } const centerToReference = endDiff / 2 - startDiff / 2; // If the padding is large enough that it causes the arrow to no longer be // centered, modify the padding so that it is centered. const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; const minPadding = min(paddingObject[minProp], largestPossiblePadding); const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); // Make sure the arrow doesn't overflow the floating element if the center // point is outside the floating element's bounds. const min$1 = minPadding; const max = clientSize - arrowDimensions[length] - maxPadding; const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; const offset = clamp(min$1, center, max); // If the reference is small enough that the arrow's padding causes it to // to point to nothing for an aligned placement, adjust the offset of the // floating element itself. To ensure `shift()` continues to take action, // a single reset is performed when this is true. const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; return { [axis]: coords[axis] + alignmentOffset, data: { [axis]: offset, centerOffset: center - offset - alignmentOffset, ...(shouldAddOffset && { alignmentOffset }) }, reset: shouldAddOffset }; } }); function getPlacementList(alignment, autoAlignment, allowedPlacements) { const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); return allowedPlacementsSortedByAlignment.filter(placement => { if (alignment) { return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); } return true; }); } /** * Optimizes the visibility of the floating element by choosing the placement * that has the most space available automatically, without needing to specify a * preferred placement. Alternative to `flip`. * @see https://floating-ui.com/docs/autoPlacement */ const autoPlacement = function (options) { if (options === void 0) { options = {}; } return { name: 'autoPlacement', options, async fn(state) { var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; const { rects, middlewareData, placement, platform, elements } = state; const { crossAxis = false, alignment, allowedPlacements = placements, autoAlignment = true, ...detectOverflowOptions } = evaluate(options, state); const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; const overflow = await detectOverflow(state, detectOverflowOptions); const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; const currentPlacement = placements$1[currentIndex]; if (currentPlacement == null) { return {}; } const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); // Make `computeCoords` start from the right place. if (placement !== currentPlacement) { return { reset: { placement: placements$1[0] } }; } const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]]; const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { placement: currentPlacement, overflows: currentOverflows }]; const nextPlacement = placements$1[currentIndex + 1]; // There are more placements to check. if (nextPlacement) { return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: nextPlacement } }; } const placementsSortedByMostSpace = allOverflows.map(d => { const alignment = getAlignment(d.placement); return [d.placement, alignment && crossAxis ? // Check along the mainAxis and main crossAxis side. d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : // Check only the mainAxis. d.overflows[0], d.overflows]; }).sort((a, b) => a[1] - b[1]); const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, // Aligned placements should not check their opposite crossAxis // side. getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; if (resetPlacement !== placement) { return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: resetPlacement } }; } return {}; } }; }; /** * Optimizes the visibility of the floating element by flipping the `placement` * in order to keep it in view when the preferred placement(s) will overflow the * clipping boundary. Alternative to `autoPlacement`. * @see https://floating-ui.com/docs/flip */ const flip = function (options) { if (options === void 0) { options = {}; } return { name: 'flip', options, async fn(state) { var _middlewareData$arrow, _middlewareData$flip; const { placement, middlewareData, rects, initialPlacement, platform, elements } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true, fallbackPlacements: specifiedFallbackPlacements, fallbackStrategy = 'bestFit', fallbackAxisSideDirection = 'none', flipAlignment = true, ...detectOverflowOptions } = evaluate(options, state); // If a reset by the arrow was caused due to an alignment offset being // added, we should skip any logic now since `flip()` has already done its // work. // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643 if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } const side = getSide(placement); const initialSideAxis = getSideAxis(initialPlacement); const isBasePlacement = getSide(initialPlacement) === initialPlacement; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none'; if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) { fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); } const placements = [initialPlacement, ...fallbackPlacements]; const overflow = await detectOverflow(state, detectOverflowOptions); const overflows = []; let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; if (checkMainAxis) { overflows.push(overflow[side]); } if (checkCrossAxis) { const sides = getAlignmentSides(placement, rects, rtl); overflows.push(overflow[sides[0]], overflow[sides[1]]); } overflowsData = [...overflowsData, { placement, overflows }]; // One or more sides is overflowing. if (!overflows.every(side => side <= 0)) { var _middlewareData$flip2, _overflowsData$filter; const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; const nextPlacement = placements[nextIndex]; if (nextPlacement) { var _overflowsData$; const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false; const hasInitialMainAxisOverflow = ((_overflowsData$ = overflowsData[0]) == null ? void 0 : _overflowsData$.overflows[0]) > 0; if (!ignoreCrossAxisOverflow || hasInitialMainAxisOverflow) { // Try next placement and re-run the lifecycle. return { data: { index: nextIndex, overflows: overflowsData }, reset: { placement: nextPlacement } }; } } // First, find the candidates that fit on the mainAxis side of overflow, // then find the placement that fits the best on the main crossAxis side. let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; // Otherwise fallback. if (!resetPlacement) { switch (fallbackStrategy) { case 'bestFit': { var _overflowsData$filter2; const placement = (_overflowsData$filter2 = overflowsData.filter(d => { if (hasFallbackAxisSideDirection) { const currentSideAxis = getSideAxis(d.placement); return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal // reading directions favoring greater width. currentSideAxis === 'y'; } return true; }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; if (placement) { resetPlacement = placement; } break; } case 'initialPlacement': resetPlacement = initialPlacement; break; } } if (placement !== resetPlacement) { return { reset: { placement: resetPlacement } }; } } return {}; } }; }; function getSideOffsets(overflow, rect) { return { top: overflow.top - rect.height, right: overflow.right - rect.width, bottom: overflow.bottom - rect.height, left: overflow.left - rect.width }; } function isAnySideFullyClipped(overflow) { return sides.some(side => overflow[side] >= 0); } /** * Provides data to hide the floating element in applicable situations, such as * when it is not in the same clipping context as the reference element. * @see https://floating-ui.com/docs/hide */ const hide = function (options) { if (options === void 0) { options = {}; } return { name: 'hide', options, async fn(state) { const { rects } = state; const { strategy = 'referenceHidden', ...detectOverflowOptions } = evaluate(options, state); switch (strategy) { case 'referenceHidden': { const overflow = await detectOverflow(state, { ...detectOverflowOptions, elementContext: 'reference' }); const offsets = getSideOffsets(overflow, rects.reference); return { data: { referenceHiddenOffsets: offsets, referenceHidden: isAnySideFullyClipped(offsets) } }; } case 'escaped': { const overflow = await detectOverflow(state, { ...detectOverflowOptions, altBoundary: true }); const offsets = getSideOffsets(overflow, rects.floating); return { data: { escapedOffsets: offsets, escaped: isAnySideFullyClipped(offsets) } }; } default: { return {}; } } } }; }; function getBoundingRect(rects) { const minX = min(...rects.map(rect => rect.left)); const minY = min(...rects.map(rect => rect.top)); const maxX = max(...rects.map(rect => rect.right)); const maxY = max(...rects.map(rect => rect.bottom)); return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; } function getRectsByLine(rects) { const sortedRects = rects.slice().sort((a, b) => a.y - b.y); const groups = []; let prevRect = null; for (let i = 0; i < sortedRects.length; i++) { const rect = sortedRects[i]; if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { groups.push([rect]); } else { groups[groups.length - 1].push(rect); } prevRect = rect; } return groups.map(rect => rectToClientRect(getBoundingRect(rect))); } /** * Provides improved positioning for inline reference elements that can span * over multiple lines, such as hyperlinks or range selections. * @see https://floating-ui.com/docs/inline */ const inline = function (options) { if (options === void 0) { options = {}; } return { name: 'inline', options, async fn(state) { const { placement, elements, rects, platform, strategy } = state; // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a // ClientRect's bounds, despite the event listener being triggered. A // padding of 2 seems to handle this issue. const { padding = 2, x, y } = evaluate(options, state); const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); const clientRects = getRectsByLine(nativeClientRects); const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); const paddingObject = getPaddingObject(padding); function getBoundingClientRect() { // There are two rects and they are disjoined. if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { // Find the first rect in which the point is fully inside. return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; } // There are 2 or more connected rects. if (clientRects.length >= 2) { if (getSideAxis(placement) === 'y') { const firstRect = clientRects[0]; const lastRect = clientRects[clientRects.length - 1]; const isTop = getSide(placement) === 'top'; const top = firstRect.top; const bottom = lastRect.bottom; const left = isTop ? firstRect.left : lastRect.left; const right = isTop ? firstRect.right : lastRect.right; const width = right - left; const height = bottom - top; return { top, bottom, left, right, width, height, x: left, y: top }; } const isLeftSide = getSide(placement) === 'left'; const maxRight = max(...clientRects.map(rect => rect.right)); const minLeft = min(...clientRects.map(rect => rect.left)); const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); const top = measureRects[0].top; const bottom = measureRects[measureRects.length - 1].bottom; const left = minLeft; const right = maxRight; const width = right - left; const height = bottom - top; return { top, bottom, left, right, width, height, x: left, y: top }; } return fallback; } const resetRects = await platform.getElementRects({ reference: { getBoundingClientRect }, floating: elements.floating, strategy }); if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { return { reset: { rects: resetRects } }; } return {}; } }; }; // For type backwards-compatibility, the `OffsetOptions` type was also // Derivable. async function convertValueToCoords(state, options) { const { placement, platform, elements } = state; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const side = getSide(placement); const alignment = getAlignment(placement); const isVertical = getSideAxis(placement) === 'y'; const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1; const crossAxisMulti = rtl && isVertical ? -1 : 1; const rawValue = evaluate(options, state); // eslint-disable-next-line prefer-const let { mainAxis, crossAxis, alignmentAxis } = typeof rawValue === 'number' ? { mainAxis: rawValue, crossAxis: 0, alignmentAxis: null } : { mainAxis: rawValue.mainAxis || 0, crossAxis: rawValue.crossAxis || 0, alignmentAxis: rawValue.alignmentAxis }; if (alignment && typeof alignmentAxis === 'number') { crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; } return isVertical ? { x: crossAxis * crossAxisMulti, y: mainAxis * mainAxisMulti } : { x: mainAxis * mainAxisMulti, y: crossAxis * crossAxisMulti }; } /** * Modifies the placement by translating the floating element along the * specified axes. * A number (shorthand for `mainAxis` or distance), or an axes configuration * object may be passed. * @see https://floating-ui.com/docs/offset */ const offset = function (options) { if (options === void 0) { options = 0; } return { name: 'offset', options, async fn(state) { var _middlewareData$offse, _middlewareData$arrow; const { x, y, placement, middlewareData } = state; const diffCoords = await convertValueToCoords(state, options); // If the placement is the same and the arrow caused an alignment offset // then we don't need to change the positioning coordinates. if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } return { x: x + diffCoords.x, y: y + diffCoords.y, data: { ...diffCoords, placement } }; } }; }; /** * Optimizes the visibility of the floating element by shifting it in order to * keep it in view when it will overflow the clipping boundary. * @see https://floating-ui.com/docs/shift */ const shift = function (options) { if (options === void 0) { options = {}; } return { name: 'shift', options, async fn(state) { const { x, y, placement } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = false, limiter = { fn: _ref => { let { x, y } = _ref; return { x, y }; } }, ...detectOverflowOptions } = evaluate(options, state); const coords = { x, y }; const overflow = await detectOverflow(state, detectOverflowOptions); const crossAxis = getSideAxis(getSide(placement)); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; if (checkMainAxis) { const minSide = mainAxis === 'y' ? 'top' : 'left'; const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; const min = mainAxisCoord + overflow[minSide]; const max = mainAxisCoord - overflow[maxSide]; mainAxisCoord = clamp(min, mainAxisCoord, max); } if (checkCrossAxis) { const minSide = crossAxis === 'y' ? 'top' : 'left'; const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; const min = crossAxisCoord + overflow[minSide]; const max = crossAxisCoord - overflow[maxSide]; crossAxisCoord = clamp(min, crossAxisCoord, max); } const limitedCoords = limiter.fn({ ...state, [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }); return { ...limitedCoords, data: { x: limitedCoords.x - x, y: limitedCoords.y - y, enabled: { [mainAxis]: checkMainAxis, [crossAxis]: checkCrossAxis } } }; } }; }; /** * Built-in `limiter` that will stop `shift()` at a certain point. */ const limitShift = function (options) { if (options === void 0) { options = {}; } return { options, fn(state) { const { x, y, placement, rects, middlewareData } = state; const { offset = 0, mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true } = evaluate(options, state); const coords = { x, y }; const crossAxis = getSideAxis(placement); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; const rawOffset = evaluate(offset, state); const computedOffset = typeof rawOffset === 'number' ? { mainAxis: rawOffset, crossAxis: 0 } : { mainAxis: 0, crossAxis: 0, ...rawOffset }; if (checkMainAxis) { const len = mainAxis === 'y' ? 'height' : 'width'; const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; if (mainAxisCoord < limitMin) { mainAxisCoord = limitMin; } else if (mainAxisCoord > limitMax) { mainAxisCoord = limitMax; } } if (checkCrossAxis) { var _middlewareData$offse, _middlewareData$offse2; const len = mainAxis === 'y' ? 'width' : 'height'; const isOriginSide = ['top', 'left'].includes(getSide(placement)); const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); if (crossAxisCoord < limitMin) { crossAxisCoord = limitMin; } else if (crossAxisCoord > limitMax) { crossAxisCoord = limitMax; } } return { [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }; } }; }; /** * Provides data that allows you to change the size of the floating element — * for instance, prevent it from overflowing the clipping boundary or match the * width of the reference element. * @see https://floating-ui.com/docs/size */ const size = function (options) { if (options === void 0) { options = {}; } return { name: 'size', options, async fn(state) { var _state$middlewareData, _state$middlewareData2; const { placement, rects, platform, elements } = state; const { apply = () => {}, ...detectOverflowOptions } = evaluate(options, state); const overflow = await detectOverflow(state, detectOverflowOptions); const side = getSide(placement); const alignment = getAlignment(placement); const isYAxis = getSideAxis(placement) === 'y'; const { width, height } = rects.floating; let heightSide; let widthSide; if (side === 'top' || side === 'bottom') { heightSide = side; widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; } else { widthSide = side; heightSide = alignment === 'end' ? 'top' : 'bottom'; } const maximumClippingHeight = height - overflow.top - overflow.bottom; const maximumClippingWidth = width - overflow.left - overflow.right; const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); const noShift = !state.middlewareData.shift; let availableHeight = overflowAvailableHeight; let availableWidth = overflowAvailableWidth; if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) { availableWidth = maximumClippingWidth; } if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) { availableHeight = maximumClippingHeight; } if (noShift && !alignment) { const xMin = max(overflow.left, 0); const xMax = max(overflow.right, 0); const yMin = max(overflow.top, 0); const yMax = max(overflow.bottom, 0); if (isYAxis) { availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); } else { availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); } } await apply({ ...state, availableWidth, availableHeight }); const nextDimensions = await platform.getDimensions(elements.floating); if (width !== nextDimensions.width || height !== nextDimensions.height) { return { reset: { rects: true } }; } return {}; } }; }; export { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size }; (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.FloatingUICore = {})); })(this, (function (exports) { 'use strict'; /** * Custom positioning reference element. * @see https://floating-ui.com/docs/virtual-elements */ const sides = ['top', 'right', 'bottom', 'left']; const alignments = ['start', 'end']; const placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + "-" + alignments[0], side + "-" + alignments[1]), []); const min = Math.min; const max = Math.max; const oppositeSideMap = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; const oppositeAlignmentMap = { start: 'end', end: 'start' }; function clamp(start, value, end) { return max(start, min(value, end)); } function evaluate(value, param) { return typeof value === 'function' ? value(param) : value; } function getSide(placement) { return placement.split('-')[0]; } function getAlignment(placement) { return placement.split('-')[1]; } function getOppositeAxis(axis) { return axis === 'x' ? 'y' : 'x'; } function getAxisLength(axis) { return axis === 'y' ? 'height' : 'width'; } function getSideAxis(placement) { return ['top', 'bottom'].includes(getSide(placement)) ? 'y' : 'x'; } function getAlignmentAxis(placement) { return getOppositeAxis(getSideAxis(placement)); } function getAlignmentSides(placement, rects, rtl) { if (rtl === void 0) { rtl = false; } const alignment = getAlignment(placement); const alignmentAxis = getAlignmentAxis(placement); const length = getAxisLength(alignmentAxis); let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top'; if (rects.reference[length] > rects.floating[length]) { mainAlignmentSide = getOppositePlacement(mainAlignmentSide); } return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)]; } function getExpandedPlacements(placement) { const oppositePlacement = getOppositePlacement(placement); return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)]; } function getOppositeAlignmentPlacement(placement) { return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]); } function getSideList(side, isStart, rtl) { const lr = ['left', 'right']; const rl = ['right', 'left']; const tb = ['top', 'bottom']; const bt = ['bottom', 'top']; switch (side) { case 'top': case 'bottom': if (rtl) return isStart ? rl : lr; return isStart ? lr : rl; case 'left': case 'right': return isStart ? tb : bt; default: return []; } } function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { const alignment = getAlignment(placement); let list = getSideList(getSide(placement), direction === 'start', rtl); if (alignment) { list = list.map(side => side + "-" + alignment); if (flipAlignment) { list = list.concat(list.map(getOppositeAlignmentPlacement)); } } return list; } function getOppositePlacement(placement) { return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]); } function expandPaddingObject(padding) { return { top: 0, right: 0, bottom: 0, left: 0, ...padding }; } function getPaddingObject(padding) { return typeof padding !== 'number' ? expandPaddingObject(padding) : { top: padding, right: padding, bottom: padding, left: padding }; } function rectToClientRect(rect) { const { x, y, width, height } = rect; return { width, height, top: y, left: x, right: x + width, bottom: y + height, x, y }; } function computeCoordsFromPlacement(_ref, placement, rtl) { let { reference, floating } = _ref; const sideAxis = getSideAxis(placement); const alignmentAxis = getAlignmentAxis(placement); const alignLength = getAxisLength(alignmentAxis); const side = getSide(placement); const isVertical = sideAxis === 'y'; const commonX = reference.x + reference.width / 2 - floating.width / 2; const commonY = reference.y + reference.height / 2 - floating.height / 2; const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; let coords; switch (side) { case 'top': coords = { x: commonX, y: reference.y - floating.height }; break; case 'bottom': coords = { x: commonX, y: reference.y + reference.height }; break; case 'right': coords = { x: reference.x + reference.width, y: commonY }; break; case 'left': coords = { x: reference.x - floating.width, y: commonY }; break; default: coords = { x: reference.x, y: reference.y }; } switch (getAlignment(placement)) { case 'start': coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); break; case 'end': coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); break; } return coords; } /** * Computes the `x` and `y` coordinates that will place the floating element * next to a given reference element. * * This export does not have any `platform` interface logic. You will need to * write one for the platform you are using Floating UI with. */ const computePosition = async (reference, floating, config) => { const { placement = 'bottom', strategy = 'absolute', middleware = [], platform } = config; const validMiddleware = middleware.filter(Boolean); const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); let rects = await platform.getElementRects({ reference, floating, strategy }); let { x, y } = computeCoordsFromPlacement(rects, placement, rtl); let statefulPlacement = placement; let middlewareData = {}; let resetCount = 0; for (let i = 0; i < validMiddleware.length; i++) { const { name, fn } = validMiddleware[i]; const { x: nextX, y: nextY, data, reset } = await fn({ x, y, initialPlacement: placement, placement: statefulPlacement, strategy, middlewareData, rects, platform, elements: { reference, floating } }); x = nextX != null ? nextX : x; y = nextY != null ? nextY : y; middlewareData = { ...middlewareData, [name]: { ...middlewareData[name], ...data } }; if (reset && resetCount <= 50) { resetCount++; if (typeof reset === 'object') { if (reset.placement) { statefulPlacement = reset.placement; } if (reset.rects) { rects = reset.rects === true ? await platform.getElementRects({ reference, floating, strategy }) : reset.rects; } ({ x, y } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); } i = -1; } } return { x, y, placement: statefulPlacement, strategy, middlewareData }; }; /** * Resolves with an object of overflow side offsets that determine how much the * element is overflowing a given clipping boundary on each side. * - positive = overflowing the boundary by that number of pixels * - negative = how many pixels left before it will overflow * - 0 = lies flush with the boundary * @see https://floating-ui.com/docs/detectOverflow */ async function detectOverflow(state, options) { var _await$platform$isEle; if (options === void 0) { options = {}; } const { x, y, platform, rects, elements, strategy } = state; const { boundary = 'clippingAncestors', rootBoundary = 'viewport', elementContext = 'floating', altBoundary = false, padding = 0 } = evaluate(options, state); const paddingObject = getPaddingObject(padding); const altContext = elementContext === 'floating' ? 'reference' : 'floating'; const element = elements[altBoundary ? altContext : elementContext]; const clippingClientRect = rectToClientRect(await platform.getClippingRect({ element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), boundary, rootBoundary, strategy })); const rect = elementContext === 'floating' ? { x, y, width: rects.floating.width, height: rects.floating.height } : rects.reference; const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { x: 1, y: 1 } : { x: 1, y: 1 }; const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ elements, rect, offsetParent, strategy }) : rect); return { top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x }; } /** * Provides data to position an inner element of the floating element so that it * appears centered to the reference element. * @see https://floating-ui.com/docs/arrow */ const arrow = options => ({ name: 'arrow', options, async fn(state) { const { x, y, placement, rects, platform, elements, middlewareData } = state; // Since `element` is required, we don't Partial<> the type. const { element, padding = 0 } = evaluate(options, state) || {}; if (element == null) { return {}; } const paddingObject = getPaddingObject(padding); const coords = { x, y }; const axis = getAlignmentAxis(placement); const length = getAxisLength(axis); const arrowDimensions = await platform.getDimensions(element); const isYAxis = axis === 'y'; const minProp = isYAxis ? 'top' : 'left'; const maxProp = isYAxis ? 'bottom' : 'right'; const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; const startDiff = coords[axis] - rects.reference[axis]; const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; // DOM platform can return `window` as the `offsetParent`. if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { clientSize = elements.floating[clientProp] || rects.floating[length]; } const centerToReference = endDiff / 2 - startDiff / 2; // If the padding is large enough that it causes the arrow to no longer be // centered, modify the padding so that it is centered. const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; const minPadding = min(paddingObject[minProp], largestPossiblePadding); const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); // Make sure the arrow doesn't overflow the floating element if the center // point is outside the floating element's bounds. const min$1 = minPadding; const max = clientSize - arrowDimensions[length] - maxPadding; const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; const offset = clamp(min$1, center, max); // If the reference is small enough that the arrow's padding causes it to // to point to nothing for an aligned placement, adjust the offset of the // floating element itself. To ensure `shift()` continues to take action, // a single reset is performed when this is true. const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; return { [axis]: coords[axis] + alignmentOffset, data: { [axis]: offset, centerOffset: center - offset - alignmentOffset, ...(shouldAddOffset && { alignmentOffset }) }, reset: shouldAddOffset }; } }); function getPlacementList(alignment, autoAlignment, allowedPlacements) { const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); return allowedPlacementsSortedByAlignment.filter(placement => { if (alignment) { return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); } return true; }); } /** * Optimizes the visibility of the floating element by choosing the placement * that has the most space available automatically, without needing to specify a * preferred placement. Alternative to `flip`. * @see https://floating-ui.com/docs/autoPlacement */ const autoPlacement = function (options) { if (options === void 0) { options = {}; } return { name: 'autoPlacement', options, async fn(state) { var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; const { rects, middlewareData, placement, platform, elements } = state; const { crossAxis = false, alignment, allowedPlacements = placements, autoAlignment = true, ...detectOverflowOptions } = evaluate(options, state); const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; const overflow = await detectOverflow(state, detectOverflowOptions); const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; const currentPlacement = placements$1[currentIndex]; if (currentPlacement == null) { return {}; } const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); // Make `computeCoords` start from the right place. if (placement !== currentPlacement) { return { reset: { placement: placements$1[0] } }; } const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]]; const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { placement: currentPlacement, overflows: currentOverflows }]; const nextPlacement = placements$1[currentIndex + 1]; // There are more placements to check. if (nextPlacement) { return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: nextPlacement } }; } const placementsSortedByMostSpace = allOverflows.map(d => { const alignment = getAlignment(d.placement); return [d.placement, alignment && crossAxis ? // Check along the mainAxis and main crossAxis side. d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : // Check only the mainAxis. d.overflows[0], d.overflows]; }).sort((a, b) => a[1] - b[1]); const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, // Aligned placements should not check their opposite crossAxis // side. getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; if (resetPlacement !== placement) { return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: resetPlacement } }; } return {}; } }; }; /** * Optimizes the visibility of the floating element by flipping the `placement` * in order to keep it in view when the preferred placement(s) will overflow the * clipping boundary. Alternative to `autoPlacement`. * @see https://floating-ui.com/docs/flip */ const flip = function (options) { if (options === void 0) { options = {}; } return { name: 'flip', options, async fn(state) { var _middlewareData$arrow, _middlewareData$flip; const { placement, middlewareData, rects, initialPlacement, platform, elements } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true, fallbackPlacements: specifiedFallbackPlacements, fallbackStrategy = 'bestFit', fallbackAxisSideDirection = 'none', flipAlignment = true, ...detectOverflowOptions } = evaluate(options, state); // If a reset by the arrow was caused due to an alignment offset being // added, we should skip any logic now since `flip()` has already done its // work. // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643 if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } const side = getSide(placement); const initialSideAxis = getSideAxis(initialPlacement); const isBasePlacement = getSide(initialPlacement) === initialPlacement; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none'; if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) { fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); } const placements = [initialPlacement, ...fallbackPlacements]; const overflow = await detectOverflow(state, detectOverflowOptions); const overflows = []; let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; if (checkMainAxis) { overflows.push(overflow[side]); } if (checkCrossAxis) { const sides = getAlignmentSides(placement, rects, rtl); overflows.push(overflow[sides[0]], overflow[sides[1]]); } overflowsData = [...overflowsData, { placement, overflows }]; // One or more sides is overflowing. if (!overflows.every(side => side <= 0)) { var _middlewareData$flip2, _overflowsData$filter; const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; const nextPlacement = placements[nextIndex]; if (nextPlacement) { var _overflowsData$; const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false; const hasInitialMainAxisOverflow = ((_overflowsData$ = overflowsData[0]) == null ? void 0 : _overflowsData$.overflows[0]) > 0; if (!ignoreCrossAxisOverflow || hasInitialMainAxisOverflow) { // Try next placement and re-run the lifecycle. return { data: { index: nextIndex, overflows: overflowsData }, reset: { placement: nextPlacement } }; } } // First, find the candidates that fit on the mainAxis side of overflow, // then find the placement that fits the best on the main crossAxis side. let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; // Otherwise fallback. if (!resetPlacement) { switch (fallbackStrategy) { case 'bestFit': { var _overflowsData$filter2; const placement = (_overflowsData$filter2 = overflowsData.filter(d => { if (hasFallbackAxisSideDirection) { const currentSideAxis = getSideAxis(d.placement); return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal // reading directions favoring greater width. currentSideAxis === 'y'; } return true; }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; if (placement) { resetPlacement = placement; } break; } case 'initialPlacement': resetPlacement = initialPlacement; break; } } if (placement !== resetPlacement) { return { reset: { placement: resetPlacement } }; } } return {}; } }; }; function getSideOffsets(overflow, rect) { return { top: overflow.top - rect.height, right: overflow.right - rect.width, bottom: overflow.bottom - rect.height, left: overflow.left - rect.width }; } function isAnySideFullyClipped(overflow) { return sides.some(side => overflow[side] >= 0); } /** * Provides data to hide the floating element in applicable situations, such as * when it is not in the same clipping context as the reference element. * @see https://floating-ui.com/docs/hide */ const hide = function (options) { if (options === void 0) { options = {}; } return { name: 'hide', options, async fn(state) { const { rects } = state; const { strategy = 'referenceHidden', ...detectOverflowOptions } = evaluate(options, state); switch (strategy) { case 'referenceHidden': { const overflow = await detectOverflow(state, { ...detectOverflowOptions, elementContext: 'reference' }); const offsets = getSideOffsets(overflow, rects.reference); return { data: { referenceHiddenOffsets: offsets, referenceHidden: isAnySideFullyClipped(offsets) } }; } case 'escaped': { const overflow = await detectOverflow(state, { ...detectOverflowOptions, altBoundary: true }); const offsets = getSideOffsets(overflow, rects.floating); return { data: { escapedOffsets: offsets, escaped: isAnySideFullyClipped(offsets) } }; } default: { return {}; } } } }; }; function getBoundingRect(rects) { const minX = min(...rects.map(rect => rect.left)); const minY = min(...rects.map(rect => rect.top)); const maxX = max(...rects.map(rect => rect.right)); const maxY = max(...rects.map(rect => rect.bottom)); return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; } function getRectsByLine(rects) { const sortedRects = rects.slice().sort((a, b) => a.y - b.y); const groups = []; let prevRect = null; for (let i = 0; i < sortedRects.length; i++) { const rect = sortedRects[i]; if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { groups.push([rect]); } else { groups[groups.length - 1].push(rect); } prevRect = rect; } return groups.map(rect => rectToClientRect(getBoundingRect(rect))); } /** * Provides improved positioning for inline reference elements that can span * over multiple lines, such as hyperlinks or range selections. * @see https://floating-ui.com/docs/inline */ const inline = function (options) { if (options === void 0) { options = {}; } return { name: 'inline', options, async fn(state) { const { placement, elements, rects, platform, strategy } = state; // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a // ClientRect's bounds, despite the event listener being triggered. A // padding of 2 seems to handle this issue. const { padding = 2, x, y } = evaluate(options, state); const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); const clientRects = getRectsByLine(nativeClientRects); const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); const paddingObject = getPaddingObject(padding); function getBoundingClientRect() { // There are two rects and they are disjoined. if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { // Find the first rect in which the point is fully inside. return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; } // There are 2 or more connected rects. if (clientRects.length >= 2) { if (getSideAxis(placement) === 'y') { const firstRect = clientRects[0]; const lastRect = clientRects[clientRects.length - 1]; const isTop = getSide(placement) === 'top'; const top = firstRect.top; const bottom = lastRect.bottom; const left = isTop ? firstRect.left : lastRect.left; const right = isTop ? firstRect.right : lastRect.right; const width = right - left; const height = bottom - top; return { top, bottom, left, right, width, height, x: left, y: top }; } const isLeftSide = getSide(placement) === 'left'; const maxRight = max(...clientRects.map(rect => rect.right)); const minLeft = min(...clientRects.map(rect => rect.left)); const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); const top = measureRects[0].top; const bottom = measureRects[measureRects.length - 1].bottom; const left = minLeft; const right = maxRight; const width = right - left; const height = bottom - top; return { top, bottom, left, right, width, height, x: left, y: top }; } return fallback; } const resetRects = await platform.getElementRects({ reference: { getBoundingClientRect }, floating: elements.floating, strategy }); if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { return { reset: { rects: resetRects } }; } return {}; } }; }; // For type backwards-compatibility, the `OffsetOptions` type was also // Derivable. async function convertValueToCoords(state, options) { const { placement, platform, elements } = state; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const side = getSide(placement); const alignment = getAlignment(placement); const isVertical = getSideAxis(placement) === 'y'; const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1; const crossAxisMulti = rtl && isVertical ? -1 : 1; const rawValue = evaluate(options, state); // eslint-disable-next-line prefer-const let { mainAxis, crossAxis, alignmentAxis } = typeof rawValue === 'number' ? { mainAxis: rawValue, crossAxis: 0, alignmentAxis: null } : { mainAxis: rawValue.mainAxis || 0, crossAxis: rawValue.crossAxis || 0, alignmentAxis: rawValue.alignmentAxis }; if (alignment && typeof alignmentAxis === 'number') { crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; } return isVertical ? { x: crossAxis * crossAxisMulti, y: mainAxis * mainAxisMulti } : { x: mainAxis * mainAxisMulti, y: crossAxis * crossAxisMulti }; } /** * Modifies the placement by translating the floating element along the * specified axes. * A number (shorthand for `mainAxis` or distance), or an axes configuration * object may be passed. * @see https://floating-ui.com/docs/offset */ const offset = function (options) { if (options === void 0) { options = 0; } return { name: 'offset', options, async fn(state) { var _middlewareData$offse, _middlewareData$arrow; const { x, y, placement, middlewareData } = state; const diffCoords = await convertValueToCoords(state, options); // If the placement is the same and the arrow caused an alignment offset // then we don't need to change the positioning coordinates. if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } return { x: x + diffCoords.x, y: y + diffCoords.y, data: { ...diffCoords, placement } }; } }; }; /** * Optimizes the visibility of the floating element by shifting it in order to * keep it in view when it will overflow the clipping boundary. * @see https://floating-ui.com/docs/shift */ const shift = function (options) { if (options === void 0) { options = {}; } return { name: 'shift', options, async fn(state) { const { x, y, placement } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = false, limiter = { fn: _ref => { let { x, y } = _ref; return { x, y }; } }, ...detectOverflowOptions } = evaluate(options, state); const coords = { x, y }; const overflow = await detectOverflow(state, detectOverflowOptions); const crossAxis = getSideAxis(getSide(placement)); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; if (checkMainAxis) { const minSide = mainAxis === 'y' ? 'top' : 'left'; const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; const min = mainAxisCoord + overflow[minSide]; const max = mainAxisCoord - overflow[maxSide]; mainAxisCoord = clamp(min, mainAxisCoord, max); } if (checkCrossAxis) { const minSide = crossAxis === 'y' ? 'top' : 'left'; const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; const min = crossAxisCoord + overflow[minSide]; const max = crossAxisCoord - overflow[maxSide]; crossAxisCoord = clamp(min, crossAxisCoord, max); } const limitedCoords = limiter.fn({ ...state, [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }); return { ...limitedCoords, data: { x: limitedCoords.x - x, y: limitedCoords.y - y, enabled: { [mainAxis]: checkMainAxis, [crossAxis]: checkCrossAxis } } }; } }; }; /** * Built-in `limiter` that will stop `shift()` at a certain point. */ const limitShift = function (options) { if (options === void 0) { options = {}; } return { options, fn(state) { const { x, y, placement, rects, middlewareData } = state; const { offset = 0, mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true } = evaluate(options, state); const coords = { x, y }; const crossAxis = getSideAxis(placement); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; const rawOffset = evaluate(offset, state); const computedOffset = typeof rawOffset === 'number' ? { mainAxis: rawOffset, crossAxis: 0 } : { mainAxis: 0, crossAxis: 0, ...rawOffset }; if (checkMainAxis) { const len = mainAxis === 'y' ? 'height' : 'width'; const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; if (mainAxisCoord < limitMin) { mainAxisCoord = limitMin; } else if (mainAxisCoord > limitMax) { mainAxisCoord = limitMax; } } if (checkCrossAxis) { var _middlewareData$offse, _middlewareData$offse2; const len = mainAxis === 'y' ? 'width' : 'height'; const isOriginSide = ['top', 'left'].includes(getSide(placement)); const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); if (crossAxisCoord < limitMin) { crossAxisCoord = limitMin; } else if (crossAxisCoord > limitMax) { crossAxisCoord = limitMax; } } return { [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }; } }; }; /** * Provides data that allows you to change the size of the floating element — * for instance, prevent it from overflowing the clipping boundary or match the * width of the reference element. * @see https://floating-ui.com/docs/size */ const size = function (options) { if (options === void 0) { options = {}; } return { name: 'size', options, async fn(state) { var _state$middlewareData, _state$middlewareData2; const { placement, rects, platform, elements } = state; const { apply = () => {}, ...detectOverflowOptions } = evaluate(options, state); const overflow = await detectOverflow(state, detectOverflowOptions); const side = getSide(placement); const alignment = getAlignment(placement); const isYAxis = getSideAxis(placement) === 'y'; const { width, height } = rects.floating; let heightSide; let widthSide; if (side === 'top' || side === 'bottom') { heightSide = side; widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; } else { widthSide = side; heightSide = alignment === 'end' ? 'top' : 'bottom'; } const maximumClippingHeight = height - overflow.top - overflow.bottom; const maximumClippingWidth = width - overflow.left - overflow.right; const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); const noShift = !state.middlewareData.shift; let availableHeight = overflowAvailableHeight; let availableWidth = overflowAvailableWidth; if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) { availableWidth = maximumClippingWidth; } if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) { availableHeight = maximumClippingHeight; } if (noShift && !alignment) { const xMin = max(overflow.left, 0); const xMax = max(overflow.right, 0); const yMin = max(overflow.top, 0); const yMax = max(overflow.bottom, 0); if (isYAxis) { availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); } else { availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); } } await apply({ ...state, availableWidth, availableHeight }); const nextDimensions = await platform.getDimensions(elements.floating); if (width !== nextDimensions.width || height !== nextDimensions.height) { return { reset: { rects: true } }; } return {}; } }; }; exports.arrow = arrow; exports.autoPlacement = autoPlacement; exports.computePosition = computePosition; exports.detectOverflow = detectOverflow; exports.flip = flip; exports.hide = hide; exports.inline = inline; exports.limitShift = limitShift; exports.offset = offset; exports.rectToClientRect = rectToClientRect; exports.shift = shift; exports.size = size; })); !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).FloatingUICore={})}(this,(function(t){"use strict";const e=["top","right","bottom","left"],n=["start","end"],i=e.reduce(((t,e)=>t.concat(e,e+"-"+n[0],e+"-"+n[1])),[]),o=Math.min,r=Math.max,a={left:"right",right:"left",bottom:"top",top:"bottom"},l={start:"end",end:"start"};function s(t,e,n){return r(t,o(e,n))}function f(t,e){return"function"==typeof t?t(e):t}function c(t){return t.split("-")[0]}function u(t){return t.split("-")[1]}function m(t){return"x"===t?"y":"x"}function d(t){return"y"===t?"height":"width"}function g(t){return["top","bottom"].includes(c(t))?"y":"x"}function p(t){return m(g(t))}function h(t,e,n){void 0===n&&(n=!1);const i=u(t),o=p(t),r=d(o);let a="x"===o?i===(n?"end":"start")?"right":"left":"start"===i?"bottom":"top";return e.reference[r]>e.floating[r]&&(a=w(a)),[a,w(a)]}function y(t){return t.replace(/start|end/g,(t=>l[t]))}function w(t){return t.replace(/left|right|bottom|top/g,(t=>a[t]))}function x(t){return"number"!=typeof t?function(t){return{top:0,right:0,bottom:0,left:0,...t}}(t):{top:t,right:t,bottom:t,left:t}}function v(t){const{x:e,y:n,width:i,height:o}=t;return{width:i,height:o,top:n,left:e,right:e+i,bottom:n+o,x:e,y:n}}function b(t,e,n){let{reference:i,floating:o}=t;const r=g(e),a=p(e),l=d(a),s=c(e),f="y"===r,m=i.x+i.width/2-o.width/2,h=i.y+i.height/2-o.height/2,y=i[l]/2-o[l]/2;let w;switch(s){case"top":w={x:m,y:i.y-o.height};break;case"bottom":w={x:m,y:i.y+i.height};break;case"right":w={x:i.x+i.width,y:h};break;case"left":w={x:i.x-o.width,y:h};break;default:w={x:i.x,y:i.y}}switch(u(e)){case"start":w[a]-=y*(n&&f?-1:1);break;case"end":w[a]+=y*(n&&f?-1:1)}return w}async function A(t,e){var n;void 0===e&&(e={});const{x:i,y:o,platform:r,rects:a,elements:l,strategy:s}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:m="floating",altBoundary:d=!1,padding:g=0}=f(e,t),p=x(g),h=l[d?"floating"===m?"reference":"floating":m],y=v(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(h)))||n?h:h.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(l.floating)),boundary:c,rootBoundary:u,strategy:s})),w="floating"===m?{x:i,y:o,width:a.floating.width,height:a.floating.height}:a.reference,b=await(null==r.getOffsetParent?void 0:r.getOffsetParent(l.floating)),A=await(null==r.isElement?void 0:r.isElement(b))&&await(null==r.getScale?void 0:r.getScale(b))||{x:1,y:1},R=v(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:w,offsetParent:b,strategy:s}):w);return{top:(y.top-R.top+p.top)/A.y,bottom:(R.bottom-y.bottom+p.bottom)/A.y,left:(y.left-R.left+p.left)/A.x,right:(R.right-y.right+p.right)/A.x}}function R(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function P(t){return e.some((e=>t[e]>=0))}function D(t){const e=o(...t.map((t=>t.left))),n=o(...t.map((t=>t.top)));return{x:e,y:n,width:r(...t.map((t=>t.right)))-e,height:r(...t.map((t=>t.bottom)))-n}}t.arrow=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:i,placement:r,rects:a,platform:l,elements:c,middlewareData:m}=e,{element:g,padding:h=0}=f(t,e)||{};if(null==g)return{};const y=x(h),w={x:n,y:i},v=p(r),b=d(v),A=await l.getDimensions(g),R="y"===v,P=R?"top":"left",D=R?"bottom":"right",T=R?"clientHeight":"clientWidth",O=a.reference[b]+a.reference[v]-w[v]-a.floating[b],E=w[v]-a.reference[v],L=await(null==l.getOffsetParent?void 0:l.getOffsetParent(g));let k=L?L[T]:0;k&&await(null==l.isElement?void 0:l.isElement(L))||(k=c.floating[T]||a.floating[b]);const C=O/2-E/2,B=k/2-A[b]/2-1,H=o(y[P],B),S=o(y[D],B),F=H,j=k-A[b]-S,z=k/2-A[b]/2+C,M=s(F,z,j),V=!m.arrow&&null!=u(r)&&z!==M&&a.reference[b]/2-(zu(e)===t)),...n.filter((e=>u(e)!==t))]:n.filter((t=>c(t)===t))).filter((n=>!t||u(n)===t||!!e&&y(n)!==n))}(p||null,x,w):w,R=await A(e,v),P=(null==(n=l.autoPlacement)?void 0:n.index)||0,D=b[P];if(null==D)return{};const T=h(D,a,await(null==m.isRTL?void 0:m.isRTL(d.floating)));if(s!==D)return{reset:{placement:b[0]}};const O=[R[c(D)],R[T[0]],R[T[1]]],E=[...(null==(o=l.autoPlacement)?void 0:o.overflows)||[],{placement:D,overflows:O}],L=b[P+1];if(L)return{data:{index:P+1,overflows:E},reset:{placement:L}};const k=E.map((t=>{const e=u(t.placement);return[t.placement,e&&g?t.overflows.slice(0,2).reduce(((t,e)=>t+e),0):t.overflows[0],t.overflows]})).sort(((t,e)=>t[1]-e[1])),C=(null==(r=k.filter((t=>t[2].slice(0,u(t[0])?2:3).every((t=>t<=0))))[0])?void 0:r[0])||k[0][0];return C!==s?{data:{index:P+1,overflows:E},reset:{placement:C}}:{}}}},t.computePosition=async(t,e,n)=>{const{placement:i="bottom",strategy:o="absolute",middleware:r=[],platform:a}=n,l=r.filter(Boolean),s=await(null==a.isRTL?void 0:a.isRTL(e));let f=await a.getElementRects({reference:t,floating:e,strategy:o}),{x:c,y:u}=b(f,i,s),m=i,d={},g=0;for(let n=0;nt+"-"+o)),e&&(r=r.concat(r.map(y)))),r}(l,R,b,E));const C=[l,...L],B=await A(e,P),H=[];let S=(null==(i=r.flip)?void 0:i.overflows)||[];if(d&&H.push(B[D]),p){const t=h(o,a,E);H.push(B[t[0]],B[t[1]])}if(S=[...S,{placement:o,overflows:H}],!H.every((t=>t<=0))){var F,j;const t=((null==(F=r.flip)?void 0:F.index)||0)+1,e=C[t];if(e){var z;const n="alignment"===p&&T!==g(e),i=(null==(z=S[0])?void 0:z.overflows[0])>0;if(!n||i)return{data:{index:t,overflows:S},reset:{placement:e}}}let n=null==(j=S.filter((t=>t.overflows[0]<=0)).sort(((t,e)=>t.overflows[1]-e.overflows[1]))[0])?void 0:j.placement;if(!n)switch(v){case"bestFit":{var M;const t=null==(M=S.filter((t=>{if(k){const e=g(t.placement);return e===T||"y"===e}return!0})).map((t=>[t.placement,t.overflows.filter((t=>t>0)).reduce(((t,e)=>t+e),0)])).sort(((t,e)=>t[1]-e[1]))[0])?void 0:M[0];t&&(n=t);break}case"initialPlacement":n=l}if(o!==n)return{reset:{placement:n}}}return{}}}},t.hide=function(t){return void 0===t&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:i="referenceHidden",...o}=f(t,e);switch(i){case"referenceHidden":{const t=R(await A(e,{...o,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:t,referenceHidden:P(t)}}}case"escaped":{const t=R(await A(e,{...o,altBoundary:!0}),n.floating);return{data:{escapedOffsets:t,escaped:P(t)}}}default:return{}}}}},t.inline=function(t){return void 0===t&&(t={}),{name:"inline",options:t,async fn(e){const{placement:n,elements:i,rects:a,platform:l,strategy:s}=e,{padding:u=2,x:m,y:d}=f(t,e),p=Array.from(await(null==l.getClientRects?void 0:l.getClientRects(i.reference))||[]),h=function(t){const e=t.slice().sort(((t,e)=>t.y-e.y)),n=[];let i=null;for(let t=0;ti.height/2?n.push([o]):n[n.length-1].push(o),i=o}return n.map((t=>v(D(t))))}(p),y=v(D(p)),w=x(u);const b=await l.getElementRects({reference:{getBoundingClientRect:function(){if(2===h.length&&h[0].left>h[1].right&&null!=m&&null!=d)return h.find((t=>m>t.left-w.left&&mt.top-w.top&&d=2){if("y"===g(n)){const t=h[0],e=h[h.length-1],i="top"===c(n),o=t.top,r=e.bottom,a=i?t.left:e.left,l=i?t.right:e.right;return{top:o,bottom:r,left:a,right:l,width:l-a,height:r-o,x:a,y:o}}const t="left"===c(n),e=r(...h.map((t=>t.right))),i=o(...h.map((t=>t.left))),a=h.filter((n=>t?n.left===i:n.right===e)),l=a[0].top,s=a[a.length-1].bottom;return{top:l,bottom:s,left:i,right:e,width:e-i,height:s-l,x:i,y:l}}return y}},floating:i.floating,strategy:s});return a.reference.x!==b.reference.x||a.reference.y!==b.reference.y||a.reference.width!==b.reference.width||a.reference.height!==b.reference.height?{reset:{rects:b}}:{}}}},t.limitShift=function(t){return void 0===t&&(t={}),{options:t,fn(e){const{x:n,y:i,placement:o,rects:r,middlewareData:a}=e,{offset:l=0,mainAxis:s=!0,crossAxis:u=!0}=f(t,e),d={x:n,y:i},p=g(o),h=m(p);let y=d[h],w=d[p];const x=f(l,e),v="number"==typeof x?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(s){const t="y"===h?"height":"width",e=r.reference[h]-r.floating[t]+v.mainAxis,n=r.reference[h]+r.reference[t]-v.mainAxis;yn&&(y=n)}if(u){var b,A;const t="y"===h?"width":"height",e=["top","left"].includes(c(o)),n=r.reference[p]-r.floating[t]+(e&&(null==(b=a.offset)?void 0:b[p])||0)+(e?0:v.crossAxis),i=r.reference[p]+r.reference[t]+(e?0:(null==(A=a.offset)?void 0:A[p])||0)-(e?v.crossAxis:0);wi&&(w=i)}return{[h]:y,[p]:w}}}},t.offset=function(t){return void 0===t&&(t=0),{name:"offset",options:t,async fn(e){var n,i;const{x:o,y:r,placement:a,middlewareData:l}=e,s=await async function(t,e){const{placement:n,platform:i,elements:o}=t,r=await(null==i.isRTL?void 0:i.isRTL(o.floating)),a=c(n),l=u(n),s="y"===g(n),m=["left","top"].includes(a)?-1:1,d=r&&s?-1:1,p=f(e,t);let{mainAxis:h,crossAxis:y,alignmentAxis:w}="number"==typeof p?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return l&&"number"==typeof w&&(y="end"===l?-1*w:w),s?{x:y*d,y:h*m}:{x:h*m,y:y*d}}(e,t);return a===(null==(n=l.offset)?void 0:n.placement)&&null!=(i=l.arrow)&&i.alignmentOffset?{}:{x:o+s.x,y:r+s.y,data:{...s,placement:a}}}}},t.rectToClientRect=v,t.shift=function(t){return void 0===t&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:i,placement:o}=e,{mainAxis:r=!0,crossAxis:a=!1,limiter:l={fn:t=>{let{x:e,y:n}=t;return{x:e,y:n}}},...u}=f(t,e),d={x:n,y:i},p=await A(e,u),h=g(c(o)),y=m(h);let w=d[y],x=d[h];if(r){const t="y"===y?"bottom":"right";w=s(w+p["y"===y?"top":"left"],w,w-p[t])}if(a){const t="y"===h?"bottom":"right";x=s(x+p["y"===h?"top":"left"],x,x-p[t])}const v=l.fn({...e,[y]:w,[h]:x});return{...v,data:{x:v.x-n,y:v.y-i,enabled:{[y]:r,[h]:a}}}}}},t.size=function(t){return void 0===t&&(t={}),{name:"size",options:t,async fn(e){var n,i;const{placement:a,rects:l,platform:s,elements:m}=e,{apply:d=()=>{},...p}=f(t,e),h=await A(e,p),y=c(a),w=u(a),x="y"===g(a),{width:v,height:b}=l.floating;let R,P;"top"===y||"bottom"===y?(R=y,P=w===(await(null==s.isRTL?void 0:s.isRTL(m.floating))?"start":"end")?"left":"right"):(P=y,R="end"===w?"top":"bottom");const D=b-h.top-h.bottom,T=v-h.left-h.right,O=o(b-h[R],D),E=o(v-h[P],T),L=!e.middlewareData.shift;let k=O,C=E;if(null!=(n=e.middlewareData.shift)&&n.enabled.x&&(C=T),null!=(i=e.middlewareData.shift)&&i.enabled.y&&(k=D),L&&!w){const t=r(h.left,0),e=r(h.right,0),n=r(h.top,0),i=r(h.bottom,0);x?C=v-2*(0!==t||0!==e?t+e:r(h.left,h.right)):k=b-2*(0!==n||0!==i?n+i:r(h.top,h.bottom))}await d({...e,availableWidth:C,availableHeight:k});const B=await s.getDimensions(m.floating);return v!==B.width||b!==B.height?{reset:{rects:!0}}:{}}}}})); { "name": "@floating-ui/core", "version": "1.7.0", "description": "Positioning library for floating elements: tooltips, popovers, dropdowns, and more", "publishConfig": { "access": "public" }, "main": "./dist/floating-ui.core.umd.js", "module": "./dist/floating-ui.core.esm.js", "unpkg": "./dist/floating-ui.core.umd.min.js", "types": "./dist/floating-ui.core.d.ts", "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/floating-ui.core.d.mts", "default": "./dist/floating-ui.core.mjs" }, "types": "./dist/floating-ui.core.d.ts", "module": "./dist/floating-ui.core.esm.js", "default": "./dist/floating-ui.core.umd.js" } }, "sideEffects": false, "files": [ "dist" ], "author": "atomiks", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/floating-ui/floating-ui.git", "directory": "packages/core" }, "homepage": "https://floating-ui.com", "dependencies": { "@floating-ui/utils": "^0.2.9" }, "devDependencies": { "config": "0.0.0" } }MIT License Copyright (c) 2021-present Floating UI contributors 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. import{rectToClientRect as t,arrow as e,autoPlacement as n,detectOverflow as o,flip as i,hide as r,inline as c,limitShift as l,offset as s,shift as u,size as f,computePosition as a}from"@floating-ui/core";const d=Math.min,h=Math.max,p=Math.round,g=Math.floor,m=t=>({x:t,y:t});function y(){return"undefined"!=typeof window}function w(t){return b(t)?(t.nodeName||"").toLowerCase():"#document"}function x(t){var e;return(null==t||null==(e=t.ownerDocument)?void 0:e.defaultView)||window}function v(t){var e;return null==(e=(b(t)?t.ownerDocument:t.document)||window.document)?void 0:e.documentElement}function b(t){return!!y()&&(t instanceof Node||t instanceof x(t).Node)}function L(t){return!!y()&&(t instanceof Element||t instanceof x(t).Element)}function T(t){return!!y()&&(t instanceof HTMLElement||t instanceof x(t).HTMLElement)}function R(t){return!(!y()||"undefined"==typeof ShadowRoot)&&(t instanceof ShadowRoot||t instanceof x(t).ShadowRoot)}function E(t){const{overflow:e,overflowX:n,overflowY:o,display:i}=H(t);return/auto|scroll|overlay|hidden|clip/.test(e+o+n)&&!["inline","contents"].includes(i)}function C(t){return["table","td","th"].includes(w(t))}function S(t){return[":popover-open",":modal"].some((e=>{try{return t.matches(e)}catch(t){return!1}}))}function F(t){const e=D(),n=L(t)?H(t):t;return["transform","translate","scale","rotate","perspective"].some((t=>!!n[t]&&"none"!==n[t]))||!!n.containerType&&"normal"!==n.containerType||!e&&!!n.backdropFilter&&"none"!==n.backdropFilter||!e&&!!n.filter&&"none"!==n.filter||["transform","translate","scale","rotate","perspective","filter"].some((t=>(n.willChange||"").includes(t)))||["paint","layout","strict","content"].some((t=>(n.contain||"").includes(t)))}function D(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}function O(t){return["html","body","#document"].includes(w(t))}function H(t){return x(t).getComputedStyle(t)}function W(t){return L(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function M(t){if("html"===w(t))return t;const e=t.assignedSlot||t.parentNode||R(t)&&t.host||v(t);return R(e)?e.host:e}function P(t){const e=M(t);return O(e)?t.ownerDocument?t.ownerDocument.body:t.body:T(e)&&E(e)?e:P(e)}function z(t,e,n){var o;void 0===e&&(e=[]),void 0===n&&(n=!0);const i=P(t),r=i===(null==(o=t.ownerDocument)?void 0:o.body),c=x(i);if(r){const t=B(c);return e.concat(c,c.visualViewport||[],E(i)?i:[],t&&n?z(t):[])}return e.concat(i,z(i,[],n))}function B(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function V(t){const e=H(t);let n=parseFloat(e.width)||0,o=parseFloat(e.height)||0;const i=T(t),r=i?t.offsetWidth:n,c=i?t.offsetHeight:o,l=p(n)!==r||p(o)!==c;return l&&(n=r,o=c),{width:n,height:o,$:l}}function A(t){return L(t)?t:t.contextElement}function N(t){const e=A(t);if(!T(e))return m(1);const n=e.getBoundingClientRect(),{width:o,height:i,$:r}=V(e);let c=(r?p(n.width):n.width)/o,l=(r?p(n.height):n.height)/i;return c&&Number.isFinite(c)||(c=1),l&&Number.isFinite(l)||(l=1),{x:c,y:l}}const k=m(0);function I(t){const e=x(t);return D()&&e.visualViewport?{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}:k}function q(e,n,o,i){void 0===n&&(n=!1),void 0===o&&(o=!1);const r=e.getBoundingClientRect(),c=A(e);let l=m(1);n&&(i?L(i)&&(l=N(i)):l=N(e));const s=function(t,e,n){return void 0===e&&(e=!1),!(!n||e&&n!==x(t))&&e}(c,o,i)?I(c):m(0);let u=(r.left+s.x)/l.x,f=(r.top+s.y)/l.y,a=r.width/l.x,d=r.height/l.y;if(c){const t=x(c),e=i&&L(i)?x(i):i;let n=t,o=B(n);for(;o&&i&&e!==n;){const t=N(o),e=o.getBoundingClientRect(),i=H(o),r=e.left+(o.clientLeft+parseFloat(i.paddingLeft))*t.x,c=e.top+(o.clientTop+parseFloat(i.paddingTop))*t.y;u*=t.x,f*=t.y,a*=t.x,d*=t.y,u+=r,f+=c,n=x(o),o=B(n)}}return t({width:a,height:d,x:u,y:f})}function X(t,e){const n=W(t).scrollLeft;return e?e.left+n:q(v(t)).left+n}function Y(t,e,n){void 0===n&&(n=!1);const o=t.getBoundingClientRect();return{x:o.left+e.scrollLeft-(n?0:X(t,o)),y:o.top+e.scrollTop}}function $(e,n,o){let i;if("viewport"===n)i=function(t,e){const n=x(t),o=v(t),i=n.visualViewport;let r=o.clientWidth,c=o.clientHeight,l=0,s=0;if(i){r=i.width,c=i.height;const t=D();(!t||t&&"fixed"===e)&&(l=i.offsetLeft,s=i.offsetTop)}return{width:r,height:c,x:l,y:s}}(e,o);else if("document"===n)i=function(t){const e=v(t),n=W(t),o=t.ownerDocument.body,i=h(e.scrollWidth,e.clientWidth,o.scrollWidth,o.clientWidth),r=h(e.scrollHeight,e.clientHeight,o.scrollHeight,o.clientHeight);let c=-n.scrollLeft+X(t);const l=-n.scrollTop;return"rtl"===H(o).direction&&(c+=h(e.clientWidth,o.clientWidth)-i),{width:i,height:r,x:c,y:l}}(v(e));else if(L(n))i=function(t,e){const n=q(t,!0,"fixed"===e),o=n.top+t.clientTop,i=n.left+t.clientLeft,r=T(t)?N(t):m(1);return{width:t.clientWidth*r.x,height:t.clientHeight*r.y,x:i*r.x,y:o*r.y}}(n,o);else{const t=I(e);i={x:n.x-t.x,y:n.y-t.y,width:n.width,height:n.height}}return t(i)}function _(t,e){const n=M(t);return!(n===e||!L(n)||O(n))&&("fixed"===H(n).position||_(n,e))}function j(t,e,n){const o=T(e),i=v(e),r="fixed"===n,c=q(t,!0,r,e);let l={scrollLeft:0,scrollTop:0};const s=m(0);function u(){s.x=X(i)}if(o||!o&&!r)if(("body"!==w(e)||E(i))&&(l=W(e)),o){const t=q(e,!0,r,e);s.x=t.x+e.clientLeft,s.y=t.y+e.clientTop}else i&&u();r&&!o&&i&&u();const f=!i||o||r?m(0):Y(i,l);return{x:c.left+l.scrollLeft-s.x-f.x,y:c.top+l.scrollTop-s.y-f.y,width:c.width,height:c.height}}function G(t){return"static"===H(t).position}function J(t,e){if(!T(t)||"fixed"===H(t).position)return null;if(e)return e(t);let n=t.offsetParent;return v(t)===n&&(n=n.ownerDocument.body),n}function K(t,e){const n=x(t);if(S(t))return n;if(!T(t)){let e=M(t);for(;e&&!O(e);){if(L(e)&&!G(e))return e;e=M(e)}return n}let o=J(t,e);for(;o&&C(o)&&G(o);)o=J(o,e);return o&&O(o)&&G(o)&&!F(o)?n:o||function(t){let e=M(t);for(;T(e)&&!O(e);){if(F(e))return e;if(S(e))return null;e=M(e)}return null}(t)||n}const Q={convertOffsetParentRelativeRectToViewportRelativeRect:function(t){let{elements:e,rect:n,offsetParent:o,strategy:i}=t;const r="fixed"===i,c=v(o),l=!!e&&S(e.floating);if(o===c||l&&r)return n;let s={scrollLeft:0,scrollTop:0},u=m(1);const f=m(0),a=T(o);if((a||!a&&!r)&&(("body"!==w(o)||E(c))&&(s=W(o)),T(o))){const t=q(o);u=N(o),f.x=t.x+o.clientLeft,f.y=t.y+o.clientTop}const d=!c||a||r?m(0):Y(c,s,!0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-s.scrollLeft*u.x+f.x+d.x,y:n.y*u.y-s.scrollTop*u.y+f.y+d.y}},getDocumentElement:v,getClippingRect:function(t){let{element:e,boundary:n,rootBoundary:o,strategy:i}=t;const r=[..."clippingAncestors"===n?S(e)?[]:function(t,e){const n=e.get(t);if(n)return n;let o=z(t,[],!1).filter((t=>L(t)&&"body"!==w(t))),i=null;const r="fixed"===H(t).position;let c=r?M(t):t;for(;L(c)&&!O(c);){const e=H(c),n=F(c);n||"fixed"!==e.position||(i=null),(r?!n&&!i:!n&&"static"===e.position&&i&&["absolute","fixed"].includes(i.position)||E(c)&&!n&&_(t,c))?o=o.filter((t=>t!==c)):i=e,c=M(c)}return e.set(t,o),o}(e,this._c):[].concat(n),o],c=r[0],l=r.reduce(((t,n)=>{const o=$(e,n,i);return t.top=h(o.top,t.top),t.right=d(o.right,t.right),t.bottom=d(o.bottom,t.bottom),t.left=h(o.left,t.left),t}),$(e,c,i));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}},getOffsetParent:K,getElementRects:async function(t){const e=this.getOffsetParent||K,n=this.getDimensions,o=await n(t.floating);return{reference:j(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}},getClientRects:function(t){return Array.from(t.getClientRects())},getDimensions:function(t){const{width:e,height:n}=V(t);return{width:e,height:n}},getScale:N,isElement:L,isRTL:function(t){return"rtl"===H(t).direction}};function U(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function Z(t,e,n,o){void 0===o&&(o={});const{ancestorScroll:i=!0,ancestorResize:r=!0,elementResize:c="function"==typeof ResizeObserver,layoutShift:l="function"==typeof IntersectionObserver,animationFrame:s=!1}=o,u=A(t),f=i||r?[...u?z(u):[],...z(e)]:[];f.forEach((t=>{i&&t.addEventListener("scroll",n,{passive:!0}),r&&t.addEventListener("resize",n)}));const a=u&&l?function(t,e){let n,o=null;const i=v(t);function r(){var t;clearTimeout(n),null==(t=o)||t.disconnect(),o=null}return function c(l,s){void 0===l&&(l=!1),void 0===s&&(s=1),r();const u=t.getBoundingClientRect(),{left:f,top:a,width:p,height:m}=u;if(l||e(),!p||!m)return;const y={rootMargin:-g(a)+"px "+-g(i.clientWidth-(f+p))+"px "+-g(i.clientHeight-(a+m))+"px "+-g(f)+"px",threshold:h(0,d(1,s))||1};let w=!0;function x(e){const o=e[0].intersectionRatio;if(o!==s){if(!w)return c();o?c(!1,o):n=setTimeout((()=>{c(!1,1e-7)}),1e3)}1!==o||U(u,t.getBoundingClientRect())||c(),w=!1}try{o=new IntersectionObserver(x,{...y,root:i.ownerDocument})}catch(t){o=new IntersectionObserver(x,y)}o.observe(t)}(!0),r}(u,n):null;let p,m=-1,y=null;c&&(y=new ResizeObserver((t=>{let[o]=t;o&&o.target===u&&y&&(y.unobserve(e),cancelAnimationFrame(m),m=requestAnimationFrame((()=>{var t;null==(t=y)||t.observe(e)}))),n()})),u&&!s&&y.observe(u),y.observe(e));let w=s?q(t):null;return s&&function e(){const o=q(t);w&&!U(w,o)&&n();w=o,p=requestAnimationFrame(e)}(),n(),()=>{var t;f.forEach((t=>{i&&t.removeEventListener("scroll",n),r&&t.removeEventListener("resize",n)})),null==a||a(),null==(t=y)||t.disconnect(),y=null,s&&cancelAnimationFrame(p)}}const tt=o,et=s,nt=n,ot=u,it=i,rt=f,ct=r,lt=e,st=c,ut=l,ft=(t,e,n)=>{const o=new Map,i={platform:Q,...n},r={...i.platform,_c:o};return a(t,e,{...i,platform:r})};export{lt as arrow,nt as autoPlacement,Z as autoUpdate,ft as computePosition,tt as detectOverflow,it as flip,z as getOverflowAncestors,ct as hide,st as inline,ut as limitShift,et as offset,Q as platform,ot as shift,rt as size}; import { rectToClientRect, arrow as arrow$1, autoPlacement as autoPlacement$1, detectOverflow as detectOverflow$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1, computePosition as computePosition$1 } from '@floating-ui/core'; /** * Custom positioning reference element. * @see https://floating-ui.com/docs/virtual-elements */ const min = Math.min; const max = Math.max; const round = Math.round; const floor = Math.floor; const createCoords = v => ({ x: v, y: v }); function hasWindow() { return typeof window !== 'undefined'; } function getNodeName(node) { if (isNode(node)) { return (node.nodeName || '').toLowerCase(); } // Mocked nodes in testing environments may not be instances of Node. By // returning `#document` an infinite loop won't occur. // https://github.com/floating-ui/floating-ui/issues/2317 return '#document'; } function getWindow(node) { var _node$ownerDocument; return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window; } function getDocumentElement(node) { var _ref; return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement; } function isNode(value) { if (!hasWindow()) { return false; } return value instanceof Node || value instanceof getWindow(value).Node; } function isElement(value) { if (!hasWindow()) { return false; } return value instanceof Element || value instanceof getWindow(value).Element; } function isHTMLElement(value) { if (!hasWindow()) { return false; } return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement; } function isShadowRoot(value) { if (!hasWindow() || typeof ShadowRoot === 'undefined') { return false; } return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot; } function isOverflowElement(element) { const { overflow, overflowX, overflowY, display } = getComputedStyle(element); return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display); } function isTableElement(element) { return ['table', 'td', 'th'].includes(getNodeName(element)); } function isTopLayer(element) { return [':popover-open', ':modal'].some(selector => { try { return element.matches(selector); } catch (_e) { return false; } }); } function isContainingBlock(elementOrCss) { const webkit = isWebKit(); const css = isElement(elementOrCss) ? getComputedStyle(elementOrCss) : elementOrCss; // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block // https://drafts.csswg.org/css-transforms-2/#individual-transforms return ['transform', 'translate', 'scale', 'rotate', 'perspective'].some(value => css[value] ? css[value] !== 'none' : false) || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || ['transform', 'translate', 'scale', 'rotate', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value)); } function getContainingBlock(element) { let currentNode = getParentNode(element); while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) { if (isContainingBlock(currentNode)) { return currentNode; } else if (isTopLayer(currentNode)) { return null; } currentNode = getParentNode(currentNode); } return null; } function isWebKit() { if (typeof CSS === 'undefined' || !CSS.supports) return false; return CSS.supports('-webkit-backdrop-filter', 'none'); } function isLastTraversableNode(node) { return ['html', 'body', '#document'].includes(getNodeName(node)); } function getComputedStyle(element) { return getWindow(element).getComputedStyle(element); } function getNodeScroll(element) { if (isElement(element)) { return { scrollLeft: element.scrollLeft, scrollTop: element.scrollTop }; } return { scrollLeft: element.scrollX, scrollTop: element.scrollY }; } function getParentNode(node) { if (getNodeName(node) === 'html') { return node; } const result = // Step into the shadow DOM of the parent of a slotted node. node.assignedSlot || // DOM Element detected. node.parentNode || // ShadowRoot detected. isShadowRoot(node) && node.host || // Fallback. getDocumentElement(node); return isShadowRoot(result) ? result.host : result; } function getNearestOverflowAncestor(node) { const parentNode = getParentNode(node); if (isLastTraversableNode(parentNode)) { return node.ownerDocument ? node.ownerDocument.body : node.body; } if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) { return parentNode; } return getNearestOverflowAncestor(parentNode); } function getOverflowAncestors(node, list, traverseIframes) { var _node$ownerDocument2; if (list === void 0) { list = []; } if (traverseIframes === void 0) { traverseIframes = true; } const scrollableAncestor = getNearestOverflowAncestor(node); const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body); const win = getWindow(scrollableAncestor); if (isBody) { const frameElement = getFrameElement(win); return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []); } return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes)); } function getFrameElement(win) { return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null; } function getCssDimensions(element) { const css = getComputedStyle(element); // In testing environments, the `width` and `height` properties are empty // strings for SVG elements, returning NaN. Fallback to `0` in this case. let width = parseFloat(css.width) || 0; let height = parseFloat(css.height) || 0; const hasOffset = isHTMLElement(element); const offsetWidth = hasOffset ? element.offsetWidth : width; const offsetHeight = hasOffset ? element.offsetHeight : height; const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight; if (shouldFallback) { width = offsetWidth; height = offsetHeight; } return { width, height, $: shouldFallback }; } function unwrapElement(element) { return !isElement(element) ? element.contextElement : element; } function getScale(element) { const domElement = unwrapElement(element); if (!isHTMLElement(domElement)) { return createCoords(1); } const rect = domElement.getBoundingClientRect(); const { width, height, $ } = getCssDimensions(domElement); let x = ($ ? round(rect.width) : rect.width) / width; let y = ($ ? round(rect.height) : rect.height) / height; // 0, NaN, or Infinity should always fallback to 1. if (!x || !Number.isFinite(x)) { x = 1; } if (!y || !Number.isFinite(y)) { y = 1; } return { x, y }; } const noOffsets = /*#__PURE__*/createCoords(0); function getVisualOffsets(element) { const win = getWindow(element); if (!isWebKit() || !win.visualViewport) { return noOffsets; } return { x: win.visualViewport.offsetLeft, y: win.visualViewport.offsetTop }; } function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) { if (isFixed === void 0) { isFixed = false; } if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) { return false; } return isFixed; } function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) { if (includeScale === void 0) { includeScale = false; } if (isFixedStrategy === void 0) { isFixedStrategy = false; } const clientRect = element.getBoundingClientRect(); const domElement = unwrapElement(element); let scale = createCoords(1); if (includeScale) { if (offsetParent) { if (isElement(offsetParent)) { scale = getScale(offsetParent); } } else { scale = getScale(element); } } const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0); let x = (clientRect.left + visualOffsets.x) / scale.x; let y = (clientRect.top + visualOffsets.y) / scale.y; let width = clientRect.width / scale.x; let height = clientRect.height / scale.y; if (domElement) { const win = getWindow(domElement); const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent; let currentWin = win; let currentIFrame = getFrameElement(currentWin); while (currentIFrame && offsetParent && offsetWin !== currentWin) { const iframeScale = getScale(currentIFrame); const iframeRect = currentIFrame.getBoundingClientRect(); const css = getComputedStyle(currentIFrame); const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x; const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y; x *= iframeScale.x; y *= iframeScale.y; width *= iframeScale.x; height *= iframeScale.y; x += left; y += top; currentWin = getWindow(currentIFrame); currentIFrame = getFrameElement(currentWin); } } return rectToClientRect({ width, height, x, y }); } // If has a CSS width greater than the viewport, then this will be // incorrect for RTL. function getWindowScrollBarX(element, rect) { const leftScroll = getNodeScroll(element).scrollLeft; if (!rect) { return getBoundingClientRect(getDocumentElement(element)).left + leftScroll; } return rect.left + leftScroll; } function getHTMLOffset(documentElement, scroll, ignoreScrollbarX) { if (ignoreScrollbarX === void 0) { ignoreScrollbarX = false; } const htmlRect = documentElement.getBoundingClientRect(); const x = htmlRect.left + scroll.scrollLeft - (ignoreScrollbarX ? 0 : // RTL scrollbar. getWindowScrollBarX(documentElement, htmlRect)); const y = htmlRect.top + scroll.scrollTop; return { x, y }; } function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { let { elements, rect, offsetParent, strategy } = _ref; const isFixed = strategy === 'fixed'; const documentElement = getDocumentElement(offsetParent); const topLayer = elements ? isTopLayer(elements.floating) : false; if (offsetParent === documentElement || topLayer && isFixed) { return rect; } let scroll = { scrollLeft: 0, scrollTop: 0 }; let scale = createCoords(1); const offsets = createCoords(0); const isOffsetParentAnElement = isHTMLElement(offsetParent); if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { scroll = getNodeScroll(offsetParent); } if (isHTMLElement(offsetParent)) { const offsetRect = getBoundingClientRect(offsetParent); scale = getScale(offsetParent); offsets.x = offsetRect.x + offsetParent.clientLeft; offsets.y = offsetRect.y + offsetParent.clientTop; } } const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll, true) : createCoords(0); return { width: rect.width * scale.x, height: rect.height * scale.y, x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x, y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y }; } function getClientRects(element) { return Array.from(element.getClientRects()); } // Gets the entire size of the scrollable document area, even extending outside // of the `` and `` rect bounds if horizontally scrollable. function getDocumentRect(element) { const html = getDocumentElement(element); const scroll = getNodeScroll(element); const body = element.ownerDocument.body; const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth); const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight); let x = -scroll.scrollLeft + getWindowScrollBarX(element); const y = -scroll.scrollTop; if (getComputedStyle(body).direction === 'rtl') { x += max(html.clientWidth, body.clientWidth) - width; } return { width, height, x, y }; } function getViewportRect(element, strategy) { 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; if (visualViewport) { width = visualViewport.width; height = visualViewport.height; const visualViewportBased = isWebKit(); if (!visualViewportBased || visualViewportBased && strategy === 'fixed') { x = visualViewport.offsetLeft; y = visualViewport.offsetTop; } } return { width, height, x, y }; } // Returns the inner client rect, subtracting scrollbars if present. function getInnerBoundingClientRect(element, strategy) { const clientRect = getBoundingClientRect(element, true, strategy === 'fixed'); const top = clientRect.top + element.clientTop; const left = clientRect.left + element.clientLeft; const scale = isHTMLElement(element) ? getScale(element) : createCoords(1); const width = element.clientWidth * scale.x; const height = element.clientHeight * scale.y; const x = left * scale.x; const y = top * scale.y; return { width, height, x, y }; } function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) { let rect; if (clippingAncestor === 'viewport') { rect = getViewportRect(element, strategy); } else if (clippingAncestor === 'document') { rect = getDocumentRect(getDocumentElement(element)); } else if (isElement(clippingAncestor)) { rect = getInnerBoundingClientRect(clippingAncestor, strategy); } else { const visualOffsets = getVisualOffsets(element); rect = { x: clippingAncestor.x - visualOffsets.x, y: clippingAncestor.y - visualOffsets.y, width: clippingAncestor.width, height: clippingAncestor.height }; } return rectToClientRect(rect); } function hasFixedPositionAncestor(element, stopNode) { const parentNode = getParentNode(element); if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) { return false; } return getComputedStyle(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode); } // A "clipping ancestor" is an `overflow` element with the characteristic of // clipping (or hiding) child elements. This returns all clipping ancestors // of the given element up the tree. function getClippingElementAncestors(element, cache) { const cachedResult = cache.get(element); if (cachedResult) { return cachedResult; } let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body'); let currentContainingBlockComputedStyle = null; const elementIsFixed = getComputedStyle(element).position === 'fixed'; let currentNode = elementIsFixed ? getParentNode(element) : element; // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block while (isElement(currentNode) && !isLastTraversableNode(currentNode)) { const computedStyle = getComputedStyle(currentNode); const currentNodeIsContaining = isContainingBlock(currentNode); if (!currentNodeIsContaining && computedStyle.position === 'fixed') { currentContainingBlockComputedStyle = null; } const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode); if (shouldDropCurrentNode) { // Drop non-containing blocks. result = result.filter(ancestor => ancestor !== currentNode); } else { // Record last containing block for next iteration. currentContainingBlockComputedStyle = computedStyle; } currentNode = getParentNode(currentNode); } cache.set(element, result); return result; } // Gets the maximum area that the element is visible in due to any number of // clipping ancestors. function getClippingRect(_ref) { let { element, boundary, rootBoundary, strategy } = _ref; const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary); const clippingAncestors = [...elementClippingAncestors, rootBoundary]; const firstClippingAncestor = clippingAncestors[0]; const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => { const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy); accRect.top = max(rect.top, accRect.top); accRect.right = min(rect.right, accRect.right); accRect.bottom = min(rect.bottom, accRect.bottom); accRect.left = max(rect.left, accRect.left); return accRect; }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy)); return { width: clippingRect.right - clippingRect.left, height: clippingRect.bottom - clippingRect.top, x: clippingRect.left, y: clippingRect.top }; } function getDimensions(element) { const { width, height } = getCssDimensions(element); return { width, height }; } function getRectRelativeToOffsetParent(element, offsetParent, strategy) { const isOffsetParentAnElement = isHTMLElement(offsetParent); const documentElement = getDocumentElement(offsetParent); const isFixed = strategy === 'fixed'; const rect = getBoundingClientRect(element, true, isFixed, offsetParent); let scroll = { scrollLeft: 0, scrollTop: 0 }; const offsets = createCoords(0); // If the scrollbar appears on the left (e.g. RTL systems). Use // Firefox with layout.scrollbar.side = 3 in about:config to test this. function setLeftRTLScrollbarOffset() { offsets.x = getWindowScrollBarX(documentElement); } if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { scroll = getNodeScroll(offsetParent); } if (isOffsetParentAnElement) { const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent); offsets.x = offsetRect.x + offsetParent.clientLeft; offsets.y = offsetRect.y + offsetParent.clientTop; } else if (documentElement) { setLeftRTLScrollbarOffset(); } } if (isFixed && !isOffsetParentAnElement && documentElement) { setLeftRTLScrollbarOffset(); } const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0); const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x; const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y; return { x, y, width: rect.width, height: rect.height }; } function isStaticPositioned(element) { return getComputedStyle(element).position === 'static'; } function getTrueOffsetParent(element, polyfill) { if (!isHTMLElement(element) || getComputedStyle(element).position === 'fixed') { return null; } if (polyfill) { return polyfill(element); } let rawOffsetParent = element.offsetParent; // Firefox returns the element as the offsetParent if it's non-static, // while Chrome and Safari return the element. The element must // be used to perform the correct calculations even if the element is // non-static. if (getDocumentElement(element) === rawOffsetParent) { rawOffsetParent = rawOffsetParent.ownerDocument.body; } return rawOffsetParent; } // Gets the closest ancestor positioned element. Handles some edge cases, // such as table ancestors and cross browser bugs. function getOffsetParent(element, polyfill) { const win = getWindow(element); if (isTopLayer(element)) { return win; } if (!isHTMLElement(element)) { let svgOffsetParent = getParentNode(element); while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) { if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) { return svgOffsetParent; } svgOffsetParent = getParentNode(svgOffsetParent); } return win; } let offsetParent = getTrueOffsetParent(element, polyfill); while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) { offsetParent = getTrueOffsetParent(offsetParent, polyfill); } if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) { return win; } return offsetParent || getContainingBlock(element) || win; } const getElementRects = async function (data) { const getOffsetParentFn = this.getOffsetParent || getOffsetParent; const getDimensionsFn = this.getDimensions; const floatingDimensions = await getDimensionsFn(data.floating); return { reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy), floating: { x: 0, y: 0, width: floatingDimensions.width, height: floatingDimensions.height } }; }; function isRTL(element) { return getComputedStyle(element).direction === 'rtl'; } const platform = { convertOffsetParentRelativeRectToViewportRelativeRect, getDocumentElement, getClippingRect, getOffsetParent, getElementRects, getClientRects, getDimensions, getScale, isElement, isRTL }; function rectsAreEqual(a, b) { return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height; } // https://samthor.au/2021/observing-dom/ function observeMove(element, onMove) { let io = null; let timeoutId; const root = getDocumentElement(element); function cleanup() { var _io; clearTimeout(timeoutId); (_io = io) == null || _io.disconnect(); io = null; } function refresh(skip, threshold) { if (skip === void 0) { skip = false; } if (threshold === void 0) { threshold = 1; } cleanup(); const elementRectForRootMargin = element.getBoundingClientRect(); const { left, top, width, height } = elementRectForRootMargin; if (!skip) { onMove(); } if (!width || !height) { return; } const insetTop = floor(top); const insetRight = floor(root.clientWidth - (left + width)); const insetBottom = floor(root.clientHeight - (top + height)); const insetLeft = floor(left); const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px"; const options = { rootMargin, threshold: max(0, min(1, threshold)) || 1 }; let isFirstUpdate = true; function handleObserve(entries) { const ratio = entries[0].intersectionRatio; if (ratio !== threshold) { if (!isFirstUpdate) { return refresh(); } if (!ratio) { // If the reference is clipped, the ratio is 0. Throttle the refresh // to prevent an infinite loop of updates. timeoutId = setTimeout(() => { refresh(false, 1e-7); }, 1000); } else { refresh(false, ratio); } } if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) { // It's possible that even though the ratio is reported as 1, the // element is not actually fully within the IntersectionObserver's root // area anymore. This can happen under performance constraints. This may // be a bug in the browser's IntersectionObserver implementation. To // work around this, we compare the element's bounding rect now with // what it was at the time we created the IntersectionObserver. If they // are not equal then the element moved, so we refresh. refresh(); } isFirstUpdate = false; } // Older browsers don't support a `document` as the root and will throw an // error. try { io = new IntersectionObserver(handleObserve, { ...options, // Handle