code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
using System.Globalization; using System.Collections.Generic; using ServiceStack.Common; using ServiceStack.Common.Web; using ServiceStack.ServiceHost; using ServiceStack.Configuration; using ServiceStack.FluentValidation; using ServiceStack.Text; using System; using System.Net; using System.Security.Cryptography; using System.Text; using ServiceStack.WebHost.Endpoints.Extensions; using HttpResponseExtensions = ServiceStack.WebHost.Endpoints.Extensions.HttpResponseExtensions; namespace ServiceStack.ServiceInterface.Auth { public class DigestAuthProvider : AuthProvider { class DigestAuthValidator : AbstractValidator<Auth> { public DigestAuthValidator() { RuleFor(x => x.UserName).NotEmpty(); RuleFor(x => x.Password).NotEmpty(); } } public static string Name = AuthService.DigestProvider; public static string Realm = "/auth/" + AuthService.DigestProvider; public static int NonceTimeOut = 600; public string PrivateKey; public IResourceManager AppSettings { get; set; } public DigestAuthProvider() { this.Provider = Name; PrivateKey = Guid.NewGuid().ToString(); this.AuthRealm = Realm; } public DigestAuthProvider(IResourceManager appSettings, string authRealm, string oAuthProvider) : base(appSettings, authRealm, oAuthProvider) { } public DigestAuthProvider(IResourceManager appSettings) : base(appSettings, Realm, Name) { } public virtual bool TryAuthenticate(IServiceBase authService, string userName, string password) { var authRepo = authService.TryResolve<IUserAuthRepository>(); if (authRepo == null) { Log.WarnFormat("Tried to authenticate without a registered IUserAuthRepository"); return false; } var session = authService.GetSession(); var digestInfo = authService.RequestContext.Get<IHttpRequest>().GetDigestAuth(); UserAuth userAuth = null; if (authRepo.TryAuthenticate(digestInfo,PrivateKey,NonceTimeOut, session.Sequence, out userAuth)) { session.PopulateWith(userAuth); session.IsAuthenticated = true; session.Sequence = digestInfo["nc"]; session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture); session.ProviderOAuthAccess = authRepo.GetUserOAuthProviders(session.UserAuthId) .ConvertAll(x => (IOAuthTokens)x); return true; } return false; } public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null) { if (request != null) { if (!LoginMatchesSession(session, request.UserName)) return false; } return !session.UserAuthName.IsNullOrEmpty(); } public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { //new CredentialsAuthValidator().ValidateAndThrow(request); return Authenticate(authService, session, request.UserName, request.Password); } protected object Authenticate(IServiceBase authService, IAuthSession session, string userName, string password) { if (!LoginMatchesSession(session, userName)) { authService.RemoveSession(); session = authService.GetSession(); } if (TryAuthenticate(authService, userName, password)) { if (session.UserAuthName == null) session.UserAuthName = userName; OnAuthenticated(authService, session, null, null); return new AuthResponse { UserName = userName, SessionId = session.Id, }; } throw HttpError.Unauthorized("Invalid UserName or Password"); } public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { var userSession = session as AuthUserSession; if (userSession != null) { LoadUserAuthInfo(userSession, tokens, authInfo); } var authRepo = authService.TryResolve<IUserAuthRepository>(); if (authRepo != null) { if (tokens != null) { authInfo.ForEach((x, y) => tokens.Items[x] = y); session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens); } foreach (var oAuthToken in session.ProviderOAuthAccess) { var authProvider = AuthService.GetAuthProvider(oAuthToken.Provider); if (authProvider == null) continue; var userAuthProvider = authProvider as OAuthProvider; if (userAuthProvider != null) { userAuthProvider.LoadUserOAuthProvider(session, oAuthToken); } } //var httpRes = authService.RequestContext.Get<IHttpResponse>(); //if (httpRes != null) //{ // httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId); //} } authService.SaveSession(session, SessionExpiry); session.OnAuthenticated(authService, session, tokens, authInfo); } public override void OnFailedAuthentication(IAuthSession session, IHttpRequest httpReq, IHttpResponse httpRes) { var digestHelper = new DigestAuthFunctions(); httpRes.StatusCode = (int)HttpStatusCode.Unauthorized; httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\", nonce=\"{2}\", qop=\"auth\"".Fmt(Provider, AuthRealm,digestHelper.GetNonce(httpReq.UserHostAddress,PrivateKey))); httpRes.EndRequest(); } } }
fanta-mnix/ServiceStack
src/ServiceStack.ServiceInterface/Auth/DigestAuthProvider.cs
C#
bsd-3-clause
6,338
<?php namespace mageekguy\atoum\fs; use mageekguy\atoum\fs\path\exception; class path { protected $drive = ''; protected $components = ''; protected $directorySeparator = DIRECTORY_SEPARATOR; public function __construct($value, $directorySeparator = null) { $this ->setDriveAndComponents($value) ->directorySeparator = (string) $directorySeparator ?: DIRECTORY_SEPARATOR ; } public function __toString() { $components = $this->components; if ($this->directorySeparator === '\\') { $components = str_replace('/', '\\', $components); } return $this->drive . $components; } public function getDirectorySeparator() { return $this->directorySeparator; } public function relativizeFrom(path $reference) { $this->resolve(); $resolvedReferencePath = $reference->getResolvedPath(); $this->drive = null; switch (true) { case $this->components === '/': $this->components = '.' . $this->components; break; case $this->components === $resolvedReferencePath->components: $this->components = '.'; break; case $this->isSubPathOf($resolvedReferencePath): $this->components = './' . ltrim(substr($this->components, strlen($resolvedReferencePath->components)), '/'); break; default: $relativePath = ''; while ($this->isNotSubPathOf($resolvedReferencePath)) { $relativePath .= '../'; $resolvedReferencePath = $resolvedReferencePath->getParentDirectoryPath(); } $this->components = static::getComponents($relativePath) . '/' . ltrim(substr($this->components, strlen($resolvedReferencePath->components)), '/'); } return $this; } public function exists() { return (file_exists((string) $this) === true); } public function resolve() { if ($this->isAbsolute() === false) { $this->absolutize(); } $components = []; foreach (explode('/', ltrim($this->components, '/')) as $component) { switch ($component) { case '.': break; case '..': if (count($components) <= 0) { throw new exception('Unable to resolve path \'' . $this . '\''); } array_pop($components); break; default: $components[] = $component; } } $this->components = '/' . implode('/', $components); return $this; } public function isSubPathOf(path $path) { $this->resolve(); $resolvedPath = $path->getResolvedPath(); return ($this->components !== $resolvedPath->components && ($resolvedPath->isRoot() === true || strpos($this->components, $resolvedPath->components . '/') === 0)); } public function isNotSubPathOf(path $path) { return ($this->isSubPathOf($path) === false); } public function isRoot() { return static::pathIsRoot($this->getResolvedPath()->components); } public function isAbsolute() { return static::pathIsAbsolute($this->components); } public function absolutize() { if ($this->isAbsolute() === false) { $this->setDriveAndComponents(getcwd() . DIRECTORY_SEPARATOR . $this->components); } return $this; } public function getRealPath() { $absolutePath = $this->getAbsolutePath(); $files = ''; $realPath = realpath((string) $absolutePath); if ($realPath === false) { while ($realPath === false && $absolutePath->isRoot() === false) { $files = '/' . basename((string) $absolutePath) . $files; $absolutePath = $absolutePath->getParentDirectoryPath(); $realPath = realpath((string) $absolutePath); } } if ($realPath === false) { throw new exception('Unable to get real path for \'' . $this . '\''); } return $absolutePath->setDriveAndComponents($realPath . $files); } public function getParentDirectoryPath() { $parentDirectory = clone $this; $parentDirectory->components = self::getComponents(dirname($parentDirectory->components)); return $parentDirectory; } public function getRealParentDirectoryPath() { $realParentDirectoryPath = $this->getParentDirectoryPath(); while ($realParentDirectoryPath->exists() === false && $realParentDirectoryPath->isRoot() === false) { $realParentDirectoryPath = $realParentDirectoryPath->getParentDirectoryPath(); } if ($realParentDirectoryPath->exists() === false) { throw new exception('Unable to find real parent directory for \'' . $this . '\''); } return $realParentDirectoryPath; } public function getRelativePathFrom(path $reference) { $clone = clone $this; return $clone->relativizeFrom($reference); } public function getResolvedPath() { $clone = clone $this; return $clone->resolve(); } public function getAbsolutePath() { $clone = clone $this; return $clone->absolutize(); } public function createParentDirectory() { $parentDirectory = $this->getParentDirectoryPath(); if (file_exists((string) $parentDirectory) === false && @mkdir($parentDirectory, 0777, true) === false) { throw new exception('Unable to create directory \'' . $parentDirectory . '\''); } return $this; } public function putContents($data) { if (@file_put_contents($this->createParentDirectory(), $data) === false) { throw new exception('Unable to put data \'' . $data . '\' in file \'' . $this . '\''); } return $this; } protected function setDriveAndComponents($value) { $drive = null; if (preg_match('#^[a-z]:#i', $value, $matches) == true) { $drive = $matches[0]; $value = substr($value, 2); } $this->drive = $drive; $this->components = self::getComponents($value); return $this; } protected static function pathIsRoot($path) { return ($path === '/'); } protected static function pathIsAbsolute($path) { return (substr($path, 0, 1) === '/'); } protected static function getComponents($path) { $path = str_replace('\\', '/', $path); if (static::pathIsRoot($path) === false) { $path = rtrim($path, '/'); } return preg_replace('#/{2,}#', '/', $path); } }
jubianchi/atoum
classes/fs/path.php
PHP
bsd-3-clause
7,037
from energenie import switch_off switch_off()
rjw57/energenie
examples/simple/off.py
Python
bsd-3-clause
47
require "og/store/sql/utils" module Og module SqliteUtils include SqlUtils # works fine without any quote. #-- # Is this verified? #++ def quote_column(val) return val end alias_method :quote_table, :quote_column end end
oxywtf/og
lib/og/adapter/sqlite/utils.rb
Ruby
bsd-3-clause
255
""" WSGI config for {{ cookiecutter.project_name }} project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os {% if cookiecutter.use_newrelic == 'y' -%} if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': import newrelic.agent newrelic.agent.initialize() {%- endif %} from django.core.wsgi import get_wsgi_application {% if cookiecutter.use_sentry == 'y' -%} if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': from raven.contrib.django.raven_compat.middleware.wsgi import Sentry {%- endif %} # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() {% if cookiecutter.use_sentry == 'y' -%} if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': application = Sentry(application) {%- endif %} {% if cookiecutter.use_newrelic == 'y' -%} if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': application = newrelic.agent.WSGIApplicationWrapper(application) {%- endif %} # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
aeikenberry/cookiecutter-django-rest-babel
{{cookiecutter.project_slug}}/config/wsgi.py
Python
bsd-3-clause
2,232
<?php require_once('connect.inc'); require_once('table.inc'); $references = array(); if (!(mysqli_real_query($link, "SELECT id, label FROM test ORDER BY id ASC LIMIT 2")) || !($res = mysqli_store_result($link))) printf("[001] [%d] %s\n", mysqli_errno($link), mysqli_error($link)); $idx = 0; while ($row = mysqli_fetch_assoc($res)) { /* mysqlnd: force separation - create copies */ $references[$idx] = array( 'id' => &$row['id'], 'label' => $row['label'] . ''); $references[$idx++]['id'] += 0; } mysqli_close($link); mysqli_data_seek($res, 0); while ($row = mysqli_fetch_assoc($res)) { /* mysqlnd: force separation - create copies */ $references[$idx] = array( 'id' => &$row['id'], 'label' => $row['label'] . ''); $references[$idx++]['id'] += 0; } mysqli_free_result($res); if (!$link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket)) printf("[002] Cannot connect to the server using host=%s, user=%s, passwd=***, dbname=%s, port=%s, socket=%s\n", $host, $user, $db, $port, $socket); if (!(mysqli_real_query($link, "SELECT id, label FROM test ORDER BY id ASC LIMIT 2")) || !($res = mysqli_use_result($link))) printf("[003] [%d] %s\n", mysqli_errno($link), mysqli_error($link)); while ($row = mysqli_fetch_assoc($res)) { /* mysqlnd: force separation - create copies*/ $references[$idx] = array( 'id' => &$row['id'], 'label' => $row['label'] . ''); $references[$idx]['id2'] = &$references[$idx]['id']; $references[$idx]['id'] += 1; $references[$idx++]['id2'] += 1; } $references[$idx++] = &$res; mysqli_free_result($res); @debug_zval_dump($references); if (!(mysqli_real_query($link, "SELECT id, label FROM test ORDER BY id ASC LIMIT 1")) || !($res = mysqli_use_result($link))) printf("[004] [%d] %s\n", mysqli_errno($link), mysqli_error($link)); $tmp = array(); while ($row = mysqli_fetch_assoc($res)) { $tmp[] = $row; } $tmp = unserialize(serialize($tmp)); debug_zval_dump($tmp); mysqli_free_result($res); mysqli_close($link); print "done!"; ?>
stephens2424/php
testdata/fuzzdir/corpus/ext_mysqli_tests_mysqli_result_references.php
PHP
bsd-3-clause
2,068
// // Mono.Security.Cryptography.SymmetricTransform implementation // // Authors: // Thomas Neidhart (tome@sbox.tugraz.at) // Sebastien Pouliot <sebastien@ximian.com> // // Portions (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2008 Novell, Inc (http://www.novell.com) // // 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. // using System; using System.Security.Cryptography; namespace Mono.Security.Cryptography { // This class implement most of the common code required for symmetric // algorithm transforms, like: // - CipherMode: Builds CBC and CFB on top of (descendant supplied) ECB // - PaddingMode, transform properties, multiple blocks, reuse... // // Descendants MUST: // - intialize themselves (like key expansion, ...) // - override the ECB (Electronic Code Book) method which will only be // called using BlockSize byte[] array. internal abstract class SymmetricTransform : ICryptoTransform { protected SymmetricAlgorithm algo; protected bool encrypt; protected int BlockSizeByte; protected byte[] temp; protected byte[] temp2; private byte[] workBuff; private byte[] workout; protected PaddingMode padmode; // Silverlight 2.0 does not support any feedback mode protected int FeedBackByte; private bool m_disposed = false; protected bool lastBlock; public SymmetricTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] rgbIV) { algo = symmAlgo; encrypt = encryption; BlockSizeByte = (algo.BlockSize >> 3); if (rgbIV == null) { rgbIV = KeyBuilder.IV (BlockSizeByte); } else { rgbIV = (byte[]) rgbIV.Clone (); } // compare the IV length with the "currently selected" block size and *ignore* IV that are too big if (rgbIV.Length < BlockSizeByte) { string msg = string.Format ("IV is too small ({0} bytes), it should be {1} bytes long.", rgbIV.Length, BlockSizeByte); throw new CryptographicException (msg); } padmode = algo.Padding; // mode buffers temp = new byte [BlockSizeByte]; Buffer.BlockCopy (rgbIV, 0, temp, 0, System.Math.Min (BlockSizeByte, rgbIV.Length)); temp2 = new byte [BlockSizeByte]; FeedBackByte = (algo.FeedbackSize >> 3); // transform buffers workBuff = new byte [BlockSizeByte]; workout = new byte [BlockSizeByte]; } ~SymmetricTransform () { Dispose (false); } void IDisposable.Dispose () { Dispose (true); GC.SuppressFinalize (this); // Finalization is now unnecessary } // MUST be overriden by classes using unmanaged ressources // the override method must call the base class protected virtual void Dispose (bool disposing) { if (!m_disposed) { if (disposing) { // dispose managed object: zeroize and free Array.Clear (temp, 0, BlockSizeByte); temp = null; Array.Clear (temp2, 0, BlockSizeByte); temp2 = null; } m_disposed = true; } } public virtual bool CanTransformMultipleBlocks { get { return true; } } public virtual bool CanReuseTransform { get { return false; } } public virtual int InputBlockSize { get { return BlockSizeByte; } } public virtual int OutputBlockSize { get { return BlockSizeByte; } } // note: Each block MUST be BlockSizeValue in size!!! // i.e. Any padding must be done before calling this method protected virtual void Transform (byte[] input, byte[] output) { switch (algo.Mode) { case CipherMode.ECB: ECB (input, output); break; case CipherMode.CBC: CBC (input, output); break; case CipherMode.CFB: CFB (input, output); break; case CipherMode.OFB: OFB (input, output); break; case CipherMode.CTS: CTS (input, output); break; default: throw new NotImplementedException ("Unkown CipherMode" + algo.Mode.ToString ()); } } // Electronic Code Book (ECB) protected abstract void ECB (byte[] input, byte[] output); // Cipher-Block-Chaining (CBC) protected virtual void CBC (byte[] input, byte[] output) { if (encrypt) { for (int i = 0; i < BlockSizeByte; i++) temp[i] ^= input[i]; ECB (temp, output); Buffer.BlockCopy (output, 0, temp, 0, BlockSizeByte); } else { Buffer.BlockCopy (input, 0, temp2, 0, BlockSizeByte); ECB (input, output); for (int i = 0; i < BlockSizeByte; i++) output[i] ^= temp[i]; Buffer.BlockCopy (temp2, 0, temp, 0, BlockSizeByte); } } // Cipher-FeedBack (CFB) // this is how *CryptoServiceProvider implements CFB // only AesCryptoServiceProvider support CFB > 8 // RijndaelManaged is incompatible with this implementation (and overrides it in it's own transform) protected virtual void CFB (byte[] input, byte[] output) { if (encrypt) { for (int x = 0; x < BlockSizeByte; x++) { // temp is first initialized with the IV ECB (temp, temp2); output [x] = (byte) (temp2 [0] ^ input [x]); Buffer.BlockCopy (temp, 1, temp, 0, BlockSizeByte - 1); Buffer.BlockCopy (output, x, temp, BlockSizeByte - 1, 1); } } else { for (int x = 0; x < BlockSizeByte; x++) { // we do not really decrypt this data! encrypt = true; // temp is first initialized with the IV ECB (temp, temp2); encrypt = false; Buffer.BlockCopy (temp, 1, temp, 0, BlockSizeByte - 1); Buffer.BlockCopy (input, x, temp, BlockSizeByte - 1, 1); output [x] = (byte) (temp2 [0] ^ input [x]); } } } // Output-FeedBack (OFB) protected virtual void OFB (byte[] input, byte[] output) { throw new CryptographicException ("OFB isn't supported by the framework"); } // Cipher Text Stealing (CTS) protected virtual void CTS (byte[] input, byte[] output) { throw new CryptographicException ("CTS isn't supported by the framework"); } private void CheckInput (byte[] inputBuffer, int inputOffset, int inputCount) { if (inputBuffer == null) throw new ArgumentNullException ("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException ("inputOffset", "< 0"); if (inputCount < 0) throw new ArgumentOutOfRangeException ("inputCount", "< 0"); // ordered to avoid possible integer overflow if (inputOffset > inputBuffer.Length - inputCount) throw new ArgumentException ("inputBuffer", ("Overflow")); } // this method may get called MANY times so this is the one to optimize public virtual int TransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (m_disposed) throw new ObjectDisposedException ("Object is disposed"); CheckInput (inputBuffer, inputOffset, inputCount); // check output parameters if (outputBuffer == null) throw new ArgumentNullException ("outputBuffer"); if (outputOffset < 0) throw new ArgumentOutOfRangeException ("outputOffset", "< 0"); // ordered to avoid possible integer overflow int len = outputBuffer.Length - inputCount - outputOffset; if (!encrypt && (0 > len) && ((padmode == PaddingMode.None) || (padmode == PaddingMode.Zeros))) { throw new CryptographicException ("outputBuffer", ("Overflow")); } else if (KeepLastBlock) { if (0 > len + BlockSizeByte) { throw new CryptographicException ("outputBuffer", ("Overflow")); } } else { if (0 > len) { // there's a special case if this is the end of the decryption process if (inputBuffer.Length - inputOffset - outputBuffer.Length == BlockSizeByte) inputCount = outputBuffer.Length - outputOffset; else throw new CryptographicException ("outputBuffer", ("Overflow")); } } return InternalTransformBlock (inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); } private bool KeepLastBlock { get { return ((!encrypt) && (padmode != PaddingMode.None) && (padmode != PaddingMode.Zeros)); } } private int InternalTransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { int offs = inputOffset; int full; // this way we don't do a modulo every time we're called // and we may save a division if (inputCount != BlockSizeByte) { if ((inputCount % BlockSizeByte) != 0) throw new CryptographicException ("Invalid input block size."); full = inputCount / BlockSizeByte; } else full = 1; if (KeepLastBlock) full--; int total = 0; if (lastBlock) { Transform (workBuff, workout); Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte); outputOffset += BlockSizeByte; total += BlockSizeByte; lastBlock = false; } for (int i = 0; i < full; i++) { Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte); Transform (workBuff, workout); Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte); offs += BlockSizeByte; outputOffset += BlockSizeByte; total += BlockSizeByte; } if (KeepLastBlock) { Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte); lastBlock = true; } return total; } RandomNumberGenerator _rng; private void Random (byte[] buffer, int start, int length) { if (_rng == null) { _rng = RandomNumberGenerator.Create (); } byte[] random = new byte [length]; _rng.GetBytes (random); Buffer.BlockCopy (random, 0, buffer, start, length); } private void ThrowBadPaddingException (PaddingMode padding, int length, int position) { string msg = String.Format ( ("Bad {0} padding."), padding); if (length >= 0) msg += String.Format ( (" Invalid length {0}."), length); if (position >= 0) msg += String.Format ( (" Error found at position {0}."), position); throw new CryptographicException (msg); } protected virtual byte[] FinalEncrypt (byte[] inputBuffer, int inputOffset, int inputCount) { // are there still full block to process ? int full = (inputCount / BlockSizeByte) * BlockSizeByte; int rem = inputCount - full; int total = full; switch (padmode) { case PaddingMode.ANSIX923: case PaddingMode.ISO10126: case PaddingMode.PKCS7: // we need to add an extra block for padding total += BlockSizeByte; break; default: if (inputCount == 0) return new byte [0]; if (rem != 0) { if (padmode == PaddingMode.None) throw new CryptographicException ("invalid block length"); // zero padding the input (by adding a block for the partial data) byte[] paddedInput = new byte [full + BlockSizeByte]; Buffer.BlockCopy (inputBuffer, inputOffset, paddedInput, 0, inputCount); inputBuffer = paddedInput; inputOffset = 0; inputCount = paddedInput.Length; total = inputCount; } break; } byte[] res = new byte [total]; int outputOffset = 0; // process all blocks except the last (final) block while (total > BlockSizeByte) { InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset); inputOffset += BlockSizeByte; outputOffset += BlockSizeByte; total -= BlockSizeByte; } // now we only have a single last block to encrypt byte padding = (byte) (BlockSizeByte - rem); switch (padmode) { case PaddingMode.ANSIX923: // XX 00 00 00 00 00 00 07 (zero + padding length) res [res.Length - 1] = padding; Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem); // the last padded block will be transformed in-place InternalTransformBlock (res, full, BlockSizeByte, res, full); break; case PaddingMode.ISO10126: // XX 3F 52 2A 81 AB F7 07 (random + padding length) Random (res, res.Length - padding, padding - 1); res [res.Length - 1] = padding; Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem); // the last padded block will be transformed in-place InternalTransformBlock (res, full, BlockSizeByte, res, full); break; case PaddingMode.PKCS7: // XX 07 07 07 07 07 07 07 (padding length) for (int i = res.Length; --i >= (res.Length - padding);) res [i] = padding; Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem); // the last padded block will be transformed in-place InternalTransformBlock (res, full, BlockSizeByte, res, full); break; default: InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset); break; } return res; } protected virtual byte[] FinalDecrypt (byte[] inputBuffer, int inputOffset, int inputCount) { int full = inputCount; int total = inputCount; if (lastBlock) total += BlockSizeByte; byte[] res = new byte [total]; int outputOffset = 0; while (full > 0) { int len = InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset); inputOffset += BlockSizeByte; outputOffset += len; full -= BlockSizeByte; } if (lastBlock) { Transform (workBuff, workout); Buffer.BlockCopy (workout, 0, res, outputOffset, BlockSizeByte); outputOffset += BlockSizeByte; lastBlock = false; } // total may be 0 (e.g. PaddingMode.None) byte padding = ((total > 0) ? res [total - 1] : (byte) 0); switch (padmode) { case PaddingMode.ANSIX923: if ((padding == 0) || (padding > BlockSizeByte)) ThrowBadPaddingException (padmode, padding, -1); for (int i = padding - 1; i > 0; i--) { if (res [total - 1 - i] != 0x00) ThrowBadPaddingException (padmode, -1, i); } total -= padding; break; case PaddingMode.ISO10126: if ((padding == 0) || (padding > BlockSizeByte)) ThrowBadPaddingException (padmode, padding, -1); total -= padding; break; case PaddingMode.PKCS7: if ((padding == 0) || (padding > BlockSizeByte)) ThrowBadPaddingException (padmode, padding, -1); for (int i = padding - 1; i > 0; i--) { if (res [total - 1 - i] != padding) ThrowBadPaddingException (padmode, -1, i); } total -= padding; break; case PaddingMode.None: // nothing to do - it's a multiple of block size case PaddingMode.Zeros: // nothing to do - user must unpad himself break; } // return output without padding if (total > 0) { byte[] data = new byte [total]; Buffer.BlockCopy (res, 0, data, 0, total); // zeroize decrypted data (copy with padding) Array.Clear (res, 0, res.Length); return data; } else return new byte [0]; } public virtual byte[] TransformFinalBlock (byte[] inputBuffer, int inputOffset, int inputCount) { if (m_disposed) throw new ObjectDisposedException ("Object is disposed"); CheckInput (inputBuffer, inputOffset, inputCount); if (encrypt) return FinalEncrypt (inputBuffer, inputOffset, inputCount); else return FinalDecrypt (inputBuffer, inputOffset, inputCount); } } }
ngs-doo/revenj
csharp/Core/Revenj.Core/Security/Mono.Security/Mono.Security.Cryptography/SymmetricTransform.cs
C#
bsd-3-clause
16,384
using System; using System.Collections.Generic; using System.Linq; using OrchardCore.ContentManagement.Routing; namespace OrchardCore.Autoroute.Services { public class AutorouteEntries : IAutorouteEntries { private readonly Dictionary<string, AutorouteEntry> _paths; private readonly Dictionary<string, AutorouteEntry> _contentItemIds; public AutorouteEntries() { _paths = new Dictionary<string, AutorouteEntry>(); _contentItemIds = new Dictionary<string, AutorouteEntry>(StringComparer.OrdinalIgnoreCase); } public bool TryGetEntryByPath(string path, out AutorouteEntry entry) { return _contentItemIds.TryGetValue(path, out entry); } public bool TryGetEntryByContentItemId(string contentItemId, out AutorouteEntry entry) { return _paths.TryGetValue(contentItemId, out entry); } public void AddEntries(IEnumerable<AutorouteEntry> entries) { lock (this) { // Evict all entries related to a container item from autoroute entries. // This is necessary to account for deletions, disabling of an item, or disabling routing of contained items. foreach (var entry in entries.Where(x => String.IsNullOrEmpty(x.ContainedContentItemId))) { var entriesToRemove = _paths.Values.Where(x => x.ContentItemId == entry.ContentItemId && !String.IsNullOrEmpty(x.ContainedContentItemId)); foreach (var entryToRemove in entriesToRemove) { _paths.Remove(entryToRemove.ContainedContentItemId); _contentItemIds.Remove(entryToRemove.Path); } } foreach (var entry in entries) { if (_paths.TryGetValue(entry.ContentItemId, out var previousContainerEntry) && String.IsNullOrEmpty(entry.ContainedContentItemId)) { _contentItemIds.Remove(previousContainerEntry.Path); } if (!String.IsNullOrEmpty(entry.ContainedContentItemId) && _paths.TryGetValue(entry.ContainedContentItemId, out var previousContainedEntry)) { _contentItemIds.Remove(previousContainedEntry.Path); } _contentItemIds[entry.Path] = entry; if (!String.IsNullOrEmpty(entry.ContainedContentItemId)) { _paths[entry.ContainedContentItemId] = entry; } else { _paths[entry.ContentItemId] = entry; } } } } public void RemoveEntries(IEnumerable<AutorouteEntry> entries) { lock (this) { foreach (var entry in entries) { // Evict all entries related to a container item from autoroute entries. var entriesToRemove = _paths.Values.Where(x => x.ContentItemId == entry.ContentItemId && !String.IsNullOrEmpty(x.ContainedContentItemId)); foreach (var entryToRemove in entriesToRemove) { _paths.Remove(entryToRemove.ContainedContentItemId); _contentItemIds.Remove(entryToRemove.Path); } _paths.Remove(entry.ContentItemId); _contentItemIds.Remove(entry.Path); } } } } }
petedavis/Orchard2
src/OrchardCore.Modules/OrchardCore.Autoroute/Services/AutorouteEntries.cs
C#
bsd-3-clause
3,716
/// <reference path="../../defs/tsd.d.ts"/> /// <reference path="./interfaces.d.ts"/> var path = require('path'); var fs = require('fs'); var _ = require('lodash'); var utils = require('./utils'); var cache = require('./cacheUtils'); var Promise = require('es6-promise').Promise; exports.grunt = require('grunt'); /////////////////////////// // Helper /////////////////////////// function executeNode(args) { return new Promise(function (resolve, reject) { exports.grunt.util.spawn({ cmd: process.execPath, args: args }, function (error, result, code) { var ret = { code: code, // New TypeScript compiler uses stdout for user code errors. Old one used stderr. output: result.stdout || result.stderr }; resolve(ret); }); }); } ///////////////////////////////////////////////////////////////// // Fast Compilation ///////////////////////////////////////////////////////////////// // Map to store if the cache was cleared after the gruntfile was parsed var cacheClearedOnce = {}; function getChangedFiles(files, targetName) { files = cache.getNewFilesForTarget(files, targetName); _.forEach(files, function (file) { exports.grunt.log.writeln(('### Fast Compile >>' + file).cyan); }); return files; } function resetChangedFiles(files, targetName) { cache.compileSuccessfull(files, targetName); } function clearCache(targetName) { cache.clearCache(targetName); cacheClearedOnce[targetName] = true; } ///////////////////////////////////////////////////////////////////// // tsc handling //////////////////////////////////////////////////////////////////// function resolveTypeScriptBinPath() { var ownRoot = path.resolve(path.dirname((module).filename), '../..'); var userRoot = path.resolve(ownRoot, '..', '..'); var binSub = path.join('node_modules', 'typescript', 'bin'); if (fs.existsSync(path.join(userRoot, binSub))) { // Using project override return path.join(userRoot, binSub); } return path.join(ownRoot, binSub); } function getTsc(binPath) { var pkg = JSON.parse(fs.readFileSync(path.resolve(binPath, '..', 'package.json')).toString()); exports.grunt.log.writeln('Using tsc v' + pkg.version); return path.join(binPath, 'tsc'); } function compileAllFiles(targetFiles, target, task, targetName) { // Make a local copy so we can modify files without having external side effects var files = _.map(targetFiles, function (file) { return file; }); var newFiles = files; if (task.fast === 'watch') { // if this is the first time its running after this file was loaded if (cacheClearedOnce[exports.grunt.task.current.target] === undefined) { // Then clear the cache for this target clearCache(targetName); } } if (task.fast !== 'never') { if (target.out) { exports.grunt.log.writeln('Fast compile will not work when --out is specified. Ignoring fast compilation'.cyan); } else { newFiles = getChangedFiles(files, targetName); if (newFiles.length !== 0) { files = newFiles; // If outDir is specified but no baseDir is specified we need to determine one if (target.outDir && !target.baseDir) { target.baseDir = utils.findCommonPath(files, '/'); } } else { exports.grunt.log.writeln('No file changes were detected. Skipping Compile'.green); return new Promise(function (resolve) { var ret = { code: 0, fileCount: 0, output: 'No files compiled as no change detected' }; resolve(ret); }); } } } // Transform files as needed. Currently all of this logic in is one module // transformers.transformFiles(newFiles, targetFiles, target, task); // If baseDir is specified create a temp tsc file to make sure that `--outDir` works fine // see https://github.com/grunt-ts/grunt-ts/issues/77 var baseDirFile = '.baseDir.ts'; var baseDirFilePath; if (target.outDir && target.baseDir && files.length > 0) { baseDirFilePath = path.join(target.baseDir, baseDirFile); if (!fs.existsSync(baseDirFilePath)) { exports.grunt.file.write(baseDirFilePath, '// Ignore this file. See https://github.com/grunt-ts/grunt-ts/issues/77'); } files.push(baseDirFilePath); } // If reference and out are both specified. // Then only compile the updated reference file as that contains the correct order if (target.reference && target.out) { var referenceFile = path.resolve(target.reference); files = [referenceFile]; } // Quote the files to compile. Needed for command line parsing by tsc files = _.map(files, function (item) { return '"' + path.resolve(item) + '"'; }); var args = files.slice(0); // boolean options if (task.sourceMap) { args.push('--sourcemap'); } if (task.declaration) { args.push('--declaration'); } if (task.removeComments) { args.push('--removeComments'); } if (task.noImplicitAny) { args.push('--noImplicitAny'); } if (task.noResolve) { args.push('--noResolve'); } if (task.noEmitOnError) { args.push('--noEmitOnError'); } if (task.preserveConstEnums) { args.push('--preserveConstEnums'); } if (task.suppressImplicitAnyIndexErrors) { args.push('--suppressImplicitAnyIndexErrors'); } // string options args.push('--target', task.target.toUpperCase()); // check the module compile option if (task.module) { var moduleOptionString = task.module.toLowerCase(); if (moduleOptionString === 'amd' || moduleOptionString === 'commonjs') { args.push('--module', moduleOptionString); } else { console.warn('WARNING: Option "module" does only support "amd" | "commonjs"'.magenta); } } // Target options: if (target.out) { args.push('--out', target.out); } if (target.outDir) { if (target.out) { console.warn('WARNING: Option "out" and "outDir" should not be used together'.magenta); } args.push('--outDir', target.outDir); } if (target.dest && (!target.out) && (!target.outDir)) { if (utils.isJavaScriptFile(target.dest)) { args.push('--out', target.dest); } else { if (target.dest === 'src') { console.warn(('WARNING: Destination for target "' + targetName + '" is "src", which is the default. If you have' + ' forgotten to specify a "dest" parameter, please add it. If this is correct, you may wish' + ' to change the "dest" parameter to "src/" or just ignore this warning.').magenta); } if (Array.isArray(target.dest)) { if (target.dest.length === 0) { } else if (target.dest.length > 0) { console.warn((('WARNING: "dest" for target "' + targetName + '" is an array. This is not supported by the' + ' TypeScript compiler or grunt-ts.' + ((target.dest.length > 1) ? ' Only the first "dest" will be used. The' + ' remaining items will be truncated.' : ''))).magenta); args.push('--outDir', target.dest[0]); } } else { args.push('--outDir', target.dest); } } } if (task.sourceRoot) { args.push('--sourceRoot', task.sourceRoot); } if (task.mapRoot) { args.push('--mapRoot', task.mapRoot); } // Locate a compiler var tsc; if (task.compiler) { exports.grunt.log.writeln('Using the custom compiler : ' + task.compiler); tsc = task.compiler; } else { tsc = getTsc(resolveTypeScriptBinPath()); } // To debug the tsc command if (task.verbose) { console.log(args.join(' ').yellow); } else { exports.grunt.log.verbose.writeln(args.join(' ').yellow); } // Create a temp last command file and use that to guide tsc. // Reason: passing all the files on the command line causes TSC to go in an infinite loop. var tempfilename = utils.getTempFile('tscommand'); if (!tempfilename) { throw (new Error('cannot create temp file')); } fs.writeFileSync(tempfilename, args.join(' ')); // Execute command return executeNode([tsc, '@' + tempfilename]).then(function (result) { if (task.fast !== 'never' && result.code === 0) { resetChangedFiles(newFiles, targetName); } result.fileCount = files.length; fs.unlinkSync(tempfilename); exports.grunt.log.writeln(result.output); return Promise.cast(result); }, function (err) { fs.unlinkSync(tempfilename); throw err; }); } exports.compileAllFiles = compileAllFiles; //# sourceMappingURL=compile.js.map
Softpagehomeware/grunt-ts
tasks/modules/compile.js
JavaScript
mit
9,276
using System; using System.ComponentModel.DataAnnotations; namespace Models.NorthwindIB.NH { [AttributeUsage(AttributeTargets.Class)] // NEW public class CustomerValidator : ValidationAttribute { public override Boolean IsValid(Object value) { var cust = value as Customer; if (cust != null && cust.CompanyName != null && cust.CompanyName.ToLower() == "error") { ErrorMessage = "This customer is not valid!"; return false; } return true; } } [AttributeUsage(AttributeTargets.Property)] public class CustomValidator : ValidationAttribute { public override Boolean IsValid(Object value) { try { var val = (string)value; if (!string.IsNullOrEmpty(val) && val.StartsWith("Error")) { ErrorMessage = "{0} equal the word 'Error'"; return false; } return true; } catch (Exception e) { var x = e; return false; } } } [MetadataType(typeof(CustomerMetaData))] [CustomerValidator] public partial class Customer { } public class CustomerMetaData { [CustomValidator] public string ContactName { get; set; } } }
gilesbradshaw/breeze.server.net
Tests/Model_NorthwindIB_NH/Customer.extended.cs
C#
mit
1,202
require 'spec_helper' feature 'Users' do around do |ex| old_url_options = Rails.application.routes.default_url_options Rails.application.routes.default_url_options = { host: 'example.foo' } ex.run Rails.application.routes.default_url_options = old_url_options end scenario 'GET /users/sign_in creates a new user account' do visit new_user_session_path fill_in 'user_name', with: 'Name Surname' fill_in 'user_username', with: 'Great' fill_in 'user_email', with: 'name@mail.com' fill_in 'user_password_sign_up', with: 'password1234' expect { click_button 'Sign up' }.to change { User.count }.by(1) end scenario 'Successful user signin invalidates password reset token' do user = create(:user) expect(user.reset_password_token).to be_nil visit new_user_password_path fill_in 'user_email', with: user.email click_button 'Reset password' user.reload expect(user.reset_password_token).not_to be_nil login_with(user) expect(current_path).to eq root_path user.reload expect(user.reset_password_token).to be_nil end end
yuyue2013/ss
spec/features/users_spec.rb
Ruby
mit
1,114
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdminService.Controller { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.ServiceFabric.Data; using Microsoft.ServiceFabric.Data.Collections; using Microsoft.AspNetCore.Hosting; using Admin; [Route("api/[controller]")] public class KeysController : Controller { private readonly IReliableStateManager stateManager; public KeysController(IReliableStateManager stateManager) { this.stateManager = stateManager; } [HttpGet] [Route("key1")] public async Task<IActionResult> GetKey1Async() { string key = await GetKey(Constants.KEY1); return Ok(key); } [HttpGet] [Route("key2")] public async Task<IActionResult> GetKey2Async() { string key = await GetKey(Constants.KEY2); return Ok(key); } [HttpPost] [Route("key1")] public async Task<IActionResult> RegenerateKey1Async() { string key = await GetKey(Constants.KEY1); return Ok(key); } [HttpPost] [Route("key2")] public async Task<IActionResult> RegenereateKey2Async() { string key = await GetKey(Constants.KEY2); return Ok(key); } private async Task<string> GetKey(string keyName) { var topics = await GetTopicDictionary(); using (var tx = this.stateManager.CreateTransaction()) { var key = await topics.TryGetValueAsync(tx, keyName); if (key.HasValue) { return key.Value; } throw new Exception("No Key initialized."); } } private async Task RegenerateKey(string keyName) { var topics = await GetTopicDictionary(); using (var tx = this.stateManager.CreateTransaction()) { string newKey = GenerateNewKey(); await topics.SetAsync(tx, keyName, newKey); await tx.CommitAsync(); } } private string GenerateNewKey() { // TODO generator a valid security key. using basic placeholder for now // should also encrypt as the key is stored in plain text when stored in // statefule service return Guid.NewGuid().ToString(); } private async Task<IReliableDictionary<string, string>> GetTopicDictionary() { return await this.stateManager.GetOrAddAsync<IReliableDictionary<string, string>>(Constants.COLLECTION_KEYS); } } }
mcollier/ServiceFabricPubSub
src/ServiceFabricPubSub/Admin/Controllers/KeysController.cs
C#
mit
2,935
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * 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 license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Feed_Writer * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\Feed\Writer\Extension\Atom\Renderer; use Zend\Feed\Writer\Extension; /** * @uses \Zend\Feed\Writer\Extension\AbstractRenderer * @category Zend * @package Zend_Feed_Writer * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Feed extends Extension\AbstractRenderer { /** * Set to TRUE if a rendering method actually renders something. This * is used to prevent premature appending of a XML namespace declaration * until an element which requires it is actually appended. * * @var bool */ protected $_called = false; /** * Render feed * * @return void */ public function render() { /** * RSS 2.0 only. Used mainly to include Atom links and * Pubsubhubbub Hub endpoint URIs under the Atom namespace */ if (strtolower($this->getType()) == 'atom') { return; } $this->_setFeedLinks($this->_dom, $this->_base); $this->_setHubs($this->_dom, $this->_base); if ($this->_called) { $this->_appendNamespaces(); } } /** * Append namespaces to root element of feed * * @return void */ protected function _appendNamespaces() { $this->getRootElement()->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); } /** * Set feed link elements * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setFeedLinks(\DOMDocument $dom, \DOMElement $root) { $flinks = $this->getDataContainer()->getFeedLinks(); if(!$flinks || empty($flinks)) { return; } foreach ($flinks as $type => $href) { $mime = 'application/' . strtolower($type) . '+xml'; $flink = $dom->createElement('atom:link'); $root->appendChild($flink); $flink->setAttribute('rel', 'self'); $flink->setAttribute('type', $mime); $flink->setAttribute('href', $href); } $this->_called = true; } /** * Set PuSH hubs * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setHubs(\DOMDocument $dom, \DOMElement $root) { $hubs = $this->getDataContainer()->getHubs(); if (!$hubs || empty($hubs)) { return; } foreach ($hubs as $hubUrl) { $hub = $dom->createElement('atom:link'); $hub->setAttribute('rel', 'hub'); $hub->setAttribute('href', $hubUrl); $root->appendChild($hub); } $this->_called = true; } }
buzzengine/buzzengine
vendor/zend-framework/library/Zend/Feed/Writer/Extension/Atom/Renderer/Feed.php
PHP
mit
3,543
/******************************************************************************* * Copyright (c) 2015 * * 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. *******************************************************************************/ package jsettlers.algorithms.heap; import java.util.ArrayList; /** * This is a unsynchronized min heap implementation. * <p> * It can heap everything that implements {@link MinHeapable}, but every object that is added to this heap may not be added to an other heap. * * @author andreas * @param <T> */ public class MinHeap<T extends MinHeapable> { private final int MIN_CAPACITY; private final ArrayList<T> heap = new ArrayList<>(); private int size = 0; /** * Creates a new min heap. * * @param capacity * The minimal and initial capacity the heap should have. May not be null. */ public MinHeap(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("too smal initial capacity"); } MIN_CAPACITY = capacity; heap.ensureCapacity(MIN_CAPACITY); } /** * Adds a new element to the heap. * * @param e * The element to add. */ public void insert(T e) { if (heap.size() > size) { heap.set(size, e); } else { heap.add(e); } siftUp(e, size); size++; } /** * sifts up an element to reestablish the heap array consistency. * * @param e * The element to sift. */ public void siftUp(T e) { siftUp(e, e.getHeapIdx()); } /** * Sifts up an element recursively until the heap consistency is reestablished. * * @param e * The element. * @param eID * The index of the element in the heap. * @return returns if the element was sifted up at least one time */ private boolean siftUp(T e, int eID) { e.setHeapIdx(eID); int parentID = getParent(eID); T parentElement = heap.get(parentID); if (parentElement.getRank() > e.getRank()) { heap.set(parentID, e); heap.set(eID, parentElement); parentElement.setHeapIdx(eID); siftUp(e, parentID); return true; } return false; } /** * Checks whether the heap is empty. * * @return true if and only if the heap is empty. */ public final boolean isEmpty() { return size == 0; } /** * Deletes the element of the heap that has the minimal value. * <p> * If the heap is empty, no action is preformed. * * @return The deleted element, or null. */ public T deleteMin() { if (size <= 0) { return null; } size--; T result = heap.get(0); T last = heap.get(size); heap.set(0, last); siftDown(last, 0); return result; } private void siftDown(T e, int pos) { e.setHeapIdx(pos); int leftChildID = getLeftChildID(pos); if (leftChildID < size) { T leftChild = heap.get(leftChildID); int rightChildID = getRightChildID(pos); T smaller; int smallerID; if (rightChildID < size) { T rightChild = heap.get(rightChildID); if (leftChild.getRank() < rightChild.getRank()) { smaller = leftChild; smallerID = getLeftChildID(pos); } else { smaller = rightChild; smallerID = getRightChildID(pos); } } else { smaller = leftChild; smallerID = getLeftChildID(pos); } if (smaller.getRank() < e.getRank()) { heap.set(pos, smaller); smaller.setHeapIdx(pos); heap.set(smallerID, e); siftDown(e, smallerID); } } } /** * Gets the position of the second child in the array. * * @param pos * The position of the parent. * @return The position of the child. */ private final int getRightChildID(int pos) { return 2 * pos + 2; } /** * Gets the position of the first child in the array. * * @param pos * The position of the parent. * @return The position of the child. */ private final int getLeftChildID(int pos) { return 2 * pos + 1; } /** * Gets the position of the parent in the array. * * @param pos * The position of the child. * @return The position of the parent. */ private final int getParent(int pos) { return (pos - 1) / 2; } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("\t"); for (int i = 0; i < size; i++) { buffer.append(heap.get(i).getRank() + "\t"); } return buffer.toString(); } /** * Clears the heap, that means that all elements are removed. */ public final void clear() { size = 0; } /** * Gets the number of elements that are in the heap. * * @return The size of the heap. */ public final int size() { return size; } /** * Removes a given element from the heap. * * @param e * The element to remove * @throws java.lang.AssertionError */ public void remove(T e) throws java.lang.AssertionError { // int idx = getIndex(e, 0); int idx = e.getHeapIdx(); // if (idx == -1) // return; assert idx != -1 : "remove wrong element"; size--; T last = heap.get(size); heap.set(idx, last); if (!siftUp(last, idx)) { siftDown(last, idx); } } /** * Checks the heap for consistency. * * @return True if all children "know" their position. */ public boolean doFullHeapCheck() { for (int i = 0; i < size; i++) { if (heap.get(i).getHeapIdx() != i) { return false; } } return checkHeap(0); } /** * Checks the heap from a given position downwards. * * @param pos * The position to start checking. * @return true if and only if the heap is ordered the right way. */ private boolean checkHeap(int pos) { T curr = heap.get(pos); int left = getLeftChildID(pos); int right = getRightChildID(pos); if (left < size) { if (heap.get(left).getRank() < curr.getRank()) { return false; } else { return checkHeap(left); } } if (right < size) { if (heap.get(right).getRank() < curr.getRank()) { return false; } else { return checkHeap(right); } } return true; } }
Peter-Maximilian/settlers-remake
jsettlers.logic/src/main/java/jsettlers/algorithms/heap/MinHeap.java
Java
mit
6,973
/* Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.help.console"]){ dojo._hasResource["dojox.help.console"]=true; dojo.provide("dojox.help.console"); dojo.require("dojox.help._base"); dojo.mixin(dojox.help,{_plainText:function(_1){ return _1.replace(/(<[^>]*>|&[^;]{2,6};)/g,""); },_displayLocated:function(_2){ var _3={}; dojo.forEach(_2,function(_4){ _3[_4[0]]=dojo.isMoz?{toString:function(){ return "Click to view"; },item:_4[1]}:_4[1]; }); },_displayHelp:function(_5,_6){ if(_5){ var _7="Help for: "+_6.name; var _8=""; for(var i=0;i<_7.length;i++){ _8+="="; } }else{ if(!_6){ }else{ var _9=false; for(var _a in _6){ var _b=_6[_a]; if(_a=="returns"&&_6.type!="Function"&&_6.type!="Constructor"){ continue; } if(_b&&(!dojo.isArray(_b)||_b.length)){ _9=true; _b=dojo.isString(_b)?dojox.help._plainText(_b):_b; if(_a=="returns"){ var _c=dojo.map(_b.types||[],"return item.title;").join("|"); if(_b.summary){ if(_c){ _c+=": "; } _c+=dojox.help._plainText(_b.summary); } }else{ if(_a=="parameters"){ for(var j=0,_d;_d=_b[j];j++){ var _e=dojo.map(_d.types,"return item.title").join("|"); var _f=""; if(_d.optional){ _f+="Optional. "; } if(_d.repating){ _f+="Repeating. "; } _f+=dojox.help._plainText(_d.summary); if(_f){ _f=" - "+_f; for(var k=0;k<_d.name.length;k++){ _f=" "+_f; } } } }else{ } } } } if(!_9){ } } } }}); dojox.help.init(); }
bjorns/logger
src/main/webapp/js/dojox/help/console.js
JavaScript
mit
1,517
import * as React from 'react'; import Checkbox from '@material-ui/core/Checkbox'; import FormGroup from '@material-ui/core/FormGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import FormLabel from '@material-ui/core/FormLabel'; export default function FormControlLabelPosition() { return ( <FormControl component="fieldset"> <FormLabel component="legend">Label placement</FormLabel> <FormGroup aria-label="position" row> <FormControlLabel value="top" control={<Checkbox />} label="Top" labelPlacement="top" /> <FormControlLabel value="start" control={<Checkbox />} label="Start" labelPlacement="start" /> <FormControlLabel value="bottom" control={<Checkbox />} label="Bottom" labelPlacement="bottom" /> <FormControlLabel value="end" control={<Checkbox />} label="End" labelPlacement="end" /> </FormGroup> </FormControl> ); }
callemall/material-ui
docs/src/pages/components/checkboxes/FormControlLabelPosition.tsx
TypeScript
mit
1,165
package backup // Copyright (c) Microsoft and contributors. All rights reserved. // // 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "net/http" ) // ProtectionIntentClient is the open API 2.0 Specs for Azure RecoveryServices Backup service type ProtectionIntentClient struct { BaseClient } // NewProtectionIntentClient creates an instance of the ProtectionIntentClient client. func NewProtectionIntentClient(subscriptionID string) ProtectionIntentClient { return NewProtectionIntentClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewProtectionIntentClientWithBaseURI creates an instance of the ProtectionIntentClient client. func NewProtectionIntentClientWithBaseURI(baseURI string, subscriptionID string) ProtectionIntentClient { return ProtectionIntentClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate create Intent for Enabling backup of an item. This is a synchronous operation. // Parameters: // vaultName - the name of the recovery services vault. // resourceGroupName - the name of the resource group where the recovery services vault is present. // fabricName - fabric name associated with the backup item. // intentObjectName - intent object name. // parameters - resource backed up item func (client ProtectionIntentClient) CreateOrUpdate(ctx context.Context, vaultName string, resourceGroupName string, fabricName string, intentObjectName string, parameters ProtectionIntentResource) (result ProtectionIntentResource, err error) { req, err := client.CreateOrUpdatePreparer(ctx, vaultName, resourceGroupName, fabricName, intentObjectName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "CreateOrUpdate", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "CreateOrUpdate", resp, "Failure sending request") return } result, err = client.CreateOrUpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client ProtectionIntentClient) CreateOrUpdatePreparer(ctx context.Context, vaultName string, resourceGroupName string, fabricName string, intentObjectName string, parameters ProtectionIntentResource) (*http.Request, error) { pathParameters := map[string]interface{}{ "fabricName": autorest.Encode("path", fabricName), "intentObjectName": autorest.Encode("path", intentObjectName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vaultName": autorest.Encode("path", vaultName), } const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/backupProtectionIntent/{intentObjectName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ProtectionIntentClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client ProtectionIntentClient) CreateOrUpdateResponder(resp *http.Response) (result ProtectionIntentResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Validate sends the validate request. // Parameters: // azureRegion - azure region to hit Api // parameters - enable backup validation request on Virtual Machine func (client ProtectionIntentClient) Validate(ctx context.Context, azureRegion string, parameters PreValidateEnableBackupRequest) (result PreValidateEnableBackupResponse, err error) { req, err := client.ValidatePreparer(ctx, azureRegion, parameters) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "Validate", nil, "Failure preparing request") return } resp, err := client.ValidateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "Validate", resp, "Failure sending request") return } result, err = client.ValidateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "Validate", resp, "Failure responding to request") } return } // ValidatePreparer prepares the Validate request. func (client ProtectionIntentClient) ValidatePreparer(ctx context.Context, azureRegion string, parameters PreValidateEnableBackupRequest) (*http.Request, error) { pathParameters := map[string]interface{}{ "azureRegion": autorest.Encode("path", azureRegion), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/Subscriptions/{subscriptionId}/providers/Microsoft.RecoveryServices/locations/{azureRegion}/backupPreValidateProtection", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ValidateSender sends the Validate request. The method will close the // http.Response Body if it receives an error. func (client ProtectionIntentClient) ValidateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ValidateResponder handles the response to the Validate request. The method always // closes the http.Response Body. func (client ProtectionIntentClient) ValidateResponder(resp *http.Response) (result PreValidateEnableBackupResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
seuffert/rclone
vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2017-07-01/backup/protectionintent.go
GO
mit
7,908
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 0.1.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ $belongsTo = $this->Bake->aliasExtractor($modelObj, 'BelongsTo'); $belongsToMany = $this->Bake->aliasExtractor($modelObj, 'BelongsToMany'); $compact = ["'" . $singularName . "'"]; ?> /** * Edit method * * @param string|null $id <?= $singularHumanName ?> id. * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $<?= $singularName ?> = $this-><?= $currentModelName ?>->get($id, [ 'contain' => [<?= $this->Bake->stringifyList($belongsToMany, ['indent' => false]) ?>] ]); if ($this->request->is(['patch', 'post', 'put'])) { $<?= $singularName ?> = $this-><?= $currentModelName ?>->patchEntity($<?= $singularName ?>, $this->request->getData()); if ($this-><?= $currentModelName; ?>->save($<?= $singularName ?>)) { $this->Flash->success(__('The <?= strtolower($singularHumanName) ?> has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The <?= strtolower($singularHumanName) ?> could not be saved. Please, try again.')); } <?php foreach (array_merge($belongsTo, $belongsToMany) as $assoc): $association = $modelObj->association($assoc); $otherName = $association->getTarget()->getAlias(); $otherPlural = $this->_variableName($otherName); ?> $<?= $otherPlural ?> = $this-><?= $currentModelName ?>-><?= $otherName ?>->find('list', ['limit' => 200]); <?php $compact[] = "'$otherPlural'"; endforeach; ?> $this->set(compact(<?= join(', ', $compact) ?>)); $this->set('_serialize', ['<?=$singularName?>']); }
FlopySwitzerland/nessi
tmp/bake/Bake-Element-Controller-edit-ctp.php
PHP
mit
2,438
version https://git-lfs.github.com/spec/v1 oid sha256:b386bb4d8bf9eb9e8099152a3eb963073051fb960b30cd512b6a07bd1f751d3d size 734
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.2.0/datatype/lang/datatype_it-IT.js
JavaScript
mit
128
class MergeRequestObserver < BaseObserver def after_create(merge_request) notification.new_merge_request(merge_request, current_user) end def after_close(merge_request, transition) Note.create_status_change_note(merge_request, current_user, merge_request.state) notification.close_mr(merge_request, current_user) end def after_merge(merge_request, transition) notification.merge_mr(merge_request) end def after_reopen(merge_request, transition) Note.create_status_change_note(merge_request, current_user, merge_request.state) end def after_update(merge_request) notification.reassigned_merge_request(merge_request, current_user) if merge_request.is_being_reassigned? end end
Aruiwen/gitlabhq
app/observers/merge_request_observer.rb
Ruby
mit
724
using System; using System.Text; using System.Web; using System.Web.Http.Description; namespace TheBigCatProject.Server.Areas.HelpPage { public static class ApiDescriptionExtensions { /// <summary> /// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" /// </summary> /// <param name="description">The <see cref="ApiDescription"/>.</param> /// <returns>The ID as a string.</returns> public static string GetFriendlyId(this ApiDescription description) { string path = description.RelativePath; string[] urlParts = path.Split('?'); string localPath = urlParts[0]; string queryKeyString = null; if (urlParts.Length > 1) { string query = urlParts[1]; string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; queryKeyString = String.Join("_", queryKeys); } StringBuilder friendlyPath = new StringBuilder(); friendlyPath.AppendFormat("{0}-{1}", description.HttpMethod.Method, localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); if (queryKeyString != null) { friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); } return friendlyPath.ToString(); } } }
EmilMitev/Telerik-Academy
Single Page Applications/07. AngularJS Workshop/TheBigCatProject/TheBigCatProject.Server/Areas/HelpPage/ApiDescriptionExtensions.cs
C#
mit
1,513
package com.xeiam.xchange.taurus.dto; import si.mazi.rescu.HttpStatusExceptionSupport; import com.fasterxml.jackson.annotation.JsonProperty; public class TaurusException extends HttpStatusExceptionSupport { public TaurusException(@JsonProperty("error") Object error) { super(error.toString()); } }
cinjoff/XChange-1
xchange-taurus/src/main/java/com/xeiam/xchange/taurus/dto/TaurusException.java
Java
mit
309
using System; using System.Threading; using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Orleans.Configuration; namespace Orleans.Transactions { internal class ActiveTransactionsTracker : IDisposable { private readonly TransactionsOptions options; private readonly TransactionLog transactionLog; private readonly ILogger logger; private readonly object lockObj; private readonly Thread allocationThread; private readonly AutoResetEvent allocationEvent; private long smallestActiveTransactionId; private long highestActiveTransactionId; private long maxAllocatedTransactionId; private volatile bool disposed; public ActiveTransactionsTracker(IOptions<TransactionsOptions> configOption, TransactionLog transactionLog, ILoggerFactory loggerFactory) { this.options = configOption.Value; this.transactionLog = transactionLog; this.logger = loggerFactory.CreateLogger(nameof(ActiveTransactionsTracker)); lockObj = new object(); allocationEvent = new AutoResetEvent(true); allocationThread = new Thread(AllocateTransactionId) { IsBackground = true, Name = nameof(ActiveTransactionsTracker) }; } public void Start(long initialTransactionId) { smallestActiveTransactionId = initialTransactionId + 1; highestActiveTransactionId = initialTransactionId; maxAllocatedTransactionId = initialTransactionId; allocationThread.Start(); } public long GetNewTransactionId() { var id = Interlocked.Increment(ref highestActiveTransactionId); if (maxAllocatedTransactionId - highestActiveTransactionId <= options.AvailableTransactionIdThreshold) { // Signal the allocation thread to allocate more Ids allocationEvent.Set(); } while (id > maxAllocatedTransactionId) { // Wait until the allocation thread catches up before returning. // This should never happen if we are pre-allocating fast enough. allocationEvent.Set(); lock (lockObj) { } } return id; } public long GetSmallestActiveTransactionId() { // NOTE: this result is not strictly correct if there are NO active transactions // but for all purposes in which this is used it is still valid. // TODO: consider renaming this or handling the no active transactions case. return Interlocked.Read(ref smallestActiveTransactionId); } public long GetHighestActiveTransactionId() { // NOTE: this result is not strictly correct if there are NO active transactions // but for all purposes in which this is used it is still valid. // TODO: consider renaming this or handling the no active transactions case. lock (lockObj) { return Math.Min(highestActiveTransactionId, maxAllocatedTransactionId); } } public void PopSmallestActiveTransactionId() { Interlocked.Increment(ref smallestActiveTransactionId); } private void AllocateTransactionId(object args) { while (!this.disposed) { try { allocationEvent.WaitOne(); if (this.disposed) return; lock (lockObj) { if (maxAllocatedTransactionId - highestActiveTransactionId <= options.AvailableTransactionIdThreshold) { var batchSize = options.TransactionIdAllocationBatchSize; transactionLog.UpdateStartRecord(maxAllocatedTransactionId + batchSize).GetAwaiter().GetResult(); maxAllocatedTransactionId += batchSize; } } } catch (ThreadAbortException) { throw; } catch (Exception exception) { this.logger.Warn( OrleansTransactionsErrorCode.Transactions_IdAllocationFailed, "Ignoring exception in " + nameof(this.AllocateTransactionId), exception); } } } public void Dispose() { if (!this.disposed) { this.disposed = true; this.allocationEvent.Set(); this.allocationEvent.Dispose(); } } } }
ashkan-saeedi-mazdeh/orleans
src/Orleans.Transactions/InClusterTM/ActiveTransactionsTracker.cs
C#
mit
4,965
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "pal_config.h" #include "pal_uid.h" #include "pal_utilities.h" #include <assert.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pwd.h> extern "C" int32_t SystemNative_GetPwUidR(uint32_t uid, Passwd* pwd, char* buf, int32_t buflen) { assert(pwd != nullptr); assert(buf != nullptr); assert(buflen >= 0); if (buflen < 0) return EINVAL; struct passwd nativePwd; struct passwd* result; int error; while ((error = getpwuid_r(uid, &nativePwd, buf, UnsignedCast(buflen), &result)) == EINTR); // positive error number returned -> failure other than entry-not-found if (error != 0) { assert(error > 0); *pwd = {}; // managed out param must be initialized return error; } // 0 returned with null result -> entry-not-found if (result == nullptr) { *pwd = {}; // managed out param must be initialized return -1; // shim convention for entry-not-found } // 0 returned with non-null result (guaranteed to be set to pwd arg) -> success assert(result == &nativePwd); pwd->Name = nativePwd.pw_name; pwd->Password = nativePwd.pw_passwd; pwd->UserId = nativePwd.pw_uid; pwd->GroupId = nativePwd.pw_gid; pwd->UserInfo = nativePwd.pw_gecos; pwd->HomeDirectory = nativePwd.pw_dir; pwd->Shell = nativePwd.pw_shell; return 0; } extern "C" uint32_t SystemNative_GetEUid() { return geteuid(); } extern "C" uint32_t SystemNative_GetEGid() { return getegid(); }
shmao/corefx
src/Native/Unix/System.Native/pal_uid.cpp
C++
mit
1,762
using System.Reflection; [assembly: AssemblyTitle("Cedar.EventStore.Tests")] [assembly: AssemblyDescription("")]
dcomartin/Cedar.EventStore
src/Cedar.EventStore.Tests/Properties/AssemblyInfo.cs
C#
mit
113
<?php namespace Lexik\Bundle\JWTAuthenticationBundle; /** * Events. * * @author Dev Lexik <dev@lexik.fr> */ final class Events { /** * Dispatched after the token generation to allow sending more data * on the authentication success response. */ const AUTHENTICATION_SUCCESS = 'lexik_jwt_authentication.on_authentication_success'; /** * Dispatched after an authentication failure. * Hook into this event to add a custom error message in the response body. */ const AUTHENTICATION_FAILURE = 'lexik_jwt_authentication.on_authentication_failure'; /** * Dispatched before the token payload is encoded by the configured encoder (JWTEncoder by default). * Hook into this event to add extra fields to the payload. */ const JWT_CREATED = 'lexik_jwt_authentication.on_jwt_created'; /** * Dispatched right after token string is created. * Hook into this event to get token representation itself. */ const JWT_ENCODED = 'lexik_jwt_authentication.on_jwt_encoded'; /** * Dispatched after the token payload has been decoded by the configured encoder (JWTEncoder by default). * Hook into this event to perform additional validation on the received payload. */ const JWT_DECODED = 'lexik_jwt_authentication.on_jwt_decoded'; /** * Dispatched after the token payload has been authenticated by the provider. * Hook into this event to perform additional modification to the authenticated token using the payload. */ const JWT_AUTHENTICATED = 'lexik_jwt_authentication.on_jwt_authenticated'; /** * Dispatched after the token has been invalidated by the provider. * Hook into this event to add a custom error message in the response body. */ const JWT_INVALID = 'lexik_jwt_authentication.on_jwt_invalid'; /** * Dispatched when no token can be found in a request. * Hook into this event to set a custom response. */ const JWT_NOT_FOUND = 'lexik_jwt_authentication.on_jwt_not_found'; /** * Dispatched when the token is expired. * The expired token's payload can be retrieved by hooking into this event, so you can set a different * response. */ const JWT_EXPIRED = 'lexik_jwt_authentication.on_jwt_expired'; }
DevKhater/symfony2-testing
vendor/lexik/jwt-authentication-bundle/Events.php
PHP
mit
2,311
<?php global $_MODULE; $_MODULE = array(); $_MODULE['<{gridhtml}prestashop>gridhtml_cf6b972204ee563b4e5691b293e931b6'] = 'Visualització simple taula HTML'; $_MODULE['<{gridhtml}prestashop>gridhtml_05ce5a49b49dd6245f71e384c4b43564'] = 'Permet que el sistema d\'estadístiques mostri les dades en una quadrícula.'; return $_MODULE;
insbadia-dawm8/gitteam
proyecto/modules/gridhtml/translations/ca.php
PHP
mit
336
var fs = require('fs') var path = require('path') var util = require('util') var semver = require('semver') exports.checkEngine = checkEngine function checkEngine (target, npmVer, nodeVer, force, strict, cb) { var nodev = force ? null : nodeVer var eng = target.engines var opt = { includePrerelease: true } if (!eng) return cb() if (nodev && eng.node && !semver.satisfies(nodev, eng.node, opt) || eng.npm && !semver.satisfies(npmVer, eng.npm, opt)) { var er = new Error(util.format('Unsupported engine for %s: wanted: %j (current: %j)', target._id, eng, {node: nodev, npm: npmVer})) er.code = 'ENOTSUP' er.required = eng er.pkgid = target._id if (strict) { return cb(er) } else { return cb(null, er) } } return cb() } exports.checkPlatform = checkPlatform function checkPlatform (target, force, cb) { var platform = process.platform var arch = process.arch var osOk = true var cpuOk = true if (force) { return cb() } if (target.os) { osOk = checkList(platform, target.os) } if (target.cpu) { cpuOk = checkList(arch, target.cpu) } if (!osOk || !cpuOk) { var er = new Error(util.format('Unsupported platform for %s: wanted %j (current: %j)', target._id, target, {os: platform, cpu: arch})) er.code = 'EBADPLATFORM' er.os = target.os || ['any'] er.cpu = target.cpu || ['any'] er.pkgid = target._id return cb(er) } return cb() } function checkList (value, list) { var tmp var match = false var blc = 0 if (typeof list === 'string') { list = [list] } if (list.length === 1 && list[0] === 'any') { return true } for (var i = 0; i < list.length; ++i) { tmp = list[i] if (tmp[0] === '!') { tmp = tmp.slice(1) if (tmp === value) { return false } ++blc } else { match = match || tmp === value } } return match || blc === list.length } exports.checkCycle = checkCycle function checkCycle (target, ancestors, cb) { // there are some very rare and pathological edge-cases where // a cycle can cause npm to try to install a never-ending tree // of stuff. // Simplest: // // A -> B -> A' -> B' -> A -> B -> A' -> B' -> A -> ... // // Solution: Simply flat-out refuse to install any name@version // that is already in the prototype tree of the ancestors object. // A more correct, but more complex, solution would be to symlink // the deeper thing into the new location. // Will do that if anyone whines about this irl. // // Note: `npm install foo` inside of the `foo` package will abort // earlier if `--force` is not set. However, if it IS set, then // we need to still fail here, but just skip the first level. Of // course, it'll still fail eventually if it's a true cycle, and // leave things in an undefined state, but that's what is to be // expected when `--force` is used. That is why getPrototypeOf // is used *twice* here: to skip the first level of repetition. var p = Object.getPrototypeOf(Object.getPrototypeOf(ancestors)) var name = target.name var version = target.version while (p && p !== Object.prototype && p[name] !== version) { p = Object.getPrototypeOf(p) } if (p[name] !== version) return cb() var er = new Error(target._id + ': Unresolvable cycle detected') var tree = [target._id, JSON.parse(JSON.stringify(ancestors))] var t = Object.getPrototypeOf(ancestors) while (t && t !== Object.prototype) { if (t === p) t.THIS_IS_P = true tree.push(JSON.parse(JSON.stringify(t))) t = Object.getPrototypeOf(t) } er.pkgid = target._id er.code = 'ECYCLE' return cb(er) } exports.checkGit = checkGit function checkGit (folder, cb) { // if it's a git repo then don't touch it! fs.lstat(folder, function (er, s) { if (er || !s.isDirectory()) return cb() else checkGit_(folder, cb) }) } function checkGit_ (folder, cb) { fs.stat(path.resolve(folder, '.git'), function (er, s) { if (!er && s.isDirectory()) { var e = new Error(folder + ': Appears to be a git repo or submodule.') e.path = folder e.code = 'EISGIT' return cb(e) } cb() }) }
giovannic/giovannic.github.com
node_modules/npm/node_modules/npm-install-checks/index.js
JavaScript
mit
4,201
package main import ( "fmt" "time" "github.com/google/jsonapi" ) // Blog is a model representing a blog site type Blog struct { ID int `jsonapi:"primary,blogs"` Title string `jsonapi:"attr,title"` Posts []*Post `jsonapi:"relation,posts"` CurrentPost *Post `jsonapi:"relation,current_post"` CurrentPostID int `jsonapi:"attr,current_post_id"` CreatedAt time.Time `jsonapi:"attr,created_at"` ViewCount int `jsonapi:"attr,view_count"` } // Post is a model representing a post on a blog type Post struct { ID int `jsonapi:"primary,posts"` BlogID int `jsonapi:"attr,blog_id"` Title string `jsonapi:"attr,title"` Body string `jsonapi:"attr,body"` Comments []*Comment `jsonapi:"relation,comments"` } // Comment is a model representing a user submitted comment type Comment struct { ID int `jsonapi:"primary,comments"` PostID int `jsonapi:"attr,post_id"` Body string `jsonapi:"attr,body"` } // JSONAPILinks implements the Linkable interface for a blog func (blog Blog) JSONAPILinks() *jsonapi.Links { return &jsonapi.Links{ "self": fmt.Sprintf("https://example.com/blogs/%d", blog.ID), } } // JSONAPIRelationshipLinks implements the RelationshipLinkable interface for a blog func (blog Blog) JSONAPIRelationshipLinks(relation string) *jsonapi.Links { if relation == "posts" { return &jsonapi.Links{ "related": fmt.Sprintf("https://example.com/blogs/%d/posts", blog.ID), } } if relation == "current_post" { return &jsonapi.Links{ "related": fmt.Sprintf("https://example.com/blogs/%d/current_post", blog.ID), } } return nil } // JSONAPIMeta implements the Metable interface for a blog func (blog Blog) JSONAPIMeta() *jsonapi.Meta { return &jsonapi.Meta{ "detail": "extra details regarding the blog", } } // JSONAPIRelationshipMeta implements the RelationshipMetable interface for a blog func (blog Blog) JSONAPIRelationshipMeta(relation string) *jsonapi.Meta { if relation == "posts" { return &jsonapi.Meta{ "detail": "posts meta information", } } if relation == "current_post" { return &jsonapi.Meta{ "detail": "current post meta information", } } return nil }
aren55555/jsonapi
examples/models.go
GO
mit
2,237
require File.expand_path('../../../enumerable/shared/enumeratorized', __FILE__) describe :keep_if, :shared => true do it "deletes elements for which the block returns a false value" do array = [1, 2, 3, 4, 5] array.send(@method) {|item| item > 3 }.should equal(array) array.should == [4, 5] end it "returns an enumerator if no block is given" do [1, 2, 3].send(@method).should be_an_instance_of(enumerator_class) end before :all do @object = [1,2,3] end it_should_behave_like :enumeratorized_with_origin_size describe "on frozen objects" do before :each do @origin = [true, false] @frozen = @origin.dup.freeze end it "returns an Enumerator if no block is given" do @frozen.send(@method).should be_an_instance_of(enumerator_class) end describe "with truthy block" do it "keeps elements after any exception" do lambda { @frozen.send(@method) { true } }.should raise_error(Exception) @frozen.should == @origin end it "raises a RuntimeError" do lambda { @frozen.send(@method) { true } }.should raise_error(RuntimeError) end end describe "with falsy block" do it "keeps elements after any exception" do lambda { @frozen.send(@method) { false } }.should raise_error(Exception) @frozen.should == @origin end it "raises a RuntimeError" do lambda { @frozen.send(@method) { false } }.should raise_error(RuntimeError) end end end end
benlovell/rubyspec
core/array/shared/keep_if.rb
Ruby
mit
1,516
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Orleans.Metadata; namespace Orleans.Runtime.Versions { /// <summary> /// Functionality for querying the declared version of grain interfaces. /// </summary> internal class GrainVersionManifest { private readonly object _lockObj = new object(); private readonly ConcurrentDictionary<GrainInterfaceType, GrainInterfaceType> _genericInterfaceMapping = new ConcurrentDictionary<GrainInterfaceType, GrainInterfaceType>(); private readonly ConcurrentDictionary<GrainType, GrainType> _genericGrainTypeMapping = new ConcurrentDictionary<GrainType, GrainType>(); private readonly IClusterManifestProvider _clusterManifestProvider; private readonly Dictionary<GrainInterfaceType, ushort> _localVersions; private Cache _cache; /// <summary> /// Initializes a new instance of the <see cref="GrainVersionManifest"/> class. /// </summary> /// <param name="clusterManifestProvider">The cluster manifest provider.</param> public GrainVersionManifest(IClusterManifestProvider clusterManifestProvider) { _clusterManifestProvider = clusterManifestProvider; _cache = BuildCache(clusterManifestProvider.Current); _localVersions = BuildLocalVersionMap(clusterManifestProvider.LocalGrainManifest); } /// <summary> /// Gets the current cluster manifest version. /// </summary> public MajorMinorVersion LatestVersion => _clusterManifestProvider.Current.Version; /// <summary> /// Gets the local version for a specified grain interface type. /// </summary> /// <param name="interfaceType">The grain intrerface type name.</param> /// <returns>The version of the specified grain interface.</returns> public ushort GetLocalVersion(GrainInterfaceType interfaceType) { if (_localVersions.TryGetValue(interfaceType, out var result)) { return result; } if (_genericInterfaceMapping.TryGetValue(interfaceType, out var genericInterfaceId)) { return GetLocalVersion(genericInterfaceId); } if (GenericGrainInterfaceType.TryParse(interfaceType, out var generic) && generic.IsConstructed) { var genericId = _genericInterfaceMapping[interfaceType] = generic.GetGenericGrainType().Value; return GetLocalVersion(genericId); } return 0; } /// <summary> /// Gets a collection of all known versions for a grain interface. /// </summary> /// <param name="interfaceType">The grain interface type name.</param> /// <returns>All known versions for the specified grain interface.</returns> public (MajorMinorVersion Version, ushort[] Result) GetAvailableVersions(GrainInterfaceType interfaceType) { var cache = GetCache(); if (cache.AvailableVersions.TryGetValue(interfaceType, out var result)) { return (cache.Version, result); } if (_genericInterfaceMapping.TryGetValue(interfaceType, out var genericInterfaceId)) { return GetAvailableVersions(genericInterfaceId); } if (GenericGrainInterfaceType.TryParse(interfaceType, out var generic) && generic.IsConstructed) { var genericId = _genericInterfaceMapping[interfaceType] = generic.GetGenericGrainType().Value; return GetAvailableVersions(genericId); } // No versions available. return (cache.Version, Array.Empty<ushort>()); } /// <summary> /// Gets the set of supported silos for a specified grain interface and version. /// </summary> /// <param name="interfaceType">The grain interface type name.</param> /// <param name="version">The grain interface version.</param> /// <returns>The set of silos which support the specified grain interface type and version.</returns> public (MajorMinorVersion Version, SiloAddress[] Result) GetSupportedSilos(GrainInterfaceType interfaceType, ushort version) { var cache = GetCache(); if (cache.SupportedSilosByInterface.TryGetValue((interfaceType, version), out var result)) { return (cache.Version, result); } if (_genericInterfaceMapping.TryGetValue(interfaceType, out var genericInterfaceId)) { return GetSupportedSilos(genericInterfaceId, version); } if (GenericGrainInterfaceType.TryParse(interfaceType, out var generic) && generic.IsConstructed) { var genericId = _genericInterfaceMapping[interfaceType] = generic.GetGenericGrainType().Value; return GetSupportedSilos(genericId, version); } // No supported silos for this version. return (cache.Version, Array.Empty<SiloAddress>()); } /// <summary> /// Gets the set of supported silos for the specified grain type. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>The silos which support the specified grain type.</returns> public (MajorMinorVersion Version, SiloAddress[] Result) GetSupportedSilos(GrainType grainType) { var cache = GetCache(); if (cache.SupportedSilosByGrainType.TryGetValue(grainType, out var result)) { return (cache.Version, result); } if (_genericGrainTypeMapping.TryGetValue(grainType, out var genericGrainType)) { return GetSupportedSilos(genericGrainType); } if (GenericGrainType.TryParse(grainType, out var generic) && generic.IsConstructed) { var genericId = _genericGrainTypeMapping[grainType] = generic.GetUnconstructedGrainType().GrainType; return GetSupportedSilos(genericId); } // No supported silos for this type. return (cache.Version, Array.Empty<SiloAddress>()); } /// <summary> /// Gets the set of supported silos for the specified combination of grain type, interface type, and version. /// </summary> /// <param name="grainType">The grain type.</param> /// <param name="interfaceType">The grain interface type name.</param> /// <param name="versions">The grain interface version.</param> /// <returns>The set of silos which support the specifed grain.</returns> public (MajorMinorVersion Version, Dictionary<ushort, SiloAddress[]> Result) GetSupportedSilos(GrainType grainType, GrainInterfaceType interfaceType, ushort[] versions) { var result = new Dictionary<ushort, SiloAddress[]>(); // Track the minimum version in case of inconsistent reads, since the caller can use that information to // ensure they refresh on the next call. MajorMinorVersion? minCacheVersion = null; foreach (var version in versions) { (var cacheVersion, var silosWithGrain) = this.GetSupportedSilos(grainType); if (!minCacheVersion.HasValue || cacheVersion > minCacheVersion.Value) { minCacheVersion = cacheVersion; } // We need to sort this so the list of silos returned will // be the same across all silos in the cluster SiloAddress[] silosWithCorrectVersion; (cacheVersion, silosWithCorrectVersion) = this.GetSupportedSilos(interfaceType, version); if (!minCacheVersion.HasValue || cacheVersion > minCacheVersion.Value) { minCacheVersion = cacheVersion; } result[version] = silosWithCorrectVersion .Intersect(silosWithGrain) .OrderBy(addr => addr) .ToArray(); } if (!minCacheVersion.HasValue) minCacheVersion = MajorMinorVersion.Zero; return (minCacheVersion.Value, result); } private Cache GetCache() { var cache = _cache; var manifest = _clusterManifestProvider.Current; if (manifest.Version == cache.Version) { return cache; } lock (_lockObj) { cache = _cache; manifest = _clusterManifestProvider.Current; if (manifest.Version == cache.Version) { return cache; } return _cache = BuildCache(manifest); } } private static Dictionary<GrainInterfaceType, ushort> BuildLocalVersionMap(GrainManifest manifest) { var result = new Dictionary<GrainInterfaceType, ushort>(); foreach (var grainInterface in manifest.Interfaces) { var id = grainInterface.Key; if (!grainInterface.Value.Properties.TryGetValue(WellKnownGrainInterfaceProperties.Version, out var versionString) || !ushort.TryParse(versionString, out var version)) { version = 0; } result[id] = version; } return result; } private static Cache BuildCache(ClusterManifest clusterManifest) { var available = new Dictionary<GrainInterfaceType, List<ushort>>(); var supportedInterfaces = new Dictionary<(GrainInterfaceType, ushort), List<SiloAddress>>(); var supportedGrains = new Dictionary<GrainType, List<SiloAddress>>(); foreach (var entry in clusterManifest.Silos) { var silo = entry.Key; var manifest = entry.Value; foreach (var grainInterface in manifest.Interfaces) { var id = grainInterface.Key; if (!grainInterface.Value.Properties.TryGetValue(WellKnownGrainInterfaceProperties.Version, out var versionString) || !ushort.TryParse(versionString, out var version)) { version = 0; } if (!available.TryGetValue(id, out var versions)) { available[id] = new List<ushort> { version }; } else if (!versions.Contains(version)) { versions.Add(version); } if (!supportedInterfaces.TryGetValue((id, version), out var supportedSilos)) { supportedInterfaces[(id, version)] = new List<SiloAddress> { silo }; } else if (!supportedSilos.Contains(silo)) { supportedSilos.Add(silo); } } foreach (var grainType in manifest.Grains) { var id = grainType.Key; if (!supportedGrains.TryGetValue(id, out var supportedSilos)) { supportedGrains[id] = new List<SiloAddress> { silo }; } else if (!supportedSilos.Contains(silo)) { supportedSilos.Add(silo); } } } var resultAvailable = new Dictionary<GrainInterfaceType, ushort[]>(); foreach (var entry in available) { entry.Value.Sort(); resultAvailable[entry.Key] = entry.Value.ToArray(); } var resultSupportedByInterface = new Dictionary<(GrainInterfaceType, ushort), SiloAddress[]>(); foreach (var entry in supportedInterfaces) { entry.Value.Sort(); resultSupportedByInterface[entry.Key] = entry.Value.ToArray(); } var resultSupportedSilosByGrainType = new Dictionary<GrainType, SiloAddress[]>(); foreach (var entry in supportedGrains) { entry.Value.Sort(); resultSupportedSilosByGrainType[entry.Key] = entry.Value.ToArray(); } return new Cache(clusterManifest.Version, resultAvailable, resultSupportedByInterface, resultSupportedSilosByGrainType); } private class Cache { public Cache( MajorMinorVersion version, Dictionary<GrainInterfaceType, ushort[]> availableVersions, Dictionary<(GrainInterfaceType, ushort), SiloAddress[]> supportedSilosByInterface, Dictionary<GrainType, SiloAddress[]> supportedSilosByGrainType) { this.Version = version; this.AvailableVersions = availableVersions; this.SupportedSilosByGrainType = supportedSilosByGrainType; this.SupportedSilosByInterface = supportedSilosByInterface; } public MajorMinorVersion Version { get; } public Dictionary<GrainInterfaceType, ushort[]> AvailableVersions { get; } public Dictionary<(GrainInterfaceType, ushort), SiloAddress[]> SupportedSilosByInterface { get; } = new Dictionary<(GrainInterfaceType, ushort), SiloAddress[]>(); public Dictionary<GrainType, SiloAddress[]> SupportedSilosByGrainType { get; } = new Dictionary<GrainType, SiloAddress[]>(); } } }
veikkoeeva/orleans
src/Orleans.Core/Manifest/GrainVersionManifest.cs
C#
mit
14,080
//===---- include/gcinfo/gcinfoutil.cpp -------------------------*- C++ -*-===// // // LLILC // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // See LICENSE file in the project root for full license information. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Implementation of utility classes used by GCInfoEncoder library /// //===----------------------------------------------------------------------===// #include "GcInfoUtil.h" //***************************************************************************** // GcInfoAllocator //***************************************************************************** int GcInfoAllocator::ZeroLengthAlloc = 0; //***************************************************************************** // Utility Functions //***************************************************************************** //------------------------------------------------------------------------ // BitPosition: Return the position of the single bit that is set in 'value'. // // Return Value: // The position (0 is LSB) of bit that is set in 'value' // // Notes: // 'value' must have exactly one bit set. // The algorithm is as follows: // - PRIME is a prime bigger than sizeof(unsigned int), which is not of the // form 2^n-1. // - Taking the modulo of 'value' with this will produce a unique hash for // all powers of 2 (which is what "value" is). // - Entries in hashTable[] which are -1 should never be used. There // should be PRIME-8*sizeof(value) entries which are -1 . //------------------------------------------------------------------------ unsigned BitPosition(unsigned value) { _ASSERTE((value != 0) && ((value & (value - 1)) == 0)); const unsigned PRIME = 37; static const char hashTable[PRIME] = { -1, 0, 1, 26, 2, 23, 27, -1, 3, 16, 24, 30, 28, 11, -1, 13, 4, 7, 17, -1, 25, 22, 31, 15, 29, 10, 12, 6, -1, 21, 14, 9, 5, 20, 8, 19, 18}; _ASSERTE(PRIME >= 8 * sizeof(value)); _ASSERTE(sizeof(hashTable) == PRIME); unsigned hash = value % PRIME; unsigned index = hashTable[hash]; _ASSERTE(index != (unsigned char)-1); return index; } //***************************************************************************** // ArrayList //***************************************************************************** void StructArrayListBase::CreateNewChunk(SIZE_T InitialChunkLength, SIZE_T ChunkLengthGrowthFactor, SIZE_T cbElement, AllocProc *pfnAlloc, SIZE_T alignment) { _ASSERTE(InitialChunkLength > 0); _ASSERTE(ChunkLengthGrowthFactor > 0); _ASSERTE(cbElement > 0); SIZE_T cbBaseSize = SIZE_T(roundUp(sizeof(StructArrayListEntryBase), alignment)); SIZE_T maxChunkCapacity = (MAXSIZE_T - cbBaseSize) / cbElement; _ASSERTE(maxChunkCapacity > 0); SIZE_T nChunkCapacity; if (!m_pChunkListHead) nChunkCapacity = InitialChunkLength; else nChunkCapacity = m_nLastChunkCapacity * ChunkLengthGrowthFactor; if (nChunkCapacity > maxChunkCapacity) { // Limit nChunkCapacity such that cbChunk computation does not overflow. nChunkCapacity = maxChunkCapacity; } SIZE_T cbChunk = cbBaseSize + SIZE_T(cbElement) * SIZE_T(nChunkCapacity); StructArrayListEntryBase *pNewChunk = (StructArrayListEntryBase *)pfnAlloc(this, cbChunk); if (m_pChunkListTail) { _ASSERTE(m_pChunkListHead); m_pChunkListTail->pNext = pNewChunk; } else { _ASSERTE(!m_pChunkListHead); m_pChunkListHead = pNewChunk; } pNewChunk->pNext = NULL; m_pChunkListTail = pNewChunk; m_nItemsInLastChunk = 0; m_nLastChunkCapacity = nChunkCapacity; }
tempbottle/llilc
lib/GcInfo/GcInfoUtil.cpp
C++
mit
3,819
using System; namespace ClosedXML.Excel { internal class XLSheetView : IXLSheetView { public XLSheetView() { View = XLSheetViewOptions.Normal; ZoomScale = 100; ZoomScaleNormal = 100; ZoomScalePageLayoutView = 100; ZoomScaleSheetLayoutView = 100; } public XLSheetView(IXLSheetView sheetView) : this() { this.SplitRow = sheetView.SplitRow; this.SplitColumn = sheetView.SplitColumn; this.FreezePanes = ((XLSheetView)sheetView).FreezePanes; } public Boolean FreezePanes { get; set; } public Int32 SplitColumn { get; set; } public Int32 SplitRow { get; set; } public XLSheetViewOptions View { get; set; } public int ZoomScale { get { return _zoomScale; } set { _zoomScale = value; switch (View) { case XLSheetViewOptions.Normal: ZoomScaleNormal = value; break; case XLSheetViewOptions.PageBreakPreview: ZoomScalePageLayoutView = value; break; case XLSheetViewOptions.PageLayout: ZoomScaleSheetLayoutView = value; break; } } } public int ZoomScaleNormal { get; set; } public int ZoomScalePageLayoutView { get; set; } public int ZoomScaleSheetLayoutView { get; set; } private int _zoomScale { get; set; } public void Freeze(Int32 rows, Int32 columns) { SplitRow = rows; SplitColumn = columns; FreezePanes = true; } public void FreezeColumns(Int32 columns) { SplitColumn = columns; FreezePanes = true; } public void FreezeRows(Int32 rows) { SplitRow = rows; FreezePanes = true; } public IXLSheetView SetView(XLSheetViewOptions value) { View = value; return this; } } }
b0bi79/ClosedXML
ClosedXML/Excel/XLSheetView.cs
C#
mit
2,252
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.entityactivation; import org.spongepowered.api.util.annotation.NonnullByDefault; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.common.interfaces.world.IMixinWorld; import org.spongepowered.common.mixin.plugin.entityactivation.ActivationRange; import org.spongepowered.common.mixin.plugin.entityactivation.interfaces.IModData_Activation; @NonnullByDefault @Mixin(net.minecraft.world.World.class) public abstract class MixinWorld_Activation implements IMixinWorld { @Inject(method = "updateEntityWithOptionalForce", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/event/ForgeEventFactory;canEntityUpdate(Lnet/minecraft/entity/Entity;)Z", shift = At.Shift.BY, by = 3, ordinal = 0, remap = false), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD) public void onUpdateEntityWithOptionalForce(net.minecraft.entity.Entity entity, boolean forceUpdate, CallbackInfo ci, int i, int j, boolean isForced, int k, boolean canUpdate) { if (forceUpdate && !ActivationRange.checkIfActive(entity)) { entity.ticksExisted++; ((IModData_Activation) entity).inactiveTick(); ci.cancel(); } } }
DDoS/SpongeForge
src/main/java/org/spongepowered/mod/mixin/entityactivation/MixinWorld_Activation.java
Java
mit
2,737
module Danger class ExampleManyMethodsPlugin < Plugin def one end # Thing two # def two(param1) end def two_point_five(param1 = nil) end # Thing three # # @param [String] param1 # A thing thing, defaults to nil. # @return [void] # def three(param1 = nil) end # Thing four # # @param [Number] param1 # A thing thing, defaults to nil. # @param [String] param2 # Another param # @return [String] # def four(param1 = nil, param2) end # Thing five # # @param [Array<String>] param1 # A thing thing. # @param [Filepath] param2 # Another param # @return [String] # def five(param1 = [], param2, param3) end # Does six # @return [Bool] # def six? end # Attribute docs # # @return [Array<String>] attr_accessor :seven attr_accessor :eight end end
KrauseFx/danger
spec/fixtures/plugins/plugin_many_methods.rb
Ruby
mit
995
namespace MYOB.AccountRight.SDK.Contracts.Version2.Company { /// <summary> /// Purchase preferences /// </summary> public class CompanyPurchasesPreferences { /// <summary> /// Purchases' terms preferences /// </summary> public CompanyPurchasesPreferencesTerms Terms { get; set; } } }
MYOB-Technology/AccountRight_Live_API_.Net_SDK
MYOB.API.SDK/SDK/Contracts/Version2/Company/CompanyPurchasesPreferences.cs
C#
mit
343
/* * Websock: high-performance binary WebSockets * Copyright (C) 2012 Joel Martin * Licensed under MPL 2.0 (see LICENSE.txt) * * Websock is similar to the standard WebSocket object but Websock * enables communication with raw TCP sockets (i.e. the binary stream) * via websockify. This is accomplished by base64 encoding the data * stream between Websock and websockify. * * Websock has built-in receive queue buffering; the message event * does not contain actual data but is simply a notification that * there is new data available. Several rQ* methods are available to * read binary data off of the receive queue. */ /*jslint browser: true, bitwise: true */ /*global Util*/ // Load Flash WebSocket emulator if needed // To force WebSocket emulator even when native WebSocket available //window.WEB_SOCKET_FORCE_FLASH = true; // To enable WebSocket emulator debug: //window.WEB_SOCKET_DEBUG=1; if (window.WebSocket && !window.WEB_SOCKET_FORCE_FLASH) { Websock_native = true; } else if (window.MozWebSocket && !window.WEB_SOCKET_FORCE_FLASH) { Websock_native = true; window.WebSocket = window.MozWebSocket; } else { /* no builtin WebSocket so load web_socket.js */ Websock_native = false; } function Websock() { "use strict"; this._websocket = null; // WebSocket object this._rQi = 0; // Receive queue index this._rQlen = 0; // Next write position in the receive queue this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB) this._rQmax = this._rQbufferSize / 8; // called in init: this._rQ = new Uint8Array(this._rQbufferSize); this._rQ = null; // Receive queue this._sQbufferSize = 1024 * 10; // 10 KiB // called in init: this._sQ = new Uint8Array(this._sQbufferSize); this._sQlen = 0; this._sQ = null; // Send queue this._mode = 'binary'; // Current WebSocket mode: 'binary', 'base64' this.maxBufferedAmount = 200; this._eventHandlers = { 'message': function () {}, 'open': function () {}, 'close': function () {}, 'error': function () {} }; } (function () { "use strict"; // this has performance issues in some versions Chromium, and // doesn't gain a tremendous amount of performance increase in Firefox // at the moment. It may be valuable to turn it on in the future. var ENABLE_COPYWITHIN = false; var MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB var typedArrayToString = (function () { // This is only for PhantomJS, which doesn't like apply-ing // with Typed Arrays try { var arr = new Uint8Array([1, 2, 3]); String.fromCharCode.apply(null, arr); return function (a) { return String.fromCharCode.apply(null, a); }; } catch (ex) { return function (a) { return String.fromCharCode.apply( null, Array.prototype.slice.call(a)); }; } })(); Websock.prototype = { // Getters and Setters get_sQ: function () { return this._sQ; }, get_rQ: function () { return this._rQ; }, get_rQi: function () { return this._rQi; }, set_rQi: function (val) { this._rQi = val; }, // Receive Queue rQlen: function () { return this._rQlen - this._rQi; }, rQpeek8: function () { return this._rQ[this._rQi]; }, rQshift8: function () { return this._rQ[this._rQi++]; }, rQskip8: function () { this._rQi++; }, rQskipBytes: function (num) { this._rQi += num; }, // TODO(directxman12): test performance with these vs a DataView rQshift16: function () { return (this._rQ[this._rQi++] << 8) + this._rQ[this._rQi++]; }, rQshift32: function () { return (this._rQ[this._rQi++] << 24) + (this._rQ[this._rQi++] << 16) + (this._rQ[this._rQi++] << 8) + this._rQ[this._rQi++]; }, rQshiftStr: function (len) { if (typeof(len) === 'undefined') { len = this.rQlen(); } var arr = new Uint8Array(this._rQ.buffer, this._rQi, len); this._rQi += len; return typedArrayToString(arr); }, rQshiftBytes: function (len) { if (typeof(len) === 'undefined') { len = this.rQlen(); } this._rQi += len; return new Uint8Array(this._rQ.buffer, this._rQi - len, len); }, rQshiftTo: function (target, len) { if (len === undefined) { len = this.rQlen(); } // TODO: make this just use set with views when using a ArrayBuffer to store the rQ target.set(new Uint8Array(this._rQ.buffer, this._rQi, len)); this._rQi += len; }, rQwhole: function () { return new Uint8Array(this._rQ.buffer, 0, this._rQlen); }, rQslice: function (start, end) { if (end) { return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start); } else { return new Uint8Array(this._rQ.buffer, this._rQi + start, this._rQlen - this._rQi - start); } }, // Check to see if we must wait for 'num' bytes (default to FBU.bytes) // to be available in the receive queue. Return true if we need to // wait (and possibly print a debug message), otherwise false. rQwait: function (msg, num, goback) { var rQlen = this._rQlen - this._rQi; // Skip rQlen() function call if (rQlen < num) { if (goback) { if (this._rQi < goback) { throw new Error("rQwait cannot backup " + goback + " bytes"); } this._rQi -= goback; } return true; // true means need more data } return false; }, // Send Queue flush: function () { if (this._websocket.bufferedAmount !== 0) { Util.Debug("bufferedAmount: " + this._websocket.bufferedAmount); } if (this._websocket.bufferedAmount < this.maxBufferedAmount) { if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) { this._websocket.send(this._encode_message()); this._sQlen = 0; } return true; } else { Util.Info("Delaying send, bufferedAmount: " + this._websocket.bufferedAmount); return false; } }, send: function (arr) { this._sQ.set(arr, this._sQlen); this._sQlen += arr.length; return this.flush(); }, send_string: function (str) { this.send(str.split('').map(function (chr) { return chr.charCodeAt(0); })); }, // Event Handlers off: function (evt) { this._eventHandlers[evt] = function () {}; }, on: function (evt, handler) { this._eventHandlers[evt] = handler; }, _allocate_buffers: function () { this._rQ = new Uint8Array(this._rQbufferSize); this._sQ = new Uint8Array(this._sQbufferSize); }, init: function (protocols, ws_schema) { this._allocate_buffers(); this._rQi = 0; this._websocket = null; // Check for full typed array support var bt = false; if (('Uint8Array' in window) && ('set' in Uint8Array.prototype)) { bt = true; } // Check for full binary type support in WebSockets // Inspired by: // https://github.com/Modernizr/Modernizr/issues/370 // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/websockets/binary.js var wsbt = false; try { if (bt && ('binaryType' in WebSocket.prototype || !!(new WebSocket(ws_schema + '://.').binaryType))) { Util.Info("Detected binaryType support in WebSockets"); wsbt = true; } } catch (exc) { // Just ignore failed test localhost connection } // Default protocols if not specified if (typeof(protocols) === "undefined") { protocols = 'binary'; } if (Array.isArray(protocols) && protocols.indexOf('binary') > -1) { protocols = 'binary'; } if (!wsbt) { throw new Error("noVNC no longer supports base64 WebSockets. " + "Please use a browser which supports binary WebSockets."); } if (protocols != 'binary') { throw new Error("noVNC no longer supports base64 WebSockets. Please " + "use the binary subprotocol instead."); } return protocols; }, open: function (uri, protocols) { var ws_schema = uri.match(/^([a-z]+):\/\//)[1]; protocols = this.init(protocols, ws_schema); this._websocket = new WebSocket(uri, protocols); if (protocols.indexOf('binary') >= 0) { this._websocket.binaryType = 'arraybuffer'; } this._websocket.onmessage = this._recv_message.bind(this); this._websocket.onopen = (function () { Util.Debug('>> WebSock.onopen'); if (this._websocket.protocol) { this._mode = this._websocket.protocol; Util.Info("Server choose sub-protocol: " + this._websocket.protocol); } else { this._mode = 'binary'; Util.Error('Server select no sub-protocol!: ' + this._websocket.protocol); } if (this._mode != 'binary') { throw new Error("noVNC no longer supports base64 WebSockets. Please " + "use the binary subprotocol instead."); } this._eventHandlers.open(); Util.Debug("<< WebSock.onopen"); }).bind(this); this._websocket.onclose = (function (e) { Util.Debug(">> WebSock.onclose"); this._eventHandlers.close(e); Util.Debug("<< WebSock.onclose"); }).bind(this); this._websocket.onerror = (function (e) { Util.Debug(">> WebSock.onerror: " + e); this._eventHandlers.error(e); Util.Debug("<< WebSock.onerror: " + e); }).bind(this); }, close: function () { if (this._websocket) { if ((this._websocket.readyState === WebSocket.OPEN) || (this._websocket.readyState === WebSocket.CONNECTING)) { Util.Info("Closing WebSocket connection"); this._websocket.close(); } this._websocket.onmessage = function (e) { return; }; } }, // private methods _encode_message: function () { // Put in a binary arraybuffer // according to the spec, you can send ArrayBufferViews with the send method return new Uint8Array(this._sQ.buffer, 0, this._sQlen); }, _expand_compact_rQ: function (min_fit) { var resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2; if (resizeNeeded) { if (!min_fit) { // just double the size if we need to do compaction this._rQbufferSize *= 2; } else { // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8 this._rQbufferSize = (this._rQlen - this._rQi + min_fit) * 8; } } // we don't want to grow unboundedly if (this._rQbufferSize > MAX_RQ_GROW_SIZE) { this._rQbufferSize = MAX_RQ_GROW_SIZE; if (this._rQbufferSize - this._rQlen - this._rQi < min_fit) { throw new Exception("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit"); } } if (resizeNeeded) { var old_rQbuffer = this._rQ.buffer; this._rQmax = this._rQbufferSize / 8; this._rQ = new Uint8Array(this._rQbufferSize); this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi)); } else { if (ENABLE_COPYWITHIN) { this._rQ.copyWithin(0, this._rQi); } else { this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi)); } } this._rQlen = this._rQlen - this._rQi; this._rQi = 0; }, _decode_message: function (data) { // push arraybuffer values onto the end var u8 = new Uint8Array(data); if (u8.length > this._rQbufferSize - this._rQlen) { this._expand_compact_rQ(u8.length); } this._rQ.set(u8, this._rQlen); this._rQlen += u8.length; }, _recv_message: function (e) { try { this._decode_message(e.data); if (this.rQlen() > 0) { this._eventHandlers.message(); // Compact the receive queue if (this._rQlen == this._rQi) { this._rQlen = 0; this._rQi = 0; } else if (this._rQlen > this._rQmax) { this._expand_compact_rQ(); } } else { Util.Debug("Ignoring empty message"); } } catch (exc) { var exception_str = ""; if (exc.name) { exception_str += "\n name: " + exc.name + "\n"; exception_str += " message: " + exc.message + "\n"; } if (typeof exc.description !== 'undefined') { exception_str += " description: " + exc.description + "\n"; } if (typeof exc.stack !== 'undefined') { exception_str += exc.stack; } if (exception_str.length > 0) { Util.Error("recv_message, caught exception: " + exception_str); } else { Util.Error("recv_message, caught exception: " + exc); } if (typeof exc.name !== 'undefined') { this._eventHandlers.error(exc.name + ": " + exc.message); } else { this._eventHandlers.error(exc); } } } }; })();
jerry-0824/017_stone
web/vnc/include/websock.js
JavaScript
mit
15,502
module Lotus module View module Rendering # Null Object pattern for layout template # # It's used when a layout doesn't have an associated template. # # A common scenario is for non-html requests. # Usually we have a template for the application layout # (eg `templates/application.html.erb`), but we don't use to have the a # template for JSON requests (eg `templates/application.json.erb`). # Because most of the times, we only return the output of the view. # # @api private # @since 0.1.0 # # @example # require 'lotus/view' # # # We have an ApplicationLayout (views/application_layout.rb): # class ApplicationLayout # include Lotus::Layout # end # # # Our layout has a template for HTML requests, located at: # # templates/application.html.erb # # # We set it as global layout # Lotus::View.layout = :application # # # We have two views for HTML and JSON articles. # # They have a template each: # # # # * templates/articles/show.html.erb # # * templates/articles/show.json.erb # module Articles # class Show # include Lotus::View # format :html # end # # class JsonShow < Show # format :json # end # end # # # We initialize the framework # Lotus::View.load! # # # # # When we ask for a HTML rendering, it will use `Articles::Show` and # # ApplicationLayout. The output will be a composition of: # # # # * templates/articles/show.html.erb # # * templates/application.html.erb # # # When we ask for a JSON rendering, it will use `Articles::JsonShow` # # and ApplicationLayout. Since, the layout doesn't have any associated # # template for JSON, the output will be a composition of: # # # # * templates/articles/show.json.erb class NullTemplate # Render the layout template # # @param scope [Lotus::View::Scope] the rendering scope # @param locals [Hash] a set of objects available during the rendering # @yield [Proc] yields the given block # # @return [String] the output of the rendering process # # @api private # @since 0.1.0 # # @see Lotus::Layout#render # @see Lotus::View::Rendering#render def render(scope, locals = {}) yield end end end end end
farrel/view
lib/lotus/view/rendering/null_template.rb
Ruby
mit
2,669
package service import ( "encoding/json" "strings" "code.cloudfoundry.org/cli/cf" "code.cloudfoundry.org/cli/cf/flagcontext" "code.cloudfoundry.org/cli/cf/flags" . "code.cloudfoundry.org/cli/cf/i18n" "code.cloudfoundry.org/cli/cf/uihelpers" "fmt" "code.cloudfoundry.org/cli/cf/api" "code.cloudfoundry.org/cli/cf/commandregistry" "code.cloudfoundry.org/cli/cf/configuration/coreconfig" "code.cloudfoundry.org/cli/cf/requirements" "code.cloudfoundry.org/cli/cf/terminal" ) type CreateUserProvidedService struct { ui terminal.UI config coreconfig.Reader userProvidedServiceInstanceRepo api.UserProvidedServiceInstanceRepository } func init() { commandregistry.Register(&CreateUserProvidedService{}) } func (cmd *CreateUserProvidedService) MetaData() commandregistry.CommandMetadata { fs := make(map[string]flags.FlagSet) fs["p"] = &flags.StringFlag{ShortName: "p", Usage: T("Credentials, provided inline or in a file, to be exposed in the VCAP_SERVICES environment variable for bound applications")} fs["l"] = &flags.StringFlag{ShortName: "l", Usage: T("URL to which logs for bound applications will be streamed")} fs["r"] = &flags.StringFlag{ShortName: "r", Usage: T("URL to which requests for bound routes will be forwarded. Scheme for this URL must be https")} fs["t"] = &flags.StringFlag{ShortName: "t", Usage: T("User provided tags")} return commandregistry.CommandMetadata{ Name: "create-user-provided-service", ShortName: "cups", Description: T("Make a user-provided service instance available to CF apps"), Usage: []string{ T(`CF_NAME create-user-provided-service SERVICE_INSTANCE [-p CREDENTIALS] [-l SYSLOG_DRAIN_URL] [-r ROUTE_SERVICE_URL] [-t TAGS] Pass comma separated credential parameter names to enable interactive mode: CF_NAME create-user-provided-service SERVICE_INSTANCE -p "comma, separated, parameter, names" Pass credential parameters as JSON to create a service non-interactively: CF_NAME create-user-provided-service SERVICE_INSTANCE -p '{"key1":"value1","key2":"value2"}' Specify a path to a file containing JSON: CF_NAME create-user-provided-service SERVICE_INSTANCE -p PATH_TO_FILE`), }, Examples: []string{ `CF_NAME create-user-provided-service my-db-mine -p "username, password"`, `CF_NAME create-user-provided-service my-db-mine -p /path/to/credentials.json`, `CF_NAME create-user-provided-service my-db-mine -t "list, of, tags"`, `CF_NAME create-user-provided-service my-drain-service -l syslog://example.com`, `CF_NAME create-user-provided-service my-route-service -r https://example.com`, ``, fmt.Sprintf("%s:", T(`Linux/Mac`)), ` CF_NAME create-user-provided-service my-db-mine -p '{"username":"admin","password":"pa55woRD"}'`, ``, fmt.Sprintf("%s:", T(`Windows Command Line`)), ` CF_NAME create-user-provided-service my-db-mine -p "{\"username\":\"admin\",\"password\":\"pa55woRD\"}"`, ``, fmt.Sprintf("%s:", T(`Windows PowerShell`)), ` CF_NAME create-user-provided-service my-db-mine -p '{\"username\":\"admin\",\"password\":\"pa55woRD\"}'`, }, Flags: fs, } } func (cmd *CreateUserProvidedService) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { if len(fc.Args()) != 1 { cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("create-user-provided-service")) return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1) } reqs := []requirements.Requirement{ requirementsFactory.NewLoginRequirement(), requirementsFactory.NewTargetedSpaceRequirement(), } if fc.IsSet("t") { reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '-t'", cf.UserProvidedServiceTagsMinimumAPIVersion)) } return reqs, nil } func (cmd *CreateUserProvidedService) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command { cmd.ui = deps.UI cmd.config = deps.Config cmd.userProvidedServiceInstanceRepo = deps.RepoLocator.GetUserProvidedServiceInstanceRepository() return cmd } func (cmd *CreateUserProvidedService) Execute(c flags.FlagContext) error { name := c.Args()[0] drainURL := c.String("l") routeServiceURL := c.String("r") credentials := strings.Trim(c.String("p"), `"'`) credentialsMap := make(map[string]interface{}) tags := c.String("t") tagsList := uihelpers.ParseTags(tags) if c.IsSet("p") { jsonBytes, err := flagcontext.GetContentsFromFlagValue(credentials) if err != nil { return err } err = json.Unmarshal(jsonBytes, &credentialsMap) if err != nil { for _, param := range strings.Split(credentials, ",") { param = strings.Trim(param, " ") credentialsMap[param] = cmd.ui.Ask(param) } } } cmd.ui.Say(T("Creating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) err := cmd.userProvidedServiceInstanceRepo.Create(name, drainURL, routeServiceURL, credentialsMap, tagsList) if err != nil { return err } cmd.ui.Ok() return nil }
odlp/antifreeze
vendor/github.com/cloudfoundry/cli/cf/commands/service/create_user_provided_service.go
GO
mit
5,467
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Spark.CSharp.Core; using Microsoft.Spark.CSharp.Interop; using Microsoft.Spark.CSharp.Interop.Ipc; namespace Microsoft.Spark.CSharp.Proxy.Ipc { [ExcludeFromCodeCoverage] //IPC calls to JVM validated using validation-enabled samples - unit test coverage not reqiured internal class StatusTrackerIpcProxy : IStatusTrackerProxy { private readonly JvmObjectReference jvmStatusTrackerReference; public StatusTrackerIpcProxy(JvmObjectReference jStatusTracker) { jvmStatusTrackerReference = jStatusTracker; } public int[] GetJobIdsForGroup(string jobGroup) { return (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getJobIdsForGroup", new object[] { jobGroup }); } public int[] GetActiveStageIds() { return (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getActiveStageIds"); } public int[] GetActiveJobsIds() { return (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getActiveJobsIds"); } public SparkJobInfo GetJobInfo(int jobId) { var jobInfoId = SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getJobInfo", new object[] { jobId }); if (jobInfoId == null) return null; JvmObjectReference jJobInfo = new JvmObjectReference((string)jobInfoId); int[] stageIds = (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jJobInfo, "stageIds"); string statusString = SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jJobInfo, "status").ToString(); var status = (JobExecutionStatus) Enum.Parse(typeof(JobExecutionStatus), statusString, true); return new SparkJobInfo(jobId, stageIds, status); } public SparkStageInfo GetStageInfo(int stageId) { var stageInfoId = SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getStageInfo", new object[] { stageId }); if (stageInfoId == null) return null; JvmObjectReference jStageInfo = new JvmObjectReference((string)stageInfoId); int currentAttemptId = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "currentAttemptId"); int submissionTime = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "submissionTime"); string name = (string)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "name"); int numTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numTasks"); int numActiveTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numActiveTasks"); int numCompletedTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numCompletedTasks"); int numFailedTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numFailedTasks"); return new SparkStageInfo(stageId, currentAttemptId, (long)submissionTime, name, numTasks, numActiveTasks, numCompletedTasks, numFailedTasks); } } }
dwnichols/Mobius
csharp/Adapter/Microsoft.Spark.CSharp/Proxy/Ipc/StatusTrackerIpcProxy.cs
C#
mit
3,621
/* Copyright 2016 The Kubernetes Authors All rights reserved. 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. */ package helm // import "k8s.io/helm/pkg/helm" import ( "errors" "path/filepath" "reflect" "testing" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "k8s.io/helm/pkg/chartutil" cpb "k8s.io/helm/pkg/proto/hapi/chart" rls "k8s.io/helm/pkg/proto/hapi/release" tpb "k8s.io/helm/pkg/proto/hapi/services" ) // Path to example charts relative to pkg/helm. const chartsDir = "../../docs/examples/" // Sentinel error to indicate to the Helm client to not send the request to Tiller. var errSkip = errors.New("test: skip") // Verify each ReleaseListOption is applied to a ListReleasesRequest correctly. func TestListReleases_VerifyOptions(t *testing.T) { // Options testdata var limit = 2 var offset = "offset" var filter = "filter" var sortBy = int32(2) var sortOrd = int32(1) var codes = []rls.Status_Code{ rls.Status_FAILED, rls.Status_DELETED, rls.Status_DEPLOYED, rls.Status_SUPERSEDED, } var namespace = "namespace" // Expected ListReleasesRequest message exp := &tpb.ListReleasesRequest{ Limit: int64(limit), Offset: offset, Filter: filter, SortBy: tpb.ListSort_SortBy(sortBy), SortOrder: tpb.ListSort_SortOrder(sortOrd), StatusCodes: codes, Namespace: namespace, } // Options used in ListReleases ops := []ReleaseListOption{ ReleaseListSort(sortBy), ReleaseListOrder(sortOrd), ReleaseListLimit(limit), ReleaseListOffset(offset), ReleaseListFilter(filter), ReleaseListStatuses(codes), ReleaseListNamespace(namespace), } // BeforeCall option to intercept Helm client ListReleasesRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.ListReleasesRequest: t.Logf("ListReleasesRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type ListReleasesRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.ListReleases(ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.listReq.Filter) } // Verify each InstallOption is applied to an InstallReleaseRequest correctly. func TestInstallRelease_VerifyOptions(t *testing.T) { // Options testdata var disableHooks = true var releaseName = "test" var namespace = "default" var reuseName = true var dryRun = true var chartName = "alpine" var chartPath = filepath.Join(chartsDir, chartName) var overrides = []byte("key1=value1,key2=value2") // Expected InstallReleaseRequest message exp := &tpb.InstallReleaseRequest{ Chart: loadChart(t, chartName), Values: &cpb.Config{Raw: string(overrides)}, DryRun: dryRun, Name: releaseName, DisableHooks: disableHooks, Namespace: namespace, ReuseName: reuseName, } // Options used in InstallRelease ops := []InstallOption{ ValueOverrides(overrides), InstallDryRun(dryRun), ReleaseName(releaseName), InstallReuseName(reuseName), InstallDisableHooks(disableHooks), } // BeforeCall option to intercept Helm client InstallReleaseRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.InstallReleaseRequest: t.Logf("InstallReleaseRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type InstallReleaseRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.InstallRelease(chartPath, namespace, ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.instReq.Name) } // Verify each DeleteOptions is applied to an UninstallReleaseRequest correctly. func TestDeleteRelease_VerifyOptions(t *testing.T) { // Options testdata var releaseName = "test" var disableHooks = true var purgeFlag = true // Expected DeleteReleaseRequest message exp := &tpb.UninstallReleaseRequest{ Name: releaseName, Purge: purgeFlag, DisableHooks: disableHooks, } // Options used in DeleteRelease ops := []DeleteOption{ DeletePurge(purgeFlag), DeleteDisableHooks(disableHooks), } // BeforeCall option to intercept Helm client DeleteReleaseRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.UninstallReleaseRequest: t.Logf("UninstallReleaseRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type UninstallReleaseRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.DeleteRelease(releaseName, ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.uninstallReq.Name) } // Verify each UpdateOption is applied to an UpdateReleaseRequest correctly. func TestUpdateRelease_VerifyOptions(t *testing.T) { // Options testdata var chartName = "alpine" var chartPath = filepath.Join(chartsDir, chartName) var releaseName = "test" var disableHooks = true var overrides = []byte("key1=value1,key2=value2") var dryRun = false // Expected UpdateReleaseRequest message exp := &tpb.UpdateReleaseRequest{ Name: releaseName, Chart: loadChart(t, chartName), Values: &cpb.Config{Raw: string(overrides)}, DryRun: dryRun, DisableHooks: disableHooks, } // Options used in UpdateRelease ops := []UpdateOption{ UpgradeDryRun(dryRun), UpdateValueOverrides(overrides), UpgradeDisableHooks(disableHooks), } // BeforeCall option to intercept Helm client UpdateReleaseRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.UpdateReleaseRequest: t.Logf("UpdateReleaseRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type UpdateReleaseRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.UpdateRelease(releaseName, chartPath, ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.updateReq.Name) } // Verify each RollbackOption is applied to a RollbackReleaseRequest correctly. func TestRollbackRelease_VerifyOptions(t *testing.T) { // Options testdata var disableHooks = true var releaseName = "test" var revision = int32(2) var dryRun = true // Expected RollbackReleaseRequest message exp := &tpb.RollbackReleaseRequest{ Name: releaseName, DryRun: dryRun, Version: revision, DisableHooks: disableHooks, } // Options used in RollbackRelease ops := []RollbackOption{ RollbackDryRun(dryRun), RollbackVersion(revision), RollbackDisableHooks(disableHooks), } // BeforeCall option to intercept Helm client RollbackReleaseRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.RollbackReleaseRequest: t.Logf("RollbackReleaseRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type RollbackReleaseRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.RollbackRelease(releaseName, ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.rollbackReq.Name) } // Verify each StatusOption is applied to a GetReleaseStatusRequest correctly. func TestReleaseStatus_VerifyOptions(t *testing.T) { // Options testdata var releaseName = "test" var revision = int32(2) // Expected GetReleaseStatusRequest message exp := &tpb.GetReleaseStatusRequest{ Name: releaseName, Version: revision, } // BeforeCall option to intercept Helm client GetReleaseStatusRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.GetReleaseStatusRequest: t.Logf("GetReleaseStatusRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type GetReleaseStatusRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.ReleaseStatus(releaseName, StatusReleaseVersion(revision)); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.statusReq.Name) } // Verify each ContentOption is applied to a GetReleaseContentRequest correctly. func TestReleaseContent_VerifyOptions(t *testing.T) { // Options testdata var releaseName = "test" var revision = int32(2) // Expected GetReleaseContentRequest message exp := &tpb.GetReleaseContentRequest{ Name: releaseName, Version: revision, } // BeforeCall option to intercept Helm client GetReleaseContentRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.GetReleaseContentRequest: t.Logf("GetReleaseContentRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type GetReleaseContentRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.ReleaseContent(releaseName, ContentReleaseVersion(revision)); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.contentReq.Name) } func assert(t *testing.T, expect, actual interface{}) { if !reflect.DeepEqual(expect, actual) { t.Fatalf("expected %#+v, actual %#+v\n", expect, actual) } } func loadChart(t *testing.T, name string) *cpb.Chart { c, err := chartutil.Load(filepath.Join(chartsDir, name)) if err != nil { t.Fatalf("failed to load test chart (%q): %s\n", name, err) } return c }
skuid/helm-value-store
vendor/k8s.io/helm/pkg/helm/helm_test.go
GO
mit
10,604
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Filesystem; use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Exception\InvalidArgumentException; use Symfony\Component\Filesystem\Exception\IOException; /** * Provides basic utility to manipulate the file system. * * @author Fabien Potencier <fabien@symfony.com> */ class Filesystem { private static $lastError; /** * Copies a file. * * If the target file is older than the origin file, it's always overwritten. * If the target file is newer, it is overwritten only when the * $overwriteNewerFiles option is set to true. * * @throws FileNotFoundException When originFile doesn't exist * @throws IOException When copy fails */ public function copy(string $originFile, string $targetFile, bool $overwriteNewerFiles = false) { $originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://'); if ($originIsLocal && !is_file($originFile)) { throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile); } $this->mkdir(\dirname($targetFile)); $doCopy = true; if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) { $doCopy = filemtime($originFile) > filemtime($targetFile); } if ($doCopy) { // https://bugs.php.net/64634 if (false === $source = @fopen($originFile, 'r')) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile); } // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(['ftp' => ['overwrite' => true]]))) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile); } $bytesCopied = stream_copy_to_stream($source, $target); fclose($source); fclose($target); unset($source, $target); if (!is_file($targetFile)) { throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile); } if ($originIsLocal) { // Like `cp`, preserve executable permission bits @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111)); if ($bytesCopied !== $bytesOrigin = filesize($originFile)) { throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile); } } } } /** * Creates a directory recursively. * * @param string|iterable $dirs The directory path * * @throws IOException On any directory creation failure */ public function mkdir($dirs, int $mode = 0777) { foreach ($this->toIterable($dirs) as $dir) { if (is_dir($dir)) { continue; } if (!self::box('mkdir', $dir, $mode, true)) { if (!is_dir($dir)) { // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one if (self::$lastError) { throw new IOException(sprintf('Failed to create "%s": ', $dir).self::$lastError, 0, null, $dir); } throw new IOException(sprintf('Failed to create "%s".', $dir), 0, null, $dir); } } } } /** * Checks the existence of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to check * * @return bool true if the file exists, false otherwise */ public function exists($files) { $maxPathLength = PHP_MAXPATHLEN - 2; foreach ($this->toIterable($files) as $file) { if (\strlen($file) > $maxPathLength) { throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file); } if (!file_exists($file)) { return false; } } return true; } /** * Sets access and modification time of file. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to create * @param int|null $time The touch time as a Unix timestamp, if not supplied the current system time is used * @param int|null $atime The access time as a Unix timestamp, if not supplied the current system time is used * * @throws IOException When touch fails */ public function touch($files, int $time = null, int $atime = null) { foreach ($this->toIterable($files) as $file) { $touch = $time ? @touch($file, $time, $atime) : @touch($file); if (true !== $touch) { throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file); } } } /** * Removes files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to remove * * @throws IOException When removal fails */ public function remove($files) { if ($files instanceof \Traversable) { $files = iterator_to_array($files, false); } elseif (!\is_array($files)) { $files = [$files]; } $files = array_reverse($files); foreach ($files as $file) { if (is_link($file)) { // See https://bugs.php.net/52176 if (!(self::box('unlink', $file) || '\\' !== \DIRECTORY_SEPARATOR || self::box('rmdir', $file)) && file_exists($file)) { throw new IOException(sprintf('Failed to remove symlink "%s": ', $file).self::$lastError); } } elseif (is_dir($file)) { $this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS)); if (!self::box('rmdir', $file) && file_exists($file)) { throw new IOException(sprintf('Failed to remove directory "%s": ', $file).self::$lastError); } } elseif (!self::box('unlink', $file) && file_exists($file)) { throw new IOException(sprintf('Failed to remove file "%s": ', $file).self::$lastError); } } } /** * Change mode for an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change mode * @param int $mode The new mode (octal) * @param int $umask The mode mask (octal) * @param bool $recursive Whether change the mod recursively or not * * @throws IOException When the change fails */ public function chmod($files, int $mode, int $umask = 0000, bool $recursive = false) { foreach ($this->toIterable($files) as $file) { if (true !== @chmod($file, $mode & ~$umask)) { throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file); } if ($recursive && is_dir($file) && !is_link($file)) { $this->chmod(new \FilesystemIterator($file), $mode, $umask, true); } } } /** * Change the owner of an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change owner * @param string|int $user A user name or number * @param bool $recursive Whether change the owner recursively or not * * @throws IOException When the change fails */ public function chown($files, $user, bool $recursive = false) { foreach ($this->toIterable($files) as $file) { if ($recursive && is_dir($file) && !is_link($file)) { $this->chown(new \FilesystemIterator($file), $user, true); } if (is_link($file) && \function_exists('lchown')) { if (true !== @lchown($file, $user)) { throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file); } } else { if (true !== @chown($file, $user)) { throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file); } } } } /** * Change the group of an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change group * @param string|int $group A group name or number * @param bool $recursive Whether change the group recursively or not * * @throws IOException When the change fails */ public function chgrp($files, $group, bool $recursive = false) { foreach ($this->toIterable($files) as $file) { if ($recursive && is_dir($file) && !is_link($file)) { $this->chgrp(new \FilesystemIterator($file), $group, true); } if (is_link($file) && \function_exists('lchgrp')) { if (true !== @lchgrp($file, $group)) { throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file); } } else { if (true !== @chgrp($file, $group)) { throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file); } } } } /** * Renames a file or a directory. * * @throws IOException When target file or directory already exists * @throws IOException When origin cannot be renamed */ public function rename(string $origin, string $target, bool $overwrite = false) { // we check that target does not exist if (!$overwrite && $this->isReadable($target)) { throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target); } if (true !== @rename($origin, $target)) { if (is_dir($origin)) { // See https://bugs.php.net/54097 & https://php.net/rename#113943 $this->mirror($origin, $target, null, ['override' => $overwrite, 'delete' => $overwrite]); $this->remove($origin); return; } throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target); } } /** * Tells whether a file exists and is readable. * * @throws IOException When windows path is longer than 258 characters */ private function isReadable(string $filename): bool { $maxPathLength = PHP_MAXPATHLEN - 2; if (\strlen($filename) > $maxPathLength) { throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename); } return is_readable($filename); } /** * Creates a symbolic link or copy a directory. * * @throws IOException When symlink fails */ public function symlink(string $originDir, string $targetDir, bool $copyOnWindows = false) { if ('\\' === \DIRECTORY_SEPARATOR) { $originDir = strtr($originDir, '/', '\\'); $targetDir = strtr($targetDir, '/', '\\'); if ($copyOnWindows) { $this->mirror($originDir, $targetDir); return; } } $this->mkdir(\dirname($targetDir)); if (is_link($targetDir)) { if (readlink($targetDir) === $originDir) { return; } $this->remove($targetDir); } if (!self::box('symlink', $originDir, $targetDir)) { $this->linkException($originDir, $targetDir, 'symbolic'); } } /** * Creates a hard link, or several hard links to a file. * * @param string|string[] $targetFiles The target file(s) * * @throws FileNotFoundException When original file is missing or not a file * @throws IOException When link fails, including if link already exists */ public function hardlink(string $originFile, $targetFiles) { if (!$this->exists($originFile)) { throw new FileNotFoundException(null, 0, null, $originFile); } if (!is_file($originFile)) { throw new FileNotFoundException(sprintf('Origin file "%s" is not a file.', $originFile)); } foreach ($this->toIterable($targetFiles) as $targetFile) { if (is_file($targetFile)) { if (fileinode($originFile) === fileinode($targetFile)) { continue; } $this->remove($targetFile); } if (!self::box('link', $originFile, $targetFile)) { $this->linkException($originFile, $targetFile, 'hard'); } } } /** * @param string $linkType Name of the link type, typically 'symbolic' or 'hard' */ private function linkException(string $origin, string $target, string $linkType) { if (self::$lastError) { if ('\\' === \DIRECTORY_SEPARATOR && false !== strpos(self::$lastError, 'error code(1314)')) { throw new IOException(sprintf('Unable to create "%s" link due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', $linkType), 0, null, $target); } } throw new IOException(sprintf('Failed to create "%s" link from "%s" to "%s".', $linkType, $origin, $target), 0, null, $target); } /** * Resolves links in paths. * * With $canonicalize = false (default) * - if $path does not exist or is not a link, returns null * - if $path is a link, returns the next direct target of the link without considering the existence of the target * * With $canonicalize = true * - if $path does not exist, returns null * - if $path exists, returns its absolute fully resolved final version * * @return string|null */ public function readlink(string $path, bool $canonicalize = false) { if (!$canonicalize && !is_link($path)) { return null; } if ($canonicalize) { if (!$this->exists($path)) { return null; } if ('\\' === \DIRECTORY_SEPARATOR) { $path = readlink($path); } return realpath($path); } if ('\\' === \DIRECTORY_SEPARATOR) { return realpath($path); } return readlink($path); } /** * Given an existing path, convert it to a path relative to a given starting path. * * @return string Path of target relative to starting path */ public function makePathRelative(string $endPath, string $startPath) { if (!$this->isAbsolutePath($startPath)) { throw new InvalidArgumentException(sprintf('The start path "%s" is not absolute.', $startPath)); } if (!$this->isAbsolutePath($endPath)) { throw new InvalidArgumentException(sprintf('The end path "%s" is not absolute.', $endPath)); } // Normalize separators on Windows if ('\\' === \DIRECTORY_SEPARATOR) { $endPath = str_replace('\\', '/', $endPath); $startPath = str_replace('\\', '/', $startPath); } $splitDriveLetter = function ($path) { return (\strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0])) ? [substr($path, 2), strtoupper($path[0])] : [$path, null]; }; $splitPath = function ($path) { $result = []; foreach (explode('/', trim($path, '/')) as $segment) { if ('..' === $segment) { array_pop($result); } elseif ('.' !== $segment && '' !== $segment) { $result[] = $segment; } } return $result; }; list($endPath, $endDriveLetter) = $splitDriveLetter($endPath); list($startPath, $startDriveLetter) = $splitDriveLetter($startPath); $startPathArr = $splitPath($startPath); $endPathArr = $splitPath($endPath); if ($endDriveLetter && $startDriveLetter && $endDriveLetter != $startDriveLetter) { // End path is on another drive, so no relative path exists return $endDriveLetter.':/'.($endPathArr ? implode('/', $endPathArr).'/' : ''); } // Find for which directory the common path stops $index = 0; while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) { ++$index; } // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels) if (1 === \count($startPathArr) && '' === $startPathArr[0]) { $depth = 0; } else { $depth = \count($startPathArr) - $index; } // Repeated "../" for each level need to reach the common path $traverser = str_repeat('../', $depth); $endPathRemainder = implode('/', \array_slice($endPathArr, $index)); // Construct $endPath from traversing to the common path, then to the remaining $endPath $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : ''); return '' === $relativePath ? './' : $relativePath; } /** * Mirrors a directory to another. * * Copies files and directories from the origin directory into the target directory. By default: * * - existing files in the target directory will be overwritten, except if they are newer (see the `override` option) * - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option) * * @param \Traversable|null $iterator Iterator that filters which files and directories to copy, if null a recursive iterator is created * @param array $options An array of boolean options * Valid options are: * - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false) * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false) * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false) * * @throws IOException When file type is unknown */ public function mirror(string $originDir, string $targetDir, \Traversable $iterator = null, array $options = []) { $targetDir = rtrim($targetDir, '/\\'); $originDir = rtrim($originDir, '/\\'); $originDirLen = \strlen($originDir); if (!$this->exists($originDir)) { throw new IOException(sprintf('The origin directory specified "%s" was not found.', $originDir), 0, null, $originDir); } // Iterate in destination folder to remove obsolete entries if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) { $deleteIterator = $iterator; if (null === $deleteIterator) { $flags = \FilesystemIterator::SKIP_DOTS; $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST); } $targetDirLen = \strlen($targetDir); foreach ($deleteIterator as $file) { $origin = $originDir.substr($file->getPathname(), $targetDirLen); if (!$this->exists($origin)) { $this->remove($file); } } } $copyOnWindows = $options['copy_on_windows'] ?? false; if (null === $iterator) { $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS; $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST); } $this->mkdir($targetDir); $filesCreatedWhileMirroring = []; foreach ($iterator as $file) { if ($file->getPathname() === $targetDir || $file->getRealPath() === $targetDir || isset($filesCreatedWhileMirroring[$file->getRealPath()])) { continue; } $target = $targetDir.substr($file->getPathname(), $originDirLen); $filesCreatedWhileMirroring[$target] = true; if (!$copyOnWindows && is_link($file)) { $this->symlink($file->getLinkTarget(), $target); } elseif (is_dir($file)) { $this->mkdir($target); } elseif (is_file($file)) { $this->copy($file, $target, isset($options['override']) ? $options['override'] : false); } else { throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file); } } } /** * Returns whether the file path is an absolute path. * * @return bool */ public function isAbsolutePath(string $file) { return strspn($file, '/\\', 0, 1) || (\strlen($file) > 3 && ctype_alpha($file[0]) && ':' === $file[1] && strspn($file, '/\\', 2, 1) ) || null !== parse_url($file, PHP_URL_SCHEME) ; } /** * Creates a temporary file with support for custom stream wrappers. * * @param string $prefix The prefix of the generated temporary filename * Note: Windows uses only the first three characters of prefix * @param string $suffix The suffix of the generated temporary filename * * @return string The new temporary filename (with path), or throw an exception on failure */ public function tempnam(string $dir, string $prefix/*, string $suffix = ''*/) { $suffix = \func_num_args() > 2 ? func_get_arg(2) : ''; list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir); // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem if ((null === $scheme || 'file' === $scheme || 'gs' === $scheme) && '' === $suffix) { $tmpFile = @tempnam($hierarchy, $prefix); // If tempnam failed or no scheme return the filename otherwise prepend the scheme if (false !== $tmpFile) { if (null !== $scheme && 'gs' !== $scheme) { return $scheme.'://'.$tmpFile; } return $tmpFile; } throw new IOException('A temporary file could not be created.'); } // Loop until we create a valid temp file or have reached 10 attempts for ($i = 0; $i < 10; ++$i) { // Create a unique filename $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true).$suffix; // Use fopen instead of file_exists as some streams do not support stat // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability $handle = @fopen($tmpFile, 'x+'); // If unsuccessful restart the loop if (false === $handle) { continue; } // Close the file if it was successfully opened @fclose($handle); return $tmpFile; } throw new IOException('A temporary file could not be created.'); } /** * Atomically dumps content into a file. * * @param string|resource $content The data to write into the file * * @throws IOException if the file cannot be written to */ public function dumpFile(string $filename, $content) { if (\is_array($content)) { throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__)); } $dir = \dirname($filename); if (!is_dir($dir)) { $this->mkdir($dir); } if (!is_writable($dir)) { throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); } // Will create a temp file with 0600 access rights // when the filesystem supports chmod. $tmpFile = $this->tempnam($dir, basename($filename)); if (false === @file_put_contents($tmpFile, $content)) { throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); } @chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask()); $this->rename($tmpFile, $filename, true); } /** * Appends content to an existing file. * * @param string|resource $content The content to append * * @throws IOException If the file is not writable */ public function appendToFile(string $filename, $content) { if (\is_array($content)) { throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__)); } $dir = \dirname($filename); if (!is_dir($dir)) { $this->mkdir($dir); } if (!is_writable($dir)) { throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); } if (false === @file_put_contents($filename, $content, FILE_APPEND)) { throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); } } private function toIterable($files): iterable { return \is_array($files) || $files instanceof \Traversable ? $files : [$files]; } /** * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> [file, tmp]). */ private function getSchemeAndHierarchy(string $filename): array { $components = explode('://', $filename, 2); return 2 === \count($components) ? [$components[0], $components[1]] : [null, $components[0]]; } /** * @return mixed */ private static function box(callable $func) { self::$lastError = null; set_error_handler(__CLASS__.'::handleError'); try { $result = $func(...\array_slice(\func_get_args(), 1)); restore_error_handler(); return $result; } catch (\Throwable $e) { } restore_error_handler(); throw $e; } /** * @internal */ public static function handleError($type, $msg) { self::$lastError = $msg; } }
gonzalovilaseca/symfony
src/Symfony/Component/Filesystem/Filesystem.php
PHP
mit
28,366
using Machine.Specifications; using PlainElastic.Net.IndexSettings; using PlainElastic.Net.Utils; namespace PlainElastic.Net.Tests.Builders.IndexSettings { [Subject(typeof(NGramTokenFilter))] class When_complete_NGramTokenFilter_built { Because of = () => result = new NGramTokenFilter() .Name("name") .Version("3.6") .MinGram(2) .MaxGram(3) .CustomPart("{ Custom }") .ToString(); It should_start_with_name = () => result.ShouldStartWith("'name': {".AltQuote()); It should_contain_type_part = () => result.ShouldContain("'type': 'nGram'".AltQuote()); It should_contain_version_part = () => result.ShouldContain("'version': '3.6'".AltQuote()); It should_contain_min_gram_part = () => result.ShouldContain("'min_gram': 2".AltQuote()); It should_contain_max_gram_part = () => result.ShouldContain("'max_gram': 3".AltQuote()); It should_contain_custom_part = () => result.ShouldContain("{ Custom }".AltQuote()); It should_return_correct_result = () => result.ShouldEqual(("'name': { " + "'type': 'nGram'," + "'version': '3.6'," + "'min_gram': 2," + "'max_gram': 3," + "{ Custom } }").AltQuote()); private static string result; } }
yonglehou/PlainElastic.Net
src/PlainElastic.Net.Tests/Builders/Analysis/TokenFilters/NGram/When_complete_NGramTokenFilter_built.cs
C#
mit
1,835
using Umbraco.Cms.Core.DependencyInjection; namespace Umbraco.Cms.Core.Composing { /// <summary> /// Provides a base class for composers which compose a component. /// </summary> /// <typeparam name="TComponent">The type of the component</typeparam> public abstract class ComponentComposer<TComponent> : IComposer where TComponent : IComponent { /// <inheritdoc /> public virtual void Compose(IUmbracoBuilder builder) { builder.Components().Append<TComponent>(); } // note: thanks to this class, a component that does not compose anything can be // registered with one line: // public class MyComponentComposer : ComponentComposer<MyComponent> { } } }
umbraco/Umbraco-CMS
src/Umbraco.Core/Composing/ComponentComposer.cs
C#
mit
761
'use strict'; var dynamoose = require('../'); dynamoose.AWS.config.update({ accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-east-1' }); dynamoose.local(); var should = require('should'); var Cat, Cat2; describe('Model', function (){ this.timeout(5000); before(function(done) { this.timeout(12000); dynamoose.setDefaults({ prefix: 'test-' }); Cat = dynamoose.model('Cat', { id: Number, name: String, owner: String, age: { type: Number }, vet:{ name: String, address: String }, ears:[{ name: String }], legs: [String], more: Object, array: Array }, {useDocumentTypes: true}); // Create a model with a range key Cat2 = dynamoose.model('Cat2', { ownerId: { type: Number, hashKey: true }, name: { type: String, rangeKey: true } }); done(); }); after(function (done) { delete dynamoose.models['test-Cat']; done(); }); it('Create simple model', function (done) { this.timeout(12000); Cat.should.have.property('$__'); Cat.$__.name.should.eql('test-Cat'); Cat.$__.options.should.have.property('create', true); var schema = Cat.$__.schema; should.exist(schema); schema.attributes.id.type.name.should.eql('number'); should(schema.attributes.id.isSet).not.be.ok; should.not.exist(schema.attributes.id.default); should.not.exist(schema.attributes.id.validator); should(schema.attributes.id.required).not.be.ok; schema.attributes.name.type.name.should.eql('string'); schema.attributes.name.isSet.should.not.be.ok; should.not.exist(schema.attributes.name.default); should.not.exist(schema.attributes.name.validator); should(schema.attributes.name.required).not.be.ok; schema.hashKey.should.equal(schema.attributes.id); // should be same object should.not.exist(schema.rangeKey); var kitten = new Cat( { id: 1, name: 'Fluffy', vet:{name:'theVet', address:'12 somewhere'}, ears:[{name:'left'}, {name:'right'}], legs: ['front right', 'front left', 'back right', 'back left'], more: {fovorites: {food: 'fish'}}, array: [{one: '1'}] } ); kitten.id.should.eql(1); kitten.name.should.eql('Fluffy'); var dynamoObj = schema.toDynamo(kitten); dynamoObj.should.eql( { ears: { L: [ { M: { name: { S: 'left' } } }, { M: { name: { S: 'right' } } } ] }, id: { N: '1' }, name: { S: 'Fluffy' }, vet: { M: { address: { S: '12 somewhere' }, name: { S: 'theVet' } } }, legs: { SS: ['front right', 'front left', 'back right', 'back left']}, more: { S: '{"fovorites":{"food":"fish"}}' }, array: { S: '[{"one":"1"}]' } }); kitten.save(done); }); it('Create simple model with range key', function () { Cat2.should.have.property('$__'); Cat2.$__.name.should.eql('test-Cat2'); Cat2.$__.options.should.have.property('create', true); var schema = Cat2.$__.schema; should.exist(schema); schema.attributes.ownerId.type.name.should.eql('number'); should(schema.attributes.ownerId.isSet).not.be.ok; should.not.exist(schema.attributes.ownerId.default); should.not.exist(schema.attributes.ownerId.validator); should(schema.attributes.ownerId.required).not.be.ok; schema.attributes.name.type.name.should.eql('string'); schema.attributes.name.isSet.should.not.be.ok; should.not.exist(schema.attributes.name.default); should.not.exist(schema.attributes.name.validator); should(schema.attributes.name.required).not.be.ok; schema.hashKey.should.equal(schema.attributes.ownerId); // should be same object schema.rangeKey.should.equal(schema.attributes.name); }); it('Get item for model', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.should.have.property('id', 1); model.should.have.property('name', 'Fluffy'); model.should.have.property('vet', { address: '12 somewhere', name: 'theVet' }); model.should.have.property('$__'); done(); }); }); it('Save existing item', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Fluffy'); model.name = 'Bad Cat'; model.vet.name = 'Tough Vet'; model.ears[0].name = 'right'; model.save(function (err) { should.not.exist(err); Cat.get({id: 1}, {consistent: true}, function(err, badCat) { should.not.exist(err); badCat.name.should.eql('Bad Cat'); badCat.vet.name.should.eql('Tough Vet'); badCat.ears[0].name.should.eql('right'); badCat.ears[1].name.should.eql('right'); done(); }); }); }); }); it('Save existing item with a false condition', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Bad Cat'); model.name = 'Whiskers'; model.save({ condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Muffin' } }, function (err) { should.exist(err); err.code.should.eql('ConditionalCheckFailedException'); Cat.get({id: 1}, {consistent: true}, function(err, badCat) { should.not.exist(err); badCat.name.should.eql('Bad Cat'); done(); }); }); }); }); it('Save existing item with a true condition', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Bad Cat'); model.name = 'Whiskers'; model.save({ condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Bad Cat' } }, function (err) { should.not.exist(err); Cat.get({id: 1}, {consistent: true}, function(err, whiskers) { should.not.exist(err); whiskers.name.should.eql('Whiskers'); done(); }); }); }); }); it('Save with a pre hook', function (done) { var flag = false; Cat.pre('save', function (next) { flag = true; next(); }); Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Whiskers'); model.name = 'Fluffy'; model.vet.name = 'Nice Guy'; model.save(function (err) { should.not.exist(err); Cat.get({id: 1}, {consistent: true}, function(err, badCat) { should.not.exist(err); badCat.name.should.eql('Fluffy'); badCat.vet.name.should.eql('Nice Guy'); flag.should.be.true; Cat.removePre('save'); done(); }); }); }); }); it('Deletes item', function (done) { var cat = new Cat({id: 1}); cat.delete(done); }); it('Get missing item', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.not.exist(model); done(); }); }); it('Static Creates new item', function (done) { Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { should.not.exist(err); should.exist(garfield); garfield.id.should.eql(666); done(); }); }); it('Static Creates new item with range key', function (done) { Cat2.create({ownerId: 666, name: 'Garfield'}, function (err, garfield) { should.not.exist(err); should.exist(garfield); garfield.ownerId.should.eql(666); done(); }); }); it('Prevent duplicate create', function (done) { Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { should.exist(err); should.not.exist(garfield); done(); }); }); it('Prevent duplicate create with range key', function (done) { Cat2.create({ownerId: 666, name: 'Garfield'}, function (err, garfield) { should.exist(err); should.not.exist(garfield); done(); }); }); it('Static Creates second item', function (done) { Cat.create({id: 777, name: 'Catbert'}, function (err, catbert) { should.not.exist(err); should.exist(catbert); catbert.id.should.eql(777); done(); }); }); it('BatchGet items', function (done) { Cat.batchGet([{id: 666}, {id: 777}], function (err, cats) { cats.length.should.eql(2); done(); }); }); it('Static Delete', function (done) { Cat.delete(666, function (err) { should.not.exist(err); Cat.get(666, function (err, delCat) { should.not.exist(err); should.not.exist(delCat); Cat.delete(777, done); }); }); }); it('Static Delete with range key', function (done) { Cat2.delete({ ownerId: 666, name: 'Garfield' }, function (err) { should.not.exist(err); Cat2.get({ ownerId: 666, name: 'Garfield' }, function (err, delCat) { should.not.exist(err); should.not.exist(delCat); done(); }); }); }); it('Static Creates new item', function (done) { Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { should.not.exist(err); should.exist(garfield); garfield.id.should.eql(666); done(); }); }); it('Static Delete with update', function (done) { Cat.delete(666, { update: true }, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(666); data.name.should.eql('Garfield'); Cat.get(666, function (err, delCat) { should.not.exist(err); should.not.exist(delCat); done(); }); }); }); it('Static Delete with update failure', function (done) { Cat.delete(666, { update: true }, function (err) { should.exist(err); err.statusCode.should.eql(400); err.code.should.eql('ConditionalCheckFailedException'); done(); }); }); describe('Model.update', function (){ before(function (done) { var stray = new Cat({id: 999, name: 'Tom'}); stray.save(done); }); it('False condition', function (done) { Cat.update({id: 999}, {name: 'Oliver'}, { condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Muffin' } }, function (err) { should.exist(err); Cat.get(999, function (err, tomcat) { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); should.not.exist(tomcat.owner); should.not.exist(tomcat.age); done(); }); }); }); it('True condition', function (done) { Cat.update({id: 999}, {name: 'Oliver'}, { condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Tom' } }, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.name.should.equal('Oliver'); Cat.get(999, function (err, oliver) { should.not.exist(err); should.exist(oliver); oliver.id.should.eql(999); oliver.name.should.eql('Oliver'); should.not.exist(oliver.owner); should.not.exist(oliver.age); done(); }); }); }); it('Default puts attribute', function (done) { Cat.update({id: 999}, {name: 'Tom'}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.name.should.equal('Tom'); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); should.not.exist(tomcat.owner); should.not.exist(tomcat.age); done(); }); }); }); it('Manual puts attribute with removal', function (done) { Cat.update({id: 999}, {$PUT: {name: null}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); should.not.exist(data.name); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); should.not.exist(tomcat.name); done(); }); }); }); it('Manual puts attribute', function (done) { Cat.update({id: 999}, {$PUT: {name: 'Tom', owner: 'Jerry', age: 3}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.owner.should.equal('Jerry'); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); tomcat.owner.should.eql('Jerry'); tomcat.age.should.eql(3); done(); }); }); }); it('Add attribute', function (done) { Cat.update({id: 999}, {$ADD: {age: 1}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.age.should.equal(4); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); tomcat.owner.should.eql('Jerry'); tomcat.age.should.eql(4); done(); }); }); }); it('Delete attribute', function (done) { Cat.update({id: 999}, {$DELETE: {owner: null}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); should.not.exist(data.owner); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); should.not.exist(tomcat.owner); tomcat.age.should.eql(4); done(); }); }); }); }); describe('Model.batchPut', function (){ it('Put new', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat({id: 10+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); for (var i=0 ; i<10 ; ++i) { delete cats[i].name; } Cat.batchGet(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); done(); }); }); }); it('Put lots of new items', function (done) { var cats = []; for (var i=0 ; i<100 ; ++i) { cats.push(new Cat({id: 100+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); for (var i=0 ; i<100 ; ++i) { delete cats[i].name; } Cat.batchGet(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); done(); }); }); }); it('Put new with range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 10+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); Cat2.batchGet(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); done(); }); }); }); it('Put new without range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 10+i})); } Cat2.batchPut(cats, function (err, result) { should.exist(err); should.not.exist(result); done(); }); }); it('Update items', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat({id: 20+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { var cat = cats[i]; cat.name = 'John_' + (cat.id + 100); } Cat.batchPut(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); for (var i=0 ; i<10 ; ++i) { delete cats[i].name; } Cat.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(cats.length); done(); }); }); }); }); it('Update with range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 20+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { var cat = cats[i]; cat.name = 'John_' + (cat.ownerId + 100); } Cat2.batchPut(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); Cat2.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(cats.length); done(); }); }); }); }); it('Update without range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 20+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { cats[i].name = null; } Cat2.batchPut(cats, function (err2, result2) { should.exist(err2); should.not.exist(result2); done(); }); }); }); }); describe('Model.batchDelete', function (){ it('Simple delete', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat({id: 30+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Cat.batchDelete(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); Cat.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(0); done(); }); }); }); }); it('Delete with range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 30+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Cat2.batchDelete(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); Cat2.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(0); done(); }); }); }); }); it('Delete without range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 30+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { delete cats[i].name; } Cat2.batchDelete(cats, function (err2, result2) { should.exist(err2); should.not.exist(result2); done(); }); }); }); }); });
benjcooley/dynamoose
test/Model.js
JavaScript
mit
21,235
# -*- coding: utf-8 -*- import os import sys try: from gluon import current except ImportError: print >> sys.stderr, """ The installed version of Web2py is too old -- it does not define current. Please upgrade Web2py to a more recent version. """ # Version of 000_config.py # Increment this if the user should update their running instance VERSION = 1 #def update_check(environment, template="default"): def update_check(settings): """ Check whether the dependencies are sufficient to run Eden @ToDo: Load deployment_settings so that we can configure the update_check - need to rework so that 000_config.py is parsed 1st @param settings: the deployment_settings """ # Get Web2py environment into our globals. #globals().update(**environment) request = current.request # Fatal errors errors = [] # Non-fatal warnings warnings = [] # ------------------------------------------------------------------------- # Check Python libraries # Get mandatory global dependencies app_path = request.folder gr_path = os.path.join(app_path, "requirements.txt") or_path = os.path.join(app_path, "optional_requirements.txt") global_dep = parse_requirements({}, gr_path) optional_dep = parse_requirements({}, or_path) templates = settings.get_template() location = settings.get_template_location() if not isinstance(templates, (tuple, list)): templates = (templates,) template_dep = {} template_optional_dep = {} for template in templates: tr_path = os.path.join(app_path, location, "templates", template, "requirements.txt") tor_path = os.path.join(app_path, location, "templates", template, "optional_requirements.txt") parse_requirements(template_dep, tr_path) parse_requirements(template_optional_dep, tor_path) # Remove optional dependencies which are already accounted for in template dependencies unique = set(optional_dep.keys()).difference(set(template_dep.keys())) for dependency in optional_dep.keys(): if dependency not in unique: del optional_dep[dependency] # Override optional dependency messages from template unique = set(optional_dep.keys()).difference(set(template_optional_dep.keys())) for dependency in optional_dep.keys(): if dependency not in unique: del optional_dep[dependency] errors, warnings = s3_check_python_lib(global_dep, template_dep, template_optional_dep, optional_dep) # @ToDo: Move these to Template # for now this is done in s3db.climate_first_run() if settings.has_module("climate"): if settings.get_database_type() != "postgres": errors.append("Climate unresolved dependency: PostgreSQL required") try: import rpy2 except ImportError: errors.append("Climate unresolved dependency: RPy2 required") try: from Scientific.IO import NetCDF except ImportError: warnings.append("Climate unresolved dependency: NetCDF required if you want to import readings") try: from scipy import stats except ImportError: warnings.append("Climate unresolved dependency: SciPy required if you want to generate graphs on the map") # ------------------------------------------------------------------------- # Check Web2Py version # # Currently, the minimum usable Web2py is determined by whether the # Scheduler is available web2py_minimum_version = "Version 2.4.7-stable+timestamp.2013.05.27.11.49.44" # Offset of datetime in return value of parse_version. datetime_index = 4 web2py_version_ok = True try: from gluon.fileutils import parse_version except ImportError: web2py_version_ok = False if web2py_version_ok: try: web2py_minimum_parsed = parse_version(web2py_minimum_version) web2py_minimum_datetime = web2py_minimum_parsed[datetime_index] web2py_installed_version = request.global_settings.web2py_version if isinstance(web2py_installed_version, str): # Post 2.4.2, request.global_settings.web2py_version is unparsed web2py_installed_parsed = parse_version(web2py_installed_version) web2py_installed_datetime = web2py_installed_parsed[datetime_index] else: # 2.4.2 & earlier style web2py_installed_datetime = web2py_installed_version[datetime_index] web2py_version_ok = web2py_installed_datetime >= web2py_minimum_datetime except: # Will get AttributeError if Web2py's parse_version is too old for # its current version format, which changed in 2.3.2. web2py_version_ok = False if not web2py_version_ok: warnings.append( "The installed version of Web2py is too old to support the current version of Sahana Eden." "\nPlease upgrade Web2py to at least version: %s" % \ web2py_minimum_version) # ------------------------------------------------------------------------- # Create required directories if needed databases_dir = os.path.join(app_path, "databases") try: os.stat(databases_dir) except OSError: # not found, create it os.mkdir(databases_dir) # ------------------------------------------------------------------------- # Copy in Templates # - 000_config.py (machine-specific settings) # - rest are run in-place # template_folder = os.path.join(app_path, "modules", "templates") template_files = { # source : destination "000_config.py" : os.path.join("models", "000_config.py"), } copied_from_template = [] for t in template_files: src_path = os.path.join(template_folder, t) dst_path = os.path.join(app_path, template_files[t]) try: os.stat(dst_path) except OSError: # Not found, copy from template if t == "000_config.py": input = open(src_path) output = open(dst_path, "w") for line in input: if "akeytochange" in line: # Generate a random hmac_key to secure the passwords in case # the database is compromised import uuid hmac_key = uuid.uuid4() line = 'settings.auth.hmac_key = "%s"' % hmac_key output.write(line) output.close() input.close() else: import shutil shutil.copy(src_path, dst_path) copied_from_template.append(template_files[t]) # @ToDo: WebSetup # http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/WebSetup #if not os.path.exists("%s/applications/websetup" % os.getcwd()): # # @ToDo: Check Permissions # # Copy files into this folder (@ToDo: Pythonise) # cp -r private/websetup "%s/applications" % os.getcwd() # Launch WebSetup #redirect(URL(a="websetup", c="default", f="index", # vars=dict(appname=request.application, # firstTime="True"))) else: # Found the file in the destination # Check if it has been edited import re edited_pattern = r"FINISHED_EDITING_\w*\s*=\s*(True|False)" edited_matcher = re.compile(edited_pattern).match has_edited = False with open(dst_path) as f: for line in f: edited_result = edited_matcher(line) if edited_result: has_edited = True edited = edited_result.group(1) break if has_edited and (edited != "True"): errors.append("Please edit %s before starting the system." % t) # Check if it's up to date (i.e. a critical update requirement) version_pattern = r"VERSION =\s*([0-9]+)" version_matcher = re.compile(version_pattern).match has_version = False with open(dst_path) as f: for line in f: version_result = version_matcher(line) if version_result: has_version = True version = version_result.group(1) break if not has_version: error = "Your %s is using settings from the old templates system. Please switch to the new templates system: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Templates" % t errors.append(error) elif int(version) != VERSION: error = "Your %s is using settings from template version %s. Please update with new settings from template version %s before starting the system." % \ (t, version, VERSION) errors.append(error) if copied_from_template: errors.append( "The following files were copied from templates and should be edited: %s" % ", ".join(copied_from_template)) return {"error_messages": errors, "warning_messages": warnings} # ------------------------------------------------------------------------- def parse_requirements(output, filepath): """ """ try: with open(filepath) as filehandle: dependencies = filehandle.read().splitlines() msg = "" for dependency in dependencies: if dependency[0] == "#": # either a normal comment or custom message if dependency[:9] == "# Warning" or dependency[7] == "# Error:": msg = dependency.split(":", 1)[1] else: import re # Check if the module name is different from the package name if "#" in dependency: dep = dependency.split("#", 1)[1] output[dep] = msg else: pattern = re.compile(r'([A-Za-z0-9_-]+)') try: dep = pattern.match(dependency).group(1) output[dep] = msg except AttributeError: # Invalid dependency syntax pass msg = "" except IOError: # No override for Template pass return output # ------------------------------------------------------------------------- def s3_check_python_lib(global_mandatory, template_mandatory, template_optional, global_optional): """ checks for optional as well as mandatory python libraries """ errors = [] warnings = [] for dependency, err in global_mandatory.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if err: errors.append(err) else: errors.append("S3 unresolved dependency: %s required for Sahana to run" % dependency) for dependency, err in template_mandatory.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if err: errors.append(err) else: errors.append("Unresolved template dependency: %s required" % dependency) for dependency, warn in template_optional.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if warn: warnings.append(warn) else: warnings.append("Unresolved optional dependency: %s required" % dependency) for dependency, warn in global_optional.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if warn: warnings.append(warn) else: warnings.append("Unresolved optional dependency: %s required" % dependency) return errors, warnings # END =========================================================================
sahana/Turkey
modules/s3_update_check.py
Python
mit
13,160
import _curry3 from './internal/_curry3.js'; /** * Move an item, at index `from`, to index `to`, in a list of elements. * A new list will be created containing the new elements order. * * @func * @memberOf R * @since v0.27.1 * @category List * @sig Number -> Number -> [a] -> [a] * @param {Number} from The source index * @param {Number} to The destination index * @param {Array} list The list which will serve to realise the move * @return {Array} The new list reordered * @example * * R.move(0, 2, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['b', 'c', 'a', 'd', 'e', 'f'] * R.move(-1, 0, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['f', 'a', 'b', 'c', 'd', 'e'] list rotation */ var move = _curry3(function(from, to, list) { var length = list.length; var result = list.slice(); var positiveFrom = from < 0 ? length + from : from; var positiveTo = to < 0 ? length + to : to; var item = result.splice(positiveFrom, 1); return positiveFrom < 0 || positiveFrom >= list.length || positiveTo < 0 || positiveTo >= list.length ? list : [] .concat(result.slice(0, positiveTo)) .concat(item) .concat(result.slice(positiveTo, list.length)); }); export default move;
CrossEye/ramda
source/move.js
JavaScript
mit
1,225
package net.jsunit; import java.io.IOException; public class MockProcessStarter implements ProcessStarter { public String[] commandPassed; public Process execute(String[] command) throws IOException { this.commandPassed = command; return null; } }
wesmaldonado/test-driven-javascript-example-application
public/js-common/jsunit/java/tests_server/net/jsunit/MockProcessStarter.java
Java
mit
295
using System; using System.Reactive.Threading.Tasks; using Octokit.Reactive.Internal; namespace Octokit.Reactive { public class ObservableCommitStatusClient : IObservableCommitStatusClient { readonly ICommitStatusClient _client; readonly IConnection _connection; public ObservableCommitStatusClient(IGitHubClient client) { Ensure.ArgumentNotNull(client, "client"); _client = client.Repository.CommitStatus; _connection = client.Connection; } /// <summary> /// Retrieves commit statuses for the specified reference. A reference can be a commit SHA, a branch name, or /// a tag name. /// </summary> /// <remarks>Only users with pull access can see this.</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="reference">The reference (SHA, branch name, or tag name) to list commits for</param> /// <returns></returns> public IObservable<CommitStatus> GetAll(string owner, string name, string reference) { return _connection.GetAndFlattenAllPages<CommitStatus>(ApiUrls.CommitStatus(owner, name, reference)); } /// <summary> /// Creates a commit status for the specified ref. /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="reference">The reference (SHA, branch name, or tag name) to list commits for</param> /// <param name="commitStatus">The commit status to create</param> /// <returns></returns> public IObservable<CommitStatus> Create(string owner, string name, string reference, NewCommitStatus commitStatus) { return _client.Create(owner, name, reference, commitStatus).ToObservable(); } } }
senlinsky/octokit.net
Octokit.Reactive/Clients/ObservableCommitStatusClient.cs
C#
mit
1,991
//----------------------------------------------------------------------- // <copyright file="DataPortalHookArgs.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary></summary> // <remarks>Generated file.</remarks> //----------------------------------------------------------------------- using System.Data; using System.Data.Common; using Csla.Data; namespace ActionExtenderSample.Business { /// <summary> /// Event arguments for the DataPortalHook.<br/> /// This class holds the arguments for events that happen during DataPortal operations. /// </summary> public class DataPortalHookArgs { #region Properties /// <summary> /// Gets or sets the criteria argument. /// </summary> /// <value>The criteria object.</value> public object CriteriaArg { get; private set; } /// <summary> /// Gets or sets the connection argument. /// </summary> /// <value>The connection.</value> public DbConnection ConnectionArg { get; private set; } /// <summary> /// Gets or sets the command argument. /// </summary> /// <value>The command.</value> public DbCommand CommandArg { get; private set; } /// <summary> /// Gets or sets the ADO transaction argument. /// </summary> /// <value>The ADO transaction.</value> public DbTransaction TransactionArg { get; private set; } /// <summary> /// Gets or sets the data reader argument. /// </summary> /// <value>The data reader.</value> public SafeDataReader DataReaderArg { get; private set; } /// <summary> /// Gets or sets the data row argument. /// </summary> /// <value>The data row.</value> public DataRow DataRowArg { get; private set; } /// <summary> /// Gets or sets the data set argument. /// </summary> /// <value>The data set.</value> public DataSet DataSetArg { get; private set; } #endregion #region Constructor /// <summary> /// Initializes a new empty instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> public DataPortalHookArgs() { } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="crit">The criteria object argument.</param> public DataPortalHookArgs(object crit) { CriteriaArg = crit; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="cmd">The command argument.</param> /// <remarks>The connection and ADO transaction arguments are set automatically, based on the command argument.</remarks> public DataPortalHookArgs(DbCommand cmd) { CommandArg = cmd; ConnectionArg = cmd.Connection; TransactionArg = cmd.Transaction; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="cmd">The command argument.</param> /// <param name="crit">The criteria argument.</param> /// <remarks>The connection and ADO transaction arguments are set automatically, based on the command argument.</remarks> public DataPortalHookArgs(DbCommand cmd, object crit) : this(cmd) { CriteriaArg = crit; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="dr">The SafeDataReader argument.</param> public DataPortalHookArgs(SafeDataReader dr) { DataReaderArg = dr; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="cmd">The command argument.</param> /// <param name="dr">The SafeDataReader argument.</param> /// <remarks>The connection and ADO transaction arguments are set automatically, based on the command argument.</remarks> public DataPortalHookArgs(DbCommand cmd, SafeDataReader dr) : this(cmd) { DataReaderArg = dr; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="cmd">The command argument.</param> /// <param name="ds">The DataSet argument.</param> /// <remarks>The connection and ADO transaction arguments are set automatically, based on the command argument.</remarks> public DataPortalHookArgs(DbCommand cmd, DataSet ds) : this(cmd) { DataSetArg = ds; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="dr">The data row argument.</param> public DataPortalHookArgs(DataRow dr) { DataRowArg = dr; } #endregion } }
MarimerLLC/cslacontrib
trunk/samples/ActionExtenderSample/ActionExtenderSample.Business/DataPortalHookArgs.cs
C#
mit
4,899
(function () { 'use strict'; angular.module('mPlatform.directives') .directive('ngTextChange', function () { return { restrict: 'A', replace: 'ngModel', link: function (scope, element, attr) { element.on('change', function () { scope.$apply(function () { scope.$eval(attr.ngTextChange); }); }); } }; }); })();
michaelmarriott/LabyrinthRipper.Mobile
www/scripts/ang/directives.js
JavaScript
mit
540
Astro.createValidator = function(validatorDefinition) { var definition = new ValidatorDefinition(validatorDefinition); var validatorGenerator = function(options, userMessage) { var validator = function(fieldValue, fieldName) { return validator.definition.validate.call( this, fieldValue, fieldName, options, // Validator options passed by user. validator // Parent validator. ); }; _.extend(validator, { definition: definition, options: options, message: userMessage }); return validator; }; // Validator is just a function with the "definition" property where all the // validator definition is stored. Validators[definition.name] = validatorGenerator; // We also return created validator if someone would like not to use long // default namespace which is e.g. `Validators.isString`. return validatorGenerator; };
ribbedcrown/meteor-astronomy-validators
lib/module/validator.js
JavaScript
mit
929
import _Object$getOwnPropertySymbols from "../../core-js/object/get-own-property-symbols"; import _Object$keys from "../../core-js/object/keys"; export default function _objectWithoutProperties(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]; } 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; }
Skillupco/babel
packages/babel-runtime/helpers/es6/objectWithoutProperties.js
JavaScript
mit
854
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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. */ module powerbi.data { export interface CompiledDataViewMapping { metadata: CompiledDataViewMappingMetadata; categorical?: CompiledDataViewCategoricalMapping; table?: CompiledDataViewTableMapping; single?: CompiledDataViewSingleMapping; tree?: CompiledDataViewTreeMapping; matrix?: CompiledDataViewMatrixMapping; } export interface CompiledDataViewMappingMetadata { /** The metadata repetition objects. */ objects?: DataViewObjects; } export interface CompiledDataViewCategoricalMapping { categories?: CompiledDataViewRoleMappingWithReduction; values?: CompiledDataViewRoleMapping | CompiledDataViewGroupedRoleMapping | CompiledDataViewListRoleMapping; } export interface CompiledDataViewGroupingRoleMapping { role: CompiledDataViewRole } export interface CompiledDataViewSingleMapping { role: CompiledDataViewRole; } export interface CompiledDataViewValuesRoleMapping { roles: CompiledDataViewRole[]; } export interface CompiledDataViewTableMapping { rows: CompiledDataViewRoleMappingWithReduction | CompiledDataViewListRoleMappingWithReduction; } export interface CompiledDataViewTreeMapping { nodes?: CompiledDataViewGroupingRoleMapping values?: CompiledDataViewValuesRoleMapping } export interface CompiledDataViewMatrixMapping { rows?: CompiledDataViewRoleForMappingWithReduction; columns?: CompiledDataViewRoleForMappingWithReduction; values?: CompiledDataViewRoleForMapping; } export type CompiledDataViewRoleMapping = CompiledDataViewRoleBindMapping | CompiledDataViewRoleForMapping; export interface CompiledDataViewRoleBindMapping { bind: { to: CompiledDataViewRole; }; } export interface CompiledDataViewRoleForMapping { for: { in: CompiledDataViewRole; }; } export type CompiledDataViewRoleMappingWithReduction = CompiledDataViewRoleBindMappingWithReduction | CompiledDataViewRoleForMappingWithReduction; export interface CompiledDataViewRoleBindMappingWithReduction extends CompiledDataViewRoleBindMapping, HasReductionAlgorithm { } export interface CompiledDataViewRoleForMappingWithReduction extends CompiledDataViewRoleForMapping, HasReductionAlgorithm { } export interface CompiledDataViewGroupedRoleMapping { group: { by: CompiledDataViewRole; select: CompiledDataViewRoleMapping[]; dataReductionAlgorithm?: ReductionAlgorithm; }; } export interface CompiledDataViewListRoleMapping { select: CompiledDataViewRoleMapping[]; } export interface CompiledDataViewListRoleMappingWithReduction extends CompiledDataViewListRoleMapping, HasReductionAlgorithm { } export enum CompiledSubtotalType { None = 0, Before = 1, After = 2 } export interface CompiledDataViewRole { role: string; items: CompiledDataViewRoleItem[]; subtotalType?: CompiledSubtotalType; } export interface CompiledDataViewRoleItem { type?: ValueType; } }
sgrebnov/PowerBI-visuals
src/Clients/Data/dataView/compiledDataViewMapping.ts
TypeScript
mit
4,466
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.block.tiles; import net.minecraft.tileentity.TileEntityDaylightDetector; import org.spongepowered.api.block.tileentity.DaylightDetector; import org.spongepowered.asm.mixin.Mixin; @Mixin(TileEntityDaylightDetector.class) public abstract class MixinTileEntityDaylightDetector extends MixinTileEntity implements DaylightDetector { }
kashike/SpongeCommon
src/main/java/org/spongepowered/common/mixin/core/block/tiles/MixinTileEntityDaylightDetector.java
Java
mit
1,625
'use strict'; import $ from 'jquery'; import { Keyboard } from './foundation.util.keyboard'; import { GetYoDigits } from './foundation.util.core'; import { Positionable } from './foundation.positionable'; import { Triggers } from './foundation.util.triggers'; /** * Dropdown module. * @module foundation.dropdown * @requires foundation.util.keyboard * @requires foundation.util.box * @requires foundation.util.triggers */ class Dropdown extends Positionable { /** * Creates a new instance of a dropdown. * @class * @name Dropdown * @param {jQuery} element - jQuery object to make into a dropdown. * Object should be of the dropdown panel, rather than its anchor. * @param {Object} options - Overrides to the default plugin settings. */ _setup(element, options) { this.$element = element; this.options = $.extend({}, Dropdown.defaults, this.$element.data(), options); this.className = 'Dropdown'; // ie9 back compat // Triggers init is idempotent, just need to make sure it is initialized Triggers.init($); this._init(); Keyboard.register('Dropdown', { 'ENTER': 'open', 'SPACE': 'open', 'ESCAPE': 'close' }); } /** * Initializes the plugin by setting/checking options and attributes, adding helper variables, and saving the anchor. * @function * @private */ _init() { var $id = this.$element.attr('id'); this.$anchors = $(`[data-toggle="${$id}"]`).length ? $(`[data-toggle="${$id}"]`) : $(`[data-open="${$id}"]`); this.$anchors.attr({ 'aria-controls': $id, 'data-is-focus': false, 'data-yeti-box': $id, 'aria-haspopup': true, 'aria-expanded': false }); this._setCurrentAnchor(this.$anchors.first()); if(this.options.parentClass){ this.$parent = this.$element.parents('.' + this.options.parentClass); }else{ this.$parent = null; } this.$element.attr({ 'aria-hidden': 'true', 'data-yeti-box': $id, 'data-resize': $id, 'aria-labelledby': this.$currentAnchor.id || GetYoDigits(6, 'dd-anchor') }); super._init(); this._events(); } _getDefaultPosition() { // handle legacy classnames var position = this.$element[0].className.match(/(top|left|right|bottom)/g); if(position) { return position[0]; } else { return 'bottom' } } _getDefaultAlignment() { // handle legacy float approach var horizontalPosition = /float-(\S+)/.exec(this.$currentAnchor.className); if(horizontalPosition) { return horizontalPosition[1]; } return super._getDefaultAlignment(); } /** * Sets the position and orientation of the dropdown pane, checks for collisions if allow-overlap is not true. * Recursively calls itself if a collision is detected, with a new position class. * @function * @private */ _setPosition() { this.$element.removeClass(`has-position-${this.position} has-alignment-${this.alignment}`); super._setPosition(this.$currentAnchor, this.$element, this.$parent); this.$element.addClass(`has-position-${this.position} has-alignment-${this.alignment}`); } /** * Make it a current anchor. * Current anchor as the reference for the position of Dropdown panes. * @param {HTML} el - DOM element of the anchor. * @function * @private */ _setCurrentAnchor(el) { this.$currentAnchor = $(el); } /** * Adds event listeners to the element utilizing the triggers utility library. * @function * @private */ _events() { var _this = this; this.$element.on({ 'open.zf.trigger': this.open.bind(this), 'close.zf.trigger': this.close.bind(this), 'toggle.zf.trigger': this.toggle.bind(this), 'resizeme.zf.trigger': this._setPosition.bind(this) }); this.$anchors.off('click.zf.trigger') .on('click.zf.trigger', function() { _this._setCurrentAnchor(this); }); if(this.options.hover){ this.$anchors.off('mouseenter.zf.dropdown mouseleave.zf.dropdown') .on('mouseenter.zf.dropdown', function(){ _this._setCurrentAnchor(this); var bodyData = $('body').data(); if(typeof(bodyData.whatinput) === 'undefined' || bodyData.whatinput === 'mouse') { clearTimeout(_this.timeout); _this.timeout = setTimeout(function(){ _this.open(); _this.$anchors.data('hover', true); }, _this.options.hoverDelay); } }).on('mouseleave.zf.dropdown', function(){ clearTimeout(_this.timeout); _this.timeout = setTimeout(function(){ _this.close(); _this.$anchors.data('hover', false); }, _this.options.hoverDelay); }); if(this.options.hoverPane){ this.$element.off('mouseenter.zf.dropdown mouseleave.zf.dropdown') .on('mouseenter.zf.dropdown', function(){ clearTimeout(_this.timeout); }).on('mouseleave.zf.dropdown', function(){ clearTimeout(_this.timeout); _this.timeout = setTimeout(function(){ _this.close(); _this.$anchors.data('hover', false); }, _this.options.hoverDelay); }); } } this.$anchors.add(this.$element).on('keydown.zf.dropdown', function(e) { var $target = $(this), visibleFocusableElements = Keyboard.findFocusable(_this.$element); Keyboard.handleKey(e, 'Dropdown', { open: function() { if ($target.is(_this.$anchors)) { _this.open(); _this.$element.attr('tabindex', -1).focus(); e.preventDefault(); } }, close: function() { _this.close(); _this.$anchors.focus(); } }); }); } /** * Adds an event handler to the body to close any dropdowns on a click. * @function * @private */ _addBodyHandler() { var $body = $(document.body).not(this.$element), _this = this; $body.off('click.zf.dropdown') .on('click.zf.dropdown', function(e){ if(_this.$anchors.is(e.target) || _this.$anchors.find(e.target).length) { return; } if(_this.$element.is(e.target) || _this.$element.find(e.target).length) { return; } _this.close(); $body.off('click.zf.dropdown'); }); } /** * Opens the dropdown pane, and fires a bubbling event to close other dropdowns. * @function * @fires Dropdown#closeme * @fires Dropdown#show */ open() { // var _this = this; /** * Fires to close other open dropdowns, typically when dropdown is opening * @event Dropdown#closeme */ this.$element.trigger('closeme.zf.dropdown', this.$element.attr('id')); this.$anchors.addClass('hover') .attr({'aria-expanded': true}); // this.$element/*.show()*/; this.$element.addClass('is-opening'); this._setPosition(); this.$element.removeClass('is-opening').addClass('is-open') .attr({'aria-hidden': false}); if(this.options.autoFocus){ var $focusable = Keyboard.findFocusable(this.$element); if($focusable.length){ $focusable.eq(0).focus(); } } if(this.options.closeOnClick){ this._addBodyHandler(); } if (this.options.trapFocus) { Keyboard.trapFocus(this.$element); } /** * Fires once the dropdown is visible. * @event Dropdown#show */ this.$element.trigger('show.zf.dropdown', [this.$element]); } /** * Closes the open dropdown pane. * @function * @fires Dropdown#hide */ close() { if(!this.$element.hasClass('is-open')){ return false; } this.$element.removeClass('is-open') .attr({'aria-hidden': true}); this.$anchors.removeClass('hover') .attr('aria-expanded', false); /** * Fires once the dropdown is no longer visible. * @event Dropdown#hide */ this.$element.trigger('hide.zf.dropdown', [this.$element]); if (this.options.trapFocus) { Keyboard.releaseFocus(this.$element); } } /** * Toggles the dropdown pane's visibility. * @function */ toggle() { if(this.$element.hasClass('is-open')){ if(this.$anchors.data('hover')) return; this.close(); }else{ this.open(); } } /** * Destroys the dropdown. * @function */ _destroy() { this.$element.off('.zf.trigger').hide(); this.$anchors.off('.zf.dropdown'); $(document.body).off('click.zf.dropdown'); } } Dropdown.defaults = { /** * Class that designates bounding container of Dropdown (default: window) * @option * @type {?string} * @default null */ parentClass: null, /** * Amount of time to delay opening a submenu on hover event. * @option * @type {number} * @default 250 */ hoverDelay: 250, /** * Allow submenus to open on hover events * @option * @type {boolean} * @default false */ hover: false, /** * Don't close dropdown when hovering over dropdown pane * @option * @type {boolean} * @default false */ hoverPane: false, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @type {number} * @default 0 */ vOffset: 0, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @type {number} * @default 0 */ hOffset: 0, /** * DEPRECATED: Class applied to adjust open position. * @option * @type {string} * @default '' */ positionClass: '', /** * Position of dropdown. Can be left, right, bottom, top, or auto. * @option * @type {string} * @default 'auto' */ position: 'auto', /** * Alignment of dropdown relative to anchor. Can be left, right, bottom, top, center, or auto. * @option * @type {string} * @default 'auto' */ alignment: 'auto', /** * Allow overlap of container/window. If false, dropdown will first try to position as defined by data-position and data-alignment, but reposition if it would cause an overflow. * @option * @type {boolean} * @default false */ allowOverlap: false, /** * Allow overlap of only the bottom of the container. This is the most common * behavior for dropdowns, allowing the dropdown to extend the bottom of the * screen but not otherwise influence or break out of the container. * @option * @type {boolean} * @default true */ allowBottomOverlap: true, /** * Allow the plugin to trap focus to the dropdown pane if opened with keyboard commands. * @option * @type {boolean} * @default false */ trapFocus: false, /** * Allow the plugin to set focus to the first focusable element within the pane, regardless of method of opening. * @option * @type {boolean} * @default false */ autoFocus: false, /** * Allows a click on the body to close the dropdown. * @option * @type {boolean} * @default false */ closeOnClick: false } export {Dropdown};
robertgraleigh/supreme-journey
node_modules/foundation-sites/js/foundation.dropdown.js
JavaScript
mit
11,158
<?php namespace Elastica\Filter; /** * Type Filter * * @category Xodoa * @package Elastica * @author James Wilson <jwilson556@gmail.com> * @link http://www.elasticsearch.org/guide/reference/query-dsl/type-filter.html */ class Type extends AbstractFilter { /** * Type name * * @var string */ protected $_type = null; /** * Construct Type Filter * * @param string $typeName Type name * @return \Elastica\Filter\Type */ public function __construct($typeName = null) { if ($typeName) { $this->setType($typeName); } } /** * Ads a field with arguments to the range query * * @param string $typeName Type name * @return \Elastica\Filter\Type current object */ public function setType($typeName) { $this->_type = $typeName; return $this; } /** * Convert object to array * * @see \Elastica\Filter\AbstractFilter::toArray() * @return array Filter array */ public function toArray() { return array( 'type' => array('value' => $this->_type), ); } }
didix16/snackhelper
vendor/ruflin/elastica/lib/Elastica/Filter/Type.php
PHP
mit
1,205
__title__ = 'pif.exceptions' __author__ = 'Artur Barseghyan' __copyright__ = 'Copyright (c) 2013 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('InvalidRegistryItemType',) class InvalidRegistryItemType(ValueError): """ Raised when an attempt is made to register an item in the registry which does not have a proper type. """
djabber/Dashboard
bottle/dash/local/lib/pif-0.7/src/pif/exceptions.py
Python
mit
352
import {EntitySubscriberInterface} from "../../../../src/subscriber/EntitySubscriberInterface"; import {EventSubscriber} from "../../../../src/decorator/listeners/EventSubscriber"; import {InsertEvent} from "../../../../src/subscriber/event/InsertEvent"; @EventSubscriber() export class FirstConnectionSubscriber implements EntitySubscriberInterface<any> { /** * Called after entity insertion. */ beforeInsert(event: InsertEvent<any>) { console.log(`BEFORE ENTITY INSERTED: `, event.entity); } }
ReaxDev/typeorm
test/functional/connection/subscriber/FirstConnectionSubscriber.ts
TypeScript
mit
532
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceBus.Messaging; using Nimbus.Extensions; namespace Nimbus.Infrastructure.MessageSendersAndReceivers { internal abstract class BatchingMessageSender : INimbusMessageSender { private const int _maxConcurrentFlushTasks = 10; private const int _maximumBatchSize = 100; private readonly List<BrokeredMessage> _outboundQueue = new List<BrokeredMessage>(); private bool _disposed; private readonly object _mutex = new object(); private readonly SemaphoreSlim _sendingSemaphore = new SemaphoreSlim(_maxConcurrentFlushTasks, _maxConcurrentFlushTasks); private Task _lazyFlushTask; protected abstract Task SendBatch(BrokeredMessage[] messages); public Task Send(BrokeredMessage message) { lock (_mutex) { _outboundQueue.Add(message); if (_outboundQueue.Count >= _maximumBatchSize) { return DoBatchSendNow(); } if (_lazyFlushTask == null) { _lazyFlushTask = FlushMessagesLazily(); } return _lazyFlushTask; } } private async Task FlushMessagesLazily() { if (_disposed) return; await Task.Delay(TimeSpan.FromMilliseconds(100)); // sleep *after* we grab a semaphore to allow messages to be batched _lazyFlushTask = null; await DoBatchSendNow(); } private async Task DoBatchSendNow() { await _sendingSemaphore.WaitAsync(); try { BrokeredMessage[] toSend; lock (_mutex) { toSend = _outboundQueue.Take(_maximumBatchSize).ToArray(); _outboundQueue.RemoveRange(0, toSend.Length); } if (toSend.None()) return; await SendBatch(toSend); GlobalMessageCounters.IncrementSentMessageCount(toSend.Length); } finally { _sendingSemaphore.Release(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { _disposed = true; } } }
rebase42/Anubus
src/Nimbus/Infrastructure/MessageSendersAndReceivers/BatchingMessageSender.cs
C#
mit
2,558
// import { createAction } from 'redux-actions'; //Actions: //Simulate loading
dgilroy77/Car.ly
src/actions/loadActions.js
JavaScript
mit
80
#include "render/action_renderer.h" #include "engine/cloak_system.h" #include "platform/auto_id.h" #include "platform/id_storage.h" #include "core/i_renderable_component.h" namespace render { ActionRenderer::~ActionRenderer() { } ActionRenderer::ActionRenderer( int32_t Id, int32_t ActionId ) : mId( Id ) , mActionId( ActionId == -1 ? AutoId( "idle" ) : ActionId ) , mSecsToEnd( 1.0 ) , mState( 0 ) , mRenderableRepo( RenderableRepo::Get() ) , mOrder( 0 ) { } void ActionRenderer::Init( const Actor& actor ) { int32_t actorId = actor.GetId(); auto renderableC( actor.Get<IRenderableComponent>() ); actorId = GetSpriteId( renderableC->GetSpriteIndex(), actorId ); SpriteCollection const& Sprites = mRenderableRepo( actorId ); Sprite const& Spr = Sprites( mActionId ); if( Spr.IsValid() ) { mSpr = &Spr; mSecsToEnd = Spr.GetSecsToEnd(); } mCompanionSprites = GetCompanionSprites( actorId, mActionId ); } glm::vec4 ActionRenderer::GetRenderableColor( Actor const& actor ) const { auto const& col = GetCloakColor( actor ) * GetColor( actor ); return col; } void ActionRenderer::FillRenderableSprites( const Actor& actor, IRenderableComponent const& renderableC, RenderableSprites_t& renderableSprites ) { if( nullptr == mSpr ) { return; } int32_t st( GetState() ); auto const& Phase = (*mSpr)( st ); auto const& col = GetRenderableColor( actor ); RenderableSprite rs( &actor, &renderableC, mActionId, mSpr, &Phase, col ); FillRenderableSprite( rs, mCompanionSprites, st ); renderableSprites.push_back( rs ); } void FillRenderableSprite( RenderableSprite& rs, CompanionSprites const& data, int32_t st ) { for( auto const& spr : data.AdditionalSprs ) { rs.AdditionalSprs.push_back( &(*spr)( st ) ); } if( nullptr != data.MaskSpr ) { rs.MaskSpr = &(*data.MaskSpr)( st ); } if( nullptr != data.NormalSpr ) { rs.NormalSpr = &(*data.NormalSpr)( st ); } } void ActionRenderer::Update( double DeltaTime ) { double nextState = mSecsToEnd == 0 ? 100 : ( mState + DeltaTime / mSecsToEnd * 100. ); if( nextState >= 100 ) { nextState = fmod( nextState, 100. ); } mState = nextState; } double ActionRenderer::GetState() const { return mState; } void ActionRenderer::SetState( double S ) { mState = S; } int32_t ActionRenderer::GetId() const { return mId; } int32_t ActionRenderer::GetOrder() const { return mOrder; } void ActionRenderer::SetOrder( int32_t order ) { mOrder = order; } bool ActionRenderer::operator<( const render::ActionRenderer& r ) const { return mOrder < r.GetOrder(); } DefaultActionRenderer::DefaultActionRenderer( int32_t Id ) : ActionRenderer( Id ) { } glm::vec4 GetCloakColor( const Actor& actor ) { glm::vec4 r = glm::vec4( 1.0 ); engine::CloakSystem::CloakState cloakState = engine::CloakSystem::GetCloakState( actor ); if ( cloakState == engine::CloakSystem::Cloaked ) { r = glm::vec4( 1.0, 1.0, 1.0, 0.5 ); } else if ( cloakState == engine::CloakSystem::Invisible ) { r = glm::vec4( 0.0 ); } return r; } glm::vec4 GetColor( const Actor& actor ) { auto renderableC = actor.Get<IRenderableComponent>(); if (renderableC.IsValid()) { return renderableC->GetColor(); } return glm::vec4( 1.0 ); } CompanionSprites GetCompanionSprites( int32_t actorId, int32_t actionId ) { CompanionSprites rv; static auto& renderableRepo( RenderableRepo::Get() ); SpriteCollection const& Sprites = renderableRepo( actorId ); SpriteCollection const& Joint = renderableRepo( Sprites.JointId() ); std::string actorName; platform::IdStorage::Get().GetName( actorId, actorName ); SpriteCollection const& Mask = renderableRepo( AutoId( actorName + "_mask" ) ); SpriteCollection const& Normal = renderableRepo( AutoId( actorName + "_normal" ) ); Sprite const& JointSpr = Joint( actionId ); Sprite const& MaskSpr = Mask( actionId ); Sprite const& NormalSpr = Normal( actionId ); if( JointSpr.IsValid() ) { rv.AdditionalSprs.push_back( &JointSpr ); } if( MaskSpr.IsValid() ) { rv.MaskSpr = &MaskSpr; } if( NormalSpr.IsValid() ) { rv.NormalSpr = &NormalSpr; } return rv; } int32_t GetSpriteId( int32_t spriteIndex, int32_t actorId ) { if (spriteIndex > 0) { static auto& idStorage = IdStorage::Get(); std::string actorName; bool const gotId = idStorage.GetName( actorId, actorName ); BOOST_ASSERT( gotId ); actorName = actorName + "_" + std::to_string( spriteIndex ); actorId = idStorage.GetId( actorName ); } return actorId; } void DefaultActionRendererLoader::BindValues() { } } // namespace render
HalalUr/Reaping2
src/render/action_renderer.cpp
C++
mit
4,908
'use strict'; const common = require('../common'); if (!common.hasIPv6) common.skip('no IPv6 support'); const assert = require('assert'); const cluster = require('cluster'); const net = require('net'); // This test ensures that the `ipv6Only` option in `net.Server.listen()` // works as expected when we use cluster with `SCHED_RR` schedulingPolicy. cluster.schedulingPolicy = cluster.SCHED_RR; const host = '::'; const WORKER_ACCOUNT = 3; if (cluster.isMaster) { const workers = []; let address; for (let i = 0; i < WORKER_ACCOUNT; i += 1) { const myWorker = new Promise((resolve) => { const worker = cluster.fork().on('exit', common.mustCall((statusCode) => { assert.strictEqual(statusCode, 0); })).on('listening', common.mustCall((workerAddress) => { if (!address) { address = workerAddress; } else { assert.deepStrictEqual(workerAddress, address); } resolve(worker); })); }); workers.push(myWorker); } Promise.all(workers).then(common.mustCall((resolvedWorkers) => { // Make sure the `ipv6Only` option works. Should be able to use the port on // IPv4. const server = net.createServer().listen({ host: '0.0.0.0', port: address.port, }, common.mustCall(() => { // Exit. server.close(); resolvedWorkers.forEach((resolvedWorker) => { resolvedWorker.disconnect(); }); })); })); } else { // As the cluster member has the potential to grab any port // from the environment, this can cause collision when master // obtains the port from cluster member and tries to listen on. // So move this to sequential, and provide a static port. // Refs: https://github.com/nodejs/node/issues/25813 net.createServer().listen({ host: host, port: common.PORT, ipv6Only: true, }, common.mustCall()); }
enclose-io/compiler
lts/test/sequential/test-cluster-net-listen-ipv6only-rr.js
JavaScript
mit
1,884
import Vue from 'vue'; import closedComponent from '~/vue_merge_request_widget/components/states/mr_widget_closed.vue'; import mountComponent from 'spec/helpers/vue_mount_component_helper'; describe('MRWidgetClosed', () => { let vm; beforeEach(() => { const Component = Vue.extend(closedComponent); vm = mountComponent(Component, { mr: { metrics: { mergedBy: {}, closedBy: { name: 'Administrator', username: 'root', webUrl: 'http://localhost:3000/root', avatarUrl: 'http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon', }, mergedAt: 'Jan 24, 2018 1:02pm GMT+0000', closedAt: 'Jan 24, 2018 1:02pm GMT+0000', readableMergedAt: '', readableClosedAt: 'less than a minute ago', }, targetBranchPath: '/twitter/flight/commits/so_long_jquery', targetBranch: 'so_long_jquery', }, }); }); afterEach(() => { vm.$destroy(); }); it('renders warning icon', () => { expect(vm.$el.querySelector('.js-ci-status-icon-warning')).not.toBeNull(); }); it('renders closed by information with author and time', () => { expect( vm.$el .querySelector('.js-mr-widget-author') .textContent.trim() .replace(/\s\s+/g, ' '), ).toContain('Closed by Administrator less than a minute ago'); }); it('links to the user that closed the MR', () => { expect(vm.$el.querySelector('.author-link').getAttribute('href')).toEqual( 'http://localhost:3000/root', ); }); it('renders information about the changes not being merged', () => { expect( vm.$el .querySelector('.mr-info-list') .textContent.trim() .replace(/\s\s+/g, ' '), ).toContain('The changes were not merged into so_long_jquery'); }); it('renders link for target branch', () => { expect(vm.$el.querySelector('.label-branch').getAttribute('href')).toEqual( '/twitter/flight/commits/so_long_jquery', ); }); });
stoplightio/gitlabhq
spec/javascripts/vue_mr_widget/components/states/mr_widget_closed_spec.js
JavaScript
mit
2,094
using System.Linq; using System.Runtime.InteropServices; using Diadoc.Api.Com; namespace Diadoc.Api.Proto { [ComVisible(true)] [Guid("6D52D398-C4C9-4ED0-B9A1-38D074C045C7")] public interface ICounteragentList { int TotalCount { get; } ReadonlyList CounteragentsList { get; } } [ComVisible(true)] [Guid("0165E953-29A3-40DA-9FCC-786ED727DA6A")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (ICounteragentList))] public partial class CounteragentList : SafeComObject, ICounteragentList { public ReadonlyList CounteragentsList { get { return new ReadonlyList(Counteragents); } } public override string ToString() { return string.Join("\r\n", Counteragents.Select(c => c.ToString()).ToArray()); } } [ComVisible(true)] [Guid("92320D36-B9E7-44A5-9F63-D799D42EAAF8")] public interface ICounteragent { string IndexKey { get; } Organization Organization { get; } long LastEventTimestampTicks { get; } string MessageFromCounteragent { get; } string MessageToCounteragent { get; } Com.CounteragentStatus CurrentCounteragentStatus { get; } } [ComVisible(true)] [Guid("839DA27C-80F7-45AB-A554-22C3DE3D624B")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (ICounteragent))] public partial class Counteragent : SafeComObject, ICounteragent { public override string ToString() { return string.Format("IndexKey: {0}, Organization: {1}, CurrentStatus: {2}, LastEventTimestampTicks: {3}", IndexKey, Organization, CurrentStatus, LastEventTimestampTicks); } public Com.CounteragentStatus CurrentCounteragentStatus { get { return (Com.CounteragentStatus) CurrentStatus; } } } [ComVisible(true)] [Guid("0C809297-EFC6-4BBD-B952-678F55D3F2D2")] public interface ICounteragentCertificateList { ReadonlyList CertificatesList { get; } } [ComVisible(true)] [Guid("C5BCC37D-E415-4232-81F6-ED0B351EED81")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(ICounteragentCertificateList))] public partial class CounteragentCertificateList : SafeComObject, ICounteragentCertificateList { public ReadonlyList CertificatesList { get { return new ReadonlyList(Certificates); } } public override string ToString() { return string.Join("\r\n", Certificates.Select(c => c.ToString()).ToArray()); } } [ComVisible(true)] [Guid("6550D3C1-1BB0-4043-B24B-1D98B529C363")] public interface ICertificate { byte[] RawCertificateData { get; } } [ComVisible(true)] [Guid("243319AA-3232-483A-BE8A-913747A971C7")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(ICertificate))] public partial class Certificate : SafeComObject, ICertificate { } }
s-rogonov/diadocsdk-csharp
src/Proto/Counteragent.cs
C#
mit
2,719
'use strict'; import React from 'react'; import PlaylistHeader from './PlaylistHeader'; import PlaylistVideos from './PlaylistVideos'; const PureRenderMixin = React.addons.PureRenderMixin; export default React.createClass({ propTypes: { playlist: React.PropTypes.array.isRequired, }, mixins: [PureRenderMixin], renderPlaylists(playlist){ return ( <div key={playlist.get('id')} className="playlist-items"> <PlaylistHeader title={playlist.get('title')} playlist={playlist.get('id')} /> <PlaylistVideos videos={playlist.get('videos')} /> </div> ); }, render() { let nodes = this.props.playlist.map(this.renderPlaylists); return ( <div className="playlist-items-container"> {nodes} </div> ); } });
whoisandie/yoda
src/scripts/Playlist.js
JavaScript
mit
785
'use strict'; /* global google */ function cdDojoDetailCtrl($scope, $state, $location, cdDojoService, cdUsersService, alertService, usSpinnerService, auth, dojo, gmap, $translate, currentUser) { $scope.dojo = dojo; $scope.model = {}; $scope.markers = []; $scope.requestInvite = {}; $scope.userMemberCheckComplete = false; currentUser = currentUser.data; var approvalRequired = ['mentor', 'champion']; var latitude, longitude; if(!_.isEmpty(currentUser)) { if(!dojo || !dojo.id){ return $state.go('error-404-no-headers'); } if(!dojo.verified && dojo.creator !== currentUser.id && !_.contains(currentUser.roles, 'cdf-admin')){ return $state.go('error-404-no-headers'); } //Check if user is a member of this Dojo var query = {dojoId:dojo.id, userId: currentUser.id}; cdDojoService.getUsersDojos(query, function (response) { $scope.dojoMember = !_.isEmpty(response); $scope.dojoOwner = false; if($scope.dojoMember) $scope.dojoOwner = (response[0].owner === 1) ? true : false; $scope.userMemberCheckComplete = true; }); } else { if(!dojo || !dojo.id || !dojo.verified) return $state.go('error-404-no-headers'); $scope.userMemberCheckComplete = true; } cdUsersService.getInitUserTypes(function (response) { var userTypes = _.filter(response, function(type) { return type.name.indexOf('u13') === -1; }); $scope.initUserTypes = userTypes; }); cdDojoService.getDojoConfig(function(json){ $scope.dojoStages = _.map(json.dojoStages, function(item){ return { value: item.value, label: $translate.instant(item.label) }; }); $scope.dojo.stage = _.find($scope.dojoStages, function(obj) { return obj.value === $scope.dojo.stage }) }); $scope.$watch('model.map', function(map){ if(map) { if(latitude && longitude) { var marker = new google.maps.Marker({ map: $scope.model.map, position: new google.maps.LatLng(latitude, longitude) }); $scope.markers.push(marker); } } }); if(gmap) { if($scope.dojo.coordinates) { var coordinates = $scope.dojo.coordinates.split(','); latitude = coordinates[0]; longitude = coordinates[1]; $scope.mapOptions = { center: new google.maps.LatLng(latitude, longitude), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; $scope.mapLoaded = true; } else { var countryCoordinates; cdDojoService.loadCountriesLatLongData(function (response) { countryCoordinates = response[$scope.dojo.alpha2]; $scope.mapOptions = { center: new google.maps.LatLng(countryCoordinates[0], countryCoordinates[1]), zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP }; $scope.mapLoaded = true; }); } } $scope.userTypeSelected = function ($item) { if(_.contains(approvalRequired, $item)) return $scope.approvalRequired = true; return $scope.approvalRequired = false; }; $scope.requestToJoin = function (requestInvite) { if(!$scope.requestInvite.userType) { $scope.requestInvite.validate="false"; return } else { var userType = requestInvite.userType.name; auth.get_loggedin_user(function (user) { usSpinnerService.spin('dojo-detail-spinner'); var data = {user:user, dojoId:dojo.id, userType:userType, emailSubject: $translate.instant('New Request to join your Dojo')}; if(_.contains(approvalRequired, userType)) { cdDojoService.requestInvite(data, function (response) { usSpinnerService.stop('dojo-detail-spinner'); if(!response.error) { alertService.showAlert($translate.instant('Join Request Sent!')); } else { alertService.showError($translate.instant(response.error)); } }); } else { //Check if user is already a member of this Dojo var query = {userId:user.id, dojoId:dojo.id}; var userDojo = {}; cdDojoService.getUsersDojos(query, function (response) { if(_.isEmpty(response)) { //Save userDojo.owner = 0; userDojo.userId = user.id; userDojo.dojoId = dojo.id; userDojo.userTypes = [userType]; cdDojoService.saveUsersDojos(userDojo, function (response) { usSpinnerService.stop('dojo-detail-spinner'); $state.go($state.current, {}, {reload: true}); alertService.showAlert($translate.instant('Successfully Joined Dojo')); }); } else { //Update userDojo = response[0]; if(!userDojo.userTypes) userDojo.userTypes = []; userDojo.userTypes.push(userType); cdDojoService.saveUsersDojos(userDojo, function (response) { usSpinnerService.stop('dojo-detail-spinner'); $state.go($state.current, {}, {reload: true}); alertService.showAlert($translate.instant('Successfully Joined Dojo')); }); } }); } }, function () { //Not logged in $state.go('register-account', {referer:$location.url()}); }); } }; $scope.leaveDojo = function () { usSpinnerService.spin('dojo-detail-spinner'); cdDojoService.removeUsersDojosLink({userId: currentUser.id, dojoId: dojo.id, emailSubject: $translate.instant('A user has left your Dojo')}, function (response) { usSpinnerService.stop('dojo-detail-spinner'); $state.go($state.current, {}, {reload: true}); }, function (err) { alertService.showError($translate.instant('Error leaving Dojo')); }); } } angular.module('cpZenPlatform') .controller('dojo-detail-controller', ['$scope', '$state', '$location', 'cdDojoService', 'cdUsersService', 'alertService', 'usSpinnerService', 'auth', 'dojo', 'gmap', '$translate', 'currentUser', cdDojoDetailCtrl]);
Aryess/cp-zen-platform
web/public/js/controllers/dojo-detail-controller.js
JavaScript
mit
6,054
#!/usr/bin/env node const os = require('os') const {spawn} = require('child_process') if (os.platform() === 'win32' || os.platform() === 'windows') console.log('skipping on windows') else spawn('yarn bats test/integration/*.bats', {stdio: 'inherit', shell: true})
heroku/heroku-cli
packages/run/bin/bats-test-runner.js
JavaScript
mit
266
var searchData= [ ['label',['Label',['../classLabel.html',1,'']]], ['labeliterator',['LabelIterator',['../classLabelIterator.html',1,'']]], ['labelsegment',['LabelSegment',['../structLabelSegment.html',1,'']]] ];
chabbimilind/cctlib
docs/html/search/classes_6c.js
JavaScript
mit
219
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.catalina.ha.backend; import java.net.InetAddress; /* * This class represents a front-end httpd server. * */ public class Proxy { protected enum State { OK, ERROR, DOWN }; public InetAddress address = null; public int port = 80; public State state = State.OK; }
plumer/codana
tomcat_files/7.0.0/Proxy.java
Java
mit
1,102
<?php /* * This file is part of the Alice package. * * (c) Nelmio <hello@nelm.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Nelmio\Alice\Throwable\Exception\Generator\Resolver; class NoSuchPropertyException extends UnresolvableValueException { }
furtadodiegos/projeto_cv
vendor/nelmio/alice/src/Throwable/Exception/Generator/Resolver/NoSuchPropertyException.php
PHP
mit
380
class AddIsRefundToDrawerTransactions < ActiveRecord::Migration def self.up add_column :drawer_transactions, :is_refund, :boolean, :default => false end def self.down remove_column :drawer_transactions, :is_refund end end
a0ali0taha/pos
vendor/db/migrate/20110627192451_add_is_refund_to_drawer_transactions.rb
Ruby
mit
239
# This migration will create one row of NotificationSetting for each Member row # It can take long time on big instances. # # This migration can be done online but with following effects: # - during migration some users will receive notifications based on their global settings (project/group settings will be ignored) # - its possible to get duplicate records for notification settings since we don't create uniq index yet # class MigrateNewNotificationSetting < ActiveRecord::Migration def up timestamp = Time.now.strftime('%F %T') execute "INSERT INTO notification_settings ( user_id, source_id, source_type, level, created_at, updated_at ) SELECT user_id, source_id, source_type, notification_level, '#{timestamp}', '#{timestamp}' FROM members WHERE user_id IS NOT NULL" end def down execute "DELETE FROM notification_settings" end end
larryli/gitlabhq
db/migrate/20160328115649_migrate_new_notification_setting.rb
Ruby
mit
861
/**! * Sortable * @author RubaXa <trash@rubaxa.org> * @author owenm <owen23355@gmail.com> * @license MIT */ (function sortableModule(factory) { "use strict"; if (typeof define === "function" && define.amd) { define(factory); } else if (typeof module != "undefined" && typeof module.exports != "undefined") { module.exports = factory(); } else { /* jshint sub:true */ window["Sortable"] = factory(); } })(function sortableFactory() { "use strict"; if (typeof window === "undefined" || !window.document) { return function sortableError() { throw new Error("Sortable.js requires a window with a document"); }; } var dragEl, parentEl, ghostEl, cloneEl, rootEl, nextEl, lastDownEl, scrollEl, scrollParentEl, scrollCustomFn, oldIndex, newIndex, activeGroup, putSortable, autoScrolls = [], scrolling = false, pointerElemChangedInterval, lastPointerElemX, lastPointerElemY, tapEvt, touchEvt, moved, lastTarget, lastDirection, pastFirstInvertThresh = false, isCircumstantialInvert = false, forRepaintDummy, realDragElRect, // dragEl rect after current animation /** @const */ R_SPACE = /\s+/g, expando = 'Sortable' + (new Date).getTime(), win = window, document = win.document, parseInt = win.parseInt, setTimeout = win.setTimeout, $ = win.jQuery || win.Zepto, Polymer = win.Polymer, captureMode = { capture: false, passive: false }, supportDraggable = ('draggable' in document.createElement('div')), supportCssPointerEvents = (function (el) { // false when IE11 if (!!navigator.userAgent.match(/(?:Trident.*rv[ :]?11\.|msie)/i)) { return false; } el = document.createElement('x'); el.style.cssText = 'pointer-events:auto'; return el.style.pointerEvents === 'auto'; })(), _silent = false, _alignedSilent = false, abs = Math.abs, min = Math.min, savedInputChecked = [], touchDragOverListeners = [], alwaysFalse = function () { return false; }, _detectDirection = function(el, options) { var elCSS = _css(el), elWidth = parseInt(elCSS.width), child1 = _getChild(el, 0, options), child2 = _getChild(el, 1, options), firstChildCSS = child1 && _css(child1), secondChildCSS = child2 && _css(child2), firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + child1.getBoundingClientRect().width, secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + child2.getBoundingClientRect().width ; if (elCSS.display === 'flex') { return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal'; } return (child1 && ( firstChildCSS.display === 'block' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS.float === 'none' || child2 && elCSS.float === 'none' && firstChildWidth + secondChildWidth > elWidth ) ? 'vertical' : 'horizontal' ); }, _isInRowColumn = function(x, y, el, axis, options) { var targetRect = realDragElRect || dragEl.getBoundingClientRect(), targetS1Opp = axis === 'vertical' ? targetRect.left : targetRect.top, targetS2Opp = axis === 'vertical' ? targetRect.right : targetRect.bottom, mouseOnOppAxis = axis === 'vertical' ? x : y ; return targetS1Opp < mouseOnOppAxis && mouseOnOppAxis < targetS2Opp; }, _getParentAutoScrollElement = function(el, includeSelf) { // skip to window if (!el || !el.getBoundingClientRect) return win; var elem = el; var gotSelf = false; do { // we don't need to get elem css if it isn't even overflowing in the first place (performance) if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) { var elemCSS = _css(elem); if ( elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll') ) { if (!elem || !elem.getBoundingClientRect || elem === document.body) return win; if (gotSelf || includeSelf) return elem; gotSelf = true; } } /* jshint boss:true */ } while (elem = elem.parentNode); return win; }, _autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl, /**Boolean*/isFallback) { // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521 if (options.scroll) { var _this = rootEl ? rootEl[expando] : window, rect, css, sens = options.scrollSensitivity, speed = options.scrollSpeed, x = evt.clientX, y = evt.clientY, winWidth = window.innerWidth, winHeight = window.innerHeight, vx, vy, scrollThisInstance = false ; // Detect scrollEl if (scrollParentEl !== rootEl) { _clearAutoScrolls(); scrollEl = options.scroll; scrollCustomFn = options.scrollFn; if (scrollEl === true) { scrollEl = _getParentAutoScrollElement(rootEl, true); scrollParentEl = scrollEl; } } var layersOut = 0; var currentParent = scrollEl; do { var el; if (currentParent && currentParent !== win) { el = currentParent; css = _css(el); rect = currentParent.getBoundingClientRect(); vx = el.clientWidth < el.scrollWidth && (css.overflowX == 'auto' || css.overflowX == 'scroll') && ((abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens)); vy = el.clientHeight < el.scrollHeight && (css.overflowY == 'auto' || css.overflowY == 'scroll') && ((abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens)); } else if (currentParent === win) { el = win; vx = (winWidth - x <= sens) - (x <= sens); vy = (winHeight - y <= sens) - (y <= sens); } if (!autoScrolls[layersOut]) { for (var i = 0; i <= layersOut; i++) { if (!autoScrolls[i]) { autoScrolls[i] = {}; } } } if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) { autoScrolls[layersOut].el = el; autoScrolls[layersOut].vx = vx; autoScrolls[layersOut].vy = vy; clearInterval(autoScrolls[layersOut].pid); if (el && (vx != 0 || vy != 0)) { scrollThisInstance = true; /* jshint loopfunc:true */ autoScrolls[layersOut].pid = setInterval((function () { // emulate drag over during autoscroll (fallback), emulating native DnD behaviour if (isFallback && this.layer === 0) { Sortable.active._emulateDragOver(true); } var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0; var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0; if ('function' === typeof(scrollCustomFn)) { if (scrollCustomFn.call(_this, scrollOffsetX, scrollOffsetY, evt, touchEvt, autoScrolls[this.layer].el) !== 'continue') { return; } } if (autoScrolls[this.layer].el === win) { win.scrollTo(win.pageXOffset + scrollOffsetX, win.pageYOffset + scrollOffsetY); } else { autoScrolls[this.layer].el.scrollTop += scrollOffsetY; autoScrolls[this.layer].el.scrollLeft += scrollOffsetX; } }).bind({layer: layersOut}), 24); } } layersOut++; } while (options.bubbleScroll && currentParent !== win && (currentParent = _getParentAutoScrollElement(currentParent, false))); scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not } }, 30), _clearAutoScrolls = function () { autoScrolls.forEach(function(autoScroll) { clearInterval(autoScroll.pid); }); autoScrolls = []; }, _prepareGroup = function (options) { function toFn(value, pull) { return function(to, from, dragEl, evt) { var ret; if (value == null && pull) { ret = true; // default pull value: true (backwards compatibility) } else if (value == null || value === false) { ret = false; } else if (pull && value === 'clone') { ret = value; } else if (typeof value === 'function') { ret = value(to, from, dragEl, evt); } else { var otherGroup = (pull ? to : from).options.group.name; ret = (value === true || (typeof value === 'string' && value === otherGroup) || (value.join && value.indexOf(otherGroup) > -1)); } return ret || (to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name); }; } var group = {}; var originalGroup = options.group; if (!originalGroup || typeof originalGroup != 'object') { originalGroup = {name: originalGroup}; } group.name = originalGroup.name; group.checkPull = toFn(originalGroup.pull, true); group.checkPut = toFn(originalGroup.put); group.revertClone = originalGroup.revertClone; options.group = group; }, _checkAlignment = function(evt) { if (!dragEl) return; dragEl.parentNode[expando] && dragEl.parentNode[expando]._computeIsAligned(evt); } ; /** * @class Sortable * @param {HTMLElement} el * @param {Object} [options] */ function Sortable(el, options) { if (!(el && el.nodeType && el.nodeType === 1)) { throw 'Sortable: `el` must be HTMLElement, and not ' + {}.toString.call(el); } this.el = el; // root element this.options = options = _extend({}, options); // Export instance el[expando] = this; // Default options var defaults = { group: null, sort: true, disabled: false, store: null, handle: null, scroll: true, scrollSensitivity: 30, scrollSpeed: 10, bubbleScroll: true, draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*', swapThreshold: 1, // percentage; 0 <= x <= 1 invertSwap: false, // invert always invertedSwapThreshold: null, // will be set to same as swapThreshold if default ghostClass: 'sortable-ghost', chosenClass: 'sortable-chosen', dragClass: 'sortable-drag', ignore: 'a, img', filter: null, preventOnFilter: true, animation: 0, setData: function (dataTransfer, dragEl) { dataTransfer.setData('Text', dragEl.textContent); }, dropBubble: false, dragoverBubble: false, dataIdAttr: 'data-id', delay: 0, touchStartThreshold: parseInt(window.devicePixelRatio, 10) || 1, forceFallback: false, fallbackClass: 'sortable-fallback', fallbackOnBody: false, fallbackTolerance: 0, fallbackOffset: {x: 0, y: 0}, supportPointer: Sortable.supportPointer !== false && ( ('PointerEvent' in window) || window.navigator && ('msPointerEnabled' in window.navigator) // microsoft ) }; // Set default options for (var name in defaults) { !(name in options) && (options[name] = defaults[name]); } if (!('direction' in options)) { options.direction = function() { return _detectDirection(el, options); }; } _prepareGroup(options); options.invertedSwapThreshold == null && (options.invertedSwapThreshold = options.swapThreshold); // Bind all private methods for (var fn in this) { if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { this[fn] = this[fn].bind(this); } } // Setup drag mode this.nativeDraggable = options.forceFallback ? false : supportDraggable; // Bind events _on(el, 'mousedown', this._onTapStart); _on(el, 'touchstart', this._onTapStart); options.supportPointer && _on(el, 'pointerdown', this._onTapStart); if (this.nativeDraggable) { _on(el, 'dragover', this); _on(el, 'dragenter', this); } touchDragOverListeners.push(this._onDragOver); // Restore sorting options.store && options.store.get && this.sort(options.store.get(this) || []); } Sortable.prototype = /** @lends Sortable.prototype */ { constructor: Sortable, // is mouse aligned with dragEl? _isAligned: true, _computeIsAligned: function(evt, isDragEl) { if (_alignedSilent) return; if (!dragEl || dragEl.parentNode !== this.el) return; if (isDragEl !== true && isDragEl !== false) { isDragEl = !!_closest(evt.target, null, dragEl, true); } this._isAligned = !scrolling && (isDragEl || this._isAligned && _isInRowColumn(evt.clientX, evt.clientY, this.el, this._getDirection(evt, null), this.options)); _alignedSilent = true; setTimeout(function() { _alignedSilent = false; }, 30); }, _getDirection: function(evt, target) { return (typeof this.options.direction === 'function') ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction; }, _onTapStart: function (/** Event|TouchEvent */evt) { var _this = this, el = this.el, options = this.options, preventOnFilter = options.preventOnFilter, type = evt.type, touch = evt.touches && evt.touches[0], target = (touch || evt).target, originalTarget = evt.target.shadowRoot && ((evt.path && evt.path[0]) || (evt.composedPath && evt.composedPath()[0])) || target, filter = options.filter, startIndex; _saveInputCheckedState(el); // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group. if (dragEl) { return; } if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) { return; // only left button or enabled } // cancel dnd if original target is content editable if (originalTarget.isContentEditable) { return; } target = _closest(target, options.draggable, el, true); if (!target) { return; } if (lastDownEl === target) { // Ignoring duplicate `down` return; } // Get the index of the dragged element within its parent startIndex = _index(target, options.draggable); // Check filter if (typeof filter === 'function') { if (filter.call(this, evt, target, this)) { _dispatchEvent(_this, originalTarget, 'filter', target, el, el, startIndex); preventOnFilter && evt.cancelable && evt.preventDefault(); return; // cancel dnd } } else if (filter) { filter = filter.split(',').some(function (criteria) { criteria = _closest(originalTarget, criteria.trim(), el, false); if (criteria) { _dispatchEvent(_this, criteria, 'filter', target, el, el, startIndex); return true; } }); if (filter) { preventOnFilter && evt.cancelable && evt.preventDefault(); return; // cancel dnd } } if (options.handle && !_closest(originalTarget, options.handle, el, false)) { return; } // Prepare `dragstart` this._prepareDragStart(evt, touch, target, startIndex); }, _handleAutoScroll: function(evt, fallback) { if (!dragEl || !this.options.scroll) return; var x = evt.clientX, y = evt.clientY, elem = document.elementFromPoint(x, y), _this = this ; // firefox does not have native autoscroll if (fallback || (window.navigator && window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1)) { _autoScroll(evt, _this.options, elem, true); // Listener for pointer element change var ogElemScroller = _getParentAutoScrollElement(elem, true); if ( scrolling && ( !pointerElemChangedInterval || x !== lastPointerElemX || y !== lastPointerElemY ) ) { pointerElemChangedInterval && clearInterval(pointerElemChangedInterval); // Detect for pointer elem change, emulating native DnD behaviour pointerElemChangedInterval = setInterval(function() { if (!dragEl) return; // could also check if scroll direction on newElem changes due to parent autoscrolling var newElem = _getParentAutoScrollElement(document.elementFromPoint(x, y), true); if (newElem !== ogElemScroller) { ogElemScroller = newElem; _clearAutoScrolls(); _autoScroll(evt, _this.options, ogElemScroller, true); } }, 10); lastPointerElemX = x; lastPointerElemY = y; } } else { // if DnD is enabled (not on firefox), first autoscroll will already scroll, so get parent autoscroll of first autoscroll if (!_this.options.bubbleScroll || _getParentAutoScrollElement(elem, true) === window) { _clearAutoScrolls(); return; } _autoScroll(evt, _this.options, _getParentAutoScrollElement(elem, false)); } }, _prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target, /** Number */startIndex) { var _this = this, el = _this.el, options = _this.options, ownerDocument = el.ownerDocument, dragStartFn; if (target && !dragEl && (target.parentNode === el)) { tapEvt = evt; rootEl = el; dragEl = target; parentEl = dragEl.parentNode; nextEl = dragEl.nextSibling; lastDownEl = target; activeGroup = options.group; oldIndex = startIndex; this._lastX = (touch || evt).clientX; this._lastY = (touch || evt).clientY; dragEl.style['will-change'] = 'all'; dragStartFn = function () { // Delayed drag has been triggered // we can re-enable the events: touchmove/mousemove _this._disableDelayedDrag(); // Make the element draggable dragEl.draggable = _this.nativeDraggable; // Bind the events: dragstart/dragend _this._triggerDragStart(evt, touch); // Drag start event _dispatchEvent(_this, rootEl, 'choose', dragEl, rootEl, rootEl, oldIndex); // Chosen item _toggleClass(dragEl, options.chosenClass, true); }; // Disable "draggable" options.ignore.split(',').forEach(function (criteria) { _find(dragEl, criteria.trim(), _disableDraggable); }); _on(ownerDocument, 'mouseup', _this._onDrop); _on(ownerDocument, 'touchend', _this._onDrop); _on(ownerDocument, 'touchcancel', _this._onDrop); options.supportPointer && _on(ownerDocument, 'pointercancel', _this._onDrop); if (options.delay) { // If the user moves the pointer or let go the click or touch // before the delay has been reached: // disable the delayed drag _on(ownerDocument, 'mouseup', _this._disableDelayedDrag); _on(ownerDocument, 'touchend', _this._disableDelayedDrag); _on(ownerDocument, 'touchcancel', _this._disableDelayedDrag); _on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler); _on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler); options.supportPointer && _on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler); _this._dragStartTimer = setTimeout(dragStartFn.bind(_this), options.delay); } else { dragStartFn(); } } }, _delayedDragTouchMoveHandler: function (/** TouchEvent|PointerEvent **/e) { var touch = e.touches ? e.touches[0] : e; if (min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) >= this.options.touchStartThreshold ) { this._disableDelayedDrag(); } }, _disableDelayedDrag: function () { var ownerDocument = this.el.ownerDocument; clearTimeout(this._dragStartTimer); _off(ownerDocument, 'mouseup', this._disableDelayedDrag); _off(ownerDocument, 'touchend', this._disableDelayedDrag); _off(ownerDocument, 'touchcancel', this._disableDelayedDrag); _off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler); _off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler); _off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler); }, _triggerDragStart: function (/** Event */evt, /** Touch */touch) { touch = touch || (evt.pointerType == 'touch' ? evt : null); if (touch) { // Touch device support tapEvt = { target: dragEl, clientX: touch.clientX, clientY: touch.clientY }; this._onDragStart(tapEvt, 'touch'); } else if (!this.nativeDraggable) { this._onDragStart(tapEvt, true); } else { _on(dragEl, 'dragend', this); _on(rootEl, 'dragstart', this._onDragStart); } try { if (document.selection) { // Timeout neccessary for IE9 _nextTick(function () { document.selection.empty(); }); } else { window.getSelection().removeAllRanges(); } } catch (err) { } }, _dragStarted: function () { if (rootEl && dragEl) { if (this.nativeDraggable) { _on(document, 'dragover', this._handleAutoScroll); _on(document, 'dragover', _checkAlignment); } var options = this.options; // Apply effect _toggleClass(dragEl, options.dragClass, false); _toggleClass(dragEl, options.ghostClass, true); _css(dragEl, 'transform', ''); Sortable.active = this; this._isAligned = true; // Drag start event _dispatchEvent(this, rootEl, 'start', dragEl, rootEl, rootEl, oldIndex); } else { this._nulling(); } }, _emulateDragOver: function (bypassLastTouchCheck) { if (touchEvt) { if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY && !bypassLastTouchCheck) { return; } this._lastX = touchEvt.clientX; this._lastY = touchEvt.clientY; if (!supportCssPointerEvents) { _css(ghostEl, 'display', 'none'); } var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY); var parent = target; var isDragEl = !!_closest(target, null, dragEl, true); while (target && target.shadowRoot) { target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY); parent = target; } if (parent) { do { if (parent[expando]) { var i = touchDragOverListeners.length; while (i--) { touchDragOverListeners[i]({ clientX: touchEvt.clientX, clientY: touchEvt.clientY, target: target, rootEl: parent }); } if (!this.options.dragoverBubble) { break; } } target = parent; // store last element } /* jshint boss:true */ while (parent = parent.parentNode); } dragEl.parentNode[expando]._computeIsAligned(touchEvt, isDragEl); if (!supportCssPointerEvents) { _css(ghostEl, 'display', ''); } } }, _onTouchMove: function (/**TouchEvent*/evt) { if (tapEvt) { var options = this.options, fallbackTolerance = options.fallbackTolerance, fallbackOffset = options.fallbackOffset, touch = evt.touches ? evt.touches[0] : evt, dx = (touch.clientX - tapEvt.clientX) + fallbackOffset.x, dy = (touch.clientY - tapEvt.clientY) + fallbackOffset.y, translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)'; // prevent duplicate event firing if (this.options.supportPointer && evt.type === 'touchmove') return; // only set the status to dragging, when we are actually dragging if (!Sortable.active) { if (fallbackTolerance && min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) < fallbackTolerance ) { return; } this._dragStarted(); } // as well as creating the ghost element on the document body this._appendGhost(); this._handleAutoScroll(touch, true); moved = true; touchEvt = touch; _css(ghostEl, 'webkitTransform', translate3d); _css(ghostEl, 'mozTransform', translate3d); _css(ghostEl, 'msTransform', translate3d); _css(ghostEl, 'transform', translate3d); evt.cancelable && evt.preventDefault(); } }, _appendGhost: function () { if (!ghostEl) { var rect = dragEl.getBoundingClientRect(), css = _css(dragEl), options = this.options, ghostRect; ghostEl = dragEl.cloneNode(true); _toggleClass(ghostEl, options.ghostClass, false); _toggleClass(ghostEl, options.fallbackClass, true); _toggleClass(ghostEl, options.dragClass, true); _css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10)); _css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10)); _css(ghostEl, 'width', rect.width); _css(ghostEl, 'height', rect.height); _css(ghostEl, 'opacity', '0.8'); _css(ghostEl, 'position', 'fixed'); _css(ghostEl, 'zIndex', '100000'); _css(ghostEl, 'pointerEvents', 'none'); options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl); // Fixing dimensions. ghostRect = ghostEl.getBoundingClientRect(); _css(ghostEl, 'width', rect.width * 2 - ghostRect.width); _css(ghostEl, 'height', rect.height * 2 - ghostRect.height); } }, _onDragStart: function (/**Event*/evt, /**boolean*/useFallback) { var _this = this; var dataTransfer = evt.dataTransfer; var options = _this.options; _this._offUpEvents(); if (activeGroup.checkPull(_this, _this, dragEl, evt)) { cloneEl = _clone(dragEl); cloneEl.draggable = false; cloneEl.style['will-change'] = ''; this._hideClone(); _toggleClass(cloneEl, _this.options.chosenClass, false); // #1143: IFrame support workaround _this._cloneId = _nextTick(function () { rootEl.insertBefore(cloneEl, dragEl); _dispatchEvent(_this, rootEl, 'clone', dragEl); }); } _toggleClass(dragEl, options.dragClass, true); if (useFallback) { if (useFallback === 'touch') { // Fixed #973: _on(document, 'touchmove', _preventScroll); // Bind touch events _on(document, 'touchmove', _this._onTouchMove); _on(document, 'touchend', _this._onDrop); _on(document, 'touchcancel', _this._onDrop); if (options.supportPointer) { _on(document, 'pointermove', _this._onTouchMove); _on(document, 'pointerup', _this._onDrop); } } else { // Old brwoser _on(document, 'mousemove', _this._onTouchMove); _on(document, 'mouseup', _this._onDrop); } _this._loopId = setInterval(_this._emulateDragOver, 50); _toggleClass(dragEl, options.dragClass, false); } else { if (dataTransfer) { dataTransfer.effectAllowed = 'move'; options.setData && options.setData.call(_this, dataTransfer, dragEl); } _on(document, 'drop', _this); // #1276 fix: _css(dragEl, 'transform', 'translateZ(0)'); _this._dragStartId = _nextTick(_this._dragStarted); } _on(document, 'selectstart', _this); }, _onDragOver: function (/**Event*/evt) { var el = this.el, target, dragRect, targetRect, revert, options = this.options, group = options.group, activeSortable = Sortable.active, isOwner = (activeGroup === group), isMovingBetweenSortable = false, canSort = options.sort ; if (evt.rootEl !== void 0 && evt.rootEl !== this.el) return; // touch fallback // no bubbling and not fallback if (!options.dragoverBubble && !evt.rootEl) { this._handleAutoScroll(evt); dragEl.parentNode[expando]._computeIsAligned(evt); } if (evt.preventDefault !== void 0) { evt.cancelable && evt.preventDefault(); !options.dragoverBubble && evt.stopPropagation(); } moved = true; target = _closest(evt.target, options.draggable, el, true); if (dragEl.animated && target === dragEl || target.animated || _silent) { return; } if (target !== lastTarget) { isCircumstantialInvert = false; pastFirstInvertThresh = false; lastTarget = null; } if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list : ( putSortable === this || ( (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt) ) ) ) ) { var direction; var axis = this._getDirection(evt, target); dragRect = dragEl.getBoundingClientRect(); if (putSortable !== this && this !== Sortable.active) { putSortable = this; isMovingBetweenSortable = true; } else if (this === Sortable.active) { isMovingBetweenSortable = false; putSortable = null; } if (revert) { this._hideClone(); parentEl = rootEl; // actualization if (cloneEl || nextEl) { rootEl.insertBefore(dragEl, cloneEl || nextEl); } else if (!canSort) { rootEl.appendChild(dragEl); } return; } if ((el.children.length === 0) || (el.children[0] === ghostEl) || (el === evt.target) && _ghostIsLast(evt, axis, el) ) { //assign target only if condition is true if (el.children.length !== 0 && el.children[0] !== ghostEl && el === evt.target) { target = _lastChild(el); } if (target) { if (target.animated) { return; } targetRect = target.getBoundingClientRect(); } if (isOwner) { activeSortable._hideClone(); } else { activeSortable._showClone(this); } if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) { if (!dragEl.contains(el)) { el.appendChild(dragEl); parentEl = el; // actualization this._isAligned = true; // must be for _ghostIsLast to pass realDragElRect = null; } this._animate(dragRect, dragEl); target && this._animate(targetRect, target); } } else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0) && target !== el) { isCircumstantialInvert = isCircumstantialInvert || options.invertSwap || dragEl.parentNode !== el || !this._isAligned; direction = _getSwapDirection(evt, target, axis, options.swapThreshold, options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target); if (direction === 0) return; realDragElRect = null; this._isAligned = true; if (!lastTarget || lastTarget !== target && (!target || !target.animated)) { pastFirstInvertThresh = false; lastTarget = target; } lastDirection = direction; targetRect = target.getBoundingClientRect(); var nextSibling = target.nextElementSibling, after = false ; after = direction === 1; var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after); if (moveVector !== false) { if (moveVector === 1 || moveVector === -1) { after = (moveVector === 1); } _silent = true; setTimeout(_unsilent, 30); if (isOwner) { activeSortable._hideClone(); } else { activeSortable._showClone(this); } if (!dragEl.contains(el)) { if (after && !nextSibling) { el.appendChild(dragEl); } else { target.parentNode.insertBefore(dragEl, after ? nextSibling : target); } } parentEl = dragEl.parentNode; // actualization this._animate(dragRect, dragEl); this._animate(targetRect, target); } } } }, _animate: function (prevRect, target) { var ms = this.options.animation; if (ms) { var currentRect = target.getBoundingClientRect(); if (target === dragEl) { realDragElRect = currentRect; } if (prevRect.nodeType === 1) { prevRect = prevRect.getBoundingClientRect(); } // Check if actually moving position if ((prevRect.left + prevRect.width / 2) === (currentRect.left + currentRect.width / 2) && (prevRect.top + prevRect.height / 2) === (currentRect.top + currentRect.height / 2) ) return; _css(target, 'transition', 'none'); _css(target, 'transform', 'translate3d(' + (prevRect.left - currentRect.left) + 'px,' + (prevRect.top - currentRect.top) + 'px,0)' ); forRepaintDummy = target.offsetWidth; // repaint _css(target, 'transition', 'all ' + ms + 'ms'); _css(target, 'transform', 'translate3d(0,0,0)'); clearTimeout(target.animated); target.animated = setTimeout(function () { _css(target, 'transition', ''); _css(target, 'transform', ''); target.animated = false; }, ms); } }, _offUpEvents: function () { var ownerDocument = this.el.ownerDocument; _off(document, 'touchmove', _preventScroll); _off(document, 'touchmove', this._onTouchMove); _off(document, 'pointermove', this._onTouchMove); _off(ownerDocument, 'mouseup', this._onDrop); _off(ownerDocument, 'touchend', this._onDrop); _off(ownerDocument, 'pointerup', this._onDrop); _off(ownerDocument, 'touchcancel', this._onDrop); _off(ownerDocument, 'pointercancel', this._onDrop); _off(document, 'selectstart', this); }, _onDrop: function (/**Event*/evt) { var el = this.el, options = this.options; scrolling = false; isCircumstantialInvert = false; pastFirstInvertThresh = false; clearInterval(this._loopId); clearInterval(pointerElemChangedInterval); _clearAutoScrolls(); _cancelThrottle(); clearTimeout(this._dragStartTimer); _cancelNextTick(this._cloneId); _cancelNextTick(this._dragStartId); // Unbind events _off(document, 'mousemove', this._onTouchMove); if (this.nativeDraggable) { _off(document, 'drop', this); _off(el, 'dragstart', this._onDragStart); _off(document, 'dragover', this._handleAutoScroll); _off(document, 'dragover', _checkAlignment); } this._offUpEvents(); if (evt) { if (moved) { evt.cancelable && evt.preventDefault(); !options.dropBubble && evt.stopPropagation(); } ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl); if (rootEl === parentEl || (putSortable && putSortable.lastPutMode !== 'clone')) { // Remove clone cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl); } if (dragEl) { if (this.nativeDraggable) { _off(dragEl, 'dragend', this); } _disableDraggable(dragEl); dragEl.style['will-change'] = ''; // Remove class's _toggleClass(dragEl, this.options.ghostClass, false); _toggleClass(dragEl, this.options.chosenClass, false); // Drag stop event _dispatchEvent(this, rootEl, 'unchoose', dragEl, parentEl, rootEl, oldIndex, null, evt); if (rootEl !== parentEl) { newIndex = _index(dragEl, options.draggable); if (newIndex >= 0) { // Add event _dispatchEvent(null, parentEl, 'add', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); // Remove event _dispatchEvent(this, rootEl, 'remove', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); // drag from one list and drop into another _dispatchEvent(null, parentEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); } putSortable && putSortable.save(); } else { if (dragEl.nextSibling !== nextEl) { // Get the index of the dragged element within its parent newIndex = _index(dragEl, options.draggable); if (newIndex >= 0) { // drag & drop within the same list _dispatchEvent(this, rootEl, 'update', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); } } } if (Sortable.active) { /* jshint eqnull:true */ if (newIndex == null || newIndex === -1) { newIndex = oldIndex; } _dispatchEvent(this, rootEl, 'end', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); // Save sorting this.save(); } } } this._nulling(); }, _nulling: function() { rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = scrollEl = scrollParentEl = autoScrolls.length = pointerElemChangedInterval = lastPointerElemX = lastPointerElemY = tapEvt = touchEvt = moved = newIndex = oldIndex = lastTarget = lastDirection = forRepaintDummy = realDragElRect = putSortable = activeGroup = Sortable.active = null; savedInputChecked.forEach(function (el) { el.checked = true; }); savedInputChecked.length = 0; }, handleEvent: function (/**Event*/evt) { switch (evt.type) { case 'drop': case 'dragend': this._onDrop(evt); break; case 'dragenter': case 'dragover': if (dragEl) { this._onDragOver(evt); _globalDragOver(evt); } break; case 'selectstart': evt.preventDefault(); break; } }, /** * Serializes the item into an array of string. * @returns {String[]} */ toArray: function () { var order = [], el, children = this.el.children, i = 0, n = children.length, options = this.options; for (; i < n; i++) { el = children[i]; if (_closest(el, options.draggable, this.el, false)) { order.push(el.getAttribute(options.dataIdAttr) || _generateId(el)); } } return order; }, /** * Sorts the elements according to the array. * @param {String[]} order order of the items */ sort: function (order) { var items = {}, rootEl = this.el; this.toArray().forEach(function (id, i) { var el = rootEl.children[i]; if (_closest(el, this.options.draggable, rootEl, false)) { items[id] = el; } }, this); order.forEach(function (id) { if (items[id]) { rootEl.removeChild(items[id]); rootEl.appendChild(items[id]); } }); }, /** * Save the current sorting */ save: function () { var store = this.options.store; store && store.set && store.set(this); }, /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. * @param {HTMLElement} el * @param {String} [selector] default: `options.draggable` * @returns {HTMLElement|null} */ closest: function (el, selector) { return _closest(el, selector || this.options.draggable, this.el, false); }, /** * Set/get option * @param {string} name * @param {*} [value] * @returns {*} */ option: function (name, value) { var options = this.options; if (value === void 0) { return options[name]; } else { options[name] = value; if (name === 'group') { _prepareGroup(options); } } }, /** * Destroy */ destroy: function () { var el = this.el; el[expando] = null; _off(el, 'mousedown', this._onTapStart); _off(el, 'touchstart', this._onTapStart); _off(el, 'pointerdown', this._onTapStart); if (this.nativeDraggable) { _off(el, 'dragover', this); _off(el, 'dragenter', this); } // Remove draggable attributes Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) { el.removeAttribute('draggable'); }); touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1); this._onDrop(); this.el = el = null; }, _hideClone: function() { if (!cloneEl.cloneHidden) { _css(cloneEl, 'display', 'none'); cloneEl.cloneHidden = true; } }, _showClone: function(putSortable) { if (putSortable.lastPutMode !== 'clone') { this._hideClone(); return; } if (cloneEl.cloneHidden) { // show clone at dragEl or original position if (rootEl.contains(dragEl) && !this.options.group.revertClone) { rootEl.insertBefore(cloneEl, dragEl); } else if (nextEl) { rootEl.insertBefore(cloneEl, nextEl); } else { rootEl.appendChild(cloneEl); } if (this.options.group.revertClone) { this._animate(dragEl, cloneEl); } _css(cloneEl, 'display', ''); cloneEl.cloneHidden = false; } } }; function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) { if (el) { ctx = ctx || document; do { if ((selector === '>*' && el.parentNode === ctx) || _matches(el, selector) || (includeCTX && el === ctx)) { return el; } if (el === ctx) break; /* jshint boss:true */ } while (el = _getParentOrHost(el)); } return null; } function _getParentOrHost(el) { return (el.host && el !== document && el.host.nodeType) ? el.host : el.parentNode; } function _globalDragOver(/**Event*/evt) { if (evt.dataTransfer) { evt.dataTransfer.dropEffect = 'move'; } evt.cancelable && evt.preventDefault(); } function _on(el, event, fn) { el.addEventListener(event, fn, captureMode); } function _off(el, event, fn) { el.removeEventListener(event, fn, captureMode); } function _toggleClass(el, name, state) { if (el && name) { if (el.classList) { el.classList[state ? 'add' : 'remove'](name); } else { var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' '); el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' '); } } } function _css(el, prop, val) { var style = el && el.style; if (style) { if (val === void 0) { if (document.defaultView && document.defaultView.getComputedStyle) { val = document.defaultView.getComputedStyle(el, ''); } else if (el.currentStyle) { val = el.currentStyle; } return prop === void 0 ? val : val[prop]; } else { if (!(prop in style)) { prop = '-webkit-' + prop; } style[prop] = val + (typeof val === 'string' ? '' : 'px'); } } } function _find(ctx, tagName, iterator) { if (ctx) { var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length; if (iterator) { for (; i < n; i++) { iterator(list[i], i); } } return list; } return []; } function _dispatchEvent(sortable, rootEl, name, targetEl, toEl, fromEl, startIndex, newIndex, originalEvt) { sortable = (sortable || rootEl[expando]); var evt, options = sortable.options, onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1); // Support for new CustomEvent feature if (window.CustomEvent) { evt = new CustomEvent(name, { bubbles: true, cancelable: true }); } else { evt = document.createEvent('Event'); evt.initEvent(name, true, true); } evt.to = toEl || rootEl; evt.from = fromEl || rootEl; evt.item = targetEl || rootEl; evt.clone = cloneEl; evt.oldIndex = startIndex; evt.newIndex = newIndex; evt.originalEvent = originalEvt; rootEl.dispatchEvent(evt); if (options[onName]) { options[onName].call(sortable, evt); } } function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvt, willInsertAfter) { var evt, sortable = fromEl[expando], onMoveFn = sortable.options.onMove, retVal; // Support for new CustomEvent feature if (window.CustomEvent) { evt = new CustomEvent('move', { bubbles: true, cancelable: true }); } else { evt = document.createEvent('Event'); evt.initEvent('move', true, true); } evt.to = toEl; evt.from = fromEl; evt.dragged = dragEl; evt.draggedRect = dragRect; evt.related = targetEl || toEl; evt.relatedRect = targetRect || toEl.getBoundingClientRect(); evt.willInsertAfter = willInsertAfter; evt.originalEvent = originalEvt; fromEl.dispatchEvent(evt); if (onMoveFn) { retVal = onMoveFn.call(sortable, evt, originalEvt); } return retVal; } function _disableDraggable(el) { el.draggable = false; } function _unsilent() { _silent = false; } function _getChild(el, childNum, options) { var currentChild = 0, i = 0, children = el.children ; while (i < children.length) { if ( children[i].style.display !== 'none' && children[i] !== ghostEl && children[i] !== dragEl && _closest(children[i], options.draggable, el, false) ) { if (currentChild === childNum) { return children[i]; } currentChild++; } i++; } return null; } function _lastChild(el) { var last = el.lastElementChild; if (last === ghostEl) { last = el.children[el.childElementCount - 2]; } return last || null; } function _ghostIsLast(evt, axis, el) { var elRect = _lastChild(el).getBoundingClientRect(), mouseOnAxis = axis === 'vertical' ? evt.clientY : evt.clientX, mouseOnOppAxis = axis === 'vertical' ? evt.clientX : evt.clientY, targetS2 = axis === 'vertical' ? elRect.bottom : elRect.right, targetS1Opp = axis === 'vertical' ? elRect.left : elRect.top, targetS2Opp = axis === 'vertical' ? elRect.right : elRect.bottom ; return ( mouseOnOppAxis > targetS1Opp && mouseOnOppAxis < targetS2Opp && mouseOnAxis > targetS2 ); } function _getSwapDirection(evt, target, axis, swapThreshold, invertedSwapThreshold, invertSwap, inside) { var targetRect = target.getBoundingClientRect(), mouseOnAxis = axis === 'vertical' ? evt.clientY : evt.clientX, targetLength = axis === 'vertical' ? targetRect.height : targetRect.width, targetS1 = axis === 'vertical' ? targetRect.top : targetRect.left, targetS2 = axis === 'vertical' ? targetRect.bottom : targetRect.right, dragRect = dragEl.getBoundingClientRect(), dragLength = axis === 'vertical' ? dragRect.height : dragRect.width, invert = false ; var dragStyle = _css(dragEl); dragLength += parseInt(dragStyle.marginLeft) + parseInt(dragStyle.marginRight); if (!invertSwap) { // Never invert or create dragEl shadow when width causes mouse to move past the end of regular swapThreshold if (inside && dragLength < targetLength * swapThreshold) { // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2 // check if past first invert threshold on side opposite of lastDirection if (!pastFirstInvertThresh && (lastDirection === 1 ? ( mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 ) : ( mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2 ) ) ) { // past first invert threshold, do not restrict inverted threshold to dragEl shadow pastFirstInvertThresh = true; } if (!pastFirstInvertThresh) { var dragS1 = axis === 'vertical' ? dragRect.top : dragRect.left, dragS2 = axis === 'vertical' ? dragRect.bottom : dragRect.right ; // dragEl shadow if ( lastDirection === 1 ? ( mouseOnAxis < targetS1 + dragLength // over dragEl shadow ) : ( mouseOnAxis > targetS2 - dragLength ) ) { return lastDirection * -1; } } else { invert = true; } } else { // Regular if ( mouseOnAxis > targetS1 + (targetLength * (1 - swapThreshold) / 2) && mouseOnAxis < targetS2 - (targetLength * (1 - swapThreshold) / 2) ) { return ((mouseOnAxis > targetS1 + targetLength / 2) ? -1 : 1); } } } invert = invert || invertSwap; if (invert) { // Invert of regular if ( mouseOnAxis < targetS1 + (targetLength * invertedSwapThreshold / 2) || mouseOnAxis > targetS2 - (targetLength * invertedSwapThreshold / 2) ) { return ((mouseOnAxis > targetS1 + targetLength / 2) ? 1 : -1); } } return 0; } /** * Generate id * @param {HTMLElement} el * @returns {String} * @private */ function _generateId(el) { var str = el.tagName + el.className + el.src + el.href + el.textContent, i = str.length, sum = 0; while (i--) { sum += str.charCodeAt(i); } return sum.toString(36); } /** * Returns the index of an element within its parent for a selected set of * elements * @param {HTMLElement} el * @param {selector} selector * @return {number} */ function _index(el, selector) { var index = 0; if (!el || !el.parentNode) { return -1; } while (el && (el = el.previousElementSibling)) { if ((el.nodeName.toUpperCase() !== 'TEMPLATE') && (selector === '>*' || _matches(el, selector))) { index++; } } return index; } function _matches(/**HTMLElement*/el, /**String*/selector) { if (el) { try { if (el.matches) { return el.matches(selector); } else if (el.msMatchesSelector) { return el.msMatchesSelector(selector); } } catch(_) { return false; } } return false; } var _throttleTimeout; function _throttle(callback, ms) { return function () { if (!_throttleTimeout) { var args = arguments, _this = this ; _throttleTimeout = setTimeout(function () { if (args.length === 1) { callback.call(_this, args[0]); } else { callback.apply(_this, args); } _throttleTimeout = void 0; }, ms); } }; } function _cancelThrottle() { clearTimeout(_throttleTimeout); _throttleTimeout = void 0; } function _extend(dst, src) { if (dst && src) { for (var key in src) { if (src.hasOwnProperty(key)) { dst[key] = src[key]; } } } return dst; } function _clone(el) { if (Polymer && Polymer.dom) { return Polymer.dom(el).cloneNode(true); } else if ($) { return $(el).clone(true)[0]; } else { return el.cloneNode(true); } } function _saveInputCheckedState(root) { savedInputChecked.length = 0; var inputs = root.getElementsByTagName('input'); var idx = inputs.length; while (idx--) { var el = inputs[idx]; el.checked && savedInputChecked.push(el); } } function _nextTick(fn) { return setTimeout(fn, 0); } function _cancelNextTick(id) { return clearTimeout(id); } function _preventScroll(evt) { if (Sortable.active && evt.cancelable) { evt.preventDefault(); } } // Export utils Sortable.utils = { on: _on, off: _off, css: _css, find: _find, is: function (el, selector) { return !!_closest(el, selector, el, false); }, extend: _extend, throttle: _throttle, closest: _closest, toggleClass: _toggleClass, clone: _clone, index: _index, nextTick: _nextTick, cancelNextTick: _cancelNextTick, detectDirection: _detectDirection, getChild: _getChild }; /** * Create sortable instance * @param {HTMLElement} el * @param {Object} [options] */ Sortable.create = function (el, options) { return new Sortable(el, options); }; // Export Sortable.version = '1.8.0-rc1'; return Sortable; });
extend1994/cdnjs
ajax/libs/Sortable/1.8.0-rc1/Sortable.js
JavaScript
mit
50,600
import { isElement, isValidElementType, ForwardRef } from 'react-is'; import unitless from '@emotion/unitless'; import validAttr from '@emotion/is-prop-valid'; import React, { useContext, useMemo, createElement, useState, useDebugValue, useEffect } from 'react'; import Stylis from 'stylis/stylis.min'; import _insertRulePlugin from 'stylis-rule-sheet'; import PropTypes from 'prop-types'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } 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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); // var isPlainObject = (function (x) { return typeof x === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // function getComponentName(target) { return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe target.displayName || // $FlowFixMe target.name || 'Component'; } // function isStatelessFunction(test) { return typeof test === 'function' && !(test.prototype && test.prototype.isReactComponent); } // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled'; var SC_ATTR_ACTIVE = 'active'; var SC_VERSION_ATTR = 'data-styled-version'; var SC_VERSION = "5.0.0-4.canary-sheet"; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; var DISABLE_SPEEDY = typeof SC_DISABLE_SPEEDY === 'boolean' && SC_DISABLE_SPEEDY || process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; // var ELEMENT_TYPE = 1; /* Node.ELEMENT_TYPE */ /** Find last style element if any inside target */ var findLastStyleTag = function findLastStyleTag(target) { var childNodes = target.childNodes; for (var i = childNodes.length; i >= 0; i--) { var child = childNodes[i]; if (child && child.nodeType === ELEMENT_TYPE && child.hasAttribute(SC_ATTR)) { return child; } } return undefined; }; /** Create a style element inside `target` or <head> after the last */ var makeStyleTag = function makeStyleTag(target) { var head = document.head; var parent = target || head; var style = document.createElement('style'); var prevStyle = findLastStyleTag(parent); var nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null; style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE); style.setAttribute(SC_VERSION_ATTR, SC_VERSION); parent.insertBefore(style, nextSibling); return style; }; /** Get the CSSStyleSheet instance for a given style element */ var getSheet = function getSheet(tag) { if (tag.sheet) { return tag.sheet; } // Avoid Firefox quirk where the style element might not have a sheet property var _document = document, styleSheets = _document.styleSheets; for (var i = 0, l = styleSheets.length; i < l; i++) { var sheet = styleSheets[i]; if (sheet.ownerNode === tag) { return sheet; } } throw new TypeError("CSSStyleSheet could not be found on HTMLStyleElement"); }; // /** CSSStyleSheet-like Tag abstraction for CSS rules */ /** Create a CSSStyleSheet-like tag depending on the environment */ var makeTag = function makeTag(isServer, target) { if (!IS_BROWSER) { return new VirtualTag(target); } else if (DISABLE_SPEEDY) { return new TextTag(target); } else { return new SpeedyTag(target); } }; /** A Tag that wraps CSSOM's CSSStyleSheet API directly */ var SpeedyTag = /*#__PURE__*/ function () { function SpeedyTag(target) { var element = this.element = makeStyleTag(target); // Avoid Edge bug where empty style elements don't create sheets element.appendChild(document.createTextNode('')); this.sheet = getSheet(element); this.length = 0; } var _proto = SpeedyTag.prototype; _proto.insertRule = function insertRule(index, rule) { try { this.sheet.insertRule(rule, index); this.length++; return true; } catch (_error) { return false; } }; _proto.deleteRule = function deleteRule(index) { this.sheet.deleteRule(index); this.length--; }; _proto.getRule = function getRule(index) { if (index < this.length) { return this.sheet.cssRules[index].cssText; } else { return ''; } }; return SpeedyTag; }(); /** A Tag that emulates the CSSStyleSheet API but uses text nodes */ var TextTag = /*#__PURE__*/ function () { function TextTag(target) { var element = this.element = makeStyleTag(target); this.nodes = element.childNodes; this.length = 0; } var _proto2 = TextTag.prototype; _proto2.insertRule = function insertRule(index, rule) { if (index <= this.length && index >= 0) { var node = document.createTextNode(rule); var refNode = this.nodes[index]; this.element.insertBefore(node, refNode || null); this.length++; return true; } else { return false; } }; _proto2.deleteRule = function deleteRule(index) { this.element.removeChild(this.nodes[index]); this.length--; }; _proto2.getRule = function getRule(index) { if (index < this.length) { return this.nodes[index].textContent; } else { return ''; } }; return TextTag; }(); /** A completely virtual (server-side) Tag that doesn't manipulate the DOM */ var VirtualTag = /*#__PURE__*/ function () { function VirtualTag(_target) { this.rules = []; this.length = 0; } var _proto3 = VirtualTag.prototype; _proto3.insertRule = function insertRule(index, rule) { if (index <= this.length) { this.rules.splice(index, 0, rule); this.length++; return true; } else { return false; } }; _proto3.deleteRule = function deleteRule(index) { this.rules.splice(index, 1); this.length--; }; _proto3.getRule = function getRule(index) { if (index < this.length) { return this.rules[index]; } else { return ''; } }; return VirtualTag; }(); // /* eslint-disable no-use-before-define */ /** Group-aware Tag that sorts rules by indices */ /** Create a GroupedTag with an underlying Tag implementation */ var makeGroupedTag = function makeGroupedTag(tag) { return new DefaultGroupedTag(tag); }; var BASE_SIZE = 1 << 8; var DefaultGroupedTag = /*#__PURE__*/ function () { function DefaultGroupedTag(tag) { this.groupSizes = new Uint32Array(BASE_SIZE); this.length = BASE_SIZE; this.tag = tag; } var _proto = DefaultGroupedTag.prototype; _proto.indexOfGroup = function indexOfGroup(group) { var index = 0; for (var i = 0; i < group; i++) { index += this.groupSizes[i]; } return index; }; _proto.insertRules = function insertRules(group, rules) { if (group >= this.groupSizes.length) { var oldBuffer = this.groupSizes; var oldSize = oldBuffer.length; var newSize = BASE_SIZE << (group / BASE_SIZE | 0); this.groupSizes = new Uint32Array(newSize); this.groupSizes.set(oldBuffer); this.length = newSize; for (var i = oldSize; i < newSize; i++) { this.groupSizes[i] = 0; } } var startIndex = this.indexOfGroup(group + 1); for (var _i = 0, l = rules.length; _i < l; _i++) { if (this.tag.insertRule(startIndex + _i, rules[_i])) { this.groupSizes[group]++; } } }; _proto.clearGroup = function clearGroup(group) { if (group < this.length) { var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; this.groupSizes[group] = 0; for (var i = startIndex; i < endIndex; i++) { this.tag.deleteRule(startIndex); } } }; _proto.getGroup = function getGroup(group) { var css = ''; if (group >= this.length || this.groupSizes[group] === 0) { return css; } var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; for (var i = startIndex; i < endIndex; i++) { css += this.tag.getRule(i) + "\n"; } return css; }; return DefaultGroupedTag; }(); // var groupIDRegister = new Map(); var reverseRegister = new Map(); var nextFreeGroup = 1; var getGroupForId = function getGroupForId(id) { if (groupIDRegister.has(id)) { return groupIDRegister.get(id); } var group = nextFreeGroup++; groupIDRegister.set(id, group); reverseRegister.set(group, id); return group; }; var getIdForGroup = function getIdForGroup(group) { return reverseRegister.get(group); }; var setGroupForId = function setGroupForId(id, group) { if (group >= nextFreeGroup) { nextFreeGroup = group + 1; } groupIDRegister.set(id, group); reverseRegister.set(group, id); }; // var PLAIN_RULE_TYPE = 1; var SELECTOR = "style[" + SC_ATTR + "][" + SC_VERSION_ATTR + "=\"" + SC_VERSION + "\"]"; var MARKER_RE = new RegExp("^" + SC_ATTR + "\\.g(\\d+)\\[id=\"([\\w\\d-]+)\"\\]"); var outputSheet = function outputSheet(sheet) { var tag = sheet.getTag(); var length = tag.length; var css = ''; for (var group = 0; group < length; group++) { var id = getIdForGroup(group); if (id === undefined) continue; var names = sheet.names.get(id); var rules = tag.getGroup(group); if (names === undefined || rules.length === 0) continue; var selector = SC_ATTR + ".g" + group + "[id=\"" + id + "\"]"; var content = ''; if (names !== undefined) { names.forEach(function (name) { if (name.length > 0) { content += name + ","; } }); } // NOTE: It's easier to collect rules and have the marker // after the actual rules to simplify the rehydration css += rules + selector; if (content.length > 0) { css += "{content:\"" + content + "\"}\n"; } else { css += '{}\n'; } } return css; }; var rehydrateNamesFromContent = function rehydrateNamesFromContent(sheet, id, content) { var names = content.slice(1, -1).split(','); for (var i = 0, l = names.length; i < l; i++) { var name = names[i]; if (name.length > 0) { sheet.registerName(id, name); } } }; var rehydrateSheetFromTag = function rehydrateSheetFromTag(sheet, style) { var _getSheet = getSheet(style), cssRules = _getSheet.cssRules; var rules = []; for (var i = 0, l = cssRules.length; i < l; i++) { var cssRule = cssRules[i]; if (cssRule.type !== PLAIN_RULE_TYPE) { rules.push(cssRule.cssText); } else { var marker = cssRule.selectorText.match(MARKER_RE); if (marker !== null) { var group = parseInt(marker[1], 10) | 0; var id = marker[2]; var content = cssRule.style.content; if (group !== 0) { // Rehydrate componentId to group index mapping setGroupForId(id, group); // Rehydrate names and rules rehydrateNamesFromContent(sheet, id, content); sheet.getTag().insertRules(group, rules); } rules.length = 0; } else { rules.push(cssRule.cssText); } } } }; var rehydrateSheet = function rehydrateSheet(sheet) { var nodes = document.querySelectorAll(SELECTOR); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) { rehydrateSheetFromTag(sheet, node); if (node.parentNode) { node.parentNode.removeChild(node); } } } }; // var SHOULD_REHYDRATE = IS_BROWSER; /** Contains the main stylesheet logic for stringification and caching */ var StyleSheet = /*#__PURE__*/ function () { /** Register a group ID to give it an index */ StyleSheet.registerId = function registerId(id) { return getGroupForId(id); }; function StyleSheet(isServer, target) { this.names = new Map(); this.isServer = isServer; this.target = target; // We rehydrate only once and use the sheet that is // created first if (!isServer && IS_BROWSER && SHOULD_REHYDRATE) { SHOULD_REHYDRATE = false; rehydrateSheet(this); } } /** Lazily initialises a GroupedTag for when it's actually needed */ var _proto = StyleSheet.prototype; _proto.getTag = function getTag() { if (this.tag === undefined) { var tag = makeTag(this.isServer, this.target); this.tag = makeGroupedTag(tag); } return this.tag; } /** Check whether a name is known for caching */ ; _proto.hasNameForId = function hasNameForId(id, name) { return this.names.has(id) && this.names.get(id).has(name); } /** Mark a group's name as known for caching */ ; _proto.registerName = function registerName(id, name) { getGroupForId(id); if (!this.names.has(id)) { var groupNames = new Set(); groupNames.add(name); this.names.set(id, groupNames); } else { this.names.get(id).add(name); } } /** Insert new rules which also marks the name as known */ ; _proto.insertRules = function insertRules(id, name, rules) { this.registerName(id, name); this.getTag().insertRules(getGroupForId(id), rules); } /** Clears all cached names for a given group ID */ ; _proto.clearNames = function clearNames(id) { if (this.names.has(id)) { this.names.get(id).clear(); } } /** Clears all rules for a given group ID */ ; _proto.clearRules = function clearRules(id) { this.getTag().clearGroup(getGroupForId(id)); this.clearNames(id); } /** Clears the entire tag which deletes all rules but not its names */ ; _proto.clearTag = function clearTag() { // NOTE: This does not clear the names, since it's only used during SSR // so that we can continuously output only new rules this.tag = undefined; } /** Outputs the current sheet as a CSS string with markers for SSR */ ; _proto.toString = function toString() { return outputSheet(this); }; return StyleSheet; }(); // // /** * Parse errors.md and turn it into a simple hash of code: message */ var ERRORS = process.env.NODE_ENV !== 'production' ? { "1": "Cannot create styled-component for component: %s.\n\n", "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n", "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n", "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document `<head>`\n\n", "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n", "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n", "12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper (see https://www.styled-components.com/docs/api#css), which ensures the styles are injected correctly.\n\n", "13": "%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n" } : {}; /** * super basic version of sprintf */ function format() { var a = arguments.length <= 0 ? undefined : arguments[0]; var b = []; for (var c = 1, len = arguments.length; c < len; c += 1) { b.push(c < 0 || arguments.length <= c ? undefined : arguments[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ var StyledComponentsError = /*#__PURE__*/ function (_Error) { _inheritsLoose(StyledComponentsError, _Error); function StyledComponentsError(code) { var _this; for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (process.env.NODE_ENV === 'production') { _this = _Error.call(this, "An error occurred. See https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/utils/errors.md#" + code + " for more information. " + (interpolations ? "Additional arguments: " + interpolations.join(', ') : '')) || this; } else { _this = _Error.call(this, format.apply(void 0, [ERRORS[code]].concat(interpolations)).trim()) || this; } return _assertThisInitialized(_this); } return StyledComponentsError; }(_wrapNativeSuper(Error)); // var Keyframes = /*#__PURE__*/ function () { function Keyframes(name, rules) { var _this = this; this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { styleSheet.insertRules(_this.id, _this.name, _this.rules); } }; this.toString = function () { throw new StyledComponentsError(12, String(_this.name)); }; this.name = name; this.rules = rules; this.id = "sc-keyframes-" + name; } var _proto = Keyframes.prototype; _proto.getName = function getName() { return this.name; }; return Keyframes; }(); // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // function addUnitIfNeeded(name, value) { // https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133 // $FlowFixMe if (value == null || typeof value === 'boolean' || value === '') { return ''; } if (typeof value === 'number' && value !== 0 && !(name in unitless)) { return value + "px"; // Presumes implicit 'px' suffix for unitless numbers } return String(value).trim(); } // /** * It's falsish not falsy because 0 is allowed. */ var isFalsish = function isFalsish(chunk) { return chunk === undefined || chunk === null || chunk === false || chunk === ''; }; var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { return !isFalsish(obj[key]); }).map(function (key) { if (isPlainObject(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName(key) + ": " + addUnitIfNeeded(key, obj[key]) + ";"; }).join(' '); return prevKey ? prevKey + " {\n " + css + "\n}" : css; }; function flatten(chunk, executionContext, styleSheet) { if (Array.isArray(chunk)) { var ruleSet = []; for (var i = 0, len = chunk.length, result; i < len; i += 1) { result = flatten(chunk[i], executionContext, styleSheet); if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result); } return ruleSet; } if (isFalsish(chunk)) { return ''; } /* Handle other components */ if (isStyledComponent(chunk)) { return "." + chunk.styledComponentId; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (isStatelessFunction(chunk) && executionContext) { var _result = chunk(executionContext); if (process.env.NODE_ENV !== 'production' && isElement(_result)) { // eslint-disable-next-line no-console console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details."); } return flatten(_result, executionContext, styleSheet); } else return chunk; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); return chunk.getName(); } else return chunk; } /* Handle objects */ return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString(); } // function css(styles) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } function constructWithOptions(componentConstructor, tag, options) { if (options === void 0) { options = EMPTY_OBJECT; } if (!isValidElementType(tag)) { throw new StyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(void 0, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; /* Modify/inject new props at runtime */ templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: Array.prototype.concat(options.attrs, attrs).filter(Boolean) })); }; return templateFunction; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x; /* get a char and divide by alphabet-length */ for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // // version of djb2 where we pretend that we're still looping over // the same string var phash = function phash(h, x) { h = h | 0; for (var i = 0, l = x.length | 0; i < l; i++) { h = (h << 5) + h + x.charCodeAt(i); } return h; }; // This is a djb2 hashing function var hash = function hash(x) { return phash(5381 | 0, x) >>> 0; }; var hasher = function hasher(str) { return generateAlphabeticName(hash(str)); }; // var stylis = new Stylis({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: false // NOTE: This means "autocomplete missing semicolons" }); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = _insertRulePlugin(function (rule) { parsingRules.push(rule); }); var _componentId; var _selector; var _selectorRegexp; var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) { if ( // the first self-ref is always untouched offset > 0 && // there should be at least two self-refs to do a replacement (.b > .b) string.slice(0, offset).indexOf(_selector) !== -1 && // no consecutive self refs (.b.b); that is a precedence boost and treated differently string.slice(offset - _selector.length, offset) !== _selector) { return "." + _componentId; } return match; }; /** * When writing a style like * * & + & { * color: red; * } * * The second ampersand should be a reference to the static component class. stylis * has no knowledge of static class so we have to intelligently replace the base selector. */ var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) { if (context === 2 && selectors.length && selectors[0].lastIndexOf(_selector) > 0) { // eslint-disable-next-line no-param-reassign selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer); } }; stylis.use([selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]); var COMMENT_REGEX = /^\s*\/\/.*$/gm; function stringifyRules(css, selector, prefix, componentId) { if (componentId === void 0) { componentId = '&'; } var flatCSS = css.replace(COMMENT_REGEX, ''); var cssStr = selector && prefix ? prefix + " " + selector + " { " + flatCSS + " }" : flatCSS; // stylis has no concept of state to be passed to plugins // but since JS is single=threaded, we can rely on that to ensure // these properties stay in sync with the current stylis run _componentId = componentId; _selector = selector; _selectorRegexp = new RegExp("\\" + _selector + "\\b", 'g'); return stylis(prefix || !selector ? '' : selector, cssStr); } // function hasFunctionObjectKey(obj) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in obj) { if (isFunction(obj[key])) { return true; } } return false; } function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule, attrs)) { return false; } else if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } if (attrs.some(function (x) { return isFunction(x) || hasFunctionObjectKey(x); })) return false; return true; } // var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = /*#__PURE__*/ function () { function ComponentStyle(rules, attrs, componentId) { this.rules = rules; this.isStatic = !isHMREnabled && IS_BROWSER && isStaticRules(rules, attrs); this.componentId = componentId; this.baseHash = hash(componentId); // NOTE: This registers the componentId, which ensures a consistent order // for this component's styles compared to others StyleSheet.registerId(componentId); } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ var _proto = ComponentStyle.prototype; _proto.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var componentId = this.componentId; if (this.isStatic) { if (!styleSheet.hasNameForId(componentId, componentId)) { var cssStatic = flatten(this.rules, executionContext, styleSheet).join(''); var cssStaticFormatted = stringifyRules(cssStatic, "." + componentId, undefined, componentId); styleSheet.insertRules(componentId, componentId, cssStaticFormatted); } return componentId; } else { var length = this.rules.length; var i = 0; var dynamicHash = this.baseHash; var css = ''; for (i = 0; i < length; i++) { var partRule = this.rules[i]; if (typeof partRule === 'string') { css += partRule; } else { var partChunk = flatten(partRule, executionContext, styleSheet); var partString = Array.isArray(partChunk) ? partChunk.join('') : partChunk; dynamicHash = phash(dynamicHash, partString + i); css += partString; } } var name = generateAlphabeticName(dynamicHash >>> 0); if (!styleSheet.hasNameForId(componentId, name)) { var cssFormatted = stringifyRules(css, "." + name, undefined, componentId); styleSheet.insertRules(componentId, name, cssFormatted); } return name; } }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn("Over " + LIMIT + " classes were generated for component " + displayName + ". \n" + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // var determineTheme = (function (props, fallbackTheme, defaultProps) { if (defaultProps === void 0) { defaultProps = EMPTY_OBJECT; } // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. /* eslint-disable react/prop-types, flowtype-errors/show-errors */ var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false; var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme; /* eslint-enable */ return theme; }); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g; var dashesAtEnds = /(^-|-$)/g; /** * TODO: Explore using CSS.escape when it becomes more available * in evergreen browsers. */ function escape(str) { return str // Replace all possible CSS selectors .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end .replace(dashesAtEnds, ''); } // function isTag(target) { return typeof target === 'string' && (process.env.NODE_ENV !== 'production' ? target.charAt(0) === target.charAt(0).toLowerCase() : true); } // function generateDisplayName(target) { // $FlowFixMe return isTag(target) ? "styled." + target : "Styled(" + getComponentName(target) + ")"; } var _TYPE_STATICS; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDerivedStateFromProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[ForwardRef] = { $$typeof: true, render: true }, _TYPE_STATICS); var defineProperty = Object.defineProperty, getOwnPropertyNames = Object.getOwnPropertyNames, _Object$getOwnPropert = Object.getOwnPropertySymbols, getOwnPropertySymbols = _Object$getOwnPropert === void 0 ? function () { return []; } : _Object$getOwnPropert, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getPrototypeOf = Object.getPrototypeOf, objectPrototype = Object.prototype; var arrayPrototype = Array.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent), // $FlowFixMe getOwnPropertySymbols(sourceComponent)); var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS; var i = keys.length; var descriptor; var key; // eslint-disable-next-line no-plusplus while (i--) { key = keys[i]; if ( // $FlowFixMe !KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && // $FlowFixMe !(targetStatics && targetStatics[key])) { descriptor = getOwnPropertyDescriptor(sourceComponent, key); if (descriptor) { try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) { /* fail silently */ } } } } return targetComponent; } return targetComponent; } // function isDerivedReactComponent(fn) { return !!(fn && fn.prototype && fn.prototype.isReactComponent); } // // Helper to call a given function, only once var once = (function (cb) { var called = false; // $FlowFixMe this works if F is "(...any[]) => any" but that would imply the return value si forwarded return function () { if (!called) { called = true; cb.apply(void 0, arguments); } }; }); var ThemeContext = React.createContext(); var ThemeConsumer = ThemeContext.Consumer; function useMergedTheme(theme, outerTheme) { if (isFunction(theme)) { var mergedTheme = theme(outerTheme); if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || typeof mergedTheme !== 'object')) { throw new StyledComponentsError(7); } return mergedTheme; } if (theme === null || Array.isArray(theme) || typeof theme !== 'object') { throw new StyledComponentsError(8); } return outerTheme ? _extends({}, outerTheme, theme) : theme; } /** * Provide a theme to an entire react component tree via context */ function ThemeProvider(props) { var outerTheme = useContext(ThemeContext); // NOTE: can't really memoize with props.theme as that'd cause incorrect memoization when it's a function var themeContext = useMergedTheme(props.theme, outerTheme); if (!props.children) { return null; } return React.createElement(ThemeContext.Provider, { value: themeContext }, React.Children.only(props.children)); } // var StyleSheetContext = React.createContext(); var StyleSheetConsumer = StyleSheetContext.Consumer; var masterSheet = new StyleSheet(false); function useStyleSheet() { var fromContext = useContext(StyleSheetContext); return fromContext !== undefined ? fromContext : masterSheet; } function useStyleSheetProvider(sheet, target) { return useMemo(function () { if (sheet) { return sheet; } else if (target) { return new StyleSheet(false, target); } else { throw new StyledComponentsError(4); } }, [sheet, target]); } function StyleSheetManager(props) { var sheet = useStyleSheetProvider(props.sheet, props.target); return React.createElement(StyleSheetContext.Provider, { value: sheet }, process.env.NODE_ENV !== 'production' ? React.Children.only(props.children) : props.children); } process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = { sheet: PropTypes.instanceOf(StyleSheet), target: PropTypes.shape({ appendChild: PropTypes.func.isRequired }) } : void 0; /* global $Call */ var identifiers = {}; /* We depend on components having unique IDs */ function generateId(displayName, parentComponentId) { var name = typeof displayName !== 'string' ? 'sc' : escape(displayName); // Ensure that no displayName can lead to duplicate componentIds var nr = (identifiers[name] || 0) + 1; identifiers[name] = nr; var componentId = name + "-" + hasher(name + nr); return parentComponentId ? parentComponentId + "-" + componentId : componentId; } function useResolvedAttrs(theme, props, attrs, utils) { if (theme === void 0) { theme = EMPTY_OBJECT; } // NOTE: can't memoize this // returns [context, resolvedAttrs] // where resolvedAttrs is only the things injected by the attrs themselves var context = _extends({}, props, { theme: theme }); var resolvedAttrs = {}; attrs.forEach(function (attrDef) { var resolvedAttrDef = attrDef; var attrDefWasFn = false; var attr; var key; if (isFunction(resolvedAttrDef)) { resolvedAttrDef = resolvedAttrDef(context); attrDefWasFn = true; } /* eslint-disable guard-for-in */ for (key in resolvedAttrDef) { attr = resolvedAttrDef[key]; if (!attrDefWasFn) { if (isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr)) { if (process.env.NODE_ENV !== 'production') { utils.warnAttrsFnObjectKeyDeprecated(key); } attr = attr(context); if (process.env.NODE_ENV !== 'production' && React.isValidElement(attr)) { utils.warnNonStyledComponentAttrsObjectKey(key); } } } resolvedAttrs[key] = attr; context[key] = attr; } /* eslint-enable */ }); return [context, resolvedAttrs]; } function useInjectedStyle(componentStyle, hasAttrs, resolvedAttrs, utils, warnTooManyClasses) { var styleSheet = useStyleSheet(); // statically styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names var isStatic = componentStyle.isStatic && !hasAttrs; var className = isStatic ? componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet) : componentStyle.generateAndInjectStyles(resolvedAttrs, styleSheet); if (process.env.NODE_ENV !== 'production' && !isStatic && warnTooManyClasses) { warnTooManyClasses(className); } useDebugValue(className); return className; } // TODO: convert these all to individual hooks, if possible function developmentDeprecationWarningsFactory(displayNameArg) { var displayName = displayNameArg || 'Unknown'; return { warnInnerRef: once(function () { return (// eslint-disable-next-line no-console console.warn("The \"innerRef\" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use \"ref\" instead like a typical component. \"innerRef\" was detected on component \"" + displayName + "\".") ); }), warnAttrsFnObjectKeyDeprecated: once(function (key) { return (// eslint-disable-next-line no-console console.warn("Functions as object-form attrs({}) keys are now deprecated and will be removed in a future version of styled-components. Switch to the new attrs(props => ({})) syntax instead for easier and more powerful composition. The attrs key in question is \"" + key + "\" on component \"" + displayName + "\".") ); }), warnNonStyledComponentAttrsObjectKey: once(function (key) { return (// eslint-disable-next-line no-console console.warn("It looks like you've used a non styled-component as the value for the \"" + key + "\" prop in an object-form attrs constructor of \"" + displayName + "\".\n" + 'You should use the new function-form attrs constructor which avoids this issue: attrs(props => ({ yourStuff }))\n' + "To continue using the deprecated object syntax, you'll need to wrap your component prop in a function to make it available inside the styled component (you'll still get the deprecation warning though.)\n" + ("For example, { " + key + ": () => InnerComponent } instead of { " + key + ": InnerComponent }")) ); }) }; } function useDevelopmentDeprecationWarnings(displayName) { return useState(function () { return developmentDeprecationWarningsFactory(displayName); })[0]; } var useDeprecationWarnings = process.env.NODE_ENV !== 'production' ? useDevelopmentDeprecationWarnings : // NOTE: return value must only be accessed in non-production, of course // $FlowFixMe function () {}; function useStyledComponentImpl(forwardedComponent, props, forwardedRef) { var componentAttrs = forwardedComponent.attrs, componentStyle = forwardedComponent.componentStyle, defaultProps = forwardedComponent.defaultProps, displayName = forwardedComponent.displayName, foldedComponentIds = forwardedComponent.foldedComponentIds, styledComponentId = forwardedComponent.styledComponentId, target = forwardedComponent.target; // NOTE: the non-hooks version only subscribes to this when !componentStyle.isStatic, // but that'd be against the rules-of-hooks. We could be naughty and do it anyway as it // should be an immutable value, but behave for now. var theme = determineTheme(props, useContext(ThemeContext), defaultProps); var utils = useDeprecationWarnings(displayName); var _useResolvedAttrs = useResolvedAttrs(theme, props, componentAttrs, utils), context = _useResolvedAttrs[0], attrs = _useResolvedAttrs[1]; var generatedClassName = useInjectedStyle(componentStyle, componentAttrs.length > 0, context, utils, process.env.NODE_ENV !== 'production' ? forwardedComponent.warnTooManyClasses : undefined); // NOTE: this has to be called unconditionally due to the rules of hooks // it will just do nothing if it's not an in-browser development build // NOTE2: there is no (supported) way to know if the wrapped component actually can // receive refs -- just passing refs will trigger warnings on any function component child :( // -- this also means we can't keep doing this check unless StyledComponent is itself a class. // // const refToForward = useCheckClassNameUsage( // forwardedRef, // target, // generatedClassName, // attrs.suppressClassNameWarning // ); var refToForward = forwardedRef; var elementToBeCreated = // $FlowFixMe props.as || // eslint-disable-line react/prop-types attrs.as || target; var isTargetTag = isTag(elementToBeCreated); var computedProps = attrs !== props ? _extends({}, attrs, props) : props; var shouldFilterProps = 'as' in computedProps || isTargetTag; var propsForElement = shouldFilterProps ? {} : _extends({}, computedProps); if (process.env.NODE_ENV !== 'production' && 'innerRef' in computedProps && isTargetTag) { utils.warnInnerRef(); } if (shouldFilterProps) { // eslint-disable-next-line guard-for-in for (var key in computedProps) { if (key !== 'as' && (!isTargetTag || validAttr(key))) { // Don't pass through non HTML tags through to HTML elements propsForElement[key] = computedProps[key]; } } } if ( // $FlowFixMe props.style && // eslint-disable-line react/prop-types attrs.style !== props.style // eslint-disable-line react/prop-types ) { // $FlowFixMe propsForElement.style = _extends({}, attrs.style, props.style); // eslint-disable-line react/prop-types } // $FlowFixMe propsForElement.className = Array.prototype.concat(foldedComponentIds, // $FlowFixMe props.className, // eslint-disable-line react/prop-types styledComponentId, attrs.className, generatedClassName).filter(Boolean).join(' '); // $FlowFixMe propsForElement.ref = refToForward; useDebugValue(styledComponentId); return createElement(elementToBeCreated, propsForElement); } function createStyledComponent(target, options, rules) { var isTargetStyledComp = isStyledComponent(target); var isCompositeComponent = !isTag(target); var _options$displayName = options.displayName, displayName = _options$displayName === void 0 ? generateDisplayName(target) : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === void 0 ? generateId(options.displayName, options.parentComponentId) : _options$componentId, _options$attrs = options.attrs, attrs = _options$attrs === void 0 ? EMPTY_ARRAY : _options$attrs; var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + "-" + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend) var finalAttrs = // $FlowFixMe isTargetStyledComp && target.attrs ? Array.prototype.concat(target.attrs, attrs).filter(Boolean) : attrs; var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend) // $FlowFixMe target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId); /** * forwardRef creates a new interim component, which we'll take advantage of * instead of extending ParentComponent to create _another_ interim class */ // $FlowFixMe this is a forced cast to merge it StyledComponentWrapperProperties var WrappedStyledComponent = React.forwardRef(function (props, ref) { return useStyledComponentImpl(WrappedStyledComponent, props, ref); }); WrappedStyledComponent.attrs = finalAttrs; WrappedStyledComponent.componentStyle = componentStyle; WrappedStyledComponent.displayName = displayName; WrappedStyledComponent.foldedComponentIds = isTargetStyledComp ? // $FlowFixMe Array.prototype.concat(target.foldedComponentIds, target.styledComponentId) : EMPTY_ARRAY; WrappedStyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles WrappedStyledComponent.target = isTargetStyledComp ? // $FlowFixMe target.target : target; // $FlowFixMe WrappedStyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = _objectWithoutPropertiesLoose(options, ["componentId"]); var newComponentId = previousComponentId && previousComponentId + "-" + (isTag(tag) ? tag : escape(getComponentName(tag))); var newOptions = _extends({}, optionsToCopy, { attrs: finalAttrs, componentId: newComponentId }); return createStyledComponent(tag, newOptions, rules); }; if (process.env.NODE_ENV !== 'production') { WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName); } // $FlowFixMe WrappedStyledComponent.toString = function () { return "." + WrappedStyledComponent.styledComponentId; }; if (isCompositeComponent) { hoistNonReactStatics(WrappedStyledComponent, target, { // all SC-specific things should not be hoisted attrs: true, componentStyle: true, displayName: true, foldedComponentIds: true, styledComponentId: true, target: true, withComponent: true }); } return WrappedStyledComponent; } // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'marker', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var styled = function styled(tag) { return constructWithOptions(createStyledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); // var GlobalStyle = /*#__PURE__*/ function () { function GlobalStyle(rules, componentId) { this.rules = rules; this.componentId = componentId; this.isStatic = isStaticRules(rules, EMPTY_ARRAY); StyleSheet.registerId(componentId); } var _proto = GlobalStyle.prototype; _proto.createStyles = function createStyles(executionContext, styleSheet) { var flatCSS = flatten(this.rules, executionContext, styleSheet); var css = stringifyRules(flatCSS.join(''), ''); var id = this.componentId; // NOTE: We use the id as a name as well, since these rules never change styleSheet.insertRules(id, id, css); }; _proto.removeStyles = function removeStyles(styleSheet) { styleSheet.clearRules(this.componentId); }; _proto.renderStyles = function renderStyles(executionContext, styleSheet) { // NOTE: Remove old styles, then inject the new ones this.removeStyles(styleSheet); this.createStyles(executionContext, styleSheet); }; return GlobalStyle; }(); if (IS_BROWSER) { window.scCGSHMRCache = {}; } function createGlobalStyle(strings) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(void 0, [strings].concat(interpolations)); var styledComponentId = "sc-global-" + hasher(JSON.stringify(rules)); var globalStyle = new GlobalStyle(rules, styledComponentId); function GlobalStyleComponent(props) { var styleSheet = useStyleSheet(); var theme = useContext(ThemeContext); if (process.env.NODE_ENV !== 'production' && React.Children.count(props.children)) { // eslint-disable-next-line no-console console.warn("The global style component " + styledComponentId + " was given child JSX. createGlobalStyle does not render children."); } if (globalStyle.isStatic) { globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, styleSheet); } else { var context = _extends({}, props); if (typeof theme !== 'undefined') { context.theme = determineTheme(props, theme); } globalStyle.renderStyles(context, styleSheet); } useEffect(function () { if (IS_BROWSER) { window.scCGSHMRCache[styledComponentId] = (window.scCGSHMRCache[styledComponentId] || 0) + 1; return function () { if (window.scCGSHMRCache[styledComponentId]) { window.scCGSHMRCache[styledComponentId] -= 1; } /** * Depending on the order "render" is called this can cause the styles to be lost * until the next render pass of the remaining instance, which may * not be immediate. */ if (window.scCGSHMRCache[styledComponentId] === 0) { globalStyle.removeStyles(styleSheet); } }; } return undefined; }, []); return null; } return GlobalStyleComponent; } // function keyframes(strings) { /* Warning if you've used keyframes on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.'); } for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(void 0, [strings].concat(interpolations)).join(''); var name = hasher(rules); return new Keyframes(name, stringifyRules(rules, name, '@keyframes')); } // /* eslint-disable camelcase, no-undef */ var getNonce = function getNonce() { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }; // var CLOSING_TAG_R = /^\s*<\/[a-z]/i; var ServerStyleSheet = /*#__PURE__*/ function () { function ServerStyleSheet() { var _this = this; this.getStyleTags = function () { var css = _this.sheet.toString(); var nonce = getNonce(); var attrs = [nonce && "nonce=\"" + nonce + "\"", SC_ATTR, SC_VERSION_ATTR + "=\"" + SC_VERSION + "\""]; var htmlAttr = attrs.filter(Boolean).join(' '); return "<style " + htmlAttr + ">" + css + "</style>"; }; this.getStyleElement = function () { var _props; var props = (_props = {}, _props[SC_ATTR] = '', _props[SC_VERSION_ATTR] = SC_VERSION, _props.dangerouslySetInnerHTML = { __html: _this.sheet.toString() }, _props); var nonce = getNonce(); if (nonce) { props.nonce = nonce; } return React.createElement("style", props); }; this.sheet = new StyleSheet(true); this.sealed = false; } var _proto = ServerStyleSheet.prototype; _proto.collectStyles = function collectStyles(children) { if (this.sealed) { throw new StyledComponentsError(2); } this.sealed = true; return React.createElement(StyleSheetManager, { sheet: this.sheet }, children); }; _proto.interleaveWithNodeStream = function interleaveWithNodeStream(input) { { throw new StyledComponentsError(3); } // eslint-disable-next-line global-require var _require = require('stream'), Readable = _require.Readable, Transform = _require.Transform; var readableStream = input; var sheet = this.sheet, getStyleTags = this.getStyleTags; var transformer = new Transform({ transform: function appendStyleChunks(chunk, /* encoding */ _, callback) { // Get the chunk and retrieve the sheet's CSS as an HTML chunk, // then reset its rules so we get only new ones for the next chunk var renderedHtml = chunk.toString(); var html = getStyleTags(); sheet.clearTag(); // prepend style html to chunk, unless the start of the chunk is a // closing tag in which case append right after that if (CLOSING_TAG_R.test(renderedHtml)) { var endOfClosingTag = renderedHtml.indexOf('>') + 1; var before = renderedHtml.slice(0, endOfClosingTag); var after = renderedHtml.slice(endOfClosingTag); this.push(before + html + after); } else { this.push(html + renderedHtml); } callback(); } }); readableStream.on('error', function (err) { // forward the error to the transform stream transformer.emit('error', err); }); return readableStream.pipe(transformer); }; return ServerStyleSheet; }(); // export default <Config: { theme?: any }, Instance>( // Component: AbstractComponent<Config, Instance> // ): AbstractComponent<$Diff<Config, { theme?: any }> & { theme?: any }, Instance> // // but the old build system tooling doesn't support the syntax var withTheme = (function (Component) { // $FlowFixMe This should be React.forwardRef<Config, Instance> var WithTheme = React.forwardRef(function (props, ref) { var theme = useContext(ThemeContext); // $FlowFixMe defaultProps isn't declared so it can be inferrable var defaultProps = Component.defaultProps; var themeProp = determineTheme(props, theme, defaultProps); if (process.env.NODE_ENV !== 'production' && themeProp === undefined) { // eslint-disable-next-line no-console console.warn("[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class \"" + getComponentName(Component) + "\""); } return React.createElement(Component, _extends({}, props, { theme: themeProp, ref: ref })); }); hoistNonReactStatics(WithTheme, Component); WithTheme.displayName = "WithTheme(" + getComponentName(Component) + ")"; return WithTheme; }); // var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = { StyleSheet: StyleSheet, masterSheet: masterSheet }; // /* Warning if you've imported this file on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native'); } /* Warning if there are several instances of styled-components */ if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) { window['__styled-components-init__'] = window['__styled-components-init__'] || 0; if (window['__styled-components-init__'] === 1) { // eslint-disable-next-line no-console console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.'); } window['__styled-components-init__'] += 1; } // export default styled; export { ServerStyleSheet, StyleSheetConsumer, StyleSheetContext, StyleSheetManager, ThemeConsumer, ThemeContext, ThemeProvider, __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS, createGlobalStyle, css, isStyledComponent, keyframes, withTheme }; //# sourceMappingURL=styled-components.browser.esm.js.map
sufuf3/cdnjs
ajax/libs/styled-components/5.0.0-4.canary-sheet/styled-components.browser.esm.js
JavaScript
mit
63,129
// Flags: --unhandled-rejections=none 'use strict'; const common = require('../common'); common.disableCrashOnUnhandledRejection(); // Verify that ignoring unhandled rejection works fine and that no warning is // logged. new Promise(() => { throw new Error('One'); }); Promise.reject('test'); process.on('warning', common.mustNotCall('warning')); process.on('uncaughtException', common.mustNotCall('uncaughtException')); process.on('rejectionHandled', common.mustNotCall('rejectionHandled')); process.on('unhandledRejection', common.mustCall(2)); setTimeout(common.mustCall(), 2);
enclose-io/compiler
lts/test/parallel/test-promise-unhandled-silent.js
JavaScript
mit
591
/** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup UnaStudio UNA Studio * @{ */ function BxDolStudioNavigationMenus(oOptions) { this.sActionsUrl = oOptions.sActionUrl; this.sPageUrl = oOptions.sPageUrl; this.sObjNameGrid = oOptions.sObjNameGrid; this.sObjName = oOptions.sObjName == undefined ? 'oBxDolStudioNavigationMenus' : oOptions.sObjName; this.sAnimationEffect = oOptions.sAnimationEffect == undefined ? 'fade' : oOptions.sAnimationEffect; this.iAnimationSpeed = oOptions.iAnimationSpeed == undefined ? 'slow' : oOptions.iAnimationSpeed; this.sParamsDivider = oOptions.sParamsDivider == undefined ? '#-#' : oOptions.sParamsDivider; this.sTextSearchInput = oOptions.sTextSearchInput == undefined ? '' : oOptions.sTextSearchInput; } BxDolStudioNavigationMenus.prototype.onChangeFilter = function() { var sValueModule = $('#bx-grid-module-' + this.sObjNameGrid).val(); var sValueSearch = $('#bx-grid-search-' + this.sObjNameGrid).val(); if(sValueSearch == this.sTextSearchInput) sValueSearch = ''; glGrids[this.sObjNameGrid].setFilter(sValueModule + this.sParamsDivider + sValueSearch, true); }; BxDolStudioNavigationMenus.prototype.onSelectSet = function(oSelect) { var sSet = $(oSelect).val(); if(sSet == 'sys_create_new') $('#bx-form-element-set_title').show(); else $('#bx-form-element-set_title').hide(); }; /** @} */
camperjz/trident
upgrade/files/9.0.0.B2-9.0.0.B3/files/studio/js/navigation_menus.js
JavaScript
mit
1,476
// HumanizeDuration.js - https://git.io/j0HgmQ ;(function () { // This has to be defined separately because of a bug: we want to alias // `gr` and `el` for backwards-compatiblity. In a breaking change, we can // remove `gr` entirely. // See https://github.com/EvanHahn/HumanizeDuration.js/issues/143 for more. var greek = { y: function (c) { return c === 1 ? 'χρόνος' : 'χρόνια' }, mo: function (c) { return c === 1 ? 'μήνας' : 'μήνες' }, w: function (c) { return c === 1 ? 'εβδομάδα' : 'εβδομάδες' }, d: function (c) { return c === 1 ? 'μέρα' : 'μέρες' }, h: function (c) { return c === 1 ? 'ώρα' : 'ώρες' }, m: function (c) { return c === 1 ? 'λεπτό' : 'λεπτά' }, s: function (c) { return c === 1 ? 'δευτερόλεπτο' : 'δευτερόλεπτα' }, ms: function (c) { return c === 1 ? 'χιλιοστό του δευτερολέπτου' : 'χιλιοστά του δευτερολέπτου' }, decimal: ',' } var languages = { ar: { y: function (c) { return c === 1 ? 'سنة' : 'سنوات' }, mo: function (c) { return c === 1 ? 'شهر' : 'أشهر' }, w: function (c) { return c === 1 ? 'أسبوع' : 'أسابيع' }, d: function (c) { return c === 1 ? 'يوم' : 'أيام' }, h: function (c) { return c === 1 ? 'ساعة' : 'ساعات' }, m: function (c) { return ['دقيقة', 'دقائق'][getArabicForm(c)] }, s: function (c) { return c === 1 ? 'ثانية' : 'ثواني' }, ms: function (c) { return c === 1 ? 'جزء من الثانية' : 'أجزاء من الثانية' }, decimal: ',' }, bg: { y: function (c) { return ['години', 'година', 'години'][getSlavicForm(c)] }, mo: function (c) { return ['месеца', 'месец', 'месеца'][getSlavicForm(c)] }, w: function (c) { return ['седмици', 'седмица', 'седмици'][getSlavicForm(c)] }, d: function (c) { return ['дни', 'ден', 'дни'][getSlavicForm(c)] }, h: function (c) { return ['часа', 'час', 'часа'][getSlavicForm(c)] }, m: function (c) { return ['минути', 'минута', 'минути'][getSlavicForm(c)] }, s: function (c) { return ['секунди', 'секунда', 'секунди'][getSlavicForm(c)] }, ms: function (c) { return ['милисекунди', 'милисекунда', 'милисекунди'][getSlavicForm(c)] }, decimal: ',' }, ca: { y: function (c) { return 'any' + (c === 1 ? '' : 's') }, mo: function (c) { return 'mes' + (c === 1 ? '' : 'os') }, w: function (c) { return 'setman' + (c === 1 ? 'a' : 'es') }, d: function (c) { return 'di' + (c === 1 ? 'a' : 'es') }, h: function (c) { return 'hor' + (c === 1 ? 'a' : 'es') }, m: function (c) { return 'minut' + (c === 1 ? '' : 's') }, s: function (c) { return 'segon' + (c === 1 ? '' : 's') }, ms: function (c) { return 'milisegon' + (c === 1 ? '' : 's') }, decimal: ',' }, cs: { y: function (c) { return ['rok', 'roku', 'roky', 'let'][getCzechOrSlovakForm(c)] }, mo: function (c) { return ['měsíc', 'měsíce', 'měsíce', 'měsíců'][getCzechOrSlovakForm(c)] }, w: function (c) { return ['týden', 'týdne', 'týdny', 'týdnů'][getCzechOrSlovakForm(c)] }, d: function (c) { return ['den', 'dne', 'dny', 'dní'][getCzechOrSlovakForm(c)] }, h: function (c) { return ['hodina', 'hodiny', 'hodiny', 'hodin'][getCzechOrSlovakForm(c)] }, m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getCzechOrSlovakForm(c)] }, s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getCzechOrSlovakForm(c)] }, ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getCzechOrSlovakForm(c)] }, decimal: ',' }, da: { y: 'år', mo: function (c) { return 'måned' + (c === 1 ? '' : 'er') }, w: function (c) { return 'uge' + (c === 1 ? '' : 'r') }, d: function (c) { return 'dag' + (c === 1 ? '' : 'e') }, h: function (c) { return 'time' + (c === 1 ? '' : 'r') }, m: function (c) { return 'minut' + (c === 1 ? '' : 'ter') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') }, decimal: ',' }, de: { y: function (c) { return 'Jahr' + (c === 1 ? '' : 'e') }, mo: function (c) { return 'Monat' + (c === 1 ? '' : 'e') }, w: function (c) { return 'Woche' + (c === 1 ? '' : 'n') }, d: function (c) { return 'Tag' + (c === 1 ? '' : 'e') }, h: function (c) { return 'Stunde' + (c === 1 ? '' : 'n') }, m: function (c) { return 'Minute' + (c === 1 ? '' : 'n') }, s: function (c) { return 'Sekunde' + (c === 1 ? '' : 'n') }, ms: function (c) { return 'Millisekunde' + (c === 1 ? '' : 'n') }, decimal: ',' }, el: greek, en: { y: function (c) { return 'year' + (c === 1 ? '' : 's') }, mo: function (c) { return 'month' + (c === 1 ? '' : 's') }, w: function (c) { return 'week' + (c === 1 ? '' : 's') }, d: function (c) { return 'day' + (c === 1 ? '' : 's') }, h: function (c) { return 'hour' + (c === 1 ? '' : 's') }, m: function (c) { return 'minute' + (c === 1 ? '' : 's') }, s: function (c) { return 'second' + (c === 1 ? '' : 's') }, ms: function (c) { return 'millisecond' + (c === 1 ? '' : 's') }, decimal: '.' }, es: { y: function (c) { return 'año' + (c === 1 ? '' : 's') }, mo: function (c) { return 'mes' + (c === 1 ? '' : 'es') }, w: function (c) { return 'semana' + (c === 1 ? '' : 's') }, d: function (c) { return 'día' + (c === 1 ? '' : 's') }, h: function (c) { return 'hora' + (c === 1 ? '' : 's') }, m: function (c) { return 'minuto' + (c === 1 ? '' : 's') }, s: function (c) { return 'segundo' + (c === 1 ? '' : 's') }, ms: function (c) { return 'milisegundo' + (c === 1 ? '' : 's') }, decimal: ',' }, et: { y: function (c) { return 'aasta' + (c === 1 ? '' : 't') }, mo: function (c) { return 'kuu' + (c === 1 ? '' : 'd') }, w: function (c) { return 'nädal' + (c === 1 ? '' : 'at') }, d: function (c) { return 'päev' + (c === 1 ? '' : 'a') }, h: function (c) { return 'tund' + (c === 1 ? '' : 'i') }, m: function (c) { return 'minut' + (c === 1 ? '' : 'it') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'it') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'it') }, decimal: ',' }, fa: { y: 'سال', mo: 'ماه', w: 'هفته', d: 'روز', h: 'ساعت', m: 'دقیقه', s: 'ثانیه', ms: 'میلی ثانیه', decimal: '.' }, fi: { y: function (c) { return c === 1 ? 'vuosi' : 'vuotta' }, mo: function (c) { return c === 1 ? 'kuukausi' : 'kuukautta' }, w: function (c) { return 'viikko' + (c === 1 ? '' : 'a') }, d: function (c) { return 'päivä' + (c === 1 ? '' : 'ä') }, h: function (c) { return 'tunti' + (c === 1 ? '' : 'a') }, m: function (c) { return 'minuutti' + (c === 1 ? '' : 'a') }, s: function (c) { return 'sekunti' + (c === 1 ? '' : 'a') }, ms: function (c) { return 'millisekunti' + (c === 1 ? '' : 'a') }, decimal: ',' }, fr: { y: function (c) { return 'an' + (c >= 2 ? 's' : '') }, mo: 'mois', w: function (c) { return 'semaine' + (c >= 2 ? 's' : '') }, d: function (c) { return 'jour' + (c >= 2 ? 's' : '') }, h: function (c) { return 'heure' + (c >= 2 ? 's' : '') }, m: function (c) { return 'minute' + (c >= 2 ? 's' : '') }, s: function (c) { return 'seconde' + (c >= 2 ? 's' : '') }, ms: function (c) { return 'milliseconde' + (c >= 2 ? 's' : '') }, decimal: ',' }, gr: greek, hr: { y: function (c) { if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) { return 'godine' } return 'godina' }, mo: function (c) { if (c === 1) { return 'mjesec' } else if (c === 2 || c === 3 || c === 4) { return 'mjeseca' } return 'mjeseci' }, w: function (c) { if (c % 10 === 1 && c !== 11) { return 'tjedan' } return 'tjedna' }, d: function (c) { return c === 1 ? 'dan' : 'dana' }, h: function (c) { if (c === 1) { return 'sat' } else if (c === 2 || c === 3 || c === 4) { return 'sata' } return 'sati' }, m: function (c) { var mod10 = c % 10 if ((mod10 === 2 || mod10 === 3 || mod10 === 4) && (c < 10 || c > 14)) { return 'minute' } return 'minuta' }, s: function (c) { if ((c === 10 || c === 11 || c === 12 || c === 13 || c === 14 || c === 16 || c === 17 || c === 18 || c === 19) || (c % 10 === 5)) { return 'sekundi' } else if (c % 10 === 1) { return 'sekunda' } else if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) { return 'sekunde' } return 'sekundi' }, ms: function (c) { if (c === 1) { return 'milisekunda' } else if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) { return 'milisekunde' } return 'milisekundi' }, decimal: ',' }, hu: { y: 'év', mo: 'hónap', w: 'hét', d: 'nap', h: 'óra', m: 'perc', s: 'másodperc', ms: 'ezredmásodperc', decimal: ',' }, id: { y: 'tahun', mo: 'bulan', w: 'minggu', d: 'hari', h: 'jam', m: 'menit', s: 'detik', ms: 'milidetik', decimal: '.' }, is: { y: 'ár', mo: function (c) { return 'mánuð' + (c === 1 ? 'ur' : 'ir') }, w: function (c) { return 'vik' + (c === 1 ? 'a' : 'ur') }, d: function (c) { return 'dag' + (c === 1 ? 'ur' : 'ar') }, h: function (c) { return 'klukkutím' + (c === 1 ? 'i' : 'ar') }, m: function (c) { return 'mínút' + (c === 1 ? 'a' : 'ur') }, s: function (c) { return 'sekúnd' + (c === 1 ? 'a' : 'ur') }, ms: function (c) { return 'millisekúnd' + (c === 1 ? 'a' : 'ur') }, decimal: '.' }, it: { y: function (c) { return 'ann' + (c === 1 ? 'o' : 'i') }, mo: function (c) { return 'mes' + (c === 1 ? 'e' : 'i') }, w: function (c) { return 'settiman' + (c === 1 ? 'a' : 'e') }, d: function (c) { return 'giorn' + (c === 1 ? 'o' : 'i') }, h: function (c) { return 'or' + (c === 1 ? 'a' : 'e') }, m: function (c) { return 'minut' + (c === 1 ? 'o' : 'i') }, s: function (c) { return 'second' + (c === 1 ? 'o' : 'i') }, ms: function (c) { return 'millisecond' + (c === 1 ? 'o' : 'i') }, decimal: ',' }, ja: { y: '年', mo: '月', w: '週', d: '日', h: '時間', m: '分', s: '秒', ms: 'ミリ秒', decimal: '.' }, ko: { y: '년', mo: '개월', w: '주일', d: '일', h: '시간', m: '분', s: '초', ms: '밀리 초', decimal: '.' }, lo: { y: 'ປີ', mo: 'ເດືອນ', w: 'ອາທິດ', d: 'ມື້', h: 'ຊົ່ວໂມງ', m: 'ນາທີ', s: 'ວິນາທີ', ms: 'ມິນລິວິນາທີ', decimal: ',' }, lt: { y: function (c) { return ((c % 10 === 0) || (c % 100 >= 10 && c % 100 <= 20)) ? 'metų' : 'metai' }, mo: function (c) { return ['mėnuo', 'mėnesiai', 'mėnesių'][getLithuanianForm(c)] }, w: function (c) { return ['savaitė', 'savaitės', 'savaičių'][getLithuanianForm(c)] }, d: function (c) { return ['diena', 'dienos', 'dienų'][getLithuanianForm(c)] }, h: function (c) { return ['valanda', 'valandos', 'valandų'][getLithuanianForm(c)] }, m: function (c) { return ['minutė', 'minutės', 'minučių'][getLithuanianForm(c)] }, s: function (c) { return ['sekundė', 'sekundės', 'sekundžių'][getLithuanianForm(c)] }, ms: function (c) { return ['milisekundė', 'milisekundės', 'milisekundžių'][getLithuanianForm(c)] }, decimal: ',' }, lv: { y: function (c) { return ['gads', 'gadi'][getLatvianForm(c)] }, mo: function (c) { return ['mēnesis', 'mēneši'][getLatvianForm(c)] }, w: function (c) { return ['nedēļa', 'nedēļas'][getLatvianForm(c)] }, d: function (c) { return ['diena', 'dienas'][getLatvianForm(c)] }, h: function (c) { return ['stunda', 'stundas'][getLatvianForm(c)] }, m: function (c) { return ['minūte', 'minūtes'][getLatvianForm(c)] }, s: function (c) { return ['sekunde', 'sekundes'][getLatvianForm(c)] }, ms: function (c) { return ['milisekunde', 'milisekundes'][getLatvianForm(c)] }, decimal: ',' }, ms: { y: 'tahun', mo: 'bulan', w: 'minggu', d: 'hari', h: 'jam', m: 'minit', s: 'saat', ms: 'milisaat', decimal: '.' }, nl: { y: 'jaar', mo: function (c) { return c === 1 ? 'maand' : 'maanden' }, w: function (c) { return c === 1 ? 'week' : 'weken' }, d: function (c) { return c === 1 ? 'dag' : 'dagen' }, h: 'uur', m: function (c) { return c === 1 ? 'minuut' : 'minuten' }, s: function (c) { return c === 1 ? 'seconde' : 'seconden' }, ms: function (c) { return c === 1 ? 'milliseconde' : 'milliseconden' }, decimal: ',' }, no: { y: 'år', mo: function (c) { return 'måned' + (c === 1 ? '' : 'er') }, w: function (c) { return 'uke' + (c === 1 ? '' : 'r') }, d: function (c) { return 'dag' + (c === 1 ? '' : 'er') }, h: function (c) { return 'time' + (c === 1 ? '' : 'r') }, m: function (c) { return 'minutt' + (c === 1 ? '' : 'er') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') }, decimal: ',' }, pl: { y: function (c) { return ['rok', 'roku', 'lata', 'lat'][getPolishForm(c)] }, mo: function (c) { return ['miesiąc', 'miesiąca', 'miesiące', 'miesięcy'][getPolishForm(c)] }, w: function (c) { return ['tydzień', 'tygodnia', 'tygodnie', 'tygodni'][getPolishForm(c)] }, d: function (c) { return ['dzień', 'dnia', 'dni', 'dni'][getPolishForm(c)] }, h: function (c) { return ['godzina', 'godziny', 'godziny', 'godzin'][getPolishForm(c)] }, m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getPolishForm(c)] }, s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getPolishForm(c)] }, ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getPolishForm(c)] }, decimal: ',' }, pt: { y: function (c) { return 'ano' + (c === 1 ? '' : 's') }, mo: function (c) { return c === 1 ? 'mês' : 'meses' }, w: function (c) { return 'semana' + (c === 1 ? '' : 's') }, d: function (c) { return 'dia' + (c === 1 ? '' : 's') }, h: function (c) { return 'hora' + (c === 1 ? '' : 's') }, m: function (c) { return 'minuto' + (c === 1 ? '' : 's') }, s: function (c) { return 'segundo' + (c === 1 ? '' : 's') }, ms: function (c) { return 'milissegundo' + (c === 1 ? '' : 's') }, decimal: ',' }, ro: { y: function (c) { return c === 1 ? 'an' : 'ani' }, mo: function (c) { return c === 1 ? 'lună' : 'luni' }, w: function (c) { return c === 1 ? 'săptămână' : 'săptămâni' }, d: function (c) { return c === 1 ? 'zi' : 'zile' }, h: function (c) { return c === 1 ? 'oră' : 'ore' }, m: function (c) { return c === 1 ? 'minut' : 'minute' }, s: function (c) { return c === 1 ? 'secundă' : 'secunde' }, ms: function (c) { return c === 1 ? 'milisecundă' : 'milisecunde' }, decimal: ',' }, ru: { y: function (c) { return ['лет', 'год', 'года'][getSlavicForm(c)] }, mo: function (c) { return ['месяцев', 'месяц', 'месяца'][getSlavicForm(c)] }, w: function (c) { return ['недель', 'неделя', 'недели'][getSlavicForm(c)] }, d: function (c) { return ['дней', 'день', 'дня'][getSlavicForm(c)] }, h: function (c) { return ['часов', 'час', 'часа'][getSlavicForm(c)] }, m: function (c) { return ['минут', 'минута', 'минуты'][getSlavicForm(c)] }, s: function (c) { return ['секунд', 'секунда', 'секунды'][getSlavicForm(c)] }, ms: function (c) { return ['миллисекунд', 'миллисекунда', 'миллисекунды'][getSlavicForm(c)] }, decimal: ',' }, uk: { y: function (c) { return ['років', 'рік', 'роки'][getSlavicForm(c)] }, mo: function (c) { return ['місяців', 'місяць', 'місяці'][getSlavicForm(c)] }, w: function (c) { return ['тижнів', 'тиждень', 'тижні'][getSlavicForm(c)] }, d: function (c) { return ['днів', 'день', 'дні'][getSlavicForm(c)] }, h: function (c) { return ['годин', 'година', 'години'][getSlavicForm(c)] }, m: function (c) { return ['хвилин', 'хвилина', 'хвилини'][getSlavicForm(c)] }, s: function (c) { return ['секунд', 'секунда', 'секунди'][getSlavicForm(c)] }, ms: function (c) { return ['мілісекунд', 'мілісекунда', 'мілісекунди'][getSlavicForm(c)] }, decimal: ',' }, ur: { y: 'سال', mo: function (c) { return c === 1 ? 'مہینہ' : 'مہینے' }, w: function (c) { return c === 1 ? 'ہفتہ' : 'ہفتے' }, d: 'دن', h: function (c) { return c === 1 ? 'گھنٹہ' : 'گھنٹے' }, m: 'منٹ', s: 'سیکنڈ', ms: 'ملی سیکنڈ', decimal: '.' }, sk: { y: function (c) { return ['rok', 'roky', 'roky', 'rokov'][getCzechOrSlovakForm(c)] }, mo: function (c) { return ['mesiac', 'mesiace', 'mesiace', 'mesiacov'][getCzechOrSlovakForm(c)] }, w: function (c) { return ['týždeň', 'týždne', 'týždne', 'týždňov'][getCzechOrSlovakForm(c)] }, d: function (c) { return ['deň', 'dni', 'dni', 'dní'][getCzechOrSlovakForm(c)] }, h: function (c) { return ['hodina', 'hodiny', 'hodiny', 'hodín'][getCzechOrSlovakForm(c)] }, m: function (c) { return ['minúta', 'minúty', 'minúty', 'minút'][getCzechOrSlovakForm(c)] }, s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekúnd'][getCzechOrSlovakForm(c)] }, ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekúnd'][getCzechOrSlovakForm(c)] }, decimal: ',' }, sv: { y: 'år', mo: function (c) { return 'månad' + (c === 1 ? '' : 'er') }, w: function (c) { return 'veck' + (c === 1 ? 'a' : 'or') }, d: function (c) { return 'dag' + (c === 1 ? '' : 'ar') }, h: function (c) { return 'timm' + (c === 1 ? 'e' : 'ar') }, m: function (c) { return 'minut' + (c === 1 ? '' : 'er') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') }, decimal: ',' }, tr: { y: 'yıl', mo: 'ay', w: 'hafta', d: 'gün', h: 'saat', m: 'dakika', s: 'saniye', ms: 'milisaniye', decimal: ',' }, th: { y: 'ปี', mo: 'เดือน', w: 'อาทิตย์', d: 'วัน', h: 'ชั่วโมง', m: 'นาที', s: 'วินาที', ms: 'มิลลิวินาที', decimal: '.' }, vi: { y: 'năm', mo: 'tháng', w: 'tuần', d: 'ngày', h: 'giờ', m: 'phút', s: 'giây', ms: 'mili giây', decimal: ',' }, zh_CN: { y: '年', mo: '个月', w: '周', d: '天', h: '小时', m: '分钟', s: '秒', ms: '毫秒', decimal: '.' }, zh_TW: { y: '年', mo: '個月', w: '周', d: '天', h: '小時', m: '分鐘', s: '秒', ms: '毫秒', decimal: '.' } } // You can create a humanizer, which returns a function with default // parameters. function humanizer (passedOptions) { var result = function humanizer (ms, humanizerOptions) { var options = extend({}, result, humanizerOptions || {}) return doHumanization(ms, options) } return extend(result, { language: 'en', delimiter: ', ', spacer: ' ', conjunction: '', serialComma: true, units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'], languages: {}, round: false, unitMeasures: { y: 31557600000, mo: 2629800000, w: 604800000, d: 86400000, h: 3600000, m: 60000, s: 1000, ms: 1 } }, passedOptions) } // The main function is just a wrapper around a default humanizer. var humanizeDuration = humanizer({}) // Build dictionary from options function getDictionary (options) { var languagesFromOptions = [options.language] if (has(options, 'fallbacks')) { if (isArray(options.fallbacks) && options.fallbacks.length) { languagesFromOptions = languagesFromOptions.concat(options.fallbacks) } else { throw new Error('fallbacks must be an array with at least one element') } } for (var i = 0; i < languagesFromOptions.length; i++) { var languageToTry = languagesFromOptions[i] if (has(options.languages, languageToTry)) { return options.languages[languageToTry] } else if (has(languages, languageToTry)) { return languages[languageToTry] } } throw new Error('No language found.') } // doHumanization does the bulk of the work. function doHumanization (ms, options) { var i, len, piece // Make sure we have a positive number. // Has the nice sideffect of turning Number objects into primitives. ms = Math.abs(ms) var dictionary = getDictionary(options) var pieces = [] // Start at the top and keep removing units, bit by bit. var unitName, unitMS, unitCount for (i = 0, len = options.units.length; i < len; i++) { unitName = options.units[i] unitMS = options.unitMeasures[unitName] // What's the number of full units we can fit? if (i + 1 === len) { if (has(options, 'maxDecimalPoints')) { // We need to use this expValue to avoid rounding functionality of toFixed call var expValue = Math.pow(10, options.maxDecimalPoints) var unitCountFloat = (ms / unitMS) unitCount = parseFloat((Math.floor(expValue * unitCountFloat) / expValue).toFixed(options.maxDecimalPoints)) } else { unitCount = ms / unitMS } } else { unitCount = Math.floor(ms / unitMS) } // Add the string. pieces.push({ unitCount: unitCount, unitName: unitName }) // Remove what we just figured out. ms -= unitCount * unitMS } var firstOccupiedUnitIndex = 0 for (i = 0; i < pieces.length; i++) { if (pieces[i].unitCount) { firstOccupiedUnitIndex = i break } } if (options.round) { var ratioToLargerUnit, previousPiece for (i = pieces.length - 1; i >= 0; i--) { piece = pieces[i] piece.unitCount = Math.round(piece.unitCount) if (i === 0) { break } previousPiece = pieces[i - 1] ratioToLargerUnit = options.unitMeasures[previousPiece.unitName] / options.unitMeasures[piece.unitName] if ((piece.unitCount % ratioToLargerUnit) === 0 || (options.largest && ((options.largest - 1) < (i - firstOccupiedUnitIndex)))) { previousPiece.unitCount += piece.unitCount / ratioToLargerUnit piece.unitCount = 0 } } } var result = [] for (i = 0, pieces.length; i < len; i++) { piece = pieces[i] if (piece.unitCount) { result.push(render(piece.unitCount, piece.unitName, dictionary, options)) } if (result.length === options.largest) { break } } if (result.length) { if (!options.conjunction || result.length === 1) { return result.join(options.delimiter) } else if (result.length === 2) { return result.join(options.conjunction) } else if (result.length > 2) { return result.slice(0, -1).join(options.delimiter) + (options.serialComma ? ',' : '') + options.conjunction + result.slice(-1) } } else { return render(0, options.units[options.units.length - 1], dictionary, options) } } function render (count, type, dictionary, options) { var decimal if (has(options, 'decimal')) { decimal = options.decimal } else if (has(dictionary, 'decimal')) { decimal = dictionary.decimal } else { decimal = '.' } var countStr = count.toString().replace('.', decimal) var dictionaryValue = dictionary[type] var word if (typeof dictionaryValue === 'function') { word = dictionaryValue(count) } else { word = dictionaryValue } return countStr + options.spacer + word } function extend (destination) { var source for (var i = 1; i < arguments.length; i++) { source = arguments[i] for (var prop in source) { if (has(source, prop)) { destination[prop] = source[prop] } } } return destination } // Internal helper function for Polish language. function getPolishForm (c) { if (c === 1) { return 0 } else if (Math.floor(c) !== c) { return 1 } else if (c % 10 >= 2 && c % 10 <= 4 && !(c % 100 > 10 && c % 100 < 20)) { return 2 } else { return 3 } } // Internal helper function for Russian and Ukranian languages. function getSlavicForm (c) { if (Math.floor(c) !== c) { return 2 } else if ((c % 100 >= 5 && c % 100 <= 20) || (c % 10 >= 5 && c % 10 <= 9) || c % 10 === 0) { return 0 } else if (c % 10 === 1) { return 1 } else if (c > 1) { return 2 } else { return 0 } } // Internal helper function for Slovak language. function getCzechOrSlovakForm (c) { if (c === 1) { return 0 } else if (Math.floor(c) !== c) { return 1 } else if (c % 10 >= 2 && c % 10 <= 4 && c % 100 < 10) { return 2 } else { return 3 } } // Internal helper function for Lithuanian language. function getLithuanianForm (c) { if (c === 1 || (c % 10 === 1 && c % 100 > 20)) { return 0 } else if (Math.floor(c) !== c || (c % 10 >= 2 && c % 100 > 20) || (c % 10 >= 2 && c % 100 < 10)) { return 1 } else { return 2 } } // Internal helper function for Latvian language. function getLatvianForm (c) { if (c === 1 || (c % 10 === 1 && c % 100 !== 11)) { return 0 } else { return 1 } } // Internal helper function for Arabic language. function getArabicForm (c) { if (c <= 2) { return 0 } if (c > 2 && c < 11) { return 1 } return 0 } // We need to make sure we support browsers that don't have // `Array.isArray`, so we define a fallback here. var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]' } function has (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key) } humanizeDuration.getSupportedLanguages = function getSupportedLanguages () { var result = [] for (var language in languages) { if (has(languages, language) && language !== 'gr') { result.push(language) } } return result } humanizeDuration.humanizer = humanizer if (typeof define === 'function' && define.amd) { define(function () { return humanizeDuration }) } else if (typeof module !== 'undefined' && module.exports) { module.exports = humanizeDuration } else { this.humanizeDuration = humanizeDuration } })(); // eslint-disable-line semi
extend1994/cdnjs
ajax/libs/humanize-duration/3.20.1/humanize-duration.js
JavaScript
mit
28,768
<?php namespace TYPO3\Flow\Tests\Unit\Session; /* * This file is part of the TYPO3.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ /** * Testcase for the Transient Session implementation * */ class TransientSessionTest extends \TYPO3\Flow\Tests\UnitTestCase { /** * @test */ public function theTransientSessionImplementsTheSessionInterface() { $session = new \TYPO3\Flow\Session\TransientSession(); $this->assertInstanceOf(\TYPO3\Flow\Session\SessionInterface::class, $session); } /** * @test */ public function aSessionIdIsGeneratedOnStartingTheSession() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->start(); $this->assertTrue(strlen($session->getId()) == 13); } /** * @test * @expectedException \TYPO3\Flow\Session\Exception\SessionNotStartedException */ public function tryingToGetTheSessionIdWithoutStartingTheSessionThrowsAnException() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->getId(); } /** * @test */ public function stringsCanBeStoredByCallingPutData() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->start(); $session->putData('theKey', 'some data'); $this->assertEquals('some data', $session->getData('theKey')); } /** * @test */ public function allSessionDataCanBeFlushedByCallingDestroy() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->start(); $session->putData('theKey', 'some data'); $session->destroy(); $session->start(); $this->assertNull($session->getData('theKey')); } /** * @test */ public function hasKeyReturnsTrueOrFalseAccordingToAvailableKeys() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->start(); $session->putData('theKey', 'some data'); $this->assertTrue($session->hasKey('theKey')); $this->assertFalse($session->hasKey('noKey')); } }
chewbakartik/flow-development-collection
TYPO3.Flow/Tests/Unit/Session/TransientSessionTest.php
PHP
mit
2,321
<?php class WP_REST_Posts_Terms_Controller extends WP_REST_Controller { protected $post_type; public function __construct( $post_type, $taxonomy ) { $this->post_type = $post_type; $this->taxonomy = $taxonomy; $this->posts_controller = new WP_REST_Posts_Controller( $post_type ); $this->terms_controller = new WP_REST_Terms_Controller( $taxonomy ); } /** * Register the routes for the objects of the controller. */ public function register_routes() { $base = $this->posts_controller->get_post_type_base( $this->post_type ); $tax_base = $this->terms_controller->get_taxonomy_base( $this->taxonomy ); register_rest_route( 'wp/v2', sprintf( '/%s/(?P<post_id>[\d]+)/%s', $base, $tax_base ), array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( 'wp/v2', sprintf( '/%s/(?P<post_id>[\d]+)/%s/(?P<term_id>[\d]+)', $base, $tax_base ), array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'create_item' ), 'permission_callback' => array( $this, 'create_item_permissions_check' ), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_item' ), 'permission_callback' => array( $this, 'create_item_permissions_check' ), 'args' => array( 'force' => array( 'default' => false, ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Get all the terms that are attached to a post * * @param WP_REST_Request $request Full details about the request * @return WP_Error|WP_REST_Response */ public function get_items( $request ) { $post = get_post( absint( $request['post_id'] ) ); $is_request_valid = $this->validate_request( $request ); if ( is_wp_error( $is_request_valid ) ) { return $is_request_valid; } $args = array( 'order' => $request['order'], 'orderby' => $request['orderby'], ); $terms = wp_get_object_terms( $post->ID, $this->taxonomy, $args ); $response = array(); foreach ( $terms as $term ) { $data = $this->terms_controller->prepare_item_for_response( $term, $request ); $response[] = $this->prepare_response_for_collection( $data ); } $response = rest_ensure_response( $response ); return $response; } /** * Get a term that is attached to a post * * @param WP_REST_Request $request Full details about the request * @return WP_Error|WP_REST_Response */ public function get_item( $request ) { $post = get_post( absint( $request['post_id'] ) ); $term_id = absint( $request['term_id'] ); $is_request_valid = $this->validate_request( $request ); if ( is_wp_error( $is_request_valid ) ) { return $is_request_valid; } $terms = wp_get_object_terms( $post->ID, $this->taxonomy ); if ( ! in_array( $term_id, wp_list_pluck( $terms, 'term_id' ) ) ) { return new WP_Error( 'rest_post_not_in_term', __( 'Invalid taxonomy for post id.' ), array( 'status' => 404 ) ); } $term = $this->terms_controller->prepare_item_for_response( get_term( $term_id, $this->taxonomy ), $request ); $response = rest_ensure_response( $term ); return $response; } /** * Add a term to a post * * @param WP_REST_Request $request Full details about the request * @return WP_Error|WP_REST_Response */ public function create_item( $request ) { $post = get_post( $request['post_id'] ); $term_id = absint( $request['term_id'] ); $is_request_valid = $this->validate_request( $request ); if ( is_wp_error( $is_request_valid ) ) { return $is_request_valid; } $term = get_term( $term_id, $this->taxonomy ); $tt_ids = wp_set_object_terms( $post->ID, $term->term_id, $this->taxonomy, true ); if ( is_wp_error( $tt_ids ) ) { return $tt_ids; } $term = $this->terms_controller->prepare_item_for_response( get_term( $term_id, $this->taxonomy ), $request ); $response = rest_ensure_response( $term ); $response->set_status( 201 ); /** * Fires after a term is added to a post via the REST API. * * @param array $term The added term data. * @param WP_Post $post The post the term was added to. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_insert_term', $term, $post, $request ); return $term; } /** * Remove a term from a post. * * @param WP_REST_Request $request Full details about the request * @return WP_Error|null */ public function delete_item( $request ) { $post = get_post( absint( $request['post_id'] ) ); $term_id = absint( $request['term_id'] ); $force = isset( $request['force'] ) ? (bool) $request['force'] : false; // We don't support trashing for this type, error out if ( ! $force ) { return new WP_Error( 'rest_trash_not_supported', __( 'Terms do not support trashing.' ), array( 'status' => 501 ) ); } $is_request_valid = $this->validate_request( $request ); if ( is_wp_error( $is_request_valid ) ) { return $is_request_valid; } $previous_item = $this->get_item( $request ); $remove = wp_remove_object_terms( $post->ID, $term_id, $this->taxonomy ); if ( is_wp_error( $remove ) ) { return $remove; } /** * Fires after a term is removed from a post via the REST API. * * @param array $previous_item The removed term data. * @param WP_Post $post The post the term was removed from. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_remove_term', $previous_item, $post, $request ); return $previous_item; } /** * Get the Term schema, conforming to JSON Schema. * * @return array */ public function get_item_schema() { return $this->terms_controller->get_item_schema(); } /** * Validate the API request for relationship requests. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|true */ protected function validate_request( $request ) { $post = get_post( (int) $request['post_id'] ); if ( empty( $post ) || empty( $post->ID ) || $post->post_type !== $this->post_type ) { return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post id.' ), array( 'status' => 404 ) ); } if ( ! $this->posts_controller->check_read_permission( $post ) ) { return new WP_Error( 'rest_forbidden', __( 'Sorry, you cannot view this post.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! empty( $request['term_id'] ) ) { $term_id = absint( $request['term_id'] ); $term = get_term( $term_id, $this->taxonomy ); if ( ! $term || $term->taxonomy !== $this->taxonomy ) { return new WP_Error( 'rest_term_invalid', __( "Term doesn't exist." ), array( 'status' => 404 ) ); } } return true; } /** * Check if a given request has access to read a post's term. * * @param WP_REST_Request $request Full details about the request. * @return bool|WP_Error */ public function get_items_permissions_check( $request ) { $post_request = new WP_REST_Request(); $post_request->set_param( 'id', $request['post_id'] ); $post_check = $this->posts_controller->get_item_permissions_check( $post_request ); if ( ! $post_check || is_wp_error( $post_check ) ) { return $post_check; } $term_request = new WP_REST_Request(); $term_request->set_param( 'id', $request['term_id'] ); $terms_check = $this->terms_controller->get_item_permissions_check( $term_request ); if ( ! $terms_check || is_wp_error( $terms_check ) ) { return $terms_check; } return true; } /** * Check if a given request has access to create a post/term relationship. * * @param WP_REST_Request $request Full details about the request. * @return bool|WP_Error */ public function create_item_permissions_check( $request ) { $post_request = new WP_REST_Request(); $post_request->set_param( 'id', $request['post_id'] ); $post_check = $this->posts_controller->update_item_permissions_check( $post_request ); if ( ! $post_check || is_wp_error( $post_check ) ) { return $post_check; } return true; } /** * Get the query params for collections * * @return array */ public function get_collection_params() { $query_params = array(); $query_params['context'] = $this->get_context_param( array( 'default' => 'view' ) ); $query_params['order'] = array( 'description' => 'Order sort attribute ascending or descending.', 'type' => 'string', 'default' => 'asc', 'enum' => array( 'asc', 'desc' ), ); $query_params['orderby'] = array( 'description' => 'Sort collection by object attribute.', 'type' => 'string', 'default' => 'name', 'enum' => array( 'count', 'name', 'slug', 'term_order', ), ); return $query_params; } }
trungnghia112/AngularJS-and-WordPress
wp-content/plugins/rest-api/lib/endpoints/class-wp-rest-posts-terms-controller.php
PHP
mit
9,539
// Copyright (c) 2013-2015 Titanium I.T. LLC. All rights reserved. See LICENSE.TXT for details. (function() { "use strict"; var arrayToSentence = require("array-to-sentence"); var objectAssign = require("object-assign"); // ponyfill for Object.assign(); check if Node supports it yet exports.check = function(arg, type, options) { var argType = getType(arg); if (!Array.isArray(type)) type = [ type ]; options = options || {}; options.name = options.name || "argument"; for (var i = 0; i < type.length; i++) { if (oneTypeMatches(arg, argType, type[i])) { if (isStructComparison(argType, type[i])) return checkStruct(arg, type[i], options); else return null; } } return describeError(argType, type, options.name); function oneTypeMatches(arg, argType, type) { if (argType === Object) return checkObject(arg, type); else if (Number.isNaN(argType)) return Number.isNaN(type); else return argType === type; function checkObject(arg, type) { if (typeof type === "function") return arg instanceof type; else if (typeof type === "object") return typeof arg === "object"; else throw new Error("unrecognized type: " + type); } } function isStructComparison(argType, type) { return argType === Object && typeof type === "object"; } function checkStruct(arg, type, options) { if (typeof type !== "object") throw new Error("unrecognized type: " + type); var keys = Object.getOwnPropertyNames(type); for (var i = 0; i < keys.length; i++) { var newOptions = objectAssign({}, options); newOptions.name = options.name + "." + keys[i]; var checkResult = exports.check(arg[keys[i]], type[keys[i]], newOptions); if (checkResult !== null) return checkResult; } return null; } function describeError(argType, type, name) { var describe = exports.describe; var articles = { articles: true }; return name + " must be " + describe(type, articles) + ", but it was " + describe(argType, articles); } }; exports.describe = function(type, options) { if (!Array.isArray(type)) type = [ type ]; if (options === undefined) options = {}; var descriptions = type.map(function(oneType) { return describeOneType(oneType); }); if (descriptions.length <= 2) return descriptions.join(" or "); else return arrayToSentence(descriptions, { lastSeparator: ", or " }); // dat Oxford comma function describeOneType(type) { switch(type) { case Boolean: return options.articles ? "a boolean" : "boolean"; case String: return options.articles ? "a string" : "string"; case Number: return options.articles ? "a number" : "number"; case Function: return options.articles ? "a function" : "function"; case Array: return options.articles ? "an array" : "array"; case undefined: return "undefined"; case null: return "null"; default: if (Number.isNaN(type)) return "NaN"; else if (typeof type === "function") return describeObject(type, options); else if (typeof type === "object") return describeStruct(type, options); else throw new Error("unrecognized type: " + type); } } function describeObject(type, options) { var articles = options.articles; if (type === Object) return articles ? "an object" : "object"; else if (type === RegExp) return articles ? "a regular expression" : "regular expression"; var name = type.name; if (name) { if (articles) name = "a " + name; } else { name = articles ? "an <anon>" : "<anon>"; } return name + " instance"; } function describeStruct(type, options) { var properties = Object.getOwnPropertyNames(type).map(function(key) { return key + ": <" + exports.describe(type[key]) + ">"; }); if (properties.length === 0) return options.articles ? "an object" : "object"; var description = " " + properties.join(", ") + " "; return (options.articles ? "an " : "") + "object containing {" + description + "}"; } }; function getType(variable) { if (variable === null) return null; if (Array.isArray(variable)) return Array; if (Number.isNaN(variable)) return NaN; switch (typeof variable) { case "boolean": return Boolean; case "string": return String; case "number": return Number; case "function": return Function; case "object": return Object; case "undefined": return undefined; default: throw new Error("Unreachable code executed. Unknown typeof value: " + typeof variable); } } }());
evrimfeyyaz/ios-calculator
node_modules/simplebuild/lib/type.js
JavaScript
mit
4,496
""" Logger for the spectroscopic toolkit packge Goal: Use decorators to log each command in full Author: Adam Ginsburg Created: 03/17/2011 """ import os import time class Logger(object): """ Logger object. Should be initiated on import. """ def __init__(self, filename): """ Open a log file for writing """ newfilename = filename ii=0 while os.path.exists(filename): newfilename = filename+".%3i" % ii ii += 1 if newfilename != filename: os.rename(filename,newfilename) self.outfile = open(filename,'w') print >>self.outfile,"Began logging at %s" % (time.strftime("%M/%d/%Y %H:%M:%S",time.localtime())) def __call__(self, function): """ """ def wrapper(*args, **kwargs): modname = function.__module__ fname = function.__name__ print >>self.outfile,"%s.%s" % (modname,fname) +\ "("+"".join([a.__name__ for a in args]) + \ "".join(["%s=%s" % (k,v) for (k,v) in kwargs])+ ")" return function return wrapper def close(self): self.outfile.close()
keflavich/pyspeckit-obsolete
pyspeckit/spectrum/logger.py
Python
mit
1,211
<?php namespace Kunstmaan\AdminBundle\Toolbar; use Doctrine\ORM\EntityManagerInterface; use Kunstmaan\AdminBundle\Entity\Exception; use Kunstmaan\AdminBundle\Helper\Toolbar\AbstractDataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class ExceptionDataCollector extends AbstractDataCollector { /** * @var EntityManagerInterface $em */ private $em; public function __construct(EntityManagerInterface $em) { $this->em = $em; } /** * @return array */ public function getAccessRoles() { return ['ROLE_ADMIN']; } /** * @return array */ public function collectData() { $model = $this->em->getRepository(Exception::class)->findExceptionStatistics(); if ( isset($model['cp_all'], $model['cp_sum']) ) { return [ 'data' => $model ]; } else { return []; } } /** * @param Request $request * @param Response $response * @param \Exception|null $exception */ public function collect(Request $request, Response $response, \Exception $exception = null) { if ( false === $this->isEnabled() ) { $this->data = false; } else { $this->data = $this->collectData(); } } /** * Gets the data for template * * @return array The request events */ public function getTemplateData() { return $this->data; } /** * @return string */ public function getName() { return 'kuma_exception'; } /** * @return bool */ public function isEnabled() { return true; } public function reset() { $this->data = []; } }
treeleaf/KunstmaanBundlesCMS
src/Kunstmaan/AdminBundle/Toolbar/ExceptionDataCollector.php
PHP
mit
1,851
var searchData= [ ['cache',['cache',['../classglobals.html#a5637b6b2c65cc2b027616212978a0e47',1,'globals']]], ['camera',['camera',['../classglobals.html#af37dc090d333e3a996373643f7c2c31f',1,'globals']]], ['camera_5fdistance',['camera_distance',['../classplayer.html#ae80ee7bccfac6b0b1167e3260db03206',1,'player']]], ['camera_5ffirst_5fperson',['camera_first_person',['../classplayer.html#ac31f384bb1a62333fc79fd1abd6fe4c4',1,'player']]], ['camera_5fpitch',['camera_pitch',['../classplayer.html#abb7b860ec40207dcc5f6e8ab414db5e5',1,'player']]], ['camera_5fyaw',['camera_yaw',['../classplayer.html#af3291faa017eb5a379d18f4efb86f8df',1,'player']]], ['cameranode_5f',['cameraNode_',['../class_u_s_p.html#a7cfd1fc925146d7b7700eaaf843ec5da',1,'USP']]], ['context',['context',['../classglobals.html#a90d6620c5d95436101be5e76b18a9002',1,'globals']]], ['current_5flevel',['current_level',['../classgs__playing.html#ad5484e116fdab7774ccd9e1a3c0c8789',1,'gs_playing']]] ];
gawag/Urho-Sample-Platformer
doxygen/html/search/variables_2.js
JavaScript
mit
980
/*! * OverlayScrollbars * https://github.com/KingSora/OverlayScrollbars * * Version: 1.7.3 * * Copyright KingSora. * https://github.com/KingSora * * Released under the MIT license. * Date: 23.06.2019 */ (function (global, factory) { if (typeof define === 'function' && define.amd) define(function() { return factory(global, global.document, undefined); }); else if (typeof module === 'object' && typeof module.exports === 'object') module.exports = factory(global, global.document, undefined); else factory(global, global.document, undefined); }(typeof window !== 'undefined' ? window : this, function(window, document, undefined) { 'use strict'; var PLUGINNAME = 'OverlayScrollbars'; var TYPES = { o : 'object', f : 'function', a : 'array', s : 'string', b : 'boolean', n : 'number', u : 'undefined', z : 'null' //d : 'date', //e : 'error', //r : 'regexp', //y : 'symbol' }; var LEXICON = { c : 'class', s : 'style', i : 'id', l : 'length', p : 'prototype', oH : 'offsetHeight', cH : 'clientHeight', sH : 'scrollHeight', oW : 'offsetWidth', cW : 'clientWidth', sW : 'scrollWidth' }; var VENDORS = { //https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix _jsCache : { }, _cssCache : { }, _cssPrefixes : ['-webkit-', '-moz-', '-o-', '-ms-'], _jsPrefixes : ['WebKit', 'Moz', 'O', 'MS'], _cssProperty : function(name) { var cache = this._cssCache; if(cache[name]) return cache[name]; var prefixes = this._cssPrefixes; var uppercasedName = this._firstLetterToUpper(name); var elmStyle = document.createElement('div')[LEXICON.s]; var resultPossibilities; var i = 0; var v = 0; var currVendorWithoutDashes; for (; i < prefixes.length; i++) { currVendorWithoutDashes = prefixes[i].replace(/-/g, ''); resultPossibilities = [ name, //transition prefixes[i] + name, //-webkit-transition currVendorWithoutDashes + uppercasedName, //webkitTransition this._firstLetterToUpper(currVendorWithoutDashes) + uppercasedName //WebkitTransition ]; for(v = 0; v < resultPossibilities[LEXICON.l]; v++) { if(elmStyle[resultPossibilities[v]] !== undefined) { cache[name] = resultPossibilities[v]; return resultPossibilities[v]; } } } return null; }, _jsAPI : function(name, isInterface, fallback) { var prefixes = this._jsPrefixes; var cache = this._jsCache; var i = 0; var result = cache[name]; if(!result) { result = window[name]; for(; i < prefixes[LEXICON.l]; i++) result = result || window[(isInterface ? prefixes[i] : prefixes[i].toLowerCase()) + this._firstLetterToUpper(name)]; cache[name] = result; } return result || fallback; }, _firstLetterToUpper : function(str) { return str.charAt(0).toUpperCase() + str.slice(1); } }; var COMPATIBILITY = { /** * Gets the current window width. * @returns {Number|number} The current window width in pixel. */ wW: function() { return window.innerWidth || document.documentElement[LEXICON.cW] || document.body[LEXICON.cW]; }, /** * Gets the current window height. * @returns {Number|number} The current window height in pixel. */ wH: function() { return window.innerHeight || document.documentElement[LEXICON.cH] || document.body[LEXICON.cH]; }, /** * Gets the MutationObserver Object or undefined if not supported. * @returns {MutationObserver|*|undefined} The MutationsObserver Object or undefined. */ mO: function() { return VENDORS._jsAPI('MutationObserver', true); }, /** * Gets the ResizeObserver Object or undefined if not supported. * @returns {MutationObserver|*|undefined} The ResizeObserver Object or undefined. */ rO: function() { return VENDORS._jsAPI('ResizeObserver', true); }, /** * Gets the RequestAnimationFrame method or it's corresponding polyfill. * @returns {*|Function} The RequestAnimationFrame method or it's corresponding polyfill. */ rAF: function() { return VENDORS._jsAPI('requestAnimationFrame', false, function (func) { return window.setTimeout(func, 1000 / 60); }); }, /** * Gets the CancelAnimationFrame method or it's corresponding polyfill. * @returns {*|Function} The CancelAnimationFrame method or it's corresponding polyfill. */ cAF: function() { return VENDORS._jsAPI('cancelAnimationFrame', false, function (id) { return window.clearTimeout(id); }); }, /** * Gets the current time. * @returns {number} The current time. */ now: function() { return Date.now && Date.now() || new Date().getTime(); }, /** * Stops the propagation of the given event. * @param event The event of which the propagation shall be stoped. */ stpP: function(event) { if(event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true; }, /** * Prevents the default action of the given event. * @param event The event of which the default action shall be prevented. */ prvD: function(event) { if(event.preventDefault && event.cancelable) event.preventDefault(); else event.returnValue = false; }, /** * Gets the pageX and pageY values of the given mouse event. * @param event The mouse event of which the pageX and pageX shall be got. * @returns {{x: number, y: number}} x = pageX value, y = pageY value. */ page: function(event) { event = event.originalEvent || event; var strPage = 'page'; var strClient = 'client'; var strX = 'X'; var strY = 'Y'; var target = event.target || event.srcElement || document; var eventDoc = target.ownerDocument || document; var doc = eventDoc.documentElement; var body = eventDoc.body; //if touch event return return pageX/Y of it if(event.touches !== undefined) { var touch = event.touches[0]; return { x : touch[strPage + strX], y : touch[strPage + strY] } } // Calculate pageX/Y if not native supported if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) { return { x : event[strClient + strX] + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0), y : event[strClient + strY] + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0) } } return { x : event[strPage + strX], y : event[strPage + strY] }; }, /** * Gets the clicked mouse button of the given mouse event. * @param event The mouse event of which the clicked button shal be got. * @returns {number} The number of the clicked mouse button. (0 : none | 1 : leftButton | 2 : middleButton | 3 : rightButton) */ mBtn: function(event) { var button = event.button; if (!event.which && button !== undefined) return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0))); else return event.which; }, /** * Checks whether a item is in the given array and returns its index. * @param item The item of which the position in the array shall be determined. * @param arr The array. * @returns {number} The zero based index of the item or -1 if the item isn't in the array. */ inA : function(item, arr) { for (var i = 0; i < arr[LEXICON.l]; i++) //Sometiems in IE a "SCRIPT70" Permission denied error occurs if HTML elements in a iFrame are compared try { if (arr[i] === item) return i; } catch(e) { } return -1; }, /** * Returns true if the given value is a array. * @param arr The potential array. * @returns {boolean} True if the given value is a array, false otherwise. */ isA: function(arr) { var def = Array.isArray; return def ? def(arr) : this.type(arr) == TYPES.a; }, /** * Determine the internal JavaScript [[Class]] of the given object. * @param obj The object of which the type shall be determined. * @returns {string} The type of the given object. */ type: function(obj) { if (obj === undefined) return obj + ""; if (obj === null) return obj + ""; return Object[LEXICON.p].toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase(); }, bind: function(func, thisObj) { if (typeof func != TYPES.f) { throw "Can't bind function!"; // closest thing possible to the ECMAScript 5 // internal IsCallable function //throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var proto = LEXICON.p; var aArgs = Array[proto].slice.call(arguments, 2); var fNOP = function() {}; var fBound = function() { return func.apply(this instanceof fNOP ? this : thisObj, aArgs.concat(Array[proto].slice.call(arguments))); }; if (func[proto]) fNOP[proto] = func[proto]; // Function.prototype doesn't have a prototype property fBound[proto] = new fNOP(); return fBound; } /** * Gets the vendor-prefixed CSS property by the given name. * For example the given name is "transform" and you're using a old Firefox browser then the returned value would be "-moz-transform". * If the browser doesn't need a vendor-prefix, then the returned string is the given name. * If the browser doesn't support the given property name at all (not even with a vendor-prefix) the returned value is null. * @param propName The unprefixed CSS property name. * @returns {string|null} The vendor-prefixed CSS property or null if the browser doesn't support the given CSS property. cssProp : function(propName) { return VENDORS._cssProperty(propName); } */ }; var MATH = Math; var JQUERY = window.jQuery; var EASING = (function() { var _easingsMath = { p : MATH.PI, c : MATH.cos, s : MATH.sin, w : MATH.pow, t : MATH.sqrt, n : MATH.asin, a : MATH.abs, o : 1.70158 }; /* x : current percent (0 - 1), t : current time (duration * percent), b : start value (from), c : end value (to), d : duration easingName : function(x, t, b, c, d) { return easedValue; } */ return { swing: function (x, t, b, c, d) { return 0.5 - _easingsMath.c(x * _easingsMath.p) / 2; }, linear: function(x, t, b, c, d) { return x; }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t + b : -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t*t + b : c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t*t*t + b : -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t*t*t*t + b : c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * _easingsMath.c(t/d * (_easingsMath.p/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * _easingsMath.s(t/d * (_easingsMath.p/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (_easingsMath.c(_easingsMath.p*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * _easingsMath.w(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-_easingsMath.w(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * _easingsMath.w(2, 10 * (t - 1)) + b; return c/2 * (-_easingsMath.w(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (_easingsMath.t(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * _easingsMath.t(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? -c/2 * (_easingsMath.t(1 - t*t) - 1) + b : c/2 * (_easingsMath.t(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=_easingsMath.o;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < _easingsMath.a(c)) { a=c; s=p/4; } else s = p/(2*_easingsMath.p) * _easingsMath.n (c/a); return -(a*_easingsMath.w(2,10*(t-=1)) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=_easingsMath.o;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < _easingsMath.a(c)) { a=c; s=p/4; } else s = p/(2*_easingsMath.p) * _easingsMath.n (c/a); return a*_easingsMath.w(2,-10*t) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=_easingsMath.o;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < _easingsMath.a(c)) { a=c; s=p/4; } else s = p/(2*_easingsMath.p) * _easingsMath.n (c/a); if (t < 1) return -.5*(a*_easingsMath.w(2,10*(t-=1)) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p )) + b; return a*_easingsMath.w(2,-10*(t-=1)) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { s = s || _easingsMath.o; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { s = s || _easingsMath.o; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { s = s || _easingsMath.o; return ((t/=d/2) < 1) ? c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b : c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - this.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { var o = 7.5625; if ((t/=d) < (1/2.75)) { return c*(o*t*t) + b; } else if (t < (2/2.75)) { return c*(o*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(o*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(o*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { return (t < d/2) ? this.easeInBounce (x, t*2, 0, c, d) * .5 + b : this.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }; /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ })(); var FRAMEWORK = (function() { var _rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); var _strSpace = ' '; var _strEmpty = ''; var _strScrollLeft = 'scrollLeft'; var _strScrollTop = 'scrollTop'; var _animations = [ ]; var _type = COMPATIBILITY.type; var _cssNumber = { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }; var extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments[LEXICON.l], deep = false; // Handle a deep copy situation if (_type(target) == TYPES.b) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (_type(target) != TYPES.o && !_type(target) == TYPES.f) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = FakejQuery; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = COMPATIBILITY.isA(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && COMPATIBILITY.isA(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[name] = extend(deep, clone, copy); // Don't bring in undefined values } else if (copy !== undefined) { target[name] = copy; } } } } // Return the modified object return target; }; var inArray = function(item, arr, fromIndex) { for (var i = fromIndex || 0; i < arr[LEXICON.l]; i++) if (arr[i] === item) return i; return -1; } var isFunction = function(obj) { return _type(obj) == TYPES.f; }; var isEmptyObject = function(obj) { for (var name in obj ) return false; return true; }; var isPlainObject = function(obj) { if (!obj || _type(obj) != TYPES.o) return false; var key; var proto = LEXICON.p; var hasOwnProperty = Object[proto].hasOwnProperty; var hasOwnConstructor = hasOwnProperty.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor[proto] && hasOwnProperty.call(obj.constructor[proto], 'isPrototypeOf'); if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } for (key in obj) { /**/ } return _type(key) == TYPES.u || hasOwnProperty.call(obj, key); }; var each = function(obj, callback) { var i = 0; if (isArrayLike(obj)) { for (; i < obj[LEXICON.l]; i++) { if (callback.call(obj[i], i, obj[i]) === false) break; } } else { for (i in obj) { if (callback.call(obj[i], i, obj[i]) === false) break; } } return obj; }; var FakejQuery = function (selector) { if(arguments[LEXICON.l] === 0) return this; var base = new FakejQuery(); var elements = selector; var i = 0; var elms; var el; if(_type(selector) == TYPES.s) { elements = [ ]; if(selector.charAt(0) === '<') { el = document.createElement('div'); el.innerHTML = selector; elms = el.children; } else { elms = document.querySelectorAll(selector); } for(; i < elms[LEXICON.l]; i++) elements.push(elms[i]); } if(elements) { if(_type(elements) != TYPES.s && (!isArrayLike(elements) || elements === window || elements === elements.self)) elements = [ elements ]; for(i = 0; i < elements[LEXICON.l]; i++) base[i] = elements[i]; base[LEXICON.l] = elements[LEXICON.l]; } return base; }; function isArrayLike(obj) { var length = !!obj && [LEXICON.l] in obj && obj[LEXICON.l]; var t = _type(obj); return isFunction(t) ? false : (t == TYPES.a || length === 0 || _type(length) == TYPES.n && length > 0 && (length - 1) in obj); } function stripAndCollapse(value) { var tokens = value.match(_rnothtmlwhite) || []; return tokens.join(_strSpace); } function matches(elem, selector) { var nodeList = (elem.parentNode || document).querySelectorAll(selector) || []; var i = nodeList[LEXICON.l]; while (i--) if (nodeList[i] == elem) return true; return false; } function insertAdjacentElement(el, strategy, child) { if(_type(child) == TYPES.a) { for(var i = 0; i < child[LEXICON.l]; i++) insertAdjacentElement(el, strategy, child[i]); } else if(_type(child) == TYPES.s) el.insertAdjacentHTML(strategy, child); else el.insertAdjacentElement(strategy, child.nodeType ? child : child[0]); } function setCSSVal(el, prop, val) { try { if(el[LEXICON.s][prop] !== undefined) el[LEXICON.s][prop] = parseCSSVal(prop, val); } catch(e) { } } function parseCSSVal(prop, val) { if(!_cssNumber[prop.toLowerCase()] && _type(val) == TYPES.n) val += 'px'; return val; } function startNextAnimationInQ(animObj, removeFromQ) { var index; var nextAnim; if(removeFromQ !== false) animObj.q.splice(0, 1); if(animObj.q[LEXICON.l] > 0) { nextAnim = animObj.q[0]; animate(animObj.el, nextAnim.props, nextAnim.duration, nextAnim.easing, nextAnim.complete, true); } else { index = inArray(animObj, _animations); if(index > -1) _animations.splice(index, 1); } } function setAnimationValue(el, prop, value) { if(prop === _strScrollLeft || prop === _strScrollTop) el[prop] = value; else setCSSVal(el, prop, value); } function animate(el, props, options, easing, complete, guaranteedNext) { var hasOptions = isPlainObject(options); var from = { }; var to = { }; var i = 0; var key; var animObj; var start; var progress; var step; var specialEasing; var duration; if(hasOptions) { easing = options.easing; start = options.start; progress = options.progress; step = options.step; specialEasing = options.specialEasing; complete = options.complete; duration = options.duration; } else duration = options; specialEasing = specialEasing || { }; duration = duration || 400; easing = easing || 'swing'; guaranteedNext = guaranteedNext || false; for(; i < _animations[LEXICON.l]; i++) { if(_animations[i].el === el) { animObj = _animations[i]; break; } } if(!animObj) { animObj = { el : el, q : [] }; _animations.push(animObj); } for (key in props) { if(key === _strScrollLeft || key === _strScrollTop) from[key] = el[key]; else from[key] = FakejQuery(el).css(key); } for (key in from) { if(from[key] !== props[key] && props[key] !== undefined) to[key] = props[key]; } if(!isEmptyObject(to)) { var timeNow; var end; var percent; var fromVal; var toVal; var easedVal; var timeStart; var frame; var elapsed; var qPos = guaranteedNext ? 0 : inArray(qObj, animObj.q); var qObj = { props : to, duration : hasOptions ? options : duration, easing : easing, complete : complete }; if (qPos === -1) { qPos = animObj.q[LEXICON.l]; animObj.q.push(qObj); } if(qPos === 0) { if(duration > 0) { timeStart = COMPATIBILITY.now(); frame = function() { timeNow = COMPATIBILITY.now(); elapsed = (timeNow - timeStart); end = qObj.stop || elapsed >= duration; percent = 1 - ((MATH.max(0, timeStart + duration - timeNow) / duration) || 0); for(key in to) { fromVal = parseFloat(from[key]); toVal = parseFloat(to[key]); easedVal = (toVal - fromVal) * EASING[specialEasing[key] || easing](percent, percent * duration, 0, 1, duration) + fromVal; setAnimationValue(el, key, easedVal); if(isFunction(step)) { step(easedVal, { elem : el, prop : key, start : fromVal, now : easedVal, end : toVal, pos : percent, options : { easing : easing, speacialEasing : specialEasing, duration : duration, complete : complete, step : step }, startTime : timeStart }); } } if(isFunction(progress)) progress({ }, percent, MATH.max(0, duration - elapsed)); if (end) { startNextAnimationInQ(animObj); if(isFunction(complete)) complete(); } else qObj.frame = COMPATIBILITY.rAF()(frame); }; qObj.frame = COMPATIBILITY.rAF()(frame); } else { for(key in to) setAnimationValue(el, key, to[key]); startNextAnimationInQ(animObj); } } } else if(guaranteedNext) startNextAnimationInQ(animObj); } function stop(el, clearQ, jumpToEnd) { var animObj; var qObj; var key; var i = 0; for(; i < _animations[LEXICON.l]; i++) { animObj = _animations[i]; if(animObj.el === el) { if(animObj.q[LEXICON.l] > 0) { qObj = animObj.q[0]; qObj.stop = true; COMPATIBILITY.cAF()(qObj.frame); animObj.q.splice(0, 1); if(jumpToEnd) for(key in qObj.props) setAnimationValue(el, key, qObj.props[key]); if(clearQ) animObj.q = [ ]; else startNextAnimationInQ(animObj, false); } break; } } } FakejQuery[LEXICON.p] = { //EVENTS: on : function(eventName, handler) { eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty]; var eventNameLength = eventName[LEXICON.l]; var i = 0; var el; return this.each(function() { el = this; try { if (el.addEventListener) { for (; i < eventNameLength; i++) el.addEventListener(eventName[i], handler); } else if(el.detachEvent) { for (; i < eventNameLength; i++) el.attachEvent('on' + eventName[i], handler); } } catch (e) { } }); }, off : function(eventName, handler) { eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty]; var eventNameLength = eventName[LEXICON.l]; var i = 0; var el; return this.each(function() { el = this; try { if (el.removeEventListener) { for (; i < eventNameLength; i++) el.removeEventListener(eventName[i], handler); } else if(el.detachEvent) { for (; i < eventNameLength; i++) el.detachEvent('on' + eventName[i], handler); } } catch (e) { } }); }, one : function (eventName, handler) { eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty]; return this.each(function() { var el = FakejQuery(this); FakejQuery.each(eventName, function(i, oneEventName) { var oneHandler = function(e) { handler.call(this, e); el.off(oneEventName, oneHandler); }; el.on(oneEventName, oneHandler); }); }); }, trigger : function(eventName) { var el; var event; return this.each(function() { el = this; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); el.dispatchEvent(event); } else { el.fireEvent("on" + eventName); } }); }, //DOM NODE INSERTING / REMOVING: append : function(child) { return this.each(function() { insertAdjacentElement(this, 'beforeend', child); }); }, prepend : function(child) { return this.each(function() { insertAdjacentElement(this, 'afterbegin', child); }); }, before : function(child) { return this.each(function() { insertAdjacentElement(this, 'beforebegin', child); }); }, after : function(child) { return this.each(function() { insertAdjacentElement(this, 'afterend', child); }); }, remove : function() { return this.each(function() { var el = this; var parentNode = el.parentNode; if(parentNode != null) parentNode.removeChild(el); }); }, unwrap : function() { var parents = [ ]; var i; var el; var parent; this.each(function() { parent = this.parentNode; if(inArray(parent, parents) === - 1) parents.push(parent); }); for(i = 0; i < parents[LEXICON.l]; i++) { el = parents[i]; parent = el.parentNode; while (el.firstChild) parent.insertBefore(el.firstChild, el); parent.removeChild(el); } return this; }, wrapAll : function(wrapperHTML) { var i; var nodes = this; var wrapper = FakejQuery(wrapperHTML)[0]; var deepest = wrapper; var parent = nodes[0].parentNode; var previousSibling = nodes[0].previousSibling; while(deepest.childNodes[LEXICON.l] > 0) deepest = deepest.childNodes[0]; for (i = 0; nodes[LEXICON.l] - i; deepest.firstChild === nodes[0] && i++) deepest.appendChild(nodes[i]); var nextSibling = previousSibling ? previousSibling.nextSibling : parent.firstChild; parent.insertBefore(wrapper, nextSibling); return this; }, wrapInner : function(wrapperHTML) { return this.each(function() { var el = FakejQuery(this); var contents = el.contents(); if (contents[LEXICON.l]) contents.wrapAll(wrapperHTML); else el.append(wrapperHTML); }); }, wrap : function(wrapperHTML) { return this.each(function() { FakejQuery(this).wrapAll(wrapperHTML); }); }, //DOM NODE MANIPULATION / INFORMATION: css : function(styles, val) { var el; var key; var cptStyle; var getCptStyle = window.getComputedStyle; if(_type(styles) == TYPES.s) { if(val === undefined) { el = this[0]; cptStyle = getCptStyle ? getCptStyle(el, null) : el.currentStyle[styles]; //https://bugzilla.mozilla.org/show_bug.cgi?id=548397 can be null sometimes if iframe with display: none (firefox only!) return getCptStyle ? cptStyle != null ? cptStyle.getPropertyValue(styles) : el[LEXICON.s][styles] : cptStyle; } else { return this.each(function() { setCSSVal(this, styles, val); }); } } else { return this.each(function() { for(key in styles) setCSSVal(this, key, styles[key]); }); } }, hasClass : function(className) { var elem, i = 0; var classNamePrepared = _strSpace + className + _strSpace; var classList; while ((elem = this[ i++ ])) { classList = elem.classList; if(classList && classList.contains(className)) return true; else if (elem.nodeType === 1 && (_strSpace + stripAndCollapse(elem.className + _strEmpty) + _strSpace).indexOf(classNamePrepared) > -1) return true; } return false; }, addClass : function(className) { var classes; var elem; var cur; var curValue; var clazz; var finalValue; var supportClassList; var elmClassList; var i = 0; var v = 0; if (className) { classes = className.match( _rnothtmlwhite ) || []; while ((elem = this[i++])) { elmClassList = elem.classList; if(supportClassList === undefined) supportClassList = elmClassList !== undefined; if(supportClassList) { while ((clazz = classes[v++])) elmClassList.add(clazz); } else { curValue = elem.className + _strEmpty; cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace); if (cur) { while ((clazz = classes[v++])) if (cur.indexOf(_strSpace + clazz + _strSpace) < 0) cur += clazz + _strSpace; finalValue = stripAndCollapse(cur); if (curValue !== finalValue) elem.className = finalValue; } } } } return this; }, removeClass : function(className) { var classes; var elem; var cur; var curValue; var clazz; var finalValue; var supportClassList; var elmClassList; var i = 0; var v = 0; if (className) { classes = className.match(_rnothtmlwhite) || []; while ((elem = this[i++])) { elmClassList = elem.classList; if(supportClassList === undefined) supportClassList = elmClassList !== undefined; if(supportClassList) { while ((clazz = classes[v++])) elmClassList.remove(clazz); } else { curValue = elem.className + _strEmpty; cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace); if (cur) { while ((clazz = classes[v++])) while (cur.indexOf(_strSpace + clazz + _strSpace) > -1) cur = cur.replace(_strSpace + clazz + _strSpace, _strSpace); finalValue = stripAndCollapse(cur); if (curValue !== finalValue) elem.className = finalValue; } } } } return this; }, hide : function() { return this.each(function() { this[LEXICON.s].display = 'none'; }); }, show : function() { return this.each(function() { this[LEXICON.s].display = 'block'; }); }, attr : function(attrName, value) { var i = 0; var el; while (el = this[i++]) { if(value === undefined) return el.getAttribute(attrName); el.setAttribute(attrName, value); } return this; }, removeAttr : function(attrName) { return this.each(function() { this.removeAttribute(attrName); }); }, offset : function() { var el = this[0]; var rect = el.getBoundingClientRect(); var scrollLeft = window.pageXOffset || document.documentElement[_strScrollLeft]; var scrollTop = window.pageYOffset || document.documentElement[_strScrollTop]; return { top: rect.top + scrollTop, left: rect.left + scrollLeft }; }, position : function() { var el = this[0]; return { top: el.offsetTop, left: el.offsetLeft }; }, scrollLeft : function(value) { var i = 0; var el; while (el = this[i++]) { if(value === undefined) return el[_strScrollLeft]; el[_strScrollLeft] = value; } return this; }, scrollTop : function(value) { var i = 0; var el; while (el = this[i++]) { if(value === undefined) return el[_strScrollTop]; el[_strScrollTop] = value; } return this; }, val : function(value) { var el = this[0]; if(!value) return el.value; el.value = value; return this; }, //DOM TRAVERSAL / FILTERING: first : function() { return this.eq(0); }, last : function() { return this.eq(-1); }, eq : function(index) { return FakejQuery(this[index >= 0 ? index : this[LEXICON.l] + index]); }, find : function(selector) { var children = [ ]; var i; this.each(function() { var el = this; var ch = el.querySelectorAll(selector); for(i = 0; i < ch[LEXICON.l]; i++) children.push(ch[i]); }); return FakejQuery(children); }, children : function(selector) { var children = [ ]; var el; var ch; var i; this.each(function() { ch = this.children; for(i = 0; i < ch[LEXICON.l]; i++) { el = ch[i]; if(selector) { if((el.matches && el.matches(selector)) || matches(el, selector)) children.push(el); } else children.push(el); } }); return FakejQuery(children); }, parent : function(selector) { var parents = [ ]; var parent; this.each(function() { parent = this.parentNode; if(selector ? FakejQuery(parent).is(selector) : true) parents.push(parent); }); return FakejQuery(parents); }, is : function(selector) { var el; var i; for(i = 0; i < this[LEXICON.l]; i++) { el = this[i]; if(selector === ":visible") return !!(el[LEXICON.oW] || el[LEXICON.oH] || el.getClientRects()[LEXICON.l]); if(selector === ":hidden") return !!!(el[LEXICON.oW] || el[LEXICON.oH] || el.getClientRects()[LEXICON.l]); if((el.matches && el.matches(selector)) || matches(el, selector)) return true; } return false; }, contents : function() { var contents = [ ]; var childs; var i; this.each(function() { childs = this.childNodes; for(i = 0; i < childs[LEXICON.l]; i++) contents.push(childs[i]); }); return FakejQuery(contents); }, each : function(callback) { return each(this, callback); }, //ANIMATION: animate : function(props, duration, easing, complete) { return this.each(function() { animate(this, props, duration, easing, complete); }); }, stop : function(clearQ, jump) { return this.each(function() { stop(this, clearQ, jump); }); } }; extend(FakejQuery, { extend : extend, inArray : inArray, isEmptyObject : isEmptyObject, isPlainObject : isPlainObject, each : each }); return FakejQuery; })(); var INSTANCES = (function() { var _targets = [ ]; var _instancePropertyString = '__overlayScrollbars__'; /** * Register, unregister or get a certain (or all) instances. * Register: Pass the target and the instance. * Unregister: Pass the target and null. * Get Instance: Pass the target from which the instance shall be got. * Get Targets: Pass no arguments. * @param target The target to which the instance shall be registered / from which the instance shall be unregistered / the instance shall be got * @param instance The instance. * @returns {*|void} Returns the instance from the given target. */ return function (target, instance) { var argLen = arguments[LEXICON.l]; if(argLen < 1) { //return all targets return _targets; } else { if(instance) { //register instance target[_instancePropertyString] = instance; _targets.push(target); } else { var index = COMPATIBILITY.inA(target, _targets); if (index > -1) { if(argLen > 1) { //unregister instance delete target[_instancePropertyString]; _targets.splice(index, 1); } else { //get instance from target return _targets[index][_instancePropertyString]; } } } } } })(); var PLUGIN = (function() { var _pluginsGlobals; var _pluginsAutoUpdateLoop; var _pluginsExtensions = [ ]; var _pluginsOptions = (function() { var possibleTemplateTypes = [ TYPES.b, //boolean TYPES.n, //number TYPES.s, //string TYPES.a, //array TYPES.o, //object TYPES.f, //function TYPES.z //null ]; var restrictedStringsSplit = ' '; var restrictedStringsPossibilitiesSplit = ':'; var classNameAllowedValues = [TYPES.z, TYPES.s]; var numberAllowedValues = TYPES.n; var booleanNullAllowedValues = [TYPES.z, TYPES.b]; var booleanTrueTemplate = [true, TYPES.b]; var booleanFalseTemplate = [false, TYPES.b]; var callbackTemplate = [null, [TYPES.z, TYPES.f]]; var inheritedAttrsTemplate = [['style', 'class'], [TYPES.s, TYPES.a, TYPES.z]]; var resizeAllowedValues = 'n:none b:both h:horizontal v:vertical'; var overflowBehaviorAllowedValues = 'v-h:visible-hidden v-s:visible-scroll s:scroll h:hidden'; var scrollbarsVisibilityAllowedValues = 'v:visible h:hidden a:auto'; var scrollbarsAutoHideAllowedValues = 'n:never s:scroll l:leave m:move'; var optionsDefaultsAndTemplate = { className: ['os-theme-dark', classNameAllowedValues], //null || string resize: ['none', resizeAllowedValues], //none || both || horizontal || vertical || n || b || h || v sizeAutoCapable: booleanTrueTemplate, //true || false clipAlways: booleanTrueTemplate, //true || false normalizeRTL: booleanTrueTemplate, //true || false paddingAbsolute: booleanFalseTemplate, //true || false autoUpdate: [null, booleanNullAllowedValues], //true || false || null autoUpdateInterval: [33, numberAllowedValues], //number nativeScrollbarsOverlaid: { showNativeScrollbars: booleanFalseTemplate, //true || false initialize: booleanTrueTemplate //true || false }, overflowBehavior: { x: ['scroll', overflowBehaviorAllowedValues], //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s y: ['scroll', overflowBehaviorAllowedValues] //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s }, scrollbars: { visibility: ['auto', scrollbarsVisibilityAllowedValues], //visible || hidden || auto || v || h || a autoHide: ['never', scrollbarsAutoHideAllowedValues], //never || scroll || leave || move || n || s || l || m autoHideDelay: [800, numberAllowedValues], //number dragScrolling: booleanTrueTemplate, //true || false clickScrolling: booleanFalseTemplate, //true || false touchSupport: booleanTrueTemplate, //true || false snapHandle: booleanFalseTemplate //true || false }, textarea: { dynWidth: booleanFalseTemplate, //true || false dynHeight: booleanFalseTemplate, //true || false inheritedAttrs : inheritedAttrsTemplate //string || array || null }, callbacks: { onInitialized: callbackTemplate, //null || function onInitializationWithdrawn: callbackTemplate, //null || function onDestroyed: callbackTemplate, //null || function onScrollStart: callbackTemplate, //null || function onScroll: callbackTemplate, //null || function onScrollStop: callbackTemplate, //null || function onOverflowChanged: callbackTemplate, //null || function onOverflowAmountChanged: callbackTemplate, //null || function onDirectionChanged: callbackTemplate, //null || function onContentSizeChanged: callbackTemplate, //null || function onHostSizeChanged: callbackTemplate, //null || function onUpdated: callbackTemplate //null || function } }; var convert = function(template) { var recursive = function(obj) { var key; var val; var valType; for(key in obj) { if(!obj.hasOwnProperty(key)) continue; val = obj[key]; valType = COMPATIBILITY.type(val); if(valType == TYPES.a) obj[key] = val[template ? 1 : 0]; else if(valType == TYPES.o) obj[key] = recursive(val); } return obj; }; return recursive(FRAMEWORK.extend(true, { }, optionsDefaultsAndTemplate)); }; return { _defaults : convert(), _template : convert(true), /** * Validates the passed object by the passed template. * @param obj The object which shall be validated. * @param template The template which defines the allowed values and types. * @param writeErrors True if errors shall be logged to the console. * @param usePreparedValues True if the validated main values shall be returned in the validated object, false otherwise. * @param keepForeignProps True if properties which aren't in the template shall be added to the validated object, false otherwise. * @returns {{}} A object which contains only the valid properties of the passed original object. */ _validate : function (obj, template, writeErrors, usePreparedValues, keepForeignProps) { var validatedOptions = { }; var objectCopy = FRAMEWORK.extend(true, { }, obj); var checkObjectProps = function(data, template, validatedOptions, prevPropName) { for (var prop in template) { if (template.hasOwnProperty(prop) && data.hasOwnProperty(prop)) { var isValid = false; var templateValue = template[prop]; var templateValueType = COMPATIBILITY.type(templateValue); var templateIsComplext = templateValueType == TYPES.o; var templateTypes = COMPATIBILITY.type(templateValue) != TYPES.a ? [ templateValue ] : templateValue; var dataValue = data[prop]; var dataValueType = COMPATIBILITY.type(dataValue); var propPrefix = prevPropName ? prevPropName + "." : ""; var error = "The option \"" + propPrefix + prop + "\" wasn't set, because"; var errorPossibleTypes = [ ]; var errorRestrictedStrings = [ ]; var restrictedStringValuesSplit; var restrictedStringValuesPossibilitiesSplit; var isRestrictedValue; var mainPossibility; var currType; var i; var v; var j; //if the template has a object as value, it means that the options are complex (verschachtelt) if(templateIsComplext && dataValueType == TYPES.o) { validatedOptions[prop] = { }; checkObjectProps(dataValue, templateValue, validatedOptions[prop], propPrefix + prop); if(FRAMEWORK.isEmptyObject(dataValue)) delete data[prop]; } else if(!templateIsComplext) { for(i = 0; i < templateTypes.length; i++) { currType = templateTypes[i]; templateValueType = COMPATIBILITY.type(currType); //if currtype is string and starts with restrictedStringPrefix and end with restrictedStringSuffix isRestrictedValue = templateValueType == TYPES.s && FRAMEWORK.inArray(currType, possibleTemplateTypes) === -1; if(isRestrictedValue) { errorPossibleTypes.push(TYPES.s); //split it into a array which contains all possible values for example: ["y:yes", "n:no", "m:maybe"] restrictedStringValuesSplit = currType.split(restrictedStringsSplit); errorRestrictedStrings = errorRestrictedStrings.concat(restrictedStringValuesSplit); for(v = 0; v < restrictedStringValuesSplit.length; v++) { //split the possible values into their possibiliteis for example: ["y", "yes"] -> the first is always the mainPossibility restrictedStringValuesPossibilitiesSplit = restrictedStringValuesSplit[v].split(restrictedStringsPossibilitiesSplit); mainPossibility = restrictedStringValuesPossibilitiesSplit[0]; for(j = 0; j < restrictedStringValuesPossibilitiesSplit.length; j++) { //if any possibility matches with the dataValue, its valid if(dataValue === restrictedStringValuesPossibilitiesSplit[j]) { isValid = true; break; } } if(isValid) break; } } else { errorPossibleTypes.push(currType); if(dataValueType === currType) { isValid = true; break; } } } if(isValid) { validatedOptions[prop] = isRestrictedValue && usePreparedValues ? mainPossibility : dataValue; } else if(writeErrors) { console.warn(error + " it doesn't accept the type [ " + dataValueType.toUpperCase() + " ] with the value of \"" + dataValue + "\".\r\n" + "Accepted types are: [ " + errorPossibleTypes.join(", ").toUpperCase() + " ]." + (errorRestrictedStrings.length > 0 ? "\r\nValid strings are: [ " + errorRestrictedStrings.join(", ").split(restrictedStringsPossibilitiesSplit).join(", ") + " ]." : "")); } delete data[prop]; } } } }; checkObjectProps(objectCopy, template, validatedOptions); //add values which aren't specified in the template to the finished validated object to prevent them from being discarded if(keepForeignProps) FRAMEWORK.extend(true, validatedOptions, objectCopy); else if(!FRAMEWORK.isEmptyObject(objectCopy) && writeErrors) console.warn("The following options are discarded due to invalidity:\r\n" + window.JSON.stringify(objectCopy, null, 2)); return validatedOptions; } } }()); /** * Initializes the object which contains global information about the plugin and each instance of it. */ function initOverlayScrollbarsStatics() { if(!_pluginsGlobals) _pluginsGlobals = new OverlayScrollbarsGlobals(_pluginsOptions._defaults); if(!_pluginsAutoUpdateLoop) _pluginsAutoUpdateLoop = new OverlayScrollbarsAutoUpdateLoop(_pluginsGlobals); } /** * The global object for the OverlayScrollbars objects. It contains resources which every OverlayScrollbars object needs. This object is initialized only once: if the first OverlayScrollbars object gets initialized. * @param defaultOptions * @constructor */ function OverlayScrollbarsGlobals(defaultOptions) { var _base = this; var strOverflow = 'overflow'; var strHidden = 'hidden'; var strScroll = 'scroll'; var bodyElement = FRAMEWORK('body'); var scrollbarDummyElement = FRAMEWORK('<div id="os-dummy-scrollbar-size"><div></div></div>'); var scrollbarDummyElement0 = scrollbarDummyElement[0]; var dummyContainerChild = FRAMEWORK(scrollbarDummyElement.children('div').eq(0)); var getCptStyle = window.getComputedStyle; bodyElement.append(scrollbarDummyElement); scrollbarDummyElement.hide().show(); //fix IE8 bug (incorrect measuring) var nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement0); var nativeScrollbarIsOverlaid = { x: nativeScrollbarSize.x === 0, y: nativeScrollbarSize.y === 0 }; FRAMEWORK.extend(_base, { defaultOptions : defaultOptions, autoUpdateLoop : false, autoUpdateRecommended : !COMPATIBILITY.mO(), nativeScrollbarSize : nativeScrollbarSize, nativeScrollbarIsOverlaid : nativeScrollbarIsOverlaid, nativeScrollbarStyling : (function() { scrollbarDummyElement.addClass('os-viewport-native-scrollbars-invisible'); //fix opera bug: scrollbar styles will only appear if overflow value is scroll or auto during the activation of the style. //and set overflow to scroll //scrollbarDummyElement.css(strOverflow, strHidden).hide().css(strOverflow, strScroll).show(); //return (scrollbarDummyElement0[LEXICON.oH] - scrollbarDummyElement0[LEXICON.cH]) === 0 && (scrollbarDummyElement0[LEXICON.oW] - scrollbarDummyElement0[LEXICON.cW]) === 0; return scrollbarDummyElement.css('scrollbar-width') === 'none' || (getCptStyle ? getCptStyle(scrollbarDummyElement0, '::-webkit-scrollbar').getPropertyValue('display') === 'none' : false); })(), overlayScrollbarDummySize : { x: 30, y: 30 }, msie : (function() { var ua = window.navigator.userAgent; var strIndexOf = 'indexOf'; var strSubString = 'substring'; var msie = ua[strIndexOf]('MSIE '); var trident = ua[strIndexOf]('Trident/'); var edge = ua[strIndexOf]('Edge/'); var rv = ua[strIndexOf]('rv:'); var result; var parseIntFunc = parseInt; // IE 10 or older => return version number if (msie > 0) result = parseIntFunc(ua[strSubString](msie + 5, ua[strIndexOf]('.', msie)), 10); // IE 11 => return version number else if (trident > 0) result = parseIntFunc(ua[strSubString](rv + 3, ua[strIndexOf]('.', rv)), 10); // Edge (IE 12+) => return version number else if (edge > 0) result = parseIntFunc(ua[strSubString](edge + 5, ua[strIndexOf]('.', edge)), 10); // other browser return result; })(), cssCalc : (function() { var dummyStyle = document.createElement('div')[LEXICON.s]; var strCalc = 'calc'; var i = -1; var prop; for(; i < VENDORS._cssPrefixes[LEXICON.l]; i++) { prop = i < 0 ? strCalc : VENDORS._cssPrefixes[i] + strCalc; dummyStyle.cssText = 'width:' + prop + '(1px);'; if (dummyStyle[LEXICON.l]) return prop; } return null; })(), restrictedMeasuring : (function() { //https://bugzilla.mozilla.org/show_bug.cgi?id=1439305 scrollbarDummyElement.css(strOverflow, strHidden); var scrollSize = { w : scrollbarDummyElement0[LEXICON.sW], h : scrollbarDummyElement0[LEXICON.sH] }; scrollbarDummyElement.css(strOverflow, 'visible'); var scrollSize2 = { w : scrollbarDummyElement0[LEXICON.sW], h : scrollbarDummyElement0[LEXICON.sH] }; return (scrollSize.w - scrollSize2.w) !== 0 || (scrollSize.h - scrollSize2.h) !== 0; })(), rtlScrollBehavior : (function() { scrollbarDummyElement.css({ 'overflow-y' : strHidden, 'overflow-x' : strScroll, 'direction' : 'rtl' }).scrollLeft(0); var dummyContainerOffset = scrollbarDummyElement.offset(); var dummyContainerChildOffset = dummyContainerChild.offset(); scrollbarDummyElement.scrollLeft(999); var dummyContainerScrollOffsetAfterScroll = dummyContainerChild.offset(); return { //origin direction = determines if the zero scroll position is on the left or right side //'i' means 'invert' (i === true means that the axis must be inverted to be correct) //true = on the left side //false = on the right side i : dummyContainerOffset.left === dummyContainerChildOffset.left, //negative = determines if the maximum scroll is positive or negative //'n' means 'negate' (n === true means that the axis must be negated to be correct) //true = negative //false = positive n : dummyContainerChildOffset.left - dummyContainerScrollOffsetAfterScroll.left === 0 }; })(), supportTransform : VENDORS._cssProperty('transform') !== null, supportTransition : VENDORS._cssProperty('transition') !== null, supportPassiveEvents : (function() { var supportsPassive = false; try { window.addEventListener('test', null, Object.defineProperty({ }, 'passive', { get: function() { supportsPassive = true; } })); } catch (e) { } return supportsPassive; })(), supportResizeObserver : !!COMPATIBILITY.rO(), supportMutationObserver : !!COMPATIBILITY.mO() }); scrollbarDummyElement.removeAttr(LEXICON.s).remove(); //Catch zoom event: (function () { if(nativeScrollbarIsOverlaid.x && nativeScrollbarIsOverlaid.y) return; var abs = MATH.abs; var windowWidth = COMPATIBILITY.wW(); var windowHeight = COMPATIBILITY.wH(); var windowDpr = getWindowDPR(); var onResize = function() { if(INSTANCES().length > 0) { var newW = COMPATIBILITY.wW(); var newH = COMPATIBILITY.wH(); var deltaW = newW - windowWidth; var deltaH = newH - windowHeight; if (deltaW === 0 && deltaH === 0) return; var deltaWRatio = MATH.round(newW / (windowWidth / 100.0)); var deltaHRatio = MATH.round(newH / (windowHeight / 100.0)); var absDeltaW = abs(deltaW); var absDeltaH = abs(deltaH); var absDeltaWRatio = abs(deltaWRatio); var absDeltaHRatio = abs(deltaHRatio); var newDPR = getWindowDPR(); var deltaIsBigger = absDeltaW > 2 && absDeltaH > 2; var difference = !differenceIsBiggerThanOne(absDeltaWRatio, absDeltaHRatio); var dprChanged = newDPR !== windowDpr && windowDpr > 0; var isZoom = deltaIsBigger && difference && dprChanged; var oldScrollbarSize = _base.nativeScrollbarSize; var newScrollbarSize; if (isZoom) { bodyElement.append(scrollbarDummyElement); newScrollbarSize = _base.nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement[0]); scrollbarDummyElement.remove(); if(oldScrollbarSize.x !== newScrollbarSize.x || oldScrollbarSize.y !== newScrollbarSize.y) { FRAMEWORK.each(INSTANCES(), function () { if(INSTANCES(this)) INSTANCES(this).update('zoom'); }); } } windowWidth = newW; windowHeight = newH; windowDpr = newDPR; } }; function differenceIsBiggerThanOne(valOne, valTwo) { var absValOne = abs(valOne); var absValTwo = abs(valTwo); return !(absValOne === absValTwo || absValOne + 1 === absValTwo || absValOne - 1 === absValTwo); } function getWindowDPR() { var dDPI = window.screen.deviceXDPI || 0; var sDPI = window.screen.logicalXDPI || 1; return window.devicePixelRatio || (dDPI / sDPI); } FRAMEWORK(window).on('resize', onResize); })(); function calcNativeScrollbarSize(measureElement) { return { x: measureElement[LEXICON.oH] - measureElement[LEXICON.cH], y: measureElement[LEXICON.oW] - measureElement[LEXICON.cW] }; } } /** * The object which manages the auto update loop for all OverlayScrollbars objects. This object is initialized only once: if the first OverlayScrollbars object gets initialized. * @constructor */ function OverlayScrollbarsAutoUpdateLoop(globals) { var _base = this; var _strAutoUpdate = 'autoUpdate'; var _strAutoUpdateInterval = _strAutoUpdate + 'Interval'; var _strLength = LEXICON.l; var _loopingInstances = [ ]; var _loopingInstancesIntervalCache = [ ]; var _loopIsActive = false; var _loopIntervalDefault = 33; var _loopInterval = _loopIntervalDefault; var _loopTimeOld = COMPATIBILITY.now(); var _loopID; /** * The auto update loop which will run every 50 milliseconds or less if the update interval of a instance is lower than 50 milliseconds. */ var loop = function() { if(_loopingInstances[_strLength] > 0 && _loopIsActive) { _loopID = COMPATIBILITY.rAF()(function () { loop(); }); var timeNew = COMPATIBILITY.now(); var timeDelta = timeNew - _loopTimeOld; var lowestInterval; var instance; var instanceOptions; var instanceAutoUpdateAllowed; var instanceAutoUpdateInterval; var now; if (timeDelta > _loopInterval) { _loopTimeOld = timeNew - (timeDelta % _loopInterval); lowestInterval = _loopIntervalDefault; for(var i = 0; i < _loopingInstances[_strLength]; i++) { instance = _loopingInstances[i]; if (instance !== undefined) { instanceOptions = instance.options(); instanceAutoUpdateAllowed = instanceOptions[_strAutoUpdate]; instanceAutoUpdateInterval = MATH.max(1, instanceOptions[_strAutoUpdateInterval]); now = COMPATIBILITY.now(); if ((instanceAutoUpdateAllowed === true || instanceAutoUpdateAllowed === null) && (now - _loopingInstancesIntervalCache[i]) > instanceAutoUpdateInterval) { instance.update('auto'); _loopingInstancesIntervalCache[i] = new Date(now += instanceAutoUpdateInterval); } lowestInterval = MATH.max(1, MATH.min(lowestInterval, instanceAutoUpdateInterval)); } } _loopInterval = lowestInterval; } } else { _loopInterval = _loopIntervalDefault; } }; /** * Add OverlayScrollbars instance to the auto update loop. Only successful if the instance isn't already added. * @param instance The instance which shall be updated in a loop automatically. */ _base.add = function(instance) { if(FRAMEWORK.inArray(instance, _loopingInstances) === -1) { _loopingInstances.push(instance); _loopingInstancesIntervalCache.push(COMPATIBILITY.now()); if (_loopingInstances[_strLength] > 0 && !_loopIsActive) { _loopIsActive = true; globals.autoUpdateLoop = _loopIsActive; loop(); } } }; /** * Remove OverlayScrollbars instance from the auto update loop. Only successful if the instance was added before. * @param instance The instance which shall be updated in a loop automatically. */ _base.remove = function(instance) { var index = FRAMEWORK.inArray(instance, _loopingInstances); if(index > -1) { //remove from loopingInstances list _loopingInstancesIntervalCache.splice(index, 1); _loopingInstances.splice(index, 1); //correct update loop behavior if (_loopingInstances[_strLength] === 0 && _loopIsActive) { _loopIsActive = false; globals.autoUpdateLoop = _loopIsActive; if(_loopID !== undefined) { COMPATIBILITY.cAF()(_loopID); _loopID = -1; } } } }; } /** * A object which manages the scrollbars visibility of the target element. * @param pluginTargetElement The element from which the scrollbars shall be hidden. * @param options The custom options. * @param extensions The custom extensions. * @param globals * @param autoUpdateLoop * @returns {*} * @constructor */ function OverlayScrollbarsInstance(pluginTargetElement, options, extensions, globals, autoUpdateLoop) { //if passed element is no HTML element: skip and return if(!isHTMLElement(pluginTargetElement)) return; //if passed element is already initialized: set passed options if there are any and return its instance if(INSTANCES(pluginTargetElement)) { var inst = INSTANCES(pluginTargetElement); inst.options(options); return inst; } //make correct instanceof var _base = new window[PLUGINNAME](); var _frameworkProto = FRAMEWORK[LEXICON.p]; //globals: var _nativeScrollbarIsOverlaid; var _overlayScrollbarDummySize; var _rtlScrollBehavior; var _autoUpdateRecommended; var _msieVersion; var _nativeScrollbarStyling; var _cssCalc; var _nativeScrollbarSize; var _supportTransition; var _supportTransform; var _supportPassiveEvents; var _supportResizeObserver; var _supportMutationObserver; var _restrictedMeasuring; //general readonly: var _initialized; var _destroyed; var _isTextarea; var _isBody; var _documentMixed; var _isTextareaHostGenerated; //general: var _isBorderBox; var _sizeAutoObserverAdded; var _paddingX; var _paddingY; var _borderX; var _borderY; var _marginX; var _marginY; var _isRTL; var _isSleeping; var _contentBorderSize = { }; var _scrollHorizontalInfo = { }; var _scrollVerticalInfo = { }; var _viewportSize = { }; var _nativeScrollbarMinSize = { }; //naming: var _strMinusHidden = '-hidden'; var _strMarginMinus = 'margin-'; var _strPaddingMinus = 'padding-'; var _strBorderMinus = 'border-'; var _strTop = 'top'; var _strRight = 'right'; var _strBottom = 'bottom'; var _strLeft = 'left'; var _strMinMinus = 'min-'; var _strMaxMinus = 'max-'; var _strWidth = 'width'; var _strHeight = 'height'; var _strFloat = 'float'; var _strEmpty = ''; var _strAuto = 'auto'; var _strScroll = 'scroll'; var _strHundredPercent = '100%'; var _strX = 'x'; var _strY = 'y'; var _strDot = '.'; var _strSpace = ' '; var _strScrollbar = 'scrollbar'; var _strMinusHorizontal = '-horizontal'; var _strMinusVertical = '-vertical'; var _strScrollLeft = _strScroll + 'Left'; var _strScrollTop = _strScroll + 'Top'; var _strMouseTouchDownEvent = 'mousedown touchstart'; var _strMouseTouchUpEvent = 'mouseup touchend touchcancel'; var _strMouseTouchMoveEvent = 'mousemove touchmove'; var _strMouseTouchEnter = 'mouseenter'; var _strMouseTouchLeave = 'mouseleave'; var _strKeyDownEvent = 'keydown'; var _strKeyUpEvent = 'keyup'; var _strSelectStartEvent = 'selectstart'; var _strTransitionEndEvent = 'transitionend webkitTransitionEnd oTransitionEnd'; var _strResizeObserverProperty = '__overlayScrollbarsRO__'; //class names: var _cassNamesPrefix = 'os-'; var _classNameHTMLElement = _cassNamesPrefix + 'html'; var _classNameHostElement = _cassNamesPrefix + 'host'; var _classNameHostTextareaElement = _classNameHostElement + '-textarea'; var _classNameHostScrollbarHorizontalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusHorizontal + _strMinusHidden; var _classNameHostScrollbarVerticalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusVertical + _strMinusHidden; var _classNameHostTransition = _classNameHostElement + '-transition'; var _classNameHostRTL = _classNameHostElement + '-rtl'; var _classNameHostResizeDisabled = _classNameHostElement + '-resize-disabled'; var _classNameHostScrolling = _classNameHostElement + '-scrolling'; var _classNameHostOverflow = _classNameHostElement + '-overflow'; var _classNameHostOverflowX = _classNameHostOverflow + '-x'; var _classNameHostOverflowY = _classNameHostOverflow + '-y'; var _classNameTextareaElement = _cassNamesPrefix + 'textarea'; var _classNameTextareaCoverElement = _classNameTextareaElement + '-cover'; var _classNamePaddingElement = _cassNamesPrefix + 'padding'; var _classNameViewportElement = _cassNamesPrefix + 'viewport'; var _classNameViewportNativeScrollbarsInvisible = _classNameViewportElement + '-native-scrollbars-invisible'; var _classNameViewportNativeScrollbarsOverlaid = _classNameViewportElement + '-native-scrollbars-overlaid'; var _classNameContentElement = _cassNamesPrefix + 'content'; var _classNameContentArrangeElement = _cassNamesPrefix + 'content-arrange'; var _classNameContentGlueElement = _cassNamesPrefix + 'content-glue'; var _classNameSizeAutoObserverElement = _cassNamesPrefix + 'size-auto-observer'; var _classNameResizeObserverElement = _cassNamesPrefix + 'resize-observer'; var _classNameResizeObserverItemElement = _cassNamesPrefix + 'resize-observer-item'; var _classNameResizeObserverItemFinalElement = _classNameResizeObserverItemElement + '-final'; var _classNameTextInherit = _cassNamesPrefix + 'text-inherit'; var _classNameScrollbar = _cassNamesPrefix + _strScrollbar; var _classNameScrollbarTrack = _classNameScrollbar + '-track'; var _classNameScrollbarTrackOff = _classNameScrollbarTrack + '-off'; var _classNameScrollbarHandle = _classNameScrollbar + '-handle'; var _classNameScrollbarHandleOff = _classNameScrollbarHandle + '-off'; var _classNameScrollbarUnusable = _classNameScrollbar + '-unusable'; var _classNameScrollbarAutoHidden = _classNameScrollbar + '-' + _strAuto + _strMinusHidden; var _classNameScrollbarCorner = _classNameScrollbar + '-corner'; var _classNameScrollbarCornerResize = _classNameScrollbarCorner + '-resize'; var _classNameScrollbarCornerResizeB = _classNameScrollbarCornerResize + '-both'; var _classNameScrollbarCornerResizeH = _classNameScrollbarCornerResize + _strMinusHorizontal; var _classNameScrollbarCornerResizeV = _classNameScrollbarCornerResize + _strMinusVertical; var _classNameScrollbarHorizontal = _classNameScrollbar + _strMinusHorizontal; var _classNameScrollbarVertical = _classNameScrollbar + _strMinusVertical; var _classNameDragging = _cassNamesPrefix + 'dragging'; var _classNameThemeNone = _cassNamesPrefix + 'theme-none'; //callbacks: var _callbacksInitQeueue = [ ]; //options: var _defaultOptions; var _currentOptions; var _currentPreparedOptions; //extensions: var _extensions = { }; var _extensionsPrivateMethods = "added removed on contract"; //update var _lastUpdateTime; var _swallowedUpdateParams = { }; var _swallowedUpdateTimeout; var _swallowUpdateLag = 42; var _imgs = [ ]; //DOM elements: var _windowElement; var _documentElement; var _htmlElement; var _bodyElement; var _targetElement; //the target element of this OverlayScrollbars object var _hostElement; //the host element of this OverlayScrollbars object -> may be the same as targetElement var _sizeAutoObserverElement; //observes size auto changes var _sizeObserverElement; //observes size and padding changes var _paddingElement; //manages the padding var _viewportElement; //is the viewport of our scrollbar model var _contentElement; //the element which holds the content var _contentArrangeElement; //is needed for correct sizing of the content element (only if native scrollbars are overlays) var _contentGlueElement; //has always the size of the content element var _textareaCoverElement; //only applied if target is a textarea element. Used for correct size calculation and for prevention of uncontrolled scrolling var _scrollbarCornerElement; var _scrollbarHorizontalElement; var _scrollbarHorizontalTrackElement; var _scrollbarHorizontalHandleElement; var _scrollbarVerticalElement; var _scrollbarVerticalTrackElement; var _scrollbarVerticalHandleElement; var _windowElementNative; var _documentElementNative; var _targetElementNative; var _hostElementNative; var _sizeAutoObserverElementNative; var _sizeObserverElementNative; var _paddingElementNative; var _viewportElementNative; var _contentElementNative; //Cache: var _hostSizeCache; var _contentScrollSizeCache; var _arrangeContentSizeCache; var _hasOverflowCache; var _hideOverflowCache; var _widthAutoCache; var _heightAutoCache; var _cssMaxValueCache; var _cssBoxSizingCache; var _cssPaddingCache; var _cssBorderCache; var _cssMarginCache; var _cssDirectionCache; var _cssDirectionDetectedCache; var _paddingAbsoluteCache; var _clipAlwaysCache; var _contentGlueSizeCache; var _overflowBehaviorCache; var _overflowAmountCache; var _ignoreOverlayScrollbarHidingCache; var _autoUpdateCache; var _sizeAutoCapableCache; var _textareaAutoWrappingCache; var _textareaInfoCache; var _updateAutoHostElementIdCache; var _updateAutoHostElementClassCache; var _updateAutoHostElementStyleCache; var _updateAutoHostElementVisibleCache; var _updateAutoTargetElementRowsCache; var _updateAutoTargetElementColsCache; var _updateAutoTargetElementWrapCache; var _contentElementScrollSizeChangeDetectedCache; var _hostElementSizeChangeDetectedCache; var _scrollbarsVisibilityCache; var _scrollbarsAutoHideCache; var _scrollbarsClickScrollingCache; var _scrollbarsDragScrollingCache; var _resizeCache; var _normalizeRTLCache; var _classNameCache; var _oldClassName; var _textareaDynHeightCache; var _textareaDynWidthCache; var _bodyMinSizeCache; var _viewportScrollSizeCache; var _displayIsHiddenCache; //MutationObserver: var _mutationObserverHost; var _mutationObserverContent; var _mutationObserverHostCallback; var _mutationObserverContentCallback; var _mutationObserversConnected; //textarea: var _textareaEvents; var _textareaHasFocus; //scrollbars: var _scrollbarsAutoHideTimeoutId; var _scrollbarsAutoHideMoveTimeoutId; var _scrollbarsAutoHideDelay; var _scrollbarsAutoHideNever; var _scrollbarsAutoHideScroll; var _scrollbarsAutoHideMove; var _scrollbarsAutoHideLeave; var _scrollbarsHandleHovered; var _scrollbarsHandleAsync; //resize var _resizeReconnectMutationObserver; var _resizeNone; var _resizeBoth; var _resizeHorizontal; var _resizeVertical; var _resizeOnMouseTouchDown; //==== Passive Event Listener ====// /** * Adds a passive event listener to the given element. * @param element The element to which the event listener shall be applied. * @param eventNames The name(s) of the event listener. * @param listener The listener method which shall be called. */ function addPassiveEventListener(element, eventNames, listener) { var events = eventNames.split(_strSpace); for (var i = 0; i < events.length; i++) element[0].addEventListener(events[i], listener, {passive: true}); } /** * Removes a passive event listener to the given element. * @param element The element from which the event listener shall be removed. * @param eventNames The name(s) of the event listener. * @param listener The listener method which shall be removed. */ function removePassiveEventListener(element, eventNames, listener) { var events = eventNames.split(_strSpace); for (var i = 0; i < events.length; i++) element[0].removeEventListener(events[i], listener, {passive: true}); } //==== Resize Observer ====// /** * Adds a resize observer to the given element. * @param targetElement The element to which the resize observer shall be applied. * @param onElementResizedCallback The callback which is fired every time the resize observer registers a size change. */ function addResizeObserver(targetElement, onElementResizedCallback) { var constMaximum = 3333333; var resizeObserver = COMPATIBILITY.rO(); var strAnimationStartEvent = 'animationstart mozAnimationStart webkitAnimationStart MSAnimationStart'; var strChildNodes = 'childNodes'; var callback = function () { targetElement[_strScrollTop](constMaximum)[_strScrollLeft](_isRTL ? _rtlScrollBehavior.n ? -constMaximum : _rtlScrollBehavior.i ? 0 : constMaximum : constMaximum); onElementResizedCallback(); }; if (_supportResizeObserver) { var element = targetElement.append(generateDiv(_classNameResizeObserverElement + ' observed')).contents()[0]; var observer = element[_strResizeObserverProperty] = new resizeObserver(callback); observer.observe(element); } else { if (_msieVersion > 9 || !_autoUpdateRecommended) { targetElement.prepend( generateDiv(_classNameResizeObserverElement, generateDiv({ className : _classNameResizeObserverItemElement, dir : "ltr" }, generateDiv(_classNameResizeObserverItemElement, generateDiv(_classNameResizeObserverItemFinalElement) ) + generateDiv(_classNameResizeObserverItemElement, generateDiv({ className : _classNameResizeObserverItemFinalElement, style : 'width: 200%; height: 200%' }) ) ) ) ); var observerElement = targetElement[0][strChildNodes][0][strChildNodes][0]; var shrinkElement = FRAMEWORK(observerElement[strChildNodes][1]); var expandElement = FRAMEWORK(observerElement[strChildNodes][0]); var expandElementChild = FRAMEWORK(expandElement[0][strChildNodes][0]); var widthCache = observerElement[LEXICON.oW]; var heightCache = observerElement[LEXICON.oH]; var isDirty; var rAFId; var currWidth; var currHeight; var factor = 2; var nativeScrollbarSize = globals.nativeScrollbarSize; //care don't make changes to this object!!! var reset = function () { /* var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y; var sizeResetHeight = observerElement[LEXICON.oH] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y; var expandChildCSS = {}; expandChildCSS[_strWidth] = sizeResetWidth; expandChildCSS[_strHeight] = sizeResetHeight; expandElementChild.css(expandChildCSS); expandElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight); shrinkElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight); */ expandElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum); shrinkElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum); }; var onResized = function () { rAFId = 0; if (!isDirty) return; widthCache = currWidth; heightCache = currHeight; callback(); }; var onScroll = function (event) { currWidth = observerElement[LEXICON.oW]; currHeight = observerElement[LEXICON.oH]; isDirty = currWidth != widthCache || currHeight != heightCache; if (event && isDirty && !rAFId) { COMPATIBILITY.cAF()(rAFId); rAFId = COMPATIBILITY.rAF()(onResized); } else if(!event) onResized(); reset(); if (event) { COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } return false; }; var expandChildCSS = {}; var observerElementCSS = {}; setTopRightBottomLeft(observerElementCSS, _strEmpty, [ -((nativeScrollbarSize.y + 1) * factor), nativeScrollbarSize.x * -factor, nativeScrollbarSize.y * -factor, -((nativeScrollbarSize.x + 1) * factor) ]); FRAMEWORK(observerElement).css(observerElementCSS); expandElement.on(_strScroll, onScroll); shrinkElement.on(_strScroll, onScroll); targetElement.on(strAnimationStartEvent, function () { onScroll(false); }); //lets assume that the divs will never be that large and a constant value is enough expandChildCSS[_strWidth] = constMaximum; expandChildCSS[_strHeight] = constMaximum; expandElementChild.css(expandChildCSS); reset(); } else { var attachEvent = _documentElementNative.attachEvent; var isIE = _msieVersion !== undefined; if (attachEvent) { targetElement.prepend(generateDiv(_classNameResizeObserverElement)); findFirst(targetElement, _strDot + _classNameResizeObserverElement)[0].attachEvent('onresize', callback); } else { var obj = _documentElementNative.createElement(TYPES.o); obj.setAttribute('tabindex', '-1'); obj.setAttribute(LEXICON.c, _classNameResizeObserverElement); obj.onload = function () { var wnd = this.contentDocument.defaultView; wnd.addEventListener('resize', callback); wnd.document.documentElement.style.display = 'none'; }; obj.type = 'text/html'; if (isIE) targetElement.prepend(obj); obj.data = 'about:blank'; if (!isIE) targetElement.prepend(obj); targetElement.on(strAnimationStartEvent, callback); } } } //direction change detection: if (targetElement[0] === _sizeObserverElementNative) { var directionChanged = function () { var dir = _hostElement.css('direction'); var css = {}; var scrollLeftValue = 0; var result = false; if (dir !== _cssDirectionDetectedCache) { if (dir === 'ltr') { css[_strLeft] = 0; css[_strRight] = _strAuto; scrollLeftValue = constMaximum; } else { css[_strLeft] = _strAuto; css[_strRight] = 0; scrollLeftValue = _rtlScrollBehavior.n ? -constMaximum : _rtlScrollBehavior.i ? 0 : constMaximum; } _sizeObserverElement.children().eq(0).css(css); targetElement[_strScrollLeft](scrollLeftValue)[_strScrollTop](constMaximum); _cssDirectionDetectedCache = dir; result = true; } return result; }; directionChanged(); targetElement.on(_strScroll, function (event) { if (directionChanged()) update(); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); return false; }); } } /** * Removes a resize observer from the given element. * @param targetElement The element to which the target resize observer is applied. */ function removeResizeObserver(targetElement) { if (_supportResizeObserver) { var element = targetElement.contents()[0]; element[_strResizeObserverProperty].disconnect(); delete element[_strResizeObserverProperty]; } else { remove(targetElement.children(_strDot + _classNameResizeObserverElement).eq(0)); } } /** * Freezes the given resize observer. * @param targetElement The element to which the target resize observer is applied. */ function freezeResizeObserver(targetElement) { if (targetElement !== undefined) { /* if (_supportResizeObserver) { var element = targetElement.contents()[0]; element[_strResizeObserverProperty].unobserve(element); } else { targetElement = targetElement.children(_strDot + _classNameResizeObserverElement).eq(0); var w = targetElement.css(_strWidth); var h = targetElement.css(_strHeight); var css = {}; css[_strWidth] = w; css[_strHeight] = h; targetElement.css(css); } */ } } /** * Unfreezes the given resize observer. * @param targetElement The element to which the target resize observer is applied. */ function unfreezeResizeObserver(targetElement) { if (targetElement !== undefined) { /* if (_supportResizeObserver) { var element = targetElement.contents()[0]; element[_strResizeObserverProperty].observe(element); } else { var css = { }; css[_strHeight] = _strEmpty; css[_strWidth] = _strEmpty; targetElement.children(_strDot + _classNameResizeObserverElement).eq(0).css(css); } */ } } //==== Mutation Observers ====// /** * Creates MutationObservers for the host and content Element if they are supported. */ function createMutationObservers() { if (_supportMutationObserver) { var mutationObserverContentLag = 11; var mutationObserver = COMPATIBILITY.mO(); var contentLastUpdate = COMPATIBILITY.now(); var mutationTarget; var mutationAttrName; var contentTimeout; var now; var sizeAuto; var action; _mutationObserverHostCallback = function(mutations) { var doUpdate = false; var mutation; if (_initialized && !_isSleeping) { FRAMEWORK.each(mutations, function () { mutation = this; mutationTarget = mutation.target; mutationAttrName = mutation.attributeName; if (mutationAttrName === LEXICON.c) doUpdate = hostClassNamesChanged(mutation.oldValue, mutationTarget.className); else if (mutationAttrName === LEXICON.s) doUpdate = mutation.oldValue !== mutationTarget[LEXICON.s].cssText; else doUpdate = true; if (doUpdate) return false; }); if (doUpdate) _base.update(_strAuto); } return doUpdate; }; _mutationObserverContentCallback = function (mutations) { var doUpdate = false; var mutation; if (_initialized && !_isSleeping) { FRAMEWORK.each(mutations, function () { mutation = this; doUpdate = isUnknownMutation(mutation); return !doUpdate; }); if (doUpdate) { now = COMPATIBILITY.now(); sizeAuto = (_heightAutoCache || _widthAutoCache); action = function () { if(!_destroyed) { contentLastUpdate = now; //if cols, rows or wrap attr was changed if (_isTextarea) textareaUpdate(); if (sizeAuto) update(); else _base.update(_strAuto); } }; clearTimeout(contentTimeout); if (mutationObserverContentLag <= 0 || now - contentLastUpdate > mutationObserverContentLag || !sizeAuto) action(); else contentTimeout = setTimeout(action, mutationObserverContentLag); } } return doUpdate; } _mutationObserverHost = new mutationObserver(_mutationObserverHostCallback); _mutationObserverContent = new mutationObserver(_mutationObserverContentCallback); } } /** * Connects the MutationObservers if they are supported. */ function connectMutationObservers() { if (_supportMutationObserver && !_mutationObserversConnected) { _mutationObserverHost.observe(_hostElementNative, { attributes: true, attributeOldValue: true, attributeFilter: [LEXICON.i, LEXICON.c, LEXICON.s] }); _mutationObserverContent.observe(_isTextarea ? _targetElementNative : _contentElementNative, { attributes: true, attributeOldValue: true, subtree: !_isTextarea, childList: !_isTextarea, characterData: !_isTextarea, attributeFilter: _isTextarea ? ['wrap', 'cols', 'rows'] : [LEXICON.i, LEXICON.c, LEXICON.s, 'open'] }); _mutationObserversConnected = true; } } /** * Disconnects the MutationObservers if they are supported. */ function disconnectMutationObservers() { if (_supportMutationObserver && _mutationObserversConnected) { _mutationObserverHost.disconnect(); _mutationObserverContent.disconnect(); _mutationObserversConnected = false; } } /** * Disconnects the MutationObservers if they are supported. * @returns {boolean|undefined} True if the MutationObservers needed to be synchronized, false or undefined otherwise. */ function synchronizeMutationObservers() { if(_mutationObserversConnected) { var mutHost = _mutationObserverHostCallback(_mutationObserverHost.takeRecords()); var mutContent = _mutationObserverContentCallback(_mutationObserverContent.takeRecords()); return mutHost || mutContent; } } //==== Events of elements ====// /** * This method gets called every time the host element gets resized. IMPORTANT: Padding changes are detected too!! * It refreshes the hostResizedEventArgs and the hostSizeResizeCache. * If there are any size changes, the update method gets called. */ function hostOnResized() { if (_isSleeping) return; var changed; var hostSize = { w: _sizeObserverElementNative[LEXICON.sW], h: _sizeObserverElementNative[LEXICON.sH] }; if (_initialized) { changed = checkCacheDouble(hostSize, _hostElementSizeChangeDetectedCache); _hostElementSizeChangeDetectedCache = hostSize; if (changed) update(true, false); } else { _hostElementSizeChangeDetectedCache = hostSize; } } /** * The mouse enter event of the host element. This event is only needed for the autoHide feature. */ function hostOnMouseEnter() { if (_scrollbarsAutoHideLeave) refreshScrollbarsAutoHide(true); } /** * The mouse leave event of the host element. This event is only needed for the autoHide feature. */ function hostOnMouseLeave() { if (_scrollbarsAutoHideLeave && !_bodyElement.hasClass(_classNameDragging)) refreshScrollbarsAutoHide(false); } /** * The mouse move event of the host element. This event is only needed for the autoHide "move" feature. */ function hostOnMouseMove() { if (_scrollbarsAutoHideMove) { refreshScrollbarsAutoHide(true); clearTimeout(_scrollbarsAutoHideMoveTimeoutId); _scrollbarsAutoHideMoveTimeoutId = setTimeout(function () { if (_scrollbarsAutoHideMove && !_destroyed) refreshScrollbarsAutoHide(false); }, 100); } } /** * Adds or removes mouse & touch events of the host element. (for handling auto-hiding of the scrollbars) * @param destroy Indicates whether the events shall be added or removed. */ function setupHostMouseTouchEvents(destroy) { var passiveEvent = destroy ? removePassiveEventListener : addPassiveEventListener; var strOnOff = destroy ? 'off' : 'on'; var setupEvent = function(target, name, listener) { if(_supportPassiveEvents) passiveEvent(target, name, listener); else target[strOnOff](name, listener); }; if(_scrollbarsAutoHideMove && !destroy) setupEvent(_hostElement, _strMouseTouchMoveEvent, hostOnMouseMove); else { if(destroy) setupEvent(_hostElement, _strMouseTouchMoveEvent, hostOnMouseMove); setupEvent(_hostElement, _strMouseTouchEnter, hostOnMouseEnter); setupEvent(_hostElement, _strMouseTouchLeave, hostOnMouseLeave); } //if the plugin is initialized and the mouse is over the host element, make the scrollbars visible if(!_initialized && !destroy) _hostElement.one("mouseover", hostOnMouseEnter); } /** * Prevents text from deselection if attached to the document element on the mousedown event of a DOM element. * @param event The select start event. */ function documentOnSelectStart(event) { COMPATIBILITY.prvD(event); return false; } /** * A callback which will be called after a img element has downloaded its src asynchronous. */ function imgOnLoad() { update(false, true); } //==== Update Detection ====// /** * Measures the min width and min height of the body element and refreshes the related cache. * @returns {boolean} True if the min width or min height has changed, false otherwise. */ function bodyMinSizeChanged() { var bodyMinSize = {}; if (_isBody && _contentArrangeElement) { bodyMinSize.w = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strWidth)); bodyMinSize.h = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strHeight)); bodyMinSize.c = checkCacheDouble(bodyMinSize, _bodyMinSizeCache); bodyMinSize.f = true; //flag for "measured at least once" } _bodyMinSizeCache = bodyMinSize; return bodyMinSize.c || false; } /** * Returns true if the class names really changed (new class without plugin host prefix) * @param oldCassNames The old ClassName string. * @param newClassNames The new ClassName string. * @returns {boolean} True if the class names has really changed, false otherwise. */ function hostClassNamesChanged(oldCassNames, newClassNames) { var currClasses = (newClassNames !== undefined && newClassNames !== null) ? newClassNames.split(_strSpace) : _strEmpty; var oldClasses = (oldCassNames !== undefined && oldCassNames !== null) ? oldCassNames.split(_strSpace) : _strEmpty; if (currClasses === _strEmpty && oldClasses === _strEmpty) return false; var diff = getArrayDifferences(oldClasses, currClasses); var changed = false; var oldClassNames = _oldClassName !== undefined && _oldClassName !== null ? _oldClassName.split(_strSpace) : [_strEmpty]; var currClassNames = _classNameCache !== undefined && _classNameCache !== null ? _classNameCache.split(_strSpace) : [_strEmpty]; //remove none theme from diff list to prevent update var idx = FRAMEWORK.inArray(_classNameThemeNone, diff); var curr; var i; var v; var o; var c; if (idx > -1) diff.splice(idx, 1); for (i = 0; i < diff.length; i++) { curr = diff[i]; if (curr.indexOf(_classNameHostElement) !== 0) { o = true; c = true; for (v = 0; v < oldClassNames.length; v++) { if (curr === oldClassNames[v]) { o = false; break; } } for (v = 0; v < currClassNames.length; v++) { if (curr === currClassNames[v]) { c = false; break; } } if (o && c) { changed = true; break; } } } return changed; } /** * Returns true if the given mutation is not from a from the plugin generated element. If the target element is a textarea the mutation is always unknown. * @param mutation The mutation which shall be checked. * @returns {boolean} True if the mutation is from a unknown element, false otherwise. */ function isUnknownMutation(mutation) { var attributeName = mutation.attributeName; var mutationTarget = mutation.target; var mutationType = mutation.type; var strClosest = 'closest'; if (mutationTarget === _contentElementNative) return attributeName === null; if (mutationType === 'attributes' && (attributeName === LEXICON.c || attributeName === LEXICON.s) && !_isTextarea) { //ignore className changes by the plugin if (attributeName === LEXICON.c && FRAMEWORK(mutationTarget).hasClass(_classNameHostElement)) return hostClassNamesChanged(mutation.oldValue, mutationTarget.getAttribute(LEXICON.c)); //only do it of browser support it natively if (typeof mutationTarget[strClosest] != TYPES.f) return true; if (mutationTarget[strClosest](_strDot + _classNameResizeObserverElement) !== null || mutationTarget[strClosest](_strDot + _classNameScrollbar) !== null || mutationTarget[strClosest](_strDot + _classNameScrollbarCorner) !== null) return false; } return true; } /** * Returns true if the content size was changed since the last time this method was called. * @returns {boolean} True if the content size was changed, false otherwise. */ function updateAutoContentSizeChanged() { if (_isSleeping) return false; var float; var textareaValueLength = _isTextarea && _widthAutoCache && !_textareaAutoWrappingCache ? _targetElement.val().length : 0; var setCSS = !_mutationObserversConnected && _widthAutoCache && !_isTextarea; var viewportScrollSize = { }; var css = { }; var bodyMinSizeC; var changed; var viewportScrollSizeChanged; //fix for https://bugzilla.mozilla.org/show_bug.cgi?id=1439305, it only works with "clipAlways : true" //it can work with "clipAlways : false" too, but we had to set the overflow of the viewportElement to hidden every time before measuring if(_restrictedMeasuring) { viewportScrollSize = { x : _viewportElementNative[LEXICON.sW], y : _viewportElementNative[LEXICON.sH] } } if (setCSS) { float = _contentElement.css(_strFloat); css[_strFloat] = _isRTL ? _strRight : _strLeft; css[_strWidth] = _strAuto; _contentElement.css(css); } var contentElementScrollSize = { w: getContentMeasureElement()[LEXICON.sW] + textareaValueLength, h: getContentMeasureElement()[LEXICON.sH] + textareaValueLength }; if (setCSS) { css[_strFloat] = float; css[_strWidth] = _strHundredPercent; _contentElement.css(css); } bodyMinSizeC = bodyMinSizeChanged(); changed = checkCacheDouble(contentElementScrollSize, _contentElementScrollSizeChangeDetectedCache); viewportScrollSizeChanged = checkCacheDouble(viewportScrollSize, _viewportScrollSizeCache, _strX, _strY); _contentElementScrollSizeChangeDetectedCache = contentElementScrollSize; _viewportScrollSizeCache = viewportScrollSize; return changed || bodyMinSizeC || viewportScrollSizeChanged; } /** * Returns true if the host element attributes (id, class, style) was changed since the last time this method was called. * @returns {boolean} */ function meaningfulAttrsChanged() { if (_isSleeping || _mutationObserversConnected) return false; var hostElementId = _hostElement.attr(LEXICON.i) || _strEmpty; var hostElementIdChanged = checkCacheSingle(hostElementId, _updateAutoHostElementIdCache); var hostElementClass = _hostElement.attr(LEXICON.c) || _strEmpty; var hostElementClassChanged = checkCacheSingle(hostElementClass, _updateAutoHostElementClassCache); var hostElementStyle = _hostElement.attr(LEXICON.s) || _strEmpty; var hostElementStyleChanged = checkCacheSingle(hostElementStyle, _updateAutoHostElementStyleCache); var hostElementVisible = _hostElement.is(':visible') || _strEmpty; var hostElementVisibleChanged = checkCacheSingle(hostElementVisible, _updateAutoHostElementVisibleCache); var targetElementRows = _isTextarea ? (_targetElement.attr('rows') || _strEmpty) : _strEmpty; var targetElementRowsChanged = checkCacheSingle(targetElementRows, _updateAutoTargetElementRowsCache); var targetElementCols = _isTextarea ? (_targetElement.attr('cols') || _strEmpty) : _strEmpty; var targetElementColsChanged = checkCacheSingle(targetElementCols, _updateAutoTargetElementColsCache); var targetElementWrap = _isTextarea ? (_targetElement.attr('wrap') || _strEmpty) : _strEmpty; var targetElementWrapChanged = checkCacheSingle(targetElementWrap, _updateAutoTargetElementWrapCache); _updateAutoHostElementIdCache = hostElementId; if (hostElementClassChanged) hostElementClassChanged = hostClassNamesChanged(_updateAutoHostElementClassCache, hostElementClass); _updateAutoHostElementClassCache = hostElementClass; _updateAutoHostElementStyleCache = hostElementStyle; _updateAutoHostElementVisibleCache = hostElementVisible; _updateAutoTargetElementRowsCache = targetElementRows; _updateAutoTargetElementColsCache = targetElementCols; _updateAutoTargetElementWrapCache = targetElementWrap; return hostElementIdChanged || hostElementClassChanged || hostElementStyleChanged || hostElementVisibleChanged || targetElementRowsChanged || targetElementColsChanged || targetElementWrapChanged; } /** * Checks is a CSS Property of a child element is affecting the scroll size of the content. * @param propertyName The CSS property name. * @returns {boolean} True if the property is affecting the content scroll size, false otherwise. */ function isSizeAffectingCSSProperty(propertyName) { if (!_initialized) return true; var flexGrow = 'flex-grow'; var flexShrink = 'flex-shrink'; var flexBasis = 'flex-basis'; var affectingPropsX = [ _strWidth, _strMinMinus + _strWidth, _strMaxMinus + _strWidth, _strMarginMinus + _strLeft, _strMarginMinus + _strRight, _strLeft, _strRight, 'font-weight', 'word-spacing', flexGrow, flexShrink, flexBasis ]; var affectingPropsXContentBox = [ _strPaddingMinus + _strLeft, _strPaddingMinus + _strRight, _strBorderMinus + _strLeft + _strWidth, _strBorderMinus + _strRight + _strWidth ]; var affectingPropsY = [ _strHeight, _strMinMinus + _strHeight, _strMaxMinus + _strHeight, _strMarginMinus + _strTop, _strMarginMinus + _strBottom, _strTop, _strBottom, 'line-height', flexGrow, flexShrink, flexBasis ]; var affectingPropsYContentBox = [ _strPaddingMinus + _strTop, _strPaddingMinus + _strBottom, _strBorderMinus + _strTop + _strWidth, _strBorderMinus + _strBottom + _strWidth ]; var _strS = 's'; var _strVS = 'v-s'; var checkX = _overflowBehaviorCache.x === _strS || _overflowBehaviorCache.x === _strVS; var checkY = _overflowBehaviorCache.y === _strS || _overflowBehaviorCache.y === _strVS; var sizeIsAffected = false; var checkPropertyName = function (arr, name) { for (var i = 0; i < arr[LEXICON.l]; i++) { if (arr[i] === name) return true; } return false; }; if (checkY) { sizeIsAffected = checkPropertyName(affectingPropsY, propertyName); if (!sizeIsAffected && !_isBorderBox) sizeIsAffected = checkPropertyName(affectingPropsYContentBox, propertyName); } if (checkX && !sizeIsAffected) { sizeIsAffected = checkPropertyName(affectingPropsX, propertyName); if (!sizeIsAffected && !_isBorderBox) sizeIsAffected = checkPropertyName(affectingPropsXContentBox, propertyName); } return sizeIsAffected; } //==== Update ====// /** * Updates the variables and size of the textarea element, and manages the scroll on new line or new character. */ function textareaUpdate() { if (_isSleeping) return; var wrapAttrOff = !_textareaAutoWrappingCache; var minWidth = _viewportSize.w /* - (!_isBorderBox && !_paddingAbsoluteCache && _widthAutoCache ? _paddingY + _borderY : 0) */; var minHeight = _viewportSize.h /* - (!_isBorderBox && !_paddingAbsoluteCache && _heightAutoCache ? _paddingY + _borderY : 0) */; var css = { }; var doMeasure = _widthAutoCache || wrapAttrOff; var origWidth; var width; var origHeight; var height; //reset min size css[_strMinMinus + _strWidth] = _strEmpty; css[_strMinMinus + _strHeight] = _strEmpty; //set width auto css[_strWidth] = _strAuto; _targetElement.css(css); //measure width origWidth = _targetElementNative[LEXICON.oW]; width = doMeasure ? MATH.max(origWidth, _targetElementNative[LEXICON.sW] - 1) : 1; /*width += (_widthAutoCache ? _marginX + (!_isBorderBox ? wrapAttrOff ? 0 : _paddingX + _borderX : 0) : 0);*/ //set measured width css[_strWidth] = _widthAutoCache ? _strAuto /*width*/ : _strHundredPercent; css[_strMinMinus + _strWidth] = _strHundredPercent; //set height auto css[_strHeight] = _strAuto; _targetElement.css(css); //measure height origHeight = _targetElementNative[LEXICON.oH]; height = MATH.max(origHeight, _targetElementNative[LEXICON.sH] - 1); //append correct size values css[_strWidth] = width; css[_strHeight] = height; _textareaCoverElement.css(css); //apply min width / min height to prevent textarea collapsing css[_strMinMinus + _strWidth] = minWidth /*+ (!_isBorderBox && _widthAutoCache ? _paddingX + _borderX : 0)*/; css[_strMinMinus + _strHeight] = minHeight /*+ (!_isBorderBox && _heightAutoCache ? _paddingY + _borderY : 0)*/; _targetElement.css(css); return { _originalWidth: origWidth, _originalHeight: origHeight, _dynamicWidth: width, _dynamicHeight: height }; } /** * Updates the plugin and DOM to the current options. * This method should only be called if a update is 100% required. * @param hostSizeChanged True if this method was called due to a host size change. * @param contentSizeChanged True if this method was called due to a content size change. * @param force True if every property shall be updated and the cache shall be ignored. * @param preventSwallowing True if this method shall be executed even if it could be swallowed. */ function update(hostSizeChanged, contentSizeChanged, force, preventSwallowing) { var now = COMPATIBILITY.now(); var swallow = _swallowUpdateLag > 0 && _initialized && (now - _lastUpdateTime) < _swallowUpdateLag && (!_heightAutoCache && !_widthAutoCache) && !preventSwallowing; var displayIsHidden = _hostElement.is(':hidden'); var displayIsHiddenChanged = checkCacheSingle(displayIsHidden, _displayIsHiddenCache, force); _displayIsHiddenCache = displayIsHidden; clearTimeout(_swallowedUpdateTimeout); if (swallow) { _swallowedUpdateParams.h = _swallowedUpdateParams.h || hostSizeChanged; _swallowedUpdateParams.c = _swallowedUpdateParams.c || contentSizeChanged; _swallowedUpdateParams.f = _swallowedUpdateParams.f || force; _swallowedUpdateTimeout = setTimeout(update, _swallowUpdateLag); } //abort update due to: //destroyed //swallowing //sleeping //host is hidden or has false display if (_destroyed || swallow || _isSleeping || (_initialized && !force && displayIsHidden) || _hostElement.css('display') === 'inline') return; _lastUpdateTime = now; hostSizeChanged = hostSizeChanged || _swallowedUpdateParams.h; contentSizeChanged = contentSizeChanged || _swallowedUpdateParams.c; force = force || _swallowedUpdateParams.f; _swallowedUpdateParams = {}; hostSizeChanged = hostSizeChanged === undefined ? false : hostSizeChanged; contentSizeChanged = contentSizeChanged === undefined ? false : contentSizeChanged; force = force === undefined ? false : force; //if scrollbar styling is possible and native scrollbars aren't overlaid the scrollbar styling will be applied which hides the native scrollbars completely. if (_nativeScrollbarStyling && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) { //native scrollbars are hidden, so change the values to zero _nativeScrollbarSize.x = 0; _nativeScrollbarSize.y = 0; } else { //refresh native scrollbar size (in case of zoom) _nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize); } // Scrollbar padding is needed for firefox, because firefox hides scrollbar automatically if the size of the div is too small. // The calculation: [scrollbar size +3 *3] // (+3 because of possible decoration e.g. borders, margins etc., but only if native scrollbar is NOT a overlaid scrollbar) // (*3 because (1)increase / (2)decrease -button and (3)resize handle) _nativeScrollbarMinSize = { x: (_nativeScrollbarSize.x + (_nativeScrollbarIsOverlaid.x ? 0 : 3)) * 3, y: (_nativeScrollbarSize.y + (_nativeScrollbarIsOverlaid.y ? 0 : 3)) * 3 }; freezeResizeObserver(_sizeObserverElement); freezeResizeObserver(_sizeAutoObserverElement); //save current scroll offset var currScroll = { x: _viewportElement[_strScrollLeft](), y: _viewportElement[_strScrollTop]() }; var currentPreparedOptionsScrollbars = _currentPreparedOptions.scrollbars; var currentPreparedOptionsTextarea = _currentPreparedOptions.textarea; //scrollbars visibility: var scrollbarsVisibility = currentPreparedOptionsScrollbars.visibility; var scrollbarsVisibilityChanged = checkCacheSingle(scrollbarsVisibility, _scrollbarsVisibilityCache, force); //scrollbars autoHide: var scrollbarsAutoHide = currentPreparedOptionsScrollbars.autoHide; var scrollbarsAutoHideChanged = checkCacheSingle(scrollbarsAutoHide, _scrollbarsAutoHideCache, force); //scrollbars click scrolling var scrollbarsClickScrolling = currentPreparedOptionsScrollbars.clickScrolling; var scrollbarsClickScrollingChanged = checkCacheSingle(scrollbarsClickScrolling, _scrollbarsClickScrollingCache, force); //scrollbars drag scrolling var scrollbarsDragScrolling = currentPreparedOptionsScrollbars.dragScrolling; var scrollbarsDragScrollingChanged = checkCacheSingle(scrollbarsDragScrolling, _scrollbarsDragScrollingCache, force); //className var className = _currentPreparedOptions.className; var classNameChanged = checkCacheSingle(className, _classNameCache, force); //resize var resize = _currentPreparedOptions.resize; var resizeChanged = checkCacheSingle(resize, _resizeCache, force) && !_isBody; //body can't be resized since the window itself acts as resize possibility. //textarea AutoWrapping var textareaAutoWrapping = _isTextarea ? _targetElement.attr('wrap') !== 'off' : false; var textareaAutoWrappingChanged = checkCacheSingle(textareaAutoWrapping, _textareaAutoWrappingCache, force); //paddingAbsolute var paddingAbsolute = _currentPreparedOptions.paddingAbsolute; var paddingAbsoluteChanged = checkCacheSingle(paddingAbsolute, _paddingAbsoluteCache, force); //clipAlways var clipAlways = _currentPreparedOptions.clipAlways; var clipAlwaysChanged = checkCacheSingle(clipAlways, _clipAlwaysCache, force); //sizeAutoCapable var sizeAutoCapable = _currentPreparedOptions.sizeAutoCapable && !_isBody; //body can never be size auto, because it shall be always as big as the viewport. var sizeAutoCapableChanged = checkCacheSingle(sizeAutoCapable, _sizeAutoCapableCache, force); //showNativeScrollbars var ignoreOverlayScrollbarHiding = _currentPreparedOptions.nativeScrollbarsOverlaid.showNativeScrollbars; var ignoreOverlayScrollbarHidingChanged = checkCacheSingle(ignoreOverlayScrollbarHiding, _ignoreOverlayScrollbarHidingCache); //autoUpdate var autoUpdate = _currentPreparedOptions.autoUpdate; var autoUpdateChanged = checkCacheSingle(autoUpdate, _autoUpdateCache); //overflowBehavior var overflowBehavior = _currentPreparedOptions.overflowBehavior; var overflowBehaviorChanged = checkCacheDouble(overflowBehavior, _overflowBehaviorCache, _strX, _strY, force); //dynWidth: var textareaDynWidth = currentPreparedOptionsTextarea.dynWidth; var textareaDynWidthChanged = checkCacheSingle(_textareaDynWidthCache, textareaDynWidth); //dynHeight: var textareaDynHeight = currentPreparedOptionsTextarea.dynHeight; var textareaDynHeightChanged = checkCacheSingle(_textareaDynHeightCache, textareaDynHeight); //scrollbars visibility _scrollbarsAutoHideNever = scrollbarsAutoHide === 'n'; _scrollbarsAutoHideScroll = scrollbarsAutoHide === 's'; _scrollbarsAutoHideMove = scrollbarsAutoHide === 'm'; _scrollbarsAutoHideLeave = scrollbarsAutoHide === 'l'; //scrollbars autoHideDelay _scrollbarsAutoHideDelay = currentPreparedOptionsScrollbars.autoHideDelay; //old className _oldClassName = _classNameCache; //resize _resizeNone = resize === 'n'; _resizeBoth = resize === 'b'; _resizeHorizontal = resize === 'h'; _resizeVertical = resize === 'v'; //normalizeRTL _normalizeRTLCache = _currentPreparedOptions.normalizeRTL; //ignore overlay scrollbar hiding ignoreOverlayScrollbarHiding = ignoreOverlayScrollbarHiding && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y); //refresh options cache _scrollbarsVisibilityCache = scrollbarsVisibility; _scrollbarsAutoHideCache = scrollbarsAutoHide; _scrollbarsClickScrollingCache = scrollbarsClickScrolling; _scrollbarsDragScrollingCache = scrollbarsDragScrolling; _classNameCache = className; _resizeCache = resize; _textareaAutoWrappingCache = textareaAutoWrapping; _paddingAbsoluteCache = paddingAbsolute; _clipAlwaysCache = clipAlways; _sizeAutoCapableCache = sizeAutoCapable; _ignoreOverlayScrollbarHidingCache = ignoreOverlayScrollbarHiding; _autoUpdateCache = autoUpdate; _overflowBehaviorCache = extendDeep({}, overflowBehavior); _textareaDynWidthCache = textareaDynWidth; _textareaDynHeightCache = textareaDynHeight; _hasOverflowCache = _hasOverflowCache || { x: false, y: false }; //set correct class name to the host element if (classNameChanged) { removeClass(_hostElement, _oldClassName + _strSpace + _classNameThemeNone); addClass(_hostElement, className !== undefined && className !== null && className.length > 0 ? className : _classNameThemeNone); } //set correct auto Update if (autoUpdateChanged) { if (autoUpdate === true) { disconnectMutationObservers(); autoUpdateLoop.add(_base); } else if (autoUpdate === null) { if (_autoUpdateRecommended) { disconnectMutationObservers(); autoUpdateLoop.add(_base); } else { autoUpdateLoop.remove(_base); connectMutationObservers(); } } else { autoUpdateLoop.remove(_base); connectMutationObservers(); } } //activate or deactivate size auto capability if (sizeAutoCapableChanged) { if (sizeAutoCapable) { if (!_contentGlueElement) { _contentGlueElement = FRAMEWORK(generateDiv(_classNameContentGlueElement)); _paddingElement.before(_contentGlueElement); } else { _contentGlueElement.show(); } if (_sizeAutoObserverAdded) { _sizeAutoObserverElement.show(); } else { _sizeAutoObserverElement = FRAMEWORK(generateDiv(_classNameSizeAutoObserverElement)); _sizeAutoObserverElementNative = _sizeAutoObserverElement[0]; _contentGlueElement.before(_sizeAutoObserverElement); var oldSize = {w: -1, h: -1}; addResizeObserver(_sizeAutoObserverElement, function () { var newSize = { w: _sizeAutoObserverElementNative[LEXICON.oW], h: _sizeAutoObserverElementNative[LEXICON.oH] }; if (checkCacheDouble(newSize, oldSize)) { if (_initialized && (_heightAutoCache && newSize.h > 0) || (_widthAutoCache && newSize.w > 0)) { update(); } else if (_initialized && (!_heightAutoCache && newSize.h === 0) || (!_widthAutoCache && newSize.w === 0)) { update(); } } oldSize = newSize; }); _sizeAutoObserverAdded = true; //fix heightAuto detector bug if height is fixed but contentHeight is 0. //the probability this bug will ever happen is very very low, thats why its ok if we use calc which isn't supported in IE8. if (_cssCalc !== null) _sizeAutoObserverElement.css(_strHeight, _cssCalc + '(100% + 1px)'); } } else { if (_sizeAutoObserverAdded) _sizeAutoObserverElement.hide(); if (_contentGlueElement) _contentGlueElement.hide(); } } //if force, update all resizeObservers too if (force) { _sizeObserverElement.find('*').trigger(_strScroll); if (_sizeAutoObserverAdded) _sizeAutoObserverElement.find('*').trigger(_strScroll); } //detect direction: var cssDirection = _hostElement.css('direction'); var cssDirectionChanged = checkCacheSingle(cssDirection, _cssDirectionCache, force); //detect box-sizing: var boxSizing = _hostElement.css('box-sizing'); var boxSizingChanged = checkCacheSingle(boxSizing, _cssBoxSizingCache, force); //detect padding: var padding = { c: force, t: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strTop)), r: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strRight)), b: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strBottom)), l: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strLeft)) }; //width + height auto detecting var: var sizeAutoObserverElementBCRect; //exception occurs in IE8 sometimes (unknown exception) try { sizeAutoObserverElementBCRect = _sizeAutoObserverAdded ? _sizeAutoObserverElementNative.getBoundingClientRect() : null; } catch (ex) { return; } _isRTL = cssDirection === 'rtl'; _isBorderBox = (boxSizing === 'border-box'); var isRTLLeft = _isRTL ? _strLeft : _strRight; var isRTLRight = _isRTL ? _strRight : _strLeft; //detect width auto: var widthAutoResizeDetection = false; var widthAutoObserverDetection = (_sizeAutoObserverAdded && (_hostElement.css(_strFloat) !== 'none' /*|| _isTextarea */)) ? (MATH.round(sizeAutoObserverElementBCRect.right - sizeAutoObserverElementBCRect.left) === 0) && (!paddingAbsolute ? (_hostElementNative[LEXICON.cW] - _paddingX) > 0 : true) : false; if (sizeAutoCapable && !widthAutoObserverDetection) { var tmpCurrHostWidth = _hostElementNative[LEXICON.oW]; var tmpCurrContentGlueWidth = _contentGlueElement.css(_strWidth); _contentGlueElement.css(_strWidth, _strAuto); var tmpNewHostWidth = _hostElementNative[LEXICON.oW]; _contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth); widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth; if (!widthAutoResizeDetection) { _contentGlueElement.css(_strWidth, tmpCurrHostWidth + 1); tmpNewHostWidth = _hostElementNative[LEXICON.oW]; _contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth); widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth; } } var widthAuto = (widthAutoObserverDetection || widthAutoResizeDetection) && sizeAutoCapable && !displayIsHidden; var widthAutoChanged = checkCacheSingle(widthAuto, _widthAutoCache, force); var wasWidthAuto = !widthAuto && _widthAutoCache; //detect height auto: var heightAuto = _sizeAutoObserverAdded && sizeAutoCapable && !displayIsHidden ? (MATH.round(sizeAutoObserverElementBCRect.bottom - sizeAutoObserverElementBCRect.top) === 0) /* && (!paddingAbsolute && (_msieVersion > 9 || !_msieVersion) ? true : true) */ : false; var heightAutoChanged = checkCacheSingle(heightAuto, _heightAutoCache, force); var wasHeightAuto = !heightAuto && _heightAutoCache; //detect border: //we need the border only if border box and auto size var strMinusWidth = '-' + _strWidth; var updateBorderX = (widthAuto && _isBorderBox) || !_isBorderBox; var updateBorderY = (heightAuto && _isBorderBox) || !_isBorderBox; var border = { c: force, t: updateBorderY ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strTop + strMinusWidth), true) : 0, r: updateBorderX ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strRight + strMinusWidth), true) : 0, b: updateBorderY ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strBottom + strMinusWidth), true) : 0, l: updateBorderX ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strLeft + strMinusWidth), true) : 0 }; //detect margin: var margin = { c: force, t: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strTop)), r: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strRight)), b: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strBottom)), l: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strLeft)) }; //detect css max width & height: var cssMaxValue = { h: String(_hostElement.css(_strMaxMinus + _strHeight)), w: String(_hostElement.css(_strMaxMinus + _strWidth)) }; //vars to apply correct css var contentElementCSS = { }; var contentGlueElementCSS = { }; //funcs var getHostSize = function() { //has to be clientSize because offsetSize respect borders return { w: _hostElementNative[LEXICON.cW], h: _hostElementNative[LEXICON.cH] }; }; var getViewportSize = function() { //viewport size is padding container because it never has padding, margin and a border //determine zoom rounding error -> sometimes scrollWidth/Height is smaller than clientWidth/Height //if this happens add the difference to the viewportSize to compensate the rounding error return { w: _paddingElementNative[LEXICON.oW] + MATH.max(0, _contentElementNative[LEXICON.cW] - _contentElementNative[LEXICON.sW]), h: _paddingElementNative[LEXICON.oH] + MATH.max(0, _contentElementNative[LEXICON.cH] - _contentElementNative[LEXICON.sH]) }; }; //set info for padding var paddingAbsoluteX = _paddingX = padding.l + padding.r; var paddingAbsoluteY = _paddingY = padding.t + padding.b; paddingAbsoluteX *= paddingAbsolute ? 1 : 0; paddingAbsoluteY *= paddingAbsolute ? 1 : 0; padding.c = checkCacheTRBL(padding, _cssPaddingCache); //set info for border _borderX = border.l + border.r; _borderY = border.t + border.b; border.c = checkCacheTRBL(border, _cssBorderCache); //set info for margin _marginX = margin.l + margin.r; _marginY = margin.t + margin.b; margin.c = checkCacheTRBL(margin, _cssMarginCache); //set info for css max value cssMaxValue.ih = parseToZeroOrNumber(cssMaxValue.h); //ih = integer height cssMaxValue.iw = parseToZeroOrNumber(cssMaxValue.w); //iw = integer width cssMaxValue.ch = cssMaxValue.h.indexOf('px') > -1; //ch = correct height cssMaxValue.cw = cssMaxValue.w.indexOf('px') > -1; //cw = correct width cssMaxValue.c = checkCacheDouble(cssMaxValue, _cssMaxValueCache, force); //refresh cache _cssDirectionCache = cssDirection; _cssBoxSizingCache = boxSizing; _widthAutoCache = widthAuto; _heightAutoCache = heightAuto; _cssPaddingCache = padding; _cssBorderCache = border; _cssMarginCache = margin; _cssMaxValueCache = cssMaxValue; //IEFix direction changed if (cssDirectionChanged && _sizeAutoObserverAdded) _sizeAutoObserverElement.css(_strFloat, isRTLRight); //apply padding: if (padding.c || cssDirectionChanged || paddingAbsoluteChanged || widthAutoChanged || heightAutoChanged || boxSizingChanged || sizeAutoCapableChanged) { var paddingElementCSS = {}; var textareaCSS = {}; setTopRightBottomLeft(contentGlueElementCSS, _strMarginMinus, [-padding.t, -padding.r, -padding.b, -padding.l]); if (paddingAbsolute) { setTopRightBottomLeft(paddingElementCSS, _strEmpty, [padding.t, padding.r, padding.b, padding.l]); if (_isTextarea) setTopRightBottomLeft(textareaCSS, _strPaddingMinus); else setTopRightBottomLeft(contentElementCSS, _strPaddingMinus); } else { setTopRightBottomLeft(paddingElementCSS, _strEmpty); if (_isTextarea) setTopRightBottomLeft(textareaCSS, _strPaddingMinus, [padding.t, padding.r, padding.b, padding.l]); else setTopRightBottomLeft(contentElementCSS, _strPaddingMinus, [padding.t, padding.r, padding.b, padding.l]); } _paddingElement.css(paddingElementCSS); _targetElement.css(textareaCSS); } //viewport size is padding container because it never has padding, margin and a border. _viewportSize = getViewportSize(); //update Textarea var textareaSize = _isTextarea ? textareaUpdate() : false; var textareaDynOrigSize = _isTextarea && textareaSize ? { w : textareaDynWidth ? textareaSize._dynamicWidth : textareaSize._originalWidth, h : textareaDynHeight ? textareaSize._dynamicHeight : textareaSize._originalHeight } : { }; //fix height auto / width auto in cooperation with current padding & boxSizing behavior: if (heightAuto && (heightAutoChanged || paddingAbsoluteChanged || boxSizingChanged || cssMaxValue.c || padding.c || border.c)) { //if (cssMaxValue.ch) contentElementCSS[_strMaxMinus + _strHeight] = (cssMaxValue.ch ? (cssMaxValue.ih - paddingAbsoluteY + (_isBorderBox ? -_borderY : _paddingY)) : _strEmpty); contentElementCSS[_strHeight] = _strAuto; } else if (heightAutoChanged || paddingAbsoluteChanged) { contentElementCSS[_strMaxMinus + _strHeight] = _strEmpty; contentElementCSS[_strHeight] = _strHundredPercent; } if (widthAuto && (widthAutoChanged || paddingAbsoluteChanged || boxSizingChanged || cssMaxValue.c || padding.c || border.c || cssDirectionChanged)) { //if (cssMaxValue.cw) contentElementCSS[_strMaxMinus + _strWidth] = (cssMaxValue.cw ? (cssMaxValue.iw - paddingAbsoluteX + (_isBorderBox ? -_borderX : _paddingX)) + (_nativeScrollbarIsOverlaid.y /*&& _hasOverflowCache.y && widthAuto */ ? _overlayScrollbarDummySize.y : 0) : _strEmpty); contentElementCSS[_strWidth] = _strAuto; contentGlueElementCSS[_strMaxMinus + _strWidth] = _strHundredPercent; //IE Fix } else if (widthAutoChanged || paddingAbsoluteChanged) { contentElementCSS[_strMaxMinus + _strWidth] = _strEmpty; contentElementCSS[_strWidth] = _strHundredPercent; contentElementCSS[_strFloat] = _strEmpty; contentGlueElementCSS[_strMaxMinus + _strWidth] = _strEmpty; //IE Fix } if (widthAuto) { if (!cssMaxValue.cw) contentElementCSS[_strMaxMinus + _strWidth] = _strEmpty; //textareaDynOrigSize.w || _strAuto :: doesnt works because applied margin will shift width contentGlueElementCSS[_strWidth] = _strAuto; contentElementCSS[_strWidth] = _strAuto; contentElementCSS[_strFloat] = isRTLRight; } else { contentGlueElementCSS[_strWidth] = _strEmpty; } if (heightAuto) { if (!cssMaxValue.ch) contentElementCSS[_strMaxMinus + _strHeight] = _strEmpty; //textareaDynOrigSize.h || _contentElementNative[LEXICON.cH] :: use for anti scroll jumping contentGlueElementCSS[_strHeight] = textareaDynOrigSize.h || _contentElementNative[LEXICON.cH]; } else { contentGlueElementCSS[_strHeight] = _strEmpty; } if (sizeAutoCapable) _contentGlueElement.css(contentGlueElementCSS); _contentElement.css(contentElementCSS); //CHECKPOINT HERE ~ contentElementCSS = {}; contentGlueElementCSS = {}; //if [content(host) client / scroll size, or target element direction, or content(host) max-sizes] changed, or force is true if (hostSizeChanged || contentSizeChanged || cssDirectionChanged || boxSizingChanged || paddingAbsoluteChanged || widthAutoChanged || widthAuto || heightAutoChanged || heightAuto || cssMaxValue.c || ignoreOverlayScrollbarHidingChanged || overflowBehaviorChanged || clipAlwaysChanged || resizeChanged || scrollbarsVisibilityChanged || scrollbarsAutoHideChanged || scrollbarsDragScrollingChanged || scrollbarsClickScrollingChanged || textareaDynWidthChanged || textareaDynHeightChanged || textareaAutoWrappingChanged || force) { var strOverflow = 'overflow'; var strOverflowX = strOverflow + '-x'; var strOverflowY = strOverflow + '-y'; var strHidden = 'hidden'; var strVisible = 'visible'; //decide whether the content overflow must get hidden for correct overflow measuring, it !MUST! be always hidden if the height is auto var hideOverflow4CorrectMeasuring = _restrictedMeasuring ? (_nativeScrollbarIsOverlaid.x || _nativeScrollbarIsOverlaid.y) || //it must be hidden if native scrollbars are overlaid (_viewportSize.w < _nativeScrollbarMinSize.y || _viewportSize.h < _nativeScrollbarMinSize.x) || //it must be hidden if host-element is too small heightAuto || displayIsHiddenChanged //it must be hidden if height is auto or display was change : heightAuto; //if there is not the restricted Measuring bug, it must be hidden if the height is auto //Reset the viewport (very important for natively overlaid scrollbars and zoom change //don't change the overflow prop as it is very expensive and affects performance !A LOT! var viewportElementResetCSS = { }; var resetXTmp = _hasOverflowCache.y && _hideOverflowCache.ys && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.y ? _viewportElement.css(isRTLLeft) : -_nativeScrollbarSize.y) : 0; var resetBottomTmp = _hasOverflowCache.x && _hideOverflowCache.xs && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.x ? _viewportElement.css(_strBottom) : -_nativeScrollbarSize.x) : 0; setTopRightBottomLeft(viewportElementResetCSS, _strEmpty); _viewportElement.css(viewportElementResetCSS); if(hideOverflow4CorrectMeasuring) _contentElement.css(strOverflow, strHidden); //measure several sizes: var contentMeasureElement = getContentMeasureElement(); //in Firefox content element has to have overflow hidden, else element margins aren't calculated properly, this element prevents this bug, but only if scrollbars aren't overlaid var contentMeasureElementGuaranty = _restrictedMeasuring && !hideOverflow4CorrectMeasuring ? _viewportElementNative : contentMeasureElement; var contentSize = { //use clientSize because natively overlaidScrollbars add borders w: textareaDynOrigSize.w || contentMeasureElement[LEXICON.cW], h: textareaDynOrigSize.h || contentMeasureElement[LEXICON.cH] }; var scrollSize = { w: MATH.max(contentMeasureElement[LEXICON.sW], contentMeasureElementGuaranty[LEXICON.sW]), h: MATH.max(contentMeasureElement[LEXICON.sH], contentMeasureElementGuaranty[LEXICON.sH]) }; //apply the correct viewport style and measure viewport size viewportElementResetCSS[_strBottom] = wasHeightAuto ? _strEmpty : resetBottomTmp; viewportElementResetCSS[isRTLLeft] = wasWidthAuto ? _strEmpty : resetXTmp; _viewportElement.css(viewportElementResetCSS); _viewportSize = getViewportSize(); //measure and correct several sizes var hostSize = getHostSize(); var contentGlueSize = { //client/scrollSize + AbsolutePadding -> because padding is only applied to the paddingElement if its absolute, so you have to add it manually //hostSize is clientSize -> so padding should be added manually, right? FALSE! Because content glue is inside hostElement, so we don't have to worry about padding w: MATH.max((widthAuto ? contentSize.w : scrollSize.w) + paddingAbsoluteX, hostSize.w), h: MATH.max((heightAuto ? contentSize.h : scrollSize.h) + paddingAbsoluteY, hostSize.h) }; contentGlueSize.c = checkCacheDouble(contentGlueSize, _contentGlueSizeCache, force); _contentGlueSizeCache = contentGlueSize; //apply correct contentGlue size if (sizeAutoCapable) { //size contentGlue correctly to make sure the element has correct size if the sizing switches to auto if (contentGlueSize.c || (heightAuto || widthAuto)) { contentGlueElementCSS[_strWidth] = contentGlueSize.w; contentGlueElementCSS[_strHeight] = contentGlueSize.h; //textarea-sizes are already calculated correctly at this point if(!_isTextarea) { contentSize = { //use clientSize because natively overlaidScrollbars add borders w: contentMeasureElement[LEXICON.cW], h: contentMeasureElement[LEXICON.cH] }; } } var textareaCoverCSS = {}; var setContentGlueElementCSSfunction = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var wh = scrollbarVars._w_h; var strWH = scrollbarVars._width_height; var autoSize = horizontal ? widthAuto : heightAuto; var borderSize = horizontal ? _borderX : _borderY; var paddingSize = horizontal ? _paddingX : _paddingY; var marginSize = horizontal ? _marginX : _marginY; var maxSize = contentGlueElementCSS[strWH] + (_isBorderBox ? borderSize : -paddingSize); //make contentGlue size -1 if element is not auto sized, to make sure that a resize event happens when the element shrinks if (!autoSize || (!autoSize && border.c)) contentGlueElementCSS[strWH] = hostSize[wh] - (_isBorderBox ? 0 : paddingSize + borderSize) - 1 - marginSize; //if size is auto and host is same size as max size, make content glue size +1 to make sure size changes will be detected if (autoSize && cssMaxValue['c' + wh] && cssMaxValue['i' + wh] === maxSize) contentGlueElementCSS[strWH] = maxSize + (_isBorderBox ? 0 : paddingSize) + 1; //if size is auto and host is smaller than size as min size, make content glue size -1 to make sure size changes will be detected (this is only needed if padding is 0) if (autoSize && (contentSize[wh] < _viewportSize[wh]) && (horizontal ? (_isTextarea ? !textareaAutoWrapping : false) : true)) { if (_isTextarea) textareaCoverCSS[strWH] = parseToZeroOrNumber(_textareaCoverElement.css(strWH)) - 1; contentGlueElementCSS[strWH] -= 1; } //make sure content glue size is at least 1 if (contentSize[wh] > 0) contentGlueElementCSS[strWH] = MATH.max(1, contentGlueElementCSS[strWH]); }; setContentGlueElementCSSfunction(true); setContentGlueElementCSSfunction(false); if (_isTextarea) _textareaCoverElement.css(textareaCoverCSS); _contentGlueElement.css(contentGlueElementCSS); } if (widthAuto) contentElementCSS[_strWidth] = _strHundredPercent; if (widthAuto && !_isBorderBox && !_mutationObserversConnected) contentElementCSS[_strFloat] = 'none'; //apply and reset content style _contentElement.css(contentElementCSS); contentElementCSS = {}; //measure again, but this time all correct sizes: var contentScrollSize = { w: MATH.max(contentMeasureElement[LEXICON.sW], contentMeasureElementGuaranty[LEXICON.sW]), h: MATH.max(contentMeasureElement[LEXICON.sH], contentMeasureElementGuaranty[LEXICON.sH]) }; contentScrollSize.c = contentSizeChanged = checkCacheDouble(contentScrollSize, _contentScrollSizeCache, force); _contentScrollSizeCache = contentScrollSize; //remove overflow hidden to restore overflow if(hideOverflow4CorrectMeasuring) _contentElement.css(strOverflow, _strEmpty); //refresh viewport size after correct measuring _viewportSize = getViewportSize(); hostSize = getHostSize(); hostSizeChanged = checkCacheDouble(hostSize, _hostSizeCache); _hostSizeCache = hostSize; var hideOverflowForceTextarea = _isTextarea && (_viewportSize.w === 0 || _viewportSize.h === 0); var previousOverflow = _overflowAmountCache; var overflowBehaviorIsVS = { }; var overflowBehaviorIsVH = { }; var overflowBehaviorIsS = { }; var overflowAmount = { }; var hasOverflow = { }; var hideOverflow = { }; var canScroll = { }; var viewportRect = _paddingElementNative.getBoundingClientRect(); var setOverflowVariables = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xyI = scrollbarVarsInverted._x_y; var xy = scrollbarVars._x_y; var wh = scrollbarVars._w_h; var widthHeight = scrollbarVars._width_height; var scrollMax = _strScroll + scrollbarVars._Left_Top + 'Max'; var fractionalOverflowAmount = viewportRect[widthHeight] ? MATH.abs(viewportRect[widthHeight] - _viewportSize[wh]) : 0; overflowBehaviorIsVS[xy] = overflowBehavior[xy] === 'v-s'; overflowBehaviorIsVH[xy] = overflowBehavior[xy] === 'v-h'; overflowBehaviorIsS[xy] = overflowBehavior[xy] === 's'; overflowAmount[xy] = MATH.max(0, MATH.round((contentScrollSize[wh] - _viewportSize[wh]) * 100) / 100); overflowAmount[xy] *= (hideOverflowForceTextarea || (_viewportElementNative[scrollMax] === 0 && fractionalOverflowAmount > 0 && fractionalOverflowAmount < 1)) ? 0 : 1; hasOverflow[xy] = overflowAmount[xy] > 0; //hideOverflow: //x || y : true === overflow is hidden by "overflow: scroll" OR "overflow: hidden" //xs || ys : true === overflow is hidden by "overflow: scroll" hideOverflow[xy] = overflowBehaviorIsVS[xy] || overflowBehaviorIsVH[xy] ? (hasOverflow[xyI] && !overflowBehaviorIsVS[xyI] && !overflowBehaviorIsVH[xyI]) : hasOverflow[xy]; hideOverflow[xy + 's'] = hideOverflow[xy] ? (overflowBehaviorIsS[xy] || overflowBehaviorIsVS[xy]) : false; canScroll[xy] = hasOverflow[xy] && hideOverflow[xy + 's']; }; setOverflowVariables(true); setOverflowVariables(false); overflowAmount.c = checkCacheDouble(overflowAmount, _overflowAmountCache, _strX, _strY, force); _overflowAmountCache = overflowAmount; hasOverflow.c = checkCacheDouble(hasOverflow, _hasOverflowCache, _strX, _strY, force); _hasOverflowCache = hasOverflow; hideOverflow.c = checkCacheDouble(hideOverflow, _hideOverflowCache, _strX, _strY, force); _hideOverflowCache = hideOverflow; //if native scrollbar is overlay at x OR y axis, prepare DOM if (_nativeScrollbarIsOverlaid.x || _nativeScrollbarIsOverlaid.y) { var borderDesign = 'px solid transparent'; var contentArrangeElementCSS = { }; var arrangeContent = { }; var arrangeChanged = force; var setContentElementCSS; if (hasOverflow.x || hasOverflow.y) { arrangeContent.w = _nativeScrollbarIsOverlaid.y && hasOverflow.y ? contentScrollSize.w + _overlayScrollbarDummySize.y : _strEmpty; arrangeContent.h = _nativeScrollbarIsOverlaid.x && hasOverflow.x ? contentScrollSize.h + _overlayScrollbarDummySize.x : _strEmpty; arrangeChanged = checkCacheSingle(arrangeContent, _arrangeContentSizeCache, force); _arrangeContentSizeCache = arrangeContent; } if (hasOverflow.c || hideOverflow.c || contentScrollSize.c || cssDirectionChanged || widthAutoChanged || heightAutoChanged || widthAuto || heightAuto || ignoreOverlayScrollbarHidingChanged) { contentElementCSS[_strMarginMinus + isRTLRight] = contentElementCSS[_strBorderMinus + isRTLRight] = _strEmpty; setContentElementCSS = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xy = scrollbarVars._x_y; var strDirection = horizontal ? _strBottom : isRTLLeft; var invertedAutoSize = horizontal ? heightAuto : widthAuto; if (_nativeScrollbarIsOverlaid[xy] && hasOverflow[xy] && hideOverflow[xy + 's']) { contentElementCSS[_strMarginMinus + strDirection] = invertedAutoSize ? (ignoreOverlayScrollbarHiding ? _strEmpty : _overlayScrollbarDummySize[xy]) : _strEmpty; contentElementCSS[_strBorderMinus + strDirection] = ((horizontal ? !invertedAutoSize : true) && !ignoreOverlayScrollbarHiding) ? (_overlayScrollbarDummySize[xy] + borderDesign) : _strEmpty; } else { arrangeContent[scrollbarVarsInverted._w_h] = contentElementCSS[_strMarginMinus + strDirection] = contentElementCSS[_strBorderMinus + strDirection] = _strEmpty; arrangeChanged = true; } }; if (_nativeScrollbarStyling) { if (ignoreOverlayScrollbarHiding) removeClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible); else addClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible); } else { setContentElementCSS(true); setContentElementCSS(false); } } if (ignoreOverlayScrollbarHiding) { arrangeContent.w = arrangeContent.h = _strEmpty; arrangeChanged = true; } if (arrangeChanged && !_nativeScrollbarStyling) { contentArrangeElementCSS[_strWidth] = hideOverflow.y ? arrangeContent.w : _strEmpty; contentArrangeElementCSS[_strHeight] = hideOverflow.x ? arrangeContent.h : _strEmpty; if (!_contentArrangeElement) { _contentArrangeElement = FRAMEWORK(generateDiv(_classNameContentArrangeElement)); _viewportElement.prepend(_contentArrangeElement); } _contentArrangeElement.css(contentArrangeElementCSS); } _contentElement.css(contentElementCSS); } var viewportElementCSS = {}; var paddingElementCSS = {}; var setViewportCSS; if (hostSizeChanged || hasOverflow.c || hideOverflow.c || contentScrollSize.c || overflowBehaviorChanged || boxSizingChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged || clipAlwaysChanged || heightAutoChanged) { viewportElementCSS[isRTLRight] = _strEmpty; setViewportCSS = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xy = scrollbarVars._x_y; var XY = scrollbarVars._X_Y; var strDirection = horizontal ? _strBottom : isRTLLeft; var reset = function () { viewportElementCSS[strDirection] = _strEmpty; _contentBorderSize[scrollbarVarsInverted._w_h] = 0; }; if (hasOverflow[xy] && hideOverflow[xy + 's']) { viewportElementCSS[strOverflow + XY] = _strScroll; if (ignoreOverlayScrollbarHiding || _nativeScrollbarStyling) { reset(); } else { viewportElementCSS[strDirection] = -(_nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[xy] : _nativeScrollbarSize[xy]); _contentBorderSize[scrollbarVarsInverted._w_h] = _nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[scrollbarVarsInverted._x_y] : 0; } } else { viewportElementCSS[strOverflow + XY] = _strEmpty; reset(); } }; setViewportCSS(true); setViewportCSS(false); // if the scroll container is too small and if there is any overflow with no overlay scrollbar (and scrollbar styling isn't possible), // make viewport element greater in size (Firefox hide Scrollbars fix) // because firefox starts hiding scrollbars on too small elements // with this behavior the overflow calculation may be incorrect or the scrollbars would appear suddenly // https://bugzilla.mozilla.org/show_bug.cgi?id=292284 if (!_nativeScrollbarStyling && (_viewportSize.h < _nativeScrollbarMinSize.x || _viewportSize.w < _nativeScrollbarMinSize.y) && ((hasOverflow.x && hideOverflow.x && !_nativeScrollbarIsOverlaid.x) || (hasOverflow.y && hideOverflow.y && !_nativeScrollbarIsOverlaid.y))) { viewportElementCSS[_strPaddingMinus + _strTop] = _nativeScrollbarMinSize.x; viewportElementCSS[_strMarginMinus + _strTop] = -_nativeScrollbarMinSize.x; viewportElementCSS[_strPaddingMinus + isRTLRight] = _nativeScrollbarMinSize.y; viewportElementCSS[_strMarginMinus + isRTLRight] = -_nativeScrollbarMinSize.y; } else { viewportElementCSS[_strPaddingMinus + _strTop] = viewportElementCSS[_strMarginMinus + _strTop] = viewportElementCSS[_strPaddingMinus + isRTLRight] = viewportElementCSS[_strMarginMinus + isRTLRight] = _strEmpty; } viewportElementCSS[_strPaddingMinus + isRTLLeft] = viewportElementCSS[_strMarginMinus + isRTLLeft] = _strEmpty; //if there is any overflow (x OR y axis) and this overflow shall be hidden, make overflow hidden, else overflow visible if ((hasOverflow.x && hideOverflow.x) || (hasOverflow.y && hideOverflow.y) || hideOverflowForceTextarea) { //only hide if is Textarea if (_isTextarea && hideOverflowForceTextarea) { paddingElementCSS[strOverflowX] = paddingElementCSS[strOverflowY] = strHidden; } } else { if (!clipAlways || (overflowBehaviorIsVH.x || overflowBehaviorIsVS.x || overflowBehaviorIsVH.y || overflowBehaviorIsVS.y)) { //only un-hide if Textarea if (_isTextarea) { paddingElementCSS[strOverflowX] = paddingElementCSS[strOverflowY] = _strEmpty; } viewportElementCSS[strOverflowX] = viewportElementCSS[strOverflowY] = strVisible; } } _paddingElement.css(paddingElementCSS); _viewportElement.css(viewportElementCSS); viewportElementCSS = { }; //force soft redraw in webkit because without the scrollbars will may appear because DOM wont be redrawn under special conditions if ((hasOverflow.c || boxSizingChanged || widthAutoChanged || heightAutoChanged) && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) { var elementStyle = _contentElementNative[LEXICON.s]; var dump; elementStyle.webkitTransform = 'scale(1)'; elementStyle.display = 'run-in'; dump = _contentElementNative[LEXICON.oH]; elementStyle.display = _strEmpty; //|| dump; //use dump to prevent it from deletion if minify elementStyle.webkitTransform = _strEmpty; } /* //force hard redraw in webkit if native overlaid scrollbars shall appear if (ignoreOverlayScrollbarHidingChanged && ignoreOverlayScrollbarHiding) { _hostElement.hide(); var dump = _hostElementNative[LEXICON.oH]; _hostElement.show(); } */ } //change to direction RTL and width auto Bugfix in Webkit //without this fix, the DOM still thinks the scrollbar is LTR and thus the content is shifted to the left contentElementCSS = {}; if (cssDirectionChanged || widthAutoChanged || heightAutoChanged) { if (_isRTL && widthAuto) { var floatTmp = _contentElement.css(_strFloat); var posLeftWithoutFloat = MATH.round(_contentElement.css(_strFloat, _strEmpty).css(_strLeft, _strEmpty).position().left); _contentElement.css(_strFloat, floatTmp); var posLeftWithFloat = MATH.round(_contentElement.position().left); if (posLeftWithoutFloat !== posLeftWithFloat) contentElementCSS[_strLeft] = posLeftWithoutFloat; } else { contentElementCSS[_strLeft] = _strEmpty; } } _contentElement.css(contentElementCSS); //handle scroll position if (_isTextarea && contentSizeChanged) { var textareaInfo = getTextareaInfo(); if (textareaInfo) { var textareaRowsChanged = _textareaInfoCache === undefined ? true : textareaInfo._rows !== _textareaInfoCache._rows; var cursorRow = textareaInfo._cursorRow; var cursorCol = textareaInfo._cursorColumn; var widestRow = textareaInfo._widestRow; var lastRow = textareaInfo._rows; var lastCol = textareaInfo._columns; var cursorPos = textareaInfo._cursorPosition; var cursorMax = textareaInfo._cursorMax; var cursorIsLastPosition = (cursorPos >= cursorMax && _textareaHasFocus); var textareaScrollAmount = { x: (!textareaAutoWrapping && (cursorCol === lastCol && cursorRow === widestRow)) ? _overflowAmountCache.x : -1, y: (textareaAutoWrapping ? cursorIsLastPosition || textareaRowsChanged && (previousOverflow !== undefined ? (currScroll.y === previousOverflow.y) : false) : (cursorIsLastPosition || textareaRowsChanged) && cursorRow === lastRow) ? _overflowAmountCache.y : -1 }; currScroll.x = textareaScrollAmount.x > -1 ? (_isRTL && _normalizeRTLCache && _rtlScrollBehavior.i ? 0 : textareaScrollAmount.x) : currScroll.x; //if inverted, scroll to 0 -> normalized this means to max scroll offset. currScroll.y = textareaScrollAmount.y > -1 ? textareaScrollAmount.y : currScroll.y; } _textareaInfoCache = textareaInfo; } if (_isRTL && _rtlScrollBehavior.i && _nativeScrollbarIsOverlaid.y && hasOverflow.x && _normalizeRTLCache) currScroll.x += _contentBorderSize.w || 0; if(widthAuto) _hostElement[_strScrollLeft](0); if(heightAuto) _hostElement[_strScrollTop](0); _viewportElement[_strScrollLeft](currScroll.x)[_strScrollTop](currScroll.y); //scrollbars management: var scrollbarsVisibilityVisible = scrollbarsVisibility === 'v'; var scrollbarsVisibilityHidden = scrollbarsVisibility === 'h'; var scrollbarsVisibilityAuto = scrollbarsVisibility === 'a'; var showScrollbarH = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, true, true, canScroll.x); var showScrollbarV = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, false, true, canScroll.y); var hideScrollbarH = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, true, false, canScroll.x); var hideScrollbarV = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, false, false, canScroll.y); //manage class name which indicates scrollable overflow if (hideOverflow.x || hideOverflow.y) addClass(_hostElement, _classNameHostOverflow); else removeClass(_hostElement, _classNameHostOverflow); if (hideOverflow.x) addClass(_hostElement, _classNameHostOverflowX); else removeClass(_hostElement, _classNameHostOverflowX); if (hideOverflow.y) addClass(_hostElement, _classNameHostOverflowY); else removeClass(_hostElement, _classNameHostOverflowY); //add or remove rtl class name for styling purposes if (cssDirectionChanged) { if (_isRTL) addClass(_hostElement, _classNameHostRTL); else removeClass(_hostElement, _classNameHostRTL); } //manage the resize feature (CSS3 resize "polyfill" for this plugin) if (_isBody) addClass(_hostElement, _classNameHostResizeDisabled); if (resizeChanged) { var addCornerEvents = function () { _scrollbarCornerElement.on(_strMouseTouchDownEvent, _resizeOnMouseTouchDown); }; var removeCornerEvents = function () { _scrollbarCornerElement.off(_strMouseTouchDownEvent, _resizeOnMouseTouchDown); }; removeClass(_scrollbarCornerElement, [ _classNameHostResizeDisabled, _classNameScrollbarCornerResize, _classNameScrollbarCornerResizeB, _classNameScrollbarCornerResizeH, _classNameScrollbarCornerResizeV].join(_strSpace)); if (_resizeNone) { addClass(_hostElement, _classNameHostResizeDisabled); removeCornerEvents(); } else { addClass(_scrollbarCornerElement, _classNameScrollbarCornerResize); if (_resizeBoth) addClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeB); else if (_resizeHorizontal) addClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeH); else if (_resizeVertical) addClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeV); removeCornerEvents(); addCornerEvents(); } } //manage the scrollbars general visibility + the scrollbar interactivity (unusable class name) if (scrollbarsVisibilityChanged || overflowBehaviorChanged || hideOverflow.c || hasOverflow.c || ignoreOverlayScrollbarHidingChanged) { if (ignoreOverlayScrollbarHiding) { if (ignoreOverlayScrollbarHidingChanged) { removeClass(_hostElement, _classNameHostScrolling); if (ignoreOverlayScrollbarHiding) { hideScrollbarH(); hideScrollbarV(); } } } else if (scrollbarsVisibilityAuto) { if (canScroll.x) showScrollbarH(); else hideScrollbarH(); if (canScroll.y) showScrollbarV(); else hideScrollbarV(); } else if (scrollbarsVisibilityVisible) { showScrollbarH(); showScrollbarV(); } else if (scrollbarsVisibilityHidden) { hideScrollbarH(); hideScrollbarV(); } } //manage the scrollbars auto hide feature (auto hide them after specific actions) if (scrollbarsAutoHideChanged || ignoreOverlayScrollbarHidingChanged) { if (_scrollbarsAutoHideLeave || _scrollbarsAutoHideMove) { setupHostMouseTouchEvents(true); setupHostMouseTouchEvents(); } else { setupHostMouseTouchEvents(true); } if (_scrollbarsAutoHideNever) refreshScrollbarsAutoHide(true); else refreshScrollbarsAutoHide(false, true); } //manage scrollbars handle length & offset - don't remove! if (hostSizeChanged || overflowAmount.c || heightAutoChanged || widthAutoChanged || resizeChanged || boxSizingChanged || paddingAbsoluteChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged) { refreshScrollbarHandleLength(true); refreshScrollbarHandleOffset(true); refreshScrollbarHandleLength(false); refreshScrollbarHandleOffset(false); } //manage interactivity if (scrollbarsClickScrollingChanged) refreshScrollbarsInteractive(true, scrollbarsClickScrolling); if (scrollbarsDragScrollingChanged) refreshScrollbarsInteractive(false, scrollbarsDragScrolling); //callbacks: if (cssDirectionChanged) { dispatchCallback("onDirectionChanged", { isRTL: _isRTL, dir: cssDirection }); } if (hostSizeChanged) { dispatchCallback("onHostSizeChanged", { width: _hostSizeCache.w, height: _hostSizeCache.h }); } if (contentSizeChanged) { dispatchCallback("onContentSizeChanged", { width: _contentScrollSizeCache.w, height: _contentScrollSizeCache.h }); } if (hasOverflow.c || hideOverflow.c) { dispatchCallback("onOverflowChanged", { x: hasOverflow.x, y: hasOverflow.y, xScrollable: hideOverflow.xs, yScrollable: hideOverflow.ys, clipped: hideOverflow.x || hideOverflow.y }); } if (overflowAmount.c) { dispatchCallback("onOverflowAmountChanged", { x: overflowAmount.x, y: overflowAmount.y }); } } //fix body min size if (_isBody && (_hasOverflowCache.c || _bodyMinSizeCache.c)) { //its possible that no min size was measured until now, because the content arrange element was just added now, in this case, measure now the min size. if (!_bodyMinSizeCache.f) bodyMinSizeChanged(); if (_nativeScrollbarIsOverlaid.y && _hasOverflowCache.x) _contentElement.css(_strMinMinus + _strWidth, _bodyMinSizeCache.w + _overlayScrollbarDummySize.y); if (_nativeScrollbarIsOverlaid.x && _hasOverflowCache.y) _contentElement.css(_strMinMinus + _strHeight, _bodyMinSizeCache.h + _overlayScrollbarDummySize.x); _bodyMinSizeCache.c = false; } unfreezeResizeObserver(_sizeObserverElement); unfreezeResizeObserver(_sizeAutoObserverElement); dispatchCallback("onUpdated", { forced: force }); } //==== Options ====// /** * Sets new options but doesn't call the update method. * @param newOptions The object which contains the new options. */ function setOptions(newOptions) { _currentOptions = extendDeep({}, _currentOptions, _pluginsOptions._validate(newOptions, _pluginsOptions._template, true)); _currentPreparedOptions = extendDeep({}, _currentPreparedOptions, _pluginsOptions._validate(newOptions, _pluginsOptions._template, false, true)); } //==== Structure ====// /** * Builds or destroys the wrapper and helper DOM elements. * @param destroy Indicates whether the DOM shall be build or destroyed. */ function setupStructureDOM(destroy) { var adoptAttrs = _currentPreparedOptions.textarea.inheritedAttrs; var adoptAttrsMap = { }; var applyAdoptedAttrs = function() { var applyAdoptedAttrsElm = destroy ? _targetElement : _hostElement; FRAMEWORK.each(adoptAttrsMap, function(k, v) { if(type(v) == TYPES.s) { if(k == LEXICON.c) applyAdoptedAttrsElm.addClass(v); else applyAdoptedAttrsElm.attr(k, v); } }); }; var hostElementClassNames = [ _classNameHostElement, _classNameHostTextareaElement, _classNameHostResizeDisabled, _classNameHostRTL, _classNameHostScrollbarHorizontalHidden, _classNameHostScrollbarVerticalHidden, _classNameHostTransition, _classNameHostScrolling, _classNameHostOverflow, _classNameHostOverflowX, _classNameHostOverflowY, _classNameThemeNone, _classNameTextareaElement, _classNameTextInherit, _classNameCache].join(_strSpace); adoptAttrs = type(adoptAttrs) == TYPES.s ? adoptAttrs.split(' ') : adoptAttrs; if(type(adoptAttrs) == TYPES.a) { FRAMEWORK.each(adoptAttrs, function(i, v) { if(type(v) == TYPES.s) adoptAttrsMap[v] = destroy ? _hostElement.attr(v) : _targetElement.attr(v); }); } if(!destroy) { if (_isTextarea) { var hostElementCSS = {}; var parent = _targetElement.parent(); _isTextareaHostGenerated = !(parent.hasClass(_classNameHostTextareaElement) && parent.children()[LEXICON.l] === 1); if (!_currentPreparedOptions.sizeAutoCapable) { hostElementCSS[_strWidth] = _targetElement.css(_strWidth); hostElementCSS[_strHeight] = _targetElement.css(_strHeight); } if(_isTextareaHostGenerated) _targetElement.wrap(generateDiv(_classNameHostTextareaElement)); _hostElement = _targetElement.parent(); _hostElement.css(hostElementCSS) .wrapInner(generateDiv(_classNameContentElement + _strSpace + _classNameTextInherit)) .wrapInner(generateDiv(_classNameViewportElement + _strSpace + _classNameTextInherit)) .wrapInner(generateDiv(_classNamePaddingElement + _strSpace + _classNameTextInherit)); _contentElement = findFirst(_hostElement, _strDot + _classNameContentElement); _viewportElement = findFirst(_hostElement, _strDot + _classNameViewportElement); _paddingElement = findFirst(_hostElement, _strDot + _classNamePaddingElement); _textareaCoverElement = FRAMEWORK(generateDiv(_classNameTextareaCoverElement)); _contentElement.prepend(_textareaCoverElement); addClass(_targetElement, _classNameTextareaElement + _strSpace + _classNameTextInherit); if(_isTextareaHostGenerated) applyAdoptedAttrs(); } else { _hostElement = _targetElement; _hostElement.wrapInner(generateDiv(_classNameContentElement)) .wrapInner(generateDiv(_classNameViewportElement)) .wrapInner(generateDiv(_classNamePaddingElement)); _contentElement = findFirst(_hostElement, _strDot + _classNameContentElement); _viewportElement = findFirst(_hostElement, _strDot + _classNameViewportElement); _paddingElement = findFirst(_hostElement, _strDot + _classNamePaddingElement); addClass(_targetElement, _classNameHostElement); } if (_nativeScrollbarStyling) addClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible); if(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y) addClass(_viewportElement, _classNameViewportNativeScrollbarsOverlaid); if (_isBody) addClass(_htmlElement, _classNameHTMLElement); _sizeObserverElement = FRAMEWORK(generateDiv('os-resize-observer-host')); _hostElement.prepend(_sizeObserverElement); _sizeObserverElementNative = _sizeObserverElement[0]; _hostElementNative = _hostElement[0]; _paddingElementNative = _paddingElement[0]; _viewportElementNative = _viewportElement[0]; _contentElementNative = _contentElement[0]; } else { _contentElement.contents() .unwrap() .unwrap() .unwrap(); removeClass(_hostElement, hostElementClassNames); if (_isTextarea) { _targetElement.removeAttr(LEXICON.s); if(_isTextareaHostGenerated) applyAdoptedAttrs(); removeClass(_targetElement, hostElementClassNames); remove(_textareaCoverElement); if(_isTextareaHostGenerated) { _targetElement.unwrap(); remove(_hostElement); } else { addClass(_hostElement, _classNameHostTextareaElement); } } else { removeClass(_targetElement, _classNameHostElement); } if (_isBody) removeClass(_htmlElement, _classNameHTMLElement); remove(_sizeObserverElement); } } /** * Adds or removes all wrapper elements interactivity events. * @param destroy Indicates whether the Events shall be added or removed. */ function setupStructureEvents(destroy) { var textareaKeyDownRestrictedKeyCodes = [ 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 123, //F1 to F12 33, 34, //page up, page down 37, 38, 39, 40, //left, up, right, down arrows 16, 17, 18, 19, 20, 144 //Shift, Ctrl, Alt, Pause, CapsLock, NumLock ]; var textareaKeyDownKeyCodesList = [ ]; var textareaUpdateIntervalID; var scrollStopDelay = 175; var scrollStopTimeoutId; var strOnOff = destroy ? 'off' : 'on'; var updateTextarea; var viewportOnScroll; if(!destroy && _isTextarea) { _textareaEvents = { }; updateTextarea = function(doClearInterval) { textareaUpdate(); _base.update(_strAuto); if(doClearInterval) clearInterval(textareaUpdateIntervalID); }; _textareaEvents[_strScroll] = function(event) { _targetElement[_strScrollLeft](_rtlScrollBehavior.i && _normalizeRTLCache ? 9999999 : 0); _targetElement[_strScrollTop](0); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); return false; }; _textareaEvents['drop'] = function() { setTimeout(function () { if(!_destroyed) updateTextarea(); }, 50); }; _textareaEvents['focus'] = function() { _textareaHasFocus = true; }; _textareaEvents['focusout'] = function() { _textareaHasFocus = false; textareaKeyDownKeyCodesList = [ ]; updateTextarea(true); }; if (_msieVersion > 9 || !_autoUpdateRecommended) { _textareaEvents['input'] = function textareaOnInput() { updateTextarea(); } } else { _textareaEvents[_strKeyDownEvent] = function textareaOnKeyDown(event) { var keyCode = event.keyCode; if (FRAMEWORK.inArray(keyCode, textareaKeyDownRestrictedKeyCodes) > -1) return; if (!textareaKeyDownKeyCodesList.length) { updateTextarea(); textareaUpdateIntervalID = setInterval(updateTextarea, 1000 / 60); } if (FRAMEWORK.inArray(keyCode, textareaKeyDownKeyCodesList) === -1) textareaKeyDownKeyCodesList.push(keyCode); }; _textareaEvents[_strKeyUpEvent] = function(event) { var keyCode = event.keyCode; var index = FRAMEWORK.inArray(keyCode, textareaKeyDownKeyCodesList); if (FRAMEWORK.inArray(keyCode, textareaKeyDownRestrictedKeyCodes) > -1) return; if (index > -1) textareaKeyDownKeyCodesList.splice(index, 1); if (!textareaKeyDownKeyCodesList.length) updateTextarea(true); }; } } if (_isTextarea) { FRAMEWORK.each(_textareaEvents, function(key, value) { _targetElement[strOnOff](key, value); }); } else { _contentElement[strOnOff](_strTransitionEndEvent, function (event) { if (_autoUpdateCache === true) return; event = event.originalEvent || event; if (isSizeAffectingCSSProperty(event.propertyName)) update(_strAuto); }); } if(!destroy) { viewportOnScroll = function(event) { if (_isSleeping) return; if (scrollStopTimeoutId !== undefined) clearTimeout(scrollStopTimeoutId); else { if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(true); if (!nativeOverlayScrollbarsAreActive()) addClass(_hostElement, _classNameHostScrolling); dispatchCallback("onScrollStart", event); } //if a scrollbars handle gets dragged, the mousemove event is responsible for refreshing the handle offset //because if CSS scroll-snap is used, the handle offset gets only refreshed on every snap point //this looks laggy & clunky, it looks much better if the offset refreshes with the mousemove if(!_scrollbarsHandleAsync) { refreshScrollbarHandleOffset(true); refreshScrollbarHandleOffset(false); } dispatchCallback("onScroll", event); scrollStopTimeoutId = setTimeout(function () { if(!_destroyed) { //OnScrollStop: clearTimeout(scrollStopTimeoutId); scrollStopTimeoutId = undefined; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); if (!nativeOverlayScrollbarsAreActive()) removeClass(_hostElement, _classNameHostScrolling); dispatchCallback("onScrollStop", event); } }, scrollStopDelay); }; if (_supportPassiveEvents) addPassiveEventListener(_viewportElement, _strScroll, viewportOnScroll); else _viewportElement.on(_strScroll, viewportOnScroll); } } //==== Scrollbars ====// /** * Builds or destroys all scrollbar DOM elements (scrollbar, track, handle) * @param destroy Indicates whether the DOM shall be build or destroyed. */ function setupScrollbarsDOM(destroy) { if(!destroy) { _scrollbarHorizontalElement = FRAMEWORK(generateDiv(_classNameScrollbar + _strSpace + _classNameScrollbarHorizontal)); _scrollbarHorizontalTrackElement = FRAMEWORK(generateDiv(_classNameScrollbarTrack)); _scrollbarHorizontalHandleElement = FRAMEWORK(generateDiv(_classNameScrollbarHandle)); _scrollbarVerticalElement = FRAMEWORK(generateDiv(_classNameScrollbar + _strSpace + _classNameScrollbarVertical)); _scrollbarVerticalTrackElement = FRAMEWORK(generateDiv(_classNameScrollbarTrack)); _scrollbarVerticalHandleElement = FRAMEWORK(generateDiv(_classNameScrollbarHandle)); _scrollbarHorizontalElement.append(_scrollbarHorizontalTrackElement); _scrollbarHorizontalTrackElement.append(_scrollbarHorizontalHandleElement); _scrollbarVerticalElement.append(_scrollbarVerticalTrackElement); _scrollbarVerticalTrackElement.append(_scrollbarVerticalHandleElement); _paddingElement.after(_scrollbarVerticalElement); _paddingElement.after(_scrollbarHorizontalElement); } else { remove(_scrollbarHorizontalElement); remove(_scrollbarVerticalElement); } } /** * Initializes all scrollbar interactivity events. (track and handle dragging, clicking, scrolling) * @param isHorizontal True if the target scrollbar is the horizontal scrollbar, false if the target scrollbar is the vertical scrollbar. */ function setupScrollbarEvents(isHorizontal) { var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var insideIFrame = _windowElementNative.top !== _windowElementNative; var xy = scrollbarVars._x_y; var XY = scrollbarVars._X_Y; var scroll = _strScroll + scrollbarVars._Left_Top; var strActive = 'active'; var strSnapHandle = 'snapHandle'; var scrollDurationFactor = 1; var increaseDecreaseScrollAmountKeyCodes = [ 16, 17 ]; //shift, ctrl var trackTimeout; var mouseDownScroll; var mouseDownOffset; var mouseDownInvertedScale; function getPointerPosition(event) { return _msieVersion && insideIFrame ? event['screen' + XY] : COMPATIBILITY.page(event)[xy]; //use screen coordinates in EDGE & IE because the page values are incorrect in frames. } function getPreparedScrollbarsOption(name) { return _currentPreparedOptions.scrollbars[name]; } function increaseTrackScrollAmount() { scrollDurationFactor = 0.5; } function decreaseTrackScrollAmount() { scrollDurationFactor = 1; } function documentKeyDown(event) { if (FRAMEWORK.inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1) increaseTrackScrollAmount(); } function documentKeyUp(event) { if (FRAMEWORK.inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1) decreaseTrackScrollAmount(); } function onMouseTouchDownContinue(event) { var originalEvent = event.originalEvent || event; var isTouchEvent = originalEvent.touches !== undefined; return _isSleeping || _destroyed || nativeOverlayScrollbarsAreActive() || !_scrollbarsDragScrollingCache || (isTouchEvent && !getPreparedScrollbarsOption('touchSupport')) ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent; } function documentDragMove(event) { if(onMouseTouchDownContinue(event)) { var trackLength = scrollbarVarsInfo._trackLength; var handleLength = scrollbarVarsInfo._handleLength; var scrollRange = scrollbarVarsInfo._maxScroll; var scrollRaw = (getPointerPosition(event) - mouseDownOffset) * mouseDownInvertedScale; var scrollDeltaPercent = scrollRaw / (trackLength - handleLength); var scrollDelta = (scrollRange * scrollDeltaPercent); scrollDelta = isFinite(scrollDelta) ? scrollDelta : 0; if (_isRTL && isHorizontal && !_rtlScrollBehavior.i) scrollDelta *= -1; _viewportElement[scroll](MATH.round(mouseDownScroll + scrollDelta)); if(_scrollbarsHandleAsync) refreshScrollbarHandleOffset(isHorizontal, mouseDownScroll + scrollDelta); if (!_supportPassiveEvents) COMPATIBILITY.prvD(event); } else documentMouseTouchUp(event); } function documentMouseTouchUp(event) { event = event || event.originalEvent; _documentElement.off(_strMouseTouchMoveEvent, documentDragMove) .off(_strMouseTouchUpEvent, documentMouseTouchUp) .off(_strKeyDownEvent, documentKeyDown) .off(_strKeyUpEvent, documentKeyUp) .off(_strSelectStartEvent, documentOnSelectStart); if(_scrollbarsHandleAsync) refreshScrollbarHandleOffset(isHorizontal, true); _scrollbarsHandleAsync = false; removeClass(_bodyElement, _classNameDragging); removeClass(scrollbarVars._handle, strActive); removeClass(scrollbarVars._track, strActive); removeClass(scrollbarVars._scrollbar, strActive); mouseDownScroll = undefined; mouseDownOffset = undefined; mouseDownInvertedScale = 1; decreaseTrackScrollAmount(); if (trackTimeout !== undefined) { _base.scrollStop(); clearTimeout(trackTimeout); trackTimeout = undefined; } if(event) { var rect = _hostElementNative.getBoundingClientRect(); var mouseInsideHost = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom; //if mouse is outside host element if (!mouseInsideHost) hostOnMouseLeave(); if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); } } function onHandleMouseTouchDown(event) { mouseDownScroll = _viewportElement[scroll](); mouseDownScroll = isNaN(mouseDownScroll) ? 0 : mouseDownScroll; if (_isRTL && isHorizontal && !_rtlScrollBehavior.n || !_isRTL) mouseDownScroll = mouseDownScroll < 0 ? 0 : mouseDownScroll; mouseDownInvertedScale = getHostElementInvertedScale()[xy]; mouseDownOffset = getPointerPosition(event); _scrollbarsHandleAsync = !getPreparedScrollbarsOption(strSnapHandle); addClass(_bodyElement, _classNameDragging); addClass(scrollbarVars._handle, strActive); addClass(scrollbarVars._scrollbar, strActive); _documentElement.on(_strMouseTouchMoveEvent, documentDragMove) .on(_strMouseTouchUpEvent, documentMouseTouchUp) .on(_strSelectStartEvent, documentOnSelectStart); if(_msieVersion || !_documentMixed) COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } scrollbarVars._handle.on(_strMouseTouchDownEvent, function(event) { if (onMouseTouchDownContinue(event)) onHandleMouseTouchDown(event); }); scrollbarVars._track.on(_strMouseTouchDownEvent, function(event) { if (onMouseTouchDownContinue(event)) { var scrollDistance = MATH.round(_viewportSize[scrollbarVars._w_h]); var trackOffset = scrollbarVars._track.offset()[scrollbarVars._left_top]; var ctrlKey = event.ctrlKey; var instantScroll = event.shiftKey; var instantScrollTransition = instantScroll && ctrlKey; var isFirstIteration = true; var easing = 'linear'; var decreaseScroll; var finishedCondition; var scrollActionFinsished = function(transition) { if(_scrollbarsHandleAsync) refreshScrollbarHandleOffset(isHorizontal, transition); }; var scrollActionInstantFinished = function() { scrollActionFinsished(); onHandleMouseTouchDown(event); }; var scrollAction = function () { if(!_destroyed) { var mouseOffset = (mouseDownOffset - trackOffset) * mouseDownInvertedScale; var handleOffset = scrollbarVarsInfo._handleOffset; var trackLength = scrollbarVarsInfo._trackLength; var handleLength = scrollbarVarsInfo._handleLength; var scrollRange = scrollbarVarsInfo._maxScroll; var currScroll = scrollbarVarsInfo._currentScroll; var scrollDuration = 270 * scrollDurationFactor; var timeoutDelay = isFirstIteration ? MATH.max(400, scrollDuration) : scrollDuration; var instantScrollPosition = scrollRange * ((mouseOffset - (handleLength / 2)) / (trackLength - handleLength)); // 100% * positionPercent var rtlIsNormal = _isRTL && isHorizontal && ((!_rtlScrollBehavior.i && !_rtlScrollBehavior.n) || _normalizeRTLCache); var decreaseScrollCondition = rtlIsNormal ? handleOffset < mouseOffset : handleOffset > mouseOffset; var scrollObj = { }; var animationObj = { easing : easing, step : function(now) { if(_scrollbarsHandleAsync) { _viewportElement[scroll](now); //https://github.com/jquery/jquery/issues/4340 refreshScrollbarHandleOffset(isHorizontal, now); } } }; instantScrollPosition = isFinite(instantScrollPosition) ? instantScrollPosition : 0; instantScrollPosition = _isRTL && isHorizontal && !_rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition; //_base.scrollStop(); if(instantScroll) { _viewportElement[scroll](instantScrollPosition); //scroll instantly to new position if(instantScrollTransition) { //get the scroll position after instant scroll (in case CSS Snap Points are used) to get the correct snapped scroll position //and the animation stops at the correct point instantScrollPosition = _viewportElement[scroll](); //scroll back to the position before instant scrolling so animation can be performed _viewportElement[scroll](currScroll); instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition; instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.n ? -instantScrollPosition : instantScrollPosition; scrollObj[xy] = instantScrollPosition; _base.scroll(scrollObj, extendDeep(animationObj, { duration : 130, complete : scrollActionInstantFinished })); } else scrollActionInstantFinished(); } else { decreaseScroll = isFirstIteration ? decreaseScrollCondition : decreaseScroll; finishedCondition = rtlIsNormal ? (decreaseScroll ? handleOffset + handleLength >= mouseOffset : handleOffset <= mouseOffset) : (decreaseScroll ? handleOffset <= mouseOffset : handleOffset + handleLength >= mouseOffset); if (finishedCondition) { clearTimeout(trackTimeout); _base.scrollStop(); trackTimeout = undefined; scrollActionFinsished(true); } else { trackTimeout = setTimeout(scrollAction, timeoutDelay); scrollObj[xy] = (decreaseScroll ? '-=' : '+=') + scrollDistance; _base.scroll(scrollObj, extendDeep(animationObj, { duration: scrollDuration })); } isFirstIteration = false; } } }; if (ctrlKey) increaseTrackScrollAmount(); mouseDownInvertedScale = getHostElementInvertedScale()[xy]; mouseDownOffset = COMPATIBILITY.page(event)[xy]; _scrollbarsHandleAsync = !getPreparedScrollbarsOption(strSnapHandle); addClass(_bodyElement, _classNameDragging); addClass(scrollbarVars._track, strActive); addClass(scrollbarVars._scrollbar, strActive); _documentElement.on(_strMouseTouchUpEvent, documentMouseTouchUp) .on(_strKeyDownEvent, documentKeyDown) .on(_strKeyUpEvent, documentKeyUp) .on(_strSelectStartEvent, documentOnSelectStart); scrollAction(); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } }).on(_strMouseTouchEnter, function() { //make sure both scrollbars will stay visible if one scrollbar is hovered if autoHide is "scroll" or "move". _scrollbarsHandleHovered = true; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(true); }).on(_strMouseTouchLeave, function() { _scrollbarsHandleHovered = false; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); }); scrollbarVars._scrollbar.on(_strMouseTouchDownEvent, function(event) { COMPATIBILITY.stpP(event); }); if (_supportTransition) { scrollbarVars._scrollbar.on(_strTransitionEndEvent, function(event) { if (event.target !== scrollbarVars._scrollbar[0]) return; refreshScrollbarHandleLength(isHorizontal); refreshScrollbarHandleOffset(isHorizontal); }); } } /** * Shows or hides the given scrollbar and applied a class name which indicates if the scrollbar is scrollable or not. * @param isHorizontal True if the horizontal scrollbar is the target, false if the vertical scrollbar is the target. * @param shallBeVisible True if the scrollbar shall be shown, false if hidden. * @param canScroll True if the scrollbar is scrollable, false otherwise. */ function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) { var scrollbarClassName = isHorizontal ? _classNameHostScrollbarHorizontalHidden : _classNameHostScrollbarVerticalHidden; var scrollbarElement = isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement; if (shallBeVisible) removeClass(_hostElement, scrollbarClassName); else addClass(_hostElement, scrollbarClassName); if (canScroll) removeClass(scrollbarElement, _classNameScrollbarUnusable); else addClass(scrollbarElement, _classNameScrollbarUnusable); } /** * Autoshows / autohides both scrollbars with. * @param shallBeVisible True if the scrollbars shall be autoshown (only the case if they are hidden by a autohide), false if the shall be auto hidden. * @param delayfree True if the scrollbars shall be hidden without a delay, false or undefined otherwise. */ function refreshScrollbarsAutoHide(shallBeVisible, delayfree) { clearTimeout(_scrollbarsAutoHideTimeoutId); if (shallBeVisible) { //if(_hasOverflowCache.x && _hideOverflowCache.xs) removeClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden); //if(_hasOverflowCache.y && _hideOverflowCache.ys) removeClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden); } else { var anyActive; var strActive = 'active'; var hide = function () { if (!_scrollbarsHandleHovered && !_destroyed) { anyActive = _scrollbarHorizontalHandleElement.hasClass(strActive) || _scrollbarVerticalHandleElement.hasClass(strActive); if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave)) addClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden); if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave)) addClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden); } }; if (_scrollbarsAutoHideDelay > 0 && delayfree !== true) _scrollbarsAutoHideTimeoutId = setTimeout(hide, _scrollbarsAutoHideDelay); else hide(); } } /** * Refreshes the handle length of the given scrollbar. * @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed. */ function refreshScrollbarHandleLength(isHorizontal) { var handleCSS = {}; var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var digit = 1000000; //get and apply intended handle length var handleRatio = MATH.min(1, (_hostSizeCache[scrollbarVars._w_h] - (_paddingAbsoluteCache ? (isHorizontal ? _paddingX : _paddingY) : 0)) / _contentScrollSizeCache[scrollbarVars._w_h]); handleCSS[scrollbarVars._width_height] = (MATH.floor(handleRatio * 100 * digit) / digit) + "%"; //the last * digit / digit is for flooring to the 4th digit if (!nativeOverlayScrollbarsAreActive()) scrollbarVars._handle.css(handleCSS); //measure the handle length to respect min & max length scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height]; scrollbarVarsInfo._handleLengthRatio = handleRatio; } /** * Refreshes the handle offset of the given scrollbar. * @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed. * @param scrollOrTransition The scroll position of the given scrollbar axis to which the handle shall be moved or a boolean which indicates whether a transition shall be applied. If undefined or boolean if the current scroll-offset is taken. (if isHorizontal ? scrollLeft : scrollTop) */ function refreshScrollbarHandleOffset(isHorizontal, scrollOrTransition) { var transition = type(scrollOrTransition) == TYPES.b; var transitionDuration = 250; var isRTLisHorizontal = _isRTL && isHorizontal; var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var strTranslateBrace = 'translate('; var strTransform = VENDORS._cssProperty('transform'); var strTransition = VENDORS._cssProperty('transition'); var nativeScroll = isHorizontal ? _viewportElement[_strScrollLeft]() : _viewportElement[_strScrollTop](); var currentScroll = scrollOrTransition === undefined || transition ? nativeScroll : scrollOrTransition; //measure the handle length to respect min & max length var handleLength = scrollbarVarsInfo._handleLength; var trackLength = scrollbarVars._track[0]['offset' + scrollbarVars._Width_Height]; var handleTrackDiff = trackLength - handleLength; var handleCSS = {}; var transformOffset; var translateValue; //DONT use the variable '_contentScrollSizeCache[scrollbarVars._w_h]' instead of '_viewportElement[0]['scroll' + scrollbarVars._Width_Height]' // because its a bit behind during the small delay when content size updates //(delay = mutationObserverContentLag, if its 0 then this var could be used) var maxScroll = (_viewportElementNative[_strScroll + scrollbarVars._Width_Height] - _viewportElementNative['client' + scrollbarVars._Width_Height]) * (_rtlScrollBehavior.n && isRTLisHorizontal ? -1 : 1); //* -1 if rtl scroll max is negative var getScrollRatio = function(base) { return isNaN(base / maxScroll) ? 0 : MATH.max(0, MATH.min(1, base / maxScroll)); }; var getHandleOffset = function(scrollRatio) { var offset = handleTrackDiff * scrollRatio; offset = isNaN(offset) ? 0 : offset; offset = (isRTLisHorizontal && !_rtlScrollBehavior.i) ? (trackLength - handleLength - offset) : offset; offset = MATH.max(0, offset); return offset; }; var scrollRatio = getScrollRatio(nativeScroll); var unsnappedScrollRatio = getScrollRatio(currentScroll); var handleOffset = getHandleOffset(unsnappedScrollRatio); var snappedHandleOffset = getHandleOffset(scrollRatio); scrollbarVarsInfo._maxScroll = maxScroll; scrollbarVarsInfo._currentScroll = nativeScroll; scrollbarVarsInfo._currentScrollRatio = scrollRatio; if (_supportTransform) { transformOffset = isRTLisHorizontal ? -(trackLength - handleLength - handleOffset) : handleOffset; //in px //transformOffset = (transformOffset / trackLength * 100) * (trackLength / handleLength); //in % translateValue = isHorizontal ? strTranslateBrace + transformOffset + 'px, 0)' : strTranslateBrace + '0, ' + transformOffset + 'px)'; handleCSS[strTransform] = translateValue; //apply or clear up transition if(_supportTransition) handleCSS[strTransition] = transition && MATH.abs(handleOffset - scrollbarVarsInfo._handleOffset) > 1 ? getCSSTransitionString(scrollbarVars._handle) + ', ' + (strTransform + _strSpace + transitionDuration + 'ms') : _strEmpty; } else handleCSS[scrollbarVars._left_top] = handleOffset; //only apply css if offset has changed and overflow exists. if (!nativeOverlayScrollbarsAreActive()) { scrollbarVars._handle.css(handleCSS); //clear up transition if(_supportTransform && _supportTransition && transition) { scrollbarVars._handle.one(_strTransitionEndEvent, function() { if(!_destroyed) scrollbarVars._handle.css(strTransition, _strEmpty); }); } } scrollbarVarsInfo._handleOffset = handleOffset; scrollbarVarsInfo._snappedHandleOffset = snappedHandleOffset; scrollbarVarsInfo._trackLength = trackLength; } /** * Refreshes the interactivity of the given scrollbar element. * @param isTrack True if the track element is the target, false if the handle element is the target. * @param value True for interactivity false for no interactivity. */ function refreshScrollbarsInteractive(isTrack, value) { var action = value ? 'removeClass' : 'addClass'; var element1 = isTrack ? _scrollbarHorizontalTrackElement : _scrollbarHorizontalHandleElement; var element2 = isTrack ? _scrollbarVerticalTrackElement : _scrollbarVerticalHandleElement; var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff; element1[action](className); element2[action](className); } /** * Returns a object which is used for fast access for specific variables. * @param isHorizontal True if the horizontal scrollbar vars shall be accessed, false if the vertical scrollbar vars shall be accessed. * @returns {{wh: string, WH: string, lt: string, _wh: string, _lt: string, t: *, h: *, c: {}, s: *}} */ function getScrollbarVars(isHorizontal) { return { _width_height: isHorizontal ? _strWidth : _strHeight, _Width_Height: isHorizontal ? 'Width' : 'Height', _left_top: isHorizontal ? _strLeft : _strTop, _Left_Top: isHorizontal ? 'Left' : 'Top', _x_y: isHorizontal ? _strX : _strY, _X_Y: isHorizontal ? 'X' : 'Y', _w_h: isHorizontal ? 'w' : 'h', _l_t: isHorizontal ? 'l' : 't', _track: isHorizontal ? _scrollbarHorizontalTrackElement : _scrollbarVerticalTrackElement, _handle: isHorizontal ? _scrollbarHorizontalHandleElement : _scrollbarVerticalHandleElement, _scrollbar: isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement, _info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo }; } //==== Scrollbar Corner ====// /** * Builds or destroys the scrollbar corner DOM element. * @param destroy Indicates whether the DOM shall be build or destroyed. */ function setupScrollbarCornerDOM(destroy) { if(!destroy) { _scrollbarCornerElement = FRAMEWORK(generateDiv(_classNameScrollbarCorner)); _hostElement.append(_scrollbarCornerElement); } else { remove(_scrollbarCornerElement); } } /** * Initializes all scrollbar corner interactivity events. */ function setupScrollbarCornerEvents() { var insideIFrame = _windowElementNative.top !== _windowElementNative; var mouseDownPosition = { }; var mouseDownSize = { }; var mouseDownInvertedScale = { }; _resizeOnMouseTouchDown = function(event) { if (onMouseTouchDownContinue(event)) { if (_mutationObserversConnected) { _resizeReconnectMutationObserver = true; disconnectMutationObservers(); } mouseDownPosition = getCoordinates(event); mouseDownSize.w = _hostElementNative[LEXICON.oW] - (!_isBorderBox ? _paddingX : 0); mouseDownSize.h = _hostElementNative[LEXICON.oH] - (!_isBorderBox ? _paddingY : 0); mouseDownInvertedScale = getHostElementInvertedScale(); _documentElement.on(_strSelectStartEvent, documentOnSelectStart) .on(_strMouseTouchMoveEvent, documentDragMove) .on(_strMouseTouchUpEvent, documentMouseTouchUp); addClass(_bodyElement, _classNameDragging); if (_scrollbarCornerElement.setCapture) _scrollbarCornerElement.setCapture(); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } }; function documentDragMove(event) { if (onMouseTouchDownContinue(event)) { var pageOffset = getCoordinates(event); var hostElementCSS = { }; if (_resizeHorizontal || _resizeBoth) hostElementCSS[_strWidth] = (mouseDownSize.w + (pageOffset.x - mouseDownPosition.x) * mouseDownInvertedScale.x); if (_resizeVertical || _resizeBoth) hostElementCSS[_strHeight] = (mouseDownSize.h + (pageOffset.y - mouseDownPosition.y) * mouseDownInvertedScale.y); _hostElement.css(hostElementCSS); COMPATIBILITY.stpP(event); } else { documentMouseTouchUp(event); } } function documentMouseTouchUp(event) { var eventIsTrusted = event !== undefined; _documentElement.off(_strSelectStartEvent, documentOnSelectStart) .off(_strMouseTouchMoveEvent, documentDragMove) .off(_strMouseTouchUpEvent, documentMouseTouchUp); removeClass(_bodyElement, _classNameDragging); if (_scrollbarCornerElement.releaseCapture) _scrollbarCornerElement.releaseCapture(); if (eventIsTrusted) { if (_resizeReconnectMutationObserver) connectMutationObservers(); _base.update(_strAuto); } _resizeReconnectMutationObserver = false; } function onMouseTouchDownContinue(event) { var originalEvent = event.originalEvent || event; var isTouchEvent = originalEvent.touches !== undefined; return _isSleeping || _destroyed ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent; } function getCoordinates(event) { return _msieVersion && insideIFrame ? { x : event.screenX , y : event.screenY } : COMPATIBILITY.page(event); } } //==== Utils ====// /** * Calls the callback with the given name. The Context of this callback is always _base (this). * @param name The name of the target which shall be called. * @param args The args with which the callback shall be called. */ function dispatchCallback(name, args) { if(_initialized) { var callback = _currentPreparedOptions.callbacks[name]; var extensionOnName = name; var ext; if(extensionOnName.substr(0, 2) === "on") extensionOnName = extensionOnName.substr(2, 1).toLowerCase() + extensionOnName.substr(3); if(type(callback) == TYPES.f) callback.call(_base, args); FRAMEWORK.each(_extensions, function() { ext = this; if(type(ext.on) == TYPES.f) ext.on(extensionOnName, args); }); } else if(!_destroyed) _callbacksInitQeueue.push({ n : name, a : args }); } /** * Sets the "top, right, bottom, left" properties, with a given prefix, of the given css object. * @param targetCSSObject The css object to which the values shall be applied. * @param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix) * @param values A array of values which shall be applied to the "top, right, bottom, left" -properties. The array order is [top, right, bottom, left]. * If this argument is undefined the value '' (empty string) will be applied to all properties. */ function setTopRightBottomLeft(targetCSSObject, prefix, values) { if (values === undefined) values = [_strEmpty, _strEmpty, _strEmpty, _strEmpty]; targetCSSObject[prefix + _strTop] = values[0]; targetCSSObject[prefix + _strRight] = values[1]; targetCSSObject[prefix + _strBottom] = values[2]; targetCSSObject[prefix + _strLeft] = values[3]; } /** * Returns the computed CSS transition string from the given element. * @param element The element from which the transition string shall be returned. * @returns {string} The CSS transition string from the given element. */ function getCSSTransitionString(element) { var transitionStr = VENDORS._cssProperty('transition'); var assembledValue = element.css(transitionStr); if(assembledValue) return assembledValue; var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*'; var regExpMain = new RegExp(regExpString); var regExpValidate = new RegExp('^(' + regExpString + ')+$'); var properties = 'property duration timing-function delay'.split(' '); var result = [ ]; var strResult; var valueArray; var i = 0; var j; var splitCssStyleByComma = function(str) { strResult = [ ]; if (!str.match(regExpValidate)) return str; while (str.match(regExpMain)) { strResult.push(RegExp.$1); str = str.replace(regExpMain, _strEmpty); } return strResult; }; for (; i < properties[LEXICON.l]; i++) { valueArray = splitCssStyleByComma(element.css(transitionStr + '-' + properties[i])); for (j = 0; j < valueArray[LEXICON.l]; j++) result[j] = (result[j] ? result[j] + _strSpace : _strEmpty) + valueArray[j]; } return result.join(', '); } /** * Calculates the host-elements inverted scale. (invertedScale = 1 / scale) * @returns {{x: number, y: number}} The scale of the host-element. */ function getHostElementInvertedScale() { var rect = _paddingElementNative.getBoundingClientRect(); return { x : _supportTransform ? 1 / (MATH.round(rect.width) / _paddingElementNative[LEXICON.oW]) || 1 : 1, y : _supportTransform ? 1 / (MATH.round(rect.height) / _paddingElementNative[LEXICON.oH]) || 1 : 1 }; } /** * Checks whether the given object is a HTMLElement. * @param o The object which shall be checked. * @returns {boolean} True the given object is a HTMLElement, false otherwise. */ function isHTMLElement(o) { var strOwnerDocument = 'ownerDocument'; var strHTMLElement = 'HTMLElement'; var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window; return ( typeof wnd[strHTMLElement] == TYPES.o ? o instanceof wnd[strHTMLElement] : //DOM2 o && typeof o == TYPES.o && o !== null && o.nodeType === 1 && typeof o.nodeName == TYPES.s ); } /** * Compares 2 arrays and returns the differences between them as a array. * @param a1 The first array which shall be compared. * @param a2 The second array which shall be compared. * @returns {Array} The differences between the two arrays. */ function getArrayDifferences(a1, a2) { var a = [ ]; var diff = [ ]; var i; var k; for (i = 0; i < a1.length; i++) a[a1[i]] = true; for (i = 0; i < a2.length; i++) { if (a[a2[i]]) delete a[a2[i]]; else a[a2[i]] = true; } for (k in a) diff.push(k); return diff; } /** * Returns Zero or the number to which the value can be parsed. * @param value The value which shall be parsed. * @param toFloat Indicates whether the number shall be parsed to a float. */ function parseToZeroOrNumber(value, toFloat) { var num = toFloat ? parseFloat(value) : parseInt(value, 10); return isNaN(num) ? 0 : num; } /** * Gets several information of the textarea and returns them as a object or undefined if the browser doesn't support it. * @returns {{cursorRow: Number, cursorCol, rows: Number, cols: number, wRow: number, pos: number, max : number}} or undefined if not supported. */ function getTextareaInfo() { //read needed values var textareaCursorPosition = _targetElementNative.selectionStart; if (textareaCursorPosition === undefined) return; var strLength = 'length'; var textareaValue = _targetElement.val(); var textareaLength = textareaValue[strLength]; var textareaRowSplit = textareaValue.split("\n"); var textareaLastRow = textareaRowSplit[strLength]; var textareaCurrentCursorRowSplit = textareaValue.substr(0, textareaCursorPosition).split("\n"); var widestRow = 0; var textareaLastCol = 0; var cursorRow = textareaCurrentCursorRowSplit[strLength]; var cursorCol = textareaCurrentCursorRowSplit[textareaCurrentCursorRowSplit[strLength] - 1][strLength]; var rowCols; var i; //get widest Row and the last column of the textarea for (i = 0; i < textareaRowSplit[strLength]; i++) { rowCols = textareaRowSplit[i][strLength]; if (rowCols > textareaLastCol) { widestRow = i + 1; textareaLastCol = rowCols; } } return { _cursorRow: cursorRow, //cursorRow _cursorColumn: cursorCol, //cursorCol _rows: textareaLastRow, //rows _columns: textareaLastCol, //cols _widestRow: widestRow, //wRow _cursorPosition: textareaCursorPosition, //pos _cursorMax: textareaLength //max }; } /** * Determines whether native overlay scrollbars are active. * @returns {boolean} True if native overlay scrollbars are active, false otherwise. */ function nativeOverlayScrollbarsAreActive() { return (_ignoreOverlayScrollbarHidingCache && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)); } /** * Gets the element which is used to measure the content size. * @returns {*} TextareaCover if target element is textarea else the ContentElement. */ function getContentMeasureElement() { return _isTextarea ? _textareaCoverElement[0] : _contentElementNative; } /** * Generates a string which represents a HTML div with the given classes or attributes. * @param classesOrAttrs The class of the div as string or a object which represents the attributes of the div. (The class attribute can also be written as "className".) * @param content The content of the div as string. * @returns {string} The concated string which represents a HTML div and its content. */ function generateDiv(classesOrAttrs, content) { return '<div ' + (classesOrAttrs ? type(classesOrAttrs) == TYPES.s ? 'class="' + classesOrAttrs + '"' : (function() { var key; var attrs = ''; if(FRAMEWORK.isPlainObject(classesOrAttrs)) { for (key in classesOrAttrs) attrs += (key === 'className' ? 'class' : key) + '="' + classesOrAttrs[key] + '" '; } return attrs; })() : _strEmpty) + '>' + (content ? content : _strEmpty) + '</div>'; } /** * Gets the value of the given property from the given object. * @param obj The object from which the property value shall be got. * @param path The property of which the value shall be got. * @returns {*} Returns the value of the searched property or undefined of the property wasn't found. */ function getObjectPropVal(obj, path) { var splits = path.split(_strDot); var i = 0; var val; for(; i < splits.length; i++) { if(!obj.hasOwnProperty(splits[i])) return; val = obj[splits[i]]; if(i < splits.length && type(val) == TYPES.o) obj = val; } return val; } /** * Sets the value of the given property from the given object. * @param obj The object from which the property value shall be set. * @param path The property of which the value shall be set. * @param val The value of the property which shall be set. */ function setObjectPropVal(obj, path, val) { var splits = path.split(_strDot); var splitsLength = splits.length; var i = 0; var extendObj = { }; var extendObjRoot = extendObj; for(; i < splitsLength; i++) extendObj = extendObj[splits[i]] = i + 1 < splitsLength ? { } : val; FRAMEWORK.extend(obj, extendObjRoot, true); } //==== Utils Cache ====// /** * Compares two values and returns the result of the comparison as a boolean. * @param current The first value which shall be compared. * @param cache The second value which shall be compared. * @param force If true the returned value is always true. * @returns {boolean} True if both variables aren't equal or some of them is undefined or when the force parameter is true, false otherwise. */ function checkCacheSingle(current, cache, force) { if (force === true) return force; if (cache === undefined) return true; else if (current !== cache) return true; return false; } /** * Compares two objects with two properties and returns the result of the comparison as a boolean. * @param current The first object which shall be compared. * @param cache The second object which shall be compared. * @param prop1 The name of the first property of the objects which shall be compared. * @param prop2 The name of the second property of the objects which shall be compared. * @param force If true the returned value is always true. * @returns {boolean} True if both variables aren't equal or some of them is undefined or when the force parameter is true, false otherwise. */ function checkCacheDouble(current, cache, prop1, prop2, force) { if (force === true) return force; if (prop2 === undefined && force === undefined) { if (prop1 === true) return prop1; else prop1 = undefined; } prop1 = prop1 === undefined ? 'w' : prop1; prop2 = prop2 === undefined ? 'h' : prop2; if (cache === undefined) return true; else if (current[prop1] !== cache[prop1] || current[prop2] !== cache[prop2]) return true; return false; } /** * Compares two objects which have four properties and returns the result of the comparison as a boolean. * @param current The first object with four properties. * @param cache The second object with four properties. * @returns {boolean} True if both objects aren't equal or some of them is undefined, false otherwise. */ function checkCacheTRBL(current, cache) { if (cache === undefined) return true; else if (current.t !== cache.t || current.r !== cache.r || current.b !== cache.b || current.l !== cache.l) return true; return false; } //==== Shortcuts ====// /** * jQuery type method shortcut. */ function type(obj) { return COMPATIBILITY.type(obj); } /** * jQuery extend method shortcut with a appended "true" as first argument. */ function extendDeep() { return FRAMEWORK.extend.apply(this, [ true ].concat([].slice.call(arguments))); } /** * jQuery addClass method shortcut. */ function addClass(el, classes) { return _frameworkProto.addClass.call(el, classes); } /** * jQuery removeClass method shortcut. */ function removeClass(el, classes) { return _frameworkProto.removeClass.call(el, classes); } /** * jQuery remove method shortcut. */ function remove(el) { return _frameworkProto.remove.call(el); } /** * Finds the first child element with the given selector of the given element. * @param el The root element from which the selector shall be valid. * @param selector The selector of the searched element. * @returns {*} The first element which is a child of the given element and matches the givens selector. */ function findFirst(el, selector) { return _frameworkProto.find.call(el, selector).eq(0); } //==== API ====// /** * Puts the instance to sleep. It wont respond to any changes in the DOM and won't update. Scrollbar Interactivity is also disabled as well as the resize handle. * This behavior can be reset by calling the update method. */ _base.sleep = function () { _isSleeping = true; }; /** * Updates the plugin and DOM to the current options. * This method should only be called if a update is 100% required. * @param force True if every property shall be updated and the cache shall be ignored. * !INTERNAL USAGE! : force can be a string "auto", "auto+" or "zoom" too * if this is the case then before a real update the content size and host element attributes gets checked, and if they changed only then the update method will be called. */ _base.update = function (force) { var attrsChanged; var contentSizeC; var isString = type(force) == TYPES.s; var imgElementSelector = 'img'; var imgElementLoadEvent = 'load'; if(isString) { if (force === _strAuto) { attrsChanged = meaningfulAttrsChanged(); contentSizeC = updateAutoContentSizeChanged(); if (attrsChanged || contentSizeC) update(false, contentSizeC, false); } else if (force === 'zoom') update(true, true); } else if(!synchronizeMutationObservers() || force) { force = _isSleeping || force; _isSleeping = false; update(false, false, force, true); } if(!_isTextarea) { _contentElement.find(imgElementSelector).each(function(i, el) { var index = COMPATIBILITY.inA(el, _imgs); if (index === -1) FRAMEWORK(el).off(imgElementLoadEvent, imgOnLoad).on(imgElementLoadEvent, imgOnLoad); }); } }; /** Gets or sets the current options. The update method will be called automatically if new options were set. * @param newOptions If new options are given, then the new options will be set, if new options aren't given (undefined or a not a plain object) then the current options will be returned. * @param value If new options is a property path string, then this value will be used to set the option to which the property path string leads. * @returns {*} */ _base.options = function (newOptions, value) { //return current options if newOptions are undefined or empty if (FRAMEWORK.isEmptyObject(newOptions) || !FRAMEWORK.isPlainObject(newOptions)) { if (type(newOptions) == TYPES.s) { if (arguments.length > 1) { var option = { }; setObjectPropVal(option, newOptions, value); setOptions(option); update(); return; } else return getObjectPropVal(_currentOptions, newOptions); } else return _currentOptions; } setOptions(newOptions); var isSleepingTmp = _isSleeping || false; _isSleeping = false; update(); _isSleeping = isSleepingTmp; }; /** * Restore the DOM, disconnects all observers, remove all resize observers and destroy all methods. */ _base.destroy = function () { _destroyed = true; //remove this instance from auto update loop autoUpdateLoop.remove(_base); //disconnect all mutation observers disconnectMutationObservers(); //remove all resize observers removeResizeObserver(_sizeObserverElement); if (_sizeAutoObserverAdded) removeResizeObserver(_sizeAutoObserverElement); //remove all extensions for(var extName in _extensions) _base.removeExt(extName); //remove all events from host element setupHostMouseTouchEvents(true); //remove all events from structure setupStructureEvents(true); //remove all helper / detection elements if (_contentGlueElement) remove(_contentGlueElement); if (_contentArrangeElement) remove(_contentArrangeElement); if (_sizeAutoObserverAdded) remove(_sizeAutoObserverElement); //remove all generated DOM setupScrollbarsDOM(true); setupScrollbarCornerDOM(true); setupStructureDOM(true); //remove all generated image load events for(var i = 0; i < _imgs[LEXICON.l]; i++) FRAMEWORK(_imgs[i]).off('load', imgOnLoad); _imgs = undefined; //remove this instance from the instances list INSTANCES(pluginTargetElement, 0); dispatchCallback("onDestroyed"); //remove all properties and methods for (var property in _base) delete _base[property]; _base = undefined; }; /** * Scrolls to a given position or element. * @param coordinates * 1. Can be "coordinates" which looks like: * { x : ?, y : ? } OR Object with x and y properties * { left : ?, top : ? } OR Object with left and top properties * { l : ?, t : ? } OR Object with l and t properties * [ ?, ? ] OR Array where the first two element are the coordinates (first is x, second is y) * ? A single value which stays for both axis * A value can be a number, a string or a calculation. * * Operators: * [NONE] The current scroll will be overwritten by the value. * '+=' The value will be added to the current scroll offset * '-=' The value will be subtracted from the current scroll offset * '*=' The current scroll wil be multiplicated by the value. * '/=' The current scroll wil be divided by the value. * * Units: * [NONE] The value is the final scroll amount. final = (value * 1) * 'px' Same as none * '%' The value is dependent on the current scroll value. final = ((currentScrollValue / 100) * value) * 'vw' The value is multiplicated by the viewport width. final = (value * viewportWidth) * 'vh' The value is multiplicated by the viewport height. final = (value * viewportHeight) * * example final values: * 200, '200px', '50%', '1vw', '1vh', '+=200', '/=1vw', '*=2px', '-=5vh', '+=33%', '+= 50% - 2px', '-= 1vw - 50%' * * 2. Can be a HTML or jQuery element: * The final scroll offset is the offset (without margin) of the given HTML / jQuery element. * * 3. Can be a object with a HTML or jQuery element with additional settings: * { * el : [HTMLElement, jQuery element], MUST be specified, else this object isn't valid. * scroll : [string, array, object], Default value is 'always'. * block : [string, array, object], Default value is 'begin'. * margin : [number, boolean, array, object] Default value is false. * } * * Possible scroll settings are: * 'always' Scrolls always. * 'ifneeded' Scrolls only if the element isnt fully in view. * 'never' Scrolls never. * * Possible block settings are: * 'begin' Both axis shall be docked to the "begin" edge. - The element will be docked to the top and left edge of the viewport. * 'end' Both axis shall be docked to the "end" edge. - The element will be docked to the bottom and right edge of the viewport. (If direction is RTL to the bottom and left edge.) * 'center' Both axis shall be docked to "center". - The element will be centered in the viewport. * 'nearest' The element will be docked to the nearest edge(s). * * Possible margin settings are: -- The actual margin of the element wont be affect, this option affects only the final scroll offset. * [BOOLEAN] If true the css margin of the element will be used, if false no margin will be used. * [NUMBER] The margin will be used for all edges. * * @param duration The duration of the scroll animation, OR a jQuery animation configuration object. * @param easing The animation easing. * @param complete The animation complete callback. * @returns {{ * position: {x: number, y: number}, * ratio: {x: number, y: number}, * max: {x: number, y: number}, * handleOffset: {x: number, y: number}, * handleLength: {x: number, y: number}, * handleLengthRatio: {x: number, y: number}, t * rackLength: {x: number, y: number}, * isRTL: boolean, * isRTLNormalized: boolean * }} */ _base.scroll = function (coordinates, duration, easing, complete) { if (arguments.length === 0 || coordinates === undefined) { var infoX = _scrollHorizontalInfo; var infoY = _scrollVerticalInfo; var normalizeInvert = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.i; var normalizeNegate = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.n; var scrollX = infoX._currentScroll; var scrollXRatio = infoX._currentScrollRatio; var maxScrollX = infoX._maxScroll; scrollXRatio = normalizeInvert ? 1 - scrollXRatio : scrollXRatio; scrollX = normalizeInvert ? maxScrollX - scrollX : scrollX; scrollX *= normalizeNegate ? -1 : 1; maxScrollX *= normalizeNegate ? -1 : 1; return { position : { x : scrollX, y : infoY._currentScroll }, ratio : { x : scrollXRatio, y : infoY._currentScrollRatio }, max : { x : maxScrollX, y : infoY._maxScroll }, handleOffset : { x : infoX._handleOffset, y : infoY._handleOffset }, handleLength : { x : infoX._handleLength, y : infoY._handleLength }, handleLengthRatio : { x : infoX._handleLengthRatio, y : infoY._handleLengthRatio }, trackLength : { x : infoX._trackLength, y : infoY._trackLength }, snappedHandleOffset : { x : infoX._snappedHandleOffset, y : infoY._snappedHandleOffset }, isRTL: _isRTL, isRTLNormalized: _normalizeRTLCache }; } synchronizeMutationObservers(); var normalizeRTL = _normalizeRTLCache; var coordinatesXAxisProps = [_strX, _strLeft, 'l']; var coordinatesYAxisProps = [_strY, _strTop, 't']; var coordinatesOperators = ['+=', '-=', '*=', '/=']; var durationIsObject = type(duration) == TYPES.o; var completeCallback = durationIsObject ? duration.complete : complete; var i; var finalScroll = { }; var specialEasing = {}; var doScrollLeft; var doScrollTop; var animationOptions; var strEnd = 'end'; var strBegin = 'begin'; var strCenter = 'center'; var strNearest = 'nearest'; var strAlways = 'always'; var strNever = 'never'; var strIfNeeded = 'ifneeded'; var strLength = LEXICON.l; var settingsAxis; var settingsScroll; var settingsBlock; var settingsMargin; var finalElement; var elementObjSettingsAxisValues = [_strX, _strY, 'xy', 'yx']; var elementObjSettingsBlockValues = [strBegin, strEnd, strCenter, strNearest]; var elementObjSettingsScrollValues = [strAlways, strNever, strIfNeeded]; var coordinatesIsElementObj = coordinates.hasOwnProperty('el'); var possibleElement = coordinatesIsElementObj ? coordinates.el : coordinates; var possibleElementIsJQuery = possibleElement instanceof FRAMEWORK || JQUERY ? possibleElement instanceof JQUERY : false; var possibleElementIsHTMLElement = possibleElementIsJQuery ? false : isHTMLElement(possibleElement); var proxyCompleteCallback = type(completeCallback) != TYPES.f ? undefined : function() { if(doScrollLeft) refreshScrollbarHandleOffset(true); if(doScrollTop) refreshScrollbarHandleOffset(false); completeCallback(); }; var checkSettingsStringValue = function (currValue, allowedValues) { for (i = 0; i < allowedValues[strLength]; i++) { if (currValue === allowedValues[i]) return true; } return false; }; var getRawScroll = function (isX, coordinates) { var coordinateProps = isX ? coordinatesXAxisProps : coordinatesYAxisProps; coordinates = type(coordinates) == TYPES.s || type(coordinates) == TYPES.n ? [ coordinates, coordinates ] : coordinates; if (type(coordinates) == TYPES.a) return isX ? coordinates[0] : coordinates[1]; else if (type(coordinates) == TYPES.o) { //decides RTL normalization "hack" with .n //normalizeRTL = type(coordinates.n) == TYPES.b ? coordinates.n : normalizeRTL; for (i = 0; i < coordinateProps[strLength]; i++) if (coordinateProps[i] in coordinates) return coordinates[coordinateProps[i]]; } }; var getFinalScroll = function (isX, rawScroll) { var isString = type(rawScroll) == TYPES.s; var operator; var amount; var scrollInfo = isX ? _scrollHorizontalInfo : _scrollVerticalInfo; var currScroll = scrollInfo._currentScroll; var maxScroll = scrollInfo._maxScroll; var mult = ' * '; var finalValue; var isRTLisX = _isRTL && isX; var normalizeShortcuts = isRTLisX && _rtlScrollBehavior.n && !normalizeRTL; var strReplace = 'replace'; var evalFunc = eval; var possibleOperator; if (isString) { //check operator if (rawScroll[strLength] > 2) { possibleOperator = rawScroll.substr(0, 2); if(FRAMEWORK.inArray(possibleOperator, coordinatesOperators) > -1) operator = possibleOperator; } //calculate units and shortcuts rawScroll = operator ? rawScroll.substr(2) : rawScroll; rawScroll = rawScroll [strReplace](/min/g, 0) //'min' = 0% [strReplace](/</g, 0) //'<' = 0% [strReplace](/max/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'max' = 100% [strReplace](/>/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'>' = 100% [strReplace](/px/g, _strEmpty) [strReplace](/%/g, mult + (maxScroll * (isRTLisX && _rtlScrollBehavior.n ? -1 : 1) / 100.0)) [strReplace](/vw/g, mult + _viewportSize.w) [strReplace](/vh/g, mult + _viewportSize.h); amount = parseToZeroOrNumber(isNaN(rawScroll) ? parseToZeroOrNumber(evalFunc(rawScroll), true).toFixed() : rawScroll); } else { amount = rawScroll; } if (amount !== undefined && !isNaN(amount) && type(amount) == TYPES.n) { var normalizeIsRTLisX = normalizeRTL && isRTLisX; var operatorCurrScroll = currScroll * (normalizeIsRTLisX && _rtlScrollBehavior.n ? -1 : 1); var invert = normalizeIsRTLisX && _rtlScrollBehavior.i; var negate = normalizeIsRTLisX && _rtlScrollBehavior.n; operatorCurrScroll = invert ? (maxScroll - operatorCurrScroll) : operatorCurrScroll; switch (operator) { case '+=': finalValue = operatorCurrScroll + amount; break; case '-=': finalValue = operatorCurrScroll - amount; break; case '*=': finalValue = operatorCurrScroll * amount; break; case '/=': finalValue = operatorCurrScroll / amount; break; default: finalValue = amount; break; } finalValue = invert ? maxScroll - finalValue : finalValue; finalValue *= negate ? -1 : 1; finalValue = isRTLisX && _rtlScrollBehavior.n ? MATH.min(0, MATH.max(maxScroll, finalValue)) : MATH.max(0, MATH.min(maxScroll, finalValue)); } return finalValue === currScroll ? undefined : finalValue; }; var getPerAxisValue = function (value, valueInternalType, defaultValue, allowedValues) { var resultDefault = [ defaultValue, defaultValue ]; var valueType = type(value); var valueArrLength; var valueArrItem; //value can be [ string, or array of two strings ] if (valueType == valueInternalType) { value = [value, value]; } else if (valueType == TYPES.a) { valueArrLength = value[strLength]; if (valueArrLength > 2 || valueArrLength < 1) value = resultDefault; else { if (valueArrLength === 1) value[1] = defaultValue; for (i = 0; i < valueArrLength; i++) { valueArrItem = value[i]; if (type(valueArrItem) != valueInternalType || !checkSettingsStringValue(valueArrItem, allowedValues)) { value = resultDefault; break; } } } } else if (valueType == TYPES.o) value = [ value[_strX]|| defaultValue, value[_strY] || defaultValue]; else value = resultDefault; return { x : value[0], y : value[1] }; }; var generateMargin = function (marginTopRightBottomLeftArray) { var result = [ ]; var currValue; var currValueType; var valueDirections = [ _strTop, _strRight, _strBottom, _strLeft ]; for(i = 0; i < marginTopRightBottomLeftArray[strLength]; i++) { if(i === valueDirections[strLength]) break; currValue = marginTopRightBottomLeftArray[i]; currValueType = type(currValue); if(currValueType == TYPES.b) result.push(currValue ? parseToZeroOrNumber(finalElement.css(_strMarginMinus + valueDirections[i])) : 0); else result.push(currValueType == TYPES.n ? currValue : 0); } return result; }; if (possibleElementIsJQuery || possibleElementIsHTMLElement) { //get settings var margin = coordinatesIsElementObj ? coordinates.margin : 0; var axis = coordinatesIsElementObj ? coordinates.axis : 0; var scroll = coordinatesIsElementObj ? coordinates.scroll : 0; var block = coordinatesIsElementObj ? coordinates.block : 0; var marginDefault = [ 0, 0, 0, 0 ]; var marginType = type(margin); var marginLength; finalElement = possibleElementIsJQuery ? possibleElement : FRAMEWORK(possibleElement); if (finalElement[strLength] === 0) return; //margin can be [ boolean, number, array of 2, array of 4, object ] if (marginType == TYPES.n || marginType == TYPES.b) margin = generateMargin([margin, margin, margin, margin]); else if (marginType == TYPES.a) { marginLength = margin[strLength]; if(marginLength === 2) margin = generateMargin([margin[0], margin[1], margin[0], margin[1]]); else if(marginLength >= 4) margin = generateMargin(margin); else margin = marginDefault; } else if (marginType == TYPES.o) margin = generateMargin([margin[_strTop], margin[_strRight], margin[_strBottom], margin[_strLeft]]); else margin = marginDefault; //block = type(block) === TYPES.b ? block ? [ strNearest, strBegin ] : [ strNearest, strEnd ] : block; settingsAxis = checkSettingsStringValue(axis, elementObjSettingsAxisValues) ? axis : 'xy'; settingsScroll = getPerAxisValue(scroll, TYPES.s, strAlways, elementObjSettingsScrollValues); settingsBlock = getPerAxisValue(block, TYPES.s, strBegin, elementObjSettingsBlockValues); settingsMargin = margin; var viewportScroll = { l: _scrollHorizontalInfo._currentScroll, t: _scrollVerticalInfo._currentScroll }; // use padding element instead of viewport element because padding element has never padding, margin or position applied. var viewportOffset = _paddingElement.offset(); //get coordinates var elementOffset = finalElement.offset(); var doNotScroll = { x : settingsScroll.x == strNever || settingsAxis == _strY, y : settingsScroll.y == strNever || settingsAxis == _strX }; elementOffset[_strTop] -= settingsMargin[0]; elementOffset[_strLeft] -= settingsMargin[3]; var elementScrollCoordinates = { x: MATH.round(elementOffset[_strLeft] - viewportOffset[_strLeft] + viewportScroll.l), y: MATH.round(elementOffset[_strTop] - viewportOffset[_strTop] + viewportScroll.t) }; if (_isRTL) { if (!_rtlScrollBehavior.n && !_rtlScrollBehavior.i) elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + viewportScroll.l); if (_rtlScrollBehavior.n && normalizeRTL) elementScrollCoordinates.x *= -1; if (_rtlScrollBehavior.i && normalizeRTL) elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + (_scrollHorizontalInfo._maxScroll - viewportScroll.l)); } //measuring is required if (settingsBlock.x != strBegin || settingsBlock.y != strBegin || settingsScroll.x == strIfNeeded || settingsScroll.y == strIfNeeded || _isRTL) { var measuringElm = finalElement[0]; var rawElementSize = _supportTransform ? measuringElm.getBoundingClientRect() : { width : measuringElm[LEXICON.oW], height : measuringElm[LEXICON.oH] }; var elementSize = { w: rawElementSize[_strWidth] + settingsMargin[3] + settingsMargin[1], h: rawElementSize[_strHeight] + settingsMargin[0] + settingsMargin[2] }; var finalizeBlock = function(isX) { var vars = getScrollbarVars(isX); var wh = vars._w_h; var lt = vars._left_top; var xy = vars._x_y; var blockIsEnd = settingsBlock[xy] == (isX ? _isRTL ? strBegin : strEnd : strEnd); var blockIsCenter = settingsBlock[xy] == strCenter; var blockIsNearest = settingsBlock[xy] == strNearest; var scrollNever = settingsScroll[xy] == strNever; var scrollIfNeeded = settingsScroll[xy] == strIfNeeded; var vpSize = _viewportSize[wh]; var vpOffset = viewportOffset[lt]; var elSize = elementSize[wh]; var elOffset = elementOffset[lt]; var divide = blockIsCenter ? 2 : 1; var elementCenterOffset = elOffset + (elSize / 2); var viewportCenterOffset = vpOffset + (vpSize / 2); var isInView = elSize <= vpSize && elOffset >= vpOffset && elOffset + elSize <= vpOffset + vpSize; if(scrollNever) doNotScroll[xy] = true; else if(!doNotScroll[xy]) { if (blockIsNearest || scrollIfNeeded) { doNotScroll[xy] = scrollIfNeeded ? isInView : false; blockIsEnd = elSize < vpSize ? elementCenterOffset > viewportCenterOffset : elementCenterOffset < viewportCenterOffset; } elementScrollCoordinates[xy] -= blockIsEnd || blockIsCenter ? ((vpSize / divide) - (elSize / divide)) * (isX && _isRTL && normalizeRTL ? -1 : 1) : 0; } }; finalizeBlock(true); finalizeBlock(false); } if (doNotScroll.y) delete elementScrollCoordinates.y; if (doNotScroll.x) delete elementScrollCoordinates.x; coordinates = elementScrollCoordinates; } finalScroll[_strScrollLeft] = getFinalScroll(true, getRawScroll(true, coordinates)); finalScroll[_strScrollTop] = getFinalScroll(false, getRawScroll(false, coordinates)); doScrollLeft = finalScroll[_strScrollLeft] !== undefined; doScrollTop = finalScroll[_strScrollTop] !== undefined; if ((doScrollLeft || doScrollTop) && (duration > 0 || durationIsObject)) { if (durationIsObject) { duration.complete = proxyCompleteCallback; _viewportElement.animate(finalScroll, duration); } else { animationOptions = { duration: duration, complete: proxyCompleteCallback }; if (type(easing) == TYPES.a || FRAMEWORK.isPlainObject(easing)) { specialEasing[_strScrollLeft] = easing[0] || easing.x; specialEasing[_strScrollTop] = easing[1] || easing.y; animationOptions.specialEasing = specialEasing; } else { animationOptions.easing = easing; } _viewportElement.animate(finalScroll, animationOptions); } } else { if (doScrollLeft) _viewportElement[_strScrollLeft](finalScroll[_strScrollLeft]); if (doScrollTop) _viewportElement[_strScrollTop](finalScroll[_strScrollTop]); } }; /** * Stops all scroll animations. * @returns {*} The current OverlayScrollbars instance (for chaining). */ _base.scrollStop = function (param1, param2, param3) { _viewportElement.stop(param1, param2, param3); return _base; }; /** * Returns all relevant elements. * @param elementName The name of the element which shall be returned. * @returns {{target: *, host: *, padding: *, viewport: *, content: *, scrollbarHorizontal: {scrollbar: *, track: *, handle: *}, scrollbarVertical: {scrollbar: *, track: *, handle: *}, scrollbarCorner: *} | *} */ _base.getElements = function (elementName) { var obj = { target: _targetElementNative, host: _hostElementNative, padding: _paddingElementNative, viewport: _viewportElementNative, content: _contentElementNative, scrollbarHorizontal: { scrollbar: _scrollbarHorizontalElement[0], track: _scrollbarHorizontalTrackElement[0], handle: _scrollbarHorizontalHandleElement[0] }, scrollbarVertical: { scrollbar: _scrollbarVerticalElement[0], track: _scrollbarVerticalTrackElement[0], handle: _scrollbarVerticalHandleElement[0] }, scrollbarCorner: _scrollbarCornerElement[0] }; return type(elementName) == TYPES.s ? getObjectPropVal(obj, elementName) : obj; }; /** * Returns a object which describes the current state of this instance. * @param stateProperty A specific property from the state object which shall be returned. * @returns {{widthAuto, heightAuto, overflowAmount, hideOverflow, hasOverflow, contentScrollSize, viewportSize, hostSize, autoUpdate} | *} */ _base.getState = function (stateProperty) { var prepare = function (obj) { if (!FRAMEWORK.isPlainObject(obj)) return obj; var extended = extendDeep({}, obj); var changePropertyName = function (from, to) { if (extended.hasOwnProperty(from)) { extended[to] = extended[from]; delete extended[from]; } }; changePropertyName('w', _strWidth); //change w to width changePropertyName('h', _strHeight); //change h to height delete extended.c; //delete c (the 'changed' prop) return extended; }; var obj = { sleeping: prepare(_isSleeping) || false, autoUpdate: prepare(!_mutationObserversConnected), widthAuto: prepare(_widthAutoCache), heightAuto: prepare(_heightAutoCache), padding: prepare(_cssPaddingCache), overflowAmount: prepare(_overflowAmountCache), hideOverflow: prepare(_hideOverflowCache), hasOverflow: prepare(_hasOverflowCache), contentScrollSize: prepare(_contentScrollSizeCache), viewportSize: prepare(_viewportSize), hostSize: prepare(_hostSizeCache), documentMixed : prepare(_documentMixed) }; return type(stateProperty) == TYPES.s ? getObjectPropVal(obj, stateProperty) : obj; }; /** * Gets all or specific extension instance. * @param extName The name of the extension from which the instance shall be got. * @returns {{}} The instance of the extension with the given name or undefined if the instance couldn't be found. */ _base.ext = function(extName) { var result; var privateMethods = _extensionsPrivateMethods.split(' '); var i = 0; if(type(extName) == TYPES.s) { if(_extensions.hasOwnProperty(extName)) { result = extendDeep({}, _extensions[extName]); for (; i < privateMethods.length; i++) delete result[privateMethods[i]]; } } else { result = { }; for(i in _extensions) result[i] = extendDeep({ }, _base.ext(i)); } return result; }; /** * Adds a extension to this instance. * @param extName The name of the extension which shall be added. * @param extensionOptions The extension options which shall be used. * @returns {{}} The instance of the added extension or undefined if the extension couldn't be added properly. */ _base.addExt = function(extName, extensionOptions) { var registeredExtensionObj = window[PLUGINNAME].extension(extName); var instance; var instanceAdded; var instanceContract; var contractResult; var contractFulfilled = true; if(registeredExtensionObj) { if(!_extensions.hasOwnProperty(extName)) { instance = registeredExtensionObj.extensionFactory.call(_base, extendDeep({ }, registeredExtensionObj.defaultOptions), FRAMEWORK, COMPATIBILITY); if (instance) { instanceContract = instance.contract; if (type(instanceContract) == TYPES.f) { contractResult = instanceContract(window); contractFulfilled = type(contractResult) == TYPES.b ? contractResult : contractFulfilled; } if(contractFulfilled) { _extensions[extName] = instance; instanceAdded = instance.added; if(type(instanceAdded) == TYPES.f) instanceAdded(extensionOptions); return _base.ext(extName); } } } else return _base.ext(extName); } else console.warn("A extension with the name \"" + extName + "\" isn't registered."); }; /** * Removes a extension from this instance. * @param extName The name of the extension which shall be removed. * @returns {boolean} True if the extension was removed, false otherwise e.g. if the extension wasn't added before. */ _base.removeExt = function(extName) { var instance = _extensions[extName]; var instanceRemoved; if(instance) { delete _extensions[extName]; instanceRemoved = instance.removed; if(type(instanceRemoved) == TYPES.f) instanceRemoved(); return true; } return false; }; /** * Constructs the plugin. * @param targetElement The element to which the plugin shall be applied. * @param options The initial options of the plugin. * @param extensions The extension(s) which shall be added right after the initialization. * @returns {boolean} True if the plugin was successfully initialized, false otherwise. */ function construct(targetElement, options, extensions) { _defaultOptions = globals.defaultOptions; _nativeScrollbarStyling = globals.nativeScrollbarStyling; _nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize); _nativeScrollbarIsOverlaid = extendDeep({}, globals.nativeScrollbarIsOverlaid); _overlayScrollbarDummySize = extendDeep({}, globals.overlayScrollbarDummySize); _rtlScrollBehavior = extendDeep({}, globals.rtlScrollBehavior); //parse & set options but don't update setOptions(extendDeep({ }, _defaultOptions, _pluginsOptions._validate(options, _pluginsOptions._template, true))); //check if the plugin hasn't to be initialized if (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.x && !_currentPreparedOptions.nativeScrollbarsOverlaid.initialize) { dispatchCallback("onInitializationWithdrawn"); return false; } _cssCalc = globals.cssCalc; _msieVersion = globals.msie; _autoUpdateRecommended = globals.autoUpdateRecommended; _supportTransition = globals.supportTransition; _supportTransform = globals.supportTransform; _supportPassiveEvents = globals.supportPassiveEvents; _supportResizeObserver = globals.supportResizeObserver; _supportMutationObserver = globals.supportMutationObserver; _restrictedMeasuring = globals.restrictedMeasuring; _documentElement = FRAMEWORK(targetElement.ownerDocument); _documentElementNative = _documentElement[0]; _windowElement = FRAMEWORK(_documentElementNative.defaultView || _documentElementNative.parentWindow); _windowElementNative = _windowElement[0]; _htmlElement = findFirst(_documentElement, 'html'); _bodyElement = findFirst(_htmlElement, 'body'); _targetElement = FRAMEWORK(targetElement); _targetElementNative = _targetElement[0]; _isTextarea = _targetElement.is('textarea'); _isBody = _targetElement.is('body'); _documentMixed = _documentElementNative !== document; var initBodyScroll; if (_isBody) { initBodyScroll = {}; initBodyScroll.l = MATH.max(_targetElement[_strScrollLeft](), _htmlElement[_strScrollLeft](), _windowElement[_strScrollLeft]()); initBodyScroll.t = MATH.max(_targetElement[_strScrollTop](), _htmlElement[_strScrollTop](), _windowElement[_strScrollTop]()); } //build OverlayScrollbars DOM and Events setupStructureDOM(); setupStructureEvents(); //build Scrollbars DOM and Events setupScrollbarsDOM(); setupScrollbarEvents(true); setupScrollbarEvents(false); //build Scrollbar Corner DOM and Events setupScrollbarCornerDOM(); setupScrollbarCornerEvents(); //create mutation observers createMutationObservers(); if(_isBody) { //apply the body scroll to handle it right in the update method _viewportElement[_strScrollLeft](initBodyScroll.l)[_strScrollTop](initBodyScroll.t); //set the focus on the viewport element so you dont have to click on the page to use keyboard keys (up / down / space) for scrolling if(document.activeElement == targetElement && _viewportElementNative.focus) { //set a tabindex to make the viewportElement focusable _viewportElement.attr('tabindex', '-1'); _viewportElementNative.focus(); /* the tabindex has to be removed due to; * If you set the tabindex attribute on an <div>, then its child content cannot be scrolled with the arrow keys unless you set tabindex on the content, too * https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex */ _viewportElement.one(_strMouseTouchDownEvent, function() { _viewportElement.removeAttr('tabindex'); }); } } //build resize observer for the host element addResizeObserver(_sizeObserverElement, hostOnResized); //update for the first time hostOnResized(); //initialize cache for host size _base.update(_strAuto); //initialize cache for content //the plugin is initialized now! _initialized = true; dispatchCallback("onInitialized"); //call all callbacks which would fire before the initialized was complete FRAMEWORK.each(_callbacksInitQeueue, function(index, value) { dispatchCallback(value.n, value.a); }); _callbacksInitQeueue = [ ]; //add extensions if(type(extensions) == TYPES.s) extensions = [ extensions ]; if(COMPATIBILITY.isA(extensions)) FRAMEWORK.each(extensions, function (index, value) {_base.addExt(value); }); else if(FRAMEWORK.isPlainObject(extensions)) FRAMEWORK.each(extensions, function (key, value) { _base.addExt(key, value); }); //add the transition class for transitions AFTER the first update & AFTER the applied extensions (for preventing unwanted transitions) setTimeout(function () { if (_supportTransition && !_destroyed) addClass(_hostElement, _classNameHostTransition); }, 333); return _initialized; } if (construct(pluginTargetElement, options, extensions)) { INSTANCES(pluginTargetElement, _base); return _base; } _base = undefined; } /** * Initializes a new OverlayScrollbarsInstance object or changes options if already initialized or returns the current instance. * @param pluginTargetElements The elements to which the Plugin shall be initialized. * @param options The custom options with which the plugin shall be initialized. * @param extensions The extension(s) which shall be added right after initialization. * @returns {*} */ window[PLUGINNAME] = function(pluginTargetElements, options, extensions) { if(arguments[LEXICON.l] === 0) return this; var arr = [ ]; var optsIsPlainObj = FRAMEWORK.isPlainObject(options); var inst; var result; //pluginTargetElements is null or undefined if(!pluginTargetElements) return optsIsPlainObj || !options ? result : arr; /* pluginTargetElements will be converted to: 1. A jQueryElement Array 2. A HTMLElement Array 3. A Array with a single HTML Element so pluginTargetElements is always a array. */ pluginTargetElements = pluginTargetElements[LEXICON.l] != undefined ? pluginTargetElements : [ pluginTargetElements[0] || pluginTargetElements ]; initOverlayScrollbarsStatics(); if(pluginTargetElements[LEXICON.l] > 0) { if(optsIsPlainObj) { FRAMEWORK.each(pluginTargetElements, function (i, v) { inst = v; if(inst !== undefined) arr.push(OverlayScrollbarsInstance(inst, options, extensions, _pluginsGlobals, _pluginsAutoUpdateLoop)); }); } else { FRAMEWORK.each(pluginTargetElements, function(i, v) { inst = INSTANCES(v); if((options === '!' && inst instanceof window[PLUGINNAME]) || (COMPATIBILITY.type(options) == TYPES.f && options(v, inst))) arr.push(inst); else if(options === undefined) arr.push(inst); }); } result = arr[LEXICON.l] === 1 ? arr[0] : arr; } return result; }; /** * Returns a object which contains global information about the plugin and each instance of it. * The returned object is just a copy, that means that changes to the returned object won't have any effect to the original object. */ window[PLUGINNAME].globals = function () { initOverlayScrollbarsStatics(); var globals = FRAMEWORK.extend(true, { }, _pluginsGlobals); delete globals['msie']; return globals; }; /** * Gets or Sets the default options for each new plugin initialization. * @param newDefaultOptions The object with which the default options shall be extended. */ window[PLUGINNAME].defaultOptions = function(newDefaultOptions) { initOverlayScrollbarsStatics(); var currDefaultOptions = _pluginsGlobals.defaultOptions; if(newDefaultOptions === undefined) return FRAMEWORK.extend(true, { }, currDefaultOptions); //set the new default options _pluginsGlobals.defaultOptions = FRAMEWORK.extend(true, { }, currDefaultOptions , _pluginsOptions._validate(newDefaultOptions, _pluginsOptions._template, true)); }; /** * Registers, Unregisters or returns a extension. * Register: Pass the name and the extension. (defaultOptions is optional) * Unregister: Pass the name and anything except a function as extension parameter. * Get extension: Pass the name of the extension which shall be got. * Get all extensions: Pass no arguments. * @param extensionName The name of the extension which shall be registered, unregistered or returned. * @param extension A function which generates the instance of the extension or anything other to remove a already registered extension. * @param defaultOptions The default options which shall be used for the registered extension. */ window[PLUGINNAME].extension = function(extensionName, extension, defaultOptions) { var extNameTypeString = COMPATIBILITY.type(extensionName) == TYPES.s; var argLen = arguments[LEXICON.l]; var i = 0; if(argLen < 1 || !extNameTypeString) { //return a copy of all extension objects return FRAMEWORK.extend(true, { length : _pluginsExtensions[LEXICON.l] }, _pluginsExtensions); } else if(extNameTypeString) { if(COMPATIBILITY.type(extension) == TYPES.f) { //register extension _pluginsExtensions.push({ name : extensionName, extensionFactory : extension, defaultOptions : defaultOptions }); } else { for(; i < _pluginsExtensions[LEXICON.l]; i++) { if (_pluginsExtensions[i].name === extensionName) { if(argLen > 1) _pluginsExtensions.splice(i, 1); //remove extension else return FRAMEWORK.extend(true, { }, _pluginsExtensions[i]); //return extension with the given name } } } } }; return window[PLUGINNAME]; })(); if(JQUERY && JQUERY.fn) { /** * The jQuery initialization interface. * @param options The initial options for the construction of the plugin. To initialize the plugin, this option has to be a object! If it isn't a object, the instance(s) are returned and the plugin wont be initialized. * @param extensions The extension(s) which shall be added right after initialization. * @returns {*} After initialization it returns the jQuery element array, else it returns the instance(s) of the elements which are selected. */ JQUERY.fn.overlayScrollbars = function (options, extensions) { var _elements = this; if(JQUERY.isPlainObject(options)) { JQUERY.each(_elements, function() { PLUGIN(this, options, extensions); }); return _elements; } else return PLUGIN(_elements, options); }; } return PLUGIN; } ));
extend1994/cdnjs
ajax/libs/overlayscrollbars/1.7.3/js/OverlayScrollbars.js
JavaScript
mit
348,965
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, Directive, InjectionToken, NgModule, Pipe, PlatformRef, SchemaMetadata, Type} from '@angular/core'; import {ComponentFixture} from './component_fixture'; import {MetadataOverride} from './metadata_override'; import {TestBed} from './test_bed'; /** * An abstract class for inserting the root test component element in a platform independent way. * * @publicApi */ export class TestComponentRenderer { insertRootElement(rootElementId: string) {} } /** * @publicApi */ export const ComponentFixtureAutoDetect = new InjectionToken<boolean[]>('ComponentFixtureAutoDetect'); /** * @publicApi */ export const ComponentFixtureNoNgZone = new InjectionToken<boolean[]>('ComponentFixtureNoNgZone'); /** * @publicApi */ export type TestModuleMetadata = { providers?: any[], declarations?: any[], imports?: any[], schemas?: Array<SchemaMetadata|any[]>, aotSummaries?: () => any[], }; /** * Static methods implemented by the `TestBedViewEngine` and `TestBedRender3` * * @publicApi */ export interface TestBedStatic { new (...args: any[]): TestBed; initTestEnvironment( ngModule: Type<any>|Type<any>[], platform: PlatformRef, aotSummaries?: () => any[]): TestBed; /** * Reset the providers for the test injector. */ resetTestEnvironment(): void; resetTestingModule(): TestBedStatic; /** * Allows overriding default compiler providers and settings * which are defined in test_injector.js */ configureCompiler(config: {providers?: any[]; useJit?: boolean;}): TestBedStatic; /** * Allows overriding default providers, directives, pipes, modules of the test injector, * which are defined in test_injector.js */ configureTestingModule(moduleDef: TestModuleMetadata): TestBedStatic; /** * Compile components with a `templateUrl` for the test's NgModule. * It is necessary to call this function * as fetching urls is asynchronous. */ compileComponents(): Promise<any>; overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBedStatic; overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBedStatic; overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBedStatic; overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBedStatic; overrideTemplate(component: Type<any>, template: string): TestBedStatic; /** * Overrides the template of the given component, compiling the template * in the context of the TestingModule. * * Note: This works for JIT and AOTed components as well. */ overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBedStatic; /** * Overwrites all providers for the given token with the given provider definition. * * Note: This works for JIT and AOTed components as well. */ overrideProvider(token: any, provider: { useFactory: Function, deps: any[], }): TestBedStatic; overrideProvider(token: any, provider: {useValue: any;}): TestBedStatic; overrideProvider(token: any, provider: { useFactory?: Function, useValue?: any, deps?: any[], }): TestBedStatic; /** * Overwrites all providers for the given token with the given provider definition. * * @deprecated as it makes all NgModules lazy. Introduced only for migrating off of it. */ deprecatedOverrideProvider(token: any, provider: { useFactory: Function, deps: any[], }): void; deprecatedOverrideProvider(token: any, provider: {useValue: any;}): void; deprecatedOverrideProvider(token: any, provider: { useFactory?: Function, useValue?: any, deps?: any[], }): TestBedStatic; get(token: any, notFoundValue?: any): any; createComponent<T>(component: Type<T>): ComponentFixture<T>; }
ValtoFrameworks/Angular-2
packages/core/testing/src/test_bed_common.ts
TypeScript
mit
4,016
import _curry3 from './internal/_curry3.js'; import prop from './prop.js'; /** * Returns `true` if the specified object property satisfies the given * predicate; `false` otherwise. You can test multiple properties with * [`R.where`](#where). * * @func * @memberOf R * @since v0.16.0 * @category Logic * @sig (a -> Boolean) -> String -> {String: a} -> Boolean * @param {Function} pred * @param {String} name * @param {*} obj * @return {Boolean} * @see R.where, R.propEq, R.propIs * @example * * R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true */ var propSatisfies = _curry3(function propSatisfies(pred, name, obj) { return pred(prop(name, obj)); }); export default propSatisfies;
ramda/ramda
source/propSatisfies.js
JavaScript
mit
715
import * as React from 'react'; /* * A utility for rendering a drag preview image */ export var DragPreviewImage = React.memo(function (_ref) { var connect = _ref.connect, src = _ref.src; React.useEffect(function () { if (typeof Image === 'undefined') return; var connected = false; var img = new Image(); img.src = src; img.onload = function () { connect(img); connected = true; }; return function () { if (connected) { connect(null); } }; }); return null; }); DragPreviewImage.displayName = 'DragPreviewImage';
cdnjs/cdnjs
ajax/libs/react-dnd/11.1.3/esm/common/DragPreviewImage.js
JavaScript
mit
595
import setupStore from 'dummy/tests/helpers/store'; import Ember from 'ember'; import testInDebug from 'dummy/tests/helpers/test-in-debug'; import {module, test} from 'qunit'; import DS from 'ember-data'; const { run } = Ember; const { attr } = DS; const { reject } = Ember.RSVP; let Person, store, env; module("integration/adapter/find - Finding Records", { beforeEach() { Person = DS.Model.extend({ updatedAt: attr('string'), name: attr('string'), firstName: attr('string'), lastName: attr('string') }); env = setupStore({ person: Person }); store = env.store; }, afterEach() { run(store, 'destroy'); } }); testInDebug("It raises an assertion when `undefined` is passed as id (#1705)", (assert) => { assert.expectAssertion(() => { store.find('person', undefined); }, "You cannot pass `undefined` as id to the store's find method"); assert.expectAssertion(() => { store.find('person', null); }, "You cannot pass `null` as id to the store's find method"); }); test("When a single record is requested, the adapter's find method should be called unless it's loaded.", (assert) => { assert.expect(2); var count = 0; env.registry.register('adapter:person', DS.Adapter.extend({ findRecord(_, type) { assert.equal(type, Person, "the find method is called with the correct type"); assert.equal(count, 0, "the find method is only called once"); count++; return { id: 1, name: "Braaaahm Dale" }; } })); run(() => { store.findRecord('person', 1); store.findRecord('person', 1); }); }); test("When a single record is requested multiple times, all .findRecord() calls are resolved after the promise is resolved", (assert) => { var deferred = Ember.RSVP.defer(); env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => deferred.promise })); run(() => { store.findRecord('person', 1).then(assert.wait(function(person) { assert.equal(person.get('id'), "1"); assert.equal(person.get('name'), "Braaaahm Dale"); let done = assert.async(); deferred.promise.then(() => { assert.ok(true, 'expected deferred.promise to fulfill'); done(); }, () => { assert.ok(false, 'expected deferred.promise to fulfill, but rejected'); done(); }); })); }); run(() => { store.findRecord('person', 1).then(assert.wait((post) => { assert.equal(post.get('id'), "1"); assert.equal(post.get('name'), "Braaaahm Dale"); let done = assert.async(); deferred.promise.then(() => { assert.ok(true, 'expected deferred.promise to fulfill'); done(); }, () => { assert.ok(false, 'expected deferred.promise to fulfill, but rejected'); done(); }); })); }); run(() => deferred.resolve({ id: 1, name: "Braaaahm Dale" })); }); test("When a single record is requested, and the promise is rejected, .findRecord() is rejected.", (assert) => { env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => reject() })); run(() => { store.findRecord('person', 1).then(null, assert.wait(() => { assert.ok(true, "The rejection handler was called"); })); }); }); test("When a single record is requested, and the promise is rejected, the record should be unloaded.", (assert) => { assert.expect(2); env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => reject() })); run(() => { store.findRecord('person', 1).then(null, assert.wait((reason) => { assert.ok(true, "The rejection handler was called"); assert.ok(!store.hasRecordForId('person', 1), "The record has been unloaded"); })); }); }); testInDebug('When a single record is requested, and the payload is blank', (assert) => { env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => Ember.RSVP.resolve({}) })); assert.expectAssertion(() => { run(() => store.findRecord('person', 'the-id')); }, /You made a `findRecord` request for a person with id the-id, but the adapter's response did not have any data/); }); testInDebug('When multiple records are requested, and the payload is blank', (assert) => { env.registry.register('adapter:person', DS.Adapter.extend({ coalesceFindRequests: true, findMany: () => Ember.RSVP.resolve({}) })); assert.expectAssertion(() => { run(() => { store.findRecord('person', '1'); store.findRecord('person', '2'); }); }, /You made a `findMany` request for person records with ids 1,2, but the adapter's response did not have any data/); }); testInDebug("warns when returned record has different id", function(assert) { env.registry.register('adapter:person', DS.Adapter.extend({ findRecord() { return { id: 1, name: "Braaaahm Dale" }; } })); assert.expectWarning(/You requested a record of type 'person' with id 'me' but the adapter returned a payload with primary data having an id of '1'/); run(function() { env.store.findRecord('person', 'me'); }); });
wecc/data
tests/integration/adapter/find-test.js
JavaScript
mit
5,129
/****************************************************************************** * Copyright (C) 2006-2012 IFS Institute for Software and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Original authors: * Dennis Hunziker * Ueli Kistler * Reto Schuettel * Robin Stocker * Contributors: * Fabio Zadrozny <fabiofz@gmail.com> - initial implementation ******************************************************************************/ /* * Copyright (C) 2006, 2007 Dennis Hunziker, Ueli Kistler * Copyright (C) 2007 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * */ package org.python.pydev.refactoring.ui.core; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.swt.graphics.Image; import org.python.pydev.refactoring.core.model.tree.ITreeNode; public class TreeLabelProvider implements ILabelProvider { private PepticImageCache cache; public TreeLabelProvider() { cache = new PepticImageCache(); } @Override public Image getImage(Object element) { Image image = null; ITreeNode node = (ITreeNode) element; image = cache.get(node.getImageName()); return image; } @Override public String getText(Object element) { if (element instanceof ITreeNode) { return ((ITreeNode) element).getLabel(); } return ""; } @Override public void addListener(ILabelProviderListener listener) { } @Override public void dispose() { cache.dispose(); cache = null; } @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public void removeListener(ILabelProviderListener listener) { } }
bobwalker99/Pydev
plugins/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/core/TreeLabelProvider.java
Java
epl-1.0
2,059
/** * Copyright (c) 2013-2015 by Brainwy Software Ltda, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package org.python.pydev.debug.curr_exception; import java.util.HashMap; import java.util.Map; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.python.pydev.shared_ui.UIConstants; import org.python.pydev.shared_ui.dialogs.DialogMemento; import org.python.pydev.ui.editors.TreeWithAddRemove; /** * @author fabioz */ public class EditIgnoredCaughtExceptionsDialog extends TrayDialog { private Button okButton; private Button cancelButton; private HashMap<String, String> map; private TreeWithAddRemove treeWithAddRemove; private DialogMemento memento; private Map<String, String> finalMap; EditIgnoredCaughtExceptionsDialog(Shell shell, HashMap<String, String> map) { super(shell); this.map = map; setHelpAvailable(false); memento = new DialogMemento(shell, "org.python.pydev.debug.curr_exception.EditIgnoredCaughtExceptionsDialog"); } @Override protected void createButtonsForButtonBar(Composite parent) { okButton = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); cancelButton = createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } @Override public boolean close() { memento.writeSettings(getShell()); return super.close(); } @Override protected Point getInitialSize() { return memento.getInitialSize(super.getInitialSize(), getShell()); } @Override protected Point getInitialLocation(Point initialSize) { return memento.getInitialLocation(initialSize, super.getInitialLocation(initialSize), getShell()); } @Override protected Control createDialogArea(Composite parent) { memento.readSettings(); Composite area = (Composite) super.createDialogArea(parent); treeWithAddRemove = new TreeWithAddRemove(area, 0, map) { @Override protected void handleAddButtonSelected(int nButton) { throw new RuntimeException("not implemented: no add buttons"); } @Override protected String getImageConstant() { return UIConstants.PUBLIC_ATTR_ICON; } @Override protected String getButtonLabel(int i) { throw new RuntimeException("not implemented: no add buttons"); } @Override protected int getNumberOfAddButtons() { return 0; } }; GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; treeWithAddRemove.setLayoutData(data); treeWithAddRemove.fitToContents(); return area; } @Override protected boolean isResizable() { return true; } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText("Edit Ignored Thrown Exceptions"); } @Override protected void okPressed() { this.finalMap = treeWithAddRemove.getTreeItemsAsMap(); super.okPressed(); } public Map<String, String> getResult() { return finalMap; } }
bobwalker99/Pydev
plugins/org.python.pydev.debug/src/org/python/pydev/debug/curr_exception/EditIgnoredCaughtExceptionsDialog.java
Java
epl-1.0
3,834
/******************************************************************************* * Copyright (c) 2012, 2014 UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Initial API and implementation and/or initial documentation - Jay Jay Billings, * Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson, * Claire Saunders, Matthew Wang, Anna Wojtowicz *******************************************************************************/ package org.eclipse.ice.datastructures.ICEObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; /** * This class is responsible for reading and writing JAXB-annotated classes into * and out of ICE. * * @author Jay Jay Billings */ public class ICEJAXBHandler { /** * This operation reads an instance of a particular class type from the * input stream into a Java Object. * * @param classList * The class list from which JAXB annotations should be read. * @param inputStream * An InputStream from which the XML should be read by JAXB. * @return An Object that is an instance of the Class that was parsed from * the XML InputStream. * @throws NullPointerException * @throws JAXBException * @throws IOException */ public Object read(ArrayList<Class> classList, InputStream inputStream) throws NullPointerException, JAXBException, IOException { // Initialize local variables JAXBContext context; Class[] clazzArray = {}; // If the input args are null, throw an exception if (classList == null) { throw new NullPointerException("NullPointerException: " + "objectClass argument can not be null"); } if (inputStream == null) { throw new NullPointerException("NullPointerException: " + "inputStream argument can not be null"); } // Create new instance of object from file and then return it. context = JAXBContext.newInstance(classList.toArray(clazzArray)); Unmarshaller unmarshaller = context.createUnmarshaller(); // New object created Object dataFromFile = unmarshaller.unmarshal(inputStream); // Return object return dataFromFile; } /** * This operation writes an instance of a particular class type from the * input stream into a Java Object. This operation requires both the Object * and the specific class type because some classes, such as local classes, * do return the appropriate class type from a call to "this.getClass()." * * @param dataObject * An Object that is an instance of the Class that is parsed to * create the XML InputStream. * @param classList * @param outputStream * An OutputStream to which the XML should be written by JAXB. * @throws NullPointerException * @throws JAXBException * @throws IOException */ public void write(Object dataObject, ArrayList<Class> classList, OutputStream outputStream) throws NullPointerException, JAXBException, IOException { JAXBContext jaxbContext = null; Class[] classArray = {}; // Throw exceptions if input args are null if (dataObject == null) { throw new NullPointerException( "NullPointerException: dataObject can not be null"); } if (outputStream == null) { throw new NullPointerException( "NullPointerException: outputStream can not be null"); } // Create the class list with which to initialize the context. If the // data object is an ListComponent, it is important to give it // both the type of the container and the generic. if (dataObject instanceof ListComponent) { // Cast the object to a generic, type-less list ListComponent list = (ListComponent) dataObject; // Don't pop the container open if it is empty if (list.size() > 0 && !classList.contains(ListComponent.class)) { classList.add(ListComponent.class); classList.add(list.get(0).getClass()); } } else if (!dataObject.getClass().isAnonymousClass()) { // Otherwise just get the class if it is not anonymous classList.add(dataObject.getClass()); } else { // Or get the base class if it is anonymous classList.add(dataObject.getClass().getSuperclass()); } // Create the context and marshal the data if classes were determined if (classList.size() > 0) { jaxbContext = JAXBContext .newInstance(classList.toArray(classArray)); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to file marshaller.marshal(dataObject, outputStream); } return; } }
gorindn/ice
src/org.eclipse.ice.datastructures/src/org/eclipse/ice/datastructures/ICEObject/ICEJAXBHandler.java
Java
epl-1.0
4,963
package org.usfirst.frc.team3952.robot; import java.io.IOException; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { DriveTrain dt; DashBoard board; Joystick stick; LinearActuatorWinch lin; //ImageProcess i; int autoLoopCounter; ServoC sc; WindshieldMotor m1; long start; //double speed; //we are using talon motors so need to make new DriveTrain class /** * This function is run when the robot is first started up and should be;ioj;oi * used for any initialization code. */ public void robotInit() { board = new DashBoard(); stick = new Joystick(0); dt=new DriveTrain(stick); lin =new LinearActuatorWinch(stick); sc=new ServoC(stick, new Servo(6)); m1=new WindshieldMotor(4,5,stick); //speed=-0.1; } /** * This function is run once each time the robot enters autonomous mode */ public void autonomousInit() { start=System.currentTimeMillis(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { dt.autonD(start); } /** * This function is called once each time the robot enters tele-operated mode */ public void teleopInit(){ } /** * This function is called periodically during operator control */ public void teleopPeriodic() { dt.drive(); board.updateDashboard(); //lin.goLAW(); sc.pCheck(); //m1.pressCheck(); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
Grande14/Team3952desTROYer
v6 3_12_2016 still comments/Robot.java
Java
epl-1.0
2,240
package org.jboss.windup.reporting; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.forge.arquillian.AddonDependencies; import org.jboss.forge.arquillian.AddonDependency; import org.jboss.forge.arquillian.archive.AddonArchive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.windup.config.DefaultEvaluationContext; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.RuleSubset; import org.jboss.windup.config.loader.RuleLoaderContext; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.GraphContextFactory; import org.jboss.windup.reporting.category.IssueCategoryRegistry; import org.jboss.windup.reporting.category.LoadIssueCategoriesRuleProvider; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.ocpsoft.rewrite.config.Configuration; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a> */ @RunWith(Arquillian.class) public class LoadIssueCategoriesRuleProviderTest { public static final String ISSUE_CATEGORIES_PATH = "src/test/resources/issue-categories"; @Inject private GraphContextFactory factory; @Inject private LoadIssueCategoriesRuleProvider provider; @Deployment @AddonDependencies({ @AddonDependency(name = "org.jboss.windup.config:windup-config"), @AddonDependency(name = "org.jboss.windup.graph:windup-graph"), @AddonDependency(name = "org.jboss.windup.reporting:windup-reporting"), @AddonDependency(name = "org.jboss.forge.furnace.container:cdi") }) public static AddonArchive getDeployment() { return ShrinkWrap .create(AddonArchive.class) .addBeansXML() .addClass(ReportingTestUtil.class) .addAsResource(new File(ISSUE_CATEGORIES_PATH)); } @Test public void testLoadIssueCategories() throws Exception { try (GraphContext context = factory.create(true)) { GraphRewrite event = new GraphRewrite(context); DefaultEvaluationContext evaluationContext = ReportingTestUtil.createEvalContext(event); List<Path> ruleLoaderPaths = new ArrayList<>(); Path testPath = Paths.get(ISSUE_CATEGORIES_PATH); ruleLoaderPaths.add(testPath); RuleLoaderContext ruleLoaderContext = new RuleLoaderContext(event.getRewriteContext(), ruleLoaderPaths, null); Configuration configuration = provider.getConfiguration(ruleLoaderContext); RuleSubset.create(configuration).perform(event, evaluationContext); IssueCategoryRegistry issueCategoryRegistry = IssueCategoryRegistry.instance(event.getRewriteContext()); Assert.assertEquals(1000, (long)issueCategoryRegistry.getByID("mandatory").getPriority()); Assert.assertEquals(2000, (long)issueCategoryRegistry.getByID("optional").getPriority()); Assert.assertEquals(3000, (long)issueCategoryRegistry.getByID("potential").getPriority()); Assert.assertEquals(4000, (long)issueCategoryRegistry.getByID("extra").getPriority()); Assert.assertEquals("extra", issueCategoryRegistry.getByID("extra").getCategoryID()); Assert.assertEquals("Extra", issueCategoryRegistry.getByID("extra").getName()); Assert.assertEquals("Extra Category", issueCategoryRegistry.getByID("extra").getDescription()); Assert.assertNotNull(issueCategoryRegistry.getByID("extra").getOrigin()); Assert.assertTrue(issueCategoryRegistry.getByID("extra").getOrigin().endsWith("test.windup.categories.xml")); } } }
jsight/windup
reporting/tests/src/test/java/org/jboss/windup/reporting/LoadIssueCategoriesRuleProviderTest.java
Java
epl-1.0
3,912
require "rjava" # Copyright (c) 2000, 2005 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # IBM Corporation - initial API and implementation module Org::Eclipse::Swt::Widgets module ListenerImports #:nodoc: class_module.module_eval { include ::Java::Lang include ::Org::Eclipse::Swt::Widgets } end # Implementers of <code>Listener</code> provide a simple # <code>handleEvent()</code> method that is used internally # by SWT to dispatch events. # <p> # After creating an instance of a class that implements this interface # it can be added to a widget using the # <code>addListener(int eventType, Listener handler)</code> method and # removed using the # <code>removeListener (int eventType, Listener handler)</code> method. # When the specified event occurs, <code>handleEvent(...)</code> will # be sent to the instance. # </p> # <p> # Classes which implement this interface are described within SWT as # providing the <em>untyped listener</em> API. Typically, widgets will # also provide a higher-level <em>typed listener</em> API, that is based # on the standard <code>java.util.EventListener</code> pattern. # </p> # <p> # Note that, since all internal SWT event dispatching is based on untyped # listeners, it is simple to build subsets of SWT for use on memory # constrained, small footprint devices, by removing the classes and # methods which implement the typed listener API. # </p> # # @see Widget#addListener # @see java.util.EventListener # @see org.eclipse.swt.events module Listener include_class_members ListenerImports typesig { [Event] } # Sent when an event that the receiver has registered for occurs. # # @param event the event which occurred def handle_event(event) raise NotImplementedError end end end
neelance/swt4ruby
swt4ruby/lib/mingw32-x86_32/org/eclipse/swt/widgets/Listener.rb
Ruby
epl-1.0
2,098
/******************************************************************************* * Copyright (c) 2009, 2010 David A Carlson. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David A Carlson (XMLmodeling.com) - initial API and implementation * * $Id$ *******************************************************************************/ package org.openhealthtools.mdht.uml.cda.ncr.impl; import java.util.Map; import org.eclipse.emf.common.util.DiagnosticChain; import org.eclipse.emf.ecore.EClass; import org.openhealthtools.mdht.uml.cda.ccd.impl.EncounterLocationImpl; import org.openhealthtools.mdht.uml.cda.ncr.NCRPackage; import org.openhealthtools.mdht.uml.cda.ncr.NeonatalICULocation; import org.openhealthtools.mdht.uml.cda.ncr.operations.NeonatalICULocationOperations; import org.openhealthtools.mdht.uml.cda.util.CDAUtil; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Neonatal ICU Location</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class NeonatalICULocationImpl extends EncounterLocationImpl implements NeonatalICULocation { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected NeonatalICULocationImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return NCRPackage.Literals.NEONATAL_ICU_LOCATION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean validateNeonatalICULocationTypeCode(DiagnosticChain diagnostics, Map<Object, Object> context) { return NeonatalICULocationOperations.validateNeonatalICULocationTypeCode(this, diagnostics, context); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean validateEncounterLocationTemplateId(DiagnosticChain diagnostics, Map<Object, Object> context) { return NeonatalICULocationOperations.validateEncounterLocationTemplateId(this, diagnostics, context); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NeonatalICULocation init() { CDAUtil.init(this); return this; } } //NeonatalICULocationImpl
drbgfc/mdht
cda/deprecated/org.openhealthtools.mdht.uml.cda.ncr/src/org/openhealthtools/mdht/uml/cda/ncr/impl/NeonatalICULocationImpl.java
Java
epl-1.0
2,533
// Aseprite Base Library // Copyright (c) 2001-2013, 2015 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "base/time.h" #if _WIN32 #include <windows.h> #else #include <ctime> #endif namespace base { Time current_time() { #if _WIN32 SYSTEMTIME st; GetLocalTime(&st); return Time(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); #else std::time_t now = std::time(nullptr); std::tm* t = std::localtime(&now); return Time( t->tm_year+1900, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); #endif } } // namespace base
Fojar/aseprite
src/base/time.cpp
C++
gpl-2.0
704
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/ # # Copyright (c) 2011 - 2014 by Wilbert Berendsen # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # See http://www.gnu.org/licenses/ for more information. """ Utility functions used in the autocomplete package. """ import functools import time import weakref def keep(f): """Returns a decorator that remembers its return value for some time.""" _delay = 5.0 # sec _cache = weakref.WeakKeyDictionary() @functools.wraps(f) def decorator(self, *args): try: result = _cache[self] except KeyError: pass else: t, ret = result if (time.time() - t) < _delay: return ret ret = f(self, *args) _cache[self] = (time.time(), ret) return ret return decorator # helper functions for displaying data from models def command(item): """Prepends '\\' to item.""" return '\\' + item def variable(item): """Appends ' = ' to item.""" return item + " = " def cmd_or_var(item): """Appends ' = ' to item if it does not start with '\\'.""" return item if item.startswith('\\') else item + " = " def make_cmds(words): """Returns generator prepending '\\' to every word.""" return ('\\' + w for w in words)
dliessi/frescobaldi
frescobaldi_app/autocomplete/util.py
Python
gpl-2.0
1,994
<?php /** * PEL: PHP Exif Library. * A library with support for reading and * writing all Exif headers in JPEG and TIFF images using PHP. * * Copyright (C) 2004, 2005, 2006 Martin Geisler. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program in the file COPYING; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ namespace Pel\Test; use lsolesen\pel\PelEntrySShort; class NumberSShortTest extends NumberTestCase { public function setUp(): void { parent::setUp(); $this->num = new PelEntrySShort(42); $this->min = - 32768; $this->max = 32767; } }
maskedjellybean/tee-prop
vendor/lsolesen/pel/test/NumberSShortTest.php
PHP
gpl-2.0
1,216
/* $Id$ */ /** @file * * VBox frontends: Qt4 GUI ("VirtualBox"): * UIWizardImportAppPageBasic1 class implementation */ /* * Copyright (C) 2009-2012 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /* Global includes: */ #include <QFileInfo> #include <QVBoxLayout> /* Local includes: */ #include "UIWizardImportAppPageBasic1.h" #include "UIWizardImportAppPageBasic2.h" #include "UIWizardImportApp.h" #include "VBoxGlobal.h" #include "VBoxFilePathSelectorWidget.h" #include "QIRichTextLabel.h" UIWizardImportAppPage1::UIWizardImportAppPage1() { } UIWizardImportAppPageBasic1::UIWizardImportAppPageBasic1() { /* Create widgets: */ QVBoxLayout *pMainLayout = new QVBoxLayout(this); { m_pLabel = new QIRichTextLabel(this); m_pFileSelector = new VBoxEmptyFileSelector(this); { m_pFileSelector->setMode(VBoxFilePathSelectorWidget::Mode_File_Open); m_pFileSelector->setHomeDir(vboxGlobal().documentsPath()); } pMainLayout->addWidget(m_pLabel); pMainLayout->addWidget(m_pFileSelector); pMainLayout->addStretch(); } /* Setup connections: */ connect(m_pFileSelector, SIGNAL(pathChanged(const QString&)), this, SIGNAL(completeChanged())); } void UIWizardImportAppPageBasic1::retranslateUi() { /* Translate page: */ setTitle(UIWizardImportApp::tr("Appliance to import")); /* Translate widgets: */ m_pLabel->setText(UIWizardImportApp::tr("<p>VirtualBox currently supports importing appliances " "saved in the Open Virtualization Format (OVF). " "To continue, select the file to import below.</p>")); m_pFileSelector->setChooseButtonText(UIWizardImportApp::tr("Open appliance...")); m_pFileSelector->setFileDialogTitle(UIWizardImportApp::tr("Select an appliance to import")); m_pFileSelector->setFileFilters(UIWizardImportApp::tr("Open Virtualization Format (%1)").arg("*.ova *.ovf")); } void UIWizardImportAppPageBasic1::initializePage() { /* Translate page: */ retranslateUi(); } bool UIWizardImportAppPageBasic1::isComplete() const { /* Make sure appliance file has allowed extension and exists: */ return VBoxGlobal::hasAllowedExtension(m_pFileSelector->path().toLower(), OVFFileExts) && QFileInfo(m_pFileSelector->path()).exists(); } bool UIWizardImportAppPageBasic1::validatePage() { /* Get import appliance widget: */ ImportAppliancePointer pImportApplianceWidget = field("applianceWidget").value<ImportAppliancePointer>(); AssertMsg(!pImportApplianceWidget.isNull(), ("Appliance Widget is not set!\n")); /* If file name was changed: */ if (m_pFileSelector->isModified()) { /* Check if set file contains valid appliance: */ if (!pImportApplianceWidget->setFile(m_pFileSelector->path())) return false; /* Reset the modified bit afterwards: */ m_pFileSelector->resetModified(); } /* If we have a valid ovf proceed to the appliance settings page: */ return pImportApplianceWidget->isValid(); }
pombredanne/VirtualBox-OSE
src/VBox/Frontends/VirtualBox/src/wizards/importappliance/UIWizardImportAppPageBasic1.cpp
C++
gpl-2.0
3,589