ExamplesPlaygroundReference Source

coral-spectrum/coral-base-labellable/src/scripts/BaseLabellable.js

  1. /**
  2. * Copyright 2020 Adobe. All rights reserved.
  3. * This file is licensed to you under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License. You may obtain a copy
  5. * of the License at http://www.apache.org/licenses/LICENSE-2.0
  6. *
  7. * Unless required by applicable law or agreed to in writing, software distributed under
  8. * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
  9. * OF ANY KIND, either express or implied. See the License for the specific language
  10. * governing permissions and limitations under the License.
  11. */
  12.  
  13. /**
  14. @base BaseLabellable
  15. @classdesc Accessibility helper for components with label and icon properties
  16. */
  17. class BaseLabellable extends superClass {
  18. _observeLabel() {
  19. this._observableLabel = this._observableLabel || this._elements.label || this._elements.content;
  20.  
  21. // Listen for mutations
  22. this._observer = new MutationObserver(this._toggleIconAriaHidden.bind(this));
  23.  
  24. // Watch for changes to the content element
  25. this._observer.observe(this._observableLabel, {
  26. // Catch changes to childList
  27. childList: true,
  28. // Catch changes to textContent
  29. characterData: true,
  30. // Monitor any child node
  31. subtree: true
  32. });
  33. }
  34.  
  35. // Hides the icon from screen readers to avoid duplicated labels
  36. _toggleIconAriaHidden() {
  37. this._renderedLabel = this._renderedLabel || this.label || this.content;
  38.  
  39. // toggle aria-hidden if tab is labelled
  40. if (this._elements.icon) {
  41. const isLabelled = (this._renderedLabel && this._renderedLabel.textContent.trim().length) ||
  42. this.getAttribute('aria-label') !== null ||
  43. this.getAttribute('aria-labelledby') !== null;
  44.  
  45. this._elements.icon[isLabelled ? 'setAttribute' : 'removeAttribute']('aria-hidden', 'true');
  46. }
  47. }
  48.  
  49. /** @ignore */
  50. static get observedAttributes() {
  51. return super.observedAttributes.concat(['aria-label', 'aria-labelledby']);
  52. }
  53.  
  54. /** @ignore */
  55. attributeChangedCallback(name, oldValue, value) {
  56. if (name === 'aria-label' || name === 'aria-labelledby') {
  57. this._toggleIconAriaHidden();
  58. } else {
  59. super.attributeChangedCallback(name, oldValue, value);
  60. }
  61. }
  62. };
  63.  
  64. export default BaseLabellable;