class.ts 1.2 KB

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