zhangnaisong
2023-08-05 24d66c8d82b628a06e93dbb1abfea2049b3d45ab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import * as Registry from '../registry';
 
export interface AttributorOptions {
  scope?: Registry.Scope;
  whitelist?: string[];
}
 
export default class Attributor {
  attrName: string;
  keyName: string;
  scope: Registry.Scope;
  whitelist: string[] | undefined;
 
  static keys(node: HTMLElement): string[] {
    return [].map.call(node.attributes, function(item: Attr) {
      return item.name;
    });
  }
 
  constructor(attrName: string, keyName: string, options: AttributorOptions = {}) {
    this.attrName = attrName;
    this.keyName = keyName;
    let attributeBit = Registry.Scope.TYPE & Registry.Scope.ATTRIBUTE;
    if (options.scope != null) {
      // Ignore type bits, force attribute bit
      this.scope = (options.scope & Registry.Scope.LEVEL) | attributeBit;
    } else {
      this.scope = Registry.Scope.ATTRIBUTE;
    }
    if (options.whitelist != null) this.whitelist = options.whitelist;
  }
 
  add(node: HTMLElement, value: string): boolean {
    if (!this.canAdd(node, value)) return false;
    node.setAttribute(this.keyName, value);
    return true;
  }
 
  canAdd(node: HTMLElement, value: any): boolean {
    let match = Registry.query(node, Registry.Scope.BLOT & (this.scope | Registry.Scope.TYPE));
    if (match == null) return false;
    if (this.whitelist == null) return true;
    if (typeof value === 'string') {
      return this.whitelist.indexOf(value.replace(/["']/g, '')) > -1;
    } else {
      return this.whitelist.indexOf(value) > -1;
    }
  }
 
  remove(node: HTMLElement): void {
    node.removeAttribute(this.keyName);
  }
 
  value(node: HTMLElement): string {
    let value = node.getAttribute(this.keyName);
    if (this.canAdd(node, value) && value) {
      return value;
    }
    return '';
  }
}