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
class AddOauthGithubToUsers < ActiveRecord::Migration[5.1] def change add_column :users, :provider, :string add_column :users, :uid, :string end end
Jacaa/todo_list
db/migrate/20170828093906_add_oauth_github_to_users.rb
Ruby
mit
161
<?php if(!isset($_SESSION)){ session_start(); } session_destroy(); header("Location: ../../../login.php"); exit;
rubenalmeida/AdminLTE
administrador/cadastros/usuarios/Logout.php
PHP
mit
117
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\PromotionBundle\Form\Type\Rule; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Type; /** * Item count rule configuration form type. * * @author Saša Stamenković <umpirsky@gmail.com> */ class ItemCountConfigurationType extends AbstractType { protected $validationGroups; public function __construct(array $validationGroups) { $this->validationGroups = $validationGroups; } /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('count', 'integer', array( 'label' => 'sylius.form.rule.item_count_configuration.count', 'constraints' => array( new NotBlank(), new Type(array('type' => 'numeric')), ) )) ->add('equal', 'checkbox', array( 'label' => 'sylius.form.rule.item_count_configuration.equal', 'constraints' => array( new Type(array('type' => 'bool')), ) )) ; } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver ->setDefaults(array( 'validation_groups' => $this->validationGroups, )) ; } /** * {@inheritdoc} */ public function getName() { return 'sylius_promotion_rule_item_count_configuration'; } }
songecko/legem-ecommerce
src/Sylius/Bundle/PromotionBundle/Form/Type/Rule/ItemCountConfigurationType.php
PHP
mit
2,036
//----------------------------------------------------------------------- // <copyright file="SingleInstance.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // This class checks to make sure that only one instance of // this application is running at a time. // </summary> //----------------------------------------------------------------------- // ReSharper disable once CheckNamespace // ReSharper disable InconsistentNaming namespace Microsoft.Shell { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Serialization.Formatters; using System.Threading; using System.Windows; using System.Windows.Threading; using System.Security; using System.Runtime.InteropServices; using System.ComponentModel; internal enum WM { NULL = 0x0000, CREATE = 0x0001, DESTROY = 0x0002, MOVE = 0x0003, SIZE = 0x0005, ACTIVATE = 0x0006, SETFOCUS = 0x0007, KILLFOCUS = 0x0008, ENABLE = 0x000A, SETREDRAW = 0x000B, SETTEXT = 0x000C, GETTEXT = 0x000D, GETTEXTLENGTH = 0x000E, PAINT = 0x000F, CLOSE = 0x0010, QUERYENDSESSION = 0x0011, QUIT = 0x0012, QUERYOPEN = 0x0013, ERASEBKGND = 0x0014, SYSCOLORCHANGE = 0x0015, SHOWWINDOW = 0x0018, ACTIVATEAPP = 0x001C, SETCURSOR = 0x0020, MOUSEACTIVATE = 0x0021, CHILDACTIVATE = 0x0022, QUEUESYNC = 0x0023, GETMINMAXINFO = 0x0024, WINDOWPOSCHANGING = 0x0046, WINDOWPOSCHANGED = 0x0047, CONTEXTMENU = 0x007B, STYLECHANGING = 0x007C, STYLECHANGED = 0x007D, DISPLAYCHANGE = 0x007E, GETICON = 0x007F, SETICON = 0x0080, NCCREATE = 0x0081, NCDESTROY = 0x0082, NCCALCSIZE = 0x0083, NCHITTEST = 0x0084, NCPAINT = 0x0085, NCACTIVATE = 0x0086, GETDLGCODE = 0x0087, SYNCPAINT = 0x0088, NCMOUSEMOVE = 0x00A0, NCLBUTTONDOWN = 0x00A1, NCLBUTTONUP = 0x00A2, NCLBUTTONDBLCLK = 0x00A3, NCRBUTTONDOWN = 0x00A4, NCRBUTTONUP = 0x00A5, NCRBUTTONDBLCLK = 0x00A6, NCMBUTTONDOWN = 0x00A7, NCMBUTTONUP = 0x00A8, NCMBUTTONDBLCLK = 0x00A9, SYSKEYDOWN = 0x0104, SYSKEYUP = 0x0105, SYSCHAR = 0x0106, SYSDEADCHAR = 0x0107, COMMAND = 0x0111, SYSCOMMAND = 0x0112, MOUSEMOVE = 0x0200, LBUTTONDOWN = 0x0201, LBUTTONUP = 0x0202, LBUTTONDBLCLK = 0x0203, RBUTTONDOWN = 0x0204, RBUTTONUP = 0x0205, RBUTTONDBLCLK = 0x0206, MBUTTONDOWN = 0x0207, MBUTTONUP = 0x0208, MBUTTONDBLCLK = 0x0209, MOUSEWHEEL = 0x020A, XBUTTONDOWN = 0x020B, XBUTTONUP = 0x020C, XBUTTONDBLCLK = 0x020D, MOUSEHWHEEL = 0x020E, CAPTURECHANGED = 0x0215, ENTERSIZEMOVE = 0x0231, EXITSIZEMOVE = 0x0232, IME_SETCONTEXT = 0x0281, IME_NOTIFY = 0x0282, IME_CONTROL = 0x0283, IME_COMPOSITIONFULL = 0x0284, IME_SELECT = 0x0285, IME_CHAR = 0x0286, IME_REQUEST = 0x0288, IME_KEYDOWN = 0x0290, IME_KEYUP = 0x0291, NCMOUSELEAVE = 0x02A2, DWMCOMPOSITIONCHANGED = 0x031E, DWMNCRENDERINGCHANGED = 0x031F, DWMCOLORIZATIONCOLORCHANGED = 0x0320, DWMWINDOWMAXIMIZEDCHANGE = 0x0321, #region Windows 7 DWMSENDICONICTHUMBNAIL = 0x0323, DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326, #endregion USER = 0x0400, // This is the hard-coded message value used by WinForms for Shell_NotifyIcon. // It's relatively safe to reuse. TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024 APP = 0x8000, } [SuppressUnmanagedCodeSecurity] internal static class NativeMethods { /// <summary> /// Delegate declaration that matches WndProc signatures. /// </summary> public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled); [DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)] private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs); [DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)] private static extern IntPtr _LocalFree(IntPtr hMem); public static string[] CommandLineToArgvW(string cmdLine) { IntPtr argv = IntPtr.Zero; try { argv = _CommandLineToArgvW(cmdLine, out var numArgs); if (argv == IntPtr.Zero) { throw new Win32Exception(); } var result = new string[numArgs]; for (int i = 0; i < numArgs; i++) { IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr))); result[i] = Marshal.PtrToStringUni(currArg); } return result; } finally { IntPtr p = _LocalFree(argv); // Otherwise LocalFree failed. // Assert.AreEqual(IntPtr.Zero, p); } } } public interface ISingleInstanceApp { bool SignalExternalCommandLineArgs(IList<string> args); } /// <summary> /// This class checks to make sure that only one instance of /// this application is running at a time. /// </summary> /// <remarks> /// Note: this class should be used with some caution, because it does no /// security checking. For example, if one instance of an app that uses this class /// is running as Administrator, any other instance, even if it is not /// running as Administrator, can activate it with command line arguments. /// For most apps, this will not be much of an issue. /// </remarks> public static class SingleInstance<TApplication> where TApplication : Application, ISingleInstanceApp { #region Private Fields /// <summary> /// String delimiter used in channel names. /// </summary> private const string Delimiter = ":"; /// <summary> /// Suffix to the channel name. /// </summary> private const string ChannelNameSuffix = "SingeInstanceIPCChannel"; /// <summary> /// Remote service name. /// </summary> private const string RemoteServiceName = "SingleInstanceApplicationService"; /// <summary> /// IPC protocol used (string). /// </summary> private const string IpcProtocol = "ipc://"; /// <summary> /// Application mutex. /// </summary> private static Mutex singleInstanceMutex; /// <summary> /// IPC channel for communications. /// </summary> private static IpcServerChannel channel; /// <summary> /// List of command line arguments for the application. /// </summary> private static IList<string> commandLineArgs; #endregion #region Public Properties /// <summary> /// Gets list of command line arguments for the application. /// </summary> public static IList<string> CommandLineArgs => commandLineArgs; #endregion #region Public Methods /// <summary> /// Checks if the instance of the application attempting to start is the first instance. /// If not, activates the first instance. /// </summary> /// <returns>True if this is the first instance of the application.</returns> public static bool InitializeAsFirstInstance(string uniqueName) { commandLineArgs = GetCommandLineArgs(uniqueName); // File.WriteAllLines(@"D:\Temp\Logazmic\args.txt",commandLineArgs); // Build unique application Id and the IPC channel name. string applicationIdentifier = uniqueName + Environment.UserName; string channelName = string.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix); // Create mutex based on unique application Id to check if this is the first instance of the application. bool firstInstance; singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance); if (firstInstance) { ((ISingleInstanceApp)(Application.Current)).SignalExternalCommandLineArgs(commandLineArgs); CreateRemoteService(channelName); } else { SignalFirstInstance(channelName, commandLineArgs); } return firstInstance; } /// <summary> /// Cleans up single-instance code, clearing shared resources, mutexes, etc. /// </summary> public static void Cleanup() { if (singleInstanceMutex != null) { singleInstanceMutex.Close(); singleInstanceMutex = null; } if (channel != null) { ChannelServices.UnregisterChannel(channel); channel = null; } } #endregion #region Private Methods /// <summary> /// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved. /// </summary> /// <returns>List of command line arg strings.</returns> private static IList<string> GetCommandLineArgs(string uniqueApplicationName) { return new List<string>(Environment.GetCommandLineArgs()); } /// <summary> /// Creates a remote service for communication. /// </summary> /// <param name="channelName">Application's IPC channel name.</param> private static void CreateRemoteService(string channelName) { BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; IDictionary props = new Dictionary<string, string>(); props["name"] = channelName; props["portName"] = channelName; props["exclusiveAddressUse"] = "false"; // Create the IPC Server channel with the channel properties channel = new IpcServerChannel(props, serverProvider); // Register the channel with the channel services ChannelServices.RegisterChannel(channel, true); // Expose the remote service with the REMOTE_SERVICE_NAME IPCRemoteService remoteService = new IPCRemoteService(); RemotingServices.Marshal(remoteService, RemoteServiceName); } /// <summary> /// Creates a client channel and obtains a reference to the remoting service exposed by the server - /// in this case, the remoting service exposed by the first instance. Calls a function of the remoting service /// class to pass on command line arguments from the second instance to the first and cause it to activate itself. /// </summary> /// <param name="channelName">Application's IPC channel name.</param> /// <param name="args"> /// Command line arguments for the second instance, passed to the first instance to take appropriate action. /// </param> private static void SignalFirstInstance(string channelName, IList<string> args) { IpcClientChannel secondInstanceChannel = new IpcClientChannel(); ChannelServices.RegisterChannel(secondInstanceChannel, true); string remotingServiceUrl = IpcProtocol + channelName + "/" + RemoteServiceName; // Obtain a reference to the remoting service exposed by the server i.e the first instance of the application IPCRemoteService firstInstanceRemoteServiceReference = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), remotingServiceUrl); // Check that the remote service exists, in some cases the first instance may not yet have created one, in which case // the second instance should just exit if (firstInstanceRemoteServiceReference != null) { // Invoke a method of the remote service exposed by the first instance passing on the command line // arguments and causing the first instance to activate itself firstInstanceRemoteServiceReference.InvokeFirstInstance(args); } } /// <summary> /// Callback for activating first instance of the application. /// </summary> /// <param name="arg">Callback argument.</param> /// <returns>Always null.</returns> private static object ActivateFirstInstanceCallback(object arg) { // Get command line args to be passed to first instance IList<string> args = arg as IList<string>; ActivateFirstInstance(args); return null; } /// <summary> /// Activates the first instance of the application with arguments from a second instance. /// </summary> /// <param name="args">List of arguments to supply the first instance of the application.</param> private static void ActivateFirstInstance(IList<string> args) { // Set main window state and process command line args if (Application.Current == null) { return; } ((TApplication)Application.Current).SignalExternalCommandLineArgs(args); } #endregion #region Private Classes /// <summary> /// Remoting service class which is exposed by the server i.e the first instance and called by the second instance /// to pass on the command line arguments to the first instance and cause it to activate itself. /// </summary> private class IPCRemoteService : MarshalByRefObject { /// <summary> /// Activates the first instance of the application. /// </summary> /// <param name="args">List of arguments to pass to the first instance.</param> public void InvokeFirstInstance(IList<string> args) { if (Application.Current != null) { // Do an asynchronous call to ActivateFirstInstance function Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Normal, new DispatcherOperationCallback(ActivateFirstInstanceCallback), args); } } /// <summary> /// Remoting Object's ease expires after every 5 minutes by default. We need to override the InitializeLifetimeService class /// to ensure that lease never expires. /// </summary> /// <returns>Always null.</returns> public override object InitializeLifetimeService() { return null; } } #endregion } }
ihtfw/Logazmic
src/Logazmic/Utils/SingleInstance.cs
C#
mit
15,765
using System; using System.Collections.Generic; /// <summary> /// Calculate sequence with queue. /// 100/100 /// https://judge.softuni.bg/Contests/Practice/Index/184#4 /// </summary> namespace _05._Sequence_With_Queue { class SequenceWithQueue { static void Main() { decimal n = decimal.Parse(Console.ReadLine()); Queue<decimal> sequence = new Queue<decimal>(); int counter = 0; //Print first num. Console.Write(n + " "); counter++; for (decimal i = 0; i < 50 / 3 + 1; i++) { //S1 sequence.Enqueue(n + 1); Console.Write(n + 1 + " "); counter++; if (counter==50) { //We need exaclly 50 numbers. break; } //S2 sequence.Enqueue(2 * n + 1); Console.Write(2 * n + 1 + " "); counter++; //S3 sequence.Enqueue(n + 2); Console.Write(n + 2 + " "); counter++; //We dequeue and we start the calculation again. n = sequence.Dequeue(); } Console.WriteLine(); } } }
delian1986/SoftUni-C-Sharp-repo
Old Courses/C# Advanced Old/01. Stacks Queues/StackQueueExercises/05. Sequence With Queue/SequenceWithQueue.cs
C#
mit
1,329
from math import sqrt def is_prime(x): for i in xrange(2, int(sqrt(x) + 1)): if x % i == 0: return False return True def rotate(v): res = [] u = str(v) while True: u = u[1:] + u[0] w = int(u) if w == v: break res.append(w) return res MILLION = 1000000 primes = filter(is_prime, range(2, MILLION)) s = set(primes) ans = 0 for item in primes: flag = True print item for y in rotate(item): if y not in s: flag = False if flag: ans += 1 print ans
neutronest/eulerproject-douby
e35/35.py
Python
mit
586
package main import ( "encoding/json" "errors" "fmt" "os" "github.com/idahobean/npm-resource/check" "github.com/idahobean/npm-resource/npm" ) func main() { NPM := npm.NewNPM() command := check.NewCommand(NPM) var request check.Request if err := json.NewDecoder(os.Stdin).Decode(&request); err != nil { fatal("reading request from stdin", err) } var err error if request.Source.PackageName == "" { err = errors.New("package_name") } if err != nil { fatal("parameter required", err) } response, err := command.Run(request) if err != nil { fatal("running command", err) } if err := json.NewEncoder(os.Stdout).Encode(response); err != nil { fatal("writing response to stdout", err) } } func fatal(message string, err error) { fmt.Fprintf(os.Stderr, "error %s: %s\n", message, err) os.Exit(1) }
idahobean/npm-resource
check/cmd/check/main.go
GO
mit
832
/* [Discuz!] (C)2001-2099 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: forum.js 33082 2013-04-18 11:13:53Z zhengqingpeng $ */ function saveData(ignoreempty) { var ignoreempty = isUndefined(ignoreempty) ? 0 : ignoreempty; var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : ($('fastpostform') ? $('fastpostform') : $('postform')); if(!obj) return; if(typeof isfirstpost != 'undefined') { if(typeof wysiwyg != 'undefined' && wysiwyg == 1) { var messageisnull = trim(html2bbcode(editdoc.body.innerHTML)) === ''; } else { var messageisnull = $('postform').message.value === ''; } if(isfirstpost && (messageisnull && $('postform').subject.value === '')) { return; } if(!isfirstpost && messageisnull) { return; } } var data = subject = message = ''; for(var i = 0; i < obj.elements.length; i++) { var el = obj.elements[i]; if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden' || el.type == 'select')) && el.name.substr(0, 6) != 'attach') { var elvalue = el.value; if(el.name == 'subject') { subject = trim(elvalue); } else if(el.name == 'message') { if(typeof wysiwyg != 'undefined' && wysiwyg == 1) { elvalue = html2bbcode(editdoc.body.innerHTML); } message = trim(elvalue); } if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) { continue; } else if(el.tagName == 'SELECT') { elvalue = el.value; } else if(el.type == 'hidden') { if(el.id) { eval('var check = typeof ' + el.id + '_upload == \'function\''); if(check) { elvalue = elvalue; if($(el.id + '_url')) { elvalue += String.fromCharCode(1) + $(el.id + '_url').value; } } else { continue; } } else { continue; } } if(trim(elvalue)) { data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9); } } } if(!subject && !message && !ignoreempty) { return; } saveUserdata('forum_'+discuz_uid, data); } function fastUload() { appendscript(JSPATH + 'forum_post.js?' + VERHASH); safescript('forum_post_js', function () { uploadWindow(function (aid, url) {updatefastpostattach(aid, url)}, 'file') }, 100, 50); } function switchAdvanceMode(url) { var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform'); if(obj && obj.message.value != '') { saveData(); url += (url.indexOf('?') != -1 ? '&' : '?') + 'cedit=yes'; } location.href = url; return false; } function sidebar_collapse(lang) { if(lang[0]) { toggle_collapse('sidebar', null, null, lang); $('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear'; } else { var collapsed = getcookie('collapse'); collapsed = updatestring(collapsed, 'sidebar', 1); setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000)); location.reload(); } } function keyPageScroll(e, prev, next, url, page) { if(loadUserdata('is_blindman')) { return true; } e = e ? e : window.event; var tagname = BROWSER.ie ? e.srcElement.tagName : e.target.tagName; if(tagname == 'INPUT' || tagname == 'TEXTAREA') return; actualCode = e.keyCode ? e.keyCode : e.charCode; if(next && actualCode == 39) { window.location = url + '&page=' + (page + 1); } if(prev && actualCode == 37) { window.location = url + '&page=' + (page - 1); } } function announcement() { var ann = new Object(); ann.anndelay = 3000;ann.annst = 0;ann.annstop = 0;ann.annrowcount = 0;ann.anncount = 0;ann.annlis = $('anc').getElementsByTagName("li");ann.annrows = new Array(); ann.announcementScroll = function () { if(this.annstop) {this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);return;} if(!this.annst) { var lasttop = -1; for(i = 0;i < this.annlis.length;i++) { if(lasttop != this.annlis[i].offsetTop) { if(lasttop == -1) lasttop = 0; this.annrows[this.annrowcount] = this.annlis[i].offsetTop - lasttop;this.annrowcount++; } lasttop = this.annlis[i].offsetTop; } if(this.annrows.length == 1) { $('an').onmouseover = $('an').onmouseout = null; } else { this.annrows[this.annrowcount] = this.annrows[1]; $('ancl').innerHTML += $('ancl').innerHTML; this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay); $('an').onmouseover = function () {ann.annstop = 1;}; $('an').onmouseout = function () {ann.annstop = 0;}; } this.annrowcount = 1; return; } if(this.annrowcount >= this.annrows.length) { $('anc').scrollTop = 0; this.annrowcount = 1; this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay); } else { this.anncount = 0; this.announcementScrollnext(this.annrows[this.annrowcount]); } }; ann.announcementScrollnext = function (time) { $('anc').scrollTop++; this.anncount++; if(this.anncount != time) { this.annst = setTimeout(function () {ann.announcementScrollnext(time);}, 10); } else { this.annrowcount++; this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay); } }; ann.announcementScroll(); } function removeindexheats() { return confirm('You to confirm that this topic should remove it from the hot topic?'); } function showTypes(id, mod) { var o = $(id); if(!o) return false; var s = o.className; mod = isUndefined(mod) ? 1 : mod; var baseh = o.getElementsByTagName('li')[0].offsetHeight * 2; var tmph = o.offsetHeight; var lang = ['Expansion', 'Collapse']; var cls = ['unfold', 'fold']; if(tmph > baseh) { var octrl = document.createElement('li'); octrl.className = cls[mod]; octrl.innerHTML = lang[mod]; o.insertBefore(octrl, o.firstChild); o.className = s + ' cttp'; mod && (o.style.height = 'auto'); octrl.onclick = function () { if(this.className == cls[0]) { o.style.height = 'auto'; this.className = cls[1]; this.innerHTML = lang[1]; } else { o.style.height = ''; this.className = cls[0]; this.innerHTML = lang[0]; } } } } var postpt = 0; function fastpostvalidate(theform, noajaxpost) { if(postpt) { return false; } postpt = 1; setTimeout(function() {postpt = 0}, 2000); noajaxpost = !noajaxpost ? 0 : noajaxpost; s = ''; if(typeof fastpostvalidateextra == 'function') { var v = fastpostvalidateextra(); if(!v) { return false; } } if(theform.message.value == '' || theform.subject.value == '') { s = 'Sorry, you can not enter a title or content'; theform.message.focus(); } else if(mb_strlen(theform.subject.value) > 80) { s = 'Your title is longer than 80 characters limit'; theform.subject.focus(); } if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) { s = 'Not meet the requirements of the length of your posts.\n\nCurrent length: ' + mb_strlen(theform.message.value) + ' ' + 'Byte\nSystem limits: ' + postminchars + ' to ' + postmaxchars + ' Byte'; } if(s) { showError(s); doane(); $('fastpostsubmit').disabled = false; return false; } $('fastpostsubmit').disabled = true; theform.message.value = theform.message.value.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]'); theform.message.value = parseurl(theform.message.value); if(!noajaxpost) { ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('fastpostsubmit')); return false; } else { return true; } } function updatefastpostattach(aid, url) { ajaxget('forum.php?mod=ajax&action=attachlist&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'attachlist'); $('attach_tblheader').style.display = ''; } function succeedhandle_fastnewpost(locationhref, message, param) { location.href = locationhref; } function errorhandle_fastnewpost() { $('fastpostsubmit').disabled = false; } function atarget(obj) { obj.target = getcookie('atarget') > 0 ? '_blank' : ''; } function setatarget(v) { $('atarget').className = 'y atarget_' + v; $('atarget').onclick = function() {setatarget(v == 1 ? -1 : 1);}; setcookie('atarget', v, 2592000); } function loadData(quiet, formobj) { var evalevent = function (obj) { var script = obj.parentNode.innerHTML; var re = /onclick="(.+?)["|>]/ig; var matches = re.exec(script); if(matches != null) { matches[1] = matches[1].replace(/this\./ig, 'obj.'); eval(matches[1]); } }; var data = ''; data = loadUserdata('forum_'+discuz_uid); var formobj = !formobj ? $('postform') : formobj; if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) { if(!quiet) { showDialog('No data can be restored!', 'info'); } return; } if(!quiet && !confirm('This action will overwrite the current content of the post, You sure you want to recover data?')) { return; } var data = data.split(/\x09\x09/); for(var i = 0; i < formobj.elements.length; i++) { var el = formobj.elements[i]; if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden'))) { for(var j = 0; j < data.length; j++) { var ele = data[j].split(/\x09/); if(ele[0] == el.name) { elvalue = !isUndefined(ele[3]) ? ele[3] : ''; if(ele[1] == 'INPUT') { if(ele[2] == 'text') { el.value = elvalue; } else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) { el.checked = true; evalevent(el); } else if(ele[2] == 'hidden') { eval('var check = typeof ' + el.id + '_upload == \'function\''); if(check) { var v = elvalue.split(/\x01/); el.value = v[0]; if(el.value) { if($(el.id + '_url') && v[1]) { $(el.id + '_url').value = v[1]; } eval(el.id + '_upload(\'' + v[0] + '\', \'' + v[1] + '\')'); if($('unused' + v[0])) { var attachtype = $('unused' + v[0]).parentNode.parentNode.parentNode.parentNode.id.substr(11); $('unused' + v[0]).parentNode.parentNode.outerHTML = ''; $('unusednum_' + attachtype).innerHTML = parseInt($('unusednum_' + attachtype).innerHTML) - 1; if($('unusednum_' + attachtype).innerHTML == 0 && $('attachnotice_' + attachtype)) { $('attachnotice_' + attachtype).style.display = 'none'; } } } } } } else if(ele[1] == 'TEXTAREA') { if(ele[0] == 'message') { if(!wysiwyg) { textobj.value = elvalue; } else { editdoc.body.innerHTML = bbcode2html(elvalue); } } else { el.value = elvalue; } } else if(ele[1] == 'SELECT') { if($(el.id + '_ctrl_menu')) { var lis = $(el.id + '_ctrl_menu').getElementsByTagName('li'); for(var k = 0; k < lis.length; k++) { if(ele[3] == lis[k].k_value) { lis[k].onclick(); break; } } } else { for(var k = 0; k < el.options.length; k++) { if(ele[3] == el.options[k].value) { el.options[k].selected = true; break; } } } } break; } } } } if($('rstnotice')) { $('rstnotice').style.display = 'none'; } extraCheckall(); } var checkForumcount = 0, checkForumtimeout = 30000, checkForumnew_handle; function checkForumnew(fid, lasttime) { var timeout = checkForumtimeout; var x = new Ajax(); x.get('forum.php?mod=ajax&action=forumchecknew&fid=' + fid + '&time=' + lasttime + '&inajax=yes', function(s){ if(s > 0) { var table = $('separatorline').parentNode; if(!isUndefined(checkForumnew_handle)) { clearTimeout(checkForumnew_handle); } removetbodyrow(table, 'forumnewshow'); var colspan = table.getElementsByTagName('tbody')[0].rows[0].children.length; var checknew = {'tid':'', 'thread':{'common':{'className':'', 'val':'<a href="javascript:void(0);" onclick="ajaxget(\'forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=1&inajax=yes\', \'forumnew\');">New topic Reply, Click to view', 'colspan': colspan }}}; addtbodyrow(table, ['tbody'], ['forumnewshow'], 'separatorline', checknew); } else { if(checkForumcount < 50) { if(checkForumcount > 0) { var multiple = Math.ceil(50 / checkForumcount); if(multiple < 5) { timeout = checkForumtimeout * (5 - multiple + 1); } } checkForumnew_handle = setTimeout(function () {checkForumnew(fid, lasttime);}, timeout); } } checkForumcount++; }); } function checkForumnew_btn(fid) { if(isUndefined(fid)) return; ajaxget('forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=2&inajax=yes', 'forumnew', 'ajaxwaitid'); lasttime = parseInt(Date.parse(new Date()) / 1000); } function addtbodyrow (table, insertID, changename, separatorid, jsonval) { if(isUndefined(table) || isUndefined(insertID[0])) { return; } var insertobj = document.createElement(insertID[0]); var thread = jsonval.thread; var tid = !isUndefined(jsonval.tid) ? jsonval.tid : '' ; if(!isUndefined(changename[1])) { removetbodyrow(table, changename[1] + tid); } insertobj.id = changename[0] + tid; if(!isUndefined(insertID[1])) { insertobj.className = insertID[1]; } if($(separatorid)) { table.insertBefore(insertobj, $(separatorid).nextSibling); } else { table.insertBefore(insertobj, table.firstChild); } var newTH = insertobj.insertRow(-1); for(var value in thread) { if(value != 0) { var cell = newTH.insertCell(-1); if(isUndefined(thread[value]['val'])) { cell.innerHTML = thread[value]; } else { cell.innerHTML = thread[value]['val']; } if(!isUndefined(thread[value]['className'])) { cell.className = thread[value]['className']; } if(!isUndefined(thread[value]['colspan'])) { cell.colSpan = thread[value]['colspan']; } } } if(!isUndefined(insertID[2])) { _attachEvent(insertobj, insertID[2], function() {insertobj.className = '';}); } } function removetbodyrow(from, objid) { if(!isUndefined(from) && $(objid)) { from.removeChild($(objid)); } } function leftside(id) { $(id).className = $(id).className == 'a' ? '' : 'a'; if(id == 'lf_fav') { setcookie('leftsidefav', $(id).className == 'a' ? 0 : 1, 2592000); } } var DTimers = new Array(); var DItemIDs = new Array(); var DTimers_exists = false; function settimer(timer, itemid) { if(timer && itemid) { DTimers.push(timer); DItemIDs.push(itemid); } if(!DTimers_exists) { setTimeout("showtime()", 1000); DTimers_exists = true; } } function showtime() { for(i=0; i<=DTimers.length; i++) { if(DItemIDs[i]) { if(DTimers[i] == 0) { $(DItemIDs[i]).innerHTML = 'Has ended'; DItemIDs[i] = ''; continue; } var timestr = ''; var timer_day = Math.floor(DTimers[i] / 86400); var timer_hour = Math.floor((DTimers[i] % 86400) / 3600); var timer_minute = Math.floor(((DTimers[i] % 86400) % 3600) / 60); var timer_second = (((DTimers[i] % 86400) % 3600) % 60); if(timer_day > 0) { timestr += timer_day + 'Day'; } if(timer_hour > 0) { timestr += timer_hour + 'Hour' } if(timer_minute > 0) { timestr += timer_minute + 'Min.' } if(timer_second > 0) { timestr += timer_second + 'Sec.' } DTimers[i] = DTimers[i] - 1; $(DItemIDs[i]).innerHTML = timestr; } } setTimeout("showtime()", 1000); } function fixed_top_nv(eleid, disbind) { this.nv = eleid && $(eleid) || $('nv'); this.openflag = this.nv && BROWSER.ie != 6; this.nvdata = {}; this.init = function (disattachevent) { if(this.openflag) { if(!disattachevent) { var obj = this; _attachEvent(window, 'resize', function(){obj.reset();obj.init(1);obj.run();}); var switchwidth = $('switchwidth'); if(switchwidth) { _attachEvent(switchwidth, 'click', function(){obj.reset();obj.openflag=false;}); } } var next = this.nv; try { while((next = next.nextSibling).nodeType != 1 || next.style.display === 'none') {} this.nvdata.next = next; this.nvdata.height = parseInt(this.nv.offsetHeight, 10); this.nvdata.width = parseInt(this.nv.offsetWidth, 10); this.nvdata.left = this.nv.getBoundingClientRect().left - document.documentElement.clientLeft; this.nvdata.position = this.nv.style.position; this.nvdata.opacity = this.nv.style.opacity; } catch (e) { this.nvdata.next = null; } } }; this.run = function () { var fixedheight = 0; if(this.openflag && this.nvdata.next){ var nvnexttop = document.body.scrollTop || document.documentElement.scrollTop; var dofixed = nvnexttop !== 0 && document.documentElement.clientHeight >= 15 && this.nvdata.next.getBoundingClientRect().top - this.nvdata.height < 0; if(dofixed) { if(this.nv.style.position != 'fixed') { this.nv.style.borderLeftWidth = '0'; this.nv.style.borderRightWidth = '0'; this.nv.style.height = this.nvdata.height + 'px'; this.nv.style.width = this.nvdata.width + 'px'; this.nv.style.top = '0'; this.nv.style.left = this.nvdata.left + 'px'; this.nv.style.position = 'fixed'; this.nv.style.zIndex = '199'; this.nv.style.opacity = 0.85; } } else { if(this.nv.style.position != this.nvdata.position) { this.reset(); } } if(this.nv.style.position == 'fixed') { fixedheight = this.nvdata.height; } } return fixedheight; }; this.reset = function () { if(this.nv) { this.nv.style.position = this.nvdata.position; this.nv.style.borderLeftWidth = ''; this.nv.style.borderRightWidth = ''; this.nv.style.height = ''; this.nv.style.width = ''; this.nv.style.opacity = this.nvdata.opacity; } }; if(!disbind && this.openflag) { this.init(); _attachEvent(window, 'scroll', this.run); } } var previewTbody = null, previewTid = null, previewDiv = null; function previewThread(tid, tbody) { if(!$('threadPreviewTR_'+tid)) { appendscript(JSPATH + 'forum_viewthread.js?' + VERHASH); newTr = document.createElement('tr'); newTr.id = 'threadPreviewTR_'+tid; newTr.className = 'threadpre'; $(tbody).appendChild(newTr); newTd = document.createElement('td'); newTd.colSpan = listcolspan; newTd.className = 'threadpretd'; newTr.appendChild(newTd); newTr.style.display = 'none'; previewTbody = tbody; previewTid = tid; if(BROWSER.ie) { previewDiv = document.createElement('div'); previewDiv.id = 'threadPreview_'+tid; previewDiv.style.id = 'none'; var x = Ajax(); x.get('forum.php?mod=viewthread&tid='+tid+'&inajax=1&from=preview', function(ret) { var evaled = false; if(ret.indexOf('ajaxerror') != -1) { evalscript(ret); evaled = true; } previewDiv.innerHTML = ret; newTd.appendChild(previewDiv); if(!evaled) evalscript(ret); newTr.style.display = ''; }); } else { newTd.innerHTML += '<div id="threadPreview_'+tid+'"></div>'; ajaxget('forum.php?mod=viewthread&tid='+tid+'&from=preview', 'threadPreview_'+tid, null, null, null, function() {newTr.style.display = '';}); } } else { $(tbody).removeChild($('threadPreviewTR_'+tid)); previewTbody = previewTid = null; } } function hideStickThread(tid) { var pre = 'stickthread_'; var tids = (new Function("return ("+(loadUserdata('sticktids') || '[]')+")"))(); var format = function (data) { var str = '{'; for (var i in data) { if(data[i] instanceof Array) { str += i + ':' + '['; for (var j = data[i].length - 1; j >= 0; j--) { str += data[i][j] + ','; }; str = str.substr(0, str.length -1); str += '],'; } } str = str.substr(0, str.length -1); str += '}'; return str; }; if(!tid) { if(tids.length > 0) { for (var i = tids.length - 1; i >= 0; i--) { var ele = $(pre+tids[i]); if(ele) { ele.parentNode.removeChild(ele); } }; } } else { var eletbody = $(pre+tid); if(eletbody) { eletbody.parentNode.removeChild(eletbody); tids.push(tid); saveUserdata('sticktids', '['+tids.join(',')+']'); } } var clearstickthread = $('clearstickthread'); if(clearstickthread) { if(tids.length > 0) { $('clearstickthread').style.display = ''; } else { $('clearstickthread').style.display = 'none'; } } var separatorline = $('separatorline'); if(separatorline) { try { if(typeof separatorline.previousElementSibling === 'undefined') { var findele = separatorline.previousSibling; while(findele && findele.nodeType != 1){ findele = findele.previousSibling; } if(findele === null) { separatorline.parentNode.removeChild(separatorline); } } else { if(separatorline.previousElementSibling === null) { separatorline.parentNode.removeChild(separatorline); } } } catch(e) { } } } function viewhot() { var obj = $('hottime'); window.location.href = "forum.php?mod=forumdisplay&filter=hot&fid="+obj.getAttribute('fid')+"&time="+obj.value; } function clearStickThread () { saveUserdata('sticktids', '[]'); location.reload(); }
zekewang918/QuitSmoking
bbs/static/js/forum.js
JavaScript
mit
22,328
<?php namespace InoOicClient\Oic\Exception; class InvalidErrorCodeException extends \RuntimeException { }
Yusuke-KOMIYAMA/aiv
binder/app/Vendor/ivan-novakov/php-openid-connect-client/src/InoOicClient/Oic/Exception/InvalidErrorCodeException.php
PHP
mit
115
/*jslint node: true */ 'use strict'; var npm = require('npm'); module.exports = Npm; function Npm (callback) { var conf = { jobs: 1 }; npm.load(conf, callback); } Npm.prototype.search = function (searchTerms, callback) { npm.commands.search(searchTerms, true, callback); }; Npm.prototype.view = function (name, callback) { npm.commands.view([name], callback); };
webjay/npm-search-store
lib/npm-api.js
JavaScript
mit
382
import { EmailTemplate } from 'email-templates' import Promise from 'bluebird' const sendgrid = require('sendgrid')(process.env.SENDGRID_MAILER_KEY) const sendEmail = Promise.promisify(sendgrid.send, { context: sendgrid }) const DEVELOPMENT = process.env.NODE_ENV === 'development' const sanitize = DEVELOPMENT ? require('sanitize-filename') : null import path from 'path' import fs from 'fs' export function getTemplate(templateName) { const templatePath = path.join(__dirname, '../', 'templates', templateName) return new EmailTemplate(templatePath, { juiceOptions: { preserveMediaQueries: true, preserveImportant: true, removeStyleTags: true } }) } export async function send({ template, sendgridGroupId, data, emailSettings, to, subject, replyto }) { // eslint-disable-line max-len try { const result = await template.render(data) if (DEVELOPMENT) { fs.writeFileSync( `${__dirname}/.temp/${sanitize(`test-${subject}-${to}.html`)}`, result.html) } const params = { from: emailSettings.from, fromname: emailSettings.fromName, replyto: replyto || emailSettings.from, to: [to], subject: `${subject}`, html: result.html } const sendgridEmail = new sendgrid.Email(params) sendgridEmail.setASMGroupID(sendgridGroupId) const email = await sendEmail(sendgridEmail) return { email } } catch (err) { console.log('send error: ', err) return { err } } }
LeadGrabr/api
src/services/email/mailers/helpers.js
JavaScript
mit
1,611
import React, { useState } from 'react'; import { StyleSheet, ImageStyle, LayoutChangeEvent } from 'react-native'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; import Animated, { useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, } from 'react-native-reanimated'; import { SafeAreaView } from 'react-native-safe-area-context'; import { useHeaderHeight } from '@react-navigation/stack'; const CHAT_HEADS = [ { imageUrl: 'https://avatars0.githubusercontent.com/u/379606?v=4&s=460' }, { imageUrl: 'https://avatars3.githubusercontent.com/u/90494?v=4&s=460' }, { imageUrl: 'https://avatars3.githubusercontent.com/u/726445?v=4&s=460' }, { imageUrl: 'https://avatars.githubusercontent.com/u/15989228?v=4&s=460' }, ]; interface AnimatedOffset { x: Animated.SharedValue<number>; y: Animated.SharedValue<number>; } interface FollowingChatHeadProps { imageUri: string; offset: AnimatedOffset; offsetToFollow: AnimatedOffset; style?: ImageStyle; } function FollowingChatHead({ imageUri, style, offset, offsetToFollow, }: FollowingChatHeadProps) { useDerivedValue(() => { offset.x.value = withSpring(offsetToFollow.x.value); offset.y.value = withSpring(offsetToFollow.y.value); }, []); const animatedStyle = useAnimatedStyle(() => { return { transform: [ { translateX: offset.x.value }, { translateY: offset.y.value }, ], }; }); return ( <Animated.Image style={[styles.box, style, animatedStyle]} source={{ uri: imageUri, }} /> ); } function useOffsetAnimatedValue() { return { x: useSharedValue(0), y: useSharedValue(0), }; } function clampToValues({ value, bottom, top, }: { value: number; bottom: number; top: number; }) { 'worklet'; return Math.max(bottom, Math.min(value, top)); } const Example = () => { const [dimensions, setDimensions] = useState({ width: 0, height: 0 }); const panOffset = useOffsetAnimatedValue(); const mainChatHeadPosition = useOffsetAnimatedValue(); const chatHeadsOffsets = CHAT_HEADS.map(useOffsetAnimatedValue); const headerHeight = useHeaderHeight(); const onLayout = ({ nativeEvent }: LayoutChangeEvent) => { const { width, height } = nativeEvent.layout; setDimensions({ width, height }); }; const panHandler = Gesture.Pan() .onUpdate(({ translationX, translationY }) => { 'worklet'; panOffset.x.value = mainChatHeadPosition.x.value + translationX; panOffset.y.value = mainChatHeadPosition.y.value + translationY; }) .onEnd(({ absoluteX, absoluteY, velocityX, velocityY }) => { 'worklet'; const { height, width } = dimensions; const velocityDragX = clampToValues({ value: velocityX * 0.05, bottom: -100, top: 100, }); const velocityDragY = clampToValues({ value: velocityY * 0.05, bottom: -100, top: 100, }); const distFromTop = absoluteY + velocityDragY - headerHeight; const distFromBottom = height + velocityDragY - absoluteY; const distFromLeft = absoluteX + velocityDragX; const distFromRight = width - absoluteX + velocityDragX; const minDist = Math.min( distFromTop, distFromBottom, distFromLeft, distFromRight ); // drag to the edge switch (minDist) { case distFromTop: { panOffset.y.value = withSpring(-IMAGE_SIZE / 2); panOffset.x.value = withSpring(panOffset.x.value + velocityDragX); mainChatHeadPosition.y.value = -IMAGE_SIZE / 2; mainChatHeadPosition.x.value = panOffset.x.value; break; } case distFromBottom: { panOffset.y.value = withSpring(height - IMAGE_SIZE / 2); panOffset.x.value = withSpring(panOffset.x.value + velocityDragX); mainChatHeadPosition.y.value = height - IMAGE_SIZE / 2; mainChatHeadPosition.x.value = panOffset.x.value; break; } case distFromLeft: { panOffset.x.value = withSpring(-IMAGE_SIZE / 2); panOffset.y.value = withSpring(panOffset.y.value + velocityDragY); mainChatHeadPosition.x.value = -IMAGE_SIZE / 2; mainChatHeadPosition.y.value = panOffset.y.value; break; } case distFromRight: { panOffset.x.value = withSpring(width - IMAGE_SIZE / 2); panOffset.y.value = withSpring(panOffset.y.value + velocityDragY); mainChatHeadPosition.x.value = width - IMAGE_SIZE / 2; mainChatHeadPosition.y.value = panOffset.y.value; break; } } }); const headsComponents = CHAT_HEADS.map(({ imageUrl }, idx) => { const headOffset = chatHeadsOffsets[idx]; if (idx === 0) { return ( <GestureDetector gesture={panHandler} key={imageUrl}> <FollowingChatHead offsetToFollow={panOffset} imageUri={imageUrl} offset={headOffset} /> </GestureDetector> ); } return ( <FollowingChatHead key={imageUrl} imageUri={imageUrl} style={{ marginLeft: idx * 5, marginTop: idx * 5, }} offset={headOffset} offsetToFollow={chatHeadsOffsets[idx - 1]} /> ); }); return ( <SafeAreaView style={styles.container} onLayout={onLayout}> {/* we want ChatHead with gesture on top */} {headsComponents.reverse()} </SafeAreaView> ); }; export default Example; const IMAGE_SIZE = 80; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF', }, box: { position: 'absolute', width: IMAGE_SIZE, height: IMAGE_SIZE, borderColor: '#F5FCFF', backgroundColor: 'plum', borderRadius: IMAGE_SIZE / 2, }, });
kmagiera/react-native-gesture-handler
example/src/new_api/chat_heads/index.tsx
TypeScript
mit
5,897
<?php namespace Extraload\Extractor; interface ExtractorInterface extends \Iterator { public function extract(); }
umpirsky/Extraload
src/Extraload/Extractor/ExtractorInterface.php
PHP
mit
121
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a Florincoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); ui->editTxComment->setPlaceholderText(tr("Enter a transaction comment (Note: This information is public)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; QString txcomment = ui->editTxComment->text(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { #if QT_VERSION < 0x050000 formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); #else formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address)); #endif } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(txcomment, recipients); else sendstatus = model->sendCoins(txcomment, recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed!"), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { ui->editTxComment->clear(); // Remove entries until only one left while(ui->entries->count()) { ui->entries->takeAt(0)->widget()->deleteLater(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); qApp->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { entry->deleteLater(); updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->editTxComment); prev = ui->editTxComment; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::setAddress(const QString &address) { SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setAddress(address); } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setVisible((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid Bitcoin address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
coinkeeper/2015-06-22_19-13_florincoin
src/qt/sendcoinsdialog.cpp
C++
mit
18,849
""" Copyright (c) 2016 Genome Research Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import time import sys import json try: import urllib.request as request from urllib.error import HTTPError except ImportError: import urllib2 as request from urllib2 import HTTPError import pandas PREV_TIME = time.time() IS_PYTHON3 = sys.version[0] == "3" def fix_missing_gene_symbols(de_novos, build='grch37'): """ adds gene symbols to variants lacking them. Args: de_novos: dataframe of de novo variants build: whether to use the 'grch37' or 'grch38' build (default=GRCh37) Returns: pandas Series of HGNC symbols, with additional annotations for many variants previously lacking a HGNC symbol. """ symbols = de_novos["symbol"].copy() # get the variants with no gene annotation, ensure chrom, start and stop # positions columns exist missing = de_novos[symbols == ""].copy() missing['end'] = missing["pos"] + missing["ref"].str.len() - 1 # find the HGNC symbols (if any) for the variants missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ] symbols[de_novos["symbol"] == ""] = missing # 360 out of 17000 de novos still lack HGNC symbols. Their consequences are: # # consequence count # ======================== ===== # downstream_gene_variant 17 # intergenic_variant 259 # regulatory_region_variant 63 # upstream_gene_variant 27 # # In spot checks, these are sufficiently distant from genes that we can't # add them to the analysis of their nearest gene. We shall analyse these # per site by giving them mock gene symbols. missing = de_novos[symbols == ""].copy() fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str) symbols[symbols == ""] = fake return symbols def open_url(url, headers): """ open url with python libraries Args: url: headers: Returns: tuple of http response, http response code, and http headers """ req = request.Request(url, headers=headers) try: handler = request.urlopen(req) except HTTPError as e: handler = e status_code = handler.getcode() response = handler.read() if IS_PYTHON3: response = response.decode("utf-8") # parse the headers into a key, value dictionary headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values())) return response, status_code, headers def rate_limit_requests(rate_limit=0.0667): """ limit ensembl requests to one per 0.067 s """ global PREV_TIME diff = time.time() - PREV_TIME if diff < rate_limit: time.sleep(rate_limit - diff) PREV_TIME = time.time() def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0): """find the hgnc symbol overlapping a variant position Args: variant: data frame or list for a variant, containing columns named "chrom", "start_pos", and "end_pos" for a single variant build: genome build to find consequences on verbose: flag indicating whether to print variants as they are checked Returns: a character string containing the HGNC symbol. """ attempts += 1 if attempts > 5: raise ValueError("too many attempts, figure out why its failing") rate_limit_requests() # define parts of the URL ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos) server_dict = {"grch37": "grch37.", "grch38": ""} base_url = "http://{}rest.ensembl.org".format(server_dict[build]) url = "{0}/{1}".format(base_url, ext) headers = {"Content-Type" : "application/json"} if verbose: print("chr{0}:{1} {2}".format(chrom, start_pos, ext)) response, status_code, requested_headers = open_url(url, headers) if status_code == 429: if "retry-after" in requested_headers: time.sleep(float(requested_headers["retry-after"])) elif "x-ratelimit-reset" in requested_headers: time.sleep(int(requested_headers["x-ratelimit-reset"])) return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts) elif status_code in [503, 504]: time.sleep(30) return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts) elif status_code != 200: raise ValueError('Invalid Ensembl response: {0}.\nSubmitted ' 'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code, base_url, ext, requested_headers, response)) json_text = json.loads(response) if len(json_text) > 0: return json_text[0]["external_name"] return ""
jeremymcrae/denovoFilter
denovoFilter/missing_symbols.py
Python
mit
5,967
MD.Keyboard = function(){ const keys = { "v": { name: "Select tool", cb: ()=> state.set("canvasMode", "select") }, "q": { name: "Freehand tool", cb: ()=> state.set("canvasMode", "fhpath") }, "l": { name: "Line tool", cb: ()=> state.set("canvasMode", "fhplineath")}, "r": { name: "Rectangle tool", cb: ()=> state.set("canvasMode", "rect")}, "o": { name: "Ellipse tool", cb: ()=> state.set("canvasMode", "ellipse")}, "s": { name: "Shape tool", cb: ()=> state.set("canvasMode", "shapelib")}, "p": { name: "Path tool", cb: ()=> state.set("canvasMode", "path")}, "t": { name: "Text tool", cb: ()=> state.set("canvasMode", "text")}, "z": { name: "Zoom tool", cb: ()=> state.set("canvasMode", "zoom")}, "e": { name: "Eyedropper tool", cb: ()=> state.set("canvasMode", "eyedropper")}, "x": { name: "Focus fill/stroke", cb: ()=> editor.focusPaint()}, "shift_x": { name: "Switch fill/stroke", cb: ()=> editor.switchPaint()}, "alt": { name: false, cb: ()=> $("#workarea").toggleClass("out", state.get("canvasMode") === "zoom" )}, "cmd_s": { name: "Save SVG File", cb: ()=> editor.save()}, "cmd_z": { name: "Undo", cb: ()=> editor.undo()}, "cmd_y": { name: "Redo", cb: ()=> editor.redo()}, "cmd_shift_z": { name: "Redo", cb: ()=> editor.redo()}, "cmd_c": { name: "Copy", cb: ()=> editor.copySelected()}, "cmd_x": { name: "Cut", cb: ()=> editor.cutSelected()}, "cmd_v": { name: "Paste", cb: ()=> editor.pasteSelected()}, "cmd_d": { name: "Duplicate", cb: ()=> editor.duplicateSelected()}, "cmd_u": { name: "View source", cb: ()=> editor.source()}, "cmd_a": { name: "Select All", cb: ()=> svgCanvas.selectAllInCurrentLayer()}, "cmd_b": { name: "Set bold text", cb: ()=> editor.text.setBold()}, "cmd_i": { name: "Set italic text", cb: ()=> editor.text.setItalic()}, "cmd_g": { name: "Group selected", cb: ()=> editor.groupSelected()}, "cmd_shift_g": { name: "Ungroup", cb: ()=> editor.ungroupSelected()}, "cmd_o": { name: "Open SVG File", cb: ()=> editor.import.open()}, "cmd_k": { name: "Place image", cb: ()=> editor.import.place()}, "backspace": { name: "Delete", cb: ()=> editor.deleteSelected()}, "delete": { name: "Delete", cb: ()=> editor.deleteSelected()}, "ctrl_arrowleft": { name: "Rotate -1deg", cb: ()=> editor.rotateSelected(0,1)}, "ctrl_arrowright": { name: "Rotate +1deg", cb: ()=> editor.rotateSelected(1,1)}, "ctrl_shift_arrowleft": { name: "Rotate -5deg", cb: ()=> editor.rotateSelected(0,5)}, "ctrl_shift_arrowright": { name: "Rotate +5deg ", cb: ()=> editor.rotateSelected(1,5)}, "shift_o": { name: "Next item", cb: ()=> svgCanvas.cycleElement(0)}, "shift_p": { name: "Prev item", cb: ()=> svgCanvas.cycleElement(1)}, "shift_r": { name: "Show/hide rulers", cb: ()=> editor.rulers.toggleRulers()}, "cmd_+": { name: "Zoom in", cb: ()=> editor.zoom.multiply(1.5)}, "cmd_-": { name: "Zoom out", cb: ()=> editor.zoom.multiply(0.75)}, "cmd_=": { name: "Actual size", cb: ()=> editor.zoom.reset()}, "arrowleft": { name: "Nudge left", cb: ()=> editor.moveSelected(-1,0)}, "arrowright": { name: "Nudge right", cb: ()=> editor.moveSelected(1,0)}, "arrowup": { name: "Nudge up", cb: ()=> editor.moveSelected(0,-1)}, "arrowdown": { name: "Nudge down", cb: ()=> editor.moveSelected(0,1)}, "shift_arrowleft": {name: "Jump left", cb: () => editor.moveSelected(state.get("canvasSnapStep") * -1, 0)}, "shift_arrowright": {name: "Jump right", cb: () => editor.moveSelected(state.get("canvasSnapStep") * 1, 0)}, "shift_arrowup": {name: "Jump up", cb: () => editor.moveSelected(0, state.get("canvasSnapStep") * -1)}, "shift_arrowdown": {name: "Jump down", cb: () => editor.moveSelected(0, state.get("canvasSnapStep") * 1)}, "cmd_arrowup":{ name: "Bring forward", cb: () => editor.moveUpSelected()}, "cmd_arrowdown":{ name: "Send backward", cb: () => editor.moveDownSelected()}, "cmd_shift_arrowup":{ name: "Bring to front", cb: () => editor.moveToTopSelected()}, "cmd_shift_arrowdown":{ name: "Send to back", cb: () => editor.moveToBottomSelected()}, "escape": { name: false, cb: ()=> editor.escapeMode()}, "enter": { name: false, cb: ()=> editor.escapeMode()}, " ": { name: "Pan canvas", cb: (e)=> editor.pan.startPan(e)}, }; document.addEventListener("keydown", function(e){ const exceptions = $(":focus").length || $("#color_picker").is(":visible"); if (exceptions) return false; const modKey = !svgedit.browser.isMac() ? "ctrlKey" : "metaKey"; const cmd = e[modKey] ? "cmd_" : ""; const shift = e.shiftKey ? "shift_" : ""; const key = cmd + shift + e.key.toLowerCase(); const canvasMode = state.get("canvasMode"); const modalIsOpen = Object.values(editor.modal).filter((modal) => { const isHidden = modal.el.classList.contains("hidden"); if (!isHidden && key === "cmd_enter") modal.confirm(); if (!isHidden && key === "escape") modal.close(); return !isHidden; }).length; // keyboard shortcut exists for app if (!modalIsOpen && keys[key]) { e.preventDefault(); keys[key].cb(); } }); document.addEventListener("keyup", function(e){ if ($("#color_picker").is(":visible")) return e; const canvasMode = state.get("canvasMode"); const key = e.key.toLowerCase(); const keys = { "alt": ()=> $("#workarea").removeClass("out"), " ": ()=> editor.pan.stopPan(), } if (keys[key]) { e.preventDefault(); keys[key](); } }) // modal shortcuts const shortcutEl = document.getElementById("shortcuts"); const docFrag = document.createDocumentFragment(); for (const key in keys) { const name = keys[key].name; if (!name) continue; const shortcut = document.createElement("div"); shortcut.classList.add("shortcut") const chords = key.split("_"); const shortcutKeys = document.createElement("div"); shortcutKeys.classList.add("shortcut-keys") chords.forEach(key => { const shortcutKey = document.createElement("div"); shortcutKey.classList.add("shortcut-key"); if (key === "arrowright") key = "→"; if (key === "arrowleft") key = "←"; if (key === "arrowup") key = "↑"; if (key === "arrowdown") key = "↓"; if (key === " ") key = "SPACEBAR"; if (key === "shift") key = "⇧"; if (key === "cmd") key = svgedit.browser.isMac() ? "⌘" : "Ctrl"; shortcutKey.textContent = key; shortcutKeys.appendChild(shortcutKey); shortcut.appendChild(shortcutKeys); }); const shortcutName = document.createElement("div"); shortcutName.classList.add("shortcut-name"); shortcutName.textContent = name; shortcutKeys.appendChild(shortcutName); docFrag.appendChild(shortcutKeys); } shortcutEl.appendChild(docFrag); }
duopixel/Method-Draw
src/js/Keyboard.js
JavaScript
mit
7,291
using System; using System.Linq; using System.Windows.Media; using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Rendering; using SolutionsUtilities.UI.WPF.Highlighting; namespace Barings.Controls.WPF.CodeEditors.Highlighting { public class HighlightMatchingWords : DocumentColorizingTransformer { public string Word { private get; set; } //public string Theme { get; set; } public HighlightMatchingWords(string word = null) { Word = word ?? "testing"; } private bool ValidateWord(int startOffset, int endOffset) { // Validate that a word at the given offset is equal ONLY to the current Word var document = CurrentContext.Document; // If the text before or after is at the beginning or end of the text, set it to a space to make it a stop character var textBeforeOffset = startOffset - 1 < 0 ? " " : document.GetText(startOffset - 1, 1); var textAfterOffset = endOffset + 1 > document.TextLength ? " " : document.GetText(endOffset, 1); // Return the result of this expression return AvalonEditExtensions.StopCharacters.Any(textBeforeOffset.Contains) && AvalonEditExtensions.StopCharacters.Any(textAfterOffset.Contains); } protected override void ColorizeLine(DocumentLine line) { if (string.IsNullOrEmpty(Word) || Word == Environment.NewLine) return; int lineStartOffset = line.Offset; string text = CurrentContext.Document.GetText(line); int start = 0; int index; var backgroundBrush = new SolidColorBrush(Color.FromArgb(80, 124, 172, 255)); while ((index = text.IndexOf(Word, start, StringComparison.OrdinalIgnoreCase)) >= 0) { int startOffset = lineStartOffset + index; int endOffset = lineStartOffset + index + Word.Length; if (!ValidateWord(startOffset, endOffset)) { start = index + 1; continue; } ChangeLinePart( startOffset, // startOffset endOffset, // endOffset element => { // This lambda gets called once for every VisualLineElement // between the specified offsets. element.TextRunProperties.SetBackgroundBrush(backgroundBrush); }); start = index + 1; // search for next occurrence } } } }
Barings/Barings.Controls.WPF
Barings.Controls.WPF/CodeEditors/Highlighting/HighlightMatchingWords.cs
C#
mit
2,681
<!-- Map --> <section id="contact" class="map"> <div class="container"> <div class="row text-left"> <div class="col-lg-12 "> <div class="row"> <div class="col-lg-12"> <h4 style="color:#006e89"><?php echo $kelas[0]['TRAINING']?></h4> <div class="panel panel-warning"> <div class="panel-heading"><h4 >Silahkan Pilih Instruktur dan Module</h4> </div> <form method="post" action = "<?php echo site_url('evaluasi/eval_nps'); ?>" enctype="multipart/form-data" accept-charset="utf-8"> <input class="form-control" type ="hidden" name="frametext_id" value="<?php echo $frame_id; ?>" > <div class="list-group"> <?php $no = 1; if(!empty($class_today)){ foreach($class_today as $row){ $wheres =array( 'frametext_id'=>$row->frametext_id, 'person_id'=>$person_id, 'module_id'=>$row->m_module_id, 'instructor_id'=>$row->m_instructor_id ); $cek = $this->model_dop->get_table_wheres('t_eval_nps',$wheres); if(empty($cek)){ ?> <input class="form-control" type ="hidden" name="instructor_id_<?php echo $no; ?>" value="<?php echo $row->m_instructor_id; ?>" > <input class="form-control" type ="hidden" name="module_id_<?php echo $no; ?>" value="<?php echo $row->m_module_id; ?>" > <a href="#" class="list-group-item" style="color:#006e89"> <label style='font-size: 12px'><input type="checkbox" name="eval_<?php echo $no; ?>" value="1"> <?php echo $row->INSTRUCTOR_NAME; $no++;?> <br/> <?php echo $row->MODULE_NAME; ?> </label><br/> </a> <?php }}}?> <input class="form-control" type ="hidden" name="jml_row" value="<?php echo $no; ?>" > <?php if(empty($cek)){?><button type="submit" class="btn btn-warning btn-lg btn-block">Mulai</button><hr/><?php } ?> <a href="<?php echo site_url('evaluasi/pelatihan/').'/'.$row->frametext_id; ?>" class="list-group-item active" > <h4>Evaluasi Sarana Pelatihan</h4> </a> </div> </form> </div> </div> </div><br/> </div> </div> </div>
dodolangus/rep_bnv_app
application/views/event/eval_ins_nps.php
PHP
mit
2,357
<?php /** * SalesChannel * * PHP version 5 * * @category Class * @package BrightpearlApiClient * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ /** * Copyright 2016 SmartBear Software * * 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. */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace BrightpearlApiClient\Model; use \ArrayAccess; /** * SalesChannel Class Doc Comment * * @category Class * @description * @package BrightpearlApiClient * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ class SalesChannel implements ArrayAccess { /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( 'sales_channel_name' => 'string', 'product_name' => 'string', 'product_condition' => 'string', 'categories' => '\BrightpearlApiClient\Model\SalesChannelCategories[]', 'description' => '\BrightpearlApiClient\Model\SalesChannelDescription', 'short_description' => '\BrightpearlApiClient\Model\SalesChannelShortDescription' ); /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ static $attributeMap = array( 'sales_channel_name' => 'salesChannelName', 'product_name' => 'productName', 'product_condition' => 'productCondition', 'categories' => 'categories', 'description' => 'description', 'short_description' => 'shortDescription' ); /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ static $setters = array( 'sales_channel_name' => 'setSalesChannelName', 'product_name' => 'setProductName', 'product_condition' => 'setProductCondition', 'categories' => 'setCategories', 'description' => 'setDescription', 'short_description' => 'setShortDescription' ); /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ static $getters = array( 'sales_channel_name' => 'getSalesChannelName', 'product_name' => 'getProductName', 'product_condition' => 'getProductCondition', 'categories' => 'getCategories', 'description' => 'getDescription', 'short_description' => 'getShortDescription' ); /** * $sales_channel_name * @var string */ protected $sales_channel_name; /** * $product_name * @var string */ protected $product_name; /** * $product_condition * @var string */ protected $product_condition; /** * $categories * @var \BrightpearlApiClient\Model\SalesChannelCategories[] */ protected $categories; /** * $description * @var \BrightpearlApiClient\Model\SalesChannelDescription */ protected $description; /** * $short_description * @var \BrightpearlApiClient\Model\SalesChannelShortDescription */ protected $short_description; /** * Constructor * @param mixed[] $data Associated array of property value initalizing the model */ public function __construct(array $data = null) { if ($data != null) { $this->sales_channel_name = $data["sales_channel_name"]; $this->product_name = $data["product_name"]; $this->product_condition = $data["product_condition"]; $this->categories = $data["categories"]; $this->description = $data["description"]; $this->short_description = $data["short_description"]; } } /** * Gets sales_channel_name * @return string */ public function getSalesChannelName() { return $this->sales_channel_name; } /** * Sets sales_channel_name * @param string $sales_channel_name * @return $this */ public function setSalesChannelName($sales_channel_name) { // $allowed_values = array("Brightpearl"); // if (!in_array($sales_channel_name, $allowed_values)) { // } $sales_channel_name = "Brightpearl"; $this->sales_channel_name = $sales_channel_name; return $this; } /** * Gets product_name * @return string */ public function getProductName() { return $this->product_name; } /** * Sets product_name * @param string $product_name * @return $this */ public function setProductName($product_name) { $this->product_name = $product_name; return $this; } /** * Gets product_condition * @return string */ public function getProductCondition() { return $this->product_condition; } /** * Sets product_condition * @param string $product_condition * @return $this */ public function setProductCondition($product_condition) { $allowed_values = array("new", "used", "refurbished"); if (!in_array($product_condition, $allowed_values)) { throw new \InvalidArgumentException("Invalid value for 'product_condition', must be one of 'new', 'used', 'refurbished'"); } $this->product_condition = $product_condition; return $this; } /** * Gets categories * @return \BrightpearlApiClient\Model\SalesChannelCategories[] */ public function getCategories() { return $this->categories; } /** * Sets categories * @param \BrightpearlApiClient\Model\SalesChannelCategories[] $categories * @return $this */ public function setCategories($categories) { $this->categories = $categories; return $this; } /** * Gets description * @return \BrightpearlApiClient\Model\SalesChannelDescription */ public function getDescription() { return $this->description; } /** * Sets description * @param \BrightpearlApiClient\Model\SalesChannelDescription $description * @return $this */ public function setDescription($description) { $this->description = $description; return $this; } /** * Gets short_description * @return \BrightpearlApiClient\Model\SalesChannelShortDescription */ public function getShortDescription() { return $this->short_description; } /** * Sets short_description * @param \BrightpearlApiClient\Model\SalesChannelShortDescription $short_description * @return $this */ public function setShortDescription($short_description) { $this->short_description = $short_description; return $this; } /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) { return isset($this->$offset); } /** * Gets offset. * @param integer $offset Offset * @return mixed */ public function offsetGet($offset) { return $this->$offset; } /** * Sets value based on offset. * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ public function offsetSet($offset, $value) { $this->$offset = $value; } /** * Unsets offset. * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->$offset); } /** * Gets the string presentation of the object * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { return json_encode(\BrightpearlApiClient\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); } else { return json_encode(\BrightpearlApiClient\ObjectSerializer::sanitizeForSerialization($this)); } } }
annex-apps/tenant-bundle
BrightpearlApiClient/lib/Model/SalesChannel.php
PHP
mit
9,169
<div class="row"> <div id="base_url" data-base="<?php echo base_url(); ?>"></div> <div class="col-lg-4 col-md-6"> <div class="x_panel"> <div class="x_title"> <h2><i class="fa fa-file"></i> Edit Form</h2> <div class="clearfix"></div> </div> <div class="x_content"> <!-- required for floating --> <!-- Nav tabs --> <ul class="nav nav-tabs bar_tabs"> <li class="active"><a href="#settings" data-toggle="tab" aria-expanded="true">Form Settings</a> </li> <li class=""><a href="#inputs" data-toggle="tab" aria-expanded="false">Form Inputs</a> </li> </ul> <!-- Tab panes --> <div class="clearfix"></div> <div class="tab-content"> <!-- FORM SETTINGS --> <div class="tab-pane active" id="settings"> <div class="form-group"> <label><span class="text-danger">*</span> Form Name</label> <input type="text" class="form-control" maxlength="50" minlength="2" name="form_name" value="<?php echo $form['form_settings']['name']; ?>" required> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label><span class="text-danger">*</span> Cost</label> <input type="text" class="form-control money" maxlength="50" minlength="2" value="<?php echo number_format($form['form_settings']['cost'], 2); ?>" name="form_cost" required placeholder="0.00"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label><span class="text-danger">*</span> Min. Payment</label> <input type="text" class="form-control money" maxlength="50" minlength="2" value="<?php echo number_format($form['form_settings']['min_cost'], 2); ?>" name="min_payment" required placeholder="0.00"> </div> </div> </div> <div class="form-group"> <label>Form Header</label> <textarea name="form_header" class="form-control" style="min-height:100px"><?php echo $form['form_settings']['header']; ?></textarea> </div> <div class="form-group"> <label>Form Footer</label> <textarea name="form_footer" class="form-control" style="min-height:100px"><?php echo $form['form_settings']['footer']; ?></textarea> </div> <div class="checkbox"> <label><input type="checkbox" name="is_active" <?php echo $form['form_settings']['active'] == 0 ? '' : 'checked'; ?>> Activate Form</label> </div> </div> <!-- FORM INPUTS --> <div class="tab-pane fade" data-url="<?php echo base_url('forms/add-input'); ?>" id="inputs"> <div class="form-group"> <label><span class="text-danger">*</span> Input Label</labeL> <input type="text" required class="form-control" name="input_label" maxlength="20" minlength="2"> </div> <div class="form-group"> <label><span class="text-danger">*</span> Input Name <small>(must be unique)</small></labeL> <input type="text" required class="form-control" name="input_name" maxlength="20" minlength="2"> </div> <br> <div class="row"> <div class="col-xs-6"> <div class="validation"> <button class="btn btn-info" data-toggle="modal" data-target="#validationRules">Set Validation Rules</button> </div> </div> <div class="col-xs-6"> <div class="clear-validation"> <button class="btn btn-warning pull-right">Clear Rules</button> </div> </div> </div> <br> <label>Input Validations Selected</label> <div class="form-group"> <input type="text" id="input_validations" value="" class="form-control" name="input_validations" readonly> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>Custom Class</label> <input type="text" class="form-control" name="input_class" maxlength="50"> </div> </div> <div class="col-md-6"> <br> <button class="btn btn-default pull-right" data-toggle="modal" data-target="#preBuiltClasses">View Presets</button> </div> </div> <div class="row"> <div class="col-sm-6 col-md-12 col-lg-6"> <div class="form-group"> <label><span class="text-danger">*</span> Input Type</labeL> <select name="input_type" class="form-control"> <option value="">Select One</option> <?php $inputType = array('text' => 'Single Line Input', 'select' => 'Select Box', 'textarea' => 'Multi-line Text Input', 'checkbox' => 'Check Boxes', 'radio' => 'Radio Buttons'); foreach($inputType as $key => $type) { echo '<option value="'.$key.'">'.ucwords($type).'</option>'; } ?> </select> </div> </div> <div class="col-sm-6 col-md-12 col-lg-6"> <div class="form-group"> <label><span class="text-danger">*</span> Column Width</labeL> <select name="input_columns" class="form-control"> <option value="">Select One</option> <?php $columns = array( 'col-md-1', 'col-md-2', 'col-md-3', 'col-md-4', 'col-md-5', 'col-md-6', 'col-md-7', 'col-md-8', 'col-md-9', 'col-md-10', 'col-md-11', 'col-md-12', ); foreach($columns as $key => $column) { echo '<option value="'.$column.'">'.($key+1).' Columns Wide</option>'; } ?> </select> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="row"> <div class="col-md-8"> <div class="input-group"> <label>Sequence</label> <select id="inputSequence" name="sequence" class="form-control"> <?php if(!empty($inputs)) { $count = 0; for($i=0;$i<count($inputs);$i++) { echo '<option>'.($i+1).'</option>'; $count++; } echo '<option selected>'.($count+1).'</option>'; } else { echo '<option>1</option>'; } ?> </select> </div> </div> </div> </div> <div class="col-md-6"> <br> <label><input type="checkbox" name="encrypt_data"> <i class="fa fa-question-circle" data-toggle="tooltip" data-title="If checked the input data that the user submits will be encrypted in the database and un-encrypted when you view it for safer storage."></i> Encrypt Input Data?</label> </div> </div> <div id="inputOptions" class="hide well well-sm"> <p><b><span class="text-danger">*</span> Add Input Values</b></p> <div id="inlineElement" class="checkbox hide"> <label><input type="checkbox" name="inline-element" value="yes"> Inline Elements</label> </div> <div class="modelInput row"> <div class="col-xs-5"> <div class="form-group"> <label><span class="text-danger">*</span> Label</label> <input type="text" id="inputOptionLabel" name="option_label_1" class="form-control" maxlength="40"> </div> </div> <div class="col-xs-5"> <div class="form-group"> <label><span class="text-danger">*</span> Value</label> <input type="text" id="inputOptionValue" name="option_value_1" class="form-control" maxlength="40"> </div> </div> <div class="col-xs-2"> <button class="btn btn-info insertNewOption pull-right"><i class="fa fa-plus"></i></button> </div> </div> <ul id="inputValuesSet" class="list-group"> </ul> <input type="hidden" id="formInputId" value=""> <input type="hidden" id="formId" value="<?php echo $form['form_settings']['id']; ?>"> <input type="hidden" id="sequenceId"> </div> <hr> <button id="addInput" class="btn btn-info pull-right"><i class="fa fa-share"></i> Save Input</button> <div class="clearfix"></div> </div> </div> <hr> <button id="saveNewForm" class="btn btn-primary">Save Form</button> </div> </div> </div> <div class="col-lg-8 col-md-6"> <div class="x_panel"> <div class="x_title"> <h2><i class="fa fa-file-o"></i> <span id="formName">Form Preview</span></h2> <div class="clearfix"></div> </div> <div class="x_content"> <div id="form-header"><?php echo $form['form_settings']['header']; ?></div> <hr> <div id="form-inputs" class="row grid-stack"> <?php if(!empty($form['form_inputs'])) { foreach($form['form_inputs'] as $key => $val) { switch($val['input_type']) { case 'text': echo '<div class="'.$val['input_columns'].' grid-stack formInputObject" data-sequence="'.$val['sequence'].'" data-validation="'.$val['input_validation'].'" data-id="'.$val['input_id'].'">'; echo '<div class="form-group">'; $required = ''; if (strpos($val['input_validation'], 'required') !== false) { $required = '<span class="text-danger">*</span> '; } echo '<label>'.$required.$val['input_label'].'</label>'; echo '<input class="'.$val['custom_class'].' form-control" name="'.$val['input_name'].'"/>'; echo '</div>'; if($val['encrypt_data']) { echo '<i class="encryptedIcon fa fa-lock"></i>'; } echo '</div>'; break; case 'select': echo '<div class="'.$val['input_columns'].' grid-stack formInputObject" data-sequence="'.$val['sequence'].'" data-validation="'.$val['input_validation'].'" data-id="'.$val['input_id'].'">'; echo '<div class="form-group">'; $required = ''; if (strpos($val['input_validation'], 'required') !== false) { $required = '<span class="text-danger">*</span> '; } echo '<label>'.$required.$val['input_label'].'</label>'; echo '<select class="'.$val['custom_class'].' form-control" name="'.$val['input_name'].'">'; echo '<option value="">Select One</option>'; foreach($val['options'] as $option) { echo '<option value="'.$option['value'].'">'.$option['name'].'</option>'; } echo '</select>'; echo '</div>'; if($val['encrypt_data']) { echo '<i class="encryptedIcon fa fa-lock"></i>'; } echo '</div>'; break; case 'textarea': echo '<div class="'.$val['input_columns'].' grid-stack formInputObject" data-sequence="'.$val['sequence'].'" data-validation="'.$val['input_validation'].'" data-id="'.$val['input_id'].'">'; echo '<div class="form-group">'; echo '<label>'.$val['input_label'].'</label>'; echo '<textarea class="'.$val['custom_class'].' form-control" name="'.$val['input_name'].'"></textarea>'; echo '</div>'; if($val['encrypt_data']) { echo '<i class="encryptedIcon fa fa-lock"></i>'; } echo '</div>'; break; case 'checkbox': echo '<div class="'.$val['input_columns'].' grid-stack formInputObject" data-sequence="'.$val['sequence'].'" data-validation="'.$val['input_validation'].'" data-id="'.$val['input_id'].'">'; $required = ''; if (strpos($val['input_validation'], 'required') !== false) { $required = '<span class="text-danger">*</span> '; } echo '<label>'.$required.$val['input_label'].'</label><br>'; foreach($val['options'] as $option) { $inline = 'checkbox'; if($val['input_inline']) { $inline = 'checkbox-inline'; } echo '<div class="'.$inline.'">'; echo '<label><input type="checkbox" class="' . $val['custom_class'] . '" name="' . $option['name'] . '[]" value="'.$option['value'].'"> ' . $option['name'] . '</label>'; echo '</div>'; } if($val['encrypt_data']) { echo '<i class="encryptedIcon fa fa-lock"></i>'; } echo '</div>'; break; default: break; } } } ?> </div> <div class="clearfix"></div> <hr> <div id="form-footer"><?php echo $form['form_settings']['footer']; ?></div> </div> </div> </div> </div> </div> <!-- EXTRA DIV FOR SOME REASON ITS NEEDED --> <div id="preBuiltClasses" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title"><i class="fa fa-wrench"></i> Prebuilt Classes</h4> </div> <div class="modal-body"> <p>Prebuilt classes will format data as the user types in the input boxes. Please make sure that you only use one of the following class types or the data won't work as expected.</p> <ul class="list-group"> <li class="list-group-item">Use "date" to format the input (00/00/0000) <button class="btn btn-primary pull-right prebuiltClass btn-sm" data-type="use">Use</button></li> <li class="list-group-item">Uce "time" to format the input (00:00:00) <button class="btn btn-primary pull-right prebuiltClass btn-sm" data-type="time">Use</button></li> <li class="list-group-item">Use "date_time" to format the input (00/00/0000 00:00:00) <button class="btn btn-primary pull-right prebuiltClass btn-sm" data-type="date_time">Use</button></li> <li class="list-group-item">Use "phone" to format the input ((000) 000-0000) <button class="btn btn-primary pull-right prebuiltClass btn-sm" data-type="phone">Use</button></li> <li class="list-group-item">Use "money" to format the input (00.00) <button class="btn btn-primary pull-right prebuiltClass btn-sm" data-type="money">Use</button></li> <li class="list-group-item">Use "ssn" to format the input (000-00-0000) <button class="btn btn-primary pull-right prebuiltClass btn-sm" data-type="ssn">Use</button></li> </ul> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <div id="validationRules" class="modal fade" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title"><i class="fa fa-check-circle-o"></i> Input Validation Rules</h4> </div> <div class="modal-body"> <form id="validationForm" action="<?php echo base_url('forms/format_validation_rules'); ?>"> <div class="row"> <?php $i=0; foreach($validation_options as $option) { ?> <div class="col-md-6"> <div class="row"> <?php if($option->parameter) { echo '<div class="col-md-8">'; } else { echo '<div class="col-md-12">'; } ?> <div class="checkbox"> <label style="padding-left:0"> <input type="checkbox" name="type_<?= $i ?>" value="<?= $option->type; ?>"> <b style="font-size: 1.4em;"><?= $option->label; ?></b> </label> </div> <span><i class="fa fa-question-circle fa-fw"></i> <?= str_replace('Returns FALSE', 'Fails the forms submission', $option->description); ?></span> </div> <?php if($option->parameter) { echo '<div class="col-md-4">'; echo '<div class="form-group param">'; echo '<label>'; echo 'Parameter'; echo '</label>'; $maxLength = ''; if($option->param_type == 'number') { $maxLength = 'max=255'; } echo '<input type="'.$option->param_type.'" '.$maxLength.' class="form-control" name="parameter_'.$i.'">'; echo '<div class="formErrors text-danger"></div>'; echo '</div>'; echo '</div>'; } ?> </div> <hr> </div> <?php if($i%2) { echo '</div><div class="row">';} ?> <?php $i++; } ?> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button class="btn btn-info" id="addValidationToInput">Add Rules</button> </div> </div> </div> </div>
bworkman1/lapp
application/views/forms/edit-form.php
PHP
mit
24,529
<?php class dmFrontWebController extends sfFrontWebController { /** * @see sfFrontWebController */ public function redirect($url, $delay = 0, $statusCode = 302) { $this->dispatcher->notify(new sfEvent($this, 'dm.controller.redirect')); return parent::redirect($url, $delay, $statusCode); } }
Symfony-Plugins/diemPlugin
dmCorePlugin/lib/controller/dmFrontWebController.php
PHP
mit
319
// React app import React from 'react' import {render} from 'react-dom' import App from './components/base_layout/App.jsx' // Redux state manager import { Provider } from 'react-redux' import { createStore } from 'redux' import reducers from './state_manager/reducers' // Electron IPC communication events import ipcRendererEvents from './ipc_layer/ipcRendererEvents' ////////////////////////// /// React Application //// ////////////////////////// export let store = createStore(reducers) render( <Provider store={store}> <App /> </Provider>, document.getElementById('app') ) ////////////////////////////// /// IPC with main process //// ////////////////////////////// ipcRendererEvents(store) /////////////////// /// Workarounds /// /////////////////// /* The chunk below will be executed after the react app is rendered */ import {resizer} from './components/base_layout/layout.css' let nav = document.querySelector('nav') let node = document.querySelector('.'+resizer) let startX, startWidth const initDrag = e => { startX = e.clientX startWidth = parseInt(window.getComputedStyle(nav).width) window.addEventListener('mousemove', doDrag, false) window.addEventListener('mouseup', stopDrag, false) } const doDrag = e => { const newWidth = (startWidth + e.clientX - startX) nav.style.width = (newWidth < 200 ? 200 : (newWidth > 400 ? 400: newWidth) ) + 'px' } const stopDrag = e => { window.removeEventListener('mousemove', doDrag, false) window.removeEventListener('mouseup', stopDrag, false) } node.addEventListener('mousedown', initDrag, false)
pastahito/remus
src/renderer_process/app/entry.js
JavaScript
mit
1,603
var mongoose = require('mongoose'), bcrypt = require('bcrypt'), userSchema = mongoose.Schema({ fullName: { type: String }, email: { type: String, required: true, unique: true, lowercase: true }, password: { type: String, required: true }, user_avatar: { type: String, default: 'http://s3.amazonaws.com/37assets/svn/765-default-avatar.png' }, registered_on: { type: Date, default: Date.now } }); userSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(user.password, salt, function(err, hash) { user.password = hash; next(); }); }); }); userSchema.methods.comparePassword = function(password, done) { bcrypt.compare(password, this.password, function(err, isMatch) { done(err, isMatch); }); }; module.exports = mongoose.model('User', userSchema, 'users');
goodheads/yourtube
server/models/user.server.model.js
JavaScript
mit
984
try: from calais import Calais except ImportError: # pragma: no cover Calais = None # NOQA if Calais is not None: def process_calais(content, key): calais = Calais(key) response = calais.analyze(content) people = [entity["name"] for entity in getattr(response, "entities", []) if entity["_type"] == "Person"] return {"people": people}
prologic/spyda
spyda/processors.py
Python
mit
385
import datetime day = datetime.datetime.now().weekday() def get_sunday(): return "Today it's Sunday" def get_monday(): return "Today it's Monday" def get_tuesday(): return "Today it's Tuesday" def get_wednesday(): return "Today it's Wednesday" def get_thursday(): return "Today it's Thursday" def get_friday(): return "Today it's Friday" def get_saturday(): return "Today it's Saturday" def get_default(): return "Looking forward to the Weekend" switcher = { 0:get_sunday, 1:get_monday, 2:get_tuesday, 3:get_wednesday, 4:get_thursday, 5:get_friday, 6:get_default } dayName = switcher.get(day,get_default)() print(dayName)
vickyi/scoala
pachong/pythonClass/switch.py
Python
mit
685
<?php /** * DropColumnSpecificationStatement class file. * * @author Anastaszor */ class DropColumnSpecificationStatement extends CachalotObject implements IDropColumnSpecificationStatement { /** * The name of the column to drop * * @var string */ private $_column_name = null; /** * Sets the name of the column to drop. * * @param string $string */ public function setColumnName($string) { $this->_column_name = $string; } /** * (non-PHPdoc) * @see IDropColumnSpecificationStatement::getColumnName() */ public function getColumnName() { return $this->_column_name; } /** * (non-PHPdoc) * @see IStatement::validate() */ public function validate() { return is_string($this->_column_name) && strlen(trim($this->_column_name)) > 0; } /** * (non-PHPdoc) * @see IStatement::toSQL() */ public function toSQL(IDialect $dialect) { return $dialect->dropColumnSpecification($this); } }
Anastaszor/Cachalot
classes/statements/parts/specifications/DropColumnSpecificationStatement.php
PHP
mit
961
Ext.define('sisprod.view.MobileUnit.UpdateMobileUnit', { extend: 'sisprod.view.base.BaseDataWindow', alias: 'widget.updateMobileUnit', messages: { basicDataTitle: 'Basic Data', componentsTitle: 'Allocation of Components', featuresTitle: 'Additional Features', equipmentNameLabel: 'Equipment Name', equipmentModelLabel: 'Model', equipmentCodeLabel: 'Code', serialNumberLabel: 'Serial Number', equipmentTypeLabel: 'Equipment Type', markLabel: 'Mark', equipmentConditionLabel: 'Condition', locationLabel: 'Location', locationEmptyText: 'Type a Location', equipmentEmptyText: 'Type a Equipment', addButtonText: 'Add', removeButtonText: 'Remove', supplierLabel: 'Owner', isOwn: 'Is Own', firstSelectALot: 'Select a Lot First', lot: 'Lot' }, title: 'Update Mobile Unit', modal: true, width: 550, initComponent: function() { var me = this; me.formOptions = { bodyPadding: 2, items: [ { xtype: 'hiddenfield', name: 'idMobileUnit', id: 'idMobileUnit' }, { xtype: 'hiddenfield', name: 'idEquipment', id: 'idEquipment' }, { xtype: 'tabpanel', height: 350, items: [ { id: 'basicData', xtype: 'panel', layout: 'anchor', title: me.messages.basicDataTitle, autoScroll: true, margin: '5 5 0 5', items: [ { xtype: 'textfield', grow: true, name: 'equipmentName', fieldLabel: me.messages.equipmentNameLabel, fieldStyle: { textTransform: 'uppercase' }, labelWidth: 120, anchor: '100%', allowBlank: false, maxLength: 200 }, { xtype: 'textfield', grow: true, name: 'equipmentModel', fieldLabel: me.messages.equipmentModelLabel, fieldStyle: { textTransform: 'uppercase' }, labelWidth: 120, anchor: '100%', maxLength: 100 }, { xtype: 'textfield', grow: true, name: 'equipmentCode', fieldLabel: me.messages.equipmentCodeLabel, fieldStyle: { textTransform: 'uppercase' }, labelWidth: 120, anchor: '100%', maxLength: 200 }, { xtype: 'textfield', grow: true, name: 'serialNumber', fieldLabel: me.messages.serialNumberLabel, fieldStyle: { textTransform: 'uppercase' }, labelWidth: 120, anchor: '100%', maxLength: 50 }, { xtype: 'combobox', fieldLabel: me.messages.supplierLabel, store: Ext.create('sisprod.store.SupplierAll').load(), displayField: 'entityName', valueField: 'idSupplier', name: 'cboSupplier', id: 'cboSupplier', labelWidth: 120, forceSelection: true, allowBlank: true, editable: false, anchor: '100%' }, { xtype: 'combofieldcontainer', showButtons: false, comboBoxOptions: { xtype: 'combobox', anchor: '100%', fieldLabel: me.messages.equipmentTypeLabel, labelWidth: 120, store: Ext.create('sisprod.store.EquipmentTypeAll').load(), displayField: 'equipmentTypeName', valueField: 'idEquipmentType', name: 'idEquipmentType', id: 'idEquipmentType', allowBlank: false, forceSelection: true, editable: false, width: 455, readOnly: true } }, { xtype: 'combofieldcontainer', comboBoxOptions: { xtype: 'combobox', width: 455, fieldLabel: me.messages.markLabel, labelWidth: 120, store: Ext.create('sisprod.store.MarkAll').load(), displayField: 'markName', valueField: 'idMark', name: 'idMark', id: 'idMark', forceSelection: true, editable: false } }, { xtype: 'combobox', grow: true, name: 'idLot', id: 'idLot', labelWidth: 120, store: Ext.create('sisprod.store.LotAll'), fieldLabel: me.messages.lot, displayField: 'lotName', valueField: 'idLot', allowBlank: false, margins: '0 5 0 0', forceSelection: true, editable: false, flex: 1 }, { xtype: 'sensitivecombocontainer', anchor: '100%', sensitiveComboBoxOptions: { labelWidth: 120, width: 455, name: 'idLocation', id: 'idLocation', fieldLabel: me.messages.locationLabel, store: Ext.create('sisprod.store.LocationTemplate'), emptyText: me.messages.locationEmptyText, forceSelection: true, displayTpl: Ext.create('Ext.XTemplate', '<tpl for=".">', '{locationName}', '</tpl>'), valueField: 'idLocation', listConfig: { getInnerTpl: function() { return "{locationName}"; } } } }, { xtype: 'combofieldcontainer', comboBoxOptions: { xtype: 'combobox', anchor: '100%', fieldLabel: me.messages.equipmentConditionLabel, labelWidth: 120, store: Ext.create('sisprod.store.EquipmentConditionAll').load(), displayField: 'equipmentConditionName', valueField: 'idEquipmentCondition', name: 'idEquipmentCondition', id: 'idEquipmentCondition', forceSelection: true, editable: false, width: 455 } }, { xtype: 'checkbox', grow: true, name: 'own', id: 'own', fieldLabel: me.messages.isOwn, labelWidth: 120, anchor: '100%' } ] }, { xtype: 'panel', layout: 'anchor', autoScroll: true, title: me.messages.componentsTitle, items: [ { xtype: 'gridpanel', id: 'componentsGrid', store: Ext.StoreManager.lookup('componentStoreGrid'), collapsible: true, columns: [ { text: 'Id', dataIndex: 'idEquipment', flex: 1, hidden: true }, { text: me.messages.equipmentNameLabel, dataIndex: 'equipmentName', flex: 10 } ], dockedItems: [{ xtype: 'toolbar', dock: 'top', items: ['->', { xtype: 'sensitivecombo', width: 350, name: 'cboComponent', fieldLabel: '', store: Ext.create('sisprod.store.EquipmentNotAsignedTemplate'), emptyText: me.messages.equipmentEmptyText, id: 'cboComponent', forceSelection: true, displayTpl: Ext.create('Ext.XTemplate', '<tpl for=".">', '{equipmentName}', '</tpl>'), valueField: 'idEquipment', listConfig: { getInnerTpl: function() { return "{equipmentName} - {equipmentTypeName}"; } } }, { iconCls: 'add', id: 'savecomponent', action: 'savecomponent', text: me.messages.addButtonText }, { iconCls: 'remove', id: 'removecomponent', text: me.messages.removeButtonText } ] }] } ] }, { xtype: 'panel', id: 'featuresPanel', layout: 'anchor', autoScroll: true, title: me.messages.featuresTitle, width: '100%', height: 250, border: true, bodyPadding: 5, fieldDefaults: { labelWidth: 250 }, items: [ ] } ] } ] }; me.callParent(arguments); } });
jgin/testphp
web/bundles/hrmpayroll/app/view/MobileUnit/UpdateMobileUnit.js
JavaScript
mit
15,982
from django.conf.urls import url from timeline import views urlpatterns = [ url(r'^$', views.timelines, name='timelines'), ]
fredwulei/fredsneverland
fredsneverland/timeline/urls.py
Python
mit
130
<svg version="1.1" class="o-icon__camera" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 277.3 203" style="enable-background:new 0 0 277.3 203;" xml:space="preserve"> <style type="text/css"> .st0{fill:#302D33;} .st1{fill:none;stroke:#302D33;stroke-width:2;stroke-miterlimit:10;} .st2{fill:none;stroke:#302D33;stroke-miterlimit:10;} .st3{fill:none;stroke:#ebe8e4;stroke-width:2;stroke-miterlimit:10;} </style> <rect x="235.7" y="58" class="st1" width="4" height="15"/> <rect x="37.7" y="58" class="st1" width="4" height="15"/> <path class="st0" d="M197.2,78.4c-3,0-5.5-2.5-5.5-5.5s2.5-5.5,5.5-5.5s5.5,2.5,5.5,5.5S200.2,78.4,197.2,78.4z"/> <g id="XMLID_1_"> <g> <path class="st0" d="M146.5,67.4c23.4,0,42.5,19.1,42.5,42.5s-19.1,42.5-42.5,42.5S104,133.3,104,109.9S123,67.4,146.5,67.4z"/> <path class="st0" d="M236.7,54v115h-195V52h63.8v2h-8.8c-12,19-18.1,38.1-18.1,56.9c0,18.7,6.1,37.5,18,56.1h137.9V54H236.7z"/> <path class="st0" d="M236.7,52v2h-2h-46.6h-0.4h-81.4h-0.4h-0.4v-2l19.2-18h44.5l19.2,18H236.7z M112.7,48h68.6l-12.8-12h-42.9 L112.7,48z"/> <path class="st0" d="M81.7,45v6h-27v-6h6v-4h15v4H81.7z M79.7,49v-2h-6h-11h-6v2H79.7z"/> </g> </g> <line class="st1" x1="211.8" y1="167.6" x2="235.3" y2="143.8"/> <line class="st1" x1="217.3" y1="168.3" x2="235.9" y2="149.4"/> <line class="st1" x1="223.5" y1="167.8" x2="235.4" y2="155.7"/> <line class="st1" x1="229.2" y1="168.3" x2="235.9" y2="161.5"/> <g> <line class="st2" x1="56.6" y1="45.7" x2="56.6" y2="50"/> <line class="st2" x1="59.5" y1="45.7" x2="59.5" y2="50"/> <line class="st2" x1="62.4" y1="45.7" x2="62.4" y2="50"/> <line class="st2" x1="65.3" y1="45.7" x2="65.3" y2="50"/> <line class="st2" x1="68.2" y1="45.7" x2="68.2" y2="50"/> <line class="st2" x1="71.1" y1="45.7" x2="71.1" y2="50"/> <line class="st2" x1="74" y1="45.7" x2="74" y2="50"/> <line class="st2" x1="76.9" y1="45.6" x2="76.9" y2="50"/> <line class="st2" x1="79.8" y1="45.6" x2="79.8" y2="50"/> </g> </svg>
kfriedgen/friedgen-starter
templates/icons/camera.php
PHP
mit
2,037
// 对字符串头尾进行空格字符的去除、包括全角半角空格、Tab等,返回一个字符串 function trim(str) { var regex1 = /^\s*/; var regex2 = /\s*$/; return (str.replace(regex1, "")).replace(regex2, ""); } // 给一个element绑定一个针对event事件的响应,响应函数为listener function addEvent(element, event, listener, isCorrect) { if (element.addEventListener) { element.addEventListener(event, listener, isCorrect); } else if (element.attachEvent) { element.attachEvent("on" + event, listener); } else { element["on" + event] = listener; } } var validate = { //将name中的所有中文字符替换(1中文字符长度=2英文字符长度) nameVali: function (str) { var chineseRegex = /[\u4E00-\uFA29]|[\uE7C7-\uE7F3]/g; var lenRegex = /^.{4,16}$/; if (str.length == 0) { return false; } else if (!lenRegex.test(str)) { return false } else { return true; } }, //密码验证 passwordVali: function (str) { return (str.length >= 8 && str.length<= 20); }, //再次输入的密码验证 repasswordVali: function (str, id) { var password = document.querySelector("#" + id).value; return (str === password); }, // 判断是否为邮箱地址 // 第一部分:由字母、数字、下划线、短线“-”、点号“.”组成, // 第二部分:为一个域名,域名由字母、数字、短线“-”、域名后缀组成, // 而域名后缀一般为.xxx或.xxx.xx,一区的域名后缀一般为2-4位,如cn,com,net,现在域名有的也会大于4位 emailVali: function (str) { var regex = /^([\w-*\.*]+)@([\w-]+)((\.[\w-]{2,4}){1,2})$/; return regex.test(str); }, // 判断是否为手机号 telephoneVali: function (str) { var regex = /^1[0-9]{10}$/; return regex.test(str); }, allVali: function () { var inputArray = document.querySelectorAll("input"); var count = 0; for (var cur = 0; cur < inputArray.length; cur++) { if (inputArray[cur].className == "correctInput") { count++; } } return (count === inputArray.length); } } function formFactory(data) { var whole = { settings: { label: data.label, name: data.name, type: data.type, validator: data.validator, rules: data.rules, success: data.success, empty: data.empty, fail: data.fail }, generateInput: function(type) { var that = this; var container = document.getElementById("father"); var span = document.createElement("span"); span.innerText = that.settings.label; var p = document.createElement("p"); p.className = "status"; var label = document.createElement("label"); var input = document.createElement("input"); input.name = that.settings.name; input.type = that.settings.type; input.id = that.settings.name; addEvent(input, "focus", function() { input.className = "inputFocus"; p.innerText = that.settings.rules; }, true); addEvent(input, "blur", function() { var verify = ""; if (type == "single") { verify = that.settings.validator(this.value); } else if (type == "verify") { verify = that.settings.validator(this.value) && (this.value.length != 0); } if (verify) { input.className = "correctInput"; p.className = "status correctSta"; p.innerText = that.settings.success; } else { input.className = "wrongInput"; p.className = "status wrongSta"; if (this.value.length == 0) { p.innerText = that.settings.empty; } else p.innerText = that.settings.fail; } }, true); container.appendChild(label); label.appendChild(span); label.appendChild(input); container.appendChild(p); }, generateButton: function() { var that = this; var container = document.getElementById("father"); var button = document.createElement("button"); button.innerHTML = that.settings.label; addEvent(button, "click", function() { if (that.settings.validator()) { alert("提交成功!"); } else alert("提交失败!"); }, false); container.appendChild(button); }, init: function() { var that = this; //判断类型 switch (that.settings.name) { case 'name': that.generateInput('single'); break; case 'password': that.generateInput('single'); break; case 'repassword': that.generateInput('verify'); break; case 'email': that.generateInput('single'); break; case 'telephone': that.generateInput('single'); break; case 'submit': that.generateButton(); break; } } } return whole.init(); } window.onload = function() { for (var i = 0; i < data.length; i++) { formFactory(data[i]); } }
hellozts4120/IFE-2016
task2/serial5/task32-zts/task.js
JavaScript
mit
6,127
/* 125.valid_palindrome */ public class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { int ni = nums[i]; for (int j = i + 1; j < nums.length; j++) { int nj = nums[j]; if (ni + nj == target) { return new int[] {i, j}; } } } throw new IllegalArgumentException("No two sum solution"); } }
aenon/OnlineJudge
leetcode/1.Array_String/125.valid_palindrome.java
Java
mit
423
import * as React from 'react'; import {px2rem} from '@bizfe/biz-mobile-ui/build/util/util'; import { Button, LinearProgress, CircleProgress } from '@bizfe/biz-mobile-ui'; const styles = { progress: { width: '90%', margin: '20px auto 0', }, } export default class Progress extends React.Component { constructor(...args) { super(...args); this.state = {progress: 10} } changeProgress(value) { if (value < 0) { value = 0; } else if (value > 100) { value = 100; } this.setState({progress: value}); } render() { return ( <div> <CircleProgress value={25}/> <CircleProgress value={90} color="red"/> <CircleProgress value={this.state.progress} size={px2rem(100)} linecap="round"/> <LinearProgress style={styles.progress}/> <LinearProgress style={Object.assign({},styles.progress,{height: px2rem(15)})} color="#8E24AA" fillColor="#FFF"/> <LinearProgress style={styles.progress} mode="determinate" value={this.state.progress}/> <Button style={Object.assign({},styles.progress, {display: 'block'})} onTouchTap={()=>this.changeProgress(this.state.progress + 20)} size="small">+ 20</Button> <Button style={Object.assign({},styles.progress, {display: 'block'})} onTouchTap={()=>this.changeProgress(this.state.progress - 10)} size="small">- 10</Button> </div> ); } }
tangjinzhou/biz-mobile-ui
examples/App/temp/Progress.js
JavaScript
mit
1,718
/* Copyright (C) 2012 Kory Nunn 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. NOTE: This code is formatted for run-speed and to assist compilers. This might make it harder to read at times, but the code's intention should be transparent. */ // IIFE our function ((exporter) => { // Define our function and its properties // These strings are used multiple times, so this makes things smaller once compiled const func = 'function', isNodeString = 'isNode', d = document, // Helper functions used throughout the script isType = (object, type) => typeof object === type, // Recursively appends children to given element. As a text node if not already an element appendChild = (element, child) => { if (child !== null) { if (Array.isArray(child)) { // Support (deeply) nested child elements child.map(subChild => appendChild(element, subChild)); } else { if (!crel[isNodeString](child)) { child = d.createTextNode(child); } element.appendChild(child); } } }; // function crel (element, settings) { // Define all used variables / shortcuts here, to make things smaller once compiled let args = arguments, // Note: assigned to a variable to assist compilers. index = 1, key, attribute; // If first argument is an element, use it as is, otherwise treat it as a tagname element = crel.isElement(element) ? element : d.createElement(element); // Check if second argument is a settings object if (isType(settings, 'object') && !crel[isNodeString](settings) && !Array.isArray(settings)) { // Don't treat settings as a child index++; // Go through settings / attributes object, if it exists for (key in settings) { // Store the attribute into a variable, before we potentially modify the key attribute = settings[key]; // Get mapped key / function, if one exists key = crel.attrMap[key] || key; // Note: We want to prioritise mapping over properties if (isType(key, func)) { key(element, attribute); } else if (isType(attribute, func)) { // ex. onClick property element[key] = attribute; } else { // Set the element attribute element.setAttribute(key, attribute); } } } // Loop through all arguments, if any, and append them to our element if they're not `null` for (; index < args.length; index++) { appendChild(element, args[index]); } return element; } // Used for mapping attribute keys to supported versions in bad browsers, or to custom functionality crel.attrMap = {}; crel.isElement = object => object instanceof Element; crel[isNodeString] = node => node instanceof Node; // Expose proxy interface crel.proxy = new Proxy(crel, { get: (target, key) => { !(key in crel) && (crel[key] = crel.bind(null, key)); return crel[key]; } }); // Export crel exporter(crel, func); })((product, func) => { if (typeof exports === 'object') { // Export for Browserify / CommonJS format module.exports = product; } else if (typeof define === func && define.amd) { // Export for RequireJS / AMD format define(() => product); } else { // Export as a 'global' function this.crel = product; } });
cdnjs/cdnjs
ajax/libs/crel/4.1.0/crel.js
JavaScript
mit
4,862
const fs = require('fs'); const dns = require('dns'); const argv = require('yargs').argv; const Seismometer = require('./seismometer'); const Communicator = require('./communicator'); function assertOnline() { return new Promise((fulfill, reject) => { dns.resolve('www.google.com', err => { if (err) { reject(new Error('Not online. Cannot resolve www.google.com')); } else { fulfill(); } }); }); } function main() { if (argv.help) { console.log('usage: npm run [--port /dev/port]'); process.exit(0); } if (argv.port) { if (!fs.existsSync(argv.port)) { console.error(`Port "${argv.port}" does not exist.`); process.exit(1); } } const communicator = new Communicator(); const seismometer = new Seismometer(); seismometer.watch(); assertOnline() .then(() => communicator.connect(argv.port)) .then(() => { console.log('Connected to', communicator.port.path); seismometer.on('quake', info => { console.log(`Quake! At ${info.date} with a magnitude of ${info.magnitude}`); communicator.send(info); }); console.log('Watching for quakes...'); }) .catch(err => { console.error(err); process.exit(1); }); } main();
jmptable/earthquake-converter
src/index.js
JavaScript
mit
1,275
export class Item { constructor(public title: string) { } }
ritzau/end-of-stuff
src/app/item.ts
TypeScript
mit
69
module SharedAnalysisFetch extend ActiveSupport::Concern def analysis inventory_id = params[:inventory_id] id = params[:analysis_id] || params[:id] @analysis = Analysis.where('inventory_id = ? AND (analyses.id = ? OR analyses.share_token = ?)', inventory_id.to_i, id.to_i, id).first unless @analysis render nothing: true, status: :not_found return nil end unless @analysis.share_token == id authenticate_user! authorize_action_for @analysis end @analysis end end
MobilityLabs/pdredesign-server
app/controllers/concerns/shared_analysis_fetch.rb
Ruby
mit
527
namespace Conejo { partial class Asociado { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Asociado)); this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components); this.label12 = new System.Windows.Forms.Label(); this.bttTelModificar = new System.Windows.Forms.Button(); this.bttDesasociar = new System.Windows.Forms.Button(); this.lbTeléfonos = new System.Windows.Forms.ListBox(); this.bttModificar = new System.Windows.Forms.Button(); this.bttEliminar = new System.Windows.Forms.Button(); this.bttAceptar = new System.Windows.Forms.Button(); this.txtTeléfono = new System.Windows.Forms.TextBox(); this.bttTelefono = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.txtNombre = new System.Windows.Forms.TextBox(); this.txtTipoAsociación = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.cbLugarTrabajo = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.dateBirth = new System.Windows.Forms.DateTimePicker(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.txtDUI = new System.Windows.Forms.TextBox(); this.txtApellidos = new System.Windows.Forms.TextBox(); this.txtNIT = new System.Windows.Forms.TextBox(); this.dateDesasociación = new System.Windows.Forms.DateTimePicker(); this.label10 = new System.Windows.Forms.Label(); this.dateAsociación = new System.Windows.Forms.DateTimePicker(); this.labelDesasociacion = new System.Windows.Forms.Label(); this.txtCódigoAsociado = new System.Windows.Forms.TextBox(); this.txtDirección = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // errorProvider1 // this.errorProvider1.ContainerControl = this; // // label12 // this.label12.AutoSize = true; this.label12.BackColor = System.Drawing.Color.Transparent; this.label12.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label12.ForeColor = System.Drawing.Color.Navy; this.label12.Location = new System.Drawing.Point(43, 280); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(58, 32); this.label12.TabIndex = 57; this.label12.Text = "Lugar de\r\nTrabajo:"; // // bttTelModificar // this.bttTelModificar.Enabled = false; this.bttTelModificar.Font = new System.Drawing.Font("Linotte-Regular", 9F, System.Drawing.FontStyle.Bold); this.bttTelModificar.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.bttTelModificar.Location = new System.Drawing.Point(389, 379); this.bttTelModificar.Name = "bttTelModificar"; this.bttTelModificar.Size = new System.Drawing.Size(75, 25); this.bttTelModificar.TabIndex = 67; this.bttTelModificar.TabStop = false; this.bttTelModificar.Text = "Modificar"; this.bttTelModificar.UseVisualStyleBackColor = true; this.bttTelModificar.Click += new System.EventHandler(this.bttTelModificar_Click); // // bttDesasociar // this.bttDesasociar.Font = new System.Drawing.Font("Linotte-Regular", 11.25F, System.Drawing.FontStyle.Bold); this.bttDesasociar.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.bttDesasociar.Location = new System.Drawing.Point(548, 451); this.bttDesasociar.Name = "bttDesasociar"; this.bttDesasociar.Size = new System.Drawing.Size(187, 49); this.bttDesasociar.TabIndex = 58; this.bttDesasociar.TabStop = false; this.bttDesasociar.Text = "Desasociar"; this.bttDesasociar.UseVisualStyleBackColor = true; this.bttDesasociar.Click += new System.EventHandler(this.bttDesasociar_Click_1); // // lbTeléfonos // this.lbTeléfonos.BackColor = System.Drawing.Color.White; this.lbTeléfonos.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lbTeléfonos.FormattingEnabled = true; this.lbTeléfonos.ItemHeight = 16; this.lbTeléfonos.Items.AddRange(new object[] { "Añadir"}); this.lbTeléfonos.Location = new System.Drawing.Point(136, 331); this.lbTeléfonos.Name = "lbTeléfonos"; this.lbTeléfonos.Size = new System.Drawing.Size(120, 112); this.lbTeléfonos.TabIndex = 66; this.lbTeléfonos.SelectedIndexChanged += new System.EventHandler(this.lbTeléfonos_SelectedIndexChanged); // // bttModificar // this.bttModificar.Font = new System.Drawing.Font("Linotte-Regular", 11.25F, System.Drawing.FontStyle.Bold); this.bttModificar.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.bttModificar.Location = new System.Drawing.Point(548, 129); this.bttModificar.Name = "bttModificar"; this.bttModificar.Size = new System.Drawing.Size(187, 49); this.bttModificar.TabIndex = 38; this.bttModificar.Text = "Guardar y Salir"; this.bttModificar.UseVisualStyleBackColor = true; this.bttModificar.Click += new System.EventHandler(this.bttModificar_Click_1); // // bttEliminar // this.bttEliminar.Enabled = false; this.bttEliminar.Font = new System.Drawing.Font("Linotte-Regular", 9F, System.Drawing.FontStyle.Bold); this.bttEliminar.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.bttEliminar.Location = new System.Drawing.Point(346, 405); this.bttEliminar.Name = "bttEliminar"; this.bttEliminar.Size = new System.Drawing.Size(75, 25); this.bttEliminar.TabIndex = 65; this.bttEliminar.TabStop = false; this.bttEliminar.Text = "Eliminar"; this.bttEliminar.UseVisualStyleBackColor = true; this.bttEliminar.Click += new System.EventHandler(this.bttEliminar_Click); // // bttAceptar // this.bttAceptar.Font = new System.Drawing.Font("Linotte-Regular", 11.25F, System.Drawing.FontStyle.Bold); this.bttAceptar.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.bttAceptar.Location = new System.Drawing.Point(548, 192); this.bttAceptar.Name = "bttAceptar"; this.bttAceptar.Size = new System.Drawing.Size(187, 49); this.bttAceptar.TabIndex = 39; this.bttAceptar.Text = "Salir"; this.bttAceptar.UseVisualStyleBackColor = true; this.bttAceptar.Click += new System.EventHandler(this.bttAceptar_Click_1); // // txtTeléfono // this.txtTeléfono.BackColor = System.Drawing.Color.White; this.txtTeléfono.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtTeléfono.Location = new System.Drawing.Point(338, 353); this.txtTeléfono.MaxLength = 9; this.txtTeléfono.Multiline = true; this.txtTeléfono.Name = "txtTeléfono"; this.txtTeléfono.Size = new System.Drawing.Size(100, 23); this.txtTeléfono.TabIndex = 64; // // bttTelefono // this.bttTelefono.Font = new System.Drawing.Font("Linotte-Regular", 9F, System.Drawing.FontStyle.Bold); this.bttTelefono.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.bttTelefono.Location = new System.Drawing.Point(308, 379); this.bttTelefono.Name = "bttTelefono"; this.bttTelefono.Size = new System.Drawing.Size(75, 25); this.bttTelefono.TabIndex = 63; this.bttTelefono.TabStop = false; this.bttTelefono.Text = "Ingresar"; this.bttTelefono.UseVisualStyleBackColor = true; this.bttTelefono.Click += new System.EventHandler(this.bttTelefono_Click); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label1.ForeColor = System.Drawing.Color.Navy; this.label1.Location = new System.Drawing.Point(43, 112); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(64, 16); this.label1.TabIndex = 37; this.label1.Text = "Nombres:"; // // label8 // this.label8.AutoSize = true; this.label8.BackColor = System.Drawing.Color.Transparent; this.label8.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label8.ForeColor = System.Drawing.Color.Navy; this.label8.Location = new System.Drawing.Point(43, 386); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(66, 16); this.label8.TabIndex = 62; this.label8.Text = "Teléfonos:"; // // txtNombre // this.txtNombre.BackColor = System.Drawing.Color.White; this.txtNombre.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtNombre.Location = new System.Drawing.Point(136, 113); this.txtNombre.MaxLength = 50; this.txtNombre.Multiline = true; this.txtNombre.Name = "txtNombre"; this.txtNombre.Size = new System.Drawing.Size(229, 23); this.txtNombre.TabIndex = 41; // // txtTipoAsociación // this.txtTipoAsociación.BackColor = System.Drawing.Color.White; this.txtTipoAsociación.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtTipoAsociación.Enabled = false; this.txtTipoAsociación.Location = new System.Drawing.Point(136, 450); this.txtTipoAsociación.Multiline = true; this.txtTipoAsociación.Name = "txtTipoAsociación"; this.txtTipoAsociación.Size = new System.Drawing.Size(119, 23); this.txtTipoAsociación.TabIndex = 51; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label2.ForeColor = System.Drawing.Color.Navy; this.label2.Location = new System.Drawing.Point(43, 149); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(63, 16); this.label2.TabIndex = 40; this.label2.Text = "Apellidos:"; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label3.ForeColor = System.Drawing.Color.Navy; this.label3.Location = new System.Drawing.Point(43, 444); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(71, 32); this.label3.TabIndex = 61; this.label3.Text = "Tipo de\r\nAsociación:"; // // label4 // this.label4.AutoSize = true; this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label4.ForeColor = System.Drawing.Color.Navy; this.label4.Location = new System.Drawing.Point(43, 252); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(64, 16); this.label4.TabIndex = 45; this.label4.Text = "Dirección:"; // // cbLugarTrabajo // this.cbLugarTrabajo.BackColor = System.Drawing.Color.White; this.cbLugarTrabajo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbLugarTrabajo.FormattingEnabled = true; this.cbLugarTrabajo.Location = new System.Drawing.Point(136, 304); this.cbLugarTrabajo.Name = "cbLugarTrabajo"; this.cbLugarTrabajo.Size = new System.Drawing.Size(229, 24); this.cbLugarTrabajo.TabIndex = 50; // // label5 // this.label5.AutoSize = true; this.label5.BackColor = System.Drawing.Color.Transparent; this.label5.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label5.ForeColor = System.Drawing.Color.Navy; this.label5.Location = new System.Drawing.Point(264, 219); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(31, 16); this.label5.TabIndex = 46; this.label5.Text = "NIT:"; // // dateBirth // this.dateBirth.Location = new System.Drawing.Point(136, 183); this.dateBirth.Name = "dateBirth"; this.dateBirth.Size = new System.Drawing.Size(229, 23); this.dateBirth.TabIndex = 43; // // label6 // this.label6.AutoSize = true; this.label6.BackColor = System.Drawing.Color.Transparent; this.label6.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label6.ForeColor = System.Drawing.Color.Navy; this.label6.Location = new System.Drawing.Point(43, 223); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(33, 16); this.label6.TabIndex = 49; this.label6.Text = "DUI:"; // // label7 // this.label7.AutoSize = true; this.label7.BackColor = System.Drawing.Color.Transparent; this.label7.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label7.ForeColor = System.Drawing.Color.Navy; this.label7.Location = new System.Drawing.Point(43, 177); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(76, 32); this.label7.TabIndex = 60; this.label7.Text = "Fecha de\r\nNacimiento:"; // // txtDUI // this.txtDUI.BackColor = System.Drawing.Color.White; this.txtDUI.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtDUI.Location = new System.Drawing.Point(136, 216); this.txtDUI.MaxLength = 10; this.txtDUI.Multiline = true; this.txtDUI.Name = "txtDUI"; this.txtDUI.Size = new System.Drawing.Size(119, 23); this.txtDUI.TabIndex = 44; // // txtApellidos // this.txtApellidos.BackColor = System.Drawing.Color.White; this.txtApellidos.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtApellidos.Location = new System.Drawing.Point(136, 145); this.txtApellidos.MaxLength = 50; this.txtApellidos.Multiline = true; this.txtApellidos.Name = "txtApellidos"; this.txtApellidos.Size = new System.Drawing.Size(229, 23); this.txtApellidos.TabIndex = 42; // // txtNIT // this.txtNIT.BackColor = System.Drawing.Color.White; this.txtNIT.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtNIT.Location = new System.Drawing.Point(308, 216); this.txtNIT.MaxLength = 17; this.txtNIT.Multiline = true; this.txtNIT.Name = "txtNIT"; this.txtNIT.Size = new System.Drawing.Size(176, 23); this.txtNIT.TabIndex = 47; // // dateDesasociación // this.dateDesasociación.Enabled = false; this.dateDesasociación.Location = new System.Drawing.Point(136, 534); this.dateDesasociación.Name = "dateDesasociación"; this.dateDesasociación.Size = new System.Drawing.Size(229, 23); this.dateDesasociación.TabIndex = 53; this.dateDesasociación.Visible = false; // // label10 // this.label10.AutoSize = true; this.label10.BackColor = System.Drawing.Color.Transparent; this.label10.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label10.ForeColor = System.Drawing.Color.Navy; this.label10.Location = new System.Drawing.Point(43, 479); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(71, 32); this.label10.TabIndex = 54; this.label10.Text = "Fecha de\r\nAsociación:"; // // dateAsociación // this.dateAsociación.Enabled = false; this.dateAsociación.Location = new System.Drawing.Point(136, 487); this.dateAsociación.Name = "dateAsociación"; this.dateAsociación.Size = new System.Drawing.Size(229, 23); this.dateAsociación.TabIndex = 52; // // labelDesasociacion // this.labelDesasociacion.AutoSize = true; this.labelDesasociacion.BackColor = System.Drawing.Color.Transparent; this.labelDesasociacion.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.labelDesasociacion.ForeColor = System.Drawing.Color.Navy; this.labelDesasociacion.Location = new System.Drawing.Point(43, 526); this.labelDesasociacion.Name = "labelDesasociacion"; this.labelDesasociacion.Size = new System.Drawing.Size(92, 32); this.labelDesasociacion.TabIndex = 56; this.labelDesasociacion.Text = "Fecha de\r\nDesasociación:"; this.labelDesasociacion.Visible = false; // // txtCódigoAsociado // this.txtCódigoAsociado.BackColor = System.Drawing.Color.White; this.txtCódigoAsociado.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtCódigoAsociado.Enabled = false; this.txtCódigoAsociado.Location = new System.Drawing.Point(136, 580); this.txtCódigoAsociado.Multiline = true; this.txtCódigoAsociado.Name = "txtCódigoAsociado"; this.txtCódigoAsociado.Size = new System.Drawing.Size(86, 23); this.txtCódigoAsociado.TabIndex = 55; // // txtDirección // this.txtDirección.BackColor = System.Drawing.Color.White; this.txtDirección.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtDirección.Location = new System.Drawing.Point(136, 249); this.txtDirección.Multiline = true; this.txtDirección.Name = "txtDirección"; this.txtDirección.Size = new System.Drawing.Size(348, 46); this.txtDirección.TabIndex = 48; // // label13 // this.label13.AutoSize = true; this.label13.BackColor = System.Drawing.Color.Transparent; this.label13.Font = new System.Drawing.Font("Linotte-SemiBold", 9.749999F); this.label13.ForeColor = System.Drawing.Color.Navy; this.label13.Location = new System.Drawing.Point(43, 574); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(71, 32); this.label13.TabIndex = 59; this.label13.Text = "Código de\r\nAsociación:"; // // label9 // this.label9.AutoSize = true; this.label9.BackColor = System.Drawing.Color.Transparent; this.label9.Font = new System.Drawing.Font("Gotham Narrow Medium", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(17)))), ((int)(((byte)(2))))); this.label9.Location = new System.Drawing.Point(133, 36); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(513, 38); this.label9.TabIndex = 69; this.label9.Text = "Asociación Cooperativa De Ahorro, Crédito Y Consumo Del\r\nPersonal De La Procuradu" + "ría Para La Defensa De Los Derechos Humanos"; this.label9.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.Color.Transparent; this.pictureBox1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.BackgroundImage"))); this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.pictureBox1.Location = new System.Drawing.Point(36, 15); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(80, 80); this.pictureBox1.TabIndex = 68; this.pictureBox1.TabStop = false; // // Asociado // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(783, 651); this.Controls.Add(this.label9); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.label12); this.Controls.Add(this.bttTelModificar); this.Controls.Add(this.bttDesasociar); this.Controls.Add(this.lbTeléfonos); this.Controls.Add(this.bttModificar); this.Controls.Add(this.bttEliminar); this.Controls.Add(this.bttAceptar); this.Controls.Add(this.txtTeléfono); this.Controls.Add(this.bttTelefono); this.Controls.Add(this.label1); this.Controls.Add(this.label8); this.Controls.Add(this.txtNombre); this.Controls.Add(this.txtTipoAsociación); this.Controls.Add(this.label2); this.Controls.Add(this.label3); this.Controls.Add(this.label4); this.Controls.Add(this.cbLugarTrabajo); this.Controls.Add(this.label5); this.Controls.Add(this.dateBirth); this.Controls.Add(this.label6); this.Controls.Add(this.label7); this.Controls.Add(this.txtDUI); this.Controls.Add(this.txtApellidos); this.Controls.Add(this.txtNIT); this.Controls.Add(this.dateDesasociación); this.Controls.Add(this.label10); this.Controls.Add(this.dateAsociación); this.Controls.Add(this.labelDesasociacion); this.Controls.Add(this.txtCódigoAsociado); this.Controls.Add(this.txtDirección); this.Controls.Add(this.label13); this.DoubleBuffered = true; this.Font = new System.Drawing.Font("Linotte-Light", 9.75F); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "Asociado"; this.Text = "Usuario"; this.Load += new System.EventHandler(this.Usuario_Load); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove); this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseUp); ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ErrorProvider errorProvider1; private System.Windows.Forms.Label label12; private System.Windows.Forms.Button bttTelModificar; private System.Windows.Forms.Button bttDesasociar; private System.Windows.Forms.ListBox lbTeléfonos; private System.Windows.Forms.Button bttModificar; private System.Windows.Forms.Button bttEliminar; private System.Windows.Forms.Button bttAceptar; private System.Windows.Forms.TextBox txtTeléfono; private System.Windows.Forms.Button bttTelefono; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox txtNombre; private System.Windows.Forms.TextBox txtTipoAsociación; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox cbLugarTrabajo; private System.Windows.Forms.Label label5; private System.Windows.Forms.DateTimePicker dateBirth; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtDUI; private System.Windows.Forms.TextBox txtApellidos; private System.Windows.Forms.TextBox txtNIT; private System.Windows.Forms.DateTimePicker dateDesasociación; private System.Windows.Forms.Label label10; private System.Windows.Forms.DateTimePicker dateAsociación; private System.Windows.Forms.Label labelDesasociacion; private System.Windows.Forms.TextBox txtCódigoAsociado; private System.Windows.Forms.TextBox txtDirección; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label9; private System.Windows.Forms.PictureBox pictureBox1; } }
EduardAl/Proyectos-Visual-Studio
Editando/Conejo/Conejo/Asociado.Designer.cs
C#
mit
28,967
package in.iamkelv.balances.alarms; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import in.iamkelv.balances.R; import in.iamkelv.balances.activities.MainActivity; import in.iamkelv.balances.models.Balances; import in.iamkelv.balances.models.BalancesDeserializer; import in.iamkelv.balances.models.PreferencesModel; import in.iamkelv.balances.models.WisePayService; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; import retrofit.converter.GsonConverter; public class SchedulingService extends IntentService { private final String ENDPOINT = "https://balances.iamkelv.in"; private PreferencesModel mPreferences; private NotificationManager mNotificationManager; public static final int NOTIFICATION_ID = 1; NotificationCompat.Builder builder; public SchedulingService() { super("SchedulingService"); } @Override protected void onHandleIntent(Intent intent) { Log.i("Balances", "Starting notification check"); mPreferences = new PreferencesModel(this); if (isNetworkAvailable()) { checkBalances(); } else { Log.e("Balances", "Network Unavailable"); } Log.i("Balances", "Notification check complete"); AlarmReceiver.completeWakefulIntent(intent); } private void sendNotification(String title, String message) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(message); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } private void checkBalances() { // Assign variables String mUsername = mPreferences.getUsername(); String mPassword = mPreferences.getPassword(); // Set type adapter Gson gson = new GsonBuilder() .registerTypeAdapter(Balances.class, new BalancesDeserializer()) .create(); // Send balance request RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(ENDPOINT) .setConverter(new GsonConverter(gson)) .build(); WisePayService service = restAdapter.create(WisePayService.class); Callback<Balances> callback = new Callback<Balances>() { @Override public void success(Balances balances, Response response) { // Get balances Double lunch = balances.lunch; Double tuck = balances.tuck; int lunchBalance = lunch.intValue(); int tuckBalance= tuck.intValue(); lunch /= 100; tuck /= 100; String strLunch = String.format("%.2f",lunch); String strTuck = String.format("%.2f",tuck); // Update preferences mPreferences.setLunchBalance(strLunch); mPreferences.setTuckBalance(strTuck); mPreferences.setLastChecked(System.currentTimeMillis()); int lunchThreshold = mPreferences.getLunchThreshold() * 100; int tuckThreshold = mPreferences.getTuckThreshold() * 100; if (lunchBalance < lunchThreshold && tuckBalance < tuckThreshold) { sendNotification("Balances Alert", "Your lunch and tuck balances are low"); } else if (lunchBalance < lunchThreshold) { sendNotification("Balances Alert", "Your lunch balance is low"); } else if (tuckBalance < tuckThreshold) { sendNotification("Balances Alert", "Your tuck balance is low"); } } @Override public void failure(RetrofitError retrofitError) { Log.e("BALANCES", "Failed callback"); // Check for authentication error if (retrofitError.getResponse().getStatus() == 401) { mPreferences.setAuthState(false); sendNotification("Balances - Error", "Your WisePay login details are incorrect. Tap here to fix."); } else { JsonObject jsonResponse = (JsonObject) retrofitError.getBodyAs(JsonObject.class); try { sendNotification("Balances - Error", jsonResponse.get("message").getAsString()); } catch (NullPointerException e) { sendNotification("Balances - Error", "An unknown error occurred while checking your balances."); } } } }; service.checkBalances(mUsername, mPassword, callback); } private boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); boolean isAvailable = false; if (networkInfo != null && networkInfo.isConnected()) { isAvailable = true; } return isAvailable; } }
kz/balances-android
app/src/main/java/in/iamkelv/balances/alarms/SchedulingService.java
Java
mit
5,935
<?php /** * @package axy\fs\ifs * @author Oleg Grigoriev <go.vasac@gmail.com> */ namespace axy\fs\ifs; /** * The file stream meta data * * @SuppressWarnings(PHPMD.CamelCasePropertyName) */ class MetaData { /** * The file name * * @var string */ public $filename; /** * TRUE if the stream timed out while waiting for data on the last call * * @var bool */ public $timed_out; /** * TRUE if the stream is in blocking IO mode * * @var bool */ public $blocked; /** * TRUE if the stream has reached end-of-file * * @var bool */ public $eof; /** * The number of bytes currently contained in the PHP's own internal buffer * * @var int */ public $unread_bytes; /** * A label describing the underlying implementation of the stream * * @var string */ public $stream_type; /** * The type of access required for this file * * @var string */ public $mode; /** * Whether the current stream can be seeked * * @var bool */ public $seekable; /** * The file name * * @var string */ public $uri; /** * The constructor * * @param array $data [optional] */ public function __construct(array $data = null) { if ($data !== null) { foreach ($this as $k => &$v) { if (isset($data[$k])) { $v = $data[$k]; } } unset($v); } $this->filename = $this->uri; } }
axypro/fs-ifs
MetaData.php
PHP
mit
1,647
package com.thecodeinside.easyfactory.core; /** * A factory's attribute. * * @author Wellington Pinheiro <wellington.pinheiro@gmail.com> * * @param <T> type of the attribute */ public class Attribute<T> { private String id; private T value; public String getId() { return this.id; } public T getValue() { return this.value; } public Attribute() { } public Attribute(String id, T value) { this.id = id; this.value = value; } @Override public String toString() { return "Attribute [id=" + id + ", value=" + value + "]"; } public boolean isReference() { return value instanceof FactoryReference; } public boolean isNotReference() { return !isReference(); } }
wrpinheiro/easy-factory
core/src/main/java/com/thecodeinside/easyfactory/core/Attribute.java
Java
mit
795
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import IncredibleOffersContainer from './IncredibleOffers/IncredibleOfferContainer'; export default ( <Route path="/" component={App}> <IndexRoute component={IncredibleOffersContainer} /> <Route path="/special-offers" component={IncredibleOffersContainer} /> <Route path="/special-offers/:filter" component={IncredibleOffersContainer} /> </Route> );
mamal72/dgkala-web
src/routes.js
JavaScript
mit
470
using System; using Csla; namespace ParentLoadROSoftDelete.Business.ERLevel { public partial class E05_SubContinent_ReChild { #region OnDeserialized actions /*/// <summary> /// This method is called on a newly deserialized object /// after deserialization is complete. /// </summary> /// <param name="context">Serialization context object.</param> protected override void OnDeserialized(System.Runtime.Serialization.StreamingContext context) { base.OnDeserialized(context); // add your custom OnDeserialized actions here. }*/ #endregion #region Implementation of DataPortal Hooks //partial void OnFetchRead(DataPortalHookArgs args) //{ // throw new NotImplementedException(); //} #endregion } }
CslaGenFork/CslaGenFork
trunk/Samples/DeepLoad/ParentLoadROSoftDelete.Business/ERLevel/E05_SubContinent_ReChild.cs
C#
mit
904
package com.syntacticsugar.vooga.gameplayer.objects.items.bullets; import com.syntacticsugar.vooga.gameplayer.event.implementations.SlowEvent; import com.syntacticsugar.vooga.gameplayer.objects.GameObjectType; public class SlowBullet extends AbstractBullet { public SlowBullet(BulletParams params, double speedDecrease, int time) { super(params); SlowEvent slow = new SlowEvent(speedDecrease, time); addCollisionBinding(GameObjectType.ENEMY, slow); } }
nbv3/voogasalad_CS308
src/com/syntacticsugar/vooga/gameplayer/objects/items/bullets/SlowBullet.java
Java
mit
465
<?php use Illuminate\Auth\Reminders\RemindableInterface; use Illuminate\Auth\Reminders\RemindableTrait; use Illuminate\Auth\UserInterface; use Illuminate\Auth\UserTrait; /** * User * * @property-write mixed $password * @property-read \Illuminate\Database\Eloquent\Collection|\Role[] $roles * @property-read \Illuminate\Database\Eloquent\Collection|\Invoice[] $invoices */ class User extends Eloquent implements UserInterface, RemindableInterface { use UserTrait, RemindableTrait; protected $hidden = array('password', 'remember_token'); protected $fillable = array('nombres', 'apellidos', 'direccion', 'telefono', 'email', 'password'); public function setPasswordAttribute($value) { $this->attributes['password'] = Hash::make($value); } public function roles() { return $this->belongsToMany('Role'); } public function invoices() { return $this->hasMany('Invoice'); } }
matrixdevelopments/laravelVentas
app/models/User.php
PHP
mit
904
from contextlib import contextmanager from functools import wraps from werkzeug.local import LocalProxy, LocalStack _additional_ctx_stack = LocalStack() __all__ = ("current_additions", "Additional", "AdditionalManager") @LocalProxy def current_additions(): """ Proxy to the currently added requirements """ rv = _additional_ctx_stack.top if rv is None: return None return rv[1] def _isinstance(f): @wraps(f) def check(self, other): if not isinstance(other, Additional): return NotImplemented return f(self, other) return check class Additional(object): """ Container object that allows to run extra requirements on checks. These additional requirements will be run at most once per check and will occur in no guarenteed order. Requirements can be added by passing them into the constructor or by calling the ``add`` method. They can be removed from this object by calling the ``remove`` method. To check if a requirement has been added to the current conext, you may call ``is_added`` or use ``in``:: some_req in additional additional.is_added(some)req) Additional objects can be iterated and length checked:: additional = Additional(some_req) assert len(additional) == 1 assert list(additional) == [some_req] Additional objects may be combined and compared to each other with the following operators: ``+`` creates a new additional object by combining two others, the new additional supplies all requirements that both parents did. ``+=`` similar to ``+`` except it is an inplace update. ``-`` creates a new additional instance by removing any requirements from the first instance that are contained in the second instance. ``-=`` similar to ``-`` except it is an inplace update. ``==`` compares two additional instances and returns true if both have the same added requirements. ``!=`` similar to ``!=`` except returns true if both have different requirements contained in them. """ def __init__(self, *requirements): self._requirements = set(requirements) def add(self, requirement, *requirements): self._requirements.update((requirement,) + requirements) def remove(self, requirement, *requirements): self._requirements.difference_update((requirement,) + requirements) @_isinstance def __add__(self, other): requirements = self._requirements | other._requirements return Additional(*requirements) @_isinstance def __iadd__(self, other): if len(other._requirements) > 0: self._requirements.add(*other._requirements) return self @_isinstance def __sub__(self, other): requirements = self._requirements - other._requirements return Additional(*requirements) @_isinstance def __isub__(self, other): if len(other._requirements) > 0: self.remove(*other._requirements) return self @_isinstance def __eq__(self, other): return self._requirements == other._requirements @_isinstance def __ne__(self, other): return not self == other def __iter__(self): return iter(self._requirements) def is_added(self, requirement): return requirement in self._requirements def __contains__(self, requirement): return self.is_added(requirement) def __len__(self): return len(self._requirements) def __bool__(self): return len(self) != 0 __nonzero__ = __bool__ def __repr__(self): return "Additional({!r})".format(self._requirements) class AdditionalManager(object): """ Used to manage the process of adding and removing additional requirements to be run. This class shouldn't be used directly, instead use ``allows.additional`` to access these controls. """ def push(self, additional, use_parent=False): """ Binds an additional to the current context, optionally use the current additionals in conjunction with this additional If ``use_parent`` is true, a new additional is created from the parent and child additionals rather than manipulating either directly. """ current = self.current if use_parent and current: additional = current + additional _additional_ctx_stack.push((self, additional)) def pop(self): """ Pops the latest additional context. If the additional context was pushed by a different additional manager, a ``RuntimeError`` is raised. """ rv = _additional_ctx_stack.pop() if rv is None or rv[0] is not self: raise RuntimeError( "popped wrong additional context ({} instead of {})".format(rv, self) ) @property def current(self): """ Returns the current additional context if set otherwise None """ try: return _additional_ctx_stack.top[1] except TypeError: return None @contextmanager def additional(self, additional, use_parent=False): """ Allows temporarily pushing an additional context, yields the new context into the following block. """ self.push(additional, use_parent) yield self.current self.pop()
justanr/flask-allows
src/flask_allows/additional.py
Python
mit
5,469
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: koubei.marketing.data.customreport.delete /// </summary> public class KoubeiMarketingDataCustomreportDeleteRequest : IAopRequest<KoubeiMarketingDataCustomreportDeleteResponse> { /// <summary> /// 自定义数据报表删除接口 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "koubei.marketing.data.customreport.delete"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
erikzhouxin/CSharpSolution
OSS/Alipay/F2FPayDll/Projects/alipay-sdk-NET20161213174056/Request/KoubeiMarketingDataCustomreportDeleteRequest.cs
C#
mit
2,427
function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } var port = normalizePort(process.env.PORT || '3000'); module.exports = { port: port, db: 'mongodb://'+process.env.IP+'/nexus' };
Mohamed-Abo-El-Soud/NexusJS
config/env/development.js
JavaScript
mit
341
/* * Copyright (c) 2018 Algolia * http://www.algolia.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.Collections.Generic; namespace Algolia.Search.Models.Rules { /// <summary> /// https://www.algolia.com/doc/tutorials/query-rules/coding-query-rules-parameters/#coding-query-rule-parameters /// </summary> public class Rule { /// <summary> /// Unique identifier for the rule (format: [A-Za-z0-9_-]+). /// </summary> public string ObjectID { get; set; } /// <summary> /// Condition of the rule, expressed using the following variables: pattern, anchoring, context. /// </summary> [Obsolete("Single condition is deprecated, use Conditions (plural) which accept one or more condition(s).")] public Condition Condition { get; set; } /// <summary> /// Conditions of the rule, which can be used to apply more than a single condition to the Rule. /// </summary> public List<Condition> Conditions { get; set; } /// <summary> /// Consequence of the rule. At least one of the following object must be used: params, promote, hide, userData /// </summary> public Consequence Consequence { get; set; } /// <summary> /// This field is intended for rule management purposes, in particular to ease searching for rules and presenting them to human readers. It is not interpreted by the API. /// </summary> public string Description { get; set; } /// <summary> /// Whether the rule is enabled. Disabled rules remain in the index, but are not applied at query time. /// </summary> public bool? Enabled { get; set; } /// <summary> /// By default, rules are permanently valid. When validity periods are specified, the rule applies only during those periods; it is ignored the rest of the time. /// The list must not be empty. /// </summary> public IEnumerable<TimeRange> Validity { get; set; } } }
algolia/algoliasearch-client-csharp
src/Algolia.Search/Models/Rules/Rule.cs
C#
mit
3,092
// The MIT License (MIT) // Copyright (c) 2014 Ben Abelshausen // 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 GTFS.IO.CSV; using System; using System.Collections.Generic; using System.IO; namespace GTFS.IO { /// <summary> /// Represents a list of GTFS source files all located in a given directory. /// </summary> public class GTFSDirectorySource : IEnumerable<IGTFSSourceFile>, IDisposable { /// <summary> /// Holds the directory. /// </summary> private DirectoryInfo _directory; /// <summary> /// Holds a custom seperator. /// </summary> private char? _customSeperator; /// <summary> /// Holds the source files. /// </summary> private List<IGTFSSourceFile> _sourceFiles; /// <summary> /// Creates a new GTFS directory source. /// </summary> /// <param name="path">The path to the directory contain all GTFS-files.</param> public GTFSDirectorySource(string path) : this(new DirectoryInfo(path)) { } /// <summary> /// Creates a new GTFS directory source. /// </summary> /// <param name="directory">The directory contain all GTFS-files.</param> public GTFSDirectorySource(DirectoryInfo directory) { _directory = directory; _customSeperator = null; } /// <summary> /// Creates a new GTFS directory source. /// </summary> /// <param name="path">The path to the directory contain all GTFS-files.</param> /// <param name="seperator">A custom seperator.</param> public GTFSDirectorySource(string path, char seperator) : this(new DirectoryInfo(path), seperator) { } /// <summary> /// Creates a new GTFS directory source. /// </summary> /// <param name="directory">The directory contain all GTFS-files.</param> /// <param name="seperator">A custom seperator.</param> public GTFSDirectorySource(DirectoryInfo directory, char seperator) { _directory = directory; _customSeperator = seperator; } /// <summary> /// Builds a list of source files; /// </summary> /// <returns></returns> private void BuildSource() { if(_sourceFiles != null) { foreach(var sourceFile in _sourceFiles) { sourceFile.Dispose(); } } var files = _directory.GetFiles("*.txt"); _sourceFiles = new List<IGTFSSourceFile>(files.Length); foreach(var file in files) { if(_customSeperator.HasValue) { // add source file with custom seperator. _sourceFiles.Add( new GTFSSourceFileLines(File.ReadLines(file.FullName), file.Name.Substring(0, file.Name.Length - file.Extension.Length), _customSeperator.Value)); } else { // no custom seperator here! _sourceFiles.Add( new GTFSSourceFileLines(File.ReadLines(file.FullName), file.Name.Substring(0, file.Name.Length - file.Extension.Length))); } } } /// <summary> /// Returns the enumerator for this IEnumerable. /// </summary> /// <returns></returns> public IEnumerator<IGTFSSourceFile> GetEnumerator() { this.BuildSource(); return _sourceFiles.GetEnumerator(); } /// <summary> /// Returns the enumerator for this IEnumerable. /// </summary> /// <returns></returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { this.BuildSource(); return _sourceFiles.GetEnumerator(); } /// <summary> /// Diposes of all native resources associated with this source. /// </summary> public void Dispose() { if (_sourceFiles != null) { foreach (var sourceFile in _sourceFiles) { sourceFile.Dispose(); } } } } }
Smartrak/GTFS
GTFS.IO.Desktop/GTFSDirectorySource.cs
C#
mit
5,420
using System; using System.Runtime.CompilerServices; namespace DotJEM.AspNetCore.FluentRouting.Invoker.MSInternal { /* This class originates from the https://github.com/aspnet/Common project, as it is * internal a slightly modified version of the code has been copied into this source, * the license of the original source is listed below. * -------------------------------------------------------------------------------------- * * Copyright (c) .NET Foundation 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. */ public struct LambdaExecutorAwaitable { private readonly object customAwaitable; private readonly Func<object, object> getAwaiterMethod; private readonly Func<object, bool> isCompletedMethod; private readonly Func<object, object> getResultMethod; private readonly Action<object, Action> onCompletedMethod; private readonly Action<object, Action> unsafeOnCompletedMethod; public LambdaExecutorAwaitable(object customAwaitable, Func<object, object> getAwaiterMethod, Func<object, bool> isCompletedMethod, Func<object, object> getResultMethod, Action<object, Action> onCompletedMethod, Action<object, Action> unsafeOnCompletedMethod) { this.customAwaitable = customAwaitable; this.getAwaiterMethod = getAwaiterMethod; this.isCompletedMethod = isCompletedMethod; this.getResultMethod = getResultMethod; this.onCompletedMethod = onCompletedMethod; this.unsafeOnCompletedMethod = unsafeOnCompletedMethod; } public Awaiter GetAwaiter() => new Awaiter(getAwaiterMethod(customAwaitable), isCompletedMethod, getResultMethod, onCompletedMethod, unsafeOnCompletedMethod); public struct Awaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly object customAwaiter; private readonly Func<object, bool> isCompletedMethod; private readonly Func<object, object> getResultMethod; private readonly Action<object, Action> onCompletedMethod; private readonly Action<object, Action> unsafeOnCompletedMethod; public bool IsCompleted => isCompletedMethod(customAwaiter); public Awaiter(object customAwaiter, Func<object, bool> isCompletedMethod, Func<object, object> getResultMethod, Action<object, Action> onCompletedMethod, Action<object, Action> unsafeOnCompletedMethod) { this.customAwaiter = customAwaiter; this.isCompletedMethod = isCompletedMethod; this.getResultMethod = getResultMethod; this.onCompletedMethod = onCompletedMethod; this.unsafeOnCompletedMethod = unsafeOnCompletedMethod; } public object GetResult() => getResultMethod(customAwaiter); public void OnCompleted(Action continuation) => onCompletedMethod(customAwaiter, continuation); public void UnsafeOnCompleted(Action continuation) => (unsafeOnCompletedMethod ?? onCompletedMethod)(customAwaiter, continuation); } } }
dotJEM/aspnetcore-fluentrouting
src/DotJEM.AspNetCore.FluentRouting/Invoker/MSInternal/LambdaExecutorAwaitable.cs
C#
mit
3,756
<?php namespace Almendra\Http\Psr\Messages; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; /** * Represents a response * * @package Almendra\Http */ class Response extends Message implements ResponseInterface { /** * HTTP Response codes. * */ const HTTP_CONTINUE = 100; const HTTP_SWITCHING_PROTOCOLS = 101; const HTTP_PROCESSING = 102; // RFC2518 const HTTP_OK = 200; const HTTP_CREATED = 201; const HTTP_ACCEPTED = 202; const HTTP_NON_AUTHORITATIVE_INFORMATION = 203; const HTTP_NO_CONTENT = 204; const HTTP_RESET_CONTENT = 205; const HTTP_PARTIAL_CONTENT = 206; const HTTP_MULTI_STATUS = 207; // RFC4918 const HTTP_ALREADY_REPORTED = 208; // RFC5842 const HTTP_IM_USED = 226; // RFC3229 const HTTP_MULTIPLE_CHOICES = 300; const HTTP_MOVED_PERMANENTLY = 301; const HTTP_FOUND = 302; const HTTP_SEE_OTHER = 303; const HTTP_NOT_MODIFIED = 304; const HTTP_USE_PROXY = 305; const HTTP_RESERVED = 306; const HTTP_TEMPORARY_REDIRECT = 307; const HTTP_PERMANENTLY_REDIRECT = 308; // RFC7238 const HTTP_BAD_REQUEST = 400; const HTTP_UNAUTHORIZED = 401; const HTTP_PAYMENT_REQUIRED = 402; const HTTP_FORBIDDEN = 403; const HTTP_NOT_FOUND = 404; const HTTP_METHOD_NOT_ALLOWED = 405; const HTTP_NOT_ACCEPTABLE = 406; const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; const HTTP_REQUEST_TIMEOUT = 408; const HTTP_CONFLICT = 409; const HTTP_GONE = 410; const HTTP_LENGTH_REQUIRED = 411; const HTTP_PRECONDITION_FAILED = 412; const HTTP_REQUEST_ENTITY_TOO_LARGE = 413; const HTTP_REQUEST_URI_TOO_LONG = 414; const HTTP_UNSUPPORTED_MEDIA_TYPE = 415; const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; const HTTP_EXPECTATION_FAILED = 417; const HTTP_I_AM_A_TEAPOT = 418; // RFC2324 const HTTP_MISDIRECTED_REQUEST = 421; // RFC7540 const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918 const HTTP_LOCKED = 423; // RFC4918 const HTTP_FAILED_DEPENDENCY = 424; // RFC4918 const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; // RFC2817 const HTTP_UPGRADE_REQUIRED = 426; // RFC2817 const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585 const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585 const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585 const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; const HTTP_INTERNAL_SERVER_ERROR = 500; const HTTP_NOT_IMPLEMENTED = 501; const HTTP_BAD_GATEWAY = 502; const HTTP_SERVICE_UNAVAILABLE = 503; const HTTP_GATEWAY_TIMEOUT = 504; const HTTP_VERSION_NOT_SUPPORTED = 505; const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295 const HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918 const HTTP_LOOP_DETECTED = 508; // RFC5842 const HTTP_NOT_EXTENDED = 510; // RFC2774 const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585 /** * Status codes and reason phrases * * @var array */ protected static $_messages = [ /* Information */ 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', /* Success */ 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', 208 => 'Already Reported', 226 => 'IM Used', /* Redirection */ 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => '(Unused)', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', /* Client Error */ 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 451 => 'Unavailable For Legal Reasons', /* Server Error */ 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 510 => 'Not Extended', 511 => 'Network Authentication Required', ]; /** * @var int Status code */ protected $_code = self::HTTP_OK; /** * @var string Reason phrase */ protected $_reasonPhrase; public function __construct(StreamInterface $body = null) { $this -> _body = $body; } public function __toString() { // transform the stream to a string $body = $this -> getBody() -> __toString(); return $body; } /** * Gets the response status code. * * The status code is a 3-digit integer result code of the server's attempt * to understand and satisfy the request. * * @return int Status code. */ public function getStatusCode() { return $this -> _code; } /** * Return an instance with the specified status code and, optionally, reason phrase. * * If no reason phrase is specified, implementations MAY choose to default * to the RFC 7231 or IANA recommended reason phrase for the response's * status code. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * updated status and reason phrase. * * @link http://tools.ietf.org/html/rfc7231#section-6 * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * @param int $code The 3-digit integer result code to set. * @param string $reasonPhrase The reason phrase to use with the * provided status code; if none is provided, implementations MAY * use the defaults as suggested in the HTTP specification. * @return static * @throws \InvalidArgumentException For invalid status code arguments. */ public function withStatus($code, $reasonPhrase = '') { $clone = clone $this; $clone -> _code = $code; $clone -> setReasonPhrase($reasonPhrase); return $clone; } protected function setReasonPhrase($reasonPhrase) { $this -> _reasonPhrase = $reasonPhrase; return $this; } /** * Gets the response reason phrase associated with the status code. * * Because a reason phrase is not a required element in a response * status line, the reason phrase value MAY be null. Implementations MAY * choose to return the default RFC 7231 recommended reason phrase (or those * listed in the IANA HTTP Status Code Registry) for the response's * status code. * * @link http://tools.ietf.org/html/rfc7231#section-6 * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * @return string Reason phrase; must return an empty string if none present. */ public function getReasonPhrase() { return $this -> _reasonPhrase; } public static function getMessages() { return self::$_messages; } public static function getMessage($code) { return self::$_messages[$code]; } }
RickyNRoses87/almendra-psr7
src/Psr/Messages/Response.php
PHP
mit
8,925
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _180117_Lectures { class Program { static void Main(string[] args) { int numbersToAdd = int.Parse(Console.ReadLine()); decimal totalNumbers = 0M; for (int counter = 0; counter < numbersToAdd; counter++) { totalNumbers += decimal.Parse(Console.ReadLine()); } Console.WriteLine(totalNumbers); } } }
Koceto/SoftUni
Old Code/Programming Fundamentals/Data Types and Variables/Exact Sum of Real Numbers/Exact Sum of Real Numbers/Program.cs
C#
mit
552
var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); app.use(express.bodyParser()); app.use(app.router); app.use(express.static(__dirname + '/public')); // Simple REST server. var users = []; app.post('/user', function(req, res) { users[req.body.name] = req.body; res.send({ error: false }); }); app.get('/user/:name', function(req, res) { var user = users[req.params.name]; if (user) { res.send({ error: false, data: user }); } else { res.send({ error: true }); } }); app.put('/user/:name', function(req, res) { var user = users[req.params.name]; if (user) { res.send({ error: false }); user.weight = req.body.weight; } else { res.send({ error: true }); } }); app.del('/user/:name', function(req, res) { var user = users[req.params.name]; if (user) { delete users[req.params.name]; res.send({ error: false }); } else { res.send({ error: true }); } }); // XMLJSON file app.get('/xhr-json.js', function(req, res) { res.sendfile('xhr-json.js', { root: __dirname + '/..' }); }); // Mocha/Chai files var mochaDir = path.dirname(require.resolve('mocha')); var chaiDir = path.dirname(require.resolve('chai')); app.get('/mocha.css', function(req, res) { res.sendfile('mocha.css', { root: mochaDir }); }); app.get('/mocha.js', function(req, res) { res.sendfile('mocha.js', { root: mochaDir }); }); app.get('/chai.js', function(req, res) { res.sendfile('chai.js', { root: chaiDir }); }); http.createServer(app).listen(4444, function() { console.log('Express server listening.'); });
rla/xhr-json
tests/server.js
JavaScript
mit
1,686
package com.tommytony.war.job; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import com.tommytony.war.War; import com.tommytony.war.volume.BlockInfo; public class ResetCursorJob implements Runnable { private final Block cornerBlock; private final BlockInfo[] originalCursorBlocks; private final boolean isSoutheast; public ResetCursorJob(Block cornerBlock, BlockInfo[] originalCursorBlocks, boolean isSoutheast) { this.cornerBlock = cornerBlock; this.originalCursorBlocks = originalCursorBlocks; this.isSoutheast = isSoutheast; } public void run() { if (this.isSoutheast) { this.cornerBlock.setType(this.originalCursorBlocks[0].getType()); this.cornerBlock.setData(this.originalCursorBlocks[0].getData()); this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.WEST : BlockFace.SOUTH).setType(this.originalCursorBlocks[1].getType()); this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.WEST : BlockFace.SOUTH).setData(this.originalCursorBlocks[1].getData()); this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.NORTH : BlockFace.WEST).setType(this.originalCursorBlocks[2].getType()); this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.NORTH : BlockFace.WEST).setData(this.originalCursorBlocks[2].getData()); } else { this.cornerBlock.setType(this.originalCursorBlocks[0].getType()); this.cornerBlock.setData(this.originalCursorBlocks[0].getData()); this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.EAST : BlockFace.NORTH).setType(this.originalCursorBlocks[1].getType()); this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.EAST : BlockFace.NORTH).setData(this.originalCursorBlocks[1].getData()); this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.SOUTH : BlockFace.EAST).setType(this.originalCursorBlocks[2].getType()); this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.SOUTH : BlockFace.EAST).setData(this.originalCursorBlocks[2].getData()); } } }
grinning/war-tommybranch
war/src/main/java/com/tommytony/war/job/ResetCursorJob.java
Java
mit
2,006
=begin Copyright (c) 2011-2012 VMware, Inc. All Rights Reserved. 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. =end require 'spec_helper' [:haml, :erb].each do |template_engine| describe "glyph_filter/_glyph.html.#{template_engine}", :type => :view do it "should render #{template_engine.to_s}" do glyph = double(:current? => true) url = 'https://google.com' expect { render(:partial => "glyph_filter/glyph.html", :locals => { :glyph => glyph, :url => url }, :handlers => [template_engine]) }.not_to raise_error end end end
socialcast/glyph_filter
spec/views/glyph_filter/_glyph.html_spec.rb
Ruby
mit
1,535
using System.Web.Mvc; using System.Web.Routing; namespace Microsoft.Azure.Blast.Web { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
smith1511/AzureBlast
AzureBlast.Web/App_Start/RouteConfig.cs
C#
mit
555
using FlatBuffers; using FlatBuffers.Schema; using Synchronica.Examples.Schema; using Synchronica.Replayers; using Synchronica.Schema; using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Threading; using UnityEngine; namespace Synchronica.Unity.Examples { class SimpleClient { private string name; private TcpClient tcpClient; private NetworkStream networkStream; private int objectId; private FlatBufferReplayer replayer = new FlatBufferReplayer(); private List<SynchronizeSceneData> sceneDataBuffer = new List<SynchronizeSceneData>(); private object sceneDataBufferLock = new object(); public SimpleClient(string name, string hostname, int port) { this.name = name; this.tcpClient = new TcpClient(); this.tcpClient.Connect(hostname, port); this.networkStream = this.tcpClient.GetStream(); Debug.Log(string.Format("Connected to {0}:{1}", hostname, port)); ThreadPool.QueueUserWorkItem(ReadThread); } public override string ToString() { return string.Format("{0}-{1}", GetType().Name, this.objectId); } private void ReadThread(object state) { var schema = new MessageSchema(); schema.Register(ServerMessageIds.LoginResponse, LoginResponse.GetRootAsLoginResponse); schema.Register(ServerMessageIds.SynchronizeSceneData, SynchronizeSceneData.GetRootAsSynchronizeSceneData); var processor = new MessageProcessor(schema); processor.Attach((int)ServerMessageIds.LoginResponse, OnLoginResponse); processor.Attach((int)ServerMessageIds.SynchronizeSceneData, OnSynchronizeSceneData); var buffer = new byte[this.tcpClient.ReceiveBufferSize]; while (this.networkStream.CanRead) { int readSize; try { readSize = this.networkStream.Read(buffer, 0, buffer.Length); } catch (IOException) { readSize = 0; } if (readSize == 0) { Debug.Log("Disconnected"); break; } var bytes = new byte[readSize]; Array.Copy(buffer, bytes, readSize); Debug.Log(string.Format("Received {0} bytes", readSize)); processor.Enqueue(bytes); processor.Process(); } } private void OnLoginResponse(Message msg) { var res = (LoginResponse)msg.Body; this.objectId = res.ObjectId; Debug.Log(string.Format("Login succeeded: {0}", this.objectId)); } private void OnSynchronizeSceneData(Message msg) { var data = (SynchronizeSceneData)msg.Body; lock (this.sceneDataBufferLock) { this.sceneDataBuffer.Add(data); } } public void Login() { var fbb = new FlatBufferBuilder(1024); var oName = fbb.CreateString(this.name); var oLogin = LoginRequest.CreateLoginRequest(fbb, oName); LoginRequest.FinishLoginRequestBuffer(fbb, oLogin); WriteBytes(FlatBufferExtensions.ToProtocolMessage(fbb, ClientMessageIds.LoginRequest)); Debug.Log("Login"); } public void Input(Command command) { var time = this.replayer.Scene.ElapsedTime; var fbb = new FlatBufferBuilder(1024); var oInput = InputRequest.CreateInputRequest(fbb, time, command); InputRequest.FinishInputRequestBuffer(fbb, oInput); WriteBytes(FlatBufferExtensions.ToProtocolMessage(fbb, ClientMessageIds.InputRequest)); Debug.Log(string.Format("Input {0} {1}ms", command, time)); } public void Update() { IEnumerable<SynchronizeSceneData> dataBuffer = null; lock (this.sceneDataBufferLock) { if (this.sceneDataBuffer.Count > 0) { dataBuffer = this.sceneDataBuffer; this.sceneDataBuffer = new List<SynchronizeSceneData>(); } } if (dataBuffer != null) { foreach (var data in dataBuffer) { //Debug.Log(string.Format("Replay: {0} -> {1}", data.StartTime, data.EndTime)); this.replayer.Replay(data.StartTime, data.EndTime, data); } } } private void WriteBytes(byte[] bytes) { Debug.Log(string.Format("Send {0} bytes", bytes.Length)); ThreadPool.QueueUserWorkItem(s => this.networkStream.Write(bytes, 0, bytes.Length)); } public FlatBufferReplayer Replayer { get { return this.replayer; } } } }
wuyuntao/Synchronica
SynchronicaUnityExamples/Assets/Scripts/SynchronicaUnityExamples/SimpleClient.cs
C#
mit
5,149
'use strict'; function getBetterUpgradeMessage(foundVersion) { let version = (foundVersion && foundVersion[1]) ? `(${foundVersion[1]}) ` : ''; return `A new version of Ghost Core ${version}is available! Hot Damn. \ <a href="http://support.ghost.org/how-to-upgrade/" target="_blank">Click here</a> \ to learn more on upgrading Ghost Core.`; } /** * Simple timeout + attempt based function that checks to see if Ghost Core has an update available, * and replaces the notification text with something a little more specific.'; */ function upgradeNotification(attempts = 100) { const elements = document.querySelectorAll('aside.gh-alerts .gh-alert-content'); elements.forEach((element) => { let foundVersion = /Ghost (\d\.\d\.\d) is available/g.exec(element.innerText); element.innerHTML = getBetterUpgradeMessage(foundVersion); }); if (elements.length === 0 && attempts > 0) { setTimeout(() => upgradeNotification(attempts - 1), 50); } } /** * Init */ document.addEventListener('DOMContentLoaded', () => setTimeout(upgradeNotification, 50));
felixrieseberg/Ghost-Desktop
main/preload/upgrade-notification.js
JavaScript
mit
1,100
using System.Threading; using MonoTouch.Foundation; using MonoTouch.UIKit; using iOS.Client.Screens; using iOS.Client.MonoTouch.Dialog; using MonoTouch.Dialog; using System.Drawing; namespace iOS.Client { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public class AppDelegate : UIApplicationDelegate { private Home _home; private Bootstrapper _bootstrapper; private UIWindow _window; public override bool FinishedLaunching(UIApplication app, NSDictionary options) { // create a new window instance based on the screen size _window = new UIWindow(UIScreen.MainScreen.Bounds); // If you have defined a view, add it here: _bootstrapper = new Bootstrapper(); _bootstrapper.Run(app, _window); SetAppearance (); _bootstrapper.Container.TryResolve<Home>(out _home); _home.OnFinishedBootstrapping += OnFinishedBootstrapping; _window.RootViewController = _home; // make the window visible _window.MakeKeyAndVisible(); return true; } void OnFinishedBootstrapping(object sender, System.EventArgs e) { _home.OnFinishedBootstrapping -= OnFinishedBootstrapping; var login = _bootstrapper.Container.Resolve<Login>(); var nav = new UINavigationController (login); BeginInvokeOnMainThread(() => { System.Threading.Thread.Sleep (2000); BigTed.BTProgressHUD.Dismiss(); _window.RootViewController = nav; }); } public void SetAppearance() { UINavigationBar.Appearance.SetBackgroundImage(Resources.NavBarBackground, UIBarMetrics.Default); UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.BlackOpaque; } } }
claudiosanchez/QBank
iOS.Client/AppDelegate.cs
C#
mit
2,075
import { Component } from '@angular/core'; @Component({ selector: 'formly-demo-home', template: ` <div class="container markdown github"> <div [innerHtml]="contnent"></div> </div> `, }) export class HomeComponent { contnent = require('!!raw-loader!!highlight-loader!markdown-loader!./../../../README.md'); }
formly-js/ng-formly
demo/src/app/home.component.ts
TypeScript
mit
331
require "route_cow/version" module RouteCow # Your code goes here... end
killthekitten/route_cow
lib/route_cow.rb
Ruby
mit
76
namespace RemindMe { partial class MaterialPopup { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MaterialPopup)); this.timer1 = new System.Windows.Forms.Timer(this.components); this.tmrFadeIn = new System.Windows.Forms.Timer(this.components); this.pnlFooter = new System.Windows.Forms.Panel(); this.tbPostpone = new MaterialSkin.Controls.MaterialTextBox(); this.cbPostpone = new MaterialSkin.Controls.MaterialCheckbox(); this.btnDisable = new MaterialSkin.Controls.MaterialButton(); this.btnOk = new MaterialSkin.Controls.MaterialButton(); this.pnlDateRepeatInformation = new System.Windows.Forms.Panel(); this.materialProgressBar1 = new MaterialSkin.Controls.MaterialProgressBar(); this.lblRepeat = new MaterialSkin.Controls.MaterialLabel(); this.lblSmallDate = new MaterialSkin.Controls.MaterialLabel(); this.pbRepeat = new System.Windows.Forms.PictureBox(); this.pbDate = new System.Windows.Forms.PictureBox(); this.pnlText = new System.Windows.Forms.Panel(); this.pnlFooter.SuspendLayout(); this.pnlDateRepeatInformation.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbRepeat)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pbDate)).BeginInit(); this.SuspendLayout(); // // timer1 // this.timer1.Interval = 10; // // tmrFadeIn // this.tmrFadeIn.Interval = 10; this.tmrFadeIn.Tick += new System.EventHandler(this.tmrFadeIn_Tick); // // pnlFooter // this.pnlFooter.Controls.Add(this.tbPostpone); this.pnlFooter.Controls.Add(this.cbPostpone); this.pnlFooter.Controls.Add(this.btnDisable); this.pnlFooter.Controls.Add(this.btnOk); this.pnlFooter.Dock = System.Windows.Forms.DockStyle.Bottom; this.pnlFooter.Location = new System.Drawing.Point(0, 288); this.pnlFooter.Name = "pnlFooter"; this.pnlFooter.Size = new System.Drawing.Size(412, 33); this.pnlFooter.TabIndex = 0; // // tbPostpone // this.tbPostpone.BackColor = System.Drawing.SystemColors.Control; this.tbPostpone.BorderStyle = System.Windows.Forms.BorderStyle.None; this.tbPostpone.Depth = 0; this.tbPostpone.Dock = System.Windows.Forms.DockStyle.Left; this.tbPostpone.Font = new System.Drawing.Font("Roboto", 12F); this.tbPostpone.Hint = "1h30m"; this.tbPostpone.Location = new System.Drawing.Point(110, 0); this.tbPostpone.MaxLength = 50; this.tbPostpone.MouseState = MaterialSkin.MouseState.OUT; this.tbPostpone.Multiline = false; this.tbPostpone.Name = "tbPostpone"; this.tbPostpone.Size = new System.Drawing.Size(76, 36); this.tbPostpone.TabIndex = 2; this.tbPostpone.Text = ""; this.tbPostpone.UseTallSize = false; this.tbPostpone.Visible = false; this.tbPostpone.TextChanged += new System.EventHandler(this.tbPostpone_TextChanged); // // cbPostpone // this.cbPostpone.AutoSize = true; this.cbPostpone.Depth = 0; this.cbPostpone.Dock = System.Windows.Forms.DockStyle.Left; this.cbPostpone.Location = new System.Drawing.Point(0, 0); this.cbPostpone.Margin = new System.Windows.Forms.Padding(0); this.cbPostpone.MouseLocation = new System.Drawing.Point(-1, -1); this.cbPostpone.MouseState = MaterialSkin.MouseState.HOVER; this.cbPostpone.Name = "cbPostpone"; this.cbPostpone.Ripple = true; this.cbPostpone.Size = new System.Drawing.Size(110, 33); this.cbPostpone.TabIndex = 1; this.cbPostpone.Text = "Postpone "; this.cbPostpone.UseVisualStyleBackColor = true; this.cbPostpone.CheckedChanged += new System.EventHandler(this.cbPostpone_OnChange_1); // // btnDisable // this.btnDisable.AutoSize = false; this.btnDisable.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.btnDisable.Depth = 0; this.btnDisable.Dock = System.Windows.Forms.DockStyle.Right; this.btnDisable.DrawShadows = true; this.btnDisable.HighEmphasis = true; this.btnDisable.Icon = null; this.btnDisable.Location = new System.Drawing.Point(239, 0); this.btnDisable.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6); this.btnDisable.MouseState = MaterialSkin.MouseState.HOVER; this.btnDisable.Name = "btnDisable"; this.btnDisable.Size = new System.Drawing.Size(80, 33); this.btnDisable.TabIndex = 3; this.btnDisable.Text = "Disable"; this.btnDisable.Type = MaterialSkin.Controls.MaterialButton.MaterialButtonType.Text; this.btnDisable.UseAccentColor = false; this.btnDisable.UseVisualStyleBackColor = true; this.btnDisable.Click += new System.EventHandler(this.btnDisable_Click); // // btnOk // this.btnOk.AutoSize = false; this.btnOk.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.btnOk.Depth = 0; this.btnOk.Dock = System.Windows.Forms.DockStyle.Right; this.btnOk.DrawShadows = true; this.btnOk.HighEmphasis = true; this.btnOk.Icon = null; this.btnOk.Location = new System.Drawing.Point(319, 0); this.btnOk.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6); this.btnOk.MouseState = MaterialSkin.MouseState.HOVER; this.btnOk.Name = "btnOk"; this.btnOk.Size = new System.Drawing.Size(93, 33); this.btnOk.TabIndex = 0; this.btnOk.Text = "OK"; this.btnOk.Type = MaterialSkin.Controls.MaterialButton.MaterialButtonType.Contained; this.btnOk.UseAccentColor = false; this.btnOk.UseVisualStyleBackColor = true; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); // // pnlDateRepeatInformation // this.pnlDateRepeatInformation.Controls.Add(this.materialProgressBar1); this.pnlDateRepeatInformation.Controls.Add(this.lblRepeat); this.pnlDateRepeatInformation.Controls.Add(this.lblSmallDate); this.pnlDateRepeatInformation.Controls.Add(this.pbRepeat); this.pnlDateRepeatInformation.Controls.Add(this.pbDate); this.pnlDateRepeatInformation.Dock = System.Windows.Forms.DockStyle.Bottom; this.pnlDateRepeatInformation.Location = new System.Drawing.Point(0, 243); this.pnlDateRepeatInformation.Name = "pnlDateRepeatInformation"; this.pnlDateRepeatInformation.Size = new System.Drawing.Size(412, 45); this.pnlDateRepeatInformation.TabIndex = 1; // // materialProgressBar1 // this.materialProgressBar1.Depth = 0; this.materialProgressBar1.Dock = System.Windows.Forms.DockStyle.Top; this.materialProgressBar1.Location = new System.Drawing.Point(0, 0); this.materialProgressBar1.MouseState = MaterialSkin.MouseState.HOVER; this.materialProgressBar1.Name = "materialProgressBar1"; this.materialProgressBar1.Size = new System.Drawing.Size(412, 5); this.materialProgressBar1.TabIndex = 1; this.materialProgressBar1.Value = 100; // // lblRepeat // this.lblRepeat.AutoSize = true; this.lblRepeat.Depth = 0; this.lblRepeat.Font = new System.Drawing.Font("Roboto", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.lblRepeat.Location = new System.Drawing.Point(232, 16); this.lblRepeat.MouseState = MaterialSkin.MouseState.HOVER; this.lblRepeat.Name = "lblRepeat"; this.lblRepeat.Size = new System.Drawing.Size(100, 19); this.lblRepeat.TabIndex = 3; this.lblRepeat.Text = "Every 5 weeks"; // // lblSmallDate // this.lblSmallDate.AutoSize = true; this.lblSmallDate.Depth = 0; this.lblSmallDate.Font = new System.Drawing.Font("Roboto", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.lblSmallDate.Location = new System.Drawing.Point(42, 16); this.lblSmallDate.MouseState = MaterialSkin.MouseState.HOVER; this.lblSmallDate.Name = "lblSmallDate"; this.lblSmallDate.Size = new System.Drawing.Size(116, 19); this.lblSmallDate.TabIndex = 2; this.lblSmallDate.Text = "12-9-2020 13:00"; // // pbRepeat // this.pbRepeat.BackgroundImage = global::RemindMe.Properties.Resources.Repeatwhite; this.pbRepeat.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.pbRepeat.Location = new System.Drawing.Point(197, 10); this.pbRepeat.Name = "pbRepeat"; this.pbRepeat.Size = new System.Drawing.Size(28, 28); this.pbRepeat.TabIndex = 1; this.pbRepeat.TabStop = false; // // pbDate // this.pbDate.BackgroundImage = global::RemindMe.Properties.Resources.RemindMe; this.pbDate.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.pbDate.Location = new System.Drawing.Point(6, 10); this.pbDate.Name = "pbDate"; this.pbDate.Size = new System.Drawing.Size(28, 28); this.pbDate.TabIndex = 0; this.pbDate.TabStop = false; // // pnlText // this.pnlText.AutoScroll = true; this.pnlText.Dock = System.Windows.Forms.DockStyle.Bottom; this.pnlText.Location = new System.Drawing.Point(0, 63); this.pnlText.Name = "pnlText"; this.pnlText.Size = new System.Drawing.Size(412, 180); this.pnlText.TabIndex = 2; // // MaterialPopup // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.ClientSize = new System.Drawing.Size(412, 321); this.Controls.Add(this.pnlText); this.Controls.Add(this.pnlDateRepeatInformation); this.Controls.Add(this.pnlFooter); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MaterialPopup"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "MaterialPopup"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MaterialPopup_FormClosing); this.Load += new System.EventHandler(this.Popup_Load); this.SizeChanged += new System.EventHandler(this.Popup_SizeChanged); this.pnlFooter.ResumeLayout(false); this.pnlFooter.PerformLayout(); this.pnlDateRepeatInformation.ResumeLayout(false); this.pnlDateRepeatInformation.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbRepeat)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pbDate)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Timer timer1; private System.Windows.Forms.Timer tmrFadeIn; private System.Windows.Forms.Panel pnlFooter; private System.Windows.Forms.Panel pnlDateRepeatInformation; private MaterialSkin.Controls.MaterialButton btnOk; private MaterialSkin.Controls.MaterialButton btnDisable; private MaterialSkin.Controls.MaterialTextBox tbPostpone; private MaterialSkin.Controls.MaterialCheckbox cbPostpone; private MaterialSkin.Controls.MaterialLabel lblRepeat; private MaterialSkin.Controls.MaterialLabel lblSmallDate; private System.Windows.Forms.PictureBox pbRepeat; private System.Windows.Forms.PictureBox pbDate; private System.Windows.Forms.Panel pnlText; private MaterialSkin.Controls.MaterialProgressBar materialProgressBar1; } }
Stefangansevles/RemindMe
RemindMe/Forms/MaterialForms/MaterialPopup.Designer.cs
C#
mit
13,938
require 'test_helper' class NotificationTest < ActionMailer::TestCase # replace this with your real tests test "the truth" do assert true end end
pugnusferreus/wamlibrary
test/functional/notification_test.rb
Ruby
mit
157
'use strict' var PassThrough = require('stream').PassThrough var statistics = require('vfile-statistics') var fileSetPipeline = require('./file-set-pipeline') module.exports = run // Run the file set pipeline once. // `callback` is invoked with a fatal error, or with a status code (`0` on // success, `1` on failure). function run(options, callback) { var settings = {} var stdin = new PassThrough() var tree var detectConfig var hasConfig var detectIgnore var hasIgnore try { stdin = process.stdin } catch (_) { // Obscure bug in Node (seen on Windows). // See: <https://github.com/nodejs/node/blob/f856234/lib/internal/process/stdio.js#L82>, // <https://github.com/AtomLinter/linter-markdown/pull/85>. } if (!callback) { throw new Error('Missing `callback`') } if (!options || !options.processor) { return next(new Error('Missing `processor`')) } // Processor. settings.processor = options.processor // Path to run as. settings.cwd = options.cwd || process.cwd() // Input. settings.files = options.files || [] settings.extensions = (options.extensions || []).map(extension) settings.filePath = options.filePath || null settings.streamIn = options.streamIn || stdin // Output. settings.streamOut = options.streamOut || process.stdout settings.streamError = options.streamError || process.stderr settings.alwaysStringify = options.alwaysStringify settings.output = options.output settings.out = options.out // Null overwrites config settings, `undefined` does not. if (settings.output === null || settings.output === undefined) { settings.output = undefined } if (settings.output && settings.out) { return next(new Error('Cannot accept both `output` and `out`')) } // Process phase management. tree = options.tree || false settings.treeIn = options.treeIn settings.treeOut = options.treeOut settings.inspect = options.inspect if (settings.treeIn === null || settings.treeIn === undefined) { settings.treeIn = tree } if (settings.treeOut === null || settings.treeOut === undefined) { settings.treeOut = tree } // Configuration. detectConfig = options.detectConfig hasConfig = Boolean(options.rcName || options.packageField) if (detectConfig && !hasConfig) { return next( new Error('Missing `rcName` or `packageField` with `detectConfig`') ) } settings.detectConfig = detectConfig === null || detectConfig === undefined ? hasConfig : detectConfig settings.rcName = options.rcName || null settings.rcPath = options.rcPath || null settings.packageField = options.packageField || null settings.settings = options.settings || {} settings.configTransform = options.configTransform settings.defaultConfig = options.defaultConfig // Ignore. detectIgnore = options.detectIgnore hasIgnore = Boolean(options.ignoreName) settings.detectIgnore = detectIgnore === null || detectIgnore === undefined ? hasIgnore : detectIgnore settings.ignoreName = options.ignoreName || null settings.ignorePath = options.ignorePath || null settings.ignorePatterns = options.ignorePatterns || [] settings.silentlyIgnore = Boolean(options.silentlyIgnore) if (detectIgnore && !hasIgnore) { return next(new Error('Missing `ignoreName` with `detectIgnore`')) } // Plugins. settings.pluginPrefix = options.pluginPrefix || null settings.plugins = options.plugins || {} // Reporting. settings.reporter = options.reporter || null settings.reporterOptions = options.reporterOptions || null settings.color = options.color || false settings.silent = options.silent || false settings.quiet = options.quiet || false settings.frail = options.frail || false // Process. fileSetPipeline.run({files: options.files || []}, settings, next) function next(error, context) { var stats = statistics((context || {}).files) var failed = Boolean( settings.frail ? stats.fatal || stats.warn : stats.fatal ) if (error) { callback(error) } else { callback(null, failed ? 1 : 0, context) } } } function extension(ext) { return ext.charAt(0) === '.' ? ext : '.' + ext }
wooorm/unified-engine
lib/index.js
JavaScript
mit
4,229
'use strict'; import {should as should_} from 'chai'; const should = should_(); import {spy, stub} from 'sinon'; import {setCanvas, canvas, context} from '../src/canvas'; import draw from '../src/draw'; // import {Sprite} from '../../../script/src/sprite'; describe('draw.js', () => { let ctx; before(() => { setCanvas('game'); // Reset settings draw.setFont({reset: true}); draw.setLine({reset: true}); draw.setShadow({reset: true}); ctx = { fillRect: stub(context, 'fillRect'), strokeRect: stub(context, 'strokeRect'), clearRect: stub(context, 'clearRect'), fillText: stub(context, 'fillText'), strokeText: stub(context, 'strokeText'), measureText: spy(context, 'measureText'), beginPath: spy(context, 'beginPath'), moveTo: spy(context, 'moveTo'), lineTo: spy(context, 'lineTo'), arc: spy(context, 'arc'), arcTo: spy(context, 'arcTo'), rect: spy(context, 'rect'), quadraticCurveTo: spy(context, 'quadraticCurveTo'), bezierCurveTo: spy(context, 'bezierCurveTo'), closePath: spy(context, 'closePath'), fill: stub(context, 'fill'), stroke: stub(context, 'stroke'), clip: stub(context, 'clip'), drawImage: stub(context, 'drawImage'), getImageData: spy(context, 'getImageData'), putImageData: stub(context, 'putImageData'), createImageData: spy(context, 'createImageData'), save: stub(context, 'save'), scale: stub(context, 'scale'), rotate: stub(context, 'rotate'), translate: stub(context, 'translate'), transform: stub(context, 'transform'), restore: stub(context, 'restore'), }; }); afterEach(() => { for(let i in ctx) { ctx[i].reset(); } }); after(() => { for(let i in ctx) { ctx[i].restore(); } }); describe('rect(x, y, w, h, stroke = false)', () => { it('should fill a rectangle with a falsey 5th parameter', () => { draw.rect(0, 0, 100, 100); ctx.fillRect.should.have.been.calledWith(0, 0, 100, 100); ctx.strokeRect.should.have.not.been.called; }); it('should stroke a rectangle with a truthy 5th parameter', () => { draw.rect(0, 0, 100, 100, true); ctx.fillRect.should.have.not.been.called; ctx.strokeRect.should.have.been.calledWith(0, 0, 100, 100); }); }); describe('point(x, y)', () => { it('should fill a 1x1 px rectangle', () => { draw.point(0, 0); ctx.fillRect.should.have.been.calledWith(0, 0, 1, 1); }); }); describe('circle(x, y, r, stroke = false)', () => { it('should fill a circle with a falsey 5th parameter', () => { draw.circle(0, 0, 5); ctx.beginPath.should.have.been.calledOnce; ctx.arc.should.have.been.calledWith(0, 0, 5); ctx.fill.should.have.been.calledOnce; ctx.stroke.should.have.not.been.called; }); it('should stroke a circle with a truthy 5th parameter', () => { draw.circle(0, 0, 5, true); ctx.beginPath.should.have.been.calledOnce; ctx.arc.should.have.been.calledWith(0, 0, 5); ctx.fill.should.have.not.been.called; ctx.stroke.should.have.been.calledOnce; }); }); describe('text(str, x, y, stroke = false)', () => { it('should fill the text with a falsey 5th parameter', () => { draw.text('Hello World', 0, 0); ctx.fillText.should.have.been.calledWith('Hello World', 0, 0); ctx.strokeText.should.have.not.been.called; }); it('should stroke the text with a truthy 5th parameter', () => { draw.text('Hello World', 0, 0, true); ctx.fillText.should.have.not.been.called; ctx.strokeText.should.have.been.calledWith('Hello World', 0, 0); }); }); describe('textWidth(text)', () => { it('should not draw any text', () => { draw.textWidth('Hello World'); ctx.measureText.should.have.been.calledWith('Hello World'); ctx.fillText.should.have.not.been.called; ctx.strokeText.should.have.not.been.called; }); it('return a number (the width of the text)', () => { draw.text('Hello World'); draw.textWidth('Hello World').should.be.a('number'); }); }); describe('image(img[, sx, sy, swidth, sheight], x, y[, w, h])', () => { it('should draw the image', () => { const img = new Image(40, 50); draw.image({img: img, swidth: 32, sheight: 32, x: 0, y: 0, width: 32, height: 32}); draw.image({img: img, sx: 10, sy: 10, x: 0, y: 0, width: 32, height: 32}); draw.image(img, 20, 20); ctx.drawImage.should.have.been.calledThrice; ctx.drawImage.should.have.been.calledWith(img, 0, 0, 32, 32, 0, 0, 32, 32); ctx.drawImage.should.have.been.calledWith(img, 10, 10, 32, 32, 0, 0, 32, 32); ctx.drawImage.should.have.been.calledWith(img, 20, 20); }); }); describe('pixelData(pd, x, y)', () => { it('should be an alias for pd.draw(x, y)', () => { const pd = new draw.PixelData(32, 32); const fn = stub(pd, 'draw'); draw.pixelData(pd, 32, 32); fn.should.have.been.calledWith(32, 32); fn.restore(); }); }); describe('clear()', () => { it('should clear the entire canvas', () => { draw.clear(); ctx.clearRect.should.have.been.calledWith(0, 0, canvas.width(), canvas.height()); }); }); describe('setColor(color)', () => { it('should set both stroke and fill colors', () => { draw.setColor('#ff0000'); context.fillStyle.should.equal('#ff0000'); context.strokeStyle.should.equal('#ff0000'); draw.setColor('#0000ff'); context.fillStyle.should.equal('#0000ff'); context.strokeStyle.should.equal('#0000ff'); }); it('should accept numbers and convert them to strings', () => { draw.setColor(0xff0000); context.fillStyle.should.equal('#ff0000'); context.strokeStyle.should.equal('#ff0000'); draw.setColor(0x0000ff); context.fillStyle.should.equal('#0000ff'); context.strokeStyle.should.equal('#0000ff'); }); }); describe('setAlpha(alpha)', () => { it('should set the global alpha', () => { draw.setAlpha(0.5); context.globalAlpha.should.equal(0.5); draw.setAlpha(1); context.globalAlpha.should.equal(1); }); it('should constrain alpha to range [0, 1]', () => { draw.setAlpha(-2); context.globalAlpha.should.equal(0); draw.setAlpha(3); context.globalAlpha.should.equal(1); }); }); describe('setComposite(composite)', () => { it('should set the global composite operation', () => { draw.setComposite('source-atop'); context.globalCompositeOperation.should.equal('source-atop'); draw.setComposite('source-over'); context.globalCompositeOperation.should.equal('source-over'); }); }); describe('setLine({cap, join, width, miter, reset = false})', () => { it('should set the appropriate line properties', () => { draw.setLine({cap: 'round'}); context.lineCap.should.equal('round'); draw.setLine({width: 15}); context.lineCap.should.equal('round'); context.lineWidth.should.equal(15); draw.setLine({join: 'bevel'}); context.lineCap.should.equal('round'); context.lineWidth.should.equal(15); context.lineJoin.should.equal('bevel'); draw.setLine({miter: 15}); context.lineCap.should.equal('round'); context.lineWidth.should.equal(15); context.lineJoin.should.equal('bevel'); context.miterLimit.should.equal(15); draw.setLine({cap: 'butt', width: 1, join: 'miter', miter: 10}); context.lineCap.should.equal('butt'); context.lineWidth.should.equal(1); context.lineJoin.should.equal('miter'); context.miterLimit.should.equal(10); }); it('should ignore other values if reset is true', () => { draw.setLine({reset: true, cap: 'round', width: 10}); context.lineCap.should.equal('butt'); context.lineWidth.should.equal(1); context.lineJoin.should.equal('miter'); context.miterLimit.should.equal(10); }); }); describe('setShadow({x, y, blur, color, reset = false})', () => { it('should set the appropriate shadow properties', () => { draw.setShadow({x: 5}); context.shadowOffsetX.should.equal(5); draw.setShadow({y: 10}); context.shadowOffsetX.should.equal(5); context.shadowOffsetY.should.equal(10); draw.setShadow({blur: 15}); context.shadowOffsetX.should.equal(5); context.shadowOffsetY.should.equal(10); context.shadowBlur.should.equal(15); draw.setShadow({color: 0xff0000}); context.shadowOffsetX.should.equal(5); context.shadowOffsetY.should.equal(10); context.shadowBlur.should.equal(15); context.shadowColor.should.equal('#ff0000'); draw.setShadow({color: '#0000ff'}); context.shadowOffsetX.should.equal(5); context.shadowOffsetY.should.equal(10); context.shadowBlur.should.equal(15); context.shadowColor.should.equal('#0000ff'); draw.setShadow({x: 0, y: 0, blur: 0, color: '#000000'}); context.shadowOffsetX.should.equal(0); context.shadowOffsetY.should.equal(0); context.shadowBlur.should.equal(0); context.shadowColor.should.equal('#000000'); }); it('should ignore other values if reset is passed', () => { draw.setShadow({x: 5, y: 5, blur: 3, color: '#00FF00', reset: true}); context.shadowOffsetX.should.equal(0); context.shadowOffsetY.should.equal(0); context.shadowBlur.should.equal(0); context.shadowColor.should.equal('#000000'); }); }); describe('setFont({family, size, align, baseline, reset = false})', () => { it('should set the appropriate font properties', () => { draw.setFont({size: 15}); context.font.should.equal('15px sans-serif'); draw.setFont({family: 'serif'}); context.font.should.equal('15px serif'); draw.setFont({align: 'center'}); context.font.should.equal('15px serif'); context.textAlign.should.equal('center'); draw.setFont({baseline: 'top'}); context.font.should.equal('15px serif'); context.textAlign.should.equal('center'); context.textBaseline.should.equal('top'); draw.setFont({family: 'sans-serif', size: 10, align: 'start', baseline: 'alphabetic'}); context.font.should.equal('10px sans-serif'); context.textAlign.should.equal('start'); context.textBaseline.should.equal('alphabetic'); }); it('should ignore other values if reset is passed', () => { draw.setFont({family: 'serif', size: 15, align: 'top', baseline: 'middle', reset: true}); context.font.should.equal('10px sans-serif'); context.textAlign.should.equal('start'); context.textBaseline.should.equal('alphabetic'); }); }); describe('transformed({scale: {x: 1, y: 1}, rotate, translate: {x: 0, y: 0}, transform: [1, 0, 0, 1, 0, 0]}, ...todo)', () => { it('should context.save() at the beginning, context.restore() at the end, and other functions inbetween', () => { const cb = spy(); draw.transformed({scale: {x: 2, y: 2}, rotate: 50, translate: {x: 15, y: 30}, transform: [1, 0, 0, 1, 0, 0]}, cb); ctx.save.should.have.been.calledBefore(ctx.scale); ctx.scale.should.have.been.calledBefore(ctx.rotate); ctx.rotate.should.have.been.calledBefore(ctx.translate); ctx.translate.should.have.been.calledBefore(ctx.transform); ctx.transform.should.have.been.calledBefore(cb); cb.should.have.been.calledOnce; ctx.restore.should.have.been.calledAfter(cb); }); it('should call all functions passed in order', () => { const cbs = [spy(), spy(), spy()]; draw.transformed({}, ...cbs); cbs[0].should.have.been.calledOnce; cbs[0].should.have.been.calledBefore(cbs[1]); cbs[1].should.have.been.calledOnce; cbs[1].should.have.been.calledBefore(cbs[2]); cbs[2].should.have.been.calledOnce; }); }); describe('Path', () => { it('should be constructed with new Path()', () => { new draw.Path().should.be.an.instanceof(draw.Path); (() => draw.Path()).should.throw(TypeError); ctx.beginPath.should.not.have.been.called; }); describe('#length', () => { it('should return the number of actions in the stack', () => { new draw.Path().move().line().length.should.equal(2); }); it('should not include the initial beginPath call', () => { new draw.Path().length.should.equal(0); }); }); describe('#move(x, y)', () => { it('should add context.moveTo(x, y) to the stack', () => { const p = new draw.Path().move(32, 32); p.length.should.equal(1); p.stroke(); ctx.moveTo.should.have.been.calledWith(32, 32); }); it('should not call context.moveTo(x, y)', () => { new draw.Path().move(32, 32); ctx.moveTo.should.not.have.been.called; }); it('should be chainable', () => { (() => new draw.Path().move(32, 32).move(16, 16)).should.not.throw(); }); }); describe('#line(x, y)', () => { it('should add context.lineTo(x, y) to the stack', () => { const p = new draw.Path().line(32, 32); p.length.should.equal(1); p.stroke(); ctx.lineTo.should.have.been.calledWith(32, 32); }); it('should not call context.lineTo(x, y)', () => { new draw.Path().line(32, 32); ctx.lineTo.should.not.have.been.called; }); it('should be chainable', () => { (() => new draw.Path().line(32, 32).line(16, 16)).should.not.throw(); }); }); describe('#rect(x, y, w, h)', () => { it('should add context.rect(x, y, w, h) to the stack', () => { const p = new draw.Path().rect(16, 16, 32, 32); p.length.should.equal(1); p.stroke(); ctx.rect.should.have.been.calledWith(16, 16, 32, 32); }); it('should not call context.rect(x, y)', () => { new draw.Path().rect(32, 32, 16, 16); ctx.rect.should.not.have.been.called; }); it('should be chainable', () => { (() => new draw.Path().rect(16, 16, 32, 32).rect(32, 32, 16, 16)).should.not.throw(); }); }); describe('#arc(x, y, r, start, end[, ccw])', () => { it('should add context.arc(x, y, r, start, end[, ccw]) to the stack', () => { const p = new draw.Path().arc(32, 32, 32, 0, Math.PI, false); p.length.should.equal(1); p.stroke(); ctx.arc.should.have.been.calledWith(32, 32, 32, 0, Math.PI, false); }); it('should not call context.arc(x, y, r, start, end[, ccw])', () => { new draw.Path().arc(32, 32, 32, 0, Math.PI, false); ctx.arc.should.not.have.been.called; }); it('should be chainable', () => { (() => new draw.Path().arc(32, 32, 32, 0, Math.PI, false).arc(32, 32, 32, 0, Math.PI, false)).should.not.throw(); }); }); describe('#curve(x1, y1, x2, y2, r)', () => { it('should add context.arcTo(x1, y1, x2, y2, r) to the stack', () => { const p = new draw.Path().curve(32, 32, 32, 64, 32); p.length.should.equal(1); p.stroke(); ctx.arcTo.should.have.been.calledWith(32, 32, 32, 64, 32); }); it('should not call context.arcTo(x1, y1, x2, y2, r)', () => { new draw.Path().curve(32, 32, 32, 64, 32); ctx.arcTo.should.not.have.been.called; }); it('should be chainable', () => { (() => new draw.Path().curve(32, 32, 32, 64, 32).curve(32, 96, 64, 96, 32)).should.not.throw(); }); }); describe('#bezier(x1, y1, x2, y2[, x3, y3])', () => { it('should add context.quadraticCurveTo(x1, y1, x2, y2) to the stack when called with 4 arguments', () => { const p = new draw.Path().bezier(32, 32, 32, 64); p.length.should.equal(1); p.stroke(); ctx.quadraticCurveTo.should.have.been.calledWith(32, 32, 32, 64); }); it('should add context.bezierCurveTo(x1, y1, x2, y2, x3, y3) to the stack when called with 6 arguments', () => { const p = new draw.Path().bezier(32, 32, 32, 64, 64, 64); p.length.should.equal(1); p.stroke(); ctx.bezierCurveTo.should.have.been.calledWith(32, 32, 32, 64, 64, 64); }); it('should not call context.quadraticCurveTo(x1, y1, x2, y2) or context.bezierCurveTo(x1, y1, x2, y2, x3, y3)', () => { new draw.Path().bezier(32, 32, 32, 64).bezier(32, 32, 32, 64, 64, 64); ctx.quadraticCurveTo.should.not.have.been.called; ctx.bezierCurveTo.should.not.have.been.called; }); it('should be chainable', () => { (() => new draw.Path().bezier(32, 32, 32, 64).bezier(32, 32, 32, 64, 64, 64).move(32, 32)).should.not.throw(); }); }); describe('#close()', () => { it('should add context.closePath() to the stack', () => { const p = new draw.Path().close(); p.length.should.equal(1); p.stroke(); ctx.closePath.should.have.been.calledOnce; }); it('should not call context.close', () => { new draw.Path().close(); ctx.closePath.should.not.have.been.called; }); it('should be chainable', () => { (() => new draw.Path().close().close()).should.not.throw(); }); }); describe('#do(fn)', () => { it('should add a given fn to the stack', () => { const cb = spy(); const p = new draw.Path().do(cb); p.length.should.equal(1); p.stroke(); cb.should.have.been.calledOnce; }); it('should not call fn', () => { const cb = spy(); const p = new draw.Path().do(cb); cb.should.not.have.been.called; }); it('should be chainable', () => { (() => new draw.Path().do(() => {}).do(() => {})).should.not.throw(); }); }); describe('#fill({color, shadow, transform})', () => { it('should call context.save() at the beginning, context.restore() at the end, and context.fill() in the middle', () => { new draw.Path().move(32, 32).line(64, 64).fill(); ctx.save.should.have.been.calledBefore(ctx.fill); ctx.fill.should.have.been.calledBefore(ctx.restore); ctx.restore.should.have.been.called; }); it('should set the color, shadow, and transform if they are specified', () => { new draw.Path().move(32, 32).do(() => { context.fillStyle.should.equal('#ff0000'); context.shadowBlur.should.equal(5); ctx.translate.should.have.been.calledWith(5, 0); }).line(64, 64).fill({ color: 0xff0000, shadow: { blur: 5 }, transform: { translate: { x: 5 } } }); }); it('should call the entire stack in order', () => { new draw.Path().move(32, 32).line(64, 64).arc(32, 32, 0, 0, 3).rect(32, 32, 32, 32).fill(); ctx.beginPath.should.have.been.calledBefore(ctx.moveTo); ctx.moveTo.should.have.been.calledBefore(ctx.lineTo); ctx.lineTo.should.have.been.calledBefore(ctx.arc); ctx.arc.should.have.been.calledBefore(ctx.rect); ctx.rect.should.have.been.calledBefore(ctx.fill); }); it('should be chainable', () => { (() => new draw.Path().fill().fill({transform: {}, shadow: {}, color: 0x000000})).should.not.throw(); }); }); describe('#stroke({color, line, transform})', () => { it('should call context.save() at the beginning, context.restore() at the end, and context.stroke() in the middle', () => { new draw.Path().move(32, 32).line(64, 64).stroke(); ctx.save.should.have.been.calledBefore(ctx.stroke); ctx.stroke.should.have.been.calledBefore(ctx.restore); ctx.restore.should.have.been.called; }); it('should set the color, line, and transform if they are specified', () => { new draw.Path().move(32, 32).do(() => { context.strokeStyle.should.equal('#ff0000'); context.lineWidth.should.equal(5); ctx.translate.should.have.been.calledWith(5, 0); }).line(64, 64).stroke({ color: 0xff0000, line: { width: 5 }, transform: { translate: { x: 5 } } }); }); it('should call the entire stack in order', () => { new draw.Path().move(32, 32).line(64, 64).arc(32, 32, 0, 0, 3).rect(32, 32, 32, 32).stroke(); ctx.beginPath.should.have.been.calledBefore(ctx.moveTo); ctx.moveTo.should.have.been.calledBefore(ctx.lineTo); ctx.lineTo.should.have.been.calledBefore(ctx.arc); ctx.arc.should.have.been.calledBefore(ctx.rect); ctx.rect.should.have.been.calledBefore(ctx.stroke); }); it('should be chainable', () => { (() => new draw.Path().stroke().stroke({transform: {}, line: '', color: 0x000000}).stroke()).should.not.throw(); }); }); describe('#doInside([{transform},] ...todo)', () => { it('should call context.save() at the beginning, context.restore() at the end, and context.clip() in the middle', () => { new draw.Path().rect(32, 32, 64, 64).doInside(() => {}); ctx.save.should.have.been.calledBefore(ctx.clip); ctx.clip.should.have.been.calledBefore(ctx.restore); ctx.restore.should.have.been.called; }); it('should set the transform if given', () => { new draw.Path().rect(32, 32, 64, 64).doInside({ translate: { x: 5 } }, () => { ctx.translate.should.have.been.called; }); }); it('should call the entire stack in order', () => { new draw.Path().move(32, 32).line(64, 64).arc(32, 32, 0, 0, 3).rect(32, 32, 32, 32).doInside(); ctx.beginPath.should.have.been.calledBefore(ctx.moveTo); ctx.moveTo.should.have.been.calledBefore(ctx.lineTo); ctx.lineTo.should.have.been.calledBefore(ctx.arc); ctx.arc.should.have.been.calledBefore(ctx.rect); ctx.rect.should.have.been.calledBefore(ctx.clip); }); it('should call all items in todo in order, after clipping', () => { const cbs = [spy(), spy(), spy()]; new draw.Path().rect(32, 32, 64, 64).doInside(...cbs); ctx.clip.should.have.been.calledBefore(cbs[0]); cbs[0].should.have.been.calledOnce; cbs[0].should.have.been.calledBefore(cbs[1]); cbs[1].should.have.been.calledOnce; cbs[1].should.have.been.calledBefore(cbs[2]); cbs[2].should.have.been.calledOnce; }); it('should be chainable', () => { (() => new draw.Path().doInside({}, () => {}).doInside(() => {}).doInside()).should.not.throw(); }); }); describe('#copy()', () => { it('should make an identical Path', () => { const p = new draw.Path().move(32, 32).line(64, 64); const c = p.copy(); c.should.be.an.instanceof(draw.Path); c.length.should.deep.equal(p.length); }); it('should not modify the original when the copy is changed used', () => { const p = new draw.Path().move(32, 32).line(64, 64); const c = p.copy().arc(64, 64, 32, 0, Math.PI * 2); p.length.should.not.equal(c.length); }); }); describe('#contains([offx, offy,] x, y)', () => { it('should be true if the point is within the path', () => { new draw.Path().move(0, 32).line(32, 32).contains(16, 32).should.be.true; new draw.Path().move(0, 32).line(32, 32).line(32, 64).contains(30, 34).should.be.true; }); it('should be true if the point is not within the path', () => { new draw.Path().move(0, 32).line(32, 32).contains(48, 32).should.be.false; new draw.Path().move(0, 32).line(32, 32).contains(16, 16).should.be.false; }); it('should allow offsets to be specified', () => { new draw.Path().move(0, 32).line(32, 32).line(32, 64).contains(130, 134).should.be.false; new draw.Path().move(0, 32).line(32, 32).line(32, 64).contains(100, 100, 130, 134).should.be.true; }); }); }); describe('PixelData', () => { const [width, height] = [32, 32]; let pd; before(() => pd = new draw.PixelData(width, height)); it('should be constructed with new PixelData([x, y,] w, h)', () => { new draw.PixelData(32, 32).should.be.an.instanceof(draw.PixelData); new draw.PixelData(16, 16, 16, 16).should.be.an.instanceof(draw.PixelData); ctx.createImageData.should.have.been.calledWith(32, 32); ctx.getImageData.should.have.been.calledWith(16, 16, 16, 16); (() => draw.PixelData(32, 32)).should.throw(TypeError); }); describe('#width', () => { it('should return the width of the PixelData', () => { pd.width.should.equal(32); }); it('should be read only', () => { (() => pd.width = 16).should.throw(TypeError); }); }); describe('#height', () => { it('should return the height of the PixelData', () => { pd.height.should.equal(32); }); it('should be read only', () => { (() => pd.height = 16).should.throw(TypeError); }); }); describe('#data[x][y]', () => { it('should return a pixel from the ImageData', () => { pd.data[16][16].should.deep.equal([0, 0, 0, 0]); }); }); describe('#data[x][y]=', () => { it('should be settable to change the ImageData', () => { pd.data[16][16] = [255, 0, 0, 255]; pd.data[16][16].should.deep.equal([255, 0, 0, 255]); pd.data[16][16] = [0, 0, 0, 0]; pd.data[16][16].should.deep.equal([0, 0, 0, 0]); }); it('should not work with only one index', () => { (() => pd.data[16] = [255, 0, 0, 255]).should.throw(TypeError); }); }); describe('#draw(x, y)', () => { it('should draw the PixelData', () => { pd.draw(32, 32); ctx.putImageData.should.have.been.calledOnce; }); }); }); });
OinkIguana/tactical-rpg
public_html/script/test/draw.js
JavaScript
mit
29,943
using System; using Csla; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.DataAccess.Sql.ERLevel { public partial class G09_Region_ReChildDal { } }
CslaGenFork/CslaGenFork
trunk/Samples/DeepLoad/DAL-DTO/SelfLoadSoftDelete.DataAccess.Sql/ERLevel/G09_Region_ReChildDal.cs
C#
mit
197
# require '/Users/Helen/Documents/Rails/hangman_twitter_bot/lib/hangman_twitter_bot' require './lib/hangman_twitter_bot' require 'pry' controller = MainController.new controller.start
lemonlimester/hangman_twitter_bot
main.rb
Ruby
mit
184
package org.beryl.app; /** Convenience class for retrieving the current Android version that's running on the device. * * Code example on how to use AndroidVersion to load a multi-versioned class at runtime for backwards compatibility without using reflection. * <pre class="code"><code class="java"> import org.beryl.app.AndroidVersion; public class StrictModeEnabler { public static void enableOnThread() { IStrictModeEnabler enabler = getStrictModeEnabler(); } // Strict Mode is only supported on Gingerbread or higher. private static IStrictModeEnabler getStrictModeEnabler() { if(AndroidVersion.isGingerbreadOrHigher()) { return new GingerbreadAndAboveStrictModeEnabler(); } else { return new NoStrictModeEnabler(); } } } </code></pre>*/ @SuppressWarnings("deprecation") public class AndroidVersion { private static final int _ANDROID_SDK_VERSION; private static final int ANDROID_SDK_VERSION_PREVIEW = Integer.MAX_VALUE; static { int android_sdk = 3; // 3 is Android 1.5 (Cupcake) which is the earliest Android SDK available. try { android_sdk = Integer.parseInt(android.os.Build.VERSION.SDK); } catch (Exception e) { android_sdk = ANDROID_SDK_VERSION_PREVIEW; } finally {} _ANDROID_SDK_VERSION = android_sdk; } /** Returns true if running on development or preview version of Android. */ public static boolean isPreviewVersion() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; } /** Gets the SDK Level available to the device. */ public static int getSdkVersion() { return _ANDROID_SDK_VERSION; } /** Returns true if running on Android 1.5 or higher. */ public static boolean isCupcakeOrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.CUPCAKE; } /** Returns true if running on Android 1.6 or higher. */ public static boolean isDonutOrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.DONUT; } /** Returns true if running on Android 2.0 or higher. */ public static boolean isEclairOrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ECLAIR; } /** Returns true if running on Android 2.1-update1 or higher. */ public static boolean isEclairMr1OrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ECLAIR_MR1; } /** Returns true if running on Android 2.2 or higher. */ public static boolean isFroyoOrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.FROYO; } /** Returns true if running on Android 2.3 or higher. */ public static boolean isGingerbreadOrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.GINGERBREAD; } /** Returns true if running on Android 2.3.3 or higher. */ public static boolean isGingerbreadMr1OrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1; } /** Returns true if running on Android 3.0 or higher. */ public static boolean isHoneycombOrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.HONEYCOMB; } /** Returns true if running on Android 3.1 or higher. */ public static boolean isHoneycombMr1OrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1; } /** Returns true if running on Android 3.2 or higher. */ public static boolean isHoneycombMr2OrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2; } /** Returns true if running on Android 4.0 or higher. */ public static boolean isIceCreamSandwichOrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; } /** Returns true if running on Android 4.0.3 or higher. */ public static boolean isIceCreamSandwichMr1OrHigher() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1; } /** Returns true if running on an earlier version than Android 4.0.3. */ public static boolean isBeforeIceCreamSandwichMr1() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1; } /** Returns true if running on an earlier version than Android 4.0. */ public static boolean isBeforeIceCreamSandwich() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; } /** Returns true if running on an earlier version than Android 3.2. */ public static boolean isBeforeHoneycombMr2() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.HONEYCOMB_MR2; } /** Returns true if running on an earlier version than Android 3.1. */ public static boolean isBeforeHoneycombMr1() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.HONEYCOMB_MR1; } /** Returns true if running on an earlier version than Android 3.0. */ public static boolean isBeforeHoneycomb() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.HONEYCOMB; } /** Returns true if running on an earlier version than Android 2.3.3. */ public static boolean isBeforeGingerbreadMr1() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.GINGERBREAD_MR1; } /** Returns true if running on an earlier version than Android 2.3. */ public static boolean isBeforeGingerbread() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.GINGERBREAD; } /** Returns true if running on an earlier version than Android 2.2. */ public static boolean isBeforeFroyo() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.FROYO; } /** Returns true if running on an earlier version than Android 2.1-update. */ public static boolean isBeforeEclairMr1() { return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ECLAIR_MR1; } /** Returns true if running on an earlier version than Android 2.0. */ public static boolean isBeforeEclair() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.ECLAIR; } /** Returns true if running on an earlier version than Android 1.6. */ public static boolean isBeforeDonut() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.DONUT; } /** Returns true if running on an earlier version than Android 1.5. */ public static boolean isBeforeCupcake() { return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.CUPCAKE; } private AndroidVersion() { // Prevent users from instantiating this class. } }
jeremyje/android-beryl
beryl/src/org/beryl/app/AndroidVersion.java
Java
mit
6,414
package bence.prognyelvek.contexts; import java.util.List; /** * @param <T> Input token type. * @param <O> Output token type. */ public interface ContextFactory<T, O> { Context<T, O> getInstance(List<T> tokens); }
zporky/langs-and-paradigms
projects/EJULOK/Java/prognyelvek/src/main/java/bence/prognyelvek/contexts/ContextFactory.java
Java
mit
224
using System.Collections.Generic; using MVPStream.Models.Data; namespace MVPStream.Models { public class SearchResults { public long Count { get; set; } public IEnumerable<Entry> Entries { get; set; } } }
ealsur/mvpstream
Models/SearchResults.cs
C#
mit
236
<?PHP date_default_timezone_set( 'America/New_York' ); include('../php/config.php'); $db = mysql_connect($config['mysql_hostname'], $config['mysql_username'], $config['mysql_password']) ; mysql_select_db($config['mysql_database'], $db); $query = mysql_query("SELECT * FROM pedutoSchedule WHERE date like '" . date("Y-m-d",strtotime("today")) . "' AND start BETWEEN ' " . date("H:i:s", strtotime("now")) . " ' and '" . date("H:i:s", strtotime("+30 minutes")) . "'"); $event = mysql_fetch_assoc( $query ); echo json_encode($event); ?>
arm5077/wheresbill
api/index.php
PHP
mit
536
require 'tempfile' require 'posix-spawn' module Grit class Git include POSIX::Spawn class GitTimeout < RuntimeError attr_accessor :command attr_accessor :bytes_read def initialize(command = nil, bytes_read = nil) @command = command @bytes_read = bytes_read end end # Raised when a native git command exits with non-zero. class CommandFailed < StandardError # The full git command that failed as a String. attr_reader :command # The integer exit status. attr_reader :exitstatus # Everything output on the command's stderr as a String. attr_reader :err def initialize(command, exitstatus=nil, err='') if exitstatus @command = command @exitstatus = exitstatus @err = err message = "Command failed [#{exitstatus}]: #{command}" message << "\n\n" << err unless err.nil? || err.empty? super message else super command end end end undef_method :clone include GitRuby def exist? File.exist?(self.git_dir) end def put_raw_object(content, type) ruby_git.put_raw_object(content, type) end def get_raw_object(object_id) ruby_git.get_raw_object_by_sha1(object_id).content end def get_git_object(object_id) ruby_git.get_raw_object_by_sha1(object_id).to_hash end def object_exists?(object_id) ruby_git.object_exists?(object_id) end def select_existing_objects(object_ids) object_ids.select do |object_id| object_exists?(object_id) end end class << self attr_accessor :git_timeout, :git_max_size def git_binary @git_binary ||= ENV['PATH'].split(':'). map { |p| File.join(p, 'git') }. find { |p| File.exist?(p) } end attr_writer :git_binary end self.git_timeout = 10 self.git_max_size = 5242880 # 5.megabytes def self.with_timeout(timeout = 10) old_timeout = Grit::Git.git_timeout Grit::Git.git_timeout = timeout yield Grit::Git.git_timeout = old_timeout end attr_accessor :git_dir, :bytes_read, :work_tree def initialize(git_dir) self.git_dir = git_dir self.work_tree = git_dir.gsub(/\/\.git$/,'') self.bytes_read = 0 end def shell_escape(str) str.to_s.gsub("'", "\\\\'").gsub(";", '\\;') end alias_method :e, :shell_escape # Check if a normal file exists on the filesystem # +file+ is the relative path from the Git dir # # Returns Boolean def fs_exist?(file) File.exist?(File.join(self.git_dir, file)) end # Read a normal file from the filesystem. # +file+ is the relative path from the Git dir # # Returns the String contents of the file def fs_read(file) File.read(File.join(self.git_dir, file)) end # Write a normal file to the filesystem. # +file+ is the relative path from the Git dir # +contents+ is the String content to be written # # Returns nothing def fs_write(file, contents) path = File.join(self.git_dir, file) FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'w') do |f| f.write(contents) end end # Delete a normal file from the filesystem # +file+ is the relative path from the Git dir # # Returns nothing def fs_delete(file) FileUtils.rm_rf(File.join(self.git_dir, file)) end # Move a normal file # +from+ is the relative path to the current file # +to+ is the relative path to the destination file # # Returns nothing def fs_move(from, to) FileUtils.mv(File.join(self.git_dir, from), File.join(self.git_dir, to)) end # Make a directory # +dir+ is the relative path to the directory to create # # Returns nothing def fs_mkdir(dir) FileUtils.mkdir_p(File.join(self.git_dir, dir)) end # Chmod the the file or dir and everything beneath # +file+ is the relative path from the Git dir # # Returns nothing def fs_chmod(mode, file = '/') FileUtils.chmod_R(mode, File.join(self.git_dir, file)) end def list_remotes Dir.glob(File.join(self.git_dir, 'refs/remotes/*')) rescue [] end def create_tempfile(seed, unlink = false) path = Tempfile.new(seed).path File.unlink(path) if unlink return path end def commit_from_sha(id) git_ruby_repo = GitRuby::Repository.new(self.git_dir) object = git_ruby_repo.get_object_by_sha1(id) if object.type == :commit id elsif object.type == :tag object.object else '' end end # Checks if the patch of a commit can be applied to the given head. # # options - grit command options hash # head_sha - String SHA or ref to check the patch against. # applies_sha - String SHA of the patch. The patch itself is retrieved # with #get_patch. # # Returns 0 if the patch applies cleanly (according to `git apply`), or # an Integer that is the sum of the failed exit statuses. def check_applies(options={}, head_sha=nil, applies_sha=nil) options, head_sha, applies_sha = {}, options, head_sha if !options.is_a?(Hash) options = options.dup options[:env] &&= options[:env].dup git_index = create_tempfile('index', true) (options[:env] ||= {}).merge!('GIT_INDEX_FILE' => git_index) options[:raise] = true status = 0 begin native(:read_tree, options.dup, head_sha) stdin = native(:diff, options.dup, "#{applies_sha}^", applies_sha) native(:apply, options.merge(:check => true, :cached => true, :input => stdin)) rescue CommandFailed => fail status += fail.exitstatus end status end # Gets a patch for a given SHA using `git diff`. # # options - grit command options hash # applies_sha - String SHA to get the patch from, using this command: # `git diff #{applies_sha}^ #{applies_sha}` # # Returns the String patch from `git diff`. def get_patch(options={}, applies_sha=nil) options, applies_sha = {}, options if !options.is_a?(Hash) options = options.dup options[:env] &&= options[:env].dup git_index = create_tempfile('index', true) (options[:env] ||= {}).merge!('GIT_INDEX_FILE' => git_index) native(:diff, options, "#{applies_sha}^", applies_sha) end # Applies the given patch against the given SHA of the current repo. # # options - grit command hash # head_sha - String SHA or ref to apply the patch to. # patch - The String patch to apply. Get this from #get_patch. # # Returns the String Tree SHA on a successful patch application, or false. def apply_patch(options={}, head_sha=nil, patch=nil) options, head_sha, patch = {}, options, head_sha if !options.is_a?(Hash) options = options.dup options[:env] &&= options[:env].dup options[:raise] = true git_index = create_tempfile('index', true) (options[:env] ||= {}).merge!('GIT_INDEX_FILE' => git_index) begin native(:read_tree, options.dup, head_sha) native(:apply, options.merge(:cached => true, :input => patch)) rescue CommandFailed return false end native(:write_tree, :env => options[:env]).to_s.chomp! end # Execute a git command, bypassing any library implementation. # # cmd - The name of the git command as a Symbol. Underscores are # converted to dashes as in :rev_parse => 'rev-parse'. # options - Command line option arguments passed to the git command. # Single char keys are converted to short options (:a => -a). # Multi-char keys are converted to long options (:arg => '--arg'). # Underscores in keys are converted to dashes. These special options # are used to control command execution and are not passed in command # invocation: # :timeout - Maximum amount of time the command can run for before # being aborted. When true, use Grit::Git.git_timeout; when numeric, # use that number of seconds; when false or 0, disable timeout. # :base - Set false to avoid passing the --git-dir argument when # invoking the git command. # :env - Hash of environment variable key/values that are set on the # child process. # :raise - When set true, commands that exit with a non-zero status # raise a CommandFailed exception. This option is available only on # platforms that support fork(2). # :process_info - By default, a single string with output written to # the process's stdout is returned. Setting this option to true # results in a [exitstatus, out, err] tuple being returned instead. # args - Non-option arguments passed on the command line. # # Optionally yields to the block an IO object attached to the child # process's STDIN. # # Examples # git.native(:rev_list, {:max_count => 10, :header => true}, "master") # # Returns a String with all output written to the child process's stdout # when the :process_info option is not set. # Returns a [exitstatus, out, err] tuple when the :process_info option is # set. The exitstatus is an small integer that was the process's exit # status. The out and err elements are the data written to stdout and # stderr as Strings. # Raises Grit::Git::GitTimeout when the timeout is exceeded or when more # than Grit::Git.git_max_size bytes are output. # Raises Grit::Git::CommandFailed when the :raise option is set true and the # git command exits with a non-zero exit status. The CommandFailed's #command, # #exitstatus, and #err attributes can be used to retrieve additional # detail about the error. def native(cmd, options = {}, *args, &block) args = args.first if args.size == 1 && args[0].is_a?(Array) args.map! { |a| a.to_s } args.reject! { |a| a.empty? } # special option arguments env = options.delete(:env) || {} raise_errors = options.delete(:raise) process_info = options.delete(:process_info) pipeline = options.delete(:pipeline) # fall back to using a shell when the last argument looks like it wants to # start a pipeline for compatibility with previous versions of grit. if args[-1].to_s[0] == ?| && pipeline return run(prefix, cmd, '', options, args) end # more options input = options.delete(:input) timeout = options.delete(:timeout); timeout = true if timeout.nil? base = options.delete(:base); base = true if base.nil? chdir = options.delete(:chdir) # build up the git process argv argv = [] argv << Git.git_binary argv << "--git-dir=#{git_dir}" if base argv << cmd.to_s.tr('_', '-') argv.concat(options_to_argv(options)) argv.concat(args) # run it and deal with fallout Grit.log(argv.join(' ')) if Grit.debug process = Child.new(env, *(argv + [{ :input => input, :chdir => chdir, :timeout => (Grit::Git.git_timeout if timeout == true), :max => (Grit::Git.git_max_size if timeout == true) }])) Grit.log(process.out) if Grit.debug Grit.log(process.err) if Grit.debug status = process.status if raise_errors && !status.success? raise CommandFailed.new(argv.join(' '), status.exitstatus, process.err) elsif process_info [status.exitstatus, process.out, process.err] else process.out end rescue TimeoutExceeded, MaximumOutputExceeded raise GitTimeout, argv.join(' ') end # Methods not defined by a library implementation execute the git command # using #native, passing the method name as the git command name. # # Examples: # git.rev_list({:max_count => 10, :header => true}, "master") def method_missing(cmd, options={}, *args, &block) native(cmd, options, *args, &block) end # Transform a ruby-style options hash to command-line arguments sutiable for # use with Kernel::exec. No shell escaping is performed. # # Returns an Array of String option arguments. def options_to_argv(options) argv = [] options.each do |key, val| if key.to_s.size == 1 if val == true argv << "-#{key}" elsif val == false # ignore else argv << "-#{key}" argv << val.to_s end else if val == true argv << "--#{key.to_s.tr('_', '-')}" elsif val == false # ignore else argv << "--#{key.to_s.tr('_', '-')}=#{val}" end end end argv end # Simple wrapper around Timeout::timeout. # # seconds - Float number of seconds before a Timeout::Error is raised. When # true, the Grit::Git.git_timeout value is used. When the timeout is less # than or equal to 0, no timeout is established. # # Raises Timeout::Error when the timeout has elapsed. def timeout_after(seconds) seconds = self.class.git_timeout if seconds == true if seconds && seconds > 0 Timeout.timeout(seconds) { yield } else yield end end # DEPRECATED OPEN3-BASED COMMAND EXECUTION # Used only for pipeline support. # Ex. # git log | grep bugfix # def run(prefix, cmd, postfix, options, args, &block) timeout = options.delete(:timeout) rescue nil timeout = true if timeout.nil? base = options.delete(:base) rescue nil base = true if base.nil? if input = options.delete(:input) block = lambda { |stdin| stdin.write(input) } end opt_args = transform_options(options) if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin/ ext_args = args.reject { |a| a.empty? }.map { |a| (a == '--' || a[0].chr == '|' || Grit.no_quote) ? a : "\"#{e(a)}\"" } gitdir = base ? "--git-dir=\"#{self.git_dir}\"" : "" call = "#{prefix}#{Git.git_binary} #{gitdir} #{cmd.to_s.gsub(/_/, '-')} #{(opt_args + ext_args).join(' ')}#{e(postfix)}" else ext_args = args.reject { |a| a.empty? }.map { |a| (a == '--' || a[0].chr == '|' || Grit.no_quote) ? a : "'#{e(a)}'" } gitdir = base ? "--git-dir='#{self.git_dir}'" : "" call = "#{prefix}#{Git.git_binary} #{gitdir} #{cmd.to_s.gsub(/_/, '-')} #{(opt_args + ext_args).join(' ')}#{e(postfix)}" end Grit.log(call) if Grit.debug response, err = timeout ? sh(call, &block) : wild_sh(call, &block) Grit.log(response) if Grit.debug Grit.log(err) if Grit.debug response end def sh(command, &block) process = Child.new( command, :timeout => Git.git_timeout, :max => Git.git_max_size ) [process.out, process.err] rescue TimeoutExceeded, MaximumOutputExceeded raise GitTimeout, command end def wild_sh(command, &block) process = Child.new(command) [process.out, process.err] end # Transform Ruby style options into git command line options # +options+ is a hash of Ruby style options # # Returns String[] # e.g. ["--max-count=10", "--header"] def transform_options(options) args = [] options.keys.each do |opt| if opt.to_s.size == 1 if options[opt] == true args << "-#{opt}" elsif options[opt] == false # ignore else val = options.delete(opt) args << "-#{opt.to_s} '#{e(val)}'" end else if options[opt] == true args << "--#{opt.to_s.gsub(/_/, '-')}" elsif options[opt] == false # ignore else val = options.delete(opt) args << "--#{opt.to_s.gsub(/_/, '-')}='#{e(val)}'" end end end args end end # Git end # Grit
gitcafe-dev/grit
lib/grit/git.rb
Ruby
mit
16,399
<?php namespace App\Test\TestCase\Controller; use App\Controller\LevelsController; use Cake\TestSuite\IntegrationTestCase; /** * App\Controller\LevelsController Test Case */ class LevelsControllerTest extends IntegrationTestCase { /** * Fixtures * * @var array */ public $fixtures = [ 'app.levels' ]; /** * Test index method * * @return void */ public function testIndex() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test view method * * @return void */ public function testView() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test add method * * @return void */ public function testAdd() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test edit method * * @return void */ public function testEdit() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test delete method * * @return void */ public function testDelete() { $this->markTestIncomplete('Not implemented yet.'); } }
delamux/emma
tests/TestCase/Controller/LevelsControllerTest.php
PHP
mit
1,202
module Assorted VERSION = "0.0.3" end
dribbble/assorted
lib/assorted/version.rb
Ruby
mit
40
namespace Mindscape.Raygun4Net.Storage { public class RaygunFile : IRaygunFile { public string Name { get; set; } public string Contents { get; set; } } }
MindscapeHQ/raygun4net
Mindscape.Raygun4Net/Storage/RaygunFile.cs
C#
mit
168
"use strict"; var Piece = require('../lib/Piece'), map = require('../lib/map'); describe('Piece.js', function() { var piece; beforeEach(function() { piece = new Piece(1, 'black', 0, 0); }); describe('Piece Constructor', function() { // めんどくせいらね }); describe('Piece.prototype.getPiece()', function() { it('this.pieceを返す', function() { expect(piece.getPiece()).toEqual(1); }); }); describe('Piece.prototype.getFile()', function() { it('this.fileを返す', function() { expect(piece.getFile()).toEqual(0); }); }); describe('Piece.prototype.getRank()', function() { it('this.rankを返す', function() { expect(piece.getRank()).toEqual(0); }); }); describe('Piece.prototype.getPlayer()', function() { it('this.playerを返す', function() { expect(piece.getPlayer()).toEqual('black'); }); }); describe('Piece.prototype.update(args)', function() { it('Pieceのフィールドの内容を引数で指定された値に変更する', function() { piece.update({ 'piece': 5, 'file': 6, 'rank': 5, 'player': 'white' }); expect(piece.getPiece()).toEqual(5); expect(piece.getFile()).toEqual(6); expect(piece.getRank()).toEqual(5); expect(piece.getPlayer()).toEqual('white'); }); }); describe('Piece.prototype.promote()', function() { it('this.pieceの値を歩→と', function() { piece.update({'piece': map.piece('歩')}); piece.promote(); expect(piece.getPiece()).toEqual(map.piece('と')); }); it('this.pieceの値を香→成香', function() { piece.update({'piece': map.piece('香')}); piece.promote(); expect(piece.getPiece()).toEqual(map.piece('成香')); }); it('this.pieceの値を桂→成桂', function() { piece.update({'piece': map.piece('桂')}); piece.promote(); expect(piece.getPiece()).toEqual(map.piece('成桂')); }); it('this.pieceの値を銀→成銀', function() { piece.update({'piece': map.piece('銀')}); piece.promote(); expect(piece.getPiece()).toEqual(map.piece('成銀')); }); it('this.pieceの値を角→馬', function() { piece.update({'piece': map.piece('角')}); piece.promote(); expect(piece.getPiece()).toEqual(map.piece('馬')); }); it('this.pieceの値を飛→龍', function() { piece.update({'piece': map.piece('飛')}); piece.promote(); expect(piece.getPiece()).toEqual(map.piece('龍')); }); }); describe('Piece.prototype.demote()', function() { it('this.pieceの値をと→歩', function() { piece.update({'piece': map.piece('と')}); piece.captured(); expect(piece.getPiece()).toEqual(map.piece('歩')); }); it('this.pieceの値を成香→香', function() { piece.update({'piece': map.piece('成香')}); piece.captured(); expect(piece.getPiece()).toEqual(map.piece('香')); }); it('this.pieceの値を成桂→桂', function() { piece.update({'piece': map.piece('成桂')}); piece.captured(); expect(piece.getPiece()).toEqual(map.piece('桂')); }); it('this.pieceの値を成銀→銀', function() { piece.update({'piece': map.piece('成銀')}); piece.captured(); expect(piece.getPiece()).toEqual(map.piece('銀')); }); it('this.pieceの値を馬→角', function() { piece.update({'piece': map.piece('馬')}); piece.captured(); expect(piece.getPiece()).toEqual(map.piece('角')); }); it('this.pieceの値を龍→飛', function() { piece.update({'piece': map.piece('龍')}); piece.captured(); expect(piece.getPiece()).toEqual(map.piece('飛')); }); }); describe('Piece.prototype.captured()', function() { beforeEach(function () { spyOn(piece, 'demote'); }); it('fileとrankを0にして、playerを反転させ駒を降格させる', function() { piece.update({'player': 'black'}); piece.captured(); expect(piece.getFile()).toEqual(0); expect(piece.getRank()).toEqual(0); expect(piece.getPlayer()).toEqual('white'); expect(piece.demote).toHaveBeenCalled(); }); }); describe('Piece.prototype.matchMovement(move)', function() { beforeEach(function () { // パッと見わかりにくいがspyを仕込んでいる for(var i = 1, l = map.csaPiece('RY'); i <= l; i++) { spyOn(piece, 'case' + map.pieceToCsaPieceMapKey(i)); } }); it('駒に対応する関数を呼び出す', function() { var move = { 'turn': 'black', 'to': [0, 0], 'piece': 1 }; for(var i = 1, l = map.csaPiece('RY'); i <= l; i++) { move.piece = i; piece.matchMovement(move); expect(piece['case' + map.pieceToCsaPieceMapKey(i)]).toHaveBeenCalled(); } }); }); describe('Piece.prototype.checkRelative(move, dfile)', function() { /* 先手と後手両方判定しているのでそこは気にしなくていい */ var move, players; beforeEach(function () { move = { 'turn': 'black', 'to': [5, 5], 'piece': undefined, 'relative': undefined }; players = ['black', 'white']; }); it('引数move.relativeが"右"でfileの位置も右側であればtrueを返す', function() { var dfile = 0, pos = [[4, 6], [6,4]]; move.relative = '右'; piece.update({'piece': map.csaPiece('GI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeTruthy(); } }); it('引数move.relativeが"右"でfileの位置が同じか左側であればfalseを返す', function() { var dfile = 0, pos = [[5, 6], [5, 4], [6, 6], [4, 4]]; move.relative = '右'; piece.update({'piece': map.csaPiece('GI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeFalsy(); } }); it('引数move.relativeが"左"でfileの位置も左側であればtrueを返す', function() { var dfile = 0, pos = [[6, 6], [4,4]]; move.relative = '左'; piece.update({'piece': map.csaPiece('GI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeTruthy(); } }); it('引数move.relativeが"左"でfileの位置が同じか右側であればfalseを返す', function() { var dfile = 0, pos = [[5, 6], [5, 4], [4, 6], [6, 4]]; move.relative = '左'; piece.update({'piece': map.csaPiece('GI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeFalsy(); } }); /* 馬と龍のケース */ it('馬と龍で引数move.relativeが"右"でfileも右側か同じ位置であればtrueを返す', function() { var dfile = 0, pos = [[4, 6], [6, 4], [5, 6], [5, 4]], pieces = [map.csaPiece('UM'), map.csaPiece('RY')]; move.relative = '右'; for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); for(var j = 0, jl = pieces.length; j < jl; j++) { move.piece = pieces[j]; piece.update({'piece': pieces[j]}); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeTruthy(); } } }); it('馬と龍で引数move.relativeが"右"でfileが左側の位置であればfalseを返す', function() { var dfile = 0, pos = [[6, 6], [4, 4]], pieces = [map.csaPiece('UM'), map.csaPiece('RY')]; move.relative = '右'; for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); for(var j = 0, jl = pieces.length; j < jl; j++) { move.piece = pieces[j]; piece.update({'piece': pieces[j]}); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeFalsy(); } } }); it('馬と龍で引数move.relativeが"左"でfileも左側か同じ位置であればtrueを返す', function() { var dfile = 0, pos = [[6, 6], [4, 6], [5, 6], [5, 4]], pieces = [map.csaPiece('UM'), map.csaPiece('RY')]; move.relative = '左'; for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); for(var j = 0, jl = pieces.length; j < jl; j++) { move.piece = pieces[j]; piece.update({'piece': pieces[j]}); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeTruthy(); } } }); it('馬と龍で引数move.relativeが"左"でfileが右側の位置であればfalseを返す', function() { var dfile = 0, pos = [[4, 6], [6, 4]], pieces = [map.csaPiece('UM'), map.csaPiece('RY')]; move.relative = '左'; for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); for(var j = 0, jl = pieces.length; j < jl; j++) { move.piece = pieces[j]; piece.update({'piece': pieces[j]}); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeFalsy(); } } }); it('引数move.relativeが"直"でfileの位置が同じであればtrueを返す', function() { var dfile = 0; move.relative = '直'; piece.update({ 'piece': map.csaPiece('GI'), 'player': 'black', 'file': 5, 'rank': 6 }); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeTruthy(); }); it('引数move.relativeが"直"でfileの位置が同じでなければfalseを返す', function() { var dfile = 0; move.relative = '直'; piece.update({ 'piece': map.csaPiece('GI'), 'player': 'black', 'file': 5, 'rank': 6 }); // fileが右側になるのであればfalse piece.update({'file': 4}); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeFalsy(); // fileが左側になるのであればfalse piece.update({'file': 6}); dfile = piece.getFile() - move.to[0]; expect(piece.checkRelative(move, dfile)).toBeFalsy(); }); }); describe('Piece.prototype.checkMotion(move)', function() { /* 先手と後手両方判定しているのでそれは気にしなくていい */ var move, players; beforeEach(function () { move = { 'turn': 'black', 'to': [5, 5], 'piece': undefined, 'motion': undefined }; players = ['black', 'white']; }); it('引数move.motionが"上"でrankの位置がpieceより下側の位置であればtrueを返す', function() { var drank = 0, pos = [[4, 6], [6, 4]]; move.motion = '上'; piece.update({'piece': map.csaPiece('GI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); drank = piece.getRank() - move.to[0]; expect(piece.checkMotion(move, drank)).toBeTruthy(); } }); it('引数move.motionが"上"でrankの位置がpieceと同じであればfalseを返す', function() { var drank = 0, pos = [[4, 5], [5, 6]]; move.motion = '上'; piece.update({'piece': map.csaPiece('GI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); drank = piece.getRank() - move.to[0]; expect(piece.checkMotion(move, drank)).toBeFalsy(); } }); it('引数move.motionが"引"でrankの位置がpieceより上側の位置であればtrueを返す', function() { var drank = 0, pos = [[4, 4], [4, 6]]; move.motion = '引'; piece.update({'piece': map.csaPiece('GI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); drank = piece.getRank() - move.to[0]; expect(piece.checkMotion(move, drank)).toBeTruthy(); } }); it('引数move.motionが"引"でrankの位置がpieceと同じであればfalseを返す', function() { var drank = 0, pos = [[4, 5], [6, 5]]; move.motion = '引'; piece.update({'piece': map.csaPiece('KI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); drank = piece.getRank() - move.to[0]; expect(piece.checkMotion(move, drank)).toBeFalsy(); } }); it('引数move.motionが"寄"でrankの位置がpieceと同じであればtrueを返す', function() { var drank = 0, pos = [[4, 5], [6, 5]]; move.motion = '寄'; piece.update({'piece': map.csaPiece('KI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); drank = piece.getRank() - move.to[0]; expect(piece.checkMotion(move, drank)).toBeTruthy(); } }); it('引数move.motionが"寄"でrankの位置がpieceと同じでなければfalseを返す', function() { var drank = 0, pos = [[4, 6], [6, 4]]; move.motion = '寄'; piece.update({'piece': map.csaPiece('KI')}); for(var i = 0, l = players.length; i < l; i++) { piece.update({ 'player': players[i], 'file': pos[i][0], 'rank': pos[i][1] }); drank = piece.getRank() - move.to[0]; expect(piece.checkMotion(move, drank)).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestForward(file, rank)', function() { it('(先手)trueを返す', function() { var move = { 'turn': 'black', 'to': [5, 4] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); expect(piece.checkDestForward(move.to[0], move.to[1])).toBeTruthy(); }); it('(後手)trueを返す', function() { var move = { 'turn': 'white', 'to': [5, 6] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); expect(piece.checkDestForward(move.to[0], move.to[1])).toBeTruthy(); }); it('(先手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 5]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestForward(move.to[0], move.to[1])).toBeFalsy(); } }); it('(後手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 4], [4, 6], [4, 5], [4, 4], [5, 5]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestForward(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestBackward(file, rank)', function() { it('(先手)trueを返す', function() { var move = { 'turn': 'black', 'to': [5, 6] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); expect(piece.checkDestBackward(move.to[0], move.to[1])).toBeTruthy(); }); it('(後手)trueを返す', function() { var move = { 'turn': 'white', 'to': [5, 4] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); expect(piece.checkDestBackward(move.to[0], move.to[1])).toBeTruthy(); }); it('(先手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 4], [4, 6], [4, 5], [4, 4], [5, 5]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestBackward(move.to[0], move.to[1])).toBeFalsy(); } }); it('(後手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 5]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestBackward(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestUpperLeft(file, rank)', function() { it('(先手)trueを返す', function() { var move = { 'turn': 'black', 'to': [6, 4] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); expect(piece.checkDestUpperLeft(move.to[0], move.to[1])).toBeTruthy(); }); it('(後手)trueを返す', function() { var move = { 'turn': 'white', 'to': [4, 6] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); expect(piece.checkDestUpperLeft(move.to[0], move.to[1])).toBeTruthy(); }); it('(先手)falseを返す', function() { var to = [[6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestUpperLeft(move.to[0], move.to[1])).toBeFalsy(); } }); it('(後手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 5], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestUpperLeft(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestLeft(file, rank)', function() { it('(先手)trueを返す', function() { var move = { 'turn': 'black', 'to': [6, 5] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); expect(piece.checkDestLeft(move.to[0], move.to[1])).toBeTruthy(); }); it('(後手)trueを返す', function() { var move = { 'turn': 'white', 'to': [4, 5] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); expect(piece.checkDestLeft(move.to[0], move.to[1])).toBeTruthy(); }); it('(先手)falseを返す', function() { var to = [[6, 4], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestLeft(move.to[0], move.to[1])).toBeFalsy(); } }); it('(後手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestLeft(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestBottomLeft(file, rank)', function() { it('(先手)trueを返す', function() { var move = { 'turn': 'black', 'to': [6, 6] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); expect(piece.checkDestBottomLeft(move.to[0], move.to[1])).toBeTruthy(); }); it('(後手)trueを返す', function() { var move = { 'turn': 'white', 'to': [4, 4] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); expect(piece.checkDestBottomLeft(move.to[0], move.to[1])).toBeTruthy(); }); it('(先手)falseを返す', function() { var to = [[6, 4], [6, 5], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestBottomLeft(move.to[0], move.to[1])).toBeFalsy(); } }); it('(後手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 5], [4, 6], [5, 4], [5, 5]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestBottomLeft(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestUpperRight(file, rank)', function() { it('(先手)trueを返す', function() { var move = { 'turn': 'black', 'to': [4, 4] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); expect(piece.checkDestUpperRight(move.to[0], move.to[1])).toBeTruthy(); }); it('(後手)trueを返す', function() { var move = { 'turn': 'white', 'to': [6, 6] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); expect(piece.checkDestUpperRight(move.to[0], move.to[1])).toBeTruthy(); }); it('(先手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [5, 4], [5, 5]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestUpperRight(move.to[0], move.to[1])).toBeFalsy(); } }); it('(後手)falseを返す', function() { var to = [[6, 4], [6, 5], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestUpperRight(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestRight(file, rank)', function() { it('(先手)trueを返す', function() { var move = { 'turn': 'black', 'to': [4, 5] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); expect(piece.checkDestRight(move.to[0], move.to[1])).toBeTruthy(); }); it('(後手)trueを返す', function() { var move = { 'turn': 'white', 'to': [6, 5] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); expect(piece.checkDestRight(move.to[0], move.to[1])).toBeTruthy(); }); it('(先手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestRight(move.to[0], move.to[1])).toBeFalsy(); } }); it('(後手)falseを返す', function() { var to = [[6, 4], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestRight(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestBottomrRight(file, rank)', function() { it('(先手)trueを返す', function() { var move = { 'turn': 'black', 'to': [4, 6] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); expect(piece.checkDestBottomRight(move.to[0], move.to[1])).toBeTruthy(); }); it('(後手)trueを返す', function() { var move = { 'turn': 'white', 'to': [6, 4] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); expect(piece.checkDestBottomRight(move.to[0], move.to[1])).toBeTruthy(); }); it('(先手)falseを返す', function() { var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 5], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestBottomRight(move.to[0], move.to[1])).toBeFalsy(); } }); it('(後手)falseを返す', function() { var to = [[6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestBottomRight(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestDirectly(file, rank)', function() { it('(先手)trueを返す', function() { var to = [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 1, 'rank': 9 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestDirectly(move.to[0], move.to[1])).toBeTruthy(); } }); it('(後手)trueを返す', function() { var to = [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8], [1, 9]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 1, 'rank': 1 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestDirectly(move.to[0], move.to[1])).toBeTruthy(); } }); it('(先手)falseを返す', function() { var to = [[1, 9], [2, 1]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 1, 'rank': 9 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestDirectly(move.to[0], move.to[1])).toBeFalsy(); } }); it('(後手)falseを返す', function() { var to = [[1, 1], [2, 9]], move = { 'turn': 'white', 'to': [] }; piece.update({ 'player': 'white', 'file': 1, 'rank': 1 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestDirectly(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestDiagonal(file, rank)', function() { it('(先後同じ)trueを返す', function() { var to = [ [6, 4], [7, 3], [8, 2], [9, 1], [6, 6], [7, 7], [8, 8], [9, 9], [4, 4], [3, 3], [2, 2], [1, 1], [4, 6], [3, 7], [2, 8], [1, 9]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestDiagonal(move.to[0], move.to[1])).toBeTruthy(); } }); it('falseを返す', function() { var to = [ [5, 5], [5, 6], [6, 5], [5, 4], [4, 5], [10, 0], [5, 0], [0, 0], [0, 10]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestDiagonal(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.checkDestOrthogonal(file, rank)', function() { it('(先後同じ)trueを返す', function() { var to = [ [6, 5], [7, 5], [8, 5], [9, 5], [5, 4], [5, 3], [5, 2], [5, 1], [4, 5], [3, 5], [2, 5], [1, 5], [5, 6], [5, 7], [5, 8], [5, 9]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestOrthogonal(move.to[0], move.to[1])).toBeTruthy(); } }); it('falseを返す', function() { var to = [ [5, 5], [6, 4], [6, 6], [4, 4], [4, 6], [10, 5], [5, 0], [0, 5], [5, 10]], move = { 'turn': 'black', 'to': [] }; piece.update({ 'player': 'black', 'file': 5, 'rank': 5 }); for(var i = 0, l = to.length; i < l; i++) { move.to = to[i]; expect(piece.checkDestOrthogonal(move.to[0], move.to[1])).toBeFalsy(); } }); }); describe('Piece.prototype.caseFU(move)', function() { beforeEach(function() { piece.update({ 'piece': map.csaPiece('FU'), 'file': 5, 'rank': 5 }); }); it('(先手)移動前の歩に該当すればtrueを返す', function() { var move = { 'turn': 'black', 'to': [5, 4], 'piece': map.csaPiece('FU') }; piece.update({'player': 'black'}); expect(piece.caseFU(move)).toBeTruthy(); }); it('(後手)移動前の歩に該当すればtrueを返す', function() { var move = { 'turn': 'white', 'to': [5, 6], 'piece': map.csaPiece('FU') }; piece.update({'player': 'white'}); expect(piece.caseFU(move)).toBeTruthy(); }); it('移動前の歩に該当しなければfalseを返す', function() { var move = { 'turn': 'black', 'to': [5, 6], 'piece': map.csaPiece('FU') }; piece.update({'player': 'black'}); expect(piece.caseFU(move)).toBeFalsy(); }); }); describe('Piece.prototype.caseKY(move)', function() { it('(先手)移動前の香に該当すればtrueを返す', function() { var move = { 'turn': 'black', 'to': [1, 1], 'piece': map.csaPiece('KY') }; piece.update({ 'piece': map.csaPiece('KY'), 'player': 'black', 'file': 1, 'rank': 9 }); expect(piece.caseKY(move)).toBeTruthy(); }); it('(後手)移動前の香に該当すればtrueを返す', function() { var move = { 'turn': 'white', 'to': [1, 9], 'piece': map.csaPiece('KY') }; piece.update({ 'piece': map.csaPiece('KY'), 'player': 'white', 'file': 1, 'rank': 1 }); expect(piece.caseKY(move)).toBeTruthy(); }); it('移動前の香に該当しなければfalseを返す', function() { var move = { 'turn': 'black', 'to': [1, 5], 'piece': map.csaPiece('KY') }; piece.update({ 'piece': map.csaPiece('KY'), 'player': 'black', 'file': 1, 'rank': 2 }); expect(piece.caseKY(move)).toBeFalsy(); }); }); describe('Piece.prototype.caseKE(move)', function() { beforeEach(function() { piece.update({ 'piece': map.csaPiece('KE'), 'file': 5, 'rank': 5 }); }); it('(先手)移動前の桂に該当すればtrueを返す', function() { var move = { 'turn': 'black', 'to': [6, 3], 'piece': map.csaPiece('KE') }; piece.update({'player': 'black'}); expect(piece.caseKE(move)).toBeTruthy(); }); it('(後手)移動前の桂に該当すればtrueを返す', function() { var move = { 'turn': 'white', 'to': [6, 7], 'piece': map.csaPiece('KE') }; piece.update({'player': 'white'}); expect(piece.caseKE(move)).toBeTruthy(); }); it('移動前の桂に該当しなければfalseを返す', function() { var move = { 'turn': 'black', 'to': [6, 2], 'piece': map.csaPiece('KE') }; piece.update({'player': 'black'}); expect(piece.caseKE(move)).toBeFalsy(); }); }); describe('Piece.prototype.caseGI(move)', function() { beforeEach(function() { piece.update({ 'piece': map.csaPiece('GI'), 'file': 5, 'rank': 5 }); }); it('(先手)移動前の銀に該当すればtrueを返す', function() { var pos = [[4, 6], [6, 6], [6, 4], [4, 4], [5, 4]], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('GI') }; piece.update({'player': 'black'}); for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseGI(move)).toBeTruthy(); } }); it('(後手)移動前の銀に該当すればtrueを返す', function() { var pos = [[4, 6], [6, 6], [6, 4], [4, 4], [5, 6]], move = { 'turn': 'white', 'to': [], 'piece': map.csaPiece('GI') }; piece.update({'player': 'white'}); for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseGI(move)).toBeTruthy(); } }); it('移動前の銀に該当しなければfalseを返す', function() { var pos = [[4, 5], [6, 5], [5, 6], [5, 5]], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('GI') }; piece.update({'player': 'black'}); for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseGI(move)).toBeFalsy(); } }); }); describe('Piece.prototype.caseKI(move)', function() { beforeEach(function() { piece.update({ 'piece': map.csaPiece('KI'), 'file': 5, 'rank': 5 }); }); it('(先手)移動前の金に該当すればtrueを返す', function() { var pos = [[5, 4], [4, 4], [4, 5], [5, 6], [6, 5], [6, 4]], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('KI') }; piece.update({'player': 'black'}); for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseKI(move)).toBeTruthy(); } }); it('(後手)移動前の金に該当すればtrueを返す', function() { var pos = [[5, 6], [6, 6], [6, 5], [5, 4], [4, 5], [4, 6]], move = { 'turn': 'white', 'to': [], 'piece': map.csaPiece('KI') }; piece.update({'player': 'white'}); for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseKI(move)).toBeTruthy(); } }); it('移動前の金に該当しなければfalseを返す', function() { var pos = [[6, 6], [4, 6], [5, 5]], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('KI') }; piece.update({'player': 'black'}); for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseKI(move)).toBeFalsy(); } }); }); describe('Piece.prototype.caseKA(move)', function() { beforeEach(function() { piece.update({ 'piece': map.csaPiece('KA'), 'file': 5, 'rank': 5 }); }); it('(先後同じ)移動前の角に該当すればtrueを返す', function() { var pos = [], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('KA') }; piece.update({'player': 'black'}); pos = [ [6, 4], [7, 3], [8, 2], [9, 1], [6, 6], [7, 7], [8, 8], [9, 9], [4, 4], [3, 3], [2, 2], [1, 1], [4, 6], [3, 7], [2, 8], [1, 9] ]; for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseKA(move)).toBeTruthy(); } }); it('移動前の角に該当しなければfalseを返す', function() { var pos = [], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('KA') }; piece.update({'player': 'black'}); pos = [ [5, 5], [5, 6], [6, 5], [5, 4], [4, 5], [10, 0], [5, 0], [0, 0], [0, 10], ]; for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseKA(move)).toBeFalsy(); } }); }); describe('Piece.prototype.caseHI(move)', function() { beforeEach(function() { piece.update({ 'piece': map.csaPiece('HI'), 'file': 5, 'rank': 5 }); }); it('(先後同じ)移動前の飛車に該当すればtrueを返す', function() { var pos = [], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('HI') }; piece.update({'player': 'black'}); pos = [ [6, 5], [7, 5], [8, 5], [9, 5], [5, 4], [5, 3], [5, 2], [5, 1], [4, 5], [3, 5], [2, 5], [1, 5], [5, 6], [5, 7], [5, 8], [5, 9] ]; for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseHI(move)).toBeTruthy(); } }); it('移動前の飛車に該当しなければfalseを返す', function() { var pos = [], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('HI') }; piece.update({'player': 'black'}); pos = [ [5, 5], [6, 4], [6, 6], [4, 4], [4, 6], [10, 5], [5, 0], [0, 5], [5, 10] ]; for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseHI(move)).toBeFalsy(); } }); }); describe('Piece.prototype.caseOU(move)', function() { beforeEach(function() { piece.update({ 'piece': map.csaPiece('OU'), 'player': 'black', 'file': 5, 'rank': 5 }); }); it('(先後同じ)移動前の王に該当すればtrueを返す', function() { var pos = [[5, 4], [4, 4], [4, 5], [4, 6], [5, 6], [6, 6], [6, 5], [6, 4]], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('OU') }; for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseOU(move)).toBeTruthy(); } }); it('移動前の王に該当しなければfalseを返す', function() { var move = { 'turn': 'black', 'to': [5, 5], 'piece': map.csaPiece('OU') }; expect(piece.caseOU(move)).toBeFalsy(); }); }); describe('Piece.prototype.caseUM(move)', function() { beforeEach(function() { piece.update({ 'piece': map.csaPiece('UM'), 'player': 'black', 'file': 5, 'rank': 5 }); }); it('(先後同じ)移動前の馬に該当すればtrueを返す', function() { var pos = [], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('UM') }; pos = [ [6, 4], [7, 3], [8, 2], [9, 1], [6, 6], [7, 7], [8, 8], [9, 9], [4, 4], [3, 3], [2, 2], [1, 1], [4, 6], [3, 7], [2, 8], [1, 9], [5, 4], [4, 5], [5, 6], [6, 5] ]; for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseUM(move)).toBeTruthy(); } }); it('移動前の馬に該当しなければfalseを返す', function() { var move = { 'turn': 'black', 'to': [5, 5], 'piece': map.csaPiece('UM') }; expect(piece.caseUM(move)).toBeFalsy(); }); }); describe('Piece.prototype.caseRY(move)', function() { beforeEach(function() { piece.update({ 'piece': map.csaPiece('RY'), 'player': 'black', 'file': 5, 'rank': 5 }); }); it('(先後同じ)移動前の龍に該当すればtrueを返す', function() { var pos = [], move = { 'turn': 'black', 'to': [], 'piece': map.csaPiece('RY') }; pos = [ [6, 5], [7, 5], [8, 5], [9, 5], [5, 4], [5, 3], [5, 2], [5, 1], [4, 5], [3, 5], [2, 5], [1, 5], [5, 6], [5, 7], [5, 8], [5, 9], [4, 4], [4, 6], [6, 6], [6, 4] ]; for(var i = 0, l = pos.length; i < l; i++) { move.to = pos[i]; expect(piece.caseRY(move)).toBeTruthy(); } }); it('移動前の龍に該当しなければfalseを返す', function() { var move = { 'turn': 'black', 'to': [5, 5], 'piece': map.csaPiece('RY') }; expect(piece.caseRY(move)).toBeFalsy(); }); }); });
sandai/kifuparser
test/Piece.test.js
JavaScript
mit
44,711
/* * Exercicio 5.7 * Livro: Aprenda a programar com C# * Autores: Antonio Trigo e Jorge Henriques * Disponível em: http://www.silabo.pt */ using System; namespace Cap5 { class Program { static void Main(string[] args) { int nota; Console.Write("Introduza a nota: "); // Não é feita validação, ou seja, o utilizador pode introduzir valores fora nota = Convert.ToInt32(Console.ReadLine());// da gama permitida (0:20) ou caracteres inválidos e como tal gerar excepções (ERROS) Console.WriteLine(nota>=10 ? "Parabéns" : "Faça um novo exame"); } } }
atrigo/livroCSharp
Exercicios/Capitulo5/Exercicio5.7.cs
C#
mit
653
process.env.NODE_ENV = 'development'; // Load environment variables from .env file. Suppress warnings using silent // if this file is missing. dotenv will never modify any environment variables // that have already been set. // https://github.com/motdotla/dotenv require('dotenv').config({silent: true}); var chalk = require('chalk'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var historyApiFallback = require('connect-history-api-fallback'); var httpProxyMiddleware = require('http-proxy-middleware'); var detect = require('detect-port'); var clearConsole = require('react-dev-utils/clearConsole'); var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); var openBrowser = require('react-dev-utils/openBrowser'); var prompt = require('react-dev-utils/prompt'); var config = require('../config/webpack.config.dev'); var paths = require('../config/paths'); // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { process.exit(1); } // Tools like Cloud9 rely on this. var DEFAULT_PORT = process.env.PORT || 3000; var compiler; var handleCompile; function setupCompiler(host, port, protocol) { // "Compiler" is a low-level interface to Webpack. // It lets us listen to some events and provide our own custom messages. compiler = webpack(config, handleCompile); // "invalid" event fires when you have changed a file, and Webpack is // recompiling a bundle. WebpackDevServer takes care to pause serving the // bundle, so if you refresh, it'll wait instead of serving the old one. // "invalid" is short for "bundle invalidated", it doesn't imply any errors. compiler.plugin('invalid', function() { clearConsole(); console.log('Compiling...'); }); // "done" event fires when Webpack has finished recompiling the bundle. // Whether or not you have warnings or errors, you will get this event. compiler.plugin('done', function(stats) { clearConsole(); // We have switched off the default Webpack output in WebpackDevServer // options so we are going to "massage" the warnings and errors and present // them in a readable focused way. var messages = formatWebpackMessages(stats.toJson({}, true)); if (!messages.errors.length && !messages.warnings.length) { console.log(chalk.green('Compiled successfully!')); console.log(); console.log('The app is running at:'); console.log(); console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/')); console.log(); console.log('Note that the development build is not optimized.'); console.log('To create a production build, use ' + chalk.cyan('npm run build') + '.'); console.log(); } // If errors exist, only show errors. if (messages.errors.length) { console.log(chalk.red('Failed to compile.')); console.log(); messages.errors.forEach(message => { console.log(message); console.log(); }); return; } // Show warnings if no errors were found. if (messages.warnings.length) { console.log(chalk.yellow('Compiled with warnings.')); console.log(); messages.warnings.forEach(message => { console.log(message); console.log(); }); // Teach some ESLint tricks. console.log('You may use special comments to disable some warnings.'); console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.'); console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.'); } }); } // We need to provide a custom onError function for httpProxyMiddleware. // It allows us to log custom error messages on the console. function onProxyError(proxy) { return function(err, req, res){ var host = req.headers && req.headers.host; console.log( chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) + ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.' ); console.log( 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' + chalk.cyan(err.code) + ').' ); console.log(); // And immediately send the proper error response to the client. // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side. if (res.writeHead && !res.headersSent) { res.writeHead(500); } res.end('Proxy error: Could not proxy request ' + req.url + ' from ' + host + ' to ' + proxy + ' (' + err.code + ').' ); } } function addMiddleware(devServer) { // `proxy` lets you to specify a fallback server during development. // Every unrecognized request will be forwarded to it. var proxy = require(paths.appPackageJson).proxy; devServer.use(historyApiFallback({ // Paths with dots should still use the history fallback. // See https://github.com/facebookincubator/create-react-app/issues/387. disableDotRule: true, // For single page apps, we generally want to fallback to /index.html. // However we also want to respect `proxy` for API calls. // So if `proxy` is specified, we need to decide which fallback to use. // We use a heuristic: if request `accept`s text/html, we pick /index.html. // Modern browsers include text/html into `accept` header when navigating. // However API calls like `fetch()` won’t generally accept text/html. // If this heuristic doesn’t work well for you, don’t use `proxy`. htmlAcceptHeaders: proxy ? ['text/html'] : ['text/html', '*/*'] })); if (proxy) { if (typeof proxy !== 'string') { console.log(chalk.red('When specified, "proxy" in package.json must be a string.')); console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".')); console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.')); process.exit(1); } // Otherwise, if proxy is specified, we will let it handle any request. // There are a few exceptions which we won't send to the proxy: // - /index.html (served as HTML5 history API fallback) // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading) // - /sockjs-node/* (WebpackDevServer uses this for hot reloading) // Tip: use https://jex.im/regulex/ to visualize the regex var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/; devServer.use(mayProxy, // Pass the scope regex both to Express and to the middleware for proxying // of both HTTP and WebSockets to work without false positives. httpProxyMiddleware(pathname => mayProxy.test(pathname), { target: proxy, logLevel: 'silent', onError: onProxyError(proxy), secure: false, changeOrigin: true }) ); } // Finally, by now we have certainly resolved the URL. // It may be /index.html, so let the dev server try serving it again. devServer.use(devServer.middleware); } function runDevServer(host, port, protocol) { var devServer = new WebpackDevServer(compiler, { // Silence WebpackDevServer's own logs since they're generally not useful. // It will still show compile warnings and errors with this setting. clientLogLevel: 'none', // By default WebpackDevServer serves physical files from current directory // in addition to all the virtual build products that it serves from memory. // This is confusing because those files won’t automatically be available in // production build folder unless we copy them. However, copying the whole // project directory is dangerous because we may expose sensitive files. // Instead, we establish a convention that only files in `public` directory // get served. Our build script will copy `public` into the `build` folder. // In `index.html`, you can get URL of `public` folder with %PUBLIC_PATH%: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In JavaScript code, you can access it with `process.env.PUBLIC_URL`. // Note that we only recommend to use `public` folder as an escape hatch // for files like `favicon.ico`, `manifest.json`, and libraries that are // for some reason broken when imported through Webpack. If you just want to // use an image, put it in `src` and `import` it from JavaScript instead. contentBase: paths.appPublic, // Enable hot reloading server. It will provide /sockjs-node/ endpoint // for the WebpackDevServer client so it can learn when the files were // updated. The WebpackDevServer client is included as an entry point // in the Webpack development configuration. Note that only changes // to CSS are currently hot reloaded. JS changes will refresh the browser. hot: true, // It is important to tell WebpackDevServer to use the same "root" path // as we specified in the config. In development, we always serve from /. publicPath: config.output.publicPath, // WebpackDevServer is noisy by default so we emit custom message instead // by listening to the compiler events with `compiler.plugin` calls above. quiet: true, // Reportedly, this avoids CPU overload on some systems. // https://github.com/facebookincubator/create-react-app/issues/293 watchOptions: { ignored: /node_modules/ }, // Enable HTTPS if the HTTPS environment variable is set to 'true' https: protocol === "https", host: host }); // Our custom middleware proxies requests to /index.html or a remote API. addMiddleware(devServer); // Launch WebpackDevServer. devServer.listen(port, (err, result) => { if (err) { return console.log(err); } clearConsole(); console.log(chalk.cyan('Starting the development server...')); console.log(); openBrowser(protocol + '://' + host + ':' + port + '/'); }); } function run(port) { var protocol = process.env.HTTPS === 'true' ? "https" : "http"; var host = process.env.HOST || 'localhost'; setupCompiler(host, port, protocol); runDevServer(host, port, protocol); } // We attempt to use the default port but if it is busy, we offer the user to // run on a different port. `detect()` Promise resolves to the next free port. detect(DEFAULT_PORT).then(port => { if (port == DEFAULT_PORT) { run(port); return; } clearConsole(); var question = chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.') + '\n\nWould you like to run the app on another port instead?'; prompt(question, true).then(shouldChangePort => { if (shouldChangePort) { run(port); } }); });
adeira/connector-frontend
scripts/start.js
JavaScript
mit
10,834
# https://www.w3resource.com/python-exercises/ # 3. Write a Python program to display the current date and time. # Sample Output : # Current date and time : # 2014-07-05 14:34:14 import datetime now = datetime.datetime.now() print now.strftime("%Y-%m-%d %H:%M:%S")
dadavidson/Python_Lab
Python-w3resource/Python_Basic/ex03.py
Python
mit
269
define([], () => { 'use strict'; class FeedsError extends Error { constructor(...args) { console.error('FeedsError', args); super(args); } } class ServerError extends Error { constructor(...args) { super(args); } } function queryToString(query) { return Array.from(query.entries()).map(([k, v]) => { return [ k, encodeURIComponent(v) ].join('='); }).join('&'); } class FeedsClient { constructor(params) { this.params = params; } put(path, body) { const url = (this.baseURLPath().concat(path)).join('/'); return fetch(url, { headers: { Authorization: this.params.token, Accept: 'application/json', 'Content-Type': 'application/json' }, mode: 'cors', method: 'PUT', body: JSON.stringify(body) }) .then((response) => { if (response.status === 500) { switch (response.headers.get('Content-Type')) { case 'application/json': return response.json() .then((result) => { throw new FeedsError(result); }); case 'text/plain': return response.text() .then((errorText) => { throw new ServerError(errorText); }); default: throw new Error('Unexpected content type: ' + response.headers.get('Content-Type')); } } else if (response.status !== 200) { throw new Error('Unexpected response: ' + response.status + ' : ' + response.statusText); } else { return response.json() .then((result) => { return result; }); } }); } post(path, body) { const url = (this.baseURLPath().concat(path)).join('/'); return fetch(url, { headers: { Authorization: this.params.token, Accept: 'application/json', 'Content-Type': 'application/json' }, mode: 'cors', method: 'POST', body: body ? JSON.stringify(body) : '' }) .then((response) => { if (response.status === 500) { switch (response.headers.get('Content-Type')) { case 'application/json': return response.json() .then((result) => { throw new FeedsError(result); }); case 'text/plain': return response.text() .then((errorText) => { throw new ServerError(errorText); }); default: throw new Error('Unexpected content type: ' + response.headers.get('Content-Type')); } } else if (response.status === 200) { return response.json(); } else if (response.status === 204) { return null; } else { throw new Error('Unexpected response: ' + response.status + ' : ' + response.statusText); } }); } postWithResult(path, body) { const url = (this.baseURLPath().concat(path)).join('/'); return fetch(url, { headers: { Authorization: this.params.token, Accept: 'application/json', 'Content-Type': 'application/json' }, mode: 'cors', method: 'POST', body: body ? JSON.stringify(body) : '' }) .then((response) => { if (response.status === 500) { switch (response.headers.get('Content-Type')) { case 'application/json': return response.json() .then((result) => { throw new FeedsError(result); }); case 'text/plain': return response.text() .then((errorText) => { throw new ServerError(errorText); }); default: throw new Error('Unexpected content type: ' + response.headers.get('Content-Type')); } } else if (response.status === 200) { return response.json(); } else { throw new Error('Unexpected response: ' + response.status + ' : ' + response.statusText); } }); } makeUrl(path, query) { const baseUrl = (this.baseURLPath().concat(path)).join('/'); if (query) { return baseUrl + '?' + queryToString(query); } return baseUrl; } get(path, query) { const url = this.makeUrl(path, query); return fetch(url, { headers: { Authorization: this.params.token, Accept: 'application/json', 'Content-Type': 'application/json' }, mode: 'cors', method: 'GET' }) .then((response) => { if (response.status === 500) { switch (response.headers.get('Content-Type')) { case 'application/json': return response.json() .then((result) => { throw new FeedsError(result); }); case 'text/plain': return response.text() .then((errorText) => { throw new ServerError(errorText); }); default: throw new Error('Unexpected content type: ' + response.headers.get('Content-Type')); } } else if (response.status === 200) { return response.json(); } else { throw new Error('Unexpected response: ' + response.status + ' : ' + response.statusText); } }); } baseURLPath() { return [this.params.url, 'api', 'V1']; } getNotifications({ count = 100 } = {}) { const options = new Map(); options.set('n', String(count)); return this.get(['notifications'], options); } getUnseenNotificationCount() { return this.get(['notifications', 'unseen_count']); } seeNotifications(param) { return this.postWithResult(['notifications', 'see'], param); } } return { FeedsClient, FeedsError, ServerError }; });
briehl/kbase-ui
src/client/modules/lib/feeds.js
JavaScript
mit
8,054
// Type definitions for ag-grid-community v20.2.0 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> import { Component } from "./component"; export declare class PopupWindow extends Component { private static TEMPLATE; static DESTROY_EVENT: string; private popupService; private eContentWrapper; private eTitle; private eClose; protected closePopup: () => void; constructor(); protected postConstruct(): void; setBody(eBody: HTMLElement): void; setTitle(title: string): void; private onBtClose; destroy(): void; }
ceolter/angular-grid
dist/lib/widgets/popupWindow.d.ts
TypeScript
mit
614
module Precious module Views class HistoryAll < Layout def title "Recent activity on Weaki" end def versions i = @versions.size + 1 versions_temp = @versions.map do |x| v = x[0] page = x[1] i -= 1 { :id => v.id, :id7 => v.id[0..6], :num => i, :author => v.author.name.respond_to?(:force_encoding) ? v.author.name.force_encoding('UTF-8') : v.author.name, :message => v.message.respond_to?(:force_encoding) ? v.message.force_encoding('UTF-8') : v.message, :date => v.authored_date.strftime("%B %d, %Y %H:%M:%S "), :gravatar => Digest::MD5.hexdigest(v.author.email.strip.downcase), :identicon => self._identicon_code(v.author.email), :date_full => v.authored_date, :page_title => page.title, :page_url => page.escaped_url_path } end versions_temp.sort_by { |v| v[:date_full] }.reverse # versions_temp.sort { |v1, v2| } end def left_shift int, shift r = ((int & 0xFF) << (shift & 0x1F)) & 0xFFFFFFFF # 1>>31, 2**32 (r & 2147483648) == 0 ? r : r - 4294967296 end def string_to_code string # sha bytes b = [Digest::SHA1.hexdigest(string)[0, 20]].pack('H*').bytes.to_a # Thanks donpark's IdenticonUtil.java for this. # Match the following Java code # ((b[0] & 0xFF) << 24) | ((b[1] & 0xFF) << 16) | # ((b[2] & 0xFF) << 8) | (b[3] & 0xFF) return left_shift(b[0], 24) | left_shift(b[1], 16) | left_shift(b[2], 8) | b[3] & 0xFF end def _identicon_code(blob) string_to_code blob + @request.host end def partial(name) if name == :author_template self.class.partial("history_authors/none") else super end end end end end
nunoflores/gollum
lib/gollum/views/history_all.rb
Ruby
mit
1,894
require 'rails_helper' RSpec.describe Api::V1::SessionsController do before do request.env['devise.mapping'] = Devise.mappings[:user] end describe 'POST #create' do context 'when login param is missing' do it 'raises an error' do expect { post :create }.to raise_error( ActionController::ParameterMissing, 'param is missing or the value is empty: login' ) end end context 'when user does not exist' do let(:login) { {username: 'test@example.com', password: '123456'} } it 'returns HTTP Unauthorized' do post :create, login: login expect(response).to have_http_status :unauthorized end it 'returns correct message' do post :create, login: login expect(JSON.parse(response.body)).to eq( 'error' => 'Invalid username or password.' ) end end context 'when password is not valid' do let(:user) do create :user, password: 'a1234567', password_confirmation: 'a1234567' end let(:login) { {username: user.email, password: '1'} } it 'returns HTTP Unauthorized' do post :create, login: login expect(response).to have_http_status :unauthorized end it 'returns correct message' do post :create, login: login expect(JSON.parse(response.body)).to eq( 'error' => 'Invalid username or password.' ) end end context 'when credentials are valid' do let!(:user) do create :user, password: 'a1234567', password_confirmation: 'a1234567', confirmed_at: Time.zone.now end let(:login) { {username: user.email, password: 'a1234567'} } it 'returns HTTP OK' do post :create, login: login expect(response).to have_http_status :no_content end it 'signs in the user' do expect(controller).to receive(:sign_in).once.with(user) post :create, login: login end end end describe 'DELETE #destroy' do it 'signs out the user' do expect(controller).to receive(:sign_out).once delete :destroy end it 'returns HTTP OK' do delete :destroy expect(response).to have_http_status :no_content end end end
knovoselic/going-postal
web/spec/controllers/api/v1/sessions_controller_spec.rb
Ruby
mit
2,304
export default { analytics: () => { return { logEvent: () => {}, setCurrentScreen: () => {} }; } };
Vizzuality/forest-watcher
__mocks__/react-native-firebase.js
JavaScript
mit
124
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'preview', 'ca', { preview: 'Visualització prèvia' } );
Kunstmaan/BootstrapCK4-Skin
plugins/preview/lang/ca.js
JavaScript
mit
238
class CreateEvents < ActiveRecord::Migration def change create_table :events, id: false do |t| t.references :event_type, nil: false, index: true t.references :email_type, nil: false, index: true t.timestamp :created_at, nil: false end end end
aggronerd/event_responder
db/migrate/20150930200028_create_events.rb
Ruby
mit
273
/** * SIP Transactions module. */ (function(JsSIP) { var C = { // Transaction states STATUS_TRYING: 1, STATUS_PROCEEDING: 2, STATUS_CALLING: 3, STATUS_ACCEPTED: 4, STATUS_COMPLETED: 5, STATUS_TERMINATED: 6, STATUS_CONFIRMED: 7, // Transaction types NON_INVITE_CLIENT: 'nict', NON_INVITE_SERVER: 'nist', INVITE_CLIENT: 'ict', INVITE_SERVER: 'ist' }; var NonInviteClientTransaction = function(request_sender, request, transport) { var via, via_transport, events = ['stateChanged']; this.type = C.NON_INVITE_CLIENT; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; this.logger = request_sender.ua.getLogger('jssip.transaction.nict', this.id); if (request_sender.ua.configuration.hack_via_tcp) { via_transport = 'TCP'; } else if (request_sender.ua.configuration.hack_via_ws) { via_transport = 'WS'; } else { via_transport = transport.server.scheme; } via = 'SIP/2.0/' + via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); this.request_sender.ua.newTransaction(this); this.initEvents(events); }; NonInviteClientTransaction.prototype = new JsSIP.EventEmitter(); NonInviteClientTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged', this); }; NonInviteClientTransaction.prototype.send = function() { var tr = this; this.stateChanged(C.STATUS_TRYING); this.F = window.setTimeout(function() {tr.timer_F();}, JsSIP.Timers.TIMER_F); if(!this.transport.send(this.request)) { this.onTransportError(); } }; NonInviteClientTransaction.prototype.onTransportError = function() { this.logger.debug('transport error occurred, deleting non-INVITE client transaction ' + this.id); window.clearTimeout(this.F); window.clearTimeout(this.K); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onTransportError(); }; NonInviteClientTransaction.prototype.timer_F = function() { this.logger.debug('Timer F expired for non-INVITE client transaction ' + this.id); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onRequestTimeout(); }; NonInviteClientTransaction.prototype.timer_K = function() { this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; NonInviteClientTransaction.prototype.receiveResponse = function(response) { var tr = this, status_code = response.status_code; if(status_code < 200) { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_PROCEEDING); this.request_sender.receiveResponse(response); break; } } else { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); window.clearTimeout(this.F); if(status_code === 408) { this.request_sender.onRequestTimeout(); } else { this.request_sender.receiveResponse(response); } this.K = window.setTimeout(function() {tr.timer_K();}, JsSIP.Timers.TIMER_K); break; case C.STATUS_COMPLETED: break; } } }; var InviteClientTransaction = function(request_sender, request, transport) { var via, tr = this, via_transport, events = ['stateChanged']; this.type = C.INVITE_CLIENT; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; this.logger = request_sender.ua.getLogger('jssip.transaction.ict', this.id); if (request_sender.ua.configuration.hack_via_tcp) { via_transport = 'TCP'; } else if (request_sender.ua.configuration.hack_via_ws) { via_transport = 'WS'; } else { via_transport = transport.server.scheme; } via = 'SIP/2.0/' + via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); this.request_sender.ua.newTransaction(this); // TODO: Adding here the cancel() method is a hack that must be fixed. // Add the cancel property to the request. //Will be called from the request instance, not the transaction itself. this.request.cancel = function(reason) { tr.cancel_request(tr, reason); }; this.initEvents(events); }; InviteClientTransaction.prototype = new JsSIP.EventEmitter(); InviteClientTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged', this); }; InviteClientTransaction.prototype.send = function() { var tr = this; this.stateChanged(C.STATUS_CALLING); this.B = window.setTimeout(function() { tr.timer_B(); }, JsSIP.Timers.TIMER_B); if(!this.transport.send(this.request)) { this.onTransportError(); } }; InviteClientTransaction.prototype.onTransportError = function() { this.logger.debug('transport error occurred, deleting INVITE client transaction ' + this.id); window.clearTimeout(this.B); window.clearTimeout(this.D); window.clearTimeout(this.M); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); if (this.state !== C.STATUS_ACCEPTED) { this.request_sender.onTransportError(); } }; // RFC 6026 7.2 InviteClientTransaction.prototype.timer_M = function() { this.logger.debug('Timer M expired for INVITE client transaction ' + this.id); if(this.state === C.STATUS_ACCEPTED) { window.clearTimeout(this.B); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); } }; // RFC 3261 17.1.1 InviteClientTransaction.prototype.timer_B = function() { this.logger.debug('Timer B expired for INVITE client transaction ' + this.id); if(this.state === C.STATUS_CALLING) { this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onRequestTimeout(); } }; InviteClientTransaction.prototype.timer_D = function() { this.logger.debug('Timer D expired for INVITE client transaction ' + this.id); window.clearTimeout(this.B); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; InviteClientTransaction.prototype.sendACK = function(response) { var tr = this; this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n'; this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n'; if(this.request.headers.Route) { this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n'; } this.ack += 'To: ' + response.getHeader('to') + '\r\n'; this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n'; this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n'; this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0]; this.ack += ' ACK\r\n'; this.ack += 'Content-Length: 0\r\n\r\n'; this.D = window.setTimeout(function() {tr.timer_D();}, JsSIP.Timers.TIMER_D); this.transport.send(this.ack); }; InviteClientTransaction.prototype.cancel_request = function(tr, reason) { var request = tr.request; this.cancel = JsSIP.C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n'; this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n'; if(this.request.headers.Route) { this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n'; } this.cancel += 'To: ' + request.headers.To.toString() + '\r\n'; this.cancel += 'From: ' + request.headers.From.toString() + '\r\n'; this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n'; this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] + ' CANCEL\r\n'; if(reason) { this.cancel += 'Reason: ' + reason + '\r\n'; } this.cancel += 'Content-Length: 0\r\n\r\n'; // Send only if a provisional response (>100) has been received. if(this.state === C.STATUS_PROCEEDING) { this.transport.send(this.cancel); } }; InviteClientTransaction.prototype.receiveResponse = function(response) { var tr = this, status_code = response.status_code; if(status_code >= 100 && status_code <= 199) { switch(this.state) { case C.STATUS_CALLING: this.stateChanged(C.STATUS_PROCEEDING); this.request_sender.receiveResponse(response); break; case C.STATUS_PROCEEDING: this.request_sender.receiveResponse(response); break; } } else if(status_code >= 200 && status_code <= 299) { switch(this.state) { case C.STATUS_CALLING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_ACCEPTED); this.M = window.setTimeout(function() { tr.timer_M(); }, JsSIP.Timers.TIMER_M); this.request_sender.receiveResponse(response); break; case C.STATUS_ACCEPTED: this.request_sender.receiveResponse(response); break; } } else if(status_code >= 300 && status_code <= 699) { switch(this.state) { case C.STATUS_CALLING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); this.sendACK(response); this.request_sender.receiveResponse(response); break; case C.STATUS_COMPLETED: this.sendACK(response); break; } } }; var AckClientTransaction = function(request_sender, request, transport) { var via, via_transport; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; this.logger = request_sender.ua.getLogger('jssip.transaction.nict', this.id); if (request_sender.ua.configuration.hack_via_tcp) { via_transport = 'TCP'; } else if (request_sender.ua.configuration.hack_via_ws) { via_transport = 'WS'; } else { via_transport = transport.server.scheme; } via = 'SIP/2.0/' + via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); }; AckClientTransaction.prototype = new JsSIP.EventEmitter(); AckClientTransaction.prototype.send = function() { if(!this.transport.send(this.request)) { this.onTransportError(); } }; AckClientTransaction.prototype.onTransportError = function() { this.logger.debug('transport error occurred, for an ACK client transaction ' + this.id); this.request_sender.onTransportError(); }; var NonInviteServerTransaction = function(request, ua) { var events = ['stateChanged']; this.type = C.NON_INVITE_SERVER; this.id = request.via_branch; this.request = request; this.transport = request.transport; this.ua = ua; this.last_response = ''; request.server_transaction = this; this.logger = ua.getLogger('jssip.transaction.nist', this.id); this.state = C.STATUS_TRYING; ua.newTransaction(this); this.initEvents(events); }; NonInviteServerTransaction.prototype = new JsSIP.EventEmitter(); NonInviteServerTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged', this); }; NonInviteServerTransaction.prototype.timer_J = function() { this.logger.debug('Timer J expired for non-INVITE server transaction ' + this.id); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); }; NonInviteServerTransaction.prototype.onTransportError = function() { if (!this.transportError) { this.transportError = true; this.logger.debug('transport error occurred, deleting non-INVITE server transaction ' + this.id); window.clearTimeout(this.J); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { var tr = this; if(status_code === 100) { /* RFC 4320 4.1 * 'A SIP element MUST NOT * send any provisional response with a * Status-Code other than 100 to a non-INVITE request.' */ switch(this.state) { case C.STATUS_TRYING: this.stateChanged(C.STATUS_PROCEEDING); if(!this.transport.send(response)) { this.onTransportError(); } break; case C.STATUS_PROCEEDING: this.last_response = response; if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; } } else if(status_code >= 200 && status_code <= 699) { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); this.last_response = response; this.J = window.setTimeout(function() { tr.timer_J(); }, JsSIP.Timers.TIMER_J); if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; case C.STATUS_COMPLETED: break; } } }; var InviteServerTransaction = function(request, ua) { var events = ['stateChanged']; this.type = C.INVITE_SERVER; this.id = request.via_branch; this.request = request; this.transport = request.transport; this.ua = ua; this.last_response = ''; request.server_transaction = this; this.logger = ua.getLogger('jssip.transaction.ist', this.id); this.state = C.STATUS_PROCEEDING; ua.newTransaction(this); this.resendProvisionalTimer = null; request.reply(100); this.initEvents(events); }; InviteServerTransaction.prototype = new JsSIP.EventEmitter(); InviteServerTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged', this); }; InviteServerTransaction.prototype.timer_H = function() { this.logger.debug('Timer H expired for INVITE server transaction ' + this.id); if(this.state === C.STATUS_COMPLETED) { this.logger.log('transactions', 'ACK for INVITE server transaction was never received, call will be terminated'); } this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); }; InviteServerTransaction.prototype.timer_I = function() { this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); }; // RFC 6026 7.1 InviteServerTransaction.prototype.timer_L = function() { this.logger.debug('Timer L expired for INVITE server transaction ' + this.id); if(this.state === C.STATUS_ACCEPTED) { this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; InviteServerTransaction.prototype.onTransportError = function() { if (!this.transportError) { this.transportError = true; this.logger.debug('transport error occurred, deleting INVITE server transaction ' + this.id); if (this.resendProvisionalTimer !== null) { window.clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } window.clearTimeout(this.L); window.clearTimeout(this.H); window.clearTimeout(this.I); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; InviteServerTransaction.prototype.resend_provisional = function() { if(!this.transport.send(this.last_response)) { this.onTransportError(); } }; // INVITE Server Transaction RFC 3261 17.2.1 InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { var tr = this; if(status_code >= 100 && status_code <= 199) { switch(this.state) { case C.STATUS_PROCEEDING: if(!this.transport.send(response)) { this.onTransportError(); } this.last_response = response; break; } } if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) { // Trigger the resendProvisionalTimer only for the first non 100 provisional response. if(this.resendProvisionalTimer === null) { this.resendProvisionalTimer = window.setInterval(function() { tr.resend_provisional();}, JsSIP.Timers.PROVISIONAL_RESPONSE_INTERVAL); } } else if(status_code >= 200 && status_code <= 299) { switch(this.state) { case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_ACCEPTED); this.last_response = response; this.L = window.setTimeout(function() { tr.timer_L(); }, JsSIP.Timers.TIMER_L); if (this.resendProvisionalTimer !== null) { window.clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } /* falls through */ case C.STATUS_ACCEPTED: // Note that this point will be reached for proceeding tr.state also. if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; } } else if(status_code >= 300 && status_code <= 699) { switch(this.state) { case C.STATUS_PROCEEDING: if (this.resendProvisionalTimer !== null) { window.clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else { this.stateChanged(C.STATUS_COMPLETED); this.H = window.setTimeout(function() { tr.timer_H(); }, JsSIP.Timers.TIMER_H); if (onSuccess) { onSuccess(); } } break; } } }; /** * INVITE: * _true_ if retransmission * _false_ new request * * ACK: * _true_ ACK to non2xx response * _false_ ACK must be passed to TU (accepted state) * ACK to 2xx response * * CANCEL: * _true_ no matching invite transaction * _false_ matching invite transaction and no final response sent * * OTHER: * _true_ retransmission * _false_ new request */ var checkTransaction = function(ua, request) { var tr; switch(request.method) { case JsSIP.C.INVITE: tr = ua.transactions.ist[request.via_branch]; if(tr) { switch(tr.state) { case C.STATUS_PROCEEDING: tr.transport.send(tr.last_response); break; // RFC 6026 7.1 Invite retransmission //received while in C.STATUS_ACCEPTED state. Absorb it. case C.STATUS_ACCEPTED: break; } return true; } break; case JsSIP.C.ACK: tr = ua.transactions.ist[request.via_branch]; // RFC 6026 7.1 if(tr) { if(tr.state === C.STATUS_ACCEPTED) { return false; } else if(tr.state === C.STATUS_COMPLETED) { tr.state = C.STATUS_CONFIRMED; tr.I = window.setTimeout(function() {tr.timer_I();}, JsSIP.Timers.TIMER_I); return true; } } // ACK to 2XX Response. else { return false; } break; case JsSIP.C.CANCEL: tr = ua.transactions.ist[request.via_branch]; if(tr) { request.reply_sl(200); if(tr.state === C.STATUS_PROCEEDING) { return false; } else { return true; } } else { request.reply_sl(481); return true; } break; default: // Non-INVITE Server Transaction RFC 3261 17.2.2 tr = ua.transactions.nist[request.via_branch]; if(tr) { switch(tr.state) { case C.STATUS_TRYING: break; case C.STATUS_PROCEEDING: case C.STATUS_COMPLETED: tr.transport.send(tr.last_response); break; } return true; } break; } }; JsSIP.Transactions = { C: C, checkTransaction: checkTransaction, NonInviteClientTransaction: NonInviteClientTransaction, InviteClientTransaction: InviteClientTransaction, AckClientTransaction: AckClientTransaction, NonInviteServerTransaction: NonInviteServerTransaction, InviteServerTransaction: InviteServerTransaction }; }(JsSIP));
CodeYellowBV/JsSIP
src/Transactions.js
JavaScript
mit
20,494
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Data; using System.Collections; using System.Web.UI.WebControls; using ServiceReference1; public partial class Meetings { public int appointmentNumber { get; set; } public DateTime startDate { get; set; } } public partial class Appointments : System.Web.UI.Page { AppointmentClient proxy; DataTable dt; protected void Page_Load(object sender, EventArgs e) { proxy = new AppointmentClient(); string un = Session["username"].ToString(); dt = proxy.getAppointmentsHistorybyPatient(un); CustomizeColumns(); GetFutureAppointments(); if (!IsPostBack) DayPilotCalendar1.DataBind(); GridView1.DataSource = dt; GridView1.DataBind(); } /// <summary> /// To expose appointment information on the page calender /// </summary> private void GetFutureAppointments() { DayPilotCalendar1.DataSource = dt; DayPilotCalendar1.DataStartField = "Start Date"; DayPilotCalendar1.DataEndField = "End Date"; DayPilotCalendar1.DataTextField = "Doctor"; DayPilotCalendar1.DataValueField = "Appointment Number"; DayPilotCalendar1.StartDate = DateTime.Now; DayPilotCalendar1.Days = 7; } /// <summary> /// To rename the orginal column names of the database to more /// friendly names to be displayed on the page for the client /// </summary> private void CustomizeColumns() { dt.Columns["appointment_id"].ColumnName = "Appointment Number"; dt.Columns["start_date"].ColumnName = "Start Date"; dt.Columns["end_date"].ColumnName = "End Date"; dt.Columns["last_name"].ColumnName = "Doctor"; } }
neunhuyeu/gds-mis
Website/PatientClient/Appointments.aspx.cs
C#
mit
1,836
# #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <gabriel@nacaolivre.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import requests from unittest import skip from sure import expect from httpretty import HTTPretty @skip def test_http_passthrough(): url = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) @skip def test_https_passthrough(): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get('https://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content)
andresriancho/HTTPretty
tests/functional/test_passthrough.py
Python
mit
2,551
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.10.0 (2021-10-11) */ (function () { 'use strict'; var global$3 = tinymce.util.Tools.resolve('tinymce.PluginManager'); var eq = function (t) { return function (a) { return t === a; }; }; var isNull = eq(null); var noop = function () { }; var constant = function (value) { return function () { return value; }; }; var identity = function (x) { return x; }; var never = constant(false); var always = constant(true); var none = function () { return NONE; }; var NONE = function () { var call = function (thunk) { return thunk(); }; var id = identity; var me = { fold: function (n, _s) { return n(); }, isSome: never, isNone: always, getOr: id, getOrThunk: call, getOrDie: function (msg) { throw new Error(msg || 'error: getOrDie called on none.'); }, getOrNull: constant(null), getOrUndefined: constant(undefined), or: id, orThunk: call, map: none, each: noop, bind: none, exists: never, forall: always, filter: function () { return none(); }, toArray: function () { return []; }, toString: constant('none()') }; return me; }(); var some = function (a) { var constant_a = constant(a); var self = function () { return me; }; var bind = function (f) { return f(a); }; var me = { fold: function (n, s) { return s(a); }, isSome: always, isNone: never, getOr: constant_a, getOrThunk: constant_a, getOrDie: constant_a, getOrNull: constant_a, getOrUndefined: constant_a, or: self, orThunk: self, map: function (f) { return some(f(a)); }, each: function (f) { f(a); }, bind: bind, exists: bind, forall: bind, filter: function (f) { return f(a) ? me : NONE; }, toArray: function () { return [a]; }, toString: function () { return 'some(' + a + ')'; } }; return me; }; var from = function (value) { return value === null || value === undefined ? NONE : some(value); }; var Optional = { some: some, none: none, from: from }; var exists = function (xs, pred) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i)) { return true; } } return false; }; var map$1 = function (xs, f) { var len = xs.length; var r = new Array(len); for (var i = 0; i < len; i++) { var x = xs[i]; r[i] = f(x, i); } return r; }; var each$1 = function (xs, f) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; f(x, i); } }; var Cell = function (initial) { var value = initial; var get = function () { return value; }; var set = function (v) { value = v; }; return { get: get, set: set }; }; var last = function (fn, rate) { var timer = null; var cancel = function () { if (!isNull(timer)) { clearTimeout(timer); timer = null; } }; var throttle = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } cancel(); timer = setTimeout(function () { timer = null; fn.apply(null, args); }, rate); }; return { cancel: cancel, throttle: throttle }; }; var insertEmoticon = function (editor, ch) { editor.insertContent(ch); }; var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var keys = Object.keys; var hasOwnProperty = Object.hasOwnProperty; var each = function (obj, f) { var props = keys(obj); for (var k = 0, len = props.length; k < len; k++) { var i = props[k]; var x = obj[i]; f(x, i); } }; var map = function (obj, f) { return tupleMap(obj, function (x, i) { return { k: i, v: f(x, i) }; }); }; var tupleMap = function (obj, f) { var r = {}; each(obj, function (x, i) { var tuple = f(x, i); r[tuple.k] = tuple.v; }); return r; }; var has = function (obj, key) { return hasOwnProperty.call(obj, key); }; var shallow = function (old, nu) { return nu; }; var baseMerge = function (merger) { return function () { var objects = []; for (var _i = 0; _i < arguments.length; _i++) { objects[_i] = arguments[_i]; } if (objects.length === 0) { throw new Error('Can\'t merge zero objects'); } var ret = {}; for (var j = 0; j < objects.length; j++) { var curObject = objects[j]; for (var key in curObject) { if (has(curObject, key)) { ret[key] = merger(ret[key], curObject[key]); } } } return ret; }; }; var merge = baseMerge(shallow); var singleton = function (doRevoke) { var subject = Cell(Optional.none()); var revoke = function () { return subject.get().each(doRevoke); }; var clear = function () { revoke(); subject.set(Optional.none()); }; var isSet = function () { return subject.get().isSome(); }; var get = function () { return subject.get(); }; var set = function (s) { revoke(); subject.set(Optional.some(s)); }; return { clear: clear, isSet: isSet, get: get, set: set }; }; var value = function () { var subject = singleton(noop); var on = function (f) { return subject.get().each(f); }; return __assign(__assign({}, subject), { on: on }); }; var checkRange = function (str, substr, start) { return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr; }; var contains = function (str, substr) { return str.indexOf(substr) !== -1; }; var startsWith = function (str, prefix) { return checkRange(str, prefix, 0); }; var global$2 = tinymce.util.Tools.resolve('tinymce.Resource'); var global$1 = tinymce.util.Tools.resolve('tinymce.util.Delay'); var global = tinymce.util.Tools.resolve('tinymce.util.Promise'); var DEFAULT_ID = 'tinymce.plugins.emoticons'; var getEmoticonDatabase = function (editor) { return editor.getParam('emoticons_database', 'emojis', 'string'); }; var getEmoticonDatabaseUrl = function (editor, pluginUrl) { var database = getEmoticonDatabase(editor); return editor.getParam('emoticons_database_url', pluginUrl + '/js/' + database + editor.suffix + '.js', 'string'); }; var getEmoticonDatabaseId = function (editor) { return editor.getParam('emoticons_database_id', DEFAULT_ID, 'string'); }; var getAppendedEmoticons = function (editor) { return editor.getParam('emoticons_append', {}, 'object'); }; var getEmotionsImageUrl = function (editor) { return editor.getParam('emoticons_images_url', 'https://twemoji.maxcdn.com/v/13.0.1/72x72/', 'string'); }; var ALL_CATEGORY = 'All'; var categoryNameMap = { symbols: 'Symbols', people: 'People', animals_and_nature: 'Animals and Nature', food_and_drink: 'Food and Drink', activity: 'Activity', travel_and_places: 'Travel and Places', objects: 'Objects', flags: 'Flags', user: 'User Defined' }; var translateCategory = function (categories, name) { return has(categories, name) ? categories[name] : name; }; var getUserDefinedEmoticons = function (editor) { var userDefinedEmoticons = getAppendedEmoticons(editor); return map(userDefinedEmoticons, function (value) { return __assign({ keywords: [], category: 'user' }, value); }); }; var initDatabase = function (editor, databaseUrl, databaseId) { var categories = value(); var all = value(); var emojiImagesUrl = getEmotionsImageUrl(editor); var getEmoji = function (lib) { if (startsWith(lib.char, '<img')) { return lib.char.replace(/src="([^"]+)"/, function (match, url) { return 'src="' + emojiImagesUrl + url + '"'; }); } else { return lib.char; } }; var processEmojis = function (emojis) { var cats = {}; var everything = []; each(emojis, function (lib, title) { var entry = { title: title, keywords: lib.keywords, char: getEmoji(lib), category: translateCategory(categoryNameMap, lib.category) }; var current = cats[entry.category] !== undefined ? cats[entry.category] : []; cats[entry.category] = current.concat([entry]); everything.push(entry); }); categories.set(cats); all.set(everything); }; editor.on('init', function () { global$2.load(databaseId, databaseUrl).then(function (emojis) { var userEmojis = getUserDefinedEmoticons(editor); processEmojis(merge(emojis, userEmojis)); }, function (err) { console.log('Failed to load emoticons: ' + err); categories.set({}); all.set([]); }); }); var listCategory = function (category) { if (category === ALL_CATEGORY) { return listAll(); } return categories.get().bind(function (cats) { return Optional.from(cats[category]); }).getOr([]); }; var listAll = function () { return all.get().getOr([]); }; var listCategories = function () { return [ALL_CATEGORY].concat(keys(categories.get().getOr({}))); }; var waitForLoad = function () { if (hasLoaded()) { return global.resolve(true); } else { return new global(function (resolve, reject) { var numRetries = 15; var interval = global$1.setInterval(function () { if (hasLoaded()) { global$1.clearInterval(interval); resolve(true); } else { numRetries--; if (numRetries < 0) { console.log('Could not load emojis from url: ' + databaseUrl); global$1.clearInterval(interval); reject(false); } } }, 100); }); } }; var hasLoaded = function () { return categories.isSet() && all.isSet(); }; return { listCategories: listCategories, hasLoaded: hasLoaded, waitForLoad: waitForLoad, listAll: listAll, listCategory: listCategory }; }; var emojiMatches = function (emoji, lowerCasePattern) { return contains(emoji.title.toLowerCase(), lowerCasePattern) || exists(emoji.keywords, function (k) { return contains(k.toLowerCase(), lowerCasePattern); }); }; var emojisFrom = function (list, pattern, maxResults) { var matches = []; var lowerCasePattern = pattern.toLowerCase(); var reachedLimit = maxResults.fold(function () { return never; }, function (max) { return function (size) { return size >= max; }; }); for (var i = 0; i < list.length; i++) { if (pattern.length === 0 || emojiMatches(list[i], lowerCasePattern)) { matches.push({ value: list[i].char, text: list[i].title, icon: list[i].char }); if (reachedLimit(matches.length)) { break; } } } return matches; }; var patternName = 'pattern'; var open = function (editor, database) { var initialState = { pattern: '', results: emojisFrom(database.listAll(), '', Optional.some(300)) }; var currentTab = Cell(ALL_CATEGORY); var scan = function (dialogApi) { var dialogData = dialogApi.getData(); var category = currentTab.get(); var candidates = database.listCategory(category); var results = emojisFrom(candidates, dialogData[patternName], category === ALL_CATEGORY ? Optional.some(300) : Optional.none()); dialogApi.setData({ results: results }); }; var updateFilter = last(function (dialogApi) { scan(dialogApi); }, 200); var searchField = { label: 'Search', type: 'input', name: patternName }; var resultsField = { type: 'collection', name: 'results' }; var getInitialState = function () { var body = { type: 'tabpanel', tabs: map$1(database.listCategories(), function (cat) { return { title: cat, name: cat, items: [ searchField, resultsField ] }; }) }; return { title: 'Emoticons', size: 'normal', body: body, initialData: initialState, onTabChange: function (dialogApi, details) { currentTab.set(details.newTabName); updateFilter.throttle(dialogApi); }, onChange: updateFilter.throttle, onAction: function (dialogApi, actionData) { if (actionData.name === 'results') { insertEmoticon(editor, actionData.value); dialogApi.close(); } }, buttons: [{ type: 'cancel', text: 'Close', primary: true }] }; }; var dialogApi = editor.windowManager.open(getInitialState()); dialogApi.focus(patternName); if (!database.hasLoaded()) { dialogApi.block('Loading emoticons...'); database.waitForLoad().then(function () { dialogApi.redial(getInitialState()); updateFilter.throttle(dialogApi); dialogApi.focus(patternName); dialogApi.unblock(); }).catch(function (_err) { dialogApi.redial({ title: 'Emoticons', body: { type: 'panel', items: [{ type: 'alertbanner', level: 'error', icon: 'warning', text: '<p>Could not load emoticons</p>' }] }, buttons: [{ type: 'cancel', text: 'Close', primary: true }], initialData: { pattern: '', results: [] } }); dialogApi.focus(patternName); dialogApi.unblock(); }); } }; var register$1 = function (editor, database) { editor.addCommand('mceEmoticons', function () { return open(editor, database); }); }; var setup = function (editor) { editor.on('PreInit', function () { editor.parser.addAttributeFilter('data-emoticon', function (nodes) { each$1(nodes, function (node) { node.attr('data-mce-resize', 'false'); node.attr('data-mce-placeholder', '1'); }); }); }); }; var init = function (editor, database) { editor.ui.registry.addAutocompleter('emoticons', { ch: ':', columns: 'auto', minChars: 2, fetch: function (pattern, maxResults) { return database.waitForLoad().then(function () { var candidates = database.listAll(); return emojisFrom(candidates, pattern, Optional.some(maxResults)); }); }, onAction: function (autocompleteApi, rng, value) { editor.selection.setRng(rng); editor.insertContent(value); autocompleteApi.hide(); } }); }; var register = function (editor) { var onAction = function () { return editor.execCommand('mceEmoticons'); }; editor.ui.registry.addButton('emoticons', { tooltip: 'Emoticons', icon: 'emoji', onAction: onAction }); editor.ui.registry.addMenuItem('emoticons', { text: 'Emoticons...', icon: 'emoji', onAction: onAction }); }; function Plugin () { global$3.add('emoticons', function (editor, pluginUrl) { var databaseUrl = getEmoticonDatabaseUrl(editor, pluginUrl); var databaseId = getEmoticonDatabaseId(editor); var database = initDatabase(editor, databaseUrl, databaseId); register$1(editor, database); register(editor); init(editor, database); setup(editor); }); } Plugin(); }());
cdnjs/cdnjs
ajax/libs/tinymce/5.10.0/plugins/emoticons/plugin.js
JavaScript
mit
18,139
/* * ajaxify.js * Ajaxify - The Ajax Plugin * https://4nf.org/ * * Copyright Arvind Gupta; MIT Licensed */ /* INTERFACE: See also https://4nf.org/interface/ Simplest plugin call: let ajaxify = new Ajaxify({options}); Ajaxifies the whole site, dynamically replacing the elements specified in "elements" across pages */ // The main plugin - Ajaxify // Is passed the global options // Checks for necessary pre-conditions - otherwise gracefully degrades // Initialises sub-plugins // Calls Pronto class Ajaxify { constructor(options) { String.prototype.iO = function(s) { return this.toString().indexOf(s) + 1; }; //Intuitively better understandable shorthand for String.indexOf() - String.iO() let $ = this; //Options default values $.s = { // basic config parameters elements: "body", //selector for element IDs that are going to be swapped (e.g. "#el1, #el2, #el3") selector : "a:not(.no-ajaxy)", //selector for links to trigger swapping - not elements to be swapped - i.e. a selection of links forms : "form:not(.no-ajaxy)", // selector for ajaxifying forms - set to "false" to disable canonical : false, // Fetch current URL from "canonical" link if given, updating the History API. In case of a re-direct... refresh : false, // Refresh the page even if link clicked is current page // visual effects settings requestDelay : 0, //in msec - Delay of Pronto request scrolltop : "s", // Smart scroll, true = always scroll to top of page, false = no scroll bodyClasses : false, // Copy body classes from target page, set to "true" to enable // script and style handling settings, prefetch deltas : true, // true = deltas loaded, false = all scripts loaded asyncdef : true, // default async value for dynamically inserted external scripts, false = synchronous / true = asynchronous alwayshints : false, // strings, - separated by ", " - if matched in any external script URL - these are always loaded on every page load inline : true, // true = all inline scripts loaded, false = only specific inline scripts are loaded inlinesync : true, // synchronise inline scripts loading by adding a central tiny delay to all of them inlinehints : false, // strings - separated by ", " - if matched in any inline scripts - only these are executed - set "inline" to false beforehand inlineskip : "adsbygoogle", // strings - separated by ", " - if matched in any inline scripts - these are NOT are executed - set "inline" to true beforehand inlineappend : true, // append scripts to the main content element, instead of "eval"-ing them style : true, // true = all style tags in the head loaded, false = style tags on target page ignored prefetchoff : false, // Plugin pre-fetches pages on hoverIntent - true = set off completely // strings - separated by ", " - hints to select out // debugging & advanced settings verbosity : 0, //Debugging level to console: default off. Can be set to 10 and higher (in case of logging enabled) memoryoff : false, // strings - separated by ", " - if matched in any URLs - only these are NOT executed - set to "true" to disable memory completely cb : 0, // callback handler on completion of each Ajax request - default 0 pluginon : true, // Plugin set "on" or "off" (==false) manually passCount: false // Show number of pass for debugging }; $.pass = 0; $.currentURL = ""; $.parse = (s, pl) => (pl = document.createElement('div'), pl.insertAdjacentHTML('afterbegin', s), pl.firstElementChild); // HTML parser $.trigger = (t, e) => { let ev = document.createEvent('HTMLEvents'); ev.initEvent("pronto." + t, true, false); ev.data = e ? e : $.Rq("e"); window.dispatchEvent(ev); } $.internal = (url) => { if (!url) return false; if (typeof(url) === "object") url = url.href; if (url==="") return true; return url.substring(0,rootUrl.length) === rootUrl || !url.iO(":"); } //Module global variables let rootUrl = location.origin, api = window.history && window.history.pushState && window.history.replaceState, //Regexes for escaping fetched HTML of a whole page - best of Baluptons Ajaxify //Makes it possible to pre-fetch an entire page docType = /<\!DOCTYPE[^>]*>/i, tagso = /<(html|head|link)([\s\>])/gi, tagsod = /<(body)([\s\>])/gi, tagsc = /<\/(html|head|body|link)\>/gi, //Helper strings div12 = '<div class="ajy-$1"$2', divid12 = '<div id="ajy-$1"$2', linki = '<link rel="stylesheet" type="text/css" href="*" />', linkr = 'link[href*="!"]', scrr = 'script[src*="!"]', inlineclass = "ajy-inline"; //Global helpers let doc=document, bdy, qa=(s,o=doc)=>o.querySelectorAll(s), qs=(s,o=doc)=>o.querySelector(s); function _copyAttributes(el, $S, flush) { //copy all attributes of element generically if (flush) [...el.attributes].forEach(e => el.removeAttribute(e.name)); //delete all old attributes [...$S.attributes].forEach(e => el.setAttribute(e.nodeName, e.nodeValue)); //low-level insertion } function _on(eventName, elementSelector, handler, el = document) { //e.currentTarget is document when the handler is called el.addEventListener(eventName, function(e) { // loop parent nodes from the target to the delegation node for (var target = e.target; target && target != this; target = target.parentNode) { if (target.matches(elementSelector)) { handler(target, e); break; } } }, !!eventName.iO('mo')); } function Hints(hints) { if (!(this instanceof Hints)) return new Hints(hints); //automatically create an instance this.myHints = (typeof hints === 'string' && hints.length > 0) ? hints.split(", ") : false; //hints are passed as a comma separated string } Hints.prototype.find = function (t) {return (!t || !this.myHints) ? false : this.myHints.some(h => t.iO(h))}; //iterate through hints within passed text (t) function lg(m){ $.s.verbosity && console && console.log(m); } // The stateful Cache class // Usage - parameter "o" values: // none - returns currently cached page // <URL> - returns page with specified URL // <object> - saves the page in cache // f - flushes the cache class Cache { constructor() { let d = false; this.a = function (o) { if (!o) return d; if (typeof o === "string") { //URL or "f" passed if(o === "f") { //"f" passed -> flush $.pages("f"); //delegate flush to $.pages lg("Cache flushed"); } else d = $.pages($.memory(o)); //URL passed -> look up page in memory return d; //return cached page } if (typeof o === "object") { d = o; return d; } }; }} // The stateful Memory class // Usage: $.memory(<URL>) - returns the same URL if not turned off internally class Memory { constructor(options) { this.a = function (h) { if (!h || $.s.memoryoff === true) return false; if ($.s.memoryoff === false) return h; return Hints($.s.memoryoff).find(h) ? false : h; }; }} // The stateful Pages class // Usage - parameter "h" values: // <URL> - returns page with specified URL from internal array // <object> - saves the passed page in internal array // false - returns false class Pages { constructor() { let d = [], i = -1; this.a = function (h) { if (typeof h === "string") { if(h === "f") d = []; else if((i=_iPage(h)) !== -1) return d[i][1]; } if (typeof h === "object") { if((i=_iPage(h)) === -1) d.push(h); else d[i] = h; } if (typeof h === "boolean") return false; }; let _iPage = h => d.findIndex(e => e[0] == h) }} // The GetPage class // First parameter (o) is a switch: // empty - returns cache // <URL> - loads HTML via Ajax, second parameter "p" must be callback // + - pre-fetches page, second parameter "p" must be URL, third parameter "p2" must be callback // - - loads page into DOM and handle scripts, second parameter "p" must hold selection to load // x - returns response // otherwise - returns selection of current page to client class GetPage { constructor() { let rsp = 0, cb = 0, plus = 0, rt = "", ct = 0, rc = 0, ac = 0; this.a = function (o, p, p2) { if (!o) return $.cache(); if (o.iO("/")) { cb = p; if(plus == o) return; return _lPage(o); } if (o === "+") { plus = p; cb = p2; return _lPage(p, true); } if (o === "a") { if (rc > 0) {_cl(); ac.abort();} return; } if (o === "s") return ((rc) ? 1 : 0) + rt; if (o === "-") return _lSel(p); if (o === "x") return rsp; if (!$.cache()) return; if (o === "body") return qs("#ajy-" + o, $.cache()); if (o === "script") return qa(o, $.cache()); return qs((o === "title") ? o : ".ajy-" + o, $.cache()); }; let _lSel = $t => ( $.pass++, _lEls($t), qa("body > script").forEach(e => (e.classList.contains(inlineclass)) ? e.parentNode.removeChild(e) : false), $.scripts(true), $.scripts("s"), $.scripts("c") ), _lPage = (h, pre) => { if (h.iO("#")) h = h.split("#")[0]; if ($.Rq("is") || !$.cache(h)) return _lAjax(h, pre); plus = 0; if (cb) return cb(); }, _ld = ($t, $h) => { if(!$h) { lg("Inserting placeholder for ID: " + $t.getAttribute("id")); var tagN = $t.tagName.toLowerCase(); $t.parentNode.replaceChild($.parse("<" + tagN + " id='" + $t.getAttribute("id") + "'></" + tagN + ">"), $t); return; } var $c = $h.cloneNode(true); // clone element node (true = deep clone) qa("script", $c).forEach(e => e.parentNode.removeChild(e)); _copyAttributes($t, $c, true); $t.innerHTML = $c.innerHTML; }, _lEls = $t => $.cache() && !_isBody($t) && $t.forEach(function($el) { _ld($el, qs("#" + $el.getAttribute("id"), $.cache())); }), _isBody = $t => $t[0].tagName.toLowerCase() == "body" && (_ld(bdy, qs("#ajy-body", $.cache())), 1), _lAjax = (hin, pre) => { var ispost = $.Rq("is"); if (pre) rt="p"; else rt="c"; ac = new AbortController(); // set abort controller rc++; // set active request counter fetch(hin, { method: ((ispost) ? "POST" : "GET"), cache: "default", mode: "same-origin", headers: {"X-Requested-With": "XMLHttpRequest"}, body: (ispost) ? $.Rq("d") : null, signal: ac.signal }).then(r => { if (!r.ok || !_isHtml(r)) { if (!pre) {location.href = hin; _cl(); $.pronto(0, $.currentURL);} return; } rsp = r; // store response return r.text(); }).then(r => { _cl(1); // clear only plus variable if (!r) return; // ensure data rsp.responseText = r; // store response text return _cache(hin, r); }).catch(err => { if(err.name === "AbortError") return; try { $.trigger("error", err); lg("Response text : " + err.message); return _cache(hin, err.message, err); } catch (e) {} }).finally(() => rc--); // reset active request counter }, _cl = c => (plus = 0, (!c) ? cb = 0 : 0), // clear plus AND/OR callback _cache = (href, h, err) => $.cache($.parse(_parseHTML(h))) && ($.pages([href, $.cache()]), 1) && cb && cb(err), _isHtml = x => (ct = x.headers.get("content-type")) && (ct.iO("html") || ct.iO("form-")), _parseHTML = h => document.createElement("html").innerHTML = _replD(h).trim(), _replD = h => String(h).replace(docType, "").replace(tagso, div12).replace(tagsod, divid12).replace(tagsc, "</div>") }} // The stateful Scripts plugin // First parameter "o" is switch: // i - initailise options // c - fetch canonical URL // <object> - handle one inline script // otherwise - delta loading class Scripts { constructor() { let $s = false, txt = 0; this.a = function (o) { if (o === "i") { if(!$s) $s = {}; return true; } if (o === "s") return _allstyle($s.y); if (o === "1") { $.detScripts($s); return _addScripts($s); } if (o === "c") return $.s.canonical && $s.can ? $s.can.getAttribute("href") : false; if (o === "d") return $.detScripts($s); if (o && typeof o == "object") return _onetxt(o); if ($.scripts("d")) return; _addScripts($s); }; let _allstyle = $s => !$.s.style || !$s || ( qa("style", qs("head")).forEach(e => e.parentNode.removeChild(e)), $s.forEach(el => _addstyle(el.textContent)) ), _onetxt = $s => (!(txt = $s.textContent).iO(").ajaxify(") && (!txt.iO("new Ajaxify(")) && (($.s.inline && !Hints($.s.inlineskip).find(txt)) || $s.classList.contains("ajaxy") || Hints($.s.inlinehints).find(txt)) ) && _addtxt($s), _addtxt = $s => { if(!txt || !txt.length) return; if($.s.inlineappend || ($s.getAttribute("type") && !$s.getAttribute("type").iO("text/javascript"))) try { return _apptxt($s); } catch (e) { } try { eval(txt); } catch (e1) { lg("Error in inline script : " + txt + "\nError code : " + e1); } }, _apptxt = $s => { let sc = document.createElement("script"); _copyAttributes(sc, $s); sc.classList.add(inlineclass); try {sc.appendChild(document.createTextNode($s.textContent))} catch(e) {sc.text = $s.textContent}; return qs("body").appendChild(sc); }, _addstyle = t => qs("head").appendChild($.parse('<style>' + t + '</style>')), _addScripts = $s => ( $.addAll($s.c, "href"), $.s.inlinesync ? setTimeout(() => $.addAll($s.j, "src")) : $.addAll($s.j, "src")) }} // The DetScripts plugin - stands for "detach scripts" // Works on "$s" <object> that is passed in and fills it // Fetches all stylesheets in the head // Fetches the canonical URL // Fetches all external scripts on the page // Fetches all inline scripts on the page class DetScripts { constructor() { let head = 0, lk = 0, j = 0; this.a = function ($s) { head = $.pass ? $.fn("head") : qs("head"); //If "pass" is 0 -> fetch head from DOM, otherwise from target page if (!head) return true; lk = qa($.pass ? ".ajy-link" : "link", head); //If "pass" is 0 -> fetch links from DOM, otherwise from target page j = $.pass ? $.fn("script") : qa("script"); //If "pass" is 0 -> fetch JSs from DOM, otherwise from target page $s.c = _rel(lk, "stylesheet"); //Extract stylesheets $s.y = qa("style", head); //Extract style tags $s.can = _rel(lk, "canonical"); //Extract canonical tag $s.j = j; //Assign JSs to internal selection }; let _rel = (lk, v) => Array.prototype.filter.call(lk, e => e.getAttribute("rel").iO(v)); }} // The AddAll plugin // Works on a new selection of scripts to apply delta-loading to it // pk parameter: // href - operate on stylesheets in the new selection // src - operate on JS scripts class AddAll { constructor() { let $scriptsO = [], $sCssO = [], $sO = [], PK = 0, url = 0; this.a = function ($this, pk) { if(!$this.length) return; //ensure input if($.s.deltas === "n") return true; //Delta-loading completely disabled PK = pk; //Copy "primary key" into internal variable if(!$.s.deltas) return _allScripts($this); //process all scripts //deltas presumed to be "true" -> proceed with normal delta-loading $scriptsO = PK == "href" ? $sCssO : $sO; //Copy old. Stylesheets or JS if(!$.pass) _newArray($this); //Fill new array on initial load, nothing more else $this.forEach(function(s) { //Iterate through selection var $t = s; url = $t.getAttribute(PK); if(_classAlways($t)) { //Class always handling _removeScript(); //remove from DOM _iScript($t); //insert back single external script in the head return; } if(url) { //URL? if(!$scriptsO.some(e => e == url)) { // Test, whether new $scriptsO.push(url); //If yes: Push to old array _iScript($t); } //Otherwise nothing to do return; } if(PK != "href" && !$t.classList.contains("no-ajaxy")) $.scripts($t); //Inline JS script? -> inject into DOM }); }; let _allScripts = $t => $t.forEach(e => _iScript(e)), _newArray = $t => $t.forEach(e => (url = e.getAttribute(PK)) ? $scriptsO.push(url) : 0), _classAlways = $t => $t.getAttribute("data-class") == "always" || Hints($.s.alwayshints).find(url), _iScript = $S => { url = $S.getAttribute(PK); if(PK == "href") return qs("head").appendChild($.parse(linki.replace("*", url))); if(!url) return $.scripts($S); var sc = document.createElement("script"); sc.async = $.s.asyncdef; _copyAttributes(sc, $S); qs("head").appendChild(sc); }, _removeScript = () => qa((PK == "href" ? linkr : scrr).replace("!", url)).forEach(e => e.parentNode.removeChild(e)) }} // The Rq plugin - stands for request // Stores all kinds of and manages data concerning the pending request // Simplifies the Pronto plugin by managing request data separately, instead of passing it around... // Second parameter (p) : data // First parameter (o) values: // = - check whether internally stored "href" ("h") variable is the same as the global currentURL // ! - update last request ("l") variable with passed href // ? - Edin's intelligent plausibility check - can spawn an external fetch abort // v - validate value passed in "p", which is expected to be a click event value - also performs "i" afterwards // i - initialise request defaults and return "c" (currentTarget) // h - access internal href hard // e - set / get internal "e" (event) // p - set / get internal "p" (push flag) // is - set / get internal "ispost" (flag whether request is a POST) // d - set / get internal "d" (data for central $.ajax()) // C - set / get internal "can" ("href" of canonical URL) // c - check whether simple canonical URL is given and return, otherwise return value passed in "p" class RQ { constructor() { let ispost = 0, data = 0, push = 0, can = 0, e = 0, c = 0, h = 0, l = false; this.a = function (o, p, t) { if(o === "=") { if(p) return h === $.currentURL //check whether internally stored "href" ("h") variable is the same as the global currentURL || h === l; //or href of last request ("l") return h === $.currentURL; //for click requests } if(o === "!") return l = h; //store href in "l" (last request) if(o === "?") { //Edin previously called this "isOK" - powerful intelligent plausibility check let xs=$.fn("s"); if (!xs.iO("0") && !p) $.fn("a"); //if fetch is not idle and new request is standard one, do ac.abort() to set it free if (xs==="1c" && p) return false; //if fetch is processing standard request and new request is prefetch, cancel prefetch until fetch is finished if (xs==="1p" && p) $.s.memoryoff ? $.fn("a") : 1; //if fetch is processing prefetch request and new request is prefetch do nothing (see [options] comment below) //([semaphore options for requests] $.fn("a") -> abort previous, proceed with new | return false -> leave previous, stop new | return true -> proceed) return true; } if(o === "v") { //validate value passed in "p", which is expected to be a click event value - also performs "i" afterwards if(!p) return false; //ensure data _setE(p, t); //Set event and href in one go if(!$.internal(h)) return false; //if not internal -> report failure o = "i"; //continue with "i" } if(o === "i") { //initialise request defaults and return "c" (currentTarget) ispost = false; //GET assumed data = null; //reset data push = true; //assume we want to push URL to the History API can = false; //reset can (canonical URL) return h; //return "h" (href) } if(o === "h") { // Access href hard if(p) { if (typeof p === "string") e = 0; // Reset e -> default handler h = (p.href) ? p.href : p; // Poke in href hard } return h; //href } if(o === "e") { //set / get internal "e" (event) if(p) _setE(p, t); //Set event and href in one go return e ? e : h; // Return "e" or if not given "h" } if(o === "p") { //set / get internal "p" (push flag) if(p !== undefined) push = p; return push; } if(o === "is") { //set / get internal "ispost" (flag whether request is a POST) if(p !== undefined) ispost = p; return ispost; } if(o === "d") { //set / get internal "d" (data for central $.ajax()) if(p) data = p; return data; } if(o === "C") { //set internal "can" ("href" of canonical URL) if(p !== undefined) can = p; return can; } if(o === "c") return can && can !== p && !p.iO("#") && !p.iO("?") ? can : p; //get internal "can" ("href" of canonical URL) }; let _setE = (p, t) => h = typeof (e = p) !== "string" ? (e.currentTarget && e.currentTarget.href) || (t && t.href) || e.currentTarget.action || e.originalEvent.state.url : e }} // The Frms plugin - stands for forms // Ajaxify all forms in the specified divs // Switch (o) values: // d - set divs variable // a - Ajaxify all forms in divs class Frms { constructor() { let fm = 0, divs = 0; this.a = function (o, p) { if (!$.s.forms || !o) return; //ensure data if(o === "d") divs = p; //set divs variable if(o === "a") divs.forEach(div => { //iterate through divs Array.prototype.filter.call(qa($.s.forms, div), function(e) { //filter forms let c = e.getAttribute("action"); return($.internal(c && c.length > 0 ? c : $.currentURL)); //ensure "action" }).forEach(frm => { //iterate through forms frm.addEventListener("submit", q => { //create event listener fm = q.target; // fetch target p = _k(); //Serialise data var g = "get", //assume GET m = fm.getAttribute("method"); //fetch method attribute if (m.length > 0 && m.toLowerCase() == "post") g = "post"; //Override with "post" var h, a = fm.getAttribute("action"); //fetch action attribute if (a && a.length > 0) h = a; //found -> store else h = $.currentURL; //not found -> select current URL $.Rq("v", q); //validate request if (g == "get") h = _b(h, p); //GET -> copy URL parameters else { $.Rq("is", true); //set is POST in request data $.Rq("d", p); //save data in request data } $.trigger("submit", h); //raise pronto.submit event $.pronto(0, { href: h }); //programmatically change page q.preventDefault(); //prevent default form action return(false); //success -> disable default behaviour }) }); }); }; let _k = () => { let o = new FormData(fm), n = qs("input[name][type=submit]", fm); if (n) o.append(n.getAttribute("name"), n.value); return o; }, _b = (m, n) => { let s = ""; if (m.iO("?")) m = m.substring(0, m.iO("?")); for (var [k, v] of n.entries()) s += `${k}=${encodeURIComponent(v)}&`; return `${m}?${s.slice(0,-1)}`; } }} // The stateful Offsets plugin // Usage: // 1) $.offsets(<URL>) - returns offset of specified URL from internal array // 2) $.offsets() - saves the current URL + offset in internal array class Offsets { constructor() { let d = [], i = -1; this.a = function (h) { if (typeof h === "string") { //Lookup page offset h = h.iO("?") ? h.split("?")[0] : h; //Handle root URL only from dynamic pages i = _iOffset(h); //Fetch offset if(i === -1) return 0; // scrollTop if not found return d[i][1]; //Return offset that was found } //Add page offset var u = $.currentURL, us1 = u.iO("?") ? u.split("?")[0] : u, us = us1.iO("#") ? us1.split("#")[0] : us1, os = [us, (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop]; i = _iOffset(us); //get page index if(i === -1) d.push(os); //doesn't exist -> push to array else d[i] = os; //exists -> overwrite }; let _iOffset = h => d.findIndex(e => e[0] == h) }} // The Scrolly plugin - manages scroll effects centrally // scrolltop values: "s" - "smart" (default), true - always scroll to top, false - no scroll // Switch (o) values: // + - add current page to offsets // ! - scroll to current page offset class Scrolly { constructor() { this.a = function (o) { if(!o) return; //ensure operator var op = o; //cache operator if(o === "+" || o === "!") o = $.currentURL; //fetch currentURL for "+" and "-" operators if(op !== "+" && o.iO("#") && (o.iO("#") < o.length - 1)) { //if hash in URL and not standalone hash let $el = qs("#" + o.split("#")[1]); //fetch the element if (!$el) return; //nothing found -> return quickly let box = $el.getBoundingClientRect(); _scrll(box.top + window.pageYOffset - document.documentElement.clientTop); // ...animate to ID return; } if($.s.scrolltop === "s") { //smart scroll enabled if(op === "+") $.offsets(); //add page offset if(op === "!") _scrll($.offsets(o)); //scroll to stored position of page return; } if(op !== "+" && $.s.scrolltop) _scrll(0); //otherwise scroll to top of page //default -> do nothing }; let _scrll = o => window.scrollTo(0, o) }} // The hApi plugin - manages operatios on the History API centrally // Second parameter (p) - set global currentURL // Switch (o) values: // = - perform a replaceState, using currentURL // otherwise - perform a pushState, using currentURL class HApi { constructor() { this.a = function (o, p) { if(!o) return; //ensure operator if(p) $.currentURL = p; //if p given -> update current URL if(o === "=") history.replaceState({ url: $.currentURL }, "state-" + $.currentURL, $.currentURL); //perform replaceState else if ($.currentURL !== window.location.href) history.pushState({ url: $.currentURL }, "state-" + $.currentURL, $.currentURL); //perform pushState }; }} // The Pronto plugin - Pronto variant of Ben Plum's Pronto plugin - low level event handling in general // Works on a selection, passed to Pronto by the selection, which specifies, which elements to Ajaxify // Switch (h) values: // i - initialise Pronto // <object> - fetch href part and continue with _request() // <URL> - set "h" variable of Rq hard and continue with _request() class Pronto { constructor() { let $gthis = 0, requestTimer = 0, pd = 150, ptim = 0; this.a = function ($this, h) { if(!h) return; //ensure data if(h === "i") { //request to initialise bdy = document.body; if(!$this.length) $this = "body"; $gthis = qa($this); //copy selection to global selector $.frms = new Frms().a; //initialise forms sub-plugin if($.s.idleTime) $.slides = new classSlides($).a; //initialise optional slideshow sub-plugin $.scrolly = new Scrolly().a; //initialise scroll effects sub-plugin $.offsets = new Offsets().a; $.hApi = new HApi().a; _init_p(); //initialise Pronto sub-plugin return $this; //return query selector for chaining } if(typeof(h) === "object") { //jump to internal page programmatically -> handler for forms sub-plugin $.Rq("h", h); _request(); return; } if(h.iO("/")) { //jump to internal page programmatically -> default handler $.Rq("h", h); _request(true); } }; let _init_p = () => { $.hApi("=", window.location.href); window.addEventListener("popstate", _onPop); if ($.s.prefetchoff !== true) { _on("mouseenter", $.s.selector, _preftime); // start prefetch timeout _on("mouseleave", $.s.selector, _prefstop); // stop prefetch timeout _on("touchstart", $.s.selector, _prefetch); } _on("click", $.s.selector, _click, bdy); $.frms("d", qa("body")); $.frms("a"); $.frms("d", $gthis); if($.s.idleTime) $.slides("i"); }, _preftime = (t, e) => ptim = setTimeout(()=> _prefetch(t, e), pd), // call prefetch if timeout expires without being cleared by _prefstop _prefstop = () => clearTimeout(ptim), _prefetch = (t, e) => { if($.s.prefetchoff === true) return; if (!$.Rq("?", true)) return; var href = $.Rq("v", e, t); if ($.Rq("=", true) || !href || Hints($.s.prefetchoff).find(href)) return; $.fn("+", href, () => false); }, _stopBubbling = e => ( e.preventDefault(), e.stopPropagation(), e.stopImmediatePropagation() ), _click = (t, e, notPush) => { if(!$.Rq("?")) return; var href = $.Rq("v", e, t); if(!href || _exoticKey(t)) return; if(href.substr(-1) ==="#") return true; if(_hashChange()) { $.hApi("=", href); return true; } $.scrolly("+"); _stopBubbling(e); if($.Rq("=")) $.hApi("="); if($.s.refresh || !$.Rq("=")) _request(notPush); }, _request = notPush => { $.Rq("!"); if(notPush) $.Rq("p", false); $.trigger("request"); $.fn($.Rq("h"), err => { if (err) { lg("Error in _request : " + err); $.trigger("error", err); } _render(); }); }, _render = () => { $.trigger("beforeload"); if($.s.requestDelay) { if(requestTimer) clearTimeout(requestTimer); requestTimer = setTimeout(_doRender, $.s.requestDelay); } else _doRender(); }, _onPop = e => { var url = window.location.href; $.Rq("i"); $.Rq("h", url); $.Rq("p", false); $.scrolly("+"); if (!url || url === $.currentURL) return; $.trigger("request"); $.fn(url, _render); }, _doRender = () => { $.trigger("load"); if($.s.bodyClasses) { var classes = $.fn("body").getAttribute("class"); bdy.setAttribute("class", classes ? classes : ""); } var href = $.Rq("h"), title; href = $.Rq("c", href); $.hApi($.Rq("p") ? "+" : "=", href); if(title = $.fn("title")) qs("title").innerHTML = title.innerHTML; $.Rq("C", $.fn("-", $gthis)); $.frms("a"); $.scrolly("!"); _gaCaptureView(href); $.trigger("render"); if($.s.passCount) qs("#" + $.s.passCount).innerHTML = "Pass: " + $.pass; if($.s.cb) $.s.cb(); }, _gaCaptureView = href => { href = "/" + href.replace(rootUrl,""); if (typeof window.ga !== "undefined") window.ga("send", "pageview", href); else if (typeof window._gaq !== "undefined") window._gaq.push(["_trackPageview", href]); }, _exoticKey = (t) => { var href = $.Rq("h"), e = $.Rq("e"), tgt = e.currentTarget.target || t.target; return (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || tgt === "_blank" || href.iO("wp-login") || href.iO("wp-admin")); }, _hashChange = () => { var e = $.Rq("e"); return (e.hash && e.href.replace(e.hash, "") === window.location.href.replace(location.hash, "") || e.href === window.location.href + "#"); } }} $.init = () => { let o = options; if (!o || typeof(o) !== "string") { if (document.readyState === "complete" || (document.readyState !== "loading" && !document.documentElement.doScroll)) run(); else document.addEventListener('DOMContentLoaded', run); return $; } else return $.pronto(0, o); }; let run = () => { $.s = Object.assign($.s, options); $.pages = new Pages().a; $.pronto = new Pronto().a; if (load()) { $.pronto($.s.elements, "i"); if ($.s.deltas) $.scripts("1"); } }, load = () => { if (!api || !$.s.pluginon) { lg("Gracefully exiting..."); return false; } lg("Ajaxify loaded..."); //verbosity option steers, whether this initialisation message is output $.scripts = new Scripts().a; $.scripts("i"); $.cache = new Cache().a; $.memory = new Memory().a; $.fn = $.getPage = new GetPage().a; $.detScripts = new DetScripts().a; $.addAll = new AddAll().a; $.Rq = new RQ().a; return true; } $.init(); // initialize Ajaxify on definition }}
cdnjs/cdnjs
ajax/libs/ajaxify/8.1.1/ajaxify.js
JavaScript
mit
30,546
/** * @license Highstock JS v8.1.0 (2020-05-05) * * Indicator series type for Highstock * * (c) 2010-2019 Sebastian Bochan * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/indicators/trendline', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'indicators/trendline.src.js', [_modules['parts/Utilities.js']], function (U) { /* * * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var isArray = U.isArray, seriesType = U.seriesType; /** * The Trend line series type. * * @private * @class * @name Highcharts.seriesTypes.trendline * * @augments Highcharts.Series */ seriesType('trendline', 'sma', /** * Trendline (linear regression) fits a straight line to the selected data * using a method called the Sum Of Least Squares. This series requires the * `linkedTo` option to be set. * * @sample stock/indicators/trendline * Trendline indicator * * @extends plotOptions.sma * @since 7.1.3 * @product highstock * @requires stock/indicators/indicators * @requires stock/indicators/trendline * @optionparent plotOptions.trendline */ { /** * @excluding period */ params: { /** * The point index which indicator calculations will base. For * example using OHLC data, index=2 means the indicator will be * calculated using Low values. * * @default 3 */ index: 3 } }, /** * @lends Highcharts.Series# */ { nameBase: 'Trendline', nameComponents: false, getValues: function (series, params) { var xVal = series.xData, yVal = series.yData, LR = [], xData = [], yData = [], sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0, xValLength = xVal.length, index = params.index, alpha, beta, i, x, y; // Get sums: for (i = 0; i < xValLength; i++) { x = xVal[i]; y = isArray(yVal[i]) ? yVal[i][index] : yVal[i]; sumX += x; sumY += y; sumXY += x * y; sumX2 += x * x; } // Get slope and offset: alpha = (xValLength * sumXY - sumX * sumY) / (xValLength * sumX2 - sumX * sumX); if (isNaN(alpha)) { alpha = 0; } beta = (sumY - alpha * sumX) / xValLength; // Calculate linear regression: for (i = 0; i < xValLength; i++) { x = xVal[i]; y = alpha * x + beta; // Prepare arrays required for getValues() method LR[i] = [x, y]; xData[i] = x; yData[i] = y; } return { xData: xData, yData: yData, values: LR }; } }); /** * A `TrendLine` series. If the [type](#series.trendline.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.trendline * @since 7.1.3 * @product highstock * @excluding dataParser, dataURL * @requires stock/indicators/indicators * @requires stock/indicators/trendline * @apioption series.trendline */ ''; // to include the above in the js output }); _registerModule(_modules, 'masters/indicators/trendline.src.js', [], function () { }); }));
cdnjs/cdnjs
ajax/libs/highcharts/8.1.0/indicators/trendline.src.js
JavaScript
mit
5,152
/*! * FilePond 4.26.0 * Licensed under MIT, https://opensource.org/licenses/MIT/ * Please visit https://pqina.nl/filepond/ for details. */ /* eslint-disable */ (function(global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : ((global = global || self), factory((global.FilePond = {}))); })(this, function(exports) { 'use strict'; var isNode = function isNode(value) { return value instanceof HTMLElement; }; var createStore = function createStore(initialState) { var queries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var actions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; // internal state var state = Object.assign({}, initialState); // contains all actions for next frame, is clear when actions are requested var actionQueue = []; var dispatchQueue = []; // returns a duplicate of the current state var getState = function getState() { return Object.assign({}, state); }; // returns a duplicate of the actions array and clears the actions array var processActionQueue = function processActionQueue() { // create copy of actions queue var queue = [].concat(actionQueue); // clear actions queue (we don't want no double actions) actionQueue.length = 0; return queue; }; // processes actions that might block the main UI thread var processDispatchQueue = function processDispatchQueue() { // create copy of actions queue var queue = [].concat(dispatchQueue); // clear actions queue (we don't want no double actions) dispatchQueue.length = 0; // now dispatch these actions queue.forEach(function(_ref) { var type = _ref.type, data = _ref.data; dispatch(type, data); }); }; // adds a new action, calls its handler and var dispatch = function dispatch(type, data, isBlocking) { // is blocking action (should never block if document is hidden) if (isBlocking && !document.hidden) { dispatchQueue.push({ type: type, data: data }); return; } // if this action has a handler, handle the action if (actionHandlers[type]) { actionHandlers[type](data); } // now add action actionQueue.push({ type: type, data: data, }); }; var query = function query(str) { var _queryHandles; for ( var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ ) { args[_key - 1] = arguments[_key]; } return queryHandles[str] ? (_queryHandles = queryHandles)[str].apply(_queryHandles, args) : null; }; var api = { getState: getState, processActionQueue: processActionQueue, processDispatchQueue: processDispatchQueue, dispatch: dispatch, query: query, }; var queryHandles = {}; queries.forEach(function(query) { queryHandles = Object.assign({}, query(state), {}, queryHandles); }); var actionHandlers = {}; actions.forEach(function(action) { actionHandlers = Object.assign({}, action(dispatch, query, state), {}, actionHandlers); }); return api; }; var defineProperty = function defineProperty(obj, property, definition) { if (typeof definition === 'function') { obj[property] = definition; return; } Object.defineProperty(obj, property, Object.assign({}, definition)); }; var forin = function forin(obj, cb) { for (var key in obj) { if (!obj.hasOwnProperty(key)) { continue; } cb(key, obj[key]); } }; var createObject = function createObject(definition) { var obj = {}; forin(definition, function(property) { defineProperty(obj, property, definition[property]); }); return obj; }; var attr = function attr(node, name) { var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; if (value === null) { return node.getAttribute(name) || node.hasAttribute(name); } node.setAttribute(name, value); }; var ns = 'http://www.w3.org/2000/svg'; var svgElements = ['svg', 'path']; // only svg elements used var isSVGElement = function isSVGElement(tag) { return svgElements.includes(tag); }; var createElement = function createElement(tag, className) { var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof className === 'object') { attributes = className; className = null; } var element = isSVGElement(tag) ? document.createElementNS(ns, tag) : document.createElement(tag); if (className) { if (isSVGElement(tag)) { attr(element, 'class', className); } else { element.className = className; } } forin(attributes, function(name, value) { attr(element, name, value); }); return element; }; var appendChild = function appendChild(parent) { return function(child, index) { if (typeof index !== 'undefined' && parent.children[index]) { parent.insertBefore(child, parent.children[index]); } else { parent.appendChild(child); } }; }; var appendChildView = function appendChildView(parent, childViews) { return function(view, index) { if (typeof index !== 'undefined') { childViews.splice(index, 0, view); } else { childViews.push(view); } return view; }; }; var removeChildView = function removeChildView(parent, childViews) { return function(view) { // remove from child views childViews.splice(childViews.indexOf(view), 1); // remove the element if (view.element.parentNode) { parent.removeChild(view.element); } return view; }; }; var IS_BROWSER = (function() { return typeof window !== 'undefined' && typeof window.document !== 'undefined'; })(); var isBrowser = function isBrowser() { return IS_BROWSER; }; var testElement = isBrowser() ? createElement('svg') : {}; var getChildCount = 'children' in testElement ? function(el) { return el.children.length; } : function(el) { return el.childNodes.length; }; var getViewRect = function getViewRect(elementRect, childViews, offset, scale) { var left = offset[0] || elementRect.left; var top = offset[1] || elementRect.top; var right = left + elementRect.width; var bottom = top + elementRect.height * (scale[1] || 1); var rect = { // the rectangle of the element itself element: Object.assign({}, elementRect), // the rectangle of the element expanded to contain its children, does not include any margins inner: { left: elementRect.left, top: elementRect.top, right: elementRect.right, bottom: elementRect.bottom, }, // the rectangle of the element expanded to contain its children including own margin and child margins // margins will be added after we've recalculated the size outer: { left: left, top: top, right: right, bottom: bottom, }, }; // expand rect to fit all child rectangles childViews .filter(function(childView) { return !childView.isRectIgnored(); }) .map(function(childView) { return childView.rect; }) .forEach(function(childViewRect) { expandRect(rect.inner, Object.assign({}, childViewRect.inner)); expandRect(rect.outer, Object.assign({}, childViewRect.outer)); }); // calculate inner width and height calculateRectSize(rect.inner); // append additional margin (top and left margins are included in top and left automatically) rect.outer.bottom += rect.element.marginBottom; rect.outer.right += rect.element.marginRight; // calculate outer width and height calculateRectSize(rect.outer); return rect; }; var expandRect = function expandRect(parent, child) { // adjust for parent offset child.top += parent.top; child.right += parent.left; child.bottom += parent.top; child.left += parent.left; if (child.bottom > parent.bottom) { parent.bottom = child.bottom; } if (child.right > parent.right) { parent.right = child.right; } }; var calculateRectSize = function calculateRectSize(rect) { rect.width = rect.right - rect.left; rect.height = rect.bottom - rect.top; }; var isNumber = function isNumber(value) { return typeof value === 'number'; }; /** * Determines if position is at destination * @param position * @param destination * @param velocity * @param errorMargin * @returns {boolean} */ var thereYet = function thereYet(position, destination, velocity) { var errorMargin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.001; return Math.abs(position - destination) < errorMargin && Math.abs(velocity) < errorMargin; }; /** * Spring animation */ var spring = // default options function spring() // method definition { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$stiffness = _ref.stiffness, stiffness = _ref$stiffness === void 0 ? 0.5 : _ref$stiffness, _ref$damping = _ref.damping, damping = _ref$damping === void 0 ? 0.75 : _ref$damping, _ref$mass = _ref.mass, mass = _ref$mass === void 0 ? 10 : _ref$mass; var target = null; var position = null; var velocity = 0; var resting = false; // updates spring state var interpolate = function interpolate(ts, skipToEndState) { // in rest, don't animate if (resting) return; // need at least a target or position to do springy things if (!(isNumber(target) && isNumber(position))) { resting = true; velocity = 0; return; } // calculate spring force var f = -(position - target) * stiffness; // update velocity by adding force based on mass velocity += f / mass; // update position by adding velocity position += velocity; // slow down based on amount of damping velocity *= damping; // we've arrived if we're near target and our velocity is near zero if (thereYet(position, target, velocity) || skipToEndState) { position = target; velocity = 0; resting = true; // we done api.onupdate(position); api.oncomplete(position); } else { // progress update api.onupdate(position); } }; /** * Set new target value * @param value */ var setTarget = function setTarget(value) { // if currently has no position, set target and position to this value if (isNumber(value) && !isNumber(position)) { position = value; } // next target value will not be animated to if (target === null) { target = value; position = value; } // let start moving to target target = value; // already at target if (position === target || typeof target === 'undefined') { // now resting as target is current position, stop moving resting = true; velocity = 0; // done! api.onupdate(position); api.oncomplete(position); return; } resting = false; }; // need 'api' to call onupdate callback var api = createObject({ interpolate: interpolate, target: { set: setTarget, get: function get() { return target; }, }, resting: { get: function get() { return resting; }, }, onupdate: function onupdate(value) {}, oncomplete: function oncomplete(value) {}, }); return api; }; var easeLinear = function easeLinear(t) { return t; }; var easeInOutQuad = function easeInOutQuad(t) { return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t; }; var tween = // default values function tween() // method definition { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$duration = _ref.duration, duration = _ref$duration === void 0 ? 500 : _ref$duration, _ref$easing = _ref.easing, easing = _ref$easing === void 0 ? easeInOutQuad : _ref$easing, _ref$delay = _ref.delay, delay = _ref$delay === void 0 ? 0 : _ref$delay; var start = null; var t; var p; var resting = true; var reverse = false; var target = null; var interpolate = function interpolate(ts, skipToEndState) { if (resting || target === null) return; if (start === null) { start = ts; } if (ts - start < delay) return; t = ts - start - delay; if (t >= duration || skipToEndState) { t = 1; p = reverse ? 0 : 1; api.onupdate(p * target); api.oncomplete(p * target); resting = true; } else { p = t / duration; api.onupdate((t >= 0 ? easing(reverse ? 1 - p : p) : 0) * target); } }; // need 'api' to call onupdate callback var api = createObject({ interpolate: interpolate, target: { get: function get() { return reverse ? 0 : target; }, set: function set(value) { // is initial value if (target === null) { target = value; api.onupdate(value); api.oncomplete(value); return; } // want to tween to a smaller value and have a current value if (value < target) { target = 1; reverse = true; } else { // not tweening to a smaller value reverse = false; target = value; } // let's go! resting = false; start = null; }, }, resting: { get: function get() { return resting; }, }, onupdate: function onupdate(value) {}, oncomplete: function oncomplete(value) {}, }); return api; }; var animator = { spring: spring, tween: tween, }; /* { type: 'spring', stiffness: .5, damping: .75, mass: 10 }; { translation: { type: 'spring', ... }, ... } { translation: { x: { type: 'spring', ... } } } */ var createAnimator = function createAnimator(definition, category, property) { // default is single definition // we check if transform is set, if so, we check if property is set var def = definition[category] && typeof definition[category][property] === 'object' ? definition[category][property] : definition[category] || definition; var type = typeof def === 'string' ? def : def.type; var props = typeof def === 'object' ? Object.assign({}, def) : {}; return animator[type] ? animator[type](props) : null; }; var addGetSet = function addGetSet(keys, obj, props) { var overwrite = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; obj = Array.isArray(obj) ? obj : [obj]; obj.forEach(function(o) { keys.forEach(function(key) { var name = key; var getter = function getter() { return props[key]; }; var setter = function setter(value) { return (props[key] = value); }; if (typeof key === 'object') { name = key.key; getter = key.getter || getter; setter = key.setter || setter; } if (o[name] && !overwrite) { return; } o[name] = { get: getter, set: setter, }; }); }); }; // add to state, // add getters and setters to internal and external api (if not set) // setup animators var animations = function animations(_ref) { var mixinConfig = _ref.mixinConfig, viewProps = _ref.viewProps, viewInternalAPI = _ref.viewInternalAPI, viewExternalAPI = _ref.viewExternalAPI; // initial properties var initialProps = Object.assign({}, viewProps); // list of all active animations var animations = []; // setup animators forin(mixinConfig, function(property, animation) { var animator = createAnimator(animation); if (!animator) { return; } // when the animator updates, update the view state value animator.onupdate = function(value) { viewProps[property] = value; }; // set animator target animator.target = initialProps[property]; // when value is set, set the animator target value var prop = { key: property, setter: function setter(value) { // if already at target, we done! if (animator.target === value) { return; } animator.target = value; }, getter: function getter() { return viewProps[property]; }, }; // add getters and setters addGetSet([prop], [viewInternalAPI, viewExternalAPI], viewProps, true); // add it to the list for easy updating from the _write method animations.push(animator); }); // expose internal write api return { write: function write(ts) { var skipToEndState = document.hidden; var resting = true; animations.forEach(function(animation) { if (!animation.resting) resting = false; animation.interpolate(ts, skipToEndState); }); return resting; }, destroy: function destroy() {}, }; }; var addEvent = function addEvent(element) { return function(type, fn) { element.addEventListener(type, fn); }; }; var removeEvent = function removeEvent(element) { return function(type, fn) { element.removeEventListener(type, fn); }; }; // mixin var listeners = function listeners(_ref) { var mixinConfig = _ref.mixinConfig, viewProps = _ref.viewProps, viewInternalAPI = _ref.viewInternalAPI, viewExternalAPI = _ref.viewExternalAPI, viewState = _ref.viewState, view = _ref.view; var events = []; var add = addEvent(view.element); var remove = removeEvent(view.element); viewExternalAPI.on = function(type, fn) { events.push({ type: type, fn: fn, }); add(type, fn); }; viewExternalAPI.off = function(type, fn) { events.splice( events.findIndex(function(event) { return event.type === type && event.fn === fn; }), 1 ); remove(type, fn); }; return { write: function write() { // not busy return true; }, destroy: function destroy() { events.forEach(function(event) { remove(event.type, event.fn); }); }, }; }; // add to external api and link to props var apis = function apis(_ref) { var mixinConfig = _ref.mixinConfig, viewProps = _ref.viewProps, viewExternalAPI = _ref.viewExternalAPI; addGetSet(mixinConfig, viewExternalAPI, viewProps); }; var isDefined = function isDefined(value) { return value != null; }; // add to state, // add getters and setters to internal and external api (if not set) // set initial state based on props in viewProps // apply as transforms each frame var defaults = { opacity: 1, scaleX: 1, scaleY: 1, translateX: 0, translateY: 0, rotateX: 0, rotateY: 0, rotateZ: 0, originX: 0, originY: 0, }; var styles = function styles(_ref) { var mixinConfig = _ref.mixinConfig, viewProps = _ref.viewProps, viewInternalAPI = _ref.viewInternalAPI, viewExternalAPI = _ref.viewExternalAPI, view = _ref.view; // initial props var initialProps = Object.assign({}, viewProps); // current props var currentProps = {}; // we will add those properties to the external API and link them to the viewState addGetSet(mixinConfig, [viewInternalAPI, viewExternalAPI], viewProps); // override rect on internal and external rect getter so it takes in account transforms var getOffset = function getOffset() { return [viewProps['translateX'] || 0, viewProps['translateY'] || 0]; }; var getScale = function getScale() { return [viewProps['scaleX'] || 0, viewProps['scaleY'] || 0]; }; var getRect = function getRect() { return view.rect ? getViewRect(view.rect, view.childViews, getOffset(), getScale()) : null; }; viewInternalAPI.rect = { get: getRect }; viewExternalAPI.rect = { get: getRect }; // apply view props mixinConfig.forEach(function(key) { viewProps[key] = typeof initialProps[key] === 'undefined' ? defaults[key] : initialProps[key]; }); // expose api return { write: function write() { // see if props have changed if (!propsHaveChanged(currentProps, viewProps)) { return; } // moves element to correct position on screen applyStyles(view.element, viewProps); // store new transforms Object.assign(currentProps, Object.assign({}, viewProps)); // no longer busy return true; }, destroy: function destroy() {}, }; }; var propsHaveChanged = function propsHaveChanged(currentProps, newProps) { // different amount of keys if (Object.keys(currentProps).length !== Object.keys(newProps).length) { return true; } // lets analyze the individual props for (var prop in newProps) { if (newProps[prop] !== currentProps[prop]) { return true; } } return false; }; var applyStyles = function applyStyles(element, _ref2) { var opacity = _ref2.opacity, perspective = _ref2.perspective, translateX = _ref2.translateX, translateY = _ref2.translateY, scaleX = _ref2.scaleX, scaleY = _ref2.scaleY, rotateX = _ref2.rotateX, rotateY = _ref2.rotateY, rotateZ = _ref2.rotateZ, originX = _ref2.originX, originY = _ref2.originY, width = _ref2.width, height = _ref2.height; var transforms = ''; var styles = ''; // handle transform origin if (isDefined(originX) || isDefined(originY)) { styles += 'transform-origin: ' + (originX || 0) + 'px ' + (originY || 0) + 'px;'; } // transform order is relevant // 0. perspective if (isDefined(perspective)) { transforms += 'perspective(' + perspective + 'px) '; } // 1. translate if (isDefined(translateX) || isDefined(translateY)) { transforms += 'translate3d(' + (translateX || 0) + 'px, ' + (translateY || 0) + 'px, 0) '; } // 2. scale if (isDefined(scaleX) || isDefined(scaleY)) { transforms += 'scale3d(' + (isDefined(scaleX) ? scaleX : 1) + ', ' + (isDefined(scaleY) ? scaleY : 1) + ', 1) '; } // 3. rotate if (isDefined(rotateZ)) { transforms += 'rotateZ(' + rotateZ + 'rad) '; } if (isDefined(rotateX)) { transforms += 'rotateX(' + rotateX + 'rad) '; } if (isDefined(rotateY)) { transforms += 'rotateY(' + rotateY + 'rad) '; } // add transforms if (transforms.length) { styles += 'transform:' + transforms + ';'; } // add opacity if (isDefined(opacity)) { styles += 'opacity:' + opacity + ';'; // if we reach zero, we make the element inaccessible if (opacity === 0) { styles += 'visibility:hidden;'; } // if we're below 100% opacity this element can't be clicked if (opacity < 1) { styles += 'pointer-events:none;'; } } // add height if (isDefined(height)) { styles += 'height:' + height + 'px;'; } // add width if (isDefined(width)) { styles += 'width:' + width + 'px;'; } // apply styles var elementCurrentStyle = element.elementCurrentStyle || ''; // if new styles does not match current styles, lets update! if (styles.length !== elementCurrentStyle.length || styles !== elementCurrentStyle) { element.style.cssText = styles; // store current styles so we can compare them to new styles later on // _not_ getting the style value is faster element.elementCurrentStyle = styles; } }; var Mixins = { styles: styles, listeners: listeners, animations: animations, apis: apis, }; var updateRect = function updateRect() { var rect = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (!element.layoutCalculated) { rect.paddingTop = parseInt(style.paddingTop, 10) || 0; rect.marginTop = parseInt(style.marginTop, 10) || 0; rect.marginRight = parseInt(style.marginRight, 10) || 0; rect.marginBottom = parseInt(style.marginBottom, 10) || 0; rect.marginLeft = parseInt(style.marginLeft, 10) || 0; element.layoutCalculated = true; } rect.left = element.offsetLeft || 0; rect.top = element.offsetTop || 0; rect.width = element.offsetWidth || 0; rect.height = element.offsetHeight || 0; rect.right = rect.left + rect.width; rect.bottom = rect.top + rect.height; rect.scrollTop = element.scrollTop; rect.hidden = element.offsetParent === null; return rect; }; var createView = // default view definition function createView() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$tag = _ref.tag, tag = _ref$tag === void 0 ? 'div' : _ref$tag, _ref$name = _ref.name, name = _ref$name === void 0 ? null : _ref$name, _ref$attributes = _ref.attributes, attributes = _ref$attributes === void 0 ? {} : _ref$attributes, _ref$read = _ref.read, read = _ref$read === void 0 ? function() {} : _ref$read, _ref$write = _ref.write, write = _ref$write === void 0 ? function() {} : _ref$write, _ref$create = _ref.create, create = _ref$create === void 0 ? function() {} : _ref$create, _ref$destroy = _ref.destroy, destroy = _ref$destroy === void 0 ? function() {} : _ref$destroy, _ref$filterFrameActio = _ref.filterFrameActionsForChild, filterFrameActionsForChild = _ref$filterFrameActio === void 0 ? function(child, actions) { return actions; } : _ref$filterFrameActio, _ref$didCreateView = _ref.didCreateView, didCreateView = _ref$didCreateView === void 0 ? function() {} : _ref$didCreateView, _ref$didWriteView = _ref.didWriteView, didWriteView = _ref$didWriteView === void 0 ? function() {} : _ref$didWriteView, _ref$ignoreRect = _ref.ignoreRect, ignoreRect = _ref$ignoreRect === void 0 ? false : _ref$ignoreRect, _ref$ignoreRectUpdate = _ref.ignoreRectUpdate, ignoreRectUpdate = _ref$ignoreRectUpdate === void 0 ? false : _ref$ignoreRectUpdate, _ref$mixins = _ref.mixins, mixins = _ref$mixins === void 0 ? [] : _ref$mixins; return function( // each view requires reference to store store ) { var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // root element should not be changed var element = createElement(tag, 'filepond--' + name, attributes); // style reference should also not be changed var style = window.getComputedStyle(element, null); // element rectangle var rect = updateRect(); var frameRect = null; // rest state var isResting = false; // pretty self explanatory var childViews = []; // loaded mixins var activeMixins = []; // references to created children var ref = {}; // state used for each instance var state = {}; // list of writers that will be called to update this view var writers = [ write, // default writer ]; var readers = [ read, // default reader ]; var destroyers = [ destroy, // default destroy ]; // core view methods var getElement = function getElement() { return element; }; var getChildViews = function getChildViews() { return childViews.concat(); }; var getReference = function getReference() { return ref; }; var createChildView = function createChildView(store) { return function(view, props) { return view(store, props); }; }; var getRect = function getRect() { if (frameRect) { return frameRect; } frameRect = getViewRect(rect, childViews, [0, 0], [1, 1]); return frameRect; }; var getStyle = function getStyle() { return style; }; /** * Read data from DOM * @private */ var _read = function _read() { frameRect = null; // read child views childViews.forEach(function(child) { return child._read(); }); var shouldUpdate = !(ignoreRectUpdate && rect.width && rect.height); if (shouldUpdate) { updateRect(rect, element, style); } // readers var api = { root: internalAPI, props: props, rect: rect }; readers.forEach(function(reader) { return reader(api); }); }; /** * Write data to DOM * @private */ var _write = function _write(ts, frameActions, shouldOptimize) { // if no actions, we assume that the view is resting var resting = frameActions.length === 0; // writers writers.forEach(function(writer) { var writerResting = writer({ props: props, root: internalAPI, actions: frameActions, timestamp: ts, shouldOptimize: shouldOptimize, }); if (writerResting === false) { resting = false; } }); // run mixins activeMixins.forEach(function(mixin) { // if one of the mixins is still busy after write operation, we are not resting var mixinResting = mixin.write(ts); if (mixinResting === false) { resting = false; } }); // updates child views that are currently attached to the DOM childViews .filter(function(child) { return !!child.element.parentNode; }) .forEach(function(child) { // if a child view is not resting, we are not resting var childResting = child._write( ts, filterFrameActionsForChild(child, frameActions), shouldOptimize ); if (!childResting) { resting = false; } }); // append new elements to DOM and update those childViews //.filter(child => !child.element.parentNode) .forEach(function(child, index) { // skip if (child.element.parentNode) { return; } // append to DOM internalAPI.appendChild(child.element, index); // call read (need to know the size of these elements) child._read(); // re-call write child._write( ts, filterFrameActionsForChild(child, frameActions), shouldOptimize ); // we just added somthing to the dom, no rest resting = false; }); // update resting state isResting = resting; didWriteView({ props: props, root: internalAPI, actions: frameActions, timestamp: ts, }); // let parent know if we are resting return resting; }; var _destroy = function _destroy() { activeMixins.forEach(function(mixin) { return mixin.destroy(); }); destroyers.forEach(function(destroyer) { destroyer({ root: internalAPI, props: props }); }); childViews.forEach(function(child) { return child._destroy(); }); }; // sharedAPI var sharedAPIDefinition = { element: { get: getElement, }, style: { get: getStyle, }, childViews: { get: getChildViews, }, }; // private API definition var internalAPIDefinition = Object.assign({}, sharedAPIDefinition, { rect: { get: getRect, }, // access to custom children references ref: { get: getReference, }, // dom modifiers is: function is(needle) { return name === needle; }, appendChild: appendChild(element), createChildView: createChildView(store), linkView: function linkView(view) { childViews.push(view); return view; }, unlinkView: function unlinkView(view) { childViews.splice(childViews.indexOf(view), 1); }, appendChildView: appendChildView(element, childViews), removeChildView: removeChildView(element, childViews), registerWriter: function registerWriter(writer) { return writers.push(writer); }, registerReader: function registerReader(reader) { return readers.push(reader); }, registerDestroyer: function registerDestroyer(destroyer) { return destroyers.push(destroyer); }, invalidateLayout: function invalidateLayout() { return (element.layoutCalculated = false); }, // access to data store dispatch: store.dispatch, query: store.query, }); // public view API methods var externalAPIDefinition = { element: { get: getElement, }, childViews: { get: getChildViews, }, rect: { get: getRect, }, resting: { get: function get() { return isResting; }, }, isRectIgnored: function isRectIgnored() { return ignoreRect; }, _read: _read, _write: _write, _destroy: _destroy, }; // mixin API methods var mixinAPIDefinition = Object.assign({}, sharedAPIDefinition, { rect: { get: function get() { return rect; }, }, }); // add mixin functionality Object.keys(mixins) .sort(function(a, b) { // move styles to the back of the mixin list (so adjustments of other mixins are applied to the props correctly) if (a === 'styles') { return 1; } else if (b === 'styles') { return -1; } return 0; }) .forEach(function(key) { var mixinAPI = Mixins[key]({ mixinConfig: mixins[key], viewProps: props, viewState: state, viewInternalAPI: internalAPIDefinition, viewExternalAPI: externalAPIDefinition, view: createObject(mixinAPIDefinition), }); if (mixinAPI) { activeMixins.push(mixinAPI); } }); // construct private api var internalAPI = createObject(internalAPIDefinition); // create the view create({ root: internalAPI, props: props, }); // append created child views to root node var childCount = getChildCount(element); // need to know the current child count so appending happens in correct order childViews.forEach(function(child, index) { internalAPI.appendChild(child.element, childCount + index); }); // call did create didCreateView(internalAPI); // expose public api return createObject(externalAPIDefinition); }; }; var createPainter = function createPainter(read, write) { var fps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 60; var name = '__framePainter'; // set global painter if (window[name]) { window[name].readers.push(read); window[name].writers.push(write); return; } window[name] = { readers: [read], writers: [write], }; var painter = window[name]; var interval = 1000 / fps; var last = null; var id = null; var requestTick = null; var cancelTick = null; var setTimerType = function setTimerType() { if (document.hidden) { requestTick = function requestTick() { return window.setTimeout(function() { return tick(performance.now()); }, interval); }; cancelTick = function cancelTick() { return window.clearTimeout(id); }; } else { requestTick = function requestTick() { return window.requestAnimationFrame(tick); }; cancelTick = function cancelTick() { return window.cancelAnimationFrame(id); }; } }; document.addEventListener('visibilitychange', function() { if (cancelTick) cancelTick(); setTimerType(); tick(performance.now()); }); var tick = function tick(ts) { // queue next tick id = requestTick(tick); // limit fps if (!last) { last = ts; } var delta = ts - last; if (delta <= interval) { // skip frame return; } // align next frame last = ts - (delta % interval); // update view painter.readers.forEach(function(read) { return read(); }); painter.writers.forEach(function(write) { return write(ts); }); }; setTimerType(); tick(performance.now()); return { pause: function pause() { cancelTick(id); }, }; }; var createRoute = function createRoute(routes, fn) { return function(_ref) { var root = _ref.root, props = _ref.props, _ref$actions = _ref.actions, actions = _ref$actions === void 0 ? [] : _ref$actions, timestamp = _ref.timestamp, shouldOptimize = _ref.shouldOptimize; actions .filter(function(action) { return routes[action.type]; }) .forEach(function(action) { return routes[action.type]({ root: root, props: props, action: action.data, timestamp: timestamp, shouldOptimize: shouldOptimize, }); }); if (fn) { fn({ root: root, props: props, actions: actions, timestamp: timestamp, shouldOptimize: shouldOptimize, }); } }; }; var insertBefore = function insertBefore(newNode, referenceNode) { return referenceNode.parentNode.insertBefore(newNode, referenceNode); }; var insertAfter = function insertAfter(newNode, referenceNode) { return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); }; var isArray = function isArray(value) { return Array.isArray(value); }; var isEmpty = function isEmpty(value) { return value == null; }; var trim = function trim(str) { return str.trim(); }; var toString = function toString(value) { return '' + value; }; var toArray = function toArray(value) { var splitter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ','; if (isEmpty(value)) { return []; } if (isArray(value)) { return value; } return toString(value) .split(splitter) .map(trim) .filter(function(str) { return str.length; }); }; var isBoolean = function isBoolean(value) { return typeof value === 'boolean'; }; var toBoolean = function toBoolean(value) { return isBoolean(value) ? value : value === 'true'; }; var isString = function isString(value) { return typeof value === 'string'; }; var toNumber = function toNumber(value) { return isNumber(value) ? value : isString(value) ? toString(value).replace(/[a-z]+/gi, '') : 0; }; var toInt = function toInt(value) { return parseInt(toNumber(value), 10); }; var toFloat = function toFloat(value) { return parseFloat(toNumber(value)); }; var isInt = function isInt(value) { return isNumber(value) && isFinite(value) && Math.floor(value) === value; }; var toBytes = function toBytes(value) { var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000; // is in bytes if (isInt(value)) { return value; } // is natural file size var naturalFileSize = toString(value).trim(); // if is value in megabytes if (/MB$/i.test(naturalFileSize)) { naturalFileSize = naturalFileSize.replace(/MB$i/, '').trim(); return toInt(naturalFileSize) * base * base; } // if is value in kilobytes if (/KB/i.test(naturalFileSize)) { naturalFileSize = naturalFileSize.replace(/KB$i/, '').trim(); return toInt(naturalFileSize) * base; } return toInt(naturalFileSize); }; var isFunction = function isFunction(value) { return typeof value === 'function'; }; var toFunctionReference = function toFunctionReference(string) { var ref = self; var levels = string.split('.'); var level = null; while ((level = levels.shift())) { ref = ref[level]; if (!ref) { return null; } } return ref; }; var methods = { process: 'POST', patch: 'PATCH', revert: 'DELETE', fetch: 'GET', restore: 'GET', load: 'GET', }; var createServerAPI = function createServerAPI(outline) { var api = {}; api.url = isString(outline) ? outline : outline.url || ''; api.timeout = outline.timeout ? parseInt(outline.timeout, 10) : 0; api.headers = outline.headers ? outline.headers : {}; forin(methods, function(key) { api[key] = createAction(key, outline[key], methods[key], api.timeout, api.headers); }); // special treatment for remove api.remove = outline.remove || null; // remove generic headers from api object delete api.headers; return api; }; var createAction = function createAction(name, outline, method, timeout, headers) { // is explicitely set to null so disable if (outline === null) { return null; } // if is custom function, done! Dev handles everything. if (typeof outline === 'function') { return outline; } // build action object var action = { url: method === 'GET' || method === 'PATCH' ? '?' + name + '=' : '', method: method, headers: headers, withCredentials: false, timeout: timeout, onload: null, ondata: null, onerror: null, }; // is a single url if (isString(outline)) { action.url = outline; return action; } // overwrite Object.assign(action, outline); // see if should reformat headers; if (isString(action.headers)) { var parts = action.headers.split(/:(.+)/); action.headers = { header: parts[0], value: parts[1], }; } // if is bool withCredentials action.withCredentials = toBoolean(action.withCredentials); return action; }; var toServerAPI = function toServerAPI(value) { return createServerAPI(value); }; var isNull = function isNull(value) { return value === null; }; var isObject = function isObject(value) { return typeof value === 'object' && value !== null; }; var isAPI = function isAPI(value) { return ( isObject(value) && isString(value.url) && isObject(value.process) && isObject(value.revert) && isObject(value.restore) && isObject(value.fetch) ); }; var getType = function getType(value) { if (isArray(value)) { return 'array'; } if (isNull(value)) { return 'null'; } if (isInt(value)) { return 'int'; } if (/^[0-9]+ ?(?:GB|MB|KB)$/gi.test(value)) { return 'bytes'; } if (isAPI(value)) { return 'api'; } return typeof value; }; var replaceSingleQuotes = function replaceSingleQuotes(str) { return str .replace(/{\s*'/g, '{"') .replace(/'\s*}/g, '"}') .replace(/'\s*:/g, '":') .replace(/:\s*'/g, ':"') .replace(/,\s*'/g, ',"') .replace(/'\s*,/g, '",'); }; var conversionTable = { array: toArray, boolean: toBoolean, int: function int(value) { return getType(value) === 'bytes' ? toBytes(value) : toInt(value); }, number: toFloat, float: toFloat, bytes: toBytes, string: function string(value) { return isFunction(value) ? value : toString(value); }, function: function _function(value) { return toFunctionReference(value); }, serverapi: toServerAPI, object: function object(value) { try { return JSON.parse(replaceSingleQuotes(value)); } catch (e) { return null; } }, }; var convertTo = function convertTo(value, type) { return conversionTable[type](value); }; var getValueByType = function getValueByType(newValue, defaultValue, valueType) { // can always assign default value if (newValue === defaultValue) { return newValue; } // get the type of the new value var newValueType = getType(newValue); // is valid type? if (newValueType !== valueType) { // is string input, let's attempt to convert var convertedValue = convertTo(newValue, valueType); // what is the type now newValueType = getType(convertedValue); // no valid conversions found if (convertedValue === null) { throw 'Trying to assign value with incorrect type to "' + option + '", allowed type: "' + valueType + '"'; } else { newValue = convertedValue; } } // assign new value return newValue; }; var createOption = function createOption(defaultValue, valueType) { var currentValue = defaultValue; return { enumerable: true, get: function get() { return currentValue; }, set: function set(newValue) { currentValue = getValueByType(newValue, defaultValue, valueType); }, }; }; var createOptions = function createOptions(options) { var obj = {}; forin(options, function(prop) { var optionDefinition = options[prop]; obj[prop] = createOption(optionDefinition[0], optionDefinition[1]); }); return createObject(obj); }; var createInitialState = function createInitialState(options) { return { // model items: [], // timeout used for calling update items listUpdateTimeout: null, // timeout used for stacking metadata updates itemUpdateTimeout: null, // queue of items waiting to be processed processingQueue: [], // options options: createOptions(options), }; }; var fromCamels = function fromCamels(string) { var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-'; return string .split(/(?=[A-Z])/) .map(function(part) { return part.toLowerCase(); }) .join(separator); }; var createOptionAPI = function createOptionAPI(store, options) { var obj = {}; forin(options, function(key) { obj[key] = { get: function get() { return store.getState().options[key]; }, set: function set(value) { store.dispatch('SET_' + fromCamels(key, '_').toUpperCase(), { value: value, }); }, }; }); return obj; }; var createOptionActions = function createOptionActions(options) { return function(dispatch, query, state) { var obj = {}; forin(options, function(key) { var name = fromCamels(key, '_').toUpperCase(); obj['SET_' + name] = function(action) { try { state.options[key] = action.value; } catch (e) {} // nope, failed // we successfully set the value of this option dispatch('DID_SET_' + name, { value: state.options[key] }); }; }); return obj; }; }; var createOptionQueries = function createOptionQueries(options) { return function(state) { var obj = {}; forin(options, function(key) { obj['GET_' + fromCamels(key, '_').toUpperCase()] = function(action) { return state.options[key]; }; }); return obj; }; }; var InteractionMethod = { API: 1, DROP: 2, BROWSE: 3, PASTE: 4, NONE: 5, }; var getUniqueId = function getUniqueId() { return Math.random() .toString(36) .substr(2, 9); }; function _typeof(obj) { if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { _typeof = function(obj) { return typeof obj; }; } else { _typeof = function(obj) { return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; }; } return _typeof(obj); } var REACT_ELEMENT_TYPE; function _jsx(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element')) || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { props = { children: void 0, }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null, }; } function _asyncIterator(iterable) { var method; if (typeof Symbol !== 'undefined') { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator]; if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator]; if (method != null) return method.call(iterable); } } throw new TypeError('Object is not async iterable'); } function _AwaitValue(value) { this.wrapped = value; } function _AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function(resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null, }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; var wrappedAwait = value instanceof _AwaitValue; Promise.resolve(wrappedAwait ? value.wrapped : value).then( function(arg) { if (wrappedAwait) { resume('next', arg); return; } settle(result.done ? 'return' : 'normal', arg); }, function(err) { resume('throw', err); } ); } catch (err) { settle('throw', err); } } function settle(type, value) { switch (type) { case 'return': front.resolve({ value: value, done: true, }); break; case 'throw': front.reject(value); break; default: front.resolve({ value: value, done: false, }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen.return !== 'function') { this.return = undefined; } } if (typeof Symbol === 'function' && Symbol.asyncIterator) { _AsyncGenerator.prototype[Symbol.asyncIterator] = function() { return this; }; } _AsyncGenerator.prototype.next = function(arg) { return this._invoke('next', arg); }; _AsyncGenerator.prototype.throw = function(arg) { return this._invoke('throw', arg); }; _AsyncGenerator.prototype.return = function(arg) { return this._invoke('return', arg); }; function _wrapAsyncGenerator(fn) { return function() { return new _AsyncGenerator(fn.apply(this, arguments)); }; } function _awaitAsyncGenerator(value) { return new _AwaitValue(value); } function _asyncGeneratorDelegate(inner, awaitWrap) { var iter = {}, waiting = false; function pump(key, value) { waiting = true; value = new Promise(function(resolve) { resolve(inner[key](value)); }); return { done: false, value: awaitWrap(value), }; } if (typeof Symbol === 'function' && Symbol.iterator) { iter[Symbol.iterator] = function() { return this; }; } iter.next = function(value) { if (waiting) { waiting = false; return value; } return pump('next', value); }; if (typeof inner.throw === 'function') { iter.throw = function(value) { if (waiting) { waiting = false; throw value; } return pump('throw', value); }; } if (typeof inner.return === 'function') { iter.return = function(value) { return pump('return', value); }; } return iter; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineEnumerableProperties(obj, descs) { for (var key in descs) { var desc = descs[key]; desc.configurable = desc.enumerable = true; if ('value' in desc) desc.writable = true; Object.defineProperty(obj, key, desc); } if (Object.getOwnPropertySymbols) { var objectSymbols = Object.getOwnPropertySymbols(descs); for (var i = 0; i < objectSymbols.length; i++) { var sym = objectSymbols[i]; var desc = descs[sym]; desc.configurable = desc.enumerable = true; if ('value' in desc) desc.writable = true; Object.defineProperty(obj, sym, desc); } } return obj; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true, }); } else { obj[key] = value; } return obj; } function _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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat( Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; }) ); } ownKeys.forEach(function(key) { _defineProperty(target, key, source[key]); }); } return target; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function(sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function(key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function(key) { Object.defineProperty( target, key, Object.getOwnPropertyDescriptor(source, key) ); }); } } return target; } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function'); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true, }, }); if (superClass) _setPrototypeOf(subClass, superClass); } 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 _instanceof(left, right) { if (right != null && typeof Symbol !== 'undefined' && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj, }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError('Cannot instantiate an arrow function'); } } function _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError('Cannot destructure undefined'); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === 'object' || typeof call === 'function')) { return call; } return _assertThisInitialized(self); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _get(target, property, receiver) { if (typeof Reflect !== 'undefined' && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function set(target, property, value, receiver) { if (typeof Reflect !== 'undefined' && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = _superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { return false; } } desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { _defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); } function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; } function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze( Object.defineProperties(strings, { raw: { value: Object.freeze(raw), }, }) ); } function _taggedTemplateLiteralLoose(strings, raw) { if (!raw) { raw = strings.slice(0); } strings.raw = raw; return strings; } function _temporalRef(val, name) { if (val === _temporalUndefined) { throw new ReferenceError(name + ' is not defined - temporal dead zone'); } else { return val; } } function _readOnlyError(name) { throw new Error('"' + name + '" is read-only'); } function _classNameTDZError(name) { throw new Error('Class "' + name + '" cannot be referenced in computed property keys.'); } var _temporalUndefined = {}; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _slicedToArrayLoose(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _nonIterableRest(); } function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if ( Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]' ) return Array.from(iter); } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return'] != null) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } function _iterableToArrayLimitLoose(arr, i) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done; ) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } function _nonIterableSpread() { throw new TypeError('Invalid attempt to spread non-iterable instance'); } function _nonIterableRest() { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } function _skipFirstGeneratorNext(fn) { return function() { var it = fn.apply(this, arguments); it.next(); return it; }; } function _toPrimitive(input, hint) { if (typeof input !== 'object' || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || 'default'); if (typeof res !== 'object') return res; throw new TypeError('@@toPrimitive must return a primitive value.'); } return (hint === 'string' ? String : Number)(input); } function _toPropertyKey(arg) { var key = _toPrimitive(arg, 'string'); return typeof key === 'symbol' ? key : String(key); } function _initializerWarningHelper(descriptor, context) { throw new Error( 'Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and set to use loose mode. ' + 'To use proposal-class-properties in spec mode with decorators, wait for ' + 'the next major version of decorators in stage 2.' ); } function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0, }); } function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function(key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators .slice() .reverse() .reduce(function(desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; } var id = 0; function _classPrivateFieldLooseKey(name) { return '__private_' + id++ + '_' + name; } function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError('attempted to use private field on non-instance'); } return receiver; } function _classPrivateFieldGet(receiver, privateMap) { var descriptor = privateMap.get(receiver); if (!descriptor) { throw new TypeError('attempted to get private field on non-instance'); } if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; } function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = privateMap.get(receiver); if (!descriptor) { throw new TypeError('attempted to set private field on non-instance'); } if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { throw new TypeError('attempted to set read only private field'); } descriptor.value = value; } return value; } function _classPrivateFieldDestructureSet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError('attempted to set private field on non-instance'); } var descriptor = privateMap.get(receiver); if (descriptor.set) { if (!('__destrObj' in descriptor)) { descriptor.__destrObj = { set value(v) { descriptor.set.call(receiver, v); }, }; } return descriptor.__destrObj; } else { if (!descriptor.writable) { throw new TypeError('attempted to set read only private field'); } return descriptor; } } function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { if (receiver !== classConstructor) { throw new TypeError('Private static access of wrong provenance'); } return descriptor.value; } function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { if (receiver !== classConstructor) { throw new TypeError('Private static access of wrong provenance'); } if (!descriptor.writable) { throw new TypeError('attempted to set read only private field'); } descriptor.value = value; return value; } function _classStaticPrivateMethodGet(receiver, classConstructor, method) { if (receiver !== classConstructor) { throw new TypeError('Private static access of wrong provenance'); } return method; } function _classStaticPrivateMethodSet() { throw new TypeError('attempted to set read only static private field'); } function _decorate(decorators, factory, superClass, mixins) { var api = _getDecoratorsApi(); if (mixins) { for (var i = 0; i < mixins.length; i++) { api = mixins[i](api); } } var r = factory(function initialize(O) { api.initializeInstanceElements(O, decorated.elements); }, superClass); var decorated = api.decorateClass( _coalesceClassElements(r.d.map(_createElementDescriptor)), decorators ); api.initializeClassElements(r.F, decorated.elements); return api.runClassFinishers(r.F, decorated.finishers); } function _getDecoratorsApi() { _getDecoratorsApi = function() { return api; }; var api = { elementsDefinitionOrder: [['method'], ['field']], initializeInstanceElements: function(O, elements) { ['method', 'field'].forEach(function(kind) { elements.forEach(function(element) { if (element.kind === kind && element.placement === 'own') { this.defineClassElement(O, element); } }, this); }, this); }, initializeClassElements: function(F, elements) { var proto = F.prototype; ['method', 'field'].forEach(function(kind) { elements.forEach(function(element) { var placement = element.placement; if ( element.kind === kind && (placement === 'static' || placement === 'prototype') ) { var receiver = placement === 'static' ? F : proto; this.defineClassElement(receiver, element); } }, this); }, this); }, defineClassElement: function(receiver, element) { var descriptor = element.descriptor; if (element.kind === 'field') { var initializer = element.initializer; descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver), }; } Object.defineProperty(receiver, element.key, descriptor); }, decorateClass: function(elements, decorators) { var newElements = []; var finishers = []; var placements = { static: [], prototype: [], own: [], }; elements.forEach(function(element) { this.addElementPlacement(element, placements); }, this); elements.forEach(function(element) { if (!_hasDecorators(element)) return newElements.push(element); var elementFinishersExtras = this.decorateElement(element, placements); newElements.push(elementFinishersExtras.element); newElements.push.apply(newElements, elementFinishersExtras.extras); finishers.push.apply(finishers, elementFinishersExtras.finishers); }, this); if (!decorators) { return { elements: newElements, finishers: finishers, }; } var result = this.decorateConstructor(newElements, decorators); finishers.push.apply(finishers, result.finishers); result.finishers = finishers; return result; }, addElementPlacement: function(element, placements, silent) { var keys = placements[element.placement]; if (!silent && keys.indexOf(element.key) !== -1) { throw new TypeError('Duplicated element (' + element.key + ')'); } keys.push(element.key); }, decorateElement: function(element, placements) { var extras = []; var finishers = []; for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { var keys = placements[element.placement]; keys.splice(keys.indexOf(element.key), 1); var elementObject = this.fromElementDescriptor(element); var elementFinisherExtras = this.toElementFinisherExtras( (0, decorators[i])(elementObject) || elementObject ); element = elementFinisherExtras.element; this.addElementPlacement(element, placements); if (elementFinisherExtras.finisher) { finishers.push(elementFinisherExtras.finisher); } var newExtras = elementFinisherExtras.extras; if (newExtras) { for (var j = 0; j < newExtras.length; j++) { this.addElementPlacement(newExtras[j], placements); } extras.push.apply(extras, newExtras); } } return { element: element, finishers: finishers, extras: extras, }; }, decorateConstructor: function(elements, decorators) { var finishers = []; for (var i = decorators.length - 1; i >= 0; i--) { var obj = this.fromClassDescriptor(elements); var elementsAndFinisher = this.toClassDescriptor( (0, decorators[i])(obj) || obj ); if (elementsAndFinisher.finisher !== undefined) { finishers.push(elementsAndFinisher.finisher); } if (elementsAndFinisher.elements !== undefined) { elements = elementsAndFinisher.elements; for (var j = 0; j < elements.length - 1; j++) { for (var k = j + 1; k < elements.length; k++) { if ( elements[j].key === elements[k].key && elements[j].placement === elements[k].placement ) { throw new TypeError( 'Duplicated element (' + elements[j].key + ')' ); } } } } } return { elements: elements, finishers: finishers, }; }, fromElementDescriptor: function(element) { var obj = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor, }; var desc = { value: 'Descriptor', configurable: true, }; Object.defineProperty(obj, Symbol.toStringTag, desc); if (element.kind === 'field') obj.initializer = element.initializer; return obj; }, toElementDescriptors: function(elementObjects) { if (elementObjects === undefined) return; return _toArray(elementObjects).map(function(elementObject) { var element = this.toElementDescriptor(elementObject); this.disallowProperty(elementObject, 'finisher', 'An element descriptor'); this.disallowProperty(elementObject, 'extras', 'An element descriptor'); return element; }, this); }, toElementDescriptor: function(elementObject) { var kind = String(elementObject.kind); if (kind !== 'method' && kind !== 'field') { throw new TypeError( 'An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"' ); } var key = _toPropertyKey(elementObject.key); var placement = String(elementObject.placement); if (placement !== 'static' && placement !== 'prototype' && placement !== 'own') { throw new TypeError( 'An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"' ); } var descriptor = elementObject.descriptor; this.disallowProperty(elementObject, 'elements', 'An element descriptor'); var element = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor), }; if (kind !== 'field') { this.disallowProperty(elementObject, 'initializer', 'A method descriptor'); } else { this.disallowProperty( descriptor, 'get', 'The property descriptor of a field descriptor' ); this.disallowProperty( descriptor, 'set', 'The property descriptor of a field descriptor' ); this.disallowProperty( descriptor, 'value', 'The property descriptor of a field descriptor' ); element.initializer = elementObject.initializer; } return element; }, toElementFinisherExtras: function(elementObject) { var element = this.toElementDescriptor(elementObject); var finisher = _optionalCallableProperty(elementObject, 'finisher'); var extras = this.toElementDescriptors(elementObject.extras); return { element: element, finisher: finisher, extras: extras, }; }, fromClassDescriptor: function(elements) { var obj = { kind: 'class', elements: elements.map(this.fromElementDescriptor, this), }; var desc = { value: 'Descriptor', configurable: true, }; Object.defineProperty(obj, Symbol.toStringTag, desc); return obj; }, toClassDescriptor: function(obj) { var kind = String(obj.kind); if (kind !== 'class') { throw new TypeError( 'A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"' ); } this.disallowProperty(obj, 'key', 'A class descriptor'); this.disallowProperty(obj, 'placement', 'A class descriptor'); this.disallowProperty(obj, 'descriptor', 'A class descriptor'); this.disallowProperty(obj, 'initializer', 'A class descriptor'); this.disallowProperty(obj, 'extras', 'A class descriptor'); var finisher = _optionalCallableProperty(obj, 'finisher'); var elements = this.toElementDescriptors(obj.elements); return { elements: elements, finisher: finisher, }; }, runClassFinishers: function(constructor, finishers) { for (var i = 0; i < finishers.length; i++) { var newConstructor = (0, finishers[i])(constructor); if (newConstructor !== undefined) { if (typeof newConstructor !== 'function') { throw new TypeError('Finishers must return a constructor.'); } constructor = newConstructor; } } return constructor; }, disallowProperty: function(obj, name, objectType) { if (obj[name] !== undefined) { throw new TypeError(objectType + " can't have a ." + name + ' property.'); } }, }; return api; } function _createElementDescriptor(def) { var key = _toPropertyKey(def.key); var descriptor; if (def.kind === 'method') { descriptor = { value: def.value, writable: true, configurable: true, enumerable: false, }; } else if (def.kind === 'get') { descriptor = { get: def.value, configurable: true, enumerable: false, }; } else if (def.kind === 'set') { descriptor = { set: def.value, configurable: true, enumerable: false, }; } else if (def.kind === 'field') { descriptor = { configurable: true, writable: true, enumerable: true, }; } var element = { kind: def.kind === 'field' ? 'field' : 'method', key: key, placement: def.static ? 'static' : def.kind === 'field' ? 'own' : 'prototype', descriptor: descriptor, }; if (def.decorators) element.decorators = def.decorators; if (def.kind === 'field') element.initializer = def.value; return element; } function _coalesceGetterSetter(element, other) { if (element.descriptor.get !== undefined) { other.descriptor.get = element.descriptor.get; } else { other.descriptor.set = element.descriptor.set; } } function _coalesceClassElements(elements) { var newElements = []; var isSameElement = function(other) { return ( other.kind === 'method' && other.key === element.key && other.placement === element.placement ); }; for (var i = 0; i < elements.length; i++) { var element = elements[i]; var other; if (element.kind === 'method' && (other = newElements.find(isSameElement))) { if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { if (_hasDecorators(element) || _hasDecorators(other)) { throw new ReferenceError( 'Duplicated methods (' + element.key + ") can't be decorated." ); } other.descriptor = element.descriptor; } else { if (_hasDecorators(element)) { if (_hasDecorators(other)) { throw new ReferenceError( "Decorators can't be placed on different accessors with for " + 'the same property (' + element.key + ').' ); } other.decorators = element.decorators; } _coalesceGetterSetter(element, other); } } else { newElements.push(element); } } return newElements; } function _hasDecorators(element) { return element.decorators && element.decorators.length; } function _isDataDescriptor(desc) { return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); } function _optionalCallableProperty(obj, name) { var value = obj[name]; if (value !== undefined && typeof value !== 'function') { throw new TypeError("Expected '" + name + "' to be a function"); } return value; } function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError('attempted to get private field on non-instance'); } return fn; } function _classPrivateMethodSet() { throw new TypeError('attempted to reassign private method'); } function _wrapRegExp(re, groups) { _wrapRegExp = function(re, groups) { return new BabelRegExp(re, groups); }; var _RegExp = _wrapNativeSuper(RegExp); var _super = RegExp.prototype; var _groups = new WeakMap(); function BabelRegExp(re, groups) { var _this = _RegExp.call(this, re); _groups.set(_this, groups); return _this; } _inherits(BabelRegExp, _RegExp); BabelRegExp.prototype.exec = function(str) { var result = _super.exec.call(this, str); if (result) result.groups = buildGroups(result, this); return result; }; BabelRegExp.prototype[Symbol.replace] = function(str, substitution) { if (typeof substitution === 'string') { var groups = _groups.get(this); return _super[Symbol.replace].call( this, str, substitution.replace(/\$<([^>]+)>/g, function(_, name) { return '$' + groups[name]; }) ); } else if (typeof substitution === 'function') { var _this = this; return _super[Symbol.replace].call(this, str, function() { var args = []; args.push.apply(args, arguments); if (typeof args[args.length - 1] !== 'object') { args.push(buildGroups(args, _this)); } return substitution.apply(this, args); }); } else { return _super[Symbol.replace].call(this, str, substitution); } }; function buildGroups(result, re) { var g = _groups.get(re); return Object.keys(g).reduce(function(groups, name) { groups[name] = result[g[name]]; return groups; }, Object.create(null)); } return _wrapRegExp.apply(this, arguments); } var arrayRemove = function arrayRemove(arr, index) { return arr.splice(index, 1); }; var run = function run(cb, sync) { if (sync) { cb(); } else if (document.hidden) { Promise.resolve(1).then(cb); } else { setTimeout(cb, 0); } }; var on = function on() { var listeners = []; var off = function off(event, cb) { arrayRemove( listeners, listeners.findIndex(function(listener) { return listener.event === event && (listener.cb === cb || !cb); }) ); }; var _fire = function fire(event, args, sync) { listeners .filter(function(listener) { return listener.event === event; }) .map(function(listener) { return listener.cb; }) .forEach(function(cb) { return run(function() { return cb.apply(void 0, _toConsumableArray(args)); }, sync); }); }; return { fireSync: function fireSync(event) { for ( var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ ) { args[_key - 1] = arguments[_key]; } _fire(event, args, true); }, fire: function fire(event) { for ( var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++ ) { args[_key2 - 1] = arguments[_key2]; } _fire(event, args, false); }, on: function on(event, cb) { listeners.push({ event: event, cb: cb }); }, onOnce: function onOnce(event, _cb) { listeners.push({ event: event, cb: function cb() { off(event, _cb); _cb.apply(void 0, arguments); }, }); }, off: off, }; }; var copyObjectPropertiesToObject = function copyObjectPropertiesToObject( src, target, excluded ) { Object.getOwnPropertyNames(src) .filter(function(property) { return !excluded.includes(property); }) .forEach(function(key) { return Object.defineProperty( target, key, Object.getOwnPropertyDescriptor(src, key) ); }); }; var PRIVATE = [ 'fire', 'process', 'revert', 'load', 'on', 'off', 'onOnce', 'retryLoad', 'extend', 'archive', 'archived', 'release', 'released', 'requestProcessing', 'freeze', ]; var createItemAPI = function createItemAPI(item) { var api = {}; copyObjectPropertiesToObject(item, api, PRIVATE); return api; }; var removeReleasedItems = function removeReleasedItems(items) { items.forEach(function(item, index) { if (item.released) { arrayRemove(items, index); } }); }; var ItemStatus = { INIT: 1, IDLE: 2, PROCESSING_QUEUED: 9, PROCESSING: 3, PROCESSING_COMPLETE: 5, PROCESSING_ERROR: 6, PROCESSING_REVERT_ERROR: 10, LOADING: 7, LOAD_ERROR: 8, }; var FileOrigin = { INPUT: 1, LIMBO: 2, LOCAL: 3, }; var getNonNumeric = function getNonNumeric(str) { return /[^0-9]+/.exec(str); }; var getDecimalSeparator = function getDecimalSeparator() { return getNonNumeric((1.1).toLocaleString())[0]; }; var getThousandsSeparator = function getThousandsSeparator() { // Added for browsers that do not return the thousands separator (happend on native browser Android 4.4.4) // We check against the normal toString output and if they're the same return a comma when decimal separator is a dot var decimalSeparator = getDecimalSeparator(); var thousandsStringWithSeparator = (1000.0).toLocaleString(); var thousandsStringWithoutSeparator = (1000.0).toString(); if (thousandsStringWithSeparator !== thousandsStringWithoutSeparator) { return getNonNumeric(thousandsStringWithSeparator)[0]; } return decimalSeparator === '.' ? ',' : '.'; }; var Type = { BOOLEAN: 'boolean', INT: 'int', NUMBER: 'number', STRING: 'string', ARRAY: 'array', OBJECT: 'object', FUNCTION: 'function', ACTION: 'action', SERVER_API: 'serverapi', REGEX: 'regex', }; // all registered filters var filters = []; // loops over matching filters and passes options to each filter, returning the mapped results var applyFilterChain = function applyFilterChain(key, value, utils) { return new Promise(function(resolve, reject) { // find matching filters for this key var matchingFilters = filters .filter(function(f) { return f.key === key; }) .map(function(f) { return f.cb; }); // resolve now if (matchingFilters.length === 0) { resolve(value); return; } // first filter to kick things of var initialFilter = matchingFilters.shift(); // chain filters matchingFilters .reduce( // loop over promises passing value to next promise function(current, next) { return current.then(function(value) { return next(value, utils); }); }, // call initial filter, will return a promise initialFilter(value, utils) // all executed ) .then(function(value) { return resolve(value); }) .catch(function(error) { return reject(error); }); }); }; var applyFilters = function applyFilters(key, value, utils) { return filters .filter(function(f) { return f.key === key; }) .map(function(f) { return f.cb(value, utils); }); }; // adds a new filter to the list var addFilter = function addFilter(key, cb) { return filters.push({ key: key, cb: cb }); }; var extendDefaultOptions = function extendDefaultOptions(additionalOptions) { return Object.assign(defaultOptions, additionalOptions); }; var getOptions = function getOptions() { return Object.assign({}, defaultOptions); }; var setOptions = function setOptions(opts) { forin(opts, function(key, value) { // key does not exist, so this option cannot be set if (!defaultOptions[key]) { return; } defaultOptions[key][0] = getValueByType( value, defaultOptions[key][0], defaultOptions[key][1] ); }); }; // default options on app var defaultOptions = { // the id to add to the root element id: [null, Type.STRING], // input field name to use name: ['filepond', Type.STRING], // disable the field disabled: [false, Type.BOOLEAN], // classname to put on wrapper className: [null, Type.STRING], // is the field required required: [false, Type.BOOLEAN], // Allow media capture when value is set captureMethod: [null, Type.STRING], // - "camera", "microphone" or "camcorder", // - Does not work with multiple on apple devices // - If set, acceptedFileTypes must be made to match with media wildcard "image/*", "audio/*" or "video/*" // sync `acceptedFileTypes` property with `accept` attribute allowSyncAcceptAttribute: [true, Type.BOOLEAN], // Feature toggles allowDrop: [true, Type.BOOLEAN], // Allow dropping of files allowBrowse: [true, Type.BOOLEAN], // Allow browsing the file system allowPaste: [true, Type.BOOLEAN], // Allow pasting files allowMultiple: [false, Type.BOOLEAN], // Allow multiple files (disabled by default, as multiple attribute is also required on input to allow multiple) allowReplace: [true, Type.BOOLEAN], // Allow dropping a file on other file to replace it (only works when multiple is set to false) allowRevert: [true, Type.BOOLEAN], // Allows user to revert file upload allowRemove: [true, Type.BOOLEAN], // Allow user to remove a file allowProcess: [true, Type.BOOLEAN], // Allows user to process a file, when set to false, this removes the file upload button allowReorder: [false, Type.BOOLEAN], // Allow reordering of files allowDirectoriesOnly: [false, Type.BOOLEAN], // Allow only selecting directories with browse (no support for filtering dnd at this point) // Revert mode forceRevert: [false, Type.BOOLEAN], // Set to 'force' to require the file to be reverted before removal // Input requirements maxFiles: [null, Type.INT], // Max number of files checkValidity: [false, Type.BOOLEAN], // Enables custom validity messages // Where to put file itemInsertLocationFreedom: [true, Type.BOOLEAN], // Set to false to always add items to begin or end of list itemInsertLocation: ['before', Type.STRING], // Default index in list to add items that have been dropped at the top of the list itemInsertInterval: [75, Type.INT], // Drag 'n Drop related dropOnPage: [false, Type.BOOLEAN], // Allow dropping of files anywhere on page (prevents browser from opening file if dropped outside of Up) dropOnElement: [true, Type.BOOLEAN], // Drop needs to happen on element (set to false to also load drops outside of Up) dropValidation: [false, Type.BOOLEAN], // Enable or disable validating files on drop ignoredFiles: [['.ds_store', 'thumbs.db', 'desktop.ini'], Type.ARRAY], // Upload related instantUpload: [true, Type.BOOLEAN], // Should upload files immediately on drop maxParallelUploads: [2, Type.INT], // Maximum files to upload in parallel // Chunks chunkUploads: [false, Type.BOOLEAN], // Enable chunked uploads chunkForce: [false, Type.BOOLEAN], // Force use of chunk uploads even for files smaller than chunk size chunkSize: [5000000, Type.INT], // Size of chunks (5MB default) chunkRetryDelays: [[500, 1000, 3000], Type.ARRAY], // Amount of times to retry upload of a chunk when it fails // The server api end points to use for uploading (see docs) server: [null, Type.SERVER_API], // File size calculations, can set to 1024, this is only used for display, properties use file size base 1000 fileSizeBase: [1000, Type.INT], // Labels and status messages labelDecimalSeparator: [getDecimalSeparator(), Type.STRING], // Default is locale separator labelThousandsSeparator: [getThousandsSeparator(), Type.STRING], // Default is locale separator labelIdle: [ 'Drag & Drop your files or <span class="filepond--label-action">Browse</span>', Type.STRING, ], labelInvalidField: ['Field contains invalid files', Type.STRING], labelFileWaitingForSize: ['Waiting for size', Type.STRING], labelFileSizeNotAvailable: ['Size not available', Type.STRING], labelFileCountSingular: ['file in list', Type.STRING], labelFileCountPlural: ['files in list', Type.STRING], labelFileLoading: ['Loading', Type.STRING], labelFileAdded: ['Added', Type.STRING], // assistive only labelFileLoadError: ['Error during load', Type.STRING], labelFileRemoved: ['Removed', Type.STRING], // assistive only labelFileRemoveError: ['Error during remove', Type.STRING], labelFileProcessing: ['Uploading', Type.STRING], labelFileProcessingComplete: ['Upload complete', Type.STRING], labelFileProcessingAborted: ['Upload cancelled', Type.STRING], labelFileProcessingError: ['Error during upload', Type.STRING], labelFileProcessingRevertError: ['Error during revert', Type.STRING], labelTapToCancel: ['tap to cancel', Type.STRING], labelTapToRetry: ['tap to retry', Type.STRING], labelTapToUndo: ['tap to undo', Type.STRING], labelButtonRemoveItem: ['Remove', Type.STRING], labelButtonAbortItemLoad: ['Abort', Type.STRING], labelButtonRetryItemLoad: ['Retry', Type.STRING], labelButtonAbortItemProcessing: ['Cancel', Type.STRING], labelButtonUndoItemProcessing: ['Undo', Type.STRING], labelButtonRetryItemProcessing: ['Retry', Type.STRING], labelButtonProcessItem: ['Upload', Type.STRING], // make sure width and height plus viewpox are even numbers so icons are nicely centered iconRemove: [ '<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M11.586 13l-2.293 2.293a1 1 0 0 0 1.414 1.414L13 14.414l2.293 2.293a1 1 0 0 0 1.414-1.414L14.414 13l2.293-2.293a1 1 0 0 0-1.414-1.414L13 11.586l-2.293-2.293a1 1 0 0 0-1.414 1.414L11.586 13z" fill="currentColor" fill-rule="nonzero"/></svg>', Type.STRING, ], iconProcess: [ '<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M14 10.414v3.585a1 1 0 0 1-2 0v-3.585l-1.293 1.293a1 1 0 0 1-1.414-1.415l3-3a1 1 0 0 1 1.414 0l3 3a1 1 0 0 1-1.414 1.415L14 10.414zM9 18a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2H9z" fill="currentColor" fill-rule="evenodd"/></svg>', Type.STRING, ], iconRetry: [ '<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M10.81 9.185l-.038.02A4.997 4.997 0 0 0 8 13.683a5 5 0 0 0 5 5 5 5 0 0 0 5-5 1 1 0 0 1 2 0A7 7 0 1 1 9.722 7.496l-.842-.21a.999.999 0 1 1 .484-1.94l3.23.806c.535.133.86.675.73 1.21l-.804 3.233a.997.997 0 0 1-1.21.73.997.997 0 0 1-.73-1.21l.23-.928v-.002z" fill="currentColor" fill-rule="nonzero"/></svg>', Type.STRING, ], iconUndo: [ '<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M9.185 10.81l.02-.038A4.997 4.997 0 0 1 13.683 8a5 5 0 0 1 5 5 5 5 0 0 1-5 5 1 1 0 0 0 0 2A7 7 0 1 0 7.496 9.722l-.21-.842a.999.999 0 1 0-1.94.484l.806 3.23c.133.535.675.86 1.21.73l3.233-.803a.997.997 0 0 0 .73-1.21.997.997 0 0 0-1.21-.73l-.928.23-.002-.001z" fill="currentColor" fill-rule="nonzero"/></svg>', Type.STRING, ], iconDone: [ '<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M18.293 9.293a1 1 0 0 1 1.414 1.414l-7.002 7a1 1 0 0 1-1.414 0l-3.998-4a1 1 0 1 1 1.414-1.414L12 15.586l6.294-6.293z" fill="currentColor" fill-rule="nonzero"/></svg>', Type.STRING, ], // event handlers oninit: [null, Type.FUNCTION], onwarning: [null, Type.FUNCTION], onerror: [null, Type.FUNCTION], onactivatefile: [null, Type.FUNCTION], oninitfile: [null, Type.FUNCTION], onaddfilestart: [null, Type.FUNCTION], onaddfileprogress: [null, Type.FUNCTION], onaddfile: [null, Type.FUNCTION], onprocessfilestart: [null, Type.FUNCTION], onprocessfileprogress: [null, Type.FUNCTION], onprocessfileabort: [null, Type.FUNCTION], onprocessfilerevert: [null, Type.FUNCTION], onprocessfile: [null, Type.FUNCTION], onprocessfiles: [null, Type.FUNCTION], onremovefile: [null, Type.FUNCTION], onpreparefile: [null, Type.FUNCTION], onupdatefiles: [null, Type.FUNCTION], onreorderfiles: [null, Type.FUNCTION], // hooks beforeDropFile: [null, Type.FUNCTION], beforeAddFile: [null, Type.FUNCTION], beforeRemoveFile: [null, Type.FUNCTION], beforePrepareFile: [null, Type.FUNCTION], // styles stylePanelLayout: [null, Type.STRING], // null 'integrated', 'compact', 'circle' stylePanelAspectRatio: [null, Type.STRING], // null or '3:2' or 1 styleItemPanelAspectRatio: [null, Type.STRING], styleButtonRemoveItemPosition: ['left', Type.STRING], styleButtonProcessItemPosition: ['right', Type.STRING], styleLoadIndicatorPosition: ['right', Type.STRING], styleProgressIndicatorPosition: ['right', Type.STRING], styleButtonRemoveItemAlign: [false, Type.BOOLEAN], // custom initial files array files: [[], Type.ARRAY], // show support by displaying credits credits: [['https://pqina.nl/', 'Powered by PQINA'], Type.ARRAY], }; var getItemByQuery = function getItemByQuery(items, query) { // just return first index if (isEmpty(query)) { return items[0] || null; } // query is index if (isInt(query)) { return items[query] || null; } // if query is item, get the id if (typeof query === 'object') { query = query.id; } // assume query is a string and return item by id return ( items.find(function(item) { return item.id === query; }) || null ); }; var getNumericAspectRatioFromString = function getNumericAspectRatioFromString(aspectRatio) { if (isEmpty(aspectRatio)) { return aspectRatio; } if (/:/.test(aspectRatio)) { var parts = aspectRatio.split(':'); return parts[1] / parts[0]; } return parseFloat(aspectRatio); }; var getActiveItems = function getActiveItems(items) { return items.filter(function(item) { return !item.archived; }); }; var Status = { EMPTY: 0, IDLE: 1, // waiting ERROR: 2, // a file is in error state BUSY: 3, // busy processing or loading READY: 4, // all files uploaded }; var ITEM_ERROR = [ ItemStatus.LOAD_ERROR, ItemStatus.PROCESSING_ERROR, ItemStatus.PROCESSING_REVERT_ERROR, ]; var ITEM_BUSY = [ ItemStatus.LOADING, ItemStatus.PROCESSING, ItemStatus.PROCESSING_QUEUED, ItemStatus.INIT, ]; var ITEM_READY = [ItemStatus.PROCESSING_COMPLETE]; var isItemInErrorState = function isItemInErrorState(item) { return ITEM_ERROR.includes(item.status); }; var isItemInBusyState = function isItemInBusyState(item) { return ITEM_BUSY.includes(item.status); }; var isItemInReadyState = function isItemInReadyState(item) { return ITEM_READY.includes(item.status); }; var queries = function queries(state) { return { GET_STATUS: function GET_STATUS() { var items = getActiveItems(state.items); var EMPTY = Status.EMPTY, ERROR = Status.ERROR, BUSY = Status.BUSY, IDLE = Status.IDLE, READY = Status.READY; if (items.length === 0) return EMPTY; if (items.some(isItemInErrorState)) return ERROR; if (items.some(isItemInBusyState)) return BUSY; if (items.some(isItemInReadyState)) return READY; return IDLE; }, GET_ITEM: function GET_ITEM(query) { return getItemByQuery(state.items, query); }, GET_ACTIVE_ITEM: function GET_ACTIVE_ITEM(query) { return getItemByQuery(getActiveItems(state.items), query); }, GET_ACTIVE_ITEMS: function GET_ACTIVE_ITEMS() { return getActiveItems(state.items); }, GET_ITEMS: function GET_ITEMS() { return state.items; }, GET_ITEM_NAME: function GET_ITEM_NAME(query) { var item = getItemByQuery(state.items, query); return item ? item.filename : null; }, GET_ITEM_SIZE: function GET_ITEM_SIZE(query) { var item = getItemByQuery(state.items, query); return item ? item.fileSize : null; }, GET_STYLES: function GET_STYLES() { return Object.keys(state.options) .filter(function(key) { return /^style/.test(key); }) .map(function(option) { return { name: option, value: state.options[option], }; }); }, GET_PANEL_ASPECT_RATIO: function GET_PANEL_ASPECT_RATIO() { var isShapeCircle = /circle/.test(state.options.stylePanelLayout); var aspectRatio = isShapeCircle ? 1 : getNumericAspectRatioFromString(state.options.stylePanelAspectRatio); return aspectRatio; }, GET_ITEM_PANEL_ASPECT_RATIO: function GET_ITEM_PANEL_ASPECT_RATIO() { return state.options.styleItemPanelAspectRatio; }, GET_ITEMS_BY_STATUS: function GET_ITEMS_BY_STATUS(status) { return getActiveItems(state.items).filter(function(item) { return item.status === status; }); }, GET_TOTAL_ITEMS: function GET_TOTAL_ITEMS() { return getActiveItems(state.items).length; }, IS_ASYNC: function IS_ASYNC() { return ( isObject(state.options.server) && (isObject(state.options.server.process) || isFunction(state.options.server.process)) ); }, }; }; var hasRoomForItem = function hasRoomForItem(state) { var count = getActiveItems(state.items).length; // if cannot have multiple items, to add one item it should currently not contain items if (!state.options.allowMultiple) { return count === 0; } // if allows multiple items, we check if a max item count has been set, if not, there's no limit var maxFileCount = state.options.maxFiles; if (maxFileCount === null) { return true; } // we check if the current count is smaller than the max count, if so, another file can still be added if (count < maxFileCount) { return true; } // no more room for another file return false; }; var limit = function limit(value, min, max) { return Math.max(Math.min(max, value), min); }; var arrayInsert = function arrayInsert(arr, index, item) { return arr.splice(index, 0, item); }; var insertItem = function insertItem(items, item, index) { if (isEmpty(item)) { return null; } // if index is undefined, append if (typeof index === 'undefined') { items.push(item); return item; } // limit the index to the size of the items array index = limit(index, 0, items.length); // add item to array arrayInsert(items, index, item); // expose return item; }; var isBase64DataURI = function isBase64DataURI(str) { return /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*)\s*$/i.test( str ); }; var getFilenameFromURL = function getFilenameFromURL(url) { return url .split('/') .pop() .split('?') .shift(); }; var getExtensionFromFilename = function getExtensionFromFilename(name) { return name.split('.').pop(); }; var guesstimateExtension = function guesstimateExtension(type) { // if no extension supplied, exit here if (typeof type !== 'string') { return ''; } // get subtype var subtype = type.split('/').pop(); // is svg subtype if (/svg/.test(subtype)) { return 'svg'; } if (/zip|compressed/.test(subtype)) { return 'zip'; } if (/plain/.test(subtype)) { return 'txt'; } if (/msword/.test(subtype)) { return 'doc'; } // if is valid subtype if (/[a-z]+/.test(subtype)) { // always use jpg extension if (subtype === 'jpeg') { return 'jpg'; } // return subtype return subtype; } return ''; }; var leftPad = function leftPad(value) { var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; return (padding + value).slice(-padding.length); }; var getDateString = function getDateString() { var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); return ( date.getFullYear() + '-' + leftPad(date.getMonth() + 1, '00') + '-' + leftPad(date.getDate(), '00') + '_' + leftPad(date.getHours(), '00') + '-' + leftPad(date.getMinutes(), '00') + '-' + leftPad(date.getSeconds(), '00') ); }; var getFileFromBlob = function getFileFromBlob(blob, filename) { var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var extension = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var file = typeof type === 'string' ? blob.slice(0, blob.size, type) : blob.slice(0, blob.size, blob.type); file.lastModifiedDate = new Date(); // copy relative path if (blob._relativePath) file._relativePath = blob._relativePath; // if blob has name property, use as filename if no filename supplied if (!isString(filename)) { filename = getDateString(); } // if filename supplied but no extension and filename has extension if (filename && extension === null && getExtensionFromFilename(filename)) { file.name = filename; } else { extension = extension || guesstimateExtension(file.type); file.name = filename + (extension ? '.' + extension : ''); } return file; }; var getBlobBuilder = function getBlobBuilder() { return (window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder); }; var createBlob = function createBlob(arrayBuffer, mimeType) { var BB = getBlobBuilder(); if (BB) { var bb = new BB(); bb.append(arrayBuffer); return bb.getBlob(mimeType); } return new Blob([arrayBuffer], { type: mimeType, }); }; var getBlobFromByteStringWithMimeType = function getBlobFromByteStringWithMimeType( byteString, mimeType ) { var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return createBlob(ab, mimeType); }; var getMimeTypeFromBase64DataURI = function getMimeTypeFromBase64DataURI(dataURI) { return (/^data:(.+);/.exec(dataURI) || [])[1] || null; }; var getBase64DataFromBase64DataURI = function getBase64DataFromBase64DataURI(dataURI) { // get data part of string (remove data:image/jpeg...,) var data = dataURI.split(',')[1]; // remove any whitespace as that causes InvalidCharacterError in IE return data.replace(/\s/g, ''); }; var getByteStringFromBase64DataURI = function getByteStringFromBase64DataURI(dataURI) { return atob(getBase64DataFromBase64DataURI(dataURI)); }; var getBlobFromBase64DataURI = function getBlobFromBase64DataURI(dataURI) { var mimeType = getMimeTypeFromBase64DataURI(dataURI); var byteString = getByteStringFromBase64DataURI(dataURI); return getBlobFromByteStringWithMimeType(byteString, mimeType); }; var getFileFromBase64DataURI = function getFileFromBase64DataURI(dataURI, filename, extension) { return getFileFromBlob(getBlobFromBase64DataURI(dataURI), filename, null, extension); }; var getFileNameFromHeader = function getFileNameFromHeader(header) { // test if is content disposition header, if not exit if (!/^content-disposition:/i.test(header)) return null; // get filename parts var matches = header .split(/filename=|filename\*=.+''/) .splice(1) .map(function(name) { return name.trim().replace(/^["']|[;"']{0,2}$/g, ''); }) .filter(function(name) { return name.length; }); return matches.length ? decodeURI(matches[matches.length - 1]) : null; }; var getFileSizeFromHeader = function getFileSizeFromHeader(header) { if (/content-length:/i.test(header)) { var size = header.match(/[0-9]+/)[0]; return size ? parseInt(size, 10) : null; } return null; }; var getTranfserIdFromHeader = function getTranfserIdFromHeader(header) { if (/x-content-transfer-id:/i.test(header)) { var id = (header.split(':')[1] || '').trim(); return id || null; } return null; }; var getFileInfoFromHeaders = function getFileInfoFromHeaders(headers) { var info = { source: null, name: null, size: null, }; var rows = headers.split('\n'); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for ( var _iterator = rows[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true ) { var header = _step.value; var name = getFileNameFromHeader(header); if (name) { info.name = name; continue; } var size = getFileSizeFromHeader(header); if (size) { info.size = size; continue; } var source = getTranfserIdFromHeader(header); if (source) { info.source = source; continue; } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return info; }; var createFileLoader = function createFileLoader(fetchFn) { var state = { source: null, complete: false, progress: 0, size: null, timestamp: null, duration: 0, request: null, }; var getProgress = function getProgress() { return state.progress; }; var abort = function abort() { if (state.request && state.request.abort) { state.request.abort(); } }; // load source var load = function load() { // get quick reference var source = state.source; api.fire('init', source); // Load Files if (source instanceof File) { api.fire('load', source); } else if (source instanceof Blob) { // Load blobs, set default name to current date api.fire('load', getFileFromBlob(source, source.name)); } else if (isBase64DataURI(source)) { // Load base 64, set default name to current date api.fire('load', getFileFromBase64DataURI(source)); } else { // Deal as if is external URL, let's load it! loadURL(source); } }; // loads a url var loadURL = function loadURL(url) { // is remote url and no fetch method supplied if (!fetchFn) { api.fire('error', { type: 'error', body: "Can't load URL", code: 400, }); return; } // set request start state.timestamp = Date.now(); // load file state.request = fetchFn( url, function(response) { // update duration state.duration = Date.now() - state.timestamp; // done! state.complete = true; // turn blob response into a file if (response instanceof Blob) { response = getFileFromBlob( response, response.name || getFilenameFromURL(url) ); } api.fire( 'load', // if has received blob, we go with blob, if no response, we return null response instanceof Blob ? response : response ? response.body : null ); }, function(error) { api.fire( 'error', typeof error === 'string' ? { type: 'error', code: 0, body: error, } : error ); }, function(computable, current, total) { // collected some meta data already if (total) { state.size = total; } // update duration state.duration = Date.now() - state.timestamp; // if we can't compute progress, we're not going to fire progress events if (!computable) { state.progress = null; return; } // update progress percentage state.progress = current / total; // expose api.fire('progress', state.progress); }, function() { api.fire('abort'); }, function(response) { var fileinfo = getFileInfoFromHeaders( typeof response === 'string' ? response : response.headers ); api.fire('meta', { size: state.size || fileinfo.size, filename: fileinfo.name, source: fileinfo.source, }); } ); }; var api = Object.assign({}, on(), { setSource: function setSource(source) { return (state.source = source); }, getProgress: getProgress, // file load progress abort: abort, // abort file load load: load, // start load }); return api; }; var isGet = function isGet(method) { return /GET|HEAD/.test(method); }; var sendRequest = function sendRequest(data, url, options) { var api = { onheaders: function onheaders() {}, onprogress: function onprogress() {}, onload: function onload() {}, ontimeout: function ontimeout() {}, onerror: function onerror() {}, onabort: function onabort() {}, abort: function abort() { aborted = true; xhr.abort(); }, }; // timeout identifier, only used when timeout is defined var aborted = false; var headersReceived = false; // set default options options = Object.assign( { method: 'POST', headers: {}, withCredentials: false, }, options ); // encode url url = encodeURI(url); // if method is GET, add any received data to url if (isGet(options.method) && data) { url = '' + url + encodeURIComponent(typeof data === 'string' ? data : JSON.stringify(data)); } // create request var xhr = new XMLHttpRequest(); // progress of load var process = isGet(options.method) ? xhr : xhr.upload; process.onprogress = function(e) { // no progress event when aborted ( onprogress is called once after abort() ) if (aborted) { return; } api.onprogress(e.lengthComputable, e.loaded, e.total); }; // tries to get header info to the app as fast as possible xhr.onreadystatechange = function() { // not interesting in these states ('unsent' and 'openend' as they don't give us any additional info) if (xhr.readyState < 2) { return; } // no server response if (xhr.readyState === 4 && xhr.status === 0) { return; } if (headersReceived) { return; } headersReceived = true; // we've probably received some useful data in response headers api.onheaders(xhr); }; // load successful xhr.onload = function() { // is classified as valid response if (xhr.status >= 200 && xhr.status < 300) { api.onload(xhr); } else { api.onerror(xhr); } }; // error during load xhr.onerror = function() { return api.onerror(xhr); }; // request aborted xhr.onabort = function() { aborted = true; api.onabort(); }; // request timeout xhr.ontimeout = function() { return api.ontimeout(xhr); }; // open up open up! xhr.open(options.method, url, true); // set timeout if defined (do it after open so IE11 plays ball) if (isInt(options.timeout)) { xhr.timeout = options.timeout; } // add headers Object.keys(options.headers).forEach(function(key) { var value = unescape(encodeURIComponent(options.headers[key])); xhr.setRequestHeader(key, value); }); // set type of response if (options.responseType) { xhr.responseType = options.responseType; } // set credentials if (options.withCredentials) { xhr.withCredentials = true; } // let's send our data xhr.send(data); return api; }; var createResponse = function createResponse(type, code, body, headers) { return { type: type, code: code, body: body, headers: headers, }; }; var createTimeoutResponse = function createTimeoutResponse(cb) { return function(xhr) { cb(createResponse('error', 0, 'Timeout', xhr.getAllResponseHeaders())); }; }; var hasQS = function hasQS(str) { return /\?/.test(str); }; var buildURL = function buildURL() { var url = ''; for (var _len = arguments.length, parts = new Array(_len), _key = 0; _key < _len; _key++) { parts[_key] = arguments[_key]; } parts.forEach(function(part) { url += hasQS(url) && hasQS(part) ? part.replace(/\?/, '&') : part; }); return url; }; var createFetchFunction = function createFetchFunction() { var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var action = arguments.length > 1 ? arguments[1] : undefined; // custom handler (should also handle file, load, error, progress and abort) if (typeof action === 'function') { return action; } // no action supplied if (!action || !isString(action.url)) { return null; } // set onload hanlder var onload = action.onload || function(res) { return res; }; var onerror = action.onerror || function(res) { return null; }; // internal handler return function(url, load, error, progress, abort, headers) { // do local or remote request based on if the url is external var request = sendRequest( url, buildURL(apiUrl, action.url), Object.assign({}, action, { responseType: 'blob', }) ); request.onload = function(xhr) { // get headers var headers = xhr.getAllResponseHeaders(); // get filename var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url); // create response load( createResponse( 'load', xhr.status, action.method === 'HEAD' ? null : getFileFromBlob(onload(xhr.response), filename), headers ) ); }; request.onerror = function(xhr) { error( createResponse( 'error', xhr.status, onerror(xhr.response) || xhr.statusText, xhr.getAllResponseHeaders() ) ); }; request.onheaders = function(xhr) { headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders())); }; request.ontimeout = createTimeoutResponse(error); request.onprogress = progress; request.onabort = abort; // should return request return request; }; }; var ChunkStatus = { QUEUED: 0, COMPLETE: 1, PROCESSING: 2, ERROR: 3, WAITING: 4, }; /* function signature: (file, metadata, load, error, progress, abort, transfer, options) => { return { abort:() => {} } } */ // apiUrl, action, name, file, metadata, load, error, progress, abort, transfer, options var processFileChunked = function processFileChunked( apiUrl, action, name, file, metadata, load, error, progress, abort, transfer, options ) { // all chunks var chunks = []; var chunkTransferId = options.chunkTransferId, chunkServer = options.chunkServer, chunkSize = options.chunkSize, chunkRetryDelays = options.chunkRetryDelays; // default state var state = { serverId: chunkTransferId, aborted: false, }; // set onload handlers var ondata = action.ondata || function(fd) { return fd; }; var onload = action.onload || function(xhr, method) { return method === 'HEAD' ? xhr.getResponseHeader('Upload-Offset') : xhr.response; }; var onerror = action.onerror || function(res) { return null; }; // create server hook var requestTransferId = function requestTransferId(cb) { var formData = new FormData(); // add metadata under same name if (isObject(metadata)) formData.append(name, JSON.stringify(metadata)); var headers = typeof action.headers === 'function' ? action.headers(file, metadata) : Object.assign({}, action.headers, { 'Upload-Length': file.size, }); var requestParams = Object.assign({}, action, { headers: headers, }); // send request object var request = sendRequest( ondata(formData), buildURL(apiUrl, action.url), requestParams ); request.onload = function(xhr) { return cb(onload(xhr, requestParams.method)); }; request.onerror = function(xhr) { return error( createResponse( 'error', xhr.status, onerror(xhr.response) || xhr.statusText, xhr.getAllResponseHeaders() ) ); }; request.ontimeout = createTimeoutResponse(error); }; var requestTransferOffset = function requestTransferOffset(cb) { var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId); var headers = typeof action.headers === 'function' ? action.headers(state.serverId) : Object.assign({}, action.headers); var requestParams = { headers: headers, method: 'HEAD', }; var request = sendRequest(null, requestUrl, requestParams); request.onload = function(xhr) { return cb(onload(xhr, requestParams.method)); }; request.onerror = function(xhr) { return error( createResponse( 'error', xhr.status, onerror(xhr.response) || xhr.statusText, xhr.getAllResponseHeaders() ) ); }; request.ontimeout = createTimeoutResponse(error); }; // create chunks var lastChunkIndex = Math.floor(file.size / chunkSize); for (var i = 0; i <= lastChunkIndex; i++) { var offset = i * chunkSize; var data = file.slice(offset, offset + chunkSize, 'application/offset+octet-stream'); chunks[i] = { index: i, size: data.size, offset: offset, data: data, file: file, progress: 0, retries: _toConsumableArray(chunkRetryDelays), status: ChunkStatus.QUEUED, error: null, request: null, timeout: null, }; } var completeProcessingChunks = function completeProcessingChunks() { return load(state.serverId); }; var canProcessChunk = function canProcessChunk(chunk) { return chunk.status === ChunkStatus.QUEUED || chunk.status === ChunkStatus.ERROR; }; var processChunk = function processChunk(chunk) { // processing is paused, wait here if (state.aborted) return; // get next chunk to process chunk = chunk || chunks.find(canProcessChunk); // no more chunks to process if (!chunk) { // all done? if ( chunks.every(function(chunk) { return chunk.status === ChunkStatus.COMPLETE; }) ) { completeProcessingChunks(); } // no chunk to handle return; } // now processing this chunk chunk.status = ChunkStatus.PROCESSING; chunk.progress = null; // allow parsing of formdata var ondata = chunkServer.ondata || function(fd) { return fd; }; var onerror = chunkServer.onerror || function(res) { return null; }; // send request object var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId); var headers = typeof chunkServer.headers === 'function' ? chunkServer.headers(chunk) : Object.assign({}, chunkServer.headers, { 'Content-Type': 'application/offset+octet-stream', 'Upload-Offset': chunk.offset, 'Upload-Length': file.size, 'Upload-Name': file.name, }); var request = (chunk.request = sendRequest( ondata(chunk.data), requestUrl, Object.assign({}, chunkServer, { headers: headers, }) )); request.onload = function() { // done! chunk.status = ChunkStatus.COMPLETE; // remove request reference chunk.request = null; // start processing more chunks processChunks(); }; request.onprogress = function(lengthComputable, loaded, total) { chunk.progress = lengthComputable ? loaded : null; updateTotalProgress(); }; request.onerror = function(xhr) { chunk.status = ChunkStatus.ERROR; chunk.request = null; chunk.error = onerror(xhr.response) || xhr.statusText; if (!retryProcessChunk(chunk)) { error( createResponse( 'error', xhr.status, onerror(xhr.response) || xhr.statusText, xhr.getAllResponseHeaders() ) ); } }; request.ontimeout = function(xhr) { chunk.status = ChunkStatus.ERROR; chunk.request = null; if (!retryProcessChunk(chunk)) { createTimeoutResponse(error)(xhr); } }; request.onabort = function() { chunk.status = ChunkStatus.QUEUED; chunk.request = null; abort(); }; }; var retryProcessChunk = function retryProcessChunk(chunk) { // no more retries left if (chunk.retries.length === 0) return false; // new retry chunk.status = ChunkStatus.WAITING; clearTimeout(chunk.timeout); chunk.timeout = setTimeout(function() { processChunk(chunk); }, chunk.retries.shift()); // we're going to retry return true; }; var updateTotalProgress = function updateTotalProgress() { // calculate total progress fraction var totalBytesTransfered = chunks.reduce(function(p, chunk) { if (p === null || chunk.progress === null) return null; return p + chunk.progress; }, 0); // can't compute progress if (totalBytesTransfered === null) return progress(false, 0, 0); // calculate progress values var totalSize = chunks.reduce(function(total, chunk) { return total + chunk.size; }, 0); // can update progress indicator progress(true, totalBytesTransfered, totalSize); }; // process new chunks var processChunks = function processChunks() { var totalProcessing = chunks.filter(function(chunk) { return chunk.status === ChunkStatus.PROCESSING; }).length; if (totalProcessing >= 1) return; processChunk(); }; var abortChunks = function abortChunks() { chunks.forEach(function(chunk) { clearTimeout(chunk.timeout); if (chunk.request) { chunk.request.abort(); } }); }; // let's go! if (!state.serverId) { requestTransferId(function(serverId) { // stop here if aborted, might have happened in between request and callback if (state.aborted) return; // pass back to item so we can use it if something goes wrong transfer(serverId); // store internally state.serverId = serverId; processChunks(); }); } else { requestTransferOffset(function(offset) { // stop here if aborted, might have happened in between request and callback if (state.aborted) return; // mark chunks with lower offset as complete chunks .filter(function(chunk) { return chunk.offset < offset; }) .forEach(function(chunk) { chunk.status = ChunkStatus.COMPLETE; chunk.progress = chunk.size; }); // continue processing processChunks(); }); } return { abort: function abort() { state.aborted = true; abortChunks(); }, }; }; /* function signature: (file, metadata, load, error, progress, abort) => { return { abort:() => {} } } */ var createFileProcessorFunction = function createFileProcessorFunction( apiUrl, action, name, options ) { return function(file, metadata, load, error, progress, abort, transfer) { // no file received if (!file) return; // if was passed a file, and we can chunk it, exit here var canChunkUpload = options.chunkUploads; var shouldChunkUpload = canChunkUpload && file.size > options.chunkSize; var willChunkUpload = canChunkUpload && (shouldChunkUpload || options.chunkForce); if (file instanceof Blob && willChunkUpload) return processFileChunked( apiUrl, action, name, file, metadata, load, error, progress, abort, transfer, options ); // set handlers var ondata = action.ondata || function(fd) { return fd; }; var onload = action.onload || function(res) { return res; }; var onerror = action.onerror || function(res) { return null; }; var headers = typeof action.headers === 'function' ? action.headers(file, metadata) || {} : Object.assign( {}, action.headers ); var requestParams = Object.assign({}, action, { headers: headers, }); // create formdata object var formData = new FormData(); // add metadata under same name if (isObject(metadata)) { formData.append(name, JSON.stringify(metadata)); } // Turn into an array of objects so no matter what the input, we can handle it the same way (file instanceof Blob ? [{ name: null, file: file }] : file).forEach(function(item) { formData.append( name, item.file, item.name === null ? item.file.name : '' + item.name + item.file.name ); }); // send request object var request = sendRequest( ondata(formData), buildURL(apiUrl, action.url), requestParams ); request.onload = function(xhr) { load( createResponse( 'load', xhr.status, onload(xhr.response), xhr.getAllResponseHeaders() ) ); }; request.onerror = function(xhr) { error( createResponse( 'error', xhr.status, onerror(xhr.response) || xhr.statusText, xhr.getAllResponseHeaders() ) ); }; request.ontimeout = createTimeoutResponse(error); request.onprogress = progress; request.onabort = abort; // should return request return request; }; }; var createProcessorFunction = function createProcessorFunction() { var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var action = arguments.length > 1 ? arguments[1] : undefined; var name = arguments.length > 2 ? arguments[2] : undefined; var options = arguments.length > 3 ? arguments[3] : undefined; // custom handler (should also handle file, load, error, progress and abort) if (typeof action === 'function') return function() { for ( var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++ ) { params[_key] = arguments[_key]; } return action.apply(void 0, [name].concat(params, [options])); }; // no action supplied if (!action || !isString(action.url)) return null; // internal handler return createFileProcessorFunction(apiUrl, action, name, options); }; /* function signature: (uniqueFileId, load, error) => { } */ var createRevertFunction = function createRevertFunction() { var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var action = arguments.length > 1 ? arguments[1] : undefined; // is custom implementation if (typeof action === 'function') { return action; } // no action supplied, return stub function, interface will work, but file won't be removed if (!action || !isString(action.url)) { return function(uniqueFileId, load) { return load(); }; } // set onload hanlder var onload = action.onload || function(res) { return res; }; var onerror = action.onerror || function(res) { return null; }; // internal implementation return function(uniqueFileId, load, error) { var request = sendRequest( uniqueFileId, apiUrl + action.url, action // contains method, headers and withCredentials properties ); request.onload = function(xhr) { load( createResponse( 'load', xhr.status, onload(xhr.response), xhr.getAllResponseHeaders() ) ); }; request.onerror = function(xhr) { error( createResponse( 'error', xhr.status, onerror(xhr.response) || xhr.statusText, xhr.getAllResponseHeaders() ) ); }; request.ontimeout = createTimeoutResponse(error); return request; }; }; var getRandomNumber = function getRandomNumber() { var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; return min + Math.random() * (max - min); }; var createPerceivedPerformanceUpdater = function createPerceivedPerformanceUpdater(cb) { var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000; var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var tickMin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 25; var tickMax = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 250; var timeout = null; var start = Date.now(); var tick = function tick() { var runtime = Date.now() - start; var delay = getRandomNumber(tickMin, tickMax); if (runtime + delay > duration) { delay = runtime + delay - duration; } var progress = runtime / duration; if (progress >= 1 || document.hidden) { cb(1); return; } cb(progress); timeout = setTimeout(tick, delay); }; tick(); return { clear: function clear() { clearTimeout(timeout); }, }; }; var createFileProcessor = function createFileProcessor(processFn) { var state = { complete: false, perceivedProgress: 0, perceivedPerformanceUpdater: null, progress: null, timestamp: null, perceivedDuration: 0, duration: 0, request: null, response: null, }; var process = function process(file, metadata) { var progressFn = function progressFn() { // we've not yet started the real download, stop here // the request might not go through, for instance, there might be some server trouble // if state.progress is null, the server does not allow computing progress and we show the spinner instead if (state.duration === 0 || state.progress === null) return; // as we're now processing, fire the progress event api.fire('progress', api.getProgress()); }; var completeFn = function completeFn() { state.complete = true; api.fire('load-perceived', state.response.body); }; // let's start processing api.fire('start'); // set request start state.timestamp = Date.now(); // create perceived performance progress indicator state.perceivedPerformanceUpdater = createPerceivedPerformanceUpdater( function(progress) { state.perceivedProgress = progress; state.perceivedDuration = Date.now() - state.timestamp; progressFn(); // if fake progress is done, and a response has been received, // and we've not yet called the complete method if (state.response && state.perceivedProgress === 1 && !state.complete) { // we done! completeFn(); } }, // random delay as in a list of files you start noticing // files uploading at the exact same speed getRandomNumber(750, 1500) ); // remember request so we can abort it later state.request = processFn( // the file to process file, // the metadata to send along metadata, // callbacks (load, error, progress, abort, transfer) // load expects the body to be a server id if // you want to make use of revert function(response) { // we put the response in state so we can access // it outside of this method state.response = isObject(response) ? response : { type: 'load', code: 200, body: '' + response, headers: {}, }; // update duration state.duration = Date.now() - state.timestamp; // force progress to 1 as we're now done state.progress = 1; // actual load is done let's share results api.fire('load', state.response.body); // we are really done // if perceived progress is 1 ( wait for perceived progress to complete ) // or if server does not support progress ( null ) if (state.perceivedProgress === 1) { completeFn(); } }, // error is expected to be an object with type, code, body function(error) { // cancel updater state.perceivedPerformanceUpdater.clear(); // update others about this error api.fire( 'error', isObject(error) ? error : { type: 'error', code: 0, body: '' + error, } ); }, // actual processing progress function(computable, current, total) { // update actual duration state.duration = Date.now() - state.timestamp; // update actual progress state.progress = computable ? current / total : null; progressFn(); }, // abort does not expect a value function() { // stop updater state.perceivedPerformanceUpdater.clear(); // fire the abort event so we can switch visuals api.fire('abort', state.response ? state.response.body : null); }, // register the id for this transfer function(transferId) { api.fire('transfer', transferId); } ); }; var abort = function abort() { // no request running, can't abort if (!state.request) return; // stop updater state.perceivedPerformanceUpdater.clear(); // abort actual request if (state.request.abort) state.request.abort(); // if has response object, we've completed the request state.complete = true; }; var reset = function reset() { abort(); state.complete = false; state.perceivedProgress = 0; state.progress = 0; state.timestamp = null; state.perceivedDuration = 0; state.duration = 0; state.request = null; state.response = null; }; var getProgress = function getProgress() { return state.progress ? Math.min(state.progress, state.perceivedProgress) : null; }; var getDuration = function getDuration() { return Math.min(state.duration, state.perceivedDuration); }; var api = Object.assign({}, on(), { process: process, // start processing file abort: abort, // abort active process request getProgress: getProgress, getDuration: getDuration, reset: reset, }); return api; }; var getFilenameWithoutExtension = function getFilenameWithoutExtension(name) { return name.substr(0, name.lastIndexOf('.')) || name; }; var createFileStub = function createFileStub(source) { var data = [source.name, source.size, source.type]; // is blob or base64, then we need to set the name if (source instanceof Blob || isBase64DataURI(source)) { data[0] = source.name || getDateString(); } else if (isBase64DataURI(source)) { // if is base64 data uri we need to determine the average size and type data[1] = source.length; data[2] = getMimeTypeFromBase64DataURI(source); } else if (isString(source)) { // url data[0] = getFilenameFromURL(source); data[1] = 0; data[2] = 'application/octet-stream'; } return { name: data[0], size: data[1], type: data[2], }; }; var isFile = function isFile(value) { return !!(value instanceof File || (value instanceof Blob && value.name)); }; var deepCloneObject = function deepCloneObject(src) { if (!isObject(src)) return src; var target = isArray(src) ? [] : {}; for (var key in src) { if (!src.hasOwnProperty(key)) continue; var v = src[key]; target[key] = v && isObject(v) ? deepCloneObject(v) : v; } return target; }; var createItem = function createItem() { var origin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var serverFileReference = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var file = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; // unique id for this item, is used to identify the item across views var id = getUniqueId(); /** * Internal item state */ var state = { // is archived archived: false, // if is frozen, no longer fires events frozen: false, // removed from view released: false, // original source source: null, // file model reference file: file, // id of file on server serverFileReference: serverFileReference, // id of file transfer on server transferId: null, // is aborted processingAborted: false, // current item status status: serverFileReference ? ItemStatus.PROCESSING_COMPLETE : ItemStatus.INIT, // active processes activeLoader: null, activeProcessor: null, }; // callback used when abort processing is called to link back to the resolve method var abortProcessingRequestComplete = null; /** * Externally added item metadata */ var metadata = {}; // item data var setStatus = function setStatus(status) { return (state.status = status); }; // fire event unless the item has been archived var fire = function fire(event) { if (state.released || state.frozen) return; for ( var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ ) { params[_key - 1] = arguments[_key]; } api.fire.apply(api, [event].concat(params)); }; // file data var getFileExtension = function getFileExtension() { return getExtensionFromFilename(state.file.name); }; var getFileType = function getFileType() { return state.file.type; }; var getFileSize = function getFileSize() { return state.file.size; }; var getFile = function getFile() { return state.file; }; // // logic to load a file // var load = function load(source, loader, onload) { // remember the original item source state.source = source; // source is known api.fireSync('init'); // file stub is already there if (state.file) { api.fireSync('load-skip'); return; } // set a stub file object while loading the actual data state.file = createFileStub(source); // starts loading loader.on('init', function() { fire('load-init'); }); // we'eve received a size indication, let's update the stub loader.on('meta', function(meta) { // set size of file stub state.file.size = meta.size; // set name of file stub state.file.filename = meta.filename; // if has received source, we done if (meta.source) { origin = FileOrigin.LIMBO; state.serverFileReference = meta.source; state.status = ItemStatus.PROCESSING_COMPLETE; } // size has been updated fire('load-meta'); }); // the file is now loading we need to update the progress indicators loader.on('progress', function(progress) { setStatus(ItemStatus.LOADING); fire('load-progress', progress); }); // an error was thrown while loading the file, we need to switch to error state loader.on('error', function(error) { setStatus(ItemStatus.LOAD_ERROR); fire('load-request-error', error); }); // user or another process aborted the file load (cannot retry) loader.on('abort', function() { setStatus(ItemStatus.INIT); fire('load-abort'); }); // done loading loader.on('load', function(file) { // as we've now loaded the file the loader is no longer required state.activeLoader = null; // called when file has loaded succesfully var success = function success(result) { // set (possibly) transformed file state.file = isFile(result) ? result : state.file; // file received if (origin === FileOrigin.LIMBO && state.serverFileReference) { setStatus(ItemStatus.PROCESSING_COMPLETE); } else { setStatus(ItemStatus.IDLE); } fire('load'); }; var error = function error(result) { // set original file state.file = file; fire('load-meta'); setStatus(ItemStatus.LOAD_ERROR); fire('load-file-error', result); }; // if we already have a server file reference, we don't need to call the onload method if (state.serverFileReference) { success(file); return; } // no server id, let's give this file the full treatment onload(file, success, error); }); // set loader source data loader.setSource(source); // set as active loader state.activeLoader = loader; // load the source data loader.load(); }; var retryLoad = function retryLoad() { if (!state.activeLoader) { return; } state.activeLoader.load(); }; var abortLoad = function abortLoad() { if (state.activeLoader) { state.activeLoader.abort(); return; } setStatus(ItemStatus.INIT); fire('load-abort'); }; // // logic to process a file // var process = function process(processor, onprocess) { // processing was aborted if (state.processingAborted) { state.processingAborted = false; return; } // now processing setStatus(ItemStatus.PROCESSING); // reset abort callback abortProcessingRequestComplete = null; // if no file loaded we'll wait for the load event if (!(state.file instanceof Blob)) { api.on('load', function() { process(processor, onprocess); }); return; } // setup processor processor.on('load', function(serverFileReference) { // need this id to be able to revert the upload state.transferId = null; state.serverFileReference = serverFileReference; }); // register transfer id processor.on('transfer', function(transferId) { // need this id to be able to revert the upload state.transferId = transferId; }); processor.on('load-perceived', function(serverFileReference) { // no longer required state.activeProcessor = null; // need this id to be able to rever the upload state.transferId = null; state.serverFileReference = serverFileReference; setStatus(ItemStatus.PROCESSING_COMPLETE); fire('process-complete', serverFileReference); }); processor.on('start', function() { fire('process-start'); }); processor.on('error', function(error) { state.activeProcessor = null; setStatus(ItemStatus.PROCESSING_ERROR); fire('process-error', error); }); processor.on('abort', function(serverFileReference) { state.activeProcessor = null; // if file was uploaded but processing was cancelled during perceived processor time store file reference state.transferId = null; state.serverFileReference = serverFileReference; setStatus(ItemStatus.IDLE); fire('process-abort'); // has timeout so doesn't interfere with remove action if (abortProcessingRequestComplete) { abortProcessingRequestComplete(); } }); processor.on('progress', function(progress) { fire('process-progress', progress); }); // when successfully transformed var success = function success(file) { // if was archived in the mean time, don't process if (state.archived) return; // process file! processor.process(file, Object.assign({}, metadata)); }; // something went wrong during transform phase var error = console.error; // start processing the file onprocess(state.file, success, error); // set as active processor state.activeProcessor = processor; }; var requestProcessing = function requestProcessing() { state.processingAborted = false; setStatus(ItemStatus.PROCESSING_QUEUED); }; var abortProcessing = function abortProcessing() { return new Promise(function(resolve) { if (!state.activeProcessor) { state.processingAborted = true; setStatus(ItemStatus.IDLE); fire('process-abort'); resolve(); return; } abortProcessingRequestComplete = function abortProcessingRequestComplete() { resolve(); }; state.activeProcessor.abort(); }); }; // // logic to revert a processed file // var revert = function revert(revertFileUpload, forceRevert) { return new Promise(function(resolve, reject) { // cannot revert without a server id for this process if (state.serverFileReference === null) { resolve(); return; } // revert the upload (fire and forget) revertFileUpload( state.serverFileReference, function() { // reset file server id as now it's no available on the server state.serverFileReference = null; resolve(); }, function(error) { // don't set error state when reverting is optional, it will always resolve if (!forceRevert) { resolve(); return; } // oh no errors setStatus(ItemStatus.PROCESSING_REVERT_ERROR); fire('process-revert-error'); reject(error); } ); // fire event setStatus(ItemStatus.IDLE); fire('process-revert'); }); }; // exposed methods var _setMetadata = function setMetadata(key, value, silent) { var keys = key.split('.'); var root = keys[0]; var last = keys.pop(); var data = metadata; keys.forEach(function(key) { return (data = data[key]); }); // compare old value against new value, if they're the same, we're not updating if (JSON.stringify(data[last]) === JSON.stringify(value)) return; // update value data[last] = value; // don't fire update if (silent) return; // fire update fire('metadata-update', { key: root, value: metadata[root], }); }; var getMetadata = function getMetadata(key) { return deepCloneObject(key ? metadata[key] : metadata); }; var api = Object.assign( { id: { get: function get() { return id; }, }, origin: { get: function get() { return origin; }, }, serverId: { get: function get() { return state.serverFileReference; }, }, transferId: { get: function get() { return state.transferId; }, }, status: { get: function get() { return state.status; }, }, filename: { get: function get() { return state.file.name; }, }, filenameWithoutExtension: { get: function get() { return getFilenameWithoutExtension(state.file.name); }, }, fileExtension: { get: getFileExtension }, fileType: { get: getFileType }, fileSize: { get: getFileSize }, file: { get: getFile }, relativePath: { get: function get() { return state.file._relativePath; }, }, source: { get: function get() { return state.source; }, }, getMetadata: getMetadata, setMetadata: function setMetadata(key, value, silent) { if (isObject(key)) { var data = key; Object.keys(data).forEach(function(key) { _setMetadata(key, data[key], value); }); return key; } _setMetadata(key, value, silent); return value; }, extend: function extend(name, handler) { return (itemAPI[name] = handler); }, abortLoad: abortLoad, retryLoad: retryLoad, requestProcessing: requestProcessing, abortProcessing: abortProcessing, load: load, process: process, revert: revert, }, on(), { freeze: function freeze() { return (state.frozen = true); }, release: function release() { return (state.released = true); }, released: { get: function get() { return state.released; }, }, archive: function archive() { return (state.archived = true); }, archived: { get: function get() { return state.archived; }, }, } ); // create it here instead of returning it instantly so we can extend it later var itemAPI = createObject(api); return itemAPI; }; var getItemIndexByQuery = function getItemIndexByQuery(items, query) { // just return first index if (isEmpty(query)) { return 0; } // invalid queries if (!isString(query)) { return -1; } // return item by id (or -1 if not found) return items.findIndex(function(item) { return item.id === query; }); }; var getItemById = function getItemById(items, itemId) { var index = getItemIndexByQuery(items, itemId); if (index < 0) { return; } return items[index] || null; }; var fetchBlob = function fetchBlob(url, load, error, progress, abort, headers) { var request = sendRequest(null, url, { method: 'GET', responseType: 'blob', }); request.onload = function(xhr) { // get headers var headers = xhr.getAllResponseHeaders(); // get filename var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url); // create response load( createResponse('load', xhr.status, getFileFromBlob(xhr.response, filename), headers) ); }; request.onerror = function(xhr) { error(createResponse('error', xhr.status, xhr.statusText, xhr.getAllResponseHeaders())); }; request.onheaders = function(xhr) { headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders())); }; request.ontimeout = createTimeoutResponse(error); request.onprogress = progress; request.onabort = abort; // should return request return request; }; var getDomainFromURL = function getDomainFromURL(url) { if (url.indexOf('//') === 0) { url = location.protocol + url; } return url .toLowerCase() .replace('blob:', '') .replace(/([a-z])?:\/\//, '$1') .split('/')[0]; }; var isExternalURL = function isExternalURL(url) { return ( (url.indexOf(':') > -1 || url.indexOf('//') > -1) && getDomainFromURL(location.href) !== getDomainFromURL(url) ); }; var dynamicLabel = function dynamicLabel(label) { return function() { return isFunction(label) ? label.apply(void 0, arguments) : label; }; }; var isMockItem = function isMockItem(item) { return !isFile(item.file); }; var listUpdated = function listUpdated(dispatch, state) { clearTimeout(state.listUpdateTimeout); state.listUpdateTimeout = setTimeout(function() { dispatch('DID_UPDATE_ITEMS', { items: getActiveItems(state.items) }); }, 0); }; var optionalPromise = function optionalPromise(fn) { for ( var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ ) { params[_key - 1] = arguments[_key]; } return new Promise(function(resolve) { if (!fn) { return resolve(true); } var result = fn.apply(void 0, params); if (result == null) { return resolve(true); } if (typeof result === 'boolean') { return resolve(result); } if (typeof result.then === 'function') { result.then(resolve); } }); }; var sortItems = function sortItems(state, compare) { state.items.sort(function(a, b) { return compare(createItemAPI(a), createItemAPI(b)); }); }; // returns item based on state var getItemByQueryFromState = function getItemByQueryFromState(state, itemHandler) { return function() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var query = _ref.query, _ref$success = _ref.success, success = _ref$success === void 0 ? function() {} : _ref$success, _ref$failure = _ref.failure, failure = _ref$failure === void 0 ? function() {} : _ref$failure, options = _objectWithoutProperties(_ref, ['query', 'success', 'failure']); var item = getItemByQuery(state.items, query); if (!item) { failure({ error: createResponse('error', 0, 'Item not found'), file: null, }); return; } itemHandler(item, success, failure, options || {}); }; }; var actions = function actions(dispatch, query, state) { return { /** * Aborts all ongoing processes */ ABORT_ALL: function ABORT_ALL() { getActiveItems(state.items).forEach(function(item) { item.freeze(); item.abortLoad(); item.abortProcessing(); }); }, /** * Sets initial files */ DID_SET_FILES: function DID_SET_FILES(_ref2) { var _ref2$value = _ref2.value, value = _ref2$value === void 0 ? [] : _ref2$value; // map values to file objects var files = value.map(function(file) { return { source: file.source ? file.source : file, options: file.options, }; }); // loop over files, if file is in list, leave it be, if not, remove // test if items should be moved var activeItems = getActiveItems(state.items); activeItems.forEach(function(item) { // if item not is in new value, remove if ( !files.find(function(file) { return file.source === item.source || file.source === item.file; }) ) { dispatch('REMOVE_ITEM', { query: item, remove: false }); } }); // add new files activeItems = getActiveItems(state.items); files.forEach(function(file, index) { // if file is already in list if ( activeItems.find(function(item) { return item.source === file.source || item.file === file.source; }) ) return; // not in list, add dispatch( 'ADD_ITEM', Object.assign({}, file, { interactionMethod: InteractionMethod.NONE, index: index, }) ); }); }, DID_UPDATE_ITEM_METADATA: function DID_UPDATE_ITEM_METADATA(_ref3) { var id = _ref3.id, action = _ref3.action; // if is called multiple times in close succession we combined all calls together to save resources clearTimeout(state.itemUpdateTimeout); state.itemUpdateTimeout = setTimeout(function() { var item = getItemById(state.items, id); // only revert and attempt to upload when we're uploading to a server if (!query('IS_ASYNC')) { // should we update the output data applyFilterChain('SHOULD_PREPARE_OUTPUT', false, { item: item, query: query, action: action, }).then(function(shouldPrepareOutput) { // plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE'); if (beforePrepareFile) shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput); if (!shouldPrepareOutput) return; dispatch( 'REQUEST_PREPARE_OUTPUT', { query: id, item: item, success: function success(file) { dispatch('DID_PREPARE_OUTPUT', { id: id, file: file }); }, }, true ); }); return; } // for async scenarios var upload = function upload() { // we push this forward a bit so the interface is updated correctly setTimeout(function() { dispatch('REQUEST_ITEM_PROCESSING', { query: id }); }, 32); }; var revert = function revert(doUpload) { item.revert( createRevertFunction( state.options.server.url, state.options.server.revert ), query('GET_FORCE_REVERT') ) .then(doUpload ? upload : function() {}) .catch(function() {}); }; var abort = function abort(doUpload) { item.abortProcessing().then(doUpload ? upload : function() {}); }; // if we should re-upload the file immediately if (item.status === ItemStatus.PROCESSING_COMPLETE) { return revert(state.options.instantUpload); } // if currently uploading, cancel upload if (item.status === ItemStatus.PROCESSING) { return abort(state.options.instantUpload); } if (state.options.instantUpload) { upload(); } }, 0); }, MOVE_ITEM: function MOVE_ITEM(_ref4) { var query = _ref4.query, index = _ref4.index; var item = getItemByQuery(state.items, query); if (!item) return; var currentIndex = state.items.indexOf(item); index = limit(index, 0, state.items.length - 1); if (currentIndex === index) return; state.items.splice(index, 0, state.items.splice(currentIndex, 1)[0]); }, SORT: function SORT(_ref5) { var compare = _ref5.compare; sortItems(state, compare); dispatch('DID_SORT_ITEMS', { items: query('GET_ACTIVE_ITEMS'), }); }, ADD_ITEMS: function ADD_ITEMS(_ref6) { var items = _ref6.items, index = _ref6.index, interactionMethod = _ref6.interactionMethod, _ref6$success = _ref6.success, success = _ref6$success === void 0 ? function() {} : _ref6$success, _ref6$failure = _ref6.failure, failure = _ref6$failure === void 0 ? function() {} : _ref6$failure; var currentIndex = index; if (index === -1 || typeof index === 'undefined') { var insertLocation = query('GET_ITEM_INSERT_LOCATION'); var totalItems = query('GET_TOTAL_ITEMS'); currentIndex = insertLocation === 'before' ? 0 : totalItems; } var ignoredFiles = query('GET_IGNORED_FILES'); var isValidFile = function isValidFile(source) { return isFile(source) ? !ignoredFiles.includes(source.name.toLowerCase()) : !isEmpty(source); }; var validItems = items.filter(isValidFile); var promises = validItems.map(function(source) { return new Promise(function(resolve, reject) { dispatch('ADD_ITEM', { interactionMethod: interactionMethod, source: source.source || source, success: resolve, failure: reject, index: currentIndex++, options: source.options || {}, }); }); }); Promise.all(promises) .then(success) .catch(failure); }, /** * @param source * @param index * @param interactionMethod */ ADD_ITEM: function ADD_ITEM(_ref7) { var source = _ref7.source, _ref7$index = _ref7.index, index = _ref7$index === void 0 ? -1 : _ref7$index, interactionMethod = _ref7.interactionMethod, _ref7$success = _ref7.success, success = _ref7$success === void 0 ? function() {} : _ref7$success, _ref7$failure = _ref7.failure, failure = _ref7$failure === void 0 ? function() {} : _ref7$failure, _ref7$options = _ref7.options, options = _ref7$options === void 0 ? {} : _ref7$options; // if no source supplied if (isEmpty(source)) { failure({ error: createResponse('error', 0, 'No source'), file: null, }); return; } // filter out invalid file items, used to filter dropped directory contents if ( isFile(source) && state.options.ignoredFiles.includes(source.name.toLowerCase()) ) { // fail silently return; } // test if there's still room in the list of files if (!hasRoomForItem(state)) { // if multiple allowed, we can't replace // or if only a single item is allowed but we're not allowed to replace it we exit if ( state.options.allowMultiple || (!state.options.allowMultiple && !state.options.allowReplace) ) { var error = createResponse('warning', 0, 'Max files'); dispatch('DID_THROW_MAX_FILES', { source: source, error: error, }); failure({ error: error, file: null }); return; } // let's replace the item // id of first item we're about to remove var _item = getActiveItems(state.items)[0]; // if has been processed remove it from the server as well if ( _item.status === ItemStatus.PROCESSING_COMPLETE || _item.status === ItemStatus.PROCESSING_REVERT_ERROR ) { var forceRevert = query('GET_FORCE_REVERT'); _item .revert( createRevertFunction( state.options.server.url, state.options.server.revert ), forceRevert ) .then(function() { if (!forceRevert) return; // try to add now dispatch('ADD_ITEM', { source: source, index: index, interactionMethod: interactionMethod, success: success, failure: failure, options: options, }); }) .catch(function() {}); // no need to handle this catch state for now if (forceRevert) return; } // remove first item as it will be replaced by this item dispatch('REMOVE_ITEM', { query: _item.id }); } // where did the file originate var origin = options.type === 'local' ? FileOrigin.LOCAL : options.type === 'limbo' ? FileOrigin.LIMBO : FileOrigin.INPUT; // create a new blank item var item = createItem( // where did this file come from origin, // an input file never has a server file reference origin === FileOrigin.INPUT ? null : source, // file mock data, if defined options.file ); // set initial meta data Object.keys(options.metadata || {}).forEach(function(key) { item.setMetadata(key, options.metadata[key]); }); // created the item, let plugins add methods applyFilters('DID_CREATE_ITEM', item, { query: query, dispatch: dispatch }); // where to insert new items var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION'); // adjust index if is not allowed to pick location if (!state.options.itemInsertLocationFreedom) { index = itemInsertLocation === 'before' ? -1 : state.items.length; } // add item to list insertItem(state.items, item, index); // sort items in list if (isFunction(itemInsertLocation) && source) { sortItems(state, itemInsertLocation); } // get a quick reference to the item id var id = item.id; // observe item events item.on('init', function() { dispatch('DID_INIT_ITEM', { id: id }); }); item.on('load-init', function() { dispatch('DID_START_ITEM_LOAD', { id: id }); }); item.on('load-meta', function() { dispatch('DID_UPDATE_ITEM_META', { id: id }); }); item.on('load-progress', function(progress) { dispatch('DID_UPDATE_ITEM_LOAD_PROGRESS', { id: id, progress: progress }); }); item.on('load-request-error', function(error) { var mainStatus = dynamicLabel(state.options.labelFileLoadError)(error); // is client error, no way to recover if (error.code >= 400 && error.code < 500) { dispatch('DID_THROW_ITEM_INVALID', { id: id, error: error, status: { main: mainStatus, sub: error.code + ' (' + error.body + ')', }, }); // reject the file so can be dealt with through API failure({ error: error, file: createItemAPI(item) }); return; } // is possible server error, so might be possible to retry dispatch('DID_THROW_ITEM_LOAD_ERROR', { id: id, error: error, status: { main: mainStatus, sub: state.options.labelTapToRetry, }, }); }); item.on('load-file-error', function(error) { dispatch('DID_THROW_ITEM_INVALID', { id: id, error: error.status, status: error.status, }); failure({ error: error.status, file: createItemAPI(item) }); }); item.on('load-abort', function() { dispatch('REMOVE_ITEM', { query: id }); }); item.on('load-skip', function() { dispatch('COMPLETE_LOAD_ITEM', { query: id, item: item, data: { source: source, success: success, }, }); }); item.on('load', function() { var handleAdd = function handleAdd(shouldAdd) { // no should not add this file if (!shouldAdd) { dispatch('REMOVE_ITEM', { query: id, }); return; } // now interested in metadata updates item.on('metadata-update', function(change) { dispatch('DID_UPDATE_ITEM_METADATA', { id: id, change: change }); }); // let plugins decide if the output data should be prepared at this point // means we'll do this and wait for idle state applyFilterChain('SHOULD_PREPARE_OUTPUT', false, { item: item, query: query, }).then(function(shouldPrepareOutput) { // plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE'); if (beforePrepareFile) shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput); var loadComplete = function loadComplete() { dispatch('COMPLETE_LOAD_ITEM', { query: id, item: item, data: { source: source, success: success, }, }); listUpdated(dispatch, state); }; // exit if (shouldPrepareOutput) { // wait for idle state and then run PREPARE_OUTPUT dispatch( 'REQUEST_PREPARE_OUTPUT', { query: id, item: item, success: function success(file) { dispatch('DID_PREPARE_OUTPUT', { id: id, file: file }); loadComplete(); }, }, true ); return; } loadComplete(); }); }; // item loaded, allow plugins to // - read data (quickly) // - add metadata applyFilterChain('DID_LOAD_ITEM', item, { query: query, dispatch: dispatch }) .then(function() { optionalPromise(query('GET_BEFORE_ADD_FILE'), createItemAPI(item)).then( handleAdd ); }) .catch(function() { handleAdd(false); }); }); item.on('process-start', function() { dispatch('DID_START_ITEM_PROCESSING', { id: id }); }); item.on('process-progress', function(progress) { dispatch('DID_UPDATE_ITEM_PROCESS_PROGRESS', { id: id, progress: progress }); }); item.on('process-error', function(error) { dispatch('DID_THROW_ITEM_PROCESSING_ERROR', { id: id, error: error, status: { main: dynamicLabel(state.options.labelFileProcessingError)(error), sub: state.options.labelTapToRetry, }, }); }); item.on('process-revert-error', function(error) { dispatch('DID_THROW_ITEM_PROCESSING_REVERT_ERROR', { id: id, error: error, status: { main: dynamicLabel(state.options.labelFileProcessingRevertError)(error), sub: state.options.labelTapToRetry, }, }); }); item.on('process-complete', function(serverFileReference) { dispatch('DID_COMPLETE_ITEM_PROCESSING', { id: id, error: null, serverFileReference: serverFileReference, }); dispatch('DID_DEFINE_VALUE', { id: id, value: serverFileReference }); }); item.on('process-abort', function() { dispatch('DID_ABORT_ITEM_PROCESSING', { id: id }); }); item.on('process-revert', function() { dispatch('DID_REVERT_ITEM_PROCESSING', { id: id }); dispatch('DID_DEFINE_VALUE', { id: id, value: null }); }); // let view know the item has been inserted dispatch('DID_ADD_ITEM', { id: id, index: index, interactionMethod: interactionMethod, }); listUpdated(dispatch, state); // start loading the source var _ref8 = state.options.server || {}, url = _ref8.url, load = _ref8.load, restore = _ref8.restore, fetch = _ref8.fetch; item.load( source, // this creates a function that loads the file based on the type of file (string, base64, blob, file) and location of file (local, remote, limbo) createFileLoader( origin === FileOrigin.INPUT ? // input, if is remote, see if should use custom fetch, else use default fetchBlob isString(source) && isExternalURL(source) ? fetch ? createFetchFunction(url, fetch) : fetchBlob // remote url : fetchBlob // try to fetch url : // limbo or local origin === FileOrigin.LIMBO ? createFetchFunction(url, restore) // limbo : createFetchFunction(url, load) // local ), // called when the file is loaded so it can be piped through the filters function(file, success, error) { // let's process the file applyFilterChain('LOAD_FILE', file, { query: query }) .then(success) .catch(error); } ); }, REQUEST_PREPARE_OUTPUT: function REQUEST_PREPARE_OUTPUT(_ref9) { var item = _ref9.item, success = _ref9.success, _ref9$failure = _ref9.failure, failure = _ref9$failure === void 0 ? function() {} : _ref9$failure; // error response if item archived var err = { error: createResponse('error', 0, 'Item not found'), file: null, }; // don't handle archived items, an item could have been archived (load aborted) while waiting to be prepared if (item.archived) return failure(err); // allow plugins to alter the file data applyFilterChain('PREPARE_OUTPUT', item.file, { query: query, item: item }).then( function(result) { applyFilterChain('COMPLETE_PREPARE_OUTPUT', result, { query: query, item: item, }).then(function(result) { // don't handle archived items, an item could have been archived (load aborted) while being prepared if (item.archived) return failure(err); // we done! success(result); }); } ); }, COMPLETE_LOAD_ITEM: function COMPLETE_LOAD_ITEM(_ref10) { var item = _ref10.item, data = _ref10.data; var success = data.success, source = data.source; // sort items in list var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION'); if (isFunction(itemInsertLocation) && source) { sortItems(state, itemInsertLocation); } // let interface know the item has loaded dispatch('DID_LOAD_ITEM', { id: item.id, error: null, serverFileReference: item.origin === FileOrigin.INPUT ? null : source, }); // item has been successfully loaded and added to the // list of items so can now be safely returned for use success(createItemAPI(item)); // if this is a local server file we need to show a different state if (item.origin === FileOrigin.LOCAL) { dispatch('DID_LOAD_LOCAL_ITEM', { id: item.id }); return; } // if is a temp server file we prevent async upload call here (as the file is already on the server) if (item.origin === FileOrigin.LIMBO) { dispatch('DID_COMPLETE_ITEM_PROCESSING', { id: item.id, error: null, serverFileReference: source, }); dispatch('DID_DEFINE_VALUE', { id: item.id, value: source, }); return; } // id we are allowed to upload the file immediately, lets do it if (query('IS_ASYNC') && state.options.instantUpload) { dispatch('REQUEST_ITEM_PROCESSING', { query: item.id }); } }, RETRY_ITEM_LOAD: getItemByQueryFromState(state, function(item) { // try loading the source one more time item.retryLoad(); }), REQUEST_ITEM_PREPARE: getItemByQueryFromState(state, function(item, _success, failure) { dispatch( 'REQUEST_PREPARE_OUTPUT', { query: item.id, item: item, success: function success(file) { dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file }); _success({ file: item, output: file, }); }, failure: failure, }, true ); }), REQUEST_ITEM_PROCESSING: getItemByQueryFromState(state, function( item, success, failure ) { // cannot be queued (or is already queued) var itemCanBeQueuedForProcessing = // waiting for something item.status === ItemStatus.IDLE || // processing went wrong earlier item.status === ItemStatus.PROCESSING_ERROR; // not ready to be processed if (!itemCanBeQueuedForProcessing) { var processNow = function processNow() { return dispatch('REQUEST_ITEM_PROCESSING', { query: item, success: success, failure: failure, }); }; var process = function process() { return document.hidden ? processNow() : setTimeout(processNow, 32); }; // if already done processing or tried to revert but didn't work, try again if ( item.status === ItemStatus.PROCESSING_COMPLETE || item.status === ItemStatus.PROCESSING_REVERT_ERROR ) { item.revert( createRevertFunction( state.options.server.url, state.options.server.revert ), query('GET_FORCE_REVERT') ) .then(process) .catch(function() {}); // don't continue with processing if something went wrong } else if (item.status === ItemStatus.PROCESSING) { item.abortProcessing().then(process); } return; } // already queued for processing if (item.status === ItemStatus.PROCESSING_QUEUED) return; item.requestProcessing(); dispatch('DID_REQUEST_ITEM_PROCESSING', { id: item.id }); dispatch('PROCESS_ITEM', { query: item, success: success, failure: failure }, true); }), PROCESS_ITEM: getItemByQueryFromState(state, function(item, success, failure) { var maxParallelUploads = query('GET_MAX_PARALLEL_UPLOADS'); var totalCurrentUploads = query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING) .length; // queue and wait till queue is freed up if (totalCurrentUploads === maxParallelUploads) { // queue for later processing state.processingQueue.push({ id: item.id, success: success, failure: failure, }); // stop it! return; } // if was not queued or is already processing exit here if (item.status === ItemStatus.PROCESSING) return; var processNext = function processNext() { // process queueud items var queueEntry = state.processingQueue.shift(); // no items left if (!queueEntry) return; // get item reference var id = queueEntry.id, success = queueEntry.success, failure = queueEntry.failure; var itemReference = getItemByQuery(state.items, id); // if item was archived while in queue, jump to next if (!itemReference || itemReference.archived) { processNext(); return; } // process queued item dispatch( 'PROCESS_ITEM', { query: id, success: success, failure: failure }, true ); }; // we done function item.onOnce('process-complete', function() { success(createItemAPI(item)); processNext(); // All items processed? No errors? var allItemsProcessed = query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING_COMPLETE).length === state.items.length; if (allItemsProcessed) { dispatch('DID_COMPLETE_ITEM_PROCESSING_ALL'); } }); // we error function item.onOnce('process-error', function(error) { failure({ error: error, file: createItemAPI(item) }); processNext(); }); // start file processing var options = state.options; item.process( createFileProcessor( createProcessorFunction( options.server.url, options.server.process, options.name, { chunkTransferId: item.transferId, chunkServer: options.server.patch, chunkUploads: options.chunkUploads, chunkForce: options.chunkForce, chunkSize: options.chunkSize, chunkRetryDelays: options.chunkRetryDelays, } ) ), // called when the file is about to be processed so it can be piped through the transform filters function(file, success, error) { // allow plugins to alter the file data applyFilterChain('PREPARE_OUTPUT', file, { query: query, item: item }) .then(function(file) { dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file }); success(file); }) .catch(error); } ); }), RETRY_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) { dispatch('REQUEST_ITEM_PROCESSING', { query: item }); }), REQUEST_REMOVE_ITEM: getItemByQueryFromState(state, function(item) { optionalPromise(query('GET_BEFORE_REMOVE_FILE'), createItemAPI(item)).then(function( shouldRemove ) { if (!shouldRemove) { return; } dispatch('REMOVE_ITEM', { query: item }); }); }), RELEASE_ITEM: getItemByQueryFromState(state, function(item) { item.release(); }), REMOVE_ITEM: getItemByQueryFromState(state, function(item, success, failure, options) { var removeFromView = function removeFromView() { // get id reference var id = item.id; // archive the item, this does not remove it from the list getItemById(state.items, id).archive(); // tell the view the item has been removed dispatch('DID_REMOVE_ITEM', { error: null, id: id, item: item }); // now the list has been modified listUpdated(dispatch, state); // correctly removed success(createItemAPI(item)); }; // if this is a local file and the server.remove function has been configured, send source there so dev can remove file from server var server = state.options.server; if ( item.origin === FileOrigin.LOCAL && server && isFunction(server.remove) && options.remove !== false ) { dispatch('DID_START_ITEM_REMOVE', { id: item.id }); server.remove( item.source, function() { return removeFromView(); }, function(status) { dispatch('DID_THROW_ITEM_REMOVE_ERROR', { id: item.id, error: createResponse('error', 0, status, null), status: { main: dynamicLabel(state.options.labelFileRemoveError)(status), sub: state.options.labelTapToRetry, }, }); } ); } else { // if is requesting revert and can revert need to call revert handler (not calling request_ because that would also trigger beforeRemoveHook) if ( options.revert && item.origin !== FileOrigin.LOCAL && item.serverId !== null ) { item.revert( createRevertFunction( state.options.server.url, state.options.server.revert ), query('GET_FORCE_REVERT') ); } // can now safely remove from view removeFromView(); } }), ABORT_ITEM_LOAD: getItemByQueryFromState(state, function(item) { item.abortLoad(); }), ABORT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) { // test if is already processed if (item.serverId) { dispatch('REVERT_ITEM_PROCESSING', { id: item.id }); return; } // abort item.abortProcessing().then(function() { var shouldRemove = state.options.instantUpload; if (shouldRemove) { dispatch('REMOVE_ITEM', { query: item.id }); } }); }), REQUEST_REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) { // not instant uploading, revert immediately if (!state.options.instantUpload) { dispatch('REVERT_ITEM_PROCESSING', { query: item }); return; } // if we're instant uploading the file will also be removed if we revert, // so if a before remove file hook is defined we need to run it now var handleRevert = function handleRevert(shouldRevert) { if (!shouldRevert) return; dispatch('REVERT_ITEM_PROCESSING', { query: item }); }; var fn = query('GET_BEFORE_REMOVE_FILE'); if (!fn) { return handleRevert(true); } var requestRemoveResult = fn(createItemAPI(item)); if (requestRemoveResult == null) { // undefined or null return handleRevert(true); } if (typeof requestRemoveResult === 'boolean') { return handleRevert(requestRemoveResult); } if (typeof requestRemoveResult.then === 'function') { requestRemoveResult.then(handleRevert); } }), REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) { item.revert( createRevertFunction(state.options.server.url, state.options.server.revert), query('GET_FORCE_REVERT') ) .then(function() { var shouldRemove = state.options.instantUpload || isMockItem(item); if (shouldRemove) { dispatch('REMOVE_ITEM', { query: item.id }); } }) .catch(function() {}); }), SET_OPTIONS: function SET_OPTIONS(_ref11) { var options = _ref11.options; forin(options, function(key, value) { dispatch('SET_' + fromCamels(key, '_').toUpperCase(), { value: value }); }); }, }; }; var formatFilename = function formatFilename(name) { return name; }; var createElement$1 = function createElement(tagName) { return document.createElement(tagName); }; var text = function text(node, value) { var textNode = node.childNodes[0]; if (!textNode) { textNode = document.createTextNode(value); node.appendChild(textNode); } else if (value !== textNode.nodeValue) { textNode.nodeValue = value; } }; var polarToCartesian = function polarToCartesian(centerX, centerY, radius, angleInDegrees) { var angleInRadians = (((angleInDegrees % 360) - 90) * Math.PI) / 180.0; return { x: centerX + radius * Math.cos(angleInRadians), y: centerY + radius * Math.sin(angleInRadians), }; }; var describeArc = function describeArc(x, y, radius, startAngle, endAngle, arcSweep) { var start = polarToCartesian(x, y, radius, endAngle); var end = polarToCartesian(x, y, radius, startAngle); return ['M', start.x, start.y, 'A', radius, radius, 0, arcSweep, 0, end.x, end.y].join(' '); }; var percentageArc = function percentageArc(x, y, radius, from, to) { var arcSweep = 1; if (to > from && to - from <= 0.5) { arcSweep = 0; } if (from > to && from - to >= 0.5) { arcSweep = 0; } return describeArc( x, y, radius, Math.min(0.9999, from) * 360, Math.min(0.9999, to) * 360, arcSweep ); }; var create = function create(_ref) { var root = _ref.root, props = _ref.props; // start at 0 props.spin = false; props.progress = 0; props.opacity = 0; // svg var svg = createElement('svg'); root.ref.path = createElement('path', { 'stroke-width': 2, 'stroke-linecap': 'round', }); svg.appendChild(root.ref.path); root.ref.svg = svg; root.appendChild(svg); }; var write = function write(_ref2) { var root = _ref2.root, props = _ref2.props; if (props.opacity === 0) { return; } if (props.align) { root.element.dataset.align = props.align; } // get width of stroke var ringStrokeWidth = parseInt(attr(root.ref.path, 'stroke-width'), 10); // calculate size of ring var size = root.rect.element.width * 0.5; // ring state var ringFrom = 0; var ringTo = 0; // now in busy mode if (props.spin) { ringFrom = 0; ringTo = 0.5; } else { ringFrom = 0; ringTo = props.progress; } // get arc path var coordinates = percentageArc(size, size, size - ringStrokeWidth, ringFrom, ringTo); // update progress bar attr(root.ref.path, 'd', coordinates); // hide while contains 0 value attr(root.ref.path, 'stroke-opacity', props.spin || props.progress > 0 ? 1 : 0); }; var progressIndicator = createView({ tag: 'div', name: 'progress-indicator', ignoreRectUpdate: true, ignoreRect: true, create: create, write: write, mixins: { apis: ['progress', 'spin', 'align'], styles: ['opacity'], animations: { opacity: { type: 'tween', duration: 500 }, progress: { type: 'spring', stiffness: 0.95, damping: 0.65, mass: 10, }, }, }, }); var create$1 = function create(_ref) { var root = _ref.root, props = _ref.props; root.element.innerHTML = (props.icon || '') + ('<span>' + props.label + '</span>'); props.isDisabled = false; }; var write$1 = function write(_ref2) { var root = _ref2.root, props = _ref2.props; var isDisabled = props.isDisabled; var shouldDisable = root.query('GET_DISABLED') || props.opacity === 0; if (shouldDisable && !isDisabled) { props.isDisabled = true; attr(root.element, 'disabled', 'disabled'); } else if (!shouldDisable && isDisabled) { props.isDisabled = false; root.element.removeAttribute('disabled'); } }; var fileActionButton = createView({ tag: 'button', attributes: { type: 'button', }, ignoreRect: true, ignoreRectUpdate: true, name: 'file-action-button', mixins: { apis: ['label'], styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'], animations: { scaleX: 'spring', scaleY: 'spring', translateX: 'spring', translateY: 'spring', opacity: { type: 'tween', duration: 250 }, }, listeners: true, }, create: create$1, write: write$1, }); var toNaturalFileSize = function toNaturalFileSize(bytes) { var decimalSeparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.'; var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000; // no negative byte sizes bytes = Math.round(Math.abs(bytes)); var KB = base; var MB = base * base; var GB = base * base * base; // just bytes if (bytes < KB) { return bytes + ' bytes'; } // kilobytes if (bytes < MB) { return Math.floor(bytes / KB) + ' KB'; } // megabytes if (bytes < GB) { return removeDecimalsWhenZero(bytes / MB, 1, decimalSeparator) + ' MB'; } // gigabytes return removeDecimalsWhenZero(bytes / GB, 2, decimalSeparator) + ' GB'; }; var removeDecimalsWhenZero = function removeDecimalsWhenZero(value, decimalCount, separator) { return value .toFixed(decimalCount) .split('.') .filter(function(part) { return part !== '0'; }) .join(separator); }; var create$2 = function create(_ref) { var root = _ref.root, props = _ref.props; // filename var fileName = createElement$1('span'); fileName.className = 'filepond--file-info-main'; // hide for screenreaders // the file is contained in a fieldset with legend that contains the filename // no need to read it twice attr(fileName, 'aria-hidden', 'true'); root.appendChild(fileName); root.ref.fileName = fileName; // filesize var fileSize = createElement$1('span'); fileSize.className = 'filepond--file-info-sub'; root.appendChild(fileSize); root.ref.fileSize = fileSize; // set initial values text(fileSize, root.query('GET_LABEL_FILE_WAITING_FOR_SIZE')); text(fileName, formatFilename(root.query('GET_ITEM_NAME', props.id))); }; var updateFile = function updateFile(_ref2) { var root = _ref2.root, props = _ref2.props; text( root.ref.fileSize, toNaturalFileSize( root.query('GET_ITEM_SIZE', props.id), '.', root.query('GET_FILE_SIZE_BASE') ) ); text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id))); }; var updateFileSizeOnError = function updateFileSizeOnError(_ref3) { var root = _ref3.root, props = _ref3.props; // if size is available don't fallback to unknown size message if (isInt(root.query('GET_ITEM_SIZE', props.id))) { return; } text(root.ref.fileSize, root.query('GET_LABEL_FILE_SIZE_NOT_AVAILABLE')); }; var fileInfo = createView({ name: 'file-info', ignoreRect: true, ignoreRectUpdate: true, write: createRoute({ DID_LOAD_ITEM: updateFile, DID_UPDATE_ITEM_META: updateFile, DID_THROW_ITEM_LOAD_ERROR: updateFileSizeOnError, DID_THROW_ITEM_INVALID: updateFileSizeOnError, }), didCreateView: function didCreateView(root) { applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root })); }, create: create$2, mixins: { styles: ['translateX', 'translateY'], animations: { translateX: 'spring', translateY: 'spring', }, }, }); var toPercentage = function toPercentage(value) { return Math.round(value * 100); }; var create$3 = function create(_ref) { var root = _ref.root; // main status var main = createElement$1('span'); main.className = 'filepond--file-status-main'; root.appendChild(main); root.ref.main = main; // sub status var sub = createElement$1('span'); sub.className = 'filepond--file-status-sub'; root.appendChild(sub); root.ref.sub = sub; didSetItemLoadProgress({ root: root, action: { progress: null } }); }; var didSetItemLoadProgress = function didSetItemLoadProgress(_ref2) { var root = _ref2.root, action = _ref2.action; var title = action.progress === null ? root.query('GET_LABEL_FILE_LOADING') : root.query('GET_LABEL_FILE_LOADING') + ' ' + toPercentage(action.progress) + '%'; text(root.ref.main, title); text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL')); }; var didSetItemProcessProgress = function didSetItemProcessProgress(_ref3) { var root = _ref3.root, action = _ref3.action; var title = action.progress === null ? root.query('GET_LABEL_FILE_PROCESSING') : root.query('GET_LABEL_FILE_PROCESSING') + ' ' + toPercentage(action.progress) + '%'; text(root.ref.main, title); text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL')); }; var didRequestItemProcessing = function didRequestItemProcessing(_ref4) { var root = _ref4.root; text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING')); text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL')); }; var didAbortItemProcessing = function didAbortItemProcessing(_ref5) { var root = _ref5.root; text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_ABORTED')); text(root.ref.sub, root.query('GET_LABEL_TAP_TO_RETRY')); }; var didCompleteItemProcessing = function didCompleteItemProcessing(_ref6) { var root = _ref6.root; text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_COMPLETE')); text(root.ref.sub, root.query('GET_LABEL_TAP_TO_UNDO')); }; var clear = function clear(_ref7) { var root = _ref7.root; text(root.ref.main, ''); text(root.ref.sub, ''); }; var error = function error(_ref8) { var root = _ref8.root, action = _ref8.action; text(root.ref.main, action.status.main); text(root.ref.sub, action.status.sub); }; var fileStatus = createView({ name: 'file-status', ignoreRect: true, ignoreRectUpdate: true, write: createRoute({ DID_LOAD_ITEM: clear, DID_REVERT_ITEM_PROCESSING: clear, DID_REQUEST_ITEM_PROCESSING: didRequestItemProcessing, DID_ABORT_ITEM_PROCESSING: didAbortItemProcessing, DID_COMPLETE_ITEM_PROCESSING: didCompleteItemProcessing, DID_UPDATE_ITEM_PROCESS_PROGRESS: didSetItemProcessProgress, DID_UPDATE_ITEM_LOAD_PROGRESS: didSetItemLoadProgress, DID_THROW_ITEM_LOAD_ERROR: error, DID_THROW_ITEM_INVALID: error, DID_THROW_ITEM_PROCESSING_ERROR: error, DID_THROW_ITEM_PROCESSING_REVERT_ERROR: error, DID_THROW_ITEM_REMOVE_ERROR: error, }), didCreateView: function didCreateView(root) { applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root })); }, create: create$3, mixins: { styles: ['translateX', 'translateY', 'opacity'], animations: { opacity: { type: 'tween', duration: 250 }, translateX: 'spring', translateY: 'spring', }, }, }); /** * Button definitions for the file view */ var Buttons = { AbortItemLoad: { label: 'GET_LABEL_BUTTON_ABORT_ITEM_LOAD', action: 'ABORT_ITEM_LOAD', className: 'filepond--action-abort-item-load', align: 'LOAD_INDICATOR_POSITION', // right }, RetryItemLoad: { label: 'GET_LABEL_BUTTON_RETRY_ITEM_LOAD', action: 'RETRY_ITEM_LOAD', icon: 'GET_ICON_RETRY', className: 'filepond--action-retry-item-load', align: 'BUTTON_PROCESS_ITEM_POSITION', // right }, RemoveItem: { label: 'GET_LABEL_BUTTON_REMOVE_ITEM', action: 'REQUEST_REMOVE_ITEM', icon: 'GET_ICON_REMOVE', className: 'filepond--action-remove-item', align: 'BUTTON_REMOVE_ITEM_POSITION', // left }, ProcessItem: { label: 'GET_LABEL_BUTTON_PROCESS_ITEM', action: 'REQUEST_ITEM_PROCESSING', icon: 'GET_ICON_PROCESS', className: 'filepond--action-process-item', align: 'BUTTON_PROCESS_ITEM_POSITION', // right }, AbortItemProcessing: { label: 'GET_LABEL_BUTTON_ABORT_ITEM_PROCESSING', action: 'ABORT_ITEM_PROCESSING', className: 'filepond--action-abort-item-processing', align: 'BUTTON_PROCESS_ITEM_POSITION', // right }, RetryItemProcessing: { label: 'GET_LABEL_BUTTON_RETRY_ITEM_PROCESSING', action: 'RETRY_ITEM_PROCESSING', icon: 'GET_ICON_RETRY', className: 'filepond--action-retry-item-processing', align: 'BUTTON_PROCESS_ITEM_POSITION', // right }, RevertItemProcessing: { label: 'GET_LABEL_BUTTON_UNDO_ITEM_PROCESSING', action: 'REQUEST_REVERT_ITEM_PROCESSING', icon: 'GET_ICON_UNDO', className: 'filepond--action-revert-item-processing', align: 'BUTTON_PROCESS_ITEM_POSITION', // right }, }; // make a list of buttons, we can then remove buttons from this list if they're disabled var ButtonKeys = []; forin(Buttons, function(key) { ButtonKeys.push(key); }); var calculateFileInfoOffset = function calculateFileInfoOffset(root) { if (getRemoveIndicatorAligment(root) === 'right') return 0; var buttonRect = root.ref.buttonRemoveItem.rect.element; return buttonRect.hidden ? null : buttonRect.width + buttonRect.left; }; var calculateButtonWidth = function calculateButtonWidth(root) { var buttonRect = root.ref.buttonAbortItemLoad.rect.element; return buttonRect.width; }; // Force on full pixels so text stays crips var calculateFileVerticalCenterOffset = function calculateFileVerticalCenterOffset(root) { return Math.floor(root.ref.buttonRemoveItem.rect.element.height / 4); }; var calculateFileHorizontalCenterOffset = function calculateFileHorizontalCenterOffset(root) { return Math.floor(root.ref.buttonRemoveItem.rect.element.left / 2); }; var getLoadIndicatorAlignment = function getLoadIndicatorAlignment(root) { return root.query('GET_STYLE_LOAD_INDICATOR_POSITION'); }; var getProcessIndicatorAlignment = function getProcessIndicatorAlignment(root) { return root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION'); }; var getRemoveIndicatorAligment = function getRemoveIndicatorAligment(root) { return root.query('GET_STYLE_BUTTON_REMOVE_ITEM_POSITION'); }; var DefaultStyle = { buttonAbortItemLoad: { opacity: 0 }, buttonRetryItemLoad: { opacity: 0 }, buttonRemoveItem: { opacity: 0 }, buttonProcessItem: { opacity: 0 }, buttonAbortItemProcessing: { opacity: 0 }, buttonRetryItemProcessing: { opacity: 0 }, buttonRevertItemProcessing: { opacity: 0 }, loadProgressIndicator: { opacity: 0, align: getLoadIndicatorAlignment }, processProgressIndicator: { opacity: 0, align: getProcessIndicatorAlignment }, processingCompleteIndicator: { opacity: 0, scaleX: 0.75, scaleY: 0.75 }, info: { translateX: 0, translateY: 0, opacity: 0 }, status: { translateX: 0, translateY: 0, opacity: 0 }, }; var IdleStyle = { buttonRemoveItem: { opacity: 1 }, buttonProcessItem: { opacity: 1 }, info: { translateX: calculateFileInfoOffset }, status: { translateX: calculateFileInfoOffset }, }; var ProcessingStyle = { buttonAbortItemProcessing: { opacity: 1 }, processProgressIndicator: { opacity: 1 }, status: { opacity: 1 }, }; var StyleMap = { DID_THROW_ITEM_INVALID: { buttonRemoveItem: { opacity: 1 }, info: { translateX: calculateFileInfoOffset }, status: { translateX: calculateFileInfoOffset, opacity: 1 }, }, DID_START_ITEM_LOAD: { buttonAbortItemLoad: { opacity: 1 }, loadProgressIndicator: { opacity: 1 }, status: { opacity: 1 }, }, DID_THROW_ITEM_LOAD_ERROR: { buttonRetryItemLoad: { opacity: 1 }, buttonRemoveItem: { opacity: 1 }, info: { translateX: calculateFileInfoOffset }, status: { opacity: 1 }, }, DID_START_ITEM_REMOVE: { processProgressIndicator: { opacity: 1, align: getRemoveIndicatorAligment }, info: { translateX: calculateFileInfoOffset }, status: { opacity: 0 }, }, DID_THROW_ITEM_REMOVE_ERROR: { processProgressIndicator: { opacity: 0, align: getRemoveIndicatorAligment }, buttonRemoveItem: { opacity: 1 }, info: { translateX: calculateFileInfoOffset }, status: { opacity: 1, translateX: calculateFileInfoOffset }, }, DID_LOAD_ITEM: IdleStyle, DID_LOAD_LOCAL_ITEM: { buttonRemoveItem: { opacity: 1 }, info: { translateX: calculateFileInfoOffset }, status: { translateX: calculateFileInfoOffset }, }, DID_START_ITEM_PROCESSING: ProcessingStyle, DID_REQUEST_ITEM_PROCESSING: ProcessingStyle, DID_UPDATE_ITEM_PROCESS_PROGRESS: ProcessingStyle, DID_COMPLETE_ITEM_PROCESSING: { buttonRevertItemProcessing: { opacity: 1 }, info: { opacity: 1 }, status: { opacity: 1 }, }, DID_THROW_ITEM_PROCESSING_ERROR: { buttonRemoveItem: { opacity: 1 }, buttonRetryItemProcessing: { opacity: 1 }, status: { opacity: 1 }, info: { translateX: calculateFileInfoOffset }, }, DID_THROW_ITEM_PROCESSING_REVERT_ERROR: { buttonRevertItemProcessing: { opacity: 1 }, status: { opacity: 1 }, info: { opacity: 1 }, }, DID_ABORT_ITEM_PROCESSING: { buttonRemoveItem: { opacity: 1 }, buttonProcessItem: { opacity: 1 }, info: { translateX: calculateFileInfoOffset }, status: { opacity: 1 }, }, DID_REVERT_ITEM_PROCESSING: IdleStyle, }; // complete indicator view var processingCompleteIndicatorView = createView({ create: function create(_ref) { var root = _ref.root; root.element.innerHTML = root.query('GET_ICON_DONE'); }, name: 'processing-complete-indicator', ignoreRect: true, mixins: { styles: ['scaleX', 'scaleY', 'opacity'], animations: { scaleX: 'spring', scaleY: 'spring', opacity: { type: 'tween', duration: 250 }, }, }, }); /** * Creates the file view */ var create$4 = function create(_ref2) { var root = _ref2.root, props = _ref2.props; var id = props.id; // allow reverting upload var allowRevert = root.query('GET_ALLOW_REVERT'); // allow remove file var allowRemove = root.query('GET_ALLOW_REMOVE'); // allow processing upload var allowProcess = root.query('GET_ALLOW_PROCESS'); // is instant uploading, need this to determine the icon of the undo button var instantUpload = root.query('GET_INSTANT_UPLOAD'); // is async set up var isAsync = root.query('IS_ASYNC'); // should align remove item buttons var alignRemoveItemButton = root.query('GET_STYLE_BUTTON_REMOVE_ITEM_ALIGN'); // enabled buttons array var buttonFilter; if (isAsync) { if (allowProcess && !allowRevert) { // only remove revert button buttonFilter = function buttonFilter(key) { return !/RevertItemProcessing/.test(key); }; } else if (!allowProcess && allowRevert) { // only remove process button buttonFilter = function buttonFilter(key) { return !/ProcessItem|RetryItemProcessing|AbortItemProcessing/.test(key); }; } else if (!allowProcess && !allowRevert) { // remove all process buttons buttonFilter = function buttonFilter(key) { return !/Process/.test(key); }; } } else { // no process controls available buttonFilter = function buttonFilter(key) { return !/Process/.test(key); }; } var enabledButtons = buttonFilter ? ButtonKeys.filter(buttonFilter) : ButtonKeys.concat(); // update icon and label for revert button when instant uploading if (instantUpload && allowRevert) { Buttons['RevertItemProcessing'].label = 'GET_LABEL_BUTTON_REMOVE_ITEM'; Buttons['RevertItemProcessing'].icon = 'GET_ICON_REMOVE'; } // remove last button (revert) if not allowed if (isAsync && !allowRevert) { var map = StyleMap['DID_COMPLETE_ITEM_PROCESSING']; map.info.translateX = calculateFileHorizontalCenterOffset; map.info.translateY = calculateFileVerticalCenterOffset; map.status.translateY = calculateFileVerticalCenterOffset; map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 }; } // should align center if (isAsync && !allowProcess) { [ 'DID_START_ITEM_PROCESSING', 'DID_REQUEST_ITEM_PROCESSING', 'DID_UPDATE_ITEM_PROCESS_PROGRESS', 'DID_THROW_ITEM_PROCESSING_ERROR', ].forEach(function(key) { StyleMap[key].status.translateY = calculateFileVerticalCenterOffset; }); StyleMap['DID_THROW_ITEM_PROCESSING_ERROR'].status.translateX = calculateButtonWidth; } // move remove button to right if (alignRemoveItemButton && allowRevert) { Buttons['RevertItemProcessing'].align = 'BUTTON_REMOVE_ITEM_POSITION'; var _map = StyleMap['DID_COMPLETE_ITEM_PROCESSING']; _map.info.translateX = calculateFileInfoOffset; _map.status.translateY = calculateFileVerticalCenterOffset; _map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 }; } if (!allowRemove) { Buttons['RemoveItem'].disabled = true; } // create the button views forin(Buttons, function(key, definition) { // create button var buttonView = root.createChildView(fileActionButton, { label: root.query(definition.label), icon: root.query(definition.icon), opacity: 0, }); // should be appended? if (enabledButtons.includes(key)) { root.appendChildView(buttonView); } // toggle if (definition.disabled) { buttonView.element.setAttribute('disabled', 'disabled'); buttonView.element.setAttribute('hidden', 'hidden'); } // add position attribute buttonView.element.dataset.align = root.query('GET_STYLE_' + definition.align); // add class buttonView.element.classList.add(definition.className); // handle interactions buttonView.on('click', function(e) { e.stopPropagation(); if (definition.disabled) return; root.dispatch(definition.action, { query: id }); }); // set reference root.ref['button' + key] = buttonView; }); // checkmark root.ref.processingCompleteIndicator = root.appendChildView( root.createChildView(processingCompleteIndicatorView) ); root.ref.processingCompleteIndicator.element.dataset.align = root.query( 'GET_STYLE_BUTTON_PROCESS_ITEM_POSITION' ); // create file info view root.ref.info = root.appendChildView(root.createChildView(fileInfo, { id: id })); // create file status view root.ref.status = root.appendChildView(root.createChildView(fileStatus, { id: id })); // add progress indicators var loadIndicatorView = root.appendChildView( root.createChildView(progressIndicator, { opacity: 0, align: root.query('GET_STYLE_LOAD_INDICATOR_POSITION'), }) ); loadIndicatorView.element.classList.add('filepond--load-indicator'); root.ref.loadProgressIndicator = loadIndicatorView; var progressIndicatorView = root.appendChildView( root.createChildView(progressIndicator, { opacity: 0, align: root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION'), }) ); progressIndicatorView.element.classList.add('filepond--process-indicator'); root.ref.processProgressIndicator = progressIndicatorView; // current active styles root.ref.activeStyles = []; }; var write$2 = function write(_ref3) { var root = _ref3.root, actions = _ref3.actions, props = _ref3.props; // route actions route({ root: root, actions: actions, props: props }); // select last state change action var action = actions .concat() .filter(function(action) { return /^DID_/.test(action.type); }) .reverse() .find(function(action) { return StyleMap[action.type]; }); // a new action happened, let's get the matching styles if (action) { // define new active styles root.ref.activeStyles = []; var stylesToApply = StyleMap[action.type]; forin(DefaultStyle, function(name, defaultStyles) { // get reference to control var control = root.ref[name]; // loop over all styles for this control forin(defaultStyles, function(key, defaultValue) { var value = stylesToApply[name] && typeof stylesToApply[name][key] !== 'undefined' ? stylesToApply[name][key] : defaultValue; root.ref.activeStyles.push({ control: control, key: key, value: value }); }); }); } // apply active styles to element root.ref.activeStyles.forEach(function(_ref4) { var control = _ref4.control, key = _ref4.key, value = _ref4.value; control[key] = typeof value === 'function' ? value(root) : value; }); }; var route = createRoute({ DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING: function DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING( _ref5 ) { var root = _ref5.root, action = _ref5.action; root.ref.buttonAbortItemProcessing.label = action.value; }, DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD: function DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD(_ref6) { var root = _ref6.root, action = _ref6.action; root.ref.buttonAbortItemLoad.label = action.value; }, DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL: function DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL( _ref7 ) { var root = _ref7.root, action = _ref7.action; root.ref.buttonAbortItemRemoval.label = action.value; }, DID_REQUEST_ITEM_PROCESSING: function DID_REQUEST_ITEM_PROCESSING(_ref8) { var root = _ref8.root; root.ref.processProgressIndicator.spin = true; root.ref.processProgressIndicator.progress = 0; }, DID_START_ITEM_LOAD: function DID_START_ITEM_LOAD(_ref9) { var root = _ref9.root; root.ref.loadProgressIndicator.spin = true; root.ref.loadProgressIndicator.progress = 0; }, DID_START_ITEM_REMOVE: function DID_START_ITEM_REMOVE(_ref10) { var root = _ref10.root; root.ref.processProgressIndicator.spin = true; root.ref.processProgressIndicator.progress = 0; }, DID_UPDATE_ITEM_LOAD_PROGRESS: function DID_UPDATE_ITEM_LOAD_PROGRESS(_ref11) { var root = _ref11.root, action = _ref11.action; root.ref.loadProgressIndicator.spin = false; root.ref.loadProgressIndicator.progress = action.progress; }, DID_UPDATE_ITEM_PROCESS_PROGRESS: function DID_UPDATE_ITEM_PROCESS_PROGRESS(_ref12) { var root = _ref12.root, action = _ref12.action; root.ref.processProgressIndicator.spin = false; root.ref.processProgressIndicator.progress = action.progress; }, }); var file = createView({ create: create$4, write: write$2, didCreateView: function didCreateView(root) { applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root })); }, name: 'file', }); /** * Creates the file view */ var create$5 = function create(_ref) { var root = _ref.root, props = _ref.props; // filename root.ref.fileName = createElement$1('legend'); root.appendChild(root.ref.fileName); // file appended root.ref.file = root.appendChildView(root.createChildView(file, { id: props.id })); // data has moved to data.js root.ref.data = false; }; /** * Data storage */ var didLoadItem = function didLoadItem(_ref2) { var root = _ref2.root, props = _ref2.props; // updates the legend of the fieldset so screenreaders can better group buttons text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id))); }; var fileWrapper = createView({ create: create$5, ignoreRect: true, write: createRoute({ DID_LOAD_ITEM: didLoadItem, }), didCreateView: function didCreateView(root) { applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root })); }, tag: 'fieldset', name: 'file-wrapper', }); var PANEL_SPRING_PROPS = { type: 'spring', damping: 0.6, mass: 7 }; var create$6 = function create(_ref) { var root = _ref.root, props = _ref.props; [ { name: 'top', }, { name: 'center', props: { translateY: null, scaleY: null, }, mixins: { animations: { scaleY: PANEL_SPRING_PROPS, }, styles: ['translateY', 'scaleY'], }, }, { name: 'bottom', props: { translateY: null, }, mixins: { animations: { translateY: PANEL_SPRING_PROPS, }, styles: ['translateY'], }, }, ].forEach(function(section) { createSection(root, section, props.name); }); root.element.classList.add('filepond--' + props.name); root.ref.scalable = null; }; var createSection = function createSection(root, section, className) { var viewConstructor = createView({ name: 'panel-' + section.name + ' filepond--' + className, mixins: section.mixins, ignoreRectUpdate: true, }); var view = root.createChildView(viewConstructor, section.props); root.ref[section.name] = root.appendChildView(view); }; var write$3 = function write(_ref2) { var root = _ref2.root, props = _ref2.props; // update scalable state if (root.ref.scalable === null || props.scalable !== root.ref.scalable) { root.ref.scalable = isBoolean(props.scalable) ? props.scalable : true; root.element.dataset.scalable = root.ref.scalable; } // no height, can't set if (!props.height) return; // get child rects var topRect = root.ref.top.rect.element; var bottomRect = root.ref.bottom.rect.element; // make sure height never is smaller than bottom and top seciton heights combined (will probably never happen, but who knows) var height = Math.max(topRect.height + bottomRect.height, props.height); // offset center part root.ref.center.translateY = topRect.height; // scale center part // use math ceil to prevent transparent lines because of rounding errors root.ref.center.scaleY = (height - topRect.height - bottomRect.height) / 100; // offset bottom part root.ref.bottom.translateY = height - bottomRect.height; }; var panel = createView({ name: 'panel', read: function read(_ref3) { var root = _ref3.root, props = _ref3.props; return (props.heightCurrent = root.ref.bottom.translateY); }, write: write$3, create: create$6, ignoreRect: true, mixins: { apis: ['height', 'heightCurrent', 'scalable'], }, }); var createDragHelper = function createDragHelper(items) { var itemIds = items.map(function(item) { return item.id; }); var prevIndex = undefined; return { setIndex: function setIndex(index) { prevIndex = index; }, getIndex: function getIndex() { return prevIndex; }, getItemIndex: function getItemIndex(item) { return itemIds.indexOf(item.id); }, }; }; var ITEM_TRANSLATE_SPRING = { type: 'spring', stiffness: 0.75, damping: 0.45, mass: 10, }; var ITEM_SCALE_SPRING = 'spring'; var StateMap = { DID_START_ITEM_LOAD: 'busy', DID_UPDATE_ITEM_LOAD_PROGRESS: 'loading', DID_THROW_ITEM_INVALID: 'load-invalid', DID_THROW_ITEM_LOAD_ERROR: 'load-error', DID_LOAD_ITEM: 'idle', DID_THROW_ITEM_REMOVE_ERROR: 'remove-error', DID_START_ITEM_REMOVE: 'busy', DID_START_ITEM_PROCESSING: 'busy processing', DID_REQUEST_ITEM_PROCESSING: 'busy processing', DID_UPDATE_ITEM_PROCESS_PROGRESS: 'processing', DID_COMPLETE_ITEM_PROCESSING: 'processing-complete', DID_THROW_ITEM_PROCESSING_ERROR: 'processing-error', DID_THROW_ITEM_PROCESSING_REVERT_ERROR: 'processing-revert-error', DID_ABORT_ITEM_PROCESSING: 'cancelled', DID_REVERT_ITEM_PROCESSING: 'idle', }; /** * Creates the file view */ var create$7 = function create(_ref) { var root = _ref.root, props = _ref.props; // select root.ref.handleClick = function(e) { return root.dispatch('DID_ACTIVATE_ITEM', { id: props.id }); }; // set id root.element.id = 'filepond--item-' + props.id; root.element.addEventListener('click', root.ref.handleClick); // file view root.ref.container = root.appendChildView( root.createChildView(fileWrapper, { id: props.id }) ); // file panel root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'item-panel' })); // default start height root.ref.panel.height = null; // by default not marked for removal props.markedForRemoval = false; // if not allowed to reorder file items, exit here if (!root.query('GET_ALLOW_REORDER')) return; // set to idle so shows grab cursor root.element.dataset.dragState = 'idle'; var grab = function grab(e) { if (!e.isPrimary) return; var removedActivateListener = false; var origin = { x: e.pageX, y: e.pageY, }; props.dragOrigin = { x: root.translateX, y: root.translateY, }; props.dragCenter = { x: e.offsetX, y: e.offsetY, }; var dragState = createDragHelper(root.query('GET_ACTIVE_ITEMS')); root.dispatch('DID_GRAB_ITEM', { id: props.id, dragState: dragState }); var drag = function drag(e) { if (!e.isPrimary) return; e.stopPropagation(); e.preventDefault(); props.dragOffset = { x: e.pageX - origin.x, y: e.pageY - origin.y, }; // if dragged stop listening to clicks, will re-add when done dragging var dist = props.dragOffset.x * props.dragOffset.x + props.dragOffset.y * props.dragOffset.y; if (dist > 16 && !removedActivateListener) { removedActivateListener = true; root.element.removeEventListener('click', root.ref.handleClick); } root.dispatch('DID_DRAG_ITEM', { id: props.id, dragState: dragState }); }; var drop = function drop(e) { if (!e.isPrimary) return; document.removeEventListener('pointermove', drag); document.removeEventListener('pointerup', drop); props.dragOffset = { x: e.pageX - origin.x, y: e.pageY - origin.y, }; root.dispatch('DID_DROP_ITEM', { id: props.id, dragState: dragState }); // start listening to clicks again if (removedActivateListener) { setTimeout(function() { return root.element.addEventListener('click', root.ref.handleClick); }, 0); } }; document.addEventListener('pointermove', drag); document.addEventListener('pointerup', drop); }; root.element.addEventListener('pointerdown', grab); }; var route$1 = createRoute({ DID_UPDATE_PANEL_HEIGHT: function DID_UPDATE_PANEL_HEIGHT(_ref2) { var root = _ref2.root, action = _ref2.action; root.height = action.height; }, }); var write$4 = createRoute( { DID_GRAB_ITEM: function DID_GRAB_ITEM(_ref3) { var root = _ref3.root, props = _ref3.props; props.dragOrigin = { x: root.translateX, y: root.translateY, }; }, DID_DRAG_ITEM: function DID_DRAG_ITEM(_ref4) { var root = _ref4.root; root.element.dataset.dragState = 'drag'; }, DID_DROP_ITEM: function DID_DROP_ITEM(_ref5) { var root = _ref5.root, props = _ref5.props; props.dragOffset = null; props.dragOrigin = null; root.element.dataset.dragState = 'drop'; }, }, function(_ref6) { var root = _ref6.root, actions = _ref6.actions, props = _ref6.props, shouldOptimize = _ref6.shouldOptimize; if (root.element.dataset.dragState === 'drop') { if (root.scaleX <= 1) { root.element.dataset.dragState = 'idle'; } } // select last state change action var action = actions .concat() .filter(function(action) { return /^DID_/.test(action.type); }) .reverse() .find(function(action) { return StateMap[action.type]; }); // no need to set same state twice if (action && action.type !== props.currentState) { // set current state props.currentState = action.type; // set state root.element.dataset.filepondItemState = StateMap[props.currentState] || ''; } // route actions var aspectRatio = root.query('GET_ITEM_PANEL_ASPECT_RATIO') || root.query('GET_PANEL_ASPECT_RATIO'); if (!aspectRatio) { route$1({ root: root, actions: actions, props: props }); if (!root.height && root.ref.container.rect.element.height > 0) { root.height = root.ref.container.rect.element.height; } } else if (!shouldOptimize) { root.height = root.rect.element.width * aspectRatio; } // sync panel height with item height if (shouldOptimize) { root.ref.panel.height = null; } root.ref.panel.height = root.height; } ); var item = createView({ create: create$7, write: write$4, destroy: function destroy(_ref7) { var root = _ref7.root, props = _ref7.props; root.element.removeEventListener('click', root.ref.handleClick); root.dispatch('RELEASE_ITEM', { query: props.id }); }, tag: 'li', name: 'item', mixins: { apis: [ 'id', 'interactionMethod', 'markedForRemoval', 'spawnDate', 'dragCenter', 'dragOrigin', 'dragOffset', ], styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity', 'height'], animations: { scaleX: ITEM_SCALE_SPRING, scaleY: ITEM_SCALE_SPRING, translateX: ITEM_TRANSLATE_SPRING, translateY: ITEM_TRANSLATE_SPRING, opacity: { type: 'tween', duration: 150 }, }, }, }); var getItemsPerRow = function(horizontalSpace, itemWidth) { // add one pixel leeway, when using percentages for item width total items can be 1.99 per row return Math.max(1, Math.floor((horizontalSpace + 1) / itemWidth)); }; var getItemIndexByPosition = function getItemIndexByPosition(view, children, positionInView) { if (!positionInView) return; var horizontalSpace = view.rect.element.width; // const children = view.childViews; var l = children.length; var last = null; // -1, don't move items to accomodate (either add to top or bottom) if (l === 0 || positionInView.top < children[0].rect.element.top) return -1; // let's get the item width var item = children[0]; var itemRect = item.rect.element; var itemHorizontalMargin = itemRect.marginLeft + itemRect.marginRight; var itemWidth = itemRect.width + itemHorizontalMargin; var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth); // stack if (itemsPerRow === 1) { for (var index = 0; index < l; index++) { var child = children[index]; var childMid = child.rect.outer.top + child.rect.element.height * 0.5; if (positionInView.top < childMid) { return index; } } return l; } // grid var itemVerticalMargin = itemRect.marginTop + itemRect.marginBottom; var itemHeight = itemRect.height + itemVerticalMargin; for (var _index = 0; _index < l; _index++) { var indexX = _index % itemsPerRow; var indexY = Math.floor(_index / itemsPerRow); var offsetX = indexX * itemWidth; var offsetY = indexY * itemHeight; var itemTop = offsetY - itemRect.marginTop; var itemRight = offsetX + itemWidth; var itemBottom = offsetY + itemHeight + itemRect.marginBottom; if (positionInView.top < itemBottom && positionInView.top > itemTop) { if (positionInView.left < itemRight) { return _index; } else if (_index !== l - 1) { last = _index; } else { last = null; } } } if (last !== null) { return last; } return l; }; var dropAreaDimensions = { height: 0, width: 0, get getHeight() { return this.height; }, set setHeight(val) { if (this.height === 0 || val === 0) this.height = val; }, get getWidth() { return this.width; }, set setWidth(val) { if (this.width === 0 || val === 0) this.width = val; }, setDimensions: function setDimensions(height, width) { if (this.height === 0 || height === 0) this.height = height; if (this.width === 0 || width === 0) this.width = width; }, }; var create$8 = function create(_ref) { var root = _ref.root; // need to set role to list as otherwise it won't be read as a list by VoiceOver attr(root.element, 'role', 'list'); root.ref.lastItemSpanwDate = Date.now(); }; /** * Inserts a new item * @param root * @param action */ var addItemView = function addItemView(_ref2) { var root = _ref2.root, action = _ref2.action; var id = action.id, index = action.index, interactionMethod = action.interactionMethod; root.ref.addIndex = index; var now = Date.now(); var spawnDate = now; var opacity = 1; if (interactionMethod !== InteractionMethod.NONE) { opacity = 0; var cooldown = root.query('GET_ITEM_INSERT_INTERVAL'); var dist = now - root.ref.lastItemSpanwDate; spawnDate = dist < cooldown ? now + (cooldown - dist) : now; } root.ref.lastItemSpanwDate = spawnDate; root.appendChildView( root.createChildView( // view type item, // props { spawnDate: spawnDate, id: id, opacity: opacity, interactionMethod: interactionMethod, } ), index ); }; var moveItem = function moveItem(item, x, y) { var vx = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var vy = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1; // set to null to remove animation while dragging if (item.dragOffset) { item.translateX = null; item.translateY = null; item.translateX = item.dragOrigin.x + item.dragOffset.x; item.translateY = item.dragOrigin.y + item.dragOffset.y; item.scaleX = 1.025; item.scaleY = 1.025; } else { item.translateX = x; item.translateY = y; if (Date.now() > item.spawnDate) { // reveal element if (item.opacity === 0) { introItemView(item, x, y, vx, vy); } // make sure is default scale every frame item.scaleX = 1; item.scaleY = 1; item.opacity = 1; } } }; var introItemView = function introItemView(item, x, y, vx, vy) { if (item.interactionMethod === InteractionMethod.NONE) { item.translateX = null; item.translateX = x; item.translateY = null; item.translateY = y; } else if (item.interactionMethod === InteractionMethod.DROP) { item.translateX = null; item.translateX = x - vx * 20; item.translateY = null; item.translateY = y - vy * 10; item.scaleX = 0.8; item.scaleY = 0.8; } else if (item.interactionMethod === InteractionMethod.BROWSE) { item.translateY = null; item.translateY = y - 30; } else if (item.interactionMethod === InteractionMethod.API) { item.translateX = null; item.translateX = x - 30; item.translateY = null; } }; /** * Removes an existing item * @param root * @param action */ var removeItemView = function removeItemView(_ref3) { var root = _ref3.root, action = _ref3.action; var id = action.id; // get the view matching the given id var view = root.childViews.find(function(child) { return child.id === id; }); // if no view found, exit if (!view) { return; } // animate view out of view view.scaleX = 0.9; view.scaleY = 0.9; view.opacity = 0; // mark for removal view.markedForRemoval = true; }; var getItemHeight = function getItemHeight(child) { return ( child.rect.element.height + child.rect.element.marginBottom * 0.5 + child.rect.element.marginTop * 0.5 ); }; var getItemWidth = function getItemWidth(child) { return ( child.rect.element.width + child.rect.element.marginLeft * 0.5 + child.rect.element.marginRight * 0.5 ); }; var dragItem = function dragItem(_ref4) { var root = _ref4.root, action = _ref4.action; var id = action.id, dragState = action.dragState; // reference to item var item = root.query('GET_ITEM', { id: id }); // get the view matching the given id var view = root.childViews.find(function(child) { return child.id === id; }); var numItems = root.childViews.length; var oldIndex = dragState.getItemIndex(item); // if no view found, exit if (!view) return; var dragPosition = { x: view.dragOrigin.x + view.dragOffset.x + view.dragCenter.x, y: view.dragOrigin.y + view.dragOffset.y + view.dragCenter.y, }; // get drag area dimensions var dragHeight = getItemHeight(view); var dragWidth = getItemWidth(view); // get rows and columns (There will always be at least one row and one column if a file is present) var cols = Math.floor(root.rect.outer.width / dragWidth); if (cols > numItems) cols = numItems; // rows are used to find when we have left the preview area bounding box var rows = Math.floor(numItems / cols + 1); dropAreaDimensions.setHeight = dragHeight * rows; dropAreaDimensions.setWidth = dragWidth * cols; // get new index of dragged item var location = { y: Math.floor(dragPosition.y / dragHeight), x: Math.floor(dragPosition.x / dragWidth), getGridIndex: function getGridIndex() { if ( dragPosition.y > dropAreaDimensions.getHeight || dragPosition.y < 0 || dragPosition.x > dropAreaDimensions.getWidth || dragPosition.x < 0 ) return oldIndex; return this.y * cols + this.x; }, getColIndex: function getColIndex() { var items = root.query('GET_ACTIVE_ITEMS'); var visibleChildren = root.childViews.filter(function(child) { return child.rect.element.height; }); var children = items.map(function(item) { return visibleChildren.find(function(childView) { return childView.id === item.id; }); }); var currentIndex = children.findIndex(function(child) { return child === view; }); var dragHeight = getItemHeight(view); var l = children.length; var idx = l; var childHeight = 0; var childBottom = 0; var childTop = 0; for (var i = 0; i < l; i++) { childHeight = getItemHeight(children[i]); childTop = childBottom; childBottom = childTop + childHeight; if (dragPosition.y < childBottom) { if (currentIndex > i) { if (dragPosition.y < childTop + dragHeight) { idx = i; break; } continue; } idx = i; break; } } return idx; }, }; // get new index var index = cols > 1 ? location.getGridIndex() : location.getColIndex(); root.dispatch('MOVE_ITEM', { query: view, index: index }); // if the index of the item changed, dispatch reorder action var currentIndex = dragState.getIndex(); if (currentIndex === undefined || currentIndex !== index) { dragState.setIndex(index); if (currentIndex === undefined) return; root.dispatch('DID_REORDER_ITEMS', { items: root.query('GET_ACTIVE_ITEMS'), origin: oldIndex, target: index, }); } }; /** * Setup action routes */ var route$2 = createRoute({ DID_ADD_ITEM: addItemView, DID_REMOVE_ITEM: removeItemView, DID_DRAG_ITEM: dragItem, }); /** * Write to view * @param root * @param actions * @param props */ var write$5 = function write(_ref5) { var root = _ref5.root, props = _ref5.props, actions = _ref5.actions, shouldOptimize = _ref5.shouldOptimize; // route actions route$2({ root: root, props: props, actions: actions }); var dragCoordinates = props.dragCoordinates; // available space on horizontal axis var horizontalSpace = root.rect.element.width; // only draw children that have dimensions var visibleChildren = root.childViews.filter(function(child) { return child.rect.element.height; }); // sort based on current active items var children = root .query('GET_ACTIVE_ITEMS') .map(function(item) { return visibleChildren.find(function(child) { return child.id === item.id; }); }) .filter(function(item) { return item; }); // get index var dragIndex = dragCoordinates ? getItemIndexByPosition(root, children, dragCoordinates) : null; // add index is used to reserve the dropped/added item index till the actual item is rendered var addIndex = root.ref.addIndex || null; // add index no longer needed till possibly next draw root.ref.addIndex = null; var dragIndexOffset = 0; var removeIndexOffset = 0; var addIndexOffset = 0; if (children.length === 0) return; var childRect = children[0].rect.element; var itemVerticalMargin = childRect.marginTop + childRect.marginBottom; var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight; var itemWidth = childRect.width + itemHorizontalMargin; var itemHeight = childRect.height + itemVerticalMargin; var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth); // stack if (itemsPerRow === 1) { var offsetY = 0; var dragOffset = 0; children.forEach(function(child, index) { if (dragIndex) { var dist = index - dragIndex; if (dist === -2) { dragOffset = -itemVerticalMargin * 0.25; } else if (dist === -1) { dragOffset = -itemVerticalMargin * 0.75; } else if (dist === 0) { dragOffset = itemVerticalMargin * 0.75; } else if (dist === 1) { dragOffset = itemVerticalMargin * 0.25; } else { dragOffset = 0; } } if (shouldOptimize) { child.translateX = null; child.translateY = null; } if (!child.markedForRemoval) { moveItem(child, 0, offsetY + dragOffset); } var itemHeight = child.rect.element.height + itemVerticalMargin; var visualHeight = itemHeight * (child.markedForRemoval ? child.opacity : 1); offsetY += visualHeight; }); } // grid else { var prevX = 0; var prevY = 0; children.forEach(function(child, index) { if (index === dragIndex) { dragIndexOffset = 1; } if (index === addIndex) { addIndexOffset += 1; } if (child.markedForRemoval && child.opacity < 0.5) { removeIndexOffset -= 1; } var visualIndex = index + addIndexOffset + dragIndexOffset + removeIndexOffset; var indexX = visualIndex % itemsPerRow; var indexY = Math.floor(visualIndex / itemsPerRow); var offsetX = indexX * itemWidth; var offsetY = indexY * itemHeight; var vectorX = Math.sign(offsetX - prevX); var vectorY = Math.sign(offsetY - prevY); prevX = offsetX; prevY = offsetY; if (child.markedForRemoval) return; if (shouldOptimize) { child.translateX = null; child.translateY = null; } moveItem(child, offsetX, offsetY, vectorX, vectorY); }); } }; /** * Filters actions that are meant specifically for a certain child of the list * @param child * @param actions */ var filterSetItemActions = function filterSetItemActions(child, actions) { return actions.filter(function(action) { // if action has an id, filter out actions that don't have this child id if (action.data && action.data.id) { return child.id === action.data.id; } // allow all other actions return true; }); }; var list = createView({ create: create$8, write: write$5, tag: 'ul', name: 'list', didWriteView: function didWriteView(_ref6) { var root = _ref6.root; root.childViews .filter(function(view) { return view.markedForRemoval && view.opacity === 0 && view.resting; }) .forEach(function(view) { view._destroy(); root.removeChildView(view); }); }, filterFrameActionsForChild: filterSetItemActions, mixins: { apis: ['dragCoordinates'], }, }); var create$9 = function create(_ref) { var root = _ref.root, props = _ref.props; root.ref.list = root.appendChildView(root.createChildView(list)); props.dragCoordinates = null; props.overflowing = false; }; var storeDragCoordinates = function storeDragCoordinates(_ref2) { var root = _ref2.root, props = _ref2.props, action = _ref2.action; if (!root.query('GET_ITEM_INSERT_LOCATION_FREEDOM')) return; props.dragCoordinates = { left: action.position.scopeLeft - root.ref.list.rect.element.left, top: action.position.scopeTop - (root.rect.outer.top + root.rect.element.marginTop + root.rect.element.scrollTop), }; }; var clearDragCoordinates = function clearDragCoordinates(_ref3) { var props = _ref3.props; props.dragCoordinates = null; }; var route$3 = createRoute({ DID_DRAG: storeDragCoordinates, DID_END_DRAG: clearDragCoordinates, }); var write$6 = function write(_ref4) { var root = _ref4.root, props = _ref4.props, actions = _ref4.actions; // route actions route$3({ root: root, props: props, actions: actions }); // current drag position root.ref.list.dragCoordinates = props.dragCoordinates; // if currently overflowing but no longer received overflow if (props.overflowing && !props.overflow) { props.overflowing = false; // reset overflow state root.element.dataset.state = ''; root.height = null; } // if is not overflowing currently but does receive overflow value if (props.overflow) { var newHeight = Math.round(props.overflow); if (newHeight !== root.height) { props.overflowing = true; root.element.dataset.state = 'overflow'; root.height = newHeight; } } }; var listScroller = createView({ create: create$9, write: write$6, name: 'list-scroller', mixins: { apis: ['overflow', 'dragCoordinates'], styles: ['height', 'translateY'], animations: { translateY: 'spring', }, }, }); var attrToggle = function attrToggle(element, name, state) { var enabledValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; if (state) { attr(element, name, enabledValue); } else { element.removeAttribute(name); } }; var resetFileInput = function resetFileInput(input) { // no value, no need to reset if (!input || input.value === '') { return; } try { // for modern browsers input.value = ''; } catch (err) {} // for IE10 if (input.value) { // quickly append input to temp form and reset form var form = createElement$1('form'); var parentNode = input.parentNode; var ref = input.nextSibling; form.appendChild(input); form.reset(); // re-inject input where it originally was if (ref) { parentNode.insertBefore(input, ref); } else { parentNode.appendChild(input); } } }; var create$a = function create(_ref) { var root = _ref.root, props = _ref.props; // set id so can be referenced from outside labels root.element.id = 'filepond--browser-' + props.id; // set name of element (is removed when a value is set) attr(root.element, 'name', root.query('GET_NAME')); // we have to link this element to the status element attr(root.element, 'aria-controls', 'filepond--assistant-' + props.id); // set label, we use labelled by as otherwise the screenreader does not read the "browse" text in the label (as it has tabindex: 0) attr(root.element, 'aria-labelledby', 'filepond--drop-label-' + props.id); // set configurable props setAcceptedFileTypes({ root: root, action: { value: root.query('GET_ACCEPTED_FILE_TYPES') }, }); toggleAllowMultiple({ root: root, action: { value: root.query('GET_ALLOW_MULTIPLE') } }); toggleDirectoryFilter({ root: root, action: { value: root.query('GET_ALLOW_DIRECTORIES_ONLY') }, }); toggleDisabled({ root: root }); toggleRequired({ root: root, action: { value: root.query('GET_REQUIRED') } }); setCaptureMethod({ root: root, action: { value: root.query('GET_CAPTURE_METHOD') } }); // handle changes to the input field root.ref.handleChange = function(e) { if (!root.element.value) { return; } // extract files and move value of webkitRelativePath path to _relativePath var files = Array.from(root.element.files).map(function(file) { file._relativePath = file.webkitRelativePath; return file; }); // we add a little delay so the OS file select window can move out of the way before we add our file setTimeout(function() { // load files props.onload(files); // reset input, it's just for exposing a method to drop files, should not retain any state resetFileInput(root.element); }, 250); }; root.element.addEventListener('change', root.ref.handleChange); }; var setAcceptedFileTypes = function setAcceptedFileTypes(_ref2) { var root = _ref2.root, action = _ref2.action; if (!root.query('GET_ALLOW_SYNC_ACCEPT_ATTRIBUTE')) return; attrToggle( root.element, 'accept', !!action.value, action.value ? action.value.join(',') : '' ); }; var toggleAllowMultiple = function toggleAllowMultiple(_ref3) { var root = _ref3.root, action = _ref3.action; attrToggle(root.element, 'multiple', action.value); }; var toggleDirectoryFilter = function toggleDirectoryFilter(_ref4) { var root = _ref4.root, action = _ref4.action; attrToggle(root.element, 'webkitdirectory', action.value); }; var toggleDisabled = function toggleDisabled(_ref5) { var root = _ref5.root; var isDisabled = root.query('GET_DISABLED'); var doesAllowBrowse = root.query('GET_ALLOW_BROWSE'); var disableField = isDisabled || !doesAllowBrowse; attrToggle(root.element, 'disabled', disableField); }; var toggleRequired = function toggleRequired(_ref6) { var root = _ref6.root, action = _ref6.action; // want to remove required, always possible if (!action.value) { attrToggle(root.element, 'required', false); } // if want to make required, only possible when zero items else if (root.query('GET_TOTAL_ITEMS') === 0) { attrToggle(root.element, 'required', true); } }; var setCaptureMethod = function setCaptureMethod(_ref7) { var root = _ref7.root, action = _ref7.action; attrToggle( root.element, 'capture', !!action.value, action.value === true ? '' : action.value ); }; var updateRequiredStatus = function updateRequiredStatus(_ref8) { var root = _ref8.root; var element = root.element; // always remove the required attribute when more than zero items if (root.query('GET_TOTAL_ITEMS') > 0) { attrToggle(element, 'required', false); attrToggle(element, 'name', false); } else { // add name attribute attrToggle(element, 'name', true, root.query('GET_NAME')); // remove any validation messages var shouldCheckValidity = root.query('GET_CHECK_VALIDITY'); if (shouldCheckValidity) { element.setCustomValidity(''); } // we only add required if the field has been deemed required if (root.query('GET_REQUIRED')) { attrToggle(element, 'required', true); } } }; var updateFieldValidityStatus = function updateFieldValidityStatus(_ref9) { var root = _ref9.root; var shouldCheckValidity = root.query('GET_CHECK_VALIDITY'); if (!shouldCheckValidity) return; root.element.setCustomValidity(root.query('GET_LABEL_INVALID_FIELD')); }; var browser = createView({ tag: 'input', name: 'browser', ignoreRect: true, ignoreRectUpdate: true, attributes: { type: 'file', }, create: create$a, destroy: function destroy(_ref10) { var root = _ref10.root; root.element.removeEventListener('change', root.ref.handleChange); }, write: createRoute({ DID_LOAD_ITEM: updateRequiredStatus, DID_REMOVE_ITEM: updateRequiredStatus, DID_THROW_ITEM_INVALID: updateFieldValidityStatus, DID_SET_DISABLED: toggleDisabled, DID_SET_ALLOW_BROWSE: toggleDisabled, DID_SET_ALLOW_DIRECTORIES_ONLY: toggleDirectoryFilter, DID_SET_ALLOW_MULTIPLE: toggleAllowMultiple, DID_SET_ACCEPTED_FILE_TYPES: setAcceptedFileTypes, DID_SET_CAPTURE_METHOD: setCaptureMethod, DID_SET_REQUIRED: toggleRequired, }), }); var Key = { ENTER: 13, SPACE: 32, }; var create$b = function create(_ref) { var root = _ref.root, props = _ref.props; // create the label and link it to the file browser var label = createElement$1('label'); attr(label, 'for', 'filepond--browser-' + props.id); // use for labeling file input (aria-labelledby on file input) attr(label, 'id', 'filepond--drop-label-' + props.id); // hide the label for screenreaders, the input element will read the contents of the label when it's focussed. If we don't set aria-hidden the screenreader will also navigate the contents of the label separately from the input. attr(label, 'aria-hidden', 'true'); // handle keys root.ref.handleKeyDown = function(e) { var isActivationKey = e.keyCode === Key.ENTER || e.keyCode === Key.SPACE; if (!isActivationKey) return; // stops from triggering the element a second time e.preventDefault(); // click link (will then in turn activate file input) root.ref.label.click(); }; root.ref.handleClick = function(e) { var isLabelClick = e.target === label || label.contains(e.target); // don't want to click twice if (isLabelClick) return; // click link (will then in turn activate file input) root.ref.label.click(); }; // attach events label.addEventListener('keydown', root.ref.handleKeyDown); root.element.addEventListener('click', root.ref.handleClick); // update updateLabelValue(label, props.caption); // add! root.appendChild(label); root.ref.label = label; }; var updateLabelValue = function updateLabelValue(label, value) { label.innerHTML = value; var clickable = label.querySelector('.filepond--label-action'); if (clickable) { attr(clickable, 'tabindex', '0'); } return value; }; var dropLabel = createView({ name: 'drop-label', ignoreRect: true, create: create$b, destroy: function destroy(_ref2) { var root = _ref2.root; root.ref.label.addEventListener('keydown', root.ref.handleKeyDown); root.element.removeEventListener('click', root.ref.handleClick); }, write: createRoute({ DID_SET_LABEL_IDLE: function DID_SET_LABEL_IDLE(_ref3) { var root = _ref3.root, action = _ref3.action; updateLabelValue(root.ref.label, action.value); }, }), mixins: { styles: ['opacity', 'translateX', 'translateY'], animations: { opacity: { type: 'tween', duration: 150 }, translateX: 'spring', translateY: 'spring', }, }, }); var blob = createView({ name: 'drip-blob', ignoreRect: true, mixins: { styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'], animations: { scaleX: 'spring', scaleY: 'spring', translateX: 'spring', translateY: 'spring', opacity: { type: 'tween', duration: 250 }, }, }, }); var addBlob = function addBlob(_ref) { var root = _ref.root; var centerX = root.rect.element.width * 0.5; var centerY = root.rect.element.height * 0.5; root.ref.blob = root.appendChildView( root.createChildView(blob, { opacity: 0, scaleX: 2.5, scaleY: 2.5, translateX: centerX, translateY: centerY, }) ); }; var moveBlob = function moveBlob(_ref2) { var root = _ref2.root, action = _ref2.action; if (!root.ref.blob) { addBlob({ root: root }); return; } root.ref.blob.translateX = action.position.scopeLeft; root.ref.blob.translateY = action.position.scopeTop; root.ref.blob.scaleX = 1; root.ref.blob.scaleY = 1; root.ref.blob.opacity = 1; }; var hideBlob = function hideBlob(_ref3) { var root = _ref3.root; if (!root.ref.blob) { return; } root.ref.blob.opacity = 0; }; var explodeBlob = function explodeBlob(_ref4) { var root = _ref4.root; if (!root.ref.blob) { return; } root.ref.blob.scaleX = 2.5; root.ref.blob.scaleY = 2.5; root.ref.blob.opacity = 0; }; var write$7 = function write(_ref5) { var root = _ref5.root, props = _ref5.props, actions = _ref5.actions; route$4({ root: root, props: props, actions: actions }); var blob = root.ref.blob; if (actions.length === 0 && blob && blob.opacity === 0) { root.removeChildView(blob); root.ref.blob = null; } }; var route$4 = createRoute({ DID_DRAG: moveBlob, DID_DROP: explodeBlob, DID_END_DRAG: hideBlob, }); var drip = createView({ ignoreRect: true, ignoreRectUpdate: true, name: 'drip', write: write$7, }); var create$c = function create(_ref) { var root = _ref.root; return (root.ref.fields = {}); }; var getField = function getField(root, id) { return root.ref.fields[id]; }; var syncFieldPositionsWithItems = function syncFieldPositionsWithItems(root) { root.query('GET_ACTIVE_ITEMS').forEach(function(item) { if (!root.ref.fields[item.id]) return; root.element.appendChild(root.ref.fields[item.id]); }); }; var didReorderItems = function didReorderItems(_ref2) { var root = _ref2.root; return syncFieldPositionsWithItems(root); }; var didAddItem = function didAddItem(_ref3) { var root = _ref3.root, action = _ref3.action; var dataContainer = createElement$1('input'); dataContainer.type = 'hidden'; dataContainer.name = root.query('GET_NAME'); dataContainer.disabled = root.query('GET_DISABLED'); root.ref.fields[action.id] = dataContainer; syncFieldPositionsWithItems(root); }; var didLoadItem$1 = function didLoadItem(_ref4) { var root = _ref4.root, action = _ref4.action; var field = getField(root, action.id); if (!field || action.serverFileReference === null) return; field.value = action.serverFileReference; }; var didSetDisabled = function didSetDisabled(_ref5) { var root = _ref5.root; root.element.disabled = root.query('GET_DISABLED'); }; var didRemoveItem = function didRemoveItem(_ref6) { var root = _ref6.root, action = _ref6.action; var field = getField(root, action.id); if (!field) return; if (field.parentNode) field.parentNode.removeChild(field); delete root.ref.fields[action.id]; }; var didDefineValue = function didDefineValue(_ref7) { var root = _ref7.root, action = _ref7.action; var field = getField(root, action.id); if (!field) return; if (action.value === null) { field.removeAttribute('value'); } else { field.value = action.value; } syncFieldPositionsWithItems(root); }; var write$8 = createRoute({ DID_SET_DISABLED: didSetDisabled, DID_ADD_ITEM: didAddItem, DID_LOAD_ITEM: didLoadItem$1, DID_REMOVE_ITEM: didRemoveItem, DID_DEFINE_VALUE: didDefineValue, DID_REORDER_ITEMS: didReorderItems, DID_SORT_ITEMS: didReorderItems, }); var data = createView({ tag: 'fieldset', name: 'data', create: create$c, write: write$8, ignoreRect: true, }); var getRootNode = function getRootNode(element) { return 'getRootNode' in element ? element.getRootNode() : document; }; var images = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'tiff']; var text$1 = ['css', 'csv', 'html', 'txt']; var map = { zip: 'zip|compressed', epub: 'application/epub+zip', }; var guesstimateMimeType = function guesstimateMimeType() { var extension = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; extension = extension.toLowerCase(); if (images.includes(extension)) { return ( 'image/' + (extension === 'jpg' ? 'jpeg' : extension === 'svg' ? 'svg+xml' : extension) ); } if (text$1.includes(extension)) { return 'text/' + extension; } return map[extension] || ''; }; var requestDataTransferItems = function requestDataTransferItems(dataTransfer) { return new Promise(function(resolve, reject) { // try to get links from transfer, if found we'll exit immediately (unless a file is in the dataTransfer as well, this is because Firefox could represent the file as a URL and a file object at the same time) var links = getLinks(dataTransfer); if (links.length && !hasFiles(dataTransfer)) { return resolve(links); } // try to get files from the transfer getFiles(dataTransfer).then(resolve); }); }; /** * Test if datatransfer has files */ var hasFiles = function hasFiles(dataTransfer) { if (dataTransfer.files) return dataTransfer.files.length > 0; return false; }; /** * Extracts files from a DataTransfer object */ var getFiles = function getFiles(dataTransfer) { return new Promise(function(resolve, reject) { // get the transfer items as promises var promisedFiles = (dataTransfer.items ? Array.from(dataTransfer.items) : []) // only keep file system items (files and directories) .filter(function(item) { return isFileSystemItem(item); }) // map each item to promise .map(function(item) { return getFilesFromItem(item); }); // if is empty, see if we can extract some info from the files property as a fallback if (!promisedFiles.length) { // TODO: test for directories (should not be allowed) // Use FileReader, problem is that the files property gets lost in the process resolve(dataTransfer.files ? Array.from(dataTransfer.files) : []); return; } // done! Promise.all(promisedFiles) .then(function(returnedFileGroups) { // flatten groups var files = []; returnedFileGroups.forEach(function(group) { files.push.apply(files, group); }); // done (filter out empty files)! resolve( files .filter(function(file) { return file; }) .map(function(file) { if (!file._relativePath) file._relativePath = file.webkitRelativePath; return file; }) ); }) .catch(console.error); }); }; var isFileSystemItem = function isFileSystemItem(item) { if (isEntry(item)) { var entry = getAsEntry(item); if (entry) { return entry.isFile || entry.isDirectory; } } return item.kind === 'file'; }; var getFilesFromItem = function getFilesFromItem(item) { return new Promise(function(resolve, reject) { if (isDirectoryEntry(item)) { getFilesInDirectory(getAsEntry(item)) .then(resolve) .catch(reject); return; } resolve([item.getAsFile()]); }); }; var getFilesInDirectory = function getFilesInDirectory(entry) { return new Promise(function(resolve, reject) { var files = []; // the total entries to read var dirCounter = 0; var fileCounter = 0; var resolveIfDone = function resolveIfDone() { if (fileCounter === 0 && dirCounter === 0) { resolve(files); } }; // the recursive function var readEntries = function readEntries(dirEntry) { dirCounter++; var directoryReader = dirEntry.createReader(); // directories are returned in batches, we need to process all batches before we're done var readBatch = function readBatch() { directoryReader.readEntries(function(entries) { if (entries.length === 0) { dirCounter--; resolveIfDone(); return; } entries.forEach(function(entry) { // recursively read more directories if (entry.isDirectory) { readEntries(entry); } else { // read as file fileCounter++; entry.file(function(file) { var correctedFile = correctMissingFileType(file); if (entry.fullPath) correctedFile._relativePath = entry.fullPath; files.push(correctedFile); fileCounter--; resolveIfDone(); }); } }); // try to get next batch of files readBatch(); }, reject); }; // read first batch of files readBatch(); }; // go! readEntries(entry); }); }; var correctMissingFileType = function correctMissingFileType(file) { if (file.type.length) return file; var date = file.lastModifiedDate; var name = file.name; var type = guesstimateMimeType(getExtensionFromFilename(file.name)); if (!type.length) return file; file = file.slice(0, file.size, type); file.name = name; file.lastModifiedDate = date; return file; }; var isDirectoryEntry = function isDirectoryEntry(item) { return isEntry(item) && (getAsEntry(item) || {}).isDirectory; }; var isEntry = function isEntry(item) { return 'webkitGetAsEntry' in item; }; var getAsEntry = function getAsEntry(item) { return item.webkitGetAsEntry(); }; /** * Extracts links from a DataTransfer object */ var getLinks = function getLinks(dataTransfer) { var links = []; try { // look in meta data property links = getLinksFromTransferMetaData(dataTransfer); if (links.length) { return links; } links = getLinksFromTransferURLData(dataTransfer); } catch (e) { // nope nope nope (probably IE trouble) } return links; }; var getLinksFromTransferURLData = function getLinksFromTransferURLData(dataTransfer) { var data = dataTransfer.getData('url'); if (typeof data === 'string' && data.length) { return [data]; } return []; }; var getLinksFromTransferMetaData = function getLinksFromTransferMetaData(dataTransfer) { var data = dataTransfer.getData('text/html'); if (typeof data === 'string' && data.length) { var matches = data.match(/src\s*=\s*"(.+?)"/); if (matches) { return [matches[1]]; } } return []; }; var dragNDropObservers = []; var eventPosition = function eventPosition(e) { return { pageLeft: e.pageX, pageTop: e.pageY, scopeLeft: e.offsetX || e.layerX, scopeTop: e.offsetY || e.layerY, }; }; var createDragNDropClient = function createDragNDropClient( element, scopeToObserve, filterElement ) { var observer = getDragNDropObserver(scopeToObserve); var client = { element: element, filterElement: filterElement, state: null, ondrop: function ondrop() {}, onenter: function onenter() {}, ondrag: function ondrag() {}, onexit: function onexit() {}, onload: function onload() {}, allowdrop: function allowdrop() {}, }; client.destroy = observer.addListener(client); return client; }; var getDragNDropObserver = function getDragNDropObserver(element) { // see if already exists, if so, return var observer = dragNDropObservers.find(function(item) { return item.element === element; }); if (observer) { return observer; } // create new observer, does not yet exist for this element var newObserver = createDragNDropObserver(element); dragNDropObservers.push(newObserver); return newObserver; }; var createDragNDropObserver = function createDragNDropObserver(element) { var clients = []; var routes = { dragenter: dragenter, dragover: dragover, dragleave: dragleave, drop: drop, }; var handlers = {}; forin(routes, function(event, createHandler) { handlers[event] = createHandler(element, clients); element.addEventListener(event, handlers[event], false); }); var observer = { element: element, addListener: function addListener(client) { // add as client clients.push(client); // return removeListener function return function() { // remove client clients.splice(clients.indexOf(client), 1); // if no more clients, clean up observer if (clients.length === 0) { dragNDropObservers.splice(dragNDropObservers.indexOf(observer), 1); forin(routes, function(event) { element.removeEventListener(event, handlers[event], false); }); } }; }, }; return observer; }; var elementFromPoint = function elementFromPoint(root, point) { if (!('elementFromPoint' in root)) { root = document; } return root.elementFromPoint(point.x, point.y); }; var isEventTarget = function isEventTarget(e, target) { // get root var root = getRootNode(target); // get element at position // if root is not actual shadow DOM and does not have elementFromPoint method, use the one on document var elementAtPosition = elementFromPoint(root, { x: e.pageX - window.pageXOffset, y: e.pageY - window.pageYOffset, }); // test if target is the element or if one of its children is return elementAtPosition === target || target.contains(elementAtPosition); }; var initialTarget = null; var setDropEffect = function setDropEffect(dataTransfer, effect) { // is in try catch as IE11 will throw error if not try { dataTransfer.dropEffect = effect; } catch (e) {} }; var dragenter = function dragenter(root, clients) { return function(e) { e.preventDefault(); initialTarget = e.target; clients.forEach(function(client) { var element = client.element, onenter = client.onenter; if (isEventTarget(e, element)) { client.state = 'enter'; // fire enter event onenter(eventPosition(e)); } }); }; }; var dragover = function dragover(root, clients) { return function(e) { e.preventDefault(); var dataTransfer = e.dataTransfer; requestDataTransferItems(dataTransfer).then(function(items) { var overDropTarget = false; clients.some(function(client) { var filterElement = client.filterElement, element = client.element, onenter = client.onenter, onexit = client.onexit, ondrag = client.ondrag, allowdrop = client.allowdrop; // by default we can drop setDropEffect(dataTransfer, 'copy'); // allow transfer of these items var allowsTransfer = allowdrop(items); // only used when can be dropped on page if (!allowsTransfer) { setDropEffect(dataTransfer, 'none'); return; } // targetting this client if (isEventTarget(e, element)) { overDropTarget = true; // had no previous state, means we are entering this client if (client.state === null) { client.state = 'enter'; onenter(eventPosition(e)); return; } // now over element (no matter if it allows the drop or not) client.state = 'over'; // needs to allow transfer if (filterElement && !allowsTransfer) { setDropEffect(dataTransfer, 'none'); return; } // dragging ondrag(eventPosition(e)); } else { // should be over an element to drop if (filterElement && !overDropTarget) { setDropEffect(dataTransfer, 'none'); } // might have just left this client? if (client.state) { client.state = null; onexit(eventPosition(e)); } } }); }); }; }; var drop = function drop(root, clients) { return function(e) { e.preventDefault(); var dataTransfer = e.dataTransfer; requestDataTransferItems(dataTransfer).then(function(items) { clients.forEach(function(client) { var filterElement = client.filterElement, element = client.element, ondrop = client.ondrop, onexit = client.onexit, allowdrop = client.allowdrop; client.state = null; // if we're filtering on element we need to be over the element to drop if (filterElement && !isEventTarget(e, element)) return; // no transfer for this client if (!allowdrop(items)) return onexit(eventPosition(e)); // we can drop these items on this client ondrop(eventPosition(e), items); }); }); }; }; var dragleave = function dragleave(root, clients) { return function(e) { if (initialTarget !== e.target) { return; } clients.forEach(function(client) { var onexit = client.onexit; client.state = null; onexit(eventPosition(e)); }); }; }; var createHopper = function createHopper(scope, validateItems, options) { // is now hopper scope scope.classList.add('filepond--hopper'); // shortcuts var catchesDropsOnPage = options.catchesDropsOnPage, requiresDropOnElement = options.requiresDropOnElement, _options$filterItems = options.filterItems, filterItems = _options$filterItems === void 0 ? function(items) { return items; } : _options$filterItems; // create a dnd client var client = createDragNDropClient( scope, catchesDropsOnPage ? document.documentElement : scope, requiresDropOnElement ); // current client state var lastState = ''; var currentState = ''; // determines if a file may be dropped client.allowdrop = function(items) { // TODO: if we can, throw error to indicate the items cannot by dropped return validateItems(filterItems(items)); }; client.ondrop = function(position, items) { var filteredItems = filterItems(items); if (!validateItems(filteredItems)) { api.ondragend(position); return; } currentState = 'drag-drop'; api.onload(filteredItems, position); }; client.ondrag = function(position) { api.ondrag(position); }; client.onenter = function(position) { currentState = 'drag-over'; api.ondragstart(position); }; client.onexit = function(position) { currentState = 'drag-exit'; api.ondragend(position); }; var api = { updateHopperState: function updateHopperState() { if (lastState !== currentState) { scope.dataset.hopperState = currentState; lastState = currentState; } }, onload: function onload() {}, ondragstart: function ondragstart() {}, ondrag: function ondrag() {}, ondragend: function ondragend() {}, destroy: function destroy() { // destroy client client.destroy(); }, }; return api; }; var listening = false; var listeners$1 = []; var handlePaste = function handlePaste(e) { // if is pasting in input or textarea and the target is outside of a filepond scope, ignore var activeEl = document.activeElement; if (activeEl && /textarea|input/i.test(activeEl.nodeName)) { // test textarea or input is contained in filepond root var inScope = false; var element = activeEl; while (element !== document.body) { if (element.classList.contains('filepond--root')) { inScope = true; break; } element = element.parentNode; } if (!inScope) return; } requestDataTransferItems(e.clipboardData).then(function(files) { // no files received if (!files.length) { return; } // notify listeners of received files listeners$1.forEach(function(listener) { return listener(files); }); }); }; var listen = function listen(cb) { // can't add twice if (listeners$1.includes(cb)) { return; } // add initial listener listeners$1.push(cb); // setup paste listener for entire page if (listening) { return; } listening = true; document.addEventListener('paste', handlePaste); }; var unlisten = function unlisten(listener) { arrayRemove(listeners$1, listeners$1.indexOf(listener)); // clean up if (listeners$1.length === 0) { document.removeEventListener('paste', handlePaste); listening = false; } }; var createPaster = function createPaster() { var cb = function cb(files) { api.onload(files); }; var api = { destroy: function destroy() { unlisten(cb); }, onload: function onload() {}, }; listen(cb); return api; }; /** * Creates the file view */ var create$d = function create(_ref) { var root = _ref.root, props = _ref.props; root.element.id = 'filepond--assistant-' + props.id; attr(root.element, 'role', 'status'); attr(root.element, 'aria-live', 'polite'); attr(root.element, 'aria-relevant', 'additions'); }; var addFilesNotificationTimeout = null; var notificationClearTimeout = null; var filenames = []; var assist = function assist(root, message) { root.element.textContent = message; }; var clear$1 = function clear(root) { root.element.textContent = ''; }; var listModified = function listModified(root, filename, label) { var total = root.query('GET_TOTAL_ITEMS'); assist( root, label + ' ' + filename + ', ' + total + ' ' + (total === 1 ? root.query('GET_LABEL_FILE_COUNT_SINGULAR') : root.query('GET_LABEL_FILE_COUNT_PLURAL')) ); // clear group after set amount of time so the status is not read twice clearTimeout(notificationClearTimeout); notificationClearTimeout = setTimeout(function() { clear$1(root); }, 1500); }; var isUsingFilePond = function isUsingFilePond(root) { return root.element.parentNode.contains(document.activeElement); }; var itemAdded = function itemAdded(_ref2) { var root = _ref2.root, action = _ref2.action; if (!isUsingFilePond(root)) { return; } root.element.textContent = ''; var item = root.query('GET_ITEM', action.id); filenames.push(item.filename); clearTimeout(addFilesNotificationTimeout); addFilesNotificationTimeout = setTimeout(function() { listModified(root, filenames.join(', '), root.query('GET_LABEL_FILE_ADDED')); filenames.length = 0; }, 750); }; var itemRemoved = function itemRemoved(_ref3) { var root = _ref3.root, action = _ref3.action; if (!isUsingFilePond(root)) { return; } var item = action.item; listModified(root, item.filename, root.query('GET_LABEL_FILE_REMOVED')); }; var itemProcessed = function itemProcessed(_ref4) { var root = _ref4.root, action = _ref4.action; // will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file var item = root.query('GET_ITEM', action.id); var filename = item.filename; var label = root.query('GET_LABEL_FILE_PROCESSING_COMPLETE'); assist(root, filename + ' ' + label); }; var itemProcessedUndo = function itemProcessedUndo(_ref5) { var root = _ref5.root, action = _ref5.action; var item = root.query('GET_ITEM', action.id); var filename = item.filename; var label = root.query('GET_LABEL_FILE_PROCESSING_ABORTED'); assist(root, filename + ' ' + label); }; var itemError = function itemError(_ref6) { var root = _ref6.root, action = _ref6.action; var item = root.query('GET_ITEM', action.id); var filename = item.filename; // will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file assist(root, action.status.main + ' ' + filename + ' ' + action.status.sub); }; var assistant = createView({ create: create$d, ignoreRect: true, ignoreRectUpdate: true, write: createRoute({ DID_LOAD_ITEM: itemAdded, DID_REMOVE_ITEM: itemRemoved, DID_COMPLETE_ITEM_PROCESSING: itemProcessed, DID_ABORT_ITEM_PROCESSING: itemProcessedUndo, DID_REVERT_ITEM_PROCESSING: itemProcessedUndo, DID_THROW_ITEM_REMOVE_ERROR: itemError, DID_THROW_ITEM_LOAD_ERROR: itemError, DID_THROW_ITEM_INVALID: itemError, DID_THROW_ITEM_PROCESSING_ERROR: itemError, }), tag: 'span', name: 'assistant', }); var toCamels = function toCamels(string) { var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-'; return string.replace(new RegExp(separator + '.', 'g'), function(sub) { return sub.charAt(1).toUpperCase(); }); }; var debounce = function debounce(func) { var interval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16; var immidiateOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var last = Date.now(); var timeout = null; return function() { for ( var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++ ) { args[_key] = arguments[_key]; } clearTimeout(timeout); var dist = Date.now() - last; var fn = function fn() { last = Date.now(); func.apply(void 0, args); }; if (dist < interval) { // we need to delay by the difference between interval and dist // for example: if distance is 10 ms and interval is 16 ms, // we need to wait an additional 6ms before calling the function) if (!immidiateOnly) { timeout = setTimeout(fn, interval - dist); } } else { // go! fn(); } }; }; var MAX_FILES_LIMIT = 1000000; var prevent = function prevent(e) { return e.preventDefault(); }; var create$e = function create(_ref) { var root = _ref.root, props = _ref.props; // Add id var id = root.query('GET_ID'); if (id) { root.element.id = id; } // Add className var className = root.query('GET_CLASS_NAME'); if (className) { className .split(' ') .filter(function(name) { return name.length; }) .forEach(function(name) { root.element.classList.add(name); }); } // Field label root.ref.label = root.appendChildView( root.createChildView( dropLabel, Object.assign({}, props, { translateY: null, caption: root.query('GET_LABEL_IDLE'), }) ) ); // List of items root.ref.list = root.appendChildView( root.createChildView(listScroller, { translateY: null }) ); // Background panel root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'panel-root' })); // Assistant notifies assistive tech when content changes root.ref.assistant = root.appendChildView( root.createChildView(assistant, Object.assign({}, props)) ); // Data root.ref.data = root.appendChildView(root.createChildView(data, Object.assign({}, props))); // Measure (tests if fixed height was set) // DOCTYPE needs to be set for this to work root.ref.measure = createElement$1('div'); root.ref.measure.style.height = '100%'; root.element.appendChild(root.ref.measure); // information on the root height or fixed height status root.ref.bounds = null; // apply initial style properties root.query('GET_STYLES') .filter(function(style) { return !isEmpty(style.value); }) .map(function(_ref2) { var name = _ref2.name, value = _ref2.value; root.element.dataset[name] = value; }); // determine if width changed root.ref.widthPrevious = null; root.ref.widthUpdated = debounce(function() { root.ref.updateHistory = []; root.dispatch('DID_RESIZE_ROOT'); }, 250); // history of updates root.ref.previousAspectRatio = null; root.ref.updateHistory = []; // prevent scrolling and zooming on iOS (only if supports pointer events, for then we can enable reorder) var canHover = window.matchMedia('(pointer: fine) and (hover: hover)').matches; var hasPointerEvents = 'PointerEvent' in window; if (root.query('GET_ALLOW_REORDER') && hasPointerEvents && !canHover) { root.element.addEventListener('touchmove', prevent, { passive: false }); root.element.addEventListener('gesturestart', prevent); } // add credits var credits = root.query('GET_CREDITS'); var hasCredits = credits.length === 2; if (hasCredits) { var frag = document.createElement('a'); frag.className = 'filepond--credits'; frag.setAttribute('aria-hidden', 'true'); frag.href = credits[0]; frag.tabindex = -1; frag.target = '_blank'; frag.rel = 'noopener noreferrer'; frag.textContent = credits[1]; root.element.appendChild(frag); root.ref.credits = frag; } }; var write$9 = function write(_ref3) { var root = _ref3.root, props = _ref3.props, actions = _ref3.actions; // route actions route$5({ root: root, props: props, actions: actions }); // apply style properties actions .filter(function(action) { return /^DID_SET_STYLE_/.test(action.type); }) .filter(function(action) { return !isEmpty(action.data.value); }) .map(function(_ref4) { var type = _ref4.type, data = _ref4.data; var name = toCamels(type.substr(8).toLowerCase(), '_'); root.element.dataset[name] = data.value; root.invalidateLayout(); }); if (root.rect.element.hidden) return; if (root.rect.element.width !== root.ref.widthPrevious) { root.ref.widthPrevious = root.rect.element.width; root.ref.widthUpdated(); } // get box bounds, we do this only once var bounds = root.ref.bounds; if (!bounds) { bounds = root.ref.bounds = calculateRootBoundingBoxHeight(root); // destroy measure element root.element.removeChild(root.ref.measure); root.ref.measure = null; } // get quick references to various high level parts of the upload tool var _root$ref = root.ref, hopper = _root$ref.hopper, label = _root$ref.label, list = _root$ref.list, panel = _root$ref.panel; // sets correct state to hopper scope if (hopper) { hopper.updateHopperState(); } // bool to indicate if we're full or not var aspectRatio = root.query('GET_PANEL_ASPECT_RATIO'); var isMultiItem = root.query('GET_ALLOW_MULTIPLE'); var totalItems = root.query('GET_TOTAL_ITEMS'); var maxItems = isMultiItem ? root.query('GET_MAX_FILES') || MAX_FILES_LIMIT : 1; var atMaxCapacity = totalItems === maxItems; // action used to add item var addAction = actions.find(function(action) { return action.type === 'DID_ADD_ITEM'; }); // if reached max capacity and we've just reached it if (atMaxCapacity && addAction) { // get interaction type var interactionMethod = addAction.data.interactionMethod; // hide label label.opacity = 0; if (isMultiItem) { label.translateY = -40; } else { if (interactionMethod === InteractionMethod.API) { label.translateX = 40; } else if (interactionMethod === InteractionMethod.BROWSE) { label.translateY = 40; } else { label.translateY = 30; } } } else if (!atMaxCapacity) { label.opacity = 1; label.translateX = 0; label.translateY = 0; } var listItemMargin = calculateListItemMargin(root); var listHeight = calculateListHeight(root); var labelHeight = label.rect.element.height; var currentLabelHeight = !isMultiItem || atMaxCapacity ? 0 : labelHeight; var listMarginTop = atMaxCapacity ? list.rect.element.marginTop : 0; var listMarginBottom = totalItems === 0 ? 0 : list.rect.element.marginBottom; var visualHeight = currentLabelHeight + listMarginTop + listHeight.visual + listMarginBottom; var boundsHeight = currentLabelHeight + listMarginTop + listHeight.bounds + listMarginBottom; // link list to label bottom position list.translateY = Math.max(0, currentLabelHeight - list.rect.element.marginTop) - listItemMargin.top; if (aspectRatio) { // fixed aspect ratio // calculate height based on width var width = root.rect.element.width; var height = width * aspectRatio; // clear history if aspect ratio has changed if (aspectRatio !== root.ref.previousAspectRatio) { root.ref.previousAspectRatio = aspectRatio; root.ref.updateHistory = []; } // remember this width var history = root.ref.updateHistory; history.push(width); var MAX_BOUNCES = 2; if (history.length > MAX_BOUNCES * 2) { var l = history.length; var bottom = l - 10; var bounces = 0; for (var i = l; i >= bottom; i--) { if (history[i] === history[i - 2]) { bounces++; } if (bounces >= MAX_BOUNCES) { // dont adjust height return; } } } // fix height of panel so it adheres to aspect ratio panel.scalable = false; panel.height = height; // available height for list var listAvailableHeight = // the height of the panel minus the label height height - currentLabelHeight - // the room we leave open between the end of the list and the panel bottom (listMarginBottom - listItemMargin.bottom) - // if we're full we need to leave some room between the top of the panel and the list (atMaxCapacity ? listMarginTop : 0); if (listHeight.visual > listAvailableHeight) { list.overflow = listAvailableHeight; } else { list.overflow = null; } // set container bounds (so pushes siblings downwards) root.height = height; } else if (bounds.fixedHeight) { // fixed height // fix height of panel panel.scalable = false; // available height for list var _listAvailableHeight = // the height of the panel minus the label height bounds.fixedHeight - currentLabelHeight - // the room we leave open between the end of the list and the panel bottom (listMarginBottom - listItemMargin.bottom) - // if we're full we need to leave some room between the top of the panel and the list (atMaxCapacity ? listMarginTop : 0); // set list height if (listHeight.visual > _listAvailableHeight) { list.overflow = _listAvailableHeight; } else { list.overflow = null; } // no need to set container bounds as these are handles by CSS fixed height } else if (bounds.cappedHeight) { // max-height // not a fixed height panel var isCappedHeight = visualHeight >= bounds.cappedHeight; var panelHeight = Math.min(bounds.cappedHeight, visualHeight); panel.scalable = true; panel.height = isCappedHeight ? panelHeight : panelHeight - listItemMargin.top - listItemMargin.bottom; // available height for list var _listAvailableHeight2 = // the height of the panel minus the label height panelHeight - currentLabelHeight - // the room we leave open between the end of the list and the panel bottom (listMarginBottom - listItemMargin.bottom) - // if we're full we need to leave some room between the top of the panel and the list (atMaxCapacity ? listMarginTop : 0); // set list height (if is overflowing) if (visualHeight > bounds.cappedHeight && listHeight.visual > _listAvailableHeight2) { list.overflow = _listAvailableHeight2; } else { list.overflow = null; } // set container bounds (so pushes siblings downwards) root.height = Math.min( bounds.cappedHeight, boundsHeight - listItemMargin.top - listItemMargin.bottom ); } else { // flexible height // not a fixed height panel var itemMargin = totalItems > 0 ? listItemMargin.top + listItemMargin.bottom : 0; panel.scalable = true; panel.height = Math.max(labelHeight, visualHeight - itemMargin); // set container bounds (so pushes siblings downwards) root.height = Math.max(labelHeight, boundsHeight - itemMargin); } // move credits to bottom if (root.ref.credits && panel.heightCurrent) root.ref.credits.style.transform = 'translateY(' + panel.heightCurrent + 'px)'; }; var calculateListItemMargin = function calculateListItemMargin(root) { var item = root.ref.list.childViews[0].childViews[0]; return item ? { top: item.rect.element.marginTop, bottom: item.rect.element.marginBottom, } : { top: 0, bottom: 0, }; }; var calculateListHeight = function calculateListHeight(root) { var visual = 0; var bounds = 0; // get file list reference var scrollList = root.ref.list; var itemList = scrollList.childViews[0]; var visibleChildren = itemList.childViews.filter(function(child) { return child.rect.element.height; }); var children = root .query('GET_ACTIVE_ITEMS') .map(function(item) { return visibleChildren.find(function(child) { return child.id === item.id; }); }) .filter(function(item) { return item; }); // no children, done! if (children.length === 0) return { visual: visual, bounds: bounds }; var horizontalSpace = itemList.rect.element.width; var dragIndex = getItemIndexByPosition(itemList, children, scrollList.dragCoordinates); var childRect = children[0].rect.element; var itemVerticalMargin = childRect.marginTop + childRect.marginBottom; var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight; var itemWidth = childRect.width + itemHorizontalMargin; var itemHeight = childRect.height + itemVerticalMargin; var newItem = typeof dragIndex !== 'undefined' && dragIndex >= 0 ? 1 : 0; var removedItem = children.find(function(child) { return child.markedForRemoval && child.opacity < 0.45; }) ? -1 : 0; var verticalItemCount = children.length + newItem + removedItem; var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth); // stack if (itemsPerRow === 1) { children.forEach(function(item) { var height = item.rect.element.height + itemVerticalMargin; bounds += height; visual += height * item.opacity; }); } // grid else { bounds = Math.ceil(verticalItemCount / itemsPerRow) * itemHeight; visual = bounds; } return { visual: visual, bounds: bounds }; }; var calculateRootBoundingBoxHeight = function calculateRootBoundingBoxHeight(root) { var height = root.ref.measureHeight || null; var cappedHeight = parseInt(root.style.maxHeight, 10) || null; var fixedHeight = height === 0 ? null : height; return { cappedHeight: cappedHeight, fixedHeight: fixedHeight, }; }; var exceedsMaxFiles = function exceedsMaxFiles(root, items) { var allowReplace = root.query('GET_ALLOW_REPLACE'); var allowMultiple = root.query('GET_ALLOW_MULTIPLE'); var totalItems = root.query('GET_TOTAL_ITEMS'); var maxItems = root.query('GET_MAX_FILES'); // total amount of items being dragged var totalBrowseItems = items.length; // if does not allow multiple items and dragging more than one item if (!allowMultiple && totalBrowseItems > 1) { return true; } // limit max items to one if not allowed to drop multiple items maxItems = allowMultiple ? maxItems : allowReplace ? maxItems : 1; // no more room? var hasMaxItems = isInt(maxItems); if (hasMaxItems && totalItems + totalBrowseItems > maxItems) { root.dispatch('DID_THROW_MAX_FILES', { source: items, error: createResponse('warning', 0, 'Max files'), }); return true; } return false; }; var getDragIndex = function getDragIndex(list, children, position) { var itemList = list.childViews[0]; return getItemIndexByPosition(itemList, children, { left: position.scopeLeft - itemList.rect.element.left, top: position.scopeTop - (list.rect.outer.top + list.rect.element.marginTop + list.rect.element.scrollTop), }); }; /** * Enable or disable file drop functionality */ var toggleDrop = function toggleDrop(root) { var isAllowed = root.query('GET_ALLOW_DROP'); var isDisabled = root.query('GET_DISABLED'); var enabled = isAllowed && !isDisabled; if (enabled && !root.ref.hopper) { var hopper = createHopper( root.element, function(items) { // allow quick validation of dropped items var beforeDropFile = root.query('GET_BEFORE_DROP_FILE') || function() { return true; }; // all items should be validated by all filters as valid var dropValidation = root.query('GET_DROP_VALIDATION'); return dropValidation ? items.every(function(item) { return ( applyFilters('ALLOW_HOPPER_ITEM', item, { query: root.query, }).every(function(result) { return result === true; }) && beforeDropFile(item) ); }) : true; }, { filterItems: function filterItems(items) { var ignoredFiles = root.query('GET_IGNORED_FILES'); return items.filter(function(item) { if (isFile(item)) { return !ignoredFiles.includes(item.name.toLowerCase()); } return true; }); }, catchesDropsOnPage: root.query('GET_DROP_ON_PAGE'), requiresDropOnElement: root.query('GET_DROP_ON_ELEMENT'), } ); hopper.onload = function(items, position) { // get item children elements and sort based on list sort var list = root.ref.list.childViews[0]; var visibleChildren = list.childViews.filter(function(child) { return child.rect.element.height; }); var children = root .query('GET_ACTIVE_ITEMS') .map(function(item) { return visibleChildren.find(function(child) { return child.id === item.id; }); }) .filter(function(item) { return item; }); applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function( queue ) { // these files don't fit so stop here if (exceedsMaxFiles(root, queue)) return false; // go root.dispatch('ADD_ITEMS', { items: queue, index: getDragIndex(root.ref.list, children, position), interactionMethod: InteractionMethod.DROP, }); }); root.dispatch('DID_DROP', { position: position }); root.dispatch('DID_END_DRAG', { position: position }); }; hopper.ondragstart = function(position) { root.dispatch('DID_START_DRAG', { position: position }); }; hopper.ondrag = debounce(function(position) { root.dispatch('DID_DRAG', { position: position }); }); hopper.ondragend = function(position) { root.dispatch('DID_END_DRAG', { position: position }); }; root.ref.hopper = hopper; root.ref.drip = root.appendChildView(root.createChildView(drip)); } else if (!enabled && root.ref.hopper) { root.ref.hopper.destroy(); root.ref.hopper = null; root.removeChildView(root.ref.drip); } }; /** * Enable or disable browse functionality */ var toggleBrowse = function toggleBrowse(root, props) { var isAllowed = root.query('GET_ALLOW_BROWSE'); var isDisabled = root.query('GET_DISABLED'); var enabled = isAllowed && !isDisabled; if (enabled && !root.ref.browser) { root.ref.browser = root.appendChildView( root.createChildView( browser, Object.assign({}, props, { onload: function onload(items) { applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch, }).then(function(queue) { // these files don't fit so stop here if (exceedsMaxFiles(root, queue)) return false; // add items! root.dispatch('ADD_ITEMS', { items: queue, index: -1, interactionMethod: InteractionMethod.BROWSE, }); }); }, }) ), 0 ); } else if (!enabled && root.ref.browser) { root.removeChildView(root.ref.browser); root.ref.browser = null; } }; /** * Enable or disable paste functionality */ var togglePaste = function togglePaste(root) { var isAllowed = root.query('GET_ALLOW_PASTE'); var isDisabled = root.query('GET_DISABLED'); var enabled = isAllowed && !isDisabled; if (enabled && !root.ref.paster) { root.ref.paster = createPaster(); root.ref.paster.onload = function(items) { applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function( queue ) { // these files don't fit so stop here if (exceedsMaxFiles(root, queue)) return false; // add items! root.dispatch('ADD_ITEMS', { items: queue, index: -1, interactionMethod: InteractionMethod.PASTE, }); }); }; } else if (!enabled && root.ref.paster) { root.ref.paster.destroy(); root.ref.paster = null; } }; /** * Route actions */ var route$5 = createRoute({ DID_SET_ALLOW_BROWSE: function DID_SET_ALLOW_BROWSE(_ref5) { var root = _ref5.root, props = _ref5.props; toggleBrowse(root, props); }, DID_SET_ALLOW_DROP: function DID_SET_ALLOW_DROP(_ref6) { var root = _ref6.root; toggleDrop(root); }, DID_SET_ALLOW_PASTE: function DID_SET_ALLOW_PASTE(_ref7) { var root = _ref7.root; togglePaste(root); }, DID_SET_DISABLED: function DID_SET_DISABLED(_ref8) { var root = _ref8.root, props = _ref8.props; toggleDrop(root); togglePaste(root); toggleBrowse(root, props); var isDisabled = root.query('GET_DISABLED'); if (isDisabled) { root.element.dataset.disabled = 'disabled'; } else { // delete root.element.dataset.disabled; <= this does not work on iOS 10 root.element.removeAttribute('data-disabled'); } }, }); var root = createView({ name: 'root', read: function read(_ref9) { var root = _ref9.root; if (root.ref.measure) { root.ref.measureHeight = root.ref.measure.offsetHeight; } }, create: create$e, write: write$9, destroy: function destroy(_ref10) { var root = _ref10.root; if (root.ref.paster) { root.ref.paster.destroy(); } if (root.ref.hopper) { root.ref.hopper.destroy(); } root.element.removeEventListener('touchmove', prevent); root.element.removeEventListener('gesturestart', prevent); }, mixins: { styles: ['height'], }, }); // creates the app var createApp = function createApp() { var initialOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // let element var originalElement = null; // get default options var defaultOptions = getOptions(); // create the data store, this will contain all our app info var store = createStore( // initial state (should be serializable) createInitialState(defaultOptions), // queries [queries, createOptionQueries(defaultOptions)], // action handlers [actions, createOptionActions(defaultOptions)] ); // set initial options store.dispatch('SET_OPTIONS', { options: initialOptions }); // kick thread if visibility changes var visibilityHandler = function visibilityHandler() { if (document.hidden) return; store.dispatch('KICK'); }; document.addEventListener('visibilitychange', visibilityHandler); // re-render on window resize start and finish var resizeDoneTimer = null; var isResizing = false; var isResizingHorizontally = false; var initialWindowWidth = null; var currentWindowWidth = null; var resizeHandler = function resizeHandler() { if (!isResizing) { isResizing = true; } clearTimeout(resizeDoneTimer); resizeDoneTimer = setTimeout(function() { isResizing = false; initialWindowWidth = null; currentWindowWidth = null; if (isResizingHorizontally) { isResizingHorizontally = false; store.dispatch('DID_STOP_RESIZE'); } }, 500); }; window.addEventListener('resize', resizeHandler); // render initial view var view = root(store, { id: getUniqueId() }); // // PRIVATE API ------------------------------------------------------------------------------------- // var isResting = false; var isHidden = false; var readWriteApi = { // necessary for update loop /** * Reads from dom (never call manually) * @private */ _read: function _read() { // test if we're resizing horizontally // TODO: see if we can optimize this by measuring root rect if (isResizing) { currentWindowWidth = window.innerWidth; if (!initialWindowWidth) { initialWindowWidth = currentWindowWidth; } if (!isResizingHorizontally && currentWindowWidth !== initialWindowWidth) { store.dispatch('DID_START_RESIZE'); isResizingHorizontally = true; } } if (isHidden && isResting) { // test if is no longer hidden isResting = view.element.offsetParent === null; } // if resting, no need to read as numbers will still all be correct if (isResting) return; // read view data view._read(); // if is hidden we need to know so we exit rest mode when revealed isHidden = view.rect.element.hidden; }, /** * Writes to dom (never call manually) * @private */ _write: function _write(ts) { // get all actions from store var actions = store .processActionQueue() // filter out set actions (these will automatically trigger DID_SET) .filter(function(action) { return !/^SET_/.test(action.type); }); // if was idling and no actions stop here if (isResting && !actions.length) return; // some actions might trigger events routeActionsToEvents(actions); // update the view isResting = view._write(ts, actions, isResizingHorizontally); // will clean up all archived items removeReleasedItems(store.query('GET_ITEMS')); // now idling if (isResting) { store.processDispatchQueue(); } }, }; // // EXPOSE EVENTS ------------------------------------------------------------------------------------- // var createEvent = function createEvent(name) { return function(data) { // create default event var event = { type: name, }; // no data to add if (!data) { return event; } // copy relevant props if (data.hasOwnProperty('error')) { event.error = data.error ? Object.assign({}, data.error) : null; } if (data.status) { event.status = Object.assign({}, data.status); } if (data.file) { event.output = data.file; } // only source is available, else add item if possible if (data.source) { event.file = data.source; } else if (data.item || data.id) { var item = data.item ? data.item : store.query('GET_ITEM', data.id); event.file = item ? createItemAPI(item) : null; } // map all items in a possible items array if (data.items) { event.items = data.items.map(createItemAPI); } // if this is a progress event add the progress amount if (/progress/.test(name)) { event.progress = data.progress; } // copy relevant props if (data.hasOwnProperty('origin') && data.hasOwnProperty('target')) { event.origin = data.origin; event.target = data.target; } return event; }; }; var eventRoutes = { DID_DESTROY: createEvent('destroy'), DID_INIT: createEvent('init'), DID_THROW_MAX_FILES: createEvent('warning'), DID_INIT_ITEM: createEvent('initfile'), DID_START_ITEM_LOAD: createEvent('addfilestart'), DID_UPDATE_ITEM_LOAD_PROGRESS: createEvent('addfileprogress'), DID_LOAD_ITEM: createEvent('addfile'), DID_THROW_ITEM_INVALID: [createEvent('error'), createEvent('addfile')], DID_THROW_ITEM_LOAD_ERROR: [createEvent('error'), createEvent('addfile')], DID_THROW_ITEM_REMOVE_ERROR: [createEvent('error'), createEvent('removefile')], DID_PREPARE_OUTPUT: createEvent('preparefile'), DID_START_ITEM_PROCESSING: createEvent('processfilestart'), DID_UPDATE_ITEM_PROCESS_PROGRESS: createEvent('processfileprogress'), DID_ABORT_ITEM_PROCESSING: createEvent('processfileabort'), DID_COMPLETE_ITEM_PROCESSING: createEvent('processfile'), DID_COMPLETE_ITEM_PROCESSING_ALL: createEvent('processfiles'), DID_REVERT_ITEM_PROCESSING: createEvent('processfilerevert'), DID_THROW_ITEM_PROCESSING_ERROR: [createEvent('error'), createEvent('processfile')], DID_REMOVE_ITEM: createEvent('removefile'), DID_UPDATE_ITEMS: createEvent('updatefiles'), DID_ACTIVATE_ITEM: createEvent('activatefile'), DID_REORDER_ITEMS: createEvent('reorderfiles'), }; var exposeEvent = function exposeEvent(event) { // create event object to be dispatched var detail = Object.assign({ pond: exports }, event); delete detail.type; view.element.dispatchEvent( new CustomEvent('FilePond:' + event.type, { // event info detail: detail, // event behaviour bubbles: true, cancelable: true, composed: true, // triggers listeners outside of shadow root }) ); // event object to params used for `on()` event handlers and callbacks `oninit()` var params = []; // if is possible error event, make it the first param if (event.hasOwnProperty('error')) { params.push(event.error); } // file is always section if (event.hasOwnProperty('file')) { params.push(event.file); } // append other props var filtered = ['type', 'error', 'file']; Object.keys(event) .filter(function(key) { return !filtered.includes(key); }) .forEach(function(key) { return params.push(event[key]); }); // on(type, () => { }) exports.fire.apply(exports, [event.type].concat(params)); // oninit = () => {} var handler = store.query('GET_ON' + event.type.toUpperCase()); if (handler) { handler.apply(void 0, params); } }; var routeActionsToEvents = function routeActionsToEvents(actions) { if (!actions.length) return; actions .filter(function(action) { return eventRoutes[action.type]; }) .forEach(function(action) { var routes = eventRoutes[action.type]; (Array.isArray(routes) ? routes : [routes]).forEach(function(route) { // this isn't fantastic, but because of the stacking of settimeouts plugins can handle the did_load before the did_init if (action.type === 'DID_INIT_ITEM') { exposeEvent(route(action.data)); } else { setTimeout(function() { exposeEvent(route(action.data)); }, 0); } }); }); }; // // PUBLIC API ------------------------------------------------------------------------------------- // var setOptions = function setOptions(options) { return store.dispatch('SET_OPTIONS', { options: options }); }; var getFile = function getFile(query) { return store.query('GET_ACTIVE_ITEM', query); }; var prepareFile = function prepareFile(query) { return new Promise(function(resolve, reject) { store.dispatch('REQUEST_ITEM_PREPARE', { query: query, success: function success(item) { resolve(item); }, failure: function failure(error) { reject(error); }, }); }); }; var addFile = function addFile(source) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new Promise(function(resolve, reject) { addFiles([{ source: source, options: options }], { index: options.index }) .then(function(items) { return resolve(items && items[0]); }) .catch(reject); }); }; var isFilePondFile = function isFilePondFile(obj) { return obj.file && obj.id; }; var removeFile = function removeFile(query, options) { // if only passed options if (typeof query === 'object' && !isFilePondFile(query) && !options) { options = query; query = undefined; } // request item removal store.dispatch('REMOVE_ITEM', Object.assign({}, options, { query: query })); // see if item has been removed return store.query('GET_ACTIVE_ITEM', query) === null; }; var addFiles = function addFiles() { for ( var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++ ) { args[_key] = arguments[_key]; } return new Promise(function(resolve, reject) { var sources = []; var options = {}; // user passed a sources array if (isArray(args[0])) { sources.push.apply(sources, args[0]); Object.assign(options, args[1] || {}); } else { // user passed sources as arguments, last one might be options object var lastArgument = args[args.length - 1]; if (typeof lastArgument === 'object' && !(lastArgument instanceof Blob)) { Object.assign(options, args.pop()); } // add rest to sources sources.push.apply(sources, args); } store.dispatch('ADD_ITEMS', { items: sources, index: options.index, interactionMethod: InteractionMethod.API, success: resolve, failure: reject, }); }); }; var getFiles = function getFiles() { return store.query('GET_ACTIVE_ITEMS'); }; var processFile = function processFile(query) { return new Promise(function(resolve, reject) { store.dispatch('REQUEST_ITEM_PROCESSING', { query: query, success: function success(item) { resolve(item); }, failure: function failure(error) { reject(error); }, }); }); }; var prepareFiles = function prepareFiles() { for ( var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++ ) { args[_key2] = arguments[_key2]; } var queries = Array.isArray(args[0]) ? args[0] : args; var items = queries.length ? queries : getFiles(); return Promise.all(items.map(prepareFile)); }; var processFiles = function processFiles() { for ( var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++ ) { args[_key3] = arguments[_key3]; } var queries = Array.isArray(args[0]) ? args[0] : args; if (!queries.length) { var files = getFiles().filter(function(item) { return ( !(item.status === ItemStatus.IDLE && item.origin === FileOrigin.LOCAL) && item.status !== ItemStatus.PROCESSING && item.status !== ItemStatus.PROCESSING_COMPLETE && item.status !== ItemStatus.PROCESSING_REVERT_ERROR ); }); return Promise.all(files.map(processFile)); } return Promise.all(queries.map(processFile)); }; var removeFiles = function removeFiles() { for ( var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++ ) { args[_key4] = arguments[_key4]; } var queries = Array.isArray(args[0]) ? args[0] : args; var options; if (typeof queries[queries.length - 1] === 'object') { options = queries.pop(); } else if (Array.isArray(args[0])) { options = args[1]; } var files = getFiles(); if (!queries.length) return Promise.all( files.map(function(file) { return removeFile(file, options); }) ); // when removing by index the indexes shift after each file removal so we need to convert indexes to ids var mappedQueries = queries .map(function(query) { return isNumber(query) ? (files[query] ? files[query].id : null) : query; }) .filter(function(query) { return query; }); return mappedQueries.map(function(q) { return removeFile(q, options); }); }; var exports = Object.assign( {}, on(), {}, readWriteApi, {}, createOptionAPI(store, defaultOptions), { /** * Override options defined in options object * @param options */ setOptions: setOptions, /** * Load the given file * @param source - the source of the file (either a File, base64 data uri or url) * @param options - object, { index: 0 } */ addFile: addFile, /** * Load the given files * @param sources - the sources of the files to load * @param options - object, { index: 0 } */ addFiles: addFiles, /** * Returns the file objects matching the given query * @param query { string, number, null } */ getFile: getFile, /** * Upload file with given name * @param query { string, number, null } */ processFile: processFile, /** * Request prepare output for file with given name * @param query { string, number, null } */ prepareFile: prepareFile, /** * Removes a file by its name * @param query { string, number, null } */ removeFile: removeFile, /** * Moves a file to a new location in the files list */ moveFile: function moveFile(query, index) { return store.dispatch('MOVE_ITEM', { query: query, index: index }); }, /** * Returns all files (wrapped in public api) */ getFiles: getFiles, /** * Starts uploading all files */ processFiles: processFiles, /** * Clears all files from the files list */ removeFiles: removeFiles, /** * Starts preparing output of all files */ prepareFiles: prepareFiles, /** * Sort list of files */ sort: function sort(compare) { return store.dispatch('SORT', { compare: compare }); }, /** * Browse the file system for a file */ browse: function browse() { // needs to be trigger directly as user action needs to be traceable (is not traceable in requestAnimationFrame) var input = view.element.querySelector('input[type=file]'); if (input) { input.click(); } }, /** * Destroys the app */ destroy: function destroy() { // request destruction exports.fire('destroy', view.element); // stop active processes (file uploads, fetches, stuff like that) // loop over items and depending on states call abort for ongoing processes store.dispatch('ABORT_ALL'); // destroy view view._destroy(); // stop listening to resize window.removeEventListener('resize', resizeHandler); // stop listening to the visiblitychange event document.removeEventListener('visibilitychange', visibilityHandler); // dispatch destroy store.dispatch('DID_DESTROY'); }, /** * Inserts the plugin before the target element */ insertBefore: function insertBefore$1(element) { return insertBefore(view.element, element); }, /** * Inserts the plugin after the target element */ insertAfter: function insertAfter$1(element) { return insertAfter(view.element, element); }, /** * Appends the plugin to the target element */ appendTo: function appendTo(element) { return element.appendChild(view.element); }, /** * Replaces an element with the app */ replaceElement: function replaceElement(element) { // insert the app before the element insertBefore(view.element, element); // remove the original element element.parentNode.removeChild(element); // remember original element originalElement = element; }, /** * Restores the original element */ restoreElement: function restoreElement() { if (!originalElement) { return; // no element to restore } // restore original element insertAfter(originalElement, view.element); // remove our element view.element.parentNode.removeChild(view.element); // remove reference originalElement = null; }, /** * Returns true if the app root is attached to given element * @param element */ isAttachedTo: function isAttachedTo(element) { return view.element === element || originalElement === element; }, /** * Returns the root element */ element: { get: function get() { return view.element; }, }, /** * Returns the current pond status */ status: { get: function get() { return store.query('GET_STATUS'); }, }, } ); // Done! store.dispatch('DID_INIT'); // create actual api object return createObject(exports); }; var createAppObject = function createAppObject() { var customOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // default options var defaultOptions = {}; forin(getOptions(), function(key, value) { defaultOptions[key] = value[0]; }); // set app options var app = createApp( Object.assign( {}, defaultOptions, {}, customOptions ) ); // return the plugin instance return app; }; var lowerCaseFirstLetter = function lowerCaseFirstLetter(string) { return string.charAt(0).toLowerCase() + string.slice(1); }; var attributeNameToPropertyName = function attributeNameToPropertyName(attributeName) { return toCamels(attributeName.replace(/^data-/, '')); }; var mapObject = function mapObject(object, propertyMap) { // remove unwanted forin(propertyMap, function(selector, mapping) { forin(object, function(property, value) { // create regexp shortcut var selectorRegExp = new RegExp(selector); // tests if var matches = selectorRegExp.test(property); // no match, skip if (!matches) { return; } // if there's a mapping, the original property is always removed delete object[property]; // should only remove, we done! if (mapping === false) { return; } // move value to new property if (isString(mapping)) { object[mapping] = value; return; } // move to group var group = mapping.group; if (isObject(mapping) && !object[group]) { object[group] = {}; } object[group][lowerCaseFirstLetter(property.replace(selectorRegExp, ''))] = value; }); // do submapping if (mapping.mapping) { mapObject(object[mapping.group], mapping.mapping); } }); }; var getAttributesAsObject = function getAttributesAsObject(node) { var attributeMapping = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // turn attributes into object var attributes = []; forin(node.attributes, function(index) { attributes.push(node.attributes[index]); }); var output = attributes .filter(function(attribute) { return attribute.name; }) .reduce(function(obj, attribute) { var value = attr(node, attribute.name); obj[attributeNameToPropertyName(attribute.name)] = value === attribute.name ? true : value; return obj; }, {}); // do mapping of object properties mapObject(output, attributeMapping); return output; }; var createAppAtElement = function createAppAtElement(element) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // how attributes of the input element are mapped to the options for the plugin var attributeMapping = { // translate to other name '^class$': 'className', '^multiple$': 'allowMultiple', '^capture$': 'captureMethod', '^webkitdirectory$': 'allowDirectoriesOnly', // group under single property '^server': { group: 'server', mapping: { '^process': { group: 'process', }, '^revert': { group: 'revert', }, '^fetch': { group: 'fetch', }, '^restore': { group: 'restore', }, '^load': { group: 'load', }, }, }, // don't include in object '^type$': false, '^files$': false, }; // add additional option translators applyFilters('SET_ATTRIBUTE_TO_OPTION_MAP', attributeMapping); // create final options object by setting options object and then overriding options supplied on element var mergedOptions = Object.assign({}, options); var attributeOptions = getAttributesAsObject( element.nodeName === 'FIELDSET' ? element.querySelector('input[type=file]') : element, attributeMapping ); // merge with options object Object.keys(attributeOptions).forEach(function(key) { if (isObject(attributeOptions[key])) { if (!isObject(mergedOptions[key])) { mergedOptions[key] = {}; } Object.assign(mergedOptions[key], attributeOptions[key]); } else { mergedOptions[key] = attributeOptions[key]; } }); // if parent is a fieldset, get files from parent by selecting all input fields that are not file upload fields // these will then be automatically set to the initial files mergedOptions.files = (options.files || []).concat( Array.from(element.querySelectorAll('input:not([type=file])')).map(function(input) { return { source: input.value, options: { type: input.dataset.type, }, }; }) ); // build plugin var app = createAppObject(mergedOptions); // add already selected files if (element.files) { Array.from(element.files).forEach(function(file) { app.addFile(file); }); } // replace the target element app.replaceElement(element); // expose return app; }; // if an element is passed, we create the instance at that element, if not, we just create an up object var createApp$1 = function createApp() { return isNode(arguments.length <= 0 ? undefined : arguments[0]) ? createAppAtElement.apply(void 0, arguments) : createAppObject.apply(void 0, arguments); }; var PRIVATE_METHODS = ['fire', '_read', '_write']; var createAppAPI = function createAppAPI(app) { var api = {}; copyObjectPropertiesToObject(app, api, PRIVATE_METHODS); return api; }; /** * Replaces placeholders in given string with replacements * @param string - "Foo {bar}"" * @param replacements - { "bar": 10 } */ var replaceInString = function replaceInString(string, replacements) { return string.replace(/(?:{([a-zA-Z]+)})/g, function(match, group) { return replacements[group]; }); }; var createWorker = function createWorker(fn) { var workerBlob = new Blob(['(', fn.toString(), ')()'], { type: 'application/javascript', }); var workerURL = URL.createObjectURL(workerBlob); var worker = new Worker(workerURL); return { transfer: function transfer(message, cb) {}, post: function post(message, cb, transferList) { var id = getUniqueId(); worker.onmessage = function(e) { if (e.data.id === id) { cb(e.data.message); } }; worker.postMessage( { id: id, message: message, }, transferList ); }, terminate: function terminate() { worker.terminate(); URL.revokeObjectURL(workerURL); }, }; }; var loadImage = function loadImage(url) { return new Promise(function(resolve, reject) { var img = new Image(); img.onload = function() { resolve(img); }; img.onerror = function(e) { reject(e); }; img.src = url; }); }; var renameFile = function renameFile(file, name) { var renamedFile = file.slice(0, file.size, file.type); renamedFile.lastModifiedDate = file.lastModifiedDate; renamedFile.name = name; return renamedFile; }; var copyFile = function copyFile(file) { return renameFile(file, file.name); }; // already registered plugins (can't register twice) var registeredPlugins = []; // pass utils to plugin var createAppPlugin = function createAppPlugin(plugin) { // already registered if (registeredPlugins.includes(plugin)) { return; } // remember this plugin registeredPlugins.push(plugin); // setup! var pluginOutline = plugin({ addFilter: addFilter, utils: { Type: Type, forin: forin, isString: isString, isFile: isFile, toNaturalFileSize: toNaturalFileSize, replaceInString: replaceInString, getExtensionFromFilename: getExtensionFromFilename, getFilenameWithoutExtension: getFilenameWithoutExtension, guesstimateMimeType: guesstimateMimeType, getFileFromBlob: getFileFromBlob, getFilenameFromURL: getFilenameFromURL, createRoute: createRoute, createWorker: createWorker, createView: createView, createItemAPI: createItemAPI, loadImage: loadImage, copyFile: copyFile, renameFile: renameFile, createBlob: createBlob, applyFilterChain: applyFilterChain, text: text, getNumericAspectRatioFromString: getNumericAspectRatioFromString, }, views: { fileActionButton: fileActionButton, }, }); // add plugin options to default options extendDefaultOptions(pluginOutline.options); }; // feature detection used by supported() method var isOperaMini = function isOperaMini() { return Object.prototype.toString.call(window.operamini) === '[object OperaMini]'; }; var hasPromises = function hasPromises() { return 'Promise' in window; }; var hasBlobSlice = function hasBlobSlice() { return 'slice' in Blob.prototype; }; var hasCreateObjectURL = function hasCreateObjectURL() { return 'URL' in window && 'createObjectURL' in window.URL; }; var hasVisibility = function hasVisibility() { return 'visibilityState' in document; }; var hasTiming = function hasTiming() { return 'performance' in window; }; // iOS 8.x var hasCSSSupports = function hasCSSSupports() { return 'supports' in (window.CSS || {}); }; // use to detect Safari 9+ var isIE11 = function isIE11() { return /MSIE|Trident/.test(window.navigator.userAgent); }; var supported = (function() { // Runs immediately and then remembers result for subsequent calls var isSupported = // Has to be a browser isBrowser() && // Can't run on Opera Mini due to lack of everything !isOperaMini() && // Require these APIs to feature detect a modern browser hasVisibility() && hasPromises() && hasBlobSlice() && hasCreateObjectURL() && hasTiming() && // doesn't need CSSSupports but is a good way to detect Safari 9+ (we do want to support IE11 though) (hasCSSSupports() || isIE11()); return function() { return isSupported; }; })(); /** * Plugin internal state (over all instances) */ var state = { // active app instances, used to redraw the apps and to find the later apps: [], }; // plugin name var name = 'filepond'; /** * Public Plugin methods */ var fn = function fn() {}; exports.Status = {}; exports.FileStatus = {}; exports.FileOrigin = {}; exports.OptionTypes = {}; exports.create = fn; exports.destroy = fn; exports.parse = fn; exports.find = fn; exports.registerPlugin = fn; exports.getOptions = fn; exports.setOptions = fn; // if not supported, no API if (supported()) { // start painter and fire load event createPainter( function() { state.apps.forEach(function(app) { return app._read(); }); }, function(ts) { state.apps.forEach(function(app) { return app._write(ts); }); } ); // fire loaded event so we know when FilePond is available var dispatch = function dispatch() { // let others know we have area ready document.dispatchEvent( new CustomEvent('FilePond:loaded', { detail: { supported: supported, create: exports.create, destroy: exports.destroy, parse: exports.parse, find: exports.find, registerPlugin: exports.registerPlugin, setOptions: exports.setOptions, }, }) ); // clean up event document.removeEventListener('DOMContentLoaded', dispatch); }; if (document.readyState !== 'loading') { // move to back of execution queue, FilePond should have been exported by then setTimeout(function() { return dispatch(); }, 0); } else { document.addEventListener('DOMContentLoaded', dispatch); } // updates the OptionTypes object based on the current options var updateOptionTypes = function updateOptionTypes() { return forin(getOptions(), function(key, value) { exports.OptionTypes[key] = value[1]; }); }; exports.Status = Object.assign({}, Status); exports.FileOrigin = Object.assign({}, FileOrigin); exports.FileStatus = Object.assign({}, ItemStatus); exports.OptionTypes = {}; updateOptionTypes(); // create method, creates apps and adds them to the app array exports.create = function create() { var app = createApp$1.apply(void 0, arguments); app.on('destroy', exports.destroy); state.apps.push(app); return createAppAPI(app); }; // destroys apps and removes them from the app array exports.destroy = function destroy(hook) { // returns true if the app was destroyed successfully var indexToRemove = state.apps.findIndex(function(app) { return app.isAttachedTo(hook); }); if (indexToRemove >= 0) { // remove from apps var app = state.apps.splice(indexToRemove, 1)[0]; // restore original dom element app.restoreElement(); return true; } return false; }; // parses the given context for plugins (does not include the context element itself) exports.parse = function parse(context) { // get all possible hooks var matchedHooks = Array.from(context.querySelectorAll('.' + name)); // filter out already active hooks var newHooks = matchedHooks.filter(function(newHook) { return !state.apps.find(function(app) { return app.isAttachedTo(newHook); }); }); // create new instance for each hook return newHooks.map(function(hook) { return exports.create(hook); }); }; // returns an app based on the given element hook exports.find = function find(hook) { var app = state.apps.find(function(app) { return app.isAttachedTo(hook); }); if (!app) { return null; } return createAppAPI(app); }; // adds a plugin extension exports.registerPlugin = function registerPlugin() { for ( var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++ ) { plugins[_key] = arguments[_key]; } // register plugins plugins.forEach(createAppPlugin); // update OptionTypes, each plugin might have extended the default options updateOptionTypes(); }; exports.getOptions = function getOptions$1() { var opts = {}; forin(getOptions(), function(key, value) { opts[key] = value[0]; }); return opts; }; exports.setOptions = function setOptions$1(opts) { if (isObject(opts)) { // update existing plugins state.apps.forEach(function(app) { app.setOptions(opts); }); // override defaults setOptions(opts); } // return new options return exports.getOptions(); }; } exports.supported = supported; Object.defineProperty(exports, '__esModule', { value: true }); });
cdnjs/cdnjs
ajax/libs/filepond/4.26.0/filepond.js
JavaScript
mit
427,759
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('vega'), require('vega-lite')) : typeof define === 'function' && define.amd ? define(['vega', 'vega-lite'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.vegaEmbed = factory(global.vega, global.vegaLite)); })(this, (function (vegaImport, vegaLiteImport) { 'use strict'; function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n["default"] = e; return Object.freeze(n); } var vegaImport__namespace = /*#__PURE__*/_interopNamespace(vegaImport); var vegaLiteImport__namespace = /*#__PURE__*/_interopNamespace(vegaLiteImport); /*! * https://github.com/Starcounter-Jack/JSON-Patch * (c) 2017 Joachim Wester * MIT license */ var __extends = undefined && undefined.__extends || function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; }(); var _hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwnProperty(obj, key) { return _hasOwnProperty.call(obj, key); } function _objectKeys(obj) { if (Array.isArray(obj)) { var keys = new Array(obj.length); for (var k = 0; k < keys.length; k++) { keys[k] = "" + k; } return keys; } if (Object.keys) { return Object.keys(obj); } var keys = []; for (var i in obj) { if (hasOwnProperty(obj, i)) { keys.push(i); } } return keys; } /** * Deeply clone the object. * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) * @param {any} obj value to clone * @return {any} cloned obj */ function _deepClone(obj) { switch (typeof obj) { case "object": return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 case "undefined": return null; //this is how JSON.stringify behaves for array items default: return obj; //no need to clone primitives } } //3x faster than cached /^\d+$/.test(str) function isInteger(str) { var i = 0; var len = str.length; var charCode; while (i < len) { charCode = str.charCodeAt(i); if (charCode >= 48 && charCode <= 57) { i++; continue; } return false; } return true; } /** * Escapes a json pointer path * @param path The raw pointer * @return the Escaped path */ function escapePathComponent(path) { if (path.indexOf('/') === -1 && path.indexOf('~') === -1) return path; return path.replace(/~/g, '~0').replace(/\//g, '~1'); } /** * Unescapes a json pointer path * @param path The escaped pointer * @return The unescaped path */ function unescapePathComponent(path) { return path.replace(/~1/g, '/').replace(/~0/g, '~'); } /** * Recursively checks whether an object has any undefined values inside. */ function hasUndefined(obj) { if (obj === undefined) { return true; } if (obj) { if (Array.isArray(obj)) { for (var i = 0, len = obj.length; i < len; i++) { if (hasUndefined(obj[i])) { return true; } } } else if (typeof obj === "object") { var objKeys = _objectKeys(obj); var objKeysLength = objKeys.length; for (var i = 0; i < objKeysLength; i++) { if (hasUndefined(obj[objKeys[i]])) { return true; } } } } return false; } function patchErrorMessageFormatter(message, args) { var messageParts = [message]; for (var key in args) { var value = typeof args[key] === 'object' ? JSON.stringify(args[key], null, 2) : args[key]; // pretty print if (typeof value !== 'undefined') { messageParts.push(key + ": " + value); } } return messageParts.join('\n'); } var PatchError = function (_super) { __extends(PatchError, _super); function PatchError(message, name, index, operation, tree) { var _newTarget = this.constructor; var _this = _super.call(this, patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree })) || this; _this.name = name; _this.index = index; _this.operation = operation; _this.tree = tree; Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 _this.message = patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree }); return _this; } return PatchError; }(Error); var JsonPatchError = PatchError; var deepClone = _deepClone; /* We use a Javascript hash to store each function. Each hash entry (property) uses the operation identifiers specified in rfc6902. In this way, we can map each patch operation to its dedicated function in efficient way. */ /* The operations applicable to an object */ var objOps = { add: function (obj, key, document) { obj[key] = this.value; return { newDocument: document }; }, remove: function (obj, key, document) { var removed = obj[key]; delete obj[key]; return { newDocument: document, removed: removed }; }, replace: function (obj, key, document) { var removed = obj[key]; obj[key] = this.value; return { newDocument: document, removed: removed }; }, move: function (obj, key, document) { /* in case move target overwrites an existing value, return the removed value, this can be taxing performance-wise, and is potentially unneeded */ var removed = getValueByPointer(document, this.path); if (removed) { removed = _deepClone(removed); } var originalValue = applyOperation(document, { op: "remove", path: this.from }).removed; applyOperation(document, { op: "add", path: this.path, value: originalValue }); return { newDocument: document, removed: removed }; }, copy: function (obj, key, document) { var valueToCopy = getValueByPointer(document, this.from); // enforce copy by value so further operations don't affect source (see issue #177) applyOperation(document, { op: "add", path: this.path, value: _deepClone(valueToCopy) }); return { newDocument: document }; }, test: function (obj, key, document) { return { newDocument: document, test: _areEquals(obj[key], this.value) }; }, _get: function (obj, key, document) { this.value = obj[key]; return { newDocument: document }; } }; /* The operations applicable to an array. Many are the same as for the object */ var arrOps = { add: function (arr, i, document) { if (isInteger(i)) { arr.splice(i, 0, this.value); } else { // array props arr[i] = this.value; } // this may be needed when using '-' in an array return { newDocument: document, index: i }; }, remove: function (arr, i, document) { var removedList = arr.splice(i, 1); return { newDocument: document, removed: removedList[0] }; }, replace: function (arr, i, document) { var removed = arr[i]; arr[i] = this.value; return { newDocument: document, removed: removed }; }, move: objOps.move, copy: objOps.copy, test: objOps.test, _get: objOps._get }; /** * Retrieves a value from a JSON document by a JSON pointer. * Returns the value. * * @param document The document to get the value from * @param pointer an escaped JSON pointer * @return The retrieved value */ function getValueByPointer(document, pointer) { if (pointer == '') { return document; } var getOriginalDestination = { op: "_get", path: pointer }; applyOperation(document, getOriginalDestination); return getOriginalDestination.value; } /** * Apply a single JSON Patch Operation on a JSON document. * Returns the {newDocument, result} of the operation. * It modifies the `document` and `operation` objects - it gets the values by reference. * If you would like to avoid touching your values, clone them: * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. * * @param document The document to patch * @param operation The operation to apply * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. * @param mutateDocument Whether to mutate the original document or clone it before applying * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. * @return `{newDocument, result}` after the operation */ function applyOperation(document, operation, validateOperation, mutateDocument, banPrototypeModifications, index) { if (validateOperation === void 0) { validateOperation = false; } if (mutateDocument === void 0) { mutateDocument = true; } if (banPrototypeModifications === void 0) { banPrototypeModifications = true; } if (index === void 0) { index = 0; } if (validateOperation) { if (typeof validateOperation == 'function') { validateOperation(operation, 0, document, operation.path); } else { validator(operation, 0); } } /* ROOT OPERATIONS */ if (operation.path === "") { var returnValue = { newDocument: document }; if (operation.op === 'add') { returnValue.newDocument = operation.value; return returnValue; } else if (operation.op === 'replace') { returnValue.newDocument = operation.value; returnValue.removed = document; //document we removed return returnValue; } else if (operation.op === 'move' || operation.op === 'copy') { // it's a move or copy to root returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field if (operation.op === 'move') { // report removed item returnValue.removed = document; } return returnValue; } else if (operation.op === 'test') { returnValue.test = _areEquals(document, operation.value); if (returnValue.test === false) { throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document); } returnValue.newDocument = document; return returnValue; } else if (operation.op === 'remove') { // a remove on root returnValue.removed = document; returnValue.newDocument = null; return returnValue; } else if (operation.op === '_get') { operation.value = document; return returnValue; } else { /* bad operation */ if (validateOperation) { throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document); } else { return returnValue; } } } /* END ROOT OPERATIONS */ else { if (!mutateDocument) { document = _deepClone(document); } var path = operation.path || ""; var keys = path.split('/'); var obj = document; var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift var len = keys.length; var existingPathFragment = undefined; var key = void 0; var validateFunction = void 0; if (typeof validateOperation == 'function') { validateFunction = validateOperation; } else { validateFunction = validator; } while (true) { key = keys[t]; if (key && key.indexOf('~') != -1) { key = unescapePathComponent(key); } if (banPrototypeModifications && key == '__proto__') { throw new TypeError('JSON-Patch: modifying `__proto__` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README'); } if (validateOperation) { if (existingPathFragment === undefined) { if (obj[key] === undefined) { existingPathFragment = keys.slice(0, t).join('/'); } else if (t == len - 1) { existingPathFragment = operation.path; } if (existingPathFragment !== undefined) { validateFunction(operation, 0, document, existingPathFragment); } } } t++; if (Array.isArray(obj)) { if (key === '-') { key = obj.length; } else { if (validateOperation && !isInteger(key)) { throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); } // only parse key when it's an integer for `arr.prop` to work else if (isInteger(key)) { key = ~~key; } } if (t >= len) { if (validateOperation && operation.op === "add" && key > obj.length) { throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); } var returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch if (returnValue.test === false) { throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document); } return returnValue; } } else { if (t >= len) { var returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch if (returnValue.test === false) { throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document); } return returnValue; } } obj = obj[key]; // If we have more keys in the path, but the next value isn't a non-null object, // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. if (validateOperation && t < len && (!obj || typeof obj !== "object")) { throw new JsonPatchError('Cannot perform operation at the desired path', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document); } } } } /** * Apply a full JSON Patch array on a JSON document. * Returns the {newDocument, result} of the patch. * It modifies the `document` object and `patch` - it gets the values by reference. * If you would like to avoid touching your values, clone them: * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. * * @param document The document to patch * @param patch The patch to apply * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. * @param mutateDocument Whether to mutate the original document or clone it before applying * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. * @return An array of `{newDocument, result}` after the patch */ function applyPatch(document, patch, validateOperation, mutateDocument, banPrototypeModifications) { if (mutateDocument === void 0) { mutateDocument = true; } if (banPrototypeModifications === void 0) { banPrototypeModifications = true; } if (validateOperation) { if (!Array.isArray(patch)) { throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY'); } } if (!mutateDocument) { document = _deepClone(document); } var results = new Array(patch.length); for (var i = 0, length_1 = patch.length; i < length_1; i++) { // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); document = results[i].newDocument; // in case root was replaced } results.newDocument = document; return results; } /** * Apply a single JSON Patch Operation on a JSON document. * Returns the updated document. * Suitable as a reducer. * * @param document The document to patch * @param operation The operation to apply * @return The updated document */ function applyReducer(document, operation, index) { var operationResult = applyOperation(document, operation); if (operationResult.test === false) { // failed test throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document); } return operationResult.newDocument; } /** * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. * @param {object} operation - operation object (patch) * @param {number} index - index of operation in the sequence * @param {object} [document] - object where the operation is supposed to be applied * @param {string} [existingPathFragment] - comes along with `document` */ function validator(operation, index, document, existingPathFragment) { if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) { throw new JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document); } else if (!objOps[operation.op]) { throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document); } else if (typeof operation.path !== 'string') { throw new JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document); } else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) { // paths that aren't empty string should start with "/" throw new JsonPatchError('Operation `path` property must start with "/"', 'OPERATION_PATH_INVALID', index, operation, document); } else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') { throw new JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document); } else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) { throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document); } else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && hasUndefined(operation.value)) { throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document); } else if (document) { if (operation.op == "add") { var pathLen = operation.path.split("/").length; var existingPathLen = existingPathFragment.split("/").length; if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { throw new JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document); } } else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') { if (operation.path !== existingPathFragment) { throw new JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document); } } else if (operation.op === 'move' || operation.op === 'copy') { var existingValue = { op: "_get", path: operation.from, value: undefined }; var error = validate([existingValue], document); if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') { throw new JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document); } } } } /** * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. * If error is encountered, returns a JsonPatchError object * @param sequence * @param document * @returns {JsonPatchError|undefined} */ function validate(sequence, document, externalValidator) { try { if (!Array.isArray(sequence)) { throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY'); } if (document) { //clone document and sequence so that we can safely try applying operations applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true); } else { externalValidator = externalValidator || validator; for (var i = 0; i < sequence.length; i++) { externalValidator(sequence[i], i, document, undefined); } } } catch (e) { if (e instanceof JsonPatchError) { return e; } else { throw e; } } } // based on https://github.com/epoberezkin/fast-deep-equal // MIT License // Copyright (c) 2017 Evgeny Poberezkin // 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. function _areEquals(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; if (arrA && arrB) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!_areEquals(a[i], b[i])) return false; return true; } if (arrA != arrB) return false; var keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!b.hasOwnProperty(keys[i])) return false; for (i = length; i-- !== 0;) { key = keys[i]; if (!_areEquals(a[key], b[key])) return false; } return true; } return a !== a && b !== b; } var core = /*#__PURE__*/Object.freeze({ __proto__: null, JsonPatchError: JsonPatchError, deepClone: deepClone, getValueByPointer: getValueByPointer, applyOperation: applyOperation, applyPatch: applyPatch, applyReducer: applyReducer, validator: validator, validate: validate, _areEquals: _areEquals }); /*! * https://github.com/Starcounter-Jack/JSON-Patch * (c) 2017 Joachim Wester * MIT license */ var beforeDict = new WeakMap(); var Mirror = function () { function Mirror(obj) { this.observers = new Map(); this.obj = obj; } return Mirror; }(); var ObserverInfo = function () { function ObserverInfo(callback, observer) { this.callback = callback; this.observer = observer; } return ObserverInfo; }(); function getMirror(obj) { return beforeDict.get(obj); } function getObserverFromMirror(mirror, callback) { return mirror.observers.get(callback); } function removeObserverFromMirror(mirror, observer) { mirror.observers.delete(observer.callback); } /** * Detach an observer from an object */ function unobserve(root, observer) { observer.unobserve(); } /** * Observes changes made to an object, which can then be retrieved using generate */ function observe(obj, callback) { var patches = []; var observer; var mirror = getMirror(obj); if (!mirror) { mirror = new Mirror(obj); beforeDict.set(obj, mirror); } else { var observerInfo = getObserverFromMirror(mirror, callback); observer = observerInfo && observerInfo.observer; } if (observer) { return observer; } observer = {}; mirror.value = _deepClone(obj); if (callback) { observer.callback = callback; observer.next = null; var dirtyCheck = function () { generate(observer); }; var fastCheck = function () { clearTimeout(observer.next); observer.next = setTimeout(dirtyCheck); }; if (typeof window !== 'undefined') { //not Node window.addEventListener('mouseup', fastCheck); window.addEventListener('keyup', fastCheck); window.addEventListener('mousedown', fastCheck); window.addEventListener('keydown', fastCheck); window.addEventListener('change', fastCheck); } } observer.patches = patches; observer.object = obj; observer.unobserve = function () { generate(observer); clearTimeout(observer.next); removeObserverFromMirror(mirror, observer); if (typeof window !== 'undefined') { window.removeEventListener('mouseup', fastCheck); window.removeEventListener('keyup', fastCheck); window.removeEventListener('mousedown', fastCheck); window.removeEventListener('keydown', fastCheck); window.removeEventListener('change', fastCheck); } }; mirror.observers.set(callback, new ObserverInfo(callback, observer)); return observer; } /** * Generate an array of patches from an observer */ function generate(observer, invertible) { if (invertible === void 0) { invertible = false; } var mirror = beforeDict.get(observer.object); _generate(mirror.value, observer.object, observer.patches, "", invertible); if (observer.patches.length) { applyPatch(mirror.value, observer.patches); } var temp = observer.patches; if (temp.length > 0) { observer.patches = []; if (observer.callback) { observer.callback(temp); } } return temp; } // Dirty check if obj is different from mirror, generate patches and update mirror function _generate(mirror, obj, patches, path, invertible) { if (obj === mirror) { return; } if (typeof obj.toJSON === "function") { obj = obj.toJSON(); } var newKeys = _objectKeys(obj); var oldKeys = _objectKeys(mirror); var deleted = false; //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" for (var t = oldKeys.length - 1; t >= 0; t--) { var key = oldKeys[t]; var oldVal = mirror[key]; if (hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) { var newVal = obj[key]; if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) { _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); } else { if (oldVal !== newVal) { if (invertible) { patches.push({ op: "test", path: path + "/" + escapePathComponent(key), value: _deepClone(oldVal) }); } patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: _deepClone(newVal) }); } } } else if (Array.isArray(mirror) === Array.isArray(obj)) { if (invertible) { patches.push({ op: "test", path: path + "/" + escapePathComponent(key), value: _deepClone(oldVal) }); } patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) }); deleted = true; // property has been deleted } else { if (invertible) { patches.push({ op: "test", path: path, value: mirror }); } patches.push({ op: "replace", path: path, value: obj }); } } if (!deleted && newKeys.length == oldKeys.length) { return; } for (var t = 0; t < newKeys.length; t++) { var key = newKeys[t]; if (!hasOwnProperty(mirror, key) && obj[key] !== undefined) { patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: _deepClone(obj[key]) }); } } } /** * Create an array of patches from the differences in two objects */ function compare$b(tree1, tree2, invertible) { if (invertible === void 0) { invertible = false; } var patches = []; _generate(tree1, tree2, patches, '', invertible); return patches; } var duplex = /*#__PURE__*/Object.freeze({ __proto__: null, unobserve: unobserve, observe: observe, generate: generate, compare: compare$b }); Object.assign({}, core, duplex, { JsonPatchError: PatchError, deepClone: _deepClone, escapePathComponent, unescapePathComponent }); // working on the output of `JSON.stringify` we know that only valid strings // are present (unless the user supplied a weird `options.indent` but in // that case we don’t care since the output would be invalid anyway). var stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g; var jsonStringifyPrettyCompact = function stringify(passedObj, options) { var indent, maxLength, replacer; options = options || {}; indent = JSON.stringify([1], undefined, options.indent === undefined ? 2 : options.indent).slice(2, -3); maxLength = indent === "" ? Infinity : options.maxLength === undefined ? 80 : options.maxLength; replacer = options.replacer; return function _stringify(obj, currentIndent, reserved) { // prettier-ignore var end, index, items, key, keyPart, keys, length, nextIndent, prettified, start, string, value; if (obj && typeof obj.toJSON === "function") { obj = obj.toJSON(); } string = JSON.stringify(obj, replacer); if (string === undefined) { return string; } length = maxLength - currentIndent.length - reserved; if (string.length <= length) { prettified = string.replace(stringOrChar, function (match, stringLiteral) { return stringLiteral || match + " "; }); if (prettified.length <= length) { return prettified; } } if (replacer != null) { obj = JSON.parse(string); replacer = undefined; } if (typeof obj === "object" && obj !== null) { nextIndent = currentIndent + indent; items = []; index = 0; if (Array.isArray(obj)) { start = "["; end = "]"; length = obj.length; for (; index < length; index++) { items.push(_stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) || "null"); } } else { start = "{"; end = "}"; keys = Object.keys(obj); length = keys.length; for (; index < length; index++) { key = keys[index]; keyPart = JSON.stringify(key) + ": "; value = _stringify(obj[key], nextIndent, keyPart.length + (index === length - 1 ? 0 : 1)); if (value !== undefined) { items.push(keyPart + value); } } } if (items.length > 0) { return [start, indent + items.join(",\n" + nextIndent), end].join("\n" + currentIndent); } } return string; }(passedObj, "", 0); }; var re$5 = {exports: {}}; // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0'; const MAX_LENGTH$2 = 256; const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16; var constants = { SEMVER_SPEC_VERSION, MAX_LENGTH: MAX_LENGTH$2, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, MAX_SAFE_COMPONENT_LENGTH }; const debug$3 = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {}; var debug_1 = debug$3; (function (module, exports) { const { MAX_SAFE_COMPONENT_LENGTH } = constants; const debug = debug_1; exports = module.exports = {}; // The actual regexps go on exports.re const re = exports.re = []; const src = exports.src = []; const t = exports.t = {}; let R = 0; const createToken = (name, value, isGlobal) => { const index = R++; debug(index, value); t[name] = index; src[index] = value; re[index] = new RegExp(value, isGlobal ? 'g' : undefined); }; // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`); createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`); createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); createToken('FULL', `^${src[t.FULLPLAIN]}$`); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`); createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`); createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`); createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)'); createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); exports.tildeTrimReplace = '$1~'; createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)'); createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); exports.caretTrimReplace = '$1^'; createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`); createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`); // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*'); // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); })(re$5, re$5.exports); // obj with keys in a consistent order. const opts = ['includePrerelease', 'loose', 'rtl']; const parseOptions$4 = options => !options ? {} : typeof options !== 'object' ? { loose: true } : opts.filter(k => options[k]).reduce((options, k) => { options[k] = true; return options; }, {}); var parseOptions_1 = parseOptions$4; const numeric = /^[0-9]+$/; const compareIdentifiers$1 = (a, b) => { const anum = numeric.test(a); const bnum = numeric.test(b); if (anum && bnum) { a = +a; b = +b; } return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; }; const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); var identifiers = { compareIdentifiers: compareIdentifiers$1, rcompareIdentifiers }; const debug$2 = debug_1; const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; const { re: re$4, t: t$4 } = re$5.exports; const parseOptions$3 = parseOptions_1; const { compareIdentifiers } = identifiers; class SemVer$e { constructor(version, options) { options = parseOptions$3(options); if (version instanceof SemVer$e) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version; } else { version = version.version; } } else if (typeof version !== 'string') { throw new TypeError(`Invalid Version: ${version}`); } if (version.length > MAX_LENGTH$1) { throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`); } debug$2('SemVer', version, options); this.options = options; this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease; const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); if (!m) { throw new TypeError(`Invalid Version: ${version}`); } this.raw = version; // these are actually numbers this.major = +m[1]; this.minor = +m[2]; this.patch = +m[3]; if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version'); } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version'); } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version'); } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = []; } else { this.prerelease = m[4].split('.').map(id => { if (/^[0-9]+$/.test(id)) { const num = +id; if (num >= 0 && num < MAX_SAFE_INTEGER) { return num; } } return id; }); } this.build = m[5] ? m[5].split('.') : []; this.format(); } format() { this.version = `${this.major}.${this.minor}.${this.patch}`; if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}`; } return this.version; } toString() { return this.version; } compare(other) { debug$2('SemVer.compare', this.version, this.options, other); if (!(other instanceof SemVer$e)) { if (typeof other === 'string' && other === this.version) { return 0; } other = new SemVer$e(other, this.options); } if (other.version === this.version) { return 0; } return this.compareMain(other) || this.comparePre(other); } compareMain(other) { if (!(other instanceof SemVer$e)) { other = new SemVer$e(other, this.options); } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); } comparePre(other) { if (!(other instanceof SemVer$e)) { other = new SemVer$e(other, this.options); } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1; } else if (!this.prerelease.length && other.prerelease.length) { return 1; } else if (!this.prerelease.length && !other.prerelease.length) { return 0; } let i = 0; do { const a = this.prerelease[i]; const b = other.prerelease[i]; debug$2('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0; } else if (b === undefined) { return 1; } else if (a === undefined) { return -1; } else if (a === b) { continue; } else { return compareIdentifiers(a, b); } } while (++i); } compareBuild(other) { if (!(other instanceof SemVer$e)) { other = new SemVer$e(other, this.options); } let i = 0; do { const a = this.build[i]; const b = other.build[i]; debug$2('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0; } else if (b === undefined) { return 1; } else if (a === undefined) { return -1; } else if (a === b) { continue; } else { return compareIdentifiers(a, b); } } while (++i); } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc(release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0; this.patch = 0; this.minor = 0; this.major++; this.inc('pre', identifier); break; case 'preminor': this.prerelease.length = 0; this.patch = 0; this.minor++; this.inc('pre', identifier); break; case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0; this.inc('patch', identifier); this.inc('pre', identifier); break; // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier); } this.inc('pre', identifier); break; case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++; } this.minor = 0; this.patch = 0; this.prerelease = []; break; case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++; } this.patch = 0; this.prerelease = []; break; case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++; } this.prerelease = []; break; // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0]; } else { let i = this.prerelease.length; while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++; i = -2; } } if (i === -1) { // didn't increment anything this.prerelease.push(0); } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0]; } } else { this.prerelease = [identifier, 0]; } } break; default: throw new Error(`invalid increment argument: ${release}`); } this.format(); this.raw = this.version; return this; } } var semver$1 = SemVer$e; const { MAX_LENGTH } = constants; const { re: re$3, t: t$3 } = re$5.exports; const SemVer$d = semver$1; const parseOptions$2 = parseOptions_1; const parse$5 = (version, options) => { options = parseOptions$2(options); if (version instanceof SemVer$d) { return version; } if (typeof version !== 'string') { return null; } if (version.length > MAX_LENGTH) { return null; } const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; if (!r.test(version)) { return null; } try { return new SemVer$d(version, options); } catch (er) { return null; } }; var parse_1 = parse$5; const parse$4 = parse_1; const valid$1 = (version, options) => { const v = parse$4(version, options); return v ? v.version : null; }; var valid_1 = valid$1; const parse$3 = parse_1; const clean = (version, options) => { const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); return s ? s.version : null; }; var clean_1 = clean; const SemVer$c = semver$1; const inc = (version, release, options, identifier) => { if (typeof options === 'string') { identifier = options; options = undefined; } try { return new SemVer$c(version, options).inc(release, identifier).version; } catch (er) { return null; } }; var inc_1 = inc; const SemVer$b = semver$1; const compare$a = (a, b, loose) => new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); var compare_1 = compare$a; const compare$9 = compare_1; const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; var eq_1 = eq$2; const parse$2 = parse_1; const eq$1 = eq_1; const diff = (version1, version2) => { if (eq$1(version1, version2)) { return null; } else { const v1 = parse$2(version1); const v2 = parse$2(version2); const hasPre = v1.prerelease.length || v2.prerelease.length; const prefix = hasPre ? 'pre' : ''; const defaultResult = hasPre ? 'prerelease' : ''; for (const key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key; } } } return defaultResult; // may be undefined } }; var diff_1 = diff; const SemVer$a = semver$1; const major = (a, loose) => new SemVer$a(a, loose).major; var major_1 = major; const SemVer$9 = semver$1; const minor = (a, loose) => new SemVer$9(a, loose).minor; var minor_1 = minor; const SemVer$8 = semver$1; const patch = (a, loose) => new SemVer$8(a, loose).patch; var patch_1 = patch; const parse$1 = parse_1; const prerelease = (version, options) => { const parsed = parse$1(version, options); return parsed && parsed.prerelease.length ? parsed.prerelease : null; }; var prerelease_1 = prerelease; const compare$8 = compare_1; const rcompare = (a, b, loose) => compare$8(b, a, loose); var rcompare_1 = rcompare; const compare$7 = compare_1; const compareLoose = (a, b) => compare$7(a, b, true); var compareLoose_1 = compareLoose; const SemVer$7 = semver$1; const compareBuild$2 = (a, b, loose) => { const versionA = new SemVer$7(a, loose); const versionB = new SemVer$7(b, loose); return versionA.compare(versionB) || versionA.compareBuild(versionB); }; var compareBuild_1 = compareBuild$2; const compareBuild$1 = compareBuild_1; const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); var sort_1 = sort; const compareBuild = compareBuild_1; const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); var rsort_1 = rsort; const compare$6 = compare_1; const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; var gt_1 = gt$3; const compare$5 = compare_1; const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; var lt_1 = lt$2; const compare$4 = compare_1; const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; var neq_1 = neq$1; const compare$3 = compare_1; const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; var gte_1 = gte$2; const compare$2 = compare_1; const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; var lte_1 = lte$2; const eq = eq_1; const neq = neq_1; const gt$2 = gt_1; const gte$1 = gte_1; const lt$1 = lt_1; const lte$1 = lte_1; const cmp$1 = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') a = a.version; if (typeof b === 'object') b = b.version; return a === b; case '!==': if (typeof a === 'object') a = a.version; if (typeof b === 'object') b = b.version; return a !== b; case '': case '=': case '==': return eq(a, b, loose); case '!=': return neq(a, b, loose); case '>': return gt$2(a, b, loose); case '>=': return gte$1(a, b, loose); case '<': return lt$1(a, b, loose); case '<=': return lte$1(a, b, loose); default: throw new TypeError(`Invalid operator: ${op}`); } }; var cmp_1 = cmp$1; const SemVer$6 = semver$1; const parse = parse_1; const { re: re$2, t: t$2 } = re$5.exports; const coerce = (version, options) => { if (version instanceof SemVer$6) { return version; } if (typeof version === 'number') { version = String(version); } if (typeof version !== 'string') { return null; } options = options || {}; let match = null; if (!options.rtl) { match = version.match(re$2[t$2.COERCE]); } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next; while ((next = re$2[t$2.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next; } re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } // leave it in a clean state re$2[t$2.COERCERTL].lastIndex = -1; } if (match === null) return null; return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options); }; var coerce_1 = coerce; var yallist = Yallist$1; Yallist$1.Node = Node; Yallist$1.create = Yallist$1; function Yallist$1(list) { var self = this; if (!(self instanceof Yallist$1)) { self = new Yallist$1(); } self.tail = null; self.head = null; self.length = 0; if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item); }); } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]); } } return self; } Yallist$1.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list'); } var next = node.next; var prev = node.prev; if (next) { next.prev = prev; } if (prev) { prev.next = next; } if (node === this.head) { this.head = next; } if (node === this.tail) { this.tail = prev; } node.list.length--; node.next = null; node.prev = null; node.list = null; return next; }; Yallist$1.prototype.unshiftNode = function (node) { if (node === this.head) { return; } if (node.list) { node.list.removeNode(node); } var head = this.head; node.list = this; node.next = head; if (head) { head.prev = node; } this.head = node; if (!this.tail) { this.tail = node; } this.length++; }; Yallist$1.prototype.pushNode = function (node) { if (node === this.tail) { return; } if (node.list) { node.list.removeNode(node); } var tail = this.tail; node.list = this; node.prev = tail; if (tail) { tail.next = node; } this.tail = node; if (!this.head) { this.head = node; } this.length++; }; Yallist$1.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]); } return this.length; }; Yallist$1.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]); } return this.length; }; Yallist$1.prototype.pop = function () { if (!this.tail) { return undefined; } var res = this.tail.value; this.tail = this.tail.prev; if (this.tail) { this.tail.next = null; } else { this.head = null; } this.length--; return res; }; Yallist$1.prototype.shift = function () { if (!this.head) { return undefined; } var res = this.head.value; this.head = this.head.next; if (this.head) { this.head.prev = null; } else { this.tail = null; } this.length--; return res; }; Yallist$1.prototype.forEach = function (fn, thisp) { thisp = thisp || this; for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this); walker = walker.next; } }; Yallist$1.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this; for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this); walker = walker.prev; } }; Yallist$1.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next; } if (i === n && walker !== null) { return walker.value; } }; Yallist$1.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev; } if (i === n && walker !== null) { return walker.value; } }; Yallist$1.prototype.map = function (fn, thisp) { thisp = thisp || this; var res = new Yallist$1(); for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)); walker = walker.next; } return res; }; Yallist$1.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this; var res = new Yallist$1(); for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)); walker = walker.prev; } return res; }; Yallist$1.prototype.reduce = function (fn, initial) { var acc; var walker = this.head; if (arguments.length > 1) { acc = initial; } else if (this.head) { walker = this.head.next; acc = this.head.value; } else { throw new TypeError('Reduce of empty list with no initial value'); } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i); walker = walker.next; } return acc; }; Yallist$1.prototype.reduceReverse = function (fn, initial) { var acc; var walker = this.tail; if (arguments.length > 1) { acc = initial; } else if (this.tail) { walker = this.tail.prev; acc = this.tail.value; } else { throw new TypeError('Reduce of empty list with no initial value'); } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i); walker = walker.prev; } return acc; }; Yallist$1.prototype.toArray = function () { var arr = new Array(this.length); for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value; walker = walker.next; } return arr; }; Yallist$1.prototype.toArrayReverse = function () { var arr = new Array(this.length); for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value; walker = walker.prev; } return arr; }; Yallist$1.prototype.slice = function (from, to) { to = to || this.length; if (to < 0) { to += this.length; } from = from || 0; if (from < 0) { from += this.length; } var ret = new Yallist$1(); if (to < from || to < 0) { return ret; } if (from < 0) { from = 0; } if (to > this.length) { to = this.length; } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next; } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value); } return ret; }; Yallist$1.prototype.sliceReverse = function (from, to) { to = to || this.length; if (to < 0) { to += this.length; } from = from || 0; if (from < 0) { from += this.length; } var ret = new Yallist$1(); if (to < from || to < 0) { return ret; } if (from < 0) { from = 0; } if (to > this.length) { to = this.length; } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev; } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value); } return ret; }; Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1; } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next; } var ret = []; for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value); walker = this.removeNode(walker); } if (walker === null) { walker = this.tail; } if (walker !== this.head && walker !== this.tail) { walker = walker.prev; } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]); } return ret; }; Yallist$1.prototype.reverse = function () { var head = this.head; var tail = this.tail; for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev; walker.prev = walker.next; walker.next = p; } this.head = tail; this.tail = head; return this; }; function insert(self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self); if (inserted.next === null) { self.tail = inserted; } if (inserted.prev === null) { self.head = inserted; } self.length++; return inserted; } function push(self, item) { self.tail = new Node(item, self.tail, null, self); if (!self.head) { self.head = self.tail; } self.length++; } function unshift(self, item) { self.head = new Node(item, null, self.head, self); if (!self.tail) { self.tail = self.head; } self.length++; } function Node(value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list); } this.list = list; this.value = value; if (prev) { prev.next = this; this.prev = prev; } else { this.prev = null; } if (next) { next.prev = this; this.next = next; } else { this.next = null; } } try { // add if support for Symbol.iterator is present require('./iterator.js')(Yallist$1); } catch (er) {} const Yallist = yallist; const MAX = Symbol('max'); const LENGTH = Symbol('length'); const LENGTH_CALCULATOR = Symbol('lengthCalculator'); const ALLOW_STALE = Symbol('allowStale'); const MAX_AGE = Symbol('maxAge'); const DISPOSE = Symbol('dispose'); const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); const LRU_LIST = Symbol('lruList'); const CACHE = Symbol('cache'); const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); const naiveLength = () => 1; // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor(options) { if (typeof options === 'number') options = { max: options }; if (!options) options = {}; if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number'); // Kind of weird to have a default max of Infinity, but oh well. this[MAX] = options.max || Infinity; const lc = options.length || naiveLength; this[LENGTH_CALCULATOR] = typeof lc !== 'function' ? naiveLength : lc; this[ALLOW_STALE] = options.stale || false; if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number'); this[MAX_AGE] = options.maxAge || 0; this[DISPOSE] = options.dispose; this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; this.reset(); } // resize the cache when the max changes. set max(mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number'); this[MAX] = mL || Infinity; trim(this); } get max() { return this[MAX]; } set allowStale(allowStale) { this[ALLOW_STALE] = !!allowStale; } get allowStale() { return this[ALLOW_STALE]; } set maxAge(mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number'); this[MAX_AGE] = mA; trim(this); } get maxAge() { return this[MAX_AGE]; } // resize the cache when the lengthCalculator changes. set lengthCalculator(lC) { if (typeof lC !== 'function') lC = naiveLength; if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC; this[LENGTH] = 0; this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); this[LENGTH] += hit.length; }); } trim(this); } get lengthCalculator() { return this[LENGTH_CALCULATOR]; } get length() { return this[LENGTH]; } get itemCount() { return this[LRU_LIST].length; } rforEach(fn, thisp) { thisp = thisp || this; for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev; forEachStep(this, fn, walker, thisp); walker = prev; } } forEach(fn, thisp) { thisp = thisp || this; for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next; forEachStep(this, fn, walker, thisp); walker = next; } } keys() { return this[LRU_LIST].toArray().map(k => k.key); } values() { return this[LRU_LIST].toArray().map(k => k.value); } reset() { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); } this[CACHE] = new Map(); // hash of items by key this[LRU_LIST] = new Yallist(); // list of items in order of use recency this[LENGTH] = 0; // length of items in the list } dump() { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h); } dumpLru() { return this[LRU_LIST]; } set(key, value, maxAge) { maxAge = maxAge || this[MAX_AGE]; if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number'); const now = maxAge ? Date.now() : 0; const len = this[LENGTH_CALCULATOR](value, key); if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)); return false; } const node = this[CACHE].get(key); const item = node.value; // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value); } item.now = now; item.maxAge = maxAge; item.value = value; this[LENGTH] += len - item.length; item.length = len; this.get(key); trim(this); return true; } const hit = new Entry(key, value, len, now, maxAge); // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value); return false; } this[LENGTH] += hit.length; this[LRU_LIST].unshift(hit); this[CACHE].set(key, this[LRU_LIST].head); trim(this); return true; } has(key) { if (!this[CACHE].has(key)) return false; const hit = this[CACHE].get(key).value; return !isStale(this, hit); } get(key) { return get(this, key, true); } peek(key) { return get(this, key, false); } pop() { const node = this[LRU_LIST].tail; if (!node) return null; del(this, node); return node.value; } del(key) { del(this, this[CACHE].get(key)); } load(arr) { // reset the cache this.reset(); const now = Date.now(); // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l]; const expiresAt = hit.e || 0; if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v);else { const maxAge = expiresAt - now; // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge); } } } } prune() { this[CACHE].forEach((value, key) => get(this, key, false)); } } const get = (self, key, doUse) => { const node = self[CACHE].get(key); if (node) { const hit = node.value; if (isStale(self, hit)) { del(self, node); if (!self[ALLOW_STALE]) return undefined; } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now(); self[LRU_LIST].unshiftNode(node); } } return hit.value; } }; const isStale = (self, hit) => { if (!hit || !hit.maxAge && !self[MAX_AGE]) return false; const diff = Date.now() - hit.now; return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && diff > self[MAX_AGE]; }; const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev; del(self, walker); walker = prev; } } }; const del = (self, node) => { if (node) { const hit = node.value; if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value); self[LENGTH] -= hit.length; self[CACHE].delete(hit.key); self[LRU_LIST].removeNode(node); } }; class Entry { constructor(key, value, length, now, maxAge) { this.key = key; this.value = value; this.length = length; this.now = now; this.maxAge = maxAge || 0; } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value; if (isStale(self, hit)) { del(self, node); if (!self[ALLOW_STALE]) hit = undefined; } if (hit) fn.call(thisp, hit.value, hit.key, self); }; var lruCache = LRUCache; class Range$a { constructor(range, options) { options = parseOptions$1(options); if (range instanceof Range$a) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range; } else { return new Range$a(range.raw, options); } } if (range instanceof Comparator$3) { // just put it in the set and return this.raw = range.value; this.set = [[range]]; this.format(); return this; } this.options = options; this.loose = !!options.loose; this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or || this.raw = range; this.set = range.split(/\s*\|\|\s*/) // map the range to a 2d array of comparators .map(range => this.parseRange(range.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length); if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${range}`); } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0]; this.set = this.set.filter(c => !isNullSet(c[0])); if (this.set.length === 0) this.set = [first];else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c]; break; } } } } this.format(); } format() { this.range = this.set.map(comps => { return comps.join(' ').trim(); }).join('||').trim(); return this.range; } toString() { return this.range; } parseRange(range) { range = range.trim(); // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = Object.keys(this.options).join(','); const memoKey = `parseRange:${memoOpts}:${range}`; const cached = cache.get(memoKey); if (cached) return cached; const loose = this.options.loose; // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); debug$1('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3` range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3` range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); // normalize spaces range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and // ready to be split into comparators. const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; const rangeList = range.split(' ').map(comp => parseComparator(comp, this.options)).join(' ').split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) // in loose mode, throw out any that are not valid comparators .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true).map(comp => new Comparator$3(comp, this.options)); // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once rangeList.length; const rangeMap = new Map(); for (const comp of rangeList) { if (isNullSet(comp)) return [comp]; rangeMap.set(comp.value, comp); } if (rangeMap.size > 1 && rangeMap.has('')) rangeMap.delete(''); const result = [...rangeMap.values()]; cache.set(memoKey, result); return result; } intersects(range, options) { if (!(range instanceof Range$a)) { throw new TypeError('a Range is required'); } return this.set.some(thisComparators => { return isSatisfiable(thisComparators, options) && range.set.some(rangeComparators => { return isSatisfiable(rangeComparators, options) && thisComparators.every(thisComparator => { return rangeComparators.every(rangeComparator => { return thisComparator.intersects(rangeComparator, options); }); }); }); }); } // if ANY of the sets match ALL of its comparators, then pass test(version) { if (!version) { return false; } if (typeof version === 'string') { try { version = new SemVer$5(version, this.options); } catch (er) { return false; } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true; } } return false; } } var range = Range$a; const LRU = lruCache; const cache = new LRU({ max: 1000 }); const parseOptions$1 = parseOptions_1; const Comparator$3 = comparator; const debug$1 = debug_1; const SemVer$5 = semver$1; const { re: re$1, t: t$1, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace } = re$5.exports; const isNullSet = c => c.value === '<0.0.0-0'; const isAny = c => c.value === ''; // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true; const remainingComparators = comparators.slice(); let testComparator = remainingComparators.pop(); while (result && remainingComparators.length) { result = remainingComparators.every(otherComparator => { return testComparator.intersects(otherComparator, options); }); testComparator = remainingComparators.pop(); } return result; }; // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug$1('comp', comp, options); comp = replaceCarets(comp, options); debug$1('caret', comp); comp = replaceTildes(comp, options); debug$1('tildes', comp); comp = replaceXRanges(comp, options); debug$1('xrange', comp); comp = replaceStars(comp, options); debug$1('stars', comp); return comp; }; const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 const replaceTildes = (comp, options) => comp.trim().split(/\s+/).map(comp => { return replaceTilde(comp, options); }).join(' '); const replaceTilde = (comp, options) => { const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; return comp.replace(r, (_, M, m, p, pr) => { debug$1('tilde', comp, _, M, m, p, pr); let ret; if (isX(M)) { ret = ''; } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; } else if (pr) { debug$1('replaceTilde pr', pr); ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; } debug$1('tilde return', ret); return ret; }); }; // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 const replaceCarets = (comp, options) => comp.trim().split(/\s+/).map(comp => { return replaceCaret(comp, options); }).join(' '); const replaceCaret = (comp, options) => { debug$1('caret', comp, options); const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; const z = options.includePrerelease ? '-0' : ''; return comp.replace(r, (_, M, m, p, pr) => { debug$1('caret', comp, _, M, m, p, pr); let ret; if (isX(M)) { ret = ''; } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; } } else if (pr) { debug$1('replaceCaret pr', pr); if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; } else { ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; } } else { ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; } } else { debug$1('no pr'); if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; } else { ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`; } } else { ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; } } debug$1('caret return', ret); return ret; }); }; const replaceXRanges = (comp, options) => { debug$1('replaceXRanges', comp, options); return comp.split(/\s+/).map(comp => { return replaceXRange(comp, options); }).join(' '); }; const replaceXRange = (comp, options) => { comp = comp.trim(); const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug$1('xRange', comp, ret, gtlt, M, m, p, pr); const xM = isX(M); const xm = xM || isX(m); const xp = xm || isX(p); const anyX = xp; if (gtlt === '=' && anyX) { gtlt = ''; } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : ''; if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0'; } else { // nothing is forbidden ret = '*'; } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0; } p = 0; if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>='; if (xm) { M = +M + 1; m = 0; p = 0; } else { m = +m + 1; p = 0; } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<'; if (xm) { M = +M + 1; } else { m = +m + 1; } } if (gtlt === '<') pr = '-0'; ret = `${gtlt + M}.${m}.${p}${pr}`; } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; } else if (xp) { ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; } debug$1('xRange return', ret); return ret; }); }; // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug$1('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re$1[t$1.STAR], ''); }; const replaceGTE0 = (comp, options) => { debug$1('replaceGTE0', comp, options); return comp.trim().replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], ''); }; // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = ''; } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}`; } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; } else if (fpr) { from = `>=${from}`; } else { from = `>=${from}${incPr ? '-0' : ''}`; } if (isX(tM)) { to = ''; } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0`; } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0`; } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}`; } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0`; } else { to = `<=${to}`; } return `${from} ${to}`.trim(); }; const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false; } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug$1(set[i].semver); if (set[i].semver === Comparator$3.ANY) { continue; } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver; if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true; } } } // Version has a -pre, but it's not one of the ones we like. return false; } return true; }; const ANY$2 = Symbol('SemVer ANY'); // hoisted class for cyclic dependency class Comparator$2 { static get ANY() { return ANY$2; } constructor(comp, options) { options = parseOptions(options); if (comp instanceof Comparator$2) { if (comp.loose === !!options.loose) { return comp; } else { comp = comp.value; } } debug('comparator', comp, options); this.options = options; this.loose = !!options.loose; this.parse(comp); if (this.semver === ANY$2) { this.value = ''; } else { this.value = this.operator + this.semver.version; } debug('comp', this); } parse(comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; const m = comp.match(r); if (!m) { throw new TypeError(`Invalid comparator: ${comp}`); } this.operator = m[1] !== undefined ? m[1] : ''; if (this.operator === '=') { this.operator = ''; } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY$2; } else { this.semver = new SemVer$4(m[2], this.options.loose); } } toString() { return this.value; } test(version) { debug('Comparator.test', version, this.options.loose); if (this.semver === ANY$2 || version === ANY$2) { return true; } if (typeof version === 'string') { try { version = new SemVer$4(version, this.options); } catch (er) { return false; } } return cmp(version, this.operator, this.semver, this.options); } intersects(comp, options) { if (!(comp instanceof Comparator$2)) { throw new TypeError('a Comparator is required'); } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false }; } if (this.operator === '') { if (this.value === '') { return true; } return new Range$9(comp.value, options).test(this.value); } else if (comp.operator === '') { if (comp.value === '') { return true; } return new Range$9(this.value, options).test(comp.semver); } const sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>'); const sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<'); const sameSemVer = this.semver.version === comp.semver.version; const differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); const oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); const oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; } } var comparator = Comparator$2; const parseOptions = parseOptions_1; const { re, t } = re$5.exports; const cmp = cmp_1; const debug = debug_1; const SemVer$4 = semver$1; const Range$9 = range; const Range$8 = range; const satisfies$3 = (version, range, options) => { try { range = new Range$8(range, options); } catch (er) { return false; } return range.test(version); }; var satisfies_1 = satisfies$3; const Range$7 = range; // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range$7(range, options).set.map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); var toComparators_1 = toComparators; const SemVer$3 = semver$1; const Range$6 = range; const maxSatisfying = (versions, range, options) => { let max = null; let maxSV = null; let rangeObj = null; try { rangeObj = new Range$6(range, options); } catch (er) { return null; } versions.forEach(v => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v; maxSV = new SemVer$3(max, options); } } }); return max; }; var maxSatisfying_1 = maxSatisfying; const SemVer$2 = semver$1; const Range$5 = range; const minSatisfying = (versions, range, options) => { let min = null; let minSV = null; let rangeObj = null; try { rangeObj = new Range$5(range, options); } catch (er) { return null; } versions.forEach(v => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v; minSV = new SemVer$2(min, options); } } }); return min; }; var minSatisfying_1 = minSatisfying; const SemVer$1 = semver$1; const Range$4 = range; const gt$1 = gt_1; const minVersion = (range, loose) => { range = new Range$4(range, loose); let minver = new SemVer$1('0.0.0'); if (range.test(minver)) { return minver; } minver = new SemVer$1('0.0.0-0'); if (range.test(minver)) { return minver; } minver = null; for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i]; let setMin = null; comparators.forEach(comparator => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer$1(comparator.semver.version); switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++; } else { compver.prerelease.push(0); } compver.raw = compver.format(); /* fallthrough */ case '': case '>=': if (!setMin || gt$1(compver, setMin)) { setMin = compver; } break; case '<': case '<=': /* Ignore maximum versions */ break; /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`); } }); if (setMin && (!minver || gt$1(minver, setMin))) minver = setMin; } if (minver && range.test(minver)) { return minver; } return null; }; var minVersion_1 = minVersion; const Range$3 = range; const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range$3(range, options).range || '*'; } catch (er) { return null; } }; var valid = validRange; const SemVer = semver$1; const Comparator$1 = comparator; const { ANY: ANY$1 } = Comparator$1; const Range$2 = range; const satisfies$2 = satisfies_1; const gt = gt_1; const lt = lt_1; const lte = lte_1; const gte = gte_1; const outside$2 = (version, range, hilo, options) => { version = new SemVer(version, options); range = new Range$2(range, options); let gtfn, ltefn, ltfn, comp, ecomp; switch (hilo) { case '>': gtfn = gt; ltefn = lte; ltfn = lt; comp = '>'; ecomp = '>='; break; case '<': gtfn = lt; ltefn = gte; ltfn = gt; comp = '<'; ecomp = '<='; break; default: throw new TypeError('Must provide a hilo val of "<" or ">"'); } // If it satisfies the range it is not outside if (satisfies$2(version, range, options)) { return false; } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i]; let high = null; let low = null; comparators.forEach(comparator => { if (comparator.semver === ANY$1) { comparator = new Comparator$1('>=0.0.0'); } high = high || comparator; low = low || comparator; if (gtfn(comparator.semver, high.semver, options)) { high = comparator; } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator; } }); // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false; } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false; } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false; } } return true; }; var outside_1 = outside$2; const outside$1 = outside_1; const gtr = (version, range, options) => outside$1(version, range, '>', options); var gtr_1 = gtr; const outside = outside_1; // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options); var ltr_1 = ltr; const Range$1 = range; const intersects = (r1, r2, options) => { r1 = new Range$1(r1, options); r2 = new Range$1(r2, options); return r1.intersects(r2); }; var intersects_1 = intersects; // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies$1 = satisfies_1; const compare$1 = compare_1; var simplify = (versions, range, options) => { const set = []; let min = null; let prev = null; const v = versions.sort((a, b) => compare$1(a, b, options)); for (const version of v) { const included = satisfies$1(version, range, options); if (included) { prev = version; if (!min) min = version; } else { if (prev) { set.push([min, prev]); } prev = null; min = null; } } if (min) set.push([min, null]); const ranges = []; for (const [min, max] of set) { if (min === max) ranges.push(min);else if (!max && min === v[0]) ranges.push('*');else if (!max) ranges.push(`>=${min}`);else if (min === v[0]) ranges.push(`<=${max}`);else ranges.push(`${min} - ${max}`); } const simplified = ranges.join(' || '); const original = typeof range.raw === 'string' ? range.raw : String(range); return simplified.length < original.length ? simplified : range; }; const Range = range; const Comparator = comparator; const { ANY } = Comparator; const satisfies = satisfies_1; const compare = compare_1; // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) return true; sub = new Range(sub, options); dom = new Range(dom, options); let sawNonNull = false; OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options); sawNonNull = sawNonNull || isSub !== null; if (isSub) continue OUTER; } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) return false; } return true; }; const simpleSubset = (sub, dom, options) => { if (sub === dom) return true; if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) return true;else if (options.includePrerelease) sub = [new Comparator('>=0.0.0-0')];else sub = [new Comparator('>=0.0.0')]; } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) return true;else dom = [new Comparator('>=0.0.0')]; } const eqSet = new Set(); let gt, lt; for (const c of sub) { if (c.operator === '>' || c.operator === '>=') gt = higherGT(gt, c, options);else if (c.operator === '<' || c.operator === '<=') lt = lowerLT(lt, c, options);else eqSet.add(c.semver); } if (eqSet.size > 1) return null; let gtltComp; if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options); if (gtltComp > 0) return null;else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) return null; } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) return null; if (lt && !satisfies(eq, String(lt), options)) return null; for (const c of dom) { if (!satisfies(eq, String(c), options)) return false; } return true; } let higher, lower; let hasDomLT, hasDomGT; // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false; } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false; } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options); if (higher === c && higher !== gt) return false; } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) return false; } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false; } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options); if (lower === c && lower !== lt) return false; } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) return false; } if (!c.operator && (lt || gt) && gtltComp !== 0) return false; } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) return false; if (lt && hasDomGT && !gt && gtltComp !== 0) return false; // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) return false; return true; }; // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) return b; const comp = compare(a.semver, b.semver, options); return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a; }; // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) return b; const comp = compare(a.semver, b.semver, options); return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a; }; var subset_1 = subset; const internalRe = re$5.exports; var semver = { re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, SemVer: semver$1, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, parse: parse_1, valid: valid_1, clean: clean_1, inc: inc_1, diff: diff_1, major: major_1, minor: minor_1, patch: patch_1, prerelease: prerelease_1, compare: compare_1, rcompare: rcompare_1, compareLoose: compareLoose_1, compareBuild: compareBuild_1, sort: sort_1, rsort: rsort_1, gt: gt_1, lt: lt_1, eq: eq_1, neq: neq_1, gte: gte_1, lte: lte_1, cmp: cmp_1, coerce: coerce_1, Comparator: comparator, Range: range, satisfies: satisfies_1, toComparators: toComparators_1, maxSatisfying: maxSatisfying_1, minSatisfying: minSatisfying_1, minVersion: minVersion_1, validRange: valid, outside: outside_1, gtr: gtr_1, ltr: ltr_1, intersects: intersects_1, simplifyRange: simplify, subset: subset_1 }; function adjustSpatial(item, encode, swap) { let t; if (encode.x2) { if (encode.x) { if (swap && item.x > item.x2) { t = item.x; item.x = item.x2; item.x2 = t; } item.width = item.x2 - item.x; } else { item.x = item.x2 - (item.width || 0); } } if (encode.xc) { item.x = item.xc - (item.width || 0) / 2; } if (encode.y2) { if (encode.y) { if (swap && item.y > item.y2) { t = item.y; item.y = item.y2; item.y2 = t; } item.height = item.y2 - item.y; } else { item.y = item.y2 - (item.height || 0); } } if (encode.yc) { item.y = item.yc - (item.height || 0) / 2; } } var Constants = { NaN: NaN, E: Math.E, LN2: Math.LN2, LN10: Math.LN10, LOG2E: Math.LOG2E, LOG10E: Math.LOG10E, PI: Math.PI, SQRT1_2: Math.SQRT1_2, SQRT2: Math.SQRT2, MIN_VALUE: Number.MIN_VALUE, MAX_VALUE: Number.MAX_VALUE }; var Ops = { '*': (a, b) => a * b, '+': (a, b) => a + b, '-': (a, b) => a - b, '/': (a, b) => a / b, '%': (a, b) => a % b, '>': (a, b) => a > b, '<': (a, b) => a < b, '<=': (a, b) => a <= b, '>=': (a, b) => a >= b, '==': (a, b) => a == b, '!=': (a, b) => a != b, '===': (a, b) => a === b, '!==': (a, b) => a !== b, '&': (a, b) => a & b, '|': (a, b) => a | b, '^': (a, b) => a ^ b, '<<': (a, b) => a << b, '>>': (a, b) => a >> b, '>>>': (a, b) => a >>> b }; var Unary = { '+': a => +a, '-': a => -a, '~': a => ~a, '!': a => !a }; const slice = Array.prototype.slice; const apply = (m, args, cast) => { const obj = cast ? cast(args[0]) : args[0]; return obj[m].apply(obj, slice.call(args, 1)); }; const datetime = (y, m, d, H, M, S, ms) => new Date(y, m || 0, d != null ? d : 1, H || 0, M || 0, S || 0, ms || 0); var Functions = { // math functions isNaN: Number.isNaN, isFinite: Number.isFinite, abs: Math.abs, acos: Math.acos, asin: Math.asin, atan: Math.atan, atan2: Math.atan2, ceil: Math.ceil, cos: Math.cos, exp: Math.exp, floor: Math.floor, log: Math.log, max: Math.max, min: Math.min, pow: Math.pow, random: Math.random, round: Math.round, sin: Math.sin, sqrt: Math.sqrt, tan: Math.tan, clamp: (a, b, c) => Math.max(b, Math.min(c, a)), // date functions now: Date.now, utc: Date.UTC, datetime: datetime, date: d => new Date(d).getDate(), day: d => new Date(d).getDay(), year: d => new Date(d).getFullYear(), month: d => new Date(d).getMonth(), hours: d => new Date(d).getHours(), minutes: d => new Date(d).getMinutes(), seconds: d => new Date(d).getSeconds(), milliseconds: d => new Date(d).getMilliseconds(), time: d => new Date(d).getTime(), timezoneoffset: d => new Date(d).getTimezoneOffset(), utcdate: d => new Date(d).getUTCDate(), utcday: d => new Date(d).getUTCDay(), utcyear: d => new Date(d).getUTCFullYear(), utcmonth: d => new Date(d).getUTCMonth(), utchours: d => new Date(d).getUTCHours(), utcminutes: d => new Date(d).getUTCMinutes(), utcseconds: d => new Date(d).getUTCSeconds(), utcmilliseconds: d => new Date(d).getUTCMilliseconds(), // sequence functions length: x => x.length, join: function () { return apply('join', arguments); }, indexof: function () { return apply('indexOf', arguments); }, lastindexof: function () { return apply('lastIndexOf', arguments); }, slice: function () { return apply('slice', arguments); }, reverse: x => x.slice().reverse(), // string functions parseFloat: parseFloat, parseInt: parseInt, upper: x => String(x).toUpperCase(), lower: x => String(x).toLowerCase(), substring: function () { return apply('substring', arguments, String); }, split: function () { return apply('split', arguments, String); }, replace: function () { return apply('replace', arguments, String); }, trim: x => String(x).trim(), // regexp functions regexp: RegExp, test: (r, t) => RegExp(r).test(t) }; const EventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y']; const Visitors = { Literal: ($, n) => n.value, Identifier: ($, n) => { const id = n.name; return $.memberDepth > 0 ? id : id === 'datum' ? $.datum : id === 'event' ? $.event : id === 'item' ? $.item : Constants[id] || $.params['$' + id]; }, MemberExpression: ($, n) => { const d = !n.computed, o = $(n.object); if (d) $.memberDepth += 1; const p = $(n.property); if (d) $.memberDepth -= 1; return o[p]; }, CallExpression: ($, n) => { const args = n.arguments; let name = n.callee.name; // handle special internal functions used by encoders // re-route to corresponding standard function if (name.startsWith('_')) { name = name.slice(1); } // special case "if" due to conditional evaluation of branches return name === 'if' ? $(args[0]) ? $(args[1]) : $(args[2]) : ($.fn[name] || Functions[name]).apply($.fn, args.map($)); }, ArrayExpression: ($, n) => n.elements.map($), BinaryExpression: ($, n) => Ops[n.operator]($(n.left), $(n.right)), UnaryExpression: ($, n) => Unary[n.operator]($(n.argument)), ConditionalExpression: ($, n) => $(n.test) ? $(n.consequent) : $(n.alternate), LogicalExpression: ($, n) => n.operator === '&&' ? $(n.left) && $(n.right) : $(n.left) || $(n.right), ObjectExpression: ($, n) => n.properties.reduce((o, p) => { $.memberDepth += 1; const k = $(p.key); $.memberDepth -= 1; o[k] = $(p.value); return o; }, {}) }; function interpret(ast, fn, params, datum, event, item) { const $ = n => Visitors[n.type]($, n); $.memberDepth = 0; $.fn = Object.create(fn); $.params = params; $.datum = datum; $.event = event; $.item = item; // route event functions to annotated vega event context EventFunctions.forEach(f => $.fn[f] = (...args) => event.vega[f](...args)); return $(ast); } var expression = { /** * Parse an expression used to update an operator value. */ operator(ctx, expr) { const ast = expr.ast, fn = ctx.functions; return _ => interpret(ast, fn, _); }, /** * Parse an expression provided as an operator parameter value. */ parameter(ctx, expr) { const ast = expr.ast, fn = ctx.functions; return (datum, _) => interpret(ast, fn, _, datum); }, /** * Parse an expression applied to an event stream. */ event(ctx, expr) { const ast = expr.ast, fn = ctx.functions; return event => interpret(ast, fn, undefined, undefined, event); }, /** * Parse an expression used to handle an event-driven operator update. */ handler(ctx, expr) { const ast = expr.ast, fn = ctx.functions; return (_, event) => { const datum = event.item && event.item.datum; return interpret(ast, fn, _, datum, event); }; }, /** * Parse an expression that performs visual encoding. */ encode(ctx, encode) { const { marktype, channels } = encode, fn = ctx.functions, swap = marktype === 'group' || marktype === 'image' || marktype === 'rect'; return (item, _) => { const datum = item.datum; let m = 0, v; for (const name in channels) { v = interpret(channels[name].ast, fn, _, datum, undefined, item); if (item[name] !== v) { item[name] = v; m = 1; } } if (marktype !== 'rule') { adjustSpatial(item, channels, swap); } return m; }; } }; function e(e) { const [n, r] = /schema\/([\w-]+)\/([\w\.\-]+)\.json$/g.exec(e).slice(1, 3); return { library: n, version: r }; } var name$1 = "vega-themes"; var version$2 = "2.10.0"; var description$1 = "Themes for stylized Vega and Vega-Lite visualizations."; var keywords$1 = ["vega", "vega-lite", "themes", "style"]; var license$1 = "BSD-3-Clause"; var author$1 = { name: "UW Interactive Data Lab", url: "https://idl.cs.washington.edu" }; var contributors$1 = [{ name: "Emily Gu", url: "https://github.com/emilygu" }, { name: "Arvind Satyanarayan", url: "http://arvindsatya.com" }, { name: "Jeffrey Heer", url: "https://idl.cs.washington.edu" }, { name: "Dominik Moritz", url: "https://www.domoritz.de" }]; var main$1 = "build/vega-themes.js"; var module$1 = "build/vega-themes.module.js"; var unpkg$1 = "build/vega-themes.min.js"; var jsdelivr$1 = "build/vega-themes.min.js"; var types$1 = "build/vega-themes.module.d.ts"; var repository$1 = { type: "git", url: "https://github.com/vega/vega-themes.git" }; var files$1 = ["src", "build"]; var scripts$1 = { prebuild: "yarn clean", build: "rollup -c", clean: "rimraf build && rimraf examples/build", "copy:data": "rsync -r node_modules/vega-datasets/data/* examples/data", "copy:build": "rsync -r build/* examples/build", "deploy:gh": "yarn build && mkdir -p examples/build && rsync -r build/* examples/build && gh-pages -d examples", prepublishOnly: "yarn clean && yarn build", preversion: "yarn lint", serve: "browser-sync start -s -f build examples --serveStatic examples", start: "yarn build && concurrently --kill-others -n Server,Rollup 'yarn serve' 'rollup -c -w'", prepare: "beemo create-config", eslintbase: "beemo eslint .", format: "yarn eslintbase --fix", lint: "yarn eslintbase" }; var devDependencies$1 = { "@rollup/plugin-json": "^4.1.0", "@rollup/plugin-node-resolve": "^11.2.0", "@wessberg/rollup-plugin-ts": "^1.3.8", "browser-sync": "^2.26.14", concurrently: "^6.0.0", "gh-pages": "^3.1.0", rollup: "^2.39.1", "rollup-plugin-bundle-size": "^1.0.3", "rollup-plugin-terser": "^7.0.2", typescript: "^4.2.2", vega: "^5.19.1", "vega-lite": "^5.0.0", "vega-lite-dev-config": "^0.16.1" }; var peerDependencies$1 = { vega: "*", "vega-lite": "*" }; var pkg$1 = { name: name$1, version: version$2, description: description$1, keywords: keywords$1, license: license$1, author: author$1, contributors: contributors$1, main: main$1, module: module$1, unpkg: unpkg$1, jsdelivr: jsdelivr$1, types: types$1, repository: repository$1, files: files$1, scripts: scripts$1, devDependencies: devDependencies$1, peerDependencies: peerDependencies$1 }; const lightColor = '#fff'; const medColor = '#888'; const darkTheme = { background: '#333', title: { color: lightColor, subtitleColor: lightColor }, style: { 'guide-label': { fill: lightColor }, 'guide-title': { fill: lightColor } }, axis: { domainColor: lightColor, gridColor: medColor, tickColor: lightColor } }; const markColor = '#4572a7'; const excelTheme = { background: '#fff', arc: { fill: markColor }, area: { fill: markColor }, line: { stroke: markColor, strokeWidth: 2 }, path: { stroke: markColor }, rect: { fill: markColor }, shape: { stroke: markColor }, symbol: { fill: markColor, strokeWidth: 1.5, size: 50 }, axis: { bandPosition: 0.5, grid: true, gridColor: '#000000', gridOpacity: 1, gridWidth: 0.5, labelPadding: 10, tickSize: 5, tickWidth: 0.5 }, axisBand: { grid: false, tickExtra: true }, legend: { labelBaseline: 'middle', labelFontSize: 11, symbolSize: 50, symbolType: 'square' }, range: { category: ['#4572a7', '#aa4643', '#8aa453', '#71598e', '#4598ae', '#d98445', '#94aace', '#d09393', '#b9cc98', '#a99cbc'] } }; const markColor$1 = '#30a2da'; const axisColor = '#cbcbcb'; const guideLabelColor = '#999'; const guideTitleColor = '#333'; const backgroundColor = '#f0f0f0'; const blackTitle = '#333'; const fiveThirtyEightTheme = { arc: { fill: markColor$1 }, area: { fill: markColor$1 }, axis: { domainColor: axisColor, grid: true, gridColor: axisColor, gridWidth: 1, labelColor: guideLabelColor, labelFontSize: 10, titleColor: guideTitleColor, tickColor: axisColor, tickSize: 10, titleFontSize: 14, titlePadding: 10, labelPadding: 4 }, axisBand: { grid: false }, background: backgroundColor, group: { fill: backgroundColor }, legend: { labelColor: blackTitle, labelFontSize: 11, padding: 1, symbolSize: 30, symbolType: 'square', titleColor: blackTitle, titleFontSize: 14, titlePadding: 10 }, line: { stroke: markColor$1, strokeWidth: 2 }, path: { stroke: markColor$1, strokeWidth: 0.5 }, rect: { fill: markColor$1 }, range: { category: ['#30a2da', '#fc4f30', '#e5ae38', '#6d904f', '#8b8b8b', '#b96db8', '#ff9e27', '#56cc60', '#52d2ca', '#52689e', '#545454', '#9fe4f8'], diverging: ['#cc0020', '#e77866', '#f6e7e1', '#d6e8ed', '#91bfd9', '#1d78b5'], heatmap: ['#d6e8ed', '#cee0e5', '#91bfd9', '#549cc6', '#1d78b5'] }, point: { filled: true, shape: 'circle' }, shape: { stroke: markColor$1 }, bar: { binSpacing: 2, fill: markColor$1, stroke: null }, title: { anchor: 'start', fontSize: 24, fontWeight: 600, offset: 20 } }; const markColor$2 = '#000'; const ggplot2Theme = { group: { fill: '#e5e5e5' }, arc: { fill: markColor$2 }, area: { fill: markColor$2 }, line: { stroke: markColor$2 }, path: { stroke: markColor$2 }, rect: { fill: markColor$2 }, shape: { stroke: markColor$2 }, symbol: { fill: markColor$2, size: 40 }, axis: { domain: false, grid: true, gridColor: '#FFFFFF', gridOpacity: 1, labelColor: '#7F7F7F', labelPadding: 4, tickColor: '#7F7F7F', tickSize: 5.67, titleFontSize: 16, titleFontWeight: 'normal' }, legend: { labelBaseline: 'middle', labelFontSize: 11, symbolSize: 40 }, range: { category: ['#000000', '#7F7F7F', '#1A1A1A', '#999999', '#333333', '#B0B0B0', '#4D4D4D', '#C9C9C9', '#666666', '#DCDCDC'] } }; const headlineFontSize = 22; const headlineFontWeight = 'normal'; const labelFont = 'Benton Gothic, sans-serif'; const labelFontSize = 11.5; const labelFontWeight = 'normal'; const markColor$3 = '#82c6df'; // const markHighlight = '#006d8f'; // const markDemocrat = '#5789b8'; // const markRepublican = '#d94f54'; const titleFont = 'Benton Gothic Bold, sans-serif'; const titleFontWeight = 'normal'; const titleFontSize = 13; const colorSchemes = { 'category-6': ['#ec8431', '#829eb1', '#c89d29', '#3580b1', '#adc839', '#ab7fb4'], 'fire-7': ['#fbf2c7', '#f9e39c', '#f8d36e', '#f4bb6a', '#e68a4f', '#d15a40', '#ab4232'], 'fireandice-6': ['#e68a4f', '#f4bb6a', '#f9e39c', '#dadfe2', '#a6b7c6', '#849eae'], 'ice-7': ['#edefee', '#dadfe2', '#c4ccd2', '#a6b7c6', '#849eae', '#607785', '#47525d'] }; const latimesTheme = { background: '#ffffff', title: { anchor: 'start', color: '#000000', font: titleFont, fontSize: headlineFontSize, fontWeight: headlineFontWeight }, arc: { fill: markColor$3 }, area: { fill: markColor$3 }, line: { stroke: markColor$3, strokeWidth: 2 }, path: { stroke: markColor$3 }, rect: { fill: markColor$3 }, shape: { stroke: markColor$3 }, symbol: { fill: markColor$3, size: 30 }, axis: { labelFont, labelFontSize, labelFontWeight, titleFont, titleFontSize, titleFontWeight }, axisX: { labelAngle: 0, labelPadding: 4, tickSize: 3 }, axisY: { labelBaseline: 'middle', maxExtent: 45, minExtent: 45, tickSize: 2, titleAlign: 'left', titleAngle: 0, titleX: -45, titleY: -11 }, legend: { labelFont, labelFontSize, symbolType: 'square', titleFont, titleFontSize, titleFontWeight }, range: { category: colorSchemes['category-6'], diverging: colorSchemes['fireandice-6'], heatmap: colorSchemes['fire-7'], ordinal: colorSchemes['fire-7'], ramp: colorSchemes['fire-7'] } }; const markColor$4 = '#ab5787'; const axisColor$1 = '#979797'; const quartzTheme = { background: '#f9f9f9', arc: { fill: markColor$4 }, area: { fill: markColor$4 }, line: { stroke: markColor$4 }, path: { stroke: markColor$4 }, rect: { fill: markColor$4 }, shape: { stroke: markColor$4 }, symbol: { fill: markColor$4, size: 30 }, axis: { domainColor: axisColor$1, domainWidth: 0.5, gridWidth: 0.2, labelColor: axisColor$1, tickColor: axisColor$1, tickWidth: 0.2, titleColor: axisColor$1 }, axisBand: { grid: false }, axisX: { grid: true, tickSize: 10 }, axisY: { domain: false, grid: true, tickSize: 0 }, legend: { labelFontSize: 11, padding: 1, symbolSize: 30, symbolType: 'square' }, range: { category: ['#ab5787', '#51b2e5', '#703c5c', '#168dd9', '#d190b6', '#00609f', '#d365ba', '#154866', '#666666', '#c4c4c4'] } }; const markColor$5 = '#3e5c69'; const voxTheme = { background: '#fff', arc: { fill: markColor$5 }, area: { fill: markColor$5 }, line: { stroke: markColor$5 }, path: { stroke: markColor$5 }, rect: { fill: markColor$5 }, shape: { stroke: markColor$5 }, symbol: { fill: markColor$5 }, axis: { domainWidth: 0.5, grid: true, labelPadding: 2, tickSize: 5, tickWidth: 0.5, titleFontWeight: 'normal' }, axisBand: { grid: false }, axisX: { gridWidth: 0.2 }, axisY: { gridDash: [3], gridWidth: 0.4 }, legend: { labelFontSize: 11, padding: 1, symbolType: 'square' }, range: { category: ['#3e5c69', '#6793a6', '#182429', '#0570b0', '#3690c0', '#74a9cf', '#a6bddb', '#e2ddf2'] } }; const markColor$6 = '#1696d2'; const axisColor$2 = '#000000'; const backgroundColor$1 = '#FFFFFF'; const font = 'Lato'; const labelFont$1 = 'Lato'; const sourceFont = 'Lato'; const gridColor = '#DEDDDD'; const titleFontSize$1 = 18; const colorSchemes$1 = { 'main-colors': ['#1696d2', '#d2d2d2', '#000000', '#fdbf11', '#ec008b', '#55b748', '#5c5859', '#db2b27'], 'shades-blue': ['#CFE8F3', '#A2D4EC', '#73BFE2', '#46ABDB', '#1696D2', '#12719E', '#0A4C6A', '#062635'], 'shades-gray': ['#F5F5F5', '#ECECEC', '#E3E3E3', '#DCDBDB', '#D2D2D2', '#9D9D9D', '#696969', '#353535'], 'shades-yellow': ['#FFF2CF', '#FCE39E', '#FDD870', '#FCCB41', '#FDBF11', '#E88E2D', '#CA5800', '#843215'], 'shades-magenta': ['#F5CBDF', '#EB99C2', '#E46AA7', '#E54096', '#EC008B', '#AF1F6B', '#761548', '#351123'], 'shades-green': ['#DCEDD9', '#BCDEB4', '#98CF90', '#78C26D', '#55B748', '#408941', '#2C5C2D', '#1A2E19'], 'shades-black': ['#D5D5D4', '#ADABAC', '#848081', '#5C5859', '#332D2F', '#262223', '#1A1717', '#0E0C0D'], 'shades-red': ['#F8D5D4', '#F1AAA9', '#E9807D', '#E25552', '#DB2B27', '#A4201D', '#6E1614', '#370B0A'], 'one-group': ['#1696d2', '#000000'], 'two-groups-cat-1': ['#1696d2', '#000000'], 'two-groups-cat-2': ['#1696d2', '#fdbf11'], 'two-groups-cat-3': ['#1696d2', '#db2b27'], 'two-groups-seq': ['#a2d4ec', '#1696d2'], 'three-groups-cat': ['#1696d2', '#fdbf11', '#000000'], 'three-groups-seq': ['#a2d4ec', '#1696d2', '#0a4c6a'], 'four-groups-cat-1': ['#000000', '#d2d2d2', '#fdbf11', '#1696d2'], 'four-groups-cat-2': ['#1696d2', '#ec0008b', '#fdbf11', '#5c5859'], 'four-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a'], 'five-groups-cat-1': ['#1696d2', '#fdbf11', '#d2d2d2', '#ec008b', '#000000'], 'five-groups-cat-2': ['#1696d2', '#0a4c6a', '#d2d2d2', '#fdbf11', '#332d2f'], 'five-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a', '#000000'], 'six-groups-cat-1': ['#1696d2', '#ec008b', '#fdbf11', '#000000', '#d2d2d2', '#55b748'], 'six-groups-cat-2': ['#1696d2', '#d2d2d2', '#ec008b', '#fdbf11', '#332d2f', '#0a4c6a'], 'six-groups-seq': ['#cfe8f3', '#a2d4ec', '#73bfe2', '#46abdb', '#1696d2', '#12719e'], 'diverging-colors': ['#ca5800', '#fdbf11', '#fdd870', '#fff2cf', '#cfe8f3', '#73bfe2', '#1696d2', '#0a4c6a'] }; const urbanInstituteTheme = { background: backgroundColor$1, title: { anchor: 'start', fontSize: titleFontSize$1, font: font }, axisX: { domain: true, domainColor: axisColor$2, domainWidth: 1, grid: false, labelFontSize: 12, labelFont: labelFont$1, labelAngle: 0, tickColor: axisColor$2, tickSize: 5, titleFontSize: 12, titlePadding: 10, titleFont: font }, axisY: { domain: false, domainWidth: 1, grid: true, gridColor: gridColor, gridWidth: 1, labelFontSize: 12, labelFont: labelFont$1, labelPadding: 8, ticks: false, titleFontSize: 12, titlePadding: 10, titleFont: font, titleAngle: 0, titleY: -10, titleX: 18 }, legend: { labelFontSize: 12, labelFont: labelFont$1, symbolSize: 100, titleFontSize: 12, titlePadding: 10, titleFont: font, orient: 'right', offset: 10 }, view: { stroke: 'transparent' }, range: { category: colorSchemes$1['six-groups-cat-1'], diverging: colorSchemes$1['diverging-colors'], heatmap: colorSchemes$1['diverging-colors'], ordinal: colorSchemes$1['six-groups-seq'], ramp: colorSchemes$1['shades-blue'] }, area: { fill: markColor$6 }, rect: { fill: markColor$6 }, line: { color: markColor$6, stroke: markColor$6, strokeWidth: 5 }, trail: { color: markColor$6, stroke: markColor$6, strokeWidth: 0, size: 1 }, path: { stroke: markColor$6, strokeWidth: 0.5 }, point: { filled: true }, text: { font: sourceFont, color: markColor$6, fontSize: 11, align: 'center', fontWeight: 400, size: 11 }, style: { bar: { fill: markColor$6, stroke: null } }, arc: { fill: markColor$6 }, shape: { stroke: markColor$6 }, symbol: { fill: markColor$6, size: 30 } }; /** * Copyright 2020 Google LLC. * * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ const markColor$7 = '#3366CC'; const gridColor$1 = '#ccc'; const defaultFont = 'Arial, sans-serif'; const googlechartsTheme = { arc: { fill: markColor$7 }, area: { fill: markColor$7 }, path: { stroke: markColor$7 }, rect: { fill: markColor$7 }, shape: { stroke: markColor$7 }, symbol: { stroke: markColor$7 }, circle: { fill: markColor$7 }, background: '#fff', padding: { top: 10, right: 10, bottom: 10, left: 10 }, style: { 'guide-label': { font: defaultFont, fontSize: 12 }, 'guide-title': { font: defaultFont, fontSize: 12 }, 'group-title': { font: defaultFont, fontSize: 12 } }, title: { font: defaultFont, fontSize: 14, fontWeight: 'bold', dy: -3, anchor: 'start' }, axis: { gridColor: gridColor$1, tickColor: gridColor$1, domain: false, grid: true }, range: { category: ['#4285F4', '#DB4437', '#F4B400', '#0F9D58', '#AB47BC', '#00ACC1', '#FF7043', '#9E9D24', '#5C6BC0', '#F06292', '#00796B', '#C2185B'], heatmap: ['#c6dafc', '#5e97f6', '#2a56c6'] } }; const version$1$1 = pkg$1.version; var themes = /*#__PURE__*/Object.freeze({ __proto__: null, dark: darkTheme, excel: excelTheme, fivethirtyeight: fiveThirtyEightTheme, ggplot2: ggplot2Theme, googlecharts: googlechartsTheme, latimes: latimesTheme, quartz: quartzTheme, urbaninstitute: urbanInstituteTheme, version: version$1$1, vox: voxTheme }); function accessor(fn, fields, name) { fn.fields = fields || []; fn.fname = name; return fn; } function getter(path) { return path.length === 1 ? get1(path[0]) : getN(path); } const get1 = field => function (obj) { return obj[field]; }; const getN = path => { const len = path.length; return function (obj) { for (let i = 0; i < len; ++i) { obj = obj[path[i]]; } return obj; }; }; function error(message) { throw Error(message); } function splitAccessPath(p) { const path = [], n = p.length; let q = null, b = 0, s = '', i, j, c; p = p + ''; function push() { path.push(s + p.substring(i, j)); s = ''; i = j + 1; } for (i = j = 0; j < n; ++j) { c = p[j]; if (c === '\\') { s += p.substring(i, j); s += p.substring(++j, ++j); i = j; } else if (c === q) { push(); q = null; b = -1; } else if (q) { continue; } else if (i === b && c === '"') { i = j + 1; q = c; } else if (i === b && c === "'") { i = j + 1; q = c; } else if (c === '.' && !b) { if (j > i) { push(); } else { i = j + 1; } } else if (c === '[') { if (j > i) push(); b = i = j + 1; } else if (c === ']') { if (!b) error('Access path missing open bracket: ' + p); if (b > 0) push(); b = 0; i = j + 1; } } if (b) error('Access path missing closing bracket: ' + p); if (q) error('Access path missing closing quote: ' + p); if (j > i) { j++; push(); } return path; } function field(field, name, opt) { const path = splitAccessPath(field); field = path.length === 1 ? path[0] : field; return accessor((opt && opt.get || getter)(path), [field], name || field); } field('id'); accessor(_ => _, [], 'identity'); accessor(() => 0, [], 'zero'); accessor(() => 1, [], 'one'); accessor(() => true, [], 'true'); accessor(() => false, [], 'false'); var isArray = Array.isArray; function isObject(_) { return _ === Object(_); } function isString(_) { return typeof _ === 'string'; } /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } /** * Format the value to be shown in the tooltip. * * @param value The value to show in the tooltip. * @param valueToHtml Function to convert a single cell value to an HTML string */ function formatValue(value, valueToHtml, maxDepth) { if (isArray(value)) { return `[${value.map(v => valueToHtml(isString(v) ? v : stringify(v, maxDepth))).join(', ')}]`; } if (isObject(value)) { let content = ''; const _a = value, { title, image } = _a, rest = __rest(_a, ["title", "image"]); if (title) { content += `<h2>${valueToHtml(title)}</h2>`; } if (image) { content += `<img src="${valueToHtml(image)}">`; } const keys = Object.keys(rest); if (keys.length > 0) { content += '<table>'; for (const key of keys) { let val = rest[key]; // ignore undefined properties if (val === undefined) { continue; } if (isObject(val)) { val = stringify(val, maxDepth); } content += `<tr><td class="key">${valueToHtml(key)}:</td><td class="value">${valueToHtml(val)}</td></tr>`; } content += `</table>`; } return content || '{}'; // show empty object if there are no properties } return valueToHtml(value); } function replacer(maxDepth) { const stack = []; return function (key, value) { if (typeof value !== 'object' || value === null) { return value; } const pos = stack.indexOf(this) + 1; stack.length = pos; if (stack.length > maxDepth) { return '[Object]'; } if (stack.indexOf(value) >= 0) { return '[Circular]'; } stack.push(value); return value; }; } /** * Stringify any JS object to valid JSON */ function stringify(obj, maxDepth) { return JSON.stringify(obj, replacer(maxDepth)); } // generated with build-style.sh var defaultStyle = `#vg-tooltip-element { visibility: hidden; padding: 8px; position: fixed; z-index: 1000; font-family: sans-serif; font-size: 11px; border-radius: 3px; box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1); /* The default theme is the light theme. */ background-color: rgba(255, 255, 255, 0.95); border: 1px solid #d9d9d9; color: black; } #vg-tooltip-element.visible { visibility: visible; } #vg-tooltip-element h2 { margin-top: 0; margin-bottom: 10px; font-size: 13px; } #vg-tooltip-element img { max-width: 200px; max-height: 200px; } #vg-tooltip-element table { border-spacing: 0; } #vg-tooltip-element table tr { border: none; } #vg-tooltip-element table tr td { overflow: hidden; text-overflow: ellipsis; padding-top: 2px; padding-bottom: 2px; } #vg-tooltip-element table tr td.key { color: #808080; max-width: 150px; text-align: right; padding-right: 4px; } #vg-tooltip-element table tr td.value { display: block; max-width: 300px; max-height: 7em; text-align: left; } #vg-tooltip-element.dark-theme { background-color: rgba(32, 32, 32, 0.9); border: 1px solid #f5f5f5; color: white; } #vg-tooltip-element.dark-theme td.key { color: #bfbfbf; } `; const EL_ID = 'vg-tooltip-element'; const DEFAULT_OPTIONS = { /** * X offset. */ offsetX: 10, /** * Y offset. */ offsetY: 10, /** * ID of the tooltip element. */ id: EL_ID, /** * ID of the tooltip CSS style. */ styleId: 'vega-tooltip-style', /** * The name of the theme. You can use the CSS class called [THEME]-theme to style the tooltips. * * There are two predefined themes: "light" (default) and "dark". */ theme: 'light', /** * Do not use the default styles provided by Vega Tooltip. If you enable this option, you need to use your own styles. It is not necessary to disable the default style when using a custom theme. */ disableDefaultStyle: false, /** * HTML sanitizer function that removes dangerous HTML to prevent XSS. * * This should be a function from string to string. You may replace it with a formatter such as a markdown formatter. */ sanitize: escapeHTML, /** * The maximum recursion depth when printing objects in the tooltip. */ maxDepth: 2, /** * A function to customize the rendered HTML of the tooltip. * @param value A value string, or object of value strings keyed by field * @param sanitize The `sanitize` function from `options.sanitize` * @returns {string} The returned string will become the `innerHTML` of the tooltip element */ formatTooltip: formatValue }; /** * Escape special HTML characters. * * @param value A value to convert to string and HTML-escape. */ function escapeHTML(value) { return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;'); } function createDefaultStyle(id) { // Just in case this id comes from a user, ensure these is no security issues if (!/^[A-Za-z]+[-:.\w]*$/.test(id)) { throw new Error('Invalid HTML ID'); } return defaultStyle.toString().replace(EL_ID, id); } /** * Position the tooltip * * @param event The mouse event. * @param tooltipBox * @param offsetX Horizontal offset. * @param offsetY Vertical offset. */ function calculatePosition(event, tooltipBox, offsetX, offsetY) { let x = event.clientX + offsetX; if (x + tooltipBox.width > window.innerWidth) { x = +event.clientX - offsetX - tooltipBox.width; } let y = event.clientY + offsetY; if (y + tooltipBox.height > window.innerHeight) { y = +event.clientY - offsetY - tooltipBox.height; } return { x, y }; } /** * The tooltip handler class. */ class Handler { /** * Create the tooltip handler and initialize the element and style. * * @param options Tooltip Options */ constructor(options) { this.options = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); const elementId = this.options.id; this.el = null; // bind this to call this.call = this.tooltipHandler.bind(this); // prepend a default stylesheet for tooltips to the head if (!this.options.disableDefaultStyle && !document.getElementById(this.options.styleId)) { const style = document.createElement('style'); style.setAttribute('id', this.options.styleId); style.innerHTML = createDefaultStyle(elementId); const head = document.head; if (head.childNodes.length > 0) { head.insertBefore(style, head.childNodes[0]); } else { head.appendChild(style); } } } /** * The tooltip handler function. */ tooltipHandler(handler, event, item, value) { // console.log(handler, event, item, value); var _a; // append a div element that we use as a tooltip unless it already exists this.el = document.getElementById(this.options.id); if (!this.el) { this.el = document.createElement('div'); this.el.setAttribute('id', this.options.id); this.el.classList.add('vg-tooltip'); document.body.appendChild(this.el); } const tooltipContainer = (_a = document.fullscreenElement) !== null && _a !== void 0 ? _a : document.body; tooltipContainer.appendChild(this.el); // hide tooltip for null, undefined, or empty string values if (value == null || value === '') { this.el.classList.remove('visible', `${this.options.theme}-theme`); return; } // set the tooltip content this.el.innerHTML = this.options.formatTooltip(value, this.options.sanitize, this.options.maxDepth); // make the tooltip visible this.el.classList.add('visible', `${this.options.theme}-theme`); const { x, y } = calculatePosition(event, this.el.getBoundingClientRect(), this.options.offsetX, this.options.offsetY); this.el.setAttribute('style', `top: ${y}px; left: ${x}px`); } } /** * Open editor url in a new window, and pass a message. */ function post (window, url, data) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const editor = window.open(url); const wait = 10000; const step = 250; const { origin } = new URL(url); // eslint-disable-next-line no-bitwise let count = ~~(wait / step); function listen(evt) { if (evt.source === editor) { count = 0; window.removeEventListener('message', listen, false); } } window.addEventListener('message', listen, false); // send message // periodically resend until ack received or timeout function send() { if (count <= 0) { return; } editor.postMessage(data, origin); setTimeout(send, step); count -= 1; } setTimeout(send, step); } // generated with build-style.sh var embedStyle = `.vega-embed { position: relative; display: inline-block; box-sizing: border-box; } .vega-embed.has-actions { padding-right: 38px; } .vega-embed details:not([open]) > :not(summary) { display: none !important; } .vega-embed summary { list-style: none; position: absolute; top: 0; right: 0; padding: 6px; z-index: 1000; background: white; box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1); color: #1b1e23; border: 1px solid #aaa; border-radius: 999px; opacity: 0.2; transition: opacity 0.4s ease-in; outline: none; cursor: pointer; line-height: 0px; } .vega-embed summary::-webkit-details-marker { display: none; } .vega-embed summary:active { box-shadow: #aaa 0px 0px 0px 1px inset; } .vega-embed summary svg { width: 14px; height: 14px; } .vega-embed details[open] summary { opacity: 0.7; } .vega-embed:hover summary, .vega-embed:focus summary { opacity: 1 !important; transition: opacity 0.2s ease; } .vega-embed .vega-actions { position: absolute; z-index: 1001; top: 35px; right: -9px; display: flex; flex-direction: column; padding-bottom: 8px; padding-top: 8px; border-radius: 4px; box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.2); border: 1px solid #d9d9d9; background: white; animation-duration: 0.15s; animation-name: scale-in; animation-timing-function: cubic-bezier(0.2, 0, 0.13, 1.5); text-align: left; } .vega-embed .vega-actions a { padding: 8px 16px; font-family: sans-serif; font-size: 14px; font-weight: 600; white-space: nowrap; color: #434a56; text-decoration: none; } .vega-embed .vega-actions a:hover { background-color: #f7f7f9; color: black; } .vega-embed .vega-actions::before, .vega-embed .vega-actions::after { content: ""; display: inline-block; position: absolute; } .vega-embed .vega-actions::before { left: auto; right: 14px; top: -16px; border: 8px solid #0000; border-bottom-color: #d9d9d9; } .vega-embed .vega-actions::after { left: auto; right: 15px; top: -14px; border: 7px solid #0000; border-bottom-color: #fff; } .vega-embed .chart-wrapper.fit-x { width: 100%; } .vega-embed .chart-wrapper.fit-y { height: 100%; } .vega-embed-wrapper { max-width: 100%; overflow: auto; padding-right: 14px; } @keyframes scale-in { from { opacity: 0; transform: scale(0.6); } to { opacity: 1; transform: scale(1); } } `; if (!String.prototype.startsWith) { // eslint-disable-next-line no-extend-native,func-names String.prototype.startsWith = function (search, pos) { return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; }; } function isURL(s) { return s.startsWith('http://') || s.startsWith('https://') || s.startsWith('//'); } function mergeDeep(dest, ...src) { for (const s of src) { deepMerge_(dest, s); } return dest; } function deepMerge_(dest, src) { for (const property of Object.keys(src)) { vegaImport.writeConfig(dest, property, src[property], true); } } var name = "vega-embed"; var version$1 = "6.20.0-next.0"; var description = "Publish Vega visualizations as embedded web components."; var keywords = ["vega", "data", "visualization", "component", "embed"]; var repository = { type: "git", url: "http://github.com/vega/vega-embed.git" }; var author = { name: "UW Interactive Data Lab", url: "http://idl.cs.washington.edu" }; var contributors = [{ name: "Dominik Moritz", url: "https://www.domoritz.de" }]; var bugs = { url: "https://github.com/vega/vega-embed/issues" }; var homepage = "https://github.com/vega/vega-embed#readme"; var license = "BSD-3-Clause"; var main = "build/vega-embed.js"; var module = "build/vega-embed.module.js"; var unpkg = "build/vega-embed.min.js"; var jsdelivr = "build/vega-embed.min.js"; var types = "build/vega-embed.module.d.ts"; var files = ["src", "build", "build-es5"]; var devDependencies = { "@auto-it/conventional-commits": "^10.32.0", "@auto-it/first-time-contributor": "^10.32.0", "@rollup/plugin-commonjs": "21.0.1", "@rollup/plugin-json": "^4.1.0", "@rollup/plugin-node-resolve": "^13.0.4", "@types/semver": "^7.3.8", "@wessberg/rollup-plugin-ts": "^1.3.14", auto: "^10.32.0", "browser-sync": "^2.27.5", concurrently: "^6.2.1", "del-cli": "^4.0.1", "jest-canvas-mock": "^2.3.1", "node-sass": "^6.0.1", "rollup-plugin-bundle-size": "^1.0.3", "rollup-plugin-terser": "^7.0.2", rollup: "2.58.1", typescript: "^4.4.3", "vega-lite-dev-config": "^0.18.0", "vega-lite": "^5.0.0", vega: "^5.19.1" }; var peerDependencies = { vega: "^5.20.2", "vega-lite": "*" }; var dependencies = { "fast-json-patch": "^3.1.0", "json-stringify-pretty-compact": "^3.0.0", semver: "^7.3.5", tslib: "^2.3.1", "vega-interpreter": "^1.0.4", "vega-schema-url-parser": "^2.2.0", "vega-themes": "^2.10.0", "vega-tooltip": "^0.27.0" }; var scripts = { prebuild: "yarn clean && yarn build:style", build: "rollup -c", "build:style": "./build-style.sh", clean: "del-cli build build-es5 src/style.ts", prepublishOnly: "yarn clean && yarn build", preversion: "yarn lint && yarn test", serve: "browser-sync start --directory -s -f build *.html", start: "yarn build && concurrently --kill-others -n Server,Rollup 'yarn serve' 'rollup -c -w'", pretest: "yarn build:style", test: "beemo jest --stdio stream", "test:inspect": "node --inspect-brk ./node_modules/.bin/jest --runInBand", prepare: "beemo create-config", prettierbase: "beemo prettier '*.{css,scss,html}'", eslintbase: "beemo eslint .", format: "yarn eslintbase --fix && yarn prettierbase --write", lint: "yarn eslintbase && yarn prettierbase --check", release: "auto shipit" }; var pkg = { name: name, version: version$1, description: description, keywords: keywords, repository: repository, author: author, contributors: contributors, bugs: bugs, homepage: homepage, license: license, main: main, module: module, unpkg: unpkg, jsdelivr: jsdelivr, types: types, files: files, devDependencies: devDependencies, peerDependencies: peerDependencies, dependencies: dependencies, scripts: scripts }; var _w$vl; const version = pkg.version; const vega = vegaImport__namespace; let vegaLite = vegaLiteImport__namespace; // For backwards compatibility with Vega-Lite before v4. const w = typeof window !== 'undefined' ? window : undefined; if (vegaLite === undefined && w !== null && w !== void 0 && (_w$vl = w['vl']) !== null && _w$vl !== void 0 && _w$vl.compile) { vegaLite = w['vl']; } const DEFAULT_ACTIONS = { export: { svg: true, png: true }, source: true, compiled: true, editor: true }; const I18N = { CLICK_TO_VIEW_ACTIONS: 'Click to view actions', COMPILED_ACTION: 'View Compiled Vega', EDITOR_ACTION: 'Open in Vega Editor', PNG_ACTION: 'Save as PNG', SOURCE_ACTION: 'View Source', SVG_ACTION: 'Save as SVG' }; const NAMES = { vega: 'Vega', 'vega-lite': 'Vega-Lite' }; const VERSION = { vega: vega.version, 'vega-lite': vegaLite ? vegaLite.version : 'not available' }; const PREPROCESSOR = { vega: vgSpec => vgSpec, 'vega-lite': (vlSpec, config) => vegaLite.compile(vlSpec, { config: config }).spec }; const SVG_CIRCLES = ` <svg viewBox="0 0 16 16" fill="currentColor" stroke="none" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"> <circle r="2" cy="8" cx="2"></circle> <circle r="2" cy="8" cx="8"></circle> <circle r="2" cy="8" cx="14"></circle> </svg>`; const CHART_WRAPPER_CLASS = 'chart-wrapper'; function isTooltipHandler(h) { return typeof h === 'function'; } function viewSource(source, sourceHeader, sourceFooter, mode) { const header = `<html><head>${sourceHeader}</head><body><pre><code class="json">`; const footer = `</code></pre>${sourceFooter}</body></html>`; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const win = window.open(''); win.document.write(header + source + footer); win.document.title = `${NAMES[mode]} JSON Source`; } /** * Try to guess the type of spec. * * @param spec Vega or Vega-Lite spec. */ function guessMode(spec, providedMode) { // Decide mode if (spec.$schema) { const parsed = e(spec.$schema); if (providedMode && providedMode !== parsed.library) { var _NAMES$providedMode; console.warn(`The given visualization spec is written in ${NAMES[parsed.library]}, but mode argument sets ${(_NAMES$providedMode = NAMES[providedMode]) !== null && _NAMES$providedMode !== void 0 ? _NAMES$providedMode : providedMode}.`); } const mode = parsed.library; if (!semver.satisfies(VERSION[mode], `^${parsed.version.slice(1)}`)) { console.warn(`The input spec uses ${NAMES[mode]} ${parsed.version}, but the current version of ${NAMES[mode]} is v${VERSION[mode]}.`); } return mode; } // try to guess from the provided spec if ('mark' in spec || 'encoding' in spec || 'layer' in spec || 'hconcat' in spec || 'vconcat' in spec || 'facet' in spec || 'repeat' in spec) { return 'vega-lite'; } if ('marks' in spec || 'signals' in spec || 'scales' in spec || 'axes' in spec) { return 'vega'; } return providedMode !== null && providedMode !== void 0 ? providedMode : 'vega'; } function isLoader(o) { return !!(o && 'load' in o); } function createLoader(opts) { return isLoader(opts) ? opts : vega.loader(opts); } function embedOptionsFromUsermeta(parsedSpec) { var _ref; return (_ref = parsedSpec.usermeta && parsedSpec.usermeta['embedOptions']) !== null && _ref !== void 0 ? _ref : {}; } /** * Embed a Vega visualization component in a web page. This function returns a promise. * * @param el DOM element in which to place component (DOM node or CSS selector). * @param spec String : A URL string from which to load the Vega specification. * Object : The Vega/Vega-Lite specification as a parsed JSON object. * @param opts A JavaScript object containing options for embedding. */ async function embed(el, spec, opts = {}) { var _parsedOpts$config, _usermetaOpts$config; let parsedSpec; let loader; if (vegaImport.isString(spec)) { loader = createLoader(opts.loader); parsedSpec = JSON.parse(await loader.load(spec)); } else { parsedSpec = spec; } const usermetaLoader = embedOptionsFromUsermeta(parsedSpec).loader; // either create the loader for the first time or create a new loader if the spec has new loader options if (!loader || usermetaLoader) { var _opts$loader; loader = createLoader((_opts$loader = opts.loader) !== null && _opts$loader !== void 0 ? _opts$loader : usermetaLoader); } const usermetaOpts = await loadOpts(embedOptionsFromUsermeta(parsedSpec), loader); const parsedOpts = await loadOpts(opts, loader); const mergedOpts = { ...mergeDeep(parsedOpts, usermetaOpts), config: vegaImport.mergeConfig((_parsedOpts$config = parsedOpts.config) !== null && _parsedOpts$config !== void 0 ? _parsedOpts$config : {}, (_usermetaOpts$config = usermetaOpts.config) !== null && _usermetaOpts$config !== void 0 ? _usermetaOpts$config : {}) }; return await _embed(el, parsedSpec, mergedOpts, loader); } async function loadOpts(opt, loader) { var _opt$config; const config = vegaImport.isString(opt.config) ? JSON.parse(await loader.load(opt.config)) : (_opt$config = opt.config) !== null && _opt$config !== void 0 ? _opt$config : {}; const patch = vegaImport.isString(opt.patch) ? JSON.parse(await loader.load(opt.patch)) : opt.patch; return { ...opt, ...(patch ? { patch } : {}), ...(config ? { config } : {}) }; } function getRoot(el) { const possibleRoot = el.getRootNode ? el.getRootNode() : document; if (possibleRoot instanceof ShadowRoot) { return { root: possibleRoot, rootContainer: possibleRoot }; } else { var _document$head; return { root: document, rootContainer: (_document$head = document.head) !== null && _document$head !== void 0 ? _document$head : document.body }; } } async function _embed(el, spec, opts = {}, loader) { var _opts$config, _opts$actions, _opts$renderer, _opts$logLevel, _opts$downloadFileNam, _ref2, _vega$expressionInter; const config = opts.theme ? vegaImport.mergeConfig(themes[opts.theme], (_opts$config = opts.config) !== null && _opts$config !== void 0 ? _opts$config : {}) : opts.config; const actions = vegaImport.isBoolean(opts.actions) ? opts.actions : mergeDeep({}, DEFAULT_ACTIONS, (_opts$actions = opts.actions) !== null && _opts$actions !== void 0 ? _opts$actions : {}); const i18n = { ...I18N, ...opts.i18n }; const renderer = (_opts$renderer = opts.renderer) !== null && _opts$renderer !== void 0 ? _opts$renderer : 'canvas'; const logLevel = (_opts$logLevel = opts.logLevel) !== null && _opts$logLevel !== void 0 ? _opts$logLevel : vega.Warn; const downloadFileName = (_opts$downloadFileNam = opts.downloadFileName) !== null && _opts$downloadFileNam !== void 0 ? _opts$downloadFileNam : 'visualization'; const element = typeof el === 'string' ? document.querySelector(el) : el; if (!element) { throw new Error(`${el} does not exist`); } if (opts.defaultStyle !== false) { // Add a default stylesheet to the head of the document. const ID = 'vega-embed-style'; const { root, rootContainer } = getRoot(element); if (!root.getElementById(ID)) { const style = document.createElement('style'); style.id = ID; style.innerText = opts.defaultStyle === undefined || opts.defaultStyle === true ? (embedStyle ).toString() : opts.defaultStyle; rootContainer.appendChild(style); } } const mode = guessMode(spec, opts.mode); let vgSpec = PREPROCESSOR[mode](spec, config); if (mode === 'vega-lite') { if (vgSpec.$schema) { const parsed = e(vgSpec.$schema); if (!semver.satisfies(VERSION.vega, `^${parsed.version.slice(1)}`)) { console.warn(`The compiled spec uses Vega ${parsed.version}, but current version is v${VERSION.vega}.`); } } } element.classList.add('vega-embed'); if (actions) { element.classList.add('has-actions'); } element.innerHTML = ''; // clear container let container = element; if (actions) { const chartWrapper = document.createElement('div'); chartWrapper.classList.add(CHART_WRAPPER_CLASS); element.appendChild(chartWrapper); container = chartWrapper; } const patch = opts.patch; if (patch) { if (patch instanceof Function) { vgSpec = patch(vgSpec); } else { vgSpec = applyPatch(vgSpec, patch, true, false).newDocument; } } // Set locale. Note that this is a global setting. if (opts.formatLocale) { vega.formatLocale(opts.formatLocale); } if (opts.timeFormatLocale) { vega.timeFormatLocale(opts.timeFormatLocale); } const { ast } = opts; // Do not apply the config to Vega when we have already applied it to Vega-Lite. // This call may throw an Error if parsing fails. const runtime = vega.parse(vgSpec, mode === 'vega-lite' ? {} : config, { ast }); const view = new (opts.viewClass || vega.View)(runtime, { loader, logLevel, renderer, ...(ast ? { expr: (_ref2 = (_vega$expressionInter = vega.expressionInterpreter) !== null && _vega$expressionInter !== void 0 ? _vega$expressionInter : opts.expr) !== null && _ref2 !== void 0 ? _ref2 : expression } : {}) }); view.addSignalListener('autosize', (_, autosize) => { const { type } = autosize; if (type == 'fit-x') { container.classList.add('fit-x'); container.classList.remove('fit-y'); } else if (type == 'fit-y') { container.classList.remove('fit-x'); container.classList.add('fit-y'); } else if (type == 'fit') { container.classList.add('fit-x', 'fit-y'); } else { container.classList.remove('fit-x', 'fit-y'); } }); if (opts.tooltip !== false) { let handler; if (isTooltipHandler(opts.tooltip)) { handler = opts.tooltip; } else { // user provided boolean true or tooltip options handler = new Handler(opts.tooltip === true ? {} : opts.tooltip).call; } view.tooltip(handler); } let { hover } = opts; if (hover === undefined) { hover = mode === 'vega'; } if (hover) { const { hoverSet, updateSet } = typeof hover === 'boolean' ? {} : hover; view.hover(hoverSet, updateSet); } if (opts) { if (opts.width != null) { view.width(opts.width); } if (opts.height != null) { view.height(opts.height); } if (opts.padding != null) { view.padding(opts.padding); } } await view.initialize(container, opts.bind).runAsync(); let documentClickHandler; if (actions !== false) { let wrapper = element; if (opts.defaultStyle !== false) { const details = document.createElement('details'); details.title = i18n.CLICK_TO_VIEW_ACTIONS; element.append(details); wrapper = details; const summary = document.createElement('summary'); summary.innerHTML = SVG_CIRCLES; details.append(summary); documentClickHandler = ev => { if (!details.contains(ev.target)) { details.removeAttribute('open'); } }; document.addEventListener('click', documentClickHandler); } const ctrl = document.createElement('div'); wrapper.append(ctrl); ctrl.classList.add('vega-actions'); // add 'Export' action if (actions === true || actions.export !== false) { for (const ext of ['svg', 'png']) { if (actions === true || actions.export === true || actions.export[ext]) { const i18nExportAction = i18n[`${ext.toUpperCase()}_ACTION`]; const exportLink = document.createElement('a'); exportLink.text = i18nExportAction; exportLink.href = '#'; exportLink.target = '_blank'; exportLink.download = `${downloadFileName}.${ext}`; // add link on mousedown so that it's correct when the click happens exportLink.addEventListener('mousedown', async function (e) { e.preventDefault(); const url = await view.toImageURL(ext, opts.scaleFactor); this.href = url; }); ctrl.append(exportLink); } } } // add 'View Source' action if (actions === true || actions.source !== false) { const viewSourceLink = document.createElement('a'); viewSourceLink.text = i18n.SOURCE_ACTION; viewSourceLink.href = '#'; viewSourceLink.addEventListener('click', function (e) { var _opts$sourceHeader, _opts$sourceFooter; viewSource(jsonStringifyPrettyCompact(spec), (_opts$sourceHeader = opts.sourceHeader) !== null && _opts$sourceHeader !== void 0 ? _opts$sourceHeader : '', (_opts$sourceFooter = opts.sourceFooter) !== null && _opts$sourceFooter !== void 0 ? _opts$sourceFooter : '', mode); e.preventDefault(); }); ctrl.append(viewSourceLink); } // add 'View Compiled' action if (mode === 'vega-lite' && (actions === true || actions.compiled !== false)) { const compileLink = document.createElement('a'); compileLink.text = i18n.COMPILED_ACTION; compileLink.href = '#'; compileLink.addEventListener('click', function (e) { var _opts$sourceHeader2, _opts$sourceFooter2; viewSource(jsonStringifyPrettyCompact(vgSpec), (_opts$sourceHeader2 = opts.sourceHeader) !== null && _opts$sourceHeader2 !== void 0 ? _opts$sourceHeader2 : '', (_opts$sourceFooter2 = opts.sourceFooter) !== null && _opts$sourceFooter2 !== void 0 ? _opts$sourceFooter2 : '', 'vega'); e.preventDefault(); }); ctrl.append(compileLink); } // add 'Open in Vega Editor' action if (actions === true || actions.editor !== false) { var _opts$editorUrl; const editorUrl = (_opts$editorUrl = opts.editorUrl) !== null && _opts$editorUrl !== void 0 ? _opts$editorUrl : 'https://vega.github.io/editor/'; const editorLink = document.createElement('a'); editorLink.text = i18n.EDITOR_ACTION; editorLink.href = '#'; editorLink.addEventListener('click', function (e) { post(window, editorUrl, { config: config, mode, renderer, spec: jsonStringifyPrettyCompact(spec) }); e.preventDefault(); }); ctrl.append(editorLink); } } function finalize() { if (documentClickHandler) { document.removeEventListener('click', documentClickHandler); } view.finalize(); } return { view, spec, vgSpec, finalize }; } /** * Create a promise to an HTML Div element with an embedded Vega-Lite or Vega visualization. * The element has a value property with the view. By default all actions except for the editor action are disabled. * * The main use case is in [Observable](https://observablehq.com/). */ async function container (spec, opt = {}) { var _opt$actions; const wrapper = document.createElement('div'); wrapper.classList.add('vega-embed-wrapper'); const div = document.createElement('div'); wrapper.appendChild(div); const actions = opt.actions === true || opt.actions === false ? opt.actions : { export: true, source: false, compiled: true, editor: true, ...((_opt$actions = opt.actions) !== null && _opt$actions !== void 0 ? _opt$actions : {}) }; const result = await embed(div, spec, { actions, ...(opt !== null && opt !== void 0 ? opt : {}) }); wrapper.value = result.view; return wrapper; } /** * Returns true if the object is an HTML element. */ function isElement(obj) { return obj instanceof HTMLElement; } const wrapper = (...args) => { if (args.length > 1 && (vegaImport.isString(args[0]) && !isURL(args[0]) || isElement(args[0]) || args.length === 3)) { return embed(args[0], args[1], args[2]); } return container(args[0], args[1]); }; wrapper.vegaLite = vegaLite; wrapper.vl = vegaLite; // backwards compatibility wrapper.container = container; wrapper.embed = embed; wrapper.vega = vega; wrapper.default = embed; wrapper.version = version; return wrapper; })); //# sourceMappingURL=vega-embed.js.map
cdnjs/cdnjs
ajax/libs/vega-embed/6.20.0-next.0/vega-embed.js
JavaScript
mit
182,412
import settings from './../settings' import {findDistance, limitPositions, chooseOne, randomInt, getAvgPostion} from './general' module.exports = { applyLimbForces: (Eves) => { for(var i = 0; i < Eves.length; i++) { var eve = Eves[i]; for(var j = 0; j < eve.limbs.length; j++) { var limb = eve.limbs[j]; var b0 = eve.bodyParts[limb.connections[0]]; var b1 = eve.bodyParts[limb.connections[1]]; var displacement, force; limb.currentLength = findDistance(b0.pos, b1.pos) if(limb.growing) { displacement = limb.maxLength - limb.currentLength; force = displacement * 0.1 - 1.5; if(limb.currentLength >= limb.maxLength) { limb.growing = false; } } else { displacement = limb.initialLength - limb.currentLength; force = displacement * 0.1 + 1.5; if(limb.currentLength <= limb.initialLength) { limb.growing = true; } } var xPosDiff = b1.pos.x - b0.pos.x; var yPosDiff = b1.pos.y - b0.pos.y; if(xPosDiff === 0) { var theta = Math.PI; } else { var theta = Math.atan(yPosDiff / xPosDiff); } if (xPosDiff >= 0) { force *= -1; } var movementFactor = 1; if(limb.growing) { movementFactor = 0.5; } var dVx0 = force / b0.mass * Math.cos(theta); var dVy0 = force / b0.mass * Math.sin(theta); var dVx1 = -force / b1.mass * Math.cos(theta) * movementFactor; var dVy1 = -force / b1.mass * Math.sin(theta) * movementFactor; b0.vel.x = Math.min( 20, Math.max( b0.vel.x + dVx0, -20 )); b0.vel.y = Math.min( 20, Math.max( b0.vel.y + dVy0, -20 )); b1.vel.x = Math.min( 20, Math.max( b1.vel.x + dVx1, -20 )); b1.vel.y = Math.min( 20, Math.max( b1.vel.y + dVy1, -20 )); } } }, updateBodyPartPositions: (Eves) => { for(var i = 0; i < Eves.length; i++) { var eve = Eves[i]; for(var j = 0; j < eve.bodyParts.length; j++) { var bodyPart = eve.bodyParts[j]; bodyPart.pos.x += bodyPart.vel.x; //check if offscreen if(bodyPart.pos.x <= bodyPart.mass || bodyPart.pos.x >= settings.width - bodyPart.mass) { bodyPart.pos.x = limitPositions(bodyPart.pos.x, 1, bodyPart.mass)[0]; bodyPart.vel.x = -1 * bodyPart.vel.x; } bodyPart.pos.y += bodyPart.vel.y; if(bodyPart.pos.y <= bodyPart.mass || bodyPart.pos.y >= settings.height - bodyPart.mass) { bodyPart.pos.y = limitPositions(1, bodyPart.pos.y, bodyPart.mass)[1]; bodyPart.vel.y = -1 * bodyPart.vel.y; } //check if offscreen //NEEEDS TO GO ON CLIENT ONLY?? // d3.select('#' + eve.id + 'b' + j) // .attr('cx', bodyPart.pos.x).attr('cy', bodyPart.pos.y); // } for(var k = 0; k < eve.limbs.length; k++) { var b0 = eve.bodyParts[eve.limbs[k].connections[0]]; var b1 = eve.bodyParts[eve.limbs[k].connections[1]]; //NEEDS TO GO ON CLIENT ONLY?? // d3.select('#' + eve.id + 'l' + k) // .attr('x1', b0.pos.x).attr('y1', b0.pos.y) // .attr('x2', b1.pos.x).attr('y2', b1.pos.y); // } } } }
iandeboisblanc/evolution
server/helpers/movement.js
JavaScript
cc0-1.0
3,327
import { editMenu, viewMenu, windowMenu, helpMenu } from './common-menus' import { addDarwinMenuItems } from './darwin-menus' import { app, Menu } from 'electron' const initialMenu = [ editMenu, viewMenu, windowMenu, helpMenu ] export const setupMenus = () => { const menuItems = (process.platform === 'darwin') ? addDarwinMenuItems(initialMenu) : initialMenu const menu = Menu.buildFromTemplate(menuItems) Menu.setApplicationMenu(menu) }
lazlojuly/modular-electron-app
menus/index.js
JavaScript
cc0-1.0
456
# frozen_string_literal: true class Collection include ActiveModel::Serializers::JSON include ActiveModel::Validations include Virtus.model attribute :id, String attribute :token, String attribute :created_at, Time, default: proc { Time.now.utc } attribute :updated_at, Time, default: proc { Time.now.utc } validates :token, presence: true def document_total document_repository.count end def last_document_sent document_repository.search("*:*", {size:1, sort: "updated_at:desc"}). results.first.updated_at.utc.to_s rescue nil end private def document_repository @document_repository = DocumentRepository.new( index_name: DocumentRepository.index_namespace(id) ) end end
GSA/i14y
app/models/collection.rb
Ruby
cc0-1.0
742
var debug = process.env.NODE_ENV !== "production" var webpack = require('webpack') module.exports = { context: __dirname, devtool: debug ? "inline-sourcemap" : null, entry: "./js/app.jsx", module: { loaders: [ { test: /\.jsx?$/, exclude:/(node_modules|bower_components)/, loader: 'babel-loader', query:{ presets: ['react', 'es2015', 'stage-0'], plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'] } } ] }, output: { path: __dirname + "/js", filename: "bundle.js" }, plugins: debug ? [] : [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), ], };
Czhang0727/electron-demo
views/webpack.config.js
JavaScript
cc0-1.0
913
#!/usr/bin/env python3 from SPARQLWrapper import SPARQLWrapper, JSON import requests import re import os import os.path import time import sys FINTO_ENDPOINT='http://api.dev.finto.fi/sparql' FINNA_API_SEARCH='https://api.finna.fi/v1/search' lang = sys.argv[1] # map ISO 639-1 language codes into the ISO 639-2 codes that Finna uses LANGMAP = { 'fi': 'fin', 'sv': 'swe', 'en': 'eng' } def row_to_concept(row): concept = {'uri': row['c']['value'], 'pref': row['pref']['value'], 'ysapref': row['ysapref']['value'], 'allarspref': row['allarspref']['value']} if 'alts' in row: concept['alts'] = row['alts']['value'] return concept def get_concepts(lang): sparql = SPARQLWrapper(FINTO_ENDPOINT) sparql.setQuery(""" PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX ysometa: <http://www.yso.fi/onto/yso-meta/> SELECT ?c ?pref (GROUP_CONCAT(?alt) AS ?alts) ?ysapref ?allarspref WHERE { GRAPH <http://www.yso.fi/onto/yso/> { ?c a skos:Concept . ?c skos:prefLabel ?pref . FILTER(LANG(?pref)='%s') OPTIONAL { ?c skos:altLabel ?alt . FILTER(LANG(?alt)='%s') } FILTER NOT EXISTS { ?c owl:deprecated true } FILTER NOT EXISTS { ?c a ysometa:Hierarchy } } GRAPH <http://www.yso.fi/onto/ysa/> { ?ysac skos:closeMatch|skos:exactMatch ?c . ?ysac skos:prefLabel ?ysapref . } GRAPH <http://www.yso.fi/onto/allars/> { ?allarsc skos:closeMatch|skos:exactMatch ?c . ?allarsc skos:prefLabel ?allarspref . } } GROUP BY ?c ?pref ?ysapref ?allarspref #LIMIT 500 """ % (lang, lang)) sparql.setReturnFormat(JSON) results = sparql.query().convert() return [row_to_concept(row) for row in results['results']['bindings']] concepts = get_concepts(lang) def search_finna(params): r = requests.get(FINNA_API_SEARCH, params=params, headers={'User-agent': 'annif 0.1'}) return r.json() def records_to_texts(records): texts = [] for rec in records: if 'title' in rec: texts.append(rec['title']) if 'summary' in rec: for summary in rec['summary']: texts.append(summary) return texts def generate_text(concept, lang): # start with pref- and altlabels labels = [concept['pref']] if lang == 'fi': # we can use the YSA label too labels.append(concept['ysapref']) if lang == 'sv': # we can use the Allars label too labels.append(concept['allarspref']) if 'alts' in concept: labels.append(concept['alts']) labels = ' '.join(labels) # look for more text in Finna API texts = [] fields = ['title','summary'] finnaterms = (concept['ysapref'], concept['allarspref']) finnalang = LANGMAP[lang] # Search type 1: exact matches using topic facet params = {'lookfor': 'topic_facet:"%s" OR topic_facet:"%s"' % finnaterms, 'filter[]': 'language:%s' % finnalang, 'lng':lang, 'limit':100, 'field[]':fields} response = search_finna(params) if 'records' in response: texts += records_to_texts(response['records']) # Search type 2: exact matches using Subject search params['lookfor'] = '"%s" OR "%s"' % finnaterms params['type'] = 'Subject' response = search_finna(params) if 'records' in response: texts += records_to_texts(response['records']) # Search type 3: fuzzy matches using Subject search params['lookfor'] = '(%s) OR (%s)' % finnaterms response = search_finna(params) if 'records' in response: texts += records_to_texts(response['records']) return "\n".join([labels] + list(set(texts))) for concept in concepts: localname = concept['uri'].split('/')[-1] outfile = 'corpus/%s-%s.raw' % (localname, lang) if os.path.exists(outfile): continue text = None tries = 0 while tries < 10: try: text = generate_text(concept, lang) break except: # failure, try again until tries exhausted tries += 1 print("Error generating text for concept %s, trying again (attempt %d)" % (concept['uri'], tries)) time.sleep(tries) # wait progressively longer between attempts if text is None: print("Failed looking up concept %s, exiting" % concept['uri']) sys.exit(1) print(localname, lang, concept['pref'], concept['ysapref'], concept['allarspref'], len(text.split())) f = open(outfile, 'w') print (concept['uri'], concept['pref'], file=f) print (text, file=f) f.close()
osma/annif
create_corpus_yso_finna.py
Python
cc0-1.0
4,644
import { navigate } from 'gatsby' export default function redirectLegacyRoutes(): void { const { hash } = window.location if (hash && hash.startsWith('#/examples/')) { const category = hash.replace('#/examples/', '') navigate(`category/${category}`, { replace: true, }) } else if (hash === '#/endpoint') { navigate('endpoint', { replace: true, }) } }
badges/shields
frontend/lib/redirect-legacy-routes.ts
TypeScript
cc0-1.0
392