_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q58300
|
formatPrice
|
validation
|
function formatPrice( cost, currencyCode, options = {} ) {
if ( undefined !== options.precision ) {
cost = applyPrecision( cost, options.precision );
}
return formatCurrency( cost, currencyCode, cost % 1 > 0 ? {} : { precision: 0 } );
}
|
javascript
|
{
"resource": ""
}
|
q58301
|
getEligibleGSuiteDomain
|
validation
|
function getEligibleGSuiteDomain( selectedDomainName, domains ) {
if ( selectedDomainName && canDomainAddGSuite( selectedDomainName ) ) {
return selectedDomainName;
}
const [ eligibleDomain ] = getGSuiteSupportedDomains( domains );
return ( eligibleDomain && eligibleDomain.name ) || '';
}
|
javascript
|
{
"resource": ""
}
|
q58302
|
getGSuiteSupportedDomains
|
validation
|
function getGSuiteSupportedDomains( domains ) {
return domains.filter( function( domain ) {
const wpcomHosted =
includes( [ domainTypes.REGISTERED ], domain.type ) &&
( domain.hasWpcomNameservers || hasGSuite( domain ) );
const mapped = includes( [ domainTypes.MAPPED ], domain.type );
const notOtherProvidor =
domain.googleAppsSubscription && domain.googleAppsSubscription.status !== 'other_provider';
return ( wpcomHosted || mapped ) && canDomainAddGSuite( domain.name ) && notOtherProvidor;
} );
}
|
javascript
|
{
"resource": ""
}
|
q58303
|
stopMutationObserver
|
validation
|
function stopMutationObserver() {
if ( mutationObserver && mutationObserverActive ) {
activePlaceholders = [];
activePlaceholderEverDetected = false;
mutationObserver.disconnect();
mutationObserverActive = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q58304
|
checkActivePlaceholders
|
validation
|
function checkActivePlaceholders() {
const placeholdersCount = activePlaceholders.length;
debug( `Checking active placeholders. Count: ${ placeholdersCount }` );
if ( placeholdersCount > 0 ) {
activePlaceholderEverDetected = true;
}
// record event if there ever were any placeholders and if they all just disappeared
if ( activePlaceholderEverDetected && placeholdersCount === 0 ) {
// tell tracks to record duration
const { startTime, trigger } = determineTimingType();
const duration = Math.round( performance.now() - startTime );
debug( `Recording placeholder wait. Duration: ${ duration }, Trigger: ${ trigger }` );
analytics.timing.record( `placeholder-wait.${ trigger }`, duration );
stopMutationObserver();
}
}
|
javascript
|
{
"resource": ""
}
|
q58305
|
getDefaultOptions
|
validation
|
function getDefaultOptions() {
const ids = config( 'directly_rtm_widget_ids' );
const env = config( 'directly_rtm_widget_environment' );
return {
id: ids[ env ],
displayAskQuestion: false,
};
}
|
javascript
|
{
"resource": ""
}
|
q58306
|
configureGlobals
|
validation
|
function configureGlobals() {
// Set up the global DirectlyRTM function, required for the RTM widget.
// This snippet is pasted from Directly's setup code.
window.DirectlyRTM =
window.DirectlyRTM ||
function() {
( window.DirectlyRTM.cq = window.DirectlyRTM.cq || [] ).push( arguments );
};
// Since we can only configure once per pageload, this library only provides a
// single global configuration.
window.DirectlyRTM( 'config', getDefaultOptions() );
}
|
javascript
|
{
"resource": ""
}
|
q58307
|
insertDOM
|
validation
|
function insertDOM() {
if ( null !== document.getElementById( 'directlyRTMScript' ) ) {
return;
}
const d = document.createElement( 'div' );
d.id = 'directlyRTMScript';
d.src = DIRECTLY_ASSETS_BASE_URL;
document.body.appendChild( d );
}
|
javascript
|
{
"resource": ""
}
|
q58308
|
loadDirectlyScript
|
validation
|
function loadDirectlyScript() {
return new Promise( ( resolve, reject ) => {
loadScript( DIRECTLY_RTM_SCRIPT_URL, function( error ) {
if ( error ) {
return reject( new Error( `Failed to load script "${ error.src }".` ) );
}
resolve();
} );
} );
}
|
javascript
|
{
"resource": ""
}
|
q58309
|
getInitialServerState
|
validation
|
function getInitialServerState( initialReducer ) {
if ( typeof window !== 'object' || ! window.initialReduxState || isSupportSession() ) {
return null;
}
const serverState = deserialize( window.initialReduxState, initialReducer );
return pick( serverState, Object.keys( window.initialReduxState ) );
}
|
javascript
|
{
"resource": ""
}
|
q58310
|
shouldAddSympathy
|
validation
|
function shouldAddSympathy() {
// If `force-sympathy` flag is enabled, always clear persistent state.
if ( config.isEnabled( 'force-sympathy' ) ) {
return true;
}
// If `no-force-sympathy` flag is enabled, never clear persistent state.
if ( config.isEnabled( 'no-force-sympathy' ) ) {
return false;
}
// Otherwise, in development mode, clear persistent state 25% of the time.
if ( 'development' === process.env.NODE_ENV && Math.random() < 0.25 ) {
return true;
}
// Otherwise, do not clear persistent state.
return false;
}
|
javascript
|
{
"resource": ""
}
|
q58311
|
updateProductEdits
|
validation
|
function updateProductEdits( edits, productId, doUpdate ) {
const prevEdits = edits || [];
let found = false;
const newEdits = prevEdits.map( productEdits => {
if ( isEqual( productId, productEdits.productId ) ) {
found = true;
return doUpdate( productEdits );
}
return productEdits;
} );
if ( ! found ) {
newEdits.push( doUpdate( undefined ) );
}
return newEdits;
}
|
javascript
|
{
"resource": ""
}
|
q58312
|
doesNotNeedSandbox
|
validation
|
function doesNotNeedSandbox( iframe ) {
const trustedHosts = [
'spotify.com',
'kickstarter.com',
'soundcloud.com',
'embed.ted.com',
'player.twitch.tv',
];
const hostName = iframe.src && url.parse( iframe.src ).hostname;
const iframeHost = hostName && hostName.toLowerCase();
return some( trustedHosts, trustedHost => endsWith( '.' + iframeHost, '.' + trustedHost ) );
}
|
javascript
|
{
"resource": ""
}
|
q58313
|
getEligibleEmailForwardingDomain
|
validation
|
function getEligibleEmailForwardingDomain( selectedDomainName, domains = [] ) {
const eligibleDomains = getEmailForwardingSupportedDomains( domains );
let selectedDomain;
if ( selectedDomainName ) {
selectedDomain = eligibleDomains.reduce( function( selected, domain ) {
return domain.name === selectedDomainName ? domain.name : selected;
}, '' );
}
return selectedDomain || ( eligibleDomains.length && eligibleDomains[ 0 ].name ) || '';
}
|
javascript
|
{
"resource": ""
}
|
q58314
|
getEmailForwardingSupportedDomains
|
validation
|
function getEmailForwardingSupportedDomains( domains ) {
return domains.filter( function( domain ) {
const domainHasGSuite = hasGSuite( domain );
const wpcomHosted =
includes( [ domainTypes.REGISTERED ], domain.type ) && domain.hasWpcomNameservers;
const mapped = includes( [ domainTypes.MAPPED ], domain.type );
return ( wpcomHosted || mapped ) && ! domainHasGSuite;
} );
}
|
javascript
|
{
"resource": ""
}
|
q58315
|
setup
|
validation
|
function setup() {
const app = express();
// for nginx
app.enable( 'trust proxy' );
app.use( cookieParser() );
app.use( userAgent.express() );
if ( 'development' === process.env.NODE_ENV ) {
// use legacy CSS rebuild system if css-hot-reload is disabled
if ( ! config.isEnabled( 'css-hot-reload' ) ) {
// only do `build` upon every request in "development"
app.use( build() );
}
require( 'bundler' )( app );
// setup logger
app.use( morgan( 'dev' ) );
if ( config.isEnabled( 'wpcom-user-bootstrap' ) ) {
if ( config( 'wordpress_logged_in_cookie' ) ) {
const username = config( 'wordpress_logged_in_cookie' ).split( '%7C' )[ 0 ];
console.info( chalk.cyan( '\nYour logged in cookie set to user: ' + username ) );
app.use( function( req, res, next ) {
if ( ! req.cookies.wordpress_logged_in ) {
req.cookies.wordpress_logged_in = config( 'wordpress_logged_in_cookie' );
}
next();
} );
} else {
console.info(
chalk.red(
'\nYou need to set `wordpress_logged_in_cookie` in secrets.json' +
' for wpcom-user-bootstrap to work in development.'
)
);
}
}
} else {
// setup logger
app.use( morgan( 'combined' ) );
}
app.use( pwa() );
// attach the static file server to serve the `public` dir
app.use( '/calypso', express.static( path.resolve( __dirname, '..', '..', 'public' ) ) );
// loaded when we detect stats blockers - see lib/analytics/index.js
app.get( '/nostats.js', function( request, response ) {
analytics.tracks.recordEvent(
'calypso_stats_blocked',
{
do_not_track: request.headers.dnt,
},
request
);
response.setHeader( 'content-type', 'application/javascript' );
response.end( "console.log('Stats are disabled');" );
} );
// serve files when not in production so that the source maps work correctly
if ( 'development' === process.env.NODE_ENV ) {
app.use( '/assets', express.static( path.resolve( __dirname, '..', '..', 'assets' ) ) );
app.use( '/client', express.static( path.resolve( __dirname, '..', '..', 'client' ) ) );
}
if ( config.isEnabled( 'devdocs' ) ) {
app.use( require( 'devdocs' )() );
}
if ( config.isEnabled( 'desktop' ) ) {
app.use(
'/desktop',
express.static( path.resolve( __dirname, '..', '..', '..', 'public_desktop' ) )
);
}
app.use( require( 'api' )() );
// attach the pages module
app.use( pages() );
return app;
}
|
javascript
|
{
"resource": ""
}
|
q58316
|
validation
|
function( pluginSlug ) {
const query = {
fields: 'icons,banners,compatibility,ratings,-contributors',
locale: getWporgLocaleCode(),
};
pluginSlug = pluginSlug.replace( new RegExp( '.php$' ), '' );
const baseUrl = 'https://api.wordpress.org/plugins/info/1.0/' + pluginSlug + '.jsonp';
return new Promise( ( resolve, reject ) => {
jsonp( baseUrl, query, function( error, data ) {
if ( error ) {
debug( 'error downloading plugin details from .org: %s', error );
reject( error );
return;
}
if ( ! data || ! data.slug ) {
debug( 'unrecognized format fetching plugin details from .org: %s', data );
reject( new Error( 'Unrecognized response format' ) );
return;
}
resolve( data );
} );
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q58317
|
validation
|
function( themeId ) {
const query = {
action: 'theme_information',
// Return an `author` object containing `user_nicename` and `display_name` attrs.
// This is for consistency with WP.com, which always returns the display name as `author`.
'request[fields][extended_author]': true,
'request[slug]': themeId,
};
return superagent
.get( WPORG_THEMES_ENDPOINT )
.set( 'Accept', 'application/json' )
.query( query )
.then( ( { body } ) => body );
}
|
javascript
|
{
"resource": ""
}
|
|
q58318
|
validation
|
function( options = {} ) {
const { search, page, number } = options;
const query = {
action: 'query_themes',
// Return an `author` object containing `user_nicename` and `display_name` attrs.
// This is for consistency with WP.com, which always returns the display name as `author`.
'request[fields][extended_author]': true,
'request[search]': search,
'request[page]': page,
'request[per_page]:': number,
};
return superagent
.get( WPORG_THEMES_ENDPOINT )
.set( 'Accept', 'application/json' )
.query( query )
.then( ( { body } ) => body );
}
|
javascript
|
{
"resource": ""
}
|
|
q58319
|
isPlainObject
|
validation
|
function isPlainObject(value) {
if (!isObject(value)) {
return false;
}
try {
var _constructor = value.constructor;
var prototype = _constructor.prototype;
return _constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf');
} catch (error) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q58320
|
toArray
|
validation
|
function toArray(value) {
return Array.from ? Array.from(value) : slice.call(value);
}
|
javascript
|
{
"resource": ""
}
|
q58321
|
forEach
|
validation
|
function forEach(data, callback) {
if (data && isFunction(callback)) {
if (Array.isArray(data) || isNumber(data.length)
/* array-like */
) {
toArray(data).forEach(function (value, key) {
callback.call(data, value, key, data);
});
} else if (isObject(data)) {
Object.keys(data).forEach(function (key) {
callback.call(data, data[key], key, data);
});
}
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q58322
|
hasClass
|
validation
|
function hasClass(element, value) {
return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1;
}
|
javascript
|
{
"resource": ""
}
|
q58323
|
addClass
|
validation
|
function addClass(element, value) {
if (!value) {
return;
}
if (isNumber(element.length)) {
forEach(element, function (elem) {
addClass(elem, value);
});
return;
}
if (element.classList) {
element.classList.add(value);
return;
}
var className = element.className.trim();
if (!className) {
element.className = value;
} else if (className.indexOf(value) < 0) {
element.className = "".concat(className, " ").concat(value);
}
}
|
javascript
|
{
"resource": ""
}
|
q58324
|
removeClass
|
validation
|
function removeClass(element, value) {
if (!value) {
return;
}
if (isNumber(element.length)) {
forEach(element, function (elem) {
removeClass(elem, value);
});
return;
}
if (element.classList) {
element.classList.remove(value);
return;
}
if (element.className.indexOf(value) >= 0) {
element.className = element.className.replace(value, '');
}
}
|
javascript
|
{
"resource": ""
}
|
q58325
|
toggleClass
|
validation
|
function toggleClass(element, value, added) {
if (!value) {
return;
}
if (isNumber(element.length)) {
forEach(element, function (elem) {
toggleClass(elem, value, added);
});
return;
} // IE10-11 doesn't support the second parameter of `classList.toggle`
if (added) {
addClass(element, value);
} else {
removeClass(element, value);
}
}
|
javascript
|
{
"resource": ""
}
|
q58326
|
getData
|
validation
|
function getData(element, name) {
if (isObject(element[name])) {
return element[name];
}
if (element.dataset) {
return element.dataset[name];
}
return element.getAttribute("data-".concat(toParamCase(name)));
}
|
javascript
|
{
"resource": ""
}
|
q58327
|
setData
|
validation
|
function setData(element, name, data) {
if (isObject(data)) {
element[name] = data;
} else if (element.dataset) {
element.dataset[name] = data;
} else {
element.setAttribute("data-".concat(toParamCase(name)), data);
}
}
|
javascript
|
{
"resource": ""
}
|
q58328
|
removeData
|
validation
|
function removeData(element, name) {
if (isObject(element[name])) {
try {
delete element[name];
} catch (error) {
element[name] = undefined;
}
} else if (element.dataset) {
// #128 Safari not allows to delete dataset property
try {
delete element.dataset[name];
} catch (error) {
element.dataset[name] = undefined;
}
} else {
element.removeAttribute("data-".concat(toParamCase(name)));
}
}
|
javascript
|
{
"resource": ""
}
|
q58329
|
removeListener
|
validation
|
function removeListener(element, type, listener) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var handler = listener;
type.trim().split(REGEXP_SPACES).forEach(function (event) {
if (!onceSupported) {
var listeners = element.listeners;
if (listeners && listeners[event] && listeners[event][listener]) {
handler = listeners[event][listener];
delete listeners[event][listener];
if (Object.keys(listeners[event]).length === 0) {
delete listeners[event];
}
if (Object.keys(listeners).length === 0) {
delete element.listeners;
}
}
}
element.removeEventListener(event, handler, options);
});
}
|
javascript
|
{
"resource": ""
}
|
q58330
|
addListener
|
validation
|
function addListener(element, type, listener) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var _handler = listener;
type.trim().split(REGEXP_SPACES).forEach(function (event) {
if (options.once && !onceSupported) {
var _element$listeners = element.listeners,
listeners = _element$listeners === void 0 ? {} : _element$listeners;
_handler = function handler() {
delete listeners[event][listener];
element.removeEventListener(event, _handler, options);
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
listener.apply(element, args);
};
if (!listeners[event]) {
listeners[event] = {};
}
if (listeners[event][listener]) {
element.removeEventListener(event, listeners[event][listener], options);
}
listeners[event][listener] = _handler;
element.listeners = listeners;
}
element.addEventListener(event, _handler, options);
});
}
|
javascript
|
{
"resource": ""
}
|
q58331
|
dispatchEvent
|
validation
|
function dispatchEvent(element, type, data) {
var event; // Event and CustomEvent on IE9-11 are global objects, not constructors
if (isFunction(Event) && isFunction(CustomEvent)) {
event = new CustomEvent(type, {
detail: data,
bubbles: true,
cancelable: true
});
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent(type, true, true, data);
}
return element.dispatchEvent(event);
}
|
javascript
|
{
"resource": ""
}
|
q58332
|
getOffset
|
validation
|
function getOffset(element) {
var box = element.getBoundingClientRect();
return {
left: box.left + (window.pageXOffset - document.documentElement.clientLeft),
top: box.top + (window.pageYOffset - document.documentElement.clientTop)
};
}
|
javascript
|
{
"resource": ""
}
|
q58333
|
addTimestamp
|
validation
|
function addTimestamp(url) {
var timestamp = "timestamp=".concat(new Date().getTime());
return url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp;
}
|
javascript
|
{
"resource": ""
}
|
q58334
|
getTransforms
|
validation
|
function getTransforms(_ref) {
var rotate = _ref.rotate,
scaleX = _ref.scaleX,
scaleY = _ref.scaleY,
translateX = _ref.translateX,
translateY = _ref.translateY;
var values = [];
if (isNumber(translateX) && translateX !== 0) {
values.push("translateX(".concat(translateX, "px)"));
}
if (isNumber(translateY) && translateY !== 0) {
values.push("translateY(".concat(translateY, "px)"));
} // Rotate should come first before scale to match orientation transform
if (isNumber(rotate) && rotate !== 0) {
values.push("rotate(".concat(rotate, "deg)"));
}
if (isNumber(scaleX) && scaleX !== 1) {
values.push("scaleX(".concat(scaleX, ")"));
}
if (isNumber(scaleY) && scaleY !== 1) {
values.push("scaleY(".concat(scaleY, ")"));
}
var transform = values.length ? values.join(' ') : 'none';
return {
WebkitTransform: transform,
msTransform: transform,
transform: transform
};
}
|
javascript
|
{
"resource": ""
}
|
q58335
|
getMaxZoomRatio
|
validation
|
function getMaxZoomRatio(pointers) {
var pointers2 = assign({}, pointers);
var ratios = [];
forEach(pointers, function (pointer, pointerId) {
delete pointers2[pointerId];
forEach(pointers2, function (pointer2) {
var x1 = Math.abs(pointer.startX - pointer2.startX);
var y1 = Math.abs(pointer.startY - pointer2.startY);
var x2 = Math.abs(pointer.endX - pointer2.endX);
var y2 = Math.abs(pointer.endY - pointer2.endY);
var z1 = Math.sqrt(x1 * x1 + y1 * y1);
var z2 = Math.sqrt(x2 * x2 + y2 * y2);
var ratio = (z2 - z1) / z1;
ratios.push(ratio);
});
});
ratios.sort(function (a, b) {
return Math.abs(a) < Math.abs(b);
});
return ratios[0];
}
|
javascript
|
{
"resource": ""
}
|
q58336
|
getPointer
|
validation
|
function getPointer(_ref2, endOnly) {
var pageX = _ref2.pageX,
pageY = _ref2.pageY;
var end = {
endX: pageX,
endY: pageY
};
return endOnly ? end : assign({
startX: pageX,
startY: pageY
}, end);
}
|
javascript
|
{
"resource": ""
}
|
q58337
|
getPointersCenter
|
validation
|
function getPointersCenter(pointers) {
var pageX = 0;
var pageY = 0;
var count = 0;
forEach(pointers, function (_ref3) {
var startX = _ref3.startX,
startY = _ref3.startY;
pageX += startX;
pageY += startY;
count += 1;
});
pageX /= count;
pageY /= count;
return {
pageX: pageX,
pageY: pageY
};
}
|
javascript
|
{
"resource": ""
}
|
q58338
|
getAdjustedSizes
|
validation
|
function getAdjustedSizes(_ref4) // or 'cover'
{
var aspectRatio = _ref4.aspectRatio,
height = _ref4.height,
width = _ref4.width;
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain';
var isValidWidth = isPositiveNumber(width);
var isValidHeight = isPositiveNumber(height);
if (isValidWidth && isValidHeight) {
var adjustedWidth = height * aspectRatio;
if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) {
height = width / aspectRatio;
} else {
width = height * aspectRatio;
}
} else if (isValidWidth) {
height = width / aspectRatio;
} else if (isValidHeight) {
width = height * aspectRatio;
}
return {
width: width,
height: height
};
}
|
javascript
|
{
"resource": ""
}
|
q58339
|
getRotatedSizes
|
validation
|
function getRotatedSizes(_ref5) {
var width = _ref5.width,
height = _ref5.height,
degree = _ref5.degree;
degree = Math.abs(degree) % 180;
if (degree === 90) {
return {
width: height,
height: width
};
}
var arc = degree % 90 * Math.PI / 180;
var sinArc = Math.sin(arc);
var cosArc = Math.cos(arc);
var newWidth = width * cosArc + height * sinArc;
var newHeight = width * sinArc + height * cosArc;
return degree > 90 ? {
width: newHeight,
height: newWidth
} : {
width: newWidth,
height: newHeight
};
}
|
javascript
|
{
"resource": ""
}
|
q58340
|
dataURLToArrayBuffer
|
validation
|
function dataURLToArrayBuffer(dataURL) {
var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, '');
var binary = atob(base64);
var arrayBuffer = new ArrayBuffer(binary.length);
var uint8 = new Uint8Array(arrayBuffer);
forEach(uint8, function (value, i) {
uint8[i] = binary.charCodeAt(i);
});
return arrayBuffer;
}
|
javascript
|
{
"resource": ""
}
|
q58341
|
arrayBufferToDataURL
|
validation
|
function arrayBufferToDataURL(arrayBuffer, mimeType) {
var chunks = []; // Chunk Typed Array for better performance (#435)
var chunkSize = 8192;
var uint8 = new Uint8Array(arrayBuffer);
while (uint8.length > 0) {
// XXX: Babel's `toConsumableArray` helper will throw error in IE or Safari 9
// eslint-disable-next-line prefer-spread
chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize))));
uint8 = uint8.subarray(chunkSize);
}
return "data:".concat(mimeType, ";base64,").concat(btoa(chunks.join('')));
}
|
javascript
|
{
"resource": ""
}
|
q58342
|
parseOrientation
|
validation
|
function parseOrientation(orientation) {
var rotate = 0;
var scaleX = 1;
var scaleY = 1;
switch (orientation) {
// Flip horizontal
case 2:
scaleX = -1;
break;
// Rotate left 180°
case 3:
rotate = -180;
break;
// Flip vertical
case 4:
scaleY = -1;
break;
// Flip vertical and rotate right 90°
case 5:
rotate = 90;
scaleY = -1;
break;
// Rotate right 90°
case 6:
rotate = 90;
break;
// Flip horizontal and rotate right 90°
case 7:
rotate = 90;
scaleX = -1;
break;
// Rotate left 90°
case 8:
rotate = -90;
break;
default:
}
return {
rotate: rotate,
scaleX: scaleX,
scaleY: scaleY
};
}
|
javascript
|
{
"resource": ""
}
|
q58343
|
crop
|
validation
|
function crop() {
if (this.ready && !this.cropped && !this.disabled) {
this.cropped = true;
this.limitCropBox(true, true);
if (this.options.modal) {
addClass(this.dragBox, CLASS_MODAL);
}
removeClass(this.cropBox, CLASS_HIDDEN);
this.setCropBoxData(this.initialCropBoxData);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58344
|
reset
|
validation
|
function reset() {
if (this.ready && !this.disabled) {
this.imageData = assign({}, this.initialImageData);
this.canvasData = assign({}, this.initialCanvasData);
this.cropBoxData = assign({}, this.initialCropBoxData);
this.renderCanvas();
if (this.cropped) {
this.renderCropBox();
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58345
|
clear
|
validation
|
function clear() {
if (this.cropped && !this.disabled) {
assign(this.cropBoxData, {
left: 0,
top: 0,
width: 0,
height: 0
});
this.cropped = false;
this.renderCropBox();
this.limitCanvas(true, true); // Render canvas after crop box rendered
this.renderCanvas();
removeClass(this.dragBox, CLASS_MODAL);
addClass(this.cropBox, CLASS_HIDDEN);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58346
|
replace
|
validation
|
function replace(url) {
var hasSameSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (!this.disabled && url) {
if (this.isImg) {
this.element.src = url;
}
if (hasSameSize) {
this.url = url;
this.image.src = url;
if (this.ready) {
this.viewBoxImage.src = url;
forEach(this.previews, function (element) {
element.getElementsByTagName('img')[0].src = url;
});
}
} else {
if (this.isImg) {
this.replaced = true;
}
this.options.data = null;
this.uncreate();
this.load(url);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58347
|
destroy
|
validation
|
function destroy() {
var element = this.element;
if (!element[NAMESPACE]) {
return this;
}
element[NAMESPACE] = undefined;
if (this.isImg && this.replaced) {
element.src = this.originalUrl;
}
this.uncreate();
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58348
|
move
|
validation
|
function move(offsetX) {
var offsetY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : offsetX;
var _this$canvasData = this.canvasData,
left = _this$canvasData.left,
top = _this$canvasData.top;
return this.moveTo(isUndefined(offsetX) ? offsetX : left + Number(offsetX), isUndefined(offsetY) ? offsetY : top + Number(offsetY));
}
|
javascript
|
{
"resource": ""
}
|
q58349
|
moveTo
|
validation
|
function moveTo(x) {
var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x;
var canvasData = this.canvasData;
var changed = false;
x = Number(x);
y = Number(y);
if (this.ready && !this.disabled && this.options.movable) {
if (isNumber(x)) {
canvasData.left = x;
changed = true;
}
if (isNumber(y)) {
canvasData.top = y;
changed = true;
}
if (changed) {
this.renderCanvas(true);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58350
|
zoom
|
validation
|
function zoom(ratio, _originalEvent) {
var canvasData = this.canvasData;
ratio = Number(ratio);
if (ratio < 0) {
ratio = 1 / (1 - ratio);
} else {
ratio = 1 + ratio;
}
return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent);
}
|
javascript
|
{
"resource": ""
}
|
q58351
|
rotateTo
|
validation
|
function rotateTo(degree) {
degree = Number(degree);
if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) {
this.imageData.rotate = degree % 360;
this.renderCanvas(true, true);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58352
|
scaleX
|
validation
|
function scaleX(_scaleX) {
var scaleY = this.imageData.scaleY;
return this.scale(_scaleX, isNumber(scaleY) ? scaleY : 1);
}
|
javascript
|
{
"resource": ""
}
|
q58353
|
scaleY
|
validation
|
function scaleY(_scaleY) {
var scaleX = this.imageData.scaleX;
return this.scale(isNumber(scaleX) ? scaleX : 1, _scaleY);
}
|
javascript
|
{
"resource": ""
}
|
q58354
|
scale
|
validation
|
function scale(scaleX) {
var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX;
var imageData = this.imageData;
var transformed = false;
scaleX = Number(scaleX);
scaleY = Number(scaleY);
if (this.ready && !this.disabled && this.options.scalable) {
if (isNumber(scaleX)) {
imageData.scaleX = scaleX;
transformed = true;
}
if (isNumber(scaleY)) {
imageData.scaleY = scaleY;
transformed = true;
}
if (transformed) {
this.renderCanvas(true, true);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58355
|
getCanvasData
|
validation
|
function getCanvasData() {
var canvasData = this.canvasData;
var data = {};
if (this.ready) {
forEach(['left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight'], function (n) {
data[n] = canvasData[n];
});
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q58356
|
setCanvasData
|
validation
|
function setCanvasData(data) {
var canvasData = this.canvasData;
var aspectRatio = canvasData.aspectRatio;
if (this.ready && !this.disabled && isPlainObject(data)) {
if (isNumber(data.left)) {
canvasData.left = data.left;
}
if (isNumber(data.top)) {
canvasData.top = data.top;
}
if (isNumber(data.width)) {
canvasData.width = data.width;
canvasData.height = data.width / aspectRatio;
} else if (isNumber(data.height)) {
canvasData.height = data.height;
canvasData.width = data.height * aspectRatio;
}
this.renderCanvas(true);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58357
|
setAspectRatio
|
validation
|
function setAspectRatio(aspectRatio) {
var options = this.options;
if (!this.disabled && !isUndefined(aspectRatio)) {
// 0 -> NaN
options.aspectRatio = Math.max(0, aspectRatio) || NaN;
if (this.ready) {
this.initCropBox();
if (this.cropped) {
this.renderCropBox();
}
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58358
|
setDragMode
|
validation
|
function setDragMode(mode) {
var options = this.options,
dragBox = this.dragBox,
face = this.face;
if (this.ready && !this.disabled) {
var croppable = mode === DRAG_MODE_CROP;
var movable = options.movable && mode === DRAG_MODE_MOVE;
mode = croppable || movable ? mode : DRAG_MODE_NONE;
options.dragMode = mode;
setData(dragBox, DATA_ACTION, mode);
toggleClass(dragBox, CLASS_CROP, croppable);
toggleClass(dragBox, CLASS_MOVE, movable);
if (!options.cropBoxMovable) {
// Sync drag mode to crop box when it is not movable
setData(face, DATA_ACTION, mode);
toggleClass(face, CLASS_CROP, croppable);
toggleClass(face, CLASS_MOVE, movable);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q58359
|
validation
|
function(event, func) {
this._events = this._events || {};
this._events[event] = this._events[event] || [];
this._events[event].push(func);
}
|
javascript
|
{
"resource": ""
}
|
|
q58360
|
validation
|
function(event, func) {
this._events = this._events || {};
if (event in this._events === false) return;
this._events[event].splice(this._events[event].indexOf(func), 1);
}
|
javascript
|
{
"resource": ""
}
|
|
q58361
|
appendItem
|
validation
|
function appendItem(item, parent, custom) {
if (item.parentNode) {
if (!item.parentNode.parentNode) {
parent.appendChild(item.parentNode);
}
} else {
parent.appendChild(item);
}
util.removeClass(item, "excluded");
if (!custom) {
item.innerHTML = item.textContent;
}
}
|
javascript
|
{
"resource": ""
}
|
q58362
|
validation
|
function() {
if (this.items.length) {
var f = document.createDocumentFragment();
if (this.config.pagination) {
var pages = this.pages.slice(0, this.pageIndex);
util.each(pages, function(i, items) {
util.each(items, function(j, item) {
appendItem(item, f, this.customOption);
}, this);
}, this);
} else {
util.each(this.items, function(i, item) {
appendItem(item, f, this.customOption);
}, this);
}
if (f.childElementCount) {
util.removeClass(this.items[this.navIndex], "active");
this.navIndex = f.querySelector(".selectr-option").idx;
util.addClass(this.items[this.navIndex], "active");
}
this.tree.appendChild(f);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q58363
|
validation
|
function(option, data) {
data = data || option;
var content = this.customOption ? this.config.renderOption(data) : option.textContent;
var opt = util.createElement("li", {
class: "selectr-option",
html: content,
role: "treeitem",
"aria-selected": false
});
opt.idx = option.idx;
this.items.push(opt);
if (option.defaultSelected) {
this.defaultSelected.push(option.idx);
}
if (option.disabled) {
opt.disabled = true;
util.addClass(opt, "disabled");
}
return opt;
}
|
javascript
|
{
"resource": ""
}
|
|
q58364
|
validation
|
function(item) {
var that = this,
r;
var docFrag = document.createDocumentFragment();
var option = this.options[item.idx];
var data = this.data ? this.data[item.idx] : option;
var content = this.customSelected ? this.config.renderSelection(data) : option.textContent;
var tag = util.createElement("li", {
class: "selectr-tag",
html: content
});
var btn = util.createElement("button", {
class: "selectr-tag-remove",
type: "button"
});
tag.appendChild(btn);
// Set property to check against later
tag.idx = item.idx;
tag.tag = option.value;
this.tags.push(tag);
if (this.config.sortSelected) {
var tags = this.tags.slice();
// Deal with values that contain numbers
r = function(val, arr) {
val.replace(/(\d+)|(\D+)/g, function(that, $1, $2) {
arr.push([$1 || Infinity, $2 || ""]);
});
};
tags.sort(function(a, b) {
var x = [],
y = [],
ac, bc;
if (that.config.sortSelected === true) {
ac = a.tag;
bc = b.tag;
} else if (that.config.sortSelected === 'text') {
ac = a.textContent;
bc = b.textContent;
}
r(ac, x);
r(bc, y);
while (x.length && y.length) {
var ax = x.shift();
var by = y.shift();
var nn = (ax[0] - by[0]) || ax[1].localeCompare(by[1]);
if (nn) return nn;
}
return x.length - y.length;
});
util.each(tags, function(i, tg) {
docFrag.appendChild(tg);
});
this.label.innerHTML = "";
} else {
docFrag.appendChild(tag);
}
if (this.config.taggable) {
this.label.insertBefore(docFrag, this.input.parentNode);
} else {
this.label.appendChild(docFrag);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q58365
|
validation
|
function(item) {
var tag = false;
util.each(this.tags, function(i, t) {
if (t.idx === item.idx) {
tag = t;
}
}, this);
if (tag) {
this.label.removeChild(tag);
this.tags.splice(this.tags.indexOf(tag), 1);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q58366
|
validation
|
function() {
var tree = this.tree;
var scrollTop = tree.scrollTop;
var scrollHeight = tree.scrollHeight;
var offsetHeight = tree.offsetHeight;
var atBottom = scrollTop >= (scrollHeight - offsetHeight);
if ((atBottom && this.pageIndex < this.pages.length)) {
var f = document.createDocumentFragment();
util.each(this.pages[this.pageIndex], function(i, item) {
appendItem(item, f, this.customOption);
}, this);
tree.appendChild(f);
this.pageIndex++;
this.emit("selectr.paginate", {
items: this.items.length,
total: this.data.length,
page: this.pageIndex,
pages: this.pages.length
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q58367
|
validation
|
function() {
if (this.config.searchable || this.config.taggable) {
this.input.value = null;
this.searching = false;
if (this.config.searchable) {
util.removeClass(this.inputContainer, "active");
}
if (util.hasClass(this.container, "notice")) {
util.removeClass(this.container, "notice");
util.addClass(this.container, "open");
this.input.focus();
}
util.each(this.items, function(i, item) {
// Items that didn't match need the class
// removing to make them visible again
util.removeClass(item, "excluded");
// Remove the span element for underlining matched items
if (!this.customOption) {
item.innerHTML = item.textContent;
}
}, this);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q58368
|
validation
|
function(query, option) {
var result = new RegExp(query, "i").exec(option.textContent);
if (result) {
return option.textContent.replace(result[0], "<span class='selectr-match'>" + result[0] + "</span>");
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q58369
|
TreePath
|
validation
|
function TreePath(container, root) {
if (container) {
this.root = root;
this.path = document.createElement('div');
this.path.className = 'jsoneditor-treepath';
this.path.setAttribute('tabindex',0);
this.contentMenuClicked;
container.appendChild(this.path);
this.reset();
}
}
|
javascript
|
{
"resource": ""
}
|
q58370
|
ModeSwitcher
|
validation
|
function ModeSwitcher(container, modes, current, onSwitch) {
// available modes
var availableModes = {
code: {
'text': translate('modeCodeText'),
'title': translate('modeCodeTitle'),
'click': function () {
onSwitch('code')
}
},
form: {
'text': translate('modeFormText'),
'title': translate('modeFormTitle'),
'click': function () {
onSwitch('form');
}
},
text: {
'text': translate('modeTextText'),
'title': translate('modeTextTitle'),
'click': function () {
onSwitch('text');
}
},
tree: {
'text': translate('modeTreeText'),
'title': translate('modeTreeTitle'),
'click': function () {
onSwitch('tree');
}
},
view: {
'text': translate('modeViewText'),
'title': translate('modeViewTitle'),
'click': function () {
onSwitch('view');
}
}
};
// list the selected modes
var items = [];
for (var i = 0; i < modes.length; i++) {
var mode = modes[i];
var item = availableModes[mode];
if (!item) {
throw new Error('Unknown mode "' + mode + '"');
}
item.className = 'jsoneditor-type-modes' + ((current == mode) ? ' jsoneditor-selected' : '');
items.push(item);
}
// retrieve the title of current mode
var currentMode = availableModes[current];
if (!currentMode) {
throw new Error('Unknown mode "' + current + '"');
}
var currentTitle = currentMode.text;
// create the html element
var box = document.createElement('button');
box.type = 'button';
box.className = 'jsoneditor-modes jsoneditor-separator';
box.innerHTML = currentTitle + ' ▾';
box.title = 'Switch editor mode';
box.onclick = function () {
var menu = new ContextMenu(items);
menu.show(box, container);
};
var frame = document.createElement('div');
frame.className = 'jsoneditor-modes';
frame.style.position = 'relative';
frame.appendChild(box);
container.appendChild(frame);
this.dom = {
container: container,
box: box,
frame: frame
};
}
|
javascript
|
{
"resource": ""
}
|
q58371
|
lastNonWhitespace
|
validation
|
function lastNonWhitespace () {
var p = chars.length - 1;
while (p >= 0) {
var pp = chars[p];
if (!isWhiteSpace(pp)) {
return pp;
}
p--;
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q58372
|
nextNonWhiteSpace
|
validation
|
function nextNonWhiteSpace() {
var iNext = i + 1;
while (iNext < jsString.length && isWhiteSpace(jsString[iNext])) {
iNext++;
}
return jsString[iNext];
}
|
javascript
|
{
"resource": ""
}
|
q58373
|
parseString
|
validation
|
function parseString(endQuote) {
chars.push('"');
i++;
var c = curr();
while (i < jsString.length && c !== endQuote) {
if (c === '"' && prev() !== '\\') {
// unescaped double quote, escape it
chars.push('\\"');
}
else if (controlChars.hasOwnProperty(c)) {
// replace unescaped control characters with escaped ones
chars.push(controlChars[c])
}
else if (c === '\\') {
// remove the escape character when followed by a single quote ', not needed
i++;
c = curr();
if (c !== '\'') {
chars.push('\\');
}
chars.push(c);
}
else {
// regular character
chars.push(c);
}
i++;
c = curr();
}
if (c === endQuote) {
chars.push('"');
i++;
}
}
|
javascript
|
{
"resource": ""
}
|
q58374
|
parseKey
|
validation
|
function parseKey() {
var specialValues = ['null', 'true', 'false'];
var key = '';
var c = curr();
var regexp = /[a-zA-Z_$\d]/; // letter, number, underscore, dollar character
while (regexp.test(c)) {
key += c;
i++;
c = curr();
}
if (specialValues.indexOf(key) === -1) {
chars.push('"' + key + '"');
}
else {
chars.push(key);
}
}
|
javascript
|
{
"resource": ""
}
|
q58375
|
_positionForIndex
|
validation
|
function _positionForIndex(index) {
var textTillIndex = el.value.substring(0,index);
var row = (textTillIndex.match(/\n/g) || []).length + 1;
var col = textTillIndex.length - textTillIndex.lastIndexOf("\n");
return {
row: row,
column: col
}
}
|
javascript
|
{
"resource": ""
}
|
q58376
|
validation
|
function () {
var scrollTop = content.scrollTop;
var diff = (finalScrollTop - scrollTop);
if (Math.abs(diff) > 3) {
content.scrollTop += diff / 3;
editor.animateCallback = callback;
editor.animateTimeout = setTimeout(animate, 50);
}
else {
// finished
if (callback) {
callback(true);
}
content.scrollTop = finalScrollTop;
delete editor.animateTimeout;
delete editor.animateCallback;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q58377
|
validation
|
function (event) {
var target = event.target;
if ((target !== absoluteAnchor) && !util.isChildOf(target, absoluteAnchor)) {
destroy();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q58378
|
render
|
validation
|
function render(element) {
connectDevtools(DesktopRenderer);
ROOT_NODE = createElement('ROOT');
const container = ROOT_NODE;
// Returns the current fiber (flushed fiber)
const node = DesktopRenderer.createContainer(ROOT_NODE);
// Schedules a top level update with current fiber and a priority level (depending upon the context)
DesktopRenderer.updateContainer(element, node, null);
//ROOT_NODE.render();
}
|
javascript
|
{
"resource": ""
}
|
q58379
|
whitespace
|
validation
|
function whitespace(rule, value, source, errors, options) {
if (/^\s+$/.test(value) || value === '') {
errors.push(util.format(options.messages.whitespace, rule.fullField));
}
}
|
javascript
|
{
"resource": ""
}
|
q58380
|
enumerable
|
validation
|
function enumerable(rule, value, source, errors, options) {
rule[ENUM] = Array.isArray(rule[ENUM]) ? rule[ENUM] : [];
if (rule[ENUM].indexOf(value) === -1) {
errors.push(util.format(options.messages[ENUM], rule.fullField, rule[ENUM].join(', ')));
}
}
|
javascript
|
{
"resource": ""
}
|
q58381
|
range
|
validation
|
function range(rule, value, source, errors, options) {
const len = typeof rule.len === 'number';
const min = typeof rule.min === 'number';
const max = typeof rule.max === 'number';
// 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane)
const spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
let val = value;
let key = null;
const num = typeof (value) === 'number';
const str = typeof (value) === 'string';
const arr = Array.isArray(value);
if (num) {
key = 'number';
} else if (str) {
key = 'string';
} else if (arr) {
key = 'array';
}
// if the value is not of a supported type for range validation
// the validation rule rule should use the
// type property to also test for a particular type
if (!key) {
return false;
}
if (arr) {
val = value.length;
}
if (str) {
// 处理码点大于U+010000的文字length属性不准确的bug,如"𠮷𠮷𠮷".lenght !== 3
val = value.replace(spRegexp, '_').length;
}
if (len) {
if (val !== rule.len) {
errors.push(util.format(options.messages[key].len, rule.fullField, rule.len));
}
} else if (min && !max && val < rule.min) {
errors.push(util.format(options.messages[key].min, rule.fullField, rule.min));
} else if (max && !min && val > rule.max) {
errors.push(util.format(options.messages[key].max, rule.fullField, rule.max));
} else if (min && max && (val < rule.min || val > rule.max)) {
errors.push(util.format(options.messages[key].range,
rule.fullField, rule.min, rule.max));
}
}
|
javascript
|
{
"resource": ""
}
|
q58382
|
required
|
validation
|
function required(rule, value, source, errors, options, type) {
if (rule.required &&
(!source.hasOwnProperty(rule.field) || util.isEmptyValue(value, type || rule.type))) {
errors.push(util.format(options.messages.required, rule.fullField));
}
}
|
javascript
|
{
"resource": ""
}
|
q58383
|
string
|
validation
|
function string(rule, value, callback, source, options) {
const errors = [];
const validate = rule.required || (!rule.required && source.hasOwnProperty(rule.field));
if (validate) {
if (isEmptyValue(value, 'string') && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options, 'string');
if (!isEmptyValue(value, 'string')) {
rules.type(rule, value, source, errors, options);
rules.range(rule, value, source, errors, options);
rules.pattern(rule, value, source, errors, options);
if (rule.whitespace === true) {
rules.whitespace(rule, value, source, errors, options);
}
}
}
callback(errors);
}
|
javascript
|
{
"resource": ""
}
|
q58384
|
regexp
|
validation
|
function regexp(rule, value, callback, source, options) {
const errors = [];
const validate = rule.required || (!rule.required && source.hasOwnProperty(rule.field));
if (validate) {
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (!isEmptyValue(value)) {
rules.type(rule, value, source, errors, options);
}
}
callback(errors);
}
|
javascript
|
{
"resource": ""
}
|
q58385
|
pattern
|
validation
|
function pattern(rule, value, source, errors, options) {
if (rule.pattern) {
if (rule.pattern instanceof RegExp) {
// if a RegExp instance is passed, reset `lastIndex` in case its `global`
// flag is accidentally set to `true`, which in a validation scenario
// is not necessary and the result might be misleading
rule.pattern.lastIndex = 0;
if (!rule.pattern.test(value)) {
errors.push(util.format(options.messages.pattern.mismatch,
rule.fullField, value, rule.pattern));
}
} else if (typeof rule.pattern === 'string') {
const _pattern = new RegExp(rule.pattern);
if (!_pattern.test(value)) {
errors.push(util.format(options.messages.pattern.mismatch,
rule.fullField, value, rule.pattern));
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58386
|
type
|
validation
|
function type(rule, value, source, errors, options) {
if (rule.required && value === undefined) {
required(rule, value, source, errors, options);
return;
}
const custom = ['integer', 'float', 'array', 'regexp', 'object',
'method', 'email', 'number', 'date', 'url', 'hex'];
const ruleType = rule.type;
if (custom.indexOf(ruleType) > -1) {
if (!types[ruleType](value)) {
errors.push(util.format(options.messages.types[ruleType], rule.fullField, rule.type));
}
// straight typeof check
} else if (ruleType && typeof (value) !== rule.type) {
errors.push(util.format(options.messages.types[ruleType], rule.fullField, rule.type));
}
}
|
javascript
|
{
"resource": ""
}
|
q58387
|
getStyleComputedProperty
|
validation
|
function getStyleComputedProperty(element, property) {
if (element.nodeType !== 1) {
return [];
} // NOTE: 1 DOM access here
var window = element.ownerDocument.defaultView;
var css = window.getComputedStyle(element, null);
return property ? css[property] : css;
}
|
javascript
|
{
"resource": ""
}
|
q58388
|
getBoundingClientRect
|
validation
|
function getBoundingClientRect(element) {
var rect = {}; // IE10 10 FIX: Please, don't ask, the element isn't
// considered in DOM in some circumstances...
// This isn't reproducible in IE10 compatibility mode of IE11
try {
if (isIE(10)) {
rect = element.getBoundingClientRect();
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
rect.top += scrollTop;
rect.left += scrollLeft;
rect.bottom += scrollTop;
rect.right += scrollLeft;
} else {
rect = element.getBoundingClientRect();
}
} catch (e) {}
var result = {
left: rect.left,
top: rect.top,
width: rect.right - rect.left,
height: rect.bottom - rect.top
}; // subtract scrollbar size from sizes
var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {};
var width = sizes.width || element.clientWidth || result.right - result.left;
var height = sizes.height || element.clientHeight || result.bottom - result.top;
var horizScrollbar = element.offsetWidth - width;
var vertScrollbar = element.offsetHeight - height; // if an hypothetical scrollbar is detected, we must be sure it's not a `border`
// we make this check conditional for performance reasons
if (horizScrollbar || vertScrollbar) {
var styles = getStyleComputedProperty(element);
horizScrollbar -= getBordersSize(styles, 'x');
vertScrollbar -= getBordersSize(styles, 'y');
result.width -= horizScrollbar;
result.height -= vertScrollbar;
}
return getClientRect(result);
}
|
javascript
|
{
"resource": ""
}
|
q58389
|
isFixed
|
validation
|
function isFixed(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
return false;
}
if (getStyleComputedProperty(element, 'position') === 'fixed') {
return true;
}
var parentNode = getParentNode(element);
if (!parentNode) {
return false;
}
return isFixed(parentNode);
}
|
javascript
|
{
"resource": ""
}
|
q58390
|
getBoundaries
|
validation
|
function getBoundaries(popper, reference, padding, boundariesElement) {
var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; // NOTE: 1 DOM access here
var boundaries = {
top: 0,
left: 0
};
var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, reference); // Handle viewport case
if (boundariesElement === 'viewport') {
boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition);
} else {
// Handle other cases based on DOM element used as boundaries
var boundariesNode = void 0;
if (boundariesElement === 'scrollParent') {
boundariesNode = getScrollParent(getParentNode(reference));
if (boundariesNode.nodeName === 'BODY') {
boundariesNode = popper.ownerDocument.documentElement;
}
} else if (boundariesElement === 'window') {
boundariesNode = popper.ownerDocument.documentElement;
} else {
boundariesNode = boundariesElement;
}
var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition); // In case of HTML, we need a different computation
if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
var _getWindowSizes = getWindowSizes(popper.ownerDocument),
height = _getWindowSizes.height,
width = _getWindowSizes.width;
boundaries.top += offsets.top - offsets.marginTop;
boundaries.bottom = height + offsets.top;
boundaries.left += offsets.left - offsets.marginLeft;
boundaries.right = width + offsets.left;
} else {
// for all the other DOM elements, this one is good
boundaries = offsets;
}
} // Add paddings
padding = padding || 0;
var isPaddingNumber = typeof padding === 'number';
boundaries.left += isPaddingNumber ? padding : padding.left || 0;
boundaries.top += isPaddingNumber ? padding : padding.top || 0;
boundaries.right -= isPaddingNumber ? padding : padding.right || 0;
boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0;
return boundaries;
}
|
javascript
|
{
"resource": ""
}
|
q58391
|
isModifierEnabled
|
validation
|
function isModifierEnabled(modifiers, modifierName) {
return modifiers.some(function (_ref) {
var name = _ref.name,
enabled = _ref.enabled;
return enabled && name === modifierName;
});
}
|
javascript
|
{
"resource": ""
}
|
q58392
|
Popper
|
validation
|
function Popper(reference, popper) {
var _this = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, Popper);
this.scheduleUpdate = function () {
return requestAnimationFrame(_this.update);
}; // make update() debounced, so that it only runs at most once-per-tick
this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it
this.options = _extends({}, Popper.Defaults, options); // init state
this.state = {
isDestroyed: false,
isCreated: false,
scrollParents: []
}; // get reference and popper elements (allow jQuery wrappers)
this.reference = reference && reference.jquery ? reference[0] : reference;
this.popper = popper && popper.jquery ? popper[0] : popper; // Deep merge modifiers options
this.options.modifiers = {};
Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {
_this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
}); // Refactoring modifiers' list (Object => Array)
this.modifiers = Object.keys(this.options.modifiers).map(function (name) {
return _extends({
name: name
}, _this.options.modifiers[name]);
}) // sort the modifiers by order
.sort(function (a, b) {
return a.order - b.order;
}); // modifiers have the ability to execute arbitrary code when Popper.js get inited
// such code is executed in the same order of its modifier
// they could add new properties to their options configuration
// BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
this.modifiers.forEach(function (modifierOptions) {
if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) {
modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);
}
}); // fire the first update to position the popper in the right place
this.update();
var eventsEnabled = this.options.eventsEnabled;
if (eventsEnabled) {
// setup event listeners, they will take care of update the position in specific situations
this.enableEventListeners();
}
this.state.eventsEnabled = eventsEnabled;
}
|
javascript
|
{
"resource": ""
}
|
q58393
|
writeOutputHTML
|
validation
|
function writeOutputHTML(dir, html) {
const outputPath = pathJoin(dir, 'index.html');
mkdirp.sync(path.dirname(outputPath));
writeFileSync(outputPath, serialize(html));
}
|
javascript
|
{
"resource": ""
}
|
q58394
|
getOutputHTML
|
validation
|
function getOutputHTML(dir) {
if (existsSync(`${dir}/index.html`)) {
return readHTML(`${dir}/index.html`);
}
const outputHTML = readHTML(inputIndexHTMLPath);
const scripts = queryAll(outputHTML, predicates.hasTagName('script'));
const moduleScripts = scripts.filter(script => getAttribute(script, 'type') === 'module');
moduleScripts.forEach(moduleScript => {
remove(moduleScript);
});
writeOutputHTML(dir, outputHTML);
return outputHTML;
}
|
javascript
|
{
"resource": ""
}
|
q58395
|
copyPolyfills
|
validation
|
function copyPolyfills(pluginConfig, outputConfig) {
if (
!pluginConfig.polyfillDynamicImports &&
!pluginConfig.polyfillWebcomponents &&
!pluginConfig.polyfillBabel
) {
return;
}
const polyfillsDir = `${outputConfig.dir.replace('/legacy', '')}/polyfills`;
mkdirp.sync(polyfillsDir);
if (pluginConfig.polyfillDynamicImports) {
copyFileSync(
path.resolve(pathJoin(__dirname, '../../src/dynamic-import-polyfill.js')),
`${polyfillsDir}/dynamic-import-polyfill.js`,
);
}
if (pluginConfig.polyfillWebcomponents) {
copyFileSync(
require.resolve('@webcomponents/webcomponentsjs/webcomponents-bundle.js'),
`${polyfillsDir}/webcomponent-polyfills.js`,
);
}
if (pluginConfig.polyfillBabel) {
copyFileSync(
require.resolve('@babel/polyfill/browser.js'),
`${polyfillsDir}/babel-polyfills.js`,
);
}
}
|
javascript
|
{
"resource": ""
}
|
q58396
|
writeModules
|
validation
|
function writeModules(pluginConfig, outputConfig, entryModules) {
const indexHTML = getOutputHTML(outputConfig.dir);
const head = query(indexHTML, predicates.hasTagName('head'));
const body = query(indexHTML, predicates.hasTagName('body'));
// If dynamic imports are polyfilled, we first need to feature detect so we can't load our app using the
// 'src' attribute.
if (pluginConfig.polyfillDynamicImports) {
// Feature detect dynamic import in a separate script, because browsers which don't
// support it will throw a syntax error and stop executing the module
append(body, createScriptModule('window.importModule=src=>import(src);'));
// The actual loading script. Loads web components and dynamic import polyfills if necessary, then
// loads the user's modules
append(
body,
createScriptModule(`
(async () => {
const p = [];
if (!('attachShadow' in Element.prototype) || !('getRootNode' in Element.prototype)) {p.push('./polyfills/webcomponent-polyfills.js');}
if (!window.importModule) {p.push('./polyfills/dynamic-import-polyfill.js');}
if (p.length > 0) {await Promise.all(p.map(p => new Promise((rs, rj) => {const s = document.createElement('script');s.src = p;s.onerror = () => rj(\`Failed to load \${s.s}\`);s.onload = () => rs();document.head.appendChild(s);})));}
${entryModules.map(src => `importModule('${src}');`).join('')}
})();
`),
);
// Because the module is loaded after some js execution, add preload hints so that it is downloaded
// from the start
entryModules.forEach(src => {
append(
head,
createElement('link', {
rel: 'preload',
as: 'script',
crossorigin: 'anonymous',
href: src,
}),
);
});
} else {
// No polyfilling needed, so just create a module script
entryModules.forEach(src => {
append(body, createScript({ type: 'module', src }));
});
}
writeOutputHTML(outputConfig.dir, indexHTML);
}
|
javascript
|
{
"resource": ""
}
|
q58397
|
karmaEsmFramework
|
validation
|
function karmaEsmFramework(karmaConfig, karmaEmitter) {
if (!karmaConfig.files.some(file => file.type === 'module')) {
throw new Error(
"Did not find any test files with type='module'." +
"Follow this format: { pattern: config.grep ? config.grep : 'test/**/*.test.js', type: 'module' }",
);
}
initialize(karmaConfig, karmaEmitter);
}
|
javascript
|
{
"resource": ""
}
|
q58398
|
createCompiler
|
validation
|
function createCompiler(config, karmaEmitter) {
const cache = new Map();
const watcher = chokidar.watch([]);
watcher.on('change', filePath => {
if (!filePath.endsWith('.test.js') && !filePath.endsWith('.spec.js')) {
karmaEmitter.refreshFiles();
}
cache.delete(filePath);
});
function addToCache(filePath, code) {
cache.set(filePath, code);
watcher.add(filePath);
}
function babelCompile(filePath, code) {
return babel.transform(code, {
filename: filePath,
...config.babelOptions,
}).code;
}
function compile(filePath, code) {
// if we should not babel compile some files, only add them to the cache
if (config.babel && config.babel.exclude) {
if (config.babel.exclude.some(exclude => minimatch(filePath, exclude))) {
addToCache(filePath, code);
return code;
}
}
const compiled = babelCompile(filePath, code);
addToCache(filePath, compiled);
return compiled;
}
function getCached(filePath) {
return cache.get(filePath);
}
return {
compile,
getCached,
};
}
|
javascript
|
{
"resource": ""
}
|
q58399
|
karmaEsmPreprocessor
|
validation
|
function karmaEsmPreprocessor(logger) {
const log = logger.create('preprocessor.esm');
function preprocess(code, file, done) {
try {
let compiledCode = esm.compiler.getCached(file.originalPath);
if (!compiledCode) {
compiledCode = esm.compiler.compile(file.originalPath, code);
}
done(null, compiledCode);
} catch (e) {
const message = `\n\n${e.message}\n at ${file.originalPath}\n\n`;
log.error(message);
done(null, code);
}
}
return preprocess;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.