Skip to content

Commit 60a7bd8

Browse files
author
昊天
committed
源码阅读
1 parent 185bb91 commit 60a7bd8

10 files changed

+77
-30
lines changed

src/helpers/extensionConfig.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ export type ExtensionSettings = {
77
typescript: boolean;
88
typescriptPropsStatePrefix: 'type' | 'interface';
99
};
10-
10+
// 获取项目空间的配置信息
1111
const extensionConfig = () =>
1212
workspace.getConfiguration(
1313
'reactSnippets.settings',

src/helpers/formatters.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@ import {
66
replaceSnippetPlaceholders,
77
revertSnippetPlaceholders,
88
} from './snippetPlaceholders';
9-
10-
export const formatSnippet = (snippetString: string) => {
9+
// 从配置工作空间中拿到配置信息对代码片段进行格式化
10+
export const formatSnippet = (snippetString: string/**传入的代码片段信息 */) => {
1111
return extensionConfig().prettierEnabled
1212
? prettier.format(snippetString, getPrettierConfig())
1313
: snippetString;
1414
};
15-
15+
// 介些代码片段
1616
export const parseSnippet = (body: string | string[]) => {
17+
// 数组转化成字符串,以\n进行换行
1718
const snippetBody = typeof body === 'string' ? body : body.join('\n');
1819

1920
return replaceSnippetPlaceholders(

src/helpers/generateSnippets.ts

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { writeFile } from 'fs';
2-
2+
// 代码片段资源
33
import componentsSnippets, {
44
ComponentsSnippet,
55
} from '../sourceSnippets/components';
@@ -19,10 +19,16 @@ import typescriptSnippets, {
1919
TypescriptSnippet,
2020
} from '../sourceSnippets/typescript';
2121

22+
23+
24+
// 工作空间配置
2225
import extensionConfig from './extensionConfig';
26+
// 代码片段解析到body
2327
import parseSnippetToBody from './parseSnippetToBody';
28+
// 替换代码片段中的Placeholders 键(代码层面的变量)转化成值(vscode可识别的语法)
29+
// @link https://code.visualstudio.com/docs/editor/userdefinedsnippets#_placeholders
2430
import { replaceSnippetPlaceholders } from './snippetPlaceholders';
25-
31+
// 代码片段key
2632
export type SnippetKeys =
2733
| OthersSnippet['key']
2834
| HooksSnippet['key']
@@ -34,7 +40,7 @@ export type SnippetKeys =
3440
| ConsoleSnippet['key']
3541
| PropTypesSnippet['key']
3642
| TestsSnippet['key'];
37-
43+
// 代码片段
3844
export type Snippet =
3945
| OthersSnippet
4046
| HooksSnippet
@@ -47,12 +53,14 @@ export type Snippet =
4753
| PropTypesSnippet
4854
| TestsSnippet;
4955

56+
//代码片段对象<SnippetKey, Snippet>
5057
export type Snippets = {
5158
[key in SnippetKeys]: Snippet;
5259
};
5360

5461
const getSnippets = () => {
55-
const { typescript, languageScopes } = extensionConfig();
62+
// 配置信息
63+
const { typescript, languageScopes/**语言环境 */ } = extensionConfig();
5664

5765
const snippets = [
5866
...(typescript ? typescriptSnippets : []),
@@ -72,16 +80,17 @@ const getSnippets = () => {
7280
});
7381
return acc;
7482
}, {} as Snippets);
75-
76-
return replaceSnippetPlaceholders(JSON.stringify(snippets, null, 2));
83+
// 转换成vscode识别的语法
84+
return replaceSnippetPlaceholders(JSON.stringify(snippets, null, 2)/**JSON.stringify进行格式化 */);
7785
};
7886

7987
const generateSnippets = () =>
8088
new Promise((resolve) => {
89+
// 代码片段json数据格式
8190
const jsonSnippets = getSnippets();
8291
writeFile(
83-
__dirname + '/../snippets/generated.json',
84-
jsonSnippets,
92+
__dirname + '/../snippets/generated.json', // 输出路径
93+
jsonSnippets, // 数据源
8594
(error) => {
8695
if (error) {
8796
console.error(error);

src/helpers/getPrettierConfig.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,14 @@ prettier
77
.resolveConfig('', { editorconfig: true })
88
.then((config) => (prettierConfig = config));
99

10+
11+
// 获取prettier的配置信息
1012
const getPrettierConfig = (): Options => {
13+
// 从vscode工作空间拿到配置信息
1114
const { prettierEnabled } = extensionConfig();
1215

1316
return {
14-
parser: 'typescript',
17+
parser: 'typescript', // ts语言的方式进行解析
1518
...(prettierEnabled && prettierConfig),
1619
};
1720
};

src/helpers/parseSnippetToBody.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ import extensionConfig from './extensionConfig';
22
import { formatSnippet } from './formatters';
33
import { Snippet } from './generateSnippets';
44
import replaceOrRemoveReactImport from './replaceOrRemoveReactImport';
5-
5+
// 将代码片段放到body中
66
const parseSnippetToBody = (snippet: Snippet) => {
7+
// 配置信息,是否在顶部引入react
8+
// @link https://github.com/841660202/vscode-react-javascript-snippets/blob/master/README.md#:~:text=project%20prettier%20config-,importReactOnTop,-If%20disabled%2C%20snippets
79
const { importReactOnTop } = extensionConfig();
810
const body =
911
typeof snippet.body === 'string' ? snippet.body : snippet.body.join('\n');

src/helpers/replaceOrRemoveReactImport.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Snippet } from './generateSnippets';
2-
2+
// 有引入react得前缀枚举
33
const snippetWithReactImportPrefixes = [
44
'rfce',
55
'rfc',
@@ -45,7 +45,7 @@ const replaceOrRemoveReactImport = ({
4545
const reactImportIndex = bodyCopy.findIndex((line) =>
4646
line.match(new RegExp(/import React/, 'g')),
4747
);
48-
48+
// 找到react 引入的代码所在行
4949
if (reactImportIndex !== -1) {
5050
const line = bodyCopy[reactImportIndex];
5151
const newLine = line

src/helpers/snippetPlaceholders.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
11
import { Mappings, Placeholders } from '../types';
22

33
import extensionConfig from './extensionConfig';
4-
4+
// Mappings 键转化成值
55
export const replaceSnippetPlaceholders = (snippetString: string) => {
66
const { typescriptPropsStatePrefix } = extensionConfig();
7+
// propsPlaceholder 使用type字段?
78
const propsPlaceholder =
89
typescriptPropsStatePrefix === 'type'
9-
? Mappings.TypeProps
10-
: Mappings.InterfaceProps;
10+
? Mappings.TypeProps // type Props = {}
11+
: Mappings.InterfaceProps; // interface Props {}
12+
// statePlaceholder 使用type字段?
1113
const statePlaceholder =
1214
typescriptPropsStatePrefix === 'type'
13-
? Mappings.TypeState
14-
: Mappings.InterfaceState;
15+
? Mappings.TypeState // type State = {}
16+
: Mappings.InterfaceState; // interface State {}
1517

1618
return String(snippetString)
17-
.replace(new RegExp(Placeholders.FileName, 'g'), '${1:${TM_FILENAME_BASE}}')
19+
.replace(new RegExp(Placeholders.FileName, 'g'), '${1:${TM_FILENAME_BASE}}') // 替换成vscode宏
1820
.replace(new RegExp(Placeholders.FirstTab, 'g'), '${1:first}')
1921
.replace(new RegExp(Placeholders.SecondTab, 'g'), '${2:second}')
2022
.replace(new RegExp(Placeholders.ThirdTab, 'g'), '${3:third}')
@@ -25,11 +27,11 @@ export const replaceSnippetPlaceholders = (snippetString: string) => {
2527
.replace(new RegExp(Placeholders.TypeProps, 'g'), propsPlaceholder)
2628
.replace(new RegExp(Placeholders.TypeState, 'g'), statePlaceholder);
2729
};
28-
30+
// Mappings 值转化成键
2931
export const revertSnippetPlaceholders = (snippetString: string) => {
3032
return String(snippetString)
3133
.replace(
32-
new RegExp(/\${1:\${TM_FILENAME_BASE}}/, 'g'),
34+
new RegExp(/\${1:\${TM_FILENAME_BASE}}/, 'g'), // Mappings(src/types.ts) 的值,替换成key
3335
Placeholders.FileName,
3436
)
3537
.replace(new RegExp(/\${1:first}/, 'g'), Placeholders.FirstTab)

src/helpers/snippetSearch.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,34 +6,39 @@ import { Snippet } from './generateSnippets';
66

77
const snippetSearch = async () => {
88
const { showQuickPick, activeTextEditor } = window;
9-
9+
// 读取所有代码片段
1010
const snippets = readFileSync(
1111
__dirname + '/../snippets/generated.json',
1212
'utf8',
1313
);
14-
14+
// 转化成数组
1515
const snippetsArray = Object.entries(JSON.parse(snippets)) as [
1616
string,
1717
Snippet,
1818
][];
19-
19+
// 代码片段数据转化成固定格式
2020
const items = snippetsArray.map(
2121
([shortDescription, { body, description, prefix: label }]) => ({
2222
body,
2323
description: description || shortDescription,
2424
label,
2525
}),
2626
);
27-
27+
// vscode提供筛选能力
28+
// @link https://code.visualstudio.com/api/references/vscode-api#QuickPick%3CT%3E
2829
const rawSnippet = await showQuickPick(items, {
2930
matchOnDescription: true,
3031
matchOnDetail: true,
3132
placeHolder: 'Search snippet by prefix or description',
3233
});
33-
34+
// 选中后,将选中的代码片段取body
3435
const body = rawSnippet ? parseSnippet(rawSnippet.body) : '';
3536

3637
if (activeTextEditor) {
38+
// 插入到光标所在位置
39+
// @link https://code.visualstudio.com/Search?q=SnippetString
40+
// @link https://code.visualstudio.com/updates/v1_9?source=techstories.org#_editor-api-to-insert-a-snippet
41+
// 看这个 @link https://code.visualstudio.com/api/references/vscode-api#SnippetString
3742
activeTextEditor.insertSnippet(new SnippetString(body));
3843
}
3944
};

src/index.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,18 @@ const showRestartMessage = async ({
3232
};
3333

3434
export async function activate(context: ExtensionContext) {
35+
// 工作空间配置更改监听
3536
workspace.onDidChangeConfiguration(showRestartMessage);
37+
3638
if (JSON.stringify(generatedSnippets).length < 10) {
3739
await generateSnippets();
3840
}
41+
// 注册查询命令
3942
const snippetSearchCommand = commands.registerCommand(
4043
'reactSnippets.search',
4144
snippetSearch,
4245
);
43-
46+
// 开启订阅,监听命令变化
4447
context.subscriptions.push(snippetSearchCommand);
4548
}
4649

test/tsrcredux.tsx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { connect } from 'react-redux'
2+
import React, { Component } from 'react'
3+
4+
type Props = {}
5+
6+
type State = {}
7+
8+
export class tsrcredux extends Component<Props, State> {
9+
state = {}
10+
11+
render() {
12+
return (
13+
<div>tsrcredux</div>
14+
)
15+
}
16+
}
17+
18+
const mapStateToProps = (state) => ({})
19+
20+
const mapDispatchToProps = {}
21+
22+
export default connect(mapStateToProps, mapDispatchToProps)(tsrcredux)

0 commit comments

Comments
 (0)