to-be-disabled.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.toBeDisabled = toBeDisabled;
  6. exports.toBeEnabled = toBeEnabled;
  7. var _utils = require("./utils");
  8. // form elements that support 'disabled'
  9. const FORM_TAGS = ['fieldset', 'input', 'select', 'optgroup', 'option', 'button', 'textarea'];
  10. /*
  11. * According to specification:
  12. * If <fieldset> is disabled, the form controls that are its descendants,
  13. * except descendants of its first optional <legend> element, are disabled
  14. *
  15. * https://html.spec.whatwg.org/multipage/form-elements.html#concept-fieldset-disabled
  16. *
  17. * This method tests whether element is first legend child of fieldset parent
  18. */
  19. function isFirstLegendChildOfFieldset(element, parent) {
  20. return (0, _utils.getTag)(element) === 'legend' && (0, _utils.getTag)(parent) === 'fieldset' && element.isSameNode(Array.from(parent.children).find(child => (0, _utils.getTag)(child) === 'legend'));
  21. }
  22. function isElementDisabledByParent(element, parent) {
  23. return isElementDisabled(parent) && !isFirstLegendChildOfFieldset(element, parent);
  24. }
  25. function canElementBeDisabled(element) {
  26. return FORM_TAGS.includes((0, _utils.getTag)(element));
  27. }
  28. function isElementDisabled(element) {
  29. return canElementBeDisabled(element) && element.hasAttribute('disabled');
  30. }
  31. function isAncestorDisabled(element) {
  32. const parent = element.parentElement;
  33. return Boolean(parent) && (isElementDisabledByParent(element, parent) || isAncestorDisabled(parent));
  34. }
  35. function isElementOrAncestorDisabled(element) {
  36. return canElementBeDisabled(element) && (isElementDisabled(element) || isAncestorDisabled(element));
  37. }
  38. function toBeDisabled(element) {
  39. (0, _utils.checkHtmlElement)(element, toBeDisabled, this);
  40. const isDisabled = isElementOrAncestorDisabled(element);
  41. return {
  42. pass: isDisabled,
  43. message: () => {
  44. const is = isDisabled ? 'is' : 'is not';
  45. return [this.utils.matcherHint(`${this.isNot ? '.not' : ''}.toBeDisabled`, 'element', ''), '', `Received element ${is} disabled:`, ` ${this.utils.printReceived(element.cloneNode(false))}`].join('\n');
  46. }
  47. };
  48. }
  49. function toBeEnabled(element) {
  50. (0, _utils.checkHtmlElement)(element, toBeEnabled, this);
  51. const isEnabled = !isElementOrAncestorDisabled(element);
  52. return {
  53. pass: isEnabled,
  54. message: () => {
  55. const is = isEnabled ? 'is' : 'is not';
  56. return [this.utils.matcherHint(`${this.isNot ? '.not' : ''}.toBeEnabled`, 'element', ''), '', `Received element ${is} enabled:`, ` ${this.utils.printReceived(element.cloneNode(false))}`].join('\n');
  57. }
  58. };
  59. }