-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecmascript.snippets
456 lines (371 loc) · 10 KB
/
ecmascript.snippets
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
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
priority -50
############
# COMMON #
############
# The smart snippets use a global options called
# "g:ultisnips_javascript.{option}" which can control the format
# of trailing semicolon, space before function paren, etc.
#
# e.g.
# let g:ultisnips_javascript = {
# \ 'keyword-spacing': 'always',
# \ 'semi': 'never',
# \ 'space-before-function-paren': 'always',
# \ }
global !p
ALWAYS = 'always'
NEVER = 'never'
def get_option(snip, option, default=None):
return snip.opt('g:ultisnips_javascript["{}"]'.format(option), default)
def semi(snip):
option = get_option(snip, 'semi', ALWAYS)
if option == NEVER:
ret = ''
elif option == ALWAYS:
ret = ';'
else:
ret = ';'
return ret
def space_before_function_paren(snip):
option = get_option(snip, 'space-before-function-paren', NEVER)
if option == NEVER:
ret = ''
elif option == ALWAYS:
ret = ' '
else:
ret = ''
return ret
def keyword_spacing(snip):
option = get_option(snip, 'keyword-spacing', ALWAYS)
if option == NEVER:
ret = ''
elif option == ALWAYS:
ret = ' '
else:
ret = ''
return ret
def upperfirst(t):
if len(t) < 2:
return '' if len(t) < 1 else t.capitalize()
return t[0].capitalize() + t[1:]
def lowerdash(t):
return '-'.join([ w.lower() for w in re.findall('[a-z]+|[A-Z]+[a-z]*', t) ])
endglobal
###########################################################################
# TextMate Snippets #
###########################################################################
snippet => "Arrow Function bare"
const ${1:fn} = ${2:arg} => ${3:retStatement};
endsnippet
snippet =>{} "Arrow Function curly return"
const ${1:fn} = ${2:arg} => {
$0
return $3;
}
endsnippet
snippet =>() "Arrow Function full"
const ${1:fn} = (${2:args}) => {
$0
return $3;
}
endsnippet
snippet fetch:G "fetch with GET"
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const req = new Request(
${1:url},
{
method: 'GET',
headers,
mode: 'cors',
cache: 'default',
}
);
fetch(req)
.then(response => {
if (!response.ok) {
throw new Error(response.status + ': ' + response.statusText);
}
return response.json();
})
.then(transformData)
.catch(e => console.log(e.message))
.finally(d => {
if (!d instanceof Error) {
$0
}
})
endsnippet
snippet fetch:P "fetch with POST"
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const req = new Request(
${1:url},
{
method: 'POST',
headers,
body: ${2:jsonObj}
mode: 'cors',
cache: 'default',
}
);
fetch(req)
.then(response => {
if (!response.ok) {
throw new Error(response.status + ': ' + response.statusText);
}
return response.json();
})
.then(transformData)
.catch(e => console.log(e.message))
.finally(d => {
if (!d instanceof Error) {
$0
}
})
endsnippet
snippet sortBy "Array sortBy proxyfied"
const by = (propAccessor, builtinType) => {
let accessor;
const traveller = (prop) => {
if (!propAccessor) {
return prop;
}
let deepProp = prop;
let breadCrumbs = propAccessor.split('.');
for (let p of breadCrumbs) {
deepProp = deepProp[p];
}
return deepProp;
}
switch (builtinType) {
case Date:
accessor = p => {
_p = traveller(p);
return _p instanceof Date ? _p.getTime() : new Date(_p).getTime();
}
break;
default:
accessor = p => traveller(p);
}
return {
ascending(a, b) {
return builtinType === String ?
accessor(a).localeCompare(accessor(b)) :
accessor(a) - accessor(b);
},
descending(a, b) {
return builtinType === String ?
accessor(b).localeCompare(accessor(a)) :
accessor(b) - accessor(a);
}
}
}
endsnippet
snippet get "Get Elements"
getElement${1/(T)|(C)|.*/(?1:s)(?2:s)/}By${1:T}${1/(T)|(I)|(C).*/(?1:agName)(?2:d)(?3:lassName)/}('$2')
endsnippet
snippet '':f "object method string"
'${1:${2:#thing}:${3:click}}': function`!p snip.rv = space_before_function_paren(snip)`(element) {
${VISUAL}$0
}${10:,}
endsnippet
snippet :f "Object Method"
${1:method_name}: function`!p snip.rv = space_before_function_paren(snip)`(${3:attribute}) {
${VISUAL}$0
}${10:,}
endsnippet
snippet :, "Object Value JS"
${1:value_name}: ${0:value},
endsnippet
snippet : "Object key key: 'value'"
${1:key}: ${2:"${3:value}"}${4:, }
endsnippet
snippet proto "Prototype (proto)"
${1:class_name}.prototype.${2:method_name} = function`!p snip.rv = space_before_function_paren(snip)`(${3:first_argument}) {
${VISUAL}$0
}`!p snip.rv = semi(snip)`
endsnippet
snippet fun "function (named)" b
function ${1:function_name}`!p snip.rv = space_before_function_paren(snip)`(${2:argument}) {
${VISUAL}$0
}
endsnippet
snippet vf "function (assigned to var)"
${1:var }${2:function_name} = function $2`!p snip.rv = space_before_function_paren(snip)`($3) {
${VISUAL}$0
}`!p snip.rv = semi(snip)`
endsnippet
# Drop priority so this only triggers when not beginning of line.
priority -51
snippet fun "function (anonymous)" w
function`!p snip.rv = space_before_function_paren(snip)`($1) {
${VISUAL}$0
}$2
endsnippet
priority -50
snippet anf "function (anonymous)" i
function`!p snip.rv = space_before_function_paren(snip)`($1) {
${VISUAL}$0
}
endsnippet
snippet iife "Immediately-Invoked Function Expression (iife)"
(function`!p snip.rv = space_before_function_paren(snip)`(${1:window}) {
${VISUAL}$0
}(${2:$1}))`!p snip.rv = semi(snip)`
endsnippet
snippet ;fe "Minify safe iife"
;(function`!p snip.rv = space_before_function_paren(snip)`(${1}) {
${VISUAL}$0
}(${2}))
endsnippet
snippet timeout "setTimeout function"
setTimeout(function`!p snip.rv = space_before_function_paren(snip)`() {
${VISUAL}$0
}${2:.bind(${3:this})}, ${1:10})`!p snip.rv = semi(snip)`
endsnippet
snippet fi "for prop in obj using hasOwnProperty" b
for`!p snip.rv = keyword_spacing(snip)`(${1:prop} in ${2:obj}){
if`!p snip.rv = keyword_spacing(snip)`($2.hasOwnProperty($1)) {
${VISUAL}$0
}
}
endsnippet
snippet if "if (condition) { ... }"
if`!p snip.rv = keyword_spacing(snip)`(${1:true}) {
${VISUAL}$0
}
endsnippet
snippet ife "if (condition) { ... } else { ... }"
if`!p snip.rv = keyword_spacing(snip)`(${1:true}) {
${VISUAL}$0
}`!p snip.rv = keyword_spacing(snip)`else`!p snip.rv = keyword_spacing(snip)`{
${2}
}
endsnippet
snippet switch
switch`!p snip.rv = keyword_spacing(snip)`(${VISUAL}${1:expression}) {
case '${VISUAL}${3:case}':
${4}
break`!p snip.rv = semi(snip)`
${0}
default:
${2}
}
endsnippet
snippet case "case 'xyz': ... break"
case`!p snip.rv = keyword_spacing(snip)`'${VISUAL}${1:case}':
${VISUAL}$0
break`!p snip.rv = semi(snip)`
endsnippet
snippet do "do { ... } while (condition)"
do`!p snip.rv = keyword_spacing(snip)`{
${VISUAL}$0
}`!p snip.rv = keyword_spacing(snip)`while`!p snip.rv = keyword_spacing(snip)`(${1:/* condition */})`!p snip.rv = semi(snip)`
endsnippet
snippet ret "Return statement"
return ${VISUAL}$0`!p snip.rv = semi(snip)`
endsnippet
snippet us
'use strict'`!p snip.rv = semi(snip)`
endsnippet
# vim:ft=snippets:
snippet im:RF "usual import state for FP in React" b
import React, {
FC,
PropsWithChildren,
useState,
} from "react";
endsnippet
snippet im:ROOP "usual import for OOP in React" b
import React, { Component } from "react";
endsnippet
snippet im:. "import classnames package" b
import classnames from "classnames";
endsnippet
snippet im:_ "import lodash package" b
import lodash from "lodash";
endsnippet
snippet us:S "useState"
const [ ${1:my}State, set${1/\w+/\u$0/}State ] = useState($2);
endsnippet
snippet us:E "useEffect"
useEffect(() => {
$0
}, [${1:updateIndicator}])
endsnippet
snippet testSetupTeardown "usual setup teardown boilerplate" b
import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
let container = null;
beforeEach(() => {
// setup a DOM element as a render target
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
// cleanup on exiting
unmountComponentAtNode(container);
container.remove();
container = null;
});
$0
endsnippet
snippet testIt "minimal function boilerplate" b
it("renders $0", () => {
act(() => {
render($1, container);
});
expect(container$2);
});
endsnippet
snippet testAct "minimal function boilerplate" b
act(() => {
render($1, container);
});
expect(container$2);
endsnippet
snippet testExpectQuerySelectorText "minimal function boilerplate" b
expect(container.querySelector("summary").textContent).toBe();
endsnippet
snippet testExpectQuerySelectorAttribute "minimal function boilerplate" b
expect(container.querySelector("summary").getAttribute("$0")).toEqual("$1");
endsnippet
snippet testExpectTextToBe "minimal function boilerplate" b
expect(container.textContent).toBe();
endsnippet
snippet testExpectTextToContain "minimal function boilerplate" b
expect(container.textContent).toContain();
endsnippet
snippet testFetch "usual setup to test mock API fetch" b
it("renders dynamic data driven stuff", async () => {
const fakeJSON = {};
jest.spyOn(global, "fetch").mockImplementation(() =>
Promise.resolve({
json: () => Promise.resolve(fakeJSON)
})
);
// Use the asynchronous version of act to apply resolved promises
await act(async () => {
render(<Component />, container);
});
// remove the mock to ensure tests are completely isolated
global.fetch.mockRestore();
});
endsnippet
snippet testHandleEvent "event checking boilerplate" b
it("changes value when clicked", () => {
const onHandle = jest.fn();
act(() => {
render(<Component on$0={onHandle} />, container);
});
const component = document.querySelector("[$1]");
expect(component.innerHTML).toBe($2);
act(() => {
component.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
expect(onHandle).toHaveBeenCalledTimes(1);
expect(button.innerHTML).toBe($3);
});
endsnippet