Blame view

src/components/util.tsx 4.96 KB
vben authored
1
import type { VNodeChild } from 'vue';
陈文彬 authored
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

export function convertToUnit(
  str: string | number | null | undefined,
  unit = 'px'
): string | undefined {
  if (str == null || str === '') {
    return undefined;
  } else if (isNaN(+str!)) {
    return String(str);
  } else {
    return `${Number(str)}${unit}`;
  }
}

/**
 * Camelize a hyphen-delimited string.
 */
const camelizeRE = /-(\w)/g;
export const camelize = (str: string): string => {
  return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
};

export function wrapInArray<T>(v: T | T[] | null | undefined): T[] {
  return v != null ? (Array.isArray(v) ? v : [v]) : [];
}

const pattern = {
  styleList: /;(?![^(]*\))/g,
  styleProp: /:(.*)/,
} as const;

function parseStyle(style: string) {
vben authored
34
  const styleMap: Recordable = {};
陈文彬 authored
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154

  for (const s of style.split(pattern.styleList)) {
    let [key, val] = s.split(pattern.styleProp);
    key = key.trim();
    if (!key) {
      continue;
    }
    // May be undefined if the `key: value` pair is incomplete.
    if (typeof val === 'string') {
      val = val.trim();
    }
    styleMap[camelize(key)] = val;
  }

  return styleMap;
}

/**
 * Intelligently merges data for createElement.
 * Merges arguments left to right, preferring the right argument.
 * Returns new VNodeData object.
 */
export function mergeData(...vNodeData: VNodeChild[]): VNodeChild;
export function mergeData(...args: any[]): VNodeChild {
  const mergeTarget: any = {};
  let i: number = args.length;
  let prop: string;

  // Allow for variadic argument length.
  while (i--) {
    // Iterate through the data properties and execute merge strategies
    // Object.keys eliminates need for hasOwnProperty call
    for (prop of Object.keys(args[i])) {
      switch (prop) {
        // Array merge strategy (array concatenation)
        case 'class':
        case 'directives':
          if (args[i][prop]) {
            mergeTarget[prop] = mergeClasses(mergeTarget[prop], args[i][prop]);
          }
          break;
        case 'style':
          if (args[i][prop]) {
            mergeTarget[prop] = mergeStyles(mergeTarget[prop], args[i][prop]);
          }
          break;
        // Space delimited string concatenation strategy
        case 'staticClass':
          if (!args[i][prop]) {
            break;
          }
          if (mergeTarget[prop] === undefined) {
            mergeTarget[prop] = '';
          }
          if (mergeTarget[prop]) {
            // Not an empty string, so concatenate
            mergeTarget[prop] += ' ';
          }
          mergeTarget[prop] += args[i][prop].trim();
          break;
        // Object, the properties of which to merge via array merge strategy (array concatenation).
        // Callback merge strategy merges callbacks to the beginning of the array,
        // so that the last defined callback will be invoked first.
        // This is done since to mimic how Object.assign merging
        // uses the last given value to assign.
        case 'on':
        case 'nativeOn':
          if (args[i][prop]) {
            mergeTarget[prop] = mergeListeners(mergeTarget[prop], args[i][prop]);
          }
          break;
        // Object merge strategy
        case 'attrs':
        case 'props':
        case 'domProps':
        case 'scopedSlots':
        case 'staticStyle':
        case 'hook':
        case 'transition':
          if (!args[i][prop]) {
            break;
          }
          if (!mergeTarget[prop]) {
            mergeTarget[prop] = {};
          }
          mergeTarget[prop] = { ...args[i][prop], ...mergeTarget[prop] };
          break;
        // Reassignment strategy (no merge)
        default:
          // slot, key, ref, tag, show, keepAlive
          if (!mergeTarget[prop]) {
            mergeTarget[prop] = args[i][prop];
          }
      }
    }
  }

  return mergeTarget;
}

export function mergeStyles(
  target: undefined | string | object[] | object,
  source: undefined | string | object[] | object
) {
  if (!target) return source;
  if (!source) return target;

  target = wrapInArray(typeof target === 'string' ? parseStyle(target) : target);

  return (target as object[]).concat(typeof source === 'string' ? parseStyle(source) : source);
}

export function mergeClasses(target: any, source: any) {
  if (!source) return target;
  if (!target) return source;

  return target ? wrapInArray(target).concat(source) : source;
}

export function mergeListeners(
vben authored
155
156
  target: Indexable<Function | Function[]> | undefined,
  source: Indexable<Function | Function[]> | undefined
陈文彬 authored
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
) {
  if (!target) return source;
  if (!source) return target;

  let event: string;

  for (event of Object.keys(source)) {
    // Concat function to array of functions if callback present.
    if (target[event]) {
      // Insert current iteration data in beginning of merged array.
      target[event] = wrapInArray(target[event]);
      (target[event] as Function[]).push(...wrapInArray(source[event]));
    } else {
      // Straight assign.
      target[event] = source[event];
    }
  }

  return target;
}