select2.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  1. /**
  2. * @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved.
  3. * Available via the MIT or new BSD license.
  4. * see: http://github.com/jrburke/almond for details
  5. */
  6. //Going sloppy to avoid 'use strict' string cost, but strict practices should
  7. //be followed.
  8. /*jslint sloppy: true */
  9. /*global setTimeout: false */
  10. var requirejs, require, define;
  11. (function (undef) {
  12. var main, req, makeMap, handlers,
  13. defined = {},
  14. waiting = {},
  15. config = {},
  16. defining = {},
  17. hasOwn = Object.prototype.hasOwnProperty,
  18. aps = [].slice,
  19. jsSuffixRegExp = /\.js$/;
  20. function hasProp(obj, prop) {
  21. return hasOwn.call(obj, prop);
  22. }
  23. /**
  24. * Given a relative module name, like ./something, normalize it to
  25. * a real name that can be mapped to a path.
  26. * @param {String} name the relative name
  27. * @param {String} baseName a real name that the name arg is relative
  28. * to.
  29. * @returns {String} normalized name
  30. */
  31. function normalize(name, baseName) {
  32. var nameParts, nameSegment, mapValue, foundMap, lastIndex,
  33. foundI, foundStarMap, starI, i, j, part,
  34. baseParts = baseName && baseName.split("/"),
  35. map = config.map,
  36. starMap = (map && map['*']) || {};
  37. //Adjust any relative paths.
  38. if (name && name.charAt(0) === ".") {
  39. //If have a base name, try to normalize against it,
  40. //otherwise, assume it is a top-level require that will
  41. //be relative to baseUrl in the end.
  42. if (baseName) {
  43. //Convert baseName to array, and lop off the last part,
  44. //so that . matches that "directory" and not name of the baseName's
  45. //module. For instance, baseName of "one/two/three", maps to
  46. //"one/two/three.js", but we want the directory, "one/two" for
  47. //this normalization.
  48. baseParts = baseParts.slice(0, baseParts.length - 1);
  49. name = name.split('/');
  50. lastIndex = name.length - 1;
  51. // Node .js allowance:
  52. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
  53. name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
  54. }
  55. name = baseParts.concat(name);
  56. //start trimDots
  57. for (i = 0; i < name.length; i += 1) {
  58. part = name[i];
  59. if (part === ".") {
  60. name.splice(i, 1);
  61. i -= 1;
  62. } else if (part === "..") {
  63. if (i === 1 && (name[2] === '..' || name[0] === '..')) {
  64. //End of the line. Keep at least one non-dot
  65. //path segment at the front so it can be mapped
  66. //correctly to disk. Otherwise, there is likely
  67. //no path mapping for a path starting with '..'.
  68. //This can still fail, but catches the most reasonable
  69. //uses of ..
  70. break;
  71. } else if (i > 0) {
  72. name.splice(i - 1, 2);
  73. i -= 2;
  74. }
  75. }
  76. }
  77. //end trimDots
  78. name = name.join("/");
  79. } else if (name.indexOf('./') === 0) {
  80. // No baseName, so this is ID is resolved relative
  81. // to baseUrl, pull off the leading dot.
  82. name = name.substring(2);
  83. }
  84. }
  85. //Apply map config if available.
  86. if ((baseParts || starMap) && map) {
  87. nameParts = name.split('/');
  88. for (i = nameParts.length; i > 0; i -= 1) {
  89. nameSegment = nameParts.slice(0, i).join("/");
  90. if (baseParts) {
  91. //Find the longest baseName segment match in the config.
  92. //So, do joins on the biggest to smallest lengths of baseParts.
  93. for (j = baseParts.length; j > 0; j -= 1) {
  94. mapValue = map[baseParts.slice(0, j).join('/')];
  95. //baseName segment has config, find if it has one for
  96. //this name.
  97. if (mapValue) {
  98. mapValue = mapValue[nameSegment];
  99. if (mapValue) {
  100. //Match, update name to the new value.
  101. foundMap = mapValue;
  102. foundI = i;
  103. break;
  104. }
  105. }
  106. }
  107. }
  108. if (foundMap) {
  109. break;
  110. }
  111. //Check for a star map match, but just hold on to it,
  112. //if there is a shorter segment match later in a matching
  113. //config, then favor over this star map.
  114. if (!foundStarMap && starMap && starMap[nameSegment]) {
  115. foundStarMap = starMap[nameSegment];
  116. starI = i;
  117. }
  118. }
  119. if (!foundMap && foundStarMap) {
  120. foundMap = foundStarMap;
  121. foundI = starI;
  122. }
  123. if (foundMap) {
  124. nameParts.splice(0, foundI, foundMap);
  125. name = nameParts.join('/');
  126. }
  127. }
  128. return name;
  129. }
  130. function makeRequire(relName, forceSync) {
  131. return function () {
  132. //A version of a require function that passes a moduleName
  133. //value for items that may need to
  134. //look up paths relative to the moduleName
  135. return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
  136. };
  137. }
  138. function makeNormalize(relName) {
  139. return function (name) {
  140. return normalize(name, relName);
  141. };
  142. }
  143. function makeLoad(depName) {
  144. return function (value) {
  145. defined[depName] = value;
  146. };
  147. }
  148. function callDep(name) {
  149. if (hasProp(waiting, name)) {
  150. var args = waiting[name];
  151. delete waiting[name];
  152. defining[name] = true;
  153. main.apply(undef, args);
  154. }
  155. if (!hasProp(defined, name) && !hasProp(defining, name)) {
  156. throw new Error('No ' + name);
  157. }
  158. return defined[name];
  159. }
  160. //Turns a plugin!resource to [plugin, resource]
  161. //with the plugin being undefined if the name
  162. //did not have a plugin prefix.
  163. function splitPrefix(name) {
  164. var prefix,
  165. index = name ? name.indexOf('!') : -1;
  166. if (index > -1) {
  167. prefix = name.substring(0, index);
  168. name = name.substring(index + 1, name.length);
  169. }
  170. return [prefix, name];
  171. }
  172. /**
  173. * Makes a name map, normalizing the name, and using a plugin
  174. * for normalization if necessary. Grabs a ref to plugin
  175. * too, as an optimization.
  176. */
  177. makeMap = function (name, relName) {
  178. var plugin,
  179. parts = splitPrefix(name),
  180. prefix = parts[0];
  181. name = parts[1];
  182. if (prefix) {
  183. prefix = normalize(prefix, relName);
  184. plugin = callDep(prefix);
  185. }
  186. //Normalize according
  187. if (prefix) {
  188. if (plugin && plugin.normalize) {
  189. name = plugin.normalize(name, makeNormalize(relName));
  190. } else {
  191. name = normalize(name, relName);
  192. }
  193. } else {
  194. name = normalize(name, relName);
  195. parts = splitPrefix(name);
  196. prefix = parts[0];
  197. name = parts[1];
  198. if (prefix) {
  199. plugin = callDep(prefix);
  200. }
  201. }
  202. //Using ridiculous property names for space reasons
  203. return {
  204. f: prefix ? prefix + '!' + name : name, //fullName
  205. n: name,
  206. pr: prefix,
  207. p: plugin
  208. };
  209. };
  210. function makeConfig(name) {
  211. return function () {
  212. return (config && config.config && config.config[name]) || {};
  213. };
  214. }
  215. handlers = {
  216. require: function (name) {
  217. return makeRequire(name);
  218. },
  219. exports: function (name) {
  220. var e = defined[name];
  221. if (typeof e !== 'undefined') {
  222. return e;
  223. } else {
  224. return (defined[name] = {});
  225. }
  226. },
  227. module: function (name) {
  228. return {
  229. id: name,
  230. uri: '',
  231. exports: defined[name],
  232. config: makeConfig(name)
  233. };
  234. }
  235. };
  236. main = function (name, deps, callback, relName) {
  237. var cjsModule, depName, ret, map, i,
  238. args = [],
  239. callbackType = typeof callback,
  240. usingExports;
  241. //Use name if no relName
  242. relName = relName || name;
  243. //Call the callback to define the module, if necessary.
  244. if (callbackType === 'undefined' || callbackType === 'function') {
  245. //Pull out the defined dependencies and pass the ordered
  246. //values to the callback.
  247. //Default to [require, exports, module] if no deps
  248. deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
  249. for (i = 0; i < deps.length; i += 1) {
  250. map = makeMap(deps[i], relName);
  251. depName = map.f;
  252. //Fast path CommonJS standard dependencies.
  253. if (depName === "require") {
  254. args[i] = handlers.require(name);
  255. } else if (depName === "exports") {
  256. //CommonJS module spec 1.1
  257. args[i] = handlers.exports(name);
  258. usingExports = true;
  259. } else if (depName === "module") {
  260. //CommonJS module spec 1.1
  261. cjsModule = args[i] = handlers.module(name);
  262. } else if (hasProp(defined, depName) ||
  263. hasProp(waiting, depName) ||
  264. hasProp(defining, depName)) {
  265. args[i] = callDep(depName);
  266. } else if (map.p) {
  267. map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
  268. args[i] = defined[depName];
  269. } else {
  270. throw new Error(name + ' missing ' + depName);
  271. }
  272. }
  273. ret = callback ? callback.apply(defined[name], args) : undefined;
  274. if (name) {
  275. //If setting exports via "module" is in play,
  276. //favor that over return value and exports. After that,
  277. //favor a non-undefined return value over exports use.
  278. if (cjsModule && cjsModule.exports !== undef &&
  279. cjsModule.exports !== defined[name]) {
  280. defined[name] = cjsModule.exports;
  281. } else if (ret !== undef || !usingExports) {
  282. //Use the return value from the function.
  283. defined[name] = ret;
  284. }
  285. }
  286. } else if (name) {
  287. //May just be an object definition for the module. Only
  288. //worry about defining if have a module name.
  289. defined[name] = callback;
  290. }
  291. };
  292. requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
  293. if (typeof deps === "string") {
  294. if (handlers[deps]) {
  295. //callback in this case is really relName
  296. return handlers[deps](callback);
  297. }
  298. //Just return the module wanted. In this scenario, the
  299. //deps arg is the module name, and second arg (if passed)
  300. //is just the relName.
  301. //Normalize module name, if it contains . or ..
  302. return callDep(makeMap(deps, callback).f);
  303. } else if (!deps.splice) {
  304. //deps is a config object, not an array.
  305. config = deps;
  306. if (config.deps) {
  307. req(config.deps, config.callback);
  308. }
  309. if (!callback) {
  310. return;
  311. }
  312. if (callback.splice) {
  313. //callback is an array, which means it is a dependency list.
  314. //Adjust args if there are dependencies
  315. deps = callback;
  316. callback = relName;
  317. relName = null;
  318. } else {
  319. deps = undef;
  320. }
  321. }
  322. //Support require(['a'])
  323. callback = callback || function () {};
  324. //If relName is a function, it is an errback handler,
  325. //so remove it.
  326. if (typeof relName === 'function') {
  327. relName = forceSync;
  328. forceSync = alt;
  329. }
  330. //Simulate async callback;
  331. if (forceSync) {
  332. main(undef, deps, callback, relName);
  333. } else {
  334. //Using a non-zero value because of concern for what old browsers
  335. //do, and latest browsers "upgrade" to 4 if lower value is used:
  336. //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
  337. //If want a value immediately, use require('id') instead -- something
  338. //that works in almond on the global level, but not guaranteed and
  339. //unlikely to work in other AMD implementations.
  340. setTimeout(function () {
  341. main(undef, deps, callback, relName);
  342. }, 4);
  343. }
  344. return req;
  345. };
  346. /**
  347. * Just drops the config on the floor, but returns req in case
  348. * the config return value is used.
  349. */
  350. req.config = function (cfg) {
  351. return req(cfg);
  352. };
  353. /**
  354. * Expose module registry for debugging and tooling
  355. */
  356. requirejs._defined = defined;
  357. define = function (name, deps, callback) {
  358. //This module may not have dependencies
  359. if (!deps.splice) {
  360. //deps is not an array, so probably means
  361. //an object literal or factory function for
  362. //the value. Adjust args.
  363. callback = deps;
  364. deps = [];
  365. }
  366. if (!hasProp(defined, name) && !hasProp(waiting, name)) {
  367. waiting[name] = [name, deps, callback];
  368. }
  369. };
  370. define.amd = {
  371. jQuery: true
  372. };
  373. }());
  374. define("almond", function(){});
  375. define('jquery',[],function () {
  376. return jQuery;
  377. });
  378. define('select2/utils',[], function () {
  379. var Utils = {};
  380. Utils.Extend = function (ChildClass, SuperClass) {
  381. var __hasProp = {}.hasOwnProperty;
  382. function BaseConstructor () {
  383. this.constructor = ChildClass;
  384. }
  385. for (var key in SuperClass) {
  386. if (__hasProp.call(SuperClass, key)) {
  387. ChildClass[key] = SuperClass[key];
  388. }
  389. }
  390. BaseConstructor.prototype = SuperClass.prototype;
  391. ChildClass.prototype = new BaseConstructor();
  392. ChildClass.__super__ = SuperClass.prototype;
  393. return ChildClass;
  394. };
  395. function getMethods (theClass) {
  396. var proto = theClass.prototype;
  397. var methods = [];
  398. for (var methodName in proto) {
  399. var m = proto[methodName];
  400. if (typeof m !== 'function') {
  401. continue;
  402. }
  403. methods.push(methodName);
  404. }
  405. return methods;
  406. }
  407. Utils.Decorate = function (SuperClass, DecoratorClass) {
  408. var decoratedMethods = getMethods(DecoratorClass);
  409. var superMethods = getMethods(SuperClass);
  410. function DecoratedClass () {
  411. var unshift = Array.prototype.unshift;
  412. var argCount = DecoratorClass.prototype.constructor.length;
  413. var calledConstructor = SuperClass.prototype.constructor;
  414. if (argCount > 0) {
  415. unshift.call(arguments, SuperClass.prototype.constructor);
  416. calledConstructor = DecoratorClass.prototype.constructor;
  417. }
  418. calledConstructor.apply(this, arguments);
  419. }
  420. DecoratorClass.displayName = SuperClass.displayName;
  421. function ctr () {
  422. this.constructor = DecoratedClass;
  423. }
  424. DecoratedClass.prototype = new ctr();
  425. for (var m = 0; m < superMethods.length; m++) {
  426. var superMethod = superMethods[m];
  427. DecoratedClass.prototype[superMethod] =
  428. SuperClass.prototype[superMethod];
  429. }
  430. var calledMethod = function (methodName) {
  431. // Stub out the original method if it's not decorating an actual method
  432. var originalMethod = function () {};
  433. if (methodName in DecoratedClass.prototype) {
  434. originalMethod = DecoratedClass.prototype[methodName];
  435. }
  436. var decoratedMethod = DecoratorClass.prototype[methodName];
  437. return function () {
  438. var unshift = Array.prototype.unshift;
  439. unshift.call(arguments, originalMethod);
  440. return decoratedMethod.apply(this, arguments);
  441. };
  442. };
  443. for (var d = 0; d < decoratedMethods.length; d++) {
  444. var decoratedMethod = decoratedMethods[d];
  445. DecoratedClass.prototype[decoratedMethod] = calledMethod(decoratedMethod);
  446. }
  447. return DecoratedClass;
  448. };
  449. var Observable = function () {
  450. this.listeners = {};
  451. };
  452. Observable.prototype.on = function (event, callback) {
  453. if (event in this.listeners) {
  454. this.listeners[event].push(callback);
  455. } else {
  456. this.listeners[event] = [callback];
  457. }
  458. };
  459. Observable.prototype.trigger = function (event) {
  460. var slice = Array.prototype.slice;
  461. if (event in this.listeners) {
  462. this.invoke(this.listeners[event], slice.call(arguments, 1));
  463. }
  464. if ('*' in this.listeners) {
  465. this.invoke(this.listeners['*'], arguments);
  466. }
  467. };
  468. Observable.prototype.invoke = function (listeners, params) {
  469. for (var i = 0, len = listeners.length; i < len; i++) {
  470. listeners[i].apply(this, params);
  471. }
  472. };
  473. Utils.Observable = Observable;
  474. return Utils;
  475. });
  476. define('select2/results',[
  477. './utils'
  478. ], function (Utils) {
  479. function Results ($element, options, dataAdapter) {
  480. this.$element = $element;
  481. this.data = dataAdapter;
  482. Results.__super__.constructor.call(this);
  483. }
  484. Utils.Extend(Results, Utils.Observable);
  485. Results.prototype.render = function () {
  486. var $results = $(
  487. '<ul class="options"></ul>'
  488. );
  489. this.$results = $results;
  490. return $results;
  491. };
  492. Results.prototype.clear = function () {
  493. this.$results.empty();
  494. };
  495. Results.prototype.append = function (data) {
  496. var $options = [];
  497. data = this.sort(data);
  498. for (var d = 0; d < data.length; d++) {
  499. var item = data[d];
  500. var $option = this.option(item);
  501. $options.push($option);
  502. }
  503. this.$results.append($options);
  504. };
  505. Results.prototype.sort = function (data) {
  506. return data;
  507. };
  508. Results.prototype.setClasses = function () {
  509. var self = this;
  510. this.data.current(function (selected) {
  511. var selectedIds = $.map(selected, function (s) {
  512. return s.id.toString();
  513. });
  514. self.$results.find('.option.selected').removeClass('selected');
  515. var $options = self.$results.find('.option');
  516. $options.each(function () {
  517. var $option = $(this);
  518. var item = $option.data('data');
  519. if (item.id != null && selectedIds.indexOf(item.id.toString()) > -1) {
  520. $option.addClass('selected');
  521. }
  522. });
  523. });
  524. };
  525. Results.prototype.option = function (data) {
  526. var $option = $(
  527. '<li class="option highlightable selectable"></li>'
  528. );
  529. if (data.children) {
  530. $option.addClass('group').removeClass('highlightable selectable');
  531. var $label = $('<strong class="group-label"></strong>');
  532. $label.html(data.text);
  533. var $children = [];
  534. for (var c = 0; c < data.children.length; c++) {
  535. var child = data.children[c];
  536. var $child = this.option(child);
  537. $children.push($child);
  538. }
  539. var $childrenContainer = $('<ul class="options nested-options"></ul>');
  540. $childrenContainer.append($children);
  541. $option.append($label);
  542. $option.append($childrenContainer);
  543. } else {
  544. $option.html(data.text);
  545. }
  546. if (data.disabled) {
  547. $option.removeClass('selectable highlightable').addClass('disabled');
  548. }
  549. if (data.id == null) {
  550. $option.removeClass('selectable highlightable');
  551. }
  552. $option.data('data', data);
  553. return $option;
  554. };
  555. Results.prototype.bind = function (container, $container) {
  556. var self = this;
  557. container.on('results:all', function (params) {
  558. self.clear();
  559. self.append(params.data);
  560. self.setClasses();
  561. });
  562. container.on('results:append', function (params) {
  563. self.append(params.data);
  564. self.setClasses();
  565. });
  566. container.on('select', function () {
  567. self.setClasses();
  568. });
  569. container.on('unselect', function () {
  570. self.setClasses();
  571. });
  572. this.$results.on('mouseup', '.option.selectable', function (evt) {
  573. var $this = $(this);
  574. var data = $this.data('data');
  575. if ($this.hasClass('selected')) {
  576. self.trigger('unselected', {
  577. originalEvent: evt,
  578. data: data
  579. });
  580. return;
  581. }
  582. self.trigger('selected', {
  583. originalEvent: evt,
  584. data: data
  585. });
  586. });
  587. this.$results.on('mouseenter', '.option.highlightable', function (evt) {
  588. self.$results.find('.option.highlighted').removeClass('highlighted');
  589. $(this).addClass('highlighted');
  590. });
  591. this.$results.on('mouseleave', '.option', function (evt) {
  592. $(this).removeClass('highlighted');
  593. });
  594. };
  595. return Results;
  596. });
  597. define('select2/selection/base',[
  598. '../utils'
  599. ], function (Utils) {
  600. function BaseSelection ($element, options) {
  601. this.$element = $element;
  602. this.options = options;
  603. BaseSelection.__super__.constructor.call(this);
  604. }
  605. Utils.Extend(BaseSelection, Utils.Observable);
  606. BaseSelection.prototype.render = function () {
  607. throw new Error('The `render` method must be defined in child classes.');
  608. };
  609. BaseSelection.prototype.bind = function (container, $container) {
  610. var self = this;
  611. container.on('selection:update', function (params) {
  612. self.update(params.data);
  613. });
  614. };
  615. BaseSelection.prototype.update = function (data) {
  616. throw new Error('The `update` method must be defined in child classes.');
  617. };
  618. return BaseSelection;
  619. });
  620. define('select2/selection/single',[
  621. './base',
  622. '../utils'
  623. ], function (BaseSelection, Utils) {
  624. function SingleSelection () {
  625. SingleSelection.__super__.constructor.apply(this, arguments);
  626. }
  627. Utils.Extend(SingleSelection, BaseSelection);
  628. SingleSelection.prototype.render = function () {
  629. var $selection = $(
  630. '<span class="single-select">' +
  631. '<span class="rendered-selection"></span>' +
  632. '</span>'
  633. );
  634. this.$selection = $selection;
  635. return $selection;
  636. };
  637. SingleSelection.prototype.bind = function (container, $container) {
  638. var self = this;
  639. SingleSelection.__super__.bind.apply(this, arguments);
  640. this.$selection.on('mousedown', function (evt) {
  641. // Only respond to left clicks
  642. if (evt.which !== 1) {
  643. return;
  644. }
  645. self.trigger('toggle', {
  646. originalEvent: evt
  647. });
  648. });
  649. container.on('selection:update', function (params) {
  650. self.update(params.data);
  651. });
  652. };
  653. SingleSelection.prototype.clear = function () {
  654. this.$selection.find('.rendered-selection').empty();
  655. };
  656. SingleSelection.prototype.display = function (data) {
  657. return data.text;
  658. };
  659. SingleSelection.prototype.selectionContainer = function () {
  660. return $('<span></span>');
  661. };
  662. SingleSelection.prototype.update = function (data) {
  663. if (data.length === 0) {
  664. this.clear();
  665. return;
  666. }
  667. var selection = data[0];
  668. var formatted = this.display(selection);
  669. this.$selection.find('.rendered-selection').html(formatted);
  670. };
  671. return SingleSelection;
  672. });
  673. define('select2/selection/multiple',[
  674. './base',
  675. '../utils'
  676. ], function (BaseSelection, Utils) {
  677. function MultipleSelection ($element, options) {
  678. this.$element = $element;
  679. this.options = options;
  680. MultipleSelection.__super__.constructor.call(this);
  681. }
  682. Utils.Extend(MultipleSelection, BaseSelection);
  683. MultipleSelection.prototype.render = function () {
  684. var $selection = $(
  685. '<span class="multiple-select">' +
  686. '<ul class="rendered-selection"></ul>' +
  687. '</span>'
  688. );
  689. this.$selection = $selection;
  690. return $selection;
  691. };
  692. MultipleSelection.prototype.bind = function (container, $container) {
  693. var self = this;
  694. MultipleSelection.__super__.bind.apply(this, arguments);
  695. this.$selection.on('click', function (evt) {
  696. self.trigger('toggle', {
  697. originalEvent: evt
  698. });
  699. });
  700. this.$selection.on('click', '.remove', function (evt) {
  701. var $remove = $(this);
  702. var $selection = $remove.parent();
  703. var data = $selection.data('data');
  704. self.trigger('unselected', {
  705. originalEvent: evt,
  706. data: data
  707. });
  708. });
  709. };
  710. MultipleSelection.prototype.clear = function () {
  711. this.$selection.find('.rendered-selection').empty();
  712. };
  713. MultipleSelection.prototype.display = function (data) {
  714. return data.text;
  715. };
  716. MultipleSelection.prototype.selectionContainer = function () {
  717. var $container = $(
  718. '<li class="choice">' +
  719. '<span class="remove">&times;</span>' +
  720. '</li>'
  721. );
  722. return $container;
  723. };
  724. MultipleSelection.prototype.update = function (data) {
  725. this.clear();
  726. if (data.length === 0) {
  727. return;
  728. }
  729. var $selections = [];
  730. for (var d = 0; d < data.length; d++) {
  731. var selection = data[d];
  732. var formatted = this.display(selection);
  733. var $selection = this.selectionContainer();
  734. $selection.append(formatted);
  735. $selection.data('data', selection);
  736. $selections.push($selection);
  737. }
  738. this.$selection.find('.rendered-selection').append($selections);
  739. };
  740. return MultipleSelection;
  741. });
  742. define('select2/selection/placeholder',[
  743. '../utils'
  744. ], function (Utils) {
  745. function Placeholder (decorated, $element, options) {
  746. this.placeholder = this.normalizePlaceholder(options.get('placeholder'));
  747. decorated.call(this, $element, options);
  748. }
  749. Placeholder.prototype.normalizePlaceholder = function (_, placeholder) {
  750. if (typeof placeholder === 'string') {
  751. placeholder = {
  752. id: '',
  753. text: placeholder
  754. };
  755. }
  756. return placeholder;
  757. };
  758. Placeholder.prototype.update = function (decorated, data) {
  759. var singlePlaceholder = (
  760. data.length == 1 && data[0].id != this.placeholder.id
  761. );
  762. var multipleSelections = data.length > 1;
  763. if (multipleSelections || singlePlaceholder) {
  764. return decorated.call(this, data);
  765. }
  766. this.clear();
  767. var $placeholder = this.selectionContainer();
  768. $placeholder.html(this.display(this.placeholder));
  769. $placeholder.addClass('placeholder').removeClass('choice');
  770. this.$selection.find('.rendered-selection').append($placeholder);
  771. };
  772. return Placeholder;
  773. });
  774. define('select2/data/base',[
  775. '../utils'
  776. ], function (Utils) {
  777. function BaseAdapter ($element, options) {
  778. BaseAdapter.__super__.constructor.call(this);
  779. }
  780. Utils.Extend(BaseAdapter, Utils.Observable);
  781. BaseAdapter.prototype.current = function (callback) {
  782. throw new Error('The `current` method must be defined in child classes.');
  783. };
  784. BaseAdapter.prototype.query = function (params, callback) {
  785. throw new Error('The `query` method must be defined in child classes.');
  786. };
  787. BaseAdapter.prototype.bind = function (container, $container) {
  788. // Can be implemented in subclasses
  789. };
  790. return BaseAdapter;
  791. });
  792. define('select2/data/select',[
  793. './base',
  794. '../utils',
  795. 'jquery'
  796. ], function (BaseAdapter, Utils, $) {
  797. function SelectAdapter ($element, options) {
  798. this.$element = $element;
  799. SelectAdapter.__super__.constructor.call(this);
  800. }
  801. Utils.Extend(SelectAdapter, BaseAdapter);
  802. SelectAdapter.prototype.current = function (callback) {
  803. var data = [];
  804. var self = this;
  805. this.$element.find(':selected').each(function () {
  806. var $option = $(this);
  807. var option = self.item($option);
  808. data.push(option);
  809. });
  810. callback(data);
  811. };
  812. SelectAdapter.prototype.select = function (data) {
  813. var self = this;
  814. if (this.$element.prop('multiple')) {
  815. this.current(function (currentData) {
  816. var val = [];
  817. data = [data];
  818. data.push.apply(data, currentData);
  819. for (var d = 0; d < data.length; d++) {
  820. id = data[d].id;
  821. if (val.indexOf(id) === -1) {
  822. val.push(id);
  823. }
  824. }
  825. self.$element.val(val);
  826. self.$element.trigger('change');
  827. });
  828. } else {
  829. var val = data.id;
  830. this.$element.val(val);
  831. this.$element.trigger('change');
  832. }
  833. };
  834. SelectAdapter.prototype.unselect = function (data) {
  835. var self = this;
  836. if (!this.$element.prop('multiple')) {
  837. return;
  838. }
  839. this.current(function (currentData) {
  840. var val = [];
  841. for (var d = 0; d < currentData.length; d++) {
  842. id = currentData[d].id;
  843. if (id !== data.id && val.indexOf(id) === -1) {
  844. val.push(id);
  845. }
  846. }
  847. self.$element.val(val);
  848. self.$element.trigger('change');
  849. });
  850. };
  851. SelectAdapter.prototype.bind = function (container, $container) {
  852. var self = this;
  853. container.on('select', function (params) {
  854. self.select(params.data);
  855. });
  856. container.on('unselect', function (params) {
  857. self.unselect(params.data);
  858. });
  859. };
  860. SelectAdapter.prototype.query = function (params, callback) {
  861. var data = [];
  862. var self = this;
  863. var $options = this.$element.children();
  864. $options.each(function () {
  865. var $option = $(this);
  866. if (!$option.is('option') && !$option.is('optgroup')) {
  867. return;
  868. }
  869. var option = self.item($option);
  870. var matches = self.matches(params, option);
  871. if (matches !== null) {
  872. data.push(matches);
  873. }
  874. });
  875. callback(data);
  876. };
  877. SelectAdapter.prototype.item = function ($option) {
  878. var data = $option.data('data');
  879. // If the data has already be generated, use it
  880. if (data == null) {
  881. if ($option.is('option')) {
  882. data = {
  883. id: $option.val(),
  884. text: $option.html(),
  885. disabled: $option.prop('disabled')
  886. };
  887. } else if ($option.is('optgroup')) {
  888. data = {
  889. text: $option.attr('label'),
  890. children: []
  891. };
  892. var $children = $option.children('option');
  893. var children = [];
  894. for (var c = 0; c < $children.length; c++) {
  895. var $child = $($children[c]);
  896. var child = this.item($child);
  897. children.push(child);
  898. }
  899. data.children = children;
  900. }
  901. $option.data('data', data);
  902. }
  903. return data;
  904. };
  905. SelectAdapter.prototype.matches = function (params, data) {
  906. var match = $.extend(true, {}, data);
  907. if (data.children) {
  908. for (var c = data.children.length - 1; c >= 0; c--) {
  909. var child = data.children[c];
  910. var matches = this.matches(params, child);
  911. // If there wasn't a match, remove the object in the array
  912. if (matches === null) {
  913. match.children.splice(c, 1);
  914. }
  915. }
  916. if (match.children.length > 0) {
  917. return match;
  918. }
  919. }
  920. if ($.trim(params.term) === '') {
  921. return match;
  922. }
  923. if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
  924. return match;
  925. }
  926. return null;
  927. };
  928. return SelectAdapter;
  929. });
  930. define('select2/data/array',[
  931. './select',
  932. '../utils'
  933. ], function (SelectAdapter, Utils) {
  934. function ArrayAdapter ($element, options) {
  935. this.data = options.options.data;
  936. ArrayAdapter.__super__.constructor.call(this, $element, options);
  937. }
  938. Utils.Extend(ArrayAdapter, SelectAdapter);
  939. ArrayAdapter.prototype.select = function (data) {
  940. var self = this;
  941. this.$element.find('option').each(function () {
  942. var $option = $(this);
  943. var option = self.item($option);
  944. if (option.id == data.id.toString()) {
  945. $option.remove();
  946. }
  947. });
  948. var $option = this.option(data);
  949. this.$element.append($option);
  950. ArrayAdapter.__super__.select.call(this, data);
  951. };
  952. ArrayAdapter.prototype.option = function (data) {
  953. var $option = $('<option></option>');
  954. $option.text(data.text);
  955. $option.val(data.id);
  956. $option.data('data', data);
  957. return $option;
  958. };
  959. ArrayAdapter.prototype.query = function (params, callback) {
  960. var matches = [];
  961. var self = this;
  962. $.each(this.data, function () {
  963. var option = this;
  964. if (self.matches(params, option)) {
  965. matches.push(option);
  966. }
  967. });
  968. callback(matches);
  969. };
  970. return ArrayAdapter;
  971. });
  972. define('select2/data/ajax',[
  973. './array',
  974. '../utils',
  975. 'jquery'
  976. ], function (ArrayAdapter, Utils, $) {
  977. function AjaxAdapter ($element, options) {
  978. this.ajaxOptions = options.get('ajax');
  979. this.processResults = this.ajaxOptions.processResults ||
  980. function (results) {
  981. return results;
  982. };
  983. ArrayAdapter.__super__.constructor.call(this, $element, options);
  984. }
  985. Utils.Extend(AjaxAdapter, ArrayAdapter);
  986. AjaxAdapter.prototype.query = function (params, callback) {
  987. var matches = [];
  988. var self = this;
  989. var options = $.extend({
  990. type: 'GET'
  991. }, this.ajaxOptions);
  992. if (typeof options.url === 'function') {
  993. options.url = options.url(params);
  994. }
  995. if (typeof options.data === 'function') {
  996. options.data = options.data(params);
  997. }
  998. var $request = $.ajax(options);
  999. $request.success(function (data) {
  1000. var results = self.processResults(data);
  1001. callback(results);
  1002. });
  1003. };
  1004. return AjaxAdapter;
  1005. });
  1006. define('select2/dropdown',[
  1007. './utils'
  1008. ], function (Utils) {
  1009. function Dropdown ($element, options) {
  1010. this.$element = $element;
  1011. }
  1012. Utils.Extend(Dropdown, Utils.Observable);
  1013. Dropdown.prototype.render = function () {
  1014. var $dropdown = $(
  1015. '<span class="dropdown">' +
  1016. '<span class="results"></span>' +
  1017. '</span>'
  1018. );
  1019. return $dropdown;
  1020. };
  1021. Dropdown.prototype.bind = function (container, $container) {
  1022. // Can be implemented in subclasses
  1023. };
  1024. return Dropdown;
  1025. });
  1026. define('select2/dropdown/search',[
  1027. ], function () {
  1028. function Search () { }
  1029. Search.prototype.render = function (decorated) {
  1030. var $rendered = decorated.call(this);
  1031. var $search = $(
  1032. '<span class="search">' +
  1033. '<input type="search" name="search" />' +
  1034. '</span>'
  1035. );
  1036. this.$searchContainer = $search;
  1037. this.$search = $search.find('input');
  1038. $rendered.prepend($search);
  1039. return $rendered;
  1040. };
  1041. Search.prototype.bind = function (decorated, container, $container) {
  1042. var self = this;
  1043. decorated.call(this, container, $container);
  1044. this.$search.on('keyup', function () {
  1045. container.trigger('query', {
  1046. term: $(this).val()
  1047. });
  1048. });
  1049. container.on('results:all', function (params) {
  1050. if (params.query.term == null || params.query.term === '') {
  1051. var showSearch = self.showSearch(params);
  1052. if (showSearch) {
  1053. self.$searchContainer.show();
  1054. } else {
  1055. self.$searchContainer.hide();
  1056. }
  1057. }
  1058. });
  1059. };
  1060. Search.prototype.showSearch = function (params) {
  1061. return true;
  1062. };
  1063. return Search;
  1064. });
  1065. define('select2/defaults',[
  1066. './results',
  1067. './selection/single',
  1068. './selection/multiple',
  1069. './selection/placeholder',
  1070. './utils',
  1071. './data/select',
  1072. './data/array',
  1073. './data/ajax',
  1074. './dropdown',
  1075. './dropdown/search'
  1076. ], function (ResultsList,
  1077. SingleSelection, MultipleSelection, Placeholder,
  1078. Utils,
  1079. SelectData, ArrayData, AjaxData,
  1080. Dropdown, Search) {
  1081. function Defaults () {
  1082. this.reset();
  1083. }
  1084. Defaults.prototype.apply = function (options) {
  1085. options = $.extend({}, options, this.defaults);
  1086. if (options.dataAdapter == null) {
  1087. if (options.ajax) {
  1088. options.dataAdapter = AjaxData;
  1089. } else if (options.data) {
  1090. options.dataAdapter = ArrayData;
  1091. } else {
  1092. options.dataAdapter = SelectData;
  1093. }
  1094. }
  1095. if (options.resultsAdapter == null) {
  1096. options.resultsAdapter = ResultsList;
  1097. }
  1098. if (options.dropdownAdapter == null) {
  1099. var SearchableDropdown = Utils.Decorate(Dropdown, Search);
  1100. options.dropdownAdapter = SearchableDropdown;
  1101. }
  1102. if (options.selectionAdapter == null) {
  1103. if (options.multiple) {
  1104. options.selectionAdapter = MultipleSelection;
  1105. } else {
  1106. options.selectionAdapter = SingleSelection;
  1107. }
  1108. // Add the placeholder mixin if a placeholder was specified
  1109. if (options.placeholder != null) {
  1110. options.selectionAdapter = Utils.Decorate(
  1111. options.selectionAdapter,
  1112. Placeholder
  1113. );
  1114. }
  1115. }
  1116. return options;
  1117. };
  1118. Defaults.prototype.reset = function () {
  1119. this.defaults = { };
  1120. };
  1121. var defaults = new Defaults();
  1122. return defaults;
  1123. });
  1124. define('select2/options',[
  1125. './defaults'
  1126. ], function (Defaults) {
  1127. function Options (options) {
  1128. this.options = Defaults.apply(options);
  1129. }
  1130. Options.prototype.fromElement = function ($e) {
  1131. return this;
  1132. };
  1133. Options.prototype.get = function (key) {
  1134. return this.options[key];
  1135. };
  1136. Options.prototype.set = function (key, val) {
  1137. this.options[key] = val;
  1138. };
  1139. return Options;
  1140. });
  1141. define('select2/core',[
  1142. 'jquery',
  1143. './options',
  1144. './utils'
  1145. ], function ($, Options, Utils) {
  1146. var Select2 = function ($element, options) {
  1147. this.$element = $element;
  1148. options = options || {};
  1149. options.multiple = options.multiple || $element.prop('multiple');
  1150. this.options = new Options(options);
  1151. Select2.__super__.constructor.call(this);
  1152. // Set up containers and adapters
  1153. var DataAdapter = this.options.get('dataAdapter');
  1154. this.data = new DataAdapter($element, this.options);
  1155. var $container = this.render();
  1156. this.$container = $container;
  1157. $container.insertAfter(this.$element);
  1158. $container.width($element.outerWidth(false));
  1159. var SelectionAdapter = this.options.get('selectionAdapter');
  1160. this.selection = new SelectionAdapter($element, this.options);
  1161. var $selectionContainer = $container.find('.selection');
  1162. var $selection = this.selection.render();
  1163. $selectionContainer.append($selection);
  1164. var DropdownAdapter = this.options.get('dropdownAdapter');
  1165. this.dropdown = new DropdownAdapter($element, this.options);
  1166. var $dropdownContainer = $container.find('.dropdown-wrapper');
  1167. var $dropdown = this.dropdown.render();
  1168. $dropdownContainer.append($dropdown);
  1169. var ResultsAdapter = this.options.get('resultsAdapter');
  1170. this.results = new ResultsAdapter($element, this.options, this.data);
  1171. var $resultsContainer = $dropdown.find('.results');
  1172. var $results = this.results.render();
  1173. $resultsContainer.append($results);
  1174. // Bind events
  1175. var self = this;
  1176. this.data.bind(this, $container);
  1177. this.selection.bind(this, $container);
  1178. this.dropdown.bind(this, $container);
  1179. this.results.bind(this, $container);
  1180. this.$element.on('change', function () {
  1181. self.data.current(function (data) {
  1182. self.trigger('selection:update', {
  1183. data: data
  1184. });
  1185. });
  1186. });
  1187. this.selection.on('toggle', function () {
  1188. self.toggleDropdown();
  1189. });
  1190. this.selection.on('unselected', function (params) {
  1191. self.trigger('unselect', params);
  1192. self.trigger('close');
  1193. });
  1194. this.results.on('selected', function (params) {
  1195. self.trigger('select', params);
  1196. self.trigger('close');
  1197. });
  1198. this.results.on('unselected', function (params) {
  1199. self.trigger('unselect', params);
  1200. self.trigger('close');
  1201. });
  1202. this.on('open', function () {
  1203. $container.addClass('open');
  1204. });
  1205. this.on('close', function () {
  1206. $container.removeClass('open');
  1207. });
  1208. // Set the initial state
  1209. this.data.current(function (initialData) {
  1210. self.trigger('selection:update', {
  1211. data: initialData
  1212. });
  1213. });
  1214. this.on('query', function (params) {
  1215. this.data.query(params, function (data) {
  1216. self.trigger('results:all', {
  1217. data: data,
  1218. query: params
  1219. });
  1220. });
  1221. });
  1222. this.trigger('query', {});
  1223. // Hide the original select
  1224. $element.hide();
  1225. };
  1226. Utils.Extend(Select2, Utils.Observable);
  1227. Select2.prototype.toggleDropdown = function () {
  1228. if (this.$container.hasClass('open')) {
  1229. this.trigger('close');
  1230. } else {
  1231. this.trigger('open');
  1232. }
  1233. };
  1234. Select2.prototype.render = function () {
  1235. var $container = $(
  1236. '<span class="select2 select2-container select2-theme-default">' +
  1237. '<span class="selection"></span>' +
  1238. '<span class="dropdown-wrapper"></span>' +
  1239. '</span>'
  1240. );
  1241. return $container;
  1242. };
  1243. return Select2;
  1244. });
  1245. define('jquery.select2',[
  1246. 'jquery',
  1247. 'select2/core'
  1248. ], function ($, Select2) {
  1249. if ($.fn.select2 == null) {
  1250. $.fn.select2 = function (options) {
  1251. options = options || {};
  1252. if (typeof options === 'object') {
  1253. this.each(function () {
  1254. var instance = new Select2($(this), options);
  1255. });
  1256. } else if (typeof options === 'string') {
  1257. var instance = this.data('select2');
  1258. instance[options](arguments.slice(1));
  1259. } else {
  1260. throw new Error('Invalid arguments for Select2: ' + options);
  1261. }
  1262. };
  1263. }
  1264. return Select2;
  1265. });
  1266. require('jquery.select2');