a644a2db7852b5fd0af8728ceeccc97c77516e102186380bfeeac5a297ca5eeee99cdfb070d20bd183d95ec12423abc08596e12e74d5221ae8ed5774b2786e 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import type { Formattable } from '../blot/abstract/blot.js';
  2. import Registry from '../registry.js';
  3. import Scope from '../scope.js';
  4. import Attributor from './attributor.js';
  5. import ClassAttributor from './class.js';
  6. import StyleAttributor from './style.js';
  7. class AttributorStore {
  8. private attributes: { [key: string]: Attributor } = {};
  9. private domNode: HTMLElement;
  10. constructor(domNode: HTMLElement) {
  11. this.domNode = domNode;
  12. this.build();
  13. }
  14. public attribute(attribute: Attributor, value: any): void {
  15. // verb
  16. if (value) {
  17. if (attribute.add(this.domNode, value)) {
  18. if (attribute.value(this.domNode) != null) {
  19. this.attributes[attribute.attrName] = attribute;
  20. } else {
  21. delete this.attributes[attribute.attrName];
  22. }
  23. }
  24. } else {
  25. attribute.remove(this.domNode);
  26. delete this.attributes[attribute.attrName];
  27. }
  28. }
  29. public build(): void {
  30. this.attributes = {};
  31. const blot = Registry.find(this.domNode);
  32. if (blot == null) {
  33. return;
  34. }
  35. const attributes = Attributor.keys(this.domNode);
  36. const classes = ClassAttributor.keys(this.domNode);
  37. const styles = StyleAttributor.keys(this.domNode);
  38. attributes
  39. .concat(classes)
  40. .concat(styles)
  41. .forEach((name) => {
  42. const attr = blot.scroll.query(name, Scope.ATTRIBUTE);
  43. if (attr instanceof Attributor) {
  44. this.attributes[attr.attrName] = attr;
  45. }
  46. });
  47. }
  48. public copy(target: Formattable): void {
  49. Object.keys(this.attributes).forEach((key) => {
  50. const value = this.attributes[key].value(this.domNode);
  51. target.format(key, value);
  52. });
  53. }
  54. public move(target: Formattable): void {
  55. this.copy(target);
  56. Object.keys(this.attributes).forEach((key) => {
  57. this.attributes[key].remove(this.domNode);
  58. });
  59. this.attributes = {};
  60. }
  61. public values(): { [key: string]: any } {
  62. return Object.keys(this.attributes).reduce(
  63. (attributes: { [key: string]: any }, name: string) => {
  64. attributes[name] = this.attributes[name].value(this.domNode);
  65. return attributes;
  66. },
  67. {},
  68. );
  69. }
  70. }
  71. export default AttributorStore;