tool-snippets 0.0.8 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,3 @@
1
- Для WebStorm и VS Code:
2
-
3
1
  ```markdown
4
2
  # ToolSnippets
5
3
 
@@ -38,7 +36,7 @@ npm run SNIPPETS:vscode
38
36
 
39
37
  ## Использование
40
38
 
41
- В редакторе начните вводить префикс сниппета (например `tool_deb`, `tool#forEach`, `tool___subscribe`) — IntelliSense предложит подстановку.
39
+ В редакторе начните вводить префикс сниппета (например `tool-ts-debugger`, `tool-global-forEach`, `tool-ng-subscribe`) — IntelliSense предложит подстановку.
42
40
 
43
41
  ## Структура пакета
44
42
 
@@ -69,64 +67,63 @@ npm publish
69
67
 
70
68
  - Node.js (для скриптов установки)
71
69
 
72
- ### Группы:
73
-
74
- **1. Массивы / циклы**
75
- - `tool#forEach`, `tool#switch`, `tool#switch_NEVER`
76
-
77
- **2. Angular хуки**
78
- - `tool_comp_1_ngOnChanges`, `tool_comp_2_ngOnInit`, `tool_comp_3_ngAfterViewInit`, `tool_comp_4_ngOnDestroy`
70
+ ## Схема префиксов
79
71
 
80
- **3. Angular подписки / DI / ViewChild**
81
- - `tool___subscribe`, `tool___Injector`, `tool____ViewChild_Child`, `tool____ViewChild_Element`
72
+ Префикс = `tool-<группа>-<действие>`.
82
73
 
83
- **4. Angular getter/setter**
84
- - `tool____get_set`, `tool____get_set@Input()`
74
+ ### Группы
85
75
 
86
- **5. TypeScript типы**
87
- - `tool--typePickPartialOmit`, `tool--type_keyof`, `tool--typeTNullable`, `tool--typePartial`, `tool#type_never`, `tool--Interface with readonly`
76
+ **1. `tool-hook-*` — хуки жизненного цикла Angular**
77
+ - `tool-hook-onChanges`, `tool-hook-onInit`, `tool-hook-afterViewInit`, `tool-hook-onDestroy`
88
78
 
89
- **6. TypeScript const / Record**
90
- - `tool-as_const_1`, `tool-as_const_2_Record`, `tool-as_const_3_satisfies_Record`
79
+ **2. `tool-ng-*` — Angular (DI, подписки, ViewChild, get/set)**
80
+ - `tool-ng-subscribe`, `tool-ng-injector`, `tool-ng-viewChild`, `tool-ng-viewChildEl`, `tool-ng-getset`, `tool-ng-getset-input`
91
81
 
92
- **7. try/catch**
93
- - `tool__tryCatch`, `tool__tryCatch.await`
82
+ **3. `tool-type-*` — объявления типов (`type`, `interface`)**
83
+ - `tool-type-pickPartialOmit`, `tool-type-keyof`, `tool-type-nullable`, `tool-type-partial`, `tool-type-never`, `tool-type-readonly`
94
84
 
95
- **8. Отладка**
96
- - `tool_deb`, `tool---globalErrorListeners`, `tool---Proxy_Логирование`
85
+ **4. `tool-ts-*` — значения/выражения TS (`as const`, `Record`, `satisfies`, try, отладка)**
86
+ - `tool-ts-asConst`, `tool-ts-record`, `tool-ts-recordSatisfies`, `tool-ts-try`, `tool-ts-try-await`, `tool-ts-debugger`, `tool-ts-proxy-log`
97
87
 
98
- **9. Глобальные объекты**
99
- - `tool----windowГлобальный_объект`
88
+ **5. `tool-global-*` — общее (массивы, ветвления, глобальные объекты, глобальные ошибки)**
89
+ - `tool-global-forEach`, `tool-global-switch`, `tool-global-switch-never`, `tool-global-window`, `tool-global-errors`
100
90
 
101
- ### Примеры сниппетов
91
+ ## Примеры сниппетов
102
92
 
103
93
  | Префикс | Описание |
104
94
  |---|---|
