yii.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. /**
  2. * Yii JavaScript module.
  3. *
  4. * @link http://www.yiiframework.com/
  5. * @copyright Copyright (c) 2008 Yii Software LLC
  6. * @license http://www.yiiframework.com/license/
  7. * @author Qiang Xue <qiang.xue@gmail.com>
  8. * @since 2.0
  9. */
  10. /**
  11. * yii is the root module for all Yii JavaScript modules.
  12. * It implements a mechanism of organizing JavaScript code in modules through the function "yii.initModule()".
  13. *
  14. * Each module should be named as "x.y.z", where "x" stands for the root module (for the Yii core code, this is "yii").
  15. *
  16. * A module may be structured as follows:
  17. *
  18. * ```javascript
  19. * window.yii.sample = (function($) {
  20. * var pub = {
  21. * // whether this module is currently active. If false, init() will not be called for this module
  22. * // it will also not be called for all its child modules. If this property is undefined, it means true.
  23. * isActive: true,
  24. * init: function() {
  25. * // ... module initialization code goes here ...
  26. * },
  27. *
  28. * // ... other public functions and properties go here ...
  29. * };
  30. *
  31. * // ... private functions and properties go here ...
  32. *
  33. * return pub;
  34. * })(window.jQuery);
  35. * ```
  36. *
  37. * Using this structure, you can define public and private functions/properties for a module.
  38. * Private functions/properties are only visible within the module, while public functions/properties
  39. * may be accessed outside of the module. For example, you can access "yii.sample.isActive".
  40. *
  41. * You must call "yii.initModule()" once for the root module of all your modules.
  42. */
  43. window.yii = (function ($) {
  44. var pub = {
  45. /**
  46. * List of JS or CSS URLs that can be loaded multiple times via AJAX requests.
  47. * Each item may be represented as either an absolute URL or a relative one.
  48. * Each item may contain a wildcard matching character `*`, that means one or more
  49. * any characters on the position. For example:
  50. * - `/css/*.css` will match any file ending with `.css` in the `css` directory of the current web site
  51. * - `http*://cdn.example.com/*` will match any files on domain `cdn.example.com`, loaded with HTTP or HTTPS
  52. * - `/js/myCustomScript.js?realm=*` will match file `/js/myCustomScript.js` with defined `realm` parameter
  53. */
  54. reloadableScripts: [],
  55. /**
  56. * The selector for clickable elements that need to support confirmation and form submission.
  57. */
  58. clickableSelector: 'a, button, input[type="submit"], input[type="button"], input[type="reset"], ' +
  59. 'input[type="image"]',
  60. /**
  61. * The selector for changeable elements that need to support confirmation and form submission.
  62. */
  63. changeableSelector: 'select, input, textarea',
  64. /**
  65. * @return string|undefined the CSRF parameter name. Undefined is returned if CSRF validation is not enabled.
  66. */
  67. getCsrfParam: function () {
  68. return $('meta[name=csrf-param]').attr('content');
  69. },
  70. /**
  71. * @return string|undefined the CSRF token. Undefined is returned if CSRF validation is not enabled.
  72. */
  73. getCsrfToken: function () {
  74. return $('meta[name=csrf-token]').attr('content');
  75. },
  76. /**
  77. * Sets the CSRF token in the meta elements.
  78. * This method is provided so that you can update the CSRF token with the latest one you obtain from the server.
  79. * @param name the CSRF token name
  80. * @param value the CSRF token value
  81. */
  82. setCsrfToken: function (name, value) {
  83. $('meta[name=csrf-param]').attr('content', name);
  84. $('meta[name=csrf-token]').attr('content', value);
  85. },
  86. /**
  87. * Updates all form CSRF input fields with the latest CSRF token.
  88. * This method is provided to avoid cached forms containing outdated CSRF tokens.
  89. */
  90. refreshCsrfToken: function () {
  91. var token = pub.getCsrfToken();
  92. if (token) {
  93. $('form input[name="' + pub.getCsrfParam() + '"]').val(token);
  94. }
  95. },
  96. /**
  97. * Displays a confirmation dialog.
  98. * The default implementation simply displays a js confirmation dialog.
  99. * You may override this by setting `yii.confirm`.
  100. * @param message the confirmation message.
  101. * @param ok a callback to be called when the user confirms the message
  102. * @param cancel a callback to be called when the user cancels the confirmation
  103. */
  104. confirm: function (message, ok, cancel) {
  105. if (window.confirm(message)) {
  106. !ok || ok();
  107. } else {
  108. !cancel || cancel();
  109. }
  110. },
  111. /**
  112. * Handles the action triggered by user.
  113. * This method recognizes the `data-method` attribute of the element. If the attribute exists,
  114. * the method will submit the form containing this element. If there is no containing form, a form
  115. * will be created and submitted using the method given by this attribute value (e.g. "post", "put").
  116. * For hyperlinks, the form action will take the value of the "href" attribute of the link.
  117. * For other elements, either the containing form action or the current page URL will be used
  118. * as the form action URL.
  119. *
  120. * If the `data-method` attribute is not defined, the `href` attribute (if any) of the element
  121. * will be assigned to `window.location`.
  122. *
  123. * Starting from version 2.0.3, the `data-params` attribute is also recognized when you specify
  124. * `data-method`. The value of `data-params` should be a JSON representation of the data (name-value pairs)
  125. * that should be submitted as hidden inputs. For example, you may use the following code to generate
  126. * such a link:
  127. *
  128. * ```php
  129. * use yii\helpers\Html;
  130. * use yii\helpers\Json;
  131. *
  132. * echo Html::a('submit', ['site/foobar'], [
  133. * 'data' => [
  134. * 'method' => 'post',
  135. * 'params' => [
  136. * 'name1' => 'value1',
  137. * 'name2' => 'value2',
  138. * ],
  139. * ],
  140. * ]);
  141. * ```
  142. *
  143. * @param $e the jQuery representation of the element
  144. * @param event Related event
  145. */
  146. handleAction: function ($e, event) {
  147. var $form = $e.attr('data-form') ? $('#' + $e.attr('data-form')) : $e.closest('form'),
  148. method = !$e.data('method') && $form ? $form.attr('method') : $e.data('method'),
  149. action = $e.attr('href'),
  150. isValidAction = action && action !== '#',
  151. params = $e.data('params'),
  152. areValidParams = params && $.isPlainObject(params),
  153. pjax = $e.data('pjax'),
  154. usePjax = pjax !== undefined && pjax !== 0 && $.support.pjax,
  155. pjaxContainer,
  156. pjaxOptions = {};
  157. if (usePjax) {
  158. pjaxContainer = $e.data('pjax-container') || $e.closest('[data-pjax-container]');
  159. if (!pjaxContainer.length) {
  160. pjaxContainer = $('body');
  161. }
  162. pjaxOptions = {
  163. container: pjaxContainer,
  164. push: !!$e.data('pjax-push-state'),
  165. replace: !!$e.data('pjax-replace-state'),
  166. scrollTo: $e.data('pjax-scrollto'),
  167. pushRedirect: $e.data('pjax-push-redirect'),
  168. replaceRedirect: $e.data('pjax-replace-redirect'),
  169. skipOuterContainers: $e.data('pjax-skip-outer-containers'),
  170. timeout: $e.data('pjax-timeout'),
  171. originalEvent: event,
  172. originalTarget: $e
  173. };
  174. }
  175. if (method === undefined) {
  176. if (isValidAction) {
  177. usePjax ? $.pjax.click(event, pjaxOptions) : window.location.assign(action);
  178. } else if ($e.is(':submit') && $form.length) {
  179. if (usePjax) {
  180. $form.on('submit', function (e) {
  181. $.pjax.submit(e, pjaxOptions);
  182. });
  183. }
  184. $form.trigger('submit');
  185. }
  186. return;
  187. }
  188. var oldMethod,
  189. oldAction,
  190. newForm = !$form.length;
  191. if (!newForm) {
  192. oldMethod = $form.attr('method');
  193. $form.attr('method', method);
  194. if (isValidAction) {
  195. oldAction = $form.attr('action');
  196. $form.attr('action', action);
  197. }
  198. } else {
  199. if (!isValidAction) {
  200. action = pub.getCurrentUrl();
  201. }
  202. $form = $('<form/>', {method: method, action: action});
  203. var target = $e.attr('target');
  204. if (target) {
  205. $form.attr('target', target);
  206. }
  207. if (!/(get|post)/i.test(method)) {
  208. $form.append($('<input/>', {name: '_method', value: method, type: 'hidden'}));
  209. method = 'post';
  210. $form.attr('method', method);
  211. }
  212. if (/post/i.test(method)) {
  213. var csrfParam = pub.getCsrfParam();
  214. if (csrfParam) {
  215. $form.append($('<input/>', {name: csrfParam, value: pub.getCsrfToken(), type: 'hidden'}));
  216. }
  217. }
  218. $form.hide().appendTo('body');
  219. }
  220. var activeFormData = $form.data('yiiActiveForm');
  221. if (activeFormData) {
  222. // Remember the element triggered the form submission. This is used by yii.activeForm.js.
  223. activeFormData.submitObject = $e;
  224. }
  225. if (areValidParams) {
  226. $.each(params, function (name, value) {
  227. $form.append($('<input/>').attr({name: name, value: value, type: 'hidden'}));
  228. });
  229. }
  230. if (usePjax) {
  231. $form.on('submit', function (e) {
  232. $.pjax.submit(e, pjaxOptions);
  233. });
  234. }
  235. $form.trigger('submit');
  236. $.when($form.data('yiiSubmitFinalizePromise')).then(function () {
  237. if (newForm) {
  238. $form.remove();
  239. return;
  240. }
  241. if (oldAction !== undefined) {
  242. $form.attr('action', oldAction);
  243. }
  244. $form.attr('method', oldMethod);
  245. if (areValidParams) {
  246. $.each(params, function (name) {
  247. $('input[name="' + name + '"]', $form).remove();
  248. });
  249. }
  250. });
  251. },
  252. getQueryParams: function (url) {
  253. var pos = url.indexOf('?');
  254. if (pos < 0) {
  255. return {};
  256. }
  257. var pairs = url.substring(pos + 1).split('#')[0].split('&'),
  258. params = {};
  259. for (var i = 0, len = pairs.length; i < len; i++) {
  260. var pair = pairs[i].split('=');
  261. var name = decodeURIComponent(pair[0].replace(/\+/g, '%20'));
  262. var value = decodeURIComponent(pair[1].replace(/\+/g, '%20'));
  263. if (!name.length) {
  264. continue;
  265. }
  266. if (params[name] === undefined) {
  267. params[name] = value || '';
  268. } else {
  269. if (!$.isArray(params[name])) {
  270. params[name] = [params[name]];
  271. }
  272. params[name].push(value || '');
  273. }
  274. }
  275. return params;
  276. },
  277. initModule: function (module) {
  278. if (module.isActive !== undefined && !module.isActive) {
  279. return;
  280. }
  281. if ($.isFunction(module.init)) {
  282. module.init();
  283. }
  284. $.each(module, function () {
  285. if ($.isPlainObject(this)) {
  286. pub.initModule(this);
  287. }
  288. });
  289. },
  290. init: function () {
  291. initCsrfHandler();
  292. initRedirectHandler();
  293. initAssetFilters();
  294. initDataMethods();
  295. },
  296. /**
  297. * Returns the URL of the current page without params and trailing slash. Separated and made public for testing.
  298. * @returns {string}
  299. */
  300. getBaseCurrentUrl: function () {
  301. return window.location.protocol + '//' + window.location.host;
  302. },
  303. /**
  304. * Returns the URL of the current page. Used for testing, you can always call `window.location.href` manually
  305. * instead.
  306. * @returns {string}
  307. */
  308. getCurrentUrl: function () {
  309. return window.location.href;
  310. }
  311. };
  312. function initCsrfHandler() {
  313. // automatically send CSRF token for all AJAX requests
  314. $.ajaxPrefilter(function (options, originalOptions, xhr) {
  315. if (!options.crossDomain && pub.getCsrfParam()) {
  316. xhr.setRequestHeader('X-CSRF-Token', pub.getCsrfToken());
  317. }
  318. });
  319. pub.refreshCsrfToken();
  320. }
  321. function initRedirectHandler() {
  322. // handle AJAX redirection
  323. $(document).ajaxComplete(function (event, xhr) {
  324. var url = xhr && xhr.getResponseHeader('X-Redirect');
  325. if (url) {
  326. window.location.assign(url);
  327. }
  328. });
  329. }
  330. function initAssetFilters() {
  331. /**
  332. * Used for storing loaded scripts and information about loading each script if it's in the process of loading.
  333. * A single script can have one of the following values:
  334. *
  335. * - `undefined` - script was not loaded at all before or was loaded with error last time.
  336. * - `true` (boolean) - script was successfully loaded.
  337. * - object - script is currently loading.
  338. *
  339. * In case of a value being an object the properties are:
  340. * - `xhrList` - represents a queue of XHR requests sent to the same URL (related with this script) in the same
  341. * small period of time.
  342. * - `xhrDone` - boolean, acts like a locking mechanism. When one of the XHR requests in the queue is
  343. * successfully completed, it will abort the rest of concurrent requests to the same URL until cleanup is done
  344. * to prevent possible errors and race conditions.
  345. * @type {{}}
  346. */
  347. var loadedScripts = {};
  348. $('script[src]').each(function () {
  349. var url = getAbsoluteUrl(this.src);
  350. loadedScripts[url] = true;
  351. });
  352. $.ajaxPrefilter('script', function (options, originalOptions, xhr) {
  353. if (options.dataType == 'jsonp') {
  354. return;
  355. }
  356. var url = getAbsoluteUrl(options.url),
  357. forbiddenRepeatedLoad = loadedScripts[url] === true && !isReloadableAsset(url),
  358. cleanupRunning = loadedScripts[url] !== undefined && loadedScripts[url]['xhrDone'] === true;
  359. if (forbiddenRepeatedLoad || cleanupRunning) {
  360. xhr.abort();
  361. return;
  362. }
  363. if (loadedScripts[url] === undefined || loadedScripts[url] === true) {
  364. loadedScripts[url] = {
  365. xhrList: [],
  366. xhrDone: false
  367. };
  368. }
  369. xhr.done(function (data, textStatus, jqXHR) {
  370. // If multiple requests were successfully loaded, perform cleanup only once
  371. if (loadedScripts[jqXHR.yiiUrl]['xhrDone'] === true) {
  372. return;
  373. }
  374. loadedScripts[jqXHR.yiiUrl]['xhrDone'] = true;
  375. for (var i = 0, len = loadedScripts[jqXHR.yiiUrl]['xhrList'].length; i < len; i++) {
  376. var singleXhr = loadedScripts[jqXHR.yiiUrl]['xhrList'][i];
  377. if (singleXhr && singleXhr.readyState !== XMLHttpRequest.DONE) {
  378. singleXhr.abort();
  379. }
  380. }
  381. loadedScripts[jqXHR.yiiUrl] = true;
  382. }).fail(function (jqXHR, textStatus) {
  383. if (textStatus === 'abort') {
  384. return;
  385. }
  386. delete loadedScripts[jqXHR.yiiUrl]['xhrList'][jqXHR.yiiIndex];
  387. var allFailed = true;
  388. for (var i = 0, len = loadedScripts[jqXHR.yiiUrl]['xhrList'].length; i < len; i++) {
  389. if (loadedScripts[jqXHR.yiiUrl]['xhrList'][i]) {
  390. allFailed = false;
  391. }
  392. }
  393. if (allFailed) {
  394. delete loadedScripts[jqXHR.yiiUrl];
  395. }
  396. });
  397. // Use prefix for custom XHR properties to avoid possible conflicts with existing properties
  398. xhr.yiiIndex = loadedScripts[url]['xhrList'].length;
  399. xhr.yiiUrl = url;
  400. loadedScripts[url]['xhrList'][xhr.yiiIndex] = xhr;
  401. });
  402. $(document).ajaxComplete(function () {
  403. var styleSheets = [];
  404. $('link[rel=stylesheet]').each(function () {
  405. var url = getAbsoluteUrl(this.href);
  406. if (isReloadableAsset(url)) {
  407. return;
  408. }
  409. $.inArray(url, styleSheets) === -1 ? styleSheets.push(url) : $(this).remove();
  410. });
  411. });
  412. }
  413. function initDataMethods() {
  414. var handler = function (event) {
  415. var $this = $(this),
  416. method = $this.data('method'),
  417. message = $this.data('confirm'),
  418. form = $this.data('form');
  419. if (method === undefined && message === undefined && form === undefined) {
  420. return true;
  421. }
  422. if (message !== undefined) {
  423. $.proxy(pub.confirm, this)(message, function () {
  424. pub.handleAction($this, event);
  425. });
  426. } else {
  427. pub.handleAction($this, event);
  428. }
  429. event.stopImmediatePropagation();
  430. return false;
  431. };
  432. // handle data-confirm and data-method for clickable and changeable elements
  433. $(document).on('click.yii', pub.clickableSelector, handler)
  434. .on('change.yii', pub.changeableSelector, handler);
  435. }
  436. function isReloadableAsset(url) {
  437. for (var i = 0; i < pub.reloadableScripts.length; i++) {
  438. var rule = getAbsoluteUrl(pub.reloadableScripts[i]);
  439. var match = new RegExp("^" + escapeRegExp(rule).split('\\*').join('.*') + "$").test(url);
  440. if (match === true) {
  441. return true;
  442. }
  443. }
  444. return false;
  445. }
  446. // http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
  447. function escapeRegExp(str) {
  448. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  449. }
  450. /**
  451. * Returns absolute URL based on the given URL
  452. * @param {string} url Initial URL
  453. * @returns {string}
  454. */
  455. function getAbsoluteUrl(url) {
  456. return url.charAt(0) === '/' ? pub.getBaseCurrentUrl() + url : url;
  457. }
  458. return pub;
  459. })(window.jQuery);
  460. window.jQuery(function () {
  461. window.yii.initModule(window.yii);
  462. });