code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
//
// ZLPhotoPickerAssetsViewController.h
// ZLAssetsPickerDemo
//
// Created by 张磊 on 14-11-12.
// Copyright (c) 2014年 com.zixue101.www. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ZLPhotoPickerCommon.h"
#import "ZLPhotoPickerGroupViewController.h"
@class ZLPhotoPickerGroup;
@interface ZLPhotoPickerAssetsViewController : UIViewController
@property (weak , nonatomic) ZLPhotoPickerGroupViewController *groupVc;
@property (nonatomic , assign) PickerViewShowStatus status;
@property (nonatomic , strong) ZLPhotoPickerGroup *assetsGroup;
@property (nonatomic , assign) NSInteger maxCount;
// 需要记录选中的值的数据
@property (strong,nonatomic) NSArray *selectPickerAssets;
// 置顶展示图片
@property (assign,nonatomic) BOOL topShowPhotoPicker;
// 是否显示Camera
@property (assign,nonatomic) BOOL isShowCamera;
@end
|
BaoSeed/TianFuYun
|
ios/TianJiCloud/Vender/View/ZLPhotoLib/Classes/ZLPhotoPicker/ViewControllers/ZLPhotoPickerAssetsViewController.h
|
C
|
mit
| 861
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>push_front</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../../index.html" title="Chapter 1. Range 2.0">
<link rel="up" href="../new.html" title="New algorithms">
<link rel="prev" href="push_back.html" title="push_back">
<link rel="next" href="remove_erase.html" title="remove_erase">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="push_back.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../new.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="remove_erase.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="range.reference.algorithms.new.push_front"></a><a class="link" href="push_front.html" title="push_front">push_front</a>
</h5></div></div></div>
<h6>
<a name="range.reference.algorithms.new.push_front.h0"></a>
<span><a name="range.reference.algorithms.new.push_front.prototype"></a></span><a class="link" href="push_front.html#range.reference.algorithms.new.push_front.prototype">Prototype</a>
</h6>
<p>
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span>
<span class="keyword">class</span> <span class="identifier">Container</span><span class="special">,</span>
<span class="keyword">class</span> <span class="identifier">SinglePassRange</span>
<span class="special">></span>
<span class="identifier">Container</span><span class="special">&</span> <span class="identifier">push_front</span><span class="special">(</span><span class="identifier">Container</span><span class="special">&</span> <span class="identifier">target</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">SinglePassRange</span><span class="special">&</span> <span class="identifier">from</span><span class="special">);</span>
</pre>
<p>
</p>
<h6>
<a name="range.reference.algorithms.new.push_front.h1"></a>
<span><a name="range.reference.algorithms.new.push_front.description"></a></span><a class="link" href="push_front.html#range.reference.algorithms.new.push_front.description">Description</a>
</h6>
<p>
<code class="computeroutput"><span class="identifier">push_front</span></code> all of the
elements in the range <code class="computeroutput"><span class="identifier">from</span></code>
to the front of the container <code class="computeroutput"><span class="identifier">target</span></code>.
</p>
<h6>
<a name="range.reference.algorithms.new.push_front.h2"></a>
<span><a name="range.reference.algorithms.new.push_front.definition"></a></span><a class="link" href="push_front.html#range.reference.algorithms.new.push_front.definition">Definition</a>
</h6>
<p>
Defined in the header file <code class="computeroutput"><span class="identifier">boost</span><span class="special">/</span><span class="identifier">range</span><span class="special">/</span><span class="identifier">algorithm_ext</span><span class="special">/</span><span class="identifier">push_front</span><span class="special">.</span><span class="identifier">hpp</span></code>
</p>
<h6>
<a name="range.reference.algorithms.new.push_front.h3"></a>
<span><a name="range.reference.algorithms.new.push_front.requirements"></a></span><a class="link" href="push_front.html#range.reference.algorithms.new.push_front.requirements">Requirements</a>
</h6>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<code class="computeroutput"><span class="identifier">SinglePassRange</span></code> is
a model of the <a class="link" href="../../../concepts/single_pass_range.html" title="Single Pass Range">Single
Pass Range</a> Concept.
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">Container</span></code> supports
insert at <code class="computeroutput"><span class="identifier">begin</span><span class="special">()</span></code>.
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">SinglePassRange</span></code>'s
value type is convertible to <code class="computeroutput"><span class="identifier">Container</span></code>'s
value type.
</li>
</ol></div>
<h6>
<a name="range.reference.algorithms.new.push_front.h4"></a>
<span><a name="range.reference.algorithms.new.push_front.complexity"></a></span><a class="link" href="push_front.html#range.reference.algorithms.new.push_front.complexity">Complexity</a>
</h6>
<p>
Linear. <code class="computeroutput"><span class="identifier">distance</span><span class="special">(</span><span class="identifier">from</span><span class="special">)</span></code>
assignments are performed.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2010 Thorsten Ottosen,
Neil Groves<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="push_back.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../new.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="remove_erase.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
yinchunlong/abelkhan-1
|
ext/c++/thirdpart/c++/boost/libs/range/doc/html/range/reference/algorithms/new/push_front.html
|
HTML
|
mit
| 7,188
|
require 'mspec/runner/filters/match'
# ActionFilter is a base class for actions that are triggered by
# specs that match the filter. The filter may be specified by
# strings that match spec descriptions or by tags for strings
# that match spec descriptions.
#
# Unlike TagFilter and RegexpFilter, ActionFilter instances do
# not affect the specs that are run. The filter is only used to
# trigger the action.
class ActionFilter
def initialize(tags = nil, descs = nil)
@tags = Array(tags)
descs = Array(descs)
@sfilter = descs.empty? ? nil : MatchFilter.new(nil, *descs)
@tfilter = nil
end
def ===(string)
@sfilter === string or @tfilter === string
end
def load
return if @tags.empty?
desc = MSpec.read_tags(@tags).map { |t| t.description }
return if desc.empty?
@tfilter = MatchFilter.new(nil, *desc)
end
def register
MSpec.register :load, self
end
def unregister
MSpec.unregister :load, self
end
end
|
pmq20/ruby-compiler
|
ruby/spec/mspec/lib/mspec/runner/actions/filter.rb
|
Ruby
|
mit
| 973
|
package com.udacity.gradle.multidex;
public class Methods19 {
public void method_0() {
}
public void method_1() {
}
public void method_2() {
}
public void method_3() {
}
public void method_4() {
}
public void method_5() {
}
public void method_6() {
}
public void method_7() {
}
public void method_8() {
}
public void method_9() {
}
public void method_10() {
}
public void method_11() {
}
public void method_12() {
}
public void method_13() {
}
public void method_14() {
}
public void method_15() {
}
public void method_16() {
}
public void method_17() {
}
public void method_18() {
}
public void method_19() {
}
public void method_20() {
}
public void method_21() {
}
public void method_22() {
}
public void method_23() {
}
public void method_24() {
}
public void method_25() {
}
public void method_26() {
}
public void method_27() {
}
public void method_28() {
}
public void method_29() {
}
public void method_30() {
}
public void method_31() {
}
public void method_32() {
}
public void method_33() {
}
public void method_34() {
}
public void method_35() {
}
public void method_36() {
}
public void method_37() {
}
public void method_38() {
}
public void method_39() {
}
public void method_40() {
}
public void method_41() {
}
public void method_42() {
}
public void method_43() {
}
public void method_44() {
}
public void method_45() {
}
public void method_46() {
}
public void method_47() {
}
public void method_48() {
}
public void method_49() {
}
public void method_50() {
}
public void method_51() {
}
public void method_52() {
}
public void method_53() {
}
public void method_54() {
}
public void method_55() {
}
public void method_56() {
}
public void method_57() {
}
public void method_58() {
}
public void method_59() {
}
public void method_60() {
}
public void method_61() {
}
public void method_62() {
}
public void method_63() {
}
public void method_64() {
}
public void method_65() {
}
public void method_66() {
}
public void method_67() {
}
public void method_68() {
}
public void method_69() {
}
public void method_70() {
}
public void method_71() {
}
public void method_72() {
}
public void method_73() {
}
public void method_74() {
}
public void method_75() {
}
public void method_76() {
}
public void method_77() {
}
public void method_78() {
}
public void method_79() {
}
public void method_80() {
}
public void method_81() {
}
public void method_82() {
}
public void method_83() {
}
public void method_84() {
}
public void method_85() {
}
public void method_86() {
}
public void method_87() {
}
public void method_88() {
}
public void method_89() {
}
public void method_90() {
}
public void method_91() {
}
public void method_92() {
}
public void method_93() {
}
public void method_94() {
}
public void method_95() {
}
public void method_96() {
}
public void method_97() {
}
public void method_98() {
}
public void method_99() {
}
public void method_100() {
}
public void method_101() {
}
public void method_102() {
}
public void method_103() {
}
public void method_104() {
}
public void method_105() {
}
public void method_106() {
}
public void method_107() {
}
public void method_108() {
}
public void method_109() {
}
public void method_110() {
}
public void method_111() {
}
public void method_112() {
}
public void method_113() {
}
public void method_114() {
}
public void method_115() {
}
public void method_116() {
}
public void method_117() {
}
public void method_118() {
}
public void method_119() {
}
public void method_120() {
}
public void method_121() {
}
public void method_122() {
}
public void method_123() {
}
public void method_124() {
}
public void method_125() {
}
public void method_126() {
}
public void method_127() {
}
public void method_128() {
}
public void method_129() {
}
public void method_130() {
}
public void method_131() {
}
public void method_132() {
}
public void method_133() {
}
public void method_134() {
}
public void method_135() {
}
public void method_136() {
}
public void method_137() {
}
public void method_138() {
}
public void method_139() {
}
public void method_140() {
}
public void method_141() {
}
public void method_142() {
}
public void method_143() {
}
public void method_144() {
}
public void method_145() {
}
public void method_146() {
}
public void method_147() {
}
public void method_148() {
}
public void method_149() {
}
public void method_150() {
}
public void method_151() {
}
public void method_152() {
}
public void method_153() {
}
public void method_154() {
}
public void method_155() {
}
public void method_156() {
}
public void method_157() {
}
public void method_158() {
}
public void method_159() {
}
public void method_160() {
}
public void method_161() {
}
public void method_162() {
}
public void method_163() {
}
public void method_164() {
}
public void method_165() {
}
public void method_166() {
}
public void method_167() {
}
public void method_168() {
}
public void method_169() {
}
public void method_170() {
}
public void method_171() {
}
public void method_172() {
}
public void method_173() {
}
public void method_174() {
}
public void method_175() {
}
public void method_176() {
}
public void method_177() {
}
public void method_178() {
}
public void method_179() {
}
public void method_180() {
}
public void method_181() {
}
public void method_182() {
}
public void method_183() {
}
public void method_184() {
}
public void method_185() {
}
public void method_186() {
}
public void method_187() {
}
public void method_188() {
}
public void method_189() {
}
public void method_190() {
}
public void method_191() {
}
public void method_192() {
}
public void method_193() {
}
public void method_194() {
}
public void method_195() {
}
public void method_196() {
}
public void method_197() {
}
public void method_198() {
}
public void method_199() {
}
public void method_200() {
}
public void method_201() {
}
public void method_202() {
}
public void method_203() {
}
public void method_204() {
}
public void method_205() {
}
public void method_206() {
}
public void method_207() {
}
public void method_208() {
}
public void method_209() {
}
public void method_210() {
}
public void method_211() {
}
public void method_212() {
}
public void method_213() {
}
public void method_214() {
}
public void method_215() {
}
public void method_216() {
}
public void method_217() {
}
public void method_218() {
}
public void method_219() {
}
public void method_220() {
}
public void method_221() {
}
public void method_222() {
}
public void method_223() {
}
public void method_224() {
}
public void method_225() {
}
public void method_226() {
}
public void method_227() {
}
public void method_228() {
}
public void method_229() {
}
public void method_230() {
}
public void method_231() {
}
public void method_232() {
}
public void method_233() {
}
public void method_234() {
}
public void method_235() {
}
public void method_236() {
}
public void method_237() {
}
public void method_238() {
}
public void method_239() {
}
public void method_240() {
}
public void method_241() {
}
public void method_242() {
}
public void method_243() {
}
public void method_244() {
}
public void method_245() {
}
public void method_246() {
}
public void method_247() {
}
public void method_248() {
}
public void method_249() {
}
public void method_250() {
}
public void method_251() {
}
public void method_252() {
}
public void method_253() {
}
public void method_254() {
}
public void method_255() {
}
public void method_256() {
}
public void method_257() {
}
public void method_258() {
}
public void method_259() {
}
public void method_260() {
}
public void method_261() {
}
public void method_262() {
}
public void method_263() {
}
public void method_264() {
}
public void method_265() {
}
public void method_266() {
}
public void method_267() {
}
public void method_268() {
}
public void method_269() {
}
public void method_270() {
}
public void method_271() {
}
public void method_272() {
}
public void method_273() {
}
public void method_274() {
}
public void method_275() {
}
public void method_276() {
}
public void method_277() {
}
public void method_278() {
}
public void method_279() {
}
public void method_280() {
}
public void method_281() {
}
public void method_282() {
}
public void method_283() {
}
public void method_284() {
}
public void method_285() {
}
public void method_286() {
}
public void method_287() {
}
public void method_288() {
}
public void method_289() {
}
public void method_290() {
}
public void method_291() {
}
public void method_292() {
}
public void method_293() {
}
public void method_294() {
}
public void method_295() {
}
public void method_296() {
}
public void method_297() {
}
public void method_298() {
}
public void method_299() {
}
public void method_300() {
}
public void method_301() {
}
public void method_302() {
}
public void method_303() {
}
public void method_304() {
}
public void method_305() {
}
public void method_306() {
}
public void method_307() {
}
public void method_308() {
}
public void method_309() {
}
public void method_310() {
}
public void method_311() {
}
public void method_312() {
}
public void method_313() {
}
public void method_314() {
}
public void method_315() {
}
public void method_316() {
}
public void method_317() {
}
public void method_318() {
}
public void method_319() {
}
public void method_320() {
}
public void method_321() {
}
public void method_322() {
}
public void method_323() {
}
public void method_324() {
}
public void method_325() {
}
public void method_326() {
}
public void method_327() {
}
public void method_328() {
}
public void method_329() {
}
public void method_330() {
}
public void method_331() {
}
public void method_332() {
}
public void method_333() {
}
public void method_334() {
}
public void method_335() {
}
public void method_336() {
}
public void method_337() {
}
public void method_338() {
}
public void method_339() {
}
public void method_340() {
}
public void method_341() {
}
public void method_342() {
}
public void method_343() {
}
public void method_344() {
}
public void method_345() {
}
public void method_346() {
}
public void method_347() {
}
public void method_348() {
}
public void method_349() {
}
public void method_350() {
}
public void method_351() {
}
public void method_352() {
}
public void method_353() {
}
public void method_354() {
}
public void method_355() {
}
public void method_356() {
}
public void method_357() {
}
public void method_358() {
}
public void method_359() {
}
public void method_360() {
}
public void method_361() {
}
public void method_362() {
}
public void method_363() {
}
public void method_364() {
}
public void method_365() {
}
public void method_366() {
}
public void method_367() {
}
public void method_368() {
}
public void method_369() {
}
public void method_370() {
}
public void method_371() {
}
public void method_372() {
}
public void method_373() {
}
public void method_374() {
}
public void method_375() {
}
public void method_376() {
}
public void method_377() {
}
public void method_378() {
}
public void method_379() {
}
public void method_380() {
}
public void method_381() {
}
public void method_382() {
}
public void method_383() {
}
public void method_384() {
}
public void method_385() {
}
public void method_386() {
}
public void method_387() {
}
public void method_388() {
}
public void method_389() {
}
public void method_390() {
}
public void method_391() {
}
public void method_392() {
}
public void method_393() {
}
public void method_394() {
}
public void method_395() {
}
public void method_396() {
}
public void method_397() {
}
public void method_398() {
}
public void method_399() {
}
public void method_400() {
}
public void method_401() {
}
public void method_402() {
}
public void method_403() {
}
public void method_404() {
}
public void method_405() {
}
public void method_406() {
}
public void method_407() {
}
public void method_408() {
}
public void method_409() {
}
public void method_410() {
}
public void method_411() {
}
public void method_412() {
}
public void method_413() {
}
public void method_414() {
}
public void method_415() {
}
public void method_416() {
}
public void method_417() {
}
public void method_418() {
}
public void method_419() {
}
public void method_420() {
}
public void method_421() {
}
public void method_422() {
}
public void method_423() {
}
public void method_424() {
}
public void method_425() {
}
public void method_426() {
}
public void method_427() {
}
public void method_428() {
}
public void method_429() {
}
public void method_430() {
}
public void method_431() {
}
public void method_432() {
}
public void method_433() {
}
public void method_434() {
}
public void method_435() {
}
public void method_436() {
}
public void method_437() {
}
public void method_438() {
}
public void method_439() {
}
public void method_440() {
}
public void method_441() {
}
public void method_442() {
}
public void method_443() {
}
public void method_444() {
}
public void method_445() {
}
public void method_446() {
}
public void method_447() {
}
public void method_448() {
}
public void method_449() {
}
public void method_450() {
}
public void method_451() {
}
public void method_452() {
}
public void method_453() {
}
public void method_454() {
}
public void method_455() {
}
public void method_456() {
}
public void method_457() {
}
public void method_458() {
}
public void method_459() {
}
public void method_460() {
}
public void method_461() {
}
public void method_462() {
}
public void method_463() {
}
public void method_464() {
}
public void method_465() {
}
public void method_466() {
}
public void method_467() {
}
public void method_468() {
}
public void method_469() {
}
public void method_470() {
}
public void method_471() {
}
public void method_472() {
}
public void method_473() {
}
public void method_474() {
}
public void method_475() {
}
public void method_476() {
}
public void method_477() {
}
public void method_478() {
}
public void method_479() {
}
public void method_480() {
}
public void method_481() {
}
public void method_482() {
}
public void method_483() {
}
public void method_484() {
}
public void method_485() {
}
public void method_486() {
}
public void method_487() {
}
public void method_488() {
}
public void method_489() {
}
public void method_490() {
}
public void method_491() {
}
public void method_492() {
}
public void method_493() {
}
public void method_494() {
}
public void method_495() {
}
public void method_496() {
}
public void method_497() {
}
public void method_498() {
}
public void method_499() {
}
public void method_500() {
}
public void method_501() {
}
public void method_502() {
}
public void method_503() {
}
public void method_504() {
}
public void method_505() {
}
public void method_506() {
}
public void method_507() {
}
public void method_508() {
}
public void method_509() {
}
public void method_510() {
}
public void method_511() {
}
public void method_512() {
}
public void method_513() {
}
public void method_514() {
}
public void method_515() {
}
public void method_516() {
}
public void method_517() {
}
public void method_518() {
}
public void method_519() {
}
public void method_520() {
}
public void method_521() {
}
public void method_522() {
}
public void method_523() {
}
public void method_524() {
}
public void method_525() {
}
public void method_526() {
}
public void method_527() {
}
public void method_528() {
}
public void method_529() {
}
public void method_530() {
}
public void method_531() {
}
public void method_532() {
}
public void method_533() {
}
public void method_534() {
}
public void method_535() {
}
public void method_536() {
}
public void method_537() {
}
public void method_538() {
}
public void method_539() {
}
public void method_540() {
}
public void method_541() {
}
public void method_542() {
}
public void method_543() {
}
public void method_544() {
}
public void method_545() {
}
public void method_546() {
}
public void method_547() {
}
public void method_548() {
}
public void method_549() {
}
public void method_550() {
}
public void method_551() {
}
public void method_552() {
}
public void method_553() {
}
public void method_554() {
}
public void method_555() {
}
public void method_556() {
}
public void method_557() {
}
public void method_558() {
}
public void method_559() {
}
public void method_560() {
}
public void method_561() {
}
public void method_562() {
}
public void method_563() {
}
public void method_564() {
}
public void method_565() {
}
public void method_566() {
}
public void method_567() {
}
public void method_568() {
}
public void method_569() {
}
public void method_570() {
}
public void method_571() {
}
public void method_572() {
}
public void method_573() {
}
public void method_574() {
}
public void method_575() {
}
public void method_576() {
}
public void method_577() {
}
public void method_578() {
}
public void method_579() {
}
public void method_580() {
}
public void method_581() {
}
public void method_582() {
}
public void method_583() {
}
public void method_584() {
}
public void method_585() {
}
public void method_586() {
}
public void method_587() {
}
public void method_588() {
}
public void method_589() {
}
public void method_590() {
}
public void method_591() {
}
public void method_592() {
}
public void method_593() {
}
public void method_594() {
}
public void method_595() {
}
public void method_596() {
}
public void method_597() {
}
public void method_598() {
}
public void method_599() {
}
public void method_600() {
}
public void method_601() {
}
public void method_602() {
}
public void method_603() {
}
public void method_604() {
}
public void method_605() {
}
public void method_606() {
}
public void method_607() {
}
public void method_608() {
}
public void method_609() {
}
public void method_610() {
}
public void method_611() {
}
public void method_612() {
}
public void method_613() {
}
public void method_614() {
}
public void method_615() {
}
public void method_616() {
}
public void method_617() {
}
public void method_618() {
}
public void method_619() {
}
public void method_620() {
}
public void method_621() {
}
public void method_622() {
}
public void method_623() {
}
public void method_624() {
}
public void method_625() {
}
public void method_626() {
}
public void method_627() {
}
public void method_628() {
}
public void method_629() {
}
public void method_630() {
}
public void method_631() {
}
public void method_632() {
}
public void method_633() {
}
public void method_634() {
}
public void method_635() {
}
public void method_636() {
}
public void method_637() {
}
public void method_638() {
}
public void method_639() {
}
public void method_640() {
}
public void method_641() {
}
public void method_642() {
}
public void method_643() {
}
public void method_644() {
}
public void method_645() {
}
public void method_646() {
}
public void method_647() {
}
public void method_648() {
}
public void method_649() {
}
public void method_650() {
}
public void method_651() {
}
public void method_652() {
}
public void method_653() {
}
public void method_654() {
}
public void method_655() {
}
public void method_656() {
}
public void method_657() {
}
public void method_658() {
}
public void method_659() {
}
public void method_660() {
}
public void method_661() {
}
public void method_662() {
}
public void method_663() {
}
public void method_664() {
}
public void method_665() {
}
public void method_666() {
}
public void method_667() {
}
public void method_668() {
}
public void method_669() {
}
public void method_670() {
}
public void method_671() {
}
public void method_672() {
}
public void method_673() {
}
public void method_674() {
}
public void method_675() {
}
public void method_676() {
}
public void method_677() {
}
public void method_678() {
}
public void method_679() {
}
public void method_680() {
}
public void method_681() {
}
public void method_682() {
}
public void method_683() {
}
public void method_684() {
}
public void method_685() {
}
public void method_686() {
}
public void method_687() {
}
public void method_688() {
}
public void method_689() {
}
public void method_690() {
}
public void method_691() {
}
public void method_692() {
}
public void method_693() {
}
public void method_694() {
}
public void method_695() {
}
public void method_696() {
}
public void method_697() {
}
public void method_698() {
}
public void method_699() {
}
public void method_700() {
}
}
|
SethsApps/ud867
|
4.07-Demo-MultidexSupport/app/src/main/java/com/udacity/gradle/multidex/Methods19.java
|
Java
|
mit
| 26,591
|
/* global suite, test */
'use strict';
var assert = require('assert');
var Table = require(__dirname + '/../lib/table');
var Column = require(__dirname + '/../lib/column');
suite('table', function() {
var table = new Table({
name: 'bang'
});
test('has name', function() {
assert.equal(table.getName(), 'bang');
});
test('has no columns', function() {
assert.equal(table.columns.length, 0);
});
test('can add column', function() {
var col = new Column({
table: table,
name: 'boom'
});
assert.equal(col.name, 'boom');
assert.equal(col.table.getName(), 'bang');
table.addColumn(col);
assert.equal(table.columns.length, 1);
assert.equal(table.boom, col);
});
test('creates query node', function() {
var sel = table.select(table.boom);
assert.equal(sel.type, 'QUERY');
});
test('creates *-query if no args is provided to select()', function() {
var sel = table.select();
assert.ok(sel.nodes[0].nodes[0].star);
});
test('can be defined', function() {
var user = Table.define({
name: 'user',
columns: ['id', 'name']
});
assert.equal(user.getName(), 'user');
assert.equal(user.columns.length, 2);
assert.equal(user.columns[0].name, 'id');
assert.equal(user.columns[1].name, 'name');
assert.equal(user.columns[0].name, user.id.name);
assert.equal(user.id.table, user);
assert.equal(user.name.table, user);
});
});
test('table with user-defined column property names', function () {
var table = Table.define({
name: 'blah',
columns: [{
name: 'id',
property: 'theId'
}, {
name: 'email',
property: 'uniqueEmail'
}]
});
var cols = table.columns;
assert.equal(cols.length, 2);
assert.equal(cols[0].name, 'id');
assert(cols[0] === table.theId, 'Expected table.theId to be the first column');
assert(table.id === undefined, 'Expected table.id to not exist');
assert.equal(cols[1].name, 'email');
assert(cols[1] === table.uniqueEmail, 'Expected table.uniqueEmail to be the second column');
assert(table.email === undefined, 'Expected table.email to not exist');
});
test('table with fancier column definitions', function() {
var table = Table.define({
name: 'blah',
columns: [{
name: 'id',
type: 'serial',
notNull: true,
primaryKey: true
}, {
name: 'email',
type: 'text',
notNull: true,
unique: true,
anythingYouWant: 'awesome'
}]
});
var cols = table.columns;
assert.equal(cols.length, 2);
var id = cols[0];
assert.equal(id.name, 'id');
assert.equal(id.type, 'serial');
assert.equal(id.notNull, true);
assert.equal(id.primaryKey, true);
var email = cols[1];
assert.equal(email.name, 'email');
assert.equal(email.type, 'text');
assert.equal(email.notNull, true);
assert.equal(email.unique, true);
assert.equal(email.anythingYouWant, 'awesome');
});
test('table with object structured column definitions', function() {
var table = Table.define({
name: 'blah',
columns: {
id: {
type: 'serial',
notNull: true,
primaryKey: true
},
email: {
type: 'text',
notNull: true,
unique: true,
anythingYouWant: 'awesome'
}
}
});
var cols = table.columns;
assert.equal(cols.length, 2);
var id = cols[0];
assert.equal(id.name, 'id');
assert.equal(id.type, 'serial');
assert.equal(id.notNull, true);
assert.equal(id.primaryKey, true);
var email = cols[1];
assert.equal(email.name, 'email');
assert.equal(email.type, 'text');
assert.equal(email.notNull, true);
assert.equal(email.unique, true);
assert.equal(email.anythingYouWant, 'awesome');
});
test('table with dynamic column definition', function() {
var table = Table.define({ name: 'foo', columns: [] });
assert.equal(table.columns.length, 0);
table.addColumn('foo');
assert.equal(table.columns.length, 1);
var error = null;
assert.throws(function() {
table.addColumn('foo');
});
assert.doesNotThrow(function() {
table.addColumn('foo', { noisy: false });
});
assert.equal(table.columns.length, 1);
});
test('hasColumn', function() {
var table = Table.define({ name: 'foo', columns: [] });
assert.equal(table.hasColumn('baz'), false);
table.addColumn('baz');
assert.equal(table.hasColumn('baz'), true);
});
test('the column "from" does not overwrite the from method', function() {
var table = Table.define({ name: 'foo', columns: [] });
table.addColumn('from');
assert.equal(typeof table.from, 'function');
});
test('getColumn returns the from column', function() {
var table = Table.define({ name: 'foo', columns: [] });
table.addColumn('from');
assert(table.getColumn('from') instanceof Column);
assert(table.get('from') instanceof Column);
});
|
sanderblue/angular-express-mysql
|
node_modules/sequelize/node_modules/sql/test/table-tests.js
|
JavaScript
|
mit
| 4,877
|
// Class for barrier instructions, modelled as a CallInstr.
//
// Copyright (c) 2011 Universidad Rey Juan Carlos
//
// 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.
#include "config.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/Support/Casting.h"
#define BARRIER_FUNCTION_NAME "pocl.barrier"
namespace pocl {
class Barrier : public llvm::CallInst {
public:
static void GetBarriers(llvm::SmallVectorImpl<Barrier *> &B,
llvm::Module &M) {
llvm::Function *F = M.getFunction(BARRIER_FUNCTION_NAME);
if (F != NULL) {
for (llvm::Function::use_iterator i = F->use_begin(), e = F->use_end();
i != e; ++i)
B.push_back(llvm::cast<Barrier>(*i));
}
}
/**
* Creates a new barrier before the given instruction.
*
* If there was already a barrier there, returns the old one.
*/
static Barrier *Create(llvm::Instruction *InsertBefore) {
llvm::Module *M = InsertBefore->getParent()->getParent()->getParent();
if (InsertBefore != &InsertBefore->getParent()->front() &&
llvm::isa<Barrier>(InsertBefore->getPrevNode()))
return llvm::cast<Barrier>(InsertBefore->getPrevNode());
llvm::Function *F = llvm::cast<llvm::Function>
(M->getOrInsertFunction(BARRIER_FUNCTION_NAME,
llvm::Type::getVoidTy(M->getContext()),
NULL));
F->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
return llvm::cast<pocl::Barrier>
(llvm::CallInst::Create(F, "", InsertBefore));
}
static bool classof(const Barrier *) { return true; };
static bool classof(const llvm::CallInst *C) {
return C->getCalledFunction() != NULL &&
C->getCalledFunction()->getName() == BARRIER_FUNCTION_NAME;
}
static bool classof(const Instruction *I) {
return (llvm::isa<llvm::CallInst>(I) &&
classof(llvm::cast<llvm::CallInst>(I)));
}
static bool classof(const User *U) {
return (llvm::isa<Instruction>(U) &&
classof(llvm::cast<llvm::Instruction>(U)));
}
static bool classof(const Value *V) {
return (llvm::isa<User>(V) &&
classof(llvm::cast<llvm::User>(V)));
}
static bool hasOnlyBarrier(const llvm::BasicBlock *bb) {
return endsWithBarrier(bb) && bb->size() == 2;
}
static bool hasBarrier(const llvm::BasicBlock *bb)
{
for (llvm::BasicBlock::const_iterator i = bb->begin(), e = bb->end();
i != e; ++i)
{
if (llvm::isa<Barrier>(i)) return true;
}
return false;
}
// Returns true in case the given basic block starts with a barrier,
// that is, contains a branch instruction after possible PHI nodes.
static bool startsWithBarrier(const llvm::BasicBlock *bb) {
const llvm::Instruction *i = bb->getFirstNonPHI();
if (i == NULL)
return false;
return llvm::isa<Barrier>(i);
}
// Returns true in case the given basic block ends with a barrier,
// that is, contains only a branch instruction after a barrier call.
static bool endsWithBarrier(const llvm::BasicBlock *bb) {
const llvm::TerminatorInst *t = bb->getTerminator();
if (t == NULL)
return false;
return bb->size() > 1 && t->getPrevNode() != NULL &&
llvm::isa<Barrier>(t->getPrevNode());
}
};
}
|
jrprice/pocl
|
lib/llvmopencl/Barrier.h
|
C
|
mit
| 4,596
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./quickOutline';
import * as nls from 'vs/nls';
import { matchesFuzzy } from 'vs/base/common/filters';
import * as strings from 'vs/base/common/strings';
import { TPromise } from 'vs/base/common/winjs.base';
import { IContext, IHighlight, QuickOpenEntryGroup, QuickOpenModel } from 'vs/base/parts/quickopen/browser/quickOpenModel';
import { IAutoFocus, Mode } from 'vs/base/parts/quickopen/common/quickOpen';
import { ICommonCodeEditor } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { SymbolInformation, DocumentSymbolProviderRegistry, symbolKindToCssClass } from 'vs/editor/common/modes';
import { BaseEditorQuickOpenAction, IDecorator } from './editorQuickOpen';
import { getDocumentSymbols, IOutline } from 'vs/editor/contrib/quickOpen/common/quickOpen';
import { editorAction, ServicesAccessor } from 'vs/editor/common/editorCommonExtensions';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Range } from 'vs/editor/common/core/range';
let SCOPE_PREFIX = ':';
class SymbolEntry extends QuickOpenEntryGroup {
private name: string;
private type: string;
private description: string;
private range: Range;
private editor: ICommonCodeEditor;
private decorator: IDecorator;
constructor(name: string, type: string, description: string, range: Range, highlights: IHighlight[], editor: ICommonCodeEditor, decorator: IDecorator) {
super();
this.name = name;
this.type = type;
this.description = description;
this.range = range;
this.setHighlights(highlights);
this.editor = editor;
this.decorator = decorator;
}
public getLabel(): string {
return this.name;
}
public getAriaLabel(): string {
return nls.localize('entryAriaLabel', "{0}, symbols", this.name);
}
public getIcon(): string {
return this.type;
}
public getDescription(): string {
return this.description;
}
public getType(): string {
return this.type;
}
public getRange(): Range {
return this.range;
}
public run(mode: Mode, context: IContext): boolean {
if (mode === Mode.OPEN) {
return this.runOpen(context);
}
return this.runPreview();
}
private runOpen(context: IContext): boolean {
// Apply selection and focus
let range = this.toSelection();
this.editor.setSelection(range);
this.editor.revealRangeInCenter(range);
this.editor.focus();
return true;
}
private runPreview(): boolean {
// Select Outline Position
let range = this.toSelection();
this.editor.revealRangeInCenter(range);
// Decorate if possible
this.decorator.decorateLine(this.range, this.editor);
return false;
}
private toSelection(): Range {
return new Range(
this.range.startLineNumber,
this.range.startColumn || 1,
this.range.startLineNumber,
this.range.startColumn || 1
);
}
}
@editorAction
export class QuickOutlineAction extends BaseEditorQuickOpenAction {
constructor() {
super(nls.localize('quickOutlineActionInput', "Type the name of an identifier you wish to navigate to"), {
id: 'editor.action.quickOutline',
label: nls.localize('QuickOutlineAction.label', "Go to Symbol..."),
alias: 'Go to Symbol...',
precondition: EditorContextKeys.hasDocumentSymbolProvider,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_O
},
menuOpts: {
group: 'navigation',
order: 3
}
});
}
public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): TPromise<void> {
let model = editor.getModel();
if (!DocumentSymbolProviderRegistry.has(model)) {
return null;
}
// Resolve outline
return getDocumentSymbols(model).then((result: IOutline) => {
if (result.entries.length === 0) {
return;
}
this._run(editor, result.entries);
});
}
private _run(editor: ICommonCodeEditor, result: SymbolInformation[]): void {
this._show(this.getController(editor), {
getModel: (value: string): QuickOpenModel => {
return new QuickOpenModel(this.toQuickOpenEntries(editor, result, value));
},
getAutoFocus: (searchValue: string): IAutoFocus => {
// Remove any type pattern (:) from search value as needed
if (searchValue.indexOf(SCOPE_PREFIX) === 0) {
searchValue = searchValue.substr(SCOPE_PREFIX.length);
}
return {
autoFocusPrefixMatch: searchValue,
autoFocusFirstEntry: !!searchValue
};
}
});
}
private toQuickOpenEntries(editor: ICommonCodeEditor, flattened: SymbolInformation[], searchValue: string): SymbolEntry[] {
const controller = this.getController(editor);
let results: SymbolEntry[] = [];
// Convert to Entries
let normalizedSearchValue = searchValue;
if (searchValue.indexOf(SCOPE_PREFIX) === 0) {
normalizedSearchValue = normalizedSearchValue.substr(SCOPE_PREFIX.length);
}
for (let i = 0; i < flattened.length; i++) {
let element = flattened[i];
let label = strings.trim(element.name);
// Check for meatch
let highlights = matchesFuzzy(normalizedSearchValue, label);
if (highlights) {
// Show parent scope as description
let description: string = null;
if (element.containerName) {
description = element.containerName;
}
// Add
results.push(new SymbolEntry(label, symbolKindToCssClass(element.kind), description, Range.lift(element.location.range), highlights, editor, controller));
}
}
// Sort properly if actually searching
if (searchValue) {
if (searchValue.indexOf(SCOPE_PREFIX) === 0) {
results = results.sort(this.sortScoped.bind(this, searchValue.toLowerCase()));
} else {
results = results.sort(this.sortNormal.bind(this, searchValue.toLowerCase()));
}
}
// Mark all type groups
if (results.length > 0 && searchValue.indexOf(SCOPE_PREFIX) === 0) {
let currentType: string = null;
let currentResult: SymbolEntry = null;
let typeCounter = 0;
for (let i = 0; i < results.length; i++) {
let result = results[i];
// Found new type
if (currentType !== result.getType()) {
// Update previous result with count
if (currentResult) {
currentResult.setGroupLabel(this.typeToLabel(currentType, typeCounter));
}
currentType = result.getType();
currentResult = result;
typeCounter = 1;
result.setShowBorder(i > 0);
}
// Existing type, keep counting
else {
typeCounter++;
}
}
// Update previous result with count
if (currentResult) {
currentResult.setGroupLabel(this.typeToLabel(currentType, typeCounter));
}
}
// Mark first entry as outline
else if (results.length > 0) {
results[0].setGroupLabel(nls.localize('symbols', "symbols ({0})", results.length));
}
return results;
}
private typeToLabel(type: string, count: number): string {
switch (type) {
case 'module': return nls.localize('modules', "modules ({0})", count);
case 'class': return nls.localize('class', "classes ({0})", count);
case 'interface': return nls.localize('interface', "interfaces ({0})", count);
case 'method': return nls.localize('method', "methods ({0})", count);
case 'function': return nls.localize('function', "functions ({0})", count);
case 'property': return nls.localize('property', "properties ({0})", count);
case 'variable': return nls.localize('variable', "variables ({0})", count);
case 'var': return nls.localize('variable2', "variables ({0})", count);
case 'constructor': return nls.localize('_constructor', "constructors ({0})", count);
case 'call': return nls.localize('call', "calls ({0})", count);
}
return type;
}
private sortNormal(searchValue: string, elementA: SymbolEntry, elementB: SymbolEntry): number {
let elementAName = elementA.getLabel().toLowerCase();
let elementBName = elementB.getLabel().toLowerCase();
// Compare by name
let r = elementAName.localeCompare(elementBName);
if (r !== 0) {
return r;
}
// If name identical sort by range instead
let elementARange = elementA.getRange();
let elementBRange = elementB.getRange();
return elementARange.startLineNumber - elementBRange.startLineNumber;
}
private sortScoped(searchValue: string, elementA: SymbolEntry, elementB: SymbolEntry): number {
// Remove scope char
searchValue = searchValue.substr(SCOPE_PREFIX.length);
// Sort by type first if scoped search
let elementAType = elementA.getType();
let elementBType = elementB.getType();
let r = elementAType.localeCompare(elementBType);
if (r !== 0) {
return r;
}
// Special sort when searching in scoped mode
if (searchValue) {
let elementAName = elementA.getLabel().toLowerCase();
let elementBName = elementB.getLabel().toLowerCase();
// Compare by name
let r = elementAName.localeCompare(elementBName);
if (r !== 0) {
return r;
}
}
// Default to sort by range
let elementARange = elementA.getRange();
let elementBRange = elementB.getRange();
return elementARange.startLineNumber - elementBRange.startLineNumber;
}
}
|
matthewshirley/vscode
|
src/vs/editor/contrib/quickOpen/browser/quickOutline.ts
|
TypeScript
|
mit
| 9,386
|
(function($) {
/**
* Example module implementation.
*
* @author
* @namespace Tc.Module
* @class Default
* @extends Tc.Module
*/
Tc.Module.Example = Tc.Module.extend({
/**
* Initializes the Example module.
*
* @method init
* @constructor
* @param {jQuery|Zepto} $ctx the jquery context
* @param {Sandbox} sandbox the sandbox to get the resources from
* @param {String} modId the unique module id
*/
init: function($ctx, sandbox, modId) {
// call base constructor
this._super($ctx, sandbox, modId);
},
/**
* Hook function to do all of your module stuff.
*
* @method on
* @param {Function} callback function
* @return void
*/
on: function(callback) {
this.$ctx.append('\n<br><span class="debug">JS Module "example" started</span>');
callback();
},
/**
* Hook function to trigger your events.
*
* @method after
* @return void
*/
after: function() {
}
});
})(Tc.$);
|
MarcDiethelm/xtc-site
|
node_modules/xtc/node_modules/generator-xtc/app/templates/frontend-example/modules/example/example.js
|
JavaScript
|
mit
| 978
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @constructor
* @extends {WebInspector.TimelineUIUtils}
*/
WebInspector.TimelineUIUtilsImpl = function()
{
WebInspector.TimelineUIUtils.call(this);
}
WebInspector.TimelineUIUtilsImpl.prototype = {
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {boolean}
*/
isBeginFrame: function(record)
{
return record.type() === WebInspector.TimelineModel.RecordType.BeginFrame;
},
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {boolean}
*/
isProgram: function(record)
{
return record.type() === WebInspector.TimelineModel.RecordType.Program;
},
/**
* @param {string} recordType
* @return {boolean}
*/
isCoalescable: function(recordType)
{
return !!WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[recordType];
},
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {boolean}
*/
isEventDivider: function(record)
{
return WebInspector.TimelineUIUtilsImpl.isEventDivider(record);
},
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {?Object}
*/
countersForRecord: function(record)
{
return record.type() === WebInspector.TimelineModel.RecordType.UpdateCounters ? record.data() : null;
},
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {?Object}
*/
highlightQuadForRecord: function(record)
{
var recordTypes = WebInspector.TimelineModel.RecordType;
switch(record.type()) {
case recordTypes.Layout:
return record.data().root;
case recordTypes.Paint:
return record.data().clip;
default:
return null;
}
},
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {string}
*/
titleForRecord: function(record)
{
return WebInspector.TimelineUIUtilsImpl._recordTitle(record);
},
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {!WebInspector.TimelineCategory}
*/
categoryForRecord: function(record)
{
return WebInspector.TimelineUIUtilsImpl.recordStyle(record).category;
},
/**
* @param {!WebInspector.TimelineModel.Record} record
* @param {!WebInspector.Linkifier} linkifier
* @return {?Node}
*/
buildDetailsNode: function(record, linkifier)
{
return WebInspector.TimelineUIUtilsImpl.buildDetailsNode(record, linkifier);
},
/**
* @param {!WebInspector.TimelineModel.Record} record
* @param {!WebInspector.TimelineModel} model
* @param {!WebInspector.Linkifier} linkifier
* @param {function(!DocumentFragment)} callback
*/
generateDetailsContent: function(record, model, linkifier, callback)
{
WebInspector.TimelineUIUtilsImpl.generateDetailsContent(record, model, linkifier, callback);
},
/**
* @return {!Element}
*/
createBeginFrameDivider: function()
{
return this.createEventDivider(WebInspector.TimelineModel.RecordType.BeginFrame);
},
/**
* @param {string} recordType
* @param {string=} title
* @return {!Element}
*/
createEventDivider: function(recordType, title)
{
return WebInspector.TimelineUIUtilsImpl._createEventDivider(recordType, title);
},
/**
* @param {!WebInspector.TimelineModel.Record} record
* @param {!RegExp} regExp
* @return {boolean}
*/
testContentMatching: function(record, regExp)
{
var tokens = [WebInspector.TimelineUIUtilsImpl._recordTitle(record)];
var data = record.data();
for (var key in data)
tokens.push(data[key])
return regExp.test(tokens.join("|"));
},
/**
* @param {!Object} total
* @param {!WebInspector.TimelineModel.Record} record
*/
aggregateTimeForRecord: function(total, record)
{
WebInspector.TimelineUIUtilsImpl.aggregateTimeForRecord(total, record);
},
/**
* @return {!WebInspector.TimelineModel.Filter}
*/
hiddenRecordsFilter: function()
{
var recordTypes = WebInspector.TimelineModel.RecordType;
var hiddenRecords = [
recordTypes.ActivateLayerTree,
recordTypes.BeginFrame,
recordTypes.DrawFrame,
recordTypes.GPUTask,
recordTypes.InvalidateLayout,
recordTypes.MarkDOMContent,
recordTypes.MarkFirstPaint,
recordTypes.MarkLoad,
recordTypes.RequestMainThreadFrame,
recordTypes.ScheduleStyleRecalculation,
recordTypes.UpdateCounters
];
return new WebInspector.TimelineRecordHiddenTypeFilter(hiddenRecords);
},
__proto__: WebInspector.TimelineUIUtils.prototype
}
WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes = {};
WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.Layout] = 1;
WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.Paint] = 1;
WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.Rasterize] = 1;
WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.DecodeImage] = 1;
WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.ResizeImage] = 1;
/**
* @return {!Object.<string, !{title: string, category: !WebInspector.TimelineCategory}>}
*/
WebInspector.TimelineUIUtils._initRecordStyles = function()
{
if (WebInspector.TimelineUIUtils._recordStylesMap)
return WebInspector.TimelineUIUtils._recordStylesMap;
var recordTypes = WebInspector.TimelineModel.RecordType;
var categories = WebInspector.TimelineUIUtils.categories();
var recordStyles = {};
recordStyles[recordTypes.Root] = { title: "#root", category: categories["loading"] };
recordStyles[recordTypes.Program] = { title: WebInspector.UIString("Other"), category: categories["other"] };
recordStyles[recordTypes.EventDispatch] = { title: WebInspector.UIString("Event"), category: categories["scripting"] };
recordStyles[recordTypes.BeginFrame] = { title: WebInspector.UIString("Frame Start"), category: categories["rendering"] };
recordStyles[recordTypes.ScheduleStyleRecalculation] = { title: WebInspector.UIString("Schedule Style Recalculation"), category: categories["rendering"] };
recordStyles[recordTypes.RecalculateStyles] = { title: WebInspector.UIString("Recalculate Style"), category: categories["rendering"] };
recordStyles[recordTypes.InvalidateLayout] = { title: WebInspector.UIString("Invalidate Layout"), category: categories["rendering"] };
recordStyles[recordTypes.Layout] = { title: WebInspector.UIString("Layout"), category: categories["rendering"] };
recordStyles[recordTypes.UpdateLayerTree] = { title: WebInspector.UIString("Update Layer Tree"), category: categories["rendering"] };
recordStyles[recordTypes.PaintSetup] = { title: WebInspector.UIString("Paint Setup"), category: categories["painting"] };
recordStyles[recordTypes.Paint] = { title: WebInspector.UIString("Paint"), category: categories["painting"] };
recordStyles[recordTypes.Rasterize] = { title: WebInspector.UIString("Paint"), category: categories["painting"] };
recordStyles[recordTypes.ScrollLayer] = { title: WebInspector.UIString("Scroll"), category: categories["rendering"] };
recordStyles[recordTypes.DecodeImage] = { title: WebInspector.UIString("Image Decode"), category: categories["painting"] };
recordStyles[recordTypes.ResizeImage] = { title: WebInspector.UIString("Image Resize"), category: categories["painting"] };
recordStyles[recordTypes.CompositeLayers] = { title: WebInspector.UIString("Composite Layers"), category: categories["painting"] };
recordStyles[recordTypes.ParseHTML] = { title: WebInspector.UIString("Parse HTML"), category: categories["loading"] };
recordStyles[recordTypes.TimerInstall] = { title: WebInspector.UIString("Install Timer"), category: categories["scripting"] };
recordStyles[recordTypes.TimerRemove] = { title: WebInspector.UIString("Remove Timer"), category: categories["scripting"] };
recordStyles[recordTypes.TimerFire] = { title: WebInspector.UIString("Timer Fired"), category: categories["scripting"] };
recordStyles[recordTypes.XHRReadyStateChange] = { title: WebInspector.UIString("XHR Ready State Change"), category: categories["scripting"] };
recordStyles[recordTypes.XHRLoad] = { title: WebInspector.UIString("XHR Load"), category: categories["scripting"] };
recordStyles[recordTypes.EvaluateScript] = { title: WebInspector.UIString("Evaluate Script"), category: categories["scripting"] };
recordStyles[recordTypes.ResourceSendRequest] = { title: WebInspector.UIString("Send Request"), category: categories["loading"] };
recordStyles[recordTypes.ResourceReceiveResponse] = { title: WebInspector.UIString("Receive Response"), category: categories["loading"] };
recordStyles[recordTypes.ResourceFinish] = { title: WebInspector.UIString("Finish Loading"), category: categories["loading"] };
recordStyles[recordTypes.FunctionCall] = { title: WebInspector.UIString("Function Call"), category: categories["scripting"] };
recordStyles[recordTypes.ResourceReceivedData] = { title: WebInspector.UIString("Receive Data"), category: categories["loading"] };
recordStyles[recordTypes.GCEvent] = { title: WebInspector.UIString("GC Event"), category: categories["scripting"] };
recordStyles[recordTypes.JSFrame] = { title: WebInspector.UIString("JS Frame"), category: categories["scripting"] };
recordStyles[recordTypes.MarkDOMContent] = { title: WebInspector.UIString("DOMContentLoaded event"), category: categories["scripting"] };
recordStyles[recordTypes.MarkLoad] = { title: WebInspector.UIString("Load event"), category: categories["scripting"] };
recordStyles[recordTypes.MarkFirstPaint] = { title: WebInspector.UIString("First paint"), category: categories["painting"] };
recordStyles[recordTypes.TimeStamp] = { title: WebInspector.UIString("Stamp"), category: categories["scripting"] };
recordStyles[recordTypes.ConsoleTime] = { title: WebInspector.UIString("Console Time"), category: categories["scripting"] };
recordStyles[recordTypes.RequestAnimationFrame] = { title: WebInspector.UIString("Request Animation Frame"), category: categories["scripting"] };
recordStyles[recordTypes.CancelAnimationFrame] = { title: WebInspector.UIString("Cancel Animation Frame"), category: categories["scripting"] };
recordStyles[recordTypes.FireAnimationFrame] = { title: WebInspector.UIString("Animation Frame Fired"), category: categories["scripting"] };
recordStyles[recordTypes.WebSocketCreate] = { title: WebInspector.UIString("Create WebSocket"), category: categories["scripting"] };
recordStyles[recordTypes.WebSocketSendHandshakeRequest] = { title: WebInspector.UIString("Send WebSocket Handshake"), category: categories["scripting"] };
recordStyles[recordTypes.WebSocketReceiveHandshakeResponse] = { title: WebInspector.UIString("Receive WebSocket Handshake"), category: categories["scripting"] };
recordStyles[recordTypes.WebSocketDestroy] = { title: WebInspector.UIString("Destroy WebSocket"), category: categories["scripting"] };
recordStyles[recordTypes.EmbedderCallback] = { title: WebInspector.UIString("Embedder Callback"), category: categories["scripting"] };
WebInspector.TimelineUIUtils._recordStylesMap = recordStyles;
return recordStyles;
}
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {!{title: string, category: !WebInspector.TimelineCategory}}
*/
WebInspector.TimelineUIUtilsImpl.recordStyle = function(record)
{
var type = record.type();
var recordStyles = WebInspector.TimelineUIUtils._initRecordStyles();
var result = recordStyles[type];
if (!result) {
result = {
title: WebInspector.UIString("Unknown: %s", type),
category: WebInspector.TimelineUIUtils.categories()["other"]
};
recordStyles[type] = result;
}
return result;
}
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {string}
*/
WebInspector.TimelineUIUtilsImpl._recordTitle = function(record)
{
var recordData = record.data();
if (record.type() === WebInspector.TimelineModel.RecordType.TimeStamp)
return recordData["message"];
if (record.type() === WebInspector.TimelineModel.RecordType.JSFrame)
return recordData["functionName"];
var title = WebInspector.TimelineUIUtilsImpl.recordStyle(record).title;
if (WebInspector.TimelineUIUtilsImpl.isEventDivider(record)) {
var startTime = Number.millisToString(record.startTime() - record._model.minimumRecordTime());
return WebInspector.UIString("%s at %s", title, startTime);
}
return title;
}
/**
* @param {!WebInspector.TimelineModel.Record} record
* @return {boolean}
*/
WebInspector.TimelineUIUtilsImpl.isEventDivider = function(record)
{
var recordTypes = WebInspector.TimelineModel.RecordType;
if (record.type() === recordTypes.TimeStamp)
return true;
if (record.type() === recordTypes.MarkFirstPaint)
return true;
if (record.type() === recordTypes.MarkDOMContent || record.type() === recordTypes.MarkLoad)
return record.data()["isMainFrame"];
return false;
}
/**
* @param {!Object} total
* @param {!WebInspector.TimelineModel.Record} record
*/
WebInspector.TimelineUIUtilsImpl.aggregateTimeForRecord = function(total, record)
{
var children = record.children();
for (var i = 0; i < children.length; ++i)
WebInspector.TimelineUIUtilsImpl.aggregateTimeForRecord(total, children[i]);
var categoryName = WebInspector.TimelineUIUtilsImpl.recordStyle(record).category.name;
total[categoryName] = (total[categoryName] || 0) + record.selfTime();
}
/**
* @param {!WebInspector.TimelineModel.Record} record
* @param {!WebInspector.Linkifier} linkifier
* @return {?Node}
*/
WebInspector.TimelineUIUtilsImpl.buildDetailsNode = function(record, linkifier)
{
var details;
var detailsText;
var recordData = record.data();
switch (record.type()) {
case WebInspector.TimelineModel.RecordType.GCEvent:
detailsText = WebInspector.UIString("%s collected", Number.bytesToString(recordData["usedHeapSizeDelta"]));
break;
case WebInspector.TimelineModel.RecordType.TimerFire:
detailsText = recordData["timerId"];
break;
case WebInspector.TimelineModel.RecordType.FunctionCall:
details = linkifyLocation(recordData["scriptId"], recordData["scriptName"], recordData["scriptLine"], 0);
break;
case WebInspector.TimelineModel.RecordType.FireAnimationFrame:
detailsText = recordData["id"];
break;
case WebInspector.TimelineModel.RecordType.EventDispatch:
detailsText = recordData ? recordData["type"] : null;
break;
case WebInspector.TimelineModel.RecordType.Paint:
var width = WebInspector.TimelineUIUtils.quadWidth(recordData.clip);
var height = WebInspector.TimelineUIUtils.quadHeight(recordData.clip);
if (width && height)
detailsText = WebInspector.UIString("%d\u2009\u00d7\u2009%d", width, height);
break;
case WebInspector.TimelineModel.RecordType.TimerInstall:
case WebInspector.TimelineModel.RecordType.TimerRemove:
details = linkifyTopCallFrame();
detailsText = recordData["timerId"];
break;
case WebInspector.TimelineModel.RecordType.RequestAnimationFrame:
case WebInspector.TimelineModel.RecordType.CancelAnimationFrame:
details = linkifyTopCallFrame();
detailsText = recordData["id"];
break;
case WebInspector.TimelineModel.RecordType.ParseHTML:
case WebInspector.TimelineModel.RecordType.RecalculateStyles:
details = linkifyTopCallFrame();
break;
case WebInspector.TimelineModel.RecordType.EvaluateScript:
var url = recordData["url"];
if (url)
details = linkifyLocation("", url, recordData["lineNumber"], 0);
break;
case WebInspector.TimelineModel.RecordType.XHRReadyStateChange:
case WebInspector.TimelineModel.RecordType.XHRLoad:
case WebInspector.TimelineModel.RecordType.ResourceSendRequest:
case WebInspector.TimelineModel.RecordType.DecodeImage:
case WebInspector.TimelineModel.RecordType.ResizeImage:
var url = recordData["url"];
if (url)
detailsText = WebInspector.displayNameForURL(url);
break;
case WebInspector.TimelineModel.RecordType.ResourceReceivedData:
case WebInspector.TimelineModel.RecordType.ResourceReceiveResponse:
case WebInspector.TimelineModel.RecordType.ResourceFinish:
var initiator = record.initiator();
if (initiator) {
var url = initiator.data()["url"];
if (url)
detailsText = WebInspector.displayNameForURL(url);
}
break;
case WebInspector.TimelineModel.RecordType.ConsoleTime:
detailsText = recordData["message"];
break;
case WebInspector.TimelineModel.RecordType.EmbedderCallback:
detailsText = recordData["callbackName"];
break;
default:
details = linkifyTopCallFrame();
break;
}
if (!details && detailsText)
details = document.createTextNode(detailsText);
return details;
/**
* @param {string} scriptId
* @param {string} url
* @param {number} lineNumber
* @param {number=} columnNumber
*/
function linkifyLocation(scriptId, url, lineNumber, columnNumber)
{
if (!url)
return null;
// FIXME(62725): stack trace line/column numbers are one-based.
columnNumber = columnNumber ? columnNumber - 1 : 0;
return linkifier.linkifyScriptLocation(record.target(), scriptId, url, lineNumber - 1, columnNumber, "timeline-details");
}
/**
* @return {?Element}
*/
function linkifyTopCallFrame()
{
if (record.stackTrace())
return linkifier.linkifyConsoleCallFrame(record.target(), record.stackTrace()[0], "timeline-details");
if (record.callSiteStackTrace())
return linkifier.linkifyConsoleCallFrame(record.target(), record.callSiteStackTrace()[0], "timeline-details");
return null;
}
}
/**
* @param {string=} recordType
* @return {boolean}
*/
WebInspector.TimelineUIUtilsImpl._needsPreviewElement = function(recordType)
{
if (!recordType)
return false;
const recordTypes = WebInspector.TimelineModel.RecordType;
switch (recordType) {
case recordTypes.ResourceSendRequest:
case recordTypes.ResourceReceiveResponse:
case recordTypes.ResourceReceivedData:
case recordTypes.ResourceFinish:
return true;
default:
return false;
}
}
/**
* @param {!WebInspector.TimelineModel.Record} record
* @param {!WebInspector.TimelineModel} model
* @param {!WebInspector.Linkifier} linkifier
* @param {function(!DocumentFragment)} callback
*/
WebInspector.TimelineUIUtilsImpl.generateDetailsContent = function(record, model, linkifier, callback)
{
var imageElement = /** @type {?Element} */ (record.getUserObject("TimelineUIUtils::preview-element") || null);
var relatedNode = null;
var recordData = record.data();
var barrier = new CallbackBarrier();
var target = record.target();
if (!imageElement && WebInspector.TimelineUIUtilsImpl._needsPreviewElement(record.type()) && target)
WebInspector.DOMPresentationUtils.buildImagePreviewContents(target, recordData["url"], false, barrier.createCallback(saveImage));
if (recordData["backendNodeId"] && target)
target.domModel.pushNodesByBackendIdsToFrontend([recordData["backendNodeId"]], barrier.createCallback(setRelatedNode));
barrier.callWhenDone(callbackWrapper);
/**
* @param {!Element=} element
*/
function saveImage(element)
{
imageElement = element || null;
record.setUserObject("TimelineUIUtils::preview-element", element);
}
/**
* @param {?Array.<!DOMAgent.NodeId>} nodeIds
*/
function setRelatedNode(nodeIds)
{
if (nodeIds && target)
relatedNode = target.domModel.nodeForId(nodeIds[0]);
}
function callbackWrapper()
{
callback(WebInspector.TimelineUIUtilsImpl._generateDetailsContentSynchronously(record, model, linkifier, imageElement, relatedNode));
}
}
/**
* @param {!WebInspector.TimelineModel.Record} record
* @param {!WebInspector.TimelineModel} model
* @param {!WebInspector.Linkifier} linkifier
* @param {?Element} imagePreviewElement
* @param {?WebInspector.DOMNode} relatedNode
* @return {!DocumentFragment}
*/
WebInspector.TimelineUIUtilsImpl._generateDetailsContentSynchronously = function(record, model, linkifier, imagePreviewElement, relatedNode)
{
var fragment = document.createDocumentFragment();
var aggregatedStats = {};
WebInspector.TimelineUIUtilsImpl.aggregateTimeForRecord(aggregatedStats, record);
if (record.children().length)
fragment.appendChild(WebInspector.TimelineUIUtils.generatePieChart(aggregatedStats, WebInspector.TimelineUIUtilsImpl.recordStyle(record).category, record.selfTime()));
else
fragment.appendChild(WebInspector.TimelineUIUtils.generatePieChart(aggregatedStats));
const recordTypes = WebInspector.TimelineModel.RecordType;
// The messages may vary per record.type();
var callSiteStackTraceLabel;
var callStackLabel;
var relatedNodeLabel;
var contentHelper = new WebInspector.TimelineDetailsContentHelper(record.target(), linkifier, true);
contentHelper.appendTextRow(WebInspector.UIString("Self Time"), Number.millisToString(record.selfTime(), true));
contentHelper.appendTextRow(WebInspector.UIString("Start Time"), Number.millisToString(record.startTime() - model.minimumRecordTime()));
var recordData = record.data();
switch (record.type()) {
case recordTypes.GCEvent:
contentHelper.appendTextRow(WebInspector.UIString("Collected"), Number.bytesToString(recordData["usedHeapSizeDelta"]));
break;
case recordTypes.TimerFire:
callSiteStackTraceLabel = WebInspector.UIString("Timer installed");
// Fall-through intended.
case recordTypes.TimerInstall:
case recordTypes.TimerRemove:
contentHelper.appendTextRow(WebInspector.UIString("Timer ID"), recordData["timerId"]);
if (record.type() === recordTypes.TimerInstall) {
contentHelper.appendTextRow(WebInspector.UIString("Timeout"), Number.millisToString(recordData["timeout"]));
contentHelper.appendTextRow(WebInspector.UIString("Repeats"), !recordData["singleShot"]);
}
break;
case recordTypes.FireAnimationFrame:
callSiteStackTraceLabel = WebInspector.UIString("Animation frame requested");
contentHelper.appendTextRow(WebInspector.UIString("Callback ID"), recordData["id"]);
break;
case recordTypes.FunctionCall:
if (recordData["scriptName"])
contentHelper.appendLocationRow(WebInspector.UIString("Location"), recordData["scriptName"], recordData["scriptLine"]);
break;
case recordTypes.ResourceSendRequest:
case recordTypes.ResourceReceiveResponse:
case recordTypes.ResourceReceivedData:
case recordTypes.ResourceFinish:
var url;
if (record.type() === recordTypes.ResourceSendRequest)
url = recordData["url"];
else if (record.initiator())
url = record.initiator().data()["url"];
if (url)
contentHelper.appendElementRow(WebInspector.UIString("Resource"), WebInspector.linkifyResourceAsNode(url));
if (imagePreviewElement)
contentHelper.appendElementRow(WebInspector.UIString("Preview"), imagePreviewElement);
if (recordData["requestMethod"])
contentHelper.appendTextRow(WebInspector.UIString("Request Method"), recordData["requestMethod"]);
if (typeof recordData["statusCode"] === "number")
contentHelper.appendTextRow(WebInspector.UIString("Status Code"), recordData["statusCode"]);
if (recordData["mimeType"])
contentHelper.appendTextRow(WebInspector.UIString("MIME Type"), recordData["mimeType"]);
if (recordData["encodedDataLength"])
contentHelper.appendTextRow(WebInspector.UIString("Encoded Data Length"), WebInspector.UIString("%d Bytes", recordData["encodedDataLength"]));
break;
case recordTypes.EvaluateScript:
var url = recordData["url"];
if (url)
contentHelper.appendLocationRow(WebInspector.UIString("Script"), url, recordData["lineNumber"]);
break;
case recordTypes.Paint:
var clip = recordData["clip"];
contentHelper.appendTextRow(WebInspector.UIString("Location"), WebInspector.UIString("(%d, %d)", clip[0], clip[1]));
var clipWidth = WebInspector.TimelineUIUtils.quadWidth(clip);
var clipHeight = WebInspector.TimelineUIUtils.quadHeight(clip);
contentHelper.appendTextRow(WebInspector.UIString("Dimensions"), WebInspector.UIString("%d × %d", clipWidth, clipHeight));
// Fall-through intended.
case recordTypes.PaintSetup:
case recordTypes.Rasterize:
case recordTypes.ScrollLayer:
relatedNodeLabel = WebInspector.UIString("Layer root");
break;
case recordTypes.DecodeImage:
case recordTypes.ResizeImage:
relatedNodeLabel = WebInspector.UIString("Image element");
var url = recordData["url"];
if (url)
contentHelper.appendElementRow(WebInspector.UIString("Image URL"), WebInspector.linkifyResourceAsNode(url));
break;
case recordTypes.RecalculateStyles: // We don't want to see default details.
if (recordData["elementCount"])
contentHelper.appendTextRow(WebInspector.UIString("Elements affected"), recordData["elementCount"]);
callStackLabel = WebInspector.UIString("Styles recalculation forced");
break;
case recordTypes.Layout:
if (recordData["dirtyObjects"])
contentHelper.appendTextRow(WebInspector.UIString("Nodes that need layout"), recordData["dirtyObjects"]);
if (recordData["totalObjects"])
contentHelper.appendTextRow(WebInspector.UIString("Layout tree size"), recordData["totalObjects"]);
if (typeof recordData["partialLayout"] === "boolean") {
contentHelper.appendTextRow(WebInspector.UIString("Layout scope"),
recordData["partialLayout"] ? WebInspector.UIString("Partial") : WebInspector.UIString("Whole document"));
}
callSiteStackTraceLabel = WebInspector.UIString("Layout invalidated");
callStackLabel = WebInspector.UIString("Layout forced");
relatedNodeLabel = WebInspector.UIString("Layout root");
break;
case recordTypes.ConsoleTime:
contentHelper.appendTextRow(WebInspector.UIString("Message"), recordData["message"]);
break;
case recordTypes.WebSocketCreate:
case recordTypes.WebSocketSendHandshakeRequest:
case recordTypes.WebSocketReceiveHandshakeResponse:
case recordTypes.WebSocketDestroy:
var initiatorData = record.initiator() ? record.initiator().data() : recordData;
if (typeof initiatorData["webSocketURL"] !== "undefined")
contentHelper.appendTextRow(WebInspector.UIString("URL"), initiatorData["webSocketURL"]);
if (typeof initiatorData["webSocketProtocol"] !== "undefined")
contentHelper.appendTextRow(WebInspector.UIString("WebSocket Protocol"), initiatorData["webSocketProtocol"]);
if (typeof recordData["message"] !== "undefined")
contentHelper.appendTextRow(WebInspector.UIString("Message"), recordData["message"]);
break;
case recordTypes.EmbedderCallback:
contentHelper.appendTextRow(WebInspector.UIString("Callback Function"), recordData["callbackName"]);
break;
default:
var detailsNode = WebInspector.TimelineUIUtilsImpl.buildDetailsNode(record, linkifier);
if (detailsNode)
contentHelper.appendElementRow(WebInspector.UIString("Details"), detailsNode);
break;
}
if (relatedNode)
contentHelper.appendElementRow(relatedNodeLabel || WebInspector.UIString("Related node"), WebInspector.DOMPresentationUtils.linkifyNodeReference(relatedNode));
if (recordData["scriptName"] && record.type() !== recordTypes.FunctionCall)
contentHelper.appendLocationRow(WebInspector.UIString("Function Call"), recordData["scriptName"], recordData["scriptLine"]);
var callSiteStackTrace = record.callSiteStackTrace();
if (callSiteStackTrace)
contentHelper.appendStackTrace(callSiteStackTraceLabel || WebInspector.UIString("Call Site stack"), callSiteStackTrace);
var recordStackTrace = record.stackTrace();
if (recordStackTrace)
contentHelper.appendStackTrace(callStackLabel || WebInspector.UIString("Call Stack"), recordStackTrace);
if (record.warnings()) {
var ul = document.createElement("ul");
for (var i = 0; i < record.warnings().length; ++i)
ul.createChild("li").textContent = record.warnings()[i];
contentHelper.appendElementRow(WebInspector.UIString("Warning"), ul);
}
fragment.appendChild(contentHelper.element);
return fragment;
}
/**
* @param {string} recordType
* @param {string=} title
* @return {!Element}
*/
WebInspector.TimelineUIUtilsImpl._createEventDivider = function(recordType, title)
{
var eventDivider = document.createElement("div");
eventDivider.className = "resources-event-divider";
var recordTypes = WebInspector.TimelineModel.RecordType;
if (recordType === recordTypes.MarkDOMContent)
eventDivider.className += " resources-blue-divider";
else if (recordType === recordTypes.MarkLoad)
eventDivider.className += " resources-red-divider";
else if (recordType === recordTypes.MarkFirstPaint)
eventDivider.className += " resources-green-divider";
else if (recordType === recordTypes.TimeStamp)
eventDivider.className += " resources-orange-divider";
else if (recordType === recordTypes.BeginFrame)
eventDivider.className += " timeline-frame-divider";
if (title)
eventDivider.title = title;
return eventDivider;
}
|
tsiry95/openshift-strongloop-cartridge
|
strongloop/node_modules/strong-arc/devtools/frontend/timeline/TimelineUIUtilsImpl.js
|
JavaScript
|
mit
| 31,362
|
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media.Animation;
namespace Magellan.Behaviors
{
/// <summary>
/// Represents a <see cref="Parameter"/> to a <see cref="NavigateAction"/>.
/// </summary>
public class Parameter : Animatable
{
/// <summary>
/// Dependency property for the <see cref="Value"/> property.
/// </summary>
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(object), typeof(Parameter), new UIPropertyMetadata(null));
/// <summary>
/// Gets or sets the name of the parameter.
/// </summary>
/// <value>The name of the parameter.</value>
[Category("Navigation")]
public string ParameterName { get; set; }
/// <summary>
/// Gets or sets the value of the parameter.
/// </summary>
/// <value>The value.</value>
[Category("Navigation")]
public object Value
{
get { return (object)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
protected override Freezable CreateInstanceCore()
{
return (Freezable)Activator.CreateInstance(GetType());
}
}
}
|
galendai/magellan-framework
|
src/Magellan.Behaviors/Parameter.cs
|
C#
|
mit
| 1,343
|
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using Mono.Cecil.Metadata;
namespace Mono.Cecil {
public abstract class TypeSystem {
sealed class CoreTypeSystem : TypeSystem {
public CoreTypeSystem (ModuleDefinition module)
: base (module)
{
}
internal override TypeReference LookupType (string @namespace, string name)
{
var type = LookupTypeDefinition (@namespace, name) ?? LookupTypeForwarded (@namespace, name);
if (type != null)
return type;
throw new NotSupportedException ();
}
TypeReference LookupTypeDefinition (string @namespace, string name)
{
var metadata = module.MetadataSystem;
if (metadata.Types == null)
Initialize (module.Types);
return module.Read (new Row<string, string> (@namespace, name), (row, reader) => {
var types = reader.metadata.Types;
for (int i = 0; i < types.Length; i++) {
if (types [i] == null)
types [i] = reader.GetTypeDefinition ((uint) i + 1);
var type = types [i];
if (type.Name == row.Col2 && type.Namespace == row.Col1)
return type;
}
return null;
});
}
TypeReference LookupTypeForwarded (string @namespace, string name)
{
if (!module.HasExportedTypes)
return null;
var exported_types = module.ExportedTypes;
for (int i = 0; i < exported_types.Count; i++) {
var exported_type = exported_types [i];
if (exported_type.Name == name && exported_type.Namespace == @namespace)
return exported_type.CreateReference ();
}
return null;
}
static void Initialize (object obj)
{
}
}
sealed class CommonTypeSystem : TypeSystem {
AssemblyNameReference corlib;
public CommonTypeSystem (ModuleDefinition module)
: base (module)
{
}
internal override TypeReference LookupType (string @namespace, string name)
{
return CreateTypeReference (@namespace, name);
}
public AssemblyNameReference GetCorlibReference ()
{
if (corlib != null)
return corlib;
const string mscorlib = "mscorlib";
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (reference.Name == mscorlib)
return corlib = reference;
}
corlib = new AssemblyNameReference {
Name = mscorlib,
Version = GetCorlibVersion (),
PublicKeyToken = new byte [] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 },
};
references.Add (corlib);
return corlib;
}
Version GetCorlibVersion ()
{
switch (module.Runtime) {
case TargetRuntime.Net_1_0:
case TargetRuntime.Net_1_1:
return new Version (1, 0, 0, 0);
case TargetRuntime.Net_2_0:
return new Version (2, 0, 0, 0);
case TargetRuntime.Net_4_0:
return new Version (4, 0, 0, 0);
default:
throw new NotSupportedException ();
}
}
TypeReference CreateTypeReference (string @namespace, string name)
{
return new TypeReference (@namespace, name, module, GetCorlibReference ());
}
}
readonly ModuleDefinition module;
TypeReference type_object;
TypeReference type_void;
TypeReference type_bool;
TypeReference type_char;
TypeReference type_sbyte;
TypeReference type_byte;
TypeReference type_int16;
TypeReference type_uint16;
TypeReference type_int32;
TypeReference type_uint32;
TypeReference type_int64;
TypeReference type_uint64;
TypeReference type_single;
TypeReference type_double;
TypeReference type_intptr;
TypeReference type_uintptr;
TypeReference type_string;
TypeReference type_typedref;
TypeSystem (ModuleDefinition module)
{
this.module = module;
}
internal static TypeSystem CreateTypeSystem (ModuleDefinition module)
{
if (module.IsCorlib ())
return new CoreTypeSystem (module);
return new CommonTypeSystem (module);
}
internal abstract TypeReference LookupType (string @namespace, string name);
TypeReference LookupSystemType (ref TypeReference reference, string name, ElementType element_type)
{
lock (module.SyncRoot) {
if (reference != null)
return reference;
var type = LookupType ("System", name);
type.etype = element_type;
return reference = type;
}
}
TypeReference LookupSystemValueType (ref TypeReference typeRef, string name, ElementType element_type)
{
lock (module.SyncRoot) {
if (typeRef != null)
return typeRef;
var type = LookupType ("System", name);
type.etype = element_type;
type.IsValueType = true;
return typeRef = type;
}
}
public IMetadataScope Corlib {
get {
var common = this as CommonTypeSystem;
if (common == null)
return module;
return common.GetCorlibReference ();
}
}
public TypeReference Object {
get { return type_object ?? (LookupSystemType (ref type_object, "Object", ElementType.Object)); }
}
public TypeReference Void {
get { return type_void ?? (LookupSystemType (ref type_void, "Void", ElementType.Void)); }
}
public TypeReference Boolean {
get { return type_bool ?? (LookupSystemValueType (ref type_bool, "Boolean", ElementType.Boolean)); }
}
public TypeReference Char {
get { return type_char ?? (LookupSystemValueType (ref type_char, "Char", ElementType.Char)); }
}
public TypeReference SByte {
get { return type_sbyte ?? (LookupSystemValueType (ref type_sbyte, "SByte", ElementType.I1)); }
}
public TypeReference Byte {
get { return type_byte ?? (LookupSystemValueType (ref type_byte, "Byte", ElementType.U1)); }
}
public TypeReference Int16 {
get { return type_int16 ?? (LookupSystemValueType (ref type_int16, "Int16", ElementType.I2)); }
}
public TypeReference UInt16 {
get { return type_uint16 ?? (LookupSystemValueType (ref type_uint16, "UInt16", ElementType.U2)); }
}
public TypeReference Int32 {
get { return type_int32 ?? (LookupSystemValueType (ref type_int32, "Int32", ElementType.I4)); }
}
public TypeReference UInt32 {
get { return type_uint32 ?? (LookupSystemValueType (ref type_uint32, "UInt32", ElementType.U4)); }
}
public TypeReference Int64 {
get { return type_int64 ?? (LookupSystemValueType (ref type_int64, "Int64", ElementType.I8)); }
}
public TypeReference UInt64 {
get { return type_uint64 ?? (LookupSystemValueType (ref type_uint64, "UInt64", ElementType.U8)); }
}
public TypeReference Single {
get { return type_single ?? (LookupSystemValueType (ref type_single, "Single", ElementType.R4)); }
}
public TypeReference Double {
get { return type_double ?? (LookupSystemValueType (ref type_double, "Double", ElementType.R8)); }
}
public TypeReference IntPtr {
get { return type_intptr ?? (LookupSystemValueType (ref type_intptr, "IntPtr", ElementType.I)); }
}
public TypeReference UIntPtr {
get { return type_uintptr ?? (LookupSystemValueType (ref type_uintptr, "UIntPtr", ElementType.U)); }
}
public TypeReference String {
get { return type_string ?? (LookupSystemType (ref type_string, "String", ElementType.String)); }
}
public TypeReference TypedReference {
get { return type_typedref ?? (LookupSystemValueType (ref type_typedref, "TypedReference", ElementType.TypedByRef)); }
}
}
}
|
SonicZentropy/TyrannyMod.pw
|
cecil-0.9.6/Mono.Cecil/TypeSystem.cs
|
C#
|
mit
| 7,404
|
#!/usr/bin/env
browserify -t babelify -o bundle.js index.js
|
mizchi/arda
|
examples/website-router/build.sh
|
Shell
|
mit
| 61
|
<?php
namespace Oro\Bundle\WorkflowBundle\Exception;
class AssemblerException extends \Exception
{
}
|
Djamy/platform
|
src/Oro/Bundle/WorkflowBundle/Exception/AssemblerException.php
|
PHP
|
mit
| 103
|
package com.reactnativenavigation.parse;
import com.reactnativenavigation.parse.params.Fraction;
import com.reactnativenavigation.parse.params.NullNumber;
import com.reactnativenavigation.parse.params.NullText;
import com.reactnativenavigation.parse.params.Number;
import com.reactnativenavigation.parse.params.Text;
import com.reactnativenavigation.parse.parsers.FractionParser;
import com.reactnativenavigation.parse.parsers.TextParser;
import org.json.JSONObject;
public class Transition {
public Text fromId = new NullText();
public Text toId = new NullText();
public Number startDelay = new NullNumber();
public Number duration = new NullNumber();
public static Transition parse(JSONObject json) {
Transition transition = new Transition();
if (json == null) return transition;
transition.fromId = TextParser.parse(json, "fromId");
transition.toId = TextParser.parse(json, "toId");
Fraction startDelay = FractionParser.parse(json, "startDelay");
if (startDelay.hasValue()) {
transition.startDelay = new Number((int) (startDelay.get() * 1000));
}
Fraction duration = FractionParser.parse(json, "duration");
if (duration.hasValue()) {
transition.duration = new Number((int) (duration.get() * 1000));
}
return transition;
}
void mergeWith(Transition other) {
if (other.fromId.hasValue()) fromId = other.fromId;
if (other.toId.hasValue()) toId = other.toId;
if (other.startDelay.hasValue()) startDelay = other.startDelay;
if (other.duration.hasValue()) duration = other.duration;
}
void mergeWithDefault(Transition defaultOptions) {
if (!fromId.hasValue()) fromId = defaultOptions.fromId;
if (!toId.hasValue()) toId = defaultOptions.toId;
if (!startDelay.hasValue()) startDelay = defaultOptions.startDelay;
if (!duration.hasValue()) duration = defaultOptions.duration;
}
}
|
Jpoliachik/react-native-navigation
|
lib/android/app/src/main/java/com/reactnativenavigation/parse/Transition.java
|
Java
|
mit
| 1,997
|
# [Boost.Any](https://boost.org/libs/any)
Boost.Any is a part of the [Boost C++ Libraries](https://github.com/boostorg). It is a safe, generic container for single values of different value types.
### Test results
@ | Build | Tests coverage | More info
----------------|-------------- | -------------- |-----------
Develop branch: | [](https://github.com/boostorg/any/actions/workflows/ci.yml) [](https://ci.appveyor.com/project/apolukhin/any/branch/develop) | [](https://coveralls.io/r/boostorg/any?branch=develop) | [details...](https://www.boost.org/development/tests/develop/developer/any.html)
Master branch: | [](https://github.com/boostorg/any/actions/workflows/ci.yml) [](https://ci.appveyor.com/project/apolukhin/any/branch/master) | [](https://coveralls.io/r/boostorg/any?branch=master) | [details...](https://www.boost.org/development/tests/master/developer/any.html)
[Latest developer documentation](https://www.boost.org/doc/libs/develop/doc/html/any.html)
### License
Distributed under the [Boost Software License, Version 1.0](https://boost.org/LICENSE_1_0.txt).
|
davehorton/drachtio-server
|
deps/boost_1_77_0/libs/any/README.md
|
Markdown
|
mit
| 1,680
|
src = ../src
services = $(src)/services
favicons = $(src)/favicons
build = .
main = ..
modules = $(src)/core.js $(services)/*.js
service_list = ../download/services.json
jls = $(main)/jquery.lifestream.js
jls_min = $(main)/jquery.lifestream.min.js
jls_css = $(main)/css/lifestream.css
uglifyjs = ../download/js/uglifyjs-cs.js
uglifyjs_min = ../download/js/uglifyjs-cs.min.js
script = ../download/js/script.js
script_min = ../download/js/script.min.js
.PHONY: all jls jls-min jls-css uglifyjs uglifyjs-min service-list script-min
all: jls jls-min jls-css uglifyjs uglifyjs-min service-list script-min
jls: $(jls)
jls-min: $(jls_min)
jls-css:
@echo "Building $@"
@node compile-css.js $(favicons) > $(jls_css)
uglifyjs: $(uglifyjs)
uglifyjs-min: $(uglifyjs_min)
script-min: $(script_min)
service-list:
@echo "Building $(service_list)"
@node service-list.js $(services) > $(service_list)
$(jls): $(modules) | $(main)
@echo "Building $@"
@cat $^ > $@
$(jls_min): $(jls)
@echo "Building $@"
@uglifyjs $^ --compress --mangle --comments > $@
$(uglifyjs): uglifyjs-cs-prologue.js parse-js-prologue.js parse-js.js \
parse-js-epilogue.js process-prologue.js process.js process-epilogue.js \
squeeze-more-prologue.js squeeze-more.js squeeze-more-epilogue.js \
uglifyjs-cs-epilogue.js
@echo "Building $@"
@cat $^ > $@
$(uglifyjs_min): $(uglifyjs)
@echo "Building $@"
@uglifyjs $^ --compress --mangle --comments > $@
$(script_min): $(script)
@echo "Building $@"
@uglifyjs $^ --compress --mangle --comments > $@
|
eldabbagh/jquery-lifestream
|
build/Makefile
|
Makefile
|
mit
| 1,525
|
'use strict';
// copied from http://www.broofa.com/Tools/Math.uuid.js
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
.split('');
exports.uuid = function () {
var chars = CHARS, uuid = new Array(36), rnd=0, r;
for (var i = 0; i < 36; i++) {
if (i===8 || i===13 || i===18 || i===23) {
uuid[i] = '-';
}
else if (i===14) {
uuid[i] = '4';
}
else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
r = rnd & 0xf;
rnd = rnd >> 4;
uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
}
}
return uuid.join('');
};
exports.in_array = function (item, array) {
if (!array) return false;
if (!Array.isArray(array)) return false;
return (array.indexOf(item) !== -1);
};
exports.to_object = function (array) {
if (typeof array === 'string') {
array = array.split(/[\s,;]+/);
}
if (!Array.isArray(array)) {
throw "arguments to to_object must be a string or array";
}
var rv = {};
for (var i = 0; i < array.length; i++) {
if (array[i] === undefined) { continue; }
rv[array[i]] = true;
}
return rv;
};
exports.sort_keys = function (obj) {
return Object.keys(obj).sort();
};
exports.uniq = function (arr) {
var out = [];
var o = 0;
for (var i=0,l=arr.length; i < l; i++) {
if (out.length === 0) {
out.push(arr[i]);
}
else if (out[o] !== arr[i]) {
out.push(arr[i]);
o++;
}
}
return out;
};
exports.extend = function (target) {
// http://stackoverflow.com/questions/14974864/
var sources = [].slice.call(arguments, 1);
sources.forEach(function (source) {
for (var prop in source) {
target[prop] = source[prop];
}
});
return target;
};
exports.ISODate = function (d) {
function pad(n) { return n<10 ? '0'+n : n; }
return d.getUTCFullYear()+'-' +
pad(d.getUTCMonth()+1)+'-' +
pad(d.getUTCDate())+'T' +
pad(d.getUTCHours())+':' +
pad(d.getUTCMinutes())+':' +
pad(d.getUTCSeconds())+'Z' ;
};
var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _monnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function _pad (num, n, p) {
var s = '' + num;
p = p || '0';
while (s.length < n) s = p + s;
return s;
}
exports.pad = _pad;
exports.date_to_str = function (d) {
return _daynames[d.getDay()] + ', ' + _pad(d.getDate(),2) + ' ' +
_monnames[d.getMonth()] + ' ' + d.getFullYear() + ' ' +
_pad(d.getHours(),2) + ':' + _pad(d.getMinutes(),2) + ':' +
_pad(d.getSeconds(),2) +
' ' + d.toString().match(/\sGMT([+-]\d+)/)[1];
};
exports.decode_qp = function (line) {
line = line.replace(/\r\n/g,"\n").replace(/[ \t]+\r?\n/g,"\n");
if (! /=/.test(line)) {
// this may be a pointless optimisation...
return new Buffer(line);
}
line = line.replace(/=\n/mg, '');
var buf = new Buffer(line.length);
var pos = 0;
for (var i=0,l=line.length; i < l; i++) {
if (line[i] === '=' &&
/=[0-9a-fA-F]{2}/.test(line[i] + line[i+1] + line[i+2])) {
i++;
buf[pos] = parseInt(line[i] + line[i+1], 16);
i++;
}
else {
buf[pos] = line.charCodeAt(i);
}
pos++;
}
return buf.slice(0, pos);
};
function _char_to_qp (ch) {
return "=" + _pad(ch.charCodeAt(0).toString(16).toUpperCase(), 2);
}
// Shameless attempt to copy from Perl's MIME::QuotedPrint::Perl code.
exports.encode_qp = function (str) {
str = str.replace(
/([^\ \t\n!"#\$%&'()*+,\-.\/0-9:;<>?\@A-Z\[\\\]^_`a-z{|}~])/g,
function (orig, p1) {
return _char_to_qp(p1);
}
).replace(/([ \t]+)$/gm, function (orig, p1) {
return p1.split('').map(_char_to_qp).join('');
});
// Now shorten lines to 76 chars, but don't break =XX encodes.
// Method: iterate over to char 73.
// If char 74, 75 or 76 is = we need to break before the =.
// Otherwise break at 76.
var cur_length = 0;
var out = '';
for (var i=0; i<str.length; i++) {
if (str[i] === '\n') {
out += '\n';
cur_length = 0;
continue;
}
cur_length++;
if (cur_length <= 73) {
out += str[i];
}
else if (cur_length > 73 && cur_length < 76) {
if (str[i] === '=') {
out += '=\n=';
cur_length = 1;
}
else {
out += str[i];
}
}
else {
// Otherwise got to char 76
// Don't insert '=\n' if end of string or next char is already \n:
if ((i === (str.length - 1)) || (str[i+1] === '\n')) {
out += str[i];
}
else {
out += '=\n' + str[i];
cur_length = 1;
}
}
}
return out;
};
exports.node_min = function (min, cur) {
var wants = min.split('.');
var has = (cur || process.version.substring(1)).split('.');
for (var i=0; i<=3; i++) {
// note use of unary + for fast type conversion to num
if (+has[i] > +wants[i]) { return true; }
if (+has[i] < +wants[i]) { return false; }
}
// they're identical
return true;
};
exports.existsSync =
require(exports.node_min('0.8') ? 'fs' : 'path').existsSync;
exports.indexOfLF = function (buf, maxlength) {
for (var i=0; i<buf.length; i++) {
if (maxlength && (i === maxlength)) break;
if (buf[i] === 0x0a) return i;
}
return -1;
};
exports.prettySize = function (size) {
if (size === 0 || !size) return 0;
var i = Math.floor(Math.log(size)/Math.log(1024));
var units = ['B', 'kB', 'MB', 'GB', 'TB'];
return (size/Math.pow(1024,i)).toFixed(2) * 1 + '' + units[i];
};
exports.valid_regexes = function (list, file) {
// list: an array of regexes. file: the file name containing the regex list
var valid = [];
for (var i=0; i<list.length; i++) {
try {
new RegExp(list[i]);
}
catch (e) {
require('./logger')
.logerror("invalid regex in " + file + ", " + list[i]);
continue;
}
valid.push(list[i]);
}
return valid; // returns a list of valid regexes
};
exports.regexp_escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
exports.base64 = function (str) {
return new Buffer(str, "UTF-8").toString("base64");
};
exports.unbase64 = function (str) {
return new Buffer(str, "base64").toString("UTF-8");
};
// Fisher-Yates shuffle
// http://bost.ocks.org/mike/shuffle/
exports.shuffle = function(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
};
exports.elapsed = function (start, decimal_places) {
var diff = (Date.now() - start) / 1000; // in seconds
if (decimal_places === undefined) {
decimal_places = diff > 5 ? 0 : diff > 2 ? 1 : 2;
}
else {
decimal_places = parseInt(decimal_places);
if (isNaN(decimal_places)) {
decimal_places = 2;
}
}
return diff.toFixed(decimal_places);
};
exports.wildcard_to_regexp = function (str) {
return str
.replace(/[-\[\]\/{}()*+?.,\\^$|#\s]/g, "\\$&")
.replace('\\*', '.*')
.replace('\\?', '.') + '$';
};
|
danucalovj/Haraka
|
utils.js
|
JavaScript
|
mit
| 7,940
|
"use strict";
/*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasicBlockStartState = void 0;
// ConvertTo-TS run at 2016-10-04T11:26:27.7669801-07:00
const ATNStateType_1 = require("./ATNStateType");
const BlockStartState_1 = require("./BlockStartState");
const Decorators_1 = require("../Decorators");
/**
*
* @author Sam Harwell
*/
class BasicBlockStartState extends BlockStartState_1.BlockStartState {
get stateType() {
return ATNStateType_1.ATNStateType.BLOCK_START;
}
}
__decorate([
Decorators_1.Override
], BasicBlockStartState.prototype, "stateType", null);
exports.BasicBlockStartState = BasicBlockStartState;
//# sourceMappingURL=BasicBlockStartState.js.map
|
glenngillen/dotfiles
|
.vscode/extensions/juanblanco.solidity-0.0.120/node_modules/antlr4ts/atn/BasicBlockStartState.js
|
JavaScript
|
mit
| 1,486
|
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>lxml.etree.DTD</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="lxml-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="/">lxml API</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="lxml-module.html">Package lxml</a> ::
<a href="lxml.etree-module.html">Module etree</a> ::
Class DTD
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="lxml.etree.DTD-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class DTD</h1><p class="nomargin-top"></p>
<pre class="base-tree">
object --+
|
<a href="lxml.etree._Validator-class.html" onclick="show_private();">_Validator</a> --+
|
<strong class="uidshort">DTD</strong>
</pre>
<hr />
<p>DTD(self, file=None, external_id=None)
A DTD validator.</p>
<p>Can load from filesystem directly given a filename or file-like object.
Alternatively, pass the keyword parameter <tt class="rst-docutils literal">external_id</tt> to load from a
catalog.</p>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="lxml.etree.DTD-class.html#__call__" class="summary-sig-name">__call__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">etree</span>)</span><br />
Validate doc using the DTD.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="lxml.etree.DTD-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">file</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">external_id</span>=<span class="summary-sig-default">None</span>)</span><br />
x.__init__(...) initializes x; see help(type(x)) for signature</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type">a new object with type S, a subtype of T</span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="lxml.etree.DTD-class.html#__new__" class="summary-sig-name">__new__</a>(<span class="summary-sig-arg">T</span>,
<span class="summary-sig-arg">S</span>,
<span class="summary-sig-arg">...</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="elements"></a><span class="summary-sig-name">elements</span>(<span class="summary-sig-arg">...</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="entities"></a><span class="summary-sig-name">entities</span>(<span class="summary-sig-arg">...</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="iterelements"></a><span class="summary-sig-name">iterelements</span>(<span class="summary-sig-arg">...</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="iterentities"></a><span class="summary-sig-name">iterentities</span>(<span class="summary-sig-arg">...</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="lxml.etree._Validator-class.html" onclick="show_private();">_Validator</a></code></b>:
<code><a href="lxml.etree._Validator-class.html#assertValid">assertValid</a></code>,
<code><a href="lxml.etree._Validator-class.html#assert_">assert_</a></code>,
<code><a href="lxml.etree._Validator-class.html#validate">validate</a></code>
</p>
<div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="lxml.etree._Validator-class.html" onclick="show_private();">_Validator</a></code></b> (private):
<code><a href="lxml.etree._Validator-class.html#_append_log_message" onclick="show_private();">_append_log_message</a></code>,
<code><a href="lxml.etree._Validator-class.html#_clear_error_log" onclick="show_private();">_clear_error_log</a></code>
</p></div>
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__delattr__</code>,
<code>__format__</code>,
<code>__getattribute__</code>,
<code>__hash__</code>,
<code>__reduce__</code>,
<code>__reduce_ex__</code>,
<code>__repr__</code>,
<code>__setattr__</code>,
<code>__sizeof__</code>,
<code>__str__</code>,
<code>__subclasshook__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="external_id"></a><span class="summary-name">external_id</span>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="name"></a><span class="summary-name">name</span>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="system_url"></a><span class="summary-name">system_url</span>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="lxml.etree._Validator-class.html" onclick="show_private();">_Validator</a></code></b>:
<code><a href="lxml.etree._Validator-class.html#error_log">error_log</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__call__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__call__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">etree</span>)</span>
<br /><em class="fname">(Call operator)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Validate doc using the DTD.</p>
<p>Returns true if the document is valid, false if not.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="__init__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">file</span>=<span class="sig-default">None</span>,
<span class="sig-arg">external_id</span>=<span class="sig-default">None</span>)</span>
<br /><em class="fname">(Constructor)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
x.__init__(...) initializes x; see help(type(x)) for signature
<dl class="fields">
<dt>Overrides:
object.__init__
</dt>
</dl>
</td></tr></table>
</div>
<a name="__new__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__new__</span>(<span class="sig-arg">T</span>,
<span class="sig-arg">S</span>,
<span class="sig-arg">...</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<dl class="fields">
<dt>Returns: a new object with type S, a subtype of T</dt>
<dt>Overrides:
object.__new__
</dt>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="lxml-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="/">lxml API</a></th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Sat Apr 25 16:24:35 2015
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
|
bertucho/epic-movie-quotes-quiz
|
dialogos/build/lxml/doc/html/api/lxml.etree.DTD-class.html
|
HTML
|
mit
| 15,689
|
/*! jQuery UI - v1.10.3 - 2013-09-04
* http://jqueryui.com
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.sk={closeText:"Zavrieť",prevText:"<Predchádzajúci",nextText:"Nasledujúci>",currentText:"Dnes",monthNames:["január","február","marec","apríl","máj","jún","júl","august","september","október","november","december"],monthNamesShort:["Jan","Feb","Mar","Apr","Máj","Jún","Júl","Aug","Sep","Okt","Nov","Dec"],dayNames:["nedeľa","pondelok","utorok","streda","štvrtok","piatok","sobota"],dayNamesShort:["Ned","Pon","Uto","Str","Štv","Pia","Sob"],dayNamesMin:["Ne","Po","Ut","St","Št","Pia","So"],weekHeader:"Ty",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.sk)});
|
livingsocial/rearview-engine
|
public/rearview/vendor/jquery/plugins/jquery-ui/development-bundle/ui/minified/i18n/jquery.ui.datepicker-sk.min.js
|
JavaScript
|
mit
| 840
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var tape = require('tape');
var zlib = require('../');
tape('zero byte', function(t) {
t.plan(2);
var gz = zlib.Gzip()
var emptyBuffer = new Buffer(0);
var received = 0;
gz.on('data', function(c) {
received += c.length;
});
gz.on('end', function() {
t.equal(received, 20);
});
gz.on('finish', function() {
t.ok(true);
});
gz.write(emptyBuffer);
gz.end();
});
|
Moccine/global-service-plus.com
|
web/libariries/bootstrap/node_modules/browserify-zlib/test/test-zlib-zero-byte.js
|
JavaScript
|
mit
| 1,571
|
<?php
namespace Chamilo\Application\Weblcms\Tool\Implementation\Link\Component;
use Chamilo\Application\Weblcms\Tool\Implementation\Link\Manager;
class CategoryMoverComponent extends Manager
{
public function get_additional_parameters()
{
return array(\Chamilo\Application\Weblcms\Tool\Manager::PARAM_PUBLICATION_ID);
}
}
|
cosnics/cosnics
|
src/Chamilo/Application/Weblcms/Tool/Implementation/Link/Component/CategoryMoverComponent.php
|
PHP
|
mit
| 345
|
/**
* $Id: learning_path_item.js 216 2009-11-13 14:08:06Z kariboe $
* @package application.lib.weblcms.tool.learning_path.javascript
*/
/**
* @author Sven Vanpoucke
*/
(function($) {
$(window).bind('beforeunload', function(e) {
var ajaxUri = getPath('WEB_PATH') + 'index.php';
var parameters = {
'application' : trackerContext,
'go' : 'leave_item',
'tracker_id' : trackerId
};
var response = $.ajax({
type : "POST",
url : ajaxUri,
data : parameters,
async : false
});
});
})(jQuery);
|
cosnicsTHLU/cosnics
|
src/Chamilo/Core/Repository/ContentObject/LearningPath/Display/Resources/Javascript/LearningPathItem.js
|
JavaScript
|
mit
| 547
|
// Flags: --expose-internals
'use strict';
const common = require('../common');
if (!common.hasCrypto) common.skip('missing crypto');
const fixtures = require('../common/fixtures');
// Test --trace-tls CLI flag.
const assert = require('assert');
const { fork } = require('child_process');
if (process.argv[2] === 'test')
return test();
const binding = require('internal/test/binding').internalBinding;
if (!binding('tls_wrap').HAVE_SSL_TRACE)
return common.skip('no SSL_trace() compiled into openssl');
const child = fork(__filename, ['test'], {
silent: true,
execArgv: ['--trace-tls']
});
let stdout = '';
let stderr = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (data) => stdout += data);
child.stderr.on('data', (data) => stderr += data);
child.on('close', common.mustCall((code, signal) => {
// For debugging and observation of actual trace output.
console.log(stderr);
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
assert.strictEqual(stdout.trim(), '');
assert(/Warning: Enabling --trace-tls can expose sensitive/.test(stderr));
assert(/Sent Record/.test(stderr));
}));
function test() {
const {
connect, keys
} = require(fixtures.path('tls-connect'));
connect({
client: {
checkServerIdentity: (servername, cert) => { },
ca: `${keys.agent1.cert}\n${keys.agent6.ca}`,
},
server: {
cert: keys.agent6.cert,
key: keys.agent6.key
},
}, common.mustCall((err, pair, cleanup) => {
if (pair.server.err) {
console.trace('server', pair.server.err);
}
if (pair.client.err) {
console.trace('client', pair.client.err);
}
assert.ifError(pair.server.err);
assert.ifError(pair.client.err);
return cleanup();
}));
}
|
enclose-io/compiler
|
lts/test/parallel/test-tls-enable-trace-cli.js
|
JavaScript
|
mit
| 1,799
|
'use strict';
var fs = require('fs');
var Promise = require('../ext/promise');
var readFile = Promise.denodeify(fs.readFile);
var lstat = Promise.denodeify(fs.stat);
var chalk = require('chalk');
var EditFileDiff = require('./edit-file-diff');
var EOL = require('os').EOL;
var isBinaryFile = require('isbinaryfile').sync;
var canEdit = require('../utilities/open-editor').canEdit;
function processTemplate(content, context) {
var options = {
evaluate: /<%([\s\S]+?)%>/g,
interpolate: /<%=([\s\S]+?)%>/g,
escape: /<%-([\s\S]+?)%>/g
};
return require('lodash.template')(content, options)(context);
}
function diffHighlight(line) {
if (line[0] === '+') {
return chalk.green(line);
} else if (line[0] === '-') {
return chalk.red(line);
} else if (line.match(/^@@/)) {
return chalk.cyan(line);
} else {
return line;
}
}
FileInfo.prototype.confirmOverwrite = function(path) {
var promptOptions = {
type: 'expand',
name: 'answer',
default: false,
message: chalk.red('Overwrite') + ' ' + path + '?',
choices: [
{ key: 'y', name: 'Yes, overwrite', value: 'overwrite' },
{ key: 'n', name: 'No, skip', value: 'skip' }
]
};
var outputPathIsFile = false;
try { outputPathIsFile = fs.statSync(this.outputPath).isFile(); } catch (err) { /* ignore */ }
var canDiff = (
!isBinaryFile(this.inputPath) && (
!outputPathIsFile ||
!isBinaryFile(this.outputPath)
)
);
if (canDiff) {
promptOptions.choices.push({ key: 'd', name: 'Diff', value: 'diff' });
if (canEdit()) {
promptOptions.choices.push({ key: 'e', name: 'Edit', value: 'edit' });
}
}
return this.ui.prompt(promptOptions)
.then(function(response) {
return response.answer;
});
};
FileInfo.prototype.displayDiff = function() {
var info = this,
jsdiff = require('diff');
return Promise.hash({
input: this.render(),
output: readFile(info.outputPath)
}).then(function(result) {
var diff = jsdiff.createPatch(
info.outputPath, result.output.toString(), result.input
);
var lines = diff.split('\n');
for (var i = 0; i < lines.length; i++) {
info.ui.write(
diffHighlight(lines[i] + EOL)
);
}
});
};
function FileInfo(options) {
this.action = options.action;
this.outputBasePath = options.outputBasePath;
this.outputPath = options.outputPath;
this.displayPath = options.displayPath;
this.inputPath = options.inputPath;
this.templateVariables = options.templateVariables;
this.ui = options.ui;
}
FileInfo.prototype.render = function() {
var path = this.inputPath,
context = this.templateVariables;
if (!this.rendered) {
this.rendered = readFile(path).then(function(content) {
return lstat(path).then(function(fileStat) {
if (isBinaryFile(content, fileStat.size)) {
return content;
} else {
try {
return processTemplate(content.toString(), context);
} catch (err) {
err.message += ' (Error in blueprint template: ' + path + ')';
throw err;
}
}
});
});
}
return this.rendered;
};
FileInfo.prototype.checkForConflict = function() {
return new Promise(function (resolve, reject) {
fs.exists(this.outputPath, function (doesExist, error) {
if (error) {
reject(error);
return;
}
var result;
if (doesExist) {
result = Promise.hash({
input: this.render(),
output: readFile(this.outputPath)
}).then(function(result) {
var type;
if (result.input.toString() === result.output.toString()) {
type = 'identical';
} else {
type = 'confirm';
}
return type;
}.bind(this));
} else {
result = 'none';
}
resolve(result);
}.bind(this));
}.bind(this));
};
FileInfo.prototype.confirmOverwriteTask = function() {
var info = this;
return function() {
return new Promise(function(resolve, reject) {
function doConfirm() {
info.confirmOverwrite(info.displayPath).then(function(action) {
if (action === 'diff') {
info.displayDiff().then(doConfirm, reject);
} else if (action === 'edit') {
var editFileDiff = new EditFileDiff({info: info});
editFileDiff.edit().then(function() {
info.action = action;
resolve(info);
}).catch(function() {
doConfirm()
.finally(function() {
resolve(info);
});
});
} else {
info.action = action;
resolve(info);
}
}, reject);
}
doConfirm();
});
}.bind(this);
};
module.exports = FileInfo;
|
xtian/ember-cli
|
lib/models/file-info.js
|
JavaScript
|
mit
| 4,920
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Core;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
[JsonConverter(typeof(CustomDataSourceLinkedServiceConverter))]
public partial class CustomDataSourceLinkedService : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("typeProperties");
writer.WriteObjectValue(TypeProperties);
writer.WritePropertyName("type");
writer.WriteStringValue(Type);
if (Optional.IsDefined(ConnectVia))
{
writer.WritePropertyName("connectVia");
writer.WriteObjectValue(ConnectVia);
}
if (Optional.IsDefined(Description))
{
writer.WritePropertyName("description");
writer.WriteStringValue(Description);
}
if (Optional.IsCollectionDefined(Parameters))
{
writer.WritePropertyName("parameters");
writer.WriteStartObject();
foreach (var item in Parameters)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
if (Optional.IsCollectionDefined(Annotations))
{
writer.WritePropertyName("annotations");
writer.WriteStartArray();
foreach (var item in Annotations)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
}
foreach (var item in AdditionalProperties)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
internal static CustomDataSourceLinkedService DeserializeCustomDataSourceLinkedService(JsonElement element)
{
object typeProperties = default;
string type = default;
Optional<IntegrationRuntimeReference> connectVia = default;
Optional<string> description = default;
Optional<IDictionary<string, ParameterSpecification>> parameters = default;
Optional<IList<object>> annotations = default;
IDictionary<string, object> additionalProperties = default;
Dictionary<string, object> additionalPropertiesDictionary = new Dictionary<string, object>();
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("typeProperties"))
{
typeProperties = property.Value.GetObject();
continue;
}
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("connectVia"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
connectVia = IntegrationRuntimeReference.DeserializeIntegrationRuntimeReference(property.Value);
continue;
}
if (property.NameEquals("description"))
{
description = property.Value.GetString();
continue;
}
if (property.NameEquals("parameters"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
Dictionary<string, ParameterSpecification> dictionary = new Dictionary<string, ParameterSpecification>();
foreach (var property0 in property.Value.EnumerateObject())
{
dictionary.Add(property0.Name, ParameterSpecification.DeserializeParameterSpecification(property0.Value));
}
parameters = dictionary;
continue;
}
if (property.NameEquals("annotations"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
List<object> array = new List<object>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(item.GetObject());
}
annotations = array;
continue;
}
additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject());
}
additionalProperties = additionalPropertiesDictionary;
return new CustomDataSourceLinkedService(type, connectVia.Value, description.Value, Optional.ToDictionary(parameters), Optional.ToList(annotations), additionalProperties, typeProperties);
}
internal partial class CustomDataSourceLinkedServiceConverter : JsonConverter<CustomDataSourceLinkedService>
{
public override void Write(Utf8JsonWriter writer, CustomDataSourceLinkedService model, JsonSerializerOptions options)
{
writer.WriteObjectValue(model);
}
public override CustomDataSourceLinkedService Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using var document = JsonDocument.ParseValue(ref reader);
return DeserializeCustomDataSourceLinkedService(document.RootElement);
}
}
}
}
|
ayeletshpigelman/azure-sdk-for-net
|
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/CustomDataSourceLinkedService.Serialization.cs
|
C#
|
mit
| 6,356
|
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Simplification;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Orleans.Analyzers
{
[ExportCodeFixProvider(LanguageNames.CSharp)]
public class GenerateOrleansSerializationAttributesCodeFix : CodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(GenerateSerializationAttributesAnalyzer.RuleId, GenerateGenerateSerializerAttributeAnalyzer.RuleId);
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken);
var declaration = root.FindNode(context.Span).FirstAncestorOrSelf<TypeDeclarationSyntax>();
foreach (var diagnostic in context.Diagnostics)
{
switch (diagnostic.Id)
{
case GenerateSerializationAttributesAnalyzer.RuleId:
context.RegisterCodeFix(
CodeAction.Create("Generate serialization attributes", cancellationToken => AddSerializationAttributes(declaration, context, cancellationToken), equivalenceKey: GenerateSerializationAttributesAnalyzer.RuleId),
diagnostic);
context.RegisterCodeFix(
CodeAction.Create("Mark properties and fields [NonSerialized]", cancellationToken => AddNonSerializedAttributes(root, declaration, context, cancellationToken), equivalenceKey: GenerateSerializationAttributesAnalyzer.RuleId + "NonSerialized"),
diagnostic);
break;
case GenerateGenerateSerializerAttributeAnalyzer.RuleId:
context.RegisterCodeFix(
CodeAction.Create("Add [GenerateSerializer] attribute", cancellationToken => AddGenerateSerializerAttribute(declaration, context, cancellationToken), equivalenceKey: GenerateGenerateSerializerAttributeAnalyzer.RuleId),
diagnostic);
break;
}
}
}
private static async Task<Document> AddGenerateSerializerAttribute(TypeDeclarationSyntax declaration, CodeFixContext context, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken).ConfigureAwait(false);
// Add the [GenerateSerializer] attribute
var attribute = Attribute(ParseName(Constants.GenerateSerializerAttributeFullyQualifiedName))
.WithAdditionalAnnotations(Simplifier.Annotation);
editor.AddAttribute(declaration, attribute);
return editor.GetChangedDocument();
}
private static async Task<Document> AddSerializationAttributes(TypeDeclarationSyntax declaration, CodeFixContext context, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken).ConfigureAwait(false);
var (serializableMembers, _, nextId) = SerializationAttributesHelper.AnalyzeTypeDeclaration(declaration);
foreach (var member in serializableMembers)
{
// Add the [Id(x)] attribute
var attribute = Attribute(ParseName(Constants.IdAttributeFullyQualifiedName))
.AddArgumentListArguments(AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)nextId++))))
.WithAdditionalAnnotations(Simplifier.Annotation);
editor.AddAttribute(member, attribute);
}
return editor.GetChangedDocument();
}
private static async Task<Document> AddNonSerializedAttributes(SyntaxNode root, TypeDeclarationSyntax declaration, CodeFixContext context, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken).ConfigureAwait(false);
var (serializableMembers, _, _) = SerializationAttributesHelper.AnalyzeTypeDeclaration(declaration);
var insertUsingDirective = true;
var ns = root.DescendantNodesAndSelf()
.OfType<UsingDirectiveSyntax>()
.FirstOrDefault(directive => string.Equals(directive.Name.ToString(), Constants.SystemNamespace));
if (ns is object)
{
insertUsingDirective = false;
}
if (insertUsingDirective)
{
var usingDirective = UsingDirective(IdentifierName(Constants.SystemNamespace)).WithTrailingTrivia(EndOfLine("\r\n"));
var lastUsing = root.DescendantNodesAndSelf().OfType<UsingDirectiveSyntax>().LastOrDefault();
if (lastUsing is object)
{
editor.InsertAfter(lastUsing, usingDirective);
}
else if (root.DescendantNodesAndSelf().OfType<NamespaceDeclarationSyntax>().FirstOrDefault() is NamespaceDeclarationSyntax firstNamespace)
{
editor.InsertBefore(lastUsing, usingDirective);
}
else if (root.DescendantNodesAndSelf().FirstOrDefault() is SyntaxNode firstNode)
{
editor.InsertBefore(firstNode, usingDirective);
}
}
foreach (var member in serializableMembers)
{
// Add the [NonSerialized] attribute
var attribute = AttributeList().AddAttributes(Attribute(ParseName(Constants.NonSerializedAttributeFullyQualifiedName)).WithAdditionalAnnotations(Simplifier.Annotation));
// Since [NonSerialized] is a field-only attribute, add the field target specifier.
if (member is PropertyDeclarationSyntax)
{
attribute = attribute.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.FieldKeyword)));
}
editor.AddAttribute(member, attribute);
}
return editor.GetChangedDocument();
}
}
}
|
veikkoeeva/orleans
|
src/Orleans.Analyzers/GenerateSerializationAttributesCodeFix.cs
|
C#
|
mit
| 6,691
|
/** @license React v16.8.2
* react-dom-unstable-fizz.node.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';function d(a,b){var c="<"+a+">";"string"===typeof b.children&&(c+=b.children);return Buffer.from(c+("</"+a+">"),"utf8")}var e="function"===typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function f(a){var b=a.destination,c=a.completedChunks;a.completedChunks=[];b.cork();try{for(a=0;a<c.length;a++)b.write(c[a])}finally{b.uncork()}b.end()}
function g(a){a.flowing=!0;setImmediate(function(){var b=a.children;a.children=null;if(!b||b.$$typeof===e){var c=b.type;b=b.props;"string"===typeof c&&(a.completedChunks.push(d(c,b)),a.flowing&&f(a),c=a.destination,"function"===typeof c.flush&&c.flush())}})}function h(a,b){return function(){b.flowing=!1;f(b)}}var k={pipeToNodeWritable:function(a,b){a={destination:b,children:a,completedChunks:[],flowing:!1};b.on("drain",h(b,a));g(a)}},l={default:k},m=l&&k||l;module.exports=m.default||m;
|
joeyparrish/cdnjs
|
ajax/libs/react-dom/16.8.2/cjs/react-dom-unstable-fizz.node.production.min.js
|
JavaScript
|
mit
| 1,122
|
!function(){function t(t){return function(e,i){e=d3.hsl(e),i=d3.hsl(i);var r=(e.h+120)*a,h=(i.h+120)*a-r,s=e.s,l=i.s-s,o=e.l,u=i.l-o;return isNaN(l)&&(l=0,s=isNaN(s)?i.s:s),isNaN(h)&&(h=0,r=isNaN(r)?i.h:r),function(a){var e=r+h*a,i=Math.pow(o+u*a,t),c=(s+l*a)*i*(1-i);return"#"+n(i+c*(-.14861*Math.cos(e)+1.78277*Math.sin(e)))+n(i+c*(-.29227*Math.cos(e)-.90649*Math.sin(e)))+n(i+c*1.97294*Math.cos(e))}}}function n(t){var n=(t=0>=t?0:t>=1?255:0|255*t).toString(16);return 16>t?"0"+n:n}var a=Math.PI/180;d3.scale.cubehelix=function(){return d3.scale.linear().range([d3.hsl(300,.5,0),d3.hsl(-240,.5,1)]).interpolate(d3.interpolateCubehelix)},d3.interpolateCubehelix=t(1),d3.interpolateCubehelix.gamma=t}();
|
ucsd-ccbb/Oncolist
|
src/frontEndUI/Prod/js/cubehelix.min.js
|
JavaScript
|
mit
| 705
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Background Information</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../index.html" title="Boost.Regex 5.1.1">
<link rel="up" href="../index.html" title="Boost.Regex 5.1.1">
<link rel="prev" href="ref/internal_details/uni_iter.html" title="Unicode Iterators">
<link rel="next" href="background_information/headers.html" title="Headers">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="ref/internal_details/uni_iter.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="background_information/headers.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="boost_regex.background_information"></a><a class="link" href="background_information.html" title="Background Information">Background Information</a>
</h2></div></div></div>
<div class="toc"><dl>
<dt><span class="section"><a href="background_information/headers.html">Headers</a></span></dt>
<dt><span class="section"><a href="background_information/locale.html">Localization</a></span></dt>
<dt><span class="section"><a href="background_information/thread_safety.html">Thread
Safety</a></span></dt>
<dt><span class="section"><a href="background_information/examples.html">Test and
Example Programs</a></span></dt>
<dt><span class="section"><a href="background_information/futher.html">References
and Further Information</a></span></dt>
<dt><span class="section"><a href="background_information/faq.html">FAQ</a></span></dt>
<dt><span class="section"><a href="background_information/performance.html">Performance</a></span></dt>
<dd><dl>
<dt><span class="section"><a href="background_information/performance/section_Testing_Perl_searches_platform_Windows_x64_compiler_Microsoft_Visual_C_version_14_0_.html">Testing
Perl searches (platform = Windows x64, compiler = Microsoft Visual C++ version
14.0)</a></span></dt>
<dt><span class="section"><a href="background_information/performance/section_Testing_Perl_searches_platform_linux_compiler_GNU_C_version_5_1_0_.html">Testing
Perl searches (platform = linux, compiler = GNU C++ version 5.1.0)</a></span></dt>
<dt><span class="section"><a href="background_information/performance/section_Testing_leftmost_longest_searches_platform_Windows_x64_compiler_Microsoft_Visual_C_version_14_0_.html">Testing
leftmost-longest searches (platform = Windows x64, compiler = Microsoft Visual
C++ version 14.0)</a></span></dt>
<dt><span class="section"><a href="background_information/performance/section_Testing_leftmost_longest_searches_platform_linux_compiler_GNU_C_version_5_1_0_.html">Testing
leftmost-longest searches (platform = linux, compiler = GNU C++ version 5.1.0)</a></span></dt>
<dt><span class="section"><a href="background_information/performance/section_Testing_simple_Perl_matches_platform_Windows_x64_compiler_Microsoft_Visual_C_version_14_0_.html">Testing
simple Perl matches (platform = Windows x64, compiler = Microsoft Visual
C++ version 14.0)</a></span></dt>
<dt><span class="section"><a href="background_information/performance/section_Testing_simple_Perl_matches_platform_linux_compiler_GNU_C_version_5_1_0_.html">Testing
simple Perl matches (platform = linux, compiler = GNU C++ version 5.1.0)</a></span></dt>
<dt><span class="section"><a href="background_information/performance/section_Testing_simple_leftmost_longest_matches_platform_Windows_x64_compiler_Microsoft_Visual_C_version_14_0_.html">Testing
simple leftmost-longest matches (platform = Windows x64, compiler = Microsoft
Visual C++ version 14.0)</a></span></dt>
<dt><span class="section"><a href="background_information/performance/section_Testing_simple_leftmost_longest_matches_platform_linux_compiler_GNU_C_version_5_1_0_.html">Testing
simple leftmost-longest matches (platform = linux, compiler = GNU C++ version
5.1.0)</a></span></dt>
</dl></dd>
<dt><span class="section"><a href="background_information/standards.html">Standards
Conformance</a></span></dt>
<dt><span class="section"><a href="background_information/redist.html">Redistributables</a></span></dt>
<dt><span class="section"><a href="background_information/acknowledgements.html">Acknowledgements</a></span></dt>
<dt><span class="section"><a href="background_information/history.html">History</a></span></dt>
</dl></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 1998-2013 John Maddock<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="ref/internal_details/uni_iter.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="background_information/headers.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
yinchunlong/abelkhan-1
|
ext/c++/thirdpart/c++/boost/libs/regex/doc/html/boost_regex/background_information.html
|
HTML
|
mit
| 6,518
|
<?php
namespace Chamilo\Application\Weblcms\Tool\Implementation\Assignment\Integration\Chamilo\Application\Calendar\Test\Source;
/**
* This test case checks the php syntax for the php files of this package
*
* @author Sven Vanpoucke - Hogeschool Gent
*/
class CheckSourceCodeTest extends \Chamilo\Libraries\Architecture\Test\Source\CheckSourceCodeTest
{
}
|
forelo/cosnics
|
src/Chamilo/Application/Weblcms/Tool/Implementation/Assignment/Integration/Chamilo/Application/Calendar/Test/Source/CheckSourceCodeTest.php
|
PHP
|
mit
| 361
|
#include <stdlib.h>
#include "chipmunk_private.h"
void
cpSpatialIndexFree(cpSpatialIndex *index)
{
if(index){
cpSpatialIndexDestroy(index);
cpfree(index);
}
}
cpSpatialIndex *
cpSpatialIndexInit(cpSpatialIndex *index, cpSpatialIndexClass *klass, cpSpatialIndexBBFunc bbfunc, cpSpatialIndex *staticIndex)
{
index->klass = klass;
index->bbfunc = bbfunc;
index->staticIndex = staticIndex;
if(staticIndex){
cpAssertHard(!staticIndex->dynamicIndex, "This static index is already associated with a dynamic index.");
staticIndex->dynamicIndex = index;
}
return index;
}
typedef struct dynamicToStaticContext {
cpSpatialIndexBBFunc bbfunc;
cpSpatialIndex *staticIndex;
cpSpatialIndexQueryFunc queryFunc;
void *data;
} dynamicToStaticContext;
static void
dynamicToStaticIter(void *obj, dynamicToStaticContext *context)
{
cpSpatialIndexQuery(context->staticIndex, obj, context->bbfunc(obj), context->queryFunc, context->data);
}
void
cpSpatialIndexCollideStatic(cpSpatialIndex *dynamicIndex, cpSpatialIndex *staticIndex, cpSpatialIndexQueryFunc func, void *data)
{
if(cpSpatialIndexCount(staticIndex) > 0){
dynamicToStaticContext context = {dynamicIndex->bbfunc, staticIndex, func, data};
cpSpatialIndexEach(dynamicIndex, (cpSpatialIndexIteratorFunc)dynamicToStaticIter, &context);
}
}
|
gwthomas/sol-framework
|
external/chipmunk/cpSpatialIndex.c
|
C
|
mit
| 1,314
|
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<base href="../../../" />
<script src="page.js"></script>
<link type="text/css" rel="stylesheet" href="page.css" />
</head>
<body>
[page:BufferGeometry] →
<h1>立方缓冲几何体([name])</h1>
<p class="desc">[name]是四边形的原始几何类,它通常使用构造函数所提供的“width”、“height”、“depth”参数来创建立方体或者不规则四边形。</p>
<iframe id="scene" src="scenes/geometry-browser.html#BoxGeometry"></iframe>
<script>
// iOS iframe auto-resize workaround
if ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) {
const scene = document.getElementById( 'scene' );
scene.style.width = getComputedStyle( scene ).width;
scene.style.height = getComputedStyle( scene ).height;
scene.setAttribute( 'scrolling', 'no' );
}
</script>
<h2>代码示例</h2>
<code>const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
</code>
<h2>构造器</h2>
<h3>[name]([param:Float width], [param:Float height], [param:Float depth], [param:Integer widthSegments], [param:Integer heightSegments], [param:Integer depthSegments])</h3>
<p>
width — X轴上面的宽度,默认值为1。<br />
height — Y轴上面的高度,默认值为1。<br />
depth — Z轴上面的深度,默认值为1。<br />
widthSegments — (可选)宽度的分段数,默认值是1。<br />
heightSegments — (可选)宽度的分段数,默认值是1。<br />
depthSegments — (可选)宽度的分段数,默认值是1。
</p>
<h2>属性</h2>
<p>共有属性请参见其基类[page:BufferGeometry]。</p>
<h3>[property:Object parameters]</h3>
<p>
一个包含着构造函数中每个参数的对象。在对象实例化之后,对该属性的任何修改都不会改变这个几何体。
</p>
<p>
使用上面的示例代码来作为基础:
<code>
geometry.parameters; // outputs an object {width: 1, height: 1, depth: 1, widthSegments: undefined, heightSegments: undefined}
cube.geometry.parameters; // as above
cube.geometry.parameters.width; // === 1
cube.geometry.parameters.widthSegments // === undefined.
</code>
</p>
<h2>方法(Methods)</h2>
<p>共有方法请参见其基类[page:BufferGeometry]。</p>
<h2>源代码</h2>
<p>
[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]
</p>
</body>
</html>
|
opensim-org/three.js
|
docs/api/zh/geometries/BoxGeometry.html
|
HTML
|
mit
| 2,625
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\Form\ChoiceList;
use Symfony\Component\Form\Exception\RuntimeException;
use Symfony\Component\Form\Exception\StringCastException;
use Symfony\Component\Form\Extension\Core\ChoiceList\ObjectChoiceList;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
/**
* A choice list presenting a list of Doctrine entities as choices
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class EntityChoiceList extends ObjectChoiceList
{
/**
* @var ObjectManager
*/
private $em;
/**
* @var string
*/
private $class;
/**
* @var \Doctrine\Common\Persistence\Mapping\ClassMetadata
*/
private $classMetadata;
/**
* Contains the query builder that builds the query for fetching the
* entities
*
* This property should only be accessed through queryBuilder.
*
* @var EntityLoaderInterface
*/
private $entityLoader;
/**
* The identifier field, if the identifier is not composite
*
* @var array
*/
private $idField = null;
/**
* Whether to use the identifier for index generation
*
* @var Boolean
*/
private $idAsIndex = false;
/**
* Whether to use the identifier for value generation
*
* @var Boolean
*/
private $idAsValue = false;
/**
* Whether the entities have already been loaded.
*
* @var Boolean
*/
private $loaded = false;
/**
* The preferred entities.
*
* @var array
*/
private $preferredEntities = array();
/**
* Creates a new entity choice list.
*
* @param ObjectManager $manager An EntityManager instance
* @param string $class The class name
* @param string $labelPath The property path used for the label
* @param EntityLoaderInterface $entityLoader An optional query builder
* @param array $entities An array of choices
* @param array $preferredEntities An array of preferred choices
* @param string $groupPath A property path pointing to the property used
* to group the choices. Only allowed if
* the choices are given as flat array.
* @param PropertyAccessorInterface $propertyAccessor The reflection graph for reading property paths.
*/
public function __construct(ObjectManager $manager, $class, $labelPath = null, EntityLoaderInterface $entityLoader = null, $entities = null, array $preferredEntities = array(), $groupPath = null, PropertyAccessorInterface $propertyAccessor = null)
{
$this->em = $manager;
$this->entityLoader = $entityLoader;
$this->classMetadata = $manager->getClassMetadata($class);
$this->class = $this->classMetadata->getName();
$this->loaded = is_array($entities) || $entities instanceof \Traversable;
$this->preferredEntities = $preferredEntities;
$identifier = $this->classMetadata->getIdentifierFieldNames();
if (1 === count($identifier)) {
$this->idField = $identifier[0];
$this->idAsValue = true;
if (in_array($this->classMetadata->getTypeOfField($this->idField), array('integer', 'smallint', 'bigint'))) {
$this->idAsIndex = true;
}
}
if (!$this->loaded) {
// Make sure the constraints of the parent constructor are
// fulfilled
$entities = array();
}
parent::__construct($entities, $labelPath, $preferredEntities, $groupPath, null, $propertyAccessor);
}
/**
* Returns the list of entities
*
* @return array
*
* @see Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
public function getChoices()
{
if (!$this->loaded) {
$this->load();
}
return parent::getChoices();
}
/**
* Returns the values for the entities
*
* @return array
*
* @see Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
public function getValues()
{
if (!$this->loaded) {
$this->load();
}
return parent::getValues();
}
/**
* Returns the choice views of the preferred choices as nested array with
* the choice groups as top-level keys.
*
* @return array
*
* @see Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
public function getPreferredViews()
{
if (!$this->loaded) {
$this->load();
}
return parent::getPreferredViews();
}
/**
* Returns the choice views of the choices that are not preferred as nested
* array with the choice groups as top-level keys.
*
* @return array
*
* @see Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
public function getRemainingViews()
{
if (!$this->loaded) {
$this->load();
}
return parent::getRemainingViews();
}
/**
* Returns the entities corresponding to the given values.
*
* @param array $values
*
* @return array
*
* @see Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
public function getChoicesForValues(array $values)
{
// Performance optimization
// Also prevents the generation of "WHERE id IN ()" queries through the
// entity loader. At least with MySQL and on the development machine
// this was tested on, no exception was thrown for such invalid
// statements, consequently no test fails when this code is removed.
// https://github.com/symfony/symfony/pull/8981#issuecomment-24230557
if (empty($values)) {
return array();
}
if (!$this->loaded) {
// Optimize performance in case we have an entity loader and
// a single-field identifier
if ($this->idAsValue && $this->entityLoader) {
$unorderedEntities = $this->entityLoader->getEntitiesByIds($this->idField, $values);
$entitiesByValue = array();
$entities = array();
// Maintain order and indices from the given $values
// An alternative approach to the following loop is to add the
// "INDEX BY" clause to the Doctrine query in the loader,
// but I'm not sure whether that's doable in a generic fashion.
foreach ($unorderedEntities as $entity) {
$value = $this->fixValue(current($this->getIdentifierValues($entity)));
$entitiesByValue[$value] = $entity;
}
foreach ($values as $i => $value) {
if (isset($entitiesByValue[$value])) {
$entities[$i] = $entitiesByValue[$value];
}
}
return $entities;
}
$this->load();
}
return parent::getChoicesForValues($values);
}
/**
* Returns the values corresponding to the given entities.
*
* @param array $entities
*
* @return array
*
* @see Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*/
public function getValuesForChoices(array $entities)
{
// Performance optimization
if (empty($entities)) {
return array();
}
if (!$this->loaded) {
// Optimize performance for single-field identifiers. We already
// know that the IDs are used as values
// Attention: This optimization does not check choices for existence
if ($this->idAsValue) {
$values = array();
foreach ($entities as $i => $entity) {
if ($entity instanceof $this->class) {
// Make sure to convert to the right format
$values[$i] = $this->fixValue(current($this->getIdentifierValues($entity)));
}
}
return $values;
}
$this->load();
}
return parent::getValuesForChoices($entities);
}
/**
* Returns the indices corresponding to the given entities.
*
* @param array $entities
*
* @return array
*
* @see Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*
* @deprecated Deprecated since version 2.4, to be removed in 3.0.
*/
public function getIndicesForChoices(array $entities)
{
// Performance optimization
if (empty($entities)) {
return array();
}
if (!$this->loaded) {
// Optimize performance for single-field identifiers. We already
// know that the IDs are used as indices
// Attention: This optimization does not check choices for existence
if ($this->idAsIndex) {
$indices = array();
foreach ($entities as $i => $entity) {
if ($entity instanceof $this->class) {
// Make sure to convert to the right format
$indices[$i] = $this->fixIndex(current($this->getIdentifierValues($entity)));
}
}
return $indices;
}
$this->load();
}
return parent::getIndicesForChoices($entities);
}
/**
* Returns the entities corresponding to the given values.
*
* @param array $values
*
* @return array
*
* @see Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
*
* @deprecated Deprecated since version 2.4, to be removed in 3.0.
*/
public function getIndicesForValues(array $values)
{
// Performance optimization
if (empty($values)) {
return array();
}
if (!$this->loaded) {
// Optimize performance for single-field identifiers.
// Attention: This optimization does not check values for existence
if ($this->idAsIndex && $this->idAsValue) {
return $this->fixIndices($values);
}
$this->load();
}
return parent::getIndicesForValues($values);
}
/**
* Creates a new unique index for this entity.
*
* If the entity has a single-field identifier, this identifier is used.
*
* Otherwise a new integer is generated.
*
* @param mixed $entity The choice to create an index for
*
* @return integer|string A unique index containing only ASCII letters,
* digits and underscores.
*/
protected function createIndex($entity)
{
if ($this->idAsIndex) {
return $this->fixIndex(current($this->getIdentifierValues($entity)));
}
return parent::createIndex($entity);
}
/**
* Creates a new unique value for this entity.
*
* If the entity has a single-field identifier, this identifier is used.
*
* Otherwise a new integer is generated.
*
* @param mixed $entity The choice to create a value for
*
* @return integer|string A unique value without character limitations.
*/
protected function createValue($entity)
{
if ($this->idAsValue) {
return (string) current($this->getIdentifierValues($entity));
}
return parent::createValue($entity);
}
/**
* {@inheritdoc}
*/
protected function fixIndex($index)
{
$index = parent::fixIndex($index);
// If the ID is a single-field integer identifier, it is used as
// index. Replace any leading minus by underscore to make it a valid
// form name.
if ($this->idAsIndex && $index < 0) {
$index = strtr($index, '-', '_');
}
return $index;
}
/**
* Loads the list with entities.
*/
private function load()
{
if ($this->entityLoader) {
$entities = $this->entityLoader->getEntities();
} else {
$entities = $this->em->getRepository($this->class)->findAll();
}
try {
// The second parameter $labels is ignored by ObjectChoiceList
parent::initialize($entities, array(), $this->preferredEntities);
} catch (StringCastException $e) {
throw new StringCastException(str_replace('argument $labelPath', 'option "property"', $e->getMessage()), null, $e);
}
$this->loaded = true;
}
/**
* Returns the values of the identifier fields of an entity.
*
* Doctrine must know about this entity, that is, the entity must already
* be persisted or added to the identity map before. Otherwise an
* exception is thrown.
*
* @param object $entity The entity for which to get the identifier
*
* @return array The identifier values
*
* @throws RuntimeException If the entity does not exist in Doctrine's identity map
*/
private function getIdentifierValues($entity)
{
if (!$this->em->contains($entity)) {
throw new RuntimeException(
'Entities passed to the choice field must be managed. Maybe ' .
'persist them in the entity manager?'
);
}
$this->em->initializeObject($entity);
return $this->classMetadata->getIdentifierValues($entity);
}
}
|
javieralfaya/tuitty
|
vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php
|
PHP
|
mit
| 14,704
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @namespace
*/
namespace Zend\Measure;
/**
* Class for handling energy conversions
*
* @uses Zend\Measure\Abstract
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Energy extends AbstractMeasure
{
const STANDARD = 'JOULE';
const ATTOJOULE = 'ATTOJOULE';
const BOARD_OF_TRADE_UNIT = 'BOARD_OF_TRADE_UNIT';
const BTU = 'BTU';
const BTU_THERMOCHEMICAL = 'BTU_TERMOCHEMICAL';
const CALORIE = 'CALORIE';
const CALORIE_15C = 'CALORIE_15C';
const CALORIE_NUTRITIONAL = 'CALORIE_NUTRITIONAL';
const CALORIE_THERMOCHEMICAL = 'CALORIE_THERMOCHEMICAL';
const CELSIUS_HEAT_UNIT = 'CELSIUS_HEAT_UNIT';
const CENTIJOULE = 'CENTIJOULE';
const CHEVAL_VAPEUR_HEURE = 'CHEVAL_VAPEUR_HEURE';
const DECIJOULE = 'DECIJOULE';
const DEKAJOULE = 'DEKAJOULE';
const DEKAWATT_HOUR = 'DEKAWATT_HOUR';
const DEKATHERM = 'DEKATHERM';
const ELECTRONVOLT = 'ELECTRONVOLT';
const ERG = 'ERG';
const EXAJOULE = 'EXAJOULE';
const EXAWATT_HOUR = 'EXAWATT_HOUR';
const FEMTOJOULE = 'FEMTOJOULE';
const FOOT_POUND = 'FOOT_POUND';
const FOOT_POUNDAL = 'FOOT_POUNDAL';
const GALLON_UK_AUTOMOTIVE = 'GALLON_UK_AUTOMOTIVE';
const GALLON_US_AUTOMOTIVE = 'GALLON_US_AUTOMOTIVE';
const GALLON_UK_AVIATION = 'GALLON_UK_AVIATION';
const GALLON_US_AVIATION = 'GALLON_US_AVIATION';
const GALLON_UK_DIESEL = 'GALLON_UK_DIESEL';
const GALLON_US_DIESEL = 'GALLON_US_DIESEL';
const GALLON_UK_DISTILATE = 'GALLON_UK_DISTILATE';
const GALLON_US_DISTILATE = 'GALLON_US_DISTILATE';
const GALLON_UK_KEROSINE_JET = 'GALLON_UK_KEROSINE_JET';
const GALLON_US_KEROSINE_JET = 'GALLON_US_KEROSINE_JET';
const GALLON_UK_LPG = 'GALLON_UK_LPG';
const GALLON_US_LPG = 'GALLON_US_LPG';
const GALLON_UK_NAPHTA = 'GALLON_UK_NAPHTA';
const GALLON_US_NAPHTA = 'GALLON_US_NAPHTA';
const GALLON_UK_KEROSENE = 'GALLON_UK_KEROSINE';
const GALLON_US_KEROSENE = 'GALLON_US_KEROSINE';
const GALLON_UK_RESIDUAL = 'GALLON_UK_RESIDUAL';
const GALLON_US_RESIDUAL = 'GALLON_US_RESIDUAL';
const GIGAELECTRONVOLT = 'GIGAELECTRONVOLT';
const GIGACALORIE = 'GIGACALORIE';
const GIGACALORIE_15C = 'GIGACALORIE_15C';
const GIGAJOULE = 'GIGAJOULE';
const GIGAWATT_HOUR = 'GIGAWATT_HOUR';
const GRAM_CALORIE = 'GRAM_CALORIE';
const HARTREE = 'HARTREE';
const HECTOJOULE = 'HECTOJOULE';
const HECTOWATT_HOUR = 'HECTOWATT_HOUR';
const HORSEPOWER_HOUR = 'HORSEPOWER_HOUR';
const HUNDRED_CUBIC_FOOT_GAS = 'HUNDRED_CUBIC_FOOT_GAS';
const INCH_OUNCE = 'INCH_OUNCE';
const INCH_POUND = 'INCH_POUND';
const JOULE = 'JOULE';
const KILOCALORIE_15C = 'KILOCALORIE_15C';
const KILOCALORIE = 'KILOCALORIE';
const KILOCALORIE_THERMOCHEMICAL = 'KILOCALORIE_THERMOCHEMICAL';
const KILOELECTRONVOLT = 'KILOELECTRONVOLT';
const KILOGRAM_CALORIE = 'KILOGRAM_CALORIE';
const KILOGRAM_FORCE_METER = 'KILOGRAM_FORCE_METER';
const KILOJOULE = 'KILOJOULE';
const KILOPOND_METER = 'KILOPOND_METER';
const KILOTON = 'KILOTON';
const KILOWATT_HOUR = 'KILOWATT_HOUR';
const LITER_ATMOSPHERE = 'LITER_ATMOSPHERE';
const MEGAELECTRONVOLT = 'MEGAELECTRONVOLT';
const MEGACALORIE = 'MEGACALORIE';
const MEGACALORIE_15C = 'MEGACALORIE_15C';
const MEGAJOULE = 'MEGAJOULE';
const MEGALERG = 'MEGALERG';
const MEGATON = 'MEGATON';
const MEGAWATTHOUR = 'MEGAWATTHOUR';
const METER_KILOGRAM_FORCE = 'METER_KILOGRAM_FORCE';
const MICROJOULE = 'MICROJOULE';
const MILLIJOULE = 'MILLIJOULE';
const MYRIAWATT_HOUR = 'MYRIAWATT_HOUR';
const NANOJOULE = 'NANOJOULE';
const NEWTON_METER = 'NEWTON_METER';
const PETAJOULE = 'PETAJOULE';
const PETAWATTHOUR = 'PETAWATTHOUR';
const PFERDESTAERKENSTUNDE = 'PFERDESTAERKENSTUNDE';
const PICOJOULE = 'PICOJOULE';
const Q_UNIT = 'Q_UNIT';
const QUAD = 'QUAD';
const TERAELECTRONVOLT = 'TERAELECTRONVOLT';
const TERAJOULE = 'TERAJOULE';
const TERAWATTHOUR = 'TERAWATTHOUR';
const THERM = 'THERM';
const THERM_US = 'THERM_US';
const THERMIE = 'THERMIE';
const TON = 'TON';
const TONNE_COAL = 'TONNE_COAL';
const TONNE_OIL = 'TONNE_OIL';
const WATTHOUR = 'WATTHOUR';
const WATTSECOND = 'WATTSECOND';
const YOCTOJOULE = 'YOCTOJOULE';
const YOTTAJOULE = 'YOTTAJOULE';
const YOTTAWATTHOUR = 'YOTTAWATTHOUR';
const ZEPTOJOULE = 'ZEPTOJOULE';
const ZETTAJOULE = 'ZETTAJOULE';
const ZETTAWATTHOUR = 'ZETTAWATTHOUR';
/**
* Calculations for all energy units
*
* @var array
*/
protected $_units = array(
'ATTOJOULE' => array('1.0e-18', 'aJ'),
'BOARD_OF_TRADE_UNIT' => array('3600000', 'BOTU'),
'BTU' => array('1055.0559', 'Btu'),
'BTU_TERMOCHEMICAL' => array('1054.3503', 'Btu'),
'CALORIE' => array('4.1868', 'cal'),
'CALORIE_15C' => array('6.1858', 'cal'),
'CALORIE_NUTRITIONAL' => array('4186.8', 'cal'),
'CALORIE_THERMOCHEMICAL' => array('4.184', 'cal'),
'CELSIUS_HEAT_UNIT' => array('1899.1005', 'Chu'),
'CENTIJOULE' => array('0.01', 'cJ'),
'CHEVAL_VAPEUR_HEURE' => array('2647795.5', 'cv heure'),
'DECIJOULE' => array('0.1', 'dJ'),
'DEKAJOULE' => array('10', 'daJ'),
'DEKAWATT_HOUR' => array('36000', 'daWh'),
'DEKATHERM' => array('1.055057e+9', 'dathm'),
'ELECTRONVOLT' => array('1.6021773e-19', 'eV'),
'ERG' => array('0.0000001', 'erg'),
'EXAJOULE' => array('1.0e+18', 'EJ'),
'EXAWATT_HOUR' => array('3.6e+21', 'EWh'),
'FEMTOJOULE' => array('1.0e-15', 'fJ'),
'FOOT_POUND' => array('1.3558179', 'ft lb'),
'FOOT_POUNDAL' => array('0.04214011', 'ft poundal'),
'GALLON_UK_AUTOMOTIVE' => array('158237172', 'gal car gasoline'),
'GALLON_US_AUTOMOTIVE' => array('131760000', 'gal car gasoline'),
'GALLON_UK_AVIATION' => array('158237172', 'gal jet gasoline'),
'GALLON_US_AVIATION' => array('131760000', 'gal jet gasoline'),
'GALLON_UK_DIESEL' => array('175963194', 'gal diesel'),
'GALLON_US_DIESEL' => array('146520000', 'gal diesel'),
'GALLON_UK_DISTILATE' => array('175963194', 'gal destilate fuel'),
'GALLON_US_DISTILATE' => array('146520000', 'gal destilate fuel'),
'GALLON_UK_KEROSINE_JET' => array('170775090', 'gal jet kerosine'),
'GALLON_US_KEROSINE_JET' => array('142200000', 'gal jet kerosine'),
'GALLON_UK_LPG' => array('121005126.0865275', 'gal lpg'),
'GALLON_US_LPG' => array('100757838.45', 'gal lpg'),
'GALLON_UK_NAPHTA' => array('160831224', 'gal jet fuel'),
'GALLON_US_NAPHTA' => array('133920000', 'gal jet fuel'),
'GALLON_UK_KEROSINE' => array('170775090', 'gal kerosine'),
'GALLON_US_KEROSINE' => array('142200000', 'gal kerosine'),
'GALLON_UK_RESIDUAL' => array('189798138', 'gal residual fuel'),
'GALLON_US_RESIDUAL' => array('158040000', 'gal residual fuel'),
'GIGAELECTRONVOLT' => array('1.6021773e-10', 'GeV'),
'GIGACALORIE' => array('4186800000', 'Gcal'),
'GIGACALORIE_15C' => array('4185800000', 'Gcal'),
'GIGAJOULE' => array('1.0e+9', 'GJ'),
'GIGAWATT_HOUR' => array('3.6e+12', 'GWh'),
'GRAM_CALORIE' => array('4.1858', 'g cal'),
'HARTREE' => array('4.3597482e-18', 'Eh'),
'HECTOJOULE' => array('100', 'hJ'),
'HECTOWATT_HOUR' => array('360000', 'hWh'),
'HORSEPOWER_HOUR' => array('2684519.5', 'hph'),
'HUNDRED_CUBIC_FOOT_GAS' => array('108720000', 'hundred ft� gas'),
'INCH_OUNCE' => array('0.0070615518', 'in oc'),
'INCH_POUND' => array('0.112984825', 'in lb'),
'JOULE' => array('1', 'J'),
'KILOCALORIE_15C' => array('4185.8', 'kcal'),
'KILOCALORIE' => array('4186','8', 'kcal'),
'KILOCALORIE_THERMOCHEMICAL' => array('4184', 'kcal'),
'KILOELECTRONVOLT' => array('1.6021773e-16', 'keV'),
'KILOGRAM_CALORIE' => array('4185.8', 'kg cal'),
'KILOGRAM_FORCE_METER' => array('9.80665', 'kgf m'),
'KILOJOULE' => array('1000', 'kJ'),
'KILOPOND_METER' => array('9.80665', 'kp m'),
'KILOTON' => array('4.184e+12', 'kt'),
'KILOWATT_HOUR' => array('3600000', 'kWh'),
'LITER_ATMOSPHERE' => array('101.325', 'l atm'),
'MEGAELECTRONVOLT' => array('1.6021773e-13', 'MeV'),
'MEGACALORIE' => array('4186800', 'Mcal'),
'MEGACALORIE_15C' => array('4185800', 'Mcal'),
'MEGAJOULE' => array('1000000', 'MJ'),
'MEGALERG' => array('0.1', 'megalerg'),
'MEGATON' => array('4.184e+15', 'Mt'),
'MEGAWATTHOUR' => array('3.6e+9', 'MWh'),
'METER_KILOGRAM_FORCE' => array('9.80665', 'm kgf'),
'MICROJOULE' => array('0.000001', '�J'),
'MILLIJOULE' => array('0.001', 'mJ'),
'MYRIAWATT_HOUR' => array('3.6e+7', 'myWh'),
'NANOJOULE' => array('1.0e-9', 'nJ'),
'NEWTON_METER' => array('1', 'Nm'),
'PETAJOULE' => array('1.0e+15', 'PJ'),
'PETAWATTHOUR' => array('3.6e+18', 'PWh'),
'PFERDESTAERKENSTUNDE' => array('2647795.5', 'ps h'),
'PICOJOULE' => array('1.0e-12', 'pJ'),
'Q_UNIT' => array('1.0550559e+21', 'Q unit'),
'QUAD' => array('1.0550559e+18', 'quad'),
'TERAELECTRONVOLT' => array('1.6021773e-7', 'TeV'),
'TERAJOULE' => array('1.0e+12', 'TJ'),
'TERAWATTHOUR' => array('3.6e+15', 'TWh'),
'THERM' => array('1.0550559e+8', 'thm'),
'THERM_US' => array('1.054804e+8', 'thm'),
'THERMIE' => array('4185800', 'th'),
'TON' => array('4.184e+9', 'T explosive'),
'TONNE_COAL' => array('2.93076e+10', 'T coal'),
'TONNE_OIL' => array('4.1868e+10', 'T oil'),
'WATTHOUR' => array('3600', 'Wh'),
'WATTSECOND' => array('1', 'Ws'),
'YOCTOJOULE' => array('1.0e-24', 'yJ'),
'YOTTAJOULE' => array('1.0e+24', 'YJ'),
'YOTTAWATTHOUR' => array('3.6e+27', 'YWh'),
'ZEPTOJOULE' => array('1.0e-21', 'zJ'),
'ZETTAJOULE' => array('1.0e+21', 'ZJ'),
'ZETTAWATTHOUR' => array('3.6e+24', 'ZWh'),
'STANDARD' => 'JOULE'
);
}
|
dynamicguy/gpweb
|
src/vendor/zend/library/Zend/Measure/Energy.php
|
PHP
|
mit
| 14,331
|
<h2 id="angularjs-requirejs-boilerplate">angularjs-requirejs-boilerplate</h2>
<p>A complete angularjs requirejs boilerplate for node. There are angular and test samples in the project,
you can quick start your new project with angularjs-requirejs-boilerplate.</p>
<h2 id="features">Features</h2>
<h3 id="front-end">Front-end</h3>
<ul>
<li><a href="http://angularjs.org/">angularjs</a>, a JavaScript MVW Framework</li>
<li><a href="http://getbootstrap.com/">bootstrap</a>, the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web</li>
<li><a href="https://jquery.org/">jquery</a>, the Write Less, Do More, JavaScript Library</li>
<li><a href="http://lesscss.org/">less</a>, a CSS pre-processor</li>
<li><a href="http://requirejs.org/">requirejs</a>, a JavaScript file and module loader</li>
<li>etc</li>
</ul>
<h3 id="back-end">Back-end</h3>
<ul>
<li><a href="http://expressjs.com/">expressjs</a>, sinatra inspired web development framework for node.js</li>
<li><a href="http://gulpjs.com/">gulp</a>, the streaming build system</li>
<li><a href="http://paularmstrong.github.io/swig/">swig</a>, a simple, powerful, and extendable JavaScript Template Engine</li>
<li>etc</li>
</ul>
<h2 id="quick-start">Quick Start</h2>
<h3 id="install-dependencies-">Install Dependencies:</h3>
<pre><code class="lang-bash">$ bower install
$ npm install
</code></pre>
<h3 id="development">Development</h3>
<p>Development Environment using gulp-nodemon, <a href="https://www.browsersync.io/">browser-sync</a> and gulp-jshint.</p>
<ol>
<li>Make sure <strong>isDevMode</strong> configuration is <strong>true</strong> in <strong>locals.js</strong></li>
<li>Start development mode with <code>gulp --development</code></li>
<li>Input <code>http://localhost:devPort</code> with browsers</li>
</ol>
<h3 id="production">Production</h3>
<ol>
<li>Make sure <strong>isDevMode</strong> configuration is <strong>false</strong> in <strong>locals.js</strong></li>
<li>Compile and build with <code>gulp --production</code></li>
<li>Start the server with node or pm2 or others</li>
<li>Input <code>http://localhost:port</code> with browsers</li>
</ol>
<h3 id="configuration">Configuration</h3>
<p>System configuration are stored in the <strong>locals.js</strong> file.</p>
<h3 id="samples-page">Samples Page</h3>
<p>Start the server and input <code>http://localhost:port/samples</code> with browsers.</p>
<h2 id="gulp">Gulp</h2>
<p>Show task list with <code>gulp help</code>.</p>
<h2 id="test">Test</h2>
<p>Test using karma and jasmine, run the test with <code>npm test</code> or <code>karma start</code>. Unit and coverage test report are stored in report directory.</p>
<h2 id="changelog">Changelog</h2>
<h3 id="2-3-0">2.3.0</h3>
<ul>
<li>watch gulp files</li>
<li>the browser reload while restart nodemon<br>
27.01.2016</li>
</ul>
<h3 id="2-2-1">2.2.1</h3>
<ul>
<li>fix task can not separate execution with development mode<br>
25.01.2016</li>
</ul>
<h3 id="2-2-0">2.2.0</h3>
<ul>
<li>add build-templates task to optimize ngTemplates that registers AngularJS templates in the $templateCache</li>
<li>add error and listening event to server<br>
17.01.2016</li>
</ul>
<h3 id="2-1-0">2.1.0</h3>
<ul>
<li>replace gulp-livereload with browser-sync</li>
<li>add gulp-help, gulp-size and others gulp components</li>
<li>remove less.js<br>
10.01.2016</li>
</ul>
<h3 id="2-0-0">2.0.0</h3>
<ul>
<li>adjust directory and code of project</li>
<li>add angular samples page</li>
<li>add README.md preview<br>
01.01.2016</li>
</ul>
<h3 id="1-1-1">1.1.1</h3>
<ul>
<li>fix mobile can not redirect</li>
<li>fix can not define custom router<br>
18.11.2015</li>
</ul>
<h3 id="1-1-0">1.1.0</h3>
<ul>
<li>add gulp task named build-views that registers AngularJS templates in the $templateCache</li>
<li>add karma and size into gulpfile</li>
<li>replace chrome launcher with phantomjs launcher in karma</li>
<li>modify layout launcher and suffix of templateUrl<br>
31.10.2015</li>
</ul>
<h3 id="1-0-0">1.0.0</h3>
<ul>
<li>initial release<br>
18.10.2015</li>
</ul>
<h2 id="license">License</h2>
<p> <a href="https://github.com/ipluser/angularjs-requirejs-boilerplate/blob/master/LICENSE">MIT</a></p>
|
ipluser/nodejs-basicer
|
views/mobile/templates/markdown/README.html
|
HTML
|
mit
| 4,190
|
export * as ns from 'mod';
export v from 'mod';
export a, * as b from 'mod';
export c, { foo } from 'mod';
export * as d, { bar } from 'mod';
export { fooooooooooooooooooooooooooooooooooooooooooooooooo } from "fooooooooooooooooooooooooooooo";
export Bar, { barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr } from "barrrrrrrrrrrrrrrrrrrrrrrrrrrr";
export { foooooooooooooooooooooooooooooooooooooooooooooo, fooooooooooooooooooooooooooooooooooooooooooooooo } from "fooooooooooooooooooooooooooooo";
|
rattrayalex/prettier
|
tests/format/js/export-extension/export.js
|
JavaScript
|
mit
| 493
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\ClassLoader\Tests;
use Symfony\Component\ClassLoader\ApcUniversalClassLoader;
class ApcUniversalClassLoaderTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (ini_get('apc.enabled') && ini_get('apc.enable_cli')) {
apcu_clear_cache();
} else {
$this->markTestSkipped('APC is not enabled.');
}
}
protected function tearDown()
{
if (ini_get('apc.enabled') && ini_get('apc.enable_cli')) {
apcu_clear_cache();
}
}
public function testConstructor()
{
$loader = new ApcUniversalClassLoader('test.prefix.');
$loader->registerNamespace('Apc\Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
$this->assertEquals($loader->findFile('\Apc\Namespaced\FooBar'), apcu_fetch('test.prefix.\Apc\Namespaced\FooBar'), '__construct() takes a prefix as its first argument');
}
/**
* @dataProvider getLoadClassTests
*/
public function testLoadClass($className, $testClassName, $message)
{
$loader = new ApcUniversalClassLoader('test.prefix.');
$loader->registerNamespace('Apc\Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
$loader->registerPrefix('Apc_Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
$loader->loadClass($testClassName);
$this->assertTrue(class_exists($className), $message);
}
public function getLoadClassTests()
{
return array(
array('\\Apc\\Namespaced\\Foo', 'Apc\\Namespaced\\Foo', '->loadClass() loads Apc\Namespaced\Foo class'),
array('Apc_Pearlike_Foo', 'Apc_Pearlike_Foo', '->loadClass() loads Apc_Pearlike_Foo class'),
);
}
/**
* @dataProvider getLoadClassFromFallbackTests
*/
public function testLoadClassFromFallback($className, $testClassName, $message)
{
$loader = new ApcUniversalClassLoader('test.prefix.fallback');
$loader->registerNamespace('Apc\Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
$loader->registerPrefix('Apc_Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
$loader->registerNamespaceFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/fallback'));
$loader->registerPrefixFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/fallback'));
$loader->loadClass($testClassName);
$this->assertTrue(class_exists($className), $message);
}
public function getLoadClassFromFallbackTests()
{
return array(
array('\\Apc\\Namespaced\\Baz', 'Apc\\Namespaced\\Baz', '->loadClass() loads Apc\Namespaced\Baz class'),
array('Apc_Pearlike_Baz', 'Apc_Pearlike_Baz', '->loadClass() loads Apc_Pearlike_Baz class'),
array('\\Apc\\Namespaced\\FooBar', 'Apc\\Namespaced\\FooBar', '->loadClass() loads Apc\Namespaced\Baz class from fallback dir'),
array('Apc_Pearlike_FooBar', 'Apc_Pearlike_FooBar', '->loadClass() loads Apc_Pearlike_Baz class from fallback dir'),
);
}
/**
* @dataProvider getLoadClassNamespaceCollisionTests
*/
public function testLoadClassNamespaceCollision($namespaces, $className, $message)
{
$loader = new ApcUniversalClassLoader('test.prefix.collision.');
$loader->registerNamespaces($namespaces);
$loader->loadClass($className);
$this->assertTrue(class_exists($className), $message);
}
public function getLoadClassNamespaceCollisionTests()
{
return array(
array(
array(
'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
),
'Apc\NamespaceCollision\A\Foo',
'->loadClass() loads NamespaceCollision\A\Foo from alpha.',
),
array(
array(
'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
),
'Apc\NamespaceCollision\A\Bar',
'->loadClass() loads NamespaceCollision\A\Bar from alpha.',
),
array(
array(
'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
),
'Apc\NamespaceCollision\A\B\Foo',
'->loadClass() loads NamespaceCollision\A\B\Foo from beta.',
),
array(
array(
'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
),
'Apc\NamespaceCollision\A\B\Bar',
'->loadClass() loads NamespaceCollision\A\B\Bar from beta.',
),
);
}
/**
* @dataProvider getLoadClassPrefixCollisionTests
*/
public function testLoadClassPrefixCollision($prefixes, $className, $message)
{
$loader = new ApcUniversalClassLoader('test.prefix.collision.');
$loader->registerPrefixes($prefixes);
$loader->loadClass($className);
$this->assertTrue(class_exists($className), $message);
}
public function getLoadClassPrefixCollisionTests()
{
return array(
array(
array(
'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc',
'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc',
),
'ApcPrefixCollision_A_Foo',
'->loadClass() loads ApcPrefixCollision_A_Foo from alpha.',
),
array(
array(
'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc',
'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc',
),
'ApcPrefixCollision_A_Bar',
'->loadClass() loads ApcPrefixCollision_A_Bar from alpha.',
),
array(
array(
'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc',
'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc',
),
'ApcPrefixCollision_A_B_Foo',
'->loadClass() loads ApcPrefixCollision_A_B_Foo from beta.',
),
array(
array(
'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc',
'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc',
),
'ApcPrefixCollision_A_B_Bar',
'->loadClass() loads ApcPrefixCollision_A_B_Bar from beta.',
),
);
}
}
|
bijen/nform
|
vendor/symfony/symfony/src/Symfony/Component/ClassLoader/Tests/ApcUniversalClassLoaderTest.php
|
PHP
|
mit
| 7,458
|
# Upgrading Your Syntax Theme
Text editor content is now rendered in the shadow DOM, which shields it from being styled by global style sheets to protect against accidental style pollution. For more background on the shadow DOM, check out the [Shadow DOM 101][shadow-dom-101] on HTML 5 Rocks.
Syntax themes are specifically intended to style only text editor content, so they are automatically loaded directly into the text editor's shadow DOM when it is enabled. This happens automatically when the the theme's `package.json` contains a `theme: "syntax"` declaration, so you don't need to change anything to target the appropriate context.
When theme style sheets are loaded into the text editor's shadow DOM, selectors intended to target the editor from the *outside* no longer make sense. Styles targeting the `.editor` and `.editor-colors` classes instead need to target the `:host` pseudo-element, which matches against the containing `atom-text-editor` node. Check out the [Shadow DOM 201][host-pseudo-element] article for more information about the `:host` pseudo-element.
Here's an example from Atom's light syntax theme. Note that the previous selectors intended to target the editor from the outside have been retained to allow the theme to keep working during the transition phase when it is possible to disable the shadow DOM.
```css
.editor-colors, :host { /* :host added */
background-color: @syntax-background-color;
color: @syntax-text-color;
}
.editor, :host { /* :host added */
.invisible-character {
color: @syntax-invisible-character-color;
}
/* more nested selectors... */
}
```
[shadow-dom-101]: http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom
[host-pseudo-element]: http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201#toc-style-host
|
avdg/atom
|
docs/upgrading/upgrading-your-syntax-theme.md
|
Markdown
|
mit
| 1,808
|
import * as THREE from 'three';
import { UIRow, UIText, UIInteger, UINumber } from './libs/ui.js';
import { SetGeometryCommand } from './commands/SetGeometryCommand.js';
function GeometryParametersPanel( editor, object ) {
const strings = editor.strings;
const signals = editor.signals;
const container = new UIRow();
const geometry = object.geometry;
const parameters = geometry.parameters;
// radius
const radiusRow = new UIRow();
const radius = new UINumber( parameters.radius ).onChange( update );
radiusRow.add( new UIText( strings.getKey( 'sidebar/geometry/tetrahedron_geometry/radius' ) ).setWidth( '90px' ) );
radiusRow.add( radius );
container.add( radiusRow );
// detail
const detailRow = new UIRow();
const detail = new UIInteger( parameters.detail ).setRange( 0, Infinity ).onChange( update );
detailRow.add( new UIText( strings.getKey( 'sidebar/geometry/tetrahedron_geometry/detail' ) ).setWidth( '90px' ) );
detailRow.add( detail );
container.add( detailRow );
//
function update() {
editor.execute( new SetGeometryCommand( editor, object, new THREE.TetrahedronGeometry(
radius.getValue(),
detail.getValue()
) ) );
signals.objectChanged.dispatch( object );
}
return container;
}
export { GeometryParametersPanel };
|
donmccurdy/three.js
|
editor/js/Sidebar.Geometry.TetrahedronGeometry.js
|
JavaScript
|
mit
| 1,286
|
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenProtocolInterpreter.IOInterface;
namespace MIDTesters.IOInterface
{
[TestClass]
public class TestMid0200 : MidTester
{
[TestMethod]
public void Mid0200Revision1()
{
string package = "00300200 1231231230";
var mid = _midInterpreter.Parse<Mid0200>(package);
Assert.AreEqual(typeof(Mid0200), mid.GetType());
Assert.IsNotNull(mid.StatusRelayOne);
Assert.IsNotNull(mid.StatusRelayTwo);
Assert.IsNotNull(mid.StatusRelayThree);
Assert.IsNotNull(mid.StatusRelayFour);
Assert.IsNotNull(mid.StatusRelayFive);
Assert.IsNotNull(mid.StatusRelaySix);
Assert.IsNotNull(mid.StatusRelaySeven);
Assert.IsNotNull(mid.StatusRelayEight);
Assert.IsNotNull(mid.StatusRelayNine);
Assert.IsNotNull(mid.StatusRelayTen);
Assert.AreEqual(package, mid.Pack());
}
[TestMethod]
public void Mid0200ByteRevision1()
{
string package = "00300200 1231231230";
byte[] bytes = GetAsciiBytes(package);
var mid = _midInterpreter.Parse<Mid0200>(bytes);
Assert.AreEqual(typeof(Mid0200), mid.GetType());
Assert.IsNotNull(mid.StatusRelayOne);
Assert.IsNotNull(mid.StatusRelayTwo);
Assert.IsNotNull(mid.StatusRelayThree);
Assert.IsNotNull(mid.StatusRelayFour);
Assert.IsNotNull(mid.StatusRelayFive);
Assert.IsNotNull(mid.StatusRelaySix);
Assert.IsNotNull(mid.StatusRelaySeven);
Assert.IsNotNull(mid.StatusRelayEight);
Assert.IsNotNull(mid.StatusRelayNine);
Assert.IsNotNull(mid.StatusRelayTen);
Assert.IsTrue(mid.PackBytes().SequenceEqual(bytes));
}
}
}
|
Rickedb/OpenProtocolInterpreter
|
src/MIDTesters/IOInterface/TestMid0200.cs
|
C#
|
mit
| 1,961
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
from devil.android import device_errors
class FlagChanger(object):
"""Changes the flags Chrome runs with.
There are two different use cases for this file:
* Flags are permanently set by calling Set().
* Flags can be temporarily set for a particular set of unit tests. These
tests should call Restore() to revert the flags to their original state
once the tests have completed.
"""
def __init__(self, device, cmdline_file):
"""Initializes the FlagChanger and records the original arguments.
Args:
device: A DeviceUtils instance.
cmdline_file: Path to the command line file on the device.
"""
self._device = device
self._cmdline_file = cmdline_file
# Save the original flags.
try:
self._orig_line = self._device.ReadFile(self._cmdline_file).strip()
except device_errors.CommandFailedError:
self._orig_line = ''
# Parse out the flags into a list to facilitate adding and removing flags.
self._current_flags = self._TokenizeFlags(self._orig_line)
def Get(self):
"""Returns list of current flags."""
return self._current_flags
def Set(self, flags):
"""Replaces all flags on the current command line with the flags given.
Args:
flags: A list of flags to set, eg. ['--single-process'].
"""
if flags:
assert flags[0] != 'chrome'
self._current_flags = flags
self._UpdateCommandLineFile()
def AddFlags(self, flags):
"""Appends flags to the command line if they aren't already there.
Args:
flags: A list of flags to add on, eg. ['--single-process'].
"""
if flags:
assert flags[0] != 'chrome'
# Avoid appending flags that are already present.
for flag in flags:
if flag not in self._current_flags:
self._current_flags.append(flag)
self._UpdateCommandLineFile()
def RemoveFlags(self, flags):
"""Removes flags from the command line, if they exist.
Args:
flags: A list of flags to remove, eg. ['--single-process']. Note that we
expect a complete match when removing flags; if you want to remove
a switch with a value, you must use the exact string used to add
it in the first place.
"""
if flags:
assert flags[0] != 'chrome'
for flag in flags:
if flag in self._current_flags:
self._current_flags.remove(flag)
self._UpdateCommandLineFile()
def Restore(self):
"""Restores the flags to their original state."""
self._current_flags = self._TokenizeFlags(self._orig_line)
self._UpdateCommandLineFile()
def _UpdateCommandLineFile(self):
"""Writes out the command line to the file, or removes it if empty."""
logging.info('Current flags: %s', self._current_flags)
# Root is not required to write to /data/local/tmp/.
use_root = '/data/local/tmp/' not in self._cmdline_file
if self._current_flags:
# The first command line argument doesn't matter as we are not actually
# launching the chrome executable using this command line.
cmd_line = ' '.join(['_'] + self._current_flags)
self._device.WriteFile(
self._cmdline_file, cmd_line, as_root=use_root)
file_contents = self._device.ReadFile(
self._cmdline_file, as_root=use_root).rstrip()
assert file_contents == cmd_line, (
'Failed to set the command line file at %s' % self._cmdline_file)
else:
self._device.RunShellCommand('rm ' + self._cmdline_file,
as_root=use_root)
assert not self._device.FileExists(self._cmdline_file), (
'Failed to remove the command line file at %s' % self._cmdline_file)
@staticmethod
def _TokenizeFlags(line):
"""Changes the string containing the command line into a list of flags.
Follows similar logic to CommandLine.java::tokenizeQuotedArguments:
* Flags are split using whitespace, unless the whitespace is within a
pair of quotation marks.
* Unlike the Java version, we keep the quotation marks around switch
values since we need them to re-create the file when new flags are
appended.
Args:
line: A string containing the entire command line. The first token is
assumed to be the program name.
"""
if not line:
return []
tokenized_flags = []
current_flag = ""
within_quotations = False
# Move through the string character by character and build up each flag
# along the way.
for c in line.strip():
if c is '"':
if len(current_flag) > 0 and current_flag[-1] == '\\':
# Last char was a backslash; pop it, and treat this " as a literal.
current_flag = current_flag[0:-1] + '"'
else:
within_quotations = not within_quotations
current_flag += c
elif not within_quotations and (c is ' ' or c is '\t'):
if current_flag is not "":
tokenized_flags.append(current_flag)
current_flag = ""
else:
current_flag += c
# Tack on the last flag.
if not current_flag:
if within_quotations:
logging.warn('Unterminated quoted argument: ' + line)
else:
tokenized_flags.append(current_flag)
# Return everything but the program name.
return tokenized_flags[1:]
|
Teamxrtc/webrtc-streaming-node
|
third_party/webrtc/src/chromium/src/build/android/pylib/flag_changer.py
|
Python
|
mit
| 5,496
|
-- avoid memory leak
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)
----------------
-- run
cc.FileUtils:getInstance():addSearchPath("src")
CC_USE_DEPRECATED_API = true
require "cocos.init"
local director = cc.Director:getInstance()
local glView = director:getOpenGLView()
if nil == glView then
glView = cc.GLViewImpl:createWithRect("Lua Tests", cc.rect(0,0,900,640))
director:setOpenGLView(glView)
end
--turn on display FPS
director:setDisplayStats(true)
--set FPS. the default value is 1.0/60 if you don't call this
director:setAnimationInterval(1.0 / 60)
local screenSize = glView:getFrameSize()
local designSize = {width = 480, height = 320}
if screenSize.height > 320 then
local resourceSize = {width = 960, height = 640}
cc.Director:getInstance():setContentScaleFactor(resourceSize.height/designSize.height)
end
glView:setDesignResolutionSize(designSize.width, designSize.height, cc.ResolutionPolicy.FIXED_HEIGHT)
local fileUtils = cc.FileUtils:getInstance()
local function addSearchPath(resPrefix, height)
local searchPaths = fileUtils:getSearchPaths()
table.insert(searchPaths, 1, resPrefix)
table.insert(searchPaths, 1, resPrefix .. "cocosbuilderRes")
if screenSize.height > 320 then
table.insert(searchPaths, 1, resPrefix .. "hd")
table.insert(searchPaths, 1, resPrefix .. "ccs-res")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/Images")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/ArmatureComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/AttributeComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/BackgroundComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/EffectComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/LoadSceneEdtiorFileTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/ParticleComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/SpriteComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/TmxMapComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/UIComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/scenetest/TriggerTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UIButton")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UICheckBox")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UIImageView")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UILabel")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UILabelBMFont")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UILayout/BackgroundImage")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UILayout/Color")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UILayout/Layout")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UILayout/Gradient_Color")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UILayout/LayoutComponent")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UILoadingBar")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UIPageView")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UIScrollView/Both")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UIScrollView/Horizontal")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UIScrollView/Vertical")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UISlider")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UITextField")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UIWidgetAddNode")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/hd/cocosui/UIEditorTest/UIListView/New")
table.insert(searchPaths, 1, resPrefix .. "hd/ActionTimeline")
else
table.insert(searchPaths, 1, resPrefix .. "ccs-res/Images")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/ArmatureComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/AttributeComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/BackgroundComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/EffectComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/LoadSceneEdtiorFileTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/ParticleComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/SpriteComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/TmxMapComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/UIComponentTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/scenetest/TriggerTest")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UIButton")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UICheckBox")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UIImageView")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UILabel")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UILabelBMFont")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UILayout/Color")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UILayout/Layout")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UILayout/LayoutComponent")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UILoadingBar")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UIPageView")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UIScrollView/Both")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UISlider")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UITextField")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UIWidgetAddNode")
table.insert(searchPaths, 1, resPrefix .. "ccs-res/cocosui/UIEditorTest/UIListView/New")
table.insert(searchPaths, 1, resPrefix .. "ActionTimeline")
end
fileUtils:setSearchPaths(searchPaths)
end
addSearchPath("res/", screenSize.height)
addSearchPath("", screenSize.height)
require "mainMenu"
local scene = cc.Scene:create()
scene:addChild(CreateTestMenu())
if cc.Director:getInstance():getRunningScene() then
cc.Director:getInstance():replaceScene(scene)
else
cc.Director:getInstance():runWithScene(scene)
end
|
dios-game/dios-cocos
|
src/oslibs/cocos/cocos-src/tests/lua-tests/src/controller.lua
|
Lua
|
mit
| 7,975
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Collections.Tests
{
public static class CollectionBaseTests
{
[Fact]
public static void Ctor_Empty()
{
var collBase = new MyCollection();
var arrList = new ArrayList();
Assert.Equal(0, collBase.Capacity);
Assert.Equal(arrList.Capacity, collBase.Capacity);
Assert.Equal(0, collBase.InnerListCapacity);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(1024)]
public static void Ctor_Capacity(int capacity)
{
var collBase = new MyCollection(capacity);
var arrList = new ArrayList(capacity);
Assert.Equal(capacity, collBase.Capacity);
Assert.Equal(arrList.Capacity, collBase.Capacity);
Assert.Equal(capacity, collBase.InnerListCapacity);
}
[Fact]
public static void CtorCapacity_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new MyCollection(-1)); // Capacity < 0
Assert.Throws<OutOfMemoryException>(() => new MyCollection(int.MaxValue)); // Capacity is too large
}
private static Foo CreateValue(int i) => new Foo(i, i.ToString());
private static MyCollection CreateCollection(int count)
{
var collBase = new MyCollection();
for (int i = 0; i < 100; i++)
{
collBase.Add(CreateValue(i));
}
return collBase;
}
[Fact]
public static void Add()
{
MyCollection collBase = new MyCollection();
for (int i = 0; i < 100; i++)
{
Foo value = CreateValue(i);
collBase.Add(value);
Assert.True(collBase.Contains(value));
}
Assert.Equal(100, collBase.Count);
for (int i = 0; i < collBase.Count; i++)
{
Foo value = CreateValue(i);
Assert.Equal(value, collBase[i]);
}
}
[Fact]
public static void Remove()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < 100; i++)
{
Foo value = CreateValue(i);
collBase.Remove(value);
Assert.False(collBase.Contains(value));
}
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Remove_Invalid()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentException>(null, () => collBase.Remove(new Foo())); // Non existent object
Assert.Equal(100, collBase.Count);
}
[Fact]
public static void Insert()
{
var collBase = new MyCollection();
for (int i = 0; i < 100; i++)
{
Foo value = CreateValue(i);
collBase.Insert(i, value);
Assert.True(collBase.Contains(value));
}
Assert.Equal(100, collBase.Count);
for (int i = 0; i < collBase.Count; i++)
{
var expected = CreateValue(i);
Assert.Equal(expected, collBase[i]);
}
}
[Fact]
public static void Insert_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase.Insert(-1, new Foo())); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase.Insert(collBase.Count + 1, new Foo())); // Index > collBase.Count
Assert.Equal(100, collBase.Count);
}
[Fact]
public static void RemoveAt()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
collBase.RemoveAt(0);
Assert.False(collBase.Contains(CreateValue(i)));
}
}
[Fact]
public static void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase.RemoveAt(-1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase.RemoveAt(collBase.Count)); // Index > collBase.Count
Assert.Equal(100, collBase.Count);
}
[Fact]
public static void Clear()
{
MyCollection collBase = CreateCollection(100);
collBase.Clear();
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void IndexOf()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
int ndx = collBase.IndexOf(CreateValue(i));
Assert.Equal(i, ndx);
}
}
[Fact]
public static void Contains()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
Assert.True(collBase.Contains(CreateValue(i)));
}
Assert.False(collBase.Contains(new Foo()));
}
[Fact]
public static void Item_Get()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
Assert.Equal(CreateValue(i), collBase[i]);
}
}
[Fact]
public static void Item_Get_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase[-1]); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase[collBase.Count]); // Index >= InnerList.Count
}
[Fact]
public static void Item_Set()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
var value = CreateValue(collBase.Count - i);
collBase[i] = value;
Assert.Equal(value, collBase[i]);
}
}
[Fact]
public static void Item_Set_Invalid()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase[-1] = new Foo()); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase[collBase.Count] = new Foo()); // Index >= InnerList.Count
Assert.Throws<ArgumentNullException>("value", () => collBase[0] = null); // Object is null
}
[Fact]
public static void CopyTo()
{
MyCollection collBase = CreateCollection(100);
// Basic
var fooArr = new Foo[100];
collBase.CopyTo(fooArr, 0);
Assert.Equal(collBase.Count, fooArr.Length);
for (int i = 0; i < fooArr.Length; i++)
{
Assert.Equal(collBase[i], fooArr.GetValue(i));
}
// With index
fooArr = new Foo[collBase.Count * 2];
collBase.CopyTo(fooArr, collBase.Count);
for (int i = collBase.Count; i < fooArr.Length; i++)
{
Assert.Equal(collBase[i - collBase.Count], fooArr.GetValue(i));
}
}
[Fact]
public static void CopyTo_Invalid()
{
MyCollection collBase = CreateCollection(100);
var fooArr = new Foo[100];
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => collBase.CopyTo(fooArr, -1));
// Index + fooArray.Length > collBase.Count
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => collBase.CopyTo(fooArr, 50));
}
[Fact]
public static void GetEnumerator()
{
MyCollection collBase = CreateCollection(100);
IEnumerator enumerator = collBase.GetEnumerator();
Assert.NotNull(enumerator);
int count = 0;
while (enumerator.MoveNext())
{
Assert.Equal(collBase[count], enumerator.Current);
count++;
}
Assert.Equal(collBase.Count, count);
}
[Fact]
public static void GetEnumerator_Invalid()
{
MyCollection collBase = CreateCollection(100);
IEnumerator enumerator = collBase.GetEnumerator();
// Index < 0
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Index >= dictionary.Count
while (enumerator.MoveNext()) ;
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.False(enumerator.MoveNext());
// Current throws after resetting
enumerator.Reset();
Assert.True(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Fact]
public static void SyncRoot()
{
// SyncRoot should be the reference to the underlying collection, not to MyCollection
var collBase = new MyCollection();
object syncRoot = collBase.SyncRoot;
Assert.NotEqual(syncRoot, collBase);
Assert.Equal(collBase.SyncRoot, collBase.SyncRoot);
}
[Fact]
public static void IListProperties()
{
MyCollection collBase = CreateCollection(100);
Assert.False(collBase.IsFixedSize);
Assert.False(collBase.IsReadOnly);
Assert.False(collBase.IsSynchronized);
}
[Fact]
public static void CapacityGet()
{
var collBase = new MyCollection(new string[10]);
Assert.True(collBase.Capacity >= collBase.Count);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(44)]
public static void CapacitySet(int capacity)
{
var collBase = new MyCollection(0);
collBase.Capacity = capacity;
Assert.Equal(capacity, collBase.Capacity);
}
[Fact]
public static void Capacity_Set_Invalid()
{
var collBase = new MyCollection(new string[10]);
Assert.Throws<ArgumentOutOfRangeException>("value", () => collBase.Capacity = -1); // Capacity < 0
Assert.Throws<OutOfMemoryException>(() => collBase.Capacity = int.MaxValue); // Capacity is very large
Assert.Throws<ArgumentOutOfRangeException>("value", () => collBase.Capacity = collBase.Count - 1); // Capacity < list.Count
}
[Fact]
public static void Add_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnInsertCalled);
Assert.True(collBase.OnInsertCompleteCalled);
Assert.True(collBase.Contains(f));
}
[Fact]
public static void Add_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase.Add(f));
Assert.Equal(0, collBase.Count);
// Throw OnInsert
collBase = new OnMethodCalledCollectionBase();
collBase.OnInsertThrow = true;
Assert.Throws<Exception>(() => collBase.Add(f));
Assert.Equal(0, collBase.Count);
// Throw OnInsertComplete
collBase = new OnMethodCalledCollectionBase();
collBase.OnInsertCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.Add(f));
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Insert_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Insert(0, f);
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnInsertCalled);
Assert.True(collBase.OnInsertCompleteCalled);
Assert.True(collBase.Contains(f));
}
[Fact]
public static void Insert_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase.Insert(0, f));
Assert.Equal(0, collBase.Count);
// Throw OnInsert
collBase = new OnMethodCalledCollectionBase();
collBase.OnInsertThrow = true;
Assert.Throws<Exception>(() => collBase.Insert(0, f));
Assert.Equal(0, collBase.Count);
// Throw OnInsertComplete
collBase = new OnMethodCalledCollectionBase();
collBase.OnInsertCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.Insert(0, f));
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Remove_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateCalled = false;
collBase.Remove(f);
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnRemoveCalled);
Assert.True(collBase.OnRemoveCompleteCalled);
Assert.False(collBase.Contains(f));
}
[Fact]
public static void Remove_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase.Remove(f));
Assert.Equal(1, collBase.Count);
// Throw OnRemove
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnRemoveThrow = true;
Assert.Throws<Exception>(() => collBase.Remove(f));
Assert.Equal(1, collBase.Count);
// Throw OnRemoveComplete
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnRemoveCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.Remove(f));
Assert.Equal(1, collBase.Count);
}
[Fact]
public static void RemoveAt_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateCalled = false;
collBase.RemoveAt(0);
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnRemoveCalled);
Assert.True(collBase.OnRemoveCompleteCalled);
Assert.False(collBase.Contains(f));
}
[Fact]
public static void RemoveAt_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase.RemoveAt(0));
Assert.Equal(1, collBase.Count);
// Throw OnRemove
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnRemoveThrow = true;
Assert.Throws<Exception>(() => collBase.RemoveAt(0));
Assert.Equal(1, collBase.Count);
// Throw OnRemoveComplete
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnRemoveCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.RemoveAt(0));
Assert.Equal(1, collBase.Count);
}
[Fact]
public static void Clear_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.Clear();
Assert.True(collBase.OnClearCalled);
Assert.True(collBase.OnClearCompleteCalled);
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Clear_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateThrow = true;
collBase.Clear();
Assert.Equal(0, collBase.Count);
// Throw OnClear
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnClearThrow = true;
Assert.Throws<Exception>(() => collBase.Clear());
Assert.Equal(1, collBase.Count);
// Throw OnClearComplete
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnClearCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.Clear());
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Set_Called()
{
var f = new Foo(1, "1");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(new Foo());
collBase.OnValidateCalled = false;
collBase[0] = f;
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnSetCalled);
Assert.True(collBase.OnSetCompleteCalled);
Assert.Equal(f, collBase[0]);
}
[Fact]
public static void Set_Throws_Called()
{
var f1 = new Foo(0, "0");
var f2 = new Foo(1, "1");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f1);
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase[0] = f2);
Assert.Equal(f1, collBase[0]);
// Throw OnSet
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f1);
collBase.OnSetThrow = true;
Assert.Throws<Exception>(() => collBase[0] = f2);
Assert.Equal(f1, collBase[0]);
// Throw OnSetComplete
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f1);
collBase.OnSetCompleteThrow = true;
Assert.Throws<Exception>(() => collBase[0] = f2);
Assert.Equal(f1, collBase[0]);
}
// CollectionBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here
private class MyCollection : CollectionBase
{
public MyCollection() : base()
{
}
public MyCollection(int capacity) : base(capacity)
{
}
public MyCollection(ICollection collection) : base()
{
foreach (object obj in collection)
{
InnerList.Add(obj);
}
}
public int InnerListCapacity
{
get { return InnerList.Capacity; }
}
public int Add(Foo f1) => List.Add(f1);
public Foo this[int indx]
{
get { return (Foo)List[indx]; }
set { List[indx] = value; }
}
public void CopyTo(Array array, int index) => List.CopyTo(array, index);
public int IndexOf(Foo f) => List.IndexOf(f);
public bool Contains(Foo f) => List.Contains(f);
public void Insert(int index, Foo f) => List.Insert(index, f);
public void Remove(Foo f) => List.Remove(f);
public bool IsSynchronized
{
get { return ((ICollection)this).IsSynchronized; }
}
public object SyncRoot
{
get { return ((ICollection)this).SyncRoot; }
}
public bool IsReadOnly
{
get { return List.IsReadOnly; }
}
public bool IsFixedSize
{
get { return List.IsFixedSize; }
}
}
private class OnMethodCalledCollectionBase : CollectionBase
{
public bool OnValidateCalled;
public bool OnSetCalled;
public bool OnSetCompleteCalled;
public bool OnInsertCalled;
public bool OnInsertCompleteCalled;
public bool OnClearCalled;
public bool OnClearCompleteCalled;
public bool OnRemoveCalled;
public bool OnRemoveCompleteCalled;
public bool OnValidateThrow;
public bool OnSetThrow;
public bool OnSetCompleteThrow;
public bool OnInsertThrow;
public bool OnInsertCompleteThrow;
public bool OnClearThrow;
public bool OnClearCompleteThrow;
public bool OnRemoveThrow;
public bool OnRemoveCompleteThrow;
public int Add(Foo f1) => List.Add(f1);
public Foo this[int indx]
{
get { return (Foo)List[indx]; }
set { List[indx] = value; }
}
public void CopyTo(Array array, int index) => List.CopyTo(array, index);
public int IndexOf(Foo f) => List.IndexOf(f);
public bool Contains(Foo f) => List.Contains(f);
public void Insert(int index, Foo f) => List.Insert(index, f);
public void Remove(Foo f) => List.Remove(f);
protected override void OnSet(int index, object oldValue, object newValue)
{
Assert.True(OnValidateCalled);
Assert.Equal(this[index], oldValue);
OnSetCalled = true;
if (OnSetThrow)
throw new Exception("OnSet");
}
protected override void OnInsert(int index, object value)
{
Assert.True(OnValidateCalled);
Assert.True(index <= Count);
if (index != Count)
{
Assert.Equal(this[index], value);
}
OnInsertCalled = true;
if (OnInsertThrow)
throw new Exception("OnInsert");
}
protected override void OnClear()
{
OnClearCalled = true;
if (OnClearThrow)
throw new Exception("OnClear");
}
protected override void OnRemove(int index, object value)
{
Assert.True(OnValidateCalled);
Assert.Equal(this[index], value);
OnRemoveCalled = true;
if (OnRemoveThrow)
throw new Exception("OnRemove");
}
protected override void OnValidate(object value)
{
OnValidateCalled = true;
if (OnValidateThrow)
throw new Exception("OnValidate");
}
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
Assert.True(OnSetCalled);
Assert.Equal(this[index], newValue);
OnSetCompleteCalled = true;
if (OnSetCompleteThrow)
throw new Exception("OnSetComplete");
}
protected override void OnInsertComplete(int index, object value)
{
Assert.True(OnInsertCalled);
Assert.Equal(this[index], value);
OnInsertCompleteCalled = true;
if (OnInsertCompleteThrow)
throw new Exception("OnInsertComplete");
}
protected override void OnClearComplete()
{
Assert.True(OnClearCalled);
Assert.Equal(0, Count);
Assert.Equal(0, InnerList.Count);
OnClearCompleteCalled = true;
if (OnClearCompleteThrow)
throw new Exception("OnClearComplete");
}
protected override void OnRemoveComplete(int index, object value)
{
Assert.True(OnRemoveCalled);
Assert.NotEqual(IndexOf((Foo)value), index);
OnRemoveCompleteCalled = true;
if (OnRemoveCompleteThrow)
throw new Exception("OnRemoveComplete");
}
}
private class Foo
{
public Foo()
{
}
public Foo(int intValue, string stringValue)
{
IntValue = intValue;
StringValue = stringValue;
}
public int IntValue { get; set; }
public string StringValue { get; set; }
public override bool Equals(object obj)
{
Foo foo = obj as Foo;
if (foo == null)
return false;
return foo.IntValue == IntValue && foo.StringValue == StringValue;
}
public override int GetHashCode() => IntValue;
}
}
}
|
marksmeltzer/corefx
|
src/System.Collections.NonGeneric/tests/CollectionBaseTests.cs
|
C#
|
mit
| 26,579
|
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2015-2016 Intel Corporation.
*
* 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.
*/
#pragma once
#include <iostream>
#include <string>
#include "lm35.h"
namespace upm {
/**
* @brief DFRobot LM35 Linear Temperature Sensor
* @defgroup lm35 libupm-lm35
* @ingroup dfrobot analog temp
*/
/**
* @library lm35
* @sensor lm35
* @comname Analog Temperature Sensor
* @altname LM35
* @type temp
* @man dfrobot
* @web http://www.dfrobot.com/index.php?route=product/product&product_id=76
* @con analog
*
* @brief API for the DFRobot LM35 Linear Temperature Sensor
*
* This sensor returns an analog voltage proportional to the
* temperature of the ambient environment.
*
* It has a range of 2C to 150C.
*
* This driver was developed using the DFRobot LM35 Linear
* Temperature Sensor
*
* @image html lm35.jpg
* @snippet lm35.cxx Interesting
*/
class LM35 {
public:
/**
* LM35 constructor
*
* @param pin Analog pin to use
* @param aref Analog reference voltage; default is 5.0 V
*/
LM35(int pin, float aref=5.0);
/**
* LM35 destructor
*/
~LM35();
/**
* Returns the temperature in degrees Celsius
*
* @return The Temperature in degrees Celsius
*/
float getTemperature();
/**
* Set sensor scale. This scale is applied to the return values
* before the offset is applied. Default is 1.0.
*
* @param scale Scale to apply.
*/
void setScale(float scale);
/**
* Set sensor offset. This offset is applied to the return values
* before scaling. Default is 0.0.
*
* @param offset Offset to apply.
*/
void setOffset(float offset);
protected:
lm35_context m_lm35;
private:
/* Disable implicit copy and assignment operators */
LM35(const LM35&) = delete;
LM35 &operator=(const LM35&) = delete;
};
}
|
malikabhi05/upm
|
src/lm35/lm35.hpp
|
C++
|
mit
| 3,235
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.appservice;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Database backup settings.
*/
public class DatabaseBackupSetting {
/**
* Database type (e.g. SqlAzure / MySql). Possible values include:
* 'SqlAzure', 'MySql', 'LocalMySql', 'PostgreSql'.
*/
@JsonProperty(value = "databaseType", required = true)
private DatabaseType databaseType;
/**
* The name property.
*/
@JsonProperty(value = "name")
private String name;
/**
* Contains a connection string name that is linked to the
* SiteConfig.ConnectionStrings.
* This is used during restore with overwrite connection strings options.
*/
@JsonProperty(value = "connectionStringName")
private String connectionStringName;
/**
* Contains a connection string to a database which is being backed up or
* restored. If the restore should happen to a new database, the database
* name inside is the new one.
*/
@JsonProperty(value = "connectionString")
private String connectionString;
/**
* Get the databaseType value.
*
* @return the databaseType value
*/
public DatabaseType databaseType() {
return this.databaseType;
}
/**
* Set the databaseType value.
*
* @param databaseType the databaseType value to set
* @return the DatabaseBackupSetting object itself.
*/
public DatabaseBackupSetting withDatabaseType(DatabaseType databaseType) {
this.databaseType = databaseType;
return this;
}
/**
* Get the name value.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name value.
*
* @param name the name value to set
* @return the DatabaseBackupSetting object itself.
*/
public DatabaseBackupSetting withName(String name) {
this.name = name;
return this;
}
/**
* Get the connectionStringName value.
*
* @return the connectionStringName value
*/
public String connectionStringName() {
return this.connectionStringName;
}
/**
* Set the connectionStringName value.
*
* @param connectionStringName the connectionStringName value to set
* @return the DatabaseBackupSetting object itself.
*/
public DatabaseBackupSetting withConnectionStringName(String connectionStringName) {
this.connectionStringName = connectionStringName;
return this;
}
/**
* Get the connectionString value.
*
* @return the connectionString value
*/
public String connectionString() {
return this.connectionString;
}
/**
* Set the connectionString value.
*
* @param connectionString the connectionString value to set
* @return the DatabaseBackupSetting object itself.
*/
public DatabaseBackupSetting withConnectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
}
|
jianghaolu/azure-sdk-for-java
|
azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/DatabaseBackupSetting.java
|
Java
|
mit
| 3,336
|
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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.
namespace SharpDX.Toolkit.Graphics
{
public struct VertexBufferBinding
{
public Buffer Buffer;
public VertexInputLayout Layout;
}
}
|
VirusFree/SharpDX
|
Source/Toolkit/SharpDX.Toolkit.Graphics/VertexBufferBinding.cs
|
C#
|
mit
| 1,295
|
var Utils = require("../../utils")
, sqlite3 = require('sqlite3').verbose()
, Query = require("./query")
module.exports = (function() {
var ConnectorManager = function(sequelize) {
this.sequelize = sequelize
this.database = db = new sqlite3.Database(sequelize.options.storage || ':memory:', function(err) {
if(!err && sequelize.options.foreignKeys !== false) {
// Make it possible to define and use foreign key constraints unless
// explicitly disallowed. It's still opt-in per relation
db.run('PRAGMA FOREIGN_KEYS=ON')
}
})
}
Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype)
ConnectorManager.prototype.query = function(sql, callee, options) {
return new Query(this.database, this.sequelize, callee, options).run(sql)
}
return ConnectorManager
})()
|
szizor/chato
|
node_modules/sequelize/lib/dialects/sqlite/connector-manager.js
|
JavaScript
|
mit
| 862
|
# Override the default ActiveRecordHelper behaviour of wrapping the input.
# This gets taken care of semantically by adding an error class to the LI tag
# containing the input.
ActionView::Base.field_error_proc = proc do |html_tag, instance_tag|
html_tag
end
module Formtastic #:nodoc:
class SemanticFormBuilder < ActionView::Helpers::FormBuilder
@@default_text_field_size = 50
@@all_fields_required_by_default = true
@@required_string = proc { %{<abbr title="#{I18n.t 'formtastic.required', :default => 'required'}">*</abbr>} }
@@optional_string = ''
@@inline_errors = :sentence
@@label_str_method = :humanize
@@collection_label_methods = %w[to_label display_name full_name name title username login value to_s]
@@inline_order = [ :input, :hints, :errors ]
@@file_methods = [ :file?, :public_filename ]
@@priority_countries = ["Australia", "Canada", "United Kingdom", "United States"]
cattr_accessor :default_text_field_size, :all_fields_required_by_default, :required_string,
:optional_string, :inline_errors, :label_str_method, :collection_label_methods,
:inline_order, :file_methods, :priority_countries
# Keeps simple mappings in a hash
INPUT_MAPPINGS = {
:string => :text_field,
:password => :password_field,
:numeric => :text_field,
:text => :text_area,
:file => :file_field
}
STRING_MAPPINGS = [ :string, :password, :numeric ]
attr_accessor :template
# Returns a suitable form input for the given +method+, using the database column information
# and other factors (like the method name) to figure out what you probably want.
#
# Options:
#
# * :as - override the input type (eg force a :string to render as a :password field)
# * :label - use something other than the method name as the label text, when false no label is printed
# * :required - specify if the column is required (true) or not (false)
# * :hint - provide some text to hint or help the user provide the correct information for a field
# * :input_html - provide options that will be passed down to the generated input
# * :wrapper_html - provide options that will be passed down to the li wrapper
#
# Input Types:
#
# Most inputs map directly to one of ActiveRecord's column types by default (eg string_input),
# but there are a few special cases and some simplification (:integer, :float and :decimal
# columns all map to a single numeric_input, for example).
#
# * :select (a select menu for associations) - default to association names
# * :check_boxes (a set of check_box inputs for associations) - alternative to :select has_many and has_and_belongs_to_many associations
# * :radio (a set of radio inputs for associations) - alternative to :select belongs_to associations
# * :time_zone (a select menu with time zones)
# * :password (a password input) - default for :string column types with 'password' in the method name
# * :text (a textarea) - default for :text column types
# * :date (a date select) - default for :date column types
# * :datetime (a date and time select) - default for :datetime and :timestamp column types
# * :time (a time select) - default for :time column types
# * :boolean (a checkbox) - default for :boolean column types (you can also have booleans as :select and :radio)
# * :string (a text field) - default for :string column types
# * :numeric (a text field, like string) - default for :integer, :float and :decimal column types
# * :country (a select menu of country names) - requires a country_select plugin to be installed
# * :hidden (a hidden field) - creates a hidden field (added for compatibility)
#
# Example:
#
# <% semantic_form_for @employee do |form| %>
# <% form.inputs do -%>
# <%= form.input :name, :label => "Full Name"%>
# <%= form.input :manager_id, :as => :radio %>
# <%= form.input :hired_at, :as => :date, :label => "Date Hired" %>
# <%= form.input :phone, :required => false, :hint => "Eg: +1 555 1234" %>
# <% end %>
# <% end %>
#
def input(method, options = {})
options[:required] = method_required?(method) unless options.key?(:required)
options[:as] ||= default_input_type(method)
html_class = [ options[:as], (options[:required] ? :required : :optional) ]
html_class << 'error' if @object && @object.respond_to?(:errors) && @object.errors.on(method.to_s)
wrapper_html = options.delete(:wrapper_html) || {}
wrapper_html[:id] ||= generate_html_id(method)
wrapper_html[:class] = (html_class << wrapper_html[:class]).flatten.compact.join(' ')
if [:boolean_select, :boolean_radio].include?(options[:as])
::ActiveSupport::Deprecation.warn(":as => :#{options[:as]} is deprecated, use :as => :#{options[:as].to_s[8..-1]} instead", caller[3..-1])
end
list_item_content = @@inline_order.map do |type|
send(:"inline_#{type}_for", method, options)
end.compact.join("\n")
return template.content_tag(:li, list_item_content, wrapper_html)
end
# Creates an input fieldset and ol tag wrapping for use around a set of inputs. It can be
# called either with a block (in which you can do the usual Rails form stuff, HTML, ERB, etc),
# or with a list of fields. These two examples are functionally equivalent:
#
# # With a block:
# <% semantic_form_for @post do |form| %>
# <% form.inputs do %>
# <%= form.input :title %>
# <%= form.input :body %>
# <% end %>
# <% end %>
#
# # With a list of fields:
# <% semantic_form_for @post do |form| %>
# <%= form.inputs :title, :body %>
# <% end %>
#
# # Output:
# <form ...>
# <fieldset class="inputs">
# <ol>
# <li class="string">...</li>
# <li class="text">...</li>
# </ol>
# </fieldset>
# </form>
#
# === Quick Forms
#
# When called without a block or a field list, an input is rendered for each column in the
# model's database table, just like Rails' scaffolding. You'll obviously want more control
# than this in a production application, but it's a great way to get started, then come back
# later to customise the form with a field list or a block of inputs. Example:
#
# <% semantic_form_for @post do |form| %>
# <%= form.inputs %>
# <% end %>
#
# === Options
#
# All options (with the exception of :name) are passed down to the fieldset as HTML
# attributes (id, class, style, etc). If provided, the :name option is passed into a
# legend tag inside the fieldset (otherwise a legend is not generated).
#
# # With a block:
# <% semantic_form_for @post do |form| %>
# <% form.inputs :name => "Create a new post", :style => "border:1px;" do %>
# ...
# <% end %>
# <% end %>
#
# # With a list (the options must come after the field list):
# <% semantic_form_for @post do |form| %>
# <%= form.inputs :title, :body, :name => "Create a new post", :style => "border:1px;" %>
# <% end %>
#
# === It's basically a fieldset!
#
# Instead of hard-coding fieldsets & legends into your form to logically group related fields,
# use inputs:
#
# <% semantic_form_for @post do |f| %>
# <% f.inputs do %>
# <%= f.input :title %>
# <%= f.input :body %>
# <% end %>
# <% f.inputs :name => "Advanced", :id => "advanced" do %>
# <%= f.input :created_at %>
# <%= f.input :user_id, :label => "Author" %>
# <% end %>
# <% end %>
#
# # Output:
# <form ...>
# <fieldset class="inputs">
# <ol>
# <li class="string">...</li>
# <li class="text">...</li>
# </ol>
# </fieldset>
# <fieldset class="inputs" id="advanced">
# <legend><span>Advanced</span></legend>
# <ol>
# <li class="datetime">...</li>
# <li class="select">...</li>
# </ol>
# </fieldset>
# </form>
#
# === Nested attributes
#
# As in Rails, you can use semantic_fields_for to nest attributes:
#
# <% semantic_form_for @post do |form| %>
# <%= form.inputs :title, :body %>
#
# <% form.semantic_fields_for :author, @bob do |author_form| %>
# <% author_form.inputs do %>
# <%= author_form.input :first_name, :required => false %>
# <%= author_form.input :last_name %>
# <% end %>
# <% end %>
# <% end %>
#
# But this does not look formtastic! This is equivalent:
#
# <% semantic_form_for @post do |form| %>
# <%= form.inputs :title, :body %>
# <% form.inputs :for => [ :author, @bob ] do |author_form| %>
# <%= author_form.input :first_name, :required => false %>
# <%= author_form.input :last_name %>
# <% end %>
# <% end %>
#
# And if you don't need to give options to your input call, you could do it
# in just one line:
#
# <% semantic_form_for @post do |form| %>
# <%= form.inputs :title, :body %>
# <%= form.inputs :first_name, :last_name, :for => @bob %>
# <% end %>
#
# Just remember that calling inputs generates a new fieldset to wrap your
# inputs. If you have two separate models, but, semantically, on the page
# they are part of the same fieldset, you should use semantic_fields_for
# instead (just as you would do with Rails' form builder).
#
def inputs(*args, &block)
html_options = args.extract_options!
html_options[:class] ||= "inputs"
if html_options[:for]
inputs_for_nested_attributes(args, html_options, &block)
elsif block_given?
field_set_and_list_wrapping(html_options, &block)
else
if @object && args.empty?
args = @object.class.reflections.map { |n,_| n if _.macro == :belongs_to }
args += @object.class.content_columns.map(&:name)
args -= %w[created_at updated_at created_on updated_on lock_version]
args.compact!
end
contents = args.map { |method| input(method.to_sym) }
field_set_and_list_wrapping(html_options, contents)
end
end
alias :input_field_set :inputs
# Creates a fieldset and ol tag wrapping for form buttons / actions as list items.
# See inputs documentation for a full example. The fieldset's default class attriute
# is set to "buttons".
#
# See inputs for html attributes and special options.
def buttons(*args, &block)
html_options = args.extract_options!
html_options[:class] ||= "buttons"
if block_given?
field_set_and_list_wrapping(html_options, &block)
else
args = [:commit] if args.empty?
contents = args.map { |button_name| send(:"#{button_name}_button") }
field_set_and_list_wrapping(html_options, contents)
end
end
alias :button_field_set :buttons
# Creates a submit input tag with the value "Save [model name]" (for existing records) or
# "Create [model name]" (for new records) by default:
#
# <%= form.commit_button %> => <input name="commit" type="submit" value="Save Post" />
#
# The value of the button text can be overridden:
#
# <%= form.commit_button "Go" %> => <input name="commit" type="submit" value="Go" />
#
# And you can pass html atributes down to the input, with or without the button text:
#
# <%= form.commit_button "Go" %> => <input name="commit" type="submit" value="Go" />
# <%= form.commit_button :class => "pretty" %> => <input name="commit" type="submit" value="Save Post" class="pretty" />
def commit_button(*args)
value = args.first.is_a?(String) ? args.shift : save_or_create_button_text
options = args.shift || {}
button_html = options.delete(:button_html) || {}
template.content_tag(:li, self.submit(value, button_html), :class => "commit")
end
# A thin wrapper around #fields_for to set :builder => Formtastic::SemanticFormBuilder
# for nesting forms:
#
# # Example:
# <% semantic_form_for @post do |post| %>
# <% post.semantic_fields_for :author do |author| %>
# <% author.inputs :name %>
# <% end %>
# <% end %>
#
# # Output:
# <form ...>
# <fieldset class="inputs">
# <ol>
# <li class="string"><input type='text' name='post[author][name]' id='post_author_name' /></li>
# </ol>
# </fieldset>
# </form>
#
def semantic_fields_for(record_or_name_or_array, *args, &block)
opts = args.extract_options!
opts.merge!(:builder => Formtastic::SemanticFormBuilder)
args.push(opts)
fields_for(record_or_name_or_array, *args, &block)
end
# Generates the label for the input. It also accepts the same arguments as
# Rails label method. It has three options that are not supported by Rails
# label method:
#
# * :required - Appends an abbr tag if :required is true
# * :label - An alternative form to give the label content. Whenever label
# is false, a blank string is returned.
# * :as_span - When true returns a span tag with class label instead of a label element
#
# == Examples
#
# f.label :title # like in rails, except that it searches the label on I18n API too
#
# f.label :title, "Your post title"
# f.label :title, :label => "Your post title" # Added for formtastic API
#
# f.label :title, :required => true # Returns <label>Title<abbr title="required">*</abbr></label>
#
def label(method, options_or_text=nil, options=nil)
if options_or_text.is_a?(Hash)
return if options_or_text[:label] == false
options = options_or_text
text = options.delete(:label)
else
text = options_or_text
options ||= {}
end
text ||= humanized_attribute_name(method)
text << required_or_optional_string(options.delete(:required))
if options.delete(:as_span)
options[:class] ||= 'label'
template.content_tag(:span, text, options)
else
super(method, text, options)
end
end
# Generates error messages for the given method. Errors can be shown as list
# or as sentence. If :none is set, no error is shown.
#
# This method is also aliased as errors_on, so you can call on your custom
# inputs as well:
#
# semantic_form_for :post do |f|
# f.text_field(:body)
# f.errors_on(:body)
# end
#
def inline_errors_for(method, options=nil) #:nodoc:
return nil unless @object && @object.respond_to?(:errors) && [:sentence, :list].include?(@@inline_errors)
errors = @object.errors.on(method.to_s)
send("error_#{@@inline_errors}", Array(errors)) unless errors.blank?
end
alias :errors_on :inline_errors_for
protected
# Deals with :for option when it's supplied to inputs methods. Additional
# options to be passed down to :for should be supplied using :for_options
# key.
#
# It should raise an error if a block with arity zero is given.
#
def inputs_for_nested_attributes(args, options, &block)
args << options.merge!(:parent => { :builder => self, :for => options[:for] })
fields_for_block = if block_given?
raise ArgumentError, 'You gave :for option with a block to inputs method, ' <<
'but the block does not accept any argument.' if block.arity <= 0
proc { |f| f.inputs(*args){ block.call(f) } }
else
proc { |f| f.inputs(*args) }
end
fields_for_args = [options.delete(:for), options.delete(:for_options) || {}].flatten
semantic_fields_for(*fields_for_args, &fields_for_block)
end
# Remove any Formtastic-specific options before passing the down options.
#
def set_options(options)
options.except(:value_method, :label_method, :collection, :required, :label,
:as, :hint, :input_html, :label_html, :value_as_class)
end
# Create a default button text. If the form is working with a object, it
# defaults to "Create model" or "Save model" depending if we are working
# with a new_record or not.
#
# When not working with models, it defaults to "Submit object".
#
def save_or_create_button_text(prefix='Submit') #:nodoc:
if @object
prefix = @object.new_record? ? 'Create' : 'Save'
object_name = @object.class.human_name
else
object_name = @object_name.to_s.send(@@label_str_method)
end
I18n.t(prefix.downcase, :default => prefix, :scope => [:formtastic]) << ' ' << object_name
end
# Determins if the attribute (eg :title) should be considered required or not.
#
# * if the :required option was provided in the options hash, the true/false value will be
# returned immediately, allowing the view to override any guesswork that follows:
#
# * if the :required option isn't provided in the options hash, and the ValidationReflection
# plugin is installed (http://github.com/redinger/validation_reflection), true is returned
# if the validates_presence_of macro has been used in the class for this attribute, or false
# otherwise.
#
# * if the :required option isn't provided, and the plugin isn't available, the value of the
# configuration option @@all_fields_required_by_default is used.
#
def method_required?(attribute) #:nodoc:
if @object && @object.class.respond_to?(:reflect_on_all_validations)
attribute_sym = attribute.to_s.sub(/_id$/, '').to_sym
@object.class.reflect_on_all_validations.any? do |validation|
validation.macro == :validates_presence_of && validation.name == attribute_sym
end
else
@@all_fields_required_by_default
end
end
# A method that deals with most of inputs (:string, :password, :file,
# :textarea and :numeric). :select, :radio, :boolean and :datetime inputs
# are not handled by this method, since they need more detailed approach.
#
# If input_html is given as option, it's passed down to the input.
#
def input_simple(type, method, options)
html_options = options.delete(:input_html) || {}
html_options = default_string_options(method).merge(html_options) if STRING_MAPPINGS.include?(type)
self.label(method, options.slice(:label, :required)) +
self.send(INPUT_MAPPINGS[type], method, html_options)
end
# Outputs a hidden field inside the wrapper, which should be hidden with CSS.
# Additionals options can be given and will be sent straight to hidden input
# element.
#
def hidden_input(method, options)
self.hidden_field(method, set_options(options))
end
# Outputs a label and a select box containing options from the parent
# (belongs_to, has_many, has_and_belongs_to_many) association. If an association
# is has_many or has_and_belongs_to_many the select box will be set as multi-select
# and size = 5
#
# Example (belongs_to):
#
# f.input :author
#
# <label for="book_author_id">Author</label>
# <select id="book_author_id" name="book[author_id]">
# <option value=""></option>
# <option value="1">Justin French</option>
# <option value="2">Jane Doe</option>
# </select>
#
# Example (has_many):
#
# f.input :chapters
#
# <label for="book_chapter_ids">Chapters</label>
# <select id="book_chapter_ids" name="book[chapter_ids]">
# <option value=""></option>
# <option value="1">Chapter 1</option>
# <option value="2">Chapter 2</option>
# </select>
#
# Example (has_and_belongs_to_many):
#
# f.input :authors
#
# <label for="book_author_ids">Authors</label>
# <select id="book_author_ids" name="book[author_ids]">
# <option value=""></option>
# <option value="1">Justin French</option>
# <option value="2">Jane Doe</option>
# </select>
#
#
# You can customize the options available in the select by passing in a collection (Array) of
# ActiveRecord objects through the :collection option. If not provided, the choices are found
# by inferring the parent's class name from the method name and simply calling find(:all) on
# it (VehicleOwner.find(:all) in the example above).
#
# Examples:
#
# f.input :author, :collection => @authors
# f.input :author, :collection => Author.find(:all)
# f.input :author, :collection => [@justin, @kate]
# f.input :author, :collection => {@justin.name => @justin.id, @kate.name => @kate.id}
#
# Note: This input looks for a label method in the parent association.
#
# You can customize the text label inside each option tag, by naming the correct method
# (:full_name, :display_name, :account_number, etc) to call on each object in the collection
# by passing in the :label_method option. By default the :label_method is whichever element of
# Formtastic::SemanticFormBuilder.collection_label_methods is found first.
#
# Examples:
#
# f.input :author, :label_method => :full_name
# f.input :author, :label_method => :display_name
# f.input :author, :label_method => :to_s
# f.input :author, :label_method => :label
#
# You can also customize the value inside each option tag, by passing in the :value_method option.
# Usage is the same as the :label_method option
#
# Examples:
#
# f.input :author, :value_method => :full_name
# f.input :author, :value_method => :display_name
# f.input :author, :value_method => :to_s
# f.input :author, :value_method => :value
#
# You can pass html_options to the select tag using :input_html => {}
#
# Examples:
#
# f.input :authors, :input_html => {:size => 20, :multiple => true}
#
# By default, all select inputs will have a blank option at the top of the list. You can add
# a prompt with the :prompt option, or disable the blank option with :include_blank => false.
#
def select_input(method, options)
collection = find_collection_for_column(method, options)
html_options = options.delete(:input_html) || {}
unless options.key?(:include_blank) || options.key?(:prompt)
options[:include_blank] = true
end
reflection = find_reflection(method)
if reflection && [ :has_many, :has_and_belongs_to_many ].include?(reflection.macro)
html_options[:multiple] ||= true
html_options[:size] ||= 5
end
input_name = generate_association_input_name(method)
self.label(input_name, options.slice(:label, :required)) +
self.select(input_name, collection, set_options(options), html_options)
end
alias :boolean_select_input :select_input
# Outputs a timezone select input as Rails' time_zone_select helper. You
# can give priority zones as option.
#
# Examples:
#
# f.input :time_zone, :as => :time_zone, :priority_zones => /Australia/
#
def time_zone_input(method, options)
html_options = options.delete(:input_html) || {}
self.label(method, options.slice(:label, :required)) +
self.time_zone_select(method, options.delete(:priority_zones), set_options(options), html_options)
end
# Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list
# items, one for each possible choice in the belongs_to association. Each li contains a
# label and a radio input.
#
# Example:
#
# f.input :author, :as => :radio
#
# Output:
#
# <fieldset>
# <legend><span>Author</span></legend>
# <ol>
# <li>
# <label for="book_author_id_1"><input id="book_author_id_1" name="book[author_id]" type="radio" value="1" /> Justin French</label>
# </li>
# <li>
# <label for="book_author_id_2"><input id="book_author_id_2" name="book[owner_id]" type="radio" value="2" /> Kate French</label>
# </li>
# </ol>
# </fieldset>
#
# You can customize the options available in the set by passing in a collection (Array) of
# ActiveRecord objects through the :collection option. If not provided, the choices are found
# by inferring the parent's class name from the method name and simply calling find(:all) on
# it (Author.find(:all) in the example above).
#
# Examples:
#
# f.input :author, :as => :radio, :collection => @authors
# f.input :author, :as => :radio, :collection => Author.find(:all)
# f.input :author, :as => :radio, :collection => [@justin, @kate]
#
# You can also customize the text label inside each option tag, by naming the correct method
# (:full_name, :display_name, :account_number, etc) to call on each object in the collection
# by passing in the :label_method option. By default the :label_method is whichever element of
# Formtastic::SemanticFormBuilder.collection_label_methods is found first.
#
# Examples:
#
# f.input :author, :as => :radio, :label_method => :full_name
# f.input :author, :as => :radio, :label_method => :display_name
# f.input :author, :as => :radio, :label_method => :to_s
# f.input :author, :as => :radio, :label_method => :label
#
# Finally, you can set :value_as_class => true if you want that LI wrappers
# contains a class with the wrapped radio input value.
#
def radio_input(method, options)
collection = find_collection_for_column(method, options)
html_options = set_options(options).merge(options.delete(:input_html) || {})
input_name = generate_association_input_name(method)
value_as_class = options.delete(:value_as_class)
list_item_content = collection.map do |c|
label = c.is_a?(Array) ? c.first : c
value = c.is_a?(Array) ? c.last : c
li_content = template.content_tag(:label,
"#{self.radio_button(input_name, value, html_options)} #{label}",
:for => generate_html_id(input_name, value.to_s.downcase)
)
li_options = value_as_class ? { :class => value.to_s.downcase } : {}
template.content_tag(:li, li_content, li_options)
end
field_set_and_list_wrapping_for_method(method, options, list_item_content)
end
alias :boolean_radio_input :radio_input
# Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
# items (li), one for each fragment for the date (year, month, day). Each li contains a label
# (eg "Year") and a select box. See date_or_datetime_input for a more detailed output example.
#
# Some of Rails' options for select_date are supported, but not everything yet.
def date_input(method, options)
date_or_datetime_input(method, options.merge(:discard_hour => true))
end
# Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
# items (li), one for each fragment for the date (year, month, day, hour, min, sec). Each li
# contains a label (eg "Year") and a select box. See date_or_datetime_input for a more
# detailed output example.
#
# Some of Rails' options for select_date are supported, but not everything yet.
def datetime_input(method, options)
date_or_datetime_input(method, options)
end
# Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
# items (li), one for each fragment for the time (hour, minute, second). Each li contains a label
# (eg "Hour") and a select box. See date_or_datetime_input for a more detailed output example.
#
# Some of Rails' options for select_time are supported, but not everything yet.
def time_input(method, options)
date_or_datetime_input(method, options.merge(:discard_year => true, :discard_month => true, :discard_day => true))
end
# <fieldset>
# <legend>Created At</legend>
# <ol>
# <li>
# <label for="user_created_at_1i">Year</label>
# <select id="user_created_at_1i" name="user[created_at(1i)]">
# <option value="2003">2003</option>
# ...
# <option value="2013">2013</option>
# </select>
# </li>
# <li>
# <label for="user_created_at_2i">Month</label>
# <select id="user_created_at_2i" name="user[created_at(2i)]">
# <option value="1">January</option>
# ...
# <option value="12">December</option>
# </select>
# </li>
# <li>
# <label for="user_created_at_3i">Day</label>
# <select id="user_created_at_3i" name="user[created_at(3i)]">
# <option value="1">1</option>
# ...
# <option value="31">31</option>
# </select>
# </li>
# </ol>
# </fieldset>
#
# This is an absolute abomination, but so is the official Rails select_date().
#
def date_or_datetime_input(method, options)
position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
inputs = options.delete(:order) || I18n.translate(:'date.order') || [:year, :month, :day]
time_inputs = [:hour, :minute]
time_inputs << [:second] if options[:include_seconds]
list_items_capture = ""
hidden_fields_capture = ""
# Gets the datetime object. It can be a Fixnum, Date or Time, or nil.
datetime = @object ? @object.send(method) : nil
html_options = options.delete(:input_html) || {}
(inputs + time_inputs).each do |input|
html_id = generate_html_id(method, "#{position[input]}i")
field_name = "#{method}(#{position[input]}i)"
if options["discard_#{input}".intern]
break if time_inputs.include?(input)
hidden_value = datetime.respond_to?(input) ? datetime.send(input) : datetime
hidden_fields_capture << template.hidden_field_tag("#{@object_name}[#{field_name}]", (hidden_value || 1), :id => html_id)
else
opts = set_options(options).merge(:prefix => @object_name, :field_name => field_name)
item_label_text = I18n.t(input.to_s, :default => input.to_s.humanize, :scope => [:datetime, :prompts])
list_items_capture << template.content_tag(:li,
template.content_tag(:label, item_label_text, :for => html_id) +
template.send("select_#{input}".intern, datetime, opts, html_options.merge(:id => html_id))
)
end
end
hidden_fields_capture + field_set_and_list_wrapping_for_method(method, options, list_items_capture)
end
# Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list
# items, one for each possible choice in the belongs_to association. Each li contains a
# label and a check_box input.
#
# This is an alternative for has many and has and belongs to many associations.
#
# Example:
#
# f.input :author, :as => :check_boxes
#
# Output:
#
# <fieldset>
# <legend><span>Authors</span></legend>
# <ol>
# <li>
# <input type="hidden" name="book[author_id][1]" value="">
# <label for="book_author_id_1"><input id="book_author_id_1" name="book[author_id][1]" type="checkbox" value="1" /> Justin French</label>
# </li>
# <li>
# <input type="hidden" name="book[author_id][2]" value="">
# <label for="book_author_id_2"><input id="book_author_id_2" name="book[owner_id][2]" type="checkbox" value="2" /> Kate French</label>
# </li>
# </ol>
# </fieldset>
#
# Notice that the value of the checkbox is the same as the id and the hidden
# field has empty value. You can override the hidden field value using the
# unchecked_value option.
#
# You can customize the options available in the set by passing in a collection (Array) of
# ActiveRecord objects through the :collection option. If not provided, the choices are found
# by inferring the parent's class name from the method name and simply calling find(:all) on
# it (Author.find(:all) in the example above).
#
# Examples:
#
# f.input :author, :as => :check_boxes, :collection => @authors
# f.input :author, :as => :check_boxes, :collection => Author.find(:all)
# f.input :author, :as => :check_boxes, :collection => [@justin, @kate]
#
# You can also customize the text label inside each option tag, by naming the correct method
# (:full_name, :display_name, :account_number, etc) to call on each object in the collection
# by passing in the :label_method option. By default the :label_method is whichever element of
# Formtastic::SemanticFormBuilder.collection_label_methods is found first.
#
# Examples:
#
# f.input :author, :as => :check_boxes, :label_method => :full_name
# f.input :author, :as => :check_boxes, :label_method => :display_name
# f.input :author, :as => :check_boxes, :label_method => :to_s
# f.input :author, :as => :check_boxes, :label_method => :label
#
# You can set :value_as_class => true if you want that LI wrappers contains
# a class with the wrapped checkbox input value.
#
def check_boxes_input(method, options)
collection = find_collection_for_column(method, options)
html_options = options.delete(:input_html) || {}
input_name = generate_association_input_name(method)
value_as_class = options.delete(:value_as_class)
unchecked_value = options.delete(:unchecked_value) || ''
html_options = { :name => "#{@object_name}[#{input_name}][]" }.merge(html_options)
list_item_content = collection.map do |c|
label = c.is_a?(Array) ? c.first : c
value = c.is_a?(Array) ? c.last : c
html_options.merge!(:id => generate_html_id(input_name, value.to_s.downcase))
li_content = template.content_tag(:label,
"#{self.check_box(input_name, html_options, value, unchecked_value)} #{label}",
:for => html_options[:id]
)
li_options = value_as_class ? { :class => value.to_s.downcase } : {}
template.content_tag(:li, li_content, li_options)
end
field_set_and_list_wrapping_for_method(method, options, list_item_content)
end
# Outputs a country select input, wrapping around a regular country_select helper.
# Rails doesn't come with a country_select helper by default any more, so you'll need to install
# the "official" plugin, or, if you wish, any other country_select plugin that behaves in the
# same way.
#
# The Rails plugin iso-3166-country-select plugin can be found "here":http://github.com/rails/iso-3166-country-select.
#
# By default, Formtastic includes a handfull of english-speaking countries as "priority counties",
# which you can change to suit your market and user base (see README for more info on config).
#
# Examples:
# f.input :location, :as => :country # use Formtastic::SemanticFormBuilder.priority_countries array for the priority countries
# f.input :location, :as => :country, :priority_countries => /Australia/ # set your own
#
def country_input(method, options)
raise "To use the :country input, please install a country_select plugin, like this one: http://github.com/rails/iso-3166-country-select" unless self.respond_to?(:country_select)
html_options = options.delete(:input_html) || {}
priority_countries = options.delete(:priority_countries) || @@priority_countries
self.label(method, options.slice(:label, :required)) +
self.country_select(method, priority_countries, set_options(options), html_options)
end
# Outputs a label containing a checkbox and the label text. The label defaults
# to the column name (method name) and can be altered with the :label option.
# :checked_value and :unchecked_value options are also available.
#
def boolean_input(method, options)
html_options = options.delete(:input_html) || {}
input = self.check_box(method, set_options(options).merge(html_options),
options.delete(:checked_value) || '1', options.delete(:unchecked_value) || '0')
label = options.delete(:label) || humanized_attribute_name(method)
self.label(method, input + label, options.slice(:required))
end
# Generates an input for the given method using the type supplied with :as.
#
# If the input is included in INPUT_MAPPINGS, it uses input_simple
# implementation which maps most of the inputs. All others have specific
# code and then a proper handler should be called (like radio_input) for
# :radio types.
#
def inline_input_for(method, options)
input_type = options.delete(:as)
if INPUT_MAPPINGS.key?(input_type)
input_simple(input_type, method, options)
else
send("#{input_type}_input", method, options)
end
end
# Generates hints for the given method using the text supplied in :hint.
#
def inline_hints_for(method, options) #:nodoc:
return if options[:hint].blank?
template.content_tag(:p, options[:hint], :class => 'inline-hints')
end
# Creates an error sentence by calling to_sentence on the errors array.
#
def error_sentence(errors) #:nodoc:
template.content_tag(:p, errors.to_sentence.untaint, :class => 'inline-errors')
end
# Creates an error li list.
#
def error_list(errors) #:nodoc:
list_elements = []
errors.each do |error|
list_elements << template.content_tag(:li, error.untaint)
end
template.content_tag(:ul, list_elements.join("\n"), :class => 'errors')
end
# Generates the required or optional string. If the value set is a proc,
# it evaluates the proc first.
#
def required_or_optional_string(required) #:nodoc:
string_or_proc = case required
when true
@@required_string
when false
@@optional_string
else
required
end
if string_or_proc.is_a?(Proc)
string_or_proc.call
else
string_or_proc.to_s
end
end
# Generates a fieldset and wraps the content in an ordered list. When working
# with nested attributes (in Rails 2.3), it allows %i as interpolation option
# in :name. So you can do:
#
# f.inputs :name => 'Task #%i', :for => :tasks
#
# And it will generate a fieldset for each task with legend 'Task #1', 'Task #2',
# 'Task #3' and so on.
#
def field_set_and_list_wrapping(html_options, contents='', &block) #:nodoc:
legend = html_options.delete(:name).to_s
legend %= parent_child_index(html_options[:parent]) if html_options[:parent]
legend = template.content_tag(:legend, template.content_tag(:span, legend)) unless legend.blank?
contents = template.capture(&block) if block_given?
# Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
contents = contents.join if contents.respond_to?(:join)
fieldset = template.content_tag(:fieldset,
legend + template.content_tag(:ol, contents),
html_options.except(:builder, :parent)
)
template.concat(fieldset) if block_given?
fieldset
end
# Also generates a fieldset and an ordered list but with label based in
# method. This methods is currently used by radio and datetime inputs.
#
def field_set_and_list_wrapping_for_method(method, options, contents)
contents = contents.join if contents.respond_to?(:join)
template.content_tag(:fieldset,
%{<legend>#{self.label(method, options.slice(:label, :required).merge!(:as_span => true))}</legend>} +
template.content_tag(:ol, contents)
)
end
# For methods that have a database column, take a best guess as to what the input method
# should be. In most cases, it will just return the column type (eg :string), but for special
# cases it will simplify (like the case of :integer, :float & :decimal to :numeric), or do
# something different (like :password and :select).
#
# If there is no column for the method (eg "virtual columns" with an attr_accessor), the
# default is a :string, a similar behaviour to Rails' scaffolding.
#
def default_input_type(method) #:nodoc:
return :string if @object.nil?
column = @object.column_for_attribute(method) if @object.respond_to?(:column_for_attribute)
if column
# handle the special cases where the column type doesn't map to an input method
return :time_zone if column.type == :string && method.to_s =~ /time_zone/
return :select if column.type == :integer && method.to_s =~ /_id$/
return :datetime if column.type == :timestamp
return :numeric if [:integer, :float, :decimal].include?(column.type)
return :password if column.type == :string && method.to_s =~ /password/
return :country if column.type == :string && method.to_s =~ /country/
# otherwise assume the input name will be the same as the column type (eg string_input)
return column.type
else
obj = @object.send(method) if @object.respond_to?(method)
return :select if find_reflection(method)
return :file if obj && @@file_methods.any? { |m| obj.respond_to?(m) }
return :password if method.to_s =~ /password/
return :string
end
end
# Used by select and radio inputs. The collection can be retrieved by
# three ways:
#
# * Explicitly provided through :collection
# * Retrivied through an association
# * Or a boolean column, which will generate a localized { "Yes" => true, "No" => false } hash.
#
# If the collection is not a hash or an array of strings, fixnums or arrays,
# we use label_method and value_method to retreive an array with the
# appropriate label and value.
#
def find_collection_for_column(column, options)
reflection = find_reflection(column)
collection = if options[:collection]
options.delete(:collection)
elsif reflection || column.to_s =~ /_id$/
parent_class = if reflection
reflection.klass
else
::ActiveSupport::Deprecation.warn("The _id way of doing things is deprecated. Please use the association method (#{column.to_s.sub(/_id$/,'')})", caller[3..-1])
column.to_s.sub(/_id$/,'').camelize.constantize
end
parent_class.find(:all)
else
create_boolean_collection(options)
end
collection = collection.to_a if collection.instance_of?(Hash)
# Return if we have an Array of strings, fixnums or arrays
return collection if collection.instance_of?(Array) &&
[Array, Fixnum, String, Symbol].include?(collection.first.class)
label = options.delete(:label_method) || detect_label_method(collection)
value = options.delete(:value_method) || :id
collection.map { |o| [o.send(label), o.send(value)] }
end
# Detected the label collection method when none is supplied using the
# values set in @@collection_label_methods.
#
def detect_label_method(collection) #:nodoc:
@@collection_label_methods.detect { |m| collection.first.respond_to?(m) }
end
# Returns a hash to be used by radio and select inputs when a boolean field
# is provided.
#
def create_boolean_collection(options)
options[:true] ||= I18n.t('yes', :default => 'Yes', :scope => [:formtastic])
options[:false] ||= I18n.t('no', :default => 'No', :scope => [:formtastic])
options[:value_as_class] = true unless options.key?(:value_as_class)
{ options.delete(:true) => true, options.delete(:false) => false }
end
# Used by association inputs (select, radio) to generate the name that should
# be used for the input
#
# belongs_to :author; f.input :author; will generate 'author_id'
# has_many :authors; f.input :authors; will generate 'author_ids'
# has_and_belongs_to_many will act like has_many
#
def generate_association_input_name(method)
if reflection = find_reflection(method)
if [:has_and_belongs_to_many, :has_many].include?(reflection.macro)
"#{method.to_s.singularize}_ids"
else
"#{method}_id"
end
else
method
end
end
# If an association method is passed in (f.input :author) try to find the
# reflection object.
#
def find_reflection(method)
@object.class.reflect_on_association(method) if @object.class.respond_to?(:reflect_on_association)
end
# Generates default_string_options by retrieving column information from
# the database.
#
def default_string_options(method) #:nodoc:
column = @object.column_for_attribute(method) if @object.respond_to?(:column_for_attribute)
if column.nil? || column.limit.nil?
{ :size => @@default_text_field_size }
else
{ :maxlength => column.limit, :size => [column.limit, @@default_text_field_size].min }
end
end
# Generate the html id for the li tag.
# It takes into account options[:index] and @auto_index to generate li
# elements with appropriate index scope. It also sanitizes the object
# and method names.
#
def generate_html_id(method_name, value='input')
if options.has_key?(:index)
index = "_#{options[:index]}"
elsif defined?(@auto_index)
index = "_#{@auto_index}"
else
index = ""
end
sanitized_method_name = method_name.to_s.sub(/\?$/,"")
"#{sanitized_object_name}#{index}_#{sanitized_method_name}_#{value}"
end
# Gets the nested_child_index value from the parent builder. In Rails 2.3
# it always returns a fixnum. In next versions it returns a hash with each
# association that the parent builds.
#
def parent_child_index(parent)
duck = parent[:builder].instance_variable_get('@nested_child_index')
if duck.is_a?(Hash)
child = parent[:for]
child = child.first if child.respond_to?(:first)
duck[child].to_i + 1
else
duck.to_i + 1
end
end
def sanitized_object_name
@sanitized_object_name ||= @object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
end
def humanized_attribute_name(method)
if @object && @object.class.respond_to?(:human_attribute_name)
@object.class.human_attribute_name(method.to_s)
else
method.to_s.send(@@label_str_method)
end
end
end
# Wrappers around form_for (etc) with :builder => SemanticFormBuilder.
#
# * semantic_form_for(@post)
# * semantic_fields_for(@post)
# * semantic_form_remote_for(@post)
# * semantic_remote_form_for(@post)
#
# Each of which are the equivalent of:
#
# * form_for(@post, :builder => Formtastic::SemanticFormBuilder))
# * fields_for(@post, :builder => Formtastic::SemanticFormBuilder))
# * form_remote_for(@post, :builder => Formtastic::SemanticFormBuilder))
# * remote_form_for(@post, :builder => Formtastic::SemanticFormBuilder))
#
# Example Usage:
#
# <% semantic_form_for @post do |f| %>
# <%= f.input :title %>
# <%= f.input :body %>
# <% end %>
#
# The above examples use a resource-oriented style of form_for() helper where only the @post
# object is given as an argument, but the generic style is also supported if you really want it,
# as is forms with inline objects (Post.new) rather than objects with instance variables (@post):
#
# <% semantic_form_for :post, @post, :url => posts_path do |f| %>
# ...
# <% end %>
#
# <% semantic_form_for :post, Post.new, :url => posts_path do |f| %>
# ...
# <% end %>
#
# The shorter, resource-oriented style is most definitely preferred, and has recieved the most
# testing to date.
#
# Please note: Although it's possible to call Rails' built-in form_for() helper without an
# object, all semantic forms *must* have an object (either Post.new or @post), as Formtastic
# has too many dependencies on an ActiveRecord object being present.
#
module SemanticFormHelper
@@builder = Formtastic::SemanticFormBuilder
# cattr_accessor :builder
def self.builder=(val)
@@builder = val
end
[:form_for, :fields_for, :form_remote_for, :remote_form_for].each do |meth|
src = <<-END_SRC
def semantic_#{meth}(record_or_name_or_array, *args, &proc)
options = args.extract_options!
options[:builder] = @@builder
options[:html] ||= {}
class_names = options[:html][:class] ? options[:html][:class].split(" ") : []
class_names << "formtastic"
class_names << case record_or_name_or_array
when String, Symbol then record_or_name_or_array.to_s # :post => "post"
when Array then record_or_name_or_array.last.class.to_s.underscore # [@post, @comment] # => "comment"
else record_or_name_or_array.class.to_s.underscore # @post => "post"
end
options[:html][:class] = class_names.join(" ")
#{meth}(record_or_name_or_array, *(args << options), &proc)
end
END_SRC
module_eval src, __FILE__, __LINE__
end
end
end
|
getnashty/liftr
|
vendor/gems/clearance-0.8.8/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/formtastic.rb
|
Ruby
|
mit
| 50,443
|
@echo off
..\..\..\packages\autorest.0.16.0\tools\AutoRest.exe -i Luis-q.json -n Microsoft.Bot.Builder.Luis -Header MICROSOFT_MIT -O .
|
yakumo/BotBuilder
|
CSharp/Library/Microsoft.Bot.Builder/Luis/generateLuisModels.bat
|
Batchfile
|
mit
| 135
|
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using FarseerPhysics.Common.ConvexHull;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// Represents a simple non-selfintersecting convex polygon.
/// Create a convex hull from the given array of points.
/// </summary>
public class PolygonShape : Shape
{
/// <summary>
/// Create a convex hull from the given array of local points.
/// The number of vertices must be in the range [3, Settings.MaxPolygonVertices].
/// Warning: the points may be re-ordered, even if they form a convex polygon
/// Warning: collinear points are handled but not removed. Collinear points may lead to poor stacking behavior.
/// </summary>
public Vertices vertices
{
get { return _vertices; }
set { setVerticesNoCopy( new Vertices( value ) ); }
}
public Vertices normals { get { return _normals; } }
public override int childCount { get { return 1; } }
Vertices _vertices;
Vertices _normals;
/// <summary>
/// Initializes a new instance of the <see cref="PolygonShape"/> class.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="density">The density.</param>
public PolygonShape( Vertices vertices, float density ) : base( density )
{
shapeType = ShapeType.Polygon;
_radius = Settings.polygonRadius;
this.vertices = vertices;
}
/// <summary>
/// Create a new PolygonShape with the specified density.
/// </summary>
/// <param name="density">The density.</param>
public PolygonShape( float density ) : base( density )
{
Debug.Assert( density >= 0f );
shapeType = ShapeType.Polygon;
_radius = Settings.polygonRadius;
_vertices = new Vertices( Settings.maxPolygonVertices );
_normals = new Vertices( Settings.maxPolygonVertices );
}
internal PolygonShape() : base( 0 )
{
shapeType = ShapeType.Polygon;
_radius = Settings.polygonRadius;
_vertices = new Vertices( Settings.maxPolygonVertices );
_normals = new Vertices( Settings.maxPolygonVertices );
}
/// <summary>
/// sets the vertices without copying over the data from verts to the local List.
/// </summary>
/// <param name="verts">Verts.</param>
public void setVerticesNoCopy( Vertices verts )
{
Debug.Assert( verts.Count >= 3 && verts.Count <= Settings.maxPolygonVertices );
_vertices = verts;
if( Settings.useConvexHullPolygons )
{
// FPE note: This check is required as the GiftWrap algorithm early exits on triangles
// So instead of giftwrapping a triangle, we just force it to be clock wise.
if( _vertices.Count <= 3 )
_vertices.forceCounterClockWise();
else
_vertices = GiftWrap.getConvexHull( _vertices );
}
if( _normals == null )
_normals = new Vertices( _vertices.Count );
else
_normals.Clear();
// Compute normals. Ensure the edges have non-zero length.
for( var i = 0; i < _vertices.Count; ++i )
{
var next = i + 1 < _vertices.Count ? i + 1 : 0;
var edge = _vertices[next] - _vertices[i];
Debug.Assert( edge.LengthSquared() > Settings.epsilon * Settings.epsilon );
// FPE optimization: Normals.Add(MathHelper.Cross(edge, 1.0f));
var temp = new Vector2( edge.Y, -edge.X );
Nez.Vector2Ext.normalize( ref temp );
_normals.Add( temp );
}
// Compute the polygon mass data
computeProperties();
}
protected override void computeProperties()
{
// Polygon mass, centroid, and inertia.
// Let rho be the polygon density in mass per unit area.
// Then:
// mass = rho * int(dA)
// centroid.X = (1/mass) * rho * int(x * dA)
// centroid.Y = (1/mass) * rho * int(y * dA)
// I = rho * int((x*x + y*y) * dA)
//
// We can compute these integrals by summing all the integrals
// for each triangle of the polygon. To evaluate the integral
// for a single triangle, we make a change of variables to
// the (u,v) coordinates of the triangle:
// x = x0 + e1x * u + e2x * v
// y = y0 + e1y * u + e2y * v
// where 0 <= u && 0 <= v && u + v <= 1.
//
// We integrate u from [0,1-v] and then v from [0,1].
// We also need to use the Jacobian of the transformation:
// D = cross(e1, e2)
//
// Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
//
// The rest of the derivation is handled by computer algebra.
Debug.Assert( vertices.Count >= 3 );
//FPE optimization: Early exit as polygons with 0 density does not have any properties.
if( _density <= 0 )
return;
//FPE optimization: Consolidated the calculate centroid and mass code to a single method.
var center = Vector2.Zero;
var area = 0.0f;
var I = 0.0f;
// pRef is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
var s = Vector2.Zero;
// This code would put the reference point inside the polygon.
for( int i = 0; i < vertices.Count; ++i )
s += vertices[i];
s *= 1.0f / vertices.Count;
const float k_inv3 = 1.0f / 3.0f;
for( int i = 0; i < vertices.Count; ++i )
{
// Triangle vertices.
Vector2 e1 = vertices[i] - s;
Vector2 e2 = i + 1 < vertices.Count ? vertices[i + 1] - s : vertices[0] - s;
var D = MathUtils.cross( e1, e2 );
var triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * ( e1 + e2 );
float ex1 = e1.X, ey1 = e1.Y;
float ex2 = e2.X, ey2 = e2.Y;
var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2;
var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2;
I += ( 0.25f * k_inv3 * D ) * ( intx2 + inty2 );
}
//The area is too small for the engine to handle.
Debug.Assert( area > Settings.epsilon );
// We save the area
massData.area = area;
// Total mass
massData.mass = _density * area;
// Center of mass
center *= 1.0f / area;
massData.centroid = center + s;
// Inertia tensor relative to the local origin (point s).
massData.inertia = _density * I;
// Shift to center of mass then to original body origin.
massData.inertia += massData.mass * ( Vector2.Dot( massData.centroid, massData.centroid ) - Vector2.Dot( center, center ) );
}
public override bool testPoint( ref Transform transform, ref Vector2 point )
{
Vector2 pLocal = MathUtils.mulT( transform.q, point - transform.p );
for( int i = 0; i < vertices.Count; ++i )
{
float dot = Vector2.Dot( normals[i], pLocal - vertices[i] );
if( dot > 0.0f )
{
return false;
}
}
return true;
}
public override bool rayCast( out RayCastOutput output, ref RayCastInput input, ref Transform transform, int childIndex )
{
output = new RayCastOutput();
// Put the ray into the polygon's frame of reference.
Vector2 p1 = MathUtils.mulT( transform.q, input.point1 - transform.p );
Vector2 p2 = MathUtils.mulT( transform.q, input.point2 - transform.p );
Vector2 d = p2 - p1;
float lower = 0.0f, upper = input.maxFraction;
int index = -1;
for( int i = 0; i < vertices.Count; ++i )
{
// p = p1 + a * d
// dot(normal, p - v) = 0
// dot(normal, p1 - v) + a * dot(normal, d) = 0
float numerator = Vector2.Dot( normals[i], vertices[i] - p1 );
float denominator = Vector2.Dot( normals[i], d );
if( denominator == 0.0f )
{
if( numerator < 0.0f )
{
return false;
}
}
else
{
// Note: we want this predicate without division:
// lower < numerator / denominator, where denominator < 0
// Since denominator < 0, we have to flip the inequality:
// lower < numerator / denominator <==> denominator * lower > numerator.
if( denominator < 0.0f && numerator < lower * denominator )
{
// Increase lower.
// The segment enters this half-space.
lower = numerator / denominator;
index = i;
}
else if( denominator > 0.0f && numerator < upper * denominator )
{
// Decrease upper.
// The segment exits this half-space.
upper = numerator / denominator;
}
}
// The use of epsilon here causes the assert on lower to trip
// in some cases. Apparently the use of epsilon was to make edge
// shapes work, but now those are handled separately.
//if (upper < lower - b2_epsilon)
if( upper < lower )
{
return false;
}
}
Debug.Assert( 0.0f <= lower && lower <= input.maxFraction );
if( index >= 0 )
{
output.fraction = lower;
output.normal = MathUtils.mul( transform.q, normals[index] );
return true;
}
return false;
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void computeAABB( out AABB aabb, ref Transform transform, int childIndex )
{
var lower = MathUtils.mul( ref transform, vertices[0] );
var upper = lower;
for( int i = 1; i < vertices.Count; ++i )
{
var v = MathUtils.mul( ref transform, vertices[i] );
lower = Vector2.Min( lower, v );
upper = Vector2.Max( upper, v );
}
var r = new Vector2( radius, radius );
aabb.lowerBound = lower - r;
aabb.upperBound = upper + r;
}
public override float computeSubmergedArea( ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc )
{
sc = Vector2.Zero;
//Transform plane into shape co-ordinates
var normalL = MathUtils.mulT( xf.q, normal );
float offsetL = offset - Vector2.Dot( normal, xf.p );
float[] depths = new float[Settings.maxPolygonVertices];
int diveCount = 0;
int intoIndex = -1;
int outoIndex = -1;
bool lastSubmerged = false;
int i;
for( i = 0; i < vertices.Count; i++ )
{
depths[i] = Vector2.Dot( normalL, vertices[i] ) - offsetL;
bool isSubmerged = depths[i] < -Settings.epsilon;
if( i > 0 )
{
if( isSubmerged )
{
if( !lastSubmerged )
{
intoIndex = i - 1;
diveCount++;
}
}
else
{
if( lastSubmerged )
{
outoIndex = i - 1;
diveCount++;
}
}
}
lastSubmerged = isSubmerged;
}
switch( diveCount )
{
case 0:
if( lastSubmerged )
{
//Completely submerged
sc = MathUtils.mul( ref xf, massData.centroid );
return massData.mass / density;
}
//Completely dry
return 0;
case 1:
if( intoIndex == -1 )
{
intoIndex = vertices.Count - 1;
}
else
{
outoIndex = vertices.Count - 1;
}
break;
}
int intoIndex2 = ( intoIndex + 1 ) % vertices.Count;
int outoIndex2 = ( outoIndex + 1 ) % vertices.Count;
float intoLambda = ( 0 - depths[intoIndex] ) / ( depths[intoIndex2] - depths[intoIndex] );
float outoLambda = ( 0 - depths[outoIndex] ) / ( depths[outoIndex2] - depths[outoIndex] );
Vector2 intoVec = new Vector2( vertices[intoIndex].X * ( 1 - intoLambda ) + vertices[intoIndex2].X * intoLambda, vertices[intoIndex].Y * ( 1 - intoLambda ) + vertices[intoIndex2].Y * intoLambda );
Vector2 outoVec = new Vector2( vertices[outoIndex].X * ( 1 - outoLambda ) + vertices[outoIndex2].X * outoLambda, vertices[outoIndex].Y * ( 1 - outoLambda ) + vertices[outoIndex2].Y * outoLambda );
//Initialize accumulator
float area = 0;
Vector2 center = new Vector2( 0, 0 );
Vector2 p2 = vertices[intoIndex2];
const float k_inv3 = 1.0f / 3.0f;
//An awkward loop from intoIndex2+1 to outIndex2
i = intoIndex2;
while( i != outoIndex2 )
{
i = ( i + 1 ) % vertices.Count;
Vector2 p3;
if( i == outoIndex2 )
p3 = outoVec;
else
p3 = vertices[i];
//Add the triangle formed by intoVec,p2,p3
{
Vector2 e1 = p2 - intoVec;
Vector2 e2 = p3 - intoVec;
float D = MathUtils.cross( e1, e2 );
float triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * ( intoVec + p2 + p3 );
}
p2 = p3;
}
//Normalize and transform centroid
center *= 1.0f / area;
sc = MathUtils.mul( ref xf, center );
return area;
}
public bool CompareTo( PolygonShape shape )
{
if( vertices.Count != shape.vertices.Count )
return false;
for( int i = 0; i < vertices.Count; i++ )
{
if( vertices[i] != shape.vertices[i] )
return false;
}
return ( radius == shape.radius && massData == shape.massData );
}
public override Shape clone()
{
var clone = new PolygonShape();
clone.shapeType = shapeType;
clone._radius = _radius;
clone._density = _density;
clone._vertices = new Vertices( _vertices );
clone._normals = new Vertices( _normals );
clone.massData = massData;
return clone;
}
}
}
|
Blucky87/Nez
|
Nez.FarseerPhysics/Farseer/Collision/Shapes/PolygonShape.cs
|
C#
|
mit
| 13,963
|
require 'rails_helper'
field_name = field_name_from __FILE__
type = type_from __FILE__
describe field_name do
it_behaves_like \
"#{type} partial", field_name,
value: {
'kind' => 'user_renamed',
'change' => %w(jack john)
},
expected_value: "\n{\n \"kind\": \"user_renamed\",\n \"change\": [\n \"jack\",\n \"john\"\n ]\n}",
input_selector: 'textarea',
content_for: true,
skip_general: true,
skip_nil: true do
it 'initializes the codemirror' do
textarea = page.at_css('textarea.form-control')
expect(textarea['data-init']).to eq 'codemirror'
end
it 'checks the value' do
textarea = page.at_css('textarea.form-control')
expect(textarea['name']).to eq "#{resources_name}[#{field_name}]"
expect(textarea.content).to eq expected_value
end
context 'when value is nil' do
let(:value) { nil }
it 'renders the belongs_to form' do
textarea = page.at_css('textarea.form-control')
expect(textarea['name']).to eq "#{resources_name}[#{field_name}]"
expect(textarea.content).to eq "\nnull"
end
end
end
end
|
reinteractive-open/wallaby
|
spec/views/wallaby/resources/form/_jsonb.html.erb_spec.rb
|
Ruby
|
mit
| 1,146
|
package commands
import (
"bytes"
"io"
"os"
"path/filepath"
"github.com/github/git-lfs/lfs"
"github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra"
)
var (
smudgeInfo = false
smudgeCmd = &cobra.Command{
Use: "smudge",
Short: "Implements the Git smudge filter",
Run: smudgeCommand,
}
)
func smudgeCommand(cmd *cobra.Command, args []string) {
requireStdin("This command should be run by the Git 'smudge' filter")
lfs.InstallHooks(false)
b := &bytes.Buffer{}
r := io.TeeReader(os.Stdin, b)
ptr, err := lfs.DecodePointer(r)
if err != nil {
mr := io.MultiReader(b, os.Stdin)
_, err := io.Copy(os.Stdout, mr)
if err != nil {
Panic(err, "Error writing data to stdout:")
}
return
}
if smudgeInfo {
localPath, err := lfs.LocalMediaPath(ptr.Oid)
if err != nil {
Exit(err.Error())
}
stat, err := os.Stat(localPath)
if err != nil {
Print("%d --", ptr.Size)
} else {
Print("%d %s", stat.Size(), localPath)
}
return
}
filename := smudgeFilename(args, err)
cb, file, err := lfs.CopyCallbackFile("smudge", filename, 1, 1)
if err != nil {
Error(err.Error())
}
err = ptr.Smudge(os.Stdout, filename, cb)
if file != nil {
file.Close()
}
if err != nil {
ptr.Encode(os.Stdout)
LoggedError(err, "Error accessing media: %s (%s)", filename, ptr.Oid)
}
}
func smudgeFilename(args []string, err error) string {
if len(args) > 0 {
return args[0]
}
if smudgeErr, ok := err.(*lfs.SmudgeError); ok {
return filepath.Base(smudgeErr.Filename)
}
return "<unknown file>"
}
func init() {
smudgeCmd.Flags().BoolVarP(&smudgeInfo, "info", "i", false, "Display the local path and size of the smudged file.")
RootCmd.AddCommand(smudgeCmd)
}
|
clareliguori/git-lfs
|
commands/command_smudge.go
|
GO
|
mit
| 1,718
|
<?php
namespace Moip\Resource;
use stdClass;
class NotificationPreferencesList extends MoipResource
{
/**
* @const string
*/
const PATH = 'preferences';
public function initialize()
{
$this->data = new stdClass();
}
/**
* Get notifications.
*
* @return array
*/
public function getNotifications()
{
return $this->data->notifications;
}
/**
* Get a notification list.
*
* @return stdClass
*/
public function get()
{
return $this->getByPath(sprintf('/%s/%s/%s', MoipResource::VERSION, self::PATH, 'notifications'));
}
protected function populate(stdClass $response)
{
$notificationsList = clone $this;
$notificationsList->data = new stdClass();
$notificationsList->data->notifications = $response;
return $notificationsList;
}
}
|
caiogaspar/moip-sdk-php
|
src/Resource/NotificationPreferencesList.php
|
PHP
|
mit
| 907
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
var a = [];
for(var i = 0; i < 1024*500*10; ++i)
a[i] = i;
|
Microsoft/ChakraCore
|
bin/NativeTests/Scripts/arraytest.js
|
JavaScript
|
mit
| 427
|
//
// CAAnimation+RZBlocks.h
// Raizlabs
//
// Created by Nick Donaldson on 12/6/13.
// Copyright 2014 Raizlabs and other contributors
// http://raizlabs.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.
//
#import <QuartzCore/QuartzCore.h>
// NOTE: Do NOT set the delegate of the animation after setting a block, or the
// block will not fire.
typedef void (^RZAnimationDidStartBlock)();
typedef void (^RZAnimationDidStopBlock)(BOOL finished);
@interface CAAnimation (RZBlocks)
- (void)rz_setAnimationDidStartBlock:(RZAnimationDidStartBlock)startBlock;
- (void)rz_setAnimationDidStopBlock:(RZAnimationDidStopBlock)stopBlock;
@end
|
fossugn/RZUtils
|
RZUtils/Categories/CoreAnimation/CAAnimation+RZBlocks.h
|
C
|
mit
| 1,677
|
-- SETTINGS
SET @iTypeOrder = (SELECT MAX(`order`) FROM `sys_options_types` WHERE `group` = 'modules');
INSERT INTO `sys_options_types`(`group`, `name`, `caption`, `icon`, `order`) VALUES
('modules', 'bx_spaces', '_bx_spaces', 'bx_spaces@modules/boonex/spaces/|std-icon.svg', IF(ISNULL(@iTypeOrder), 1, @iTypeOrder + 1));
SET @iTypeId = LAST_INSERT_ID();
INSERT INTO `sys_options_categories` (`type_id`, `name`, `caption`, `order`)
VALUES (@iTypeId, 'bx_spaces', '_bx_spaces', 1);
SET @iCategId = LAST_INSERT_ID();
INSERT INTO `sys_options` (`name`, `value`, `category_id`, `caption`, `type`, `extra`, `check`, `check_error`, `order`) VALUES
('bx_spaces_num_connections_quick', '6', @iCategId, '_bx_spaces_option_num_connections_quick', 'digit', '', '', '', 10),
('bx_spaces_per_page_browse', '24', @iCategId, '_bx_spaces_option_per_page_browse', 'digit', '', '', '', 11),
('bx_spaces_num_rss', '10', @iCategId, '_bx_spaces_option_num_rss', 'digit', '', '', '', 12),
('bx_spaces_per_page_browse_showcase', '32', @iCategId, '_sys_option_per_page_browse_showcase', 'digit', '', '', '', 15),
('bx_spaces_per_page_browse_recommended', '10', @iCategId, '_sys_option_per_page_browse_recommended', 'digit', '', '', '', 16),
('bx_spaces_searchable_fields', 'space_name,space_desc', @iCategId, '_bx_spaces_option_searchable_fields', 'list', 'a:2:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:21:"get_searchable_fields";}', '', '', 30);
-- PAGES
-- PAGE: create profile
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_create_profile', 'create-space-profile', '_bx_spaces_page_title_sys_create_profile', '_bx_spaces_page_title_create_profile', 'bx_spaces', 5, 2147483647, 1, 'page.php?i=create-space-profile', '', '', '', 0, 1, 0, '', '');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_spaces_create_profile', 1, 'bx_spaces', '_bx_spaces_page_block_title_create_profile', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:13:\"entity_create\";}', 0, 1, 1);
-- PAGE: view profile
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_view_profile', 'view-space-profile', '_bx_spaces_page_title_sys_view_profile', '_bx_spaces_page_title_view_profile', 'bx_spaces', 10, 2147483647, 1, 'page.php?i=view-space-profile', '', '', '', 0, 1, 0, 'BxSpacesPageEntry', 'modules/boonex/spaces/classes/BxSpacesPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_spaces_view_profile', 1, 'bx_spaces', '', '_bx_spaces_page_block_title_entry_social_sharing', 13, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:21:\"entity_social_sharing\";}', 0, 0, 1, 0),
('bx_spaces_view_profile', 2, 'bx_spaces', '', '_bx_spaces_page_block_title_profile_info', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:11:\"entity_info\";}', 0, 0, 1, 0),
('bx_spaces_view_profile', 2, 'bx_spaces', '', '_bx_spaces_page_block_title_parent', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:13:\"entity_parent\";}', 0, 0, 1, 1),
('bx_spaces_view_profile', 2, 'bx_spaces', '', '_bx_spaces_page_block_title_childs', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:13:\"entity_childs\";}', 0, 0, 1, 2),
('bx_spaces_view_profile', 3, 'bx_spaces', '', '_bx_spaces_page_block_title_fans', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:4:\"fans\";}', 0, 0, 1, 0),
('bx_spaces_view_profile', 3, 'bx_spaces', '', '_bx_spaces_page_block_title_admins', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:6:\"admins\";}', 0, 0, 1, 1),
('bx_spaces_view_profile', 4, 'bx_spaces', '', '_bx_spaces_page_block_title_profile_description', 13, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:17:\"entity_text_block\";}', 0, 0, 1, 0),
('bx_spaces_view_profile', 4, 'bx_spaces', '', '_bx_spaces_page_block_title_profile_comments', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:15:\"entity_comments\";}', 0, 0, 0, 0);
-- PAGE: view closed profile
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_view_profile_closed', 'view-space-profile-closed', '_bx_spaces_page_title_sys_view_profile_closed', '_bx_spaces_page_title_view_profile', 'bx_spaces', 10, 2147483647, 1, 'page.php?i=view-space-profile', '', '', '', 0, 1, 0, 'BxSpacesPageEntry', 'modules/boonex/spaces/classes/BxSpacesPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_spaces_view_profile_closed', 2, 'bx_spaces', '', '_bx_spaces_page_block_title_profile_info', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:11:\"entity_info\";}', 0, 0, 1, 0),
('bx_spaces_view_profile_closed', 3, 'bx_spaces', '', '_bx_spaces_page_block_title_fans', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:4:\"fans\";}', 0, 0, 1, 0);
-- PAGE: edit profile
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_edit_profile', 'edit-space-profile', '_bx_spaces_page_title_sys_edit_profile', '_bx_spaces_page_title_edit_profile', 'bx_spaces', 5, 2147483647, 1, 'page.php?i=edit-space-profile', '', '', '', 0, 1, 0, 'BxSpacesPageEntry', 'modules/boonex/spaces/classes/BxSpacesPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_spaces_edit_profile', 1, 'bx_spaces', '_bx_spaces_page_block_title_edit_profile', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:11:\"entity_edit\";}', 0, 0, 0);
-- PAGE: edit profile cover
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_edit_profile_cover', 'edit-space-cover', '_bx_spaces_page_title_sys_edit_profile_cover', '_bx_spaces_page_title_edit_profile_cover', 'bx_spaces', 5, 2147483647, 1, 'page.php?i=edit-space-cover', '', '', '', 0, 1, 0, 'BxSpacesPageEntry', 'modules/boonex/spaces/classes/BxSpacesPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_spaces_edit_profile_cover', 1, 'bx_spaces', '_bx_spaces_page_block_title_edit_profile_cover', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:17:\"entity_edit_cover\";}', 0, 0, 0);
-- PAGE: invite members
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_invite', 'invite-to-space', '_bx_spaces_page_title_sys_invite_to_space', '_bx_spaces_page_title_invite_to_space', 'bx_spaces', 5, 2147483647, 1, 'page.php?i=invite-to-space', '', '', '', 0, 1, 0, 'BxSpacesPageEntry', 'modules/boonex/spaces/classes/BxSpacesPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_spaces_invite', 1, 'bx_spaces', '_bx_spaces_page_block_title_invite_to_space', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:13:\"entity_invite\";}', 0, 0, 0);
-- PAGE: delete profile
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_delete_profile', 'delete-space-profile', '_bx_spaces_page_title_sys_delete_profile', '_bx_spaces_page_title_delete_profile', 'bx_spaces', 5, 2147483647, 1, 'page.php?i=delete-space-profile', '', '', '', 0, 1, 0, 'BxSpacesPageEntry', 'modules/boonex/spaces/classes/BxSpacesPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_spaces_delete_profile', 1, 'bx_spaces', '_bx_spaces_page_block_title_delete_profile', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:13:\"entity_delete\";}', 0, 0, 0);
-- PAGE: profile info
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_profile_info', 'space-profile-info', '_bx_spaces_page_title_sys_profile_info', '_bx_spaces_page_title_profile_info', 'bx_spaces', 5, 2147483647, 1, 'page.php?i=space-profile-info', '', '', '', 0, 1, 0, 'BxSpacesPageEntry', 'modules/boonex/spaces/classes/BxSpacesPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_spaces_profile_info', 1, 'bx_spaces', '_bx_spaces_page_block_title_system_profile_info', '_bx_spaces_page_block_title_profile_info_link', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:16:\"entity_info_full\";}', 0, 0, 1, 1),
('bx_spaces_profile_info', 1, 'bx_spaces', '', '_bx_spaces_page_block_title_profile_description', 13, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:17:\"entity_text_block\";}', 0, 0, 1, 2);
-- PAGE: space fans
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_fans', 'space-fans', '_bx_spaces_page_title_sys_space_fans', '_bx_spaces_page_title_space_fans', 'bx_spaces', 5, 2147483647, 1, 'page.php?i=space-fans', '', '', '', 0, 1, 0, 'BxSpacesPageEntry', 'modules/boonex/spaces/classes/BxSpacesPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_spaces_fans', 1, 'bx_spaces', '_bx_spaces_page_block_title_system_fans', '_bx_spaces_page_block_title_fans_link', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:10:"fans_table";}', 0, 0, 1, 1);
-- PAGE: view entry comments
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_profile_comments', '_bx_spaces_page_title_sys_profile_comments', '_bx_spaces_page_title_profile_comments', 'bx_spaces', 5, 2147483647, 1, 'space-profile-comments', '', '', '', '', 0, 1, 0, 'BxSpacesPageEntry', 'modules/boonex/spaces/classes/BxSpacesPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_spaces_profile_comments', 1, 'bx_spaces', '_bx_spaces_page_block_title_profile_comments', '_bx_spaces_page_block_title_profile_comments_link', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:15:\"entity_comments\";}', 0, 0, 0, 1);
-- PAGE: module home
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_home', '_bx_spaces_page_title_sys_recent', '_bx_spaces_page_title_recent', 'bx_spaces', 5, 2147483647, 1, 'spaces-home', 'page.php?i=spaces-home', '', '', '', 0, 1, 0, 'BxSpacesPageBrowse', 'modules/boonex/spaces/classes/BxSpacesPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_spaces_home', 1, 'bx_spaces', '_bx_spaces_page_block_title_featured_profiles', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:15:"browse_featured";s:6:"params";a:1:{i:0;s:7:"gallery";}}', 0, 1, 0),
('bx_spaces_home', 1, 'bx_spaces', '_bx_spaces_page_block_title_latest_profiles', 11, 2147483647, 'service', 'a:3:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:22:\"browse_recent_profiles\";s:6:"params";a:1:{i:0;b:1;}}', 0, 1, 1);
-- PAGE: top profiles
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_top', '_bx_spaces_page_title_sys_top', '_bx_spaces_page_title_top', 'bx_spaces', 5, 2147483647, 1, 'spaces-top', 'page.php?i=spaces-top', '', '', '', 0, 1, 0, 'BxSpacesPageBrowse', 'modules/boonex/spaces/classes/BxSpacesPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_spaces_top', 1, 'bx_spaces', '_bx_spaces_page_block_title_top_profiles', 11, 2147483647, 'service', 'a:3:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:19:\"browse_top_profiles\";s:6:"params";a:1:{i:0;b:1;}}', 0, 1, 0);
-- PAGE: search for entries
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_search', '_bx_spaces_page_title_sys_entries_search', '_bx_spaces_page_title_entries_search', 'bx_spaces', 5, 2147483647, 1, 'spaces-search', 'page.php?i=spaces-search', '', '', '', 0, 1, 0, 'BxSpacesPageBrowse', 'modules/boonex/spaces/classes/BxSpacesPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_spaces_search', 1, 'bx_spaces', '_bx_spaces_page_block_title_search_form', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:8:"get_form";s:6:"params";a:1:{i:0;a:1:{s:6:"object";s:9:"bx_spaces";}}s:5:"class";s:27:"TemplSearchExtendedServices";}', 0, 1, 1, 1),
('bx_spaces_search', 1, 'bx_spaces', '_bx_spaces_page_block_title_search_results', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:11:"get_results";s:6:"params";a:1:{i:0;a:2:{s:6:"object";s:9:"bx_spaces";s:10:"show_empty";b:1;}}s:5:"class";s:27:"TemplSearchExtendedServices";}', 0, 1, 1, 2),
('bx_spaces_search', 1, 'bx_spaces', '_bx_spaces_page_block_title_search_form_cmts', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:8:"get_form";s:6:"params";a:1:{i:0;a:1:{s:6:"object";s:14:"bx_spaces_cmts";}}s:5:"class";s:27:"TemplSearchExtendedServices";}', 0, 1, 0, 3),
('bx_spaces_search', 1, 'bx_spaces', '_bx_spaces_page_block_title_search_results_cmts', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:11:"get_results";s:6:"params";a:1:{i:0;a:2:{s:6:"object";s:14:"bx_spaces_cmts";s:10:"show_empty";b:1;}}s:5:"class";s:27:"TemplSearchExtendedServices";}', 0, 1, 0, 4);
-- PAGE: module manage own
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_manage', '_bx_spaces_page_title_sys_manage', '_bx_spaces_page_title_manage', 'bx_spaces', 5, 2147483647, 1, 'spaces-manage', 'page.php?i=spaces-manage', '', '', '', 0, 1, 0, 'BxSpacesPageBrowse', 'modules/boonex/spaces/classes/BxSpacesPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_spaces_manage', 1, 'bx_spaces', '_bx_spaces_page_block_title_system_manage', '_bx_spaces_page_block_title_manage', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:12:\"manage_tools\";}}', 0, 1, 0);
-- PAGE: module manage all
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_administration', '_bx_spaces_page_title_sys_manage_administration', '_bx_spaces_page_title_manage', 'bx_spaces', 5, 192, 1, 'spaces-administration', 'page.php?i=spaces-administration', '', '', '', 0, 1, 0, 'BxSpacesPageBrowse', 'modules/boonex/spaces/classes/BxSpacesPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_spaces_administration', 1, 'bx_spaces', '_bx_spaces_page_block_title_system_manage_administration', '_bx_spaces_page_block_title_manage', 11, 192, 'service', 'a:3:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:12:\"manage_tools\";s:6:\"params\";a:1:{i:0;s:14:\"administration\";}}', 0, 1, 0);
-- PAGE: user's spaces
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `visible_for_levels_editable`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_joined', 'joined-spaces', '_bx_spaces_page_title_sys_joined_entries', '_bx_spaces_page_title_joined_entries', 'bx_spaces', 5, 2147483647, 1, '', '', '', '', 0, 1, 0, 'BxSpacesPageJoinedEntries', 'modules/boonex/spaces/classes/BxSpacesPageJoinedEntries.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_spaces_joined', 1, 'bx_spaces', '_bx_spaces_page_block_title_sys_entries_actions', '_bx_spaces_page_block_title_entries_actions', 13, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:18:"my_entries_actions";}', 0, 0, 1, 1),
('bx_spaces_joined', 1, 'bx_spaces', '_bx_spaces_page_block_title_sys_entries_of_author', '_bx_spaces_page_block_title_entries_of_author', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:22:"browse_created_entries";}', 0, 0, 0, 2),
('bx_spaces_joined', 1, 'bx_spaces', '_bx_spaces_page_block_title_sys_favorites_of_author', '_bx_spaces_page_block_title_favorites_of_author', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:15:"browse_favorite";s:6:"params";a:1:{i:0;s:12:"{profile_id}";}}', 0, 1, 1, 3),
('bx_spaces_joined', 1, 'bx_spaces', '_bx_spaces_page_block_title_sys_joined_entries', '_bx_spaces_page_block_title_joined_entries', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:21:"browse_joined_entries";s:6:"params";a:2:{i:0;i:0;i:1;b:1;}}', 0, 0, 1, 4);
-- PAGE: add block to homepage
SET @iBlockOrder = (SELECT `order` FROM `sys_pages_blocks` WHERE `object` = 'sys_home' AND `cell_id` = 1 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_pages_blocks` (`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('sys_home', 1, 'bx_spaces', '', '_bx_spaces_page_block_title_latest_profiles', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:22:"browse_recent_profiles";}', 1, 0, 0, IFNULL(@iBlockOrder, 0) + 1),
('sys_home', 1, 'bx_spaces', '_bx_spaces_page_block_title_sys_recommended_entries_view_showcase', '_bx_spaces_page_block_title_recommended_entries_view_showcase', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:18:"browse_recommended";}', 1, 0, 0, IFNULL(@iBlockOrder, 0) + 2);
-- PAGE: service blocks
SET @iBlockOrder = (SELECT `order` FROM `sys_pages_blocks` WHERE `object` = '' AND `cell_id` = 0 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_pages_blocks` (`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('', 0, 'bx_spaces', '', '_bx_spaces_page_block_title_categories', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:15:"categories_list";s:6:"params";a:2:{i:0;s:14:"bx_spaces_cats";i:1;a:2:{s:10:\"show_empty\";b:1;s:21:\"show_empty_categories\";b:1;}}s:5:"class";s:20:"TemplServiceCategory";}', 1, 1, 1, IFNULL(@iBlockOrder, 0) + 1),
('', 0, 'bx_spaces', '_bx_spaces_page_block_title_sys_featured_entries_view_showcase', '_bx_spaces_page_block_title_featured_entries_view_showcase', 11, 2147483647, 'service', 'a:3:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:15:\"browse_featured\";s:6:\"params\";a:3:{s:9:\"unit_view\";s:8:\"showcase\";s:13:\"empty_message\";b:0;s:13:\"ajax_paginate\";b:0;}}', 0, 1, 1, IFNULL(@iBlockOrder, 0) + 2),
('', 0, 'bx_spaces', '_bx_spaces_page_block_title_sys_recommended_entries_view_showcase', '_bx_spaces_page_block_title_recommended_entries_view_showcase', 11, 2147483647, 'service', 'a:3:{s:6:\"module\";s:9:\"bx_spaces\";s:6:\"method\";s:18:\"browse_recommended\";s:6:\"params\";a:3:{s:9:\"unit_view\";s:8:\"showcase\";s:13:\"empty_message\";b:0;s:13:\"ajax_paginate\";b:0;}}', 0, 1, 1, IFNULL(@iBlockOrder, 0) + 3);
-- MENU
-- MENU: add to site menu
SET @iSiteMenuOrder = (SELECT `order` FROM `sys_menu_items` WHERE `set_name` = 'sys_site' AND `active` = 1 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('sys_site', 'bx_spaces', 'spaces-home', '_bx_spaces_menu_item_title_system_entries_home', '_bx_spaces_menu_item_title_entries_home', 'page.php?i=spaces-home', '', '', 'object-group col-red2', 'bx_spaces_submenu', 2147483647, 1, 1, IFNULL(@iSiteMenuOrder, 0) + 1);
-- MENU: add to homepage menu
SET @iHomepageMenuOrder = (SELECT `order` FROM `sys_menu_items` WHERE `set_name` = 'sys_homepage' AND `active` = 1 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('sys_homepage', 'bx_spaces', 'spaces-home', '_bx_spaces_menu_item_title_system_entries_home', '_bx_spaces_menu_item_title_entries_home', 'page.php?i=spaces-home', '', '', 'object-group col-red2', 'bx_spaces_submenu', 2147483647, 1, 1, IFNULL(@iHomepageMenuOrder, 0) + 1);
-- MENU: add to "add content" menu
SET @iAddMenuOrder = (SELECT `order` FROM `sys_menu_items` WHERE `set_name` = 'sys_add_content_links' AND `active` = 1 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('sys_add_content_links', 'bx_spaces', 'create-space-profile', '_bx_spaces_menu_item_title_system_create_profile', '_bx_spaces_menu_item_title_create_profile', 'page.php?i=create-space-profile', '', '', 'object-group col-red2', '', 2147483647, 1, 1, IFNULL(@iAddMenuOrder, 0) + 1);
-- MENU: view actions
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_view_actions', '_bx_spaces_menu_title_view_profile_actions', 'bx_spaces_view_actions', 'bx_spaces', 9, 0, 1, 'BxSpacesMenuView', 'modules/boonex/spaces/classes/BxSpacesMenuView.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_spaces_view_actions', 'bx_spaces', '_bx_spaces_menu_set_title_view_profile_actions', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `submenu_popup`, `visible_for_levels`, `active`, `copyable`, `editable`, `order`) VALUES
('bx_spaces_view_actions', 'bx_spaces', 'profile-fan-add', '_bx_spaces_menu_item_title_system_become_fan', '{title_add_fan}', 'javascript:void(0)', 'bx_conn_action(this, \'bx_spaces_fans\', \'add\', \'{profile_id}\')', '', 'user-plus', '', 0, 2147483647, 1, 0, 0, 5),
('bx_spaces_view_actions', 'bx_spaces', 'profile-subscribe-add', '_bx_spaces_menu_item_title_system_subscribe', '_bx_spaces_menu_item_title_subscribe', 'javascript:void(0)', 'bx_conn_action(this, \'sys_profiles_subscriptions\', \'add\', \'{profile_id}\')', '', 'check', '', 0, 2147483647, 1, 0, 1, 20),
('bx_spaces_view_actions', 'bx_spaces', 'profile-actions-more', '_bx_spaces_menu_item_title_system_more_actions', '_bx_spaces_menu_item_title_more_actions', 'javascript:void(0)', 'bx_menu_popup(''bx_spaces_view_actions_more'', this, {}, {profile_id:{profile_id}});', '', 'cog', 'bx_spaces_view_actions_more', 1, 2147483647, 1, 0, 1, 9999);
-- MENU: view actions more
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_view_actions_more', '_bx_spaces_menu_title_view_profile_actions_more', 'bx_spaces_view_actions_more', 'bx_spaces', 6, 0, 1, 'BxSpacesMenuView', 'modules/boonex/spaces/classes/BxSpacesMenuView.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_spaces_view_actions_more', 'bx_spaces', '_bx_spaces_menu_set_title_view_profile_actions_more', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('bx_spaces_view_actions_more', 'bx_spaces', 'profile-fan-remove', '_bx_spaces_menu_item_title_system_leave_space', '{title_remove_fan}', 'javascript:void(0)', 'bx_conn_action(this, \'bx_spaces_fans\', \'remove\', \'{profile_id}\')', '', 'user-times', '', 2147483647, 1, 0, 10),
('bx_spaces_view_actions_more', 'bx_spaces', 'profile-subscribe-remove', '_bx_spaces_menu_item_title_system_unsubscribe', '_bx_spaces_menu_item_title_unsubscribe', 'javascript:void(0)', 'bx_conn_action(this, \'sys_profiles_subscriptions\', \'remove\', \'{profile_id}\')', '', 'check', '', 2147483647, 1, 0, 20),
('bx_spaces_view_actions_more', 'bx_spaces', 'edit-space-cover', '_bx_spaces_menu_item_title_system_edit_cover', '_bx_spaces_menu_item_title_edit_cover', 'page.php?i=edit-space-cover&id={content_id}', '', '', 'pencil-alt', '', 2147483647, 1, 0, 30),
('bx_spaces_view_actions_more', 'bx_spaces', 'edit-space-profile', '_bx_spaces_menu_item_title_system_edit_profile', '_bx_spaces_menu_item_title_edit_profile', 'page.php?i=edit-space-profile&id={content_id}', '', '', 'pencil-alt', '', 2147483647, 1, 0, 40),
('bx_spaces_view_actions_more', 'bx_spaces', 'invite-to-space', '_bx_spaces_menu_item_title_system_invite', '_bx_spaces_menu_item_title_invite', 'page.php?i=invite-to-space&id={content_id}', '', '', 'user-plus', '', 2147483647, 1, 0, 42),
('bx_spaces_view_actions_more', 'bx_spaces', 'delete-space-profile', '_bx_spaces_menu_item_title_system_delete_profile', '_bx_spaces_menu_item_title_delete_profile', 'page.php?i=delete-space-profile&id={content_id}', '', '', 'remove', '', 2147483647, 1, 0, 50);
-- MENU: actions menu for my entries
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_my', '_bx_spaces_menu_title_entries_my', 'bx_spaces_my', 'bx_spaces', 9, 0, 1, 'BxSpacesMenu', 'modules/boonex/spaces/classes/BxSpacesMenu.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_spaces_my', 'bx_spaces', '_bx_spaces_menu_set_title_entries_my', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('bx_spaces_my', 'bx_spaces', 'create-space-profile', '_bx_spaces_menu_item_title_system_create_profile', '_bx_spaces_menu_item_title_create_profile', 'page.php?i=create-space-profile', '', '', 'plus', '', 2147483647, 1, 0, 0);
-- MENU: module sub-menu
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_submenu', '_bx_spaces_menu_title_submenu', 'bx_spaces_submenu', 'bx_spaces', 8, 0, 1, '', '');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_spaces_submenu', 'bx_spaces', '_bx_spaces_menu_set_title_submenu', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('bx_spaces_submenu', 'bx_spaces', 'spaces-home', '_bx_spaces_menu_item_title_system_entries_recent', '_bx_spaces_menu_item_title_entries_recent', 'page.php?i=spaces-home', '', '', '', '', 2147483647, 1, 1, 1),
('bx_spaces_submenu', 'bx_spaces', 'spaces-top', '_bx_spaces_menu_item_title_system_entries_top', '_bx_spaces_menu_item_title_entries_top', 'page.php?i=spaces-top', '', '', '', '', 2147483647, 1, 1, 2),
('bx_spaces_submenu', 'bx_spaces', 'spaces-search', '_bx_spaces_menu_item_title_system_entries_search', '_bx_spaces_menu_item_title_entries_search', 'page.php?i=spaces-search', '', '', '', '', 2147483647, 1, 1, 3),
('bx_spaces_submenu', 'bx_spaces', 'spaces-manage', '_bx_spaces_menu_item_title_system_entries_manage', '_bx_spaces_menu_item_title_entries_manage', 'page.php?i=spaces-manage', '', '', '', '', 2147483646, 1, 1, 4);
-- MENU: view submenu
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_view_submenu', '_bx_spaces_menu_title_view_profile_submenu', 'bx_spaces_view_submenu', 'bx_spaces', 8, 0, 1, 'BxSpacesMenuView', 'modules/boonex/spaces/classes/BxSpacesMenuView.php'),
('bx_spaces_view_submenu_cover', '_bx_spaces_menu_title_view_profile_submenu_cover', 'bx_spaces_view_submenu', 'bx_spaces', 7, 0, 1, 'BxSpacesMenuView', 'modules/boonex/spaces/classes/BxSpacesMenuView.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_spaces_view_submenu', 'bx_spaces', '_bx_spaces_menu_set_title_view_profile_submenu', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('bx_spaces_view_submenu', 'bx_spaces', 'view-space-profile', '_bx_spaces_menu_item_title_system_view_profile_view', '_bx_spaces_menu_item_title_view_profile_view', 'page.php?i=view-space-profile&id={content_id}', '', '', 'object-group col-red2', '', 2147483647, 1, 0, 1),
('bx_spaces_view_submenu', 'bx_spaces', 'space-profile-info', '_bx_spaces_menu_item_title_system_view_profile_info', '_bx_spaces_menu_item_title_view_profile_info', 'page.php?i=space-profile-info&id={content_id}', '', '', 'info-circle col-gray', '', 2147483647, 1, 0, 2),
('bx_spaces_view_submenu', 'bx_spaces', 'space-profile-comments', '_bx_spaces_menu_item_title_system_view_profile_comments', '_bx_spaces_menu_item_title_view_profile_comments', 'page.php?i=space-profile-comments&id={content_id}', '', '', '', '', 2147483647, 0, 0, 3),
('bx_spaces_view_submenu', 'bx_spaces', 'space-fans', '_bx_spaces_menu_item_title_system_view_fans', '_bx_spaces_menu_item_title_view_fans', 'page.php?i=space-fans&profile_id={profile_id}', '', '', 'object-group col-blue3', '', 2147483647, 1, 0, 4);
-- MENU: custom menu for snippet meta info
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_snippet_meta', '_sys_menu_title_snippet_meta', 'bx_spaces_snippet_meta', 'bx_spaces', 15, 0, 1, 'BxSpacesMenuSnippetMeta', 'modules/boonex/spaces/classes/BxSpacesMenuSnippetMeta.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_spaces_snippet_meta', 'bx_spaces', '_sys_menu_set_title_snippet_meta', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `editable`, `order`) VALUES
('bx_spaces_snippet_meta', 'bx_spaces', 'join', '_sys_menu_item_title_system_sm_join', '_sys_menu_item_title_sm_join', '', '', '', '', '', 2147483647, 1, 0, 1, 1),
('bx_spaces_snippet_meta', 'bx_spaces', 'leave', '_sys_menu_item_title_system_sm_leave', '_sys_menu_item_title_sm_leave', '', '', '', '', '', 2147483647, 0, 0, 1, 2),
('bx_spaces_snippet_meta', 'bx_spaces', 'subscribe', '_sys_menu_item_title_system_sm_subscribe', '_sys_menu_item_title_sm_subscribe', '', '', '', '', '', 2147483647, 0, 0, 1, 3),
('bx_spaces_snippet_meta', 'bx_spaces', 'unsubscribe', '_sys_menu_item_title_system_sm_unsubscribe', '_sys_menu_item_title_sm_unsubscribe', '', '', '', '', '', 2147483647, 0, 0, 1, 4),
('bx_spaces_snippet_meta', 'bx_spaces', 'date', '_sys_menu_item_title_system_sm_date', '_sys_menu_item_title_sm_date', '', '', '', '', '', 2147483647, 0, 0, 1, 5),
('bx_spaces_snippet_meta', 'bx_spaces', 'tags', '_sys_menu_item_title_system_sm_tags', '_sys_menu_item_title_sm_tags', '', '', '', '', '', 2147483647, 0, 0, 1, 6),
('bx_spaces_snippet_meta', 'bx_spaces', 'views', '_sys_menu_item_title_system_sm_views', '_sys_menu_item_title_sm_views', '', '', '', '', '', 2147483647, 0, 0, 1, 7),
('bx_spaces_snippet_meta', 'bx_spaces', 'comments', '_sys_menu_item_title_system_sm_comments', '_sys_menu_item_title_sm_comments', '', '', '', '', '', 2147483647, 0, 0, 1, 8),
('bx_spaces_snippet_meta', 'bx_spaces', 'members', '_sys_menu_item_title_system_sm_members', '_sys_menu_item_title_sm_members', '', '', '', '', '', 2147483647, 1, 0, 1, 9),
('bx_spaces_snippet_meta', 'bx_spaces', 'subscribers', '_sys_menu_item_title_system_sm_subscribers', '_sys_menu_item_title_sm_subscribers', '', '', '', '', '', 2147483647, 0, 0, 1, 10);
-- MENU: profile stats
SET @iNotifMenuOrder = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_menu_items` WHERE `set_name` = 'sys_profile_stats' AND `active` = 1 LIMIT 1);
INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `addon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('sys_profile_stats', 'bx_spaces', 'profile-stats-manage-spaces', '_bx_spaces_menu_item_title_system_manage_my_spaces', '_bx_spaces_menu_item_title_manage_my_spaces', 'page.php?i=spaces-manage', '', '_self', 'object-group col-red2', 'a:2:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:41:"get_menu_addon_manage_tools_profile_stats";}', '', 2147483646, 1, 0, @iNotifMenuOrder + 2);
-- MENU: manage tools submenu
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_menu_manage_tools', '_bx_spaces_menu_title_manage_tools', 'bx_spaces_menu_manage_tools', 'bx_spaces', 6, 0, 1, 'BxSpacesMenuManageTools', 'modules/boonex/spaces/classes/BxSpacesMenuManageTools.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_spaces_menu_manage_tools', 'bx_spaces', '_bx_spaces_menu_set_title_manage_tools', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('bx_spaces_menu_manage_tools', 'bx_spaces', 'delete', '_bx_spaces_menu_item_title_system_delete', '_bx_spaces_menu_item_title_delete', 'javascript:void(0)', 'javascript:{js_object}.onClickDelete({content_id});', '_self', 'far trash-alt', '', 2147483647, 1, 0, 1),
('bx_spaces_menu_manage_tools', 'bx_spaces', 'delete-with-content', '_bx_spaces_menu_item_title_system_delete_with_content', '_bx_spaces_menu_item_title_delete_with_content', 'javascript:void(0)', 'javascript:{js_object}.onClickDeleteWithContent({content_id});', '_self', 'far trash-alt', '', 2147483647, 1, 0, 2);
-- MENU: dashboard manage tools
SET @iManageMenuOrder = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_menu_items` WHERE `set_name`='sys_account_dashboard_manage_tools' LIMIT 1);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `addon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('sys_account_dashboard_manage_tools', 'bx_spaces', 'spaces-administration', '_bx_spaces_menu_item_title_system_admt_spaces', '_bx_spaces_menu_item_title_admt_spaces', 'page.php?i=spaces-administration', '', '_self', '', 'a:2:{s:6:"module";s:9:"bx_spaces";s:6:"method";s:27:"get_menu_addon_manage_tools";}', '', 192, 1, 0, @iManageMenuOrder + 1);
-- MENU: add menu item to profiles modules (trigger* menu sets are processed separately upon modules enable/disable)
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('trigger_profile_view_submenu', 'bx_spaces', 'joined-spaces', '_bx_spaces_menu_item_title_system_view_joined_spaces', '_bx_spaces_menu_item_title_view_joined_spaces', 'page.php?i=joined-spaces&profile_id={profile_id}', '', '', 'object-group col-red2', '', 2147483647, 1, 0, 0);
-- ACL
INSERT INTO `sys_acl_actions` (`Module`, `Name`, `AdditionalParamName`, `Title`, `Desc`, `Countable`, `DisabledForLevels`) VALUES
('bx_spaces', 'create entry', NULL, '_bx_spaces_acl_action_create_profile', '', 1, 1);
SET @iIdActionProfileCreate = LAST_INSERT_ID();
INSERT INTO `sys_acl_actions` (`Module`, `Name`, `AdditionalParamName`, `Title`, `Desc`, `Countable`, `DisabledForLevels`) VALUES
('bx_spaces', 'delete entry', NULL, '_bx_spaces_acl_action_delete_profile', '', 1, 1);
SET @iIdActionProfileDelete = LAST_INSERT_ID();
INSERT INTO `sys_acl_actions` (`Module`, `Name`, `AdditionalParamName`, `Title`, `Desc`, `Countable`, `DisabledForLevels`) VALUES
('bx_spaces', 'view entry', NULL, '_bx_spaces_acl_action_view_profile', '', 1, 0);
SET @iIdActionProfileView = LAST_INSERT_ID();
INSERT INTO `sys_acl_actions` (`Module`, `Name`, `AdditionalParamName`, `Title`, `Desc`, `Countable`, `DisabledForLevels`) VALUES
('bx_spaces', 'edit any entry', NULL, '_bx_spaces_acl_action_edit_any_profile', '', 1, 3);
SET @iIdActionProfileEditAny = LAST_INSERT_ID();
SET @iUnauthenticated = 1;
SET @iAccount = 2;
SET @iStandard = 3;
SET @iUnconfirmed = 4;
SET @iPending = 5;
SET @iSuspended = 6;
SET @iModerator = 7;
SET @iAdministrator = 8;
SET @iPremium = 9;
INSERT INTO `sys_acl_matrix` (`IDLevel`, `IDAction`) VALUES
-- profile create
(@iAccount, @iIdActionProfileCreate),
(@iStandard, @iIdActionProfileCreate),
(@iUnconfirmed, @iIdActionProfileCreate),
(@iPending, @iIdActionProfileCreate),
(@iModerator, @iIdActionProfileCreate),
(@iAdministrator, @iIdActionProfileCreate),
(@iPremium, @iIdActionProfileCreate),
-- profile delete
(@iAccount, @iIdActionProfileDelete),
(@iStandard, @iIdActionProfileDelete),
(@iUnconfirmed, @iIdActionProfileDelete),
(@iPending, @iIdActionProfileDelete),
(@iModerator, @iIdActionProfileDelete),
(@iAdministrator, @iIdActionProfileDelete),
(@iPremium, @iIdActionProfileDelete),
-- profile view
(@iUnauthenticated, @iIdActionProfileView),
(@iAccount, @iIdActionProfileView),
(@iStandard, @iIdActionProfileView),
(@iUnconfirmed, @iIdActionProfileView),
(@iPending, @iIdActionProfileView),
(@iModerator, @iIdActionProfileView),
(@iAdministrator, @iIdActionProfileView),
(@iPremium, @iIdActionProfileView),
-- any profile edit
(@iModerator, @iIdActionProfileEditAny),
(@iAdministrator, @iIdActionProfileEditAny);
-- COMMENTS
INSERT INTO `sys_objects_cmts` (`Name`, `Module`, `Table`, `CharsPostMin`, `CharsPostMax`, `CharsDisplayMax`, `Html`, `PerView`, `PerViewReplies`, `BrowseType`, `IsBrowseSwitch`, `PostFormPosition`, `NumberOfLevels`, `IsDisplaySwitch`, `IsRatable`, `ViewingThreshold`, `IsOn`, `RootStylePrefix`, `BaseUrl`, `ObjectVote`, `TriggerTable`, `TriggerFieldId`, `TriggerFieldAuthor`, `TriggerFieldTitle`, `TriggerFieldComments`, `ClassName`, `ClassFile`) VALUES
('bx_spaces', 'bx_spaces', 'bx_spaces_cmts', 1, 5000, 1000, 3, 5, 3, 'tail', 1, 'bottom', 1, 1, 1, -3, 1, 'cmt', 'page.php?i=view-space-profile&id={object_id}', '', 'bx_spaces_data', 'id', 'author', 'space_name', 'comments', '', '');
-- VIEWS
INSERT INTO `sys_objects_view` (`name`, `table_track`, `period`, `is_on`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_count`, `class_name`, `class_file`) VALUES
('bx_spaces', 'bx_spaces_views_track', '86400', '1', 'bx_spaces_data', 'id', 'author', 'views', '', '');
-- VOTES
INSERT INTO `sys_objects_vote` (`Name`, `TableMain`, `TableTrack`, `PostTimeout`, `MinValue`, `MaxValue`, `IsUndo`, `IsOn`, `TriggerTable`, `TriggerFieldId`, `TriggerFieldAuthor`, `TriggerFieldRate`, `TriggerFieldRateCount`, `ClassName`, `ClassFile`) VALUES
('bx_spaces', 'bx_spaces_votes', 'bx_spaces_votes_track', '604800', '1', '1', '0', '1', 'bx_spaces_data', 'id', 'author', 'rate', 'votes', '', '');
-- SCORES
INSERT INTO `sys_objects_score` (`name`, `module`, `table_main`, `table_track`, `post_timeout`, `is_on`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_score`, `trigger_field_cup`, `trigger_field_cdown`, `class_name`, `class_file`) VALUES
('bx_spaces', 'bx_spaces', 'bx_spaces_scores', 'bx_spaces_scores_track', '604800', '0', 'bx_spaces_data', 'id', 'author', 'score', 'sc_up', 'sc_down', '', '');
-- REPORTS
INSERT INTO `sys_objects_report` (`name`, `table_main`, `table_track`, `is_on`, `base_url`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_count`, `class_name`, `class_file`) VALUES
('bx_spaces', 'bx_spaces_reports', 'bx_spaces_reports_track', '1', 'page.php?i=view-space-profile&id={object_id}', 'bx_spaces_data', 'id', 'author', 'reports', '', '');
-- FAFORITES
INSERT INTO `sys_objects_favorite` (`name`, `table_track`, `is_on`, `is_undo`, `is_public`, `base_url`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_count`, `class_name`, `class_file`) VALUES
('bx_spaces', 'bx_spaces_favorites_track', '1', '1', '1', 'page.php?i=view-space-profile&id={object_id}', 'bx_spaces_data', 'id', 'author', 'favorites', '', '');
-- FEATURED
INSERT INTO `sys_objects_feature` (`name`, `is_on`, `is_undo`, `base_url`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_flag`, `class_name`, `class_file`) VALUES
('bx_spaces', '1', '1', 'page.php?i=view-space-profile&id={object_id}', 'bx_spaces_data', 'id', 'author', 'featured', '', '');
-- METATAGS
INSERT INTO `sys_objects_metatags` (`object`, `table_keywords`, `table_locations`, `table_mentions`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces', 'bx_spaces_meta_keywords', '', 'bx_spaces_meta_mentions', '', '');
-- CATEGORY
INSERT INTO `sys_objects_category` (`object`, `search_object`, `form_object`, `list_name`, `table`, `field`, `join`, `where`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_cats', 'bx_spaces', 'bx_space', 'bx_spaces_cats', 'bx_spaces_data', 'space_cat', 'INNER JOIN `sys_profiles` ON (`sys_profiles`.`content_id` = `bx_spaces_data`.`id` AND `sys_profiles`.`type` = ''bx_spaces'')', 'AND `sys_profiles`.`status` = ''active''', '', '');
-- SEARCH
SET @iSearchOrder = (SELECT IFNULL(MAX(`Order`), 0) FROM `sys_objects_search`);
INSERT INTO `sys_objects_search` (`ObjectName`, `Title`, `Order`, `ClassName`, `ClassPath`) VALUES
('bx_spaces', '_bx_spaces', @iSearchOrder + 1, 'BxSpacesSearchResult', 'modules/boonex/spaces/classes/BxSpacesSearchResult.php');
-- CONNECTIONS
INSERT INTO `sys_objects_connection` (`object`, `table`, `type`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_fans', 'bx_spaces_fans', 'mutual', '', '');
-- STATS
SET @iMaxOrderStats = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_statistics`);
INSERT INTO `sys_statistics` (`module`, `name`, `title`, `link`, `icon`, `query`, `order`) VALUES
('bx_spaces', 'bx_spaces', '_bx_spaces', 'page.php?i=spaces-home', 'object-group col-red2', 'SELECT COUNT(*) FROM `bx_spaces_data` AS `td` LEFT JOIN `sys_profiles` AS `tp` ON `td`.`id` = `tp`.`content_id` AND `tp`.`type`=''bx_spaces'' WHERE 1 AND `tp`.`status`=''active''', @iMaxOrderStats + 1);
-- CHARTS
SET @iMaxOrderCharts = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_objects_chart`);
INSERT INTO `sys_objects_chart` (`object`, `title`, `table`, `field_date_ts`, `field_date_dt`, `field_status`, `query`, `active`, `order`, `class_name`, `class_file`) VALUES
('bx_spaces_growth', '_bx_spaces_chart_growth', 'bx_spaces_data', 'added', '', '', 'SELECT {field_date_formatted} AS `period`, COUNT(*) AS {object} FROM {table} LEFT JOIN `sys_profiles` AS `tp` ON {table}.`id` = `tp`.`content_id` AND `tp`.`type`=''bx_spaces'' WHERE 1 AND `tp`.`status`=''active'' {where_inteval} GROUP BY `period` ORDER BY {table}.{field_date} ASC', 1, @iMaxOrderCharts + 1, 'BxDolChartGrowth', ''),
('bx_spaces_growth_speed', '_bx_spaces_chart_growth_speed', 'bx_spaces_data', 'added', '', '', 'SELECT {field_date_formatted} AS `period`, COUNT(*) AS {object} FROM {table} LEFT JOIN `sys_profiles` AS `tp` ON {table}.`id` = `tp`.`content_id` AND `tp`.`type`=''bx_spaces'' WHERE 1 AND `tp`.`status`=''active'' {where_inteval} GROUP BY `period` ORDER BY {table}.{field_date} ASC', 1, @iMaxOrderCharts + 2, 'BxDolChartGrowthSpeed', '');
-- GRID: connections
INSERT INTO `sys_objects_grid` (`object`, `source_type`, `source`, `table`, `field_id`, `field_order`, `field_active`, `paginate_url`, `paginate_per_page`, `paginate_simple`, `paginate_get_start`, `paginate_get_per_page`, `filter_fields`, `filter_fields_translatable`, `filter_mode`, `sorting_fields`, `sorting_fields_translatable`, `visible_for_levels`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_fans', 'Sql', 'SELECT `p`.`id`, `c`.`added`, `c`.`mutual` FROM `sys_profiles` AS `p` INNER JOIN `sys_accounts` AS `a` ON (`a`.`id` = `p`.`account_id`) {join_connections}', 'sys_profiles', 'id', 'c`.`added', '', '', 10, NULL, 'start', '', 'name,email', '', 'auto', '', '', 2147483647, 'BxSpacesGridConnections', 'modules/boonex/spaces/classes/BxSpacesGridConnections.php');
INSERT INTO `sys_grid_fields` (`object`, `name`, `title`, `width`, `params`, `order`) VALUES
('bx_spaces_fans', 'name', '_sys_name', '50%', '', 10),
('bx_spaces_fans', 'actions', '', '50%', '', 20);
INSERT INTO `sys_grid_actions` (`object`, `type`, `name`, `title`, `icon`, `confirm`, `order`) VALUES
('bx_spaces_fans', 'single', 'accept', '_sys_accept', '', 0, 10),
('bx_spaces_fans', 'single', 'to_admins', '_bx_spaces_txt_to_admins', '', 0, 20),
('bx_spaces_fans', 'single', 'from_admins', '_bx_spaces_txt_from_admins', '', 0, 30),
('bx_spaces_fans', 'single', 'delete', '', 'remove', 1, 40);
-- GRIDS: administration
INSERT INTO `sys_objects_grid` (`object`, `source_type`, `source`, `table`, `field_id`, `field_order`, `field_active`, `paginate_url`, `paginate_per_page`, `paginate_simple`, `paginate_get_start`, `paginate_get_per_page`, `filter_fields`, `filter_fields_translatable`, `filter_mode`, `sorting_fields`, `sorting_fields_translatable`, `visible_for_levels`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_administration', 'Sql', 'SELECT `td`.*, `td`.`space_name` AS `name`, `ta`.`email` AS `account`, `td`.`added` AS `added_ts`, `tp`.`status` AS `status` FROM `bx_spaces_data` AS `td` LEFT JOIN `sys_profiles` AS `tp` ON `td`.`id`=`tp`.`content_id` AND `tp`.`type`=''bx_spaces'' LEFT JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id` WHERE 1 ', 'bx_spaces_data', 'id', 'added', 'status', '', 20, NULL, 'start', '', 'space_name', '', 'like', 'reports', '', 192, 'BxSpacesGridAdministration', 'modules/boonex/spaces/classes/BxSpacesGridAdministration.php'),
('bx_spaces_common', 'Sql', 'SELECT `td`.*, `td`.`space_name` AS `name`, `ta`.`email` AS `account`, `td`.`added` AS `added_ts`, `tp`.`status` AS `status` FROM `bx_spaces_data` AS `td` LEFT JOIN `sys_profiles` AS `tp` ON `td`.`id`=`tp`.`content_id` AND `tp`.`type`=''bx_spaces'' LEFT JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id` WHERE 1 ', 'bx_spaces_data', 'id', 'added', 'status', '', 20, NULL, 'start', '', 'space_name', '', 'like', '', '', 2147483647, 'BxSpacesGridCommon', 'modules/boonex/spaces/classes/BxSpacesGridCommon.php');
INSERT INTO `sys_grid_fields` (`object`, `name`, `title`, `width`, `translatable`, `chars_limit`, `params`, `order`) VALUES
('bx_spaces_administration', 'checkbox', '_sys_select', '2%', 0, '', '', 1),
('bx_spaces_administration', 'switcher', '_bx_spaces_grid_column_title_adm_active', '8%', 0, '', '', 2),
('bx_spaces_administration', 'reports', '_sys_txt_reports_title', '5%', 0, '', '', 3),
('bx_spaces_administration', 'name', '_bx_spaces_grid_column_title_adm_name', '25%', 0, '', '', 4),
('bx_spaces_administration', 'added_ts', '_bx_spaces_grid_column_title_adm_added', '20%', 1, '25', '', 5),
('bx_spaces_administration', 'account', '_bx_spaces_grid_column_title_adm_account', '20%', 0, '25', '', 6),
('bx_spaces_administration', 'actions', '', '20%', 0, '', '', 7),
('bx_spaces_common', 'checkbox', '_sys_select', '2%', 0, '', '', 1),
('bx_spaces_common', 'name', '_bx_spaces_grid_column_title_adm_name', '48%', 0, '', '', 2),
('bx_spaces_common', 'added_ts', '_bx_spaces_grid_column_title_adm_added', '30%', 1, '25', '', 3),
('bx_spaces_common', 'actions', '', '20%', 0, '', '', 4);
INSERT INTO `sys_grid_actions` (`object`, `type`, `name`, `title`, `icon`, `icon_only`, `confirm`, `order`) VALUES
('bx_spaces_administration', 'bulk', 'delete', '_bx_spaces_grid_action_title_adm_delete', '', 0, 1, 2),
('bx_spaces_administration', 'bulk', 'delete_with_content', '_bx_spaces_grid_action_title_adm_delete_with_content', '', 0, 1, 3),
('bx_spaces_administration', 'single', 'settings', '_bx_spaces_grid_action_title_adm_more_actions', 'cog', 1, 0, 2),
('bx_spaces_common', 'bulk', 'delete', '_bx_spaces_grid_action_title_adm_delete', '', 0, 1, 1),
('bx_spaces_common', 'bulk', 'delete_with_content', '_bx_spaces_grid_action_title_adm_delete_with_content', '', 0, 1, 2),
('bx_spaces_common', 'single', 'settings', '_bx_spaces_grid_action_title_adm_more_actions', 'cog', 1, 0, 1);
-- ALERTS
INSERT INTO `sys_alerts_handlers` (`name`, `class`, `file`, `service_call`) VALUES
('bx_spaces', 'BxSpacesAlertsResponse', 'modules/boonex/spaces/classes/BxSpacesAlertsResponse.php', '');
SET @iHandler := LAST_INSERT_ID();
INSERT INTO `sys_alerts` (`unit`, `action`, `handler_id`) VALUES
('system', 'save_setting', @iHandler),
('bx_timeline', 'post_common', @iHandler),
('bx_spaces_pics', 'file_deleted', @iHandler),
('bx_spaces_fans', 'connection_added', @iHandler),
('bx_spaces_fans', 'connection_removed', @iHandler),
('profile', 'delete', @iHandler),
('bx_spaces', 'fan_added', @iHandler),
('bx_spaces', 'join_invitation', @iHandler),
('bx_spaces', 'join_request', @iHandler),
('bx_spaces', 'join_request_accepted', @iHandler),
('bx_spaces', 'timeline_view', @iHandler),
('bx_spaces', 'timeline_post', @iHandler),
('bx_spaces', 'timeline_delete', @iHandler),
('bx_spaces', 'timeline_comment', @iHandler),
('bx_spaces', 'timeline_vote', @iHandler),
('bx_spaces', 'timeline_report', @iHandler),
('bx_spaces', 'timeline_repost', @iHandler);
-- PRIVACY
INSERT INTO `sys_objects_privacy` (`object`, `module`, `action`, `title`, `default_group`, `spaces`, `table`, `table_field_id`, `table_field_author`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_allow_view_to', 'bx_spaces', 'view', '_bx_spaces_form_profile_input_allow_view_to', '3', '', 'bx_spaces_data', 'id', 'author', 'BxSpacesPrivacy', 'modules/boonex/spaces/classes/BxSpacesPrivacy.php'),
('bx_spaces_allow_view_notification_to', 'bx_spaces', 'view_event', '_bx_spaces_form_profile_input_allow_view_notification_to', '3', '', 'bx_notifications_events', 'id', 'object_owner_id', 'BxSpacesPrivacyNotifications', 'modules/boonex/spaces/classes/BxSpacesPrivacyNotifications.php');
-- EMAIL TEMPLATES
INSERT INTO `sys_email_templates` (`Module`, `NameSystem`, `Name`, `Subject`, `Body`) VALUES
('bx_spaces', '_bx_spaces_email_join_request', 'bx_spaces_join_request', '_bx_spaces_email_join_request_subject', '_bx_spaces_email_join_request_body'),
('bx_spaces', '_bx_spaces_email_join_reject', 'bx_spaces_join_reject', '_bx_spaces_email_join_reject_subject', '_bx_spaces_email_join_reject_body'),
('bx_spaces', '_bx_spaces_email_join_confirm', 'bx_spaces_join_confirm', '_bx_spaces_email_join_confirm_subject', '_bx_spaces_email_join_confirm_body'),
('bx_spaces', '_bx_spaces_email_fan_remove', 'bx_spaces_fan_remove', '_bx_spaces_email_fan_remove_subject', '_bx_spaces_email_fan_remove_body'),
('bx_spaces', '_bx_spaces_email_fan_become_admin', 'bx_spaces_fan_become_admin', '_bx_spaces_email_fan_become_admin_subject', '_bx_spaces_email_fan_become_admin_body'),
('bx_spaces', '_bx_spaces_email_admin_become_fan', 'bx_spaces_admin_become_fan', '_bx_spaces_email_admin_become_fan_subject', '_bx_spaces_email_admin_become_fan_body'),
('bx_spaces', '_bx_spaces_email_invitation', 'bx_spaces_invitation', '_bx_spaces_email_invitation_subject', '_bx_spaces_email_invitation_body');
-- UPLOADERS
INSERT INTO `sys_objects_uploader` (`object`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_spaces_cover_crop', 1, 'BxSpacesUploaderCoverCrop', 'modules/boonex/spaces/classes/BxSpacesUploaderCoverCrop.php'),
('bx_spaces_picture_crop', 1, 'BxSpacesUploaderPictureCrop', 'modules/boonex/spaces/classes/BxSpacesUploaderPictureCrop.php');
|
camperjz/trident
|
modules/boonex/spaces/updates/9.0.0_9.0.1/source/install/sql/enable.sql
|
SQL
|
mit
| 57,244
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>BWU Datagrid example: 09 Row Reordering</title>
<link rel="import" href="src/e09_row_reordering/app_element.html">
<link rel='stylesheet' href='asset/examples.css'>
<link rel="stylesheet" href='../packages/bwu_datagrid/asset/smoothness/jquery-ui-1.8.16.custom.css'> <!-- TODO remove, only here due to a bug in code generation when files change -->
</head>
<body>
<app-element></app-element>
<script type="application/dart">export 'package:polymer/init.dart';</script>
</body>
</html>
|
terrasea/bwu_datagrid
|
example/e09_row_reordering.html
|
HTML
|
mit
| 736
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef __OPENCV_CORE_UTILITY_H__
#define __OPENCV_CORE_UTILITY_H__
#ifndef __cplusplus
# error utility.hpp header must be compiled as C++
#endif
#include "opencv2/core.hpp"
namespace cv
{
/*!
Automatically Allocated Buffer Class
The class is used for temporary buffers in functions and methods.
If a temporary buffer is usually small (a few K's of memory),
but its size depends on the parameters, it makes sense to create a small
fixed-size array on stack and use it if it's large enough. If the required buffer size
is larger than the fixed size, another buffer of sufficient size is allocated dynamically
and released after the processing. Therefore, in typical cases, when the buffer size is small,
there is no overhead associated with malloc()/free().
At the same time, there is no limit on the size of processed data.
This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
the number of stack-allocated elements. Here is how the class is used:
\code
void my_func(const cv::Mat& m)
{
cv::AutoBuffer<float> buf; // create automatic buffer containing 1000 floats
buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
// otherwise the buffer of "m.rows" floats will be allocated
// dynamically and deallocated in cv::AutoBuffer destructor
...
}
\endcode
*/
template<typename _Tp, size_t fixed_size = 1024/sizeof(_Tp)+8> class AutoBuffer
{
public:
typedef _Tp value_type;
//! the default constructor
AutoBuffer();
//! constructor taking the real buffer size
AutoBuffer(size_t _size);
//! the copy constructor
AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf);
//! the assignment operator
AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf);
//! destructor. calls deallocate()
~AutoBuffer();
//! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
void allocate(size_t _size);
//! deallocates the buffer if it was dynamically allocated
void deallocate();
//! resizes the buffer and preserves the content
void resize(size_t _size);
//! returns the current buffer size
size_t size() const;
//! returns pointer to the real buffer, stack-allocated or head-allocated
operator _Tp* ();
//! returns read-only pointer to the real buffer, stack-allocated or head-allocated
operator const _Tp* () const;
protected:
//! pointer to the real buffer, can point to buf if the buffer is small enough
_Tp* ptr;
//! size of the real buffer
size_t sz;
//! pre-allocated buffer. At least 1 element to confirm C++ standard reqirements
_Tp buf[(fixed_size > 0) ? fixed_size : 1];
};
//! Sets/resets the break-on-error mode.
/*!
When the break-on-error mode is set, the default error handler
issues a hardware exception, which can make debugging more convenient.
\return the previous state
*/
CV_EXPORTS bool setBreakOnError(bool flag);
extern "C" typedef int (*ErrorCallback)( int status, const char* func_name,
const char* err_msg, const char* file_name,
int line, void* userdata );
//! Sets the new error handler and the optional user data.
/*!
The function sets the new error handler, called from cv::error().
\param errCallback the new error handler. If NULL, the default error handler is used.
\param userdata the optional user data pointer, passed to the callback.
\param prevUserdata the optional output parameter where the previous user data pointer is stored
\return the previous error handler
*/
CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0);
CV_EXPORTS String format( const char* fmt, ... );
CV_EXPORTS String tempfile( const char* suffix = 0);
CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
CV_EXPORTS void setNumThreads(int nthreads);
CV_EXPORTS int getNumThreads();
CV_EXPORTS int getThreadNum();
CV_EXPORTS_W const String& getBuildInformation();
//! Returns the number of ticks.
/*!
The function returns the number of ticks since the certain event (e.g. when the machine was turned on).
It can be used to initialize cv::RNG or to measure a function execution time by reading the tick count
before and after the function call. The granularity of ticks depends on the hardware and OS used. Use
cv::getTickFrequency() to convert ticks to seconds.
*/
CV_EXPORTS_W int64 getTickCount();
/*!
Returns the number of ticks per seconds.
The function returns the number of ticks (as returned by cv::getTickCount()) per second.
The following code computes the execution time in milliseconds:
\code
double exec_time = (double)getTickCount();
// do something ...
exec_time = ((double)getTickCount() - exec_time)*1000./getTickFrequency();
\endcode
*/
CV_EXPORTS_W double getTickFrequency();
/*!
Returns the number of CPU ticks.
On platforms where the feature is available, the function returns the number of CPU ticks
since the certain event (normally, the system power-on moment). Using this function
one can accurately measure the execution time of very small code fragments,
for which cv::getTickCount() granularity is not enough.
*/
CV_EXPORTS_W int64 getCPUTickCount();
//! Available CPU features. Currently, the following features are recognized:
enum {
CPU_MMX = 1,
CPU_SSE = 2,
CPU_SSE2 = 3,
CPU_SSE3 = 4,
CPU_SSSE3 = 5,
CPU_SSE4_1 = 6,
CPU_SSE4_2 = 7,
CPU_POPCNT = 8,
CPU_AVX = 10,
CPU_NEON = 11
};
// remember to keep this list identical to the one in cvdef.h
/*!
Returns SSE etc. support status
The function returns true if certain hardware features are available.
\note {Note that the function output is not static. Once you called cv::useOptimized(false),
most of the hardware acceleration is disabled and thus the function will returns false,
until you call cv::useOptimized(true)}
*/
CV_EXPORTS_W bool checkHardwareSupport(int feature);
//! returns the number of CPUs (including hyper-threading)
CV_EXPORTS_W int getNumberOfCPUs();
/*!
Aligns pointer by the certain number of bytes
This small inline function aligns the pointer by the certian number of bytes by shifting
it forward by 0 or a positive offset.
*/
template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
{
return (_Tp*)(((size_t)ptr + n-1) & -n);
}
/*!
Aligns buffer size by the certain number of bytes
This small inline function aligns a buffer size by the certian number of bytes by enlarging it.
*/
static inline size_t alignSize(size_t sz, int n)
{
CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2
return (sz + n-1) & -n;
}
/*!
Turns on/off available optimization
The function turns on or off the optimized code in OpenCV. Some optimization can not be enabled
or disabled, but, for example, most of SSE code in OpenCV can be temporarily turned on or off this way.
\note{Since optimization may imply using special data structures, it may be unsafe
to call this function anywhere in the code. Instead, call it somewhere at the top level.}
*/
CV_EXPORTS_W void setUseOptimized(bool onoff);
/*!
Returns the current optimization status
The function returns the current optimization status, which is controlled by cv::setUseOptimized().
*/
CV_EXPORTS_W bool useOptimized();
static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); }
/////////////////////////////// Parallel Primitives //////////////////////////////////
// a base body class
class CV_EXPORTS ParallelLoopBody
{
public:
virtual ~ParallelLoopBody();
virtual void operator() (const Range& range) const = 0;
};
CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.);
/////////////////////////// Synchronization Primitives ///////////////////////////////
class CV_EXPORTS Mutex
{
public:
Mutex();
~Mutex();
Mutex(const Mutex& m);
Mutex& operator = (const Mutex& m);
void lock();
bool trylock();
void unlock();
struct Impl;
protected:
Impl* impl;
};
class CV_EXPORTS AutoLock
{
public:
AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); }
~AutoLock() { mutex->unlock(); }
protected:
Mutex* mutex;
private:
AutoLock(const AutoLock&);
AutoLock& operator = (const AutoLock&);
};
class CV_EXPORTS TLSDataContainer
{
private:
int key_;
protected:
TLSDataContainer();
virtual ~TLSDataContainer();
public:
virtual void* createDataInstance() const = 0;
virtual void deleteDataInstance(void* data) const = 0;
void* getData() const;
};
template <typename T>
class TLSData : protected TLSDataContainer
{
public:
inline TLSData() {}
inline ~TLSData() {}
inline T* get() const { return (T*)getData(); }
private:
virtual void* createDataInstance() const { return new T; }
virtual void deleteDataInstance(void* data) const { delete (T*)data; }
};
// The CommandLineParser class is designed for command line arguments parsing
class CV_EXPORTS CommandLineParser
{
public:
CommandLineParser(int argc, const char* const argv[], const String& keys);
CommandLineParser(const CommandLineParser& parser);
CommandLineParser& operator = (const CommandLineParser& parser);
~CommandLineParser();
String getPathToApplication() const;
template <typename T>
T get(const String& name, bool space_delete = true) const
{
T val = T();
getByName(name, space_delete, ParamType<T>::type, (void*)&val);
return val;
}
template <typename T>
T get(int index, bool space_delete = true) const
{
T val = T();
getByIndex(index, space_delete, ParamType<T>::type, (void*)&val);
return val;
}
bool has(const String& name) const;
bool check() const;
void about(const String& message);
void printMessage() const;
void printErrors() const;
protected:
void getByName(const String& name, bool space_delete, int type, void* dst) const;
void getByIndex(int index, bool space_delete, int type, void* dst) const;
struct Impl;
Impl* impl;
};
/////////////////////////////// AutoBuffer implementation ////////////////////////////////////////
template<typename _Tp, size_t fixed_size> inline
AutoBuffer<_Tp, fixed_size>::AutoBuffer()
{
ptr = buf;
sz = fixed_size;
}
template<typename _Tp, size_t fixed_size> inline
AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size)
{
ptr = buf;
sz = fixed_size;
allocate(_size);
}
template<typename _Tp, size_t fixed_size> inline
AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf )
{
ptr = buf;
sz = fixed_size;
allocate(abuf.size());
for( size_t i = 0; i < sz; i++ )
ptr[i] = abuf.ptr[i];
}
template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>&
AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf)
{
if( this != &abuf )
{
deallocate();
allocate(abuf.size());
for( size_t i = 0; i < sz; i++ )
ptr[i] = abuf.ptr[i];
}
return *this;
}
template<typename _Tp, size_t fixed_size> inline
AutoBuffer<_Tp, fixed_size>::~AutoBuffer()
{ deallocate(); }
template<typename _Tp, size_t fixed_size> inline void
AutoBuffer<_Tp, fixed_size>::allocate(size_t _size)
{
if(_size <= sz)
{
sz = _size;
return;
}
deallocate();
if(_size > fixed_size)
{
ptr = new _Tp[_size];
sz = _size;
}
}
template<typename _Tp, size_t fixed_size> inline void
AutoBuffer<_Tp, fixed_size>::deallocate()
{
if( ptr != buf )
{
delete[] ptr;
ptr = buf;
sz = fixed_size;
}
}
template<typename _Tp, size_t fixed_size> inline void
AutoBuffer<_Tp, fixed_size>::resize(size_t _size)
{
if(_size <= sz)
{
sz = _size;
return;
}
size_t i, prevsize = sz, minsize = MIN(prevsize, _size);
_Tp* prevptr = ptr;
ptr = _size > fixed_size ? new _Tp[_size] : buf;
sz = _size;
if( ptr != prevptr )
for( i = 0; i < minsize; i++ )
ptr[i] = prevptr[i];
for( i = prevsize; i < _size; i++ )
ptr[i] = _Tp();
if( prevptr != buf )
delete[] prevptr;
}
template<typename _Tp, size_t fixed_size> inline size_t
AutoBuffer<_Tp, fixed_size>::size() const
{ return sz; }
template<typename _Tp, size_t fixed_size> inline
AutoBuffer<_Tp, fixed_size>::operator _Tp* ()
{ return ptr; }
template<typename _Tp, size_t fixed_size> inline
AutoBuffer<_Tp, fixed_size>::operator const _Tp* () const
{ return ptr; }
#ifndef OPENCV_NOSTL
template<> inline std::string CommandLineParser::get<std::string>(int index, bool space_delete) const
{
return get<String>(index, space_delete);
}
template<> inline std::string CommandLineParser::get<std::string>(const String& name, bool space_delete) const
{
return get<String>(name, space_delete);
}
#endif // OPENCV_NOSTL
} //namespace cv
#endif //__OPENCV_CORE_UTILITY_H__
|
ianyh/heroku-buildpack-python-opencv
|
vendor/.heroku/include/opencv2/core/utility.hpp
|
C++
|
mit
| 15,573
|
<?php namespace Laracasts\Utilities\JavaScript\Facades;
use Illuminate\Support\Facades\Facade;
class JavaScript extends Facade {
/**
* Name of the binding in the IoC container
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'JavaScript';
}
}
|
PavelPolyakov/laravel-demo
|
vendor/laracasts/utilities/src/Laracasts/Utilities/JavaScript/Facades/JavaScript.php
|
PHP
|
mit
| 319
|
using System.Collections.Generic;
using System.Linq;
using Baseline;
using Marten.Events;
using Marten.Patching;
namespace Marten.Services
{
public class ChangeSet : IChangeSet
{
public readonly IList<object> Updated = new List<object>();
public readonly IList<object> Inserted = new List<object>();
public readonly IList<EventStream> Streams = new List<EventStream>();
public readonly IList<IStorageOperation> Operations = new List<IStorageOperation>();
IEnumerable<object> IChangeSet.Updated => Updated;
IEnumerable<object> IChangeSet.Inserted => Inserted;
IEnumerable<IDeletion> IChangeSet.Deleted => Operations.OfType<IDeletion>();
public DocumentChange[] Changes;
public ChangeSet(DocumentChange[] documentChanges)
{
Changes = documentChanges;
Updated.AddRange(documentChanges.Select(x => x.Document));
}
public IEnumerable<IEvent> GetEvents()
{
return Streams.SelectMany(s => s.Events);
}
IEnumerable<PatchOperation> IChangeSet.Patches => Operations.OfType<PatchOperation>();
public IEnumerable<EventStream> GetStreams()
{
return Streams;
}
}
}
|
jokokko/marten
|
src/Marten/Services/ChangeSet.cs
|
C#
|
mit
| 1,271
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr" id="html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>jQuery Test Suite</title>
<link rel="Stylesheet" media="screen" href="qunit/qunit/qunit.css" />
<link rel="Stylesheet" media="screen" href="data/testsuite.css" />
<!-- Includes -->
<script src="data/testinit.js"></script>
<script src="qunit/qunit/qunit.js"></script>
<!-- Loads minified version if min=true is present in the search -->
<!-- Nullifies querySelectorAll if noqsa=true is present -->
<script>
(function() {
var src = "../dist/jquery.js";
QUnit.config.urlConfig.push( "min" );
if ( QUnit.urlParams.min ) {
src = "../dist/jquery.min.js";
}
QUnit.config.urlConfig.push( "noqsa" );
if ( QUnit.urlParams.noqsa ) {
document.querySelectorAll = null;
}
document.write( "<script src='" + src + "'><\/script>" );
})();
</script>
<script src="data/testrunner.js"></script>
<script src="unit/core.js"></script>
<script src="unit/callbacks.js"></script>
<script src="unit/deferred.js"></script>
<script src="unit/support.js"></script>
<script src="unit/data.js"></script>
<script src="unit/queue.js"></script>
<script src="unit/attributes.js"></script>
<script src="unit/event.js"></script>
<script src="unit/selector.js"></script>
<script src="unit/traversing.js"></script>
<script src="unit/manipulation.js"></script>
<script src="unit/css.js"></script>
<script src="unit/serialize.js"></script>
<script src="unit/ajax.js"></script>
<script src="unit/effects.js"></script>
<script src="unit/offset.js"></script>
<script src="unit/dimensions.js"></script>
<script src="unit/deprecated.js"></script>
<script src="unit/exports.js"></script>
<!-- Subproject tests must be last because they replace our test fixture -->
<script>
testSubproject( "Sizzle", "../src/sizzle/test/", /^unit\/.*\.js$/ );
</script>
<script>
// html5shiv, enabling HTML5 elements to be used with jQuery
( "abbr article aside audio bdi canvas data details figcaption figure footer header hgroup " +
"mark meter nav output progress section summary time video"
).replace(/\w+/g, function(n) {
document.createElement(n);
});
</script>
</head>
<body id="body">
<h1 id="qunit-header"><a href="/jquery/test/index.html">jQuery Test Suite</a></h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<!-- Test HTML -->
<div id="nothiddendiv" style="height:1px;background:white;" class="nothiddendiv">
<div id="nothiddendivchild"></div>
</div>
<!-- this iframe is outside the #qunit-fixture so it won't reload constantly wasting time, but it means the tests must be "safe" and clean up after themselves -->
<iframe id="loadediframe" name="loadediframe" style="display:none;" src="data/iframe.html"></iframe>
<dl id="dl" style="position:absolute;top:-32767px;left:-32767px;width:1px">
<div id="qunit-fixture">
<p id="firstp">See <a id="simon1" href="http://simon.incutio.com/archive/2003/03/25/#getElementsBySelector" rel="bookmark">this blog entry</a> for more information.</p>
<p id="ap">
Here are some links in a normal paragraph: <a id="google" href="http://www.google.com/" title="Google!">Google</a>,
<a id="groups" href="http://groups.google.com/" class="GROUPS">Google Groups (Link)</a>.
This link has <code><a href="http://smin" id="anchor1">class="blog"</a></code>:
<a href="http://diveintomark.org/" class="blog" hreflang="en" id="mark">diveintomark</a>
</p>
<div id="foo">
<p id="sndp">Everything inside the red border is inside a div with <code>id="foo"</code>.</p>
<p lang="en" id="en">This is a normal link: <a id="yahoo" href="http://www.yahoo.com/" class="blogTest">Yahoo</a></p>
<p id="sap">This link has <code><a href="#2" id="anchor2">class="blog"</a></code>: <a href="http://simon.incutio.com/" class="blog link" id="simon">Simon Willison's Weblog</a></p>
</div>
<span id="name+value"></span>
<p id="first">Try them out:</p>
<ul id="firstUL"></ul>
<ol id="empty"></ol>
<form id="form" action="formaction">
<label for="action" id="label-for">Action:</label>
<input type="text" name="action" value="Test" id="text1" maxlength="30"/>
<input type="text" name="text2" value="Test" id="text2" disabled="disabled"/>
<input type="radio" name="radio1" id="radio1" value="on"/>
<input type="radio" name="radio2" id="radio2" checked="checked"/>
<input type="checkbox" name="check" id="check1" checked="checked"/>
<input type="checkbox" id="check2" value="on"/>
<input type="hidden" name="hidden" id="hidden1"/>
<input type="text" style="display:none;" name="foo[bar]" id="hidden2"/>
<input type="text" id="name" name="name" value="name" />
<input type="search" id="search" name="search" value="search" />
<button id="button" name="button" type="button">Button</button>
<textarea id="area1" maxlength="30">foobar</textarea>
<select name="select1" id="select1">
<option id="option1a" class="emptyopt" value="">Nothing</option>
<option id="option1b" value="1">1</option>
<option id="option1c" value="2">2</option>
<option id="option1d" value="3">3</option>
</select>
<select name="select2" id="select2">
<option id="option2a" class="emptyopt" value="">Nothing</option>
<option id="option2b" value="1">1</option>
<option id="option2c" value="2">2</option>
<option id="option2d" selected="selected" value="3">3</option>
</select>
<select name="select3" id="select3" multiple="multiple">
<option id="option3a" class="emptyopt" value="">Nothing</option>
<option id="option3b" selected="selected" value="1">1</option>
<option id="option3c" selected="selected" value="2">2</option>
<option id="option3d" value="3">3</option>
<option id="option3e">no value</option>
</select>
<select name="select4" id="select4" multiple="multiple">
<optgroup disabled="disabled">
<option id="option4a" class="emptyopt" value="">Nothing</option>
<option id="option4b" disabled="disabled" selected="selected" value="1">1</option>
<option id="option4c" selected="selected" value="2">2</option>
</optgroup>
<option selected="selected" disabled="disabled" id="option4d" value="3">3</option>
<option id="option4e">no value</option>
</select>
<select name="select5" id="select5">
<option id="option5a" value="3">1</option>
<option id="option5b" value="2">2</option>
<option id="option5c" value="1" data-attr="">3</option>
</select>
<object id="object1" codebase="stupid">
<param name="p1" value="x1" />
<param name="p2" value="x2" />
</object>
<span id="台北Táiběi"></span>
<span id="台北" lang="中文"></span>
<span id="utf8class1" class="台北Táiběi 台北"></span>
<span id="utf8class2" class="台北"></span>
<span id="foo:bar" class="foo:bar"></span>
<span id="test.foo[5]bar" class="test.foo[5]bar"></span>
<foo_bar id="foobar">test element</foo_bar>
</form>
<b id="floatTest">Float test.</b>
<iframe id="iframe" name="iframe"></iframe>
<form id="lengthtest">
<input type="text" id="length" name="test"/>
<input type="text" id="idTest" name="id"/>
</form>
<table id="table"></table>
<form id="name-tests">
<!-- Inputs with a grouped name attribute. -->
<input name="types[]" id="types_all" type="checkbox" value="all" />
<input name="types[]" id="types_anime" type="checkbox" value="anime" />
<input name="types[]" id="types_movie" type="checkbox" value="movie" />
</form>
<form id="testForm" action="#" method="get">
<textarea name="T3" rows="2" cols="15">?
Z</textarea>
<input type="hidden" name="H1" value="x" />
<input type="hidden" name="H2" />
<input name="PWD" type="password" value="" />
<input name="T1" type="text" />
<input name="T2" type="text" value="YES" readonly="readonly" />
<input type="checkbox" name="C1" value="1" />
<input type="checkbox" name="C2" />
<input type="radio" name="R1" value="1" />
<input type="radio" name="R1" value="2" />
<input type="text" name="My Name" value="me" />
<input type="reset" name="reset" value="NO" />
<select name="S1">
<option value="abc">ABC</option>
<option value="abc">ABC</option>
<option value="abc">ABC</option>
</select>
<select name="S2" multiple="multiple" size="3">
<option value="abc">ABC</option>
<option value="abc">ABC</option>
<option value="abc">ABC</option>
</select>
<select name="S3">
<option selected="selected">YES</option>
</select>
<select name="S4">
<option value="" selected="selected">NO</option>
</select>
<input type="submit" name="sub1" value="NO" />
<input type="submit" name="sub2" value="NO" />
<input type="image" name="sub3" value="NO" />
<button name="sub4" type="submit" value="NO">NO</button>
<input name="D1" type="text" value="NO" disabled="disabled" />
<input type="checkbox" checked="checked" disabled="disabled" name="D2" value="NO" />
<input type="radio" name="D3" value="NO" checked="checked" disabled="disabled" />
<select name="D4" disabled="disabled">
<option selected="selected" value="NO">NO</option>
</select>
<input id="list-test" type="text" />
<datalist id="datalist">
<option value="option"></option>
</datalist>
</form>
<div id="moretests">
<form>
<div id="checkedtest" style="display:none;">
<input type="radio" name="checkedtestradios" checked="checked"/>
<input type="radio" name="checkedtestradios" value="on"/>
<input type="checkbox" name="checkedtestcheckboxes" checked="checked"/>
<input type="checkbox" name="checkedtestcheckboxes" />
</div>
</form>
<div id="nonnodes"><span>hi</span> there <!-- mon ami --></div>
<div id="t2037">
<div><div class="hidden">hidden</div></div>
</div>
<div id="t6652">
<div></div>
</div>
<div id="no-clone-exception"><object><embed></embed></object></div>
</div>
<div id="tabindex-tests">
<ol id="listWithTabIndex" tabindex="5">
<li id="foodWithNegativeTabIndex" tabindex="-1">Rice</li>
<li id="foodNoTabIndex">Beans</li>
<li>Blinis</li>
<li>Tofu</li>
</ol>
<div id="divWithNoTabIndex">I'm hungry. I should...</div>
<span>...</span><a href="#" id="linkWithNoTabIndex">Eat lots of food</a><span>...</span> |
<span>...</span><a href="#" id="linkWithTabIndex" tabindex="2">Eat a little food</a><span>...</span> |
<span>...</span><a href="#" id="linkWithNegativeTabIndex" tabindex="-1">Eat no food</a><span>...</span>
<span>...</span><a id="linkWithNoHrefWithNoTabIndex">Eat a burger</a><span>...</span>
<span>...</span><a id="linkWithNoHrefWithTabIndex" tabindex="1">Eat some funyuns</a><span>...</span>
<span>...</span><a id="linkWithNoHrefWithNegativeTabIndex" tabindex="-1">Eat some funyuns</a><span>...</span>
</div>
<div id="liveHandlerOrder">
<span id="liveSpan1"><a href="#" id="liveLink1"></a></span>
<span id="liveSpan2"><a href="#" id="liveLink2"></a></span>
</div>
<div id="siblingTest">
<em id="siblingfirst">1</em>
<em id="siblingnext">2</em>
<em id="siblingthird">
<em id="siblingchild">
<em id="siblinggrandchild">
<em id="siblinggreatgrandchild"></em>
</em>
</em>
</em>
<span id="siblingspan"></span>
</div>
</div>
</dl>
<div id="fx-test-group" style="position:absolute;width:1px;height:1px;overflow:hidden;">
<div id="fx-queue" name="test">
<div id="fadein" class='chain test' name='div'>fadeIn<div>fadeIn</div></div>
<div id="fadeout" class='chain test out'>fadeOut<div>fadeOut</div></div>
<div id="show" class='chain test'>show<div>show</div></div>
<div id="hide" class='chain test out'>hide<div>hide</div></div>
<div id="togglein" class='chain test'>togglein<div>togglein</div></div>
<div id="toggleout" class='chain test out'>toggleout<div>toggleout</div></div>
<div id="slideup" class='chain test'>slideUp<div>slideUp</div></div>
<div id="slidedown" class='chain test out'>slideDown<div>slideDown</div></div>
<div id="slidetogglein" class='chain test'>slideToggleIn<div>slideToggleIn</div></div>
<div id="slidetoggleout" class='chain test out'>slideToggleOut<div>slideToggleOut</div></div>
<div id="fadetogglein" class='chain test'>fadeToggleIn<div>fadeToggleIn</div></div>
<div id="fadetoggleout" class='chain test out'>fadeToggleOut<div>fadeToggleOut</div></div>
<div id="fadeto" class='chain test'>fadeTo<div>fadeTo</div></div>
</div>
<div id="fx-tests"></div>
</div>
<map name="imgmap" id="imgmap">
<area shape="rect" coords="0,0,200,50">
</map>
</body>
</html>
|
fsjohnhuang/iPromise
|
theory/jQuery.deferred/1.8/jquery-1.8.0/test/index.html
|
HTML
|
mit
| 12,987
|
#!/bin/bash
set -v
function log() {
echo -e "\033[0;33m[INFO] "$@"\033[0m"
}
function logError() {
echo -e 1>&2 "\033[0;31m"$@"\033[0m"
any_errors=1
}
function die() {
logError "$@"
exit 1
}
export -f log
export -f die
if [ -z ${DUB} ]; then
die 'Error: Variable $DUB must be defined to run the tests.'
fi
if [ -z ${DC} ]; then
log '$DC not defined, assuming dmd...'
DC=dmd
fi
CURR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
for script in $(ls $CURR_DIR/*.sh); do
if [ "$script" = "$(readlink -f ${BASH_SOURCE[0]})" ]; then continue; fi
if [ -e $script.min_frontend ] && [ ! -z "$FRONTEND" -a "$FRONTEND" \< $(cat $script.min_frontend) ]; then continue; fi
log "Running $script..."
DUB=$DUB DC=$DC CURR_DIR="$CURR_DIR" $script || logError "Script failure."
done
for pack in $(ls -d $CURR_DIR/*/); do
if [ -e $pack/.min_frontend ] && [ ! -z "$FRONTEND" -a "$FRONTEND" \< $(cat $pack/.min_frontend) ]; then continue; fi
# First we build the packages
if [ ! -e $pack/.no_build ]; then # For sourceLibrary
if [ -e $pack/.fail_build ]; then
log "Building $pack, expected failure..."
$DUB build --force --root=$pack --compiler=$DC 2>/dev/null && logError "Error: Failure expected, but build passed."
else
log "Building $pack..."
$DUB build --force --root=$pack --compiler=$DC || logError "Build failure."
fi
fi
# We run the ones that are supposed to be runned
if [ ! -e $pack/.no_build ] && [ ! -e $pack/.no_run ]; then
log "Running $pack..."
$DUB run --force --root=$pack --compiler=$DC || logError "Run failure."
fi
# Finally, the unittest part
if [ ! -e $pack/.no_build ] && [ ! -e $pack/.no_test ]; then
log "Testing $pack..."
$DUB test --force --root=$pack --compiler=$DC || logError "Test failure."
fi
done
exit $any_errors
|
p0nce/dub
|
test/run-unittest.sh
|
Shell
|
mit
| 1,936
|
<?php
function smarty_function_styleoption($params, &$smarty)
{
$name = $params['name'];
$value = $params['value'];
if (isset($value))
return "$name: $value; ";
else
return '';
}
?>
|
Kenovix/san-miguel
|
web/contabilidad/admin/libs/smartylibs/plugins/function.styleoption.php
|
PHP
|
mit
| 224
|
<?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\PayumBundle\Payum\Request;
use Payum\Core\Request\BaseStatusRequest;
use Sylius\Bundle\PaymentsBundle\Model\PaymentInterface;
class StatusRequest extends BaseStatusRequest
{
/**
* {@inheritdoc}
*/
public function markNew()
{
$this->status = PaymentInterface::STATE_NEW;
}
/**
* {@inheritdoc}
*/
public function isNew()
{
return $this->status === PaymentInterface::STATE_NEW;
}
/**
* {@inheritdoc}
*/
public function markSuccess()
{
$this->status = PaymentInterface::STATE_COMPLETED;
}
/**
* {@inheritdoc}
*/
public function isSuccess()
{
return $this->status === PaymentInterface::STATE_COMPLETED;
}
/**
* {@inheritdoc}
*/
public function markSuspended()
{
$this->status = PaymentInterface::STATE_PROCESSING;
}
/**
* {@inheritdoc}
*/
public function isSuspended()
{
return $this->status === PaymentInterface::STATE_PROCESSING;
}
/**
* {@inheritdoc}
*/
public function markExpired()
{
$this->status = PaymentInterface::STATE_FAILED;
}
/**
* {@inheritdoc}
*/
public function isExpired()
{
return $this->status === PaymentInterface::STATE_FAILED;
}
/**
* {@inheritdoc}
*/
public function markCanceled()
{
$this->status = PaymentInterface::STATE_CANCELLED;
}
/**
* {@inheritdoc}
*/
public function isCanceled()
{
return $this->status === PaymentInterface::STATE_CANCELLED;
}
/**
* {@inheritdoc}
*/
public function markPending()
{
$this->status = PaymentInterface::STATE_PROCESSING;
}
/**
* {@inheritdoc}
*/
public function isPending()
{
return $this->status === PaymentInterface::STATE_PROCESSING;
}
/**
* {@inheritdoc}
*/
public function markFailed()
{
$this->status = PaymentInterface::STATE_FAILED;
}
/**
* {@inheritdoc}
*/
public function isFailed()
{
return $this->status === PaymentInterface::STATE_FAILED;
}
/**
* {@inheritdoc}
*/
public function markUnknown()
{
$this->status = PaymentInterface::STATE_UNKNOWN;
}
/**
* {@inheritdoc}
*/
public function isUnknown()
{
return $this->status === PaymentInterface::STATE_UNKNOWN;
}
}
|
chuandadexiaoyu/UniversitySylius
|
src/Sylius/Bundle/PayumBundle/Payum/Request/StatusRequest.php
|
PHP
|
mit
| 2,730
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_07) on Tue May 28 14:16:24 BST 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface org.neo4j.kernel.GraphDatabaseAPI (Neo4j Community 2.0.0-M03 API)</title>
<meta name="date" content="2013-05-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.neo4j.kernel.GraphDatabaseAPI (Neo4j Community 2.0.0-M03 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em>Neo4j Community</em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/neo4j/kernel/class-use/GraphDatabaseAPI.html" target="_top">Frames</a></li>
<li><a href="GraphDatabaseAPI.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.neo4j.kernel.GraphDatabaseAPI" class="title">Uses of Interface<br>org.neo4j.kernel.GraphDatabaseAPI</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">GraphDatabaseAPI</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.neo4j.jmx">org.neo4j.jmx</a></td>
<td class="colLast">
<div class="block">Management support using JMX.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.neo4j.kernel">org.neo4j.kernel</a></td>
<td class="colLast">
<div class="block">Implementation for embedding a Neo4j graph database in an application.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.neo4j.jmx">
<!-- -->
</a>
<h3>Uses of <a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">GraphDatabaseAPI</a> in <a href="../../../../org/neo4j/jmx/package-summary.html">org.neo4j.jmx</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../org/neo4j/jmx/package-summary.html">org.neo4j.jmx</a> with parameters of type <a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">GraphDatabaseAPI</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="http://docs.oracle.com/javase/6/docs/api/javax/management/ObjectName.html?is-external=true" title="class or interface in javax.management">ObjectName</a></code></td>
<td class="colLast"><span class="strong">JmxUtils.</span><code><strong><a href="../../../../org/neo4j/jmx/JmxUtils.html#getObjectName(org.neo4j.kernel.GraphDatabaseAPI, java.lang.String)">getObjectName</a></strong>(<a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">GraphDatabaseAPI</a> database,
<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.neo4j.kernel">
<!-- -->
</a>
<h3>Uses of <a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">GraphDatabaseAPI</a> in <a href="../../../../org/neo4j/kernel/package-summary.html">org.neo4j.kernel</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/neo4j/kernel/package-summary.html">org.neo4j.kernel</a> that implement <a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">GraphDatabaseAPI</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../org/neo4j/kernel/AbstractGraphDatabase.html" title="class in org.neo4j.kernel">AbstractGraphDatabase</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../org/neo4j/kernel/EmbeddedGraphDatabase.html" title="class in org.neo4j.kernel">EmbeddedGraphDatabase</a></strong></code>
<div class="block">An implementation of <a href="../../../../org/neo4j/graphdb/GraphDatabaseService.html" title="interface in org.neo4j.graphdb"><code>GraphDatabaseService</code></a> that is used to embed Neo4j
in an application.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../org/neo4j/kernel/EmbeddedReadOnlyGraphDatabase.html" title="class in org.neo4j.kernel">EmbeddedReadOnlyGraphDatabase</a></strong></code>
<div class="block">A read-only version of <a href="../../../../org/neo4j/kernel/EmbeddedGraphDatabase.html" title="class in org.neo4j.kernel"><code>EmbeddedGraphDatabase</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../org/neo4j/kernel/InternalAbstractGraphDatabase.html" title="class in org.neo4j.kernel">InternalAbstractGraphDatabase</a></strong></code>
<div class="block">Base implementation of GraphDatabaseService.</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../org/neo4j/kernel/package-summary.html">org.neo4j.kernel</a> that return <a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">GraphDatabaseAPI</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">GraphDatabaseAPI</a></code></td>
<td class="colLast"><span class="strong">KernelData.</span><code><strong><a href="../../../../org/neo4j/kernel/KernelData.html#graphDatabase()">graphDatabase</a></strong>()</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/neo4j/kernel/GraphDatabaseAPI.html" title="interface in org.neo4j.kernel">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em>Neo4j Community</em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/neo4j/kernel/class-use/GraphDatabaseAPI.html" target="_top">Frames</a></li>
<li><a href="GraphDatabaseAPI.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2002-2013 <a href="http://neo4j.org/">The Neo4j Graph Database Project</a>. All Rights Reserved.</small></p>
</body>
</html>
|
LeArNalytics/LeArNalytics
|
neo4j/neo4j-community-2.0.0-M03/doc/java/api/org/neo4j/kernel/class-use/GraphDatabaseAPI.html
|
HTML
|
mit
| 10,383
|
/*!
* jQuery JavaScript Library v2.0.1 -sizzle,-css,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-27T00:57Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "2.0.1 -sizzle,-css,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: Date.now,
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*
* Optional (non-Sizzle) selector module for custom builds.
*
* Note that this DOES NOT SUPPORT many documented jQuery
* features in exchange for its smaller size:
*
* Attribute not equal selector
* Positional selectors (:first; :eq(n); :odd; etc.)
* Type selectors (:input; :checkbox; :button; etc.)
* State-based selectors (:animated; :visible; :hidden; etc.)
* :has(selector)
* :not(complex selector)
* custom selectors via Sizzle extensions
* Leading combinators (e.g., $collection.find("> *"))
* Reliable functionality on XML fragments
* Requiring all parts of a selector to match elements under context
* (e.g., $div.find("div > *") now matches children of $div)
* Matching against non-elements
* Reliable sorting of disconnected nodes
* querySelectorAll bug fixes (e.g., unreliable :focus on WebKit)
*
* If any of these are unacceptable tradeoffs, either use Sizzle or
* customize this stub for the project's specific needs.
*/
var selector_hasDuplicate,
matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector,
selector_sortOrder = function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
selector_hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ) {
// Choose the first element that is related to our document
if ( a === document || jQuery.contains(document, a) ) {
return -1;
}
if ( b === document || jQuery.contains(document, b) ) {
return 1;
}
// Maintain original order
return 0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
};
jQuery.extend({
find: function( selector, context, results, seed ) {
var elem, nodeType,
i = 0;
results = results || [];
context = context || document;
// Same basic safeguard as Sizzle
if ( !selector || typeof selector !== "string" ) {
return results;
}
// Early return if context is not an element or document
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( seed ) {
while ( (elem = seed[i++]) ) {
if ( jQuery.find.matchesSelector(elem, selector) ) {
results.push( elem );
}
}
} else {
jQuery.merge( results, context.querySelectorAll(selector) );
}
return results;
},
unique: function( results ) {
var elem,
duplicates = [],
i = 0,
j = 0;
selector_hasDuplicate = false;
results.sort( selector_sortOrder );
if ( selector_hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
},
text: function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += jQuery.text( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
return elem.textContent;
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
},
contains: function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) );
},
isXMLDoc: function( elem ) {
return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML";
},
expr: {
attrHandle: {},
match: {
bool: /^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i,
needsContext: /^[\x20\t\r\n\f]*[>+~]/
}
}
});
jQuery.extend( jQuery.find, {
matches: function( expr, elements ) {
return jQuery.find( expr, null, null, elements );
},
matchesSelector: function( elem, expr ) {
return matches.call( elem, expr );
},
attr: function( elem, name ) {
return elem.getAttribute( name );
}
});
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var input = document.createElement("input"),
fragment = document.createDocumentFragment(),
div = document.createElement("div"),
select = document.createElement("select"),
opt = select.appendChild( document.createElement("option") );
// Finish early in limited environments
if ( !input.type ) {
return support;
}
input.type = "checkbox";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Will be defined later
support.reliableMarginRight = true;
support.boxSizingReliable = true;
support.pixelPosition = false;
// Make sure checked status is properly cloned
// Support: IE9, IE10
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement("input");
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment.appendChild( input );
// Support: Safari 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: Firefox, Chrome, Safari
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
support.focusinBubbles = "onfocusin" in window;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv,
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",
body = document.getElementsByTagName("body")[ 0 ];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
// Check box-sizing and margin behavior.
body.appendChild( container ).appendChild( div );
div.innerHTML = "";
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
body.removeChild( container );
});
return support;
})( {} );
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var data_user, data_priv,
rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType ?
owner.nodeType === 1 || owner.nodeType === 9 : true;
};
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
return this.get( owner, key );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( core_rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
// These may be used throughout the jQuery core codebase
data_user = new Data();
data_priv = new Data();
jQuery.extend({
acceptData: Data.accepts,
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[ 0 ],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return jQuery.access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? JSON.parse( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
// Temporarily disable this handler to check existence
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
// Restore handler
jQuery.expr.attrHandle[ name ] = fn;
return ret;
};
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return core_indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return core_indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because core_push.apply(_, arraylike) throws
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
i = 0,
l = elems.length,
fragment = context.createDocumentFragment(),
nodes = [];
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.firstChild;
}
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, events, type, key, j,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( Data.accepts( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
events = Object.keys( data.events || {} );
if ( events.length ) {
for ( j = 0; (type = events[j]) !== undefined; j++ ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var l = elems.length,
i = 0;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Limit scope pollution from any deprecated API
// (function() {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
// If there is a window object, that at least has a document property,
// define jQuery and $ identifiers
if ( typeof window === "object" && typeof window.document === "object" ) {
window.jQuery = window.$ = jQuery;
}
})( window );
|
michael829/jquery-builder
|
dist/2.0.1/jquery-ajax-css-event-alias-sizzle.js
|
JavaScript
|
mit
| 117,313
|
'use strict';
describe('Loading 0202-layers-overlays-simple-example.html', function() {
beforeEach(function() {
browser.get('0202-layers-overlays-simple-example.html');
browser.wait(function() {
return element(by.css('img.leaflet-tile-loaded')).isPresent();
}, 5000);
});
it('should change the layer tiles if clicked on the leaflet control switch layer', function() {
expect(element(by.xpath('//img[contains(@src, "http://c.tile.openstreetmap.org/")]')).isPresent()).toBe(true);
browser.actions().mouseMove(element(by.xpath('//a[contains(@class, "leaflet-control-layers-toggle")][1]'))).perform();
browser.wait(function() {
return element(by.xpath('//img[contains(@src, "http://suite.opengeo.org/geoserver/usa/wms")]')).isPresent();
}, 5000);
expect(element(by.xpath('//img[contains(@src, "http://suite.opengeo.org/geoserver/usa/wms")]')).isPresent()).toBe(true);
var overlayButton = element(by.xpath('//input[@type=\'checkbox\'][1]'));
overlayButton.click();
browser.driver.sleep(300);
expect(element(by.xpath('//img[contains(@src, "http://suite.opengeo.org/geoserver/usa/wms")]')).isPresent()).toBe(false);
});
});
|
abdelrahmansaeedhassan/FirstTest
|
test/e2e/0202-layers-overlays-simple-example.js
|
JavaScript
|
mit
| 1,191
|
/*
Ractive.js v1.3.0-edge
Build: 3c34b67ed6ee7e3072fccc80bb50bfb9ef90f3bd
Date: Fri Jan 04 2019 18:04:51 GMT+0000 (UTC)
Website: https://ractive.js.org
License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(function() {
var current = global.Ractive;
var exports = factory();
global.Ractive = exports;
exports.noConflict = function() { global.Ractive = current; return exports; };
})();
}(this, (function () { 'use strict';
/* istanbul ignore if */
if (!Object.assign) {
Object.assign = function(target) {
var sources = [], len = arguments.length - 1;
while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
if (target == null) { throw new TypeError('Cannot convert undefined or null to object'); }
var to = Object(target);
var sourcesLength = sources.length;
for (var index = 0; index < sourcesLength; index++) {
var nextSource = sources[index];
for (var nextKey in nextSource) {
if (!Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { continue; }
to[nextKey] = nextSource[nextKey];
}
}
return to;
};
}
function hasOwn(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
function fillGaps(target) {
var sources = [], len = arguments.length - 1;
while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
for (var i = 0; i < sources.length; i++) {
var source = sources[i];
for (var key in source) {
// Source can be a prototype-less object.
if (key in target || !hasOwn(source, key)) { continue; }
target[key] = source[key];
}
}
return target;
}
function toPairs(obj) {
if ( obj === void 0 ) obj = {};
var pairs = [];
for (var key in obj) {
// Source can be a prototype-less object.
if (!hasOwn(obj, key)) { continue; }
pairs.push([key, obj[key]]);
}
return pairs;
}
var obj = Object;
var assign = obj.assign;
var create = obj.create;
var defineProperty = obj.defineProperty;
var defineProperties = obj.defineProperties;
var keys = obj.keys;
var toString = Object.prototype.toString;
var isArray = Array.isArray;
function isEqual(a, b) {
if (a === null && b === null) {
return true;
}
if (isObjectType(a) || isObjectType(b)) {
return false;
}
return a === b;
}
// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function isNumeric(thing) {
return !isNaN(parseFloat(thing)) && isFinite(thing);
}
function isObject(thing) {
return thing && toString.call(thing) === '[object Object]';
}
function isObjectLike(thing) {
return !!(thing && (isObjectType(thing) || isFunction(thing)));
}
function isObjectType(thing) {
return typeof thing === 'object';
}
function isFunction(thing) {
return typeof thing === 'function';
}
function isString(thing) {
return typeof thing === 'string';
}
function isNumber(thing) {
return typeof thing === 'number';
}
/* istanbul ignore if */
if (!Array.prototype.find) {
defineProperty(Array.prototype, 'find', {
value: function value(callback, thisArg) {
if (this === null || this === undefined)
{ throw new TypeError('Array.prototype.find called on null or undefined'); }
if (!isFunction(callback)) { throw new TypeError((callback + " is not a function")); }
var array = Object(this);
var arrayLength = array.length >>> 0;
for (var index = 0; index < arrayLength; index++) {
if (!hasOwn(array, index)) { continue; }
if (!callback.call(thisArg, array[index], index, array)) { continue; }
return array[index];
}
return undefined;
},
configurable: true,
writable: true
});
}
// NOTE: Node doesn't exist in IE8. Nothing can be done.
/* istanbul ignore if */
if (
typeof window !== 'undefined' &&
window.Node &&
window.Node.prototype &&
!window.Node.prototype.contains
) {
Node.prototype.contains = function(node) {
var this$1 = this;
if (!node) { throw new TypeError('node required'); }
do {
if (this$1 === node) { return true; }
} while ((node = node && node.parentNode));
return false;
};
}
/* istanbul ignore if */
if (typeof window !== 'undefined' && window.performance && !window.performance.now) {
window.performance = window.performance || {};
var nowOffset = Date.now();
window.performance.now = function() {
return Date.now() - nowOffset;
};
}
/* eslint no-console:"off" */
var win = typeof window !== 'undefined' ? window : null;
var doc = win ? document : null;
var isClient = !!doc;
var base = typeof global !== 'undefined' ? global : win;
var hasConsole =
typeof console !== 'undefined' && isFunction(console.warn) && isFunction(console.warn.apply);
var svg = doc
? doc.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1')
: false;
var vendors = ['o', 'ms', 'moz', 'webkit'];
/* istanbul ignore if */
if (!base.Promise) {
var PENDING = {};
var FULFILLED = {};
var REJECTED = {};
var Promise$1 = (base.Promise = function(callback) {
var fulfilledHandlers = [];
var rejectedHandlers = [];
var state = PENDING;
var result;
var dispatchHandlers;
var makeResolver = function (newState) {
return function(value) {
if (state !== PENDING) { return; }
result = value;
state = newState;
dispatchHandlers = makeDispatcher(
state === FULFILLED ? fulfilledHandlers : rejectedHandlers,
result
);
wait(dispatchHandlers);
};
};
var fulfill = makeResolver(FULFILLED);
var reject = makeResolver(REJECTED);
try {
callback(fulfill, reject);
} catch (err) {
reject(err);
}
return {
// `then()` returns a Promise - 2.2.7
then: function then(onFulfilled, onRejected) {
var promise2 = new Promise$1(function (fulfill, reject) {
var processResolutionHandler = function (handler, handlers, forward) {
if (isFunction(handler)) {
handlers.push(function (p1result) {
try {
resolve$1(promise2, handler(p1result), fulfill, reject);
} catch (err) {
reject(err);
}
});
} else {
handlers.push(forward);
}
};
processResolutionHandler(onFulfilled, fulfilledHandlers, fulfill);
processResolutionHandler(onRejected, rejectedHandlers, reject);
if (state !== PENDING) {
wait(dispatchHandlers);
}
});
return promise2;
},
catch: function catch$1(onRejected) {
return this.then(null, onRejected);
},
finally: function finally$1(callback) {
return this.then(
function (v) {
callback();
return v;
},
function (e) {
callback();
throw e;
}
);
}
};
});
Promise$1.all = function(promises) {
return new Promise$1(function (fulfill, reject) {
var result = [];
var pending;
var i;
if (!promises.length) {
fulfill(result);
return;
}
var processPromise = function (promise, i) {
if (promise && isFunction(promise.then)) {
promise.then(function (value) {
result[i] = value;
--pending || fulfill(result);
}, reject);
} else {
result[i] = promise;
--pending || fulfill(result);
}
};
pending = i = promises.length;
while (i--) {
processPromise(promises[i], i);
}
});
};
Promise$1.race = function(promises) {
return new Promise$1(function (fulfill, reject) {
var pending = true;
function ok(v) {
if (!pending) { return; }
pending = false;
fulfill(v);
}
function fail(e) {
if (!pending) { return; }
pending = false;
reject(e);
}
for (var i = 0; i < promises.length; i++) {
if (promises[i] && isFunction(promises[i].then)) {
promises[i].then(ok, fail);
}
}
});
};
Promise$1.resolve = function(value) {
if (value && isFunction(value.then)) { return value; }
return new Promise$1(function (fulfill) {
fulfill(value);
});
};
Promise$1.reject = function(reason) {
if (reason && isFunction(reason.then)) { return reason; }
return new Promise$1(function (fulfill, reject) {
reject(reason);
});
};
// TODO use MutationObservers or something to simulate setImmediate
var wait = function(callback) {
setTimeout(callback, 0);
};
var makeDispatcher = function(handlers, result) {
return function() {
for (var handler = (void 0); (handler = handlers.shift()); ) {
handler(result);
}
};
};
var resolve$1 = function(promise, x, fulfil, reject) {
var then;
if (x === promise) {
throw new TypeError("A promise's fulfillment handler cannot return the same promise");
}
if (x instanceof Promise$1) {
x.then(fulfil, reject);
} else if (x && (isObjectType(x) || isFunction(x))) {
try {
then = x.then;
} catch (e) {
reject(e);
return;
}
if (isFunction(then)) {
var called;
var resolvePromise = function(y) {
if (called) { return; }
called = true;
resolve$1(promise, y, fulfil, reject);
};
var rejectPromise = function(r) {
if (called) { return; }
called = true;
reject(r);
};
try {
then.call(x, resolvePromise, rejectPromise);
} catch (e) {
if (!called) {
reject(e);
called = true;
return;
}
}
} else {
fulfil(x);
}
} else {
fulfil(x);
}
};
}
/* istanbul ignore if */
if (
typeof window !== 'undefined' &&
!(window.requestAnimationFrame && window.cancelAnimationFrame)
) {
var lastTime = 0;
window.requestAnimationFrame = function(callback) {
var currentTime = Date.now();
var timeToNextCall = Math.max(0, 16 - (currentTime - lastTime));
var id = window.setTimeout(function () {
callback(currentTime + timeToNextCall);
}, timeToNextCall);
lastTime = currentTime + timeToNextCall;
return id;
};
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
var defaults = {
// render placement:
el: void 0,
append: false,
delegate: true,
enhance: false,
// template:
template: null,
// parse:
allowExpressions: true,
delimiters: ['{{', '}}'],
tripleDelimiters: ['{{{', '}}}'],
staticDelimiters: ['[[', ']]'],
staticTripleDelimiters: ['[[[', ']]]'],
csp: true,
interpolate: false,
preserveWhitespace: false,
sanitize: false,
stripComments: true,
contextLines: 0,
// data & binding:
data: create(null),
helpers: create(null),
computed: create(null),
syncComputedChildren: false,
resolveInstanceMembers: false,
warnAboutAmbiguity: false,
adapt: [],
isolated: true,
twoway: true,
lazy: false,
// transitions:
noIntro: false,
noOutro: false,
transitionsEnabled: true,
complete: void 0,
nestedTransitions: true,
// css:
css: null,
noCSSTransform: false
};
// These are a subset of the easing equations found at
// https://raw.github.com/danro/easing-js - license info
// follows:
// --------------------------------------------------
// easing.js v0.5.4
// Generic set of easing functions with AMD support
// https://github.com/danro/easing-js
// This code may be freely distributed under the MIT license
// http://danro.mit-license.org/
// --------------------------------------------------
// All functions adapted from Thomas Fuchs & Jeremy Kahn
// Easing Equations (c) 2003 Robert Penner, BSD license
// https://raw.github.com/danro/easing-js/master/LICENSE
// --------------------------------------------------
// In that library, the functions named easeIn, easeOut, and
// easeInOut below are named easeInCubic, easeOutCubic, and
// (you guessed it) easeInOutCubic.
//
// You can add additional easing functions to this list, and they
// will be globally available.
var easing = {
linear: function linear(pos) {
return pos;
},
easeIn: function easeIn(pos) {
/* istanbul ignore next */
return Math.pow(pos, 3);
},
easeOut: function easeOut(pos) {
return Math.pow(pos - 1, 3) + 1;
},
easeInOut: function easeInOut(pos) {
/* istanbul ignore next */
if ((pos /= 0.5) < 1) {
return 0.5 * Math.pow(pos, 3);
}
/* istanbul ignore next */
return 0.5 * (Math.pow(pos - 2, 3) + 2);
}
};
function noop() {}
/* global console */
/* eslint no-console:"off" */
var alreadyWarned = {};
var log;
var printWarning;
var welcome;
if (hasConsole) {
var welcomeIntro = [
"%cRactive.js %c1.3.0-edge %cin debug mode, %cmore...",
'color: rgb(114, 157, 52); font-weight: normal;',
'color: rgb(85, 85, 85); font-weight: normal;',
'color: rgb(85, 85, 85); font-weight: normal;',
'color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;'
];
var welcomeMessage = "You're running Ractive 1.3.0-edge in debug mode - messages will be printed to the console to help you fix problems and optimise your application.\n\nTo disable debug mode, add this line at the start of your app:\n Ractive.DEBUG = false;\n\nTo disable debug mode when your app is minified, add this snippet:\n Ractive.DEBUG = /unminified/.test(function(){/*unminified*/});\n\nGet help and support:\n http://ractive.js.org\n http://stackoverflow.com/questions/tagged/ractivejs\n http://groups.google.com/forum/#!forum/ractive-js\n http://twitter.com/ractivejs\n\nFound a bug? Raise an issue:\n https://github.com/ractivejs/ractive/issues\n\n";
welcome = function () {
if (Ractive.WELCOME_MESSAGE === false) {
welcome = noop;
return;
}
var message = 'WELCOME_MESSAGE' in Ractive ? Ractive.WELCOME_MESSAGE : welcomeMessage;
var hasGroup = !!console.groupCollapsed;
if (hasGroup) { console.groupCollapsed.apply(console, welcomeIntro); }
console.log(message);
if (hasGroup) {
console.groupEnd(welcomeIntro);
}
welcome = noop;
};
printWarning = function (message, args) {
welcome();
// extract information about the instance this message pertains to, if applicable
if (isObjectType(args[args.length - 1])) {
var options = args.pop();
var ractive = options ? options.ractive : null;
if (ractive) {
// if this is an instance of a component that we know the name of, add
// it to the message
var name;
if (ractive.component && (name = ractive.component.name)) {
message = "<" + name + "> " + message;
}
var node;
if (
(node =
options.node || (ractive.fragment && ractive.fragment.rendered && ractive.find('*')))
) {
args.push(node);
}
}
}
console.warn.apply(
console,
['%cRactive.js: %c' + message, 'color: rgb(114, 157, 52);', 'color: rgb(85, 85, 85);'].concat(
args
)
);
};
log = function() {
console.log.apply(console, arguments);
};
} else {
printWarning = log = welcome = noop;
}
function format(message, args) {
return message.replace(/%s/g, function () { return args.shift(); });
}
function fatal(message) {
var args = [], len = arguments.length - 1;
while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
message = format(message, args);
throw new Error(message);
}
function logIfDebug() {
if (Ractive.DEBUG) {
log.apply(null, arguments);
}
}
function warn(message) {
var args = [], len = arguments.length - 1;
while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
message = format(message, args);
printWarning(message, args);
}
function warnOnce(message) {
var args = [], len = arguments.length - 1;
while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
message = format(message, args);
if (alreadyWarned[message]) {
return;
}
alreadyWarned[message] = true;
printWarning(message, args);
}
function warnIfDebug() {
if (Ractive.DEBUG) {
warn.apply(null, arguments);
}
}
function warnOnceIfDebug() {
if (Ractive.DEBUG) {
warnOnce.apply(null, arguments);
}
}
// Error messages that are used (or could be) in multiple places
var badArguments = 'Bad arguments';
var noRegistryFunctionReturn =
'A function was specified for "%s" %s, but no %s was returned';
var missingPlugin = function (name, type) { return ("Missing \"" + name + "\" " + type + " plugin. You may need to download a plugin via http://ractive.js.org/integrations/#" + type + "s"); };
function findInViewHierarchy(registryName, ractive, name) {
var instance = findInstance(registryName, ractive, name);
return instance ? instance[registryName][name] : null;
}
function findInstance(registryName, ractive, name) {
while (ractive) {
if (name in ractive[registryName]) {
return ractive;
}
if (ractive.isolated) {
return null;
}
ractive = ractive.parent;
}
}
function interpolate(from, to, ractive, type) {
if (from === to) { return null; }
if (type) {
var interpol = findInViewHierarchy('interpolators', ractive, type);
if (interpol) { return interpol(from, to) || null; }
fatal(missingPlugin(type, 'interpolator'));
}
return (
interpolators.number(from, to) ||
interpolators.array(from, to) ||
interpolators.object(from, to) ||
null
);
}
var interpolators = {
number: function number(from, to) {
if (!isNumeric(from) || !isNumeric(to)) {
return null;
}
from = +from;
to = +to;
var delta = to - from;
if (!delta) {
return function() {
return from;
};
}
return function(t) {
return from + t * delta;
};
},
array: function array(from, to) {
var len, i;
if (!isArray(from) || !isArray(to)) {
return null;
}
var intermediate = [];
var interpolators = [];
i = len = Math.min(from.length, to.length);
while (i--) {
interpolators[i] = interpolate(from[i], to[i]);
}
// surplus values - don't interpolate, but don't exclude them either
for (i = len; i < from.length; i += 1) {
intermediate[i] = from[i];
}
for (i = len; i < to.length; i += 1) {
intermediate[i] = to[i];
}
return function(t) {
var i = len;
while (i--) {
intermediate[i] = interpolators[i](t);
}
return intermediate;
};
},
object: function object(from, to) {
if (!isObject(from) || !isObject(to)) {
return null;
}
var properties = [];
var intermediate = {};
var interpolators = {};
var loop = function ( prop ) {
if (hasOwn(from, prop)) {
if (hasOwn(to, prop)) {
properties.push(prop);
interpolators[prop] = interpolate(from[prop], to[prop]) || (function () { return to[prop]; });
} else {
intermediate[prop] = from[prop];
}
}
};
for (var prop in from) loop( prop );
for (var prop$1 in to) {
if (hasOwn(to, prop$1) && !hasOwn(from, prop$1)) {
intermediate[prop$1] = to[prop$1];
}
}
var len = properties.length;
return function(t) {
var i = len;
while (i--) {
var prop = properties[i];
intermediate[prop] = interpolators[prop](t);
}
return intermediate;
};
}
};
var refPattern = /\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g;
var splitPattern = /([^\\](?:\\\\)*)\./;
var escapeKeyPattern = /\\|\./g;
var unescapeKeyPattern = /((?:\\)+)\1|\\(\.)/g;
function escapeKey(key) {
if (isString(key)) {
return key.replace(escapeKeyPattern, '\\$&');
}
return key;
}
function normalise(ref) {
return ref ? ref.replace(refPattern, '.$1') : '';
}
function splitKeypath(keypath) {
var result = [];
var match;
keypath = normalise(keypath);
while ((match = splitPattern.exec(keypath))) {
var index = match.index + match[1].length;
result.push(keypath.substr(0, index));
keypath = keypath.substr(index + 1);
}
result.push(keypath);
return result;
}
function unescapeKey(key) {
if (isString(key)) {
return key.replace(unescapeKeyPattern, '$1$2');
}
return key;
}
function addToArray(array, value) {
var index = array.indexOf(value);
if (index === -1) {
array.push(value);
}
}
function arrayContains(array, value) {
for (var i = 0, c = array.length; i < c; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
function arrayContentsMatch(a, b) {
var i;
if (!isArray(a) || !isArray(b)) {
return false;
}
if (a.length !== b.length) {
return false;
}
i = a.length;
while (i--) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function ensureArray(x) {
if (isString(x)) {
return [x];
}
if (x === undefined) {
return [];
}
return x;
}
function lastItem(array) {
return array[array.length - 1];
}
function removeFromArray(array, member) {
if (!array) {
return;
}
var index = array.indexOf(member);
if (index !== -1) {
array.splice(index, 1);
}
}
function combine() {
var arrays = [], len = arguments.length;
while ( len-- ) arrays[ len ] = arguments[ len ];
var res = arrays.concat.apply([], arrays);
var i = res.length;
while (i--) {
var idx = res.indexOf(res[i]);
if (~idx && idx < i) { res.splice(i, 1); }
}
return res;
}
function toArray(arrayLike) {
var array = [];
var i = arrayLike.length;
while (i--) {
array[i] = arrayLike[i];
}
return array;
}
function findMap(array, fn) {
var len = array.length;
for (var i = 0; i < len; i++) {
var result = fn(array[i]);
if (result) { return result; }
}
}
function buildNewIndices(one, two, comparator) {
var oldArray = one;
var newArray = two;
if (comparator) {
oldArray = oldArray.map(comparator);
newArray = newArray.map(comparator);
}
var oldLength = oldArray.length;
var usedIndices = {};
var firstUnusedIndex = 0;
return oldArray.map(function (item) {
var index;
var start = firstUnusedIndex;
do {
index = newArray.indexOf(item, start);
if (index === -1) {
return -1;
}
start = index + 1;
} while (usedIndices[index] === true && start < oldLength);
// keep track of the first unused index, so we don't search
// the whole of newArray for each item in oldArray unnecessarily
if (index === firstUnusedIndex) {
firstUnusedIndex += 1;
}
// allow next instance of next "equal" to be found item
usedIndices[index] = true;
return index;
});
}
var fnBind = Function.prototype.bind;
function bind(fn, context) {
if (!/this/.test(fn.toString())) { return fn; }
var bound = fnBind.call(fn, context);
for (var prop in fn) { bound[prop] = fn[prop]; }
return bound;
}
var shuffleTasks = { early: [], mark: [] };
var registerQueue = { early: [], mark: [] };
var noVirtual = { virtual: false };
var ModelBase = function ModelBase(parent) {
this.deps = [];
this.children = [];
this.childByKey = {};
this.links = [];
this.bindings = [];
if (parent) {
this.parent = parent;
this.root = parent.root;
}
};
var ModelBase__proto__ = ModelBase.prototype;
ModelBase__proto__.addShuffleTask = function addShuffleTask (task, stage) {
if ( stage === void 0 ) stage = 'early';
shuffleTasks[stage].push(task);
};
ModelBase__proto__.addShuffleRegister = function addShuffleRegister (item, stage) {
if ( stage === void 0 ) stage = 'early';
registerQueue[stage].push({ model: this, item: item });
};
ModelBase__proto__.downstreamChanged = function downstreamChanged () {};
ModelBase__proto__.findMatches = function findMatches (keys$$1) {
var len = keys$$1.length;
var existingMatches = [this];
var matches;
var i;
var loop = function ( ) {
var key = keys$$1[i];
if (key === '*') {
matches = [];
existingMatches.forEach(function (model) {
matches.push.apply(matches, model.getValueChildren(model.get()));
});
} else {
matches = existingMatches.map(function (model) { return model.joinKey(key); });
}
existingMatches = matches;
};
for (i = 0; i < len; i += 1) loop( );
return matches;
};
ModelBase__proto__.getKeypath = function getKeypath (ractive) {
if (ractive !== this.ractive && this._link) { return this._link.target.getKeypath(ractive); }
if (!this.keypath) {
var parent = this.parent && this.parent.getKeypath(ractive);
this.keypath = parent
? ((this.parent.getKeypath(ractive)) + "." + (escapeKey(this.key)))
: escapeKey(this.key);
}
return this.keypath;
};
ModelBase__proto__.getValueChildren = function getValueChildren (value) {
var this$1 = this;
var children;
if (isArray(value)) {
children = [];
if ('length' in this && this.length !== value.length) {
children.push(this.joinKey('length'));
}
value.forEach(function (m, i) {
children.push(this$1.joinKey(i));
});
} else if (isObject(value) || isFunction(value)) {
children = keys(value).map(function (key) { return this$1.joinKey(key); });
} else if (value != null) {
children = [];
}
var computed = this.computed;
if (computed) {
children.push.apply(children, keys(computed).map(function (k) { return this$1.joinKey(k); }));
}
return children;
};
ModelBase__proto__.getVirtual = function getVirtual (shouldCapture) {
var this$1 = this;
var value = this.get(shouldCapture, { virtual: false });
if (isObject(value)) {
var result = isArray(value) ? [] : create(null);
var keys$$1 = keys(value);
var i = keys$$1.length;
while (i--) {
var child = this$1.childByKey[keys$$1[i]];
if (!child) { result[keys$$1[i]] = value[keys$$1[i]]; }
else if (child._link) { result[keys$$1[i]] = child._link.getVirtual(); }
else { result[keys$$1[i]] = child.getVirtual(); }
}
i = this.children.length;
while (i--) {
var child$1 = this$1.children[i];
if (!(child$1.key in result) && child$1._link) {
result[child$1.key] = child$1._link.getVirtual();
}
}
if (this.computed) {
keys$$1 = keys(this.computed);
i = keys$$1.length;
while (i--) {
result[keys$$1[i]] = this$1.computed[keys$$1[i]].get();
}
}
return result;
} else { return value; }
};
ModelBase__proto__.has = function has (key) {
var this$1 = this;
if (this._link) { return this._link.has(key); }
var value = this.get(false, noVirtual);
if (!value) { return false; }
key = unescapeKey(key);
if ((isFunction(value) || isObject(value)) && key in value) { return true; }
var computed = this.computed;
if (computed && key in this.computed) { return true; }
computed = this.root.ractive && this.root.ractive.computed;
if (computed) {
keys(computed).forEach(function (k) {
if (computed[k].pattern && computed[k].pattern.test(this$1.getKeypath())) { return true; }
});
}
return false;
};
ModelBase__proto__.joinAll = function joinAll (keys$$1, opts) {
var model = this;
for (var i = 0; i < keys$$1.length; i += 1) {
if (
opts &&
opts.lastLink === false &&
i + 1 === keys$$1.length &&
model.childByKey[keys$$1[i]] &&
model.childByKey[keys$$1[i]]._link
)
{ return model.childByKey[keys$$1[i]]; }
model = model.joinKey(keys$$1[i], opts);
}
return model;
};
ModelBase__proto__.notifyUpstream = function notifyUpstream (startPath) {
var this$1 = this;
var parent = this.parent;
var path = startPath || [this.key];
while (parent) {
if (parent.patterns) { parent.patterns.forEach(function (o) { return o.notify(path.slice()); }); }
path.unshift(parent.key);
parent.links.forEach(function (l) { return l.notifiedUpstream(path, this$1.root); });
parent.deps.forEach(function (d) { return d.handleChange(path); });
parent.downstreamChanged(startPath);
parent = parent.parent;
}
};
ModelBase__proto__.rebind = function rebind (next, previous, safe) {
var this$1 = this;
if (this._link) {
this._link.rebind(next, previous, false);
}
// tell the deps to move to the new target
var i = this.deps.length;
while (i--) {
if (this$1.deps[i].rebind) { this$1.deps[i].rebind(next, previous, safe); }
}
i = this.links.length;
while (i--) {
var link = this$1.links[i];
// only relink the root of the link tree
if (link.owner && link.owner._link) { link.relinking(next, safe); }
}
i = this.children.length;
while (i--) {
var child = this$1.children[i];
child.rebind(next ? next.joinKey(child.key) : undefined, child, safe);
}
i = this.bindings.length;
while (i--) {
this$1.bindings[i].rebind(next, previous, safe);
}
};
ModelBase__proto__.reference = function reference () {
'refs' in this ? this.refs++ : (this.refs = 1);
};
ModelBase__proto__.register = function register (dep) {
this.deps.push(dep);
};
ModelBase__proto__.registerLink = function registerLink (link) {
addToArray(this.links, link);
};
ModelBase__proto__.registerPatternObserver = function registerPatternObserver (observer) {
(this.patterns || (this.patterns = [])).push(observer);
this.register(observer);
};
ModelBase__proto__.registerTwowayBinding = function registerTwowayBinding (binding) {
this.bindings.push(binding);
};
ModelBase__proto__.unreference = function unreference () {
if ('refs' in this) { this.refs--; }
};
ModelBase__proto__.unregister = function unregister (dep) {
removeFromArray(this.deps, dep);
};
ModelBase__proto__.unregisterLink = function unregisterLink (link) {
removeFromArray(this.links, link);
};
ModelBase__proto__.unregisterPatternObserver = function unregisterPatternObserver (observer) {
removeFromArray(this.patterns, observer);
this.unregister(observer);
};
ModelBase__proto__.unregisterTwowayBinding = function unregisterTwowayBinding (binding) {
removeFromArray(this.bindings, binding);
};
ModelBase__proto__.updateFromBindings = function updateFromBindings$1 (cascade) {
var this$1 = this;
var i = this.bindings.length;
while (i--) {
var value = this$1.bindings[i].getValue();
if (value !== this$1.value) { this$1.set(value); }
}
// check for one-way bindings if there are no two-ways
if (!this.bindings.length) {
var oneway = findBoundValue(this.deps);
if (oneway && oneway.value !== this.value) { this.set(oneway.value); }
}
if (cascade) {
this.children.forEach(updateFromBindings);
this.links.forEach(updateFromBindings);
if (this._link) { this._link.updateFromBindings(cascade); }
}
};
// TODO: this may be better handled by overriding `get` on models with a parent that isRoot
function maybeBind(model, value, shouldBind) {
if (shouldBind && isFunction(value) && model.parent && model.parent.isRoot) {
if (!model.boundValue) {
model.boundValue = bind(value._r_unbound || value, model.parent.ractive);
}
return model.boundValue;
}
return value;
}
function updateFromBindings(model) {
model.updateFromBindings(true);
}
function findBoundValue(list) {
var i = list.length;
while (i--) {
if (list[i].bound) {
var owner = list[i].owner;
if (owner) {
var value = owner.name === 'checked' ? owner.node.checked : owner.node.value;
return { value: value };
}
}
}
}
function fireShuffleTasks(stage) {
if (!stage) {
fireShuffleTasks('early');
fireShuffleTasks('mark');
} else {
var tasks = shuffleTasks[stage];
shuffleTasks[stage] = [];
var i = tasks.length;
while (i--) { tasks[i](); }
var register = registerQueue[stage];
registerQueue[stage] = [];
i = register.length;
while (i--) { register[i].model.register(register[i].item); }
}
}
function shuffle(model, newIndices, link, unsafe) {
model.shuffling = true;
var i = newIndices.length;
while (i--) {
var idx = newIndices[i];
// nothing is actually changing, so move in the index and roll on
if (i === idx) {
continue;
}
// rebind the children on i to idx
if (i in model.childByKey)
{ model.childByKey[i].rebind(
!~idx ? undefined : model.joinKey(idx),
model.childByKey[i],
!unsafe
); }
}
var upstream = model.source().length !== model.source().value.length;
model.links.forEach(function (l) { return l.shuffle(newIndices); });
if (!link) { fireShuffleTasks('early'); }
i = model.deps.length;
while (i--) {
if (model.deps[i].shuffle) { model.deps[i].shuffle(newIndices); }
}
model[link ? 'marked' : 'mark']();
if (!link) { fireShuffleTasks('mark'); }
if (upstream) { model.notifyUpstream(); }
model.shuffling = false;
}
var stack = [];
var captureGroup;
function startCapturing() {
stack.push((captureGroup = []));
}
function stopCapturing() {
var dependencies = stack.pop();
captureGroup = stack[stack.length - 1];
return dependencies;
}
function capture(model) {
if (captureGroup) {
captureGroup.push(model);
}
}
function bind$1(x) {
x.bind();
}
function cancel(x) {
x.cancel();
}
function destroyed(x) {
x.destroyed();
}
function handleChange(x) {
x.handleChange();
}
function mark(x) {
x.mark();
}
function markForce(x) {
x.mark(true);
}
function marked(x) {
x.marked();
}
function markedAll(x) {
x.markedAll();
}
function render(x) {
x.render();
}
function shuffled(x) {
x.shuffled();
}
function teardown(x) {
x.teardown();
}
function unbind(x) {
x.unbind();
}
function unrender(x) {
x.unrender();
}
function update(x) {
x.update();
}
function toString$1(x) {
return x.toString();
}
function toEscapedString(x) {
return x.toString(true);
}
// this is the dry method of checking to see if a rebind applies to
// a particular keypath because in some cases, a dep may be bound
// directly to a particular keypath e.g. foo.bars.0.baz and need
// to avoid getting kicked to foo.bars.1.baz if foo.bars is unshifted
function rebindMatch(template, next, previous, fragment) {
var keypath = template.r || template;
// no valid keypath, go with next
if (!keypath || !isString(keypath)) { return next; }
// completely contextual ref, go with next
if (
keypath === '.' ||
keypath[0] === '@' ||
(next || previous).isKey ||
(next || previous).isKeypath
)
{ return next; }
var parts = keypath.split('/');
var keys = splitKeypath(parts[parts.length - 1]);
var last = keys[keys.length - 1];
// check the keypath against the model keypath to see if it matches
var model = next || previous;
// check to see if this was an alias
if (model && keys.length === 1 && last !== model.key && fragment) {
keys = findAlias(last, fragment) || keys;
}
var i = keys.length;
var match = true;
var shuffling = false;
while (model && i--) {
if (model.shuffling) { shuffling = true; }
// non-strict comparison to account for indices in keypaths
if (keys[i] != model.key) { match = false; }
model = model.parent;
}
// next is undefined, but keypath is shuffling and previous matches
if (!next && match && shuffling) { return previous; }
else if (next && !match && shuffling)
// next is defined, but doesn't match the keypath
{ return previous; }
else { return next; }
}
function findAlias(name, fragment) {
while (fragment) {
var z = fragment.aliases;
if (z && z[name]) {
var aliases = (fragment.owner.iterations ? fragment.owner : fragment).owner.template.z;
for (var i = 0; i < aliases.length; i++) {
if (aliases[i].n === name) {
var alias = aliases[i].x;
if (!alias.r) { return false; }
var parts = alias.r.split('/');
return splitKeypath(parts[parts.length - 1]);
}
}
return;
}
fragment = fragment.componentParent || fragment.parent;
}
}
// temporary placeholder target for detached implicit links
var Missing = {
key: '@missing',
animate: noop,
applyValue: noop,
get: noop,
getKeypath: function getKeypath() {
return this.key;
},
joinAll: function joinAll() {
return this;
},
joinKey: function joinKey() {
return this;
},
mark: noop,
registerLink: noop,
shufle: noop,
set: noop,
unregisterLink: noop
};
Missing.parent = Missing;
var LinkModel = (function (ModelBase) {
function LinkModel(parent, owner, target, key) {
ModelBase.call(this, parent);
this.owner = owner;
this.target = target;
this.key = key === undefined ? owner.key : key;
if (owner && owner.isLink) { this.sourcePath = (owner.sourcePath) + "." + (this.key); }
if (target) { target.registerLink(this); }
if (parent) { this.isReadonly = parent.isReadonly; }
this.isLink = true;
}
if ( ModelBase ) LinkModel.__proto__ = ModelBase;
var LinkModel__proto__ = LinkModel.prototype = Object.create( ModelBase && ModelBase.prototype );
LinkModel__proto__.constructor = LinkModel;
LinkModel__proto__.animate = function animate (from, to, options, interpolator) {
return this.target.animate(from, to, options, interpolator);
};
LinkModel__proto__.applyValue = function applyValue (value) {
if (this.boundValue) { this.boundValue = null; }
this.target.applyValue(value);
};
LinkModel__proto__.attach = function attach (fragment) {
var model = resolveReference(fragment, this.key);
if (model) {
this.relinking(model, false);
} else {
// if there is no link available, move everything here to real models
this.owner.unlink();
}
};
LinkModel__proto__.detach = function detach () {
this.relinking(Missing, false);
};
LinkModel__proto__.get = function get (shouldCapture, opts) {
if ( opts === void 0 ) opts = {};
if (shouldCapture) {
capture(this);
// may need to tell the target to unwrap
opts.unwrap = 'unwrap' in opts ? opts.unwrap : true;
}
var bind = 'shouldBind' in opts ? opts.shouldBind : true;
opts.shouldBind = this.mapping && this.target.parent && this.target.parent.isRoot;
return maybeBind(this, this.target.get(false, opts), bind);
};
LinkModel__proto__.getKeypath = function getKeypath (ractive) {
if (ractive && ractive !== this.root.ractive) { return this.target.getKeypath(ractive); }
return ModelBase.prototype.getKeypath.call(this, ractive);
};
LinkModel__proto__.handleChange = function handleChange$1 () {
this.deps.forEach(handleChange);
this.links.forEach(handleChange);
this.notifyUpstream();
};
LinkModel__proto__.isDetached = function isDetached () {
return this.virtual && this.target === Missing;
};
LinkModel__proto__.joinKey = function joinKey (key) {
// TODO: handle nested links
if (key === undefined || key === '') { return this; }
if (!hasOwn(this.childByKey, key)) {
var child = new LinkModel(this, this, this.target.joinKey(key), key);
this.children.push(child);
this.childByKey[key] = child;
}
return this.childByKey[key];
};
LinkModel__proto__.mark = function mark (force) {
this.target.mark(force);
};
LinkModel__proto__.marked = function marked$1 () {
if (this.boundValue) { this.boundValue = null; }
this.links.forEach(marked);
this.deps.forEach(handleChange);
};
LinkModel__proto__.markedAll = function markedAll$1 () {
this.children.forEach(markedAll);
this.marked();
};
LinkModel__proto__.notifiedUpstream = function notifiedUpstream (startPath, root) {
var this$1 = this;
this.links.forEach(function (l) { return l.notifiedUpstream(startPath, this$1.root); });
this.deps.forEach(handleChange);
if (startPath && this.rootLink && this.root !== root) {
var path = startPath.slice(1);
path.unshift(this.key);
this.notifyUpstream(path);
}
};
LinkModel__proto__.relinked = function relinked () {
this.target.registerLink(this);
this.children.forEach(function (c) { return c.relinked(); });
};
LinkModel__proto__.relinking = function relinking (target, safe) {
var this$1 = this;
if (this.rootLink && this.sourcePath)
{ target = rebindMatch(this.sourcePath, target, this.target); }
if (!target || this.target === target) { return; }
this.target && this.target.unregisterLink(this);
this.target = target;
this.children.forEach(function (c) {
c.relinking(target.joinKey(c.key), safe);
});
if (this.rootLink)
{ this.addShuffleTask(function () {
this$1.relinked();
if (!safe) {
this$1.markedAll();
this$1.notifyUpstream();
}
}); }
};
LinkModel__proto__.set = function set (value) {
if (this.boundValue) { this.boundValue = null; }
this.target.set(value);
};
LinkModel__proto__.shuffle = function shuffle$1 (newIndices) {
// watch for extra shuffles caused by a shuffle in a downstream link
if (this.shuffling) { return; }
// let the real model handle firing off shuffles
if (!this.target.shuffling) {
if (this.target.shuffle) {
this.target.shuffle(newIndices);
} else {
// the target is a computation, which can't shuffle
this.target.mark();
}
} else {
shuffle(this, newIndices, true);
}
};
LinkModel__proto__.source = function source () {
if (this.target.source) { return this.target.source(); }
else { return this.target; }
};
LinkModel__proto__.teardown = function teardown$3 () {
if (this._link) { this._link.teardown(); }
this.target.unregisterLink(this);
this.children.forEach(teardown);
};
return LinkModel;
}(ModelBase));
ModelBase.prototype.link = function link(model, keypath, options) {
var lnk = this._link || new LinkModel(this.parent, this, model, this.key);
lnk.implicit = options && options.implicit;
lnk.mapping = options && options.mapping;
lnk.sourcePath = keypath;
lnk.rootLink = true;
if (this._link) { this._link.relinking(model, false); }
this.rebind(lnk, this, false);
fireShuffleTasks();
this._link = lnk;
lnk.markedAll();
this.notifyUpstream();
return lnk;
};
ModelBase.prototype.unlink = function unlink() {
if (this._link) {
var ln = this._link;
this._link = undefined;
ln.rebind(this, ln, false);
fireShuffleTasks();
ln.teardown();
this.notifyUpstream();
}
};
function fromExpression(body, length) {
if ( length === void 0 ) length = 0;
var args = new Array(length);
while (length--) {
args[length] = "_" + length;
}
// Functions created directly with new Function() look like this:
// function anonymous (_0 /**/) { return _0*2 }
//
// With this workaround, we get a little more compact:
// function (_0){return _0*2}
return new Function([], ("return function (" + (args.join(',')) + "){return(" + body + ");};"))();
}
var functions = create(null);
function getFunction(str, i) {
if (functions[str]) { return functions[str]; }
return (functions[str] = createFunction(str, i));
}
function addFunctions(template) {
if (!template) { return; }
var exp = template.e;
if (!exp) { return; }
keys(exp).forEach(function (str) {
if (functions[str]) { return; }
functions[str] = exp[str];
});
}
var TEMPLATE_VERSION = 4;
var leadingWhitespace = /^\s+/;
var ParseError = function(message) {
this.name = 'ParseError';
this.message = message;
try {
throw new Error(message);
} catch (e) {
this.stack = e.stack;
}
};
ParseError.prototype = Error.prototype;
var Parser = function(str, options) {
var item;
var lineStart = 0;
this.str = str;
this.options = options || {};
this.pos = 0;
this.lines = this.str.split('\n');
this.lineEnds = this.lines.map(function (line) {
var lineEnd = lineStart + line.length + 1; // +1 for the newline
lineStart = lineEnd;
return lineEnd;
}, 0);
// Custom init logic
if (this.init) { this.init(str, options); }
var items = [];
while (this.pos < this.str.length && (item = this.read())) {
items.push(item);
}
this.leftover = this.remaining();
this.result = this.postProcess ? this.postProcess(items, options) : items;
};
Parser.prototype = {
read: function read(converters) {
var this$1 = this;
var i, item;
if (!converters) { converters = this.converters; }
var pos = this.pos;
var len = converters.length;
for (i = 0; i < len; i += 1) {
this$1.pos = pos; // reset for each attempt
if ((item = converters[i](this$1))) {
return item;
}
}
return null;
},
getContextMessage: function getContextMessage(pos, message) {
var ref = this.getLinePos(pos);
var lineNum = ref[0];
var columnNum = ref[1];
if (this.options.contextLines === -1) {
return [lineNum, columnNum, (message + " at line " + lineNum + " character " + columnNum)];
}
var line = this.lines[lineNum - 1];
var contextUp = '';
var contextDown = '';
if (this.options.contextLines) {
var start =
lineNum - 1 - this.options.contextLines < 0 ? 0 : lineNum - 1 - this.options.contextLines;
contextUp = this.lines
.slice(start, lineNum - 1 - start)
.join('\n')
.replace(/\t/g, ' ');
contextDown = this.lines
.slice(lineNum, lineNum + this.options.contextLines)
.join('\n')
.replace(/\t/g, ' ');
if (contextUp) {
contextUp += '\n';
}
if (contextDown) {
contextDown = '\n' + contextDown;
}
}
var numTabs = 0;
var annotation =
contextUp +
line.replace(/\t/g, function (match, char) {
if (char < columnNum) {
numTabs += 1;
}
return ' ';
}) +
'\n' +
new Array(columnNum + numTabs).join(' ') +
'^----' +
contextDown;
return [
lineNum,
columnNum,
(message + " at line " + lineNum + " character " + columnNum + ":\n" + annotation)
];
},
getLinePos: function getLinePos(char) {
var this$1 = this;
var lineNum = 0;
var lineStart = 0;
while (char >= this.lineEnds[lineNum]) {
lineStart = this$1.lineEnds[lineNum];
lineNum += 1;
}
var columnNum = char - lineStart;
return [lineNum + 1, columnNum + 1, char]; // line/col should be one-based, not zero-based!
},
error: function error(message) {
var ref = this.getContextMessage(this.pos, message);
var lineNum = ref[0];
var columnNum = ref[1];
var msg = ref[2];
var error = new ParseError(msg);
error.line = lineNum;
error.character = columnNum;
error.shortMessage = message;
throw error;
},
matchString: function matchString(string) {
if (this.str.substr(this.pos, string.length) === string) {
this.pos += string.length;
return string;
}
},
matchPattern: function matchPattern(pattern) {
var match;
if ((match = pattern.exec(this.remaining()))) {
this.pos += match[0].length;
return match[1] || match[0];
}
},
sp: function sp() {
this.matchPattern(leadingWhitespace);
},
remaining: function remaining() {
return this.str.substring(this.pos);
},
nextChar: function nextChar() {
return this.str.charAt(this.pos);
},
warn: function warn(message) {
var msg = this.getContextMessage(this.pos, message)[2];
warnIfDebug(msg);
}
};
Parser.extend = function(proto) {
var Parent = this;
var Child = function(str, options) {
Parser.call(this, str, options);
};
Child.prototype = create(Parent.prototype);
for (var key in proto) {
if (hasOwn(proto, key)) {
Child.prototype[key] = proto[key];
}
}
Child.extend = Parser.extend;
return Child;
};
var TEXT = 1;
var INTERPOLATOR = 2;
var TRIPLE = 3;
var SECTION = 4;
var INVERTED = 5;
var CLOSING = 6;
var ELEMENT = 7;
var PARTIAL = 8;
var COMMENT = 9;
var DELIMCHANGE = 10;
var ANCHOR = 11;
var ATTRIBUTE = 13;
var CLOSING_TAG = 14;
var COMPONENT = 15;
var YIELDER = 16;
var INLINE_PARTIAL = 17;
var DOCTYPE = 18;
var ALIAS = 19;
var AWAIT = 55;
var NUMBER_LITERAL = 20;
var STRING_LITERAL = 21;
var ARRAY_LITERAL = 22;
var OBJECT_LITERAL = 23;
var BOOLEAN_LITERAL = 24;
var REGEXP_LITERAL = 25;
var GLOBAL = 26;
var KEY_VALUE_PAIR = 27;
var REFERENCE = 30;
var REFINEMENT = 31;
var MEMBER = 32;
var PREFIX_OPERATOR = 33;
var BRACKETED = 34;
var CONDITIONAL = 35;
var INFIX_OPERATOR = 36;
var INVOCATION = 40;
var SECTION_IF = 50;
var SECTION_UNLESS = 51;
var SECTION_EACH = 52;
var SECTION_WITH = 53;
var SECTION_IF_WITH = 54;
var ELSE = 60;
var ELSEIF = 61;
var THEN = 62;
var CATCH = 63;
var EVENT = 70;
var DECORATOR = 71;
var TRANSITION = 72;
var BINDING_FLAG = 73;
var DELEGATE_FLAG = 74;
var delimiterChangePattern = /^[^\s=]+/;
var whitespacePattern = /^\s+/;
function readDelimiterChange(parser) {
if (!parser.matchString('=')) {
return null;
}
var start = parser.pos;
// allow whitespace before new opening delimiter
parser.sp();
var opening = parser.matchPattern(delimiterChangePattern);
if (!opening) {
parser.pos = start;
return null;
}
// allow whitespace (in fact, it's necessary...)
if (!parser.matchPattern(whitespacePattern)) {
return null;
}
var closing = parser.matchPattern(delimiterChangePattern);
if (!closing) {
parser.pos = start;
return null;
}
// allow whitespace before closing '='
parser.sp();
if (!parser.matchString('=')) {
parser.pos = start;
return null;
}
return [opening, closing];
}
var regexpPattern = /^(\/(?:[^\n\r\u2028\u2029/\\[]|\\.|\[(?:[^\n\r\u2028\u2029\]\\]|\\.)*])+\/(?:([gimuy])(?![a-z]*\2))*(?![a-zA-Z_$0-9]))/;
function readNumberLiteral(parser) {
var result;
if ((result = parser.matchPattern(regexpPattern))) {
return {
t: REGEXP_LITERAL,
v: result
};
}
return null;
}
var pattern = /[-/\\^$*+?.()|[\]{}]/g;
function escapeRegExp(str) {
return str.replace(pattern, '\\$&');
}
var regExpCache = {};
function getLowestIndex(haystack, needles) {
return haystack.search(
regExpCache[needles.join()] ||
(regExpCache[needles.join()] = new RegExp(needles.map(escapeRegExp).join('|')))
);
}
// https://github.com/kangax/html-minifier/issues/63#issuecomment-37763316
//export const booleanAttributes = /^(allowFullscreen|async|autofocus|autoplay|checked|compact|controls|declare|default|defaultChecked|defaultMuted|defaultSelected|defer|disabled|enabled|formNoValidate|hidden|indeterminate|inert|isMap|itemScope|loop|multiple|muted|noHref|noResize|noShade|noValidate|noWrap|open|pauseOnExit|readOnly|required|reversed|scoped|seamless|selected|sortable|translate|trueSpeed|typeMustMatch|visible)$/i;
var booleanAttributes = {
allowfullscreen: 1,
async: 1,
autofocus: 1,
autoplay: 1,
checked: 1,
compact: 1,
controls: 1,
declare: 1,
default: 1,
defaultchecked: 1,
defaultmuted: 1,
defaultselected: 1,
defer: 1,
disabled: 1,
enabled: 1,
formnovalidate: 1,
hidden: 1,
indeterminate: 1,
inert: 1,
ismap: 1,
itemscope: 1,
loop: 1,
multiple: 1,
muted: 1,
nohref: 1,
noresize: 1,
noshade: 1,
novalidate: 1,
nowrap: 1,
open: 1,
pauseonexit: 1,
readonly: 1,
required: 1,
reversed: 1,
scoped: 1,
seamless: 1,
selected: 1,
sortable: 1,
translate: 1,
truespeed: 1,
typemustmatch: 1,
visible: 1
};
var voidElements = {
area: 1,
base: 1,
br: 1,
col: 1,
command: 1,
doctype: 1,
embed: 1,
hr: 1,
img: 1,
input: 1,
keygen: 1,
link: 1,
meta: 1,
param: 1,
source: 1,
track: 1,
wbr: 1
};
var htmlEntities = {
quot: 34,
amp: 38,
apos: 39,
lt: 60,
gt: 62,
nbsp: 160,
iexcl: 161,
cent: 162,
pound: 163,
curren: 164,
yen: 165,
brvbar: 166,
sect: 167,
uml: 168,
copy: 169,
ordf: 170,
laquo: 171,
not: 172,
shy: 173,
reg: 174,
macr: 175,
deg: 176,
plusmn: 177,
sup2: 178,
sup3: 179,
acute: 180,
micro: 181,
para: 182,
middot: 183,
cedil: 184,
sup1: 185,
ordm: 186,
raquo: 187,
frac14: 188,
frac12: 189,
frac34: 190,
iquest: 191,
Agrave: 192,
Aacute: 193,
Acirc: 194,
Atilde: 195,
Auml: 196,
Aring: 197,
AElig: 198,
Ccedil: 199,
Egrave: 200,
Eacute: 201,
Ecirc: 202,
Euml: 203,
Igrave: 204,
Iacute: 205,
Icirc: 206,
Iuml: 207,
ETH: 208,
Ntilde: 209,
Ograve: 210,
Oacute: 211,
Ocirc: 212,
Otilde: 213,
Ouml: 214,
times: 215,
Oslash: 216,
Ugrave: 217,
Uacute: 218,
Ucirc: 219,
Uuml: 220,
Yacute: 221,
THORN: 222,
szlig: 223,
agrave: 224,
aacute: 225,
acirc: 226,
atilde: 227,
auml: 228,
aring: 229,
aelig: 230,
ccedil: 231,
egrave: 232,
eacute: 233,
ecirc: 234,
euml: 235,
igrave: 236,
iacute: 237,
icirc: 238,
iuml: 239,
eth: 240,
ntilde: 241,
ograve: 242,
oacute: 243,
ocirc: 244,
otilde: 245,
ouml: 246,
divide: 247,
oslash: 248,
ugrave: 249,
uacute: 250,
ucirc: 251,
uuml: 252,
yacute: 253,
thorn: 254,
yuml: 255,
OElig: 338,
oelig: 339,
Scaron: 352,
scaron: 353,
Yuml: 376,
fnof: 402,
circ: 710,
tilde: 732,
Alpha: 913,
Beta: 914,
Gamma: 915,
Delta: 916,
Epsilon: 917,
Zeta: 918,
Eta: 919,
Theta: 920,
Iota: 921,
Kappa: 922,
Lambda: 923,
Mu: 924,
Nu: 925,
Xi: 926,
Omicron: 927,
Pi: 928,
Rho: 929,
Sigma: 931,
Tau: 932,
Upsilon: 933,
Phi: 934,
Chi: 935,
Psi: 936,
Omega: 937,
alpha: 945,
beta: 946,
gamma: 947,
delta: 948,
epsilon: 949,
zeta: 950,
eta: 951,
theta: 952,
iota: 953,
kappa: 954,
lambda: 955,
mu: 956,
nu: 957,
xi: 958,
omicron: 959,
pi: 960,
rho: 961,
sigmaf: 962,
sigma: 963,
tau: 964,
upsilon: 965,
phi: 966,
chi: 967,
psi: 968,
omega: 969,
thetasym: 977,
upsih: 978,
piv: 982,
ensp: 8194,
emsp: 8195,
thinsp: 8201,
zwnj: 8204,
zwj: 8205,
lrm: 8206,
rlm: 8207,
ndash: 8211,
mdash: 8212,
lsquo: 8216,
rsquo: 8217,
sbquo: 8218,
ldquo: 8220,
rdquo: 8221,
bdquo: 8222,
dagger: 8224,
Dagger: 8225,
bull: 8226,
hellip: 8230,
permil: 8240,
prime: 8242,
Prime: 8243,
lsaquo: 8249,
rsaquo: 8250,
oline: 8254,
frasl: 8260,
euro: 8364,
image: 8465,
weierp: 8472,
real: 8476,
trade: 8482,
alefsym: 8501,
larr: 8592,
uarr: 8593,
rarr: 8594,
darr: 8595,
harr: 8596,
crarr: 8629,
lArr: 8656,
uArr: 8657,
rArr: 8658,
dArr: 8659,
hArr: 8660,
forall: 8704,
part: 8706,
exist: 8707,
empty: 8709,
nabla: 8711,
isin: 8712,
notin: 8713,
ni: 8715,
prod: 8719,
sum: 8721,
minus: 8722,
lowast: 8727,
radic: 8730,
prop: 8733,
infin: 8734,
ang: 8736,
and: 8743,
or: 8744,
cap: 8745,
cup: 8746,
int: 8747,
there4: 8756,
sim: 8764,
cong: 8773,
asymp: 8776,
ne: 8800,
equiv: 8801,
le: 8804,
ge: 8805,
sub: 8834,
sup: 8835,
nsub: 8836,
sube: 8838,
supe: 8839,
oplus: 8853,
otimes: 8855,
perp: 8869,
sdot: 8901,
lceil: 8968,
rceil: 8969,
lfloor: 8970,
rfloor: 8971,
lang: 9001,
rang: 9002,
loz: 9674,
spades: 9824,
clubs: 9827,
hearts: 9829,
diams: 9830
};
var controlCharacters = [
8364,
129,
8218,
402,
8222,
8230,
8224,
8225,
710,
8240,
352,
8249,
338,
141,
381,
143,
144,
8216,
8217,
8220,
8221,
8226,
8211,
8212,
732,
8482,
353,
8250,
339,
157,
382,
376
];
var entityPattern = new RegExp(
'&(#?(?:x[\\w\\d]+|\\d+|' + keys(htmlEntities).join('|') + '));?',
'g'
);
var codePointSupport = isFunction(String.fromCodePoint);
var codeToChar = codePointSupport ? String.fromCodePoint : String.fromCharCode;
function decodeCharacterReferences(html) {
return html.replace(entityPattern, function (match, entity) {
var code;
// Handle named entities
if (entity[0] !== '#') {
code = htmlEntities[entity];
} else if (entity[1] === 'x') {
code = parseInt(entity.substring(2), 16);
} else {
code = parseInt(entity.substring(1), 10);
}
if (!code) {
return match;
}
return codeToChar(validateCode(code));
});
}
var lessThan = /</g;
var greaterThan = />/g;
var amp = /&/g;
var invalid = 65533;
function escapeHtml(str) {
return str
.replace(amp, '&')
.replace(lessThan, '<')
.replace(greaterThan, '>');
}
// some code points are verboten. If we were inserting HTML, the browser would replace the illegal
// code points with alternatives in some cases - since we're bypassing that mechanism, we need
// to replace them ourselves
//
// Source: http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Illegal_characters
/* istanbul ignore next */
function validateCode(code) {
if (!code) {
return invalid;
}
// line feed becomes generic whitespace
if (code === 10) {
return 32;
}
// ASCII range. (Why someone would use HTML entities for ASCII characters I don't know, but...)
if (code < 128) {
return code;
}
// code points 128-159 are dealt with leniently by browsers, but they're incorrect. We need
// to correct the mistake or we'll end up with missing € signs and so on
if (code <= 159) {
return controlCharacters[code - 128];
}
// basic multilingual plane
if (code < 55296) {
return code;
}
// UTF-16 surrogate halves
if (code <= 57343) {
return invalid;
}
// rest of the basic multilingual plane
if (code <= 65535) {
return code;
} else if (!codePointSupport) {
return invalid;
}
// supplementary multilingual plane 0x10000 - 0x1ffff
if (code >= 65536 && code <= 131071) {
return code;
}
// supplementary ideographic plane 0x20000 - 0x2ffff
if (code >= 131072 && code <= 196607) {
return code;
}
return invalid;
}
var expectedExpression = 'Expected a JavaScript expression';
var expectedParen = 'Expected closing paren';
// bulletproof number regex from https://gist.github.com/Rich-Harris/7544330
var numberPattern = /^(?:[+-]?)0*(?:(?:(?:[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/;
function readNumberLiteral$1(parser) {
var result;
if ((result = parser.matchPattern(numberPattern))) {
return {
t: NUMBER_LITERAL,
v: result
};
}
return null;
}
function readBooleanLiteral(parser) {
var remaining = parser.remaining();
if (remaining.substr(0, 4) === 'true') {
parser.pos += 4;
return {
t: BOOLEAN_LITERAL,
v: 'true'
};
}
if (remaining.substr(0, 5) === 'false') {
parser.pos += 5;
return {
t: BOOLEAN_LITERAL,
v: 'false'
};
}
return null;
}
// Match one or more characters until: ", ', \, or EOL/EOF.
// EOL/EOF is written as (?!.) (meaning there's no non-newline char next).
var stringMiddlePattern = /^(?=.)[^"'\\]+?(?:(?!.)|(?=["'\\]))/;
// Match one escape sequence, including the backslash.
var escapeSequencePattern = /^\\(?:[`'"\\bfnrt]|0(?![0-9])|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|(?=.)[^ux0-9])/;
// Match one ES5 line continuation (backslash + line terminator).
var lineContinuationPattern = /^\\(?:\r\n|[\u000A\u000D\u2028\u2029])/;
// Helper for defining getDoubleQuotedString and getSingleQuotedString.
function makeQuotedStringMatcher(okQuote) {
return function(parser) {
var literal = '"';
var done = false;
var next;
while (!done) {
next =
parser.matchPattern(stringMiddlePattern) ||
parser.matchPattern(escapeSequencePattern) ||
parser.matchString(okQuote);
if (next) {
if (next === "\"") {
literal += "\\\"";
} else if (next === "\\'") {
literal += "'";
} else {
literal += next;
}
} else {
next = parser.matchPattern(lineContinuationPattern);
if (next) {
// convert \(newline-like) into a \u escape, which is allowed in JSON
literal += '\\u' + ('000' + next.charCodeAt(1).toString(16)).slice(-4);
} else {
done = true;
}
}
}
literal += '"';
// use JSON.parse to interpret escapes
return JSON.parse(literal);
};
}
var singleMatcher = makeQuotedStringMatcher("\"");
var doubleMatcher = makeQuotedStringMatcher("'");
function readStringLiteral(parser) {
var start = parser.pos;
var quote = parser.matchString("'") || parser.matchString("\"");
if (quote) {
var string = (quote === "'" ? singleMatcher : doubleMatcher)(parser);
if (!parser.matchString(quote)) {
parser.pos = start;
return null;
}
return {
t: STRING_LITERAL,
v: string
};
}
return null;
}
// Match one or more characters until: ", ', or \
var stringMiddlePattern$1 = /^[^`"\\\$]+?(?:(?=[`"\\\$]))/;
var escapes = /[\r\n\t\b\f]/g;
function getString(literal) {
return JSON.parse(("\"" + (literal.replace(escapes, escapeChar)) + "\""));
}
function escapeChar(c) {
switch (c) {
case '\n':
return '\\n';
case '\r':
return '\\r';
case '\t':
return '\\t';
case '\b':
return '\\b';
case '\f':
return '\\f';
}
}
function readTemplateStringLiteral(parser) {
if (!parser.matchString('`')) { return null; }
var literal = '';
var done = false;
var next;
var parts = [];
while (!done) {
next =
parser.matchPattern(stringMiddlePattern$1) ||
parser.matchPattern(escapeSequencePattern) ||
parser.matchString('$') ||
parser.matchString('"');
if (next) {
if (next === "\"") {
literal += "\\\"";
} else if (next === '\\`') {
literal += '`';
} else if (next === '$') {
if (parser.matchString('{')) {
parts.push({ t: STRING_LITERAL, v: getString(literal) });
literal = '';
parser.sp();
var expr = readExpression(parser);
if (!expr) { parser.error('Expected valid expression'); }
parts.push({ t: BRACKETED, x: expr });
parser.sp();
if (!parser.matchString('}'))
{ parser.error("Expected closing '}' after interpolated expression"); }
} else {
literal += '$';
}
} else {
literal += next;
}
} else {
next = parser.matchPattern(lineContinuationPattern);
if (next) {
// convert \(newline-like) into a \u escape, which is allowed in JSON
literal += '\\u' + ('000' + next.charCodeAt(1).toString(16)).slice(-4);
} else {
done = true;
}
}
}
if (literal.length) { parts.push({ t: STRING_LITERAL, v: getString(literal) }); }
if (!parser.matchString('`')) { parser.error("Expected closing '`'"); }
if (parts.length === 1) {
return parts[0];
} else {
var result = parts.pop();
var part;
while ((part = parts.pop())) {
result = {
t: INFIX_OPERATOR,
s: '+',
o: [part, result]
};
}
return {
t: BRACKETED,
x: result
};
}
}
var name = /^[a-zA-Z_$][a-zA-Z_$0-9]*/;
var spreadPattern = /^\s*\.{3}/;
var legalReference = /^(?:[a-zA-Z$_0-9]|\\\.)+(?:(?:\.(?:[a-zA-Z$_0-9]|\\\.)+)|(?:\[[0-9]+\]))*/;
var relaxedName = /^[a-zA-Z_$][-\/a-zA-Z_$0-9]*(?:\.(?:[a-zA-Z_$][-\/a-zA-Z_$0-9]*))*/;
var identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
// http://mathiasbynens.be/notes/javascript-properties
// can be any name, string literal, or number literal
function readKey(parser) {
var token;
if ((token = readStringLiteral(parser))) {
return identifier.test(token.v) ? token.v : '"' + token.v.replace(/"/g, '\\"') + '"';
}
if ((token = readNumberLiteral$1(parser))) {
return token.v;
}
if ((token = parser.matchPattern(name))) {
return token;
}
return null;
}
function readKeyValuePair(parser) {
var spread;
var start = parser.pos;
// allow whitespace between '{' and key
parser.sp();
var refKey = parser.nextChar() !== "'" && parser.nextChar() !== '"';
if (refKey) { spread = parser.matchPattern(spreadPattern); }
var key = spread ? readExpression(parser) : readKey(parser);
if (key === null) {
parser.pos = start;
return null;
}
// allow whitespace between key and ':'
parser.sp();
// es2015 shorthand property
if (refKey && (parser.nextChar() === ',' || parser.nextChar() === '}')) {
if (!spread && !name.test(key)) {
parser.error(("Expected a valid reference, but found '" + key + "' instead."));
}
var pair = {
t: KEY_VALUE_PAIR,
k: key,
v: {
t: REFERENCE,
n: key
}
};
if (spread) {
pair.p = true;
}
return pair;
}
// next character must be ':'
if (!parser.matchString(':')) {
parser.pos = start;
return null;
}
// allow whitespace between ':' and value
parser.sp();
// next expression must be a, well... expression
var value = readExpression(parser);
if (value === null) {
parser.pos = start;
return null;
}
return {
t: KEY_VALUE_PAIR,
k: key,
v: value
};
}
function readKeyValuePairs(parser) {
var start = parser.pos;
var pair = readKeyValuePair(parser);
if (pair === null) {
return null;
}
var pairs = [pair];
if (parser.matchString(',')) {
var keyValuePairs = readKeyValuePairs(parser);
if (!keyValuePairs) {
parser.pos = start;
return null;
}
return pairs.concat(keyValuePairs);
}
return pairs;
}
function readObjectLiteral(parser) {
var start = parser.pos;
// allow whitespace
parser.sp();
if (!parser.matchString('{')) {
parser.pos = start;
return null;
}
var keyValuePairs = readKeyValuePairs(parser);
// allow whitespace between final value and '}'
parser.sp();
if (!parser.matchString('}')) {
parser.pos = start;
return null;
}
return {
t: OBJECT_LITERAL,
m: keyValuePairs
};
}
function readArrayLiteral(parser) {
var start = parser.pos;
// allow whitespace before '['
parser.sp();
if (!parser.matchString('[')) {
parser.pos = start;
return null;
}
var expressionList = readExpressionList(parser, true);
if (!parser.matchString(']')) {
parser.pos = start;
return null;
}
return {
t: ARRAY_LITERAL,
m: expressionList
};
}
function readLiteral(parser) {
return (
readNumberLiteral$1(parser) ||
readBooleanLiteral(parser) ||
readStringLiteral(parser) ||
readTemplateStringLiteral(parser) ||
readObjectLiteral(parser) ||
readArrayLiteral(parser) ||
readNumberLiteral(parser)
);
}
// if a reference is a browser global, we don't deference it later, so it needs special treatment
var globals = /^(?:Array|console|Date|RegExp|decodeURIComponent|decodeURI|encodeURIComponent|encodeURI|isFinite|isNaN|parseFloat|parseInt|JSON|Math|NaN|undefined|null|Object|Number|String|Boolean)\b/;
// keywords are not valid references, with the exception of `this`
var keywords = /^(?:break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|throw|try|typeof|var|void|while|with)$/;
var prefixPattern = /^(?:\@\.|\@|~\/|(?:\^\^\/(?:\^\^\/)*(?:\.\.\/)*)|(?:\.\.\/)+|\.\/(?:\.\.\/)*|\.)/;
var specials = /^(key|index|keypath|rootpath|this|global|shared|context|event|node|local|style|helpers|last|macro)/;
function readReference(parser) {
var prefix, name$$1, global, reference, lastDotIndex;
var startPos = parser.pos;
prefix = parser.matchPattern(prefixPattern) || '';
name$$1 =
(!prefix && parser.relaxedNames && parser.matchPattern(relaxedName)) ||
parser.matchPattern(legalReference);
var actual = prefix.length + ((name$$1 && name$$1.length) || 0);
if (prefix === '@.') {
prefix = '@';
if (name$$1) { name$$1 = 'this.' + name$$1; }
else { name$$1 = 'this'; }
}
if (!name$$1 && prefix) {
name$$1 = prefix;
prefix = '';
}
if (!name$$1) {
return null;
}
if (prefix === '@') {
if (!specials.test(name$$1)) {
parser.error(("Unrecognized special reference @" + name$$1));
} else if ((!name$$1.indexOf('event') || !name$$1.indexOf('node')) && !parser.inEvent) {
parser.error("@event and @node are only valid references within an event directive");
} else if (~name$$1.indexOf('context')) {
parser.pos = parser.pos - (name$$1.length - 7);
return {
t: BRACKETED,
x: {
t: REFERENCE,
n: '@context'
}
};
}
}
// bug out if it's a keyword (exception for ancestor/restricted refs - see https://github.com/ractivejs/ractive/issues/1497)
if (!prefix && !parser.relaxedNames && keywords.test(name$$1)) {
parser.pos = startPos;
return null;
}
// if this is a browser global, stop here
if (!prefix && globals.test(name$$1)) {
global = globals.exec(name$$1)[0];
parser.pos = startPos + global.length;
return {
t: GLOBAL,
v: global
};
}
reference = (prefix || '') + normalise(name$$1);
if (parser.matchString('(')) {
// if this is a method invocation (as opposed to a function) we need
// to strip the method name from the reference combo, else the context
// will be wrong
// but only if the reference was actually a member and not a refinement
lastDotIndex = reference.lastIndexOf('.');
if (lastDotIndex !== -1 && name$$1[name$$1.length - 1] !== ']') {
if (lastDotIndex === 0) {
reference = '.';
parser.pos = startPos;
} else {
var refLength = reference.length;
reference = reference.substr(0, lastDotIndex);
parser.pos = startPos + (actual - (refLength - lastDotIndex));
}
} else {
parser.pos -= 1;
}
}
return {
t: REFERENCE,
n: reference.replace(/^this\./, './').replace(/^this$/, '.')
};
}
function readBracketedExpression(parser) {
if (!parser.matchString('(')) { return null; }
parser.sp();
var expr = readExpression(parser);
if (!expr) { parser.error(expectedExpression); }
parser.sp();
if (!parser.matchString(')')) { parser.error(expectedParen); }
return {
t: BRACKETED,
x: expr
};
}
function readPrimary(parser) {
return readLiteral(parser) || readReference(parser) || readBracketedExpression(parser);
}
function readRefinement(parser) {
// some things call for strict refinement (partial names), meaning no space between reference and refinement
if (!parser.strictRefinement) {
parser.sp();
}
// "." name
if (parser.matchString('.')) {
parser.sp();
var name$$1 = parser.matchPattern(name);
if (name$$1) {
return {
t: REFINEMENT,
n: name$$1
};
}
parser.error('Expected a property name');
}
// "[" expression "]"
if (parser.matchString('[')) {
parser.sp();
var expr = readExpression(parser);
if (!expr) { parser.error(expectedExpression); }
parser.sp();
if (!parser.matchString(']')) { parser.error("Expected ']'"); }
return {
t: REFINEMENT,
x: expr
};
}
return null;
}
function readMemberOrInvocation(parser) {
var expression = readPrimary(parser);
if (!expression) { return null; }
while (expression) {
var refinement = readRefinement(parser);
if (refinement) {
expression = {
t: MEMBER,
x: expression,
r: refinement
};
} else if (parser.matchString('(')) {
parser.sp();
var expressionList = readExpressionList(parser, true);
parser.sp();
if (!parser.matchString(')')) {
parser.error(expectedParen);
}
expression = {
t: INVOCATION,
x: expression
};
if (expressionList) { expression.o = expressionList; }
} else {
break;
}
}
return expression;
}
var readTypeOf;
var makePrefixSequenceMatcher = function(symbol, fallthrough) {
return function(parser) {
var expression;
if ((expression = fallthrough(parser))) {
return expression;
}
if (!parser.matchString(symbol)) {
return null;
}
parser.sp();
expression = readExpression(parser);
if (!expression) {
parser.error(expectedExpression);
}
return {
s: symbol,
o: expression,
t: PREFIX_OPERATOR
};
};
};
// create all prefix sequence matchers, return readTypeOf
(function() {
var i, len, matcher, fallthrough;
var prefixOperators = '! ~ + - typeof'.split(' ');
fallthrough = readMemberOrInvocation;
for (i = 0, len = prefixOperators.length; i < len; i += 1) {
matcher = makePrefixSequenceMatcher(prefixOperators[i], fallthrough);
fallthrough = matcher;
}
// typeof operator is higher precedence than multiplication, so provides the
// fallthrough for the multiplication sequence matcher we're about to create
// (we're skipping void and delete)
readTypeOf = fallthrough;
})();
var readTypeof = readTypeOf;
var readLogicalOr;
var makeInfixSequenceMatcher = function(symbol, fallthrough) {
return function(parser) {
// > and / have to be quoted
if (parser.inUnquotedAttribute && (symbol === '>' || symbol === '/'))
{ return fallthrough(parser); }
var start, left, right;
left = fallthrough(parser);
if (!left) {
return null;
}
// Loop to handle left-recursion in a case like `a * b * c` and produce
// left association, i.e. `(a * b) * c`. The matcher can't call itself
// to parse `left` because that would be infinite regress.
while (true) {
start = parser.pos;
parser.sp();
if (!parser.matchString(symbol)) {
parser.pos = start;
return left;
}
// special case - in operator must not be followed by [a-zA-Z_$0-9]
if (symbol === 'in' && /[a-zA-Z_$0-9]/.test(parser.remaining().charAt(0))) {
parser.pos = start;
return left;
}
parser.sp();
// right operand must also consist of only higher-precedence operators
right = fallthrough(parser);
if (!right) {
parser.pos = start;
return left;
}
left = {
t: INFIX_OPERATOR,
s: symbol,
o: [left, right]
};
// Loop back around. If we don't see another occurrence of the symbol,
// we'll return left.
}
};
};
// create all infix sequence matchers, and return readLogicalOr
(function() {
var i, len, matcher, fallthrough;
// All the infix operators on order of precedence (source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence)
// Each sequence matcher will initially fall through to its higher precedence
// neighbour, and only attempt to match if one of the higher precedence operators
// (or, ultimately, a literal, reference, or bracketed expression) already matched
var infixOperators = '* / % + - << >> >>> < <= > >= in instanceof == != === !== & ^ | && ||'.split(
' '
);
// A typeof operator is higher precedence than multiplication
fallthrough = readTypeof;
for (i = 0, len = infixOperators.length; i < len; i += 1) {
matcher = makeInfixSequenceMatcher(infixOperators[i], fallthrough);
fallthrough = matcher;
}
// Logical OR is the fallthrough for the conditional matcher
readLogicalOr = fallthrough;
})();
var readLogicalOr$1 = readLogicalOr;
// The conditional operator is the lowest precedence operator, so we start here
function getConditional(parser) {
var expression = readLogicalOr$1(parser);
if (!expression) {
return null;
}
var start = parser.pos;
parser.sp();
if (!parser.matchString('?')) {
parser.pos = start;
return expression;
}
parser.sp();
var ifTrue = readExpression(parser);
if (!ifTrue) {
parser.error(expectedExpression);
}
parser.sp();
if (!parser.matchString(':')) {
parser.error('Expected ":"');
}
parser.sp();
var ifFalse = readExpression(parser);
if (!ifFalse) {
parser.error(expectedExpression);
}
return {
t: CONDITIONAL,
o: [expression, ifTrue, ifFalse]
};
}
function readExpression(parser) {
// if eval is false, no expressions
if (parser.allowExpressions === false) {
var ref = readReference(parser);
parser.sp();
return ref;
}
// The conditional operator is the lowest precedence operator (except yield,
// assignment operators, and commas, none of which are supported), so we
// start there. If it doesn't match, it 'falls through' to progressively
// higher precedence operators, until it eventually matches (or fails to
// match) a 'primary' - a literal or a reference. This way, the abstract syntax
// tree has everything in its proper place, i.e. 2 + 3 * 4 === 14, not 20.
return getConditional(parser);
}
function readExpressionList(parser, spread) {
var isSpread;
var expressions = [];
var pos = parser.pos;
do {
parser.sp();
if (spread) {
isSpread = parser.matchPattern(spreadPattern);
}
var expr = readExpression(parser);
if (expr === null && expressions.length) {
parser.error(expectedExpression);
} else if (expr === null) {
parser.pos = pos;
return null;
}
if (isSpread) {
expr.p = true;
}
expressions.push(expr);
parser.sp();
} while (parser.matchString(','));
return expressions;
}
function readExpressionOrReference(parser, expectedFollowers) {
var start = parser.pos;
var expression = readExpression(parser);
if (!expression) {
// valid reference but invalid expression e.g. `{{new}}`?
var ref = parser.matchPattern(/^(\w+)/);
if (ref) {
return {
t: REFERENCE,
n: ref
};
}
return null;
}
for (var i = 0; i < expectedFollowers.length; i += 1) {
if (parser.remaining().substr(0, expectedFollowers[i].length) === expectedFollowers[i]) {
return expression;
}
}
parser.pos = start;
return readReference(parser);
}
function flattenExpression(expression) {
var refs;
var count = 0;
extractRefs(expression, (refs = []));
var stringified = stringify(expression);
return {
r: refs,
s: getVars(stringified)
};
function getVars(expr) {
var vars = [];
for (var i = count - 1; i >= 0; i--) {
vars.push(("x$" + i));
}
return vars.length ? ("(function(){var " + (vars.join(',')) + ";return(" + expr + ");})()") : expr;
}
function stringify(node) {
if (isString(node)) {
return node;
}
switch (node.t) {
case BOOLEAN_LITERAL:
case GLOBAL:
case NUMBER_LITERAL:
case REGEXP_LITERAL:
return node.v;
case STRING_LITERAL:
return JSON.stringify(String(node.v));
case ARRAY_LITERAL:
if (node.m && hasSpread(node.m)) {
return ("[].concat(" + (makeSpread(node.m, '[', ']', stringify)) + ")");
} else {
return '[' + (node.m ? node.m.map(stringify).join(',') : '') + ']';
}
case OBJECT_LITERAL:
if (node.m && hasSpread(node.m)) {
return ("Object.assign({}," + (makeSpread(node.m, '{', '}', stringifyPair)) + ")");
} else {
return '{' + (node.m ? node.m.map(function (n) { return ((n.k) + ":" + (stringify(n.v))); }).join(',') : '') + '}';
}
case PREFIX_OPERATOR:
return (node.s === 'typeof' ? 'typeof ' : node.s) + stringify(node.o);
case INFIX_OPERATOR:
return (
stringify(node.o[0]) +
(node.s.substr(0, 2) === 'in' ? ' ' + node.s + ' ' : node.s) +
stringify(node.o[1])
);
case INVOCATION:
if (node.o && hasSpread(node.o)) {
var id = count++;
return ("(x$" + id + "=" + (stringify(node.x)) + ").apply(x$" + id + "," + (stringify({
t: ARRAY_LITERAL,
m: node.o
})) + ")");
} else {
return stringify(node.x) + '(' + (node.o ? node.o.map(stringify).join(',') : '') + ')';
}
case BRACKETED:
return '(' + stringify(node.x) + ')';
case MEMBER:
return stringify(node.x) + stringify(node.r);
case REFINEMENT:
return node.n ? '.' + node.n : '[' + stringify(node.x) + ']';
case CONDITIONAL:
return stringify(node.o[0]) + '?' + stringify(node.o[1]) + ':' + stringify(node.o[2]);
case REFERENCE:
return '_' + refs.indexOf(node.n);
default:
throw new Error('Expected legal JavaScript');
}
}
function stringifyPair(node) {
return node.p ? stringify(node.k) : ((node.k) + ":" + (stringify(node.v)));
}
function makeSpread(list, open, close, fn) {
var out = list.reduce(
function (a, c) {
if (c.p) {
a.str += "" + (a.open ? close + ',' : a.str.length ? ',' : '') + (fn(c));
} else {
a.str += "" + (!a.str.length ? open : !a.open ? ',' + open : ',') + (fn(c));
}
a.open = !c.p;
return a;
},
{ open: false, str: '' }
);
if (out.open) { out.str += close; }
return out.str;
}
}
function hasSpread(list) {
for (var i = 0; i < list.length; i++) {
if (list[i].p) { return true; }
}
return false;
}
// TODO maybe refactor this?
function extractRefs(node, refs) {
if (node.t === REFERENCE && isString(node.n)) {
if (!~refs.indexOf(node.n)) {
refs.unshift(node.n);
}
}
var list = node.o || node.m;
if (list) {
if (isObject(list)) {
extractRefs(list, refs);
} else {
var i = list.length;
while (i--) {
extractRefs(list[i], refs);
}
}
}
if (node.k && node.t === KEY_VALUE_PAIR && !isString(node.k)) {
extractRefs(node.k, refs);
}
if (node.x) {
extractRefs(node.x, refs);
}
if (node.r) {
extractRefs(node.r, refs);
}
if (node.v) {
extractRefs(node.v, refs);
}
}
function refineExpression(expression, mustache) {
var referenceExpression;
if (expression) {
while (expression.t === BRACKETED && expression.x) {
expression = expression.x;
}
if (expression.t === REFERENCE) {
var n = expression.n;
if (!~n.indexOf('@context')) {
mustache.r = expression.n;
} else {
mustache.x = flattenExpression(expression);
}
} else {
if ((referenceExpression = getReferenceExpression(expression))) {
mustache.rx = referenceExpression;
} else {
mustache.x = flattenExpression(expression);
}
}
return mustache;
}
}
// TODO refactor this! it's bewildering
function getReferenceExpression(expression) {
var members = [];
var refinement;
while (expression.t === MEMBER && expression.r.t === REFINEMENT) {
refinement = expression.r;
if (refinement.x) {
if (refinement.x.t === REFERENCE) {
members.unshift(refinement.x);
} else {
members.unshift(flattenExpression(refinement.x));
}
} else {
members.unshift(refinement.n);
}
expression = expression.x;
}
if (expression.t !== REFERENCE) {
return null;
}
return {
r: expression.n,
m: members
};
}
var attributeNamePattern = /^[^\s"'>\/=(]+/;
var onPattern = /^on/;
var eventPattern = /^on-([a-zA-Z\*\.$_]((?:[a-zA-Z\*\.$_0-9\-]|\\-)+))$/;
var reservedEventNames = /^(?:change|reset|teardown|update|construct|config|init|render|complete|unrender|detach|insert|destruct|attachchild|detachchild)$/;
var decoratorPattern = /^as-([a-z-A-Z][-a-zA-Z_0-9]*)$/;
var transitionPattern = /^([a-zA-Z](?:(?!-in-out)[-a-zA-Z_0-9])*)-(in|out|in-out)$/;
var boundPattern = /^((bind|class)-(([-a-zA-Z0-9_])+))$/;
var directives = {
lazy: { t: BINDING_FLAG, v: 'l' },
twoway: { t: BINDING_FLAG, v: 't' },
'no-delegation': { t: DELEGATE_FLAG }
};
var unquotedAttributeValueTextPattern = /^[^\s"'=<>\/`]+/;
var proxyEvent = /^[^\s"'=<>@\[\]()]*/;
var whitespace = /^\s+/;
var slashes = /\\/g;
function splitEvent(str) {
var result = [];
var s = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === '-' && str[i - 1] !== '\\') {
result.push(str.substring(s, i).replace(slashes, ''));
s = i + 1;
}
}
result.push(str.substring(s).replace(slashes, ''));
return result;
}
function readAttribute(parser) {
var name, i, nearest, idx;
parser.sp();
name = parser.matchPattern(attributeNamePattern);
if (!name) {
return null;
}
// check for accidental delimiter consumption e.g. <tag bool{{>attrs}} />
nearest = name.length;
for (i = 0; i < parser.tags.length; i++) {
if (~(idx = name.indexOf(parser.tags[i].open))) {
if (idx < nearest) { nearest = idx; }
}
}
if (nearest < name.length) {
parser.pos -= name.length - nearest;
name = name.substr(0, nearest);
if (!name) { return null; }
}
return { n: name };
}
function readAttributeValue(parser) {
var start = parser.pos;
// next character must be `=`, `/`, `>` or whitespace
if (!/[=\/>\s]/.test(parser.nextChar())) {
parser.error('Expected `=`, `/`, `>` or whitespace');
}
parser.sp();
if (!parser.matchString('=')) {
parser.pos = start;
return null;
}
parser.sp();
var valueStart = parser.pos;
var startDepth = parser.sectionDepth;
var value =
readQuotedAttributeValue(parser, "'") ||
readQuotedAttributeValue(parser, "\"") ||
readUnquotedAttributeValue(parser);
if (value === null) {
parser.error('Expected valid attribute value');
}
if (parser.sectionDepth !== startDepth) {
parser.pos = valueStart;
parser.error(
'An attribute value must contain as many opening section tags as closing section tags'
);
}
if (!value.length) {
return '';
}
if (value.length === 1 && isString(value[0])) {
return decodeCharacterReferences(value[0]);
}
return value;
}
function readUnquotedAttributeValueToken(parser) {
var text, index;
var start = parser.pos;
text = parser.matchPattern(unquotedAttributeValueTextPattern);
if (!text) {
return null;
}
var haystack = text;
var needles = parser.tags.map(function (t) { return t.open; }); // TODO refactor... we do this in readText.js as well
if ((index = getLowestIndex(haystack, needles)) !== -1) {
text = text.substr(0, index);
parser.pos = start + text.length;
}
return text;
}
function readUnquotedAttributeValue(parser) {
parser.inAttribute = true;
var tokens = [];
var token = readMustache(parser) || readUnquotedAttributeValueToken(parser);
while (token) {
tokens.push(token);
token = readMustache(parser) || readUnquotedAttributeValueToken(parser);
}
if (!tokens.length) {
return null;
}
parser.inAttribute = false;
return tokens;
}
function readQuotedAttributeValue(parser, quoteMark) {
var start = parser.pos;
if (!parser.matchString(quoteMark)) {
return null;
}
parser.inAttribute = quoteMark;
var tokens = [];
var token = readMustache(parser) || readQuotedStringToken(parser, quoteMark);
while (token !== null) {
tokens.push(token);
token = readMustache(parser) || readQuotedStringToken(parser, quoteMark);
}
if (!parser.matchString(quoteMark)) {
parser.pos = start;
return null;
}
parser.inAttribute = false;
return tokens;
}
function readQuotedStringToken(parser, quoteMark) {
var haystack = parser.remaining();
var needles = parser.tags.map(function (t) { return t.open; }); // TODO refactor... we do this in readText.js as well
needles.push(quoteMark);
var index = getLowestIndex(haystack, needles);
if (index === -1) {
parser.error('Quoted attribute value must have a closing quote');
}
if (!index) {
return null;
}
parser.pos += index;
return haystack.substr(0, index);
}
function readAttributeOrDirective(parser) {
var match, directive;
var attribute = readAttribute(parser, false);
if (!attribute) { return null; }
// lazy, twoway
if ((directive = directives[attribute.n])) {
attribute.t = directive.t;
if (directive.v) { attribute.v = directive.v; }
delete attribute.n; // no name necessary
parser.sp();
if (parser.nextChar() === '=') { attribute.f = readAttributeValue(parser); }
} else if ((match = decoratorPattern.exec(attribute.n))) {
// decorators
attribute.n = match[1];
attribute.t = DECORATOR;
readArguments(parser, attribute);
} else if ((match = transitionPattern.exec(attribute.n))) {
// transitions
attribute.n = match[1];
attribute.t = TRANSITION;
readArguments(parser, attribute);
attribute.v = match[2] === 'in-out' ? 't0' : match[2] === 'in' ? 't1' : 't2';
} else if ((match = eventPattern.exec(attribute.n))) {
// on-click etc
attribute.n = splitEvent(match[1]);
attribute.t = EVENT;
if (parser.matchString('(')) {
attribute.a = flattenExpression({
t: ARRAY_LITERAL,
m: readExpressionList(parser)
});
if (!parser.matchString(')')) { parser.error("Expected closing ')'"); }
}
parser.inEvent = true;
// check for a proxy event
if (!readProxyEvent(parser, attribute)) {
// otherwise, it's an expression
readArguments(parser, attribute, true);
} else if (reservedEventNames.test(attribute.f)) {
parser.pos -= attribute.f.length;
parser.error(
'Cannot use reserved event names (change, reset, teardown, update, construct, config, init, render, unrender, complete, detach, insert, destruct, attachchild, detachchild)'
);
}
parser.inEvent = false;
} else if ((match = boundPattern.exec(attribute.n))) {
// bound directives
var bind = match[2] === 'bind';
attribute.n = bind ? match[3] : match[1];
attribute.t = ATTRIBUTE;
readArguments(parser, attribute, false, true);
if (!attribute.f && bind) {
attribute.f = [{ t: INTERPOLATOR, r: match[3] }];
}
} else {
parser.sp();
var value = parser.nextChar() === '=' ? readAttributeValue(parser) : null;
attribute.f = value != null ? value : attribute.f;
if (parser.sanitizeEventAttributes && onPattern.test(attribute.n)) {
return { exclude: true };
} else {
attribute.f = attribute.f || (attribute.f === '' ? '' : 0);
attribute.t = ATTRIBUTE;
}
}
return attribute;
}
function readProxyEvent(parser, attribute) {
var start = parser.pos;
if (!parser.matchString('=')) { parser.error("Missing required directive arguments"); }
var quote = parser.matchString("'") || parser.matchString("\"");
parser.sp();
var proxy = parser.matchPattern(proxyEvent);
if (proxy !== undefined) {
if (quote) {
parser.sp();
if (!parser.matchString(quote)) { parser.pos = start; }
else { return (attribute.f = proxy) || true; }
} else if (!parser.matchPattern(whitespace)) {
parser.pos = start;
} else {
return (attribute.f = proxy) || true;
}
} else {
parser.pos = start;
}
}
function readArguments(parser, attribute, required, single) {
if ( required === void 0 ) required = false;
if ( single === void 0 ) single = false;
parser.sp();
if (!parser.matchString('=')) {
if (required) { parser.error("Missing required directive arguments"); }
return;
}
parser.sp();
var quote = parser.matchString('"') || parser.matchString("'");
var spread = parser.spreadArgs;
parser.spreadArgs = true;
parser.inUnquotedAttribute = !quote;
var expr = single
? readExpressionOrReference(parser, [quote || ' ', '/', '>'])
: { m: readExpressionList(parser), t: ARRAY_LITERAL };
parser.inUnquotedAttribute = false;
parser.spreadArgs = spread;
if (quote) {
parser.sp();
if (parser.matchString(quote) !== quote) { parser.error(("Expected matching quote '" + quote + "'")); }
}
if (single) {
var interpolator = { t: INTERPOLATOR };
refineExpression(expr, interpolator);
attribute.f = [interpolator];
} else {
attribute.f = flattenExpression(expr);
}
}
var delimiterChangeToken = { t: DELIMCHANGE, exclude: true };
function readMustache(parser) {
var mustache, i;
// If we're inside a <script> or <style> tag, and we're not
// interpolating, bug out
if (parser.interpolate[parser.inside] === false) {
return null;
}
for (i = 0; i < parser.tags.length; i += 1) {
if ((mustache = readMustacheOfType(parser, parser.tags[i]))) {
return mustache;
}
}
if (parser.inTag && !parser.inAttribute) {
mustache = readAttributeOrDirective(parser);
if (mustache) {
parser.sp();
return mustache;
}
}
}
function readMustacheOfType(parser, tag) {
var mustache, reader, i;
var start = parser.pos;
if (parser.matchString('\\' + tag.open)) {
if (start === 0 || parser.str[start - 1] !== '\\') {
return tag.open;
}
} else if (!parser.matchString(tag.open)) {
return null;
}
// delimiter change?
if ((mustache = readDelimiterChange(parser))) {
// find closing delimiter or abort...
if (!parser.matchString(tag.close)) {
return null;
}
// ...then make the switch
tag.open = mustache[0];
tag.close = mustache[1];
parser.sortMustacheTags();
return delimiterChangeToken;
}
parser.sp();
// illegal section closer
if (parser.matchString('/')) {
parser.pos -= 1;
var rewind = parser.pos;
if (!readNumberLiteral(parser)) {
parser.pos = rewind - tag.close.length;
if (parser.inAttribute) {
parser.pos = start;
return null;
} else {
parser.error("Attempted to close a section that wasn't open");
}
} else {
parser.pos = rewind;
}
}
for (i = 0; i < tag.readers.length; i += 1) {
reader = tag.readers[i];
if ((mustache = reader(parser, tag))) {
if (tag.isStatic) {
mustache.s = 1;
}
if (parser.includeLinePositions) {
mustache.q = parser.getLinePos(start);
}
return mustache;
}
}
parser.pos = start;
return null;
}
function readTriple(parser, tag) {
var expression = readExpression(parser);
if (!expression) {
return null;
}
if (!parser.matchString(tag.close)) {
parser.error(("Expected closing delimiter '" + (tag.close) + "'"));
}
var triple = { t: TRIPLE };
refineExpression(expression, triple); // TODO handle this differently - it's mysterious
return triple;
}
function readUnescaped(parser, tag) {
if (!parser.matchString('&')) {
return null;
}
parser.sp();
var expression = readExpression(parser);
if (!expression) {
return null;
}
if (!parser.matchString(tag.close)) {
parser.error(("Expected closing delimiter '" + (tag.close) + "'"));
}
var triple = { t: TRIPLE };
refineExpression(expression, triple); // TODO handle this differently - it's mysterious
return triple;
}
var legalAlias = /^(?:[a-zA-Z$_0-9]|\\\.)+(?:(?:(?:[a-zA-Z$_0-9]|\\\.)+)|(?:\[[0-9]+\]))*/;
var asRE = /^as/i;
function readAliases(parser) {
var aliases = [];
var alias;
var start = parser.pos;
parser.sp();
alias = readAlias(parser);
if (alias) {
alias.x = refineExpression(alias.x, {});
aliases.push(alias);
parser.sp();
while (parser.matchString(',')) {
alias = readAlias(parser);
if (!alias) {
parser.error('Expected another alias.');
}
alias.x = refineExpression(alias.x, {});
aliases.push(alias);
parser.sp();
}
return aliases;
}
parser.pos = start;
return null;
}
function readAlias(parser) {
var start = parser.pos;
parser.sp();
var expr = readExpression(parser, []);
if (!expr) {
parser.pos = start;
return null;
}
parser.sp();
parser.matchPattern(asRE);
parser.sp();
var alias = parser.matchPattern(legalAlias);
if (!alias) {
parser.pos = start;
return null;
}
return { n: alias, x: expr };
}
function readPartial(parser, tag) {
var type = parser.matchString('>') || parser.matchString('yield');
var partial = { t: type === '>' ? PARTIAL : YIELDER };
var aliases;
if (!type) { return null; }
parser.sp();
if (type === '>' || !(aliases = parser.matchString('with'))) {
// Partial names can include hyphens, so we can't use readExpression
// blindly. Instead, we use the `relaxedNames` flag to indicate that
// `foo-bar` should be read as a single name, rather than 'subtract
// bar from foo'
parser.relaxedNames = parser.strictRefinement = true;
var expression = readExpression(parser);
parser.relaxedNames = parser.strictRefinement = false;
if (!expression && type === '>') { return null; }
if (expression) {
refineExpression(expression, partial); // TODO...
parser.sp();
if (type !== '>') { aliases = parser.matchString('with'); }
}
}
parser.sp();
// check for alias context e.g. `{{>foo bar as bat, bip as bop}}`
if (aliases || type === '>') {
aliases = readAliases(parser);
if (aliases && aliases.length) {
partial.z = aliases;
} else {
// otherwise check for literal context e.g. `{{>foo bar}}` then
// turn it into `{{#with bar}}{{>foo}}{{/with}}`
var context = readExpression(parser);
if (context) {
partial.c = {};
refineExpression(context, partial.c);
}
}
if (type !== '>' && (!partial.c && !partial.z)) {
// {{yield with}} requires some aliases
parser.error("Expected a context or one or more aliases");
}
}
parser.sp();
if (!parser.matchString(tag.close)) {
parser.error(("Expected closing delimiter '" + (tag.close) + "'"));
}
return partial;
}
function readComment(parser, tag) {
if (!parser.matchString('!')) {
return null;
}
var index = parser.remaining().indexOf(tag.close);
if (index !== -1) {
parser.pos += index + tag.close.length;
return { t: COMMENT };
}
}
function readInterpolator(parser, tag) {
var expression, err;
var start = parser.pos;
// TODO would be good for perf if we could do away with the try-catch
try {
expression = readExpressionOrReference(parser, [tag.close]);
} catch (e) {
err = e;
}
if (!expression) {
if (parser.str.charAt(start) === '!') {
// special case - comment
parser.pos = start;
return null;
}
if (err) {
throw err;
}
}
if (!parser.matchString(tag.close)) {
parser.error(("Expected closing delimiter '" + (tag.close) + "' after reference"));
if (!expression) {
// special case - comment
if (parser.nextChar() === '!') {
return null;
}
parser.error("Expected expression or legal reference");
}
}
var interpolator = { t: INTERPOLATOR };
refineExpression(expression, interpolator); // TODO handle this differently - it's mysterious
return interpolator;
}
function readClosing(parser, tag) {
var start = parser.pos;
if (!parser.matchString(tag.open)) {
return null;
}
parser.sp();
if (!parser.matchString('/')) {
parser.pos = start;
return null;
}
parser.sp();
var remaining = parser.remaining();
var index = remaining.indexOf(tag.close);
if (index !== -1) {
var closing = {
t: CLOSING,
r: remaining.substr(0, index).split(' ')[0]
};
parser.pos += index;
if (!parser.matchString(tag.close)) {
parser.error(("Expected closing delimiter '" + (tag.close) + "'"));
}
return closing;
}
parser.pos = start;
return null;
}
var patterns = {
else: /^\s*else\s*/,
elseif: /^\s*elseif\s+/,
then: /^\s*then\s*/,
catch: /^\s*catch\s*/
};
var types = {
else: ELSE,
elseif: ELSEIF,
then: THEN,
catch: CATCH
};
function readInlineBlock(parser, tag, type) {
var start = parser.pos;
if (!parser.matchString(tag.open)) {
return null;
}
if (!parser.matchPattern(patterns[type])) {
parser.pos = start;
return null;
}
var res = { t: types[type] };
if (type === 'elseif') {
res.x = readExpression(parser);
} else if (type === 'catch' || type === 'then') {
var nm = parser.matchPattern(name);
if (nm) { res.n = nm; }
}
if (!parser.matchString(tag.close)) {
parser.error(("Expected closing delimiter '" + (tag.close) + "'"));
}
return res;
}
var handlebarsBlockCodes = {
each: SECTION_EACH,
if: SECTION_IF,
with: SECTION_IF_WITH,
unless: SECTION_UNLESS
};
var indexRefPattern = /^\s*:\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/;
var keyIndexRefPattern = /^\s*,\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/;
var handlebarsBlockPattern = new RegExp('^(' + keys(handlebarsBlockCodes).join('|') + ')\\b');
function readSection(parser, tag) {
var expression,
section,
child,
children,
hasElse,
block,
unlessBlock,
closed,
i,
expectedClose,
hasThen,
hasCatch,
inlineThen;
var aliasOnly = false;
var start = parser.pos;
if (parser.matchString('^')) {
// watch out for parent context refs - {{^^/^^/foo}}
if (parser.matchString('^/')) {
parser.pos = start;
return null;
}
section = { t: SECTION, f: [], n: SECTION_UNLESS };
} else if (parser.matchString('#')) {
section = { t: SECTION, f: [] };
if (parser.matchString('partial')) {
parser.pos = start - parser.standardDelimiters[0].length;
parser.error(
'Partial definitions can only be at the top level of the template, or immediately inside components'
);
}
if ((block = parser.matchString('await'))) {
expectedClose = block;
section.t = AWAIT;
} else if ((block = parser.matchPattern(handlebarsBlockPattern))) {
expectedClose = block;
section.n = handlebarsBlockCodes[block];
}
} else {
return null;
}
parser.sp();
if (block === 'with') {
var aliases = readAliases(parser);
if (aliases) {
aliasOnly = true;
section.z = aliases;
section.t = ALIAS;
}
} else if (block === 'each') {
var alias = readAlias(parser);
if (alias) {
section.z = [{ n: alias.n, x: { r: '.' } }];
expression = alias.x;
}
}
if (!aliasOnly) {
if (!expression) { expression = readExpression(parser); }
if (!expression) {
parser.error('Expected expression');
}
// extra each aliases
if (block === 'each' && parser.matchString(',')) {
var aliases$1 = readAliases(parser);
if (aliases$1) {
if (section.z) { aliases$1.unshift(section.z[0]); }
section.z = aliases$1;
}
}
// optional index and key references
if ((block === 'each' || !block) && (i = parser.matchPattern(indexRefPattern))) {
var extra;
if ((extra = parser.matchPattern(keyIndexRefPattern))) {
section.i = i + ',' + extra;
} else {
section.i = i;
}
} else if (block === 'await' && parser.matchString('then')) {
parser.sp();
hasThen = true;
inlineThen = parser.matchPattern(name);
if (!inlineThen) { inlineThen = true; }
}
if (!block && expression.n) {
expectedClose = expression.n;
}
}
parser.sp();
if (!parser.matchString(tag.close)) {
parser.error(("Expected closing delimiter '" + (tag.close) + "'"));
}
parser.sectionDepth += 1;
children = section.f;
var pos;
do {
pos = parser.pos;
if ((child = readClosing(parser, tag))) {
if (expectedClose && child.r !== expectedClose) {
if (!block) {
if (child.r)
{ parser.warn(
("Expected " + (tag.open) + "/" + expectedClose + (tag.close) + " but found " + (tag.open) + "/" + (child.r) + (tag.close))
); }
} else {
parser.pos = pos;
parser.error(("Expected " + (tag.open) + "/" + expectedClose + (tag.close)));
}
}
parser.sectionDepth -= 1;
closed = true;
} else if (
!aliasOnly &&
((child = readInlineBlock(parser, tag, 'elseif')) ||
(child = readInlineBlock(parser, tag, 'else')) ||
(block === 'await' &&
((child = readInlineBlock(parser, tag, 'then')) ||
(child = readInlineBlock(parser, tag, 'catch')))))
) {
if (section.n === SECTION_UNLESS) {
parser.error('{{else}} not allowed in {{#unless}}');
}
if (hasElse) {
if (child.t === ELSE) {
parser.error('there can only be one {{else}} block, at the end of a section');
} else if (child.t === ELSEIF) {
parser.error('illegal {{elseif...}} after {{else}}');
}
}
if (!unlessBlock && (inlineThen || !hasThen) && !hasCatch) {
if (block === 'await') {
var s = { f: children };
section.f = [s];
if (inlineThen) {
s.t = THEN;
inlineThen !== true && (s.n = inlineThen);
} else {
s.t = SECTION;
}
} else {
unlessBlock = [];
}
}
var mustache = {
t: SECTION,
f: (children = [])
};
if (child.t === ELSE) {
if (block === 'await') {
section.f.push(mustache);
mustache.t = ELSE;
} else {
mustache.n = SECTION_UNLESS;
unlessBlock.push(mustache);
}
hasElse = true;
} else if (child.t === ELSEIF) {
mustache.n = SECTION_IF;
refineExpression(child.x, mustache);
unlessBlock.push(mustache);
} else if (child.t === THEN) {
if (hasElse) { parser.error('{{then}} block must appear before any {{else}} block'); }
if (hasCatch) { parser.error('{{then}} block must appear before any {{catch}} block'); }
if (hasThen) { parser.error('there can only be one {{then}} block per {{#await}}'); }
mustache.t = THEN;
hasThen = true;
child.n && (mustache.n = child.n);
section.f.push(mustache);
} else if (child.t === CATCH) {
if (hasElse) { parser.error('{{catch}} block must appear before any {{else}} block'); }
if (hasCatch) { parser.error('there can only be one {{catch}} block per {{#await}}'); }
mustache.t = CATCH;
hasCatch = true;
mustache.n = child.n;
section.f.push(mustache);
}
} else {
child = parser.read(READERS);
if (!child) {
break;
}
children.push(child);
}
} while (!closed);
if (unlessBlock) {
section.l = unlessBlock;
}
if (!aliasOnly) {
refineExpression(expression, section);
}
if (block === 'await' && (inlineThen || !hasThen) && !hasCatch && !hasElse) {
var s$1 = { f: section.f };
section.f = [s$1];
if (inlineThen) {
s$1.t = THEN;
inlineThen !== true && (s$1.n = inlineThen);
} else {
s$1.t = SECTION;
}
}
// TODO if a section is empty it should be discarded. Don't do
// that here though - we need to clean everything up first, as
// it may contain removeable whitespace. As a temporary measure,
// to pass the existing tests, remove empty `f` arrays
if (!section.f.length) {
delete section.f;
}
return section;
}
var OPEN_COMMENT = '<!--';
var CLOSE_COMMENT = '-->';
function readHtmlComment(parser) {
var start = parser.pos;
if (parser.textOnlyMode || !parser.matchString(OPEN_COMMENT)) {
return null;
}
var remaining = parser.remaining();
var endIndex = remaining.indexOf(CLOSE_COMMENT);
if (endIndex === -1) {
parser.error("Illegal HTML - expected closing comment sequence ('-->')");
}
var content = remaining.substr(0, endIndex);
parser.pos += endIndex + 3;
var comment = {
t: COMMENT,
c: content
};
if (parser.includeLinePositions) {
comment.q = parser.getLinePos(start);
}
return comment;
}
var leadingLinebreak = /^[ \t\f\r\n]*\r?\n/;
var trailingLinebreak = /\r?\n[ \t\f\r\n]*$/;
function stripStandalones(items) {
var i, current, backOne, backTwo, lastSectionItem;
for (i = 1; i < items.length; i += 1) {
current = items[i];
backOne = items[i - 1];
backTwo = items[i - 2];
// if we're at the end of a [text][comment][text] sequence...
if (isString(current) && isComment(backOne) && isString(backTwo)) {
// ... and the comment is a standalone (i.e. line breaks either side)...
if (trailingLinebreak.test(backTwo) && leadingLinebreak.test(current)) {
// ... then we want to remove the whitespace after the first line break
items[i - 2] = backTwo.replace(trailingLinebreak, '\n');
// and the leading line break of the second text token
items[i] = current.replace(leadingLinebreak, '');
}
}
// if the current item is a section, and it is preceded by a linebreak, and
// its first item is a linebreak...
if (isSection(current) && isString(backOne)) {
if (
trailingLinebreak.test(backOne) &&
isString(current.f[0]) &&
leadingLinebreak.test(current.f[0])
) {
items[i - 1] = backOne.replace(trailingLinebreak, '\n');
current.f[0] = current.f[0].replace(leadingLinebreak, '');
}
}
// if the last item was a section, and it is followed by a linebreak, and
// its last item is a linebreak...
if (isString(current) && isSection(backOne)) {
lastSectionItem = lastItem(backOne.f);
if (
isString(lastSectionItem) &&
trailingLinebreak.test(lastSectionItem) &&
leadingLinebreak.test(current)
) {
backOne.f[backOne.f.length - 1] = lastSectionItem.replace(trailingLinebreak, '\n');
items[i] = current.replace(leadingLinebreak, '');
}
}
}
return items;
}
function isComment(item) {
return item.t === COMMENT || item.t === DELIMCHANGE;
}
function isSection(item) {
return (item.t === SECTION || item.t === INVERTED) && item.f;
}
function trimWhitespace(items, leadingPattern, trailingPattern) {
var item;
if (leadingPattern) {
item = items[0];
if (isString(item)) {
item = item.replace(leadingPattern, '');
if (!item) {
items.shift();
} else {
items[0] = item;
}
}
}
if (trailingPattern) {
item = lastItem(items);
if (isString(item)) {
item = item.replace(trailingPattern, '');
if (!item) {
items.pop();
} else {
items[items.length - 1] = item;
}
}
}
}
var contiguousWhitespace = /[ \t\f\r\n]+/g;
var leadingWhitespace$1 = /^[ \t\f\r\n]+/;
var trailingWhitespace = /[ \t\f\r\n]+$/;
var leadingNewLine = /^(?:\r\n|\r|\n)/;
var trailingNewLine = /(?:\r\n|\r|\n)$/;
function cleanup(
items,
stripComments,
preserveWhitespace,
removeLeadingWhitespace,
removeTrailingWhitespace,
whiteSpaceElements
) {
if (isString(items)) { return; }
var i,
item,
previousItem,
nextItem,
preserveWhitespaceInsideFragment,
removeLeadingWhitespaceInsideFragment,
removeTrailingWhitespaceInsideFragment;
// First pass - remove standalones and comments etc
stripStandalones(items);
i = items.length;
while (i--) {
item = items[i];
// Remove delimiter changes, unsafe elements etc
if (item.exclude) {
items.splice(i, 1);
} else if (stripComments && item.t === COMMENT) {
// Remove comments, unless we want to keep them
items.splice(i, 1);
}
}
// If necessary, remove leading and trailing whitespace
trimWhitespace(
items,
removeLeadingWhitespace ? leadingWhitespace$1 : null,
removeTrailingWhitespace ? trailingWhitespace : null
);
i = items.length;
while (i--) {
item = items[i];
removeLeadingWhitespaceInsideFragment = removeTrailingWhitespaceInsideFragment = false;
// Recurse
if (item.f) {
var isPreserveWhitespaceElement =
item.t === ELEMENT &&
(whiteSpaceElements[item.e.toLowerCase()] || whiteSpaceElements[item.e]);
preserveWhitespaceInsideFragment = preserveWhitespace || isPreserveWhitespaceElement;
if (!preserveWhitespace && isPreserveWhitespaceElement) {
trimWhitespace(item.f, leadingNewLine, trailingNewLine);
}
if (!preserveWhitespaceInsideFragment) {
previousItem = items[i - 1];
nextItem = items[i + 1];
// if the previous item was a text item with trailing whitespace,
// remove leading whitespace inside the fragment
if (!previousItem || (isString(previousItem) && trailingWhitespace.test(previousItem))) {
removeLeadingWhitespaceInsideFragment = true;
}
// and vice versa
if (!nextItem || (isString(nextItem) && leadingWhitespace$1.test(nextItem))) {
removeTrailingWhitespaceInsideFragment = true;
}
}
cleanup(
item.f,
stripComments,
preserveWhitespaceInsideFragment,
removeLeadingWhitespaceInsideFragment,
removeTrailingWhitespaceInsideFragment,
whiteSpaceElements
);
}
// Split if-else blocks into two (an if, and an unless)
if (item.l) {
cleanup(
item.l,
stripComments,
preserveWhitespace,
removeLeadingWhitespaceInsideFragment,
removeTrailingWhitespaceInsideFragment,
whiteSpaceElements
);
item.l.forEach(function (s) { return (s.l = 1); });
item.l.unshift(i + 1, 0);
items.splice.apply(items, item.l);
delete item.l; // TODO would be nice if there was a way around this
}
// Clean up conditional attributes
if (item.m) {
cleanup(
item.m,
stripComments,
preserveWhitespace,
removeLeadingWhitespaceInsideFragment,
removeTrailingWhitespaceInsideFragment,
whiteSpaceElements
);
if (item.m.length < 1) { delete item.m; }
}
}
// final pass - fuse text nodes together
i = items.length;
while (i--) {
if (isString(items[i])) {
if (isString(items[i + 1])) {
items[i] = items[i] + items[i + 1];
items.splice(i + 1, 1);
}
if (!preserveWhitespace) {
items[i] = items[i].replace(contiguousWhitespace, ' ');
}
if (items[i] === '') {
items.splice(i, 1);
}
}
}
}
var closingTagPattern = /^([a-zA-Z]{1,}:?[a-zA-Z0-9\-]*)\s*\>/;
function readClosingTag(parser) {
var tag;
var start = parser.pos;
// are we looking at a closing tag?
if (!parser.matchString('</')) {
return null;
}
if ((tag = parser.matchPattern(closingTagPattern))) {
if (parser.inside && tag !== parser.inside) {
parser.pos = start;
return null;
}
return {
t: CLOSING_TAG,
e: tag
};
}
// We have an illegal closing tag, report it
parser.pos -= 2;
parser.error('Illegal closing tag');
}
function hyphenateCamel(camelCaseStr) {
return camelCaseStr.replace(/([A-Z])/g, function (match, $1) {
return '-' + $1.toLowerCase();
});
}
var tagNamePattern = /^[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/;
var anchorPattern = /^[a-zA-Z_$][-a-zA-Z0-9_$]*/;
var validTagNameFollower = /^[\s\n\/>]/;
var semiEnd = /;\s*$/;
var exclude = { exclude: true };
// based on http://developers.whatwg.org/syntax.html#syntax-tag-omission
var disallowedContents = {
li: ['li'],
dt: ['dt', 'dd'],
dd: ['dt', 'dd'],
p: 'address article aside blockquote div dl fieldset footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p pre section table ul'.split(
' '
),
rt: ['rt', 'rp'],
rp: ['rt', 'rp'],
optgroup: ['optgroup'],
option: ['option', 'optgroup'],
thead: ['tbody', 'tfoot'],
tbody: ['tbody', 'tfoot'],
tfoot: ['tbody'],
tr: ['tr', 'tbody'],
td: ['td', 'th', 'tr'],
th: ['td', 'th', 'tr']
};
function readElement$1(parser) {
var attribute,
selfClosing,
children,
partials,
hasPartials,
child,
closed,
pos,
remaining,
closingTag,
anchor;
var start = parser.pos;
if (parser.inside || parser.inAttribute || parser.textOnlyMode) {
return null;
}
if (!parser.matchString('<')) {
return null;
}
// if this is a closing tag, abort straight away
if (parser.nextChar() === '/') {
return null;
}
var element = {};
if (parser.includeLinePositions) {
element.q = parser.getLinePos(start);
}
// check for doctype decl
if (parser.matchString('!')) {
element.t = DOCTYPE;
if (!parser.matchPattern(/^doctype/i)) {
parser.error('Expected DOCTYPE declaration');
}
element.a = parser.matchPattern(/^(.+?)>/);
return element;
} else if ((anchor = parser.matchString('#'))) {
// check for anchor
parser.sp();
element.t = ANCHOR;
element.n = parser.matchPattern(anchorPattern);
} else {
// otherwise, it's an element/component
element.t = ELEMENT;
// element name
element.e = parser.matchPattern(tagNamePattern);
if (!element.e) {
return null;
}
}
// next character must be whitespace, closing solidus or '>'
if (!validTagNameFollower.test(parser.nextChar())) {
parser.error('Illegal tag name');
}
parser.sp();
parser.inTag = true;
// directives and attributes
while ((attribute = readMustache(parser))) {
if (attribute !== false) {
if (!element.m) { element.m = []; }
element.m.push(attribute);
}
parser.sp();
}
parser.inTag = false;
// allow whitespace before closing solidus
parser.sp();
// self-closing solidus?
if (parser.matchString('/')) {
selfClosing = true;
}
// closing angle bracket
if (!parser.matchString('>')) {
return null;
}
var lowerCaseName = (element.e || element.n).toLowerCase();
var preserveWhitespace = parser.preserveWhitespace;
if (!selfClosing && (anchor || !voidElements[element.e.toLowerCase()])) {
if (!anchor) {
parser.elementStack.push(lowerCaseName);
// Special case - if we open a script element, further tags should
// be ignored unless they're a closing script element
if (lowerCaseName in parser.interpolate) {
parser.inside = lowerCaseName;
}
}
children = [];
partials = create(null);
do {
pos = parser.pos;
remaining = parser.remaining();
if (!remaining) {
// if this happens to be a script tag and there's no content left, it's because
// a closing script tag can't appear in a script
if (parser.inside === 'script') {
closed = true;
break;
}
parser.error(
("Missing end " + (parser.elementStack.length > 1 ? 'tags' : 'tag') + " (" + (parser.elementStack
.reverse()
.map(function (x) { return ("</" + x + ">"); })
.join('')) + ")")
);
}
// if for example we're in an <li> element, and we see another
// <li> tag, close the first so they become siblings
if (!anchor && !canContain(lowerCaseName, remaining)) {
closed = true;
} else if (!anchor && (closingTag = readClosingTag(parser))) {
// closing tag
closed = true;
var closingTagName = closingTag.e.toLowerCase();
// if this *isn't* the closing tag for the current element...
if (closingTagName !== lowerCaseName) {
// rewind parser
parser.pos = pos;
// if it doesn't close a parent tag, error
if (!~parser.elementStack.indexOf(closingTagName)) {
var errorMessage = 'Unexpected closing tag';
// add additional help for void elements, since component names
// might clash with them
if (voidElements[closingTagName.toLowerCase()]) {
errorMessage += " (<" + closingTagName + "> is a void element - it cannot contain children)";
}
parser.error(errorMessage);
}
}
} else if (anchor && readAnchorClose(parser, element.n)) {
closed = true;
} else {
// implicit close by closing section tag. TODO clean this up
var tag = {
open: parser.standardDelimiters[0],
close: parser.standardDelimiters[1]
};
if (readClosing(parser, tag) || readInline(parser, tag)) {
closed = true;
parser.pos = pos;
} else if ((child = parser.read(PARTIAL_READERS))) {
if (partials[child.n]) {
parser.pos = pos;
parser.error('Duplicate partial definition');
}
cleanup(
child.f,
parser.stripComments,
preserveWhitespace,
!preserveWhitespace,
!preserveWhitespace,
parser.whiteSpaceElements
);
partials[child.n] = child.f;
hasPartials = true;
} else {
if ((child = parser.read(READERS))) {
children.push(child);
} else {
closed = true;
}
}
}
} while (!closed);
if (children.length) {
element.f = children;
}
if (hasPartials) {
element.p = partials;
}
parser.elementStack.pop();
}
parser.inside = null;
if (parser.sanitizeElements && parser.sanitizeElements.indexOf(lowerCaseName) !== -1) {
return exclude;
}
if (
element.m &&
lowerCaseName !== 'input' &&
lowerCaseName !== 'select' &&
lowerCaseName !== 'textarea' &&
lowerCaseName !== 'option'
) {
var attrs = element.m;
var classes, styles, cls, style;
var i = 0;
var a;
while (i < attrs.length) {
a = attrs[i];
if (a.t !== ATTRIBUTE) {
i++;
continue;
}
if (a.n.indexOf('class-') === 0 && !a.f) {
// static class directives
(classes || (classes = [])).push(a.n.slice(6));
attrs.splice(i, 1);
} else if (a.n.indexOf('style-') === 0 && isString(a.f)) {
// static style directives
(styles || (styles = [])).push(((hyphenateCamel(a.n.slice(6))) + ": " + (a.f) + ";"));
attrs.splice(i, 1);
} else if (a.n === 'class' && isString(a.f)) {
// static class attrs
(classes || (classes = [])).push(a.f);
attrs.splice(i, 1);
} else if (a.n === 'style' && isString(a.f)) {
// static style attrs
(styles || (styles = [])).push(a.f + (semiEnd.test(a.f) ? '' : ';'));
attrs.splice(i, 1);
} else if (a.n === 'class') {
cls = a;
i++;
} else if (a.n === 'style') {
style = a;
i++;
} else if (
!~a.n.indexOf(':') &&
a.n !== 'value' &&
a.n !== 'contenteditable' &&
isString(a.f)
) {
a.g = 1;
i++;
} else {
i++;
}
}
if (classes) {
if (!cls || !isString(cls.f))
{ attrs.unshift({ t: ATTRIBUTE, n: 'class', f: classes.join(' '), g: 1 }); }
else { cls.f += ' ' + classes.join(' '); }
} else if (cls && isString(cls.f)) { cls.g = 1; }
if (styles) {
if (!style || !isString(style.f))
{ attrs.unshift({ t: ATTRIBUTE, n: 'style', f: styles.join(' '), g: 1 }); }
else { style.f += '; ' + styles.join(' '); }
} else if (style && isString(style.f)) { style.g = 1; }
}
return element;
}
function canContain(name, remaining) {
var match = /^<([a-zA-Z][a-zA-Z0-9]*)/.exec(remaining);
var disallowed = disallowedContents[name];
if (!match || !disallowed) {
return true;
}
return !~disallowed.indexOf(match[1].toLowerCase());
}
function readAnchorClose(parser, name) {
var pos = parser.pos;
if (!parser.matchString('</')) {
return null;
}
parser.matchString('#');
parser.sp();
if (!parser.matchString(name)) {
parser.pos = pos;
return null;
}
parser.sp();
if (!parser.matchString('>')) {
parser.pos = pos;
return null;
}
return true;
}
var inlines = /^\s*(elseif|else|then|catch)\s*/;
function readInline(parser, tag) {
var pos = parser.pos;
if (!parser.matchString(tag.open)) { return; }
if (parser.matchPattern(inlines)) {
return true;
} else {
parser.pos = pos;
}
}
function readText(parser) {
var index, disallowed, barrier;
var remaining = parser.remaining();
if (parser.textOnlyMode) {
disallowed = parser.tags.map(function (t) { return t.open; });
disallowed = disallowed.concat(parser.tags.map(function (t) { return '\\' + t.open; }));
index = getLowestIndex(remaining, disallowed);
} else {
barrier = parser.inside ? '</' + parser.inside : '<';
if (parser.inside && !parser.interpolate[parser.inside]) {
index = remaining.indexOf(barrier);
} else {
disallowed = parser.tags.map(function (t) { return t.open; });
disallowed = disallowed.concat(parser.tags.map(function (t) { return '\\' + t.open; }));
// http://developers.whatwg.org/syntax.html#syntax-attributes
if (parser.inAttribute === true) {
// we're inside an unquoted attribute value
disallowed.push("\"", "'", "=", "<", ">", '`');
} else if (parser.inAttribute) {
// quoted attribute value
disallowed.push(parser.inAttribute);
} else {
disallowed.push(barrier);
}
index = getLowestIndex(remaining, disallowed);
}
}
if (!index) {
return null;
}
if (index === -1) {
index = remaining.length;
}
parser.pos += index;
if ((parser.inside && parser.inside !== 'textarea') || parser.textOnlyMode) {
return remaining.substr(0, index);
} else {
return decodeCharacterReferences(remaining.substr(0, index));
}
}
var partialDefinitionSectionPattern = /^\s*#\s*partial\s+/;
function readPartialDefinitionSection(parser) {
var child, closed;
var start = parser.pos;
var delimiters = parser.standardDelimiters;
if (!parser.matchString(delimiters[0])) {
return null;
}
if (!parser.matchPattern(partialDefinitionSectionPattern)) {
parser.pos = start;
return null;
}
var name = parser.matchPattern(/^[a-zA-Z_$][a-zA-Z_$0-9\-\/]*/);
if (!name) {
parser.error('expected legal partial name');
}
parser.sp();
if (!parser.matchString(delimiters[1])) {
parser.error(("Expected closing delimiter '" + (delimiters[1]) + "'"));
}
var content = [];
var open = delimiters[0];
var close = delimiters[1];
do {
if ((child = readClosing(parser, { open: open, close: close }))) {
if (child.r !== 'partial') {
parser.error(("Expected " + open + "/partial" + close));
}
closed = true;
} else {
child = parser.read(READERS);
if (!child) {
parser.error(("Expected " + open + "/partial" + close));
}
content.push(child);
}
} while (!closed);
return {
t: INLINE_PARTIAL,
n: name,
f: content
};
}
function readTemplate(parser) {
var fragment = [];
var partials = create(null);
var hasPartials = false;
var preserveWhitespace = parser.preserveWhitespace;
while (parser.pos < parser.str.length) {
var pos = parser.pos;
var item = (void 0), partial = (void 0);
if ((partial = parser.read(PARTIAL_READERS))) {
if (partials[partial.n]) {
parser.pos = pos;
parser.error('Duplicated partial definition');
}
cleanup(
partial.f,
parser.stripComments,
preserveWhitespace,
!preserveWhitespace,
!preserveWhitespace,
parser.whiteSpaceElements
);
partials[partial.n] = partial.f;
hasPartials = true;
} else if ((item = parser.read(READERS))) {
fragment.push(item);
} else {
parser.error('Unexpected template content');
}
}
var result = {
v: TEMPLATE_VERSION,
t: fragment
};
if (hasPartials) {
result.p = partials;
}
return result;
}
function insertExpressions(obj, expr) {
keys(obj).forEach(function (key) {
if (isExpression(key, obj)) { return addTo(obj, expr); }
var ref = obj[key];
if (hasChildren(ref)) { insertExpressions(ref, expr); }
});
}
function isExpression(key, obj) {
return key === 's' && isArray(obj.r);
}
function addTo(obj, expr) {
var s = obj.s;
var r = obj.r;
if (!expr[s]) { expr[s] = fromExpression(s, r.length); }
}
function hasChildren(ref) {
return isArray(ref) || isObject(ref);
}
var shared = {};
// See https://github.com/ractivejs/template-spec for information
// about the Ractive template specification
var STANDARD_READERS = [
readPartial,
readUnescaped,
readSection,
readInterpolator,
readComment
];
var TRIPLE_READERS = [readTriple];
var READERS = [readMustache, readHtmlComment, readElement$1, readText];
var PARTIAL_READERS = [readPartialDefinitionSection];
var preserveWhitespaceElements = { pre: 1, script: 1, style: 1, textarea: 1 };
var defaultInterpolate = { textarea: true, script: true, style: true, template: true };
var StandardParser = Parser.extend({
init: function init(str, options) {
var tripleDelimiters = options.tripleDelimiters || shared.defaults.tripleDelimiters;
var staticDelimiters = options.staticDelimiters || shared.defaults.staticDelimiters;
var staticTripleDelimiters =
options.staticTripleDelimiters || shared.defaults.staticTripleDelimiters;
this.standardDelimiters = options.delimiters || shared.defaults.delimiters;
this.tags = [
{
isStatic: false,
isTriple: false,
open: this.standardDelimiters[0],
close: this.standardDelimiters[1],
readers: STANDARD_READERS
},
{
isStatic: false,
isTriple: true,
open: tripleDelimiters[0],
close: tripleDelimiters[1],
readers: TRIPLE_READERS
},
{
isStatic: true,
isTriple: false,
open: staticDelimiters[0],
close: staticDelimiters[1],
readers: STANDARD_READERS
},
{
isStatic: true,
isTriple: true,
open: staticTripleDelimiters[0],
close: staticTripleDelimiters[1],
readers: TRIPLE_READERS
}
];
this.contextLines = options.contextLines || shared.defaults.contextLines;
this.sortMustacheTags();
this.sectionDepth = 0;
this.elementStack = [];
this.interpolate = assign(
{},
defaultInterpolate,
shared.defaults.interpolate,
options.interpolate
);
if (options.sanitize === true) {
options.sanitize = {
// blacklist from https://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/lang/html/html4-elements-whitelist.json
elements: 'applet base basefont body frame frameset head html isindex link meta noframes noscript object param script style title'.split(
' '
),
eventAttributes: true
};
}
this.stripComments = options.stripComments !== false;
this.preserveWhitespace = isObjectType(options.preserveWhitespace)
? false
: options.preserveWhitespace;
this.sanitizeElements = options.sanitize && options.sanitize.elements;
this.sanitizeEventAttributes = options.sanitize && options.sanitize.eventAttributes;
this.includeLinePositions = options.includeLinePositions;
this.textOnlyMode = options.textOnlyMode;
this.csp = options.csp;
this.allowExpressions = options.allowExpressions;
if (options.expression) { this.converters = [readExpression]; }
if (options.attributes) { this.inTag = true; }
// special whitespace handling requested for certain elements
this.whiteSpaceElements = assign({}, options.preserveWhitespace, preserveWhitespaceElements);
},
postProcess: function postProcess(result, options) {
var parserResult = result[0];
if (options.expression) {
var expr = flattenExpression(parserResult);
expr.e = fromExpression(expr.s, expr.r.length);
return expr;
} else {
// special case - empty string
if (!result.length) {
return { t: [], v: TEMPLATE_VERSION };
}
if (this.sectionDepth > 0) {
this.error('A section was left open');
}
cleanup(
parserResult.t,
this.stripComments,
this.preserveWhitespace,
!this.preserveWhitespace,
!this.preserveWhitespace,
this.whiteSpaceElements
);
if (this.csp !== false) {
var expr$1 = {};
insertExpressions(parserResult.t, expr$1);
insertExpressions(parserResult.p || {}, expr$1);
if (keys(expr$1).length) { parserResult.e = expr$1; }
}
return parserResult;
}
},
converters: [readTemplate],
sortMustacheTags: function sortMustacheTags() {
// Sort in order of descending opening delimiter length (longer first),
// to protect against opening delimiters being substrings of each other
this.tags.sort(function (a, b) {
return b.open.length - a.open.length;
});
}
});
function parse(template, options) {
return new StandardParser(template, options || {}).result;
}
var parseOptions = [
'delimiters',
'tripleDelimiters',
'staticDelimiters',
'staticTripleDelimiters',
'csp',
'interpolate',
'preserveWhitespace',
'sanitize',
'stripComments',
'contextLines',
'allowExpressions',
'attributes'
];
var TEMPLATE_INSTRUCTIONS = "Either preparse or use a ractive runtime source that includes the parser. ";
var COMPUTATION_INSTRUCTIONS = "Either include a version of Ractive that can parse or convert your computation strings to functions.";
function throwNoParse(method, error, instructions) {
if (!method) {
fatal(("Missing Ractive.parse - cannot parse " + error + ". " + instructions));
}
}
function createFunction(body, length) {
throwNoParse(fromExpression, 'new expression function', TEMPLATE_INSTRUCTIONS);
return fromExpression(body, length);
}
function createFunctionFromString(str, bindTo) {
throwNoParse(parse, 'compution string "${str}"', COMPUTATION_INSTRUCTIONS);
var tpl = parse(str, { expression: true });
return function() {
return tpl.e.apply(bindTo, tpl.r.map(function (r) { return bindTo.get(r); }));
};
}
var parser = {
fromId: function fromId(id, options) {
if (!doc) {
if (options && options.noThrow) {
return;
}
throw new Error(("Cannot retrieve template #" + id + " as Ractive is not running in a browser."));
}
if (id) { id = id.replace(/^#/, ''); }
var template;
if (!(template = doc.getElementById(id))) {
if (options && options.noThrow) {
return;
}
throw new Error(("Could not find template element with id #" + id));
}
if (template.tagName.toUpperCase() !== 'SCRIPT') {
if (options && options.noThrow) {
return;
}
throw new Error(("Template element with id #" + id + ", must be a <script> element"));
}
return 'textContent' in template ? template.textContent : template.innerHTML;
},
isParsed: function isParsed(template) {
return !isString(template);
},
getParseOptions: function getParseOptions(ractive) {
// Could be Ractive or a Component
if (ractive.defaults) {
ractive = ractive.defaults;
}
return parseOptions.reduce(function (val, key) {
val[key] = ractive[key];
return val;
}, {});
},
parse: function parse$1(template, options) {
throwNoParse(parse, 'template', TEMPLATE_INSTRUCTIONS);
var parsed = parse(template, options);
addFunctions(parsed);
return parsed;
},
parseFor: function parseFor(template, ractive) {
return this.parse(template, this.getParseOptions(ractive));
}
};
function getComputationSignature(ractive, key, signature) {
var getter;
var setter;
// useful for debugging
var getterString;
var getterUseStack;
var setterString;
if (isFunction(signature)) {
getter = bind(signature, ractive);
getterString = signature.toString();
getterUseStack = true;
}
if (isString(signature)) {
getter = createFunctionFromString(signature, ractive);
getterString = signature;
}
if (isObjectType(signature)) {
if (isString(signature.get)) {
getter = createFunctionFromString(signature.get, ractive);
getterString = signature.get;
} else if (isFunction(signature.get)) {
getter = bind(signature.get, ractive);
getterString = signature.get.toString();
getterUseStack = true;
} else {
fatal('`%s` computation must have a `get()` method', key);
}
if (isFunction(signature.set)) {
setter = bind(signature.set, ractive);
setterString = signature.set.toString();
}
}
return {
getter: getter,
setter: setter,
getterString: getterString,
setterString: setterString,
getterUseStack: getterUseStack
};
}
var id = 0;
var TransitionManager = function TransitionManager(callback, parent) {
this.callback = callback;
this.parent = parent;
this.intros = [];
this.outros = [];
this.children = [];
this.totalChildren = this.outroChildren = 0;
this.detachQueue = [];
this.outrosComplete = false;
this.id = id++;
if (parent) {
parent.addChild(this);
}
};
var TransitionManager__proto__ = TransitionManager.prototype;
TransitionManager__proto__.add = function add (transition) {
var list = transition.isIntro ? this.intros : this.outros;
transition.starting = true;
list.push(transition);
};
TransitionManager__proto__.addChild = function addChild (child) {
this.children.push(child);
this.totalChildren += 1;
this.outroChildren += 1;
};
TransitionManager__proto__.checkStart = function checkStart () {
if (this.parent && this.parent.started) { this.start(); }
};
TransitionManager__proto__.decrementOutros = function decrementOutros () {
this.outroChildren -= 1;
check(this);
};
TransitionManager__proto__.decrementTotal = function decrementTotal () {
this.totalChildren -= 1;
check(this);
};
TransitionManager__proto__.detachNodes = function detachNodes () {
var this$1 = this;
var len = this.detachQueue.length;
for (var i = 0; i < len; i++) { this$1.detachQueue[i].detach(); }
len = this.children.length;
for (var i$1 = 0; i$1 < len; i$1++) { this$1.children[i$1].detachNodes(); }
this.detachQueue = [];
};
TransitionManager__proto__.ready = function ready () {
if (this.detachQueue.length) { detachImmediate(this); }
};
TransitionManager__proto__.remove = function remove (transition) {
var list = transition.isIntro ? this.intros : this.outros;
removeFromArray(list, transition);
check(this);
};
TransitionManager__proto__.start = function start () {
this.started = true;
this.children.forEach(function (c) { return c.start(); });
this.intros.concat(this.outros).forEach(function (t) { return t.start(); });
check(this);
};
function check(tm) {
if (!tm.started || tm.outros.length || tm.outroChildren) { return; }
// If all outros are complete, and we haven't already done this,
// we notify the parent if there is one, otherwise
// start detaching nodes
if (!tm.outrosComplete) {
tm.outrosComplete = true;
if (tm.parent) { tm.parent.decrementOutros(tm); }
if (!tm.parent || tm.parent.outrosComplete) {
tm.detachNodes();
}
}
// Once everything is done, we can notify parent transition
// manager and call the callback
if (!tm.intros.length && !tm.totalChildren) {
if (isFunction(tm.callback)) {
tm.callback();
}
if (tm.parent && !tm.notifiedTotal) {
tm.notifiedTotal = true;
tm.parent.decrementTotal();
}
}
}
// check through the detach queue to see if a node is up or downstream from a
// transition and if not, go ahead and detach it
function detachImmediate(manager) {
var queue = manager.detachQueue;
var outros = collectAllOutros(manager);
if (!outros.length) {
manager.detachNodes();
} else {
var i = queue.length;
var j = 0;
var node, trans;
var nqueue = (manager.detachQueue = []);
start: while (i--) {
node = queue[i].node;
j = outros.length;
while (j--) {
trans = outros[j].element.node;
// check to see if the node is, contains, or is contained by the transitioning node
if (trans === node || trans.contains(node) || node.contains(trans)) {
nqueue.push(queue[i]);
continue start;
}
}
// no match, we can drop it
queue[i].detach();
}
}
}
function collectAllOutros(manager, _list) {
var list = _list;
// if there's no list, we're starting at the root to build one
if (!list) {
list = [];
var parent = manager;
while (parent.parent) { parent = parent.parent; }
return collectAllOutros(parent, list);
} else {
// grab all outros from child managers
var i = manager.children.length;
while (i--) {
list = collectAllOutros(manager.children[i], list);
}
// grab any from this manager if there are any
if (manager.outros.length) { list = list.concat(manager.outros); }
return list;
}
}
var batch;
var runloop = {
active: function active() {
return !!batch;
},
start: function start() {
var fulfilPromise;
var promise = new Promise(function (f) { return (fulfilPromise = f); });
batch = {
previousBatch: batch,
transitionManager: new TransitionManager(fulfilPromise, batch && batch.transitionManager),
fragments: [],
tasks: [],
immediateObservers: [],
deferredObservers: [],
promise: promise
};
return promise;
},
end: function end() {
flushChanges();
if (!batch.previousBatch) { batch.transitionManager.start(); }
else { batch.transitionManager.checkStart(); }
batch = batch.previousBatch;
},
addFragment: function addFragment(fragment) {
addToArray(batch.fragments, fragment);
},
// TODO: come up with a better way to handle fragments that trigger their own update
addFragmentToRoot: function addFragmentToRoot(fragment) {
if (!batch) { return; }
var b = batch;
while (b.previousBatch) {
b = b.previousBatch;
}
addToArray(b.fragments, fragment);
},
addObserver: function addObserver(observer, defer) {
if (!batch) {
observer.dispatch();
} else {
addToArray(defer ? batch.deferredObservers : batch.immediateObservers, observer);
}
},
registerTransition: function registerTransition(transition) {
transition._manager = batch.transitionManager;
batch.transitionManager.add(transition);
},
// synchronise node detachments with transition ends
detachWhenReady: function detachWhenReady(thing) {
batch.transitionManager.detachQueue.push(thing);
},
scheduleTask: function scheduleTask(task, postRender) {
var _batch;
if (!batch) {
task();
} else {
_batch = batch;
while (postRender && _batch.previousBatch) {
// this can't happen until the DOM has been fully updated
// otherwise in some situations (with components inside elements)
// transitions and decorators will initialise prematurely
_batch = _batch.previousBatch;
}
_batch.tasks.push(task);
}
},
promise: function promise() {
if (!batch) { return Promise.resolve(); }
var target = batch;
while (target.previousBatch) {
target = target.previousBatch;
}
return target.promise || Promise.resolve();
}
};
function dispatch(observer) {
observer.dispatch();
}
function flushChanges() {
var which = batch.immediateObservers;
batch.immediateObservers = [];
which.forEach(dispatch);
// Now that changes have been fully propagated, we can update the DOM
// and complete other tasks
var i = batch.fragments.length;
var fragment;
which = batch.fragments;
batch.fragments = [];
while (i--) {
fragment = which[i];
fragment.update();
}
batch.transitionManager.ready();
which = batch.deferredObservers;
batch.deferredObservers = [];
which.forEach(dispatch);
var tasks = batch.tasks;
batch.tasks = [];
for (i = 0; i < tasks.length; i += 1) {
tasks[i]();
}
// If updating the view caused some model blowback - e.g. a triple
// containing <option> elements caused the binding on the <select>
// to update - then we start over
if (
batch.fragments.length ||
batch.immediateObservers.length ||
batch.deferredObservers.length ||
batch.tasks.length
)
{ return flushChanges(); }
}
// TODO what happens if a transition is aborted?
var tickers = [];
var running = false;
function tick() {
runloop.start();
var now = performance.now();
var i;
var ticker;
for (i = 0; i < tickers.length; i += 1) {
ticker = tickers[i];
if (!ticker.tick(now)) {
// ticker is complete, remove it from the stack, and decrement i so we don't miss one
tickers.splice(i--, 1);
}
}
runloop.end();
if (tickers.length) {
requestAnimationFrame(tick);
} else {
running = false;
}
}
var Ticker = function Ticker(options) {
this.duration = options.duration;
this.step = options.step;
this.complete = options.complete;
this.easing = options.easing;
this.start = performance.now();
this.end = this.start + this.duration;
this.running = true;
tickers.push(this);
if (!running) { requestAnimationFrame(tick); }
};
var Ticker__proto__ = Ticker.prototype;
Ticker__proto__.tick = function tick (now) {
if (!this.running) { return false; }
if (now > this.end) {
if (this.step) { this.step(1); }
if (this.complete) { this.complete(1); }
return false;
}
var elapsed = now - this.start;
var eased = this.easing(elapsed / this.duration);
if (this.step) { this.step(eased); }
return true;
};
Ticker__proto__.stop = function stop () {
if (this.abort) { this.abort(); }
this.running = false;
};
var prefixers = {};
// TODO this is legacy. sooner we can replace the old adaptor API the better
/* istanbul ignore next */
function prefixKeypath(obj, prefix) {
var prefixed = {};
if (!prefix) {
return obj;
}
prefix += '.';
for (var key in obj) {
if (hasOwn(obj, key)) {
prefixed[prefix + key] = obj[key];
}
}
return prefixed;
}
function getPrefixer(rootKeypath) {
var rootDot;
if (!prefixers[rootKeypath]) {
rootDot = rootKeypath ? rootKeypath + '.' : '';
/* istanbul ignore next */
prefixers[rootKeypath] = function(relativeKeypath, value) {
var obj;
if (isString(relativeKeypath)) {
obj = {};
obj[rootDot + relativeKeypath] = value;
return obj;
}
if (isObjectType(relativeKeypath)) {
// 'relativeKeypath' is in fact a hash, not a keypath
return rootDot ? prefixKeypath(relativeKeypath, rootKeypath) : relativeKeypath;
}
};
}
return prefixers[rootKeypath];
}
var shared$1 = {};
var Model = (function (ModelBase) {
function Model(parent, key) {
ModelBase.call(this, parent);
this.ticker = null;
if (parent) {
this.key = unescapeKey(key);
this.isReadonly = parent.isReadonly;
if (parent.value) {
this.value = parent.value[this.key];
if (isArray(this.value)) { this.length = this.value.length; }
this.adapt();
}
}
}
if ( ModelBase ) Model.__proto__ = ModelBase;
var Model__proto__ = Model.prototype = Object.create( ModelBase && ModelBase.prototype );
Model__proto__.constructor = Model;
Model__proto__.adapt = function adapt () {
var this$1 = this;
var adaptors = this.root.adaptors;
var len = adaptors.length;
this.rewrap = false;
// Exit early if no adaptors
if (len === 0) { return; }
var value = this.wrapper
? 'newWrapperValue' in this
? this.newWrapperValue
: this.wrapperValue
: this.value;
// TODO remove this legacy nonsense
var ractive = this.root.ractive;
var keypath = this.getKeypath();
// tear previous adaptor down if present
if (this.wrapper) {
var shouldTeardown =
this.wrapperValue === value
? false
: !this.wrapper.reset || this.wrapper.reset(value) === false;
if (shouldTeardown) {
this.wrapper.teardown();
delete this.wrapper;
delete this.wrapperValue;
delete this.newWrapperValue;
// don't branch for undefined values
if (this.value !== undefined) {
var parentValue = this.parent.value || this.parent.createBranch(this.key);
if (parentValue[this.key] !== value) { parentValue[this.key] = value; }
this.value = value;
}
} else {
delete this.newWrapperValue;
this.value = this.wrapper.get();
return;
}
}
var i;
for (i = 0; i < len; i += 1) {
var adaptor = adaptors[i];
if (adaptor.filter(value, keypath, ractive)) {
this$1.wrapper = adaptor.wrap(ractive, value, keypath, getPrefixer(keypath));
this$1.wrapperValue = value;
this$1.wrapper.__model = this$1; // massive temporary hack to enable array adaptor
this$1.value = this$1.wrapper.get();
break;
}
}
};
Model__proto__.animate = function animate (from, to, options, interpolator) {
var this$1 = this;
if (this.ticker) { this.ticker.stop(); }
var fulfilPromise;
var promise = new Promise(function (fulfil) { return (fulfilPromise = fulfil); });
this.ticker = new Ticker({
duration: options.duration,
easing: options.easing,
step: function (t) {
var value = interpolator(t);
this$1.applyValue(value);
if (options.step) { options.step(t, value); }
},
complete: function () {
this$1.applyValue(to);
if (options.complete) { options.complete(to); }
this$1.ticker = null;
fulfilPromise(to);
}
});
promise.stop = this.ticker.stop;
return promise;
};
Model__proto__.applyValue = function applyValue (value, notify) {
if ( notify === void 0 ) notify = true;
if (isEqual(value, this.value)) { return; }
if (this.boundValue) { this.boundValue = null; }
if (this.parent.wrapper && this.parent.wrapper.set) {
this.parent.wrapper.set(this.key, value);
this.parent.value = this.parent.wrapper.get();
this.value = this.parent.value[this.key];
if (this.wrapper) { this.newWrapperValue = this.value; }
this.adapt();
} else if (this.wrapper) {
this.newWrapperValue = value;
this.adapt();
} else {
var parentValue = this.parent.value || this.parent.createBranch(this.key);
if (isObjectLike(parentValue)) {
parentValue[this.key] = value;
} else {
warnIfDebug(("Attempted to set a property of a non-object '" + (this.getKeypath()) + "'"));
return;
}
this.value = value;
this.adapt();
}
// keep track of array stuff
if (isArray(value)) {
this.length = value.length;
this.isArray = true;
} else {
this.isArray = false;
}
// notify dependants
this.links.forEach(handleChange);
this.children.forEach(mark);
this.deps.forEach(handleChange);
if (notify) { this.notifyUpstream(); }
if (this.parent.isArray) {
if (this.key === 'length') { this.parent.length = value; }
else { this.parent.joinKey('length').mark(); }
}
};
Model__proto__.compute = function compute (key, computed) {
var registry = this.computed || (this.computed = {});
if (registry[key]) {
registry[key].signature = getComputationSignature(this.root.ractive, key, computed);
registry[key].mark();
} else {
registry[key] = new shared$1.Computation(
this,
getComputationSignature(this.root.ractive, key, computed),
key
);
}
return registry[key];
};
Model__proto__.createBranch = function createBranch (key) {
var branch = isNumeric(key) ? [] : {};
this.applyValue(branch, false);
return branch;
};
Model__proto__.get = function get (shouldCapture, opts) {
if (this._link) { return this._link.get(shouldCapture, opts); }
if (shouldCapture) { capture(this); }
// if capturing, this value needs to be unwrapped because it's for external use
if (opts && opts.virtual) { return this.getVirtual(false); }
return maybeBind(
this,
(opts && 'unwrap' in opts ? opts.unwrap !== false : shouldCapture) && this.wrapper
? this.wrapperValue
: this.value,
!opts || opts.shouldBind !== false
);
};
Model__proto__.joinKey = function joinKey (key, opts) {
var this$1 = this;
if (this._link) {
if (opts && opts.lastLink !== false && (key === undefined || key === '')) { return this; }
return this._link.joinKey(key);
}
if (key === undefined || key === '') { return this; }
var child;
if (hasOwn(this.childByKey, key)) { child = this.childByKey[key]; }
else { child = this.computed && this.computed[key]; }
if (!child) {
var computed;
if (this.isRoot && this.ractive && (computed = this.ractive.computed[key])) {
child = this.compute(key, computed);
} else if (!this.isRoot && this.root.ractive) {
var registry = this.root.ractive.computed;
for (var k in registry) {
computed = registry[k];
if (computed.pattern && computed.pattern.test(this$1.getKeypath() + '.' + key)) {
child = this$1.compute(key, computed);
}
}
}
}
if (!child) {
child = new Model(this, key);
this.children.push(child);
this.childByKey[key] = child;
}
if (child._link && (!opts || opts.lastLink !== false)) { return child._link; }
return child;
};
Model__proto__.mark = function mark$1 (force) {
if (this._link) { return this._link.mark(force); }
var old = this.value;
var value = this.retrieve();
if (force || !isEqual(value, old)) {
this.value = value;
if (this.boundValue) { this.boundValue = null; }
// make sure the wrapper stays in sync
if (old !== value || this.rewrap) {
if (this.wrapper) { this.newWrapperValue = value; }
this.adapt();
}
// keep track of array stuff
if (isArray(value)) {
this.length = value.length;
this.isArray = true;
} else {
this.isArray = false;
}
this.children.forEach(force ? markForce : mark);
this.links.forEach(marked);
this.deps.forEach(handleChange);
}
};
Model__proto__.merge = function merge (array, comparator) {
var newIndices = buildNewIndices(
this.value === array ? recreateArray(this) : this.value,
array,
comparator
);
this.parent.value[this.key] = array;
this.shuffle(newIndices, true);
};
Model__proto__.retrieve = function retrieve () {
return this.parent.value ? this.parent.value[this.key] : undefined;
};
Model__proto__.set = function set (value) {
if (this.ticker) { this.ticker.stop(); }
this.applyValue(value);
};
Model__proto__.shuffle = function shuffle$2 (newIndices, unsafe) {
shuffle(this, newIndices, false, unsafe);
};
Model__proto__.source = function source () {
return this;
};
Model__proto__.teardown = function teardown$4 () {
var this$1 = this;
if (this._link) {
this._link.teardown();
this._link = null;
}
this.children.forEach(teardown);
if (this.wrapper) { this.wrapper.teardown(); }
if (this.computed) { keys(this.computed).forEach(function (k) { return this$1.computed[k].teardown(); }); }
};
return Model;
}(ModelBase));
function recreateArray(model) {
var array = [];
for (var i = 0; i < model.length; i++) {
array[i] = (model.childByKey[i] || {}).value;
}
return array;
}
/* global global */
var data = {};
var SharedModel = (function (Model) {
function SharedModel(value, name, ractive) {
Model.call(this, null, ("@" + name));
this.key = "@" + name;
this.value = value;
this.isRoot = true;
this.root = this;
this.adaptors = [];
this.ractive = ractive;
}
if ( Model ) SharedModel.__proto__ = Model;
var SharedModel__proto__ = SharedModel.prototype = Object.create( Model && Model.prototype );
SharedModel__proto__.constructor = SharedModel;
SharedModel__proto__.getKeypath = function getKeypath () {
return this.key;
};
SharedModel__proto__.retrieve = function retrieve () {
return this.value;
};
return SharedModel;
}(Model));
var SharedModel$1 = new SharedModel(data, 'shared');
var GlobalModel = new SharedModel(base, 'global');
function findContext(fragment) {
var frag = fragment;
while (frag && !frag.context && !frag.aliases) { frag = frag.parent; }
return frag;
}
function resolveReference(fragment, ref) {
var initialFragment = fragment;
// current context ref
if (ref === '.') { return fragment.findContext(); }
// ancestor references
if (ref[0] === '~') { return fragment.ractive.viewmodel.joinAll(splitKeypath(ref.slice(2))); }
// scoped references
if (ref[0] === '.' || ref[0] === '^') {
var frag = fragment;
var parts = ref.split('/');
var explicitContext = parts[0] === '^^';
// find nearest context node
while (frag && !frag.context) {
frag = up(frag);
}
var context$1 = frag && frag.context;
// walk up the context chain
while (frag && parts[0] === '^^') {
parts.shift();
// the current fragment should always be a context,
// and if it happens to be an iteration, jump above the each block
if (frag.isIteration) {
frag = frag.parent.parent;
} else {
// otherwise jump above the current fragment
frag = up(frag);
}
// walk to the next contexted fragment
while (frag && !frag.context) {
frag = up(frag);
}
context$1 = frag && frag.context;
}
if (!context$1 && explicitContext) {
throw new Error(
("Invalid context parent reference ('" + ref + "'). There is not context at that level.")
);
}
// walk up the context path
while (parts[0] === '.' || parts[0] === '..') {
var part = parts.shift();
if (part === '..') {
context$1 = context$1.parent;
}
}
ref = parts.join('/');
// special case - `{{.foo}}` means the same as `{{./foo}}`
if (ref[0] === '.') { ref = ref.slice(1); }
return context$1.joinAll(splitKeypath(ref));
}
var keys$$1 = splitKeypath(ref);
if (!keys$$1.length) { return; }
var base = keys$$1.shift();
// special refs
if (base[0] === '@') {
// shorthand from outside the template
// @this referring to local ractive instance
if (base === '@this' || base === '@') {
return fragment.ractive.viewmodel.getRactiveModel().joinAll(keys$$1);
} else if (base === '@index' || base === '@key') {
// @index or @key referring to the nearest repeating index or key
if (keys$$1.length) { badReference(base); }
var repeater = findIter(fragment);
return repeater && repeater[("get" + (base[1] === 'i' ? 'Index' : 'Key'))]();
} else if (base === '@last') {
var repeater$1 = findIter(fragment);
return repeater$1 && repeater$1.parent.getLast();
} else if (base === '@global') {
// @global referring to window or global
return GlobalModel.joinAll(keys$$1);
} else if (base === '@shared') {
// @global referring to window or global
return SharedModel$1.joinAll(keys$$1);
} else if (base === '@keypath' || base === '@rootpath') {
// @keypath or @rootpath, the current keypath string
var root = ref[1] === 'r' ? fragment.ractive.root : null;
var f = fragment;
while (
f &&
(!f.context || (f.isRoot && f.ractive.component && (root || !f.ractive.isolated)))
) {
f = f.isRoot ? f.componentParent : f.parent;
}
return f.getKeypath(root);
} else if (base === '@context') {
return new SharedModel(fragment.getContext(), 'context').joinAll(keys$$1);
} else if (base === '@local') {
// @context-local data
return fragment.getContext()._data.joinAll(keys$$1);
} else if (base === '@style') {
// @style shared model
return fragment.ractive.constructor._cssModel.joinAll(keys$$1);
} else if (base === '@helpers') {
// @helpers instance model
return fragment.ractive.viewmodel.getHelpers().joinAll(keys$$1);
} else if (base === '@macro') {
var handle = findMacro(fragment);
if (handle) { return new SharedModel(handle, 'macro').joinAll(keys$$1); }
else { return; }
} else {
// nope
throw new Error(("Invalid special reference '" + base + "'"));
}
}
// helpers
if (base && !keys$$1.length) {
var helpers = fragment.ractive.viewmodel.getHelpers();
if (helpers.has(base)) { return helpers.joinKey(base); }
}
var context = findContext(fragment);
// check immediate context for a match
if (context) {
if (context.context) {
context = context.context;
if (context.has(base)) { return context.joinKey(base).joinAll(keys$$1); }
} else {
// alias block, so get next full context for later
context = fragment.findContext();
}
} else {
context = fragment.findContext();
}
// walk up the fragment hierarchy looking for a matching ref, alias, or key in a context
var createMapping = false;
var shouldWarn = fragment.ractive.warnAboutAmbiguity;
var crossed = 0;
var model;
while (fragment) {
// repeated fragments
if (fragment.isIteration) {
if (base === fragment.parent.keyRef) {
model = fragment.getKey();
} else if (base === fragment.parent.indexRef) {
model = fragment.getIndex();
}
if (model && keys$$1.length) { badReference(base); }
}
// alias node or iteration
if (!model && fragment.aliases && hasOwn(fragment.aliases, base)) {
model = fragment.aliases[base];
}
// check fragment context to see if it has the key we need
if (!model && fragment.context && fragment.context.has(base)) {
model = fragment.context.joinKey(base);
// this is an implicit mapping
if (createMapping) {
if (shouldWarn)
{ warnIfDebug(
("'" + ref + "' resolved but is ambiguous and will create a mapping to a parent component.")
); }
} else if (shouldWarn && crossed) { warnIfDebug(("'" + ref + "' resolved but is ambiguous.")); }
}
if (model) {
if (createMapping) {
model = initialFragment.ractive.viewmodel.createLink(base, model, base, { implicit: true });
}
if (keys$$1.length > 0 && isFunction(model.joinAll)) {
model = model.joinAll(keys$$1);
}
return model;
}
// don't consider alias blocks when checking for ambiguity
if (fragment.context && !fragment.aliases) { crossed = 1; }
if (
(fragment.componentParent || (!fragment.parent && fragment.ractive.component)) &&
!fragment.ractive.isolated
) {
// ascend through component boundary
fragment = fragment.componentParent || fragment.ractive.component.up;
createMapping = true;
} else {
fragment = fragment.parent;
}
}
// if enabled, check the instance for a match
var instance = initialFragment.ractive;
if (instance.resolveInstanceMembers && base !== 'data' && base in instance) {
return instance.viewmodel
.getRactiveModel()
.joinKey(base)
.joinAll(keys$$1);
}
if (shouldWarn) {
warnIfDebug(("'" + ref + "' is ambiguous and did not resolve."));
}
// didn't find anything, so go ahead and create the key on the local model
return context.joinKey(base).joinAll(keys$$1);
}
function up(fragment) {
return fragment && ((!fragment.ractive.isolated && fragment.componentParent) || fragment.parent);
}
function findIter(start) {
var fragment = start;
var next;
while (!fragment.isIteration && (next = up(fragment))) {
fragment = next;
}
return fragment.isIteration && fragment;
}
function findMacro(start) {
var fragment = start;
while (fragment) {
if (fragment.owner.handle) { return fragment.owner.handle; }
fragment = up(fragment);
}
}
function badReference(key) {
throw new Error(("An index or key reference (" + key + ") cannot have child properties"));
}
var extern = {};
function getRactiveContext(ractive) {
var assigns = [], len = arguments.length - 1;
while ( len-- > 0 ) assigns[ len ] = arguments[ len + 1 ];
var fragment =
ractive.fragment ||
ractive._fakeFragment ||
(ractive._fakeFragment = new FakeFragment(ractive));
return fragment.getContext.apply(fragment, assigns);
}
function getContext() {
var assigns = [], len = arguments.length;
while ( len-- ) assigns[ len ] = arguments[ len ];
if (!this.ctx) { this.ctx = new extern.Context(this); }
assigns.unshift(create(this.ctx));
return assign.apply(null, assigns);
}
var FakeFragment = function FakeFragment(ractive) {
this.ractive = ractive;
};
FakeFragment.prototype.findContext = function findContext () {
return this.ractive.viewmodel;
};
var proto = FakeFragment.prototype;
proto.getContext = getContext;
proto.find = proto.findComponent = proto.findAll = proto.findAllComponents = noop;
function findParentWithContext(fragment) {
var frag = fragment;
while (frag && !frag.context) { frag = frag.parent; }
if (!frag) { return fragment && fragment.ractive.fragment; }
else { return frag; }
}
var keep = false;
function set(pairs, options) {
var k = keep;
var deep = options && options.deep;
var shuffle = options && options.shuffle;
var promise = runloop.start();
if (options && 'keep' in options) { keep = options.keep; }
var i = pairs.length;
while (i--) {
var model = pairs[i][0];
var value = pairs[i][1];
var keypath = pairs[i][2];
if (!model) {
runloop.end();
throw new Error(("Failed to set invalid keypath '" + keypath + "'"));
}
if (deep) { deepSet(model, value); }
else if (shuffle) {
var array = value;
var target = model.get();
// shuffle target array with itself
if (!array) { array = target; }
// if there's not an array there yet, go ahead and set
if (target === undefined) {
model.set(array);
} else {
if (!isArray(target) || !isArray(array)) {
runloop.end();
throw new Error('You cannot merge an array with a non-array');
}
var comparator = getComparator(shuffle);
model.merge(array, comparator);
}
} else { model.set(value); }
}
runloop.end();
keep = k;
return promise;
}
var star = /\*/;
function gather(ractive, keypath, base, isolated) {
if (!base && (keypath[0] === '.' || keypath[1] === '^')) {
warnIfDebug(
"Attempted to set a relative keypath from a non-relative context. You can use a context object to set relative keypaths."
);
return [];
}
var keys$$1 = splitKeypath(keypath);
var model = base || ractive.viewmodel;
if (star.test(keypath)) {
return model.findMatches(keys$$1);
} else {
if (model === ractive.viewmodel) {
// allow implicit mappings
if (
ractive.component &&
!ractive.isolated &&
!model.has(keys$$1[0]) &&
keypath[0] !== '@' &&
keypath[0] &&
!isolated
) {
return [resolveReference(ractive.fragment || new FakeFragment(ractive), keypath)];
} else {
return [model.joinAll(keys$$1)];
}
} else {
return [model.joinAll(keys$$1)];
}
}
}
function build(ractive, keypath, value, isolated) {
var sets = [];
// set multiple keypaths in one go
if (isObject(keypath)) {
var loop = function ( k ) {
if (hasOwn(keypath, k)) {
sets.push.apply(sets, gather(ractive, k, null, isolated).map(function (m) { return [m, keypath[k], k]; }));
}
};
for (var k in keypath) loop( k );
} else {
// set a single keypath
sets.push.apply(sets, gather(ractive, keypath, null, isolated).map(function (m) { return [m, value, keypath]; }));
}
return sets;
}
var deepOpts = { virtual: false };
function deepSet(model, value) {
var dest = model.get(false, deepOpts);
// if dest doesn't exist, just set it
if (dest == null || !isObjectType(value)) { return model.set(value); }
if (!isObjectType(dest)) { return model.set(value); }
for (var k in value) {
if (hasOwn(value, k)) {
deepSet(model.joinKey(k), value[k]);
}
}
}
var comparators = {};
function getComparator(option) {
if (option === true) { return null; } // use existing arrays
if (isFunction(option)) { return option; }
if (isString(option)) {
return comparators[option] || (comparators[option] = function (thing) { return thing[option]; });
}
throw new Error('If supplied, options.compare must be a string, function, or true'); // TODO link to docs
}
var errorMessage = 'Cannot add to a non-numeric value';
function add(ractive, keypath, d, options) {
if (!isString(keypath) || !isNumeric(d)) {
throw new Error('Bad arguments');
}
var sets = build(ractive, keypath, d, options && options.isolated);
return set(
sets.map(function (pair) {
var model = pair[0];
var add = pair[1];
var value = model.get();
if (!isNumeric(add) || !isNumeric(value)) { throw new Error(errorMessage); }
return [model, value + add];
})
);
}
function Ractive$add(keypath, d, options) {
var num = isNumber(d) ? d : 1;
var opts = isObjectType(d) ? d : options;
return add(this, keypath, num, opts);
}
function immediate(value) {
var result = Promise.resolve(value);
defineProperty(result, 'stop', { value: noop });
return result;
}
var linear = easing.linear;
function getOptions(options, instance) {
options = options || {};
var easing$$1;
if (options.easing) {
easing$$1 = isFunction(options.easing) ? options.easing : instance.easing[options.easing];
}
return {
easing: easing$$1 || linear,
duration: 'duration' in options ? options.duration : 400,
complete: options.complete || noop,
step: options.step || noop,
interpolator: options.interpolator
};
}
function animate(ractive, model, to, options) {
options = getOptions(options, ractive);
var from = model.get();
// don't bother animating values that stay the same
if (isEqual(from, to)) {
options.complete(options.to);
return immediate(to);
}
var interpolator = interpolate(from, to, ractive, options.interpolator);
// if we can't interpolate the value, set it immediately
if (!interpolator) {
runloop.start();
model.set(to);
runloop.end();
return immediate(to);
}
return model.animate(from, to, options, interpolator);
}
function Ractive$animate(keypath, to, options) {
if (isObjectType(keypath)) {
var keys$$1 = keys(keypath);
throw new Error(("ractive.animate(...) no longer supports objects. Instead of ractive.animate({\n " + (keys$$1.map(function (key) { return ("'" + key + "': " + (keypath[key])); }).join('\n ')) + "\n}, {...}), do\n\n" + (keys$$1.map(function (key) { return ("ractive.animate('" + key + "', " + (keypath[key]) + ", {...});"); }).join('\n')) + "\n"));
}
return animate(this, this.viewmodel.joinAll(splitKeypath(keypath)), to, options);
}
function enqueue(ractive, event) {
if (ractive.event) {
ractive._eventQueue.push(ractive.event);
}
ractive.event = event;
}
function dequeue(ractive) {
if (ractive._eventQueue.length) {
ractive.event = ractive._eventQueue.pop();
} else {
ractive.event = null;
}
}
var initStars = {};
var bubbleStars = {};
// cartesian product of name parts and stars
// adjusted appropriately for special cases
function variants(name, initial) {
var map = initial ? initStars : bubbleStars;
if (map[name]) { return map[name]; }
var parts = name.split('.');
var result = [];
var base = false;
// initial events the implicit namespace of 'this'
if (initial) {
parts.unshift('this');
base = true;
}
// use max - 1 bits as a bitmap to pick a part or a *
// need to skip the full star case if the namespace is synthetic
var max = Math.pow(2, parts.length) - (initial ? 1 : 0);
for (var i = 0; i < max; i++) {
var join = [];
for (var j = 0; j < parts.length; j++) {
join.push(1 & (i >> j) ? '*' : parts[j]);
}
result.unshift(join.join('.'));
}
if (base) {
// include non-this-namespaced versions
if (parts.length > 2) {
result.push.apply(result, variants(name, false));
} else {
result.push('*');
result.push(name);
}
}
map[name] = result;
return result;
}
function fireEvent(ractive, eventName, context, args) {
if ( args === void 0 ) args = [];
if (!eventName) {
return;
}
context.name = eventName;
args.unshift(context);
var eventNames = ractive._nsSubs ? variants(eventName, true) : ['*', eventName];
return fireEventAs(ractive, eventNames, context, args, true);
}
function fireEventAs(ractive, eventNames, context, args, initialFire) {
if ( initialFire === void 0 ) initialFire = false;
var bubble = true;
if (initialFire || ractive._nsSubs) {
enqueue(ractive, context);
var i = eventNames.length;
while (i--) {
if (eventNames[i] in ractive._subs) {
bubble = notifySubscribers(ractive, ractive._subs[eventNames[i]], context, args) && bubble;
}
}
dequeue(ractive);
}
if (ractive.parent && bubble) {
if (initialFire && ractive.component) {
var fullName = ractive.component.name + '.' + eventNames[eventNames.length - 1];
eventNames = variants(fullName, false);
if (context && !context.component) {
context.component = ractive;
}
}
bubble = fireEventAs(ractive.parent, eventNames, context, args);
}
return bubble;
}
function notifySubscribers(ractive, subscribers, context, args) {
var originalEvent = null;
var stopEvent = false;
// subscribers can be modified inflight, e.g. "once" functionality
// so we need to copy to make sure everyone gets called
subscribers = subscribers.slice();
for (var i = 0, len = subscribers.length; i < len; i += 1) {
if (!subscribers[i].off && subscribers[i].handler.apply(ractive, args) === false) {
stopEvent = true;
}
}
if (context && stopEvent && (originalEvent = context.event)) {
originalEvent.preventDefault && originalEvent.preventDefault();
originalEvent.stopPropagation && originalEvent.stopPropagation();
}
return !stopEvent;
}
var Hook = function Hook(event) {
this.event = event;
this.method = 'on' + event;
};
Hook.prototype.fire = function fire (ractive, arg) {
var context = getRactiveContext(ractive);
var method = this.method;
if (ractive[method]) {
arg ? ractive[method](context, arg) : ractive[method](context);
}
fireEvent(ractive, this.event, context, arg ? [arg, ractive] : [ractive]);
};
function getChildQueue(queue, ractive) {
return queue[ractive._guid] || (queue[ractive._guid] = []);
}
function fire(hookQueue, ractive) {
var childQueue = getChildQueue(hookQueue.queue, ractive);
hookQueue.hook.fire(ractive);
// queue is "live" because components can end up being
// added while hooks fire on parents that modify data values.
while (childQueue.length) {
fire(hookQueue, childQueue.shift());
}
delete hookQueue.queue[ractive._guid];
}
var HookQueue = function HookQueue(event) {
this.hook = new Hook(event);
this.inProcess = {};
this.queue = {};
};
var HookQueue__proto__ = HookQueue.prototype;
HookQueue__proto__.begin = function begin (ractive) {
this.inProcess[ractive._guid] = true;
};
HookQueue__proto__.end = function end (ractive) {
var parent = ractive.parent;
// If this is *isn't* a child of a component that's in process,
// it should call methods or fire at this point
if (!parent || !this.inProcess[parent._guid]) {
fire(this, ractive);
} else {
// elsewise, handoff to parent to fire when ready
getChildQueue(this.queue, parent).push(ractive);
}
delete this.inProcess[ractive._guid];
};
var hooks = {};
[
'construct',
'config',
'attachchild',
'detach',
'detachchild',
'insert',
'complete',
'reset',
'render',
'unrendering',
'unrender',
'teardown',
'destruct',
'update'
].forEach(function (hook) {
hooks[hook] = new Hook(hook);
});
hooks.init = new HookQueue('init');
function findAnchors(fragment, name) {
if ( name === void 0 ) name = null;
var res = [];
findAnchorsIn(fragment, name, res);
return res;
}
function findAnchorsIn(item, name, result) {
if (item.isAnchor) {
if (!name || item.name === name) {
result.push(item);
}
} else if (item.items) {
item.items.forEach(function (i) { return findAnchorsIn(i, name, result); });
} else if (item.iterations) {
item.iterations.forEach(function (i) { return findAnchorsIn(i, name, result); });
} else if (item.fragment && !item.component) {
findAnchorsIn(item.fragment, name, result);
}
}
function updateAnchors(instance, name) {
if ( name === void 0 ) name = null;
var anchors = findAnchors(instance.fragment, name);
var idxs = {};
var children = instance._children.byName;
anchors.forEach(function (a) {
var name = a.name;
if (!(name in idxs)) { idxs[name] = 0; }
var idx = idxs[name];
var child = (children[name] || [])[idx];
if (child && child.lastBound !== a) {
if (child.lastBound) { child.lastBound.removeChild(child); }
a.addChild(child);
}
idxs[name]++;
});
}
function unrenderChild(meta) {
if (meta.instance.fragment.rendered) {
meta.shouldDestroy = true;
meta.instance.unrender();
}
meta.instance.el = null;
}
function attachChild(child, options) {
if ( options === void 0 ) options = {};
var children = this._children;
var idx;
if (child.parent && child.parent !== this)
{ throw new Error(
("Instance " + (child._guid) + " is already attached to a different instance " + (child.parent._guid) + ". Please detach it from the other instance using detachChild first.")
); }
else if (child.parent)
{ throw new Error(("Instance " + (child._guid) + " is already attached to this instance.")); }
var meta = {
instance: child,
ractive: this,
name: options.name || child.constructor.name || 'Ractive',
target: options.target || false,
bubble: bubble,
findNextNode: findNextNode
};
meta.nameOption = options.name;
// child is managing itself
if (!meta.target) {
meta.up = this.fragment;
meta.external = true;
} else {
var list;
if (!(list = children.byName[meta.target])) {
list = [];
this.set(("@this.children.byName." + (meta.target)), list);
}
idx = options.prepend ? 0 : options.insertAt !== undefined ? options.insertAt : list.length;
}
child.parent = this;
child.root = this.root;
child.component = meta;
children.push(meta);
var promise = runloop.start();
var rm = child.viewmodel.getRactiveModel();
rm.joinKey('parent', { lastLink: false }).link(this.viewmodel.getRactiveModel());
rm.joinKey('root', { lastLink: false }).link(this.root.viewmodel.getRactiveModel());
hooks.attachchild.fire(child);
if (meta.target) {
unrenderChild(meta);
this.splice(("@this.children.byName." + (meta.target)), idx, 0, meta);
updateAnchors(this, meta.target);
} else {
if (!child.isolated) { child.viewmodel.attached(this.fragment); }
}
runloop.end();
promise.ractive = child;
return promise.then(function () { return child; });
}
function bubble() {
runloop.addFragment(this.instance.fragment);
}
function findNextNode() {
if (this.anchor) { return this.anchor.findNextNode(); }
}
function compute(path, computed) {
this.computed[path] = computed;
if (isString(computed) || isFunction(computed))
{ computed = this.computed[path] = { get: computed }; }
var keys = splitKeypath(path);
if (!~path.indexOf('*')) {
var last = keys.pop();
return this.viewmodel.joinAll(keys).compute(last, computed);
} else {
computed.pattern = new RegExp(
'^' +
keys
.map(function (k) { return k.replace(/\*\*/g, '(.+)').replace(/\*/g, '((?:\\\\.|[^\\.])+)'); })
.join('\\.') +
'$'
);
}
}
function Ractive$compute(path, computed) {
var promise = runloop.start();
var comp = compute.call(this, path, computed);
if (comp) {
var keys = splitKeypath(path);
if (keys.length === 1 && !comp.isReadonly) {
comp.set(this.viewmodel.value[keys[0]]);
}
var first = keys.reduce(function (a, c) { return a && a.childByKey[c]; }, this.viewmodel);
if (first) {
first.rebind(comp, first, false);
if (first.parent) { delete first.parent.childByKey[first.key]; }
fireShuffleTasks();
}
}
runloop.end();
return promise;
}
function Ractive$detach() {
if (this.isDetached) {
return this.el;
}
if (this.el) {
removeFromArray(this.el.__ractive_instances__, this);
}
this.el = this.fragment.detach();
this.isDetached = true;
hooks.detach.fire(this);
return this.el;
}
function detachChild(child) {
var children = this._children;
var meta, index;
var i = children.length;
while (i--) {
if (children[i].instance === child) {
index = i;
meta = children[i];
break;
}
}
if (!meta || child.parent !== this)
{ throw new Error(("Instance " + (child._guid) + " is not attached to this instance.")); }
var promise = runloop.start();
if (meta.anchor) { meta.anchor.removeChild(meta); }
if (!child.isolated) { child.viewmodel.detached(); }
children.splice(index, 1);
if (meta.target) {
this.splice(
("@this.children.byName." + (meta.target)),
children.byName[meta.target].indexOf(meta),
1
);
updateAnchors(this, meta.target);
}
var rm = child.viewmodel.getRactiveModel();
rm.joinKey('parent', { lastLink: false }).unlink();
rm.joinKey('root', { lastLink: false }).link(rm);
child.root = child;
child.parent = null;
child.component = null;
hooks.detachchild.fire(child);
runloop.end();
promise.ractive = child;
return promise.then(function () { return child; });
}
function Ractive$find(selector, options) {
var this$1 = this;
if ( options === void 0 ) options = {};
if (!this.rendered)
{ throw new Error(
("Cannot call ractive.find('" + selector + "') unless instance is rendered to the DOM")
); }
var node = this.fragment.find(selector, options);
if (node) { return node; }
if (options.remote) {
for (var i = 0; i < this._children.length; i++) {
if (!this$1._children[i].instance.fragment.rendered) { continue; }
node = this$1._children[i].instance.find(selector, options);
if (node) { return node; }
}
}
}
function Ractive$findAll(selector, options) {
if ( options === void 0 ) options = {};
if (!this.rendered)
{ throw new Error(
("Cannot call ractive.findAll('" + selector + "', ...) unless instance is rendered to the DOM")
); }
if (!isArray(options.result)) { options.result = []; }
this.fragment.findAll(selector, options);
if (options.remote) {
// seach non-fragment children
this._children.forEach(function (c) {
if (!c.target && c.instance.fragment && c.instance.fragment.rendered) {
c.instance.findAll(selector, options);
}
});
}
return options.result;
}
function Ractive$findAllComponents(selector, options) {
if (!options && isObjectType(selector)) {
options = selector;
selector = '';
}
options = options || {};
if (!isArray(options.result)) { options.result = []; }
this.fragment.findAllComponents(selector, options);
if (options.remote) {
// search non-fragment children
this._children.forEach(function (c) {
if (!c.target && c.instance.fragment && c.instance.fragment.rendered) {
if (!selector || c.name === selector) {
options.result.push(c.instance);
}
c.instance.findAllComponents(selector, options);
}
});
}
return options.result;
}
function Ractive$findComponent(selector, options) {
var this$1 = this;
if ( options === void 0 ) options = {};
if (isObjectType(selector)) {
options = selector;
selector = '';
}
var child = this.fragment.findComponent(selector, options);
if (child) { return child; }
if (options.remote) {
if (!selector && this._children.length) { return this._children[0].instance; }
for (var i = 0; i < this._children.length; i++) {
// skip children that are or should be in an anchor
if (this$1._children[i].target) { continue; }
if (this$1._children[i].name === selector) { return this$1._children[i].instance; }
child = this$1._children[i].instance.findComponent(selector, options);
if (child) { return child; }
}
}
}
function Ractive$findContainer(selector) {
if (this.container) {
if (this.container.component && this.container.component.name === selector) {
return this.container;
} else {
return this.container.findContainer(selector);
}
}
return null;
}
function Ractive$findParent(selector) {
if (this.parent) {
if (this.parent.component && this.parent.component.name === selector) {
return this.parent;
} else {
return this.parent.findParent(selector);
}
}
return null;
}
function findElement(start, orComponent, name) {
if ( orComponent === void 0 ) orComponent = true;
while (
start &&
(start.type !== ELEMENT || (name && start.name !== name)) &&
(!orComponent || (start.type !== COMPONENT && start.type !== ANCHOR))
) {
// start is a fragment - look at the owner
if (start.owner) { start = start.owner; }
else if (start.component)
// start is a component or yielder - look at the container
{ start = start.containerFragment || start.component.up; }
else if (start.parent)
// start is an item - look at the parent
{ start = start.parent; }
else if (start.up)
// start is an item without a parent - look at the parent fragment
{ start = start.up; }
else { start = undefined; }
}
return start;
}
// This function takes an array, the name of a mutator method, and the
// arguments to call that mutator method with, and returns an array that
// maps the old indices to their new indices.
// So if you had something like this...
//
// array = [ 'a', 'b', 'c', 'd' ];
// array.push( 'e' );
//
// ...you'd get `[ 0, 1, 2, 3 ]` - in other words, none of the old indices
// have changed. If you then did this...
//
// array.unshift( 'z' );
//
// ...the indices would be `[ 1, 2, 3, 4, 5 ]` - every item has been moved
// one higher to make room for the 'z'. If you removed an item, the new index
// would be -1...
//
// array.splice( 2, 2 );
//
// ...this would result in [ 0, 1, -1, -1, 2, 3 ].
//
// This information is used to enable fast, non-destructive shuffling of list
// sections when you do e.g. `ractive.splice( 'items', 2, 2 );
function getNewIndices(length, methodName, args) {
var newIndices = [];
var spliceArguments = getSpliceEquivalent(length, methodName, args);
if (!spliceArguments) {
return null; // TODO support reverse and sort?
}
var balance = spliceArguments.length - 2 - spliceArguments[1];
var removeStart = Math.min(length, spliceArguments[0]);
var removeEnd = removeStart + spliceArguments[1];
newIndices.startIndex = removeStart;
var i;
for (i = 0; i < removeStart; i += 1) {
newIndices.push(i);
}
for (; i < removeEnd; i += 1) {
newIndices.push(-1);
}
for (; i < length; i += 1) {
newIndices.push(i + balance);
}
// there is a net shift for the rest of the array starting with index + balance
if (balance !== 0) {
newIndices.touchedFrom = spliceArguments[0];
} else {
newIndices.touchedFrom = length;
}
return newIndices;
}
// The pop, push, shift an unshift methods can all be represented
// as an equivalent splice
function getSpliceEquivalent(length, methodName, args) {
switch (methodName) {
case 'splice':
if (args[0] !== undefined && args[0] < 0) {
args[0] = length + Math.max(args[0], -length);
}
if (args[0] === undefined) { args[0] = 0; }
while (args.length < 2) {
args.push(length - args[0]);
}
if (!isNumber(args[1])) {
args[1] = length - args[0];
}
// ensure we only remove elements that exist
args[1] = Math.min(args[1], length - args[0]);
return args;
case 'sort':
case 'reverse':
return null;
case 'pop':
if (length) {
return [length - 1, 1];
}
return [0, 0];
case 'push':
return [length, 0].concat(args);
case 'shift':
return [0, length ? 1 : 0];
case 'unshift':
return [0, 0].concat(args);
}
}
var arrayProto = Array.prototype;
function makeArrayMethod(methodName) {
function path(keypath) {
var args = [], len = arguments.length - 1;
while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
return model(this.viewmodel.joinAll(splitKeypath(keypath)), args);
}
function model(mdl, args) {
var array = mdl.get();
if (!isArray(array)) {
if (array === undefined) {
array = [];
var result$1 = arrayProto[methodName].apply(array, args);
var promise$1 = runloop.start().then(function () { return result$1; });
mdl.set(array);
runloop.end();
return promise$1;
} else {
throw new Error(
("shuffle array method " + methodName + " called on non-array at " + (mdl.getKeypath()))
);
}
}
var newIndices = getNewIndices(array.length, methodName, args);
var result = arrayProto[methodName].apply(array, args);
var promise = runloop.start().then(function () { return result; });
promise.result = result;
if (newIndices) {
if (mdl.shuffle) {
mdl.shuffle(newIndices);
} else {
// it's a computation, which don't have a shuffle, so just invalidate
mdl.mark();
}
} else {
mdl.set(result);
}
runloop.end();
return promise;
}
return { path: path, model: model };
}
function update$1(ractive, model, options) {
// if the parent is wrapped, the adaptor will need to be updated before
// updating on this keypath
if (model.parent && model.parent.wrapper) {
model.parent.adapt();
}
var promise = runloop.start();
model.mark(options && options.force);
// notify upstream of changes
model.notifyUpstream();
runloop.end();
hooks.update.fire(ractive, model);
return promise;
}
function Ractive$update(keypath, options) {
var opts, path;
if (isString(keypath)) {
path = splitKeypath(keypath);
opts = options;
} else {
opts = keypath;
}
return update$1(this, path ? this.viewmodel.joinAll(path) : this.viewmodel, opts);
}
var modelPush = makeArrayMethod('push').model;
var modelPop = makeArrayMethod('pop').model;
var modelShift = makeArrayMethod('shift').model;
var modelUnshift = makeArrayMethod('unshift').model;
var modelSort = makeArrayMethod('sort').model;
var modelSplice = makeArrayMethod('splice').model;
var modelReverse = makeArrayMethod('reverse').model;
var ContextData = (function (Model) {
function ContextData(options) {
Model.call(this, null, null);
this.isRoot = true;
this.root = this;
this.value = {};
this.ractive = options.ractive;
this.adaptors = [];
this.context = options.context;
}
if ( Model ) ContextData.__proto__ = Model;
var ContextData__proto__ = ContextData.prototype = Object.create( Model && Model.prototype );
ContextData__proto__.constructor = ContextData;
ContextData__proto__.getKeypath = function getKeypath () {
return '@context.data';
};
ContextData__proto__.rebound = function rebound () {};
return ContextData;
}(Model));
var Context = function Context(fragment, element) {
this.fragment = fragment;
this.element = element || findElement(fragment);
this.node = this.element && this.element.node;
this.ractive = fragment.ractive;
this.root = this;
};
var Context__proto__ = Context.prototype;
var prototypeAccessors = { decorators: {},_data: {} };
prototypeAccessors.decorators.get = function () {
var items = {};
if (!this.element) { return items; }
this.element.decorators.forEach(function (d) { return (items[d.name] = d.handle); });
return items;
};
prototypeAccessors._data.get = function () {
return (
this.model ||
(this.root.model = new ContextData({
ractive: this.ractive,
context: this.root
}))
);
};
// the usual mutation suspects
Context__proto__.add = function add (keypath, d, options) {
var num = isNumber(d) ? +d : 1;
var opts = isObjectType(d) ? d : options;
return set(
build$1(this, keypath, num).map(function (pair) {
var model = pair[0];
var val = pair[1];
var value = model.get();
if (!isNumeric(val) || !isNumeric(value)) { throw new Error('Cannot add non-numeric value'); }
return [model, value + val];
}),
opts
);
};
Context__proto__.animate = function animate$1 (keypath, value, options) {
var model = findModel(this, keypath).model;
return animate(this.ractive, model, value, options);
};
Context__proto__.find = function find (selector) {
return this.fragment.find(selector);
};
Context__proto__.findAll = function findAll (selector) {
var result = [];
this.fragment.findAll(selector, { result: result });
return result;
};
Context__proto__.findAllComponents = function findAllComponents (selector) {
var result = [];
this.fragment.findAllComponents(selector, { result: result });
return result;
};
Context__proto__.findComponent = function findComponent (selector) {
return this.fragment.findComponent(selector);
};
// get relative keypaths and values
Context__proto__.get = function get (keypath) {
if (!keypath) { return this.fragment.findContext().get(true); }
var ref = findModel(this, keypath);
var model = ref.model;
return model ? model.get(true) : undefined;
};
Context__proto__.getParent = function getParent (component) {
var fragment = this.fragment;
if (fragment.context)
{ fragment = findParentWithContext(fragment.parent || (component && fragment.componentParent)); }
else {
fragment = findParentWithContext(fragment.parent || (component && fragment.componentParent));
if (fragment)
{ fragment = findParentWithContext(
fragment.parent || (component && fragment.componentParent)
); }
}
if (!fragment || fragment === this.fragment) { return; }
else { return fragment.getContext(); }
};
Context__proto__.hasListener = function hasListener (name, bubble) {
// if the owner is a component, start there because the nearest element
// may exist outside of the immediate context (yield)
var el = this.fragment.owner.component
? this.fragment.owner
: this.element || this.fragment.owner;
var base;
do {
base = el.component || el;
if (base.template.t === ELEMENT) {
if (findEvent(base, name)) { return true; }
}
el = el.up && el.up.owner;
if (el && el.component) { el = el.component; }
} while (el && bubble);
};
Context__proto__.link = function link (source, dest) {
var there = findModel(this, source).model;
var here = findModel(this, dest).model;
var promise = runloop.start();
here.link(there, source);
runloop.end();
return promise;
};
Context__proto__.listen = function listen (event, handler) {
var el = this.element;
el.on(event, handler);
return {
cancel: function cancel() {
el.off(event, handler);
}
};
};
Context__proto__.observe = function observe (keypath, callback, options) {
if ( options === void 0 ) options = {};
if (isObject(keypath)) { options = callback || {}; }
options.fragment = this.fragment;
return this.ractive.observe(keypath, callback, options);
};
Context__proto__.observeOnce = function observeOnce (keypath, callback, options) {
if ( options === void 0 ) options = {};
if (isObject(keypath)) { options = callback || {}; }
options.fragment = this.fragment;
return this.ractive.observeOnce(keypath, callback, options);
};
Context__proto__.pop = function pop (keypath) {
return modelPop(findModel(this, keypath).model, []);
};
Context__proto__.push = function push (keypath) {
var values = [], len = arguments.length - 1;
while ( len-- > 0 ) values[ len ] = arguments[ len + 1 ];
return modelPush(findModel(this, keypath).model, values);
};
Context__proto__.raise = function raise (name, event) {
var args = [], len = arguments.length - 2;
while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ];
var el = this.element;
var ev;
while (el) {
if (el.component) { el = el.component; }
ev = findEvent(el, name);
if (ev) {
return ev.fire(
ev.element.getContext(
event || {},
event && !('original' in event) ? { original: {} } : {}
),
args
);
}
el = el.up && el.up.owner;
}
};
Context__proto__.readLink = function readLink (keypath, options) {
return this.ractive.readLink(this.resolve(keypath), options);
};
Context__proto__.resolve = function resolve (path, ractive) {
var ref = findModel(this, path);
var model = ref.model;
var instance = ref.instance;
return model ? model.getKeypath(ractive || instance) : path;
};
Context__proto__.reverse = function reverse (keypath) {
return modelReverse(findModel(this, keypath).model, []);
};
Context__proto__.set = function set$2 (keypath, value, options) {
return set(build$1(this, keypath, value), options);
};
Context__proto__.shift = function shift (keypath) {
return modelShift(findModel(this, keypath).model, []);
};
Context__proto__.splice = function splice (keypath, index, drop) {
var add = [], len = arguments.length - 3;
while ( len-- > 0 ) add[ len ] = arguments[ len + 3 ];
add.unshift(index, drop);
return modelSplice(findModel(this, keypath).model, add);
};
Context__proto__.sort = function sort (keypath) {
return modelSort(findModel(this, keypath).model, []);
};
Context__proto__.subtract = function subtract (keypath, d, options) {
var num = isNumber(d) ? d : 1;
var opts = isObjectType(d) ? d : options;
return set(
build$1(this, keypath, num).map(function (pair) {
var model = pair[0];
var val = pair[1];
var value = model.get();
if (!isNumeric(val) || !isNumeric(value)) { throw new Error('Cannot add non-numeric value'); }
return [model, value - val];
}),
opts
);
};
Context__proto__.toggle = function toggle (keypath, options) {
var ref = findModel(this, keypath);
var model = ref.model;
return set([[model, !model.get()]], options);
};
Context__proto__.unlink = function unlink (dest) {
var here = findModel(this, dest).model;
var promise = runloop.start();
if (here.owner && here.owner._link) { here.owner.unlink(); }
runloop.end();
return promise;
};
Context__proto__.unlisten = function unlisten (event, handler) {
this.element.off(event, handler);
};
Context__proto__.unshift = function unshift (keypath) {
var add = [], len = arguments.length - 1;
while ( len-- > 0 ) add[ len ] = arguments[ len + 1 ];
return modelUnshift(findModel(this, keypath).model, add);
};
Context__proto__.update = function update (keypath, options) {
return update$1(this.ractive, findModel(this, keypath).model, options);
};
Context__proto__.updateModel = function updateModel (keypath, cascade) {
var ref = findModel(this, keypath);
var model = ref.model;
var promise = runloop.start();
model.updateFromBindings(cascade);
runloop.end();
return promise;
};
// two-way binding related helpers
Context__proto__.isBound = function isBound () {
var ref = this.getBindingModel(this);
var model = ref.model;
return !!model;
};
Context__proto__.getBindingPath = function getBindingPath (ractive) {
var ref = this.getBindingModel(this);
var model = ref.model;
var instance = ref.instance;
if (model) { return model.getKeypath(ractive || instance); }
};
Context__proto__.getBinding = function getBinding () {
var ref = this.getBindingModel(this);
var model = ref.model;
if (model) { return model.get(true); }
};
Context__proto__.getBindingModel = function getBindingModel (ctx) {
var el = ctx.element;
return { model: el.binding && el.binding.model, instance: el.up.ractive };
};
Context__proto__.setBinding = function setBinding (value) {
var ref = this.getBindingModel(this);
var model = ref.model;
return set([[model, value]]);
};
Object.defineProperties( Context__proto__, prototypeAccessors );
Context.forRactive = getRactiveContext;
// circular deps are fun
extern.Context = Context;
// TODO: at some point perhaps this could support relative * keypaths?
function build$1(ctx, keypath, value) {
var sets = [];
// set multiple keypaths in one go
if (isObject(keypath)) {
for (var k in keypath) {
if (hasOwn(keypath, k)) {
sets.push([findModel(ctx, k).model, keypath[k]]);
}
}
} else {
// set a single keypath
sets.push([findModel(ctx, keypath).model, value]);
}
return sets;
}
function findModel(ctx, path) {
var frag = ctx.fragment;
if (!isString(path)) {
return { model: frag.findContext(), instance: path };
}
return { model: resolveReference(frag, path), instance: frag.ractive };
}
function findEvent(el, name) {
return el.events && el.events.find && el.events.find(function (e) { return ~e.template.n.indexOf(name); });
}
function Ractive$fire(eventName) {
var args = [], len = arguments.length - 1;
while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
var ctx;
// watch for reproxy
if (args[0] instanceof Context) {
var proto = args.shift();
ctx = create(proto);
assign(ctx, proto);
} else if (isObjectType(args[0]) && (args[0] === null || args[0].constructor === Object)) {
ctx = Context.forRactive(this, args.shift());
} else {
ctx = Context.forRactive(this);
}
return fireEvent(this, eventName, ctx, args);
}
function Ractive$get(keypath, opts) {
if (!isString(keypath)) { return this.viewmodel.get(true, keypath); }
var keys = splitKeypath(keypath);
var key = keys[0];
var model;
if (!this.viewmodel.has(key)) {
// if this is an inline component, we may need to create
// an implicit mapping
if (this.component && !this.isolated) {
model = resolveReference(this.fragment || new FakeFragment(this), key);
}
}
model = this.viewmodel.joinAll(keys);
return model.get(true, opts);
}
var query = doc && doc.querySelector;
function getContext$1(node) {
if (isString(node) && query) {
node = query.call(document, node);
}
var instances;
if (node) {
if (node._ractive) {
return node._ractive.proxy.getContext();
} else if ((instances = node.__ractive_instances__)) {
if (instances.length === 1) { return getRactiveContext(instances[0]); }
} else { return getContext$1(node.parentNode); }
}
}
function getContext$2(node, options) {
if (!node) { return getRactiveContext(this); }
if (isString(node)) {
node = this.find(node, options);
}
return getContext$1(node);
}
var html = 'http://www.w3.org/1999/xhtml';
var mathml = 'http://www.w3.org/1998/Math/MathML';
var svg$1 = 'http://www.w3.org/2000/svg';
var xlink = 'http://www.w3.org/1999/xlink';
var xml = 'http://www.w3.org/XML/1998/namespace';
var xmlns = 'http://www.w3.org/2000/xmlns';
var namespaces = { html: html, mathml: mathml, svg: svg$1, xlink: xlink, xml: xml, xmlns: xmlns };
var createElement;
var matches;
var div;
var methodNames;
var unprefixed;
var prefixed;
var i;
var j;
var makeFunction;
// Test for SVG support
if (!svg) {
/* istanbul ignore next */
createElement = function (type, ns, extend) {
if (ns && ns !== html) {
throw "This browser does not support namespaces other than http://www.w3.org/1999/xhtml. The most likely cause of this error is that you're trying to render SVG in an older browser. See http://ractive.js.org/support/#svgs for more information";
}
return extend ? doc.createElement(type, extend) : doc.createElement(type);
};
} else {
createElement = function (type, ns, extend) {
if (!ns || ns === html) {
return extend ? doc.createElement(type, extend) : doc.createElement(type);
}
return extend ? doc.createElementNS(ns, type, extend) : doc.createElementNS(ns, type);
};
}
function createDocumentFragment() {
return doc.createDocumentFragment();
}
function getElement(input) {
var output;
if (!input || typeof input === 'boolean') {
return;
}
/* istanbul ignore next */
if (!win || !doc || !input) {
return null;
}
// We already have a DOM node - no work to do. (Duck typing alert!)
if (input.nodeType) {
return input;
}
// Get node from string
if (isString(input)) {
// try ID first
output = doc.getElementById(input);
// then as selector, if possible
if (!output && doc.querySelector) {
try {
output = doc.querySelector(input);
} catch (e) {
/* this space intentionally left blank */
}
}
// did it work?
if (output && output.nodeType) {
return output;
}
}
// If we've been given a collection (jQuery, Zepto etc), extract the first item
if (input[0] && input[0].nodeType) {
return input[0];
}
return null;
}
if (!isClient) {
matches = null;
} else {
div = createElement('div');
methodNames = ['matches', 'matchesSelector'];
makeFunction = function(methodName) {
return function(node, selector) {
return node[methodName](selector);
};
};
i = methodNames.length;
while (i-- && !matches) {
unprefixed = methodNames[i];
if (div[unprefixed]) {
matches = makeFunction(unprefixed);
} else {
j = vendors.length;
while (j--) {
prefixed = vendors[i] + unprefixed.substr(0, 1).toUpperCase() + unprefixed.substring(1);
if (div[prefixed]) {
matches = makeFunction(prefixed);
break;
}
}
}
}
// IE8... and apparently phantom some?
/* istanbul ignore next */
if (!matches) {
matches = function(node, selector) {
var parentNode, i;
parentNode = node.parentNode;
if (!parentNode) {
// empty dummy <div>
div.innerHTML = '';
parentNode = div;
node = node.cloneNode();
div.appendChild(node);
}
var nodes = parentNode.querySelectorAll(selector);
i = nodes.length;
while (i--) {
if (nodes[i] === node) {
return true;
}
}
return false;
};
}
}
function detachNode(node) {
// stupid ie
// eslint-disable-next-line valid-typeof
if (node && typeof node.parentNode !== 'unknown' && node.parentNode) {
node.parentNode.removeChild(node);
}
return node;
}
function safeToStringValue(value) {
return value == null || (isNumber(value) && isNaN(value)) || !value.toString ? '' : '' + value;
}
function safeAttributeString(string) {
return safeToStringValue(string)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function Ractive$insert(target, anchor) {
if (!this.fragment.rendered) {
// TODO create, and link to, documentation explaining this
throw new Error(
'The API has changed - you must call `ractive.render(target[, anchor])` to render your Ractive instance. Once rendered you can use `ractive.insert()`.'
);
}
target = getElement(target);
anchor = getElement(anchor) || null;
if (!target) {
throw new Error('You must specify a valid target to insert into');
}
target.insertBefore(this.detach(), anchor);
this.el = target;
(target.__ractive_instances__ || (target.__ractive_instances__ = [])).push(this);
this.isDetached = false;
fireInsertHook(this);
}
function fireInsertHook(ractive) {
hooks.insert.fire(ractive);
ractive.findAllComponents('*').forEach(function (child) {
fireInsertHook(child.instance);
});
}
function link(there, here, options) {
var model;
var target = (options && (options.ractive || options.instance)) || this;
// may need to allow a mapping to resolve implicitly
var sourcePath = splitKeypath(there);
if (!target.viewmodel.has(sourcePath[0]) && target.component) {
model = resolveReference(target.component.up, sourcePath[0]);
model = model.joinAll(sourcePath.slice(1));
}
var src = model || target.viewmodel.joinAll(sourcePath);
var dest = this.viewmodel.joinAll(splitKeypath(here), { lastLink: false });
if (isUpstream(src, dest) || isUpstream(dest, src)) {
throw new Error('A keypath cannot be linked to itself.');
}
var promise = runloop.start();
dest.link(src, (options && options.keypath) || there);
runloop.end();
return promise;
}
function isUpstream(check, start) {
var model = start;
while (model) {
if (model === check || model.owner === check) { return true; }
model = model.target || model.parent;
}
}
var Observer = function Observer(ractive, model, callback, options) {
this.context = options.context || ractive;
this.callback = callback;
this.ractive = ractive;
this.keypath = options.keypath;
this.options = options;
if (model) { this.resolved(model); }
if (isFunction(options.old)) {
this.oldContext = create(ractive);
this.oldFn = options.old;
}
if (options.init !== false) {
this.dirty = true;
this.dispatch();
} else {
updateOld(this);
}
this.dirty = false;
};
var Observer__proto__ = Observer.prototype;
Observer__proto__.cancel = function cancel () {
this.cancelled = true;
if (this.model) {
this.model.unregister(this);
} else {
this.resolver.unbind();
}
removeFromArray(this.ractive._observers, this);
};
Observer__proto__.dispatch = function dispatch () {
if (!this.cancelled) {
this.callback.call(this.context, this.newValue, this.oldValue, this.keypath);
updateOld(this, true);
this.dirty = false;
}
};
Observer__proto__.handleChange = function handleChange () {
var this$1 = this;
if (!this.dirty) {
var newValue = this.model.get();
if (isEqual(newValue, this.oldValue)) { return; }
this.newValue = newValue;
if (this.options.strict && this.newValue === this.oldValue) { return; }
runloop.addObserver(this, this.options.defer);
this.dirty = true;
if (this.options.once) { runloop.scheduleTask(function () { return this$1.cancel(); }); }
} else {
// make sure the newValue stays updated in case this observer gets touched multiple times in one loop
this.newValue = this.model.get();
}
};
Observer__proto__.rebind = function rebind (next, previous) {
var this$1 = this;
next = rebindMatch(this.keypath, next, previous);
if (next === this.model) { return false; }
if (this.model) { this.model.unregister(this); }
if (next) { next.addShuffleTask(function () { return this$1.resolved(next); }); }
};
Observer__proto__.resolved = function resolved (model) {
this.model = model;
this.oldValue = undefined;
this.newValue = model.get();
model.register(this);
};
function updateOld(observer, fresh) {
var next = fresh
? observer.model
? observer.model.get()
: observer.newValue
: observer.newValue;
observer.oldValue = observer.oldFn
? observer.oldFn.call(observer.oldContext, undefined, next, observer.keypath)
: next;
}
var star$1 = /\*+/g;
var PatternObserver = function PatternObserver(ractive, baseModel, keys$$1, callback, options) {
var this$1 = this;
this.context = options.context || ractive;
this.ractive = ractive;
this.baseModel = baseModel;
this.keys = keys$$1;
this.callback = callback;
var pattern = keys$$1.join('\\.').replace(star$1, '(.+)');
var baseKeypath = (this.baseKeypath = baseModel.getKeypath(ractive));
this.pattern = new RegExp(("^" + (baseKeypath ? baseKeypath + '\\.' : '') + pattern + "$"));
this.recursive = keys$$1.length === 1 && keys$$1[0] === '**';
if (this.recursive) { this.keys = ['*']; }
if (options.old) {
this.oldContext = create(ractive);
this.oldFn = options.old;
}
this.oldValues = {};
this.newValues = {};
this.defer = options.defer;
this.once = options.once;
this.strict = options.strict;
this.dirty = false;
this.changed = [];
this.partial = false;
this.links = options.links;
var models = baseModel.findMatches(this.keys);
models.forEach(function (model) {
this$1.newValues[model.getKeypath(this$1.ractive)] = model.get();
});
if (options.init !== false) {
this.dispatch();
} else {
updateOld$1(this, this.newValues);
}
baseModel.registerPatternObserver(this);
};
var PatternObserver__proto__ = PatternObserver.prototype;
PatternObserver__proto__.cancel = function cancel () {
this.baseModel.unregisterPatternObserver(this);
removeFromArray(this.ractive._observers, this);
};
PatternObserver__proto__.dispatch = function dispatch () {
var this$1 = this;
var newValues = this.newValues;
this.newValues = {};
keys(newValues).forEach(function (keypath) {
var newValue = newValues[keypath];
var oldValue = this$1.oldValues[keypath];
if (this$1.strict && newValue === oldValue) { return; }
if (isEqual(newValue, oldValue)) { return; }
var args = [newValue, oldValue, keypath];
if (keypath) {
var wildcards = this$1.pattern.exec(keypath);
if (wildcards) {
args = args.concat(wildcards.slice(1));
}
}
this$1.callback.apply(this$1.context, args);
});
updateOld$1(this, newValues, this.partial);
this.dirty = false;
};
PatternObserver__proto__.notify = function notify (key) {
this.changed.push(key);
};
PatternObserver__proto__.shuffle = function shuffle (newIndices) {
var this$1 = this;
if (!isArray(this.baseModel.value)) { return; }
var max = this.baseModel.value.length;
for (var i = 0; i < newIndices.length; i++) {
if (newIndices[i] === -1 || newIndices[i] === i) { continue; }
this$1.changed.push([i]);
}
for (var i$1 = newIndices.touchedFrom; i$1 < max; i$1++) {
this$1.changed.push([i$1]);
}
};
PatternObserver__proto__.handleChange = function handleChange () {
var this$1 = this;
if (!this.dirty || this.changed.length) {
if (!this.dirty) { this.newValues = {}; }
if (!this.changed.length) {
this.baseModel.findMatches(this.keys).forEach(function (model) {
var keypath = model.getKeypath(this$1.ractive);
this$1.newValues[keypath] = model.get();
});
this.partial = false;
} else {
var count = 0;
if (this.recursive) {
this.changed.forEach(function (keys$$1) {
var model = this$1.baseModel.joinAll(keys$$1);
if (model.isLink && !this$1.links) { return; }
count++;
this$1.newValues[model.getKeypath(this$1.ractive)] = model.get();
});
} else {
var ok = this.baseModel.isRoot
? this.changed.map(function (keys$$1) { return keys$$1.map(escapeKey).join('.'); })
: this.changed.map(function (keys$$1) { return this$1.baseKeypath + '.' + keys$$1.map(escapeKey).join('.'); });
this.baseModel.findMatches(this.keys).forEach(function (model) {
var keypath = model.getKeypath(this$1.ractive);
var check = function (k) {
return (
(k.indexOf(keypath) === 0 &&
(k.length === keypath.length || k[keypath.length] === '.')) ||
(keypath.indexOf(k) === 0 &&
(k.length === keypath.length || keypath[k.length] === '.'))
);
};
// is this model on a changed keypath?
if (ok.filter(check).length) {
count++;
this$1.newValues[keypath] = model.get();
}
});
}
// no valid change triggered, so bail to avoid breakage
if (!count) { return; }
this.partial = true;
}
runloop.addObserver(this, this.defer);
this.dirty = true;
this.changed.length = 0;
if (this.once) { this.cancel(); }
}
};
function updateOld$1(observer, vals, partial) {
var olds = observer.oldValues;
if (observer.oldFn) {
if (!partial) { observer.oldValues = {}; }
keys(vals).forEach(function (k) {
var args = [olds[k], vals[k], k];
var parts = observer.pattern.exec(k);
if (parts) {
args.push.apply(args, parts.slice(1));
}
observer.oldValues[k] = observer.oldFn.apply(observer.oldContext, args);
});
} else {
if (partial) {
keys(vals).forEach(function (k) { return (olds[k] = vals[k]); });
} else {
observer.oldValues = vals;
}
}
}
function negativeOne() {
return -1;
}
var ArrayObserver = function ArrayObserver(ractive, model, callback, options) {
this.ractive = ractive;
this.model = model;
this.keypath = model.getKeypath();
this.callback = callback;
this.options = options;
this.pending = null;
model.register(this);
if (options.init !== false) {
this.sliced = [];
this.shuffle([]);
this.dispatch();
} else {
this.sliced = this.slice();
}
};
var ArrayObserver__proto__ = ArrayObserver.prototype;
ArrayObserver__proto__.cancel = function cancel () {
this.model.unregister(this);
removeFromArray(this.ractive._observers, this);
};
ArrayObserver__proto__.dispatch = function dispatch () {
this.callback(this.pending);
this.pending = null;
if (this.options.once) { this.cancel(); }
};
ArrayObserver__proto__.handleChange = function handleChange (path) {
if (this.pending) {
// post-shuffle
runloop.addObserver(this, this.options.defer);
} else if (!path) {
// entire array changed
this.shuffle(this.sliced.map(negativeOne));
this.handleChange();
}
};
ArrayObserver__proto__.shuffle = function shuffle (newIndices) {
var this$1 = this;
var newValue = this.slice();
var inserted = [];
var deleted = [];
var start;
var hadIndex = {};
newIndices.forEach(function (newIndex, oldIndex) {
hadIndex[newIndex] = true;
if (newIndex !== oldIndex && start === undefined) {
start = oldIndex;
}
if (newIndex === -1) {
deleted.push(this$1.sliced[oldIndex]);
}
});
if (start === undefined) { start = newIndices.length; }
var len = newValue.length;
for (var i = 0; i < len; i += 1) {
if (!hadIndex[i]) { inserted.push(newValue[i]); }
}
this.pending = { inserted: inserted, deleted: deleted, start: start };
this.sliced = newValue;
};
ArrayObserver__proto__.slice = function slice () {
var value = this.model.get();
return isArray(value) ? value.slice() : [];
};
function observe(keypath, callback, options) {
var this$1 = this;
var observers = [];
var map;
var opts;
if (isObject(keypath)) {
map = keypath;
opts = callback || {};
} else {
if (isFunction(keypath)) {
map = { '': keypath };
opts = callback || {};
} else {
map = {};
map[keypath] = callback;
opts = options || {};
}
}
var silent = false;
keys(map).forEach(function (keypath) {
var callback = map[keypath];
var caller = function() {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
if (silent) { return; }
return callback.apply(this, args);
};
var keypaths = keypath.split(' ');
if (keypaths.length > 1) { keypaths = keypaths.filter(function (k) { return k; }); }
keypaths.forEach(function (keypath) {
opts.keypath = keypath;
var observer = createObserver(this$1, keypath, caller, opts);
if (observer) { observers.push(observer); }
});
});
// add observers to the Ractive instance, so they can be
// cancelled on ractive.teardown()
this._observers.push.apply(this._observers, observers);
return {
cancel: function () { return observers.forEach(function (o) { return o.cancel(); }); },
isSilenced: function () { return silent; },
silence: function () { return (silent = true); },
resume: function () { return (silent = false); }
};
}
function createObserver(ractive, keypath, callback, options) {
var keys$$1 = splitKeypath(keypath);
var wildcardIndex = keys$$1.indexOf('*');
if (!~wildcardIndex) { wildcardIndex = keys$$1.indexOf('**'); }
options.fragment = options.fragment || ractive.fragment;
var model;
if (!options.fragment) {
model = ractive.viewmodel.joinKey(keys$$1[0]);
} else {
// .*.whatever relative wildcard is a special case because splitkeypath doesn't handle the leading .
if (~keys$$1[0].indexOf('.*')) {
model = options.fragment.findContext();
wildcardIndex = 0;
keys$$1[0] = keys$$1[0].slice(1);
} else {
model =
wildcardIndex === 0
? options.fragment.findContext()
: resolveReference(options.fragment, keys$$1[0]);
}
}
// the model may not exist key
if (!model) { model = ractive.viewmodel.joinKey(keys$$1[0]); }
if (!~wildcardIndex) {
model = model.joinAll(keys$$1.slice(1));
if (options.array) {
return new ArrayObserver(ractive, model, callback, options);
} else {
return new Observer(ractive, model, callback, options);
}
} else {
var double = keys$$1.indexOf('**');
if (~double) {
if (double + 1 !== keys$$1.length || ~keys$$1.indexOf('*')) {
warnOnceIfDebug(
"Recursive observers may only specify a single '**' at the end of the path."
);
return;
}
}
model = model.joinAll(keys$$1.slice(1, wildcardIndex));
return new PatternObserver(ractive, model, keys$$1.slice(wildcardIndex), callback, options);
}
}
var onceOptions = { init: false, once: true };
function observeOnce(keypath, callback, options) {
if (isObject(keypath) || isFunction(keypath)) {
options = assign(callback || {}, onceOptions);
return this.observe(keypath, options);
}
options = assign(options || {}, onceOptions);
return this.observe(keypath, callback, options);
}
var trim = function (str) { return str.trim(); };
var notEmptyString = function (str) { return str !== ''; };
function Ractive$off(eventName, callback) {
var this$1 = this;
// if no event is specified, remove _all_ event listeners
if (!eventName) {
this._subs = {};
} else {
// Handle multiple space-separated event names
var eventNames = eventName
.split(' ')
.map(trim)
.filter(notEmptyString);
eventNames.forEach(function (event) {
var subs = this$1._subs[event];
// if given a specific callback to remove, remove only it
if (subs && callback) {
var entry = subs.find(function (s) { return s.callback === callback; });
if (entry) {
removeFromArray(subs, entry);
entry.off = true;
if (event.indexOf('.')) { this$1._nsSubs--; }
}
} else if (subs) {
// otherwise, remove all listeners for this event
if (event.indexOf('.')) { this$1._nsSubs -= subs.length; }
subs.length = 0;
}
});
}
return this;
}
function Ractive$on(eventName, callback) {
var this$1 = this;
// eventName may already be a map
var map = isObjectType(eventName) ? eventName : {};
// or it may be a string along with a callback
if (isString(eventName)) { map[eventName] = callback; }
var silent = false;
var events = [];
var loop = function ( k ) {
var callback$1 = map[k];
var caller = function() {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
if (!silent) { return callback$1.apply(this, args); }
};
var entry = {
callback: callback$1,
handler: caller
};
if (hasOwn(map, k)) {
var names = k
.split(' ')
.map(trim)
.filter(notEmptyString);
names.forEach(function (n) {
(this$1._subs[n] || (this$1._subs[n] = [])).push(entry);
if (n.indexOf('.')) { this$1._nsSubs++; }
events.push([n, entry]);
});
}
};
for (var k in map) loop( k );
return {
cancel: function () { return events.forEach(function (e) { return this$1.off(e[0], e[1].callback); }); },
isSilenced: function () { return silent; },
silence: function () { return (silent = true); },
resume: function () { return (silent = false); }
};
}
function Ractive$once(eventName, handler) {
var listener = this.on(eventName, function() {
handler.apply(this, arguments);
listener.cancel();
});
// so we can still do listener.cancel() manually
return listener;
}
var pop = makeArrayMethod('pop').path;
var push = makeArrayMethod('push').path;
function readLink(keypath, options) {
if ( options === void 0 ) options = {};
var path = splitKeypath(keypath);
if (this.viewmodel.has(path[0])) {
var model = this.viewmodel.joinAll(path);
if (!model.isLink) { return; }
while ((model = model.target) && options.canonical !== false) {
if (!model.isLink) { break; }
}
if (model) { return { ractive: model.root.ractive, keypath: model.getKeypath() }; }
}
}
var PREFIX = '/* Ractive.js component styles */';
// Holds current definitions of styles.
var styleDefinitions = [];
// Flag to tell if we need to update the CSS
var isDirty = false;
// These only make sense on the browser. See additional setup below.
var styleElement = null;
var useCssText = null;
function addCSS(styleDefinition) {
styleDefinitions.push(styleDefinition);
isDirty = true;
}
function applyCSS(force) {
var styleElement = style();
// Apply only seems to make sense when we're in the DOM. Server-side renders
// can call toCSS to get the updated CSS.
if (!styleElement || (!force && !isDirty)) { return; }
if (useCssText) {
styleElement.styleSheet.cssText = getCSS(null);
} else {
styleElement.innerHTML = getCSS(null);
}
isDirty = false;
}
function getCSS(cssIds) {
var filteredStyleDefinitions = cssIds
? styleDefinitions.filter(function (style) { return ~cssIds.indexOf(style.id); })
: styleDefinitions;
filteredStyleDefinitions.forEach(function (d) { return (d.applied = true); });
return filteredStyleDefinitions.reduce(
function (styles, style) { return ("" + (styles ? (styles + "\n\n/* {" + (style.id) + "} */\n" + (style.styles)) : '')); },
PREFIX
);
}
function style() {
// If we're on the browser, additional setup needed.
if (doc && !styleElement) {
styleElement = doc.createElement('style');
styleElement.type = 'text/css';
styleElement.setAttribute('data-ractive-css', '');
doc.getElementsByTagName('head')[0].appendChild(styleElement);
useCssText = !!styleElement.styleSheet;
}
return styleElement;
}
var adaptConfigurator = {
extend: function (Parent, proto, options) {
proto.adapt = combine(proto.adapt, ensureArray(options.adapt));
},
init: function init() {}
};
var remove = /\/\*(?:[\s\S]*?)\*\//g;
var escape = /url\(\s*(['"])(?:\\[\s\S]|(?!\1).)*\1\s*\)|url\((?:\\[\s\S]|[^)])*\)|(['"])(?:\\[\s\S]|(?!\2).)*\2/gi;
var value = /\0(\d+)/g;
// Removes comments and strings from the given CSS to make it easier to parse.
// Callback receives the cleaned CSS and a function which can be used to put
// the removed strings back in place after parsing is done.
function cleanCss(css, callback, additionalReplaceRules) {
if ( additionalReplaceRules === void 0 ) additionalReplaceRules = [];
var values = [];
var reconstruct = function (css) { return css.replace(value, function (match, n) { return values[n]; }); };
css = css.replace(escape, function (match) { return ("\u0000" + (values.push(match) - 1)); }).replace(remove, '');
additionalReplaceRules.forEach(function (pattern) {
css = css.replace(pattern, function (match) { return ("\u0000" + (values.push(match) - 1)); });
});
return callback(css, reconstruct);
}
var selectorsPattern = /(?:^|\}|\{|\x01)\s*([^\{\}\0\x01]+)\s*(?=\{)/g;
var importPattern = /@import\s*\([^)]*\)\s*;?/gi;
var importEndPattern = /\x01/g;
var keyframesDeclarationPattern = /@keyframes\s+[^\{\}]+\s*\{(?:[^{}]+|\{[^{}]+})*}/gi;
var selectorUnitPattern = /((?:(?:\[[^\]]+\])|(?:[^\s\+\>~:]))+)((?:::?[^\s\+\>\~\(:]+(?:\([^\)]+\))?)*\s*[\s\+\>\~]?)\s*/g;
var excludePattern = /^(?:@|\d+%)/;
var dataRvcGuidPattern = /\[data-ractive-css~="\{[a-z0-9-]+\}"]/g;
function trim$1(str) {
return str.trim();
}
function extractString(unit) {
return unit.str;
}
function transformSelector(selector, parent) {
var selectorUnits = [];
var match;
while ((match = selectorUnitPattern.exec(selector))) {
selectorUnits.push({
str: match[0],
base: match[1],
modifiers: match[2]
});
}
// For each simple selector within the selector, we need to create a version
// that a) combines with the id, and b) is inside the id
var base = selectorUnits.map(extractString);
var transformed = [];
var i = selectorUnits.length;
while (i--) {
var appended = base.slice();
// Pseudo-selectors should go after the attribute selector
var unit = selectorUnits[i];
appended[i] = unit.base + parent + unit.modifiers || '';
var prepended = base.slice();
prepended[i] = parent + ' ' + prepended[i];
transformed.push(appended.join(' '), prepended.join(' '));
}
return transformed.join(', ');
}
function transformCss(css, id) {
var dataAttr = "[data-ractive-css~=\"{" + id + "}\"]";
var transformed;
if (dataRvcGuidPattern.test(css)) {
transformed = css.replace(dataRvcGuidPattern, dataAttr);
} else {
transformed = cleanCss(
css,
function (css, reconstruct) {
css = css
.replace(importPattern, '$&\x01')
.replace(selectorsPattern, function (match, $1) {
// don't transform at-rules and keyframe declarations
if (excludePattern.test($1)) { return match; }
var selectors = $1.split(',').map(trim$1);
var transformed =
selectors.map(function (selector) { return transformSelector(selector, dataAttr); }).join(', ') + ' ';
return match.replace($1, transformed);
})
.replace(importEndPattern, '');
return reconstruct(css);
},
[keyframesDeclarationPattern]
);
}
return transformed;
}
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
function uuid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
function setCSSData(keypath, value, options) {
var opts = isObjectType(keypath) ? value : options;
var model = this._cssModel;
model.locked = true;
var promise = set(build({ viewmodel: model }, keypath, value, true), opts);
model.locked = false;
var cascade = runloop.start();
this.extensions.forEach(function (e) {
var model = e._cssModel;
model.mark();
model.downstreamChanged('', 1);
});
runloop.end();
applyChanges(this, !opts || opts.apply !== false);
return promise.then(function () { return cascade; });
}
function applyChanges(component, apply) {
var local = recomputeCSS(component);
var child = component.extensions
.map(function (e) { return applyChanges(e, false); })
.reduce(function (a, c) { return c || a; }, false);
if (apply && (local || child)) {
var def = component._cssDef;
if (!def || (def && def.applied)) { applyCSS(true); }
}
return local || child;
}
function recomputeCSS(component) {
var css = component.css;
if (!isFunction(css)) { return; }
var def = component._cssDef;
var result = evalCSS(component, css);
var styles = def.transform ? transformCss(result, def.id) : result;
if (def.styles === styles) { return; }
def.styles = styles;
return true;
}
var CSSModel = (function (SharedModel) {
function CSSModel(component) {
SharedModel.call(this, component.cssData, '@style');
this.component = component;
}
if ( SharedModel ) CSSModel.__proto__ = SharedModel;
var CSSModel__proto__ = CSSModel.prototype = Object.create( SharedModel && SharedModel.prototype );
CSSModel__proto__.constructor = CSSModel;
CSSModel__proto__.downstreamChanged = function downstreamChanged (path, depth) {
if (this.locked) { return; }
var component = this.component;
component.extensions.forEach(function (e) {
var model = e._cssModel;
model.mark();
model.downstreamChanged(path, depth || 1);
});
if (!depth) {
applyChanges(component, true);
}
};
return CSSModel;
}(SharedModel));
var hasCurly = /\{/;
var cssConfigurator = {
name: 'css',
// Called when creating a new component definition
extend: function (Parent, proto, options, Child) {
Child._cssIds = gatherIds(Parent);
defineProperty(Child, 'cssData', {
configurable: true,
value: assign(create(Parent.cssData), options.cssData || {})
});
defineProperty(Child, '_cssModel', {
configurable: true,
value: new CSSModel(Child)
});
if (options.css) { initCSS(options, Child, proto); }
},
// Called when creating a new component instance
init: function (Parent, target, options) {
if (!options.css) { return; }
warnIfDebug("\nThe css option is currently not supported on a per-instance basis and will be discarded. Instead, we recommend instantiating from a component definition with a css option.\n\nconst Component = Ractive.extend({\n\t...\n\tcss: '/* your css */',\n\t...\n});\n\nconst componentInstance = new Component({ ... })\n\t\t");
}
};
function gatherIds(start) {
var cmp = start;
var ids = [];
while (cmp) {
if (cmp.prototype.cssId) { ids.push(cmp.prototype.cssId); }
cmp = cmp.Parent;
}
return ids;
}
function evalCSS(component, css) {
if (isString(css)) { return css; }
var cssData = component.cssData;
var model = component._cssModel;
var data = function data(path) {
return model.joinAll(splitKeypath(path)).get();
};
data.__proto__ = cssData;
var result = css.call(component, data);
return isString(result) ? result : '';
}
function initCSS(options, target, proto) {
var css =
options.css === true
? ''
: isString(options.css) && !hasCurly.test(options.css)
? getElement(options.css) || options.css
: options.css;
var cssProp = css;
var id = options.cssId || uuid();
if (isObjectType(css)) {
css = 'textContent' in css ? css.textContent : css.innerHTML;
cssProp = css;
} else if (isFunction(css)) {
cssProp = css;
css = evalCSS(target, css);
}
var def = {
transform: 'noCSSTransform' in options ? !options.noCSSTransform : !options.noCssTransform
};
defineProperty(target, '_cssDef', { configurable: true, value: def });
defineProperty(target, 'css', {
get: function get() {
return cssProp;
},
set: function set(next) {
cssProp = next;
var css = evalCSS(target, cssProp);
var styles = def.styles;
def.styles = def.transform ? transformCss(css, id) : css;
if (def.applied && styles !== def.styles) { applyCSS(true); }
}
});
def.styles = def.transform ? transformCss(css, id) : css;
def.id = proto.cssId = id;
target._cssIds.push(id);
addCSS(target._cssDef);
}
function validate(data) {
// Warn if userOptions.data is a non-POJO
if (data && data.constructor !== Object) {
if (isFunction(data)) {
// TODO do we need to support this in the new Ractive() case?
} else if (!isObjectType(data)) {
fatal(("data option must be an object or a function, `" + data + "` is not valid"));
} else {
warnIfDebug(
'If supplied, options.data should be a plain JavaScript object - using a non-POJO as the root object may work, but is discouraged'
);
}
}
}
var dataConfigurator = {
name: 'data',
extend: function (Parent, proto, options) {
var key;
var value;
// check for non-primitives, which could cause mutation-related bugs
if (options.data && isObject(options.data)) {
for (key in options.data) {
value = options.data[key];
if (value && isObjectType(value)) {
if (isObject(value) || isArray(value)) {
warnIfDebug("Passing a `data` option with object and array properties to Ractive.extend() is discouraged, as mutating them is likely to cause bugs. Consider using a data function instead:\n\n // this...\n data: function () {\n return {\n myObject: {}\n };\n })\n\n // instead of this:\n data: {\n myObject: {}\n }");
}
}
}
}
proto.data = combine$1(proto.data, options.data);
},
init: function (Parent, ractive, options) {
var result = combine$1(Parent.prototype.data, options.data);
if (isFunction(result)) { result = result.call(ractive); }
// bind functions to the ractive instance at the top level,
// unless it's a non-POJO (in which case alarm bells should ring)
if (result && result.constructor === Object) {
for (var prop in result) {
if (isFunction(result[prop])) {
var value = result[prop];
result[prop] = bind(value, ractive);
result[prop]._r_unbound = value;
}
}
}
return result || {};
},
reset: function reset(ractive) {
var result = this.init(ractive.constructor, ractive, ractive.viewmodel);
ractive.viewmodel.root.set(result);
return true;
}
};
function emptyData() {
return {};
}
function combine$1(parentValue, childValue) {
validate(childValue);
var parentIsFn = isFunction(parentValue);
// Very important, otherwise child instance can become
// the default data object on Ractive or a component.
// then ractive.set() ends up setting on the prototype!
if (!childValue && !parentIsFn) {
// this needs to be a function so that it can still inherit parent defaults
childValue = emptyData;
}
var childIsFn = isFunction(childValue);
// Fast path, where we just need to copy properties from
// parent to child
if (!parentIsFn && !childIsFn) {
return fromProperties(childValue, parentValue);
}
return function() {
var child = childIsFn ? callDataFunction(childValue, this) : childValue;
var parent = parentIsFn ? callDataFunction(parentValue, this) : parentValue;
return fromProperties(child, parent);
};
}
function callDataFunction(fn, context) {
var data = fn.call(context);
if (!data) { return; }
if (!isObjectType(data)) {
fatal('Data function must return an object');
}
if (data.constructor !== Object) {
warnOnceIfDebug(
'Data function returned something other than a plain JavaScript object. This might work, but is strongly discouraged'
);
}
return data;
}
function fromProperties(primary, secondary) {
if (primary && secondary) {
for (var key in secondary) {
if (!(key in primary)) {
primary[key] = secondary[key];
}
}
return primary;
}
return primary || secondary;
}
var templateConfigurator = {
name: 'template',
extend: function extend(Parent, proto, options) {
// only assign if exists
if ('template' in options) {
var template = options.template;
if (isFunction(template)) {
proto.template = template;
} else {
proto.template = parseTemplate(template, proto);
}
}
},
init: function init(Parent, ractive, options) {
// TODO because of prototypal inheritance, we might just be able to use
// ractive.template, and not bother passing through the Parent object.
// At present that breaks the test mocks' expectations
var template = 'template' in options ? options.template : Parent.prototype.template;
template = template || { v: TEMPLATE_VERSION, t: [] };
if (isFunction(template)) {
var fn = template;
template = getDynamicTemplate(ractive, fn);
ractive._config.template = {
fn: fn,
result: template
};
}
template = parseTemplate(template, ractive);
// TODO the naming of this is confusing - ractive.template refers to [...],
// but Component.prototype.template refers to {v:1,t:[],p:[]}...
// it's unnecessary, because the developer never needs to access
// ractive.template
ractive.template = template.t;
if (template.p) {
extendPartials(ractive.partials, template.p);
}
},
reset: function reset(ractive) {
var result = resetValue(ractive);
if (result) {
var parsed = parseTemplate(result, ractive);
ractive.template = parsed.t;
extendPartials(ractive.partials, parsed.p, true);
return true;
}
}
};
function resetValue(ractive) {
var initial = ractive._config.template;
// If this isn't a dynamic template, there's nothing to do
if (!initial || !initial.fn) {
return;
}
var result = getDynamicTemplate(ractive, initial.fn);
// TODO deep equality check to prevent unnecessary re-rendering
// in the case of already-parsed templates
if (result !== initial.result) {
initial.result = result;
return result;
}
}
function getDynamicTemplate(ractive, fn) {
return fn.call(ractive, {
fromId: parser.fromId,
isParsed: parser.isParsed,
parse: function parse(template, options) {
if ( options === void 0 ) options = parser.getParseOptions(ractive);
return parser.parse(template, options);
}
});
}
function parseTemplate(template, ractive) {
if (isString(template)) {
// parse will validate and add expression functions
template = parseAsString(template, ractive);
} else {
// need to validate and add exp for already parsed template
validate$1(template);
addFunctions(template);
}
return template;
}
function parseAsString(template, ractive) {
// ID of an element containing the template?
if (template[0] === '#') {
template = parser.fromId(template);
}
return parser.parseFor(template, ractive);
}
function validate$1(template) {
// Check that the template even exists
if (template == undefined) {
throw new Error(("The template cannot be " + template + "."));
} else if (!isNumber(template.v)) {
// Check the parsed template has a version at all
throw new Error(
"The template parser was passed a non-string template, but the template doesn't have a version. Make sure you're passing in the template you think you are."
);
} else if (template.v !== TEMPLATE_VERSION) {
// Check we're using the correct version
throw new Error(
("Mismatched template version (expected " + TEMPLATE_VERSION + ", got " + (template.v) + ") Please ensure you are using the latest version of Ractive.js in your build process as well as in your app")
);
}
}
function extendPartials(existingPartials, newPartials, overwrite) {
if (!newPartials) { return; }
// TODO there's an ambiguity here - we need to overwrite in the `reset()`
// case, but not initially...
for (var key in newPartials) {
if (overwrite || !hasOwn(existingPartials, key)) {
existingPartials[key] = newPartials[key];
}
}
}
var registryNames = [
'adaptors',
'components',
'computed',
'decorators',
'easing',
'events',
'helpers',
'interpolators',
'partials',
'transitions'
];
var registriesOnDefaults = ['computed', 'helpers'];
var Registry = function Registry(name, useDefaults) {
this.name = name;
this.useDefaults = useDefaults;
};
var Registry__proto__ = Registry.prototype;
Registry__proto__.extend = function extend (Parent, proto, options) {
var parent = this.useDefaults ? Parent.defaults : Parent;
var target = this.useDefaults ? proto : proto.constructor;
this.configure(parent, target, options);
};
Registry__proto__.init = function init () {
// noop
};
Registry__proto__.configure = function configure (Parent, target, options) {
var name = this.name;
var option = options[name];
var registry = create(Parent[name]);
assign(registry, option);
target[name] = registry;
if (name === 'partials' && target[name]) {
keys(target[name]).forEach(function (key) {
addFunctions(target[name][key]);
});
}
};
Registry__proto__.reset = function reset (ractive) {
var registry = ractive[this.name];
var changed = false;
keys(registry).forEach(function (key) {
var item = registry[key];
if (item._fn) {
if (item._fn.isOwner) {
registry[key] = item._fn;
} else {
delete registry[key];
}
changed = true;
}
});
return changed;
};
var registries = registryNames.map(function (name) {
var putInDefaults = registriesOnDefaults.indexOf(name) > -1;
return new Registry(name, putInDefaults);
});
function wrap(parent, name, method) {
if (!/_super/.test(method)) { return method; }
function wrapper() {
var superMethod = getSuperMethod(wrapper._parent, name);
var hasSuper = '_super' in this;
var oldSuper = this._super;
this._super = superMethod;
var result = method.apply(this, arguments);
if (hasSuper) {
this._super = oldSuper;
} else {
delete this._super;
}
return result;
}
wrapper._parent = parent;
wrapper._method = method;
return wrapper;
}
function getSuperMethod(parent, name) {
if (name in parent) {
var value = parent[name];
return isFunction(value) ? value : function () { return value; };
}
return noop;
}
function getMessage(deprecated, correct, isError) {
return (
"options." + deprecated + " has been deprecated in favour of options." + correct + "." +
(isError ? (" You cannot specify both options, please use options." + correct + ".") : '')
);
}
function deprecateOption(options, deprecatedOption, correct) {
if (deprecatedOption in options) {
if (!(correct in options)) {
warnIfDebug(getMessage(deprecatedOption, correct));
options[correct] = options[deprecatedOption];
} else {
throw new Error(getMessage(deprecatedOption, correct, true));
}
}
}
function deprecate(options) {
deprecateOption(options, 'beforeInit', 'onconstruct');
deprecateOption(options, 'init', 'onrender');
deprecateOption(options, 'complete', 'oncomplete');
deprecateOption(options, 'eventDefinitions', 'events');
// Using extend with Component instead of options,
// like Human.extend( Spider ) means adaptors as a registry
// gets copied to options. So we have to check if actually an array
if (isArray(options.adaptors)) {
deprecateOption(options, 'adaptors', 'adapt');
}
}
var config = {
extend: function (Parent, proto, options, Child) { return configure('extend', Parent, proto, options, Child); },
init: function (Parent, ractive, options) { return configure('init', Parent, ractive, options); },
reset: function (ractive) { return order.filter(function (c) { return c.reset && c.reset(ractive); }).map(function (c) { return c.name; }); }
};
var custom = {
adapt: adaptConfigurator,
computed: config,
css: cssConfigurator,
data: dataConfigurator,
helpers: config,
template: templateConfigurator
};
var defaultKeys = keys(defaults);
var isStandardKey = makeObj(defaultKeys.filter(function (key) { return !custom[key]; }));
// blacklisted keys that we don't double extend
var isBlacklisted = makeObj(
defaultKeys.concat(registries.map(function (r) { return r.name; }), ['on', 'observe', 'attributes', 'cssData', 'use'])
);
var order = [].concat(
defaultKeys.filter(function (key) { return !registries[key] && !custom[key]; }),
registries,
//custom.data,
custom.template,
custom.css
);
function configure(method, Parent, target, options, Child) {
deprecate(options);
for (var key in options) {
if (hasOwn(isStandardKey, key)) {
var value = options[key];
// warn the developer if they passed a function and ignore its value
// NOTE: we allow some functions on "el" because we duck type element lists
// and some libraries or ef'ed-up virtual browsers (phantomJS) return a
// function object as the result of querySelector methods
if (key !== 'el' && isFunction(value)) {
warnIfDebug(
(key + " is a Ractive option that does not expect a function and will be ignored"),
method === 'init' ? target : null
);
} else {
target[key] = value;
}
}
}
// disallow combination of `append` and `enhance`
if (target.append && target.enhance) {
throw new Error('Cannot use append and enhance at the same time');
}
registries.forEach(function (registry) {
registry[method](Parent, target, options, Child);
});
adaptConfigurator[method](Parent, target, options, Child);
templateConfigurator[method](Parent, target, options, Child);
cssConfigurator[method](Parent, target, options, Child);
extendOtherMethods(Parent.prototype, target, options);
}
var _super = /\b_super\b/;
function extendOtherMethods(parent, target, options) {
for (var key in options) {
if (!isBlacklisted[key] && hasOwn(options, key)) {
var member = options[key];
// if this is a method that overwrites a method, wrap it:
if (isFunction(member)) {
if (
(key in proto$9 ||
(key.slice(0, 2) === 'on' && key.slice(2) in hooks && key in target)) &&
!_super.test(member.toString())
) {
warnIfDebug(
("Overriding Ractive prototype function '" + key + "' without calling the '" + _super + "' method can be very dangerous.")
);
}
member = wrap(parent, key, member);
}
target[key] = member;
}
}
}
function makeObj(array) {
var obj = {};
array.forEach(function (x) { return (obj[x] = true); });
return obj;
}
var Item = function Item(options) {
this.up = options.up;
this.ractive = options.up.ractive;
this.template = options.template;
this.index = options.index;
this.type = options.template.t;
this.dirty = false;
};
var Item__proto__ = Item.prototype;
Item__proto__.bubble = function bubble () {
if (!this.dirty) {
this.dirty = true;
this.up.bubble();
}
};
Item__proto__.destroyed = function destroyed () {
if (this.fragment) { this.fragment.destroyed(); }
};
Item__proto__.find = function find () {
return null;
};
Item__proto__.findComponent = function findComponent () {
return null;
};
Item__proto__.findNextNode = function findNextNode () {
return this.up.findNextNode(this);
};
Item__proto__.rebound = function rebound (update) {
if (this.fragment) { this.fragment.rebound(update); }
};
Item__proto__.shuffled = function shuffled () {
if (this.fragment) { this.fragment.shuffled(); }
};
Item__proto__.valueOf = function valueOf () {
return this.toString();
};
Item.prototype.findAll = noop;
Item.prototype.findAllComponents = noop;
var ContainerItem = (function (Item) {
function ContainerItem(options) {
Item.call(this, options);
}
if ( Item ) ContainerItem.__proto__ = Item;
var ContainerItem__proto__ = ContainerItem.prototype = Object.create( Item && Item.prototype );
ContainerItem__proto__.constructor = ContainerItem;
ContainerItem__proto__.detach = function detach () {
return this.fragment ? this.fragment.detach() : createDocumentFragment();
};
ContainerItem__proto__.find = function find (selector) {
if (this.fragment) {
return this.fragment.find(selector);
}
};
ContainerItem__proto__.findAll = function findAll (selector, options) {
if (this.fragment) {
this.fragment.findAll(selector, options);
}
};
ContainerItem__proto__.findComponent = function findComponent (name) {
if (this.fragment) {
return this.fragment.findComponent(name);
}
};
ContainerItem__proto__.findAllComponents = function findAllComponents (name, options) {
if (this.fragment) {
this.fragment.findAllComponents(name, options);
}
};
ContainerItem__proto__.firstNode = function firstNode (skipParent) {
return this.fragment && this.fragment.firstNode(skipParent);
};
ContainerItem__proto__.toString = function toString (escape) {
return this.fragment ? this.fragment.toString(escape) : '';
};
return ContainerItem;
}(Item));
var ComputationChild = (function (Model) {
function ComputationChild(parent, key) {
Model.call(this, parent, key);
this.isReadonly = !this.root.ractive.syncComputedChildren;
this.dirty = true;
this.isComputed = true;
}
if ( Model ) ComputationChild.__proto__ = Model;
var ComputationChild__proto__ = ComputationChild.prototype = Object.create( Model && Model.prototype );
ComputationChild__proto__.constructor = ComputationChild;
var prototypeAccessors$1 = { setRoot: {} };
prototypeAccessors$1.setRoot.get = function () {
return this.parent.setRoot;
};
ComputationChild__proto__.applyValue = function applyValue (value) {
Model.prototype.applyValue.call(this, value);
if (!this.isReadonly) {
var source = this.parent;
// computed models don't have a shuffle method
while (source && source.shuffle) {
source = source.parent;
}
if (source) {
source.dependencies.forEach(mark);
}
}
if (this.setRoot) {
this.setRoot.set(this.setRoot.value);
}
};
ComputationChild__proto__.get = function get (shouldCapture, opts) {
if (shouldCapture) { capture(this); }
if (this.dirty) {
this.dirty = false;
var parentValue = this.parent.get();
this.value = parentValue ? parentValue[this.key] : undefined;
if (this.wrapper) { this.newWrapperValue = this.value; }
this.adapt();
}
return (opts && 'unwrap' in opts ? opts.unwrap !== false : shouldCapture) && this.wrapper
? this.wrapperValue
: this.value;
};
ComputationChild__proto__.handleChange = function handleChange$2 () {
if (this.dirty) { return; }
this.dirty = true;
if (this.boundValue) { this.boundValue = null; }
this.links.forEach(marked);
this.deps.forEach(handleChange);
this.children.forEach(handleChange);
};
ComputationChild__proto__.joinKey = function joinKey (key) {
if (key === undefined || key === '') { return this; }
if (!hasOwn(this.childByKey, key)) {
var child = new ComputationChild(this, key);
this.children.push(child);
this.childByKey[key] = child;
}
return this.childByKey[key];
};
Object.defineProperties( ComputationChild__proto__, prototypeAccessors$1 );
return ComputationChild;
}(Model));
/* global console */
/* eslint no-console:"off" */
var Computation = (function (Model) {
function Computation(parent, signature, key) {
Model.call(this, parent, key);
this.signature = signature;
this.isReadonly = !this.signature.setter;
this.isComputed = true;
this.dependencies = [];
this.children = [];
this.childByKey = {};
this.deps = [];
this.dirty = true;
// TODO: is there a less hackish way to do this?
this.shuffle = undefined;
}
if ( Model ) Computation.__proto__ = Model;
var Computation__proto__ = Computation.prototype = Object.create( Model && Model.prototype );
Computation__proto__.constructor = Computation;
var prototypeAccessors$2 = { setRoot: {} };
prototypeAccessors$2.setRoot.get = function () {
if (this.signature.setter) { return this; }
};
Computation__proto__.get = function get (shouldCapture, opts) {
if (shouldCapture) { capture(this); }
if (this.dirty) {
this.dirty = false;
var old = this.value;
this.value = this.getValue();
// this may cause a view somewhere to update, so it must be in a runloop
if (!runloop.active()) {
runloop.start();
if (!isEqual(old, this.value)) { this.notifyUpstream(); }
runloop.end();
} else {
if (!isEqual(old, this.value)) { this.notifyUpstream(); }
}
if (this.wrapper) { this.newWrapperValue = this.value; }
this.adapt();
}
// if capturing, this value needs to be unwrapped because it's for external use
return maybeBind(
this,
// if unwrap is supplied, it overrides capture
this.wrapper && (opts && 'unwrap' in opts ? opts.unwrap !== false : shouldCapture)
? this.wrapperValue
: this.value,
!opts || opts.shouldBind !== false
);
};
Computation__proto__.getContext = function getContext () {
return this.parent.isRoot ? this.root.ractive : this.parent.get(false, noVirtual);
};
Computation__proto__.getValue = function getValue () {
startCapturing();
var result;
try {
result = this.signature.getter.call(this.root.ractive, this.getContext());
} catch (err) {
warnIfDebug(("Failed to compute " + (this.getKeypath()) + ": " + (err.message || err)));
// TODO this is all well and good in Chrome, but...
// ...also, should encapsulate this stuff better, and only
// show it if Ractive.DEBUG
if (hasConsole) {
if (console.groupCollapsed)
{ console.groupCollapsed(
'%cshow details',
'color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;'
); }
var sig = this.signature;
console.error(
((err.name) + ": " + (err.message) + "\n\n" + (sig.getterString) + (sig.getterUseStack ? '\n\n' + err.stack : ''))
);
if (console.groupCollapsed) { console.groupEnd(); }
}
}
var dependencies = stopCapturing();
this.setDependencies(dependencies);
return result;
};
Computation__proto__.mark = function mark () {
this.handleChange();
};
Computation__proto__.rebind = function rebind (next, previous) {
// computations will grab all of their deps again automagically
if (next !== previous) { this.handleChange(); }
};
Computation__proto__.set = function set (value) {
if (this.isReadonly) {
throw new Error(("Cannot set read-only computed value '" + (this.key) + "'"));
}
this.signature.setter(value);
this.mark();
};
Computation__proto__.setDependencies = function setDependencies (dependencies) {
var this$1 = this;
// unregister any soft dependencies we no longer have
var i = this.dependencies.length;
while (i--) {
var model = this$1.dependencies[i];
if (!~dependencies.indexOf(model)) { model.unregister(this$1); }
}
// and add any new ones
i = dependencies.length;
while (i--) {
var model$1 = dependencies[i];
if (!~this$1.dependencies.indexOf(model$1)) { model$1.register(this$1); }
}
this.dependencies = dependencies;
};
Computation__proto__.teardown = function teardown () {
var this$1 = this;
var i = this.dependencies.length;
while (i--) {
if (this$1.dependencies[i]) { this$1.dependencies[i].unregister(this$1); }
}
if (this.parent.computed[this.key] === this) { delete this.parent.computed[this.key]; }
Model.prototype.teardown.call(this);
};
Object.defineProperties( Computation__proto__, prototypeAccessors$2 );
return Computation;
}(Model));
var prototype = Computation.prototype;
var child = ComputationChild.prototype;
prototype.handleChange = child.handleChange;
prototype.joinKey = child.joinKey;
shared$1.Computation = Computation;
var ExpressionProxy = (function (Model) {
function ExpressionProxy(fragment, template) {
var this$1 = this;
Model.call(this, fragment.ractive.viewmodel, null);
this.fragment = fragment;
this.template = template;
this.isReadonly = true;
this.isComputed = true;
this.dirty = true;
this.fn =
fragment.ractive.allowExpressions === false
? noop
: getFunction(template.s, template.r.length);
this.models = this.template.r.map(function (ref) {
return resolveReference(this$1.fragment, ref);
});
this.dependencies = [];
this.shuffle = undefined;
this.bubble();
}
if ( Model ) ExpressionProxy.__proto__ = Model;
var ExpressionProxy__proto__ = ExpressionProxy.prototype = Object.create( Model && Model.prototype );
ExpressionProxy__proto__.constructor = ExpressionProxy;
ExpressionProxy__proto__.bubble = function bubble (actuallyChanged) {
if ( actuallyChanged === void 0 ) actuallyChanged = true;
// refresh the keypath
this.keypath = undefined;
if (actuallyChanged) {
this.handleChange();
}
};
ExpressionProxy__proto__.getKeypath = function getKeypath () {
var this$1 = this;
if (!this.template) { return '@undefined'; }
if (!this.keypath) {
this.keypath =
'@' +
this.template.s.replace(/_(\d+)/g, function (match, i) {
if (i >= this$1.models.length) { return match; }
var model = this$1.models[i];
return model ? model.getKeypath() : '@undefined';
});
}
return this.keypath;
};
ExpressionProxy__proto__.getValue = function getValue () {
var this$1 = this;
startCapturing();
var result;
try {
var params = this.models.map(function (m) { return (m ? m.get(true) : undefined); });
result = this.fn.apply(this.fragment.ractive, params);
} catch (err) {
warnIfDebug(("Failed to compute " + (this.getKeypath()) + ": " + (err.message || err)));
}
var dependencies = stopCapturing();
// remove missing deps
this.dependencies
.filter(function (d) { return !~dependencies.indexOf(d); })
.forEach(function (d) {
d.unregister(this$1);
removeFromArray(this$1.dependencies, d);
});
// register new deps
dependencies
.filter(function (d) { return !~this$1.dependencies.indexOf(d); })
.forEach(function (d) {
d.register(this$1);
this$1.dependencies.push(d);
});
return result;
};
ExpressionProxy__proto__.notifyUpstream = function notifyUpstream () {};
ExpressionProxy__proto__.rebind = function rebind (next, previous, safe) {
var idx = this.models.indexOf(previous);
if (~idx) {
next = rebindMatch(this.template.r[idx], next, previous);
if (next !== previous) {
previous.unregister(this);
this.models.splice(idx, 1, next);
if (next) { next.addShuffleRegister(this, 'mark'); }
}
}
this.bubble(!safe);
};
ExpressionProxy__proto__.rebound = function rebound (update) {
var this$1 = this;
this.models = this.template.r.map(function (ref) { return resolveReference(this$1.fragment, ref); });
if (update) { this.bubble(true); }
};
ExpressionProxy__proto__.retrieve = function retrieve () {
return this.get();
};
ExpressionProxy__proto__.teardown = function teardown () {
var this$1 = this;
this.fragment = undefined;
if (this.dependencies) { this.dependencies.forEach(function (d) { return d.unregister(this$1); }); }
Model.prototype.teardown.call(this);
};
ExpressionProxy__proto__.unreference = function unreference () {
Model.prototype.unreference.call(this);
collect(this);
};
ExpressionProxy__proto__.unregister = function unregister (dep) {
Model.prototype.unregister.call(this, dep);
collect(this);
};
ExpressionProxy__proto__.unregisterLink = function unregisterLink (link) {
Model.prototype.unregisterLink.call(this, link);
collect(this);
};
return ExpressionProxy;
}(Model));
var prototype$1 = ExpressionProxy.prototype;
var computation = Computation.prototype;
prototype$1.get = computation.get;
prototype$1.handleChange = computation.handleChange;
prototype$1.joinKey = computation.joinKey;
prototype$1.mark = computation.mark;
prototype$1.unbind = noop;
function collect(model) {
if (!model.deps.length && !model.refs && !model.links.length) { model.teardown(); }
}
var ReferenceExpressionProxy = (function (LinkModel) {
function ReferenceExpressionProxy(fragment, template) {
LinkModel.call(this, null, null, null, '@undefined');
this.root = fragment.ractive.viewmodel;
this.template = template;
this.rootLink = true;
this.template = template;
this.fragment = fragment;
this.rebound();
}
if ( LinkModel ) ReferenceExpressionProxy.__proto__ = LinkModel;
var ReferenceExpressionProxy__proto__ = ReferenceExpressionProxy.prototype = Object.create( LinkModel && LinkModel.prototype );
ReferenceExpressionProxy__proto__.constructor = ReferenceExpressionProxy;
ReferenceExpressionProxy__proto__.getKeypath = function getKeypath () {
return this.model ? this.model.getKeypath() : '@undefined';
};
ReferenceExpressionProxy__proto__.rebound = function rebound () {
var this$1 = this;
var fragment = this.fragment;
var template = this.template;
var base = (this.base = resolve(fragment, template));
var idx;
if (this.proxy) {
teardown$1(this);
}
var proxy = (this.proxy = {
rebind: function (next, previous) {
if (previous === base) {
next = rebindMatch(template, next, previous);
if (next !== base) {
this$1.base = base = next;
}
} else if (~(idx = members.indexOf(previous))) {
next = rebindMatch(template.m[idx].n, next, previous);
if (next !== members[idx]) {
members.splice(idx, 1, next || Missing);
}
}
if (next !== previous) {
previous.unregister(proxy);
if (next) { next.addShuffleTask(function () { return next.register(proxy); }); }
}
},
handleChange: function () {
pathChanged();
}
});
base.register(proxy);
var members = (this.members = template.m.map(function (tpl) {
if (isString(tpl)) {
return { get: function () { return tpl; } };
}
var model;
if (tpl.t === REFERENCE) {
model = resolveReference(fragment, tpl.n);
model.register(proxy);
return model;
}
model = new ExpressionProxy(fragment, tpl);
model.register(proxy);
return model;
}));
var pathChanged = function () {
var model = base.joinAll(
members.reduce(function (list, m) {
var k = m.get();
if (isArray(k)) { return list.concat(k); }
else { list.push(escapeKey(String(k))); }
return list;
}, [])
);
if (model !== this$1.model) {
this$1.model = model;
this$1.relinking(model);
fireShuffleTasks();
refreshPathDeps(this$1);
}
};
pathChanged();
};
ReferenceExpressionProxy__proto__.teardown = function teardown () {
teardown$1(this);
LinkModel.prototype.teardown.call(this);
};
ReferenceExpressionProxy__proto__.unreference = function unreference () {
LinkModel.prototype.unreference.call(this);
if (!this.deps.length && !this.refs) { this.teardown(); }
};
ReferenceExpressionProxy__proto__.unregister = function unregister (dep) {
LinkModel.prototype.unregister.call(this, dep);
if (!this.deps.length && !this.refs) { this.teardown(); }
};
return ReferenceExpressionProxy;
}(LinkModel));
function teardown$1(proxy) {
if (proxy.base) { proxy.base.unregister(proxy.proxy); }
if (proxy.models) {
proxy.models.forEach(function (m) {
if (m.unregister) { m.unregister(proxy); }
});
}
}
function refreshPathDeps(proxy) {
var len = proxy.deps.length;
var i, v;
for (i = 0; i < len; i++) {
v = proxy.deps[i];
if (v.pathChanged) { v.pathChanged(); }
if (v.fragment && v.fragment.pathModel) { v.fragment.pathModel.applyValue(proxy.getKeypath()); }
}
len = proxy.children.length;
for (i = 0; i < len; i++) {
refreshPathDeps(proxy.children[i]);
}
}
var eproto = ExpressionProxy.prototype;
var proto$1 = ReferenceExpressionProxy.prototype;
proto$1.unreference = eproto.unreference;
proto$1.unregister = eproto.unregister;
proto$1.unregisterLink = eproto.unregisterLink;
function resolve(fragment, template) {
if (template.r) {
return resolveReference(fragment, template.r);
} else if (template.x) {
return new ExpressionProxy(fragment, template.x);
} else if (template.rx) {
return new ReferenceExpressionProxy(fragment, template.rx);
}
}
function resolveAliases(aliases, fragment, dest) {
if ( dest === void 0 ) dest = {};
for (var i = 0; i < aliases.length; i++) {
if (!dest[aliases[i].n]) {
var m = resolve(fragment, aliases[i].x);
dest[aliases[i].n] = m;
m.reference();
}
}
return dest;
}
var Alias = (function (ContainerItem) {
function Alias(options) {
ContainerItem.call(this, options);
this.fragment = null;
}
if ( ContainerItem ) Alias.__proto__ = ContainerItem;
var Alias__proto__ = Alias.prototype = Object.create( ContainerItem && ContainerItem.prototype );
Alias__proto__.constructor = Alias;
Alias__proto__.bind = function bind () {
this.fragment = new Fragment({
owner: this,
template: this.template.f
});
this.fragment.aliases = resolveAliases(this.template.z, this.up);
this.fragment.bind();
};
Alias__proto__.rebound = function rebound (update) {
var aliases = this.fragment.aliases;
for (var k in aliases) {
if (aliases[k].rebound) { aliases[k].rebound(update); }
else {
aliases[k].unreference();
aliases[k] = 0;
}
}
resolveAliases(this.template.z, this.up, aliases);
if (this.fragment) { this.fragment.rebound(update); }
};
Alias__proto__.render = function render (target, occupants) {
this.rendered = true;
if (this.fragment) { this.fragment.render(target, occupants); }
};
Alias__proto__.unbind = function unbind (view) {
var this$1 = this;
for (var k in this$1.fragment.aliases) {
this$1.fragment.aliases[k].unreference();
}
this.fragment.aliases = {};
if (this.fragment) { this.fragment.unbind(view); }
};
Alias__proto__.unrender = function unrender (shouldDestroy) {
if (this.rendered && this.fragment) { this.fragment.unrender(shouldDestroy); }
this.rendered = false;
};
Alias__proto__.update = function update () {
if (this.dirty) {
this.dirty = false;
this.fragment.update();
}
};
return Alias;
}(ContainerItem));
var space = /\s+/;
function readStyle(css) {
if (!isString(css)) { return {}; }
return cleanCss(css, function (css, reconstruct) {
return css
.split(';')
.filter(function (rule) { return !!rule.trim(); })
.map(reconstruct)
.reduce(function (rules, rule) {
var i = rule.indexOf(':');
var name = rule.substr(0, i).trim();
rules[name] = rule.substr(i + 1).trim();
return rules;
}, {});
});
}
function readClass(str) {
var list = str.split(space);
// remove any empty entries
var i = list.length;
while (i--) {
if (!list[i]) { list.splice(i, 1); }
}
return list;
}
var textTypes = [
undefined,
'text',
'search',
'url',
'email',
'hidden',
'password',
'search',
'reset',
'submit'
];
function getUpdateDelegate(attribute) {
var element = attribute.element;
var name = attribute.name;
if (name === 'value') {
if (attribute.interpolator) { attribute.interpolator.bound = true; }
// special case - selects
if (element.name === 'select' && name === 'value') {
return element.getAttribute('multiple') ? updateMultipleSelectValue : updateSelectValue;
}
if (element.name === 'textarea') { return updateStringValue; }
// special case - contenteditable
if (element.getAttribute('contenteditable') != null) { return updateContentEditableValue; }
// special case - <input>
if (element.name === 'input') {
var type = element.getAttribute('type');
// type='file' value='{{fileList}}'>
if (type === 'file') { return noop; } // read-only
// type='radio' name='{{twoway}}'
if (type === 'radio' && element.binding && element.binding.attribute.name === 'name')
{ return updateRadioValue; }
if (~textTypes.indexOf(type)) { return updateStringValue; }
}
return updateValue;
}
var node = element.node;
// special case - <input type='radio' name='{{twoway}}' value='foo'>
if (attribute.isTwoway && name === 'name') {
if (node.type === 'radio') { return updateRadioName; }
if (node.type === 'checkbox') { return updateCheckboxName; }
}
if (name === 'style') { return updateStyleAttribute; }
if (name.indexOf('style-') === 0) { return updateInlineStyle; }
// special case - class names. IE fucks things up, again
if (name === 'class' && (!node.namespaceURI || node.namespaceURI === html))
{ return updateClassName; }
if (name.indexOf('class-') === 0) { return updateInlineClass; }
if (attribute.isBoolean) {
var type$1 = element.getAttribute('type');
if (attribute.interpolator && name === 'checked' && (type$1 === 'checkbox' || type$1 === 'radio'))
{ attribute.interpolator.bound = true; }
return updateBoolean;
}
if (attribute.namespace && attribute.namespace !== attribute.node.namespaceURI)
{ return updateNamespacedAttribute; }
return updateAttribute;
}
function updateMultipleSelectValue(reset) {
var value = this.getValue();
if (!isArray(value)) { value = [value]; }
var options = this.node.options;
var i = options.length;
if (reset) {
while (i--) { options[i].selected = false; }
} else {
while (i--) {
var option = options[i];
var optionValue = option._ractive ? option._ractive.value : option.value; // options inserted via a triple don't have _ractive
option.selected = arrayContains(value, optionValue);
}
}
}
function updateSelectValue(reset) {
var value = this.getValue();
if (!this.locked) {
// TODO is locked still a thing?
this.node._ractive.value = value;
var options = this.node.options;
var i = options.length;
var wasSelected = false;
if (reset) {
while (i--) { options[i].selected = false; }
} else {
while (i--) {
var option = options[i];
var optionValue = option._ractive ? option._ractive.value : option.value; // options inserted via a triple don't have _ractive
if (option.disabled && option.selected) { wasSelected = true; }
if (optionValue == value) {
// double equals as we may be comparing numbers with strings
option.selected = true;
return;
}
}
}
if (!wasSelected) { this.node.selectedIndex = -1; }
}
}
function updateContentEditableValue(reset) {
var value = this.getValue();
if (!this.locked) {
if (reset) { this.node.innerHTML = ''; }
else { this.node.innerHTML = value === undefined ? '' : value; }
}
}
function updateRadioValue(reset) {
var node = this.node;
var wasChecked = node.checked;
var value = this.getValue();
if (reset) { return (node.checked = false); }
//node.value = this.element.getAttribute( 'value' );
node.value = this.node._ractive.value = value;
node.checked = this.element.compare(value, this.element.getAttribute('name'));
// This is a special case - if the input was checked, and the value
// changed so that it's no longer checked, the twoway binding is
// most likely out of date. To fix it we have to jump through some
// hoops... this is a little kludgy but it works
if (wasChecked && !node.checked && this.element.binding && this.element.binding.rendered) {
this.element.binding.group.model.set(this.element.binding.group.getValue());
}
}
function updateValue(reset) {
if (!this.locked) {
if (reset) {
this.node.removeAttribute('value');
this.node.value = this.node._ractive.value = null;
} else {
var value = this.getValue();
this.node.value = this.node._ractive.value = value;
this.node.setAttribute('value', safeToStringValue(value));
}
}
}
function updateStringValue(reset) {
if (!this.locked) {
if (reset) {
this.node._ractive.value = '';
this.node.removeAttribute('value');
} else {
var value = this.getValue();
this.node._ractive.value = value;
var safeValue = safeToStringValue(value);
// fixes #3281 – Safari moves caret position when setting an input value to the same value
if (this.node.value !== safeValue) {
this.node.value = safeValue;
}
this.node.setAttribute('value', safeValue);
}
}
}
function updateRadioName(reset) {
if (reset) { this.node.checked = false; }
else { this.node.checked = this.element.compare(this.getValue(), this.element.binding.getValue()); }
}
function updateCheckboxName(reset) {
var ref = this;
var element = ref.element;
var node = ref.node;
var binding = element.binding;
var value = this.getValue();
var valueAttribute = element.getAttribute('value');
if (!isArray(value)) {
binding.isChecked = node.checked = element.compare(value, valueAttribute);
} else {
var i = value.length;
while (i--) {
if (element.compare(valueAttribute, value[i])) {
binding.isChecked = node.checked = true;
return;
}
}
binding.isChecked = node.checked = false;
}
}
function updateStyleAttribute(reset) {
var props = reset ? {} : readStyle(this.getValue() || '');
var style = this.node.style;
var keys$$1 = keys(props);
var prev = this.previous || [];
var i = 0;
while (i < keys$$1.length) {
if (keys$$1[i] in style) {
var safe = props[keys$$1[i]].replace('!important', '');
style.setProperty(keys$$1[i], safe, safe.length !== props[keys$$1[i]].length ? 'important' : '');
}
i++;
}
// remove now-missing attrs
i = prev.length;
while (i--) {
if (!~keys$$1.indexOf(prev[i]) && prev[i] in style) { style.setProperty(prev[i], '', ''); }
}
this.previous = keys$$1;
}
function updateInlineStyle(reset) {
if (!this.style) {
this.style = hyphenateCamel(this.name.substr(6));
}
if (reset && this.node.style.getPropertyValue(this.style) !== this.last) { return; }
var value = reset ? '' : safeToStringValue(this.getValue());
var safe = value.replace('!important', '');
this.node.style.setProperty(this.style, safe, safe.length !== value.length ? 'important' : '');
this.last = this.node.style.getPropertyValue(this.style);
}
function updateClassName(reset) {
var value = reset ? [] : readClass(safeToStringValue(this.getValue()));
// watch out for werdo svg elements
var cls = this.node.className;
cls = cls.baseVal !== undefined ? cls.baseVal : cls;
var attr = readClass(cls);
var prev = this.previous || [];
var className = value.concat(attr.filter(function (c) { return !~prev.indexOf(c); })).join(' ');
if (className !== cls) {
if (!isString(this.node.className)) {
this.node.className.baseVal = className;
} else {
this.node.className = className;
}
}
this.previous = value;
}
function updateInlineClass(reset) {
var name = this.name.substr(6);
// watch out for werdo svg elements
var cls = this.node.className;
cls = cls.baseVal !== undefined ? cls.baseVal : cls;
var attr = readClass(cls);
var value = reset ? false : this.getValue();
if (!this.inlineClass) { this.inlineClass = name; }
if (value && !~attr.indexOf(name)) { attr.push(name); }
else if (!value && ~attr.indexOf(name)) { attr.splice(attr.indexOf(name), 1); }
if (!isString(this.node.className)) {
this.node.className.baseVal = attr.join(' ');
} else {
this.node.className = attr.join(' ');
}
}
function updateBoolean(reset) {
// with two-way binding, only update if the change wasn't initiated by the user
// otherwise the cursor will often be sent to the wrong place
if (!this.locked) {
if (reset) {
if (this.useProperty) { this.node[this.propertyName] = false; }
this.node.removeAttribute(this.propertyName);
} else {
if (this.useProperty) {
this.node[this.propertyName] = this.getValue();
} else {
var val = this.getValue();
if (val) {
this.node.setAttribute(this.propertyName, isString(val) ? val : '');
} else {
this.node.removeAttribute(this.propertyName);
}
}
}
}
}
function updateAttribute(reset) {
if (reset) {
if (this.node.getAttribute(this.name) === this.value) {
this.node.removeAttribute(this.name);
}
} else {
this.value = safeToStringValue(this.getString());
this.node.setAttribute(this.name, this.value);
}
}
function updateNamespacedAttribute(reset) {
if (reset) {
if (
this.value ===
this.node.getAttributeNS(this.namespace, this.name.slice(this.name.indexOf(':') + 1))
) {
this.node.removeAttributeNS(this.namespace, this.name.slice(this.name.indexOf(':') + 1));
}
} else {
this.value = safeToStringValue(this.getString());
this.node.setAttributeNS(
this.namespace,
this.name.slice(this.name.indexOf(':') + 1),
this.value
);
}
}
var propertyNames = {
'accept-charset': 'acceptCharset',
accesskey: 'accessKey',
bgcolor: 'bgColor',
class: 'className',
codebase: 'codeBase',
colspan: 'colSpan',
contenteditable: 'contentEditable',
datetime: 'dateTime',
dirname: 'dirName',
for: 'htmlFor',
'http-equiv': 'httpEquiv',
ismap: 'isMap',
maxlength: 'maxLength',
novalidate: 'noValidate',
pubdate: 'pubDate',
readonly: 'readOnly',
rowspan: 'rowSpan',
tabindex: 'tabIndex',
usemap: 'useMap'
};
var div$1 = doc ? createElement('div') : null;
var attributes = false;
function inAttributes() {
return attributes;
}
var ConditionalAttribute = (function (Item) {
function ConditionalAttribute(options) {
Item.call(this, options);
this.attributes = [];
this.owner = options.owner;
this.fragment = new Fragment({
ractive: this.ractive,
owner: this,
template: this.template
});
// this fragment can't participate in node-y things
this.fragment.findNextNode = noop;
this.dirty = false;
}
if ( Item ) ConditionalAttribute.__proto__ = Item;
var ConditionalAttribute__proto__ = ConditionalAttribute.prototype = Object.create( Item && Item.prototype );
ConditionalAttribute__proto__.constructor = ConditionalAttribute;
ConditionalAttribute__proto__.bind = function bind () {
this.fragment.bind();
};
ConditionalAttribute__proto__.bubble = function bubble () {
if (!this.dirty) {
this.dirty = true;
this.owner.bubble();
}
};
ConditionalAttribute__proto__.destroyed = function destroyed () {
this.unrender();
};
ConditionalAttribute__proto__.render = function render () {
this.node = this.owner.node;
if (this.node) {
this.isSvg = this.node.namespaceURI === svg$1;
}
attributes = true;
if (!this.rendered) { this.fragment.render(); }
this.rendered = true;
this.dirty = true; // TODO this seems hacky, but necessary for tests to pass in browser AND node.js
this.update();
attributes = false;
};
ConditionalAttribute__proto__.toString = function toString () {
return this.fragment.toString();
};
ConditionalAttribute__proto__.unbind = function unbind (view) {
this.fragment.unbind(view);
};
ConditionalAttribute__proto__.unrender = function unrender () {
this.rendered = false;
this.fragment.unrender();
};
ConditionalAttribute__proto__.update = function update () {
var this$1 = this;
var str;
var attrs;
if (this.dirty) {
this.dirty = false;
var current = attributes;
attributes = true;
this.fragment.update();
if (this.rendered && this.node) {
str = this.fragment.toString();
attrs = parseAttributes(str, this.isSvg);
// any attributes that previously existed but no longer do
// must be removed
this.attributes
.filter(function (a) { return notIn(attrs, a); })
.forEach(function (a) {
this$1.node.removeAttribute(a.name);
});
attrs.forEach(function (a) {
this$1.node.setAttribute(a.name, a.value);
});
this.attributes = attrs;
}
attributes = current || false;
}
};
return ConditionalAttribute;
}(Item));
var onlyWhitespace = /^\s*$/;
function parseAttributes(str, isSvg) {
if (onlyWhitespace.test(str)) { return []; }
var tagName = isSvg ? 'svg' : 'div';
return str
? (div$1.innerHTML = "<" + tagName + " " + str + "></" + tagName + ">") && toArray(div$1.childNodes[0].attributes)
: [];
}
function notIn(haystack, needle) {
var i = haystack.length;
while (i--) {
if (haystack[i].name === needle.name) {
return false;
}
}
return true;
}
function lookupNamespace(node, prefix) {
var qualified = "xmlns:" + prefix;
while (node) {
if (node.hasAttribute && node.hasAttribute(qualified)) { return node.getAttribute(qualified); }
node = node.parentNode;
}
return namespaces[prefix];
}
var attribute = false;
function inAttribute() {
return attribute;
}
var Attribute = (function (Item) {
function Attribute(options) {
Item.call(this, options);
this.name = options.template.n;
this.namespace = null;
this.owner = options.owner || options.up.owner || options.element || findElement(options.up);
this.element =
options.element || (this.owner.attributeByName ? this.owner : findElement(options.up));
this.up = options.up; // shared
this.ractive = this.up.ractive;
this.rendered = false;
this.updateDelegate = null;
this.fragment = null;
this.element.attributeByName[this.name] = this;
if (!isArray(options.template.f)) {
this.value = options.template.f;
if (this.value === 0) {
this.value = '';
} else if (this.value === undefined) {
this.value = true;
}
return;
} else {
this.fragment = new Fragment({
owner: this,
template: options.template.f
});
}
this.interpolator =
this.fragment &&
this.fragment.items.length === 1 &&
this.fragment.items[0].type === INTERPOLATOR &&
this.fragment.items[0];
if (this.interpolator) { this.interpolator.owner = this; }
}
if ( Item ) Attribute.__proto__ = Item;
var Attribute__proto__ = Attribute.prototype = Object.create( Item && Item.prototype );
Attribute__proto__.constructor = Attribute;
Attribute__proto__.bind = function bind () {
if (this.fragment) {
this.fragment.bind();
}
};
Attribute__proto__.bubble = function bubble () {
if (!this.dirty) {
this.up.bubble();
this.element.bubble();
this.dirty = true;
}
};
Attribute__proto__.firstNode = function firstNode () {};
Attribute__proto__.getString = function getString () {
attribute = true;
var value = this.fragment
? this.fragment.toString()
: this.value != null
? '' + this.value
: '';
attribute = false;
return value;
};
// TODO could getValue ever be called for a static attribute,
// or can we assume that this.fragment exists?
Attribute__proto__.getValue = function getValue () {
attribute = true;
var value = this.fragment
? this.fragment.valueOf()
: booleanAttributes[this.name.toLowerCase()]
? true
: this.value;
attribute = false;
return value;
};
Attribute__proto__.render = function render () {
var node = this.element.node;
this.node = node;
// should we use direct property access, or setAttribute?
if (!node.namespaceURI || node.namespaceURI === namespaces.html) {
this.propertyName = propertyNames[this.name] || this.name;
if (node[this.propertyName] !== undefined) {
this.useProperty = true;
}
// is attribute a boolean attribute or 'value'? If so we're better off doing e.g.
// node.selected = true rather than node.setAttribute( 'selected', '' )
if (booleanAttributes[this.name.toLowerCase()] || this.isTwoway) {
this.isBoolean = true;
}
if (this.propertyName === 'value') {
node._ractive.value = this.value;
}
}
if (node.namespaceURI) {
var index = this.name.indexOf(':');
if (index !== -1) {
this.namespace = lookupNamespace(node, this.name.slice(0, index));
} else {
this.namespace = node.namespaceURI;
}
}
this.rendered = true;
this.updateDelegate = getUpdateDelegate(this);
this.updateDelegate();
};
Attribute__proto__.toString = function toString () {
if (inAttributes()) { return ''; }
attribute = true;
var value = this.getValue();
// Special case - select and textarea values (should not be stringified)
if (
this.name === 'value' &&
(this.element.getAttribute('contenteditable') !== undefined ||
(this.element.name === 'select' || this.element.name === 'textarea'))
) {
return;
}
// Special case – bound radio `name` attributes
if (
this.name === 'name' &&
this.element.name === 'input' &&
this.interpolator &&
this.element.getAttribute('type') === 'radio'
) {
return ("name=\"{{" + (this.interpolator.model.getKeypath()) + "}}\"");
}
// Special case - style and class attributes and directives
if (
this.owner === this.element &&
(this.name === 'style' || this.name === 'class' || this.style || this.inlineClass)
) {
return;
}
if (
!this.rendered &&
this.owner === this.element &&
(!this.name.indexOf('style-') || !this.name.indexOf('class-'))
) {
if (!this.name.indexOf('style-')) {
this.style = hyphenateCamel(this.name.substr(6));
} else {
this.inlineClass = this.name.substr(6);
}
return;
}
if (booleanAttributes[this.name.toLowerCase()])
{ return value
? isString(value)
? ((this.name) + "=\"" + (safeAttributeString(value)) + "\"")
: this.name
: ''; }
if (value == null) { return ''; }
var str = safeAttributeString(this.getString());
attribute = false;
return str ? ((this.name) + "=\"" + str + "\"") : this.name;
};
Attribute__proto__.unbind = function unbind (view) {
if (this.fragment) { this.fragment.unbind(view); }
};
Attribute__proto__.unrender = function unrender () {
this.updateDelegate(true);
this.rendered = false;
};
Attribute__proto__.update = function update () {
if (this.dirty) {
var binding;
this.dirty = false;
if (this.fragment) { this.fragment.update(); }
if (this.rendered) { this.updateDelegate(); }
if (this.isTwoway && !this.locked) {
this.interpolator.twowayBinding.lastVal(true, this.interpolator.model.get());
} else if (this.name === 'value' && (binding = this.element.binding)) {
// special case: name bound element with dynamic value
var attr = binding.attribute;
if (attr && !attr.dirty && attr.rendered) {
this.element.binding.attribute.updateDelegate();
}
}
}
};
return Attribute;
}(Item));
var BindingFlag = (function (Item) {
function BindingFlag(options) {
Item.call(this, options);
this.owner = options.owner || options.up.owner || findElement(options.up);
this.element = this.owner.attributeByName ? this.owner : findElement(options.up);
this.flag = options.template.v === 'l' ? 'lazy' : 'twoway';
this.bubbler = this.owner === this.element ? this.element : this.up;
if (this.element.type === ELEMENT) {
if (isArray(options.template.f)) {
this.fragment = new Fragment({
owner: this,
template: options.template.f
});
}
this.interpolator =
this.fragment &&
this.fragment.items.length === 1 &&
this.fragment.items[0].type === INTERPOLATOR &&
this.fragment.items[0];
}
}
if ( Item ) BindingFlag.__proto__ = Item;
var BindingFlag__proto__ = BindingFlag.prototype = Object.create( Item && Item.prototype );
BindingFlag__proto__.constructor = BindingFlag;
BindingFlag__proto__.bind = function bind () {
if (this.fragment) { this.fragment.bind(); }
set$1(this, this.getValue(), true);
};
BindingFlag__proto__.bubble = function bubble () {
if (!this.dirty) {
this.bubbler.bubble();
this.dirty = true;
}
};
BindingFlag__proto__.getValue = function getValue () {
if (this.fragment) { return this.fragment.valueOf(); }
else if ('value' in this) { return this.value; }
else if ('f' in this.template) { return this.template.f; }
else { return true; }
};
BindingFlag__proto__.render = function render () {
set$1(this, this.getValue(), true);
};
BindingFlag__proto__.toString = function toString () {
return '';
};
BindingFlag__proto__.unbind = function unbind (view) {
if (this.fragment) { this.fragment.unbind(view); }
delete this.element[this.flag];
};
BindingFlag__proto__.unrender = function unrender () {
if (this.element.rendered) { this.element.recreateTwowayBinding(); }
};
BindingFlag__proto__.update = function update () {
if (this.dirty) {
this.dirty = false;
if (this.fragment) { this.fragment.update(); }
set$1(this, this.getValue(), true);
}
};
return BindingFlag;
}(Item));
function set$1(flag, value, update) {
if (value === 0) {
flag.value = true;
} else if (value === 'true') {
flag.value = true;
} else if (value === 'false' || value === '0') {
flag.value = false;
} else {
flag.value = value;
}
var current = flag.element[flag.flag];
flag.element[flag.flag] = flag.value;
if (update && !flag.element.attributes.binding && current !== flag.value) {
flag.element.recreateTwowayBinding();
}
return flag.value;
}
function Comment(options) {
Item.call(this, options);
}
var proto$2 = create(Item.prototype);
assign(proto$2, {
bind: noop,
unbind: noop,
update: noop,
detach: function detach() {
return detachNode(this.node);
},
firstNode: function firstNode() {
return this.node;
},
render: function render(target) {
this.rendered = true;
this.node = doc.createComment(this.template.c);
target.appendChild(this.node);
},
toString: function toString() {
return ("<!-- " + (this.template.c) + " -->");
},
unrender: function unrender(shouldDestroy) {
if (this.rendered && shouldDestroy) { this.detach(); }
this.rendered = false;
}
});
Comment.prototype = proto$2;
// Teardown. This goes through the root fragment and all its children, removing observers
// and generally cleaning up after itself
function Ractive$teardown() {
var this$1 = this;
if (this.torndown) {
warnIfDebug('ractive.teardown() was called on a Ractive instance that was already torn down');
return Promise.resolve();
}
this.shouldDestroy = true;
return teardown$2(this, function () { return (this$1.fragment.rendered ? this$1.unrender() : Promise.resolve()); });
}
function teardown$2(instance, getPromise) {
instance.torndown = true;
instance.fragment.unbind();
instance._observers.slice().forEach(cancel);
if (instance.el && instance.el.__ractive_instances__) {
removeFromArray(instance.el.__ractive_instances__, instance);
}
var promise = getPromise();
hooks.teardown.fire(instance);
promise.then(function () {
hooks.destruct.fire(instance);
instance.viewmodel.teardown();
});
return promise;
}
var RactiveModel = (function (SharedModel) {
function RactiveModel(ractive) {
SharedModel.call(this, ractive, '@this');
this.ractive = ractive;
}
if ( SharedModel ) RactiveModel.__proto__ = SharedModel;
var RactiveModel__proto__ = RactiveModel.prototype = Object.create( SharedModel && SharedModel.prototype );
RactiveModel__proto__.constructor = RactiveModel;
RactiveModel__proto__.joinKey = function joinKey (key) {
var model = SharedModel.prototype.joinKey.call(this, key);
if ((key === 'root' || key === 'parent') && !model.isLink) { return initLink(model, key); }
else if (key === 'data') { return this.ractive.viewmodel; }
else if (key === 'cssData') { return this.ractive.constructor._cssModel; }
return model;
};
return RactiveModel;
}(SharedModel));
function initLink(model, key) {
model.applyValue = function(value) {
this.parent.value[key] = value;
if (value && value.viewmodel) {
this.link(value.viewmodel.getRactiveModel(), key);
this._link.markedAll();
} else {
this.link(create(Missing), key);
this._link.markedAll();
}
};
if (key === 'root') {
var mark = model.mark;
model.mark = function(force) {
if (this._marking) { return; }
this._marking = true;
mark.apply(this, force);
this._marking = false;
};
}
model.applyValue(model.parent.ractive[key], key);
model._link.set = function (v) { return model.applyValue(v); };
model._link.applyValue = function (v) { return model.applyValue(v); };
return model._link;
}
var specialModels = {
'@this': function _this(root) {
return root.getRactiveModel();
},
'@global': function _global() {
return GlobalModel;
},
'@shared': function _shared() {
return SharedModel$1;
},
'@style': function _style(root) {
return root.getRactiveModel().joinKey('cssData');
},
'@helpers': function _helpers(root) {
return root.getHelpers();
}
};
specialModels['@'] = specialModels['@this'];
var RootModel = (function (Model) {
function RootModel(options) {
Model.call(this, null, null);
this.isRoot = true;
this.root = this;
this.ractive = options.ractive; // TODO sever this link
this.value = options.data;
this.adaptors = options.adapt;
this.adapt();
}
if ( Model ) RootModel.__proto__ = Model;
var RootModel__proto__ = RootModel.prototype = Object.create( Model && Model.prototype );
RootModel__proto__.constructor = RootModel;
RootModel__proto__.attached = function attached (fragment) {
attachImplicits(this, fragment);
};
RootModel__proto__.createLink = function createLink (keypath, target, targetPath, options) {
var keys = splitKeypath(keypath);
var model = this;
while (keys.length) {
var key = keys.shift();
model = model.childByKey[key] || model.joinKey(key);
}
return model.link(target, targetPath, options);
};
RootModel__proto__.detached = function detached () {
detachImplicits(this);
};
RootModel__proto__.get = function get (shouldCapture, options) {
if (shouldCapture) { capture(this); }
if (!options || options.virtual !== false) {
return this.getVirtual();
} else {
return this.value;
}
};
RootModel__proto__.getHelpers = function getHelpers () {
if (!this.helpers) { this.helpers = new SharedModel(this.ractive.helpers, 'helpers', this.ractive); }
return this.helpers;
};
RootModel__proto__.getKeypath = function getKeypath () {
return '';
};
RootModel__proto__.getRactiveModel = function getRactiveModel () {
return this.ractiveModel || (this.ractiveModel = new RactiveModel(this.ractive));
};
RootModel__proto__.getValueChildren = function getValueChildren () {
var children = Model.prototype.getValueChildren.call(this, this.value);
this.children.forEach(function (child) {
if (child._link) {
var idx = children.indexOf(child);
if (~idx) { children.splice(idx, 1, child._link); }
else { children.push(child._link); }
}
});
return children;
};
RootModel__proto__.has = function has (key) {
if (key[0] === '~' && key[1] === '/') { key = key.slice(2); }
if (specialModels[key] || key === '') { return true; }
if (Model.prototype.has.call(this, key)) {
return true;
} else {
var unescapedKey = unescapeKey(key);
// mappings/links and computations
if (this.childByKey[unescapedKey] && this.childByKey[unescapedKey]._link) { return true; }
}
};
RootModel__proto__.joinKey = function joinKey (key, opts) {
if (key[0] === '~' && key[1] === '/') { key = key.slice(2); }
if (key[0] === '@') {
var fn = specialModels[key];
if (fn) { return fn(this); }
} else {
return Model.prototype.joinKey.call(this, key, opts);
}
};
RootModel__proto__.set = function set (value) {
// TODO wrapping root node is a baaaad idea. We should prevent this
var wrapper = this.wrapper;
if (wrapper) {
var shouldTeardown = !wrapper.reset || wrapper.reset(value) === false;
if (shouldTeardown) {
wrapper.teardown();
this.wrapper = null;
this.value = value;
this.adapt();
}
} else {
this.value = value;
this.adapt();
}
this.deps.forEach(handleChange);
this.children.forEach(mark);
};
RootModel__proto__.retrieve = function retrieve () {
return this.wrapper ? this.wrapper.get() : this.value;
};
RootModel__proto__.teardown = function teardown () {
Model.prototype.teardown.call(this);
this.ractiveModel && this.ractiveModel.teardown();
};
return RootModel;
}(Model));
RootModel.prototype.update = noop;
function attachImplicits(model, fragment) {
if (model._link && model._link.implicit && model._link.isDetached()) {
model.attach(fragment);
}
// look for virtual children to relink and cascade
for (var k in model.childByKey) {
if (model.value) {
if (k in model.value) {
attachImplicits(model.childByKey[k], fragment);
} else if (!model.childByKey[k]._link || model.childByKey[k]._link.isDetached()) {
var mdl = resolveReference(fragment, k);
if (mdl) {
model.childByKey[k].link(mdl, k, { implicit: true });
}
}
}
}
}
function detachImplicits(model) {
if (model._link && model._link.implicit) {
model.unlink();
}
for (var k in model.childByKey) {
detachImplicits(model.childByKey[k]);
}
}
function subscribe(instance, options, type) {
var subs = (instance.constructor[("_" + type)] || []).concat(toPairs(options[type] || []));
var single = type === 'on' ? 'once' : (type + "Once");
subs.forEach(function (ref) {
var target = ref[0];
var config = ref[1];
if (isFunction(config)) {
instance[type](target, config);
} else if (isObjectType(config) && isFunction(config.handler)) {
instance[config.once ? single : type](target, config.handler, create(config));
}
});
}
var registryNames$1 = [
'adaptors',
'components',
'decorators',
'easing',
'events',
'interpolators',
'partials',
'transitions'
];
var protoRegistries = ['computed', 'helpers'];
var uid = 0;
function construct(ractive, options) {
if (Ractive.DEBUG) { welcome(); }
initialiseProperties(ractive);
handleAttributes(ractive);
// set up event subscribers
subscribe(ractive, options, 'on');
// if there's not a delegation setting, inherit from parent if it's not default
if (
!hasOwn(options, 'delegate') &&
ractive.parent &&
ractive.parent.delegate !== ractive.delegate
) {
ractive.delegate = false;
}
// plugins that need to run at construct
if (isArray(options.use)) {
ractive.use.apply(ractive, options.use.filter(function (p) { return p.construct; }));
}
hooks.construct.fire(ractive, options);
if (options.onconstruct) { options.onconstruct.call(ractive, getRactiveContext(ractive), options); }
// Add registries
var i = registryNames$1.length;
while (i--) {
var name = registryNames$1[i];
ractive[name] = assign(create(ractive.constructor[name] || null), options[name]);
}
i = protoRegistries.length;
while (i--) {
var name$1 = protoRegistries[i];
ractive[name$1] = assign(create(ractive.constructor.prototype[name$1]), options[name$1]);
}
if (ractive._attributePartial) {
ractive.partials['extra-attributes'] = ractive._attributePartial;
delete ractive._attributePartial;
}
// Create a viewmodel
var viewmodel = new RootModel({
adapt: getAdaptors(ractive, ractive.adapt, options),
data: dataConfigurator.init(ractive.constructor, ractive, options),
ractive: ractive
});
// once resolved, share the adaptors array between the root model and instance
ractive.adapt = viewmodel.adaptors;
ractive.viewmodel = viewmodel;
for (var k in ractive.computed) {
compute.call(ractive, k, ractive.computed[k]);
}
}
function getAdaptors(ractive, protoAdapt, options) {
protoAdapt = protoAdapt.map(lookup);
var adapt = ensureArray(options.adapt).map(lookup);
var srcs = [protoAdapt, adapt];
if (ractive.parent && !ractive.isolated) {
srcs.push(ractive.parent.viewmodel.adaptors);
}
return combine.apply(null, srcs);
function lookup(adaptor) {
if (isString(adaptor)) {
adaptor = findInViewHierarchy('adaptors', ractive, adaptor);
if (!adaptor) {
fatal(missingPlugin(adaptor, 'adaptor'));
}
}
return adaptor;
}
}
function initialiseProperties(ractive) {
// Generate a unique identifier, for places where you'd use a weak map if it
// existed
ractive._guid = 'r-' + uid++;
// events
ractive._subs = create(null);
ractive._nsSubs = 0;
// storage for item configuration from instantiation to reset,
// like dynamic functions or original values
ractive._config = {};
// events
ractive.event = null;
ractive._eventQueue = [];
// observers
ractive._observers = [];
// external children
ractive._children = [];
ractive._children.byName = {};
ractive.children = ractive._children;
if (!ractive.component) {
ractive.root = ractive;
ractive.parent = ractive.container = null; // TODO container still applicable?
}
}
function handleAttributes(ractive) {
var component = ractive.component;
var attributes = ractive.constructor.attributes;
if (attributes && component) {
var tpl = component.template;
var attrs = tpl.m ? tpl.m.slice() : [];
// grab all of the passed attribute names
var props = attrs.filter(function (a) { return a.t === ATTRIBUTE; }).map(function (a) { return a.n; });
// warn about missing requireds
attributes.required.forEach(function (p) {
if (!~props.indexOf(p)) {
warnIfDebug(("Component '" + (component.name) + "' requires attribute '" + p + "' to be provided"));
}
});
// set up a partial containing non-property attributes
var all = attributes.optional.concat(attributes.required);
var partial = [];
var i = attrs.length;
while (i--) {
var a = attrs[i];
if (a.t === ATTRIBUTE && !~all.indexOf(a.n)) {
if (attributes.mapAll) {
// map the attribute if requested and make the extra attribute in the partial refer to the mapping
partial.unshift({
t: ATTRIBUTE,
n: a.n,
f: [{ t: INTERPOLATOR, r: ("~/" + (a.n)) }]
});
} else {
// transfer the attribute to the extra attributes partal
partial.unshift(attrs.splice(i, 1)[0]);
}
} else if (
!attributes.mapAll &&
(a.t === DECORATOR || a.t === TRANSITION || a.t === BINDING_FLAG)
) {
partial.unshift(attrs.splice(i, 1)[0]);
}
}
if (partial.length) { component.template = { t: tpl.t, e: tpl.e, f: tpl.f, m: attrs, p: tpl.p }; }
ractive._attributePartial = partial;
}
}
var Component = (function (Item) {
function Component(options, ComponentConstructor) {
var this$1 = this;
Item.call(this, options);
var template = options.template;
this.isAnchor = template.t === ANCHOR;
this.type = this.isAnchor ? ANCHOR : COMPONENT; // override ELEMENT from super
var attrs = template.m;
var partials = template.p || {};
if (!('content' in partials)) { partials.content = template.f || []; }
this._partials = partials; // TEMP
if (this.isAnchor) {
this.name = template.n;
this.addChild = addChild;
this.removeChild = removeChild;
} else {
var instance = create(ComponentConstructor.prototype);
this.instance = instance;
this.name = template.e;
if (instance.el || instance.target) {
warnIfDebug(
("The <" + (this.name) + "> component has a default '" + (instance.el ? 'el' : 'target') + "' property; it has been disregarded")
);
instance.el = instance.target = null;
}
// find container
var fragment = options.up;
var container;
while (fragment) {
if (fragment.owner.type === YIELDER) {
container = fragment.owner.container;
break;
}
fragment = fragment.parent;
}
// add component-instance-specific properties
instance.parent = this.up.ractive;
instance.container = container || null;
instance.root = instance.parent.root;
instance.component = this;
construct(this.instance, { partials: partials });
// these can be modified during construction
template = this.template;
attrs = template.m;
// allow components that are so inclined to add programmatic mappings
if (isArray(this.mappings)) {
attrs = (attrs || []).concat(this.mappings);
} else if (isString(this.mappings)) {
attrs = (attrs || []).concat(parser.parse(this.mappings, { attributes: true }).t);
}
// for hackability, this could be an open option
// for any ractive instance, but for now, just
// for components and just for ractive...
instance._inlinePartials = partials;
}
this.attributeByName = {};
this.attributes = [];
if (attrs) {
var leftovers = [];
attrs.forEach(function (template) {
switch (template.t) {
case ATTRIBUTE:
case EVENT:
this$1.attributes.push(
createItem({
owner: this$1,
up: this$1.up,
template: template
})
);
break;
case TRANSITION:
case BINDING_FLAG:
case DECORATOR:
break;
default:
leftovers.push(template);
break;
}
});
if (leftovers.length) {
this.attributes.push(
new ConditionalAttribute({
owner: this,
up: this.up,
template: leftovers
})
);
}
}
this.eventHandlers = [];
}
if ( Item ) Component.__proto__ = Item;
var Component__proto__ = Component.prototype = Object.create( Item && Item.prototype );
Component__proto__.constructor = Component;
Component__proto__.bind = function bind () {
if (!this.isAnchor) {
this.attributes.forEach(bind$1);
this.eventHandlers.forEach(bind$1);
initialise(
this.instance,
{
partials: this._partials
},
{
cssIds: this.up.cssIds
}
);
if (this.instance.target || this.instance.el) { this.extern = true; }
this.bound = true;
}
};
Component__proto__.bubble = function bubble () {
if (!this.dirty) {
this.dirty = true;
this.up.bubble();
}
};
Component__proto__.destroyed = function destroyed () {
if (!this.isAnchor && this.instance.fragment) { this.instance.fragment.destroyed(); }
};
Component__proto__.detach = function detach () {
if (this.isAnchor) {
if (this.instance) { return this.instance.fragment.detach(); }
return createDocumentFragment();
}
return this.instance.fragment.detach();
};
Component__proto__.find = function find (selector, options) {
if (this.instance) { return this.instance.fragment.find(selector, options); }
};
Component__proto__.findAll = function findAll (selector, options) {
if (this.instance) { this.instance.fragment.findAll(selector, options); }
};
Component__proto__.findComponent = function findComponent (name, options) {
if (!name || this.name === name) { return this.instance; }
if (this.instance.fragment) {
return this.instance.fragment.findComponent(name, options);
}
};
Component__proto__.findAllComponents = function findAllComponents (name, options) {
var result = options.result;
if (this.instance && (!name || this.name === name)) {
result.push(this.instance);
}
if (this.instance) { this.instance.findAllComponents(name, options); }
};
Component__proto__.firstNode = function firstNode (skipParent) {
if (this.instance) { return this.instance.fragment.firstNode(skipParent); }
};
Component__proto__.getContext = function getContext () {
var assigns = [], len = arguments.length;
while ( len-- ) assigns[ len ] = arguments[ len ];
assigns.unshift(this.instance);
return getRactiveContext.apply(null, assigns);
};
Component__proto__.rebound = function rebound (update$$1) {
this.attributes.forEach(function (x) { return x.rebound(update$$1); });
};
Component__proto__.render = function render$2 (target, occupants) {
if (this.isAnchor) {
this.rendered = true;
this.target = target;
if (!checking.length) {
checking.push(this.ractive);
if (occupants) {
this.occupants = occupants;
checkAnchors();
this.occupants = null;
} else {
runloop.scheduleTask(checkAnchors, true);
}
}
} else {
this.attributes.forEach(render);
this.eventHandlers.forEach(render);
if (this.extern) {
this.instance.delegate = false;
this.instance.render();
} else {
render$1(this.instance, target, null, occupants);
}
this.rendered = true;
}
};
Component__proto__.shuffled = function shuffled () {
Item.prototype.shuffled.call(this);
this.instance &&
!this.instance.isolated &&
this.instance.fragment &&
this.instance.fragment.shuffled();
};
Component__proto__.toString = function toString () {
if (this.instance) { return this.instance.toHTML(); }
};
Component__proto__.unbind = function unbind$1 (view) {
if (!this.isAnchor) {
this.bound = false;
this.attributes.forEach(unbind);
if (view) { this.instance.fragment.unbind(); }
else { teardown$2(this.instance, function () { return runloop.promise(); }); }
}
};
Component__proto__.unrender = function unrender$1 (shouldDestroy) {
this.shouldDestroy = shouldDestroy;
if (this.isAnchor) {
if (this.item) { unrenderItem(this, this.item); }
this.target = null;
if (!checking.length) {
checking.push(this.ractive);
runloop.scheduleTask(checkAnchors, true);
}
} else {
this.instance.unrender();
this.instance.el = this.instance.target = null;
this.attributes.forEach(unrender);
this.eventHandlers.forEach(unrender);
}
this.rendered = false;
};
Component__proto__.update = function update$2 () {
this.dirty = false;
if (this.instance) {
this.instance.fragment.update();
this.attributes.forEach(update);
this.eventHandlers.forEach(update);
}
};
return Component;
}(Item));
function addChild(meta) {
if (this.item) { this.removeChild(this.item); }
var child = meta.instance;
meta.anchor = this;
meta.up = this.up;
meta.name = meta.nameOption || this.name;
this.name = meta.name;
if (!child.isolated) { child.viewmodel.attached(this.up); }
// render as necessary
if (this.rendered) {
renderItem(this, meta);
}
}
function removeChild(meta) {
// unrender as necessary
if (this.item === meta) {
unrenderItem(this, meta);
this.name = this.template.n;
}
}
function renderItem(anchor, meta) {
if (!anchor.rendered) { return; }
meta.shouldDestroy = false;
meta.up = anchor.up;
anchor.item = meta;
anchor.instance = meta.instance;
var nextNode = anchor.up.findNextNode(anchor);
if (meta.instance.fragment.rendered) {
meta.instance.unrender();
}
meta.partials = meta.instance.partials;
meta.instance.partials = assign(create(meta.partials), meta.partials, anchor._partials);
meta.instance.fragment.unbind(true);
meta.instance.fragment.componentParent = anchor.up;
meta.instance.fragment.bind(meta.instance.viewmodel);
anchor.attributes.forEach(bind$1);
anchor.eventHandlers.forEach(bind$1);
anchor.attributes.forEach(render);
anchor.eventHandlers.forEach(render);
var target = anchor.up.findParentNode();
render$1(meta.instance, target, target.contains(nextNode) ? nextNode : null, anchor.occupants);
if (meta.lastBound !== anchor) {
meta.lastBound = anchor;
}
}
function unrenderItem(anchor, meta) {
if (!anchor.rendered) { return; }
meta.shouldDestroy = true;
meta.instance.unrender();
anchor.eventHandlers.forEach(unrender);
anchor.attributes.forEach(unrender);
anchor.eventHandlers.forEach(unbind);
anchor.attributes.forEach(unbind);
meta.instance.el = meta.instance.anchor = null;
meta.instance.fragment.componentParent = null;
meta.up = null;
meta.anchor = null;
anchor.item = null;
anchor.instance = null;
}
var checking = [];
function checkAnchors() {
var list = checking;
checking = [];
list.forEach(updateAnchors);
}
function setupArgsFn(item, template, fragment, opts) {
if ( opts === void 0 ) opts = {};
if (template && template.f && template.f.s) {
item.fn = getFunction(template.f.s, template.f.r.length);
if (opts.register === true) {
item.models = resolveArgs(item, template, fragment, opts);
}
}
}
function resolveArgs(item, template, fragment, opts) {
if ( opts === void 0 ) opts = {};
return template.f.r.map(function (ref, i) {
var model;
if (opts.specialRef && (model = opts.specialRef(ref, i))) { return model; }
model = resolveReference(fragment, ref);
if (opts.register === true) {
model.register(item);
}
return model;
});
}
function teardownArgsFn(item, template) {
if (template && template.f && template.f.s) {
if (item.models)
{ item.models.forEach(function (m) {
if (m && m.unregister) { m.unregister(item); }
}); }
item.models = null;
}
}
var missingDecorator = {
update: noop,
teardown: noop
};
var Decorator = function Decorator(options) {
this.owner = options.owner || options.up.owner || findElement(options.up);
this.element = this.owner.attributeByName ? this.owner : findElement(options.up);
this.up = options.up || this.owner.up;
this.ractive = this.owner.ractive;
var template = (this.template = options.template);
this.name = template.n;
this.node = null;
this.handle = null;
this.element.decorators.push(this);
};
var Decorator__proto__ = Decorator.prototype;
Decorator__proto__.bind = function bind () {
// if the owner is the elment, make sure the context includes the element
var frag = this.element === this.owner ? new Fragment({ owner: this.owner }) : this.up;
setupArgsFn(this, this.template, frag, { register: true });
};
Decorator__proto__.bubble = function bubble () {
if (!this.dirty) {
this.dirty = true;
// decorators may be owned directly by an element or by a fragment if conditional
this.owner.bubble();
this.up.bubble();
}
};
Decorator__proto__.destroyed = function destroyed () {
if (this.handle) {
this.handle.teardown();
this.handle = null;
}
this.shouldDestroy = true;
};
Decorator__proto__.handleChange = function handleChange () {
this.bubble();
};
Decorator__proto__.rebind = function rebind (next, previous, safe) {
var idx = this.models.indexOf(previous);
if (!~idx) { return; }
next = rebindMatch(this.template.f.r[idx], next, previous);
if (next === previous) { return; }
previous.unregister(this);
this.models.splice(idx, 1, next);
if (next) { next.addShuffleRegister(this, 'mark'); }
if (!safe) { this.bubble(); }
};
Decorator__proto__.rebound = function rebound (update) {
teardownArgsFn(this, this.template);
setupArgsFn(this, this.template, this.up, { register: true });
if (update) { this.bubble(); }
};
Decorator__proto__.render = function render () {
var this$1 = this;
this.shouldDestroy = false;
if (this.handle) { this.unrender(); }
runloop.scheduleTask(function () {
// bail if the host element has managed to become unrendered
if (!this$1.element.rendered) { return; }
var fn = findInViewHierarchy('decorators', this$1.ractive, this$1.name);
if (!fn) {
warnOnce(missingPlugin(this$1.name, 'decorator'));
this$1.handle = missingDecorator;
return;
}
this$1.node = this$1.element.node;
var args;
if (this$1.fn) {
args = this$1.models.map(function (model) {
if (!model) { return undefined; }
return model.get();
});
args = this$1.fn.apply(this$1.ractive, args);
}
this$1.handle = fn.apply(this$1.ractive, [this$1.node].concat(args));
if (!this$1.handle || !this$1.handle.teardown) {
throw new Error(
("The '" + (this$1.name) + "' decorator must return an object with a teardown method")
);
}
// watch out for decorators that cause their host element to be unrendered
if (this$1.shouldDestroy) { this$1.destroyed(); }
}, true);
};
Decorator__proto__.toString = function toString () {
return '';
};
Decorator__proto__.unbind = function unbind () {
teardownArgsFn(this, this.template);
};
Decorator__proto__.unrender = function unrender (shouldDestroy) {
if ((!shouldDestroy || this.element.rendered) && this.handle) {
this.handle.teardown();
this.handle = null;
}
};
Decorator__proto__.update = function update () {
var instance = this.handle;
if (!this.dirty) {
if (instance && instance.invalidate) {
runloop.scheduleTask(function () { return instance.invalidate(); }, true);
}
return;
}
this.dirty = false;
if (instance) {
if (!instance.update) {
this.unrender();
this.render();
} else {
var args = this.models.map(function (model) { return model && model.get(); });
instance.update.apply(this.ractive, this.fn.apply(this.ractive, args));
}
}
};
Decorator.prototype.firstNode = noop;
var Doctype = (function (Item) {
function Doctype () {
Item.apply(this, arguments);
}
if ( Item ) Doctype.__proto__ = Item;
var Doctype__proto__ = Doctype.prototype = Object.create( Item && Item.prototype );
Doctype__proto__.constructor = Doctype;
Doctype__proto__.toString = function toString () {
return '<!DOCTYPE' + this.template.a + '>';
};
return Doctype;
}(Item));
var proto$3 = Doctype.prototype;
proto$3.bind = proto$3.render = proto$3.teardown = proto$3.unbind = proto$3.unrender = proto$3.update = noop;
var Binding = function Binding(element, name) {
if ( name === void 0 ) name = 'value';
this.element = element;
this.ractive = element.ractive;
this.attribute = element.attributeByName[name];
var interpolator = this.attribute.interpolator;
interpolator.twowayBinding = this;
var model = interpolator.model;
if (model.isReadonly && !model.setRoot) {
var keypath = model.getKeypath().replace(/^@/, '');
warnOnceIfDebug(
("Cannot use two-way binding on <" + (element.name) + "> element: " + keypath + " is read-only. To suppress this warning use <" + (element.name) + " twoway='false'...>"),
{ ractive: this.ractive }
);
return false;
}
this.attribute.isTwoway = true;
this.model = model;
// initialise value, if it's undefined
var value = model.get();
this.wasUndefined = value === undefined;
if (value === undefined && this.getInitialValue) {
value = this.getInitialValue();
model.set(value);
}
this.lastVal(true, value);
var parentForm = findElement(this.element, false, 'form');
if (parentForm) {
this.resetValue = value;
parentForm.formBindings.push(this);
}
};
var Binding__proto__ = Binding.prototype;
Binding__proto__.bind = function bind () {
this.model.registerTwowayBinding(this);
};
Binding__proto__.handleChange = function handleChange () {
var this$1 = this;
var value = this.getValue();
if (this.lastVal() === value) { return; }
runloop.start();
this.attribute.locked = true;
this.model.set(value);
this.lastVal(true, value);
// if the value changes before observers fire, unlock to be updatable cause something weird and potentially freezy is up
if (this.model.get() !== value) { this.attribute.locked = false; }
else { runloop.scheduleTask(function () { return (this$1.attribute.locked = false); }); }
runloop.end();
};
Binding__proto__.lastVal = function lastVal (setting, value) {
if (setting) { this.lastValue = value; }
else { return this.lastValue; }
};
Binding__proto__.rebind = function rebind (next, previous) {
var this$1 = this;
if (this.model && this.model === previous) { previous.unregisterTwowayBinding(this); }
if (next) {
this.model = next;
runloop.scheduleTask(function () { return next.registerTwowayBinding(this$1); });
}
};
Binding__proto__.rebound = function rebound () {
if (this.model) { this.model.unregisterTwowayBinding(this); }
this.model = this.attribute.interpolator.model;
this.model.registerTwowayBinding(this);
};
Binding__proto__.render = function render () {
this.node = this.element.node;
this.node._ractive.binding = this;
this.rendered = true; // TODO is this used anywhere?
};
Binding__proto__.setFromNode = function setFromNode (node) {
this.model.set(node.value);
};
Binding__proto__.unbind = function unbind () {
this.model.unregisterTwowayBinding(this);
};
Binding.prototype.unrender = noop;
// This is the handler for DOM events that would lead to a change in the model
// (i.e. change, sometimes, input, and occasionally click and keyup)
function handleDomEvent() {
this._ractive.binding.handleChange();
}
var CheckboxBinding = (function (Binding) {
function CheckboxBinding(element) {
Binding.call(this, element, 'checked');
}
if ( Binding ) CheckboxBinding.__proto__ = Binding;
var CheckboxBinding__proto__ = CheckboxBinding.prototype = Object.create( Binding && Binding.prototype );
CheckboxBinding__proto__.constructor = CheckboxBinding;
CheckboxBinding__proto__.render = function render () {
Binding.prototype.render.call(this);
this.element.on('change', handleDomEvent);
if (this.node.attachEvent) {
this.element.on('click', handleDomEvent);
}
};
CheckboxBinding__proto__.unrender = function unrender () {
this.element.off('change', handleDomEvent);
this.element.off('click', handleDomEvent);
};
CheckboxBinding__proto__.getInitialValue = function getInitialValue () {
return !!this.element.getAttribute('checked');
};
CheckboxBinding__proto__.getValue = function getValue () {
return this.node.checked;
};
CheckboxBinding__proto__.setFromNode = function setFromNode (node) {
this.model.set(node.checked);
};
return CheckboxBinding;
}(Binding));
function getBindingGroup(group, model, getValue) {
var hash = group + "-bindingGroup";
return model[hash] || (model[hash] = new BindingGroup(hash, model, getValue));
}
var BindingGroup = function BindingGroup(hash, model, getValue) {
var this$1 = this;
this.model = model;
this.hash = hash;
this.getValue = function () {
this$1.value = getValue.call(this$1);
return this$1.value;
};
this.bindings = [];
};
var BindingGroup__proto__ = BindingGroup.prototype;
BindingGroup__proto__.add = function add (binding) {
this.bindings.push(binding);
};
BindingGroup__proto__.bind = function bind () {
this.value = this.model.get();
this.model.registerTwowayBinding(this);
this.bound = true;
};
BindingGroup__proto__.remove = function remove (binding) {
removeFromArray(this.bindings, binding);
if (!this.bindings.length) {
this.unbind();
}
};
BindingGroup__proto__.unbind = function unbind () {
this.model.unregisterTwowayBinding(this);
this.bound = false;
delete this.model[this.hash];
};
BindingGroup.prototype.rebind = Binding.prototype.rebind;
var push$1 = [].push;
function getValue() {
var this$1 = this;
var all = this.bindings
.filter(function (b) { return b.node && b.node.checked; })
.map(function (b) { return b.element.getAttribute('value'); });
var res = [];
all.forEach(function (v) {
if (!this$1.bindings[0].arrayContains(res, v)) { res.push(v); }
});
return res;
}
var CheckboxNameBinding = (function (Binding) {
function CheckboxNameBinding(element) {
Binding.call(this, element, 'name');
this.checkboxName = true; // so that ractive.updateModel() knows what to do with this
// Each input has a reference to an array containing it and its
// group, as two-way binding depends on being able to ascertain
// the status of all inputs within the group
this.group = getBindingGroup('checkboxes', this.model, getValue);
this.group.add(this);
if (this.noInitialValue) {
this.group.noInitialValue = true;
}
// If no initial value was set, and this input is checked, we
// update the model
if (this.group.noInitialValue && this.element.getAttribute('checked')) {
var existingValue = this.model.get();
var bindingValue = this.element.getAttribute('value');
if (!this.arrayContains(existingValue, bindingValue)) {
push$1.call(existingValue, bindingValue); // to avoid triggering runloop with array adaptor
}
}
}
if ( Binding ) CheckboxNameBinding.__proto__ = Binding;
var CheckboxNameBinding__proto__ = CheckboxNameBinding.prototype = Object.create( Binding && Binding.prototype );
CheckboxNameBinding__proto__.constructor = CheckboxNameBinding;
CheckboxNameBinding__proto__.bind = function bind () {
if (!this.group.bound) {
this.group.bind();
}
};
CheckboxNameBinding__proto__.getInitialValue = function getInitialValue () {
// This only gets called once per group (of inputs that
// share a name), because it only gets called if there
// isn't an initial value. By the same token, we can make
// a note of that fact that there was no initial value,
// and populate it using any `checked` attributes that
// exist (which users should avoid, but which we should
// support anyway to avoid breaking expectations)
this.noInitialValue = true; // TODO are noInitialValue and wasUndefined the same thing?
return [];
};
CheckboxNameBinding__proto__.getValue = function getValue () {
return this.group.value;
};
CheckboxNameBinding__proto__.handleChange = function handleChange () {
this.isChecked = this.element.node.checked;
this.group.value = this.model.get();
var value = this.element.getAttribute('value');
if (this.isChecked && !this.arrayContains(this.group.value, value)) {
this.group.value.push(value);
} else if (!this.isChecked && this.arrayContains(this.group.value, value)) {
this.removeFromArray(this.group.value, value);
}
// make sure super knows there's a change
this.lastValue = null;
Binding.prototype.handleChange.call(this);
};
CheckboxNameBinding__proto__.render = function render () {
Binding.prototype.render.call(this);
var node = this.node;
var existingValue = this.model.get();
var bindingValue = this.element.getAttribute('value');
if (isArray(existingValue)) {
this.isChecked = this.arrayContains(existingValue, bindingValue);
} else {
this.isChecked = this.element.compare(existingValue, bindingValue);
}
node.name = '{{' + this.model.getKeypath() + '}}';
node.checked = this.isChecked;
this.element.on('change', handleDomEvent);
// in case of IE emergency, bind to click event as well
if (this.node.attachEvent) {
this.element.on('click', handleDomEvent);
}
};
CheckboxNameBinding__proto__.setFromNode = function setFromNode (node) {
this.group.bindings.forEach(function (binding) { return (binding.wasUndefined = true); });
if (node.checked) {
var valueSoFar = this.group.getValue();
valueSoFar.push(this.element.getAttribute('value'));
this.group.model.set(valueSoFar);
}
};
CheckboxNameBinding__proto__.unbind = function unbind () {
this.group.remove(this);
};
CheckboxNameBinding__proto__.unrender = function unrender () {
var el = this.element;
el.off('change', handleDomEvent);
el.off('click', handleDomEvent);
};
CheckboxNameBinding__proto__.arrayContains = function arrayContains (selectValue, optionValue) {
var this$1 = this;
var i = selectValue.length;
while (i--) {
if (this$1.element.compare(optionValue, selectValue[i])) { return true; }
}
return false;
};
CheckboxNameBinding__proto__.removeFromArray = function removeFromArray (array, item) {
var this$1 = this;
if (!array) { return; }
var i = array.length;
while (i--) {
if (this$1.element.compare(item, array[i])) {
array.splice(i, 1);
}
}
};
return CheckboxNameBinding;
}(Binding));
var ContentEditableBinding = (function (Binding) {
function ContentEditableBinding () {
Binding.apply(this, arguments);
}
if ( Binding ) ContentEditableBinding.__proto__ = Binding;
var ContentEditableBinding__proto__ = ContentEditableBinding.prototype = Object.create( Binding && Binding.prototype );
ContentEditableBinding__proto__.constructor = ContentEditableBinding;
ContentEditableBinding__proto__.getInitialValue = function getInitialValue () {
return this.element.fragment ? this.element.fragment.toString() : '';
};
ContentEditableBinding__proto__.getValue = function getValue () {
return this.element.node.innerHTML;
};
ContentEditableBinding__proto__.render = function render () {
Binding.prototype.render.call(this);
var el = this.element;
el.on('change', handleDomEvent);
el.on('blur', handleDomEvent);
if (!this.ractive.lazy) {
el.on('input', handleDomEvent);
if (this.node.attachEvent) {
el.on('keyup', handleDomEvent);
}
}
};
ContentEditableBinding__proto__.setFromNode = function setFromNode (node) {
this.model.set(node.innerHTML);
};
ContentEditableBinding__proto__.unrender = function unrender () {
var el = this.element;
el.off('blur', handleDomEvent);
el.off('change', handleDomEvent);
el.off('input', handleDomEvent);
el.off('keyup', handleDomEvent);
};
return ContentEditableBinding;
}(Binding));
function handleBlur() {
handleDomEvent.call(this);
var value = this._ractive.binding.model.get();
this.value = value == undefined ? '' : value;
}
function handleDelay(delay) {
var timeout;
return function() {
var this$1 = this;
if (timeout) { clearTimeout(timeout); }
timeout = setTimeout(function () {
var binding = this$1._ractive.binding;
if (binding.rendered) { handleDomEvent.call(this$1); }
timeout = null;
}, delay);
};
}
var GenericBinding = (function (Binding) {
function GenericBinding () {
Binding.apply(this, arguments);
}
if ( Binding ) GenericBinding.__proto__ = Binding;
var GenericBinding__proto__ = GenericBinding.prototype = Object.create( Binding && Binding.prototype );
GenericBinding__proto__.constructor = GenericBinding;
GenericBinding__proto__.getInitialValue = function getInitialValue () {
return '';
};
GenericBinding__proto__.getValue = function getValue () {
return this.node.value;
};
GenericBinding__proto__.render = function render () {
Binding.prototype.render.call(this);
// any lazy setting for this element overrides the root
// if the value is a number, it's a timeout
var lazy = this.ractive.lazy;
var timeout = false;
var el = this.element;
if ('lazy' in this.element) {
lazy = this.element.lazy;
}
if (isNumeric(lazy)) {
timeout = +lazy;
lazy = false;
}
this.handler = timeout ? handleDelay(timeout) : handleDomEvent;
var node = this.node;
el.on('change', handleDomEvent);
if (node.type !== 'file') {
if (!lazy) {
el.on('input', this.handler);
// IE is a special snowflake
if (node.attachEvent) {
el.on('keyup', this.handler);
}
}
el.on('blur', handleBlur);
}
};
GenericBinding__proto__.unrender = function unrender () {
var el = this.element;
this.rendered = false;
el.off('change', handleDomEvent);
el.off('input', this.handler);
el.off('keyup', this.handler);
el.off('blur', handleBlur);
};
return GenericBinding;
}(Binding));
var FileBinding = (function (GenericBinding) {
function FileBinding () {
GenericBinding.apply(this, arguments);
}
if ( GenericBinding ) FileBinding.__proto__ = GenericBinding;
var FileBinding__proto__ = FileBinding.prototype = Object.create( GenericBinding && GenericBinding.prototype );
FileBinding__proto__.constructor = FileBinding;
FileBinding__proto__.getInitialValue = function getInitialValue () {
/* istanbul ignore next */
return undefined;
};
FileBinding__proto__.getValue = function getValue () {
/* istanbul ignore next */
return this.node.files;
};
FileBinding__proto__.render = function render () {
/* istanbul ignore next */
this.element.lazy = false;
/* istanbul ignore next */
GenericBinding.prototype.render.call(this);
};
FileBinding__proto__.setFromNode = function setFromNode (node) {
/* istanbul ignore next */
this.model.set(node.files);
};
return FileBinding;
}(GenericBinding));
function getSelectedOptions(select) {
/* istanbul ignore next */
return select.selectedOptions
? toArray(select.selectedOptions)
: select.options
? toArray(select.options).filter(function (option) { return option.selected; })
: [];
}
var MultipleSelectBinding = (function (Binding) {
function MultipleSelectBinding () {
Binding.apply(this, arguments);
}
if ( Binding ) MultipleSelectBinding.__proto__ = Binding;
var MultipleSelectBinding__proto__ = MultipleSelectBinding.prototype = Object.create( Binding && Binding.prototype );
MultipleSelectBinding__proto__.constructor = MultipleSelectBinding;
MultipleSelectBinding__proto__.getInitialValue = function getInitialValue () {
return this.element.options
.filter(function (option) { return option.getAttribute('selected'); })
.map(function (option) { return option.getAttribute('value'); });
};
MultipleSelectBinding__proto__.getValue = function getValue () {
var options = this.element.node.options;
var len = options.length;
var selectedValues = [];
for (var i = 0; i < len; i += 1) {
var option = options[i];
if (option.selected) {
var optionValue = option._ractive ? option._ractive.value : option.value;
selectedValues.push(optionValue);
}
}
return selectedValues;
};
MultipleSelectBinding__proto__.handleChange = function handleChange () {
var attribute = this.attribute;
var previousValue = attribute.getValue();
var value = this.getValue();
if (previousValue === undefined || !arrayContentsMatch(value, previousValue)) {
Binding.prototype.handleChange.call(this);
}
return this;
};
MultipleSelectBinding__proto__.render = function render () {
Binding.prototype.render.call(this);
this.element.on('change', handleDomEvent);
if (this.model.get() === undefined) {
// get value from DOM, if possible
this.handleChange();
}
};
MultipleSelectBinding__proto__.setFromNode = function setFromNode (node) {
var selectedOptions = getSelectedOptions(node);
var i = selectedOptions.length;
var result = new Array(i);
while (i--) {
var option = selectedOptions[i];
result[i] = option._ractive ? option._ractive.value : option.value;
}
this.model.set(result);
};
MultipleSelectBinding__proto__.unrender = function unrender () {
this.element.off('change', handleDomEvent);
};
return MultipleSelectBinding;
}(Binding));
var NumericBinding = (function (GenericBinding) {
function NumericBinding () {
GenericBinding.apply(this, arguments);
}
if ( GenericBinding ) NumericBinding.__proto__ = GenericBinding;
var NumericBinding__proto__ = NumericBinding.prototype = Object.create( GenericBinding && GenericBinding.prototype );
NumericBinding__proto__.constructor = NumericBinding;
NumericBinding__proto__.getInitialValue = function getInitialValue () {
return undefined;
};
NumericBinding__proto__.getValue = function getValue () {
var value = parseFloat(this.node.value);
return isNaN(value) ? undefined : value;
};
NumericBinding__proto__.setFromNode = function setFromNode (node) {
var value = parseFloat(node.value);
if (!isNaN(value)) { this.model.set(value); }
};
return NumericBinding;
}(GenericBinding));
var siblings = {};
function getSiblings(hash) {
return siblings[hash] || (siblings[hash] = []);
}
var RadioBinding = (function (Binding) {
function RadioBinding(element) {
Binding.call(this, element, 'checked');
this.siblings = getSiblings(this.ractive._guid + this.element.getAttribute('name'));
this.siblings.push(this);
}
if ( Binding ) RadioBinding.__proto__ = Binding;
var RadioBinding__proto__ = RadioBinding.prototype = Object.create( Binding && Binding.prototype );
RadioBinding__proto__.constructor = RadioBinding;
RadioBinding__proto__.getValue = function getValue () {
return this.node.checked;
};
RadioBinding__proto__.handleChange = function handleChange () {
runloop.start();
this.siblings.forEach(function (binding) {
binding.model.set(binding.getValue());
});
runloop.end();
};
RadioBinding__proto__.render = function render () {
Binding.prototype.render.call(this);
this.element.on('change', handleDomEvent);
if (this.node.attachEvent) {
this.element.on('click', handleDomEvent);
}
};
RadioBinding__proto__.setFromNode = function setFromNode (node) {
this.model.set(node.checked);
};
RadioBinding__proto__.unbind = function unbind () {
removeFromArray(this.siblings, this);
};
RadioBinding__proto__.unrender = function unrender () {
this.element.off('change', handleDomEvent);
this.element.off('click', handleDomEvent);
};
return RadioBinding;
}(Binding));
function getValue$1() {
var checked = this.bindings.filter(function (b) { return b.node.checked; });
if (checked.length > 0) {
return checked[0].element.getAttribute('value');
}
}
var RadioNameBinding = (function (Binding) {
function RadioNameBinding(element) {
var this$1 = this;
Binding.call(this, element, 'name');
this.group = getBindingGroup('radioname', this.model, getValue$1);
this.group.add(this);
if (element.checked) {
this.group.value = this.getValue();
}
this.attribute.interpolator.pathChanged = function () { return this$1.updateName(); };
}
if ( Binding ) RadioNameBinding.__proto__ = Binding;
var RadioNameBinding__proto__ = RadioNameBinding.prototype = Object.create( Binding && Binding.prototype );
RadioNameBinding__proto__.constructor = RadioNameBinding;
RadioNameBinding__proto__.bind = function bind () {
if (!this.group.bound) {
this.group.bind();
}
};
RadioNameBinding__proto__.getInitialValue = function getInitialValue () {
if (this.element.getAttribute('checked')) {
return this.element.getAttribute('value');
}
};
RadioNameBinding__proto__.getValue = function getValue () {
return this.element.getAttribute('value');
};
RadioNameBinding__proto__.handleChange = function handleChange () {
// If this <input> is the one that's checked, then the value of its
// `name` model gets set to its value
if (this.node.checked) {
this.group.value = this.getValue();
Binding.prototype.handleChange.call(this);
}
this.updateName();
};
RadioNameBinding__proto__.lastVal = function lastVal (setting, value) {
if (!this.group) { return; }
if (setting) { this.group.lastValue = value; }
else { return this.group.lastValue; }
};
RadioNameBinding__proto__.rebind = function rebind (next, previous) {
Binding.prototype.rebind.call(this, next, previous);
this.updateName();
};
RadioNameBinding__proto__.rebound = function rebound (update) {
Binding.prototype.rebound.call(this, update);
this.updateName();
};
RadioNameBinding__proto__.render = function render () {
Binding.prototype.render.call(this);
var node = this.node;
this.updateName();
node.checked = this.element.compare(this.model.get(), this.element.getAttribute('value'));
this.element.on('change', handleDomEvent);
if (node.attachEvent) {
this.element.on('click', handleDomEvent);
}
};
RadioNameBinding__proto__.setFromNode = function setFromNode (node) {
if (node.checked) {
this.group.model.set(this.element.getAttribute('value'));
}
};
RadioNameBinding__proto__.unbind = function unbind () {
this.group.remove(this);
};
RadioNameBinding__proto__.unrender = function unrender () {
var el = this.element;
el.off('change', handleDomEvent);
el.off('click', handleDomEvent);
};
RadioNameBinding__proto__.updateName = function updateName () {
if (this.node) { this.node.name = "{{" + (this.model.getKeypath()) + "}}"; }
};
return RadioNameBinding;
}(Binding));
var SingleSelectBinding = (function (Binding) {
function SingleSelectBinding () {
Binding.apply(this, arguments);
}
if ( Binding ) SingleSelectBinding.__proto__ = Binding;
var SingleSelectBinding__proto__ = SingleSelectBinding.prototype = Object.create( Binding && Binding.prototype );
SingleSelectBinding__proto__.constructor = SingleSelectBinding;
SingleSelectBinding__proto__.forceUpdate = function forceUpdate () {
var this$1 = this;
var value = this.getValue();
if (value !== undefined) {
this.attribute.locked = true;
runloop.scheduleTask(function () { return (this$1.attribute.locked = false); });
this.model.set(value);
}
};
SingleSelectBinding__proto__.getInitialValue = function getInitialValue () {
if (this.element.getAttribute('value') !== undefined) {
return;
}
var options = this.element.options;
var len = options.length;
if (!len) { return; }
var value;
var optionWasSelected;
var i = len;
// take the final selected option...
while (i--) {
var option = options[i];
if (option.getAttribute('selected')) {
if (!option.getAttribute('disabled')) {
value = option.getAttribute('value');
}
optionWasSelected = true;
break;
}
}
// or the first non-disabled option, if none are selected
if (!optionWasSelected) {
while (++i < len) {
if (!options[i].getAttribute('disabled')) {
value = options[i].getAttribute('value');
break;
}
}
}
// This is an optimisation (aka hack) that allows us to forgo some
// other more expensive work
// TODO does it still work? seems at odds with new architecture
if (value !== undefined) {
this.element.attributeByName.value.value = value;
}
return value;
};
SingleSelectBinding__proto__.getValue = function getValue () {
var options = this.node.options;
var len = options.length;
var i;
for (i = 0; i < len; i += 1) {
var option = options[i];
if (options[i].selected && !options[i].disabled) {
return option._ractive ? option._ractive.value : option.value;
}
}
};
SingleSelectBinding__proto__.render = function render () {
Binding.prototype.render.call(this);
this.element.on('change', handleDomEvent);
};
SingleSelectBinding__proto__.setFromNode = function setFromNode (node) {
var option = getSelectedOptions(node)[0];
this.model.set(option._ractive ? option._ractive.value : option.value);
};
SingleSelectBinding__proto__.unrender = function unrender () {
this.element.off('change', handleDomEvent);
};
return SingleSelectBinding;
}(Binding));
function isBindable(attribute) {
// The fragment must be a single non-string fragment
if (
!attribute ||
!attribute.template.f ||
attribute.template.f.length !== 1 ||
attribute.template.f[0].s
)
{ return false; }
// A binding is an interpolator `{{ }}`, yey.
if (attribute.template.f[0].t === INTERPOLATOR) { return true; }
// The above is probably the only true case. For the rest, show an appropriate
// warning before returning false.
// You can't bind a triple curly. HTML values on an attribute makes no sense.
if (attribute.template.f[0].t === TRIPLE)
{ warnIfDebug('It is not possible create a binding using a triple mustache.'); }
return false;
}
function selectBinding(element) {
var name = element.name;
var attributes = element.attributeByName;
if (name !== 'input' && name !== 'textarea' && name !== 'select' && !attributes.contenteditable)
{ return; }
var isBindableByValue = isBindable(attributes.value);
var isBindableByContentEditable = isBindable(attributes.contenteditable);
var isContentEditable = element.getAttribute('contenteditable');
// contenteditable
// Bind if the contenteditable is true or a binding that may become true.
if ((isContentEditable || isBindableByContentEditable) && isBindableByValue)
{ return ContentEditableBinding; }
// <input>
if (name === 'input') {
var type = element.getAttribute('type');
if (type === 'radio') {
var isBindableByName = isBindable(attributes.name);
var isBindableByChecked = isBindable(attributes.checked);
// For radios we can either bind the name or checked, but not both.
// Name binding is handed instead.
if (isBindableByName && isBindableByChecked) {
warnIfDebug(
'A radio input can have two-way binding on its name attribute, or its checked attribute - not both',
{ ractive: element.root }
);
return RadioNameBinding;
}
if (isBindableByName) { return RadioNameBinding; }
if (isBindableByChecked) { return RadioBinding; }
// Dead end. Unknown binding on radio input.
return null;
}
if (type === 'checkbox') {
var isBindableByName$1 = isBindable(attributes.name);
var isBindableByChecked$1 = isBindable(attributes.checked);
// A checkbox with bindings for both name and checked. Checked treated as
// the checkbox value, name is treated as a regular binding.
//
// See https://github.com/ractivejs/ractive/issues/1749
if (isBindableByName$1 && isBindableByChecked$1) { return CheckboxBinding; }
if (isBindableByName$1) { return CheckboxNameBinding; }
if (isBindableByChecked$1) { return CheckboxBinding; }
// Dead end. Unknown binding on checkbox input.
return null;
}
if (type === 'file' && isBindableByValue) { return FileBinding; }
if (type === 'number' && isBindableByValue) { return NumericBinding; }
if (type === 'range' && isBindableByValue) { return NumericBinding; }
// Some input of unknown type (browser usually falls back to text).
if (isBindableByValue) { return GenericBinding; }
// Dead end. Some unknown input and an unbindable.
return null;
}
// <select>
if (name === 'select' && isBindableByValue) {
return element.getAttribute('multiple') ? MultipleSelectBinding : SingleSelectBinding;
}
// <textarea>
if (name === 'textarea' && isBindableByValue) { return GenericBinding; }
// Dead end. Some unbindable element.
return null;
}
var endsWithSemi = /;\s*$/;
var Element = (function (ContainerItem) {
function Element(options) {
var this$1 = this;
ContainerItem.call(this, options);
this.name = options.template.e.toLowerCase();
// find parent element
this.parent = findElement(this.up, false);
if (this.parent && this.parent.name === 'option') {
throw new Error(
("An <option> element cannot contain other elements (encountered <" + (this.name) + ">)")
);
}
this.decorators = [];
// create attributes
this.attributeByName = {};
var attrs;
var n, attr, val, cls, name, template, leftovers;
var m = this.template.m;
var len = (m && m.length) || 0;
for (var i = 0; i < len; i++) {
template = m[i];
if (template.g) {
(this$1.statics || (this$1.statics = {}))[template.n] = isString(template.f)
? template.f
: template.n;
} else {
switch (template.t) {
case ATTRIBUTE:
case BINDING_FLAG:
case DECORATOR:
case EVENT:
case TRANSITION:
attr = createItem({
owner: this$1,
up: this$1.up,
template: template
});
n = template.n;
attrs = attrs || (attrs = this$1.attributes = []);
if (n === 'value') { val = attr; }
else if (n === 'name') { name = attr; }
else if (n === 'class') { cls = attr; }
else { attrs.push(attr); }
break;
case DELEGATE_FLAG:
this$1.delegate = false;
break;
default:
(leftovers || (leftovers = [])).push(template);
break;
}
}
}
if (val) { attrs.push(val); }
if (name) { attrs.push(name); }
if (cls) { attrs.unshift(cls); }
if (leftovers) {
(attrs || (this.attributes = [])).push(
new ConditionalAttribute({
owner: this,
up: this.up,
template: leftovers
})
);
// empty leftovers array
leftovers = [];
}
// create children
if (options.template.f && !options.deferContent) {
this.fragment = new Fragment({
template: options.template.f,
owner: this,
cssIds: null
});
}
this.binding = null; // filled in later
}
if ( ContainerItem ) Element.__proto__ = ContainerItem;
var Element__proto__ = Element.prototype = Object.create( ContainerItem && ContainerItem.prototype );
Element__proto__.constructor = Element;
Element__proto__.bind = function bind () {
var attrs = this.attributes;
if (attrs) {
attrs.binding = true;
var len = attrs.length;
for (var i = 0; i < len; i++) { attrs[i].bind(); }
attrs.binding = false;
}
if (this.fragment) { this.fragment.bind(); }
// create two-way binding if necessary
if (!this.binding) { this.recreateTwowayBinding(); }
else { this.binding.bind(); }
};
Element__proto__.createTwowayBinding = function createTwowayBinding () {
if ('twoway' in this ? this.twoway : this.ractive.twoway) {
var Binding = selectBinding(this);
if (Binding) {
var binding = new Binding(this);
if (binding && binding.model) { return binding; }
}
}
};
Element__proto__.destroyed = function destroyed$1 () {
if (this.attributes) { this.attributes.forEach(destroyed); }
if (this.fragment) { this.fragment.destroyed(); }
};
Element__proto__.detach = function detach () {
// if this element is no longer rendered, the transitions are complete and the attributes can be torn down
if (!this.rendered) { this.destroyed(); }
return detachNode(this.node);
};
Element__proto__.find = function find (selector, options) {
if (this.node && matches(this.node, selector)) { return this.node; }
if (this.fragment) {
return this.fragment.find(selector, options);
}
};
Element__proto__.findAll = function findAll (selector, options) {
var result = options.result;
if (matches(this.node, selector)) {
result.push(this.node);
}
if (this.fragment) {
this.fragment.findAll(selector, options);
}
};
Element__proto__.findNextNode = function findNextNode () {
return null;
};
Element__proto__.firstNode = function firstNode () {
return this.node;
};
Element__proto__.getAttribute = function getAttribute (name) {
if (this.statics && name in this.statics) { return this.statics[name]; }
var attribute = this.attributeByName[name];
return attribute ? attribute.getValue() : undefined;
};
Element__proto__.getContext = function getContext () {
var assigns = [], len = arguments.length;
while ( len-- ) assigns[ len ] = arguments[ len ];
if (this.fragment) { return (ref = this.fragment).getContext.apply(ref, assigns); }
if (!this.ctx) { this.ctx = new Context(this.up, this); }
assigns.unshift(create(this.ctx));
return assign.apply(null, assigns);
var ref;
};
Element__proto__.off = function off (event, callback, capture) {
if ( capture === void 0 ) capture = false;
var delegate = this.up.delegate;
var ref = this.listeners && this.listeners[event];
if (!ref) { return; }
removeFromArray(ref, callback);
if (delegate) {
var listeners =
(delegate.listeners || (delegate.listeners = [])) &&
(delegate.listeners[event] || (delegate.listeners[event] = []));
if (listeners.refs && !--listeners.refs) { delegate.off(event, delegateHandler, true); }
} else if (this.rendered) {
var n = this.node;
var add = n.addEventListener;
var rem = n.removeEventListener;
if (!ref.length) {
rem.call(n, event, handler, capture);
} else if (ref.length && !ref.refs && capture) {
rem.call(n, event, handler, true);
add.call(n, event, handler, false);
}
}
};
Element__proto__.on = function on (event, callback, capture) {
if ( capture === void 0 ) capture = false;
var delegate = this.up.delegate;
var ref = (this.listeners || (this.listeners = {}))[event] || (this.listeners[event] = []);
if (delegate) {
var listeners =
((delegate.listeners || (delegate.listeners = [])) && delegate.listeners[event]) ||
(delegate.listeners[event] = []);
if (!listeners.refs) {
listeners.refs = 0;
delegate.on(event, delegateHandler, true);
listeners.refs++;
} else {
listeners.refs++;
}
} else if (this.rendered) {
var n = this.node;
var add = n.addEventListener;
var rem = n.removeEventListener;
if (!ref.length) {
add.call(n, event, handler, capture);
} else if (ref.length && !ref.refs && capture) {
rem.call(n, event, handler, false);
add.call(n, event, handler, true);
}
}
addToArray(this.listeners[event], callback);
};
Element__proto__.recreateTwowayBinding = function recreateTwowayBinding () {
if (this.binding) {
this.binding.unbind();
this.binding.unrender();
}
if ((this.binding = this.createTwowayBinding())) {
this.binding.bind();
if (this.rendered) { this.binding.render(); }
}
};
Element__proto__.rebound = function rebound (update$$1) {
ContainerItem.prototype.rebound.call(this, update$$1);
if (this.attributes) { this.attributes.forEach(function (x) { return x.rebound(update$$1); }); }
if (this.binding) { this.binding.rebound(update$$1); }
};
Element__proto__.render = function render (target, occupants) {
var this$1 = this;
// TODO determine correct namespace
this.namespace = getNamespace(this);
var node;
var existing = false;
if (occupants) {
var n;
while ((n = occupants.shift())) {
if (
n.nodeName.toUpperCase() === this$1.template.e.toUpperCase() &&
n.namespaceURI === this$1.namespace
) {
this$1.node = node = n;
existing = true;
break;
} else {
detachNode(n);
}
}
}
if (!existing && this.node) {
node = this.node;
target.appendChild(node);
existing = true;
}
if (!node) {
var name = this.template.e;
node = createElement(
this.namespace === html ? name.toLowerCase() : name,
this.namespace,
this.getAttribute('is')
);
this.node = node;
}
// tie the node to this vdom element
defineProperty(node, '_ractive', {
value: {
proxy: this
},
configurable: true
});
if (this.statics) {
keys(this.statics).forEach(function (k) {
node.setAttribute(k, this$1.statics[k]);
});
}
if (existing && this.foundNode) { this.foundNode(node); }
// register intro before rendering content so children can find the intro
var intro = this.intro;
if (intro && intro.shouldFire('intro')) {
intro.isIntro = true;
intro.isOutro = false;
runloop.registerTransition(intro);
}
if (this.fragment) {
var children = existing ? toArray(node.childNodes) : undefined;
this.fragment.render(node, children);
// clean up leftover children
if (children) {
children.forEach(detachNode);
}
}
if (existing) {
// store initial values for two-way binding
if (this.binding && this.binding.wasUndefined) { this.binding.setFromNode(node); }
// remove unused attributes
var i = node.attributes.length;
while (i--) {
var name$1 = node.attributes[i].name;
if (!(name$1 in this$1.attributeByName) && (!this$1.statics || !(name$1 in this$1.statics)))
{ node.removeAttribute(name$1); }
}
}
// Is this a top-level node of a component? If so, we may need to add
// a data-ractive-css attribute, for CSS encapsulation
if (this.up.cssIds) {
node.setAttribute('data-ractive-css', this.up.cssIds.map(function (x) { return ("{" + x + "}"); }).join(' '));
}
if (this.attributes) {
var len = this.attributes.length;
for (var i$1 = 0; i$1 < len; i$1++) { this$1.attributes[i$1].render(); }
}
if (this.binding) { this.binding.render(); }
if (!this.up.delegate && this.listeners) {
var ls = this.listeners;
for (var k in ls) {
if (ls[k] && ls[k].length) { this$1.node.addEventListener(k, handler, !!ls[k].refs); }
}
}
if (!existing) {
target.appendChild(node);
}
this.rendered = true;
};
Element__proto__.toString = function toString () {
var this$1 = this;
var tagName = this.template.e;
var attrs = (this.attributes && this.attributes.map(stringifyAttribute).join('')) || '';
if (this.statics)
{ keys(this.statics).forEach(
function (k) { return k !== 'class' && k !== 'style' && (attrs = " " + k + "=\"" + (this$1.statics[k]) + "\"" + attrs); }
); }
// Special case - selected options
if (this.name === 'option' && this.isSelected()) {
attrs += ' selected';
}
// Special case - two-way radio name bindings
if (this.name === 'input' && inputIsCheckedRadio(this)) {
attrs += ' checked';
}
// Special case style and class attributes and directives
var style = this.statics ? this.statics.style : undefined;
var cls = this.statics ? this.statics.class : undefined;
this.attributes &&
this.attributes.forEach(function (attr) {
if (attr.name === 'class') {
cls = (cls || '') + (cls ? ' ' : '') + safeAttributeString(attr.getString());
} else if (attr.name === 'style') {
style = (style || '') + (style ? ' ' : '') + safeAttributeString(attr.getString());
if (style && !endsWithSemi.test(style)) { style += ';'; }
} else if (attr.style) {
style =
(style || '') +
(style ? ' ' : '') +
(attr.style) + ": " + (safeAttributeString(attr.getString())) + ";";
} else if (attr.inlineClass && attr.getValue()) {
cls = (cls || '') + (cls ? ' ' : '') + attr.inlineClass;
}
});
// put classes first, then inline style
if (style !== undefined) { attrs = ' style' + (style ? ("=\"" + style + "\"") : '') + attrs; }
if (cls !== undefined) { attrs = ' class' + (cls ? ("=\"" + cls + "\"") : '') + attrs; }
if (this.up.cssIds) {
attrs += " data-ractive-css=\"" + (this.up.cssIds.map(function (x) { return ("{" + x + "}"); }).join(' ')) + "\"";
}
var str = "<" + tagName + attrs + ">";
if (voidElements[this.name.toLowerCase()]) { return str; }
// Special case - textarea
if (this.name === 'textarea' && this.getAttribute('value') !== undefined) {
str += escapeHtml(this.getAttribute('value'));
} else if (this.getAttribute('contenteditable') !== undefined) {
// Special case - contenteditable
str += this.getAttribute('value') || '';
}
if (this.fragment) {
str += this.fragment.toString(!/^(?:script|style)$/i.test(this.template.e)); // escape text unless script/style
}
str += "</" + tagName + ">";
return str;
};
Element__proto__.unbind = function unbind (view) {
var attrs = this.attributes;
if (attrs) {
attrs.unbinding = true;
var len = attrs.length;
for (var i = 0; i < len; i++) { attrs[i].unbind(view); }
attrs.unbinding = false;
}
if (this.binding) { this.binding.unbind(view); }
if (this.fragment) { this.fragment.unbind(view); }
};
Element__proto__.unrender = function unrender (shouldDestroy) {
if (!this.rendered) { return; }
this.rendered = false;
// unrendering before intro completed? complete it now
// TODO should be an API for aborting transitions
var transition = this.intro;
if (transition && transition.complete) { transition.complete(); }
// Detach as soon as we can
if (this.name === 'option') {
// <option> elements detach immediately, so that
// their parent <select> element syncs correctly, and
// since option elements can't have transitions anyway
this.detach();
} else if (shouldDestroy) {
runloop.detachWhenReady(this);
}
// outro transition
var outro = this.outro;
if (outro && outro.shouldFire('outro')) {
outro.isIntro = false;
outro.isOutro = true;
runloop.registerTransition(outro);
}
if (this.fragment) { this.fragment.unrender(); }
if (this.binding) { this.binding.unrender(); }
};
Element__proto__.update = function update () {
if (this.dirty) {
this.dirty = false;
var attrs = this.attributes;
if (attrs) {
var len = attrs.length;
for (var i = 0; i < len; i++) { attrs[i].update(); }
}
if (this.fragment) { this.fragment.update(); }
}
};
return Element;
}(ContainerItem));
function inputIsCheckedRadio(element) {
var nameAttr = element.attributeByName.name;
return (
element.getAttribute('type') === 'radio' &&
(nameAttr || {}).interpolator &&
element.getAttribute('value') === nameAttr.interpolator.model.get()
);
}
function stringifyAttribute(attribute) {
var str = attribute.toString();
return str ? ' ' + str : '';
}
function getNamespace(element) {
// Use specified namespace...
var xmlns$$1 = element.getAttribute('xmlns');
if (xmlns$$1) { return xmlns$$1; }
// ...or SVG namespace, if this is an <svg> element
if (element.name === 'svg') { return svg$1; }
var parent = element.parent;
if (parent) {
// ...or HTML, if the parent is a <foreignObject>
if (parent.name === 'foreignobject') { return html; }
// ...or inherit from the parent node
return parent.node.namespaceURI;
}
return element.ractive.el.namespaceURI;
}
function delegateHandler(ev) {
var name = ev.type;
var end = ev.currentTarget;
var endEl = end._ractive && end._ractive.proxy;
var node = ev.target;
var bubble = true;
var listeners;
// starting with the origin node, walk up the DOM looking for ractive nodes with a matching event listener
while (bubble && node && node !== end) {
var proxy = node._ractive && node._ractive.proxy;
if (proxy && proxy.up.delegate === endEl && shouldFire(ev, node, end)) {
listeners = proxy.listeners && proxy.listeners[name];
if (listeners) {
var len = listeners.length;
for (var i = 0; i < len; i++) { bubble = listeners[i].call(node, ev) !== false && bubble; }
}
}
node = node.parentNode || node.correspondingUseElement; // SVG with a <use> element in certain environments
}
return bubble;
}
var UIEvent = win !== null ? win.UIEvent : null;
function shouldFire(event, start, end) {
if (UIEvent && event instanceof UIEvent) {
var node = start;
while (node && node !== end) {
if (node.disabled) { return false; }
node = node.parentNode || node.correspondingUseElement;
}
}
return true;
}
function handler(ev) {
var this$1 = this;
var el = this._ractive.proxy;
var listeners;
if (el.listeners && (listeners = el.listeners[ev.type])) {
var len = listeners.length;
for (var i = 0; i < len; i++) { listeners[i].call(this$1, ev); }
}
}
var Form = (function (Element) {
function Form(options) {
Element.call(this, options);
this.formBindings = [];
}
if ( Element ) Form.__proto__ = Element;
var Form__proto__ = Form.prototype = Object.create( Element && Element.prototype );
Form__proto__.constructor = Form;
Form__proto__.render = function render (target, occupants) {
Element.prototype.render.call(this, target, occupants);
this.on('reset', handleReset);
};
Form__proto__.unrender = function unrender (shouldDestroy) {
this.off('reset', handleReset);
Element.prototype.unrender.call(this, shouldDestroy);
};
return Form;
}(Element));
function handleReset() {
var element = this._ractive.proxy;
runloop.start();
element.formBindings.forEach(updateModel);
runloop.end();
}
function updateModel(binding) {
binding.model.set(binding.resetValue);
}
var DOMEvent = function DOMEvent(name, owner) {
if (name.indexOf('*') !== -1) {
fatal(
("Only component proxy-events may contain \"*\" wildcards, <" + (owner.name) + " on-" + name + "=\"...\"/> is not valid")
);
}
this.name = name;
this.owner = owner;
this.handler = null;
};
var DOMEvent__proto__ = DOMEvent.prototype;
DOMEvent__proto__.bind = function bind () {};
DOMEvent__proto__.render = function render (directive) {
var this$1 = this;
var name = this.name;
var register = function () {
var node = this$1.owner.node;
this$1.owner.on(
name,
(this$1.handler = function (event) {
return directive.fire({
node: node,
original: event,
event: event,
name: name
});
})
);
};
if (name !== 'load') {
// schedule events so that they take place after twoway binding
runloop.scheduleTask(register, true);
} else {
// unless its a load event
register();
}
};
DOMEvent__proto__.unbind = function unbind () {};
DOMEvent__proto__.unrender = function unrender () {
if (this.handler) { this.owner.off(this.name, this.handler); }
};
var CustomEvent = function CustomEvent(eventPlugin, owner, name, args) {
this.eventPlugin = eventPlugin;
this.owner = owner;
this.name = name;
this.handler = null;
this.args = args;
};
var CustomEvent__proto__ = CustomEvent.prototype;
CustomEvent__proto__.bind = function bind () {};
CustomEvent__proto__.render = function render (directive) {
var this$1 = this;
runloop.scheduleTask(function () {
var node = this$1.owner.node;
this$1.handler = this$1.eventPlugin.apply(
this$1.owner.ractive,
[
node,
function (event) {
if ( event === void 0 ) event = {};
if (event.original) { event.event = event.original; }
else { event.original = event.event; }
event.name = this$1.name;
event.node = event.node || node;
return directive.fire(event);
}
].concat(this$1.args || [])
);
});
};
CustomEvent__proto__.unbind = function unbind () {};
CustomEvent__proto__.unrender = function unrender () {
this.handler.teardown();
};
var RactiveEvent = function RactiveEvent(component, name) {
this.component = component;
this.name = name;
this.handler = null;
};
var RactiveEvent__proto__ = RactiveEvent.prototype;
RactiveEvent__proto__.bind = function bind (directive) {
var ractive = this.component.instance;
this.handler = ractive.on(this.name, function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
// watch for reproxy
if (args[0] instanceof Context) {
var ctx = args.shift();
ctx.component = ractive;
directive.fire(ctx, args);
} else {
directive.fire({}, args);
}
// cancel bubbling
return false;
});
};
RactiveEvent__proto__.render = function render () {};
RactiveEvent__proto__.unbind = function unbind () {
this.handler.cancel();
};
RactiveEvent__proto__.unrender = function unrender () {};
var specialPattern = /^(event|arguments|@node|@event|@context)(\..+)?$/;
var dollarArgsPattern = /^\$(\d+)(\..+)?$/;
var EventDirective = function EventDirective(options) {
this.owner = options.owner || options.up.owner || findElement(options.up);
this.element = this.owner.attributeByName ? this.owner : findElement(options.up, true);
this.template = options.template;
this.up = options.up;
this.ractive = options.up.ractive;
this.events = [];
};
var EventDirective__proto__ = EventDirective.prototype;
EventDirective__proto__.bind = function bind () {
var this$1 = this;
// sometimes anchors will cause an unbind without unrender
if (this.events.length) {
this.events.forEach(function (e) { return e.unrender(); });
this.events = [];
}
if (this.element.type === COMPONENT || this.element.type === ANCHOR) {
this.template.n.forEach(function (n) {
this$1.events.push(new RactiveEvent(this$1.element, n));
});
} else {
var args;
if ((args = this.template.a)) {
var rs = args.r.map(function (r) {
var model = resolveReference(this$1.up, r);
return model ? model.get() : undefined;
});
try {
args = getFunction(args.s, rs.length).apply(null, rs);
} catch (err) {
args = null;
warnIfDebug(
("Failed to compute args for event on-" + (this.template.n.join('- ')) + ": " + (err.message ||
err))
);
}
}
this.template.n.forEach(function (n) {
var fn = findInViewHierarchy('events', this$1.ractive, n);
if (fn) {
this$1.events.push(new CustomEvent(fn, this$1.element, n, args));
} else {
this$1.events.push(new DOMEvent(n, this$1.element));
}
});
}
// method calls
this.models = null;
addToArray(this.element.events || (this.element.events = []), this);
setupArgsFn(this, this.template);
if (!this.fn) { this.action = this.template.f; }
this.events.forEach(function (e) { return e.bind(this$1); });
};
EventDirective__proto__.destroyed = function destroyed () {
this.events.forEach(function (e) { return e.unrender(); });
};
EventDirective__proto__.fire = function fire (event, args) {
var this$1 = this;
if ( args === void 0 ) args = [];
var context =
event instanceof Context && event.refire ? event : this.element.getContext(event);
if (this.fn) {
var values = [];
var models = resolveArgs(this, this.template, this.up, {
specialRef: function specialRef(ref) {
var specialMatch = specialPattern.exec(ref);
if (specialMatch) {
// on-click="foo(event.node)"
return {
special: specialMatch[1],
keys: specialMatch[2] ? splitKeypath(specialMatch[2].substr(1)) : []
};
}
var dollarMatch = dollarArgsPattern.exec(ref);
if (dollarMatch) {
// on-click="foo($1)"
return {
special: 'arguments',
keys: [dollarMatch[1] - 1].concat(
dollarMatch[2] ? splitKeypath(dollarMatch[2].substr(1)) : []
)
};
}
}
});
if (models) {
models.forEach(function (model) {
if (!model) { return values.push(undefined); }
if (model.special) {
var which = model.special;
var obj;
if (which === '@node') {
obj = this$1.element.node;
} else if (which === '@event') {
obj = event && event.event;
} else if (which === 'event') {
warnOnceIfDebug(
"The event reference available to event directives is deprecated and should be replaced with @context and @event"
);
obj = context;
} else if (which === '@context') {
obj = context;
} else {
obj = args;
}
var keys = model.keys.slice();
while (obj && keys.length) { obj = obj[keys.shift()]; }
return values.push(obj);
}
if (model.wrapper) {
return values.push(model.wrapperValue);
}
values.push(model.get());
});
}
// make event available as `this.event`
var ractive = this.ractive;
var oldEvent = ractive.event;
ractive.event = context;
var returned = this.fn.apply(ractive, values);
var result = returned.pop();
// Auto prevent and stop if return is explicitly false
if (result === false) {
var original = event ? event.original : undefined;
if (original) {
original.preventDefault && original.preventDefault();
original.stopPropagation && original.stopPropagation();
} else {
warnOnceIfDebug(
("handler '" + (this.template.n.join(
' '
)) + "' returned false, but there is no event available to cancel")
);
}
} else if (!returned.length && isArray(result) && isString(result[0])) {
// watch for proxy events
result = fireEvent(this.ractive, result.shift(), context, result);
}
ractive.event = oldEvent;
return result;
} else {
return fireEvent(this.ractive, this.action, context, args);
}
};
EventDirective__proto__.handleChange = function handleChange () {};
EventDirective__proto__.render = function render () {
var this$1 = this;
this.events.forEach(function (e) { return e.render(this$1); });
};
EventDirective__proto__.toString = function toString () {
return '';
};
EventDirective__proto__.unbind = function unbind (view) {
removeFromArray(this.element.events, this);
this.events.forEach(function (e) { return e.unbind(view); });
};
EventDirective__proto__.unrender = function unrender () {
this.events.forEach(function (e) { return e.unrender(); });
};
var proto$4 = EventDirective.prototype;
proto$4.firstNode = proto$4.rebound = proto$4.update = noop;
function progressiveText(item, target, occupants, text) {
if (occupants) {
var n = occupants[0];
if (n && n.nodeType === 3) {
var idx = n.nodeValue.indexOf(text);
occupants.shift();
if (idx === 0) {
if (n.nodeValue.length !== text.length) {
occupants.unshift(n.splitText(text.length));
}
} else {
n.nodeValue = text;
}
} else {
n = item.node = doc.createTextNode(text);
if (occupants[0]) {
target.insertBefore(n, occupants[0]);
} else {
target.appendChild(n);
}
}
item.node = n;
} else {
if (!item.node) { item.node = doc.createTextNode(text); }
target.appendChild(item.node);
}
}
var Mustache = (function (Item) {
function Mustache(options) {
Item.call(this, options);
if (options.owner) { this.parent = options.owner; }
this.isStatic = !!options.template.s;
this.model = null;
this.dirty = false;
}
if ( Item ) Mustache.__proto__ = Item;
var Mustache__proto__ = Mustache.prototype = Object.create( Item && Item.prototype );
Mustache__proto__.constructor = Mustache;
Mustache__proto__.bind = function bind (pre) {
// yield mustaches and inner contexts should resolve in container context
var start = this.template.y
? this.template.y.containerFragment
: this.containerFragment || this.up;
// try to find a model for this view
var model = pre || resolve(start, this.template);
if (model) {
var value = model.get();
if (this.isStatic) {
this.model = { get: function () { return value; } };
model.unreference();
return;
}
model.register(this);
this.model = model;
}
};
Mustache__proto__.handleChange = function handleChange () {
this.bubble();
};
Mustache__proto__.rebind = function rebind (next, previous, safe) {
if (this.isStatic) { return; }
next = rebindMatch(this.template, next, previous, this.up);
if (next === this.model) { return false; }
if (this.model) {
this.model.unregister(this);
}
if (next) { next.addShuffleRegister(this, 'mark'); }
this.model = next;
if (!safe) { this.handleChange(); }
return true;
};
Mustache__proto__.rebound = function rebound (update) {
if (this.model) {
if (this.model.rebound) { this.model.rebound(update); }
else {
// check to see if the model actually changed...
// yield mustaches and inner contexts should resolve in container context
var start = this.template.y
? this.template.y.containerFragment
: this.containerFragment || this.up;
// try to find a model for this view
var model = resolve(start, this.template);
if (model !== this.model) {
this.model.unregister(this);
this.bind(model);
}
}
if (update) { this.bubble(); }
}
if (this.fragment) { this.fragment.rebound(update); }
};
Mustache__proto__.unbind = function unbind () {
if (!this.isStatic) {
this.model && this.model.unregister(this);
this.model = undefined;
}
};
return Mustache;
}(Item));
function MustacheContainer(options) {
Mustache.call(this, options);
}
var proto$5 = (MustacheContainer.prototype = Object.create(ContainerItem.prototype));
assign(proto$5, Mustache.prototype, { constructor: MustacheContainer });
var Interpolator = (function (Mustache) {
function Interpolator () {
Mustache.apply(this, arguments);
}
if ( Mustache ) Interpolator.__proto__ = Mustache;
var Interpolator__proto__ = Interpolator.prototype = Object.create( Mustache && Mustache.prototype );
Interpolator__proto__.constructor = Interpolator;
Interpolator__proto__.bubble = function bubble () {
if (this.owner) { this.owner.bubble(); }
Mustache.prototype.bubble.call(this);
};
Interpolator__proto__.detach = function detach () {
return detachNode(this.node);
};
Interpolator__proto__.firstNode = function firstNode () {
return this.node;
};
Interpolator__proto__.getString = function getString () {
return this.model ? safeToStringValue(this.model.get()) : '';
};
Interpolator__proto__.render = function render (target, occupants) {
if (inAttributes()) { return; }
var value = (this.value = this.getString());
this.rendered = true;
progressiveText(this, target, occupants, value);
};
Interpolator__proto__.toString = function toString (escape) {
var string = this.getString();
return escape ? escapeHtml(string) : string;
};
Interpolator__proto__.unrender = function unrender (shouldDestroy) {
if (shouldDestroy) { this.detach(); }
this.rendered = false;
};
Interpolator__proto__.update = function update () {
if (this.dirty) {
this.dirty = false;
if (this.rendered) {
var value = this.getString();
if (value !== this.value) { this.node.data = this.value = value; }
}
}
};
Interpolator__proto__.valueOf = function valueOf () {
return this.model ? this.model.get() : undefined;
};
return Interpolator;
}(Mustache));
var Input = (function (Element) {
function Input () {
Element.apply(this, arguments);
}
if ( Element ) Input.__proto__ = Element;
var Input__proto__ = Input.prototype = Object.create( Element && Element.prototype );
Input__proto__.constructor = Input;
Input__proto__.render = function render (target, occupants) {
Element.prototype.render.call(this, target, occupants);
this.node.defaultValue = this.node.value;
};
Input__proto__.compare = function compare (value, attrValue) {
var comparator = this.getAttribute('value-comparator');
if (comparator) {
if (isFunction(comparator)) {
return comparator(value, attrValue);
}
if (value && attrValue) {
return value[comparator] == attrValue[comparator];
}
}
return value == attrValue;
};
return Input;
}(Element));
// simple JSON parser, without the restrictions of JSON parse
// (i.e. having to double-quote keys).
//
// If passed a hash of values as the second argument, ${placeholders}
// will be replaced with those values
var specials$1 = {
true: true,
false: false,
null: null,
undefined: undefined
};
var specialsPattern = new RegExp('^(?:' + keys(specials$1).join('|') + ')');
var numberPattern$1 = /^(?:[+-]?)(?:(?:(?:0|[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/;
var placeholderPattern = /\$\{([^\}]+)\}/g;
var placeholderAtStartPattern = /^\$\{([^\}]+)\}/;
var onlyWhitespace$1 = /^\s*$/;
var JsonParser = Parser.extend({
init: function init(str, options) {
this.values = options.values;
this.sp();
},
postProcess: function postProcess(result) {
if (result.length !== 1 || !onlyWhitespace$1.test(this.leftover)) {
return null;
}
return { value: result[0].v };
},
converters: [
function getPlaceholder(parser) {
if (!parser.values) { return null; }
var placeholder = parser.matchPattern(placeholderAtStartPattern);
if (placeholder && hasOwn(parser.values, placeholder)) {
return { v: parser.values[placeholder] };
}
},
function getSpecial(parser) {
var special = parser.matchPattern(specialsPattern);
if (special) { return { v: specials$1[special] }; }
},
function getNumber(parser) {
var number = parser.matchPattern(numberPattern$1);
if (number) { return { v: +number }; }
},
function getString(parser) {
var stringLiteral = readStringLiteral(parser);
var values = parser.values;
if (stringLiteral && values) {
return {
v: stringLiteral.v.replace(placeholderPattern, function (match, $1) { return $1 in values ? values[$1] : $1; }
)
};
}
return stringLiteral;
},
function getObject(parser) {
if (!parser.matchString('{')) { return null; }
var result = {};
parser.sp();
if (parser.matchString('}')) {
return { v: result };
}
var pair;
while ((pair = getKeyValuePair(parser))) {
result[pair.key] = pair.value;
parser.sp();
if (parser.matchString('}')) {
return { v: result };
}
if (!parser.matchString(',')) {
return null;
}
}
return null;
},
function getArray(parser) {
if (!parser.matchString('[')) { return null; }
var result = [];
parser.sp();
if (parser.matchString(']')) {
return { v: result };
}
var valueToken;
while ((valueToken = parser.read())) {
result.push(valueToken.v);
parser.sp();
if (parser.matchString(']')) {
return { v: result };
}
if (!parser.matchString(',')) {
return null;
}
parser.sp();
}
return null;
}
]
});
function getKeyValuePair(parser) {
parser.sp();
var key = readKey(parser);
if (!key) { return null; }
var pair = { key: key };
parser.sp();
if (!parser.matchString(':')) {
return null;
}
parser.sp();
var valueToken = parser.read();
if (!valueToken) { return null; }
pair.value = valueToken.v;
return pair;
}
function parseJSON(str, values) {
var parser = new JsonParser(str, { values: values });
return parser.result;
}
var Mapping = (function (Item) {
function Mapping(options) {
Item.call(this, options);
this.name = options.template.n;
this.owner = options.owner || options.up.owner || options.element || findElement(options.up);
this.element =
options.element || (this.owner.attributeByName ? this.owner : findElement(options.up));
this.up = this.element.up; // shared
this.ractive = this.up.ractive;
this.element.attributeByName[this.name] = this;
this.value = options.template.f;
}
if ( Item ) Mapping.__proto__ = Item;
var Mapping__proto__ = Mapping.prototype = Object.create( Item && Item.prototype );
Mapping__proto__.constructor = Mapping;
Mapping__proto__.bind = function bind () {
var template = this.template.f;
var viewmodel = this.element.instance.viewmodel;
if (template === 0) {
// empty attributes are `true`
viewmodel.joinKey(this.name).set(true);
} else if (isString(template)) {
var parsed = parseJSON(template);
viewmodel.joinKey(this.name).set(parsed ? parsed.value : template);
} else if (isArray(template)) {
createMapping(this, true);
}
};
Mapping__proto__.rebound = function rebound (update) {
if (this.boundFragment) { this.boundFragment.rebound(update); }
if (this.link) {
this.model = resolve(this.up, this.template.f[0]);
var model = this.element.instance.viewmodel.joinAll(splitKeypath(this.name));
model.link(this.model, this.name, { mapping: true });
}
};
Mapping__proto__.render = function render () {};
Mapping__proto__.unbind = function unbind (view) {
if (this.model) { this.model.unregister(this); }
if (this.boundFragment) { this.boundFragment.unbind(view); }
if (this.element.bound) {
if (this.link.target === this.model) { this.link.owner.unlink(); }
}
};
Mapping__proto__.unrender = function unrender () {};
Mapping__proto__.update = function update () {
if (this.dirty) {
this.dirty = false;
if (this.boundFragment) { this.boundFragment.update(); }
}
};
return Mapping;
}(Item));
function createMapping(item) {
var template = item.template.f;
var viewmodel = item.element.instance.viewmodel;
var childData = viewmodel.value;
if (template.length === 1 && template[0].t === INTERPOLATOR) {
var model = resolve(item.up, template[0]);
var val = model.get(false);
// if the interpolator is not static
if (!template[0].s) {
item.model = model;
item.link = viewmodel.createLink(item.name, model, template[0].r, {
mapping: true
});
// initialize parent side of the mapping from child data
if (val === undefined && !model.isReadonly && item.name in childData) {
model.set(childData[item.name]);
}
} else if (!isObjectType(val) || template[0].x) {
// copy non-object, non-computed vals through
viewmodel.joinKey(splitKeypath(item.name)).set(val);
} else {
// warn about trying to copy an object
warnIfDebug(("Cannot copy non-computed object value from static mapping '" + (item.name) + "'"));
}
// if the item isn't going to manage the model, give it a change to tear down if it's computed
if (model !== item.model) { model.unregister(); }
} else {
item.boundFragment = new Fragment({
owner: item,
template: template
}).bind();
item.model = viewmodel.joinKey(splitKeypath(item.name));
item.model.set(item.boundFragment.valueOf());
// item is a *bit* of a hack
item.boundFragment.bubble = function () {
Fragment.prototype.bubble.call(item.boundFragment);
// defer this to avoid mucking around model deps if there happens to be an expression involved
runloop.scheduleTask(function () {
item.boundFragment.update();
item.model.set(item.boundFragment.valueOf());
});
};
}
}
var Option = (function (Element) {
function Option(options) {
var template = options.template;
if (!template.a) { template.a = {}; }
// If the value attribute is missing, use the element's content,
// as long as it isn't disabled
if (template.a.value === undefined && !('disabled' in template.a)) {
template.a.value = template.f || '';
}
Element.call(this, options);
this.select = findElement(this.parent || this.up, false, 'select');
}
if ( Element ) Option.__proto__ = Element;
var Option__proto__ = Option.prototype = Object.create( Element && Element.prototype );
Option__proto__.constructor = Option;
Option__proto__.bind = function bind () {
if (!this.select) {
Element.prototype.bind.call(this);
return;
}
// If the select has a value, it overrides the `selected` attribute on
// this option - so we delete the attribute
var selectedAttribute = this.attributeByName.selected;
if (selectedAttribute && this.select.getAttribute('value') !== undefined) {
var index = this.attributes.indexOf(selectedAttribute);
this.attributes.splice(index, 1);
delete this.attributeByName.selected;
}
Element.prototype.bind.call(this);
this.select.options.push(this);
};
Option__proto__.bubble = function bubble () {
// if we're using content as value, may need to update here
var value = this.getAttribute('value');
if (this.node && this.node.value !== value) {
this.node._ractive.value = value;
}
Element.prototype.bubble.call(this);
};
Option__proto__.getAttribute = function getAttribute (name) {
var attribute = this.attributeByName[name];
return attribute
? attribute.getValue()
: name === 'value' && this.fragment
? this.fragment.valueOf()
: undefined;
};
Option__proto__.isSelected = function isSelected () {
var this$1 = this;
var optionValue = this.getAttribute('value');
if (optionValue === undefined || !this.select) {
return false;
}
var selectValue = this.select.getAttribute('value');
if (this.select.compare(selectValue, optionValue)) {
return true;
}
if (this.select.getAttribute('multiple') && isArray(selectValue)) {
var i = selectValue.length;
while (i--) {
if (this$1.select.compare(selectValue[i], optionValue)) {
return true;
}
}
}
};
Option__proto__.render = function render (target, occupants) {
Element.prototype.render.call(this, target, occupants);
if (!this.attributeByName.value) {
this.node._ractive.value = this.getAttribute('value');
}
};
Option__proto__.unbind = function unbind (view) {
Element.prototype.unbind.call(this, view);
if (this.select) {
removeFromArray(this.select.options, this);
}
};
return Option;
}(Element));
function getPartialTemplate(ractive, name, up) {
// If the partial in instance or view heirarchy instances, great
var partial = getPartialFromRegistry(ractive, name, up || {});
if (partial) { return partial; }
// Does it exist on the page as a script tag?
partial = parser.fromId(name, { noThrow: true });
if (partial) {
// parse and register to this ractive instance
var parsed = parser.parseFor(partial, ractive);
// register extra partials on the ractive instance if they don't already exist
if (parsed.p) { fillGaps(ractive.partials, parsed.p); }
// register (and return main partial if there are others in the template)
return (ractive.partials[name] = parsed.t);
}
}
function getPartialFromRegistry(ractive, name, up) {
// if there was an instance up-hierarchy, cool
var partial = findParentPartial(name, up.owner);
if (partial) { return partial; }
// find first instance in the ractive or view hierarchy that has this partial
var instance = findInstance('partials', ractive, name);
if (!instance) {
return;
}
partial = instance.partials[name];
// partial is a function?
var fn;
if (isFunction(partial)) {
fn = partial;
// super partial
if (fn.styleSet) { return fn; }
fn = partial.bind(instance);
fn.isOwner = hasOwn(instance.partials, name);
partial = fn.call(ractive, parser);
}
if (!partial && partial !== '') {
warnIfDebug(noRegistryFunctionReturn, name, 'partial', 'partial', {
ractive: ractive
});
return;
}
// If this was added manually to the registry,
// but hasn't been parsed, parse it now
if (!parser.isParsed(partial)) {
// use the parseOptions of the ractive instance on which it was found
var parsed = parser.parseFor(partial, instance);
// Partials cannot contain nested partials!
// TODO add a test for this
if (parsed.p) {
warnIfDebug('Partials ({{>%s}}) cannot contain nested inline partials', name, { ractive: ractive });
}
// if fn, use instance to store result, otherwise needs to go
// in the correct point in prototype chain on instance or constructor
var target = fn ? instance : findOwner(instance, name);
// may be a template with partials, which need to be registered and main template extracted
target.partials[name] = partial = parsed.t;
}
// store for reset
if (fn) { partial._fn = fn; }
return partial.v ? partial.t : partial;
}
function findOwner(ractive, key) {
return hasOwn(ractive.partials, key) ? ractive : findConstructor(ractive.constructor, key);
}
function findConstructor(constructor, key) {
if (!constructor) {
return;
}
return hasOwn(constructor.partials, key) ? constructor : findConstructor(constructor.Parent, key);
}
function findParentPartial(name, parent) {
if (parent) {
if (
parent.template &&
parent.template.p &&
!isArray(parent.template.p) &&
hasOwn(parent.template.p, name)
) {
return parent.template.p[name];
} else if (parent.up && parent.up.owner) {
return findParentPartial(name, parent.up.owner);
}
}
}
function Partial(options) {
MustacheContainer.call(this, options);
var tpl = options.template;
// yielder is a special form of partial that will later require special handling
if (tpl.t === YIELDER) {
this.yielder = 1;
} else if (tpl.t === ELEMENT) {
// this is a macro partial, complete with macro constructor
// leaving this as an element will confuse up-template searches
this.type = PARTIAL;
this.macro = options.macro;
}
}
var proto$6 = (Partial.prototype = create(MustacheContainer.prototype));
assign(proto$6, {
constructor: Partial,
bind: function bind() {
var template = this.template;
if (this.yielder) {
// the container is the instance that owns this node
this.container = this.up.ractive;
this.component = this.container.component;
this.containerFragment = this.up;
// normal component
if (this.component) {
// yields skip the owning instance and go straight to the surrounding context
this.up = this.component.up;
// {{yield}} is equivalent to {{yield content}}
if (!template.r && !template.x && !template.rx) { this.refName = 'content'; }
} else {
// plain-ish instance that may be attached to a parent later
this.fragment = new Fragment({
owner: this,
template: []
});
this.fragment.bind();
return;
}
}
// this is a macro/super partial
if (this.macro) {
this.fn = this.macro;
} else {
// this is a plain partial or yielder
if (!this.refName) { this.refName = template.r; }
// if the refName exists as a partial, this is a plain old partial reference where no model binding will happen
if (this.refName) {
partialFromValue(this, this.refName);
}
// this is a dynamic/inline partial
if (!this.partial && !this.fn) {
MustacheContainer.prototype.bind.call(this);
if (this.model) { partialFromValue(this, this.model.get()); }
}
}
if (!this.partial && !this.fn) {
warnOnceIfDebug(("Could not find template for partial '" + (this.name) + "'"));
}
createFragment(this, this.partial || []);
// macro/super partial
if (this.fn) { initMacro(this); }
this.fragment.bind();
},
bubble: function bubble() {
if (!this.dirty) {
this.dirty = true;
if (this.yielder) {
this.containerFragment.bubble();
} else {
this.up.bubble();
}
}
},
findNextNode: function findNextNode() {
return (this.containerFragment || this.up).findNextNode(this);
},
handleChange: function handleChange() {
this.dirtyTemplate = true;
this.externalChange = true;
this.bubble();
},
rebound: function rebound(update) {
var this$1 = this;
var aliases = this.fragment && this.fragment.aliases;
if (aliases) {
for (var k in aliases) {
if (aliases[k].rebound) { aliases[k].rebound(update); }
else {
aliases[k].unreference();
aliases[k] = 0;
}
}
if (this.template.z) {
resolveAliases(this.template.z, this.containerFragment || this.up, aliases);
}
}
if (this._attrs) {
keys(this._attrs).forEach(function (k) { return this$1._attrs[k].rebound(update); });
}
MustacheContainer.prototype.rebound.call(this, update);
},
refreshAttrs: function refreshAttrs() {
var this$1 = this;
keys(this._attrs).forEach(function (k) {
this$1.handle.attributes[k] = !this$1._attrs[k].items.length || this$1._attrs[k].valueOf();
});
},
resetTemplate: function resetTemplate() {
var this$1 = this;
if (this.fn && this.proxy) {
if (this.externalChange) {
if (isFunction(this.proxy.teardown)) { this.proxy.teardown(); }
this.fn = this.proxy = null;
} else {
this.partial = this.fnTemplate;
return true;
}
}
var partial = this.partial;
this.partial = null;
if (this.refName) {
this.partial = getPartialTemplate(this.ractive, this.refName, this.up);
}
if (!this.partial && this.model) {
partialFromValue(this, this.model.get());
}
if (!this.fn && partial === this.partial) { return false; }
this.unbindAttrs();
if (this.fn) {
initMacro(this);
if (isFunction(this.proxy.render)) { runloop.scheduleTask(function () { return this$1.proxy.render(); }); }
} else if (!this.partial) {
warnOnceIfDebug(("Could not find template for partial '" + (this.name) + "'"));
}
return true;
},
render: function render(target, occupants) {
if (this.fn && this.fn._cssDef && !this.fn._cssDef.applied) { applyCSS(); }
this.fragment.render(target, occupants);
if (this.proxy && isFunction(this.proxy.render)) { this.proxy.render(); }
},
unbind: function unbind(view) {
this.fragment.unbind(view);
this.fragment.aliases = null;
this.unbindAttrs(view);
MustacheContainer.prototype.unbind.call(this, view);
},
unbindAttrs: function unbindAttrs(view) {
var this$1 = this;
if (this._attrs) {
keys(this._attrs).forEach(function (k) {
this$1._attrs[k].unbind(view);
});
}
},
unrender: function unrender(shouldDestroy) {
if (this.proxy && isFunction(this.proxy.teardown)) { this.proxy.teardown(); }
this.fragment.unrender(shouldDestroy);
},
update: function update() {
var this$1 = this;
var proxy = this.proxy;
this.updating = 1;
if (this.dirtyAttrs) {
this.dirtyAttrs = false;
keys(this._attrs).forEach(function (k) { return this$1._attrs[k].update(); });
this.refreshAttrs();
if (isFunction(proxy.update)) { proxy.update(this.handle.attributes); }
}
if (this.dirtyTemplate) {
this.dirtyTemplate = false;
this.resetTemplate() && this.fragment.resetTemplate(this.partial || []);
}
if (this.dirty) {
this.dirty = false;
if (proxy && isFunction(proxy.invalidate)) { proxy.invalidate(); }
this.fragment.update();
}
this.externalChange = false;
this.updating = 0;
}
});
function createFragment(self, partial) {
self.partial = partial;
contextifyTemplate(self);
var options = {
owner: self,
template: self.partial
};
if (self.yielder) { options.ractive = self.container.parent; }
if (self.fn) { options.cssIds = self.fn._cssIds; }
var fragment = (self.fragment = new Fragment(options));
// partials may have aliases that need to be in place before binding
if (self.template.z) {
fragment.aliases = resolveAliases(self.template.z, self.containerFragment || self.up);
}
}
function contextifyTemplate(self) {
if (self.template.c) {
self.partial = [{ t: SECTION, n: SECTION_WITH, f: self.partial }];
assign(self.partial[0], self.template.c);
if (self.yielder) { self.partial[0].y = self; }
}
}
function partialFromValue(self, value, okToParse) {
var tpl = value;
if (isArray(tpl)) {
self.partial = tpl;
} else if (tpl && isObjectType(tpl)) {
if (isArray(tpl.t)) { self.partial = tpl.t; }
else if (isString(tpl.template))
{ self.partial = parsePartial(tpl.template, tpl.template, self.ractive).t; }
} else if (isFunction(tpl) && tpl.styleSet) {
self.fn = tpl;
if (self.fragment) { self.fragment.cssIds = tpl._cssIds; }
} else if (tpl != null) {
tpl = getPartialTemplate(self.ractive, '' + tpl, self.containerFragment || self.up);
if (tpl) {
self.name = value;
if (tpl.styleSet) {
self.fn = tpl;
if (self.fragment) { self.fragment.cssIds = tpl._cssIds; }
} else { self.partial = tpl; }
} else if (okToParse) {
self.partial = parsePartial('' + value, '' + value, self.ractive).t;
} else {
self.name = value;
}
}
return self.partial;
}
function setTemplate(template) {
partialFromValue(this, template, true);
if (!this.initing) {
this.dirtyTemplate = true;
this.fnTemplate = this.partial;
if (this.updating) {
this.bubble();
runloop.promise();
} else {
var promise = runloop.start();
this.bubble();
runloop.end();
return promise;
}
}
}
function aliasLocal(ref, name) {
var aliases = this.fragment.aliases || (this.fragment.aliases = {});
if (!name) {
aliases[ref] = this._data;
} else {
aliases[name] = this._data.joinAll(splitKeypath(ref));
}
}
var extras = 'extra-attributes';
function initMacro(self) {
var fn = self.fn;
var fragment = self.fragment;
// defensively copy the template in case it changes
var template = (self.template = assign({}, self.template));
var handle = (self.handle = fragment.getContext({
proxy: self,
aliasLocal: aliasLocal,
name: self.template.e || self.name,
attributes: {},
setTemplate: setTemplate.bind(self),
template: template,
macro: fn
}));
if (!template.p) { template.p = {}; }
template.p = handle.partials = assign({}, template.p);
if (!hasOwn(template.p, 'content')) { template.p.content = template.f || []; }
if (isArray(fn.attributes)) {
self._attrs = {};
var invalidate = function() {
this.dirty = true;
self.dirtyAttrs = true;
self.bubble();
};
if (isArray(template.m)) {
var attrs = template.m;
template.p[extras] = template.m = attrs.filter(function (a) { return !~fn.attributes.indexOf(a.n); });
attrs
.filter(function (a) { return ~fn.attributes.indexOf(a.n); })
.forEach(function (a) {
var fragment = new Fragment({
template: a.f,
owner: self
});
fragment.bubble = invalidate;
fragment.findFirstNode = noop;
self._attrs[a.n] = fragment;
});
} else {
template.p[extras] = [];
}
} else {
template.p[extras] = template.m;
}
if (self._attrs) {
keys(self._attrs).forEach(function (k) {
self._attrs[k].bind();
});
self.refreshAttrs();
}
self.initing = 1;
self.proxy = fn.call(self.ractive, handle, handle.attributes) || {};
if (!self.partial) { self.partial = []; }
self.fnTemplate = self.partial;
self.initing = 0;
contextifyTemplate(self);
fragment.resetTemplate(self.partial);
}
function parsePartial(name, partial, ractive) {
var parsed;
try {
parsed = parser.parse(partial, parser.getParseOptions(ractive));
} catch (e) {
warnIfDebug(("Could not parse partial from expression '" + name + "'\n" + (e.message)));
}
return parsed || { t: [] };
}
var KeyModel = function KeyModel(value, context, instance) {
this.value = this.key = value;
this.context = context;
this.isReadonly = this.isKey = true;
this.deps = [];
this.links = [];
this.children = [];
this.instance = instance;
};
var KeyModel__proto__ = KeyModel.prototype;
KeyModel__proto__.applyValue = function applyValue (value) {
if (value !== this.value) {
this.value = this.key = value;
this.deps.forEach(handleChange);
this.links.forEach(handleChange);
this.children.forEach(function (c) {
c.applyValue(c.context.getKeypath(c.instance));
});
}
};
KeyModel__proto__.destroyed = function destroyed () {
if (this.upstream) { this.upstream.unregisterChild(this); }
};
KeyModel__proto__.get = function get (shouldCapture) {
if (shouldCapture) { capture(this); }
return unescapeKey(this.value);
};
KeyModel__proto__.getKeypath = function getKeypath () {
return unescapeKey(this.value);
};
KeyModel__proto__.has = function has () {
return false;
};
KeyModel__proto__.rebind = function rebind (next, previous) {
var this$1 = this;
var i = this.deps.length;
while (i--) { this$1.deps[i].rebind(next, previous, false); }
i = this.links.length;
while (i--) { this$1.links[i].relinking(next, false); }
};
KeyModel__proto__.register = function register (dependant) {
this.deps.push(dependant);
};
KeyModel__proto__.registerChild = function registerChild (child) {
addToArray(this.children, child);
child.upstream = this;
};
KeyModel__proto__.registerLink = function registerLink (link) {
addToArray(this.links, link);
};
KeyModel__proto__.unregister = function unregister (dependant) {
removeFromArray(this.deps, dependant);
};
KeyModel__proto__.unregisterChild = function unregisterChild (child) {
removeFromArray(this.children, child);
};
KeyModel__proto__.unregisterLink = function unregisterLink (link) {
removeFromArray(this.links, link);
};
KeyModel.prototype.reference = noop;
KeyModel.prototype.unreference = noop;
var keypathString = /^"(\\"|[^"])+"$/;
var RepeatedFragment = function RepeatedFragment(options) {
this.parent = options.owner.up;
// bit of a hack, so reference resolution works without another
// layer of indirection
this.up = this;
this.owner = options.owner;
this.ractive = this.parent.ractive;
this.delegate =
this.ractive.delegate !== false && (this.parent.delegate || findDelegate(this.parent));
// delegation disabled by directive
if (this.delegate && this.delegate.delegate === false) { this.delegate = false; }
// let the element know it's a delegate handler
if (this.delegate) { this.delegate.delegate = this.delegate; }
// encapsulated styles should be inherited until they get applied by an element
this.cssIds = 'cssIds' in options ? options.cssIds : this.parent ? this.parent.cssIds : null;
this.context = null;
this.rendered = false;
this.iterations = [];
this.template = options.template;
this.indexRef = options.indexRef;
this.keyRef = options.keyRef;
this.pendingNewIndices = null;
this.previousIterations = null;
// track array versus object so updates of type rest
this.isArray = false;
};
var RepeatedFragment__proto__ = RepeatedFragment.prototype;
RepeatedFragment__proto__.bind = function bind (context) {
var this$1 = this;
this.context = context;
this.bound = true;
var value = context.get();
var aliases = (this.aliases = this.owner.template.z && this.owner.template.z.slice());
var shuffler = aliases && aliases.find(function (a) { return a.n === 'shuffle'; });
if (shuffler && shuffler.x && shuffler.x.x) {
if (shuffler.x.x.s === 'true') { this.shuffler = true; }
else if (keypathString.test(shuffler.x.x.s))
{ this.shuffler = splitKeypath(shuffler.x.x.s.slice(1, -1)); }
}
if (this.shuffler) { this.values = shuffleValues(this, this.shuffler); }
if (this.source) { this.source.model.unbind(this.source); }
var source = context.isComputed && aliases && aliases.find(function (a) { return a.n === 'source'; });
if (source && source.x && source.x.r) {
var model = resolve(this, source.x);
this.source = {
handleChange: function handleChange() {},
rebind: function rebind(next) {
this.model.unregister(this);
this.model = next;
next.register(this);
}
};
this.source.model = model;
model.register(this.source);
}
// {{#each array}}...
if ((this.isArray = isArray(value))) {
// we can't use map, because of sparse arrays
this.iterations = [];
var max = (this.length = value.length);
for (var i = 0; i < max; i += 1) {
this$1.iterations[i] = this$1.createIteration(i, i);
}
} else if (isObject(value)) {
// {{#each object}}...
this.isArray = false;
// TODO this is a dreadful hack. There must be a neater way
if (this.indexRef) {
var refs = this.indexRef.split(',');
this.keyRef = refs[0];
this.indexRef = refs[1];
}
var ks = keys(value);
this.length = ks.length;
this.iterations = ks.map(function (key, index) {
return this$1.createIteration(key, index);
});
}
return this;
};
RepeatedFragment__proto__.bubble = function bubble (index) {
if (!this.bubbled) { this.bubbled = []; }
this.bubbled.push(index);
if (!this.rebounding) { this.owner.bubble(); }
};
RepeatedFragment__proto__.createIteration = function createIteration (key, index) {
var fragment = new Fragment({
owner: this,
template: this.template
});
fragment.isIteration = true;
fragment.delegate = this.delegate;
if (this.aliases) { fragment.aliases = {}; }
swizzleFragment(this, fragment, key, index);
return fragment.bind(fragment.context);
};
RepeatedFragment__proto__.destroyed = function destroyed () {
var this$1 = this;
var len = this.iterations.length;
for (var i = 0; i < len; i++) { this$1.iterations[i].destroyed(); }
if (this.pathModel) { this.pathModel.destroyed(); }
if (this.rootModel) { this.rootModel.destroyed(); }
};
RepeatedFragment__proto__.detach = function detach () {
var docFrag = createDocumentFragment();
this.iterations.forEach(function (fragment) { return docFrag.appendChild(fragment.detach()); });
return docFrag;
};
RepeatedFragment__proto__.find = function find (selector, options) {
return findMap(this.iterations, function (i) { return i.find(selector, options); });
};
RepeatedFragment__proto__.findAll = function findAll (selector, options) {
return this.iterations.forEach(function (i) { return i.findAll(selector, options); });
};
RepeatedFragment__proto__.findAllComponents = function findAllComponents (name, options) {
return this.iterations.forEach(function (i) { return i.findAllComponents(name, options); });
};
RepeatedFragment__proto__.findComponent = function findComponent (name, options) {
return findMap(this.iterations, function (i) { return i.findComponent(name, options); });
};
RepeatedFragment__proto__.findContext = function findContext () {
return this.context;
};
RepeatedFragment__proto__.findNextNode = function findNextNode (iteration) {
var this$1 = this;
if (iteration.index < this.iterations.length - 1) {
for (var i = iteration.index + 1; i < this.iterations.length; i++) {
var node = this$1.iterations[i].firstNode(true);
if (node) { return node; }
}
}
return this.owner.findNextNode();
};
RepeatedFragment__proto__.firstNode = function firstNode (skipParent) {
return this.iterations[0] ? this.iterations[0].firstNode(skipParent) : null;
};
RepeatedFragment__proto__.getLast = function getLast () {
return this.lastModel || (this.lastModel = new KeyModel(this.length - 1));
};
RepeatedFragment__proto__.rebind = function rebind (next) {
var this$1 = this;
this.context = next;
if (this.source) { return; }
this.iterations.forEach(function (fragment) {
swizzleFragment(this$1, fragment, fragment.key, fragment.index);
});
};
RepeatedFragment__proto__.rebound = function rebound (update$$1) {
var this$1 = this;
this.context = this.owner.model;
this.iterations.forEach(function (f, i) {
f.context = contextFor(this$1, f, i);
f.rebound(update$$1);
});
};
RepeatedFragment__proto__.render = function render (target, occupants) {
var xs = this.iterations;
if (xs) {
var len = xs.length;
for (var i = 0; i < len; i++) {
xs[i].render(target, occupants);
}
}
this.rendered = true;
};
RepeatedFragment__proto__.shuffle = function shuffle (newIndices, merge) {
var this$1 = this;
if (!this.pendingNewIndices) { this.previousIterations = this.iterations.slice(); }
if (!this.pendingNewIndices) { this.pendingNewIndices = []; }
this.pendingNewIndices.push(newIndices);
var iterations = [];
newIndices.forEach(function (newIndex, oldIndex) {
if (newIndex === -1) { return; }
var fragment = this$1.iterations[oldIndex];
iterations[newIndex] = fragment;
if (newIndex !== oldIndex && fragment) {
fragment.dirty = true;
if (merge) { fragment.shouldRebind = 1; }
}
});
this.iterations = iterations;
// if merging, we're in the midst of an update already
if (!merge) { this.bubble(); }
};
RepeatedFragment__proto__.shuffled = function shuffled$1 () {
this.iterations.forEach(shuffled);
};
RepeatedFragment__proto__.toString = function toString (escape) {
return this.iterations ? this.iterations.map(escape ? toEscapedString : toString$1).join('') : '';
};
RepeatedFragment__proto__.unbind = function unbind (view) {
this.bound = false;
if (this.source) { this.source.model.unregister(this.source); }
var iterations = this.pendingNewIndices ? this.previousIterations : this.iterations;
var len = iterations.length;
for (var i = 0; i < len; i++) { iterations[i].unbind(view); }
return this;
};
RepeatedFragment__proto__.unrender = function unrender (shouldDestroy) {
var this$1 = this;
var len = this.iterations.length;
for (var i = 0; i < len; i++) { this$1.iterations[i].unrender(shouldDestroy); }
if (this.pendingNewIndices && this.previousIterations) {
len = this.previousIterations.length;
for (var i$1 = 0; i$1 < len; i$1++) { this$1.previousIterations[i$1].unrender(shouldDestroy); }
}
this.rendered = false;
};
RepeatedFragment__proto__.update = function update () {
var this$1 = this;
if (this.pendingNewIndices) {
this.bubbled.length = 0;
this.updatePostShuffle();
return;
}
if (this.updating) { return; }
this.updating = true;
if (this.shuffler) {
var values = shuffleValues(this, this.shuffler);
this.shuffle(buildNewIndices(this.values, values), true);
this.updatePostShuffle();
} else {
var len = this.iterations.length;
for (var i = 0; i < len; i++) {
var f = this$1.iterations[i];
f && f.idxModel && f.idxModel.applyValue(i);
}
var value = this.context.get();
var wasArray = this.isArray;
var toRemove;
var oldKeys;
var reset = true;
var i$1;
if ((this.isArray = isArray(value))) {
// if there's a source to map back to, make sure everything stays bound correctly
if (this.source) {
this.rebounding = 1;
var source = this.source.model.get();
this.iterations.forEach(function (f, c) {
if (c < value.length && f.lastValue !== value[c] && ~(i$1 = source.indexOf(value[c]))) {
swizzleFragment(this$1, f, c, c);
f.rebound(true);
}
});
this.rebounding = 0;
}
if (wasArray) {
reset = false;
if (this.iterations.length > value.length) {
toRemove = this.iterations.splice(value.length);
}
}
} else if (isObject(value) && !wasArray) {
reset = false;
toRemove = [];
oldKeys = {};
i$1 = this.iterations.length;
while (i$1--) {
var fragment = this$1.iterations[i$1];
if (fragment.key in value) {
oldKeys[fragment.key] = true;
} else {
this$1.iterations.splice(i$1, 1);
toRemove.push(fragment);
}
}
}
var newLength = isArray(value) ? value.length : isObject(value) ? keys(value).length : 0;
this.length = newLength;
this.updateLast();
if (reset) {
toRemove = this.iterations;
this.iterations = [];
}
if (toRemove) {
len = toRemove.length;
for (var i$2 = 0; i$2 < len; i$2++) { toRemove[i$2].unbind().unrender(true); }
}
// update the remaining ones
if (!reset && this.isArray && this.bubbled && this.bubbled.length) {
var bubbled = this.bubbled;
this.bubbled = [];
len = bubbled.length;
for (var i$3 = 0; i$3 < len; i$3++)
{ this$1.iterations[bubbled[i$3]] && this$1.iterations[bubbled[i$3]].update(); }
} else {
len = this.iterations.length;
for (var i$4 = 0; i$4 < len; i$4++) { this$1.iterations[i$4].update(); }
}
// add new iterations
var docFrag;
var fragment$1;
if (newLength > this.iterations.length) {
docFrag = this.rendered ? createDocumentFragment() : null;
i$1 = this.iterations.length;
if (isArray(value)) {
while (i$1 < value.length) {
fragment$1 = this$1.createIteration(i$1, i$1);
this$1.iterations.push(fragment$1);
if (this$1.rendered) { fragment$1.render(docFrag); }
i$1 += 1;
}
} else if (isObject(value)) {
// TODO this is a dreadful hack. There must be a neater way
if (this.indexRef && !this.keyRef) {
var refs = this.indexRef.split(',');
this.keyRef = refs[0];
this.indexRef = refs[1];
}
keys(value).forEach(function (key) {
if (!oldKeys || !(key in oldKeys)) {
fragment$1 = this$1.createIteration(key, i$1);
this$1.iterations.push(fragment$1);
if (this$1.rendered) { fragment$1.render(docFrag); }
i$1 += 1;
}
});
}
if (this.rendered) {
var parentNode = this.parent.findParentNode();
var anchor = this.parent.findNextNode(this.owner);
parentNode.insertBefore(docFrag, anchor);
}
}
}
this.updating = false;
};
RepeatedFragment__proto__.updateLast = function updateLast () {
if (this.lastModel) { this.lastModel.applyValue(this.length - 1); }
};
RepeatedFragment__proto__.updatePostShuffle = function updatePostShuffle () {
var this$1 = this;
var newIndices = this.pendingNewIndices[0];
var parentNode = this.rendered ? this.parent.findParentNode() : null;
var nextNode = parentNode && this.owner.findNextNode();
var docFrag = parentNode ? createDocumentFragment() : null;
// map first shuffle through
this.pendingNewIndices.slice(1).forEach(function (indices) {
newIndices.forEach(function (newIndex, oldIndex) {
newIndices[oldIndex] = indices[newIndex];
});
});
var len = (this.length = this.context.get().length);
var prev = this.previousIterations;
var iters = this.iterations;
var value = this.context.get();
var stash = {};
var idx, dest, pos, next, anchor, rebound;
var map = new Array(newIndices.length);
newIndices.forEach(function (e, i) { return (map[e] = i); });
this.updateLast();
idx = pos = 0;
while (idx < len) {
dest = newIndices[pos];
next = null;
rebound = false;
if (dest === -1) {
// drop it like it's hot
prev[pos].unbind().unrender(true);
prev[pos++] = 0;
} else if (dest > idx) {
// need to stash or pull one up
next = newIndices[pos + 1]; // TODO: maybe a shouldMove function that tracks multiple entries?
if (next <= dest) {
stash[dest] = prev[pos];
prev[pos++] = null;
} else {
next = stash[idx] || prev[map[idx]];
prev[map[idx]] = null;
anchor = prev[nextRendered(pos, newIndices, prev)];
anchor = (anchor && parentNode && anchor.firstNode()) || nextNode;
if (next) {
rebound = this$1.source && next.lastValue !== value[idx];
swizzleFragment(this$1, next, idx, idx);
if (parentNode) { parentNode.insertBefore(next.detach(), anchor); }
} else {
next = iters[idx] = this$1.createIteration(idx, idx);
if (parentNode) {
next.render(docFrag);
parentNode.insertBefore(docFrag, anchor);
}
}
idx++;
}
} else {
// all is well
next = iters[idx];
anchor = prev[nextRendered(pos, newIndices, prev)];
anchor = (anchor && parentNode && anchor.firstNode()) || nextNode;
if (!next) {
next = iters[idx] = this$1.createIteration(idx, idx);
if (parentNode) {
next.render(docFrag);
parentNode.insertBefore(docFrag, anchor);
}
} else if (pos !== idx || stash[idx]) {
rebound = this$1.source && next.lastValue !== value[idx];
swizzleFragment(this$1, next, idx, idx);
if (stash[idx] && parentNode) { parentNode.insertBefore(next.detach(), anchor); }
}
idx++;
prev[pos++] = null;
}
if (next && isObjectType(next)) {
if (next.shouldRebind || rebound) {
next.rebound(rebound);
next.shouldRebind = 0;
}
next.update();
next.shuffled();
}
}
// clean up any stragglers
var plen = prev.length;
for (var i = 0; i < plen; i++) { prev[i] && prev[i].unbind().unrender(true); }
if (this.shuffler) { this.values = shuffleValues(this, this.shuffler); }
this.pendingNewIndices = null;
this.previousIterations = null;
};
RepeatedFragment.prototype.getContext = getContext;
RepeatedFragment.prototype.getKeypath = getKeypath;
// find the topmost delegate
function findDelegate(start) {
var frag = start;
var delegate, el;
out: while (frag) {
// find next element
el = 0;
while (!el && frag) {
if (frag.owner.type === ELEMENT) { el = frag.owner; }
if (frag.owner.ractive && frag.owner.ractive.delegate === false) { break out; }
frag = frag.parent || frag.componentParent;
}
if (el.delegate === false) { break out; }
delegate = el.delegate || el;
// find next repeated fragment
while (frag) {
if (frag.iterations) { break; }
if (frag.owner.ractive && frag.owner.ractive.delegate === false) { break out; }
frag = frag.parent || frag.componentParent;
}
}
return delegate;
}
function nextRendered(start, newIndices, frags) {
var len = newIndices.length;
for (var i = start; i < len; i++) {
if (~newIndices[i] && frags[i] && frags[i].rendered) { return i; }
}
}
function swizzleFragment(section, fragment, key, idx) {
var model = section.context ? contextFor(section, fragment, key) : undefined;
fragment.key = key;
fragment.index = idx;
fragment.context = model;
if (section.source) { fragment.lastValue = model && model.get(); }
if (fragment.idxModel) { fragment.idxModel.applyValue(idx); }
if (fragment.keyModel) { fragment.keyModel.applyValue(key); }
if (fragment.pathModel) {
fragment.pathModel.context = model;
fragment.pathModel.applyValue(model.getKeypath());
}
if (fragment.rootModel) {
fragment.rootModel.context = model;
fragment.rootModel.applyValue(model.getKeypath(fragment.ractive.root));
}
// handle any aliases
var aliases = fragment.aliases;
section.aliases &&
section.aliases.forEach(function (a) {
if (a.x.r === '.') { aliases[a.n] = model; }
else if (a.x.r === '@index') { aliases[a.n] = fragment.getIndex(); }
else if (a.x.r === '@key') { aliases[a.n] = fragment.getKey(); }
else if (a.x.r === '@keypath') { aliases[a.n] = fragment.getKeypath(); }
else if (a.x.r === '@rootpath') { aliases[a.n] = fragment.getKeypath(true); }
});
}
function shuffleValues(section, shuffler) {
if (shuffler === true) {
return section.context.get().slice();
} else {
return section.context.get().map(function (v) { return shuffler.reduce(function (a, c) { return a && a[c]; }, v); });
}
}
function contextFor(section, fragment, key) {
if (section.source) {
var idx;
var source = section.source.model.get();
if (source.indexOf && ~(idx = source.indexOf(section.context.joinKey(key).get())))
{ return section.source.model.joinKey(idx); }
}
return section.context.joinKey(key);
}
function isEmpty(value) {
return (
!value ||
(isArray(value) && value.length === 0) ||
(isObject(value) && keys(value).length === 0)
);
}
function getType(value, hasIndexRef) {
if (hasIndexRef || isArray(value)) { return SECTION_EACH; }
if (isObjectLike(value)) { return SECTION_IF_WITH; }
if (value === undefined) { return null; }
return SECTION_IF;
}
var Section = (function (MustacheContainer) {
function Section(options) {
MustacheContainer.call(this, options);
this.sectionType = options.template.n || null;
this.templateSectionType = this.sectionType;
this.subordinate = options.template.l === 1;
this.fragment = null;
}
if ( MustacheContainer ) Section.__proto__ = MustacheContainer;
var Section__proto__ = Section.prototype = Object.create( MustacheContainer && MustacheContainer.prototype );
Section__proto__.constructor = Section;
Section__proto__.bind = function bind () {
MustacheContainer.prototype.bind.call(this);
if (this.subordinate) {
this.sibling = this.up.items[this.up.items.indexOf(this) - 1];
this.sibling.nextSibling = this;
}
// if we managed to bind, we need to create children
if (this.model) {
this.dirty = true;
this.update();
} else if (
this.sectionType &&
this.sectionType === SECTION_UNLESS &&
(!this.sibling || !this.sibling.isTruthy())
) {
this.fragment = new Fragment({
owner: this,
template: this.template.f
}).bind();
}
};
Section__proto__.bubble = function bubble () {
if (!this.dirty && this.yield) {
this.dirty = true;
this.containerFragment.bubble();
} else { MustacheContainer.prototype.bubble.call(this); }
};
Section__proto__.detach = function detach () {
var frag = this.fragment || this.detached;
return frag ? frag.detach() : MustacheContainer.prototype.detach.call(this);
};
Section__proto__.isTruthy = function isTruthy () {
if (this.subordinate && this.sibling.isTruthy()) { return true; }
var value = !this.model ? undefined : this.model.isRoot ? this.model.value : this.model.get();
return !!value && (this.templateSectionType === SECTION_IF_WITH || !isEmpty(value));
};
Section__proto__.rebind = function rebind (next, previous, safe) {
if (MustacheContainer.prototype.rebind.call(this, next, previous, safe)) {
if (this.fragment && this.sectionType !== SECTION_IF && this.sectionType !== SECTION_UNLESS) {
this.fragment.rebind(next);
}
}
};
Section__proto__.rebound = function rebound (update) {
if (this.model) {
if (this.model.rebound) { this.model.rebound(update); }
else {
MustacheContainer.prototype.unbind.call(this);
MustacheContainer.prototype.bind.call(this);
if (
this.sectionType === SECTION_WITH ||
this.sectionType === SECTION_IF_WITH ||
this.sectionType === SECTION_EACH
) {
if (this.fragment) { this.fragment.rebind(this.model); }
}
if (update) { this.bubble(); }
}
}
if (this.fragment) { this.fragment.rebound(update); }
};
Section__proto__.render = function render (target, occupants) {
this.rendered = true;
if (this.fragment) { this.fragment.render(target, occupants); }
};
Section__proto__.shuffle = function shuffle (newIndices) {
if (this.fragment && this.sectionType === SECTION_EACH) {
this.fragment.shuffle(newIndices);
}
};
Section__proto__.unbind = function unbind (view) {
MustacheContainer.prototype.unbind.call(this, view);
if (this.fragment) { this.fragment.unbind(view); }
};
Section__proto__.unrender = function unrender (shouldDestroy) {
if (this.rendered && this.fragment) { this.fragment.unrender(shouldDestroy); }
this.rendered = false;
};
Section__proto__.update = function update () {
var this$1 = this;
if (!this.dirty) { return; }
if (this.fragment && this.sectionType !== SECTION_IF && this.sectionType !== SECTION_UNLESS) {
this.fragment.context = this.model;
}
if (!this.model && this.sectionType !== SECTION_UNLESS) { return; }
this.dirty = false;
var value = !this.model ? undefined : this.model.isRoot ? this.model.value : this.model.get();
var siblingFalsey = !this.subordinate || !this.sibling.isTruthy();
var lastType = this.sectionType;
if (this.yield && this.yield !== value) {
this.up = this.containerFragment;
this.container = null;
this.yield = null;
if (this.rendered) { this.fragment.unbind().unrender(true); }
this.fragment = null;
} else if (this.rendered && !this.yield && value instanceof Context) {
if (this.rendered) { this.fragment.unbind().unrender(true); }
this.fragment = null;
}
// watch for switching section types
if (this.sectionType === null || this.templateSectionType === null)
{ this.sectionType = getType(value, this.template.i); }
if (lastType && lastType !== this.sectionType && this.fragment) {
if (this.rendered) {
this.fragment.unbind().unrender(true);
}
this.fragment = null;
}
var newFragment;
var fragmentShouldExist =
this.sectionType === SECTION_EACH || // each always gets a fragment, which may have no iterations
this.sectionType === SECTION_WITH || // with (partial context) always gets a fragment
(siblingFalsey && (this.sectionType === SECTION_UNLESS ? !this.isTruthy() : this.isTruthy())); // if, unless, and if-with depend on siblings and the condition
if (fragmentShouldExist) {
if (!this.fragment) { this.fragment = this.detached; }
if (this.fragment) {
// check for detached fragment
if (this.detached) {
attach(this, this.fragment);
this.detached = false;
this.rendered = true;
}
if (!this.fragment.bound) { this.fragment.bind(this.model); }
this.fragment.update();
} else {
if (this.sectionType === SECTION_EACH) {
newFragment = new RepeatedFragment({
owner: this,
template: this.template.f,
indexRef: this.template.i
}).bind(this.model);
} else {
// only with and if-with provide context - if and unless do not
var context =
this.sectionType !== SECTION_IF && this.sectionType !== SECTION_UNLESS
? this.model
: null;
if (value instanceof Context) {
this.yield = value;
this.containerFragment = this.up;
this.up = value.fragment;
this.container = value.ractive;
context = undefined;
}
newFragment = new Fragment({
owner: this,
template: this.template.f
}).bind(context);
}
}
} else {
if (this.fragment && this.rendered) {
if (keep !== true) {
this.fragment.unbind().unrender(true);
} else {
this.unrender(false);
this.detached = this.fragment;
runloop.promise().then(function () {
if (this$1.detached) { this$1.detach(); }
});
}
} else if (this.fragment) {
this.fragment.unbind();
}
this.fragment = null;
}
if (newFragment) {
if (this.rendered) {
attach(this, newFragment);
}
this.fragment = newFragment;
}
if (this.nextSibling) {
this.nextSibling.dirty = true;
this.nextSibling.update();
}
};
return Section;
}(MustacheContainer));
function attach(section, fragment) {
var anchor = (section.containerFragment || section.up).findNextNode(section);
if (anchor) {
var docFrag = createDocumentFragment();
fragment.render(docFrag);
anchor.parentNode.insertBefore(docFrag, anchor);
} else {
fragment.render(section.up.findParentNode());
}
}
var Select = (function (Element) {
function Select(options) {
Element.call(this, options);
this.options = [];
}
if ( Element ) Select.__proto__ = Element;
var Select__proto__ = Select.prototype = Object.create( Element && Element.prototype );
Select__proto__.constructor = Select;
Select__proto__.foundNode = function foundNode (node) {
if (this.binding) {
var selectedOptions = getSelectedOptions(node);
if (selectedOptions.length > 0) {
this.selectedOptions = selectedOptions;
}
}
};
Select__proto__.render = function render (target, occupants) {
Element.prototype.render.call(this, target, occupants);
this.sync();
var node = this.node;
var i = node.options.length;
while (i--) {
node.options[i].defaultSelected = node.options[i].selected;
}
this.rendered = true;
};
Select__proto__.sync = function sync () {
var this$1 = this;
var selectNode = this.node;
if (!selectNode) { return; }
var options = toArray(selectNode.options);
if (this.selectedOptions) {
options.forEach(function (o) {
if (this$1.selectedOptions.indexOf(o) >= 0) { o.selected = true; }
else { o.selected = false; }
});
this.binding.setFromNode(selectNode);
delete this.selectedOptions;
return;
}
var selectValue = this.getAttribute('value');
var isMultiple = this.getAttribute('multiple');
var array = isMultiple && isArray(selectValue);
// If the <select> has a specified value, that should override
// these options
if (selectValue !== undefined) {
var optionWasSelected;
options.forEach(function (o) {
var optionValue = o._ractive ? o._ractive.value : o.value;
var shouldSelect = isMultiple
? array && this$1.valueContains(selectValue, optionValue)
: this$1.compare(selectValue, optionValue);
if (shouldSelect) {
optionWasSelected = true;
}
o.selected = shouldSelect;
});
if (!optionWasSelected && !isMultiple) {
if (this.binding) {
this.binding.forceUpdate();
}
}
} else if (this.binding && this.binding.forceUpdate) {
// Otherwise the value should be initialised according to which
// <option> element is selected, if twoway binding is in effect
this.binding.forceUpdate();
}
};
Select__proto__.valueContains = function valueContains (selectValue, optionValue) {
var this$1 = this;
var i = selectValue.length;
while (i--) {
if (this$1.compare(optionValue, selectValue[i])) { return true; }
}
};
Select__proto__.compare = function compare (optionValue, selectValue) {
var comparator = this.getAttribute('value-comparator');
if (comparator) {
if (isFunction(comparator)) {
return comparator(selectValue, optionValue);
}
if (selectValue && optionValue) {
return selectValue[comparator] == optionValue[comparator];
}
}
return selectValue == optionValue;
};
Select__proto__.update = function update () {
var dirty = this.dirty;
Element.prototype.update.call(this);
if (dirty) {
this.sync();
}
};
return Select;
}(Element));
var Textarea = (function (Input) {
function Textarea(options) {
var template = options.template;
options.deferContent = true;
Input.call(this, options);
// check for single interpolator binding
if (!this.attributeByName.value) {
if (template.f && isBindable({ template: template })) {
(this.attributes || (this.attributes = [])).push(
createItem({
owner: this,
template: { t: ATTRIBUTE, f: template.f, n: 'value' },
up: this.up
})
);
} else {
this.fragment = new Fragment({
owner: this,
cssIds: null,
template: template.f
});
}
}
}
if ( Input ) Textarea.__proto__ = Input;
var Textarea__proto__ = Textarea.prototype = Object.create( Input && Input.prototype );
Textarea__proto__.constructor = Textarea;
Textarea__proto__.bubble = function bubble () {
var this$1 = this;
if (!this.dirty) {
this.dirty = true;
if (this.rendered && !this.binding && this.fragment) {
runloop.scheduleTask(function () {
this$1.dirty = false;
this$1.node.value = this$1.fragment.toString();
});
}
this.up.bubble(); // default behaviour
}
};
return Textarea;
}(Input));
var Text = (function (Item) {
function Text(options) {
Item.call(this, options);
this.type = TEXT;
}
if ( Item ) Text.__proto__ = Item;
var Text__proto__ = Text.prototype = Object.create( Item && Item.prototype );
Text__proto__.constructor = Text;
Text__proto__.detach = function detach () {
return detachNode(this.node);
};
Text__proto__.firstNode = function firstNode () {
return this.node;
};
Text__proto__.render = function render (target, occupants) {
if (inAttributes()) { return; }
this.rendered = true;
progressiveText(this, target, occupants, this.template);
};
Text__proto__.toString = function toString (escape) {
return escape ? escapeHtml(this.template) : this.template;
};
Text__proto__.unrender = function unrender (shouldDestroy) {
if (this.rendered && shouldDestroy) { this.detach(); }
this.rendered = false;
};
Text__proto__.valueOf = function valueOf () {
return this.template;
};
return Text;
}(Item));
var proto$7 = Text.prototype;
proto$7.bind = proto$7.unbind = proto$7.update = noop;
var visible;
var hidden = 'hidden';
if (doc) {
var prefix$2;
/* istanbul ignore next */
if (hidden in doc) {
prefix$2 = '';
} else {
var i$1 = vendors.length;
while (i$1--) {
var vendor = vendors[i$1];
hidden = vendor + 'Hidden';
if (hidden in doc) {
prefix$2 = vendor;
break;
}
}
}
/* istanbul ignore else */
if (prefix$2 !== undefined) {
doc.addEventListener(prefix$2 + 'visibilitychange', onChange);
onChange();
} else {
// gah, we're in an old browser
if ('onfocusout' in doc) {
doc.addEventListener('focusout', onHide);
doc.addEventListener('focusin', onShow);
} else {
win.addEventListener('pagehide', onHide);
win.addEventListener('blur', onHide);
win.addEventListener('pageshow', onShow);
win.addEventListener('focus', onShow);
}
visible = true; // until proven otherwise. Not ideal but hey
}
}
function onChange() {
visible = !doc[hidden];
}
/* istanbul ignore next */
function onHide() {
visible = false;
}
/* istanbul ignore next */
function onShow() {
visible = true;
}
var prefix;
/* istanbul ignore next */
if (!isClient) {
prefix = null;
} else {
var prefixCache = {};
var testStyle = createElement('div').style;
// technically this also normalizes on hyphenated styles as well
prefix = function(prop) {
if (!prefixCache[prop]) {
var name = hyphenateCamel(prop);
if (testStyle[prop] !== undefined) {
prefixCache[prop] = name;
} else {
/* istanbul ignore next */
// test vendors...
var i = vendors.length;
while (i--) {
var vendor = "-" + (vendors[i]) + "-" + name;
if (testStyle[vendor] !== undefined) {
prefixCache[prop] = vendor;
break;
}
}
}
}
return prefixCache[prop];
};
}
var prefix$1 = prefix;
var vendorPattern = new RegExp('^(?:' + vendors.join('|') + ')([A-Z])');
function hyphenate(str) {
/* istanbul ignore next */
if (!str) { return ''; } // edge case
/* istanbul ignore next */
if (vendorPattern.test(str)) { str = '-' + str; }
return str.replace(/[A-Z]/g, function (match) { return '-' + match.toLowerCase(); });
}
var createTransitions;
if (!isClient) {
createTransitions = null;
} else {
var testStyle$1 = createElement('div').style;
var linear$1 = function (x) { return x; };
var canUseCssTransitions = {};
var cannotUseCssTransitions = {};
// determine some facts about our environment
var TRANSITION$1;
var TRANSITIONEND;
var CSS_TRANSITIONS_ENABLED;
var TRANSITION_DURATION;
var TRANSITION_PROPERTY;
var TRANSITION_TIMING_FUNCTION;
if (testStyle$1.transition !== undefined) {
TRANSITION$1 = 'transition';
TRANSITIONEND = 'transitionend';
CSS_TRANSITIONS_ENABLED = true;
} else if (testStyle$1.webkitTransition !== undefined) {
TRANSITION$1 = 'webkitTransition';
TRANSITIONEND = 'webkitTransitionEnd';
CSS_TRANSITIONS_ENABLED = true;
} else {
CSS_TRANSITIONS_ENABLED = false;
}
if (TRANSITION$1) {
TRANSITION_DURATION = TRANSITION$1 + 'Duration';
TRANSITION_PROPERTY = TRANSITION$1 + 'Property';
TRANSITION_TIMING_FUNCTION = TRANSITION$1 + 'TimingFunction';
}
createTransitions = function(t, to, options, changedProperties, resolve) {
// Wait a beat (otherwise the target styles will be applied immediately)
// TODO use a fastdom-style mechanism?
setTimeout(function () {
var jsTransitionsComplete;
var cssTransitionsComplete;
var cssTimeout; // eslint-disable-line prefer-const
function transitionDone() {
clearTimeout(cssTimeout);
}
function checkComplete() {
if (jsTransitionsComplete && cssTransitionsComplete) {
t.unregisterCompleteHandler(transitionDone);
// will changes to events and fire have an unexpected consequence here?
t.ractive.fire(t.name + ':end', t.node, t.isIntro);
resolve();
}
}
// this is used to keep track of which elements can use CSS to animate
// which properties
var hashPrefix = (t.node.namespaceURI || '') + t.node.tagName;
// need to reset transition properties
var style = t.node.style;
var previous = {
property: style[TRANSITION_PROPERTY],
timing: style[TRANSITION_TIMING_FUNCTION],
duration: style[TRANSITION_DURATION]
};
function transitionEndHandler(event) {
var index = changedProperties.indexOf(event.propertyName);
if (index !== -1) {
changedProperties.splice(index, 1);
}
if (changedProperties.length) {
// still transitioning...
return;
}
clearTimeout(cssTimeout);
cssTransitionsDone();
}
function cssTransitionsDone() {
style[TRANSITION_PROPERTY] = previous.property;
style[TRANSITION_TIMING_FUNCTION] = previous.duration;
style[TRANSITION_DURATION] = previous.timing;
t.node.removeEventListener(TRANSITIONEND, transitionEndHandler, false);
cssTransitionsComplete = true;
checkComplete();
}
t.node.addEventListener(TRANSITIONEND, transitionEndHandler, false);
// safety net in case transitionend never fires
cssTimeout = setTimeout(function () {
changedProperties = [];
cssTransitionsDone();
}, options.duration + (options.delay || 0) + 50);
t.registerCompleteHandler(transitionDone);
style[TRANSITION_PROPERTY] = changedProperties.join(',');
var easingName = hyphenate(options.easing || 'linear');
style[TRANSITION_TIMING_FUNCTION] = easingName;
var cssTiming = style[TRANSITION_TIMING_FUNCTION] === easingName;
style[TRANSITION_DURATION] = options.duration / 1000 + 's';
setTimeout(function () {
var i = changedProperties.length;
var hash;
var originalValue = null;
var index;
var propertiesToTransitionInJs = [];
var prop;
var suffix;
var interpolator;
while (i--) {
prop = changedProperties[i];
hash = hashPrefix + prop;
if (cssTiming && CSS_TRANSITIONS_ENABLED && !cannotUseCssTransitions[hash]) {
var initial = style[prop];
style[prop] = to[prop];
// If we're not sure if CSS transitions are supported for
// this tag/property combo, find out now
if (!(hash in canUseCssTransitions)) {
originalValue = t.getStyle(prop);
// if this property is transitionable in this browser,
// the current style will be different from the target style
canUseCssTransitions[hash] = t.getStyle(prop) != to[prop];
cannotUseCssTransitions[hash] = !canUseCssTransitions[hash];
// Reset, if we're going to use timers after all
if (cannotUseCssTransitions[hash]) {
style[prop] = initial;
}
}
}
if (!cssTiming || !CSS_TRANSITIONS_ENABLED || cannotUseCssTransitions[hash]) {
// we need to fall back to timer-based stuff
if (originalValue === null) { originalValue = t.getStyle(prop); }
// need to remove this from changedProperties, otherwise transitionEndHandler
// will get confused
index = changedProperties.indexOf(prop);
if (index === -1) {
warnIfDebug(
'Something very strange happened with transitions. Please raise an issue at https://github.com/ractivejs/ractive/issues - thanks!',
{ node: t.node }
);
} else {
changedProperties.splice(index, 1);
}
// TODO Determine whether this property is animatable at all
suffix = /[^\d]*$/.exec(originalValue)[0];
interpolator = interpolate(parseFloat(originalValue), parseFloat(to[prop]));
// ...then kick off a timer-based transition
if (interpolator) {
propertiesToTransitionInJs.push({
name: prop,
interpolator: interpolator,
suffix: suffix
});
} else {
style[prop] = to[prop];
}
originalValue = null;
}
}
// javascript transitions
if (propertiesToTransitionInJs.length) {
var easing;
if (isString(options.easing)) {
easing = t.ractive.easing[options.easing];
if (!easing) {
warnOnceIfDebug(missingPlugin(options.easing, 'easing'));
easing = linear$1;
}
} else if (isFunction(options.easing)) {
easing = options.easing;
} else {
easing = linear$1;
}
new Ticker({
duration: options.duration,
easing: easing,
step: function step(pos) {
var i = propertiesToTransitionInJs.length;
while (i--) {
var prop = propertiesToTransitionInJs[i];
style[prop.name] = prop.interpolator(pos) + prop.suffix;
}
},
complete: function complete() {
jsTransitionsComplete = true;
checkComplete();
}
});
} else {
jsTransitionsComplete = true;
}
if (changedProperties.length) {
style[TRANSITION_PROPERTY] = changedProperties.join(',');
} else {
style[TRANSITION_PROPERTY] = 'none';
// We need to cancel the transitionEndHandler, and deal with
// the fact that it will never fire
t.node.removeEventListener(TRANSITIONEND, transitionEndHandler, false);
cssTransitionsComplete = true;
checkComplete();
}
}, 0);
}, options.delay || 0);
};
}
var createTransitions$1 = createTransitions;
var getComputedStyle = win && win.getComputedStyle;
var resolved = Promise.resolve();
var names = {
t0: 'intro-outro',
t1: 'intro',
t2: 'outro'
};
var Transition = function Transition(options) {
this.owner = options.owner || options.up.owner || findElement(options.up);
this.element = this.owner.attributeByName ? this.owner : findElement(options.up);
this.ractive = this.owner.ractive;
this.template = options.template;
this.up = options.up;
this.options = options;
this.onComplete = [];
};
var Transition__proto__ = Transition.prototype;
Transition__proto__.animateStyle = function animateStyle (style, value, options) {
var this$1 = this;
if (arguments.length === 4) {
throw new Error(
't.animateStyle() returns a promise - use .then() instead of passing a callback'
);
}
// Special case - page isn't visible. Don't animate anything, because
// that way you'll never get CSS transitionend events
if (!visible) {
this.setStyle(style, value);
return resolved;
}
var to;
if (isString(style)) {
to = {};
to[style] = value;
} else {
to = style;
// shuffle arguments
options = value;
}
return new Promise(function (fulfil) {
// Edge case - if duration is zero, set style synchronously and complete
if (!options.duration) {
this$1.setStyle(to);
fulfil();
return;
}
// Get a list of the properties we're animating
var propertyNames = keys(to);
var changedProperties = [];
// Store the current styles
var computedStyle = getComputedStyle(this$1.node);
var i = propertyNames.length;
while (i--) {
var prop = propertyNames[i];
var name = prefix$1(prop);
var current = computedStyle[prefix$1(prop)];
// record the starting points
var init = this$1.node.style[name];
if (!(name in this$1.originals)) { this$1.originals[name] = this$1.node.style[name]; }
this$1.node.style[name] = to[prop];
this$1.targets[name] = this$1.node.style[name];
this$1.node.style[name] = init;
// we need to know if we're actually changing anything
if (current != to[prop]) {
// use != instead of !==, so we can compare strings with numbers
changedProperties.push(name);
// if we happened to prefix, make sure there is a properly prefixed value
to[name] = to[prop];
// make the computed style explicit, so we can animate where
// e.g. height='auto'
this$1.node.style[name] = current;
}
}
// If we're not actually changing anything, the transitionend event
// will never fire! So we complete early
if (!changedProperties.length) {
fulfil();
return;
}
createTransitions$1(this$1, to, options, changedProperties, fulfil);
});
};
Transition__proto__.bind = function bind () {
var options = this.options;
var type = options.template && options.template.v;
if (type) {
if (type === 't0' || type === 't1') { this.element.intro = this; }
if (type === 't0' || type === 't2') { this.element.outro = this; }
this.eventName = names[type];
}
var ractive = this.owner.ractive;
this.name = options.name || options.template.n;
if (options.params) {
this.params = options.params;
}
if (isFunction(this.name)) {
this._fn = this.name;
this.name = this._fn.name;
} else {
this._fn = findInViewHierarchy('transitions', ractive, this.name);
}
if (!this._fn) {
warnOnceIfDebug(missingPlugin(this.name, 'transition'), { ractive: ractive });
}
setupArgsFn(this, options.template);
};
Transition__proto__.getParams = function getParams () {
if (this.params) { return this.params; }
// get expression args if supplied
if (this.fn) {
var values = resolveArgs(this, this.template, this.up).map(function (model) {
if (!model) { return undefined; }
return model.get();
});
return this.fn.apply(this.ractive, values);
}
};
Transition__proto__.getStyle = function getStyle (props) {
var computedStyle = getComputedStyle(this.node);
if (isString(props)) {
return computedStyle[prefix$1(props)];
}
if (!isArray(props)) {
throw new Error(
'Transition$getStyle must be passed a string, or an array of strings representing CSS properties'
);
}
var styles = {};
var i = props.length;
while (i--) {
var prop = props[i];
var value = computedStyle[prefix$1(prop)];
if (value === '0px') { value = 0; }
styles[prop] = value;
}
return styles;
};
Transition__proto__.processParams = function processParams (params, defaults) {
if (isNumber(params)) {
params = { duration: params };
} else if (isString(params)) {
if (params === 'slow') {
params = { duration: 600 };
} else if (params === 'fast') {
params = { duration: 200 };
} else {
params = { duration: 400 };
}
} else if (!params) {
params = {};
}
return assign({}, defaults, params);
};
Transition__proto__.registerCompleteHandler = function registerCompleteHandler (fn) {
addToArray(this.onComplete, fn);
};
Transition__proto__.setStyle = function setStyle (style, value) {
var this$1 = this;
if (isString(style)) {
var name = prefix$1(style);
if (!hasOwn(this.originals, name)) { this.originals[name] = this.node.style[name]; }
this.node.style[name] = value;
this.targets[name] = this.node.style[name];
} else {
var prop;
for (prop in style) {
if (hasOwn(style, prop)) {
this$1.setStyle(prop, style[prop]);
}
}
}
return this;
};
Transition__proto__.shouldFire = function shouldFire (type) {
if (!this.ractive.transitionsEnabled) { return false; }
// check for noIntro and noOutro cases, which only apply when the owner ractive is rendering and unrendering, respectively
if (type === 'intro' && this.ractive.rendering && nearestProp('noIntro', this.ractive, true))
{ return false; }
if (type === 'outro' && this.ractive.unrendering && nearestProp('noOutro', this.ractive, false))
{ return false; }
var params = this.getParams(); // this is an array, the params object should be the first member
// if there's not a parent element, this can't be nested, so roll on
if (!this.element.parent) { return true; }
// if there is a local param, it takes precedent
if (params && params[0] && isObject(params[0]) && 'nested' in params[0]) {
if (params[0].nested !== false) { return true; }
} else {
// use the nearest instance setting
// find the nearest instance that actually has a nested setting
if (nearestProp('nestedTransitions', this.ractive) !== false) { return true; }
}
// check to see if this is actually a nested transition
var el = this.element.parent;
while (el) {
if (el[type] && el[type].starting) { return false; }
el = el.parent;
}
return true;
};
Transition__proto__.start = function start () {
var this$1 = this;
var node = (this.node = this.element.node);
var originals = (this.originals = {}); //= node.getAttribute( 'style' );
var targets = (this.targets = {});
var completed;
var args = this.getParams();
// create t.complete() - we don't want this on the prototype,
// because we don't want `this` silliness when passing it as
// an argument
this.complete = function (noReset) {
this$1.starting = false;
if (completed) {
return;
}
this$1.onComplete.forEach(function (fn) { return fn(); });
if (!noReset && this$1.isIntro) {
for (var k in targets) {
if (node.style[k] === targets[k]) { node.style[k] = originals[k]; }
}
}
this$1._manager.remove(this$1);
completed = true;
};
// If the transition function doesn't exist, abort
if (!this._fn) {
this.complete();
return;
}
var promise = this._fn.apply(this.ractive, [this].concat(args));
if (promise) { promise.then(this.complete); }
};
Transition__proto__.toString = function toString () {
return '';
};
Transition__proto__.unbind = function unbind () {
if (!this.element.attributes.unbinding) {
var type = this.options && this.options.template && this.options.template.v;
if (type === 't0' || type === 't1') { this.element.intro = null; }
if (type === 't0' || type === 't2') { this.element.outro = null; }
}
};
Transition__proto__.unregisterCompleteHandler = function unregisterCompleteHandler (fn) {
removeFromArray(this.onComplete, fn);
};
var proto$8 = Transition.prototype;
proto$8.destroyed = proto$8.firstNode = proto$8.rebound = proto$8.render = proto$8.unrender = proto$8.update = noop;
function nearestProp(prop, ractive, rendering) {
var instance = ractive;
while (instance) {
if (
hasOwn(instance, prop) &&
(rendering === undefined || rendering ? instance.rendering : instance.unrendering)
)
{ return instance[prop]; }
instance = instance.component && instance.component.ractive;
}
return ractive[prop];
}
var elementCache = {};
var ieBug;
var ieBlacklist;
try {
createElement('table').innerHTML = 'foo';
} catch (/* istanbul ignore next */ err) {
ieBug = true;
ieBlacklist = {
TABLE: ['<table class="x">', '</table>'],
THEAD: ['<table><thead class="x">', '</thead></table>'],
TBODY: ['<table><tbody class="x">', '</tbody></table>'],
TR: ['<table><tr class="x">', '</tr></table>'],
SELECT: ['<select class="x">', '</select>']
};
}
function insertHtml(html$$1, node) {
var nodes = [];
// render 0 and false
if (html$$1 == null || html$$1 === '') { return nodes; }
var container;
var wrapper;
var selectedOption;
/* istanbul ignore if */
if (ieBug && (wrapper = ieBlacklist[node.tagName])) {
container = element('DIV');
container.innerHTML = wrapper[0] + html$$1 + wrapper[1];
container = container.querySelector('.x');
if (container.tagName === 'SELECT') {
selectedOption = container.options[container.selectedIndex];
}
} else if (node.namespaceURI === svg$1) {
container = element('DIV');
container.innerHTML = '<svg class="x">' + html$$1 + '</svg>';
container = container.querySelector('.x');
} else if (node.tagName === 'TEXTAREA') {
container = createElement('div');
if (typeof container.textContent !== 'undefined') {
container.textContent = html$$1;
} else {
container.innerHTML = html$$1;
}
} else {
container = element(node.tagName);
container.innerHTML = html$$1;
if (container.tagName === 'SELECT') {
selectedOption = container.options[container.selectedIndex];
}
}
var child;
while ((child = container.firstChild)) {
nodes.push(child);
container.removeChild(child);
}
// This is really annoying. Extracting <option> nodes from the
// temporary container <select> causes the remaining ones to
// become selected. So now we have to deselect them. IE8, you
// amaze me. You really do
// ...and now Chrome too
var i;
if (node.tagName === 'SELECT') {
i = nodes.length;
while (i--) {
if (nodes[i] !== selectedOption) {
nodes[i].selected = false;
}
}
}
return nodes;
}
function element(tagName) {
return elementCache[tagName] || (elementCache[tagName] = createElement(tagName));
}
var Triple = (function (Mustache) {
function Triple(options) {
Mustache.call(this, options);
}
if ( Mustache ) Triple.__proto__ = Mustache;
var Triple__proto__ = Triple.prototype = Object.create( Mustache && Mustache.prototype );
Triple__proto__.constructor = Triple;
Triple__proto__.detach = function detach () {
var docFrag = createDocumentFragment();
if (this.nodes) { this.nodes.forEach(function (node) { return docFrag.appendChild(node); }); }
return docFrag;
};
Triple__proto__.find = function find (selector) {
var this$1 = this;
var len = this.nodes.length;
var i;
for (i = 0; i < len; i += 1) {
var node = this$1.nodes[i];
if (node.nodeType !== 1) { continue; }
if (matches(node, selector)) { return node; }
var queryResult = node.querySelector(selector);
if (queryResult) { return queryResult; }
}
return null;
};
Triple__proto__.findAll = function findAll (selector, options) {
var this$1 = this;
var result = options.result;
var len = this.nodes.length;
var i;
for (i = 0; i < len; i += 1) {
var node = this$1.nodes[i];
if (node.nodeType !== 1) { continue; }
if (matches(node, selector)) { result.push(node); }
var queryAllResult = node.querySelectorAll(selector);
if (queryAllResult) {
result.push.apply(result, queryAllResult);
}
}
};
Triple__proto__.findComponent = function findComponent () {
return null;
};
Triple__proto__.firstNode = function firstNode () {
return this.rendered && this.nodes[0];
};
Triple__proto__.render = function render (target, occupants, anchor) {
var this$1 = this;
if (!this.nodes) {
var html = this.model ? this.model.get() : '';
this.nodes = insertHtml(html, target);
}
var nodes = this.nodes;
// progressive enhancement
if (occupants) {
var i = -1;
var next;
// start with the first node that should be rendered
while (occupants.length && (next = this.nodes[i + 1])) {
var n = (void 0);
// look through the occupants until a matching node is found
while ((n = occupants.shift())) {
var t = n.nodeType;
if (
t === next.nodeType &&
((t === 1 && n.outerHTML === next.outerHTML) ||
((t === 3 || t === 8) && n.nodeValue === next.nodeValue))
) {
this$1.nodes.splice(++i, 1, n); // replace the generated node with the existing one
break;
} else {
target.removeChild(n); // remove the non-matching existing node
}
}
}
if (i >= 0) {
// update the list of remaining nodes to attach, excluding any that were replaced by existing nodes
nodes = this.nodes.slice(i);
}
// update the anchor to be the next occupant
if (occupants.length) { anchor = occupants[0]; }
}
// attach any remainging nodes to the parent
if (nodes.length) {
var frag = createDocumentFragment();
nodes.forEach(function (n) { return frag.appendChild(n); });
if (anchor) {
target.insertBefore(frag, anchor);
} else {
target.appendChild(frag);
}
}
this.rendered = true;
};
Triple__proto__.toString = function toString () {
var value = this.model && this.model.get();
value = value != null ? '' + value : '';
return inAttribute() ? decodeCharacterReferences(value) : value;
};
Triple__proto__.unrender = function unrender () {
if (this.nodes)
{ this.nodes.forEach(function (node) {
// defer detachment until all relevant outros are done
runloop.detachWhenReady({
node: node,
detach: function detach() {
detachNode(node);
}
});
}); }
this.rendered = false;
this.nodes = null;
};
Triple__proto__.update = function update () {
if (this.rendered && this.dirty) {
this.dirty = false;
this.unrender();
this.render(this.up.findParentNode(), null, this.up.findNextNode(this));
} else {
// make sure to reset the dirty flag even if not rendered
this.dirty = false;
}
};
return Triple;
}(Mustache));
// finds the component constructor in the registry or view hierarchy registries
function getComponentConstructor(ractive, name) {
var instance = findInstance('components', ractive, name);
var Component;
if (instance) {
Component = instance.components[name];
if (Component && !Component.isInstance) {
if (Component.default && Component.default.isInstance) { Component = Component.default; }
else if (!Component.then && isFunction(Component)) {
// function option, execute and store for reset
var fn = Component.bind(instance);
fn.isOwner = hasOwn(instance.components, name);
Component = fn();
if (!Component) {
warnIfDebug(noRegistryFunctionReturn, name, 'component', 'component', {
ractive: ractive
});
return;
}
if (isString(Component)) {
// allow string lookup
Component = getComponentConstructor(ractive, Component);
}
Component._fn = fn;
instance.components[name] = Component;
}
}
}
return Component;
}
function asyncProxy(promise, options) {
var partials = options.template.p || {};
var name = options.template.e;
var opts = assign({}, options, {
template: { t: ELEMENT, e: name },
macro: function macro(handle) {
handle.setTemplate(partials['async-loading'] || []);
promise.then(
function (cmp) {
options.up.ractive.components[name] = cmp;
if (partials['async-loaded']) {
handle.partials.component = [options.template];
handle.setTemplate(partials['async-loaded']);
} else {
handle.setTemplate([options.template]);
}
},
function (err) {
if (partials['async-failed']) {
handle.aliasLocal('error', 'error');
handle.set('@local.error', err);
handle.setTemplate(partials['async-failed']);
} else {
handle.setTemplate([]);
}
}
);
}
});
return new Partial(opts);
}
function extract(tpl, type, name) {
var p = tpl.f.find(function (s) { return s.t === type; });
if (p) {
if (p.n)
{ return [
{
t: 19,
n: 54,
f: p.f || [],
z: [{ n: p.n, x: { r: ("__await." + name) } }]
}
]; }
else { return p.f || []; }
} else { return []; }
}
function Await(options) {
var tpl = options.template;
var success = extract(tpl, THEN, 'value');
var error = extract(tpl, CATCH, 'error');
var pending = extract(tpl, SECTION);
var undef = extract(tpl, ELSE);
var opts = assign({}, options, {
template: {
t: ELEMENT,
m: [
{
t: ATTRIBUTE,
n: 'for',
f: [{ t: INTERPOLATOR, r: tpl.r, rx: tpl.rx, x: tpl.x }]
}
]
},
macro: function macro(handle, attrs) {
handle.aliasLocal('__await');
function update(attrs) {
if (attrs.for && isFunction(attrs.for.then)) {
handle.setTemplate(pending);
attrs.for.then(
function (v) {
handle.set('@local.value', v);
handle.setTemplate(success);
},
function (e) {
handle.set('@local.error', e);
handle.setTemplate(error);
}
);
} else if (attrs.for === undefined) {
handle.setTemplate(undef);
} else {
handle.set('@local.value', attrs.for);
handle.setTemplate(success);
}
}
update(attrs);
return {
update: update
};
}
});
opts.macro.attributes = ['for'];
return new Partial(opts);
}
var constructors = {};
constructors[ALIAS] = Alias;
constructors[ANCHOR] = Component;
constructors[AWAIT] = Await;
constructors[DOCTYPE] = Doctype;
constructors[INTERPOLATOR] = Interpolator;
constructors[PARTIAL] = Partial;
constructors[SECTION] = Section;
constructors[TRIPLE] = Triple;
constructors[YIELDER] = Partial;
constructors[ATTRIBUTE] = Attribute;
constructors[BINDING_FLAG] = BindingFlag;
constructors[DECORATOR] = Decorator;
constructors[EVENT] = EventDirective;
constructors[TRANSITION] = Transition;
constructors[COMMENT] = Comment;
var specialElements = {
doctype: Doctype,
form: Form,
input: Input,
option: Option,
select: Select,
textarea: Textarea
};
function createItem(options) {
if (isString(options.template)) {
return new Text(options);
}
var ctor;
var name;
var type = options.template.t;
if (type === ELEMENT) {
name = options.template.e;
// could be a macro partial
ctor = findInstance('partials', options.up.ractive, name);
if (ctor) {
ctor = ctor.partials[name];
if (ctor.styleSet) {
options.macro = ctor;
return new Partial(options);
}
}
// could be component or element
ctor = getComponentConstructor(options.up.ractive, name);
if (ctor) {
if (isFunction(ctor.then)) {
return asyncProxy(ctor, options);
} else if (isFunction(ctor)) {
return new Component(options, ctor);
}
}
ctor = specialElements[name.toLowerCase()] || Element;
return new ctor(options);
}
var Item;
// component mappings are a special case of attribute
if (type === ATTRIBUTE) {
var el = options.owner;
if (!el || (el.type !== ANCHOR && el.type !== COMPONENT && el.type !== ELEMENT)) {
el = findElement(options.up);
}
options.element = el;
Item = el.type === COMPONENT || el.type === ANCHOR ? Mapping : Attribute;
} else {
Item = constructors[type];
}
if (!Item) { throw new Error(("Unrecognised item type " + type)); }
return new Item(options);
}
// TODO all this code needs to die
function processItems(items, values, guid, counter) {
if ( counter === void 0 ) counter = 0;
return items
.map(function (item) {
if (item.type === TEXT) {
return item.template;
}
if (item.fragment) {
if (item.fragment.iterations) {
return item.fragment.iterations
.map(function (fragment) {
return processItems(fragment.items, values, guid, counter);
})
.join('');
} else {
return processItems(item.fragment.items, values, guid, counter);
}
}
var placeholderId = guid + "-" + (counter++);
var model = item.model || item.newModel;
values[placeholderId] = model
? model.wrapper
? model.wrapperValue
: model.get()
: undefined;
return '${' + placeholderId + '}';
})
.join('');
}
var Fragment = function Fragment(options) {
this.owner = options.owner; // The item that owns this fragment - an element, section, partial, or attribute
this.isRoot = !options.owner.up;
this.parent = this.isRoot ? null : this.owner.up;
this.ractive = options.ractive || (this.isRoot ? options.owner : this.parent.ractive);
this.componentParent = this.isRoot && this.ractive.component ? this.ractive.component.up : null;
if (!this.isRoot || this.ractive.delegate) {
this.delegate = this.owner.containerFragment
? this.owner.containerFragment && this.owner.containerFragment.delegate
: (this.componentParent && this.componentParent.delegate) ||
(this.parent && this.parent.delegate);
} else {
this.delegate = false;
}
this.context = null;
this.rendered = false;
// encapsulated styles should be inherited until they get applied by an element
if ('cssIds' in options) {
this.cssIds = options.cssIds && options.cssIds.length && options.cssIds;
} else {
this.cssIds = this.parent ? this.parent.cssIds : null;
}
this.dirty = false;
this.dirtyValue = true; // used for attribute values
this.template = options.template || [];
this.createItems();
};
var Fragment__proto__ = Fragment.prototype;
Fragment__proto__.bind = function bind (context) {
var this$1 = this;
this.context = context;
var len = this.items.length;
for (var i = 0; i < len; i++) { this$1.items[i].bind(); }
this.bound = true;
// in rare cases, a forced resolution (or similar) will cause the
// fragment to be dirty before it's even finished binding. In those
// cases we update immediately
if (this.dirty) { this.update(); }
return this;
};
Fragment__proto__.bubble = function bubble () {
this.dirtyValue = true;
if (!this.dirty) {
this.dirty = true;
if (this.isRoot) {
// TODO encapsulate 'is component root, but not overall root' check?
if (this.ractive.component) {
this.ractive.component.bubble();
} else if (this.bound) {
runloop.addFragment(this);
}
} else {
this.owner.bubble(this.index);
}
}
};
Fragment__proto__.createItems = function createItems () {
var this$1 = this;
// this is a hot code path
var max = this.template.length;
this.items = [];
for (var i = 0; i < max; i++) {
this$1.items[i] = createItem({
up: this$1,
template: this$1.template[i],
index: i
});
}
};
Fragment__proto__.destroyed = function destroyed () {
var this$1 = this;
var len = this.items.length;
for (var i = 0; i < len; i++) { this$1.items[i].destroyed(); }
if (this.pathModel) { this.pathModel.destroyed(); }
if (this.rootModel) { this.rootModel.destroyed(); }
};
Fragment__proto__.detach = function detach () {
var docFrag = createDocumentFragment();
var xs = this.items;
var len = xs.length;
for (var i = 0; i < len; i++) {
docFrag.appendChild(xs[i].detach());
}
return docFrag;
};
Fragment__proto__.find = function find (selector, options) {
return findMap(this.items, function (i) { return i.find(selector, options); });
};
Fragment__proto__.findAll = function findAll (selector, options) {
if (this.items) {
this.items.forEach(function (i) { return i.findAll && i.findAll(selector, options); });
}
};
Fragment__proto__.findComponent = function findComponent (name, options) {
return findMap(this.items, function (i) { return i.findComponent(name, options); });
};
Fragment__proto__.findAllComponents = function findAllComponents (name, options) {
if (this.items) {
this.items.forEach(function (i) { return i.findAllComponents && i.findAllComponents(name, options); });
}
};
Fragment__proto__.findContext = function findContext () {
var base = findParentWithContext(this);
if (!base || !base.context) { return this.ractive.viewmodel; }
else { return base.context; }
};
Fragment__proto__.findNextNode = function findNextNode (item) {
var this$1 = this;
// search for the next node going forward
if (item) {
var it;
for (var i = item.index + 1; i < this.items.length; i++) {
it = this$1.items[i];
if (!it || !it.firstNode) { continue; }
var node = it.firstNode(true);
if (node) { return node; }
}
}
// if this is the root fragment, and there are no more items,
// it means we're at the end...
if (this.isRoot) {
if (this.ractive.component) {
return this.ractive.component.up.findNextNode(this.ractive.component);
}
// TODO possible edge case with other content
// appended to this.ractive.el?
return null;
}
if (this.parent) { return this.owner.findNextNode(this); } // the argument is in case the parent is a RepeatedFragment
};
Fragment__proto__.findParentNode = function findParentNode () {
var fragment = this;
do {
if (fragment.owner.type === ELEMENT) {
return fragment.owner.node;
}
if (fragment.isRoot && !fragment.ractive.component) {
// TODO encapsulate check
return fragment.ractive.el;
}
if (fragment.owner.type === YIELDER) {
fragment = fragment.owner.containerFragment;
} else {
fragment = fragment.componentParent || fragment.parent; // TODO ugh
}
} while (fragment);
throw new Error('Could not find parent node'); // TODO link to issue tracker
};
Fragment__proto__.firstNode = function firstNode (skipParent) {
var node = findMap(this.items, function (i) { return i.firstNode(true); });
if (node) { return node; }
if (skipParent) { return null; }
return this.parent.findNextNode(this.owner);
};
Fragment__proto__.getKey = function getKey () {
return this.keyModel || (this.keyModel = new KeyModel(this.key));
};
Fragment__proto__.getIndex = function getIndex () {
return this.idxModel || (this.idxModel = new KeyModel(this.index));
};
Fragment__proto__.rebind = function rebind (next) {
this.context = next;
if (this.rootModel) { this.rootModel.context = this.context; }
if (this.pathModel) { this.pathModel.context = this.context; }
};
Fragment__proto__.rebound = function rebound (update$$1) {
this.items.forEach(function (x) { return x.rebound(update$$1); });
if (update$$1) {
if (this.rootModel) { this.rootModel.applyValue(this.context.getKeypath(this.ractive.root)); }
if (this.pathModel) { this.pathModel.applyValue(this.context.getKeypath()); }
}
};
Fragment__proto__.render = function render (target, occupants) {
if (this.rendered) { throw new Error('Fragment is already rendered!'); }
this.rendered = true;
var xs = this.items;
var len = xs.length;
for (var i = 0; i < len; i++) {
xs[i].render(target, occupants);
}
};
Fragment__proto__.resetTemplate = function resetTemplate (template) {
var wasBound = this.bound;
var wasRendered = this.rendered;
// TODO ensure transitions are disabled globally during reset
if (wasBound) {
if (wasRendered) { this.unrender(true); }
this.unbind();
}
this.template = template;
this.createItems();
if (wasBound) {
this.bind(this.context);
if (wasRendered) {
var parentNode = this.findParentNode();
var anchor = this.findNextNode();
if (anchor) {
var docFrag = createDocumentFragment();
this.render(docFrag);
parentNode.insertBefore(docFrag, anchor);
} else {
this.render(parentNode);
}
}
}
};
Fragment__proto__.shuffled = function shuffled$2 () {
this.items.forEach(shuffled);
if (this.rootModel) { this.rootModel.applyValue(this.context.getKeypath(this.ractive.root)); }
if (this.pathModel) { this.pathModel.applyValue(this.context.getKeypath()); }
};
Fragment__proto__.toString = function toString (escape) {
return this.items.map(escape ? toEscapedString : toString$1).join('');
};
Fragment__proto__.unbind = function unbind (view) {
var this$1 = this;
this.context = null;
var len = this.items.length;
for (var i = 0; i < len; i++) { this$1.items[i].unbind(view); }
this.bound = false;
return this;
};
Fragment__proto__.unrender = function unrender (shouldDestroy) {
var this$1 = this;
var len = this.items.length;
for (var i = 0; i < len; i++) { this$1.items[i].unrender(shouldDestroy); }
this.rendered = false;
};
Fragment__proto__.update = function update () {
var this$1 = this;
if (this.dirty) {
if (!this.updating) {
this.dirty = false;
this.updating = true;
var len = this.items.length;
for (var i = 0; i < len; i++) { this$1.items[i].update(); }
this.updating = false;
} else if (this.isRoot) {
runloop.addFragmentToRoot(this);
}
}
};
Fragment__proto__.valueOf = function valueOf () {
if (this.items.length === 1) {
return this.items[0].valueOf();
}
if (this.dirtyValue) {
var values = {};
var source = processItems(this.items, values, this.ractive._guid);
var parsed = parseJSON(source, values);
this.value = parsed ? parsed.value : this.toString();
this.dirtyValue = false;
}
return this.value;
};
Fragment.prototype.getContext = getContext;
Fragment.prototype.getKeypath = getKeypath;
function getKeypath(root) {
var base = findParentWithContext(this);
var model;
if (root) {
if (!this.rootModel) {
this.rootModel = new KeyModel(
this.context.getKeypath(this.ractive.root),
this.context,
this.ractive.root
);
model = this.rootModel;
} else { return this.rootModel; }
} else {
if (!this.pathModel) {
this.pathModel = new KeyModel(this.context.getKeypath(), this.context);
model = this.pathModel;
} else { return this.pathModel; }
}
if (base && base.context) { base.getKeypath(root).registerChild(model); }
return model;
}
function initialise(ractive, userOptions, options) {
// initialize settable computeds
var computed = ractive.viewmodel.computed;
if (computed) {
for (var k in computed) {
if (k in ractive.viewmodel.value && computed[k] && !computed[k].isReadonly) {
computed[k].set(ractive.viewmodel.value[k]);
}
}
}
// init config from Parent and options
config.init(ractive.constructor, ractive, userOptions);
// call any passed in plugins
if (isArray(userOptions.use))
{ ractive.use.apply(ractive, userOptions.use.filter(function (p) { return !p.construct; })); }
hooks.config.fire(ractive);
hooks.init.begin(ractive);
var fragment = (ractive.fragment = createFragment$1(ractive, options));
if (fragment) { fragment.bind(ractive.viewmodel); }
hooks.init.end(ractive);
// general config done, set up observers
subscribe(ractive, userOptions, 'observe');
if (fragment) {
// render automatically ( if `el` is specified )
var el = (ractive.el = ractive.target = getElement(ractive.el || ractive.target));
if (el && !ractive.component) {
var promise = ractive.render(el, ractive.append);
if (Ractive.DEBUG_PROMISES) {
promise.catch(function (err) {
warnOnceIfDebug(
'Promise debugging is enabled, to help solve errors that happen asynchronously. Some browsers will log unhandled promise rejections, in which case you can safely disable promise debugging:\n Ractive.DEBUG_PROMISES = false;'
);
warnIfDebug('An error happened during rendering', { ractive: ractive });
logIfDebug(err);
throw err;
});
}
}
}
}
function createFragment$1(ractive, options) {
if ( options === void 0 ) options = {};
if (ractive.template) {
var cssIds = [].concat(ractive.constructor._cssIds || [], options.cssIds || []);
return new Fragment({
owner: ractive,
template: ractive.template,
cssIds: cssIds
});
}
}
function render$1(ractive, target, anchor, occupants) {
// set a flag to let any transitions know that this instance is currently rendering
ractive.rendering = true;
var promise = runloop.start();
runloop.scheduleTask(function () { return hooks.render.fire(ractive); }, true);
if (ractive.fragment.rendered) {
throw new Error(
'You cannot call ractive.render() on an already rendered instance! Call ractive.unrender() first'
);
}
if (ractive.destroyed) {
ractive.destroyed = false;
ractive.fragment = createFragment$1(ractive).bind(ractive.viewmodel);
}
anchor = getElement(anchor) || ractive.anchor;
ractive.el = ractive.target = target;
ractive.anchor = anchor;
// ensure encapsulated CSS is up-to-date
if (ractive.cssId) { applyCSS(); }
if (target) {
(target.__ractive_instances__ || (target.__ractive_instances__ = [])).push(ractive);
if (anchor) {
var docFrag = doc.createDocumentFragment();
ractive.fragment.render(docFrag);
target.insertBefore(docFrag, anchor);
} else {
ractive.fragment.render(target, occupants);
}
}
runloop.end();
ractive.rendering = false;
return promise.then(function () {
if (ractive.torndown) { return; }
hooks.complete.fire(ractive);
});
}
function Ractive$render(target, anchor) {
if (this.torndown) {
warnIfDebug('ractive.render() was called on a Ractive instance that was already torn down');
return Promise.resolve();
}
target = getElement(target) || this.el;
if (!this.append && target) {
// Teardown any existing instances *before* trying to set up the new one -
// avoids certain weird bugs
var others = target.__ractive_instances__;
if (others) { others.forEach(teardown); }
// make sure we are the only occupants
if (!this.enhance) {
target.innerHTML = ''; // TODO is this quicker than removeChild? Initial research inconclusive
}
}
var occupants = this.enhance ? toArray(target.childNodes) : null;
var promise = render$1(this, target, anchor, occupants);
if (occupants) {
while (occupants.length) { target.removeChild(occupants.pop()); }
}
return promise;
}
var shouldRerender = ['template', 'partials', 'components', 'decorators', 'events'];
function Ractive$reset(data) {
data = data || {};
if (!isObjectType(data)) {
throw new Error('The reset method takes either no arguments, or an object containing new data');
}
// TEMP need to tidy this up
data = dataConfigurator.init(this.constructor, this, { data: data });
var promise = runloop.start();
// If the root object is wrapped, try and use the wrapper's reset value
var wrapper = this.viewmodel.wrapper;
if (wrapper && wrapper.reset) {
if (wrapper.reset(data) === false) {
// reset was rejected, we need to replace the object
this.viewmodel.set(data);
}
} else {
this.viewmodel.set(data);
}
// reset config items and track if need to rerender
var changes = config.reset(this);
var rerender;
var i = changes.length;
while (i--) {
if (shouldRerender.indexOf(changes[i]) > -1) {
rerender = true;
break;
}
}
if (rerender) {
hooks.unrender.fire(this);
this.fragment.resetTemplate(this.template);
hooks.render.fire(this);
hooks.complete.fire(this);
}
runloop.end();
hooks.reset.fire(this, data);
return promise;
}
function collect$1(source, name, attr, dest) {
source.forEach(function (item) {
// queue to rerender if the item is a partial and the current name matches
if (item.type === PARTIAL && (item.refName === name || item.name === name)) {
item.inAttribute = attr;
dest.push(item);
return; // go no further
}
// if it has a fragment, process its items
if (item.fragment) {
collect$1(item.fragment.iterations || item.fragment.items, name, attr, dest);
} else if (isArray(item.items)) {
// or if it is itself a fragment, process its items
collect$1(item.items, name, attr, dest);
} else if (item.type === COMPONENT && item.instance) {
// or if it is a component, step in and process its items
// ...unless the partial is shadowed
if (item.instance.partials[name]) { return; }
collect$1(item.instance.fragment.items, name, attr, dest);
}
// if the item is an element, process its attributes too
if (item.type === ELEMENT) {
if (isArray(item.attributes)) {
collect$1(item.attributes, name, true, dest);
}
}
});
}
function resetPartial(name, partial) {
var collection = [];
collect$1(this.fragment.items, name, false, collection);
var promise = runloop.start();
this.partials[name] = partial;
collection.forEach(handleChange);
runloop.end();
return promise;
}
// TODO should resetTemplate be asynchronous? i.e. should it be a case
// of outro, update template, intro? I reckon probably not, since that
// could be achieved with unrender-resetTemplate-render. Also, it should
// conceptually be similar to resetPartial, which couldn't be async
function Ractive$resetTemplate(template) {
templateConfigurator.init(null, this, { template: template });
var transitionsEnabled = this.transitionsEnabled;
this.transitionsEnabled = false;
// Is this is a component, we need to set the `shouldDestroy`
// flag, otherwise it will assume by default that a parent node
// will be detached, and therefore it doesn't need to bother
// detaching its own nodes
var component = this.component;
if (component) { component.shouldDestroy = true; }
this.unrender();
if (component) { component.shouldDestroy = false; }
var promise = runloop.start();
// remove existing fragment and create new one
this.fragment.unbind().unrender(true);
this.fragment = new Fragment({
template: this.template,
root: this,
owner: this
});
var docFrag = createDocumentFragment();
this.fragment.bind(this.viewmodel).render(docFrag);
// if this is a component, its el may not be valid, so find a
// target based on the component container
if (component && !component.external) {
this.fragment.findParentNode().insertBefore(docFrag, component.findNextNode());
} else {
this.el.insertBefore(docFrag, this.anchor);
}
runloop.end();
this.transitionsEnabled = transitionsEnabled;
return promise;
}
var reverse = makeArrayMethod('reverse').path;
function Ractive$set(keypath, value, options) {
var ractive = this;
var opts = isObjectType(keypath) ? value : options;
return set(build(ractive, keypath, value, opts && opts.isolated), opts);
}
var shift = makeArrayMethod('shift').path;
var sort = makeArrayMethod('sort').path;
var splice = makeArrayMethod('splice').path;
function Ractive$subtract(keypath, d, options) {
var num = isNumber(d) ? -d : -1;
var opts = isObjectType(d) ? d : options;
return add(this, keypath, num, opts);
}
function Ractive$toggle(keypath, options) {
if (!isString(keypath)) {
throw new TypeError(badArguments);
}
return set(
gather(this, keypath, null, options && options.isolated).map(function (m) { return [m, !m.get()]; }),
options
);
}
function Ractive$toCSS() {
var cssIds = [this.cssId ].concat( this.findAllComponents().map(function (c) { return c.cssId; }));
var uniqueCssIds = keys(cssIds.reduce(function (ids, id) { return (ids[id] = true, ids); }, {}));
return getCSS(uniqueCssIds);
}
function Ractive$toHTML() {
return this.fragment.toString(true);
}
function toText() {
return this.fragment.toString(false);
}
function Ractive$transition(name, node, params) {
if (node instanceof HTMLElement) {
// good to go
} else if (isObject(node)) {
// omitted, use event node
params = node;
}
// if we allow query selector, then it won't work
// simple params like "fast"
// else if ( typeof node === 'string' ) {
// // query selector
// node = this.find( node )
// }
node = node || this.event.node;
if (!node || !node._ractive) {
fatal(("No node was supplied for transition " + name));
}
params = params || {};
var owner = node._ractive.proxy;
var transition = new Transition({ owner: owner, up: owner.up, name: name, params: params });
transition.bind();
var promise = runloop.start();
runloop.registerTransition(transition);
runloop.end();
promise.then(function () { return transition.unbind(); });
return promise;
}
function unlink(here) {
var promise = runloop.start();
this.viewmodel.joinAll(splitKeypath(here), { lastLink: false }).unlink();
runloop.end();
return promise;
}
function Ractive$unrender() {
if (!this.fragment.rendered) {
warnIfDebug('ractive.unrender() was called on a Ractive instance that was not rendered');
return Promise.resolve();
}
this.unrendering = true;
var promise = runloop.start();
hooks.unrendering.fire(this);
// If this is a component, and the component isn't marked for destruction,
// don't detach nodes from the DOM unnecessarily
var shouldDestroy =
!this.component ||
(this.component.anchor || {}).shouldDestroy ||
this.component.shouldDestroy ||
this.shouldDestroy;
this.fragment.unrender(shouldDestroy);
if (shouldDestroy) { this.destroyed = true; }
removeFromArray(this.el.__ractive_instances__, this);
hooks.unrender.fire(this);
runloop.end();
this.unrendering = false;
return promise;
}
var unshift = makeArrayMethod('unshift').path;
function Ractive$updateModel(keypath, cascade) {
var promise = runloop.start();
if (!keypath) {
this.viewmodel.updateFromBindings(true);
} else {
this.viewmodel.joinAll(splitKeypath(keypath)).updateFromBindings(cascade !== false);
}
runloop.end();
return promise;
}
function use() {
var this$1 = this;
var plugins = [], len = arguments.length;
while ( len-- ) plugins[ len ] = arguments[ len ];
plugins.forEach(function (p) {
p({
proto: this$1,
Ractive: this$1.constructor.Ractive,
instance: this$1
});
});
return this;
}
var proto$9 = {
add: Ractive$add,
animate: Ractive$animate,
attachChild: attachChild,
compute: Ractive$compute,
detach: Ractive$detach,
detachChild: detachChild,
find: Ractive$find,
findAll: Ractive$findAll,
findAllComponents: Ractive$findAllComponents,
findComponent: Ractive$findComponent,
findContainer: Ractive$findContainer,
findParent: Ractive$findParent,
fire: Ractive$fire,
get: Ractive$get,
getContext: getContext$2,
insert: Ractive$insert,
link: link,
observe: observe,
observeOnce: observeOnce,
off: Ractive$off,
on: Ractive$on,
once: Ractive$once,
pop: pop,
push: push,
readLink: readLink,
render: Ractive$render,
reset: Ractive$reset,
resetPartial: resetPartial,
resetTemplate: Ractive$resetTemplate,
reverse: reverse,
set: Ractive$set,
shift: shift,
sort: sort,
splice: splice,
subtract: Ractive$subtract,
teardown: Ractive$teardown,
toggle: Ractive$toggle,
toCSS: Ractive$toCSS,
toCss: Ractive$toCSS,
toHTML: Ractive$toHTML,
toHtml: Ractive$toHTML,
toText: toText,
transition: Ractive$transition,
unlink: unlink,
unrender: Ractive$unrender,
unshift: unshift,
update: Ractive$update,
updateModel: Ractive$updateModel,
use: use
};
function isInstance(object) {
return object && object instanceof this;
}
function styleGet(keypath, opts) {
return this._cssModel.joinAll(splitKeypath(keypath)).get(true, opts);
}
var styles = [];
function addStyle(id, css) {
if (styles.find(function (s) { return s.id === id; }))
{ throw new Error(("Extra styles with the id '" + id + "' have already been added.")); }
styles.push({ id: id, css: css });
if (!this.css) {
Object.defineProperty(this, 'css', { configurable: false, writable: false, value: buildCSS });
}
if (!this._cssDef) {
Object.defineProperty(this, '_cssDef', {
configurable: true,
writable: false,
value: {
transform: false,
id: 'Ractive.addStyle'
}
});
addCSS(this._cssDef);
}
recomputeCSS(this);
applyCSS(true);
}
function buildCSS(data) {
return styles
.map(function (s) { return "\n/* ---- extra style " + (s.id) + " */\n" + (isFunction(s.css) ? s.css(data) : s.css); })
.join('');
}
function hasStyle(id) {
return !!styles.find(function (s) { return s.id === id; });
}
function sharedSet(keypath, value, options) {
var opts = isObjectType(keypath) ? value : options;
var model = SharedModel$1;
return set(build({ viewmodel: model }, keypath, value, true), opts);
}
function sharedGet(keypath, opts) {
return SharedModel$1.joinAll(splitKeypath(keypath)).get(true, opts);
}
function use$1() {
var this$1 = this;
var plugins = [], len = arguments.length;
while ( len-- ) plugins[ len ] = arguments[ len ];
plugins.forEach(function (p) {
isFunction(p) &&
p({
proto: this$1.prototype,
Ractive: this$1.Ractive,
instance: this$1
});
});
return this;
}
var callsSuper = /super\s*\(|\.call\s*\(\s*this/;
function extend() {
var options = [], len = arguments.length;
while ( len-- ) options[ len ] = arguments[ len ];
if (!options.length) {
return extendOne(this);
} else {
return options.reduce(extendOne, this);
}
}
function extendWith(Class, options) {
if ( options === void 0 ) options = {};
return extendOne(this, options, Class);
}
function extendOne(Parent, options, Target) {
if ( options === void 0 ) options = {};
var proto;
var Child = isFunction(Target) && Target;
if (options.prototype instanceof Ractive) {
throw new Error("Ractive no longer supports multiple inheritance.");
}
if (Child) {
if (!(Child.prototype instanceof Parent)) {
throw new Error(
"Only classes that inherit the appropriate prototype may be used with extend"
);
}
if (!callsSuper.test(Child.toString())) {
throw new Error("Only classes that call super in their constructor may be used with extend");
}
proto = Child.prototype;
} else {
Child = function(options) {
if (!(this instanceof Child)) { return new Child(options); }
construct(this, options || {});
initialise(this, options || {}, {});
};
proto = create(Parent.prototype);
proto.constructor = Child;
Child.prototype = proto;
}
// Static properties
defineProperties(Child, {
// alias prototype as defaults
defaults: { value: proto },
extend: { value: extend, writable: true, configurable: true },
extendWith: { value: extendWith, writable: true, configurable: true },
extensions: { value: [] },
use: { value: use$1 },
isInstance: { value: isInstance },
Parent: { value: Parent },
Ractive: { value: Ractive },
styleGet: { value: styleGet.bind(Child), configurable: true },
styleSet: { value: setCSSData.bind(Child), configurable: true }
});
// extend configuration
config.extend(Parent, proto, options, Child);
// store event and observer registries on the constructor when extending
Child._on = (Parent._on || []).concat(toPairs(options.on));
Child._observe = (Parent._observe || []).concat(toPairs(options.observe));
Parent.extensions.push(Child);
// attribute defs are not inherited, but they need to be stored
if (options.attributes) {
var attrs;
// allow an array of optional props or an object with arrays for optional and required props
if (isArray(options.attributes)) {
attrs = { optional: options.attributes, required: [] };
} else {
attrs = options.attributes;
}
// make sure the requisite keys actually store arrays
if (!isArray(attrs.required)) { attrs.required = []; }
if (!isArray(attrs.optional)) { attrs.optional = []; }
Child.attributes = attrs;
}
dataConfigurator.extend(Parent, proto, options, Child);
defineProperty(Child, 'helpers', { writable: true, value: proto.helpers });
if (isArray(options.use)) { Child.use.apply(Child, options.use); }
return Child;
}
defineProperties(Ractive, {
sharedGet: { value: sharedGet },
sharedSet: { value: sharedSet },
styleGet: { configurable: true, value: styleGet.bind(Ractive) },
styleSet: { configurable: true, value: setCSSData.bind(Ractive) },
addCSS: { configurable: false, value: addStyle.bind(Ractive) },
hasCSS: { configurable: false, value: hasStyle.bind(Ractive) }
});
function macro(fn, opts) {
if (!isFunction(fn)) { throw new Error("The macro must be a function"); }
assign(fn, opts);
defineProperties(fn, {
extensions: { value: [] },
_cssIds: { value: [] },
cssData: { value: assign(create(this.cssData), fn.cssData || {}) },
styleGet: { value: styleGet.bind(fn) },
styleSet: { value: setCSSData.bind(fn) }
});
defineProperty(fn, '_cssModel', { value: new CSSModel(fn) });
if (fn.css) { initCSS(fn, fn, fn); }
this.extensions.push(fn);
return fn;
}
function joinKeys() {
var keys = [], len = arguments.length;
while ( len-- ) keys[ len ] = arguments[ len ];
return keys.map(escapeKey).join('.');
}
function splitKeypath$1(keypath) {
return splitKeypath(keypath).map(unescapeKey);
}
function findPlugin(name, type, instance) {
return findInViewHierarchy(type, instance, name);
}
function Ractive(options) {
if (!(this instanceof Ractive)) { return new Ractive(options); }
construct(this, options || {});
initialise(this, options || {}, {});
}
// check to see if we're being asked to force Ractive as a global for some weird environments
if (win && !win.Ractive) {
var opts$1 = '';
var script =
document.currentScript ||
/* istanbul ignore next */ document.querySelector('script[data-ractive-options]');
if (script) { opts$1 = script.getAttribute('data-ractive-options') || ''; }
/* istanbul ignore next */
if (~opts$1.indexOf('ForceGlobal')) { win.Ractive = Ractive; }
} else if (win) {
warn("Ractive already appears to be loaded while loading 1.3.0-edge.");
}
assign(Ractive.prototype, proto$9, defaults);
Ractive.prototype.constructor = Ractive;
// alias prototype as `defaults`
Ractive.defaults = Ractive.prototype;
// share defaults with the parser
shared.defaults = Ractive.defaults;
shared.Ractive = Ractive;
// static properties
defineProperties(Ractive, {
// debug flag
DEBUG: { writable: true, value: true },
DEBUG_PROMISES: { writable: true, value: true },
// static methods:
extend: { value: extend },
extendWith: { value: extendWith },
escapeKey: { value: escapeKey },
evalObjectString: { value: parseJSON },
findPlugin: { value: findPlugin },
getContext: { value: getContext$1 },
getCSS: { value: getCSS },
isInstance: { value: isInstance },
joinKeys: { value: joinKeys },
macro: { value: macro },
normaliseKeypath: { value: normalise },
parse: { value: parse },
splitKeypath: { value: splitKeypath$1 },
// sharedSet and styleSet are in _extend because circular refs
unescapeKey: { value: unescapeKey },
use: { value: use$1 },
// support
enhance: { writable: true, value: false },
svg: { value: svg },
// version
VERSION: { value: '1.3.0-edge' },
// plugins
adaptors: { writable: true, value: {} },
components: { writable: true, value: {} },
decorators: { writable: true, value: {} },
easing: { writable: true, value: easing },
events: { writable: true, value: {} },
extensions: { value: [] },
helpers: { writable: true, value: defaults.helpers },
interpolators: { writable: true, value: interpolators },
partials: { writable: true, value: {} },
transitions: { writable: true, value: {} },
// CSS variables
cssData: { configurable: true, value: {} },
// access to @shared without an instance
sharedData: { value: data },
// for getting the source Ractive lib from a constructor
Ractive: { value: Ractive },
// to allow extending contexts
Context: { value: extern.Context.prototype }
});
// cssData must already be in place
defineProperty(Ractive, '_cssModel', {
configurable: true,
value: new CSSModel(Ractive)
});
defineProperty(Ractive.prototype, 'rendered', {
get: function get() {
return this.fragment && this.fragment.rendered;
}
});
return Ractive;
})));
//# sourceMappingURL=ractive.js.map
|
joeyparrish/cdnjs
|
ajax/libs/ractive/1.3.0-build-1/ractive.js
|
JavaScript
|
mit
| 509,632
|
/*!
* OOUI v0.31.3
* https://www.mediawiki.org/wiki/OOUI
*
* Copyright 2011–2019 OOUI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2019-04-04T19:10:54Z
*/
.oo-ui-window {
background: transparent;
}
.oo-ui-window-frame {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.oo-ui-window-content {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
overflow: hidden;
}
.oo-ui-window-content:focus {
outline: 0;
}
.oo-ui-window-head,
.oo-ui-window-foot {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.oo-ui-window-body {
margin: 0;
padding: 0;
background: none;
}
.oo-ui-window-overlay {
position: absolute;
top: 0;
/* @noflip */
left: 0;
}
.oo-ui-dialog-content > .oo-ui-window-head,
.oo-ui-dialog-content > .oo-ui-window-body,
.oo-ui-dialog-content > .oo-ui-window-foot {
position: absolute;
right: 0;
left: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.oo-ui-dialog-content > .oo-ui-window-head {
overflow: hidden;
z-index: 1;
top: 0;
}
.oo-ui-dialog-content > .oo-ui-window-body {
overflow: auto;
-webkit-overflow-scrolling: touch;
z-index: 2;
top: 0;
bottom: 0;
}
.oo-ui-dialog-content > .oo-ui-window-foot {
z-index: 3;
bottom: 0;
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget {
position: relative;
text-align: center;
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget .oo-ui-buttonElement-button {
display: block;
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget .oo-ui-labelElement-label {
position: relative;
top: auto;
bottom: auto;
}
.oo-ui-messageDialog-actions-horizontal {
display: table;
table-layout: fixed;
width: 100%;
}
.oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget {
display: table-cell;
width: 1%;
}
.oo-ui-messageDialog-actions-vertical {
display: block;
}
.oo-ui-messageDialog-actions-vertical .oo-ui-actionWidget {
display: block;
overflow: hidden;
text-overflow: ellipsis;
}
.oo-ui-messageDialog-content > .oo-ui-window-foot {
outline: 1px solid #a2a9b1;
}
.oo-ui-messageDialog-title,
.oo-ui-messageDialog-message {
display: block;
line-height: 1.42857143em;
text-align: center;
}
.oo-ui-messageDialog-title {
font-size: 1.5em;
color: #000;
}
.oo-ui-messageDialog-message {
font-size: 1.1em;
color: #222;
text-align: right;
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget {
min-height: 2.85714286em;
margin-left: 0;
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget:last-child {
margin-left: 0;
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget:first-child {
margin-right: 0;
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget .oo-ui-buttonElement-button {
border: 0;
border-radius: 0;
padding: 0;
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget.oo-ui-labelElement .oo-ui-labelElement-label {
line-height: 2.85714286em;
text-align: center;
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive .oo-ui-buttonElement-button:active {
background-color: rgba(8, 126, 204, 0.1);
}
.oo-ui-messageDialog-actions .oo-ui-actionWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive .oo-ui-buttonElement-button:active {
background-color: rgba(212, 83, 83, 0.1);
}
.oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget {
border-left: 1px solid #a2a9b1;
margin: 0;
}
.oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget:first-child > .oo-ui-buttonElement-button {
border-radius: 0 0 2px 0;
}
.oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget:last-child {
border-left-width: 0;
}
.oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget:last-child > .oo-ui-buttonElement-button {
border-radius: 0 0 0 2px;
}
.oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget:only-child > .oo-ui-buttonElement-button {
border-radius: 0 0 2px 2px;
}
.oo-ui-messageDialog-actions-vertical .oo-ui-actionWidget {
border-bottom: 1px solid #a2a9b1;
margin: 0;
}
.oo-ui-messageDialog-actions-vertical .oo-ui-actionWidget:last-child {
border-bottom-width: 0;
}
.oo-ui-messageDialog-actions-vertical .oo-ui-actionWidget:last-child > .oo-ui-buttonElement-button {
border-radius: 0 0 2px 2px;
}
.oo-ui-processDialog-location {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.oo-ui-processDialog-title {
display: inline;
padding: 0;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget,
.oo-ui-processDialog-actions-other .oo-ui-actionWidget {
white-space: nowrap;
}
.oo-ui-processDialog-actions-safe,
.oo-ui-processDialog-actions-primary {
position: absolute;
top: 0;
bottom: 0;
}
.oo-ui-processDialog-actions-safe {
right: 0;
}
.oo-ui-processDialog-actions-primary {
left: 0;
}
.oo-ui-processDialog-errors {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
z-index: 4;
overflow-x: hidden;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
.oo-ui-processDialog-content .oo-ui-window-head {
height: 3.14285714em;
}
.oo-ui-processDialog-content .oo-ui-window-body {
top: 3.14285714em;
outline: 1px solid #c8ccd1;
}
.oo-ui-processDialog-navigation {
position: relative;
height: 3.14285714em;
}
.oo-ui-processDialog-location {
height: 3.14285714em;
cursor: default;
text-align: center;
}
.oo-ui-processDialog-title {
font-weight: bold;
line-height: 3.14285714em;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-framed,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-framed,
.oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-framed {
margin: 0.42857143em;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement:first-child,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement:first-child,
.oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement:first-child {
margin-right: 0;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button,
.oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button {
padding-right: 2.42857143em;
padding-top: 0;
min-height: 3.14285714em;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon,
.oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon {
right: 0.5em;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement:first-child,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement:first-child,
.oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement:first-child {
margin-right: 0;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement > .oo-ui-buttonElement-button,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement > .oo-ui-buttonElement-button,
.oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement > .oo-ui-buttonElement-button {
padding: 0.75em 1em;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement.oo-ui-iconElement > .oo-ui-buttonElement-button,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement.oo-ui-iconElement > .oo-ui-buttonElement-button,
.oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement.oo-ui-iconElement > .oo-ui-buttonElement-button {
padding-right: 2.17857143em;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless .oo-ui-labelElement-label,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless .oo-ui-labelElement-label,
.oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless .oo-ui-labelElement-label {
line-height: 1.42857143em;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless:hover,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless:hover {
background-color: rgba(0, 0, 0, 0.05);
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless:active,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless:active {
background-color: rgba(0, 0, 0, 0.1);
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive:hover,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive:hover {
background-color: rgba(8, 126, 204, 0.05);
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive:active,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive:active {
background-color: rgba(8, 126, 204, 0.1);
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive .oo-ui-labelElement-label,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive .oo-ui-labelElement-label {
font-weight: bold;
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-destructive:hover,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-destructive:hover {
background-color: rgba(212, 83, 83, 0.05);
}
.oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-destructive:active,
.oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-destructive:active {
background-color: rgba(212, 83, 83, 0.1);
}
.oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement {
margin-left: 0;
}
.oo-ui-processDialog > .oo-ui-window-frame {
min-height: 5em;
}
.oo-ui-processDialog-errors {
background-color: rgba(255, 255, 255, 0.9);
padding: 3em 3em 1.5em 3em;
text-align: center;
}
.oo-ui-processDialog-errors .oo-ui-buttonWidget {
margin: 2em 1em 2em 1em;
}
.oo-ui-processDialog-errors-title {
font-size: 1.5em;
color: #000;
margin-bottom: 2em;
}
.oo-ui-processDialog-error {
text-align: right;
margin: 1em;
padding: 1em;
border: 1px solid #d33;
background-color: #fff7f7;
border-radius: 2px;
}
.oo-ui-windowManager-modal > .oo-ui-dialog {
position: fixed;
width: 0;
height: 0;
overflow: hidden;
z-index: 4;
}
.oo-ui-windowManager-modal > .oo-ui-dialog.oo-ui-window-active {
width: auto;
height: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
padding: 1em;
}
.oo-ui-windowManager-modal > .oo-ui-dialog.oo-ui-window-active > .oo-ui-window-frame {
position: absolute;
left: 0;
right: 0;
margin: auto;
max-width: 100%;
max-height: 100%;
}
.oo-ui-windowManager-fullscreen > .oo-ui-dialog > .oo-ui-window-frame {
width: 100%;
height: 100%;
top: 0;
bottom: 0;
}
.oo-ui-windowManager-modal-active {
overflow: hidden;
position: relative;
}
.oo-ui-windowManager-modal > .oo-ui-dialog {
background-color: rgba(255, 255, 255, 0.5);
opacity: 0;
-webkit-transition: opacity ease-out 250ms;
-moz-transition: opacity ease-out 250ms;
transition: opacity ease-out 250ms;
}
.oo-ui-windowManager-modal > .oo-ui-dialog > .oo-ui-window-frame {
background-color: #fff;
opacity: 0;
-webkit-transform: scale(0.5);
-moz-transform: scale(0.5);
-ms-transform: scale(0.5);
transform: scale(0.5);
-webkit-transition: all ease-out 250ms;
-moz-transition: all ease-out 250ms;
transition: all ease-out 250ms;
}
.oo-ui-windowManager-modal > .oo-ui-dialog.oo-ui-window-setup {
opacity: 1;
}
.oo-ui-windowManager-modal > .oo-ui-dialog.oo-ui-window-setup > .oo-ui-window-frame {
opacity: 1;
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
}
.oo-ui-windowManager-modal.oo-ui-windowManager-floating > .oo-ui-dialog > .oo-ui-window-frame {
top: 1em;
bottom: 1em;
max-height: 100%;
max-height: calc( 100% - 2em );
border: 1px solid #a2a9b1;
border-radius: 2px;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.25);
}
|
extend1994/cdnjs
|
ajax/libs/oojs-ui/0.31.3/oojs-ui-windows-wikimediaui.rtl.css
|
CSS
|
mit
| 13,348
|
package hudson.cli;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.TopLevelItem;
import hudson.model.ViewTest.CompositeView;
import hudson.model.View;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import jenkins.model.Jenkins;
import jenkins.model.ModifiableTopLevelItemGroup;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Jenkins.class)
@SuppressStaticInitializationFor("hudson.cli.CLICommand")
public class ListJobsCommandTest {
private /*final*/ Jenkins jenkins;
private /*final*/ ListJobsCommand command;
private final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
private final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
@Before
public void setUp() {
jenkins = mock(Jenkins.class);
mockStatic(Jenkins.class);
when(Jenkins.getInstance()).thenReturn(jenkins);
when(Jenkins.getActiveInstance()).thenReturn(jenkins);
command = mock(ListJobsCommand.class, Mockito.CALLS_REAL_METHODS);
command.stdout = new PrintStream(stdout);
command.stderr = new PrintStream(stderr);
}
@Test
public void failForNonexistingName() throws Exception {
when(jenkins.getView("NoSuchViewOrItemGroup")).thenReturn(null);
when(jenkins.getItemByFullName("NoSuchViewOrItemGroup")).thenReturn(null);
try {
runWith("NoSuchViewOrItemGroup");
fail("Exception should be thrown in the previous call.");
} catch (IllegalArgumentException e) { // Expected
assertThat(e.getMessage(), containsString("No view or item group with the given name 'NoSuchViewOrItemGroup' found."));
}
assertThat(stdout, is(empty()));
}
/*
@Test
@Issue("JENKINS-18393")
public void failForMatrixProject() throws Exception {
final MatrixProject matrix = mock(MatrixProject.class);
final MatrixConfiguration config = mock(MatrixConfiguration.class);
when(matrix.getItems()).thenReturn(Arrays.asList(config));
when(jenkins.getView("MatrixJob")).thenReturn(null);
when(jenkins.getItemByFullName("MatrixJob")).thenReturn(matrix);
assertThat(runWith("MatrixJob"), equalTo(-1));
assertThat(stdout, is(empty()));
assertThat(stderr.toString(), containsString("No view or item group with the given name found"));
}
*/
@Ignore("TODO enable when you figure out why ListJobsCommandTest$1Folder$$EnhancerByMockitoWithCGLIB$$f124784a calls ReturnsEmptyValues, or just use MockFolder and move to the test module with JenkinsRule")
@Test
public void getAllJobsFromFolders() throws Exception {
abstract class Folder implements ModifiableTopLevelItemGroup, TopLevelItem {
}
final Folder folder = mock(Folder.class);
final Folder nestedFolder = mock(Folder.class);
when(folder.getDisplayName()).thenReturn("Folder");
when(nestedFolder.getDisplayName()).thenReturn("NestedFolder");
final TopLevelItem job = job("job");
final TopLevelItem nestedJob = job("nestedJob");
when(job.hasPermission(Item.READ)).thenReturn(true);
when(nestedJob.hasPermission(Item.READ)).thenReturn(true);
when(job.getRelativeNameFrom((ItemGroup<TopLevelItem>) folder)).thenReturn("job");
when(nestedJob.getRelativeNameFrom((ItemGroup<TopLevelItem>) folder)).thenReturn("nestedJob");
when(folder.getItems()).thenReturn(Arrays.asList(nestedFolder, job));
when(nestedFolder.getItems()).thenReturn(Arrays.asList(nestedJob));
when(jenkins.getView("OuterFolder")).thenReturn(null);
when(jenkins.getItemByFullName("OuterFolder")).thenReturn(folder);
assertThat(runWith("OuterFolder"), equalTo(0));
assertThat(stdout, listsJobs("job", "nestedJob"));
assertThat(stderr, is(empty()));
}
@Test
public void getAllJobsForEmptyName() throws Exception {
final Collection<TopLevelItem> jenkinsJobs = Arrays.asList(
job("some-job"), job("some-other-job")
);
when(jenkins.getItems()).thenReturn((List<TopLevelItem>) jenkinsJobs);
assertThat(runWith(null), equalTo(0));
assertThat(stderr, is(empty()));
assertThat(stdout, listsJobs("some-job", "some-other-job"));
}
@Test
public void getJobsFromView() throws Exception {
final Collection<TopLevelItem> viewJobs = Arrays.asList(
job("some-job"), job("some-other-job")
);
final View customView = view();
when(customView.getItems()).thenReturn(viewJobs);
when(jenkins.getView("CustomView")).thenReturn(customView);
assertThat(runWith("CustomView"), equalTo(0));
assertThat(stderr, is(empty()));
assertThat(stdout, listsJobs("some-job", "some-other-job"));
}
@Test
public void getJobsRecursivelyFromViewGroup() throws Exception {
final CompositeView rootView = mock(CompositeView.class);
when(rootView.getAllItems()).thenCallRealMethod();
final View leftView = view();
final View rightView = view();
final TopLevelItem rootJob = job("rootJob");
final TopLevelItem leftJob = job("leftJob");
final TopLevelItem rightJob = job("rightJob");
final TopLevelItem sharedJob = job("sharedJob");
when(rootView.getViews()).thenReturn(Arrays.asList(leftView, rightView));
when(rootView.getItems()).thenReturn(Arrays.asList(rootJob, sharedJob));
when(leftView.getItems()).thenReturn(Arrays.asList(leftJob, sharedJob));
when(rightView.getItems()).thenReturn(Arrays.asList(rightJob));
when(jenkins.getView("Root")).thenReturn(rootView);
assertThat(runWith("Root"), equalTo(0));
assertThat(stderr, is(empty()));
assertThat(stdout, listsJobs("rootJob", "leftJob", "rightJob", "sharedJob"));
}
private View view() {
final View view = mock(View.class);
when(view.getAllItems()).thenCallRealMethod();
return view;
}
private TopLevelItem job(final String name) {
final TopLevelItem item = mock(TopLevelItem.class);
when(item.getName()).thenReturn(name);
when(item.getDisplayName()).thenReturn(name);
return item;
}
private int runWith(final String name) throws Exception {
command.name = name;
return command.run();
}
private TypeSafeMatcher<ByteArrayOutputStream> empty() {
return new TypeSafeMatcher<ByteArrayOutputStream>() {
@Override
protected boolean matchesSafely(ByteArrayOutputStream item) {
return item.toString().isEmpty();
}
@Override
public void describeTo(Description description) {
description.appendText("Empty output");
}
};
}
private TypeSafeMatcher<ByteArrayOutputStream> listsJobs(final String... expected) {
return new TypeSafeMatcher<ByteArrayOutputStream>() {
@Override
protected boolean matchesSafely(ByteArrayOutputStream item) {
final HashSet<String> jobs = new HashSet<String>(
Arrays.asList(item.toString().split(System.getProperty("line.separator")))
);
return new HashSet<String>(Arrays.asList(expected)).equals(jobs);
}
@Override
public void describeTo(Description description) {
description.appendText("Job listing of " + Arrays.toString(expected));
}
};
}
}
|
dariver/jenkins
|
core/src/test/java/hudson/cli/ListJobsCommandTest.java
|
Java
|
mit
| 8,621
|
require 'spec_helper'
describe OmniAuth::Strategies::Salesforce do
strategy = nil
before do
OmniAuth.config.test_mode = true
rack_app = []
rack_app.stub :call
strategy = OmniAuth::Strategies::Salesforce.new rack_app, 'Consumer Key', 'Consumer Secret'
end
describe "request_phase" do
env = nil
before do
env = {
'rack.session' => {},
'HTTP_USER_AGENT' => 'unknown',
'REQUEST_METHOD' => 'GET',
'rack.input' => '',
'rack.url_scheme' => 'http',
'SERVER_NAME' => 'server.example',
'QUERY_STRING' => 'code=xxxx',
'SCRIPT_NAME' => '',
'SERVER_PORT' => 80
}
end
context "when using a mobile browser" do
user_agents = {
:Pre => "Mozilla/5.0 (webOS/1.4.0; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.1",
:iPod => "Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A93 Safari/419.3",
:iPhone => "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3",
:iPad => "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10",
:Nexus => "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
:myTouch => "Mozilla/5.0 (Linux; U; Android 1.6; en-us; WOWMobile myTouch 3G Build/unknown) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1",
:Storm => "BlackBerry9530/4.7.0.148 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/105",
:Torch => "Mozilla/5.0 (BlackBerry; U; BlackBerry 9810; en-US) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.0.0 Mobile Safari/534.11+",
:generic_mobile => "some mobile device"
}
user_agents.each_pair do |name, agent|
context "with the user agent from a #{name.to_s}" do
before do
env['HTTP_USER_AGENT'] = agent
strategy.call!(env)
strategy.request_phase
end
subject {strategy.options}
it "sets the :display option to 'touch'" do
subject[:display].should == 'touch'
end
end
end
end
context "when using a desktop browser" do
user_agents = {
:Chrome => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21",
:Safari => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1",
:IE => "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
:anything_else => "unknown"
}
user_agents.each_pair do |name, agent|
context "with the user agent from #{name.to_s}" do
before do
env['HTTP_USER_AGENT'] = agent
strategy.call!(env)
strategy.request_phase
end
subject {strategy.options}
it "sets the :display option to 'page'" do
subject[:display].should == 'page'
end
end
end
end
end
describe "callback phase" do
raw_info = nil
before do
raw_info = {
'id' => 'salesforce id',
'display_name' => 'display name',
'email' => 'email',
'nick_name' => 'nick name',
'first_name' => 'first name',
'last_name' => 'last name',
'photos' => {'thumbnail' => '/thumbnail/url'},
'urls'=> {
"enterprise" => "https://salesforce.example/services",
"metadata" => "https://salesforce.example/services"
}
}
client = OAuth2::Client.new 'id', 'secret', {:site => 'example.com'}
access_token = OAuth2::AccessToken.from_hash client, {
'access_token' => 'token',
'instance_url' => 'http://instance.salesforce.example',
'signature' => 'invalid',
'issued_at' => '1296458209517'
}
strategy.stub(:raw_info) { raw_info }
strategy.stub(:access_token) { access_token }
end
describe "uid" do
it "sets the id" do
strategy.uid.should == raw_info['id']
end
end
describe "info" do
subject { strategy.info }
it "returns an info hash" do
subject.should_not be_nil
end
it "sets name" do
subject['name'].should == raw_info['display_name']
end
it "sets email" do
subject['email'].should == raw_info['email']
end
it "sets nickname" do
subject['nickname'].should == raw_info['nick_name']
end
it "sets first_name" do
subject['first_name'].should == raw_info['first_name']
end
it "sets last_name" do
subject['last_name'].should == raw_info['last_name']
end
it "sets location" do
subject['location'].should == ''
end
it "sets description" do
subject['description'].should == ''
end
it "sets image" do
subject['image'].should == raw_info['photos']['thumbnail'] + "?oauth_token=#{strategy.access_token.token}"
end
it "sets phone" do
subject['phone'].should == ''
end
it "sets urls" do
subject['urls'].should == raw_info['urls']
end
end
describe "credentials" do
subject { strategy.credentials }
it "sets token" do
subject['token'].should == strategy.access_token.token
end
it "sets instance_url" do
subject['instance_url'].should == strategy.access_token.params["instance_url"]
end
context "given a refresh token" do
it "sets refresh_token" do
subject['refresh_token'].should == strategy.access_token.refresh_token
end
end
context "when not given a refresh token" do
it "does not set a refresh token" do
subject['refresh_token'].should be_nil
end
end
end
describe "extra" do
subject { strategy.extra }
it "sets instance_url" do
subject['instance_url'].should == strategy.access_token.params['instance_url']
end
it "sets pod" do
subject['pod'].should == strategy.access_token.params['instance_url']
end
it "sets signature" do
subject['signature'].should == strategy.access_token.params['signature']
end
it "sets issued_at" do
subject['issued_at'].should == strategy.access_token.params['issued_at']
end
end
describe "user id validation" do
client_id = nil
issued_at = nil
signature = nil
instance_url = 'http://instance.salesforce.example'
before do
client_id = "https://login.salesforce.com/id/00Dd0000000d45TEBQ/005d0000000fyGPCCY"
issued_at = "1331142541514"
signature = Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', strategy.options.client_secret.to_s, client_id + issued_at))
end
context "when the signature does not match" do
before do
access_token = OAuth2::AccessToken.from_hash strategy.access_token.client, {
'id' => 'forged client id',
'issued_at' => issued_at,
'instance_url' => 'http://instance.salesforce.example',
'signature' => signature
}
strategy.stub(:access_token) { access_token }
end
it "should call fail!" do
strategy.should_receive(:fail!)
strategy.auth_hash
end
end
context "when the signature does match" do
before do
access_token = OAuth2::AccessToken.from_hash strategy.access_token.client, {
'id' => client_id,
'issued_at' => issued_at,
'instance_url' => 'http://instance.salesforce.example',
'signature' => signature
}
strategy.stub(:access_token) { access_token }
end
it "should not fail" do
strategy.should_not_receive(:fail!)
strategy.auth_hash
end
end
end
end
end
|
Course-Master/omniauth-salesforce
|
spec/omniauth/strategies/salesforce_spec.rb
|
Ruby
|
mit
| 7,540
|
<?php
namespace Illuminate\Tests\Integration\Auth;
use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\Gate;
use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser;
use Illuminate\Tests\Integration\Auth\Fixtures\Policies\AuthenticationTestUserPolicy;
/**
* @group integration
*/
class GatePolicyResolutionTest extends TestCase
{
public function testPolicyCanBeGuessedUsingClassConventions()
{
$this->assertInstanceOf(
AuthenticationTestUserPolicy::class,
Gate::getPolicyFor(AuthenticationTestUser::class)
);
}
public function testPolicyCanBeGuessedUsingCallback()
{
Gate::guessPolicyNamesUsing(function () {
return AuthenticationTestUserPolicy::class;
});
$this->assertInstanceOf(
AuthenticationTestUserPolicy::class,
Gate::getPolicyFor(AuthenticationTestUser::class)
);
}
public function testPolicyCanBeGuessedMultipleTimes()
{
Gate::guessPolicyNamesUsing(function () {
return [
'App\\Policies\\TestUserPolicy',
AuthenticationTestUserPolicy::class,
];
});
$this->assertInstanceOf(
AuthenticationTestUserPolicy::class,
Gate::getPolicyFor(AuthenticationTestUser::class)
);
}
}
|
cviebrock/framework
|
tests/Integration/Auth/GatePolicyResolutionTest.php
|
PHP
|
mit
| 1,369
|
<?php
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup UnaCore UNA Core
* @{
*/
require_once('./inc/header.inc.php');
require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
require_once(BX_DIRECTORY_PATH_INC . "utils.inc.php");
bx_import('BxDolLanguages');
$sObject = bx_process_input(bx_get('o'));
$sDisplay = bx_process_input(bx_get('d'));
$sAction = bx_process_input(bx_get('a'));
if(!empty($sAction))
$sAction = 'performAction' . bx_gen_method_name($sAction);
// try to create form object and call its method
if(!empty($sObject) && !empty($sDisplay) && !empty($sAction)) {
$oForm = BxTemplFormView::getObjectInstance($sObject, $sDisplay);
if($oForm && method_exists($oForm, $sAction))
$oForm->$sAction();
}
/** @} */
|
unaio/una
|
upgrade/files/11.0.4-12.0.0.B1/files/form.php
|
PHP
|
mit
| 819
|
import HasManyHelper from './has-many-helper';
import {module, test} from 'qunit';
module('Integration | ORM | hasMany #accessor');
/*
#association behavior works regardless of the state of the parent
*/
HasManyHelper.forEachScenario((scenario) => {
test(`the references of a ${scenario.title} are correct`, function(assert) {
let { parent, children, accessor, idsAccessor } = scenario.go();
assert.equal(parent[accessor].models.length, children.length, 'parent has correct number of children');
assert.equal(parent[idsAccessor].length, children.length, 'parent has correct number of child ids');
children.forEach(function(child, i) {
assert.deepEqual(parent[accessor].models[i], children[i], 'each child is in parent.children array');
if (!child.isNew()) {
assert.ok(parent[idsAccessor].indexOf(child.id) > -1, 'each saved child id is in parent.childrenIds array');
}
});
});
});
|
lazybensch/ember-cli-mirage
|
tests/integration/orm/has-many/accessor-test.js
|
JavaScript
|
mit
| 938
|
/**
* (c) 2010-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*/
/**
* Gets fired when the legend item belonging to a point is clicked. The default
* action is to toggle the visibility of the point. This can be prevented by
* returning `false` or calling `event.preventDefault()`.
*
* @callback Highcharts.PointLegendItemClickCallbackFunction
*
* @param {Highcharts.Point} this
* The point on which the event occured.
*
* @param {Highcharts.PointLegendItemClickEventObject} event
* The event that occured.
*/
/**
* Information about the legend click event.
*
* @interface Highcharts.PointLegendItemClickEventObject
*//**
* Related browser event.
* @name Highcharts.PointLegendItemClickEventObject#browserEvent
* @type {Highcharts.PointerEvent}
*//**
* Prevent the default action of toggle the visibility of the point.
* @name Highcharts.PointLegendItemClickEventObject#preventDefault
* @type {Function}
*//**
* Related point.
* @name Highcharts.PointLegendItemClickEventObject#target
* @type {Highcharts.Point}
*//**
* Event type.
* @name Highcharts.PointLegendItemClickEventObject#type
* @type {"legendItemClick"}
*/
/**
* Gets fired when the legend item belonging to a series is clicked. The default
* action is to toggle the visibility of the series. This can be prevented by
* returning `false` or calling `event.preventDefault()`.
*
* @callback Highcharts.SeriesLegendItemClickCallbackFunction
*
* @param {Highcharts.Series} this
* The series where the event occured.
*
* @param {Highcharts.SeriesLegendItemClickEventObject} event
* The event that occured.
*/
/**
* Information about the legend click event.
*
* @interface Highcharts.SeriesLegendItemClickEventObject
*//**
* Related browser event.
* @name Highcharts.SeriesLegendItemClickEventObject#browserEvent
* @type {Highcharts.PointerEvent}
*//**
* Prevent the default action of toggle the visibility of the series.
* @name Highcharts.SeriesLegendItemClickEventObject#preventDefault
* @type {Function}
*//**
* Related series.
* @name Highcharts.SeriesLegendItemClickEventObject#target
* @type {Highcharts.Series}
*//**
* Event type.
* @name Highcharts.SeriesLegendItemClickEventObject#type
* @type {"legendItemClick"}
*/
'use strict';
import Highcharts from './Globals.js';
import './Utilities.js';
var H = Highcharts,
addEvent = H.addEvent,
css = H.css,
discardElement = H.discardElement,
defined = H.defined,
fireEvent = H.fireEvent,
isFirefox = H.isFirefox,
marginNames = H.marginNames,
merge = H.merge,
pick = H.pick,
setAnimation = H.setAnimation,
stableSort = H.stableSort,
win = H.win,
wrap = H.wrap;
/**
* The overview of the chart's series. The legend object is instanciated
* internally in the chart constructor, and is available from the `chart.legend`
* property. Each chart has only one legend.
*
* @class
* @name Highcharts.Legend
*
* @param {Highcharts.Chart} chart
* The chart instance.
*
* @param {Highcharts.LegendOptions} options
* Legend options.
*/
Highcharts.Legend = function (chart, options) {
this.init(chart, options);
};
Highcharts.Legend.prototype = {
/**
* Initialize the legend.
*
* @private
* @function Highcharts.Legend#init
*
* @param {Highcharts.Chart} chart
* The chart instance.
*
* @param {Highcharts.LegendOptions} options
* Legend options.
*/
init: function (chart, options) {
/**
* Chart of this legend.
*
* @readonly
* @name Highcharts.Legend#chart
* @type {Highcharts.Chart}
*/
this.chart = chart;
this.setOptions(options);
if (options.enabled) {
// Render it
this.render();
// move checkboxes
addEvent(this.chart, 'endResize', function () {
this.legend.positionCheckboxes();
});
if (this.proximate) {
this.unchartrender = addEvent(
this.chart,
'render',
function () {
this.legend.proximatePositions();
this.legend.positionItems();
}
);
} else if (this.unchartrender) {
this.unchartrender();
}
}
},
/**
* @private
* @function Highcharts.Legend#setOptions
*
* @param {Highcharts.LegendOptions} options
*/
setOptions: function (options) {
var padding = pick(options.padding, 8);
/**
* Legend options.
*
* @readonly
* @name Highcharts.Legend#options
* @type {Highcharts.LegendOptions}
*/
this.options = options;
if (!this.chart.styledMode) {
this.itemStyle = options.itemStyle;
this.itemHiddenStyle = merge(
this.itemStyle,
options.itemHiddenStyle
);
}
this.itemMarginTop = options.itemMarginTop || 0;
this.padding = padding;
this.initialItemY = padding - 5; // 5 is pixels above the text
this.symbolWidth = pick(options.symbolWidth, 16);
this.pages = [];
this.proximate = options.layout === 'proximate' && !this.chart.inverted;
},
/**
* Update the legend with new options. Equivalent to running `chart.update`
* with a legend configuration option.
*
* @sample highcharts/legend/legend-update/
* Legend update
*
* @function Highcharts.Legend#update
*
* @param {Highcharts.LegendOptions} options
* Legend options.
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart after the axis is altered. If doing
* more operations on the chart, it is a good idea to set redraw to
* false and call {@link Chart#redraw} after.
* Whether to redraw the chart.
*
* @fires Highcharts.Legends#event:afterUpdate
*/
update: function (options, redraw) {
var chart = this.chart;
this.setOptions(merge(true, this.options, options));
this.destroy();
chart.isDirtyLegend = chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
fireEvent(this, 'afterUpdate');
},
/**
* Set the colors for the legend item.
*
* @private
* @function Highcharts.Legend#colorizeItem
*
* @param {Highcharts.Point|Highcharts.Series} item
* A Series or Point instance
*
* @param {boolean} [visible=false]
* Dimmed or colored
*
* @todo
* Make events official: Fires the event `afterColorizeItem`.
*/
colorizeItem: function (item, visible) {
item.legendGroup[visible ? 'removeClass' : 'addClass'](
'highcharts-legend-item-hidden'
);
if (!this.chart.styledMode) {
var legend = this,
options = legend.options,
legendItem = item.legendItem,
legendLine = item.legendLine,
legendSymbol = item.legendSymbol,
hiddenColor = legend.itemHiddenStyle.color,
textColor = visible ? options.itemStyle.color : hiddenColor,
symbolColor = visible ?
(item.color || hiddenColor) :
hiddenColor,
markerOptions = item.options && item.options.marker,
symbolAttr = { fill: symbolColor };
if (legendItem) {
legendItem.css({
fill: textColor,
color: textColor // #1553, oldIE
});
}
if (legendLine) {
legendLine.attr({ stroke: symbolColor });
}
if (legendSymbol) {
// Apply marker options
if (markerOptions && legendSymbol.isMarker) { // #585
symbolAttr = item.pointAttribs();
if (!visible) {
// #6769
symbolAttr.stroke = symbolAttr.fill = hiddenColor;
}
}
legendSymbol.attr(symbolAttr);
}
}
fireEvent(this, 'afterColorizeItem', { item: item, visible: visible });
},
/**
* @private
* @function Highcharts.Legend#positionItems
*/
positionItems: function () {
// Now that the legend width and height are established, put the items
// in the final position
this.allItems.forEach(this.positionItem, this);
if (!this.chart.isResizing) {
this.positionCheckboxes();
}
},
/**
* Position the legend item.
*
* @private
* @function Highcharts.Legend#positionItem
*
* @param {Highcharts.Point|Highcharts.Series} item
* The item to position
*/
positionItem: function (item) {
var legend = this,
options = legend.options,
symbolPadding = options.symbolPadding,
ltr = !options.rtl,
legendItemPos = item._legendItemPos,
itemX = legendItemPos[0],
itemY = legendItemPos[1],
checkbox = item.checkbox,
legendGroup = item.legendGroup;
if (legendGroup && legendGroup.element) {
legendGroup[defined(legendGroup.translateY) ? 'animate' : 'attr']({
translateX: ltr ?
itemX :
legend.legendWidth - itemX - 2 * symbolPadding - 4,
translateY: itemY
});
}
if (checkbox) {
checkbox.x = itemX;
checkbox.y = itemY;
}
},
/**
* Destroy a single legend item, used internally on removing series items.
*
* @private
* @function Highcharts.Legend#destroyItem
*
* @param {Highcharts.Point|Highcharts.Series} item
* The item to remove
*/
destroyItem: function (item) {
var checkbox = item.checkbox;
// destroy SVG elements
['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'].forEach(
function (key) {
if (item[key]) {
item[key] = item[key].destroy();
}
}
);
if (checkbox) {
discardElement(item.checkbox);
}
},
/**
* Destroy the legend. Used internally. To reflow objects, `chart.redraw`
* must be called after destruction.
*
* @private
* @function Highcharts.Legend#destroy
*/
destroy: function () {
function destroyItems(key) {
if (this[key]) {
this[key] = this[key].destroy();
}
}
// Destroy items
this.getAllItems().forEach(function (item) {
['legendItem', 'legendGroup'].forEach(destroyItems, item);
});
// Destroy legend elements
[
'clipRect',
'up',
'down',
'pager',
'nav',
'box',
'title',
'group'
].forEach(destroyItems, this);
this.display = null; // Reset in .render on update.
},
/**
* Position the checkboxes after the width is determined.
*
* @private
* @function Highcharts.Legend#positionCheckboxes
*/
positionCheckboxes: function () {
var alignAttr = this.group && this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight,
titleHeight = this.titleHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
this.allItems.forEach(function (item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = translateY + titleHeight + checkbox.y +
(this.scrollOffset || 0) + 3;
css(checkbox, {
left: (alignAttr.translateX + item.checkboxOffset +
checkbox.x - 20) + 'px',
top: top + 'px',
display: this.proximate || (
top > translateY - 6 &&
top < translateY + clipHeight - 6
) ?
'' :
'none'
});
}
}, this);
}
},
/**
* Render the legend title on top of the legend.
*
* @private
* @function Highcharts.Legend#renderTitle
*/
renderTitle: function () {
var options = this.options,
padding = this.padding,
titleOptions = options.title,
titleHeight = 0,
bBox;
if (titleOptions.text) {
if (!this.title) {
/**
* SVG element of the legend title.
*
* @readonly
* @name Highcharts.Legend#title
* @type {Highcharts.SVGElement}
*/
this.title = this.chart.renderer.label(
titleOptions.text,
padding - 3,
padding - 4,
null,
null,
null,
options.useHTML,
null,
'legend-title'
)
.attr({ zIndex: 1 });
if (!this.chart.styledMode) {
this.title.css(titleOptions.style);
}
this.title.add(this.group);
}
// Set the max title width (#7253)
if (!titleOptions.width) {
this.title.css({
width: this.maxLegendWidth + 'px'
});
}
bBox = this.title.getBBox();
titleHeight = bBox.height;
this.offsetWidth = bBox.width; // #1717
this.contentGroup.attr({ translateY: titleHeight });
}
this.titleHeight = titleHeight;
},
/**
* Set the legend item text.
*
* @function Highcharts.Legend#setText
*
* @param {Highcharts.Point|Highcharts.Series} item
* The item for which to update the text in the legend.
*/
setText: function (item) {
var options = this.options;
item.legendItem.attr({
text: options.labelFormat ?
H.format(options.labelFormat, item, this.chart.time) :
options.labelFormatter.call(item)
});
},
/**
* Render a single specific legend item. Called internally from the `render`
* function.
*
* @private
* @function Highcharts.Legend#renderItem
*
* @param {Highcharts.Point|Highcharts.Series} item
* The item to render.
*/
renderItem: function (item) {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
options = legend.options,
horizontal = options.layout === 'horizontal',
symbolWidth = legend.symbolWidth,
symbolPadding = options.symbolPadding,
itemStyle = legend.itemStyle,
itemHiddenStyle = legend.itemHiddenStyle,
itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
ltr = !options.rtl,
bBox,
li = item.legendItem,
isSeries = !item.series,
series = !isSeries && item.series.drawLegendSymbol ?
item.series :
item,
seriesOptions = series.options,
showCheckbox = legend.createCheckboxForItem &&
seriesOptions &&
seriesOptions.showCheckbox,
// full width minus text width
itemExtraWidth = symbolWidth + symbolPadding + itemDistance +
(showCheckbox ? 20 : 0),
useHTML = options.useHTML,
itemClassName = item.options.className;
if (!li) { // generate it once, later move it
// Generate the group box, a group to hold the symbol and text. Text
// is to be appended in Legend class.
item.legendGroup = renderer.g('legend-item')
.addClass(
'highcharts-' + series.type + '-series ' +
'highcharts-color-' + item.colorIndex +
(itemClassName ? ' ' + itemClassName : '') +
(isSeries ? ' highcharts-series-' + item.index : '')
)
.attr({ zIndex: 1 })
.add(legend.scrollGroup);
// Generate the list item text and add it to the group
item.legendItem = li = renderer.text(
'',
ltr ? symbolWidth + symbolPadding : -symbolPadding,
legend.baseline || 0,
useHTML
);
if (!chart.styledMode) {
// merge to prevent modifying original (#1021)
li.css(merge(item.visible ? itemStyle : itemHiddenStyle));
}
li.attr({
align: ltr ? 'left' : 'right',
zIndex: 2
})
.add(item.legendGroup);
// Get the baseline for the first item - the font size is equal for
// all
if (!legend.baseline) {
legend.fontMetrics = renderer.fontMetrics(
chart.styledMode ? 12 : itemStyle.fontSize,
li
);
legend.baseline =
legend.fontMetrics.f + 3 + legend.itemMarginTop;
li.attr('y', legend.baseline);
}
// Draw the legend symbol inside the group box
legend.symbolHeight = options.symbolHeight || legend.fontMetrics.f;
series.drawLegendSymbol(legend, item);
if (legend.setItemEvents) {
legend.setItemEvents(item, li, useHTML);
}
}
// Add the HTML checkbox on top
if (showCheckbox && !item.checkbox) {
legend.createCheckboxForItem(item);
}
// Colorize the items
legend.colorizeItem(item, item.visible);
// Take care of max width and text overflow (#6659)
if (chart.styledMode || !itemStyle.width) {
li.css({
width: (
options.itemWidth ||
legend.widthOption ||
chart.spacingBox.width
) - itemExtraWidth
});
}
// Always update the text
legend.setText(item);
// calculate the positions for the next line
bBox = li.getBBox();
item.itemWidth = item.checkboxOffset =
options.itemWidth ||
item.legendItemWidth ||
bBox.width + itemExtraWidth;
legend.maxItemWidth = Math.max(legend.maxItemWidth, item.itemWidth);
legend.totalItemWidth += item.itemWidth;
legend.itemHeight = item.itemHeight = Math.round(
item.legendItemHeight || bBox.height || legend.symbolHeight
);
},
/**
* Get the position of the item in the layout. We now know the
* maxItemWidth from the previous loop.
*
* @private
* @function Highcharts.Legend#layoutItem
*
* @param {Highcharts.Point|Highcharts.Series} item
*/
layoutItem: function (item) {
var options = this.options,
padding = this.padding,
horizontal = options.layout === 'horizontal',
itemHeight = item.itemHeight,
itemMarginBottom = options.itemMarginBottom || 0,
itemMarginTop = this.itemMarginTop,
itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
maxLegendWidth = this.maxLegendWidth,
itemWidth = (
options.alignColumns &&
this.totalItemWidth > maxLegendWidth
) ?
this.maxItemWidth :
item.itemWidth;
// If the item exceeds the width, start a new line
if (
horizontal &&
this.itemX - padding + itemWidth > maxLegendWidth
) {
this.itemX = padding;
if (this.lastLineHeight) { // Not for the first line (#10167)
this.itemY += (
itemMarginTop +
this.lastLineHeight +
itemMarginBottom
);
}
this.lastLineHeight = 0; // reset for next line (#915, #3976)
}
// Set the edge positions
this.lastItemY = itemMarginTop + this.itemY + itemMarginBottom;
this.lastLineHeight = Math.max( // #915
itemHeight,
this.lastLineHeight
);
// cache the position of the newly generated or reordered items
item._legendItemPos = [this.itemX, this.itemY];
// advance
if (horizontal) {
this.itemX += itemWidth;
} else {
this.itemY += itemMarginTop + itemHeight + itemMarginBottom;
this.lastLineHeight = itemHeight;
}
// the width of the widest item
this.offsetWidth = this.widthOption || Math.max(
(
horizontal ? this.itemX - padding - (item.checkbox ?
// decrease by itemDistance only when no checkbox #4853
0 :
itemDistance
) : itemWidth
) + padding,
this.offsetWidth
);
},
/**
* Get all items, which is one item per series for most series and one
* item per point for pie series and its derivatives.
*
* @private
* @function Highcharts.Legend#getAllItems
*
* @return {Array<Highcharts.Point|Highcharts.Series>}
* The current items in the legend.
*
* @fires Highcharts.Legend#event:afterGetAllItems
*
* @todo
* Make events official: Fires the event `afterGetAllItems`.
*/
getAllItems: function () {
var allItems = [];
this.chart.series.forEach(function (series) {
var seriesOptions = series && series.options;
// Handle showInLegend. If the series is linked to another series,
// defaults to false.
if (series && pick(
seriesOptions.showInLegend,
!defined(seriesOptions.linkedTo) ? undefined : false, true
)) {
// Use points or series for the legend item depending on
// legendType
allItems = allItems.concat(
series.legendItems ||
(
seriesOptions.legendType === 'point' ?
series.data :
series
)
);
}
});
fireEvent(this, 'afterGetAllItems', { allItems: allItems });
return allItems;
},
/**
* Get a short, three letter string reflecting the alignment and layout.
*
* @private
* @function Highcharts.Legend#getAlignment
*
* @return {string}
* The alignment, empty string if floating
*/
getAlignment: function () {
var options = this.options;
// Use the first letter of each alignment option in order to detect
// the side. (#4189 - use charAt(x) notation instead of [x] for IE7)
if (this.proximate) {
return options.align.charAt(0) + 'tv';
}
return options.floating ? '' : (
options.align.charAt(0) +
options.verticalAlign.charAt(0) +
options.layout.charAt(0)
);
},
/**
* Adjust the chart margins by reserving space for the legend on only one
* side of the chart. If the position is set to a corner, top or bottom is
* reserved for horizontal legends and left or right for vertical ones.
*
* @private
* @function Highcharts.Legend#adjustMargins
*
* @param {Array<number>} margin
*
* @param {number} spacing
*/
adjustMargins: function (margin, spacing) {
var chart = this.chart,
options = this.options,
alignment = this.getAlignment(),
titleMargin = chart.options.title.margin !== undefined ?
chart.titleOffset +
chart.options.title.margin :
0;
if (alignment) {
([
/(lth|ct|rth)/,
/(rtv|rm|rbv)/,
/(rbh|cb|lbh)/,
/(lbv|lm|ltv)/
]).forEach(function (alignments, side) {
if (alignments.test(alignment) && !defined(margin[side])) {
// Now we have detected on which side of the chart we should
// reserve space for the legend
chart[marginNames[side]] = Math.max(
chart[marginNames[side]],
(
chart.legend[
(side + 1) % 2 ? 'legendHeight' : 'legendWidth'
] +
[1, -1, -1, 1][side] * options[
(side % 2) ? 'x' : 'y'
] +
pick(options.margin, 12) +
spacing[side] +
(
side === 0 &&
(chart.titleOffset === 0 ? 0 : titleMargin)
) // #7428, #7894
)
);
}
});
}
},
/**
* @private
* @function Highcharts.Legend#proximatePositions
*/
proximatePositions: function () {
var chart = this.chart,
boxes = [],
alignLeft = this.options.align === 'left';
this.allItems.forEach(function (item) {
var lastPoint,
height,
useFirstPoint = alignLeft,
target,
top;
if (item.yAxis && item.points) {
if (item.xAxis.options.reversed) {
useFirstPoint = !useFirstPoint;
}
lastPoint = H.find(
useFirstPoint ?
item.points :
item.points.slice(0).reverse(),
function (item) {
return H.isNumber(item.plotY);
}
);
height = item.legendGroup.getBBox().height;
top = item.yAxis.top - chart.plotTop;
if (item.visible) {
target = lastPoint ? lastPoint.plotY : item.yAxis.height;
target += top - 0.3 * height;
} else {
target = top + item.yAxis.height;
}
boxes.push({
target: target,
size: height,
item: item
});
}
}, this);
H.distribute(boxes, chart.plotHeight);
boxes.forEach(function (box) {
box.item._legendItemPos[1] =
chart.plotTop - chart.spacing[0] + box.pos;
});
},
/**
* Render the legend. This method can be called both before and after
* `chart.render`. If called after, it will only rearrange items instead
* of creating new ones. Called internally on initial render and after
* redraws.
*
* @private
* @function Highcharts.Legend#render
*/
render: function () {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
legendGroup = legend.group,
allItems,
display,
legendWidth,
legendHeight,
box = legend.box,
options = legend.options,
padding = legend.padding,
alignTo,
allowedWidth,
y;
legend.itemX = padding;
legend.itemY = legend.initialItemY;
legend.offsetWidth = 0;
legend.lastItemY = 0;
legend.widthOption = H.relativeLength(
options.width,
chart.spacingBox.width - padding
);
// Compute how wide the legend is allowed to be
allowedWidth = chart.spacingBox.width - 2 * padding - options.x;
if (['rm', 'lm'].indexOf(legend.getAlignment().substring(0, 2)) > -1) {
allowedWidth /= 2;
}
legend.maxLegendWidth = legend.widthOption || allowedWidth;
if (!legendGroup) {
/**
* SVG group of the legend.
*
* @readonly
* @name Highcharts.Legend#group
* @type {Highcharts.SVGElement}
*/
legend.group = legendGroup = renderer.g('legend')
.attr({ zIndex: 7 })
.add();
legend.contentGroup = renderer.g()
.attr({ zIndex: 1 }) // above background
.add(legendGroup);
legend.scrollGroup = renderer.g()
.add(legend.contentGroup);
}
legend.renderTitle();
// add each series or point
allItems = legend.getAllItems();
// sort by legendIndex
stableSort(allItems, function (a, b) {
return ((a.options && a.options.legendIndex) || 0) -
((b.options && b.options.legendIndex) || 0);
});
// reversed legend
if (options.reversed) {
allItems.reverse();
}
/**
* All items for the legend, which is an array of series for most series
* and an array of points for pie series and its derivatives.
*
* @readonly
* @name Highcharts.Legend#allItems
* @type {Array<Highcharts.Point|Highcharts.Series>}
*/
legend.allItems = allItems;
legend.display = display = !!allItems.length;
// Render the items. First we run a loop to set the text and properties
// and read all the bounding boxes. The next loop computes the item
// positions based on the bounding boxes.
legend.lastLineHeight = 0;
legend.maxItemWidth = 0;
legend.totalItemWidth = 0;
legend.itemHeight = 0;
allItems.forEach(legend.renderItem, legend);
allItems.forEach(legend.layoutItem, legend);
// Get the box
legendWidth = (legend.widthOption || legend.offsetWidth) + padding;
legendHeight = legend.lastItemY + legend.lastLineHeight +
legend.titleHeight;
legendHeight = legend.handleOverflow(legendHeight);
legendHeight += padding;
// Draw the border and/or background
if (!box) {
/**
* SVG element of the legend box.
*
* @readonly
* @name Highcharts.Legend#box
* @type {Highcharts.SVGElement}
*/
legend.box = box = renderer.rect()
.addClass('highcharts-legend-box')
.attr({
r: options.borderRadius
})
.add(legendGroup);
box.isNew = true;
}
// Presentational
if (!chart.styledMode) {
box
.attr({
stroke: options.borderColor,
'stroke-width': options.borderWidth || 0,
fill: options.backgroundColor || 'none'
})
.shadow(options.shadow);
}
if (legendWidth > 0 && legendHeight > 0) {
box[box.isNew ? 'attr' : 'animate'](
box.crisp.call({}, { // #7260
x: 0,
y: 0,
width: legendWidth,
height: legendHeight
}, box.strokeWidth())
);
box.isNew = false;
}
// hide the border if no items
box[display ? 'show' : 'hide']();
// Open for responsiveness
if (chart.styledMode && legendGroup.getStyle('display') === 'none') {
legendWidth = legendHeight = 0;
}
legend.legendWidth = legendWidth;
legend.legendHeight = legendHeight;
if (display) {
// If aligning to the top and the layout is horizontal, adjust for
// the title (#7428)
alignTo = chart.spacingBox;
if (/(lth|ct|rth)/.test(legend.getAlignment())) {
y = alignTo.y + chart.titleOffset;
alignTo = merge(alignTo, {
y: chart.titleOffset > 0 ?
y += chart.options.title.margin : y
});
}
legendGroup.align(merge(options, {
width: legendWidth,
height: legendHeight,
verticalAlign: this.proximate ? 'top' : options.verticalAlign
}), true, alignTo);
}
if (!this.proximate) {
this.positionItems();
}
fireEvent(this, 'afterRender');
},
/**
* Set up the overflow handling by adding navigation with up and down arrows
* below the legend.
*
* @private
* @function Highcharts.Legend#handleOverflow
*
* @param {number} legendHeight
*
* @return {number}
*/
handleOverflow: function (legendHeight) {
var legend = this,
chart = this.chart,
renderer = chart.renderer,
options = this.options,
optionsY = options.y,
alignTop = options.verticalAlign === 'top',
padding = this.padding,
spaceHeight = chart.spacingBox.height +
(alignTop ? -optionsY : optionsY) - padding,
maxHeight = options.maxHeight,
clipHeight,
clipRect = this.clipRect,
navOptions = options.navigation,
animation = pick(navOptions.animation, true),
arrowSize = navOptions.arrowSize || 12,
nav = this.nav,
pages = this.pages,
lastY,
allItems = this.allItems,
clipToHeight = function (height) {
if (typeof height === 'number') {
clipRect.attr({
height: height
});
} else if (clipRect) { // Reset (#5912)
legend.clipRect = clipRect.destroy();
legend.contentGroup.clip();
}
// useHTML
if (legend.contentGroup.div) {
legend.contentGroup.div.style.clip = height ?
'rect(' + padding + 'px,9999px,' +
(padding + height) + 'px,0)' :
'auto';
}
},
addTracker = function (key) {
legend[key] = renderer
.circle(0, 0, arrowSize * 1.3)
.translate(arrowSize / 2, arrowSize / 2)
.add(nav);
if (!chart.styledMode) {
legend[key].attr('fill', 'rgba(0,0,0,0.0001)');
}
return legend[key];
};
// Adjust the height
if (
options.layout === 'horizontal' &&
options.verticalAlign !== 'middle' &&
!options.floating
) {
spaceHeight /= 2;
}
if (maxHeight) {
spaceHeight = Math.min(spaceHeight, maxHeight);
}
// Reset the legend height and adjust the clipping rectangle
pages.length = 0;
if (legendHeight > spaceHeight && navOptions.enabled !== false) {
this.clipHeight = clipHeight =
Math.max(spaceHeight - 20 - this.titleHeight - padding, 0);
this.currentPage = pick(this.currentPage, 1);
this.fullHeight = legendHeight;
// Fill pages with Y positions so that the top of each a legend item
// defines the scroll top for each page (#2098)
allItems.forEach(function (item, i) {
var y = item._legendItemPos[1],
h = Math.round(item.legendItem.getBBox().height),
len = pages.length;
if (!len || (y - pages[len - 1] > clipHeight &&
(lastY || y) !== pages[len - 1])) {
pages.push(lastY || y);
len++;
}
// Keep track of which page each item is on
item.pageIx = len - 1;
if (lastY) {
allItems[i - 1].pageIx = len - 1;
}
if (
i === allItems.length - 1 &&
y + h - pages[len - 1] > clipHeight &&
y !== lastY // #2617
) {
pages.push(y);
item.pageIx = len;
}
if (y !== lastY) {
lastY = y;
}
});
// Only apply clipping if needed. Clipping causes blurred legend in
// PDF export (#1787)
if (!clipRect) {
clipRect = legend.clipRect =
renderer.clipRect(0, padding, 9999, 0);
legend.contentGroup.clip(clipRect);
}
clipToHeight(clipHeight);
// Add navigation elements
if (!nav) {
this.nav = nav = renderer.g()
.attr({ zIndex: 1 })
.add(this.group);
this.up = renderer
.symbol(
'triangle',
0,
0,
arrowSize,
arrowSize
)
.add(nav);
addTracker('upTracker')
.on('click', function () {
legend.scroll(-1, animation);
});
this.pager = renderer.text('', 15, 10)
.addClass('highcharts-legend-navigation');
if (!chart.styledMode) {
this.pager.css(navOptions.style);
}
this.pager.add(nav);
this.down = renderer
.symbol(
'triangle-down',
0,
0,
arrowSize,
arrowSize
)
.add(nav);
addTracker('downTracker')
.on('click', function () {
legend.scroll(1, animation);
});
}
// Set initial position
legend.scroll(0);
legendHeight = spaceHeight;
// Reset
} else if (nav) {
clipToHeight();
this.nav = nav.destroy(); // #6322
this.scrollGroup.attr({
translateY: 1
});
this.clipHeight = 0; // #1379
}
return legendHeight;
},
/**
* Scroll the legend by a number of pages.
*
* @private
* @function Highcharts.Legend#scroll
*
* @param {number} scrollBy
* The number of pages to scroll.
*
* @param {Highcharts.AnimationOptionsObject} animation
* Whether and how to apply animation.
*/
scroll: function (scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
pager = this.pager,
padding = this.padding;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== undefined) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: 'visible'
});
[this.up, this.upTracker].forEach(function (elem) {
elem.attr({
'class': currentPage === 1 ?
'highcharts-legend-nav-inactive' :
'highcharts-legend-nav-active'
});
});
pager.attr({
text: currentPage + '/' + pageCount
});
[this.down, this.downTracker].forEach(function (elem) {
elem.attr({
// adjust to text width
'x': 18 + this.pager.getBBox().width,
'class': currentPage === pageCount ?
'highcharts-legend-nav-inactive' :
'highcharts-legend-nav-active'
});
}, this);
if (!this.chart.styledMode) {
this.up
.attr({
fill: currentPage === 1 ?
navOptions.inactiveColor :
navOptions.activeColor
});
this.upTracker
.css({
cursor: currentPage === 1 ? 'default' : 'pointer'
});
this.down
.attr({
fill: currentPage === pageCount ?
navOptions.inactiveColor :
navOptions.activeColor
});
this.downTracker
.css({
cursor: currentPage === pageCount ?
'default' :
'pointer'
});
}
this.scrollOffset = -pages[currentPage - 1] + this.initialItemY;
this.scrollGroup.animate({
translateY: this.scrollOffset
});
this.currentPage = currentPage;
this.positionCheckboxes();
}
}
};
/**
* Legend symbol mixin.
*
* @private
* @mixin Highcharts.LegendSymbolMixin
*/
H.LegendSymbolMixin = {
/**
* Get the series' symbol in the legend
*
* @private
* @function Highcharts.LegendSymbolMixin.drawRectangle
*
* @param {Highcharts.Legend} legend
* The legend object
*
* @param {Highcharts.Point|Highcharts.Series} item
* The series (this) or point
*/
drawRectangle: function (legend, item) {
var options = legend.options,
symbolHeight = legend.symbolHeight,
square = options.squareSymbol,
symbolWidth = square ? symbolHeight : legend.symbolWidth;
item.legendSymbol = this.chart.renderer.rect(
square ? (legend.symbolWidth - symbolHeight) / 2 : 0,
legend.baseline - symbolHeight + 1, // #3988
symbolWidth,
symbolHeight,
pick(legend.options.symbolRadius, symbolHeight / 2)
)
.addClass('highcharts-point')
.attr({
zIndex: 3
}).add(item.legendGroup);
},
/**
* Get the series' symbol in the legend. This method should be overridable
* to create custom symbols through
* Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
*
* @private
* @function Highcharts.LegendSymbolMixin.drawLineMarker
*
* @param {Highcharts.Legend} legend
* The legend object.
*/
drawLineMarker: function (legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendSymbol,
symbolWidth = legend.symbolWidth,
symbolHeight = legend.symbolHeight,
generalRadius = symbolHeight / 2,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline -
Math.round(legend.fontMetrics.b * 0.3),
attr = {};
// Draw the line
if (!this.chart.styledMode) {
attr = {
'stroke-width': options.lineWidth || 0
};
if (options.dashStyle) {
attr.dashstyle = options.dashStyle;
}
}
this.legendLine = renderer.path([
'M',
0,
verticalCenter,
'L',
symbolWidth,
verticalCenter
])
.addClass('highcharts-graph')
.attr(attr)
.add(legendItemGroup);
// Draw the marker
if (markerOptions && markerOptions.enabled !== false && symbolWidth) {
// Do not allow the marker to be larger than the symbolHeight
radius = Math.min(
pick(markerOptions.radius, generalRadius),
generalRadius
);
// Restrict symbol markers size
if (this.symbol.indexOf('url') === 0) {
markerOptions = merge(markerOptions, {
width: symbolHeight,
height: symbolHeight
});
radius = 0;
}
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius,
markerOptions
)
.addClass('highcharts-point')
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
}
};
// Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
// and for #2580, a similar drawing flaw in Firefox 26.
// Explore if there's a general cause for this. The problem may be related
// to nested group elements, as the legend item texts are within 4 group
// elements.
if (
/Trident\/7\.0/.test(win.navigator && win.navigator.userAgent) ||
isFirefox
) {
wrap(Highcharts.Legend.prototype, 'positionItem', function (proceed, item) {
var legend = this,
// If chart destroyed in sync, this is undefined (#2030)
runPositionItem = function () {
if (item._legendItemPos) {
proceed.call(legend, item);
}
};
// Do it now, for export and to get checkbox placement
runPositionItem();
// Do it after to work around the core issue
if (!legend.bubbleLegend) {
setTimeout(runPositionItem);
}
});
}
|
joeyparrish/cdnjs
|
ajax/libs/highcharts/7.1.0/es-modules/parts/Legend.js
|
JavaScript
|
mit
| 47,686
|
<?php
namespace SleepingOwl\Admin\Form\Element;
class Radio extends Select
{
}
|
Asvae/SleepingOwlAdmin
|
src/Form/Element/Radio.php
|
PHP
|
mit
| 81
|
#!/usr/bin/env python
"""
This module contains the :class:`Column` class, which defines a "vertical"
array of tabular data. Whereas :class:`.Row` instances are independent of their
parent :class:`.Table`, columns depend on knowledge of both their position in
the parent (column name, data type) as well as the rows that contain their data.
"""
import six
from agate.mapped_sequence import MappedSequence
from agate.utils import NullOrder, memoize
if six.PY3: # pragma: no cover
# pylint: disable=W0622
xrange = range
def null_handler(k):
"""
Key method for sorting nulls correctly.
"""
if k is None:
return NullOrder()
return k
class Column(MappedSequence):
"""
Proxy access to column data. Instances of :class:`Column` should
not be constructed directly. They are created by :class:`.Table`
instances and are unique to them.
Columns are implemented as subclass of :class:`.MappedSequence`. They
deviate from the underlying implementation in that loading of their data
is deferred until it is needed.
:param name:
The name of this column.
:param data_type:
An instance of :class:`.DataType`.
:param rows:
A :class:`.MappedSequence` that contains the :class:`.Row` instances
containing the data for this column.
:param row_names:
An optional list of row names (keys) for this column.
"""
__slots__ = ['_index', '_name', '_data_type', '_rows', '_row_names']
def __init__(self, index, name, data_type, rows, row_names=None):
self._index = index
self._name = name
self._data_type = data_type
self._rows = rows
self._keys = row_names
def __getstate__(self):
"""
Return state values to be pickled.
This is necessary on Python2.7 when using :code:`__slots__`.
"""
return {
'_index': self._index,
'_name': self._name,
'_data_type': self._data_type,
'_rows': self._rows,
'_keys': self._keys
}
def __setstate__(self, data):
"""
Restore pickled state.
This is necessary on Python2.7 when using :code:`__slots__`.
"""
self._index = data['_index']
self._name = data['_name']
self._data_type = data['_data_type']
self._rows = data['_rows']
self._keys = data['_keys']
@property
def index(self):
"""
This column's index.
"""
return self._index
@property
def name(self):
"""
This column's name.
"""
return self._name
@property
def data_type(self):
"""
This column's data type.
"""
return self._data_type
@memoize
def values(self):
"""
Get the values in this column, as a tuple.
"""
return tuple(row[self._index] for row in self._rows)
@memoize
def values_distinct(self):
"""
Get the distinct values in this column, as a tuple.
"""
return tuple(set(self.values()))
@memoize
def values_without_nulls(self):
"""
Get the values in this column with any null values removed.
"""
return tuple(d for d in self.values() if d is not None)
@memoize
def values_sorted(self):
"""
Get the values in this column sorted.
"""
return sorted(self.values(), key=null_handler)
@memoize
def values_without_nulls_sorted(self):
"""
Get the values in this column with any null values removed and sorted.
"""
return sorted(self.values_without_nulls(), key=null_handler)
|
flother/agate
|
agate/columns.py
|
Python
|
mit
| 3,731
|
<!DOCTYPE html>
<html>
<head>
<title>Neon</title>
<script src="../neon.js" type="text/javascript"></script>
<script src="../stdlib/node_support.js" type="text/javascript"></script>
<script src="../stdlib/custom_event.js" type="text/javascript"></script>
<script src="../stdlib/custom_event_support.js" type="text/javascript"></script>
<script src="../stdlib/bubbling_support.js" type="text/javascript"></script>
<script src="neon_stdlib_test.js" type="text/javascript"></script>
</head>
<body>
<h1>Neon</h1>
</body>
</html>
|
escusado/neon
|
test/neon_stdlib_browser.html
|
HTML
|
mit
| 556
|
/*!
* # Semantic UI 2.7.1 - Checkbox
* http://github.com/semantic-org/semantic-ui/
*
*
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
'use strict';
$.isFunction = $.isFunction || function(obj) {
return typeof obj === "function" && typeof obj.nodeType !== "number";
};
window = (typeof window != 'undefined' && window.Math == Math)
? window
: (typeof self != 'undefined' && self.Math == Math)
? self
: Function('return this')()
;
$.fn.checkbox = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = $.extend(true, {}, $.fn.checkbox.settings, parameters),
className = settings.className,
namespace = settings.namespace,
selector = settings.selector,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$label = $(this).children(selector.label),
$input = $(this).children(selector.input),
input = $input[0],
initialLoad = false,
shortcutPressed = false,
instance = $module.data(moduleNamespace),
observer,
element = this,
module
;
module = {
initialize: function() {
module.verbose('Initializing checkbox', settings);
module.create.label();
module.bind.events();
module.set.tabbable();
module.hide.input();
module.observeChanges();
module.instantiate();
module.setup();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying module');
module.unbind.events();
module.show.input();
$module.removeData(moduleNamespace);
},
fix: {
reference: function() {
if( $module.is(selector.input) ) {
module.debug('Behavior called on <input> adjusting invoked element');
$module = $module.closest(selector.checkbox);
module.refresh();
}
}
},
setup: function() {
module.set.initialLoad();
if( module.is.indeterminate() ) {
module.debug('Initial value is indeterminate');
module.indeterminate();
}
else if( module.is.checked() ) {
module.debug('Initial value is checked');
module.check();
}
else {
module.debug('Initial value is unchecked');
module.uncheck();
}
module.remove.initialLoad();
},
refresh: function() {
$label = $module.children(selector.label);
$input = $module.children(selector.input);
input = $input[0];
},
hide: {
input: function() {
module.verbose('Modifying <input> z-index to be unselectable');
$input.addClass(className.hidden);
}
},
show: {
input: function() {
module.verbose('Modifying <input> z-index to be selectable');
$input.removeClass(className.hidden);
}
},
observeChanges: function() {
if('MutationObserver' in window) {
observer = new MutationObserver(function(mutations) {
module.debug('DOM tree modified, updating selector cache');
module.refresh();
});
observer.observe(element, {
childList : true,
subtree : true
});
module.debug('Setting up mutation observer', observer);
}
},
attachEvents: function(selector, event) {
var
$element = $(selector)
;
event = $.isFunction(module[event])
? module[event]
: module.toggle
;
if($element.length > 0) {
module.debug('Attaching checkbox events to element', selector, event);
$element
.on('click' + eventNamespace, event)
;
}
else {
module.error(error.notFound);
}
},
event: {
change: function(event) {
if( !module.should.ignoreCallbacks() ) {
settings.onChange.call(input);
}
},
click: function(event) {
var
$target = $(event.target)
;
if( $target.is(selector.input) ) {
module.verbose('Using default check action on initialized checkbox');
return;
}
if( $target.is(selector.link) ) {
module.debug('Clicking link inside checkbox, skipping toggle');
return;
}
module.toggle();
$input.focus();
event.preventDefault();
},
keydown: function(event) {
var
key = event.which,
keyCode = {
enter : 13,
space : 32,
escape : 27,
left : 37,
up : 38,
right : 39,
down : 40
}
;
var r = module.get.radios(),
rIndex = r.index($module),
rLen = r.length,
checkIndex = false;
if(key == keyCode.left || key == keyCode.up) {
checkIndex = (rIndex === 0 ? rLen : rIndex) - 1;
} else if(key == keyCode.right || key == keyCode.down) {
checkIndex = rIndex === rLen-1 ? 0 : rIndex+1;
}
if (!module.should.ignoreCallbacks() && checkIndex !== false) {
if(!settings.beforeUnchecked.apply(input)) {
module.verbose('Option not allowed to be unchecked, cancelling key navigation');
return false;
}
if (!settings.beforeChecked.apply($(r[checkIndex]).children(selector.input)[0])) {
module.verbose('Next option should not allow check, cancelling key navigation');
return false;
}
}
if(key == keyCode.escape) {
module.verbose('Escape key pressed blurring field');
$input.blur();
shortcutPressed = true;
}
else if(!event.ctrlKey && ( key == keyCode.space || key == keyCode.enter) ) {
module.verbose('Enter/space key pressed, toggling checkbox');
module.toggle();
shortcutPressed = true;
}
else {
shortcutPressed = false;
}
},
keyup: function(event) {
if(shortcutPressed) {
event.preventDefault();
}
}
},
check: function() {
if( !module.should.allowCheck() ) {
return;
}
module.debug('Checking checkbox', $input);
module.set.checked();
if( !module.should.ignoreCallbacks() ) {
settings.onChecked.call(input);
settings.onChange.call(input);
}
},
uncheck: function() {
if( !module.should.allowUncheck() ) {
return;
}
module.debug('Unchecking checkbox');
module.set.unchecked();
if( !module.should.ignoreCallbacks() ) {
settings.onUnchecked.call(input);
settings.onChange.call(input);
}
},
indeterminate: function() {
if( module.should.allowIndeterminate() ) {
module.debug('Checkbox is already indeterminate');
return;
}
module.debug('Making checkbox indeterminate');
module.set.indeterminate();
if( !module.should.ignoreCallbacks() ) {
settings.onIndeterminate.call(input);
settings.onChange.call(input);
}
},
determinate: function() {
if( module.should.allowDeterminate() ) {
module.debug('Checkbox is already determinate');
return;
}
module.debug('Making checkbox determinate');
module.set.determinate();
if( !module.should.ignoreCallbacks() ) {
settings.onDeterminate.call(input);
settings.onChange.call(input);
}
},
enable: function() {
if( module.is.enabled() ) {
module.debug('Checkbox is already enabled');
return;
}
module.debug('Enabling checkbox');
module.set.enabled();
settings.onEnable.call(input);
// preserve legacy callbacks
settings.onEnabled.call(input);
},
disable: function() {
if( module.is.disabled() ) {
module.debug('Checkbox is already disabled');
return;
}
module.debug('Disabling checkbox');
module.set.disabled();
settings.onDisable.call(input);
// preserve legacy callbacks
settings.onDisabled.call(input);
},
get: {
radios: function() {
var
name = module.get.name()
;
return $('input[name="' + name + '"]').closest(selector.checkbox);
},
otherRadios: function() {
return module.get.radios().not($module);
},
name: function() {
return $input.attr('name');
}
},
is: {
initialLoad: function() {
return initialLoad;
},
radio: function() {
return ($input.hasClass(className.radio) || $input.attr('type') == 'radio');
},
indeterminate: function() {
return $input.prop('indeterminate') !== undefined && $input.prop('indeterminate');
},
checked: function() {
return $input.prop('checked') !== undefined && $input.prop('checked');
},
disabled: function() {
return $input.prop('disabled') !== undefined && $input.prop('disabled');
},
enabled: function() {
return !module.is.disabled();
},
determinate: function() {
return !module.is.indeterminate();
},
unchecked: function() {
return !module.is.checked();
}
},
should: {
allowCheck: function() {
if(module.is.determinate() && module.is.checked() && !module.is.initialLoad() ) {
module.debug('Should not allow check, checkbox is already checked');
return false;
}
if(!module.should.ignoreCallbacks() && settings.beforeChecked.apply(input) === false) {
module.debug('Should not allow check, beforeChecked cancelled');
return false;
}
return true;
},
allowUncheck: function() {
if(module.is.determinate() && module.is.unchecked() && !module.is.initialLoad() ) {
module.debug('Should not allow uncheck, checkbox is already unchecked');
return false;
}
if(!module.should.ignoreCallbacks() && settings.beforeUnchecked.apply(input) === false) {
module.debug('Should not allow uncheck, beforeUnchecked cancelled');
return false;
}
return true;
},
allowIndeterminate: function() {
if(module.is.indeterminate() && !module.is.initialLoad() ) {
module.debug('Should not allow indeterminate, checkbox is already indeterminate');
return false;
}
if(!module.should.ignoreCallbacks() && settings.beforeIndeterminate.apply(input) === false) {
module.debug('Should not allow indeterminate, beforeIndeterminate cancelled');
return false;
}
return true;
},
allowDeterminate: function() {
if(module.is.determinate() && !module.is.initialLoad() ) {
module.debug('Should not allow determinate, checkbox is already determinate');
return false;
}
if(!module.should.ignoreCallbacks() && settings.beforeDeterminate.apply(input) === false) {
module.debug('Should not allow determinate, beforeDeterminate cancelled');
return false;
}
return true;
},
ignoreCallbacks: function() {
return (initialLoad && !settings.fireOnInit);
}
},
can: {
change: function() {
return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') || $input.prop('readonly') );
},
uncheck: function() {
return (typeof settings.uncheckable === 'boolean')
? settings.uncheckable
: !module.is.radio()
;
}
},
set: {
initialLoad: function() {
initialLoad = true;
},
checked: function() {
module.verbose('Setting class to checked');
$module
.removeClass(className.indeterminate)
.addClass(className.checked)
;
if( module.is.radio() ) {
module.uncheckOthers();
}
if(!module.is.indeterminate() && module.is.checked()) {
module.debug('Input is already checked, skipping input property change');
return;
}
module.verbose('Setting state to checked', input);
$input
.prop('indeterminate', false)
.prop('checked', true)
;
module.trigger.change();
},
unchecked: function() {
module.verbose('Removing checked class');
$module
.removeClass(className.indeterminate)
.removeClass(className.checked)
;
if(!module.is.indeterminate() && module.is.unchecked() ) {
module.debug('Input is already unchecked');
return;
}
module.debug('Setting state to unchecked');
$input
.prop('indeterminate', false)
.prop('checked', false)
;
module.trigger.change();
},
indeterminate: function() {
module.verbose('Setting class to indeterminate');
$module
.addClass(className.indeterminate)
;
if( module.is.indeterminate() ) {
module.debug('Input is already indeterminate, skipping input property change');
return;
}
module.debug('Setting state to indeterminate');
$input
.prop('indeterminate', true)
;
module.trigger.change();
},
determinate: function() {
module.verbose('Removing indeterminate class');
$module
.removeClass(className.indeterminate)
;
if( module.is.determinate() ) {
module.debug('Input is already determinate, skipping input property change');
return;
}
module.debug('Setting state to determinate');
$input
.prop('indeterminate', false)
;
},
disabled: function() {
module.verbose('Setting class to disabled');
$module
.addClass(className.disabled)
;
if( module.is.disabled() ) {
module.debug('Input is already disabled, skipping input property change');
return;
}
module.debug('Setting state to disabled');
$input
.prop('disabled', 'disabled')
;
module.trigger.change();
},
enabled: function() {
module.verbose('Removing disabled class');
$module.removeClass(className.disabled);
if( module.is.enabled() ) {
module.debug('Input is already enabled, skipping input property change');
return;
}
module.debug('Setting state to enabled');
$input
.prop('disabled', false)
;
module.trigger.change();
},
tabbable: function() {
module.verbose('Adding tabindex to checkbox');
if( $input.attr('tabindex') === undefined) {
$input.attr('tabindex', 0);
}
}
},
remove: {
initialLoad: function() {
initialLoad = false;
}
},
trigger: {
change: function() {
var
events = document.createEvent('HTMLEvents'),
inputElement = $input[0]
;
if(inputElement) {
module.verbose('Triggering native change event');
events.initEvent('change', true, false);
inputElement.dispatchEvent(events);
}
}
},
create: {
label: function() {
if($input.prevAll(selector.label).length > 0) {
$input.prev(selector.label).detach().insertAfter($input);
module.debug('Moving existing label', $label);
}
else if( !module.has.label() ) {
$label = $('<label>').insertAfter($input);
module.debug('Creating label', $label);
}
}
},
has: {
label: function() {
return ($label.length > 0);
}
},
bind: {
events: function() {
module.verbose('Attaching checkbox events');
$module
.on('click' + eventNamespace, module.event.click)
.on('change' + eventNamespace, module.event.change)
.on('keydown' + eventNamespace, selector.input, module.event.keydown)
.on('keyup' + eventNamespace, selector.input, module.event.keyup)
;
}
},
unbind: {
events: function() {
module.debug('Removing events');
$module
.off(eventNamespace)
;
}
},
uncheckOthers: function() {
var
$radios = module.get.otherRadios()
;
module.debug('Unchecking other radios', $radios);
$radios.removeClass(className.checked);
},
toggle: function() {
if( !module.can.change() ) {
if(!module.is.radio()) {
module.debug('Checkbox is read-only or disabled, ignoring toggle');
}
return;
}
if( module.is.indeterminate() || module.is.unchecked() ) {
module.debug('Currently unchecked');
module.check();
}
else if( module.is.checked() && module.can.uncheck() ) {
module.debug('Currently checked');
module.uncheck();
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
if($.isPlainObject(settings[name])) {
$.extend(true, settings[name], value);
}
else {
settings[name] = value;
}
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(!settings.silent && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(!settings.silent && settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
if(!settings.silent) {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
}
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if(Array.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.checkbox.settings = {
name : 'Checkbox',
namespace : 'checkbox',
silent : false,
debug : false,
verbose : true,
performance : true,
// delegated event context
uncheckable : 'auto',
fireOnInit : false,
onChange : function(){},
beforeChecked : function(){},
beforeUnchecked : function(){},
beforeDeterminate : function(){},
beforeIndeterminate : function(){},
onChecked : function(){},
onUnchecked : function(){},
onDeterminate : function() {},
onIndeterminate : function() {},
onEnable : function(){},
onDisable : function(){},
// preserve misspelled callbacks (will be removed in 3.0)
onEnabled : function(){},
onDisabled : function(){},
className : {
checked : 'checked',
indeterminate : 'indeterminate',
disabled : 'disabled',
hidden : 'hidden',
radio : 'radio',
readOnly : 'read-only'
},
error : {
method : 'The method you called is not defined'
},
selector : {
checkbox : '.ui.checkbox',
label : 'label, .box',
input : 'input[type="checkbox"], input[type="radio"]',
link : 'a[href]'
}
};
})( jQuery, window, document );
|
extend1994/cdnjs
|
ajax/libs/fomantic-ui/2.7.1/components/checkbox.js
|
JavaScript
|
mit
| 27,502
|
/* Tabulator v4.2.3 (c) Oliver Folkerd */
/*
* This file is part of the Tabulator package.
*
* (c) Oliver Folkerd <oliver.folkerd@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Full Documentation & Demos can be found at: http://olifolkerd.github.io/tabulator/
*
*/
(function (factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
})(function ($, undefined) {
$.widget("ui.tabulator", {
_create: function _create() {
this.table = new Tabulator(this.element[0], this.options);
//map tabulator functions to jquery wrapper
for (var key in Tabulator.prototype) {
if (typeof Tabulator.prototype[key] === "function" && key.charAt(0) !== "_") {
this[key] = this.table[key].bind(this.table);
}
}
},
_setOption: function _setOption(option, value) {
console.error("Tabulator jQuery wrapper does not support setting options after the table has been instantiated");
},
_destroy: function _destroy(option, value) {
this.table.destroy();
}
});
});
|
extend1994/cdnjs
|
ajax/libs/tabulator/4.2.3/js/jquery_wrapper.js
|
JavaScript
|
mit
| 1,340
|
package info.bitrich.xchangestream.hitbtc.dto;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.core.AllOf.allOf;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.TimeZone;
import org.hamcrest.Matcher;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Created by Pavel Chertalev on 19.03.2018. */
@RunWith(Parameterized.class)
public class HitbtcMessageTest {
private static final Logger LOG = LoggerFactory.getLogger(HitbtcMessageTest.class);
private final Class<?> clazz;
private final Matcher<String> matcher;
private final String testResource;
private final ObjectMapper objectMapper;
public HitbtcMessageTest(Class<?> clazz, Matcher<String> matcher, String testResource) {
this.clazz = clazz;
this.matcher = matcher;
this.testResource = testResource;
this.objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
SimpleModule module = new SimpleModule();
module.addSerializer(BigDecimal.class, new ToStringSerializer());
SimpleDateFormat customFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
customFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
module.addSerializer(Date.class, new DateSerializer(false, customFormat));
objectMapper.registerModule(module);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@Test
public void test() throws IOException, URISyntaxException {
LOG.info("Testing {} message...", testResource);
String message =
new String(
Files.readAllBytes(Paths.get(getClass().getResource(testResource).toURI())),
StandardCharsets.UTF_8);
Object object = objectMapper.readValue(message, clazz);
Assert.assertNotNull(object);
message = objectMapper.writeValueAsString(object);
LOG.info(message);
assertThat(message, matcher);
}
@Parameterized.Parameters
@SuppressWarnings("unchecked")
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][] {
{
HitbtcWebSocketSubscriptionMessage.class,
allOf(
hasJsonPath("$.method", equalTo("subscribeTicker")),
hasJsonPath("$.id", equalTo(123)),
hasJsonPath("$.params.symbol", equalTo("ETHBTC"))),
"/example/subscriptionMessage.json"
},
{
HitbtcWebSocketTickerTransaction.class,
allOf(
hasJsonPath("$.method", equalTo("ticker")),
hasJsonPath("$.params.ask", equalTo("0.054464")),
hasJsonPath("$.params.bid", equalTo("0.054463")),
hasJsonPath("$.params.last", equalTo("0.054463")),
hasJsonPath("$.params.open", equalTo("0.057133")),
hasJsonPath("$.params.low", equalTo("0.053615")),
hasJsonPath("$.params.high", equalTo("0.057559")),
hasJsonPath("$.params.volume", equalTo("33068.346")),
hasJsonPath("$.params.volumeQuote", equalTo("1832.687530809")),
hasJsonPath("$.params.timestamp", equalTo("2017-10-19T15:45:44.941Z")),
hasJsonPath("$.params.symbol", equalTo("ETHBTC"))),
"/example/notificationTicker.json"
},
{
HitbtcWebSocketTradesTransaction.class,
allOf(
hasJsonPath("$.method", equalTo("snapshotTrades")),
hasJsonPath("$.params.data[0].id", equalTo("54469456")),
hasJsonPath("$.params.data[0].price", equalTo("0.054656")),
hasJsonPath("$.params.data[0].quantity", equalTo("0.057")),
hasJsonPath("$.params.data[0].side", equalTo("buy")),
hasJsonPath("$.params.data[0].timestamp", equalTo("2017-10-19T16:33:42.821Z")),
hasJsonPath("$.params.data[2].id", equalTo("54469697")),
hasJsonPath("$.params.data[2].price", equalTo("0.054669")),
hasJsonPath("$.params.data[2].quantity", equalTo("0.002")),
hasJsonPath("$.params.data[2].side", equalTo("buy")),
hasJsonPath("$.params.data[2].timestamp", equalTo("2017-10-19T16:34:13.288Z")),
hasJsonPath("$.params.symbol", equalTo("ETHBTC"))),
"/example/notificationSnapshotTrades.json"
},
{
HitbtcWebSocketOrderBookTransaction.class,
allOf(
hasJsonPath("$.method", equalTo("snapshotOrderbook")),
hasJsonPath("$.params.ask[0].price", equalTo("0.054588")),
hasJsonPath("$.params.ask[0].size", equalTo("0.245")),
hasJsonPath("$.params.ask[1].price", equalTo("0.054590")),
hasJsonPath("$.params.ask[1].size", equalTo("0.000")),
hasJsonPath("$.params.bid[0].price", equalTo("0.054558")),
hasJsonPath("$.params.bid[0].size", equalTo("0.500")),
hasJsonPath("$.params.bid[1].price", equalTo("0.054557")),
hasJsonPath("$.params.bid[1].size", equalTo("0.076")),
hasJsonPath("$.params.sequence", equalTo(8073827)),
hasJsonPath("$.params.symbol", equalTo("ETHBTC"))),
"/example/notificationSnapshotOrderBook.json"
}
});
}
}
|
stachon/XChange
|
xchange-stream-hitbtc/src/test/java/info/bitrich/xchangestream/hitbtc/dto/HitbtcMessageTest.java
|
Java
|
mit
| 6,233
|
#include "f2c.h"
#include "blaswrap.h"
/* Table of constant values */
static integer c__0 = 0;
static doublereal c_b7 = 1.;
static integer c__1 = 1;
static integer c_n1 = -1;
/* Subroutine */ int dlasd1_(integer *nl, integer *nr, integer *sqre,
doublereal *d__, doublereal *alpha, doublereal *beta, doublereal *u,
integer *ldu, doublereal *vt, integer *ldvt, integer *idxq, integer *
iwork, doublereal *work, integer *info)
{
/* System generated locals */
integer u_dim1, u_offset, vt_dim1, vt_offset, i__1;
doublereal d__1, d__2;
/* Local variables */
integer i__, k, m, n, n1, n2, iq, iz, iu2, ldq, idx, ldu2, ivt2, idxc,
idxp, ldvt2;
extern /* Subroutine */ int dlasd2_(integer *, integer *, integer *,
integer *, doublereal *, doublereal *, doublereal *, doublereal *,
doublereal *, integer *, doublereal *, integer *, doublereal *,
doublereal *, integer *, doublereal *, integer *, integer *,
integer *, integer *, integer *, integer *, integer *), dlasd3_(
integer *, integer *, integer *, integer *, doublereal *,
doublereal *, integer *, doublereal *, doublereal *, integer *,
doublereal *, integer *, doublereal *, integer *, doublereal *,
integer *, integer *, integer *, doublereal *, integer *),
dlascl_(char *, integer *, integer *, doublereal *, doublereal *,
integer *, integer *, doublereal *, integer *, integer *),
dlamrg_(integer *, integer *, doublereal *, integer *, integer *,
integer *);
integer isigma;
extern /* Subroutine */ int xerbla_(char *, integer *);
doublereal orgnrm;
integer coltyp;
/* -- LAPACK auxiliary routine (version 3.1) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* DLASD1 computes the SVD of an upper bidiagonal N-by-M matrix B, */
/* where N = NL + NR + 1 and M = N + SQRE. DLASD1 is called from DLASD0. */
/* A related subroutine DLASD7 handles the case in which the singular */
/* values (and the singular vectors in factored form) are desired. */
/* DLASD1 computes the SVD as follows: */
/* ( D1(in) 0 0 0 ) */
/* B = U(in) * ( Z1' a Z2' b ) * VT(in) */
/* ( 0 0 D2(in) 0 ) */
/* = U(out) * ( D(out) 0) * VT(out) */
/* where Z' = (Z1' a Z2' b) = u' VT', and u is a vector of dimension M */
/* with ALPHA and BETA in the NL+1 and NL+2 th entries and zeros */
/* elsewhere; and the entry b is empty if SQRE = 0. */
/* The left singular vectors of the original matrix are stored in U, and */
/* the transpose of the right singular vectors are stored in VT, and the */
/* singular values are in D. The algorithm consists of three stages: */
/* The first stage consists of deflating the size of the problem */
/* when there are multiple singular values or when there are zeros in */
/* the Z vector. For each such occurence the dimension of the */
/* secular equation problem is reduced by one. This stage is */
/* performed by the routine DLASD2. */
/* The second stage consists of calculating the updated */
/* singular values. This is done by finding the square roots of the */
/* roots of the secular equation via the routine DLASD4 (as called */
/* by DLASD3). This routine also calculates the singular vectors of */
/* the current problem. */
/* The final stage consists of computing the updated singular vectors */
/* directly using the updated singular values. The singular vectors */
/* for the current problem are multiplied with the singular vectors */
/* from the overall problem. */
/* Arguments */
/* ========= */
/* NL (input) INTEGER */
/* The row dimension of the upper block. NL >= 1. */
/* NR (input) INTEGER */
/* The row dimension of the lower block. NR >= 1. */
/* SQRE (input) INTEGER */
/* = 0: the lower block is an NR-by-NR square matrix. */
/* = 1: the lower block is an NR-by-(NR+1) rectangular matrix. */
/* The bidiagonal matrix has row dimension N = NL + NR + 1, */
/* and column dimension M = N + SQRE. */
/* D (input/output) DOUBLE PRECISION array, */
/* dimension (N = NL+NR+1). */
/* On entry D(1:NL,1:NL) contains the singular values of the */
/* upper block; and D(NL+2:N) contains the singular values of */
/* the lower block. On exit D(1:N) contains the singular values */
/* of the modified matrix. */
/* ALPHA (input/output) DOUBLE PRECISION */
/* Contains the diagonal element associated with the added row. */
/* BETA (input/output) DOUBLE PRECISION */
/* Contains the off-diagonal element associated with the added */
/* row. */
/* U (input/output) DOUBLE PRECISION array, dimension(LDU,N) */
/* On entry U(1:NL, 1:NL) contains the left singular vectors of */
/* the upper block; U(NL+2:N, NL+2:N) contains the left singular */
/* vectors of the lower block. On exit U contains the left */
/* singular vectors of the bidiagonal matrix. */
/* LDU (input) INTEGER */
/* The leading dimension of the array U. LDU >= max( 1, N ). */
/* VT (input/output) DOUBLE PRECISION array, dimension(LDVT,M) */
/* where M = N + SQRE. */
/* On entry VT(1:NL+1, 1:NL+1)' contains the right singular */
/* vectors of the upper block; VT(NL+2:M, NL+2:M)' contains */
/* the right singular vectors of the lower block. On exit */
/* VT' contains the right singular vectors of the */
/* bidiagonal matrix. */
/* LDVT (input) INTEGER */
/* The leading dimension of the array VT. LDVT >= max( 1, M ). */
/* IDXQ (output) INTEGER array, dimension(N) */
/* This contains the permutation which will reintegrate the */
/* subproblem just solved back into sorted order, i.e. */
/* D( IDXQ( I = 1, N ) ) will be in ascending order. */
/* IWORK (workspace) INTEGER array, dimension( 4 * N ) */
/* WORK (workspace) DOUBLE PRECISION array, dimension( 3*M**2 + 2*M ) */
/* INFO (output) INTEGER */
/* = 0: successful exit. */
/* < 0: if INFO = -i, the i-th argument had an illegal value. */
/* > 0: if INFO = 1, an singular value did not converge */
/* Further Details */
/* =============== */
/* Based on contributions by */
/* Ming Gu and Huan Ren, Computer Science Division, University of */
/* California at Berkeley, USA */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Test the input parameters. */
/* Parameter adjustments */
--d__;
u_dim1 = *ldu;
u_offset = 1 + u_dim1;
u -= u_offset;
vt_dim1 = *ldvt;
vt_offset = 1 + vt_dim1;
vt -= vt_offset;
--idxq;
--iwork;
--work;
/* Function Body */
*info = 0;
if (*nl < 1) {
*info = -1;
} else if (*nr < 1) {
*info = -2;
} else if (*sqre < 0 || *sqre > 1) {
*info = -3;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("DLASD1", &i__1);
return 0;
}
n = *nl + *nr + 1;
m = n + *sqre;
/* The following values are for bookkeeping purposes only. They are */
/* integer pointers which indicate the portion of the workspace */
/* used by a particular array in DLASD2 and DLASD3. */
ldu2 = n;
ldvt2 = m;
iz = 1;
isigma = iz + m;
iu2 = isigma + n;
ivt2 = iu2 + ldu2 * n;
iq = ivt2 + ldvt2 * m;
idx = 1;
idxc = idx + n;
coltyp = idxc + n;
idxp = coltyp + n;
/* Scale. */
/* Computing MAX */
d__1 = abs(*alpha), d__2 = abs(*beta);
orgnrm = max(d__1,d__2);
d__[*nl + 1] = 0.;
i__1 = n;
for (i__ = 1; i__ <= i__1; ++i__) {
if ((d__1 = d__[i__], abs(d__1)) > orgnrm) {
orgnrm = (d__1 = d__[i__], abs(d__1));
}
/* L10: */
}
dlascl_("G", &c__0, &c__0, &orgnrm, &c_b7, &n, &c__1, &d__[1], &n, info);
*alpha /= orgnrm;
*beta /= orgnrm;
/* Deflate singular values. */
dlasd2_(nl, nr, sqre, &k, &d__[1], &work[iz], alpha, beta, &u[u_offset],
ldu, &vt[vt_offset], ldvt, &work[isigma], &work[iu2], &ldu2, &
work[ivt2], &ldvt2, &iwork[idxp], &iwork[idx], &iwork[idxc], &
idxq[1], &iwork[coltyp], info);
/* Solve Secular Equation and update singular vectors. */
ldq = k;
dlasd3_(nl, nr, sqre, &k, &d__[1], &work[iq], &ldq, &work[isigma], &u[
u_offset], ldu, &work[iu2], &ldu2, &vt[vt_offset], ldvt, &work[
ivt2], &ldvt2, &iwork[idxc], &iwork[coltyp], &work[iz], info);
if (*info != 0) {
return 0;
}
/* Unscale. */
dlascl_("G", &c__0, &c__0, &c_b7, &orgnrm, &n, &c__1, &d__[1], &n, info);
/* Prepare the IDXQ sorting permutation. */
n1 = k;
n2 = n - k;
dlamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &idxq[1]);
return 0;
/* End of DLASD1 */
} /* dlasd1_ */
|
dacap/loseface
|
third_party/clapack/SRC/dlasd1.c
|
C
|
mit
| 9,310
|
/* Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _PLATFORM_APQ8084_IOMAP_H_
#define _PLATFORM_APQ8084_IOMAP_H_
#define MSM_SHARED_BASE 0x0FA00000
#define MSM_SHARED_IMEM_BASE 0xFE805000
#define RESTART_REASON_ADDR (MSM_SHARED_IMEM_BASE + 0x65C)
#define KPSS_BASE 0xF9000000
#define MSM_GIC_DIST_BASE KPSS_BASE
#define MSM_GIC_CPU_BASE (KPSS_BASE + 0x2000)
#define APCS_KPSS_ACS_BASE (KPSS_BASE + 0x00008000)
#define APCS_APC_KPSS_PLL_BASE (KPSS_BASE + 0x0000A000)
#define APCS_KPSS_CFG_BASE (KPSS_BASE + 0x00010000)
#define APCS_KPSS_WDT_BASE (KPSS_BASE + 0x00017000)
#define KPSS_APCS_QTMR_AC_BASE (KPSS_BASE + 0x00020000)
#define KPSS_APCS_F0_QTMR_V1_BASE (KPSS_BASE + 0x00021000)
#define QTMR_BASE KPSS_APCS_F0_QTMR_V1_BASE
#define PERIPH_SS_BASE 0xF9800000
#define MSM_SDC1_BASE (PERIPH_SS_BASE + 0x00024000)
#define MSM_SDC1_SDHCI_BASE (PERIPH_SS_BASE + 0x00024900)
#define MSM_SDC3_BASE (PERIPH_SS_BASE + 0x00064000)
#define MSM_SDC3_SDHCI_BASE (PERIPH_SS_BASE + 0x00064900)
#define MSM_SDC2_BASE (PERIPH_SS_BASE + 0x000A4000)
#define MSM_SDC2_SDHCI_BASE (PERIPH_SS_BASE + 0x000A4900)
#define MSM_SDC4_BASE (PERIPH_SS_BASE + 0x000E4000)
#define MSM_SDC4_SDHCI_BASE (PERIPH_SS_BASE + 0x000E4900)
#define BLSP1_UART0_BASE (PERIPH_SS_BASE + 0x0011D000)
#define BLSP1_UART1_BASE (PERIPH_SS_BASE + 0x0011E000)
#define BLSP1_UART2_BASE (PERIPH_SS_BASE + 0x0011F000)
#define BLSP1_UART3_BASE (PERIPH_SS_BASE + 0x00120000)
#define BLSP1_UART4_BASE (PERIPH_SS_BASE + 0x00121000)
#define BLSP1_UART5_BASE (PERIPH_SS_BASE + 0x00122000)
#define CLK_CTL_BASE 0xFC400000
/* GPLL */
#define GPLL0_STATUS (CLK_CTL_BASE + 0x001C)
#define APCS_GPLL_ENA_VOTE (CLK_CTL_BASE + 0x1480)
#define APCS_CLOCK_BRANCH_ENA_VOTE (CLK_CTL_BASE + 0x1484)
/* UART */
#define BLSP1_AHB_CBCR (CLK_CTL_BASE + 0x5C4)
#define BLSP2_AHB_CBCR (CLK_CTL_BASE + 0x944)
#define BLSP1_UART2_APPS_CBCR (CLK_CTL_BASE + 0x704)
#define BLSP1_UART2_APPS_CMD_RCGR (CLK_CTL_BASE + 0x70C)
#define BLSP1_UART2_APPS_CFG_RCGR (CLK_CTL_BASE + 0x710)
#define BLSP1_UART2_APPS_M (CLK_CTL_BASE + 0x714)
#define BLSP1_UART2_APPS_N (CLK_CTL_BASE + 0x718)
#define BLSP1_UART2_APPS_D (CLK_CTL_BASE + 0x71C)
/* USB */
#define USB_HS_BCR (CLK_CTL_BASE + 0x480)
#define USB_HS_SYSTEM_CBCR (CLK_CTL_BASE + 0x484)
#define USB_HS_AHB_CBCR (CLK_CTL_BASE + 0x488)
#define USB_HS_SYSTEM_CMD_RCGR (CLK_CTL_BASE + 0x490)
#define USB_HS_SYSTEM_CFG_RCGR (CLK_CTL_BASE + 0x494)
/* SDCC */
#define SDCC1_BCR (CLK_CTL_BASE + 0x4C0) /* block reset */
#define SDCC1_APPS_CBCR (CLK_CTL_BASE + 0x4C4) /* branch control */
#define SDCC1_AHB_CBCR (CLK_CTL_BASE + 0x4C8)
#define SDCC1_CMD_RCGR (CLK_CTL_BASE + 0x4D0) /* cmd */
#define SDCC1_CFG_RCGR (CLK_CTL_BASE + 0x4D4) /* cfg */
#define SDCC1_M (CLK_CTL_BASE + 0x4D8) /* m */
#define SDCC1_N (CLK_CTL_BASE + 0x4DC) /* n */
#define SDCC1_D (CLK_CTL_BASE + 0x4E0) /* d */
#define SDCC1_CDCCAL_SLEEP_CBCR (CLK_CTL_BASE + 0x4E4)
/* Addresses below this point needs to be verified.
* Included only for compilation purposes.
*/
#define MSM_USB_BASE (PERIPH_SS_BASE + 0x00255000)
#define CLK_CTL_BASE 0xFC400000
#define GCC_WDOG_DEBUG (CLK_CTL_BASE + 0x00001780)
#define USB_HS_BCR (CLK_CTL_BASE + 0x480)
#define SPMI_BASE 0xFC4C0000
#define SPMI_GENI_BASE (SPMI_BASE + 0xA000)
#define SPMI_PIC_BASE (SPMI_BASE + 0xB000)
#define MSM_CE2_BAM_BASE 0xFD444000
#define MSM_CE2_BASE 0xFD45A000
#define USB2_PHY_SEL 0xFD4AB000
#define TLMM_BASE_ADDR 0xFD510000
#define GPIO_CONFIG_ADDR(x) (TLMM_BASE_ADDR + 0x1000 + (x)*0x10)
#define GPIO_IN_OUT_ADDR(x) (TLMM_BASE_ADDR + 0x1004 + (x)*0x10)
#define MPM2_MPM_CTRL_BASE 0xFC4A1000
#define MPM2_MPM_PS_HOLD 0xFC4AB000
#define MPM2_MPM_SLEEP_TIMETICK_COUNT_VAL 0xFC4A3000
/* DRV strength for sdcc */
#define SDC1_HDRV_PULL_CTL (TLMM_BASE_ADDR + 0x00002044)
/* SDHCI */
#define SDCC_MCI_HC_MODE (0x00000078)
#define SDCC_HC_PWRCTL_STATUS_REG (0x000000DC)
#define SDCC_HC_PWRCTL_MASK_REG (0x000000E0)
#define SDCC_HC_PWRCTL_CLEAR_REG (0x000000E4)
#define SDCC_HC_PWRCTL_CTL_REG (0x000000E8)
/* mdss */
#define MSM_MMSS_CLK_CTL_BASE 0xFD8C0000
#define MIPI_DSI_BASE (0xFD922800)
#define MIPI_DSI0_BASE (MIPI_DSI_BASE)
#define MIPI_DSI1_BASE (0xFD922E00)
#define REG_DSI(off) (MIPI_DSI_BASE + 0x04 + (off))
#define MDP_BASE (0xfd900000)
#define REG_MDP(off) (MDP_BASE + (off))
#define SOFT_RESET 0x118
#define CLK_CTRL 0x11C
#define TRIG_CTRL 0x084
#define CTRL 0x004
#define COMMAND_MODE_DMA_CTRL 0x03C
#define COMMAND_MODE_MDP_CTRL 0x040
#define COMMAND_MODE_MDP_DCS_CMD_CTRL 0x044
#define COMMAND_MODE_MDP_STREAM0_CTRL 0x058
#define COMMAND_MODE_MDP_STREAM0_TOTAL 0x05C
#define COMMAND_MODE_MDP_STREAM1_CTRL 0x060
#define COMMAND_MODE_MDP_STREAM1_TOTAL 0x064
#define ERR_INT_MASK0 0x10C
#define LANE_SWAP_CTL 0x0B0
#define TIMING_CTL 0x0C4
#define VIDEO_MODE_ACTIVE_H 0x024
#define VIDEO_MODE_ACTIVE_V 0x028
#define VIDEO_MODE_TOTAL 0x02C
#define VIDEO_MODE_HSYNC 0x030
#define VIDEO_MODE_VSYNC 0x034
#define VIDEO_MODE_VSYNC_VPOS 0x038
#define MDP_VP_0_RGB_0_BASE REG_MDP(0x2200)
#define MDP_VP_0_RGB_1_BASE REG_MDP(0x2600)
#define MDP_VP_0_MIXER_0_BASE REG_MDP(0x3A00)
#define MDP_VP_0_MIXER_1_BASE REG_MDP(0x3E00)
#define DMA_CMD_OFFSET 0x048
#define DMA_CMD_LENGTH 0x04C
#define INT_CTRL 0x110
#define CMD_MODE_DMA_SW_TRIGGER 0x090
#define EOT_PACKET_CTRL 0x0CC
#define MISR_CMD_CTRL 0x0A0
#define MISR_VIDEO_CTRL 0x0A4
#define VIDEO_MODE_CTRL 0x010
#define HS_TIMER_CTRL 0x0BC
#endif
|
lg-devs/g2-bootloader
|
platform/apq8084/include/platform/iomap.h
|
C
|
mit
| 8,245
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package clases;
/**
*
* @author ANDRES
*/
public class Persona {
protected String nombres;
protected String apellidos;
protected String direccion;
protected String ciudad;
protected String telefono;
protected String RFC;
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Persona(String nombres, String apellidos, String direccion, String ciudad, String telefono, String RFC) {
this.nombres = nombres;
this.apellidos = apellidos;
this.direccion = direccion;
this.ciudad = ciudad;
this.telefono = telefono;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
}
|
julio101290/JuliusCaesarERP
|
JulioCesarERP/src/clases/Persona.java
|
Java
|
mit
| 1,479
|
'use strict';
module.exports = {
name: 'ember-cli-legacy-blueprints'
};
|
gabz75/ember-cli-deploy-redis-publish
|
node_modules/ember-cli-legacy-blueprints/index.js
|
JavaScript
|
mit
| 75
|
using System.Data.Entity;
using System.Reflection;
using Abp.EntityFramework;
using Abp.Modules;
using AbpCompanyName.AbpProjectName.EntityFramework;
namespace AbpCompanyName.AbpProjectName
{
[DependsOn(typeof(AbpEntityFrameworkModule), typeof(AbpProjectNameCoreModule))]
public class AbpProjectNameDataModule : AbpModule
{
public override void PreInitialize()
{
Configuration.DefaultNameOrConnectionString = "Default";
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
Database.SetInitializer<AbpProjectNameDbContext>(null);
}
}
}
|
nicklv/aspnetboilerplate-templates
|
src/AbpCompanyName.AbpProjectName.EntityFramework/AbpProjectNameDataModule.cs
|
C#
|
mit
| 699
|
---
url: /security
classes: topic-page
title: Auth0 Security Fundamentals
description: Learn about various topics regarding how to handle sensitive data when using Auth0 services.
---
<div class="topic-page-header">
<div data-name="example" class="topic-page-badge"></div>
<h1>Auth0 Security Fundamentals</h1>
<p>
Learn about various topics regarding how to handle sensitive data when using Auth0 services.
</p>
</div>
## Handling Tokens
<%= include('../_includes/_topic-links', { links: [
'security/store-tokens',
'security/token-exp',
'tokens/refresh-token'
] }) %>
## Preventing Security Attacks
<%= include('../_includes/_topic-links', { links: [
'security/common-threats'
] }) %>
|
hamzawi06/docs
|
articles/security/index.md
|
Markdown
|
mit
| 711
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Bootstrap · Content moved</title>
<link rel="canonical" href="https://martijncuppens.github.io/bootstrap-mixins-documentation/bootstrap-mixins-documentation/docs/4.1/getting-started/introduction/">
<meta http-equiv="refresh" content="0; url=https://martijncuppens.github.io/bootstrap-mixins-documentation/bootstrap-mixins-documentation/docs/4.1/getting-started/introduction/">
<meta name="robots" content="noindex">
<style>
html {
display: flex;
align-items: center;
justify-content: center;
margin: 0;
width: 100vw;
height: 100vh;
text-align: center;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
h1 {
margin-top: 0;
margin-bottom: .5rem;
}
a {
color: #007bff;
text-decoration: none;
}
</style>
</head>
<body>
<h1>Redirecting…</h1>
<a href="https://martijncuppens.github.io/bootstrap-mixins-documentation/bootstrap-mixins-documentation/docs/4.1/getting-started/introduction/">Click here if you are not redirected</a>
<script>window.location="https://martijncuppens.github.io/bootstrap-mixins-documentation/bootstrap-mixins-documentation/docs/4.1/getting-started/introduction/";</script>
</body>
</html>
|
MartijnCuppens/MartijnCuppens.github.io
|
bootstrap-mixins-documentation/docs/index.html
|
HTML
|
mit
| 1,578
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Composition;
namespace News.Helpers.Composition.ImageLoader
{
public interface IManagedSurface : IDisposable
{
IImageLoader ImageLoader { get; }
ICompositionSurface Surface { get; }
Uri Source { get; }
Size Size { get; }
IAsyncAction RedrawSurface();
IAsyncAction RedrawSurface(Uri uri);
IAsyncAction RedrawSurface(Uri uri, Size size);
void Resize(Size size);
}
class ManagedSurface : IManagedSurface
{
private IImageLoaderInternal _imageLoader;
private CompositionDrawingSurface _surface;
private Uri _uri;
public IImageLoader ImageLoader
{
get
{
return _imageLoader;
}
}
public ICompositionSurface Surface
{
get
{
return _surface;
}
}
public Uri Source
{
get
{
return _uri;
}
}
public Size Size
{
get
{
if (_surface != null)
{
return _surface.Size;
}
else
{
return Size.Empty;
}
}
}
public ManagedSurface(IImageLoaderInternal imageLoader, Uri uri, Size size)
{
_imageLoader = imageLoader;
_uri = uri;
_surface = _imageLoader.CreateSurface(size);
_imageLoader.DeviceReplacedEvent += OnDeviceReplaced;
}
private async void OnDeviceReplaced(object sender, object e)
{
Debug.WriteLine("CompositionImageLoader - Redrawing ManagedSurface from Device Replaced");
await RedrawSurface();
}
public IAsyncAction RedrawSurface()
{
return RedrawSurfaceWorker(_uri, Size.Empty).AsAsyncAction();
}
public IAsyncAction RedrawSurface(Uri uri)
{
return RedrawSurfaceWorker(uri, Size.Empty).AsAsyncAction();
}
public IAsyncAction RedrawSurface(Uri uri, Size size)
{
return RedrawSurfaceWorker(uri, size).AsAsyncAction();
}
public void Resize(Size size)
{
_imageLoader.ResizeSurface(_surface, size);
}
private async Task RedrawSurfaceWorker(Uri uri, Size size)
{
_uri = uri;
await _imageLoader.DrawSurface(_surface, _uri, size);
}
public void Dispose()
{
_surface.Dispose();
_imageLoader.DeviceReplacedEvent -= OnDeviceReplaced;
_surface = null;
_imageLoader = null;
_uri = null;
}
}
}
|
josephIDM/josephworkouts
|
apps/music/Music.UWP/Composition/ImageLoader/ManagedSurface.cs
|
C#
|
mit
| 3,003
|
<a href='https://github.com/angular/angular.js/edit/v1.3.x/src/ng/directive/ngEventDirs.js?message=docs(ngClick)%3A%20describe%20your%20change...#L3' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.3.8/src/ng/directive/ngEventDirs.js#L3' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">ngClick</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
- directive in module <a href="api/ng">ng</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>The ngClick directive allows you to specify custom behavior when
an element is clicked.</p>
</div>
<div>
<h2>Directive Info</h2>
<ul>
<li>This directive executes at priority level 0.</li>
</ul>
<h2 id="usage">Usage</h2>
<div class="usage">
<ul>
<li>as attribute:
<pre><code><ANY ng-click=""> ... </ANY></code></pre>
</li>
</div>
<section class="api-section">
<h3>Arguments</h3>
<table class="variables-matrix input-arguments">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
ngClick
</td>
<td>
<a href="" class="label type-hint type-hint-expression">expression</a>
</td>
<td>
<p><a href="guide/expression">Expression</a> to evaluate upon
click. (<a href="guide/expression#-event-">Event object is available as <code>$event</code></a>)</p>
</td>
</tr>
</tbody>
</table>
</section>
<h2 id="example">Example</h2><p>
<div>
<a ng-click="openPlunkr('examples/example-example68')" class="btn pull-right">
<i class="glyphicon glyphicon-edit"> </i>
Edit in Plunker</a>
<div class="runnable-example"
path="examples/example-example68">
<div class="runnable-example-file"
name="index.html"
language="html"
type="html">
<pre><code><button ng-click="count = count + 1" ng-init="count=0"> Increment </button> <span> count: {{count}} </span></code></pre>
</div>
<div class="runnable-example-file"
name="protractor.js"
type="protractor"
language="js">
<pre><code>it('should check ng-click', function() { expect(element(by.binding('count')).getText()).toMatch('0'); element(by.css('button')).click(); expect(element(by.binding('count')).getText()).toMatch('1'); });</code></pre>
</div>
<iframe class="runnable-example-frame" src="examples/example-example68/index.html" name="example-example68"></iframe>
</div>
</div>
</p>
</div>
|
ariborneo/Phalcon-development
|
public/assets/plugins/angular/docs/partials/api/ng/directive/ngClick.html
|
HTML
|
mit
| 3,032
|
Before you make the config, please upgrade your NexT version to v6.0.6 or greater.
Please note the difference between **site config file** and **theme config file**
---
# Sign up to Leancloud and create an app
- Go to Leancloud website [leancloud.cn](leancloud.cn) and sign up to Leancloud. Then login.
- Click `1` to enter the console:

- Then click `1` to create an app:

- Type your app name in `1` in the pop up window(eg. "test"), then choose `2`, which means developer's plan, and then click `3` to create the app:

# Create Counter class and enable plugin in NexT
- Click `1`(app name) to enter the app manage page:

- then click `1` to create a class for counter:

- Type `Counter` in the pop up window in `1`, check `2`, then click `3`:

- Click `1` to enter the app setting, then click `2`:

- Paste `App ID` and `App Key` to **theme config file**`_config.yml` like this:
```yml
leancloud_visitors:
enable: true
app_id: <<your app id>>
app_key: <<your app key>>
# Dependencies: https://github.com/theme-next/hexo-leancloud-counter-security
security: true
betterPerformance: false
```
- Set domain whitelist: Click`1`, then type your domain into `2`(**protocol, domain and port should be exactly the same**):

# Deploy web engine to avoid your data being changed illegally
- Click `1 -> 2 -> 3` by order

- Click`1`:

- In the pop up window, click `1` to choose type `Hook`, then choose`beforeUpdate` in `2`, choose `Counter` in `3`. Paste code below into `4`, then click `5` to save it:
```javascript
var query = new AV.Query("Counter");
if (request.object.updatedKeys.indexOf('time') !== -1) {
return query.get(request.object.id).then(function (obj) {
if (obj.get("time") + 1 !== request.object.get("time")) {
throw new AV.Cloud.Error('Invalid update!');
}
})
}
```

- Click `1` to deploy after the message in the red rect shows up:

- Click `1` in the pop up:

- Click `1` to close the pop up window after the message in the red rect shows up:

# Set access control for your database
- Open **theme config file**`_config.yml`, set `leancloud_visitors: security` to `true`:
```yml
leancloud_visitors:
enable: true
app_id: <<your app id>>
app_key: <<your app key>>
# Dependencies: https://github.com/theme-next/hexo-leancloud-counter-security
security: true
betterPerformance: false
```
**Explaination for `betterPerformance`:**
Because the Leancloud developer's plan has limits in requst thread amount and running time, counter number may be very slow to load in some times. If set `betterPerformance` to true, counter number will be displayed quickly by assuming the request is accepted normally.
- Open cmd then switch to **root path of site**, type commands to install `hexo-leancloud-counter-security` plugin:
```
npm install hexo-leancloud-counter-security --save
```
- Open **site config file**`_config.yml`, add those config:
```yml
leancloud_counter_security:
enable_sync: true
app_id: <<your app id>>
app_key: <<your app key>
username:
password:
```
- Type command:
```
hexo lc-counter register <<username>> <<password>>
```
or
```
hexo lc-counter r <<username>> <<password>>
```
Change `<<username>>` and `<<password>>` to your own username and password (no need to be the same as leancloud account). They will be used in the hexo deploying.
- Open **site config file**`_config.yml`, change `<<username>>` and `<<password>>`to those you set above:
```yml
leancloud_counter_security:
enable_sync: true
app_id: <<your app id>>
app_key: <<your app key>
username: <<your username>> # will be asked while deploying if be left blank
password: <<your password>> # recommend to leave it blank for security, will be asked while deploying if be left blank
```
- Add the deployer in the `deploy` of **site config file**`_config.yml`:
```yml
deploy:
# other deployer
- type: leancloud_counter_security_sync
```
- Return to the Leancloud console. Click `1 -> 2`, check if there is a record added in the _User (the img below is using username "admin" for example):

- Click `1 -> 2 -> 3` by order:

- <del>Click `1`(add_fields), then choose `2`:</del>Do as below "create" setting(choose the user you create):

- click `1`(create), then choose `2`, type the username in `3`, then click `4 -> 5`:

Now your page should be similar to this img after finishing the step.

- Click `1`(delete), then choose `2`:

Now the bug is fixed.
---
See detailed version here: https://leaferx.online/2018/03/16/lc-security-en/
|
DaddyTrap/daddytrap.github.io
|
themes/next/docs/LEANCLOUD-COUNTER-SECURITY.md
|
Markdown
|
cc0-1.0
| 6,074
|
//>>built
define({"widgets/OverviewMap/setting/nls/strings":{visible:"\u986f\u793a\u9810\u8a2d\u7684\u7e3d\u89bd\u5716",minWidth:"\u6700\u5c0f\u5bec\u5ea6",minHeight:"\u6700\u5c0f\u9ad8\u5ea6",maxWidth:"\u6700\u5927\u5bec\u5ea6",maxHeight:"\u6700\u5927\u9ad8\u5ea6",minText:"\u6700\u5c0f\u503c",maxText:"\u6700\u5927\u503c",attachText:"\u6307\u5b9a\u8981\u9644\u52a0\u6b64 widget \u7684\u5730\u5716\u89d2\u843d\u3002",expandText:"\u6700\u521d\u5c55\u958b\u7684 widget",topLeft:"\u5de6\u4e0a",topRight:"\u53f3\u4e0a",
bottomLeft:"\u5de6\u4e0b",bottomRight:"\u53f3\u4e0b",_localized:{}}});
|
pjdohertygis/MapSAROnline
|
Web Mapping Application/widgets/OverviewMap/setting/nls/Setting_zh-tw.js
|
JavaScript
|
cc0-1.0
| 587
|
/*******************************************************************************
* Copyright (c) 2012 David A Carlson.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.cts2.entity.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ViewerNotification;
import org.openhealthtools.mdht.cts2.association.provider.Cts2EditPlugin;
import org.openhealthtools.mdht.cts2.core.CompleteDirectory;
import org.openhealthtools.mdht.cts2.core.provider.DirectoryItemProvider;
import org.openhealthtools.mdht.cts2.entity.EntityFactory;
import org.openhealthtools.mdht.cts2.entity.EntityList;
import org.openhealthtools.mdht.cts2.entity.EntityPackage;
/**
* This is the item provider adapter for a {@link org.openhealthtools.mdht.cts2.entity.EntityList} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public class EntityListItemProvider extends DirectoryItemProvider implements IEditingDomainItemProvider,
IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public EntityListItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
}
return itemPropertyDescriptors;
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(EntityPackage.Literals.ENTITY_LIST__ENTRY);
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns EntityList.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/EntityList"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getText(Object object) {
CompleteDirectory labelValue = ((EntityList) object).getComplete();
String label = labelValue == null
? null
: labelValue.toString();
return label == null || label.length() == 0
? getString("_UI_EntityList_type")
: getString("_UI_EntityList_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(EntityList.class)) {
case EntityPackage.ENTITY_LIST__ENTRY:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add(createChildParameter(
EntityPackage.Literals.ENTITY_LIST__ENTRY, EntityFactory.eINSTANCE.createEntityListEntry()));
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return Cts2EditPlugin.INSTANCE;
}
}
|
drbgfc/mdht
|
cts2/plugins/org.openhealthtools.mdht.cts2.core.edit/src/org/openhealthtools/mdht/cts2/entity/provider/EntityListItemProvider.java
|
Java
|
epl-1.0
| 5,861
|
/*******************************************************************************
* Copyright (c) 2012 Christian W. Damus and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Christian W. Damus - initial API and implementation
*
*******************************************************************************/
package org.openhealthtools.mdht.uml.cda.util;
import static org.openhealthtools.mdht.uml.cda.util.CDAUtil.CDA_ANNOTATION_SOURCE;
import java.util.Collections;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.openhealthtools.mdht.emf.runtime.util.Initializer;
/**
* An initializer that processes legacy CDA annotations for population of defaults in new objects.
*/
public class AnnotationBasedInitializer implements Initializer<EObject> {
public static final Initializer.Factory FACTORY = new FactoryImpl();
private final Class<? extends EObject> targetType;
private final EAnnotation annotation;
/**
* Initializes me (heh heh) with the eclass that I initialize.
*
* @param eclass my target eclass
*/
@SuppressWarnings("unchecked")
private AnnotationBasedInitializer(EClass eclass) {
this.targetType = (Class<? extends EObject>) eclass.getInstanceClass();
this.annotation = eclass.getEAnnotation(CDA_ANNOTATION_SOURCE);
}
public EObject initialize(EObject object) {
if (annotation != null) {
CDAUtil.init(object, annotation.getDetails().map());
}
return object;
}
final public Class<? extends EObject> getTargetType() {
return targetType;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof AnnotationBasedInitializer) &&
((AnnotationBasedInitializer) obj).targetType.equals(targetType);
}
@Override
public int hashCode() {
return targetType.hashCode();
}
static void ensureCompatibility(EClass eclass, Initializer.Registry registry) {
if (!Initializer.Util.hasInitializers(eclass.getEPackage())) {
// add our initializer to the legacy package if it isn't already present
registry.initializeEPackage(eclass.getEPackage(), FACTORY);
}
}
//
// Nested types
//
public static class FactoryImpl implements Initializer.Factory {
public Iterable<? extends Initializer<? extends EObject>> createInitializers(EClass eclass) {
return Collections.singletonList(new AnnotationBasedInitializer(eclass));
}
}
}
|
drbgfc/mdht
|
cda/plugins/org.openhealthtools.mdht.uml.cda/src/org/openhealthtools/mdht/uml/cda/util/AnnotationBasedInitializer.java
|
Java
|
epl-1.0
| 2,637
|
/**
* Copyright 2005-2010 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.test.jaxrs.services.tests;
import java.util.Collections;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.test.jaxrs.services.resources.DeterminingMediaTypeTestService;
/**
* This test class checks if the
* {@link javax.ws.rs.core.Request#evaluatePreconditions(java.util.Date, javax.ws.rs.core.EntityTag)}
* methods works fine.
*
* @author Stephan Koops
*/
public class DeterminingMediaTypeTest extends JaxRsTestCase {
@Override
protected Application getApplication() {
return new Application() {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Set<Class<?>> getClasses() {
return (Set) Collections
.singleton(DeterminingMediaTypeTestService.class);
}
};
}
public void testHtmlPlainGif1() {
final Response response = get("htmlPlainGif", MediaType.TEXT_ALL);
assertEquals(Status.SUCCESS_OK, response.getStatus());
assertEqualMediaType(MediaType.TEXT_HTML, response);
}
public void testHtmlPlainGif2() {
final Response response = get("htmlPlainGif", MediaType.ALL);
assertEquals(Status.SUCCESS_OK, response.getStatus());
assertEqualMediaType(MediaType.TEXT_HTML, response);
}
public void testHtmlPlainGif3() {
final Response response = get("htmlPlainGif", MediaType.IMAGE_GIF);
assertEquals(Status.SUCCESS_OK, response.getStatus());
assertEqualMediaType(MediaType.IMAGE_GIF, response);
}
public void testHtmlPlainGif4() {
final Response response = get("htmlPlainGif", MediaType.TEXT_PLAIN);
assertEquals(Status.SUCCESS_OK, response.getStatus());
assertEqualMediaType(MediaType.TEXT_PLAIN, response);
}
public void testTextStar1() {
Response response = get("textStar", MediaType.TEXT_ALL);
assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus());
response = get("textStar", MediaType.ALL);
assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus());
response = get("textStar", MediaType.IMAGE_GIF);
assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus());
}
public void testTextStar2() {
final Response response = get("textStar", MediaType.TEXT_HTML);
assertEquals(Status.SUCCESS_OK, response.getStatus());
assertEqualMediaType(MediaType.TEXT_HTML, response);
}
public void testTextStar3() {
final Response response = get("textStar", MediaType.TEXT_PLAIN);
assertEquals(Status.SUCCESS_OK, response.getStatus());
assertEqualMediaType(MediaType.TEXT_PLAIN, response);
}
}
|
alastrina123/debrief
|
org.mwc.asset.comms/docs/restlet_src/org.restlet.test/org/restlet/test/jaxrs/services/tests/DeterminingMediaTypeTest.java
|
Java
|
epl-1.0
| 4,002
|
<!--
Copyright (c) 2015-2018 Red Hat, Inc.
This program and the accompanying materials are made
available under the terms of the Eclipse Public License 2.0
which is available at https://www.eclipse.org/legal/epl-2.0/
SPDX-License-Identifier: EPL-2.0
Contributors:
Red Hat, Inc. - initial API and implementation
-->
<dashboard-panel panel-title="Recent Factories">
<md-progress-linear md-mode="indeterminate"
ng-show="lastFactoriesController.isLoading"></md-progress-linear>
<div class="dashboard-last-factories" ng-show="!lastFactoriesController.isLoading">
<div class="dashboard-add-button">
<che-button-primary che-button-title="Create Factory"
ng-href="#/factories/create-factory"></che-button-primary>
</div>
<span ng-show="lastFactoriesController.getFactories().length === 0" class="last-factories-empty-label">No factories found</span>
<che-list ng-show="lastFactoriesController.getFactories().length > 0">
<cdvy-factory-item layout="row"
ng-repeat="factory in lastFactoriesController.getFactories() | orderBy:lastFactoriesController.factoriesOrderBy | limitTo:lastFactoriesController.maxItems"
cdvy-factory="factory"
cdvy-is-selectable="false"/>
</che-list>
</div>
</dashboard-panel>
|
akervern/che
|
dashboard/src/app/factories/last-factories/last-factories.html
|
HTML
|
epl-1.0
| 1,390
|
/*******************************************************************************
* Copyright (c) 2017 Red Hat, Inc and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc - initial API and implementation
*******************************************************************************/
package org.eclipse.reddeer.eclipse.ui.perspectives;
/**
* Web perspective implementation
*
* @author rhopp
*
*/
public class WebPerspective extends AbstractPerspective {
/**
* Constructs the perspective with "Web".
*/
public WebPerspective() {
super("Web");
}
}
|
jboss-reddeer/reddeer
|
plugins/org.eclipse.reddeer.eclipse/src/org/eclipse/reddeer/eclipse/ui/perspectives/WebPerspective.java
|
Java
|
epl-1.0
| 785
|
/*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.selenium.factory;
import static org.eclipse.che.dto.server.DtoFactory.newDto;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import java.util.Collections;
import org.eclipse.che.api.factory.shared.dto.IdeActionDto;
import org.eclipse.che.api.factory.shared.dto.IdeDto;
import org.eclipse.che.api.factory.shared.dto.OnAppLoadedDto;
import org.eclipse.che.selenium.core.SeleniumWebDriver;
import org.eclipse.che.selenium.core.constant.TestTimeoutsConstants;
import org.eclipse.che.selenium.core.factory.FactoryTemplate;
import org.eclipse.che.selenium.core.factory.TestFactory;
import org.eclipse.che.selenium.core.factory.TestFactoryInitializer;
import org.eclipse.che.selenium.pageobject.Ide;
import org.eclipse.che.selenium.pageobject.ProjectExplorer;
import org.eclipse.che.selenium.pageobject.dashboard.Dashboard;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/** @author Musienko Maxim */
public class CheckWelcomePanelOnCodenvyTest {
@Inject private Ide ide;
@Inject private TestFactoryInitializer testFactoryInitializer;
@Inject private ProjectExplorer projectExplorer;
@Inject private Dashboard dashboard;
@Inject private SeleniumWebDriver seleniumWebDriver;
private TestFactory testFactory;
private WebDriverWait webDriverWait;
@BeforeClass
public void setUp() throws Exception {
String urlToContentWelcomePanel = "https://codenvy.io/docs/admin-guide/runbook/index.html";
webDriverWait = new WebDriverWait(ide.driver(), TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC);
TestFactoryInitializer.TestFactoryBuilder factoryBuilder =
testFactoryInitializer.fromTemplate(FactoryTemplate.MINIMAL);
factoryBuilder.withIde(
newDto(IdeDto.class)
.withOnAppLoaded(
newDto(OnAppLoadedDto.class)
.withActions(
Collections.singletonList(
newDto(IdeActionDto.class)
.withId("openWelcomePage")
.withProperties(
ImmutableMap.of(
"greetingTitle",
"greetingTitle",
"greetingContentUrl",
urlToContentWelcomePanel))))));
testFactory = factoryBuilder.build();
}
@AfterClass
public void tearDown() throws Exception {
testFactory.delete();
}
@Test
public void shouldAppearsWelcomePanelAfterUsingFactory() throws Exception {
dashboard.open();
testFactory.open(ide.driver());
seleniumWebDriver.switchFromDashboardIframeToIde();
projectExplorer.waitItem("Spring");
checkWelcomePanel();
}
private void checkWelcomePanel() {
String expectedTextFragment =
"Runbook\n"
+ "This article provides specific performance and security guidance for Codenvy on-premises installations based on our experience running";
webDriverWait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("greetingFrame")));
webDriverWait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.tagName("body"), expectedTextFragment));
}
}
|
TypeFox/che
|
selenium/che-selenium-test/src/test/java/org/eclipse/che/selenium/factory/CheckWelcomePanelOnCodenvyTest.java
|
Java
|
epl-1.0
| 3,856
|
/**
* Copyright (c) 2014-2016 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.io.transport.mqtt;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang.StringUtils;
import org.eclipse.smarthome.core.events.EventPublisher;
import org.eclipse.smarthome.io.transport.mqtt.internal.MqttBrokerConnection;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* MQTT Service for creating new connections to MQTT brokers from the Smart Home configuration file and registering
* message publishers and subscribers. This service is the main entry point for all bundles wanting to use the MQTT
* transport.
*
* @author Davy Vanherbergen
* @author Markus Rathgeb - Synchronize access to broker connections
*/
public class MqttService implements ManagedService {
private final Logger logger = LoggerFactory.getLogger(MqttService.class);
private final Map<String, MqttBrokerConnection> brokerConnections = new ConcurrentHashMap<String, MqttBrokerConnection>();
private EventPublisher eventPublisher;
@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
// load broker configurations from configuration file
if (properties == null || properties.isEmpty()) {
return;
}
Enumeration<String> keys = properties.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if (key.equals("service.pid")) {
// ignore the only non-broker property..
continue;
}
String[] subkeys = key.split("\\.");
if (subkeys.length != 2) {
logger.debug("MQTT Broker property '{}' should have the format 'broker.propertykey'", key);
continue;
}
String value = (String) properties.get(key);
String name = subkeys[0].toLowerCase();
String property = subkeys[1];
if (StringUtils.isBlank(value)) {
logger.trace("Property is empty: {}", key);
continue;
} else {
logger.trace("Processing property: {} = {}", key, value);
}
final MqttBrokerConnection conn = getConnection(name);
if (property.equals("url")) {
conn.setUrl(value);
} else if (property.equals("user")) {
conn.setUser(value);
} else if (property.equals("pwd")) {
conn.setPassword(value);
} else if (property.equals("qos")) {
conn.setQos(Integer.parseInt(value));
} else if (property.equals("retain")) {
conn.setRetain(Boolean.parseBoolean(value));
} else if (property.equals("async")) {
conn.setAsync(Boolean.parseBoolean(value));
} else if (property.equals("clientId")) {
conn.setClientId(value);
} else if (property.equals("lwt")) {
MqttWillAndTestament will = MqttWillAndTestament.fromString(value);
logger.debug("Setting last will: {}", will);
conn.setLastWill(will);
} else if (property.equals("keepAlive")) {
conn.setKeepAliveInterval(Integer.parseInt(value));
} else {
logger.warn("Unrecognized property: {}", key);
}
}
logger.info("MQTT Service initialization completed.");
startAllBrokerConnections();
}
/**
* Start service.
*/
public void activate() {
logger.debug("Starting MQTT Service...");
}
/**
* Stop service.
*/
public void deactivate() {
logger.debug("Stopping MQTT Service...");
stopAllBrokerConnections();
logger.debug("MQTT Service stopped.");
}
private void startAllBrokerConnections() {
/*
* No need to synchronize the access to the broker connections.
* We don't add or remove entries only use the existing ones and the map is a concurrent one.
*/
for (final MqttBrokerConnection conn : brokerConnections.values()) {
try {
conn.start();
} catch (final Exception e) {
conn.connectionLost(e);
logger.error("Error starting broker connection", e);
}
}
}
private void stopAllBrokerConnections() {
/*
* No need to synchronize the access to the broker connections.
* We don't add or remove entries only use the existing ones and the map is a concurrent one.
*/
for (final MqttBrokerConnection conn : brokerConnections.values()) {
logger.info("Stopping broker connection '{}'", conn.getName());
conn.close();
}
}
/**
* Lookup an broker connection by name.
*
* @param brokerName to look for.
* @return existing connection or new one if it didn't exist yet.
*/
private MqttBrokerConnection getConnection(String brokerName) {
synchronized (brokerConnections) {
MqttBrokerConnection conn = brokerConnections.get(brokerName.toLowerCase());
if (conn == null) {
conn = new MqttBrokerConnection(brokerName);
brokerConnections.put(brokerName.toLowerCase(), conn);
}
return conn;
}
}
/**
* Register a new connection observer that could act on MQTT connection changes.
*
* @param brokerName Name of the broker that connection should be observed.
* @param connectionObserver The connection observer that should be informed about connection changes.
*/
public void registerConnectionObserver(String brokerName, MqttConnectionObserver connectionObserver) {
getConnection(brokerName).addConnectionObserver(connectionObserver);
}
/**
* Unregister an existing connection observer.
*
* @param brokerName Name of the broker that connection has been observed.
* @param connectionObserver The connection observer that should not be informed anymore.
*/
public void unregisterConnectionObserver(String brokerName, MqttConnectionObserver connectionObserver) {
getConnection(brokerName).removeConnectionObserver(connectionObserver);
}
/**
* Register a new message consumer which can process messages received on
*
* @param brokerName Name of the broker on which to listen for messages.
* @param mqttMessageConsumer Consumer which will process any received message.
*/
public void registerMessageConsumer(String brokerName, MqttMessageConsumer mqttMessageConsumer) {
mqttMessageConsumer.setEventPublisher(eventPublisher);
getConnection(brokerName).addConsumer(mqttMessageConsumer);
}
/**
* Unregisters an existing message.
*
* @param mqttMessageConsumer Consumer which needs to be unregistered.
*/
public void unregisterMessageConsumer(String brokerName, MqttMessageConsumer mqttMessageConsumer) {
getConnection(brokerName).removeConsumer(mqttMessageConsumer);
}
public void registerMessageProducer(String brokerName, MqttMessageProducer commandPublisher) {
getConnection(brokerName).addProducer(commandPublisher);
}
/**
* Register a new message producer which can send messages to the given
* broker.
*
* @param brokerName Name of the broker to which messages can be sent.
* @param mqttMessageProducer Producer which generates the messages.
*/
public void unregisterMessageProducer(String brokerName, MqttMessageProducer commandPublisher) {
getConnection(brokerName).removeProducer(commandPublisher);
}
/**
* Set the publisher to use for publishing SmartHome updates.
*
* @param eventPublisher EventPublisher
*/
public void setEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
/**
* Remove the publisher to use for publishing SmartHome updates.
*
* @param eventPublisher EventPublisher
*/
public void unsetEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = null;
}
}
|
CrackerStealth/smarthome
|
bundles/io/org.eclipse.smarthome.io.transport.mqtt/src/main/java/org/eclipse/smarthome/io/transport/mqtt/MqttService.java
|
Java
|
epl-1.0
| 8,761
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.