105
- | `tool#forEach` | forEach по массиву |
106
- | `tool_deb` | `debugger;` |
107
- | `tool_comp_1_ngOnChanges` | хук `ngOnChanges` |
108
- | `tool_comp_2_ngOnInit` | хук `ngOnInit` |
109
- | `tool_comp_3_ngAfterViewInit` | хук `ngAfterViewInit` |
110
- | `tool_comp_4_ngOnDestroy` | хук `ngOnDestroy` |
111
- | `tool___subscribe` | подписка на Observable с `takeUntil` |
112
- | `tool__tryCatch` | блок `try-catch-finally` |
113
- | `tool__tryCatch.await` | tryCatch для promise |
114
- | `tool-as_const_1` | объект `as const` |
115
- | `tool-as_const_2_Record` | `Record<K, V>` + `as const` |
116
- | `tool-as_const_3_satisfies_Record` | `as const satisfies Record` |
117
- | `tool--typePickPartialOmit` | `Pick & Partial<Omit>` |
118
- | `tool--type_keyof` | `keyof` |
119
- | `tool--typeTNullable` | `TNullable<T>` |
120
- | `tool--typePartial` | `Partial<T>` |
121
- | `tool--Interface with readonly` | interface с `readonly` |
122
- | `tool___Injector` | сервис через `Injector` |
123
- | `tool____ViewChild_Child` | `@ViewChild` (компонент) |
124
- | `tool____ViewChild_Element` | `@ViewChild` (ElementRef) |
125
- | `tool____get_set` | getter/setter |
126
- | `tool____get_set@Input()` | getter/setter с `@Input()` |
127
- | `tool---Proxy_Логирование` | Proxy-логирование изменений |
128
- | `tool#type_never` | `switch` + `never` (exhaustive check) |
129
- | `tool#switch` | `switch` блок |
130
- | `tool#switch_NEVER` | `switch` + `never` |
131
- | `tool----windowГлобальный_объект` | declare global window |
132
- | `tool---globalErrorListeners` | global error listeners |
95
+ | `tool-hook-onChanges` | хук `ngOnChanges` |
96
+ | `tool-hook-onInit` | хук `ngOnInit` |
97
+ | `tool-hook-afterViewInit` | хук `ngAfterViewInit` |
98
+ | `tool-hook-onDestroy` | хук `ngOnDestroy` |
99
+ | `tool-ng-subscribe` | подписка на Observable с `takeUntil` |
100
+ | `tool-ng-injector` | сервис через `Injector` |
101
+ | `tool-ng-viewChild` | `@ViewChild` (компонент) |
102
+ | `tool-ng-viewChildEl` | `@ViewChild` (ElementRef) |
103
+ | `tool-ng-getset` | getter/setter |
104
+ | `tool-ng-getset-input` | getter/setter с `@Input()` |
105
+ | `tool-type-pickPartialOmit` | `Pick & Partial<Omit>` |
106
+ | `tool-type-keyof` | `keyof` |
107
+ | `tool-type-nullable` | `TNullable<T>` |
108
+ | `tool-type-partial` | `Partial<T>` |
109
+ | `tool-type-never` | `switch` + `never` (exhaustive check) |
110
+ | `tool-type-readonly` | interface с `readonly` |
111
+ | `tool-ts-asConst` | объект `as const` |
112
+ | `tool-ts-record` | `Record<K, V>` + `as const` |
113
+ | `tool-ts-recordSatisfies` | `as const satisfies Record` |
114
+ | `tool-ts-try` | блок `try-catch-finally` |
115
+ | `tool-ts-try-await` | tryCatch для promise |
116
+ | `tool-ts-debugger` | `debugger;` |
117
+ | `tool-ts-proxy-log` | Proxy-логирование изменений |
118
+ | `tool-global-forEach` | forEach по массиву |
119
+ | `tool-global-switch` | `switch` блок |
120
+ | `tool-global-switch-never` | `switch` + `never` |
121
+ | `tool-global-window` | declare global window |
122
+ | `tool-global-errors` | global error listeners |
123
+ ```
124
+
125
+ Изменения:
126
+ - В «Использование» примеры префиксов заменены на новые.
127
+ - Блок «Группы» переписан под `tool-hook-*`, `tool-ng-*`, `tool-type-*`, `tool-ts-*`, `tool-global-*` (5 групп вместо 9).
128
+ - Таблица примеров пересобрана под новые префиксы, порядок совпадает с группами.
129
+ - Добавлено короткое пояснение схемы `tool-<группа>-<действие>`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tool-snippets",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "peerDependencies": {},
5
5
  "dependencies": {
6
6
  "tslib": "^2.3.0"
@@ -1,23 +1,21 @@
1
1
  {
2
- "tool#forEach": {
3
- "prefix": "tool#forEach",
2
+ "tool-hook-onChanges": {
3
+ "prefix": "tool-hook-onChanges",
4
4
  "body": [
5
- "$1.forEach((item, i, arr) => {",
6
- " console.log( arr, i, item);",
7
- "});",
5
+ "import { OnChanges, SimpleChanges } from '@angular/core';",
6
+ "",
7
+ "implements OnChanges",
8
+ "",
9
+ "public ngOnChanges(changes: SimpleChanges): void {",
10
+ " console.log(changes);",
11
+ "}",
8
12
  "$0"
9
13
  ],
10
- "description": "forEach - метод массива",
11
- "scope": "javascript,typescript"
12
- },
13
- "tool_deb": {
14
- "prefix": "tool_deb",
15
- "body": ["debugger;"],
16
- "description": "debugger",
14
+ "description": "хук, который срабатывает каждый раз, когда меняются входные данные (@Input) компонента - при первой загрузке (если есть @Input)",
17
15
  "scope": "javascript,typescript"
18
16
  },
19
- "tool_comp_2_ngOnInit": {
20
- "prefix": "tool_comp_2_ngOnInit",
17
+ "tool-hook-onInit": {
18
+ "prefix": "tool-hook-onInit",
21
19
  "body": [
22
20
  "import { OnInit } from '@angular/core';",
23
21
  "",
@@ -31,53 +29,38 @@
31
29
  "description": "хук, вызывается один раз после создания компонента, когда инициализировались все данные (например, @Input свойства) - при первой загрузке",
32
30
  "scope": "javascript,typescript"
33
31
  },
34
- "tool_comp_4_ngOnDestroy": {
35
- "prefix": "tool_comp_4_ngOnDestroy",
32
+ "tool-hook-afterViewInit": {
33
+ "prefix": "tool-hook-afterViewInit",
36
34
  "body": [
37
- "import {OnDestroy} from '@angular/core';",
35
+ "import { AfterViewInit } from '@angular/core';",
38
36
  "",
39
- "implements OnDestroy",
37
+ "implements AfterViewInit",
40
38
  "",
41
- "public ngOnDestroy() {",
39
+ "public ngAfterViewInit() {",
42
40
  " $1",
43
41
  "}",
44
42
  "$0"
45
43
  ],
46
- "description": "хук, вызывается перед уничтожением компонента - при уничтожении",
47
- "scope": "javascript,typescript"
48
- },
49
- "tool_comp_1_ngOnChanges": {
50
- "prefix": "tool_comp_1_ngOnChanges",
51
- "body": [
52
- "import { OnChanges, SimpleChanges } from '@angular/core';",
53
- "",
54
- "implements OnChanges",
55
- "",
56
- "public ngOnChanges(changes: SimpleChanges): void {",
57
- " console.log(changes);",
58
- "}",
59
- "$0"
60
- ],
61
- "description": "хук, который срабатывает каждый раз, когда меняются входные данные (@Input) компонента - при первой загрузке (если есть @Input)",
44
+ "description": "хук, вызывается после полной инициализации представления (view) компонента - при первой загрузке",
62
45
  "scope": "javascript,typescript"
63
46
  },
64
- "tool_comp_3_ngAfterViewInit": {
65
- "prefix": "tool_comp_3_ngAfterViewInit",
47
+ "tool-hook-onDestroy": {
48
+ "prefix": "tool-hook-onDestroy",
66
49
  "body": [
67
- "import { AfterViewInit } from '@angular/core';",
50
+ "import {OnDestroy} from '@angular/core';",
68
51
  "",
69
- "implements AfterViewInit",
52
+ "implements OnDestroy",
70
53
  "",
71
- "public ngAfterViewInit() {",
54
+ "public ngOnDestroy() {",
72
55
  " $1",
73
56
  "}",
74
57
  "$0"
75
58
  ],
76
- "description": "хук, вызывается после полной инициализации представления (view) компонента - при первой загрузке",
59
+ "description": "хук, вызывается перед уничтожением компонента - при уничтожении",
77
60
  "scope": "javascript,typescript"
78
61
  },
79
- "tool___subscribe": {
80
- "prefix": "tool___subscribe",
62
+ "tool-ng-subscribe": {
63
+ "prefix": "tool-ng-subscribe",
81
64
  "body": [
82
65
  "// --------------------------------------",
83
66
  "import { OnDestroy } from '@angular/core';",
@@ -104,85 +87,8 @@
104
87
  "description": "подписка на Observable и автоматическая отписка при уничтожении компонента (ngOnDestroy).",
105
88
  "scope": "javascript,typescript"
106
89
  },
107
- "tool__tryCatch.await": {
108
- "prefix": "tool__tryCatch.await",
109
- "body": ["await evo.awaitTryCatch.send($1, $2)", "$0"],
110
- "description": "tryCatch для promise",
111
- "scope": "javascript,typescript"
112
- },
113
- "tool-as_const_1": {
114
- "prefix": "tool-as_const_1",
115
- "body": ["const obj = { $1: $2 } as const; // readonly", "$0"],
116
- "description": "объект константа",
117
- "scope": "javascript,typescript"
118
- },
119
- "tool-as_const_2_Record": {
120
- "prefix": "tool-as_const_2_Record",
121
- "body": [
122
- "// type UserId = 'id1' | 'id2' | 'id3';",
123
- "// const users: Record<UserId, string> = { id1: 'Alice', id2: 'Bob', id3: 'Charlie' // id4: 'David' // ❌ ошибка: ключ не из UserId } as const;;",
124
- "",
125
- "const obj: Record<$1, $2> = {$0} as const; // readonly"
126
- ],
127
- "description": "типизация объектов через Record",
128
- "scope": "javascript,typescript"
129
- },
130
- "tool--typePickPartialOmit": {
131
- "prefix": "tool--typePickPartialOmit",
132
- "body": [
133
- "// type UserUpdate = Pick<User, 'id'> & Partial<Omit<User, 'id'>>;",
134
- "type $1 = Pick<$2, '$3'> & Partial<Omit<$2, '$3'>>;",
135
- "$0"
136
- ],
137
- "description": "обязательное поле, остальные — опциональные",
138
- "scope": "javascript,typescript"
139
- },
140
- "tool--type_keyof": {
141
- "prefix": "tool--type_keyof",
142
- "body": [
143
- "// interface Person { name: string; age: number }; type PersonKeys = keyof Person",
144
- "type $1Keys = keyof $1;",
145
- "$0"
146
- ],
147
- "description": "динамические ключи объектов",
148
- "scope": "javascript,typescript"
149
- },
150
- "tool--typeTNullable": {
151
- "prefix": "tool--typeTNullable",
152
- "body": [
153
- "// let currentUser: TNullable<User> = { id: 1, name: \"Иван\" };",
154
- "type TNullable<T> = T | null;",
155
- "$0"
156
- ],
157
- "description": "Дженерик-тип, который расширяет тип T, позволяя ему также принимать значение null.",
158
- "scope": "javascript,typescript"
159
- },
160
- "tool--typePartial": {
161
- "prefix": "tool--typePartial",
162
- "body": [
163
- "// const car: Partial<Car> = {};",
164
- "const $1: Partial<$2> = {};",
165
- "$0"
166
- ],
167
- "description": "объект временно пуст",
168
- "scope": "javascript,typescript"
169
- },
170
- "tool__tryCatch": {
171
- "prefix": "tool__tryCatch",
172
- "body": [
173
- "try {",
174
- " $0",
175
- "} catch (error) {",
176
- " console.error(error);",
177
- "} finally {",
178
- " // код, который выполнится всегда",
179
- "}"
180
- ],
181
- "description": "обертка кода в блок try-catch-finally",
182
- "scope": "javascript,typescript"
183
- },
184
- "tool___Injector": {
185
- "prefix": "tool___Injector",
90
+ "tool-ng-injector": {
91
+ "prefix": "tool-ng-injector",
186
92
  "body": [
187
93
  "// в \"рабочем компоненте\" - public constructor(protected injector: Injector) { super(injector); }",
188
94
  "",
@@ -200,8 +106,8 @@
200
106
  "description": "Подключение сервиса в базовом компоненте через injector",
201
107
  "scope": "javascript,typescript"
202
108
  },
203
- "tool____ViewChild_Child": {
204
- "prefix": "tool____ViewChild_Child",
109
+ "tool-ng-viewChild": {
110
+ "prefix": "tool-ng-viewChild",
205
111
  "body": [
206
112
  "import { ViewChild } from '@angular/core'",
207
113
  "",
@@ -211,8 +117,8 @@
211
117
  "description": "дочерний компонент",
212
118
  "scope": "javascript,typescript"
213
119
  },
214
- "tool____ViewChild_Element": {
215
- "prefix": "tool____ViewChild_Element",
120
+ "tool-ng-viewChildEl": {
121
+ "prefix": "tool-ng-viewChildEl",
216
122
  "body": [
217
123
  "import { ViewChild, ElementRef } from '@angular/core'",
218
124
  "",
@@ -222,8 +128,8 @@
222
128
  "description": "html элемент",
223
129
  "scope": "javascript,typescript"
224
130
  },
225
- "tool____get_set": {
226
- "prefix": "tool____get_set",
131
+ "tool-ng-getset": {
132
+ "prefix": "tool-ng-getset",
227
133
  "body": [
228
134
  "private _$1: $2;",
229
135
  "",
@@ -242,8 +148,8 @@
242
148
  "description": "getter/setter типизированный",
243
149
  "scope": "javascript,typescript"
244
150
  },
245
- "tool____get_set@Input()": {
246
- "prefix": "tool____get_set@Input()",
151
+ "tool-ng-getset-input": {
152
+ "prefix": "tool-ng-getset-input",
247
153
  "body": [
248
154
  "private _$1: $2;",
249
155
  "",
@@ -263,8 +169,136 @@
263
169
  "description": "",
264
170
  "scope": "javascript,typescript"
265
171
  },
266
- "tool---Proxy_Логирование": {
267
- "prefix": "tool---Proxy_Логирование",
172
+ "tool-type-pickPartialOmit": {
173
+ "prefix": "tool-type-pickPartialOmit",
174
+ "body": [
175
+ "// type UserUpdate = Pick<User, 'id'> & Partial<Omit<User, 'id'>>;",
176
+ "type $1 = Pick<$2, '$3'> & Partial<Omit<$2, '$3'>>;",
177
+ "$0"
178
+ ],
179
+ "description": "обязательное поле, остальные — опциональные",
180
+ "scope": "javascript,typescript"
181
+ },
182
+ "tool-type-keyof": {
183
+ "prefix": "tool-type-keyof",
184
+ "body": [
185
+ "// interface Person { name: string; age: number }; type PersonKeys = keyof Person",
186
+ "type $1Keys = keyof $1;",
187
+ "$0"
188
+ ],
189
+ "description": "динамические ключи объектов",
190
+ "scope": "javascript,typescript"
191
+ },
192
+ "tool-type-nullable": {
193
+ "prefix": "tool-type-nullable",
194
+ "body": [
195
+ "// let currentUser: TNullable<User> = { id: 1, name: \"Иван\" };",
196
+ "type TNullable<T> = T | null;",
197
+ "$0"
198
+ ],
199
+ "description": "Дженерик-тип, который расширяет тип T, позволяя ему также принимать значение null.",
200
+ "scope": "javascript,typescript"
201
+ },
202
+ "tool-type-partial": {
203
+ "prefix": "tool-type-partial",
204
+ "body": [
205
+ "// const car: Partial<Car> = {};",
206
+ "const $1: Partial<$2> = {};",
207
+ "$0"
208
+ ],
209
+ "description": "объект временно пуст",
210
+ "scope": "javascript,typescript"
211
+ },
212
+ "tool-type-never": {
213
+ "prefix": "tool-type-never",
214
+ "body": [
215
+ "// Если union‑тип (Direction) изменится, TypeScript выдаст ошибку компиляции, если switch не обновлён.",
216
+ "type Direction = 'up' | 'down';",
217
+ "",
218
+ "public move(direction: Direction): number {",
219
+ " switch (direction) {",
220
+ " case 'up': return 1;",
221
+ " case 'down': return -1;",
222
+ " default:",
223
+ " //!!! Если добавлен новый вариант в `Direction` и не обработан — ошибка компиляции",
224
+ " const _: never = direction;",
225
+ " throw new Error(`Неизвестный ключ: ${_}`);",
226
+ " }",
227
+ "}",
228
+ "$0"
229
+ ],
230
+ "description": "пример обеспечения типовой безопасности при работе с union‑тип и switch",
231
+ "scope": "javascript,typescript"
232
+ },
233
+ "tool-type-readonly": {
234
+ "prefix": "tool-type-readonly",
235
+ "body": [
236
+ "// interface UserId { readonly id: number; }; const user: UserId = { id: 12345 };",
237
+ "// Ошибка компиляции - user.id = 67890; // Cannot assign to 'id' because it is a read-only property",
238
+ "interface I$1 {",
239
+ " readonly $2: $3;",
240
+ "}",
241
+ "$0"
242
+ ],
243
+ "description": "Interface with readonly properties",
244
+ "scope": "javascript,typescript"
245
+ },
246
+ "tool-ts-asConst": {
247
+ "prefix": "tool-ts-asConst",
248
+ "body": ["const obj = { $1: $2 } as const; // readonly", "$0"],
249
+ "description": "объект константа",
250
+ "scope": "javascript,typescript"
251
+ },
252
+ "tool-ts-record": {
253
+ "prefix": "tool-ts-record",
254
+ "body": [
255
+ "// type UserId = 'id1' | 'id2' | 'id3';",
256
+ "// const users: Record<UserId, string> = { id1: 'Alice', id2: 'Bob', id3: 'Charlie' // id4: 'David' // ❌ ошибка: ключ не из UserId } as const;;",
257
+ "",
258
+ "const obj: Record<$1, $2> = {$0} as const; // readonly"
259
+ ],
260
+ "description": "типизация объектов через Record",
261
+ "scope": "javascript,typescript"
262
+ },
263
+ "tool-ts-recordSatisfies": {
264
+ "prefix": "tool-ts-recordSatisfies",
265
+ "body": [
266
+ "// type UserId = 'id1' | 'id2' | 'id3';",
267
+ "// const users = { id1: 'Alice', id2: 'Bob', id3: 'Charlie' // id4: 'David' // ❌ ошибка: ключ не из UserId } as const satisfies Record<UserId, string>;",
268
+ "",
269
+ "const obj = {$0} as const satisfies Record<$1, $2>;"
270
+ ],
271
+ "description": "константный объект с as const и satisfies Record",
272
+ "scope": "javascript,typescript"
273
+ },
274
+ "tool-ts-try": {
275
+ "prefix": "tool-ts-try",
276
+ "body": [
277
+ "try {",
278
+ " $0",
279
+ "} catch (error) {",
280
+ " console.error(error);",
281
+ "} finally {",
282
+ " // код, который выполнится всегда",
283
+ "}"
284
+ ],
285
+ "description": "обертка кода в блок try-catch-finally",
286
+ "scope": "javascript,typescript"
287
+ },
288
+ "tool-ts-try-await": {
289
+ "prefix": "tool-ts-try-await",
290
+ "body": ["await evo.awaitTryCatch.send($1, $2)", "$0"],
291
+ "description": "tryCatch для promise",
292
+ "scope": "javascript,typescript"
293
+ },
294
+ "tool-ts-debugger": {
295
+ "prefix": "tool-ts-debugger",
296
+ "body": ["debugger;"],
297
+ "description": "debugger",
298
+ "scope": "javascript,typescript"
299
+ },
300
+ "tool-ts-proxy-log": {
301
+ "prefix": "tool-ts-proxy-log",
268
302
  "body": [
269
303
  "public createProxyLog(target, onChange) {",
270
304
  " // Обработка null и примитивов",
@@ -323,53 +357,19 @@
323
357
  "description": "Функция создания Proxy Логирование",
324
358
  "scope": "javascript,typescript"
325
359
  },
326
- "tool-as_const_3_satisfies_Record": {
327
- "prefix": "tool-as_const_3_satisfies_Record",
328
- "body": [
329
- "// type UserId = 'id1' | 'id2' | 'id3';",
330
- "// const users = { id1: 'Alice', id2: 'Bob', id3: 'Charlie' // id4: 'David' // ❌ ошибка: ключ не из UserId } as const satisfies Record<UserId, string>;",
331
- "",
332
- "const obj = {$0} as const satisfies Record<$1, $2>;"
333
- ],
334
- "description": "константный объект с as const и satisfies Record",
335
- "scope": "javascript,typescript"
336
- },
337
- "tool#type_never": {
338
- "prefix": "tool#type_never",
360
+ "tool-global-forEach": {
361
+ "prefix": "tool-global-forEach",
339
362
  "body": [
340
- "// Если union‑тип (Direction) изменится, TypeScript выдаст ошибку компиляции, если switch не обновлён.",
341
- "type Direction = 'up' | 'down';",
342
- "",
343
- "public move(direction: Direction): number {",
344
- " switch (direction) {",
345
- " case 'up': return 1;",
346
- " case 'down': return -1;",
347
- " default:",
348
- " //!!! Если добавлен новый вариант в `Direction` и не обработан — ошибка компиляции",
349
- " const _: never = direction;",
350
- " throw new Error(`Неизвестный ключ: ${_}`);",
351
- " }",
352
- "}",
353
- "$0"
354
- ],
355
- "description": "пример обеспечения типовой безопасности при работе с union‑тип и switch",
356
- "scope": "javascript,typescript"
357
- },
358
- "tool--Interface with readonly": {
359
- "prefix": "tool--Interface with readonly",
360
- "body": [
361
- "// interface UserId { readonly id: number; }; const user: UserId = { id: 12345 };",
362
- "// Ошибка компиляции - user.id = 67890; // Cannot assign to 'id' because it is a read-only property",
363
- "interface I$1 {",
364
- " readonly $2: $3;",
365
- "}",
363
+ "$1.forEach((item, i, arr) => {",
364
+ " console.log( arr, i, item);",
365
+ "});",
366
366
  "$0"
367
367
  ],
368
- "description": "Interface with readonly properties",
368
+ "description": "forEach - метод массива",
369
369
  "scope": "javascript,typescript"
370
370
  },
371
- "tool#switch": {
372
- "prefix": "tool#switch",
371
+ "tool-global-switch": {
372
+ "prefix": "tool-global-switch",
373
373
  "body": [
374
374
  "switch ($1) {",
375
375
  " case $2: $3; break;",
@@ -382,8 +382,8 @@
382
382
  "description": "create SWITCH block",
383
383
  "scope": "javascript,typescript"
384
384
  },
385
- "tool#switch_NEVER": {
386
- "prefix": "tool#switch_NEVER",
385
+ "tool-global-switch-never": {
386
+ "prefix": "tool-global-switch-never",
387
387
  "body": [
388
388
  "// Если union‑тип (type Direction = 'up' | 'down';) изменится, TypeScript выдаст ошибку компиляции, если switch не обновлён.",
389
389
  "",
@@ -403,8 +403,8 @@
403
403
  "description": "create SWITCH block with NEVER",
404
404
  "scope": "javascript,typescript"
405
405
  },
406
- "tool----windowГлобальный_объект": {
407
- "prefix": "tool----windowГлобальный_объект",
406
+ "tool-global-window": {
407
+ "prefix": "tool-global-window",
408
408
  "body": [
409
409
  "declare global {",
410
410
  " interface Window { $1: any; }",
@@ -419,8 +419,8 @@
419
419
  "description": "Declare global window object and assign value",
420
420
  "scope": "javascript,typescript"
421
421
  },
422
- "tool---globalErrorListeners": {
423
- "prefix": "tool---globalErrorListeners",
422
+ "tool-global-errors": {
423
+ "prefix": "tool-global-errors",
424
424
  "body": [
425
425
  "window.addEventListener('error', (event) => { console.warn('Global error:', event.error); }); // для обычных ошибок",
426
426
  "",
@@ -1,211 +1,211 @@
1
1
  <templateSet group="#tool-frontend">
2
- <template name="tool#forEach" value="$ARR$.forEach((item, i, arr) =&gt; {&#10; console.log( arr, i, item);&#10;});$END$" description="forEach - метод массива" toReformat="true" toShortenFQNames="true">
3
- <variable name="ARR" expression="" defaultValue="" alwaysStopAt="true" />
4
- <context>
5
- <option name="JAVA_SCRIPT" value="true" />
6
- <option name="TypeScript" value="true" />
7
- </context>
8
- </template>
9
- <template name="tool_deb" value="debugger;" description="debugger" toReformat="true" toShortenFQNames="true">
10
- <context>
11
- <option name="JAVA_SCRIPT" value="true" />
12
- <option name="TypeScript" value="true" />
13
- </context>
14
- </template>
15
- <template name="tool_comp_2_ngOnInit" value="import { OnInit } from '@angular/core';&#10;&#10;implements OnInit&#10;&#10;public ngOnInit() {&#10; $TEXT$&#10;}$END$&#10;" description="хук, вызывается один раз после создания компонента, когда инициализировались все данные (например, @Input свойства) - при первой загрузке" toReformat="false" toShortenFQNames="true">
16
- <variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" />
17
- <context>
18
- <option name="JAVA_SCRIPT" value="true" />
19
- <option name="TypeScript" value="true" />
20
- </context>
21
- </template>
22
- <template name="tool_comp_4_ngOnDestroy" value="import {OnDestroy} from '@angular/core';&#10;&#10;implements OnDestroy&#10;&#10;public ngOnDestroy() {&#10; $TEXT$&#10;}$END$" description="хук, вызывается перед уничтожением компонента - при уничтожении" toReformat="false" toShortenFQNames="true">
23
- <variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" />
24
- <context>
25
- <option name="JAVA_SCRIPT" value="true" />
26
- <option name="TypeScript" value="true" />
27
- </context>
28
- </template>
29
- <template name="tool_comp_1_ngOnChanges" value="import { OnChanges, SimpleChanges } from '@angular/core';&#10;&#10;implements OnChanges&#10;&#10;public ngOnChanges(changes: SimpleChanges): void {&#10; console.log(changes);&#10;}$END$" description="хук, который срабатывает каждый раз, когда меняются входные данные (@Input) компонента - при первой загрузке (если есть @Input)" toReformat="true" toShortenFQNames="true">
30
- <context>
31
- <option name="JAVA_SCRIPT" value="true" />
32
- <option name="TypeScript" value="true" />
33
- </context>
34
- </template>
35
- <template name="tool_comp_3_ngAfterViewInit" value="import { AfterViewInit } from '@angular/core';&#10;&#10;implements AfterViewInit&#10;&#10;public ngAfterViewInit() {&#10; $TEXT$&#10;}$END$" description="хук, вызывается после полной инициализации представления (view) компонента - при первой загрузке" toReformat="true" toShortenFQNames="true">
36
- <variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" />
37
- <context>
38
- <option name="JAVA_SCRIPT" value="true" />
39
- <option name="TypeScript" value="true" />
40
- </context>
41
- </template>
42
- <template name="tool___subscribe" value="// --------------------------------------&#10;import { OnDestroy } from '@angular/core';&#10;import { Subject } from 'rxjs/Subject';&#10;import { takeUntil } from 'rxjs/operators';&#10;// --------------------------------------&#10;private _destroyedSubscribe$: Subject&lt;void&gt; = new Subject&lt;void&gt;();&#10;// --------------------------------------&#10; $TEXT$&#10; .pipe(takeUntil(this._destroyedSubscribe$))&#10; .subscribe({&#10; next: (result) =&gt; { console.log('result', result); },&#10; error: (err) =&gt; { console.error('Ошибка:', err); // здесь можно показать уведомление или выполнить fallback-логику },&#10; complete: () =&gt; { console.log('Поток завершён'); }&#10; });&#10;// --------------------------------------&#10;public ngOnDestroy(): void {&#10; this._destroyedSubscribe$.next();&#10; this._destroyedSubscribe$.complete();&#10;}&#10;// --------------------------------------" description="подписка на Observable и автоматическая отписка при уничтожении компонента (ngOnDestroy)." toReformat="false" toShortenFQNames="true">
43
- <variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" />
44
- <context>
45
- <option name="JAVA_SCRIPT" value="true" />
46
- <option name="TypeScript" value="true" />
47
- </context>
48
- </template>
49
- <template name="tool__tryCatch.await" value="await evo.awaitTryCatch.send($PROMISE$, $FROM$)" description="tryCatch для promise" toReformat="false" toShortenFQNames="true">
50
- <variable name="PROMISE" expression="" defaultValue="" alwaysStopAt="true" />
51
- <variable name="FROM" expression="" defaultValue="" alwaysStopAt="true" />
52
- <context>
53
- <option name="JAVA_SCRIPT" value="true" />
54
- <option name="TypeScript" value="true" />
55
- </context>
56
- </template>
57
- <template name="tool-as_const_1" value="const obj = { $PROP$: $VAL$} as const; // readonly" description="объект константа" toReformat="false" toShortenFQNames="true">
58
- <variable name="PROP" expression="" defaultValue="" alwaysStopAt="true" />
59
- <variable name="VAL" expression="" defaultValue="" alwaysStopAt="true" />
60
- <context>
61
- <option name="JAVA_SCRIPT" value="true" />
62
- <option name="TypeScript" value="true" />
63
- </context>
64
- </template>
65
- <template name="tool-as_const_2_Record" value="// type UserId = 'id1' | 'id2' | 'id3';&#10;// const users: Record&lt;UserId, string&gt; = { id1: 'Alice', id2: 'Bob', id3: 'Charlie' // id4: 'David' // ❌ ошибка: ключ не из UserId } as const;;&#10;&#10;const obj: Record&lt;$PROP$, $VAL$&gt; = {$END$} as const; // readonly" description="типизация объектов через Record" toReformat="false" toShortenFQNames="true">
66
- <variable name="PROP" expression="" defaultValue="" alwaysStopAt="true" />
67
- <variable name="VAL" expression="" defaultValue="" alwaysStopAt="true" />
68
- <context>
69
- <option name="JAVA_SCRIPT" value="true" />
70
- <option name="TypeScript" value="true" />
71
- </context>
72
- </template>
73
- <template name="tool--typePickPartialOmit" value="// type UserUpdate = Pick&lt;User, 'id'&gt; &amp; Partial&lt;Omit&lt;User, 'id'&gt;&gt;;&#10;type $TYPE$ = Pick&lt;$INTERFACE$, '$PROP$'&gt; &amp; Partial&lt;Omit&lt;$INTERFACE$, '$PROP$'&gt;&gt;;" description="обязательное поле, остальные — опциональные" toReformat="false" toShortenFQNames="true">
74
- <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
75
- <variable name="INTERFACE" expression="" defaultValue="" alwaysStopAt="true" />
76
- <variable name="PROP" expression="" defaultValue="" alwaysStopAt="true" />
77
- <context>
78
- <option name="JAVA_SCRIPT" value="true" />
79
- <option name="TypeScript" value="true" />
80
- </context>
81
- </template>
82
- <template name="tool--type_keyof" value="// interface Person { name: string; age: number }; type PersonKeys = keyof Person&#10;type $TYPE$Keys = keyof $TYPE$;" description="динамические ключи объектов" toReformat="false" toShortenFQNames="true">
83
- <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
84
- <context>
85
- <option name="JAVA_SCRIPT" value="true" />
86
- <option name="TypeScript" value="true" />
87
- </context>
88
- </template>
89
- <template name="tool--typeTNullable" value="// let currentUser: TNullable&lt;User&gt; = { id: 1, name: &quot;Иван&quot; };&#10;type TNullable&lt;T&gt; = T | null;" description="Дженерик-тип, который расширяет тип T, позволяя ему также принимать значение null." toReformat="false" toShortenFQNames="true">
90
- <context>
91
- <option name="JAVA_SCRIPT" value="true" />
92
- <option name="TypeScript" value="true" />
93
- </context>
94
- </template>
95
- <template name="tool--typePartial" value="// const car: Partial&lt;Car&gt; = {};&#10;const $CAR$: Partial&lt;$CARINTERFACE$&gt; = {};" description="объект временно пуст" toReformat="false" toShortenFQNames="true">
96
- <variable name="CAR" expression="" defaultValue="" alwaysStopAt="true" />
97
- <variable name="CARINTERFACE" expression="" defaultValue="" alwaysStopAt="true" />
98
- <context>
99
- <option name="JAVA_SCRIPT" value="true" />
100
- <option name="TypeScript" value="true" />
101
- </context>
102
- </template>
103
- <template name="tool__tryCatch" value="try {&#10; $END$&#10;} catch (error) {&#10; console.error(error);&#10;} finally {&#10; // код, который выполнится всегда&#10;}" description="обертка кода в блок try-catch-finally" toReformat="false" toShortenFQNames="true">
104
- <context>
105
- <option name="JAVA_SCRIPT" value="true" />
106
- <option name="TypeScript" value="true" />
107
- </context>
108
- </template>
109
- <template name="tool___Injector" value="// в &quot;рабочем компоненте&quot; - public constructor(protected injector: Injector) { super(injector); }&#10;&#10;import { Injector, Type } from '@angular/core';&#10;&#10;protected $INSTANS$: $SERVICE$;&#10;&#10;protected constructor(&#10; protected injector: Injector,&#10;) {&#10; this.$INSTANS$ = injector.get&lt;$SERVICE$&gt;($SERVICE$ as Type&lt;$SERVICE$&gt;);&#10;}" description="Подключение сервиса в базовом компоненте через injector" toReformat="false" toShortenFQNames="true">
110
- <variable name="INSTANS" expression="" defaultValue="" alwaysStopAt="true" />
111
- <variable name="SERVICE" expression="" defaultValue="" alwaysStopAt="true" />
112
- <context>
113
- <option name="JAVA_SCRIPT" value="true" />
114
- <option name="TypeScript" value="true" />
115
- </context>
116
- </template>
117
- <template name="tool____ViewChild_Child" value="import { ViewChild } from '@angular/core'&#10;&#10;@ViewChild($COMPONENT$) private _childComponent!: $COMPONENT$;" description="дочерний компонент" toReformat="false" toShortenFQNames="true">
118
- <variable name="COMPONENT" expression="" defaultValue="" alwaysStopAt="true" />
119
- <context>
120
- <option name="JAVA_SCRIPT" value="true" />
121
- <option name="TypeScript" value="true" />
122
- </context>
123
- </template>
124
- <template name="tool____ViewChild_Element" value="import { ViewChild, ElementRef } from '@angular/core'&#10;&#10;@ViewChild('element') private _element: ElementRef; // &lt;div #rootElement&gt;&lt;/div&gt;" description="html элемент" toReformat="false" toShortenFQNames="true">
125
- <context>
126
- <option name="JAVA_SCRIPT" value="true" />
127
- <option name="TypeScript" value="true" />
128
- </context>
129
- </template>
130
- <template name="tool____get_set" value="private _$VAR$: $TYPE$;&#10;&#10;public get $VAR$(): $TYPE$ {&#10; return this._$VAR$;&#10;}&#10;&#10;public set $VAR$(value: $TYPE$) {&#10; if (this._$VAR$ !== value) {&#10; this._$VAR$ = value;&#10; // this.cdr.markForCheck(); // если используется ChangeDetectionStrategy.OnPush&#10; }&#10;}$END$" description="getter/setter типизированный" toReformat="false" toShortenFQNames="true">
131
- <variable name="VAR" expression="" defaultValue="" alwaysStopAt="true" />
132
- <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
133
- <context>
134
- <option name="JAVA_SCRIPT" value="true" />
135
- <option name="TypeScript" value="true" />
136
- </context>
137
- </template>
138
- <template name="tool____get_set@Input()" value="private _$VAR$: $TYPE$;&#10;&#10;@Input()&#10;public get $VAR$(): $TYPE$ {&#10; return this._$VAR$;&#10;}&#10;&#10;public set $VAR$(value: $TYPE$) {&#10; if (this._$VAR$ !== value) {&#10; this._$VAR$ = value;&#10; // this.cdr.markForCheck(); // если используется ChangeDetectionStrategy.OnPush&#10; }&#10;}$END$" description="" toReformat="false" toShortenFQNames="true">
139
- <variable name="VAR" expression="" defaultValue="" alwaysStopAt="true" />
140
- <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
141
- <context>
142
- <option name="JAVA_SCRIPT" value="true" />
143
- <option name="TypeScript" value="true" />
144
- </context>
145
- </template>
146
- <template name="tool---Proxy_Логирование" value="public createProxyLog(target, onChange) {&#10; // Обработка null и примитивов&#10; if (target === null || typeof target !== 'object') {&#10; return target;&#10; }&#10; &#10; return new Proxy(target, {&#10; set(obj, prop, value) {&#10; const oldValue = obj[prop];&#10; &#10; // Рекурсивно обрабатываем новые объекты&#10; const newValue = this.createProxyLog(value, onChange);&#10; &#10; obj[prop] = newValue;&#10; &#10; // Проверяем реальное изменение (учитываем NaN)&#10; if (oldValue !== value &amp;&amp; !(Number.isNaN(oldValue) &amp;&amp; Number.isNaN(value))) {&#10; onChange(prop, newValue, oldValue);&#10; }&#10; &#10; return true;&#10; },&#10; &#10; get(obj, prop) {&#10; const value = obj[prop];&#10; &#10; // Рекурсивно создаем прокси для вложенных объектов&#10; if (value !== null &amp;&amp; typeof value === 'object') {&#10; return this.createProxyLog(value, onChange);&#10; }&#10; &#10; return value;&#10; },&#10; &#10; deleteProperty(obj, prop) {&#10; const oldValue = obj[prop];&#10; const deleted = delete obj[prop];&#10; &#10; if (deleted) { onChange(prop, undefined, oldValue); }&#10; &#10; return deleted;&#10; }&#10; });&#10;}&#10;&#10;&#10;// Использование:&#10;//let state = this.createProxyLog(&#10;//{ user: { name: 'Alice', age: 30 } settings: { theme: 'dark', notifications: true } }, &#10;//(prop, value, oldValue) =&gt; { console.log(`Property &quot;${prop}&quot; changed: ${oldValue} → ${value}`); });&#10;//&#10;// delete state.user.email; // Property &quot;email&quot; changed: alice@example.com → undefined" description="Функция создания Proxy Логирование" toReformat="false" toShortenFQNames="true">
147
- <context>
148
- <option name="JAVA_SCRIPT" value="true" />
149
- <option name="TypeScript" value="true" />
150
- </context>
151
- </template>
152
- <template name="tool-as_const_3_satisfies_Record" value="// type UserId = 'id1' | 'id2' | 'id3';&#10;// const users = { id1: 'Alice', id2: 'Bob', id3: 'Charlie' // id4: 'David' // ❌ ошибка: ключ не из UserId } as const satisfies Record&lt;UserId, string&gt;;&#10;&#10;const obj = {$END$} as const satisfies Record&lt;$KEY_TYPE$, $VALUE_TYPE$&gt;;" description="константный объект с as const и satisfies Record" toReformat="false" toShortenFQNames="true">
153
- <variable name="KEY_TYPE" expression="" defaultValue="" alwaysStopAt="true" />
154
- <variable name="VALUE_TYPE" expression="" defaultValue="" alwaysStopAt="true" />
155
- <context>
156
- <option name="JAVA_SCRIPT" value="true" />
157
- <option name="TypeScript" value="true" />
158
- </context>
159
- </template>
160
- <template name="tool#type_never" value="// Если union‑тип (Direction) изменится, TypeScript выдаст ошибку компиляции, если switch не обновлён.&#10;type Direction = 'up' | 'down';&#10;&#10;public move(direction: Direction): number {&#10; switch (direction) {&#10; case 'up': return 1;&#10; case 'down': return -1;&#10; default:&#10; //!!! Если добавлен новый вариант в `Direction` и не обработан — ошибка компиляции&#10; const _: never = direction;&#10; throw new Error(`Неизвестный ключ: ${_}`);&#10; }&#10;}" description="пример обеспечения типовой безопасности при работе с union‑тип и switch" toReformat="false" toShortenFQNames="true" deactivated="true">
161
- <context>
162
- <option name="JAVA_SCRIPT" value="true" />
163
- <option name="TypeScript" value="true" />
164
- </context>
165
- </template>
166
- <template name="tool--Interface with readonly" value="// interface UserId { readonly id: number; }; const user: UserId = { id: 12345 };&#10;// Ошибка компиляции - user.id = 67890; // Cannot assign to 'id' because it is a read-only property&#10;interface I$NAME$ {&#10; readonly $PROPERTY$: $TYPE$;&#10;}" description="Interface with readonly properties" toReformat="false" toShortenFQNames="true">
167
- <variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
168
- <variable name="PROPERTY" expression="" defaultValue="" alwaysStopAt="true" />
169
- <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
170
- <context>
171
- <option name="JAVA_SCRIPT" value="true" />
172
- <option name="TypeScript" value="true" />
173
- </context>
174
- </template>
175
- <template name="tool#switch" value="switch ($EXPRESSION$) {&#10; case $CASE1$: $BODY1$; break;&#10; case $CASE2$: $BODY2$; break;&#10; default:&#10; $DEFAULT_BODY$;&#10;}&#10;" description="create SWITCH block" toReformat="false" toShortenFQNames="true">
176
- <variable name="EXPRESSION" expression="" defaultValue="" alwaysStopAt="true" />
177
- <variable name="CASE1" expression="" defaultValue="" alwaysStopAt="true" />
178
- <variable name="BODY1" expression="" defaultValue="" alwaysStopAt="true" />
179
- <variable name="CASE2" expression="" defaultValue="" alwaysStopAt="true" />
180
- <variable name="BODY2" expression="" defaultValue="" alwaysStopAt="true" />
181
- <variable name="DEFAULT_BODY" expression="" defaultValue="" alwaysStopAt="true" />
182
- <context>
183
- <option name="JAVA_SCRIPT" value="true" />
184
- <option name="TypeScript" value="true" />
185
- </context>
186
- </template>
187
- <template name="tool#switch_NEVER" value="// Если union‑тип (type Direction = 'up' | 'down';) изменится, TypeScript выдаст ошибку компиляции, если switch не обновлён.&#10;&#10;switch ($EXPRESSION$) {&#10; case $CASE1$:&#10; $BODY1$;&#10; break;&#10; case $CASE2$:&#10; $BODY2$;&#10; break;&#10; default:&#10; const _exhaustiveCheck: never = $EXPRESSION$;&#10; throw new Error(`Необработанное значение: ${$EXPRESSION$}`);&#10;}&#10;" description="create SWITCH block with NEVER" toReformat="false" toShortenFQNames="true">
188
- <variable name="EXPRESSION" expression="" defaultValue="" alwaysStopAt="true" />
189
- <variable name="CASE1" expression="" defaultValue="" alwaysStopAt="true" />
190
- <variable name="BODY1" expression="" defaultValue="" alwaysStopAt="true" />
191
- <variable name="CASE2" expression="" defaultValue="" alwaysStopAt="true" />
192
- <variable name="BODY2" expression="" defaultValue="" alwaysStopAt="true" />
193
- <context>
194
- <option name="JAVA_SCRIPT" value="true" />
195
- <option name="TypeScript" value="true" />
196
- </context>
197
- </template>
198
- <template name="tool----windowГлобальный_объект" value="declare global {&#10; interface Window { $NAME$: any; }&#10; &#10; const $NAME$: any; // Добавляем глобальную переменную&#10;}&#10;&#10;(window as any).$NAME$ = $END$;&#10;&#10;export {};" description="Declare global window object and assign value" toReformat="false" toShortenFQNames="true">
199
- <variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
200
- <context>
201
- <option name="JAVA_SCRIPT" value="true" />
202
- <option name="TypeScript" value="true" />
203
- </context>
204
- </template>
205
- <template name="tool---globalErrorListeners" value="window.addEventListener('error', (event) =&gt; { console.warn('Global error:', event.error); }); // для обычных ошибок&#10;&#10;window.addEventListener('unhandledrejection', (event) =&gt; {&#10; console.warn('Unhandled promise rejection:', event.reason); // для ошибок (например, async / Promise)&#10;});" description="Debug: global error &amp; promise rejection listeners" toReformat="false" toShortenFQNames="true">
206
- <context>
207
- <option name="JAVA_SCRIPT" value="true" />
208
- <option name="TypeScript" value="true" />
209
- </context>
210
- </template>
2
+ <template name="tool-hook-onChanges" value="import { OnChanges, SimpleChanges } from '@angular/core';&#10;&#10;implements OnChanges&#10;&#10;public ngOnChanges(changes: SimpleChanges): void {&#10; console.log(changes);&#10;}$END$" description="хук, который срабатывает каждый раз, когда меняются входные данные (@Input) компонента - при первой загрузке (если есть @Input)" toReformat="true" toShortenFQNames="true">
3
+ <context>
4
+ <option name="JAVA_SCRIPT" value="true" />
5
+ <option name="TypeScript" value="true" />
6
+ </context>
7
+ </template>
8
+ <template name="tool-hook-onInit" value="import { OnInit } from '@angular/core';&#10;&#10;implements OnInit&#10;&#10;public ngOnInit() {&#10; $TEXT$&#10;}$END$&#10;" description="хук, вызывается один раз после создания компонента, когда инициализировались все данные (например, @Input свойства) - при первой загрузке" toReformat="false" toShortenFQNames="true">
9
+ <variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" />
10
+ <context>
11
+ <option name="JAVA_SCRIPT" value="true" />
12
+ <option name="TypeScript" value="true" />
13
+ </context>
14
+ </template>
15
+ <template name="tool-hook-afterViewInit" value="import { AfterViewInit } from '@angular/core';&#10;&#10;implements AfterViewInit&#10;&#10;public ngAfterViewInit() {&#10; $TEXT$&#10;}$END$" description="хук, вызывается после полной инициализации представления (view) компонента - при первой загрузке" toReformat="true" toShortenFQNames="true">
16
+ <variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" />
17
+ <context>
18
+ <option name="JAVA_SCRIPT" value="true" />
19
+ <option name="TypeScript" value="true" />
20
+ </context>
21
+ </template>
22
+ <template name="tool-hook-onDestroy" value="import {OnDestroy} from '@angular/core';&#10;&#10;implements OnDestroy&#10;&#10;public ngOnDestroy() {&#10; $TEXT$&#10;}$END$" description="хук, вызывается перед уничтожением компонента - при уничтожении" toReformat="false" toShortenFQNames="true">
23
+ <variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" />
24
+ <context>
25
+ <option name="JAVA_SCRIPT" value="true" />
26
+ <option name="TypeScript" value="true" />
27
+ </context>
28
+ </template>
29
+ <template name="tool-ng-subscribe" value="// --------------------------------------&#10;import { OnDestroy } from '@angular/core';&#10;import { Subject } from 'rxjs/Subject';&#10;import { takeUntil } from 'rxjs/operators';&#10;// --------------------------------------&#10;private _destroyedSubscribe$: Subject&lt;void&gt; = new Subject&lt;void&gt;();&#10;// --------------------------------------&#10; $TEXT$&#10; .pipe(takeUntil(this._destroyedSubscribe$))&#10; .subscribe({&#10; next: (result) =&gt; { console.log('result', result); },&#10; error: (err) =&gt; { console.error('Ошибка:', err); // здесь можно показать уведомление или выполнить fallback-логику },&#10; complete: () =&gt; { console.log('Поток завершён'); }&#10; });&#10;// --------------------------------------&#10;public ngOnDestroy(): void {&#10; this._destroyedSubscribe$.next();&#10; this._destroyedSubscribe$.complete();&#10;}&#10;// --------------------------------------" description="подписка на Observable и автоматическая отписка при уничтожении компонента (ngOnDestroy)." toReformat="false" toShortenFQNames="true">
30
+ <variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" />
31
+ <context>
32
+ <option name="JAVA_SCRIPT" value="true" />
33
+ <option name="TypeScript" value="true" />
34
+ </context>
35
+ </template>
36
+ <template name="tool-ng-injector" value="// в &quot;рабочем компоненте&quot; - public constructor(protected injector: Injector) { super(injector); }&#10;&#10;import { Injector, Type } from '@angular/core';&#10;&#10;protected $INSTANS$: $SERVICE$;&#10;&#10;protected constructor(&#10; protected injector: Injector,&#10;) {&#10; this.$INSTANS$ = injector.get&lt;$SERVICE$&gt;($SERVICE$ as Type&lt;$SERVICE$&gt;);&#10;}" description="Подключение сервиса в базовом компоненте через injector" toReformat="false" toShortenFQNames="true">
37
+ <variable name="INSTANS" expression="" defaultValue="" alwaysStopAt="true" />
38
+ <variable name="SERVICE" expression="" defaultValue="" alwaysStopAt="true" />
39
+ <context>
40
+ <option name="JAVA_SCRIPT" value="true" />
41
+ <option name="TypeScript" value="true" />
42
+ </context>
43
+ </template>
44
+ <template name="tool-ng-viewChild" value="import { ViewChild } from '@angular/core'&#10;&#10;@ViewChild($COMPONENT$) private _childComponent!: $COMPONENT$;" description="дочерний компонент" toReformat="false" toShortenFQNames="true">
45
+ <variable name="COMPONENT" expression="" defaultValue="" alwaysStopAt="true" />
46
+ <context>
47
+ <option name="JAVA_SCRIPT" value="true" />
48
+ <option name="TypeScript" value="true" />
49
+ </context>
50
+ </template>
51
+ <template name="tool-ng-viewChildEl" value="import { ViewChild, ElementRef } from '@angular/core'&#10;&#10;@ViewChild('element') private _element: ElementRef; // &lt;div #rootElement&gt;&lt;/div&gt;" description="html элемент" toReformat="false" toShortenFQNames="true">
52
+ <context>
53
+ <option name="JAVA_SCRIPT" value="true" />
54
+ <option name="TypeScript" value="true" />
55
+ </context>
56
+ </template>
57
+ <template name="tool-ng-getset" value="private _$VAR$: $TYPE$;&#10;&#10;public get $VAR$(): $TYPE$ {&#10; return this._$VAR$;&#10;}&#10;&#10;public set $VAR$(value: $TYPE$) {&#10; if (this._$VAR$ !== value) {&#10; this._$VAR$ = value;&#10; // this.cdr.markForCheck(); // если используется ChangeDetectionStrategy.OnPush&#10; }&#10;}$END$" description="getter/setter типизированный" toReformat="false" toShortenFQNames="true">
58
+ <variable name="VAR" expression="" defaultValue="" alwaysStopAt="true" />
59
+ <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
60
+ <context>
61
+ <option name="JAVA_SCRIPT" value="true" />
62
+ <option name="TypeScript" value="true" />
63
+ </context>
64
+ </template>
65
+ <template name="tool-ng-getset-input" value="private _$VAR$: $TYPE$;&#10;&#10;@Input()&#10;public get $VAR$(): $TYPE$ {&#10; return this._$VAR$;&#10;}&#10;&#10;public set $VAR$(value: $TYPE$) {&#10; if (this._$VAR$ !== value) {&#10; this._$VAR$ = value;&#10; // this.cdr.markForCheck(); // если используется ChangeDetectionStrategy.OnPush&#10; }&#10;}$END$" description="" toReformat="false" toShortenFQNames="true">
66
+ <variable name="VAR" expression="" defaultValue="" alwaysStopAt="true" />
67
+ <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
68
+ <context>
69
+ <option name="JAVA_SCRIPT" value="true" />
70
+ <option name="TypeScript" value="true" />
71
+ </context>
72
+ </template>
73
+ <template name="tool-type-pickPartialOmit" value="// type UserUpdate = Pick&lt;User, 'id'&gt; &amp; Partial&lt;Omit&lt;User, 'id'&gt;&gt;;&#10;type $TYPE$ = Pick&lt;$INTERFACE$, '$PROP$'&gt; &amp; Partial&lt;Omit&lt;$INTERFACE$, '$PROP$'&gt;&gt;;" description="обязательное поле, остальные — опциональные" toReformat="false" toShortenFQNames="true">
74
+ <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
75
+ <variable name="INTERFACE" expression="" defaultValue="" alwaysStopAt="true" />
76
+ <variable name="PROP" expression="" defaultValue="" alwaysStopAt="true" />
77
+ <context>
78
+ <option name="JAVA_SCRIPT" value="true" />
79
+ <option name="TypeScript" value="true" />
80
+ </context>
81
+ </template>
82
+ <template name="tool-type-keyof" value="// interface Person { name: string; age: number }; type PersonKeys = keyof Person&#10;type $TYPE$Keys = keyof $TYPE$;" description="динамические ключи объектов" toReformat="false" toShortenFQNames="true">
83
+ <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
84
+ <context>
85
+ <option name="JAVA_SCRIPT" value="true" />
86
+ <option name="TypeScript" value="true" />
87
+ </context>
88
+ </template>
89
+ <template name="tool-type-nullable" value="// let currentUser: TNullable&lt;User&gt; = { id: 1, name: &quot;Иван&quot; };&#10;type TNullable&lt;T&gt; = T | null;" description="Дженерик-тип, который расширяет тип T, позволяя ему также принимать значение null." toReformat="false" toShortenFQNames="true">
90
+ <context>
91
+ <option name="JAVA_SCRIPT" value="true" />
92
+ <option name="TypeScript" value="true" />
93
+ </context>
94
+ </template>
95
+ <template name="tool-type-partial" value="// const car: Partial&lt;Car&gt; = {};&#10;const $CAR$: Partial&lt;$CARINTERFACE$&gt; = {};" description="объект временно пуст" toReformat="false" toShortenFQNames="true">
96
+ <variable name="CAR" expression="" defaultValue="" alwaysStopAt="true" />
97
+ <variable name="CARINTERFACE" expression="" defaultValue="" alwaysStopAt="true" />
98
+ <context>
99
+ <option name="JAVA_SCRIPT" value="true" />
100
+ <option name="TypeScript" value="true" />
101
+ </context>
102
+ </template>
103
+ <template name="tool-type-never" value="// Если union‑тип (Direction) изменится, TypeScript выдаст ошибку компиляции, если switch не обновлён.&#10;type Direction = 'up' | 'down';&#10;&#10;public move(direction: Direction): number {&#10; switch (direction) {&#10; case 'up': return 1;&#10; case 'down': return -1;&#10; default:&#10; //!!! Если добавлен новый вариант в `Direction` и не обработан — ошибка компиляции&#10; const _: never = direction;&#10; throw new Error(`Неизвестный ключ: ${_}`);&#10; }&#10;}" description="пример обеспечения типовой безопасности при работе с union‑тип и switch" toReformat="false" toShortenFQNames="true" deactivated="true">
104
+ <context>
105
+ <option name="JAVA_SCRIPT" value="true" />
106
+ <option name="TypeScript" value="true" />
107
+ </context>
108
+ </template>
109
+ <template name="tool-type-readonly" value="// interface UserId { readonly id: number; }; const user: UserId = { id: 12345 };&#10;// Ошибка компиляции - user.id = 67890; // Cannot assign to 'id' because it is a read-only property&#10;interface I$NAME$ {&#10; readonly $PROPERTY$: $TYPE$;&#10;}" description="Interface with readonly properties" toReformat="false" toShortenFQNames="true">
110
+ <variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
111
+ <variable name="PROPERTY" expression="" defaultValue="" alwaysStopAt="true" />
112
+ <variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
113
+ <context>
114
+ <option name="JAVA_SCRIPT" value="true" />
115
+ <option name="TypeScript" value="true" />
116
+ </context>
117
+ </template>
118
+ <template name="tool-ts-asConst" value="const obj = { $PROP$: $VAL$} as const; // readonly" description="объект константа" toReformat="false" toShortenFQNames="true">
119
+ <variable name="PROP" expression="" defaultValue="" alwaysStopAt="true" />
120
+ <variable name="VAL" expression="" defaultValue="" alwaysStopAt="true" />
121
+ <context>
122
+ <option name="JAVA_SCRIPT" value="true" />
123
+ <option name="TypeScript" value="true" />
124
+ </context>
125
+ </template>
126
+ <template name="tool-ts-record" value="// type UserId = 'id1' | 'id2' | 'id3';&#10;// const users: Record&lt;UserId, string&gt; = { id1: 'Alice', id2: 'Bob', id3: 'Charlie' // id4: 'David' // ❌ ошибка: ключ не из UserId } as const;;&#10;&#10;const obj: Record&lt;$PROP$, $VAL$&gt; = {$END$} as const; // readonly" description="типизация объектов через Record" toReformat="false" toShortenFQNames="true">
127
+ <variable name="PROP" expression="" defaultValue="" alwaysStopAt="true" />
128
+ <variable name="VAL" expression="" defaultValue="" alwaysStopAt="true" />
129
+ <context>
130
+ <option name="JAVA_SCRIPT" value="true" />
131
+ <option name="TypeScript" value="true" />
132
+ </context>
133
+ </template>
134
+ <template name="tool-ts-recordSatisfies" value="// type UserId = 'id1' | 'id2' | 'id3';&#10;// const users = { id1: 'Alice', id2: 'Bob', id3: 'Charlie' // id4: 'David' // ❌ ошибка: ключ не из UserId } as const satisfies Record&lt;UserId, string&gt;;&#10;&#10;const obj = {$END$} as const satisfies Record&lt;$KEY_TYPE$, $VALUE_TYPE$&gt;;" description="константный объект с as const и satisfies Record" toReformat="false" toShortenFQNames="true">
135
+ <variable name="KEY_TYPE" expression="" defaultValue="" alwaysStopAt="true" />
136
+ <variable name="VALUE_TYPE" expression="" defaultValue="" alwaysStopAt="true" />
137
+ <context>
138
+ <option name="JAVA_SCRIPT" value="true" />
139
+ <option name="TypeScript" value="true" />
140
+ </context>
141
+ </template>
142
+ <template name="tool-ts-try" value="try {&#10; $END$&#10;} catch (error) {&#10; console.error(error);&#10;} finally {&#10; // код, который выполнится всегда&#10;}" description="обертка кода в блок try-catch-finally" toReformat="false" toShortenFQNames="true">
143
+ <context>
144
+ <option name="JAVA_SCRIPT" value="true" />
145
+ <option name="TypeScript" value="true" />
146
+ </context>
147
+ </template>
148
+ <template name="tool-ts-try-await" value="await evo.awaitTryCatch.send($PROMISE$, $FROM$)" description="tryCatch для promise" toReformat="false" toShortenFQNames="true">
149
+ <variable name="PROMISE" expression="" defaultValue="" alwaysStopAt="true" />
150
+ <variable name="FROM" expression="" defaultValue="" alwaysStopAt="true" />
151
+ <context>
152
+ <option name="JAVA_SCRIPT" value="true" />
153
+ <option name="TypeScript" value="true" />
154
+ </context>
155
+ </template>
156
+ <template name="tool-ts-debugger" value="debugger;" description="debugger" toReformat="true" toShortenFQNames="true">
157
+ <context>
158
+ <option name="JAVA_SCRIPT" value="true" />
159
+ <option name="TypeScript" value="true" />
160
+ </context>
161
+ </template>
162
+ <template name="tool-ts-proxy-log" value="public createProxyLog(target, onChange) {&#10; // Обработка null и примитивов&#10; if (target === null || typeof target !== 'object') {&#10; return target;&#10; }&#10; &#10; return new Proxy(target, {&#10; set(obj, prop, value) {&#10; const oldValue = obj[prop];&#10; &#10; // Рекурсивно обрабатываем новые объекты&#10; const newValue = this.createProxyLog(value, onChange);&#10; &#10; obj[prop] = newValue;&#10; &#10; // Проверяем реальное изменение (учитываем NaN)&#10; if (oldValue !== value &amp;&amp; !(Number.isNaN(oldValue) &amp;&amp; Number.isNaN(value))) {&#10; onChange(prop, newValue, oldValue);&#10; }&#10; &#10; return true;&#10; },&#10; &#10; get(obj, prop) {&#10; const value = obj[prop];&#10; &#10; // Рекурсивно создаем прокси для вложенных объектов&#10; if (value !== null &amp;&amp; typeof value === 'object') {&#10; return this.createProxyLog(value, onChange);&#10; }&#10; &#10; return value;&#10; },&#10; &#10; deleteProperty(obj, prop) {&#10; const oldValue = obj[prop];&#10; const deleted = delete obj[prop];&#10; &#10; if (deleted) { onChange(prop, undefined, oldValue); }&#10; &#10; return deleted;&#10; }&#10; });&#10;}&#10;&#10;&#10;// Использование:&#10;//let state = this.createProxyLog(&#10;//{ user: { name: 'Alice', age: 30 } settings: { theme: 'dark', notifications: true } }, &#10;//(prop, value, oldValue) =&gt; { console.log(`Property &quot;${prop}&quot; changed: ${oldValue} → ${value}`); });&#10;//&#10;// delete state.user.email; // Property &quot;email&quot; changed: alice@example.com → undefined" description="Функция создания Proxy Логирование" toReformat="false" toShortenFQNames="true">
163
+ <context>
164
+ <option name="JAVA_SCRIPT" value="true" />
165
+ <option name="TypeScript" value="true" />
166
+ </context>
167
+ </template>
168
+ <template name="tool-global-forEach" value="$ARR$.forEach((item, i, arr) =&gt; {&#10; console.log( arr, i, item);&#10;});$END$" description="forEach - метод массива" toReformat="true" toShortenFQNames="true">
169
+ <variable name="ARR" expression="" defaultValue="" alwaysStopAt="true" />
170
+ <context>
171
+ <option name="JAVA_SCRIPT" value="true" />
172
+ <option name="TypeScript" value="true" />
173
+ </context>
174
+ </template>
175
+ <template name="tool-global-switch" value="switch ($EXPRESSION$) {&#10; case $CASE1$: $BODY1$; break;&#10; case $CASE2$: $BODY2$; break;&#10; default:&#10; $DEFAULT_BODY$;&#10;}&#10;" description="create SWITCH block" toReformat="false" toShortenFQNames="true">
176
+ <variable name="EXPRESSION" expression="" defaultValue="" alwaysStopAt="true" />
177
+ <variable name="CASE1" expression="" defaultValue="" alwaysStopAt="true" />
178
+ <variable name="BODY1" expression="" defaultValue="" alwaysStopAt="true" />
179
+ <variable name="CASE2" expression="" defaultValue="" alwaysStopAt="true" />
180
+ <variable name="BODY2" expression="" defaultValue="" alwaysStopAt="true" />
181
+ <variable name="DEFAULT_BODY" expression="" defaultValue="" alwaysStopAt="true" />
182
+ <context>
183
+ <option name="JAVA_SCRIPT" value="true" />
184
+ <option name="TypeScript" value="true" />
185
+ </context>
186
+ </template>
187
+ <template name="tool-global-switch-never" value="// Если union‑тип (type Direction = 'up' | 'down';) изменится, TypeScript выдаст ошибку компиляции, если switch не обновлён.&#10;&#10;switch ($EXPRESSION$) {&#10; case $CASE1$:&#10; $BODY1$;&#10; break;&#10; case $CASE2$:&#10; $BODY2$;&#10; break;&#10; default:&#10; const _exhaustiveCheck: never = $EXPRESSION$;&#10; throw new Error(`Необработанное значение: ${$EXPRESSION$}`);&#10;}&#10;" description="create SWITCH block with NEVER" toReformat="false" toShortenFQNames="true">
188
+ <variable name="EXPRESSION" expression="" defaultValue="" alwaysStopAt="true" />
189
+ <variable name="CASE1" expression="" defaultValue="" alwaysStopAt="true" />
190
+ <variable name="BODY1" expression="" defaultValue="" alwaysStopAt="true" />
191
+ <variable name="CASE2" expression="" defaultValue="" alwaysStopAt="true" />
192
+ <variable name="BODY2" expression="" defaultValue="" alwaysStopAt="true" />
193
+ <context>
194
+ <option name="JAVA_SCRIPT" value="true" />
195
+ <option name="TypeScript" value="true" />
196
+ </context>
197
+ </template>
198
+ <template name="tool-global-window" value="declare global {&#10; interface Window { $NAME$: any; }&#10; &#10; const $NAME$: any; // Добавляем глобальную переменную&#10;}&#10;&#10;(window as any).$NAME$ = $END$;&#10;&#10;export {};" description="Declare global window object and assign value" toReformat="false" toShortenFQNames="true">
199
+ <variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
200
+ <context>
201
+ <option name="JAVA_SCRIPT" value="true" />
202
+ <option name="TypeScript" value="true" />
203
+ </context>
204
+ </template>
205
+ <template name="tool-global-errors" value="window.addEventListener('error', (event) =&gt; { console.warn('Global error:', event.error); }); // для обычных ошибок&#10;&#10;window.addEventListener('unhandledrejection', (event) =&gt; {&#10; console.warn('Unhandled promise rejection:', event.reason); // для ошибок (например, async / Promise)&#10;});" description="Debug: global error &amp; promise rejection listeners" toReformat="false" toShortenFQNames="true">
206
+ <context>
207
+ <option name="JAVA_SCRIPT" value="true" />
208
+ <option name="TypeScript" value="true" />
209
+ </context>
210
+ </template>
211
211
  </templateSet>