yii.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. conflictParams = ['submit', 'reset', 'elements', 'length', 'name', 'acceptCharset',
  158. 'action', 'enctype', 'method', 'target'];
  159. // Forms and their child elements should not use input names or ids that conflict with properties of a form,
  160. // such as submit, length, or method.
  161. $.each(conflictParams, function (index, param) {
  162. if (areValidParams && params.hasOwnProperty(param)) {
  163. console.error("Parameter name '" + param + "' conflicts with a same named form property. " +
  164. "Please use another name.");
  165. }
  166. });
  167. if (usePjax) {
  168. pjaxContainer = $e.data('pjax-container');
  169. if (pjaxContainer === undefined || !pjaxContainer.length) {
  170. pjaxContainer = $e.closest('[data-pjax-container]').attr('id')
  171. ? ('#' + $e.closest('[data-pjax-container]').attr('id'))
  172. : '';
  173. }
  174. if (!pjaxContainer.length) {
  175. pjaxContainer = 'body';
  176. }
  177. pjaxOptions = {
  178. container: pjaxContainer,
  179. push: !!$e.data('pjax-push-state'),
  180. replace: !!$e.data('pjax-replace-state'),
  181. scrollTo: $e.data('pjax-scrollto'),
  182. pushRedirect: $e.data('pjax-push-redirect'),
  183. replaceRedirect: $e.data('pjax-replace-redirect'),
  184. skipOuterContainers: $e.data('pjax-skip-outer-containers'),
  185. timeout: $e.data('pjax-timeout'),
  186. originalEvent: event,
  187. originalTarget: $e
  188. };
  189. }
  190. if (method === undefined) {
  191. if (isValidAction) {
  192. usePjax ? $.pjax.click(event, pjaxOptions) : window.location.assign(action);
  193. } else if ($e.is(':submit') && $form.length) {
  194. if (usePjax) {
  195. $form.on('submit', function (e) {
  196. $.pjax.submit(e, pjaxOptions);
  197. });
  198. }
  199. $form.trigger('submit');
  200. }
  201. return;
  202. }
  203. var oldMethod,
  204. oldAction,
  205. newForm = !$form.length;
  206. if (!newForm) {
  207. oldMethod = $form.attr('method');
  208. $form.attr('method', method);
  209. if (isValidAction) {
  210. oldAction = $form.attr('action');
  211. $form.attr('action', action);
  212. }
  213. } else {
  214. if (!isValidAction) {
  215. action = pub.getCurrentUrl();
  216. }
  217. $form = $('<form/>', {method: method, action: action});
  218. var target = $e.attr('target');
  219. if (target) {
  220. $form.attr('target', target);
  221. }
  222. if (!/(get|post)/i.test(method)) {
  223. $form.append($('<input/>', {name: '_method', value: method, type: 'hidden'}));
  224. method = 'post';
  225. $form.attr('method', method);
  226. }
  227. if (/post/i.test(method)) {
  228. var csrfParam = pub.getCsrfParam();
  229. if (csrfParam) {
  230. $form.append($('<input/>', {name: csrfParam, value: pub.getCsrfToken(), type: 'hidden'}));
  231. }
  232. }
  233. $form.hide().appendTo('body');
  234. }
  235. var activeFormData = $form.data('yiiActiveForm');
  236. if (activeFormData) {
  237. // Remember the element triggered the form submission. This is used by yii.activeForm.js.
  238. activeFormData.submitObject = $e;
  239. }
  240. if (areValidParams) {
  241. $.each(params, function (name, value) {
  242. $form.append($('<input/>').attr({name: name, value: value, type: 'hidden'}));
  243. });
  244. }
  245. if (usePjax) {
  246. $form.on('submit', function (e) {
  247. $.pjax.submit(e, pjaxOptions);
  248. });
  249. }
  250. $form.trigger('submit');
  251. $.when($form.data('yiiSubmitFinalizePromise')).done(function () {
  252. if (newForm) {
  253. $form.remove();
  254. return;
  255. }
  256. if (oldAction !== undefined) {
  257. $form.attr('action', oldAction);
  258. }
  259. $form.attr('method', oldMethod);
  260. if (areValidParams) {
  261. $.each(params, function (name) {
  262. $('input[name="' + name + '"]', $form).remove();
  263. });
  264. }
  265. });
  266. },
  267. getQueryParams: function (url) {
  268. var pos = url.indexOf('?');
  269. if (pos < 0) {
  270. return {};
  271. }
  272. var pairs = $.grep(url.substring(pos + 1).split('#')[0].split('&'), function (value) {
  273. return value !== '';
  274. });
  275. var params = {};
  276. for (var i = 0, len = pairs.length; i < len; i++) {
  277. var pair = pairs[i].split('=');
  278. var name = decodeURIComponent(pair[0].replace(/\+/g, '%20'));
  279. var value = decodeURIComponent(pair[1].replace(/\+/g, '%20'));
  280. if (!name.length) {
  281. continue;
  282. }
  283. if (params[name] === undefined) {
  284. params[name] = value || '';
  285. } else {
  286. if (!$.isArray(params[name])) {
  287. params[name] = [params[name]];
  288. }
  289. params[name].push(value || '');
  290. }
  291. }
  292. return params;
  293. },
  294. initModule: function (module) {
  295. if (module.isActive !== undefined && !module.isActive) {
  296. return;
  297. }
  298. if ($.isFunction(module.init)) {
  299. module.init();
  300. }
  301. $.each(module, function () {
  302. if ($.isPlainObject(this)) {
  303. pub.initModule(this);
  304. }
  305. });
  306. },
  307. init: function () {
  308. initCsrfHandler();
  309. initRedirectHandler();
  310. initAssetFilters();
  311. initDataMethods();
  312. },
  313. /**
  314. * Returns the URL of the current page without params and trailing slash. Separated and made public for testing.
  315. * @returns {string}
  316. */
  317. getBaseCurrentUrl: function () {
  318. return window.location.protocol + '//' + window.location.host;
  319. },
  320. /**
  321. * Returns the URL of the current page. Used for testing, you can always call `window.location.href` manually
  322. * instead.
  323. * @returns {string}
  324. */
  325. getCurrentUrl: function () {
  326. return window.location.href;
  327. }
  328. };
  329. function initCsrfHandler() {
  330. // automatically send CSRF token for all AJAX requests
  331. $.ajaxPrefilter(function (options, originalOptions, xhr) {
  332. if (!options.crossDomain && pub.getCsrfParam()) {
  333. xhr.setRequestHeader('X-CSRF-Token', pub.getCsrfToken());
  334. }
  335. });
  336. pub.refreshCsrfToken();
  337. }
  338. function initRedirectHandler() {
  339. // handle AJAX redirection
  340. $(document).ajaxComplete(function (event, xhr) {
  341. var url = xhr && xhr.getResponseHeader('X-Redirect');
  342. if (url) {
  343. window.location.assign(url);
  344. }
  345. });
  346. }
  347. function initAssetFilters() {
  348. /**
  349. * Used for storing loaded scripts and information about loading each script if it's in the process of loading.
  350. * A single script can have one of the following values:
  351. *
  352. * - `undefined` - script was not loaded at all before or was loaded with error last time.
  353. * - `true` (boolean) - script was successfully loaded.
  354. * - object - script is currently loading.
  355. *
  356. * In case of a value being an object the properties are:
  357. * - `xhrList` - represents a queue of XHR requests sent to the same URL (related with this script) in the same
  358. * small period of time.
  359. * - `xhrDone` - boolean, acts like a locking mechanism. When one of the XHR requests in the queue is
  360. * successfully completed, it will abort the rest of concurrent requests to the same URL until cleanup is done
  361. * to prevent possible errors and race conditions.
  362. * @type {{}}
  363. */
  364. var loadedScripts = {};
  365. $('script[src]').each(function () {
  366. var url = getAbsoluteUrl(this.src);
  367. loadedScripts[url] = true;
  368. });
  369. $.ajaxPrefilter('script', function (options, originalOptions, xhr) {
  370. if (options.dataType == 'jsonp') {
  371. return;
  372. }
  373. var url = getAbsoluteUrl(options.url),
  374. forbiddenRepeatedLoad = loadedScripts[url] === true && !isReloadableAsset(url),
  375. cleanupRunning = loadedScripts[url] !== undefined && loadedScripts[url]['xhrDone'] === true;
  376. if (forbiddenRepeatedLoad || cleanupRunning) {
  377. xhr.abort();
  378. return;
  379. }
  380. if (loadedScripts[url] === undefined || loadedScripts[url] === true) {
  381. loadedScripts[url] = {
  382. xhrList: [],
  383. xhrDone: false
  384. };
  385. }
  386. xhr.done(function (data, textStatus, jqXHR) {
  387. // If multiple requests were successfully loaded, perform cleanup only once
  388. if (loadedScripts[jqXHR.yiiUrl]['xhrDone'] === true) {
  389. return;
  390. }
  391. loadedScripts[jqXHR.yiiUrl]['xhrDone'] = true;
  392. for (var i = 0, len = loadedScripts[jqXHR.yiiUrl]['xhrList'].length; i < len; i++) {
  393. var singleXhr = loadedScripts[jqXHR.yiiUrl]['xhrList'][i];
  394. if (singleXhr && singleXhr.readyState !== XMLHttpRequest.DONE) {
  395. singleXhr.abort();
  396. }
  397. }
  398. loadedScripts[jqXHR.yiiUrl] = true;
  399. }).fail(function (jqXHR, textStatus) {
  400. if (textStatus === 'abort') {
  401. return;
  402. }
  403. delete loadedScripts[jqXHR.yiiUrl]['xhrList'][jqXHR.yiiIndex];
  404. var allFailed = true;
  405. for (var i = 0, len = loadedScripts[jqXHR.yiiUrl]['xhrList'].length; i < len; i++) {
  406. if (loadedScripts[jqXHR.yiiUrl]['xhrList'][i]) {
  407. allFailed = false;
  408. }
  409. }
  410. if (allFailed) {
  411. delete loadedScripts[jqXHR.yiiUrl];
  412. }
  413. });
  414. // Use prefix for custom XHR properties to avoid possible conflicts with existing properties
  415. xhr.yiiIndex = loadedScripts[url]['xhrList'].length;
  416. xhr.yiiUrl = url;
  417. loadedScripts[url]['xhrList'][xhr.yiiIndex] = xhr;
  418. });
  419. $(document).ajaxComplete(function () {
  420. var styleSheets = [];
  421. $('link[rel=stylesheet]').each(function () {
  422. var url = getAbsoluteUrl(this.href);
  423. if (isReloadableAsset(url)) {
  424. return;
  425. }
  426. $.inArray(url, styleSheets) === -1 ? styleSheets.push(url) : $(this).remove();
  427. });
  428. });
  429. }
  430. function initDataMethods() {
  431. var handler = function (event) {
  432. var $this = $(this),
  433. method = $this.data('method'),
  434. message = $this.data('confirm'),
  435. form = $this.data('form');
  436. if (method === undefined && message === undefined && form === undefined) {
  437. return true;
  438. }
  439. if (message !== undefined && message !== false && message !== '') {
  440. $.proxy(pub.confirm, this)(message, function () {
  441. pub.handleAction($this, event);
  442. });
  443. } else {
  444. pub.handleAction($this, event);
  445. }
  446. event.stopImmediatePropagation();
  447. return false;
  448. };
  449. // handle data-confirm and data-method for clickable and changeable elements
  450. $(document).on('click.yii', pub.clickableSelector, handler)
  451. .on('change.yii', pub.changeableSelector, handler);
  452. }
  453. function isReloadableAsset(url) {
  454. for (var i = 0; i < pub.reloadableScripts.length; i++) {
  455. var rule = getAbsoluteUrl(pub.reloadableScripts[i]);
  456. var match = new RegExp("^" + escapeRegExp(rule).split('\\*').join('.+') + "$").test(url);
  457. if (match === true) {
  458. return true;
  459. }
  460. }
  461. return false;
  462. }
  463. // http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
  464. function escapeRegExp(str) {
  465. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  466. }
  467. /**
  468. * Returns absolute URL based on the given URL
  469. * @param {string} url Initial URL
  470. * @returns {string}
  471. */
  472. function getAbsoluteUrl(url) {
  473. return url.charAt(0) === '/' ? pub.getBaseCurrentUrl() + url : url;
  474. }
  475. return pub;
  476. })(window.jQuery);
  477. window.jQuery(function () {
  478. window.yii.initModule(window.yii);
  479. });