e760494b3359975336de875a215941b39a00d2ea6412a4f6b585d120d6660596c4642cc8574c341cfde37a54598e56d397289e2d1dcc38aeba97aef1a6dfbb 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import Attributor from './attributor.js';
  2. function match(node: HTMLElement, prefix: string): string[] {
  3. const className = node.getAttribute('class') || '';
  4. return className
  5. .split(/\s+/)
  6. .filter((name) => name.indexOf(`${prefix}-`) === 0);
  7. }
  8. class ClassAttributor extends Attributor {
  9. public static keys(node: HTMLElement): string[] {
  10. return (node.getAttribute('class') || '')
  11. .split(/\s+/)
  12. .map((name) => name.split('-').slice(0, -1).join('-'));
  13. }
  14. public add(node: HTMLElement, value: any): boolean {
  15. if (!this.canAdd(node, value)) {
  16. return false;
  17. }
  18. this.remove(node);
  19. node.classList.add(`${this.keyName}-${value}`);
  20. return true;
  21. }
  22. public remove(node: HTMLElement): void {
  23. const matches = match(node, this.keyName);
  24. matches.forEach((name) => {
  25. node.classList.remove(name);
  26. });
  27. if (node.classList.length === 0) {
  28. node.removeAttribute('class');
  29. }
  30. }
  31. public value(node: HTMLElement): any {
  32. const result = match(node, this.keyName)[0] || '';
  33. const value = result.slice(this.keyName.length + 1); // +1 for hyphen
  34. return this.canAdd(node, value) ? value : '';
  35. }
  36. }
  37. export default ClassAttributor;