states.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. (function ($) {
  2. /**
  3. * The base States namespace.
  4. *
  5. * Having the local states variable allows us to use the States namespace
  6. * without having to always declare "Drupal.states".
  7. */
  8. var states = Drupal.states = {
  9. // An array of functions that should be postponed.
  10. postponed: []
  11. };
  12. /**
  13. * Attaches the states.
  14. */
  15. Drupal.behaviors.states = {
  16. attach: function (context, settings) {
  17. for (var selector in settings.states) {
  18. for (var state in settings.states[selector]) {
  19. new states.Dependent({
  20. element: $(selector),
  21. state: states.State.sanitize(state),
  22. dependees: settings.states[selector][state]
  23. });
  24. }
  25. }
  26. // Execute all postponed functions now.
  27. while (states.postponed.length) {
  28. (states.postponed.shift())();
  29. }
  30. }
  31. };
  32. /**
  33. * Object representing an element that depends on other elements.
  34. *
  35. * @param args
  36. * Object with the following keys (all of which are required):
  37. * - element: A jQuery object of the dependent element
  38. * - state: A State object describing the state that is dependent
  39. * - dependees: An object with dependency specifications. Lists all elements
  40. * that this element depends on.
  41. */
  42. states.Dependent = function (args) {
  43. $.extend(this, { values: {}, oldValue: undefined }, args);
  44. for (var selector in this.dependees) {
  45. this.initializeDependee(selector, this.dependees[selector]);
  46. }
  47. };
  48. /**
  49. * Comparison functions for comparing the value of an element with the
  50. * specification from the dependency settings. If the object type can't be
  51. * found in this list, the === operator is used by default.
  52. */
  53. states.Dependent.comparisons = {
  54. 'RegExp': function (reference, value) {
  55. return reference.test(value);
  56. },
  57. 'Function': function (reference, value) {
  58. // The "reference" variable is a comparison function.
  59. return reference(value);
  60. },
  61. 'Number': function (reference, value) {
  62. // If "reference" is a number and "value" is a string, then cast reference
  63. // as a string before applying the strict comparison in compare(). Otherwise
  64. // numeric keys in the form's #states array fail to match string values
  65. // returned from jQuery's val().
  66. return (value.constructor.name === 'String') ? compare(String(reference), value) : compare(reference, value);
  67. }
  68. };
  69. states.Dependent.prototype = {
  70. /**
  71. * Initializes one of the elements this dependent depends on.
  72. *
  73. * @param selector
  74. * The CSS selector describing the dependee.
  75. * @param dependeeStates
  76. * The list of states that have to be monitored for tracking the
  77. * dependee's compliance status.
  78. */
  79. initializeDependee: function (selector, dependeeStates) {
  80. var self = this;
  81. // Cache for the states of this dependee.
  82. self.values[selector] = {};
  83. $.each(dependeeStates, function (state, value) {
  84. state = states.State.sanitize(state);
  85. // Initialize the value of this state.
  86. self.values[selector][state.pristine] = undefined;
  87. // Monitor state changes of the specified state for this dependee.
  88. $(selector).bind('state:' + state, function (e) {
  89. var complies = self.compare(value, e.value);
  90. self.update(selector, state, complies);
  91. });
  92. // Make sure the event we just bound ourselves to is actually fired.
  93. new states.Trigger({ selector: selector, state: state });
  94. });
  95. },
  96. /**
  97. * Compares a value with a reference value.
  98. *
  99. * @param reference
  100. * The value used for reference.
  101. * @param value
  102. * The value to compare with the reference value.
  103. * @return
  104. * true, undefined or false.
  105. */
  106. compare: function (reference, value) {
  107. if (reference.constructor.name in states.Dependent.comparisons) {
  108. // Use a custom compare function for certain reference value types.
  109. return states.Dependent.comparisons[reference.constructor.name](reference, value);
  110. }
  111. else {
  112. // Do a plain comparison otherwise.
  113. return compare(reference, value);
  114. }
  115. },
  116. /**
  117. * Update the value of a dependee's state.
  118. *
  119. * @param selector
  120. * CSS selector describing the dependee.
  121. * @param state
  122. * A State object describing the dependee's updated state.
  123. * @param value
  124. * The new value for the dependee's updated state.
  125. */
  126. update: function (selector, state, value) {
  127. // Only act when the 'new' value is actually new.
  128. if (value !== this.values[selector][state.pristine]) {
  129. this.values[selector][state.pristine] = value;
  130. this.reevaluate();
  131. }
  132. },
  133. /**
  134. * Triggers change events in case a state changed.
  135. */
  136. reevaluate: function () {
  137. var value = undefined;
  138. // Merge all individual values to find out whether this dependee complies.
  139. for (var selector in this.values) {
  140. for (var state in this.values[selector]) {
  141. state = states.State.sanitize(state);
  142. var complies = this.values[selector][state.pristine];
  143. value = ternary(value, invert(complies, state.invert));
  144. }
  145. }
  146. // Only invoke a state change event when the value actually changed.
  147. if (value !== this.oldValue) {
  148. // Store the new value so that we can compare later whether the value
  149. // actually changed.
  150. this.oldValue = value;
  151. // Normalize the value to match the normalized state name.
  152. value = invert(value, this.state.invert);
  153. // By adding "trigger: true", we ensure that state changes don't go into
  154. // infinite loops.
  155. this.element.trigger({ type: 'state:' + this.state, value: value, trigger: true });
  156. }
  157. }
  158. };
  159. states.Trigger = function (args) {
  160. $.extend(this, args);
  161. if (this.state in states.Trigger.states) {
  162. this.element = $(this.selector);
  163. // Only call the trigger initializer when it wasn't yet attached to this
  164. // element. Otherwise we'd end up with duplicate events.
  165. if (!this.element.data('trigger:' + this.state)) {
  166. this.initialize();
  167. }
  168. }
  169. };
  170. states.Trigger.prototype = {
  171. initialize: function () {
  172. var self = this;
  173. var trigger = states.Trigger.states[this.state];
  174. if (typeof trigger == 'function') {
  175. // We have a custom trigger initialization function.
  176. trigger.call(window, this.element);
  177. }
  178. else {
  179. $.each(trigger, function (event, valueFn) {
  180. self.defaultTrigger(event, valueFn);
  181. });
  182. }
  183. // Mark this trigger as initialized for this element.
  184. this.element.data('trigger:' + this.state, true);
  185. },
  186. defaultTrigger: function (event, valueFn) {
  187. var self = this;
  188. var oldValue = valueFn.call(this.element);
  189. // Attach the event callback.
  190. this.element.bind(event, function (e) {
  191. var value = valueFn.call(self.element, e);
  192. // Only trigger the event if the value has actually changed.
  193. if (oldValue !== value) {
  194. self.element.trigger({ type: 'state:' + self.state, value: value, oldValue: oldValue });
  195. oldValue = value;
  196. }
  197. });
  198. states.postponed.push(function () {
  199. // Trigger the event once for initialization purposes.
  200. self.element.trigger({ type: 'state:' + self.state, value: oldValue, oldValue: undefined });
  201. });
  202. }
  203. };
  204. /**
  205. * This list of states contains functions that are used to monitor the state
  206. * of an element. Whenever an element depends on the state of another element,
  207. * one of these trigger functions is added to the dependee so that the
  208. * dependent element can be updated.
  209. */
  210. states.Trigger.states = {
  211. // 'empty' describes the state to be monitored
  212. empty: {
  213. // 'keyup' is the (native DOM) event that we watch for.
  214. 'keyup': function () {
  215. // The function associated to that trigger returns the new value for the
  216. // state.
  217. return this.val() == '';
  218. }
  219. },
  220. checked: {
  221. 'change': function () {
  222. return this.prop('checked');
  223. }
  224. },
  225. // For radio buttons, only return the value if the radio button is selected.
  226. value: {
  227. 'keyup': function () {
  228. // Radio buttons share the same :input[name="key"] selector.
  229. if (this.length > 1) {
  230. // Initial checked value of radios is undefined, so we return false.
  231. return this.filter(':checked').val() || false;
  232. }
  233. return this.val();
  234. },
  235. 'change': function () {
  236. // Radio buttons share the same :input[name="key"] selector.
  237. if (this.length > 1) {
  238. // Initial checked value of radios is undefined, so we return false.
  239. return this.filter(':checked').val() || false;
  240. }
  241. return this.val();
  242. }
  243. },
  244. collapsed: {
  245. 'collapsed': function(e) {
  246. return (e !== undefined && 'value' in e) ? e.value : this.is('.collapsed');
  247. }
  248. }
  249. };
  250. /**
  251. * A state object is used for describing the state and performing aliasing.
  252. */
  253. states.State = function(state) {
  254. // We may need the original unresolved name later.
  255. this.pristine = this.name = state;
  256. // Normalize the state name.
  257. while (true) {
  258. // Iteratively remove exclamation marks and invert the value.
  259. while (this.name.charAt(0) == '!') {
  260. this.name = this.name.substring(1);
  261. this.invert = !this.invert;
  262. }
  263. // Replace the state with its normalized name.
  264. if (this.name in states.State.aliases) {
  265. this.name = states.State.aliases[this.name];
  266. }
  267. else {
  268. break;
  269. }
  270. }
  271. };
  272. /**
  273. * Create a new State object by sanitizing the passed value.
  274. */
  275. states.State.sanitize = function (state) {
  276. if (state instanceof states.State) {
  277. return state;
  278. }
  279. else {
  280. return new states.State(state);
  281. }
  282. };
  283. /**
  284. * This list of aliases is used to normalize states and associates negated names
  285. * with their respective inverse state.
  286. */
  287. states.State.aliases = {
  288. 'enabled': '!disabled',
  289. 'invisible': '!visible',
  290. 'invalid': '!valid',
  291. 'untouched': '!touched',
  292. 'optional': '!required',
  293. 'filled': '!empty',
  294. 'unchecked': '!checked',
  295. 'irrelevant': '!relevant',
  296. 'expanded': '!collapsed',
  297. 'readwrite': '!readonly'
  298. };
  299. states.State.prototype = {
  300. invert: false,
  301. /**
  302. * Ensures that just using the state object returns the name.
  303. */
  304. toString: function() {
  305. return this.name;
  306. }
  307. };
  308. /**
  309. * Global state change handlers. These are bound to "document" to cover all
  310. * elements whose state changes. Events sent to elements within the page
  311. * bubble up to these handlers. We use this system so that themes and modules
  312. * can override these state change handlers for particular parts of a page.
  313. */
  314. {
  315. $(document).bind('state:disabled', function(e) {
  316. // Only act when this change was triggered by a dependency and not by the
  317. // element monitoring itself.
  318. if (e.trigger) {
  319. $(e.target)
  320. .attr('disabled', e.value)
  321. .filter('.form-element')
  322. .closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'addClass' : 'removeClass']('form-disabled');
  323. // Note: WebKit nightlies don't reflect that change correctly.
  324. // See https://bugs.webkit.org/show_bug.cgi?id=23789
  325. }
  326. });
  327. $(document).bind('state:required', function(e) {
  328. if (e.trigger) {
  329. if (e.value) {
  330. $(e.target).closest('.form-item, .form-wrapper').find('label').append('<span class="form-required">*</span>');
  331. }
  332. else {
  333. $(e.target).closest('.form-item, .form-wrapper').find('label .form-required').remove();
  334. }
  335. }
  336. });
  337. $(document).bind('state:visible', function(e) {
  338. if (e.trigger) {
  339. $(e.target).closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'show' : 'hide']();
  340. }
  341. });
  342. $(document).bind('state:checked', function(e) {
  343. if (e.trigger) {
  344. $(e.target).prop('checked', e.value);
  345. }
  346. });
  347. $(document).bind('state:collapsed', function(e) {
  348. if (e.trigger) {
  349. if ($(e.target).is('.collapsed') !== e.value) {
  350. $('> legend a', e.target).click();
  351. }
  352. }
  353. });
  354. }
  355. /**
  356. * These are helper functions implementing addition "operators" and don't
  357. * implement any logic that is particular to states.
  358. */
  359. {
  360. // Bitwise AND with a third undefined state.
  361. function ternary (a, b) {
  362. return a === undefined ? b : (b === undefined ? a : a && b);
  363. };
  364. // Inverts a (if it's not undefined) when invert is true.
  365. function invert (a, invert) {
  366. return (invert && a !== undefined) ? !a : a;
  367. };
  368. // Compares two values while ignoring undefined values.
  369. function compare (a, b) {
  370. return (a === b) ? (a === undefined ? a : true) : (a === undefined || b === undefined);
  371. }
  372. }
  373. })(jQuery);