✨ feat(vscode): 构造参数区,改它的和来自能单独打开源码

This commit is contained in:
cruldra committed 2026-10-04 15:34:44 +08:00
1 parent e322f01edb
commit e8ae19d084
13 files changed
+345 -70

No files matched your search

+6
View File
@@ -289,6 +289,12 @@ export function toBlockViews(
translate: node => layerTranslator ? layerTranslator.expression(node, layerDocument) : [{ text: node.text, role: 'plain' }],
doc: node => layerTranslator?.doc(node, layerDocument),
lookup: layerRules.lookup ?? (() => undefined),
snippet: (node) => {
const startRow = node.startPosition.row
const end = node.endPosition
const endRow = end.column === 0 && end.row > startRow ? end.row - 1 : end.row
return sourceRows({ startIndex: node.startIndex, endIndex: node.endIndex, startRow, endRow })
},
}
/** 一行译文,连着摊开实参的表、块的说明(有才有)。 */
const textView = (block: TextBlock): { translation: PreviewText, table?: PreviewTable, doc?: Markdown } => {
+31
View File
@@ -594,11 +594,40 @@ export type PreviewText = Inline[] | Markdown
*/
export interface Defines { defines?: SourceRange }
/**
* 能单独打开编辑的一段源码:这几行整行,去掉共同缩进,着色和块的 code / codeTokens 同一套切法。
* 网页不自己切。点铅笔之后只出现这一段,不换整张卡片。
*/
export interface SourceSnippet {
/** 起止行,0 起,含头含尾。 */
startLine: number
endLine: number
code: string
/** 着色,拼起来等于 code。 */
codeTokens: Segment[]
}
/**
* 属性表一个子行的某一格里,能单独打开的一段源码。
* cell 是第几格(0 起),from / to 是这一格文字里这一处的范围(含头不含尾)。
*/
export interface CellEdit {
cell: number
from: number
to: number
snippet: SourceSnippet
}
/** 属性表里展开的一个子行:几列对齐的格子,例如参数的名称 / 类型 / 默认值、字典一项的键 / 值。 */
export interface PropertyItem extends Defines {
cells: Inline[][]
/** 展开在这个子行下面的下一层子行(字典 / 对象的值又是字典 / 对象时,它的各项);一层层可以一直往下套。 */
items?: PropertyItem[]
/**
* 这一行里能单独打开的几段源码(状态「改它的」的每一处、读取的数据的「来自」)。
* 打开后只出现那一段。没有能打开的就不写。
*/
edits?: CellEdit[]
/**
* 排在这一行最后一格里、那格文字下面的表:实参表里一个实参的值里有跨几行写的调用时,是那个调用的实参表,
* 表里的行又可以带 table,一层层往下套。总是展开的。
@@ -916,6 +945,8 @@ export interface RuleContext {
displayLanguage?: string
/** 用当前翻译插件把一个表达式或类型节点翻成一行译文(Translator.expression):名字带源码下标,能跳到定义、高亮各处出现;没有翻译插件时照抄源码。 */
translate: (node: Node) => Inline[]
/** 一个节点占的整行源码和着色(见 SourceSnippet),和块视图切行是同一套。规则把它挂在译文旁边。 */
snippet: (node: Node) => SourceSnippet
/** 用当前翻译插件取一段说明文字(Translator.doc);没有翻译插件、没有文字时没有。 */
doc: (node: Node) => Markdown | undefined
/**
+44 -18
View File
@@ -64,7 +64,7 @@ describe('react 库规则:认领', () => {
expect(propertyLines(properties(view)).slice(0, 4)).toEqual([
'名称: DesktopTitlebar ⟦具名导出|⟧ ⟦客户端组件|⟧',
'说明: 窗口顶部 40px. 整条连同里面的文字都是拖拽区 (data-tauri-drag-region="deep"), 按钮除外. 侧栏开关只在侧栏顶部.',
'属性: 1 个',
'构造参数: 1 个',
' platform | DesktopShell["platform"] | — | 是',
])
})
@@ -83,13 +83,13 @@ describe('react 库规则:认领', () => {
})
})
describe('react 库规则:属性', () => {
describe('react 库规则:构造参数', () => {
it('luffy 的 LegalDocPage:来自 LegalDocPageProps(名字能跳到定义),字段带说明时多一列说明', async () => {
const view = await card(LEGAL, 'LegalDocPage')
const row = properties(view).find(item => item.label === '属性')
const row = properties(view).find(item => item.label === '构造参数')
expect(row?.columns).toEqual(['名称', '类型', '默认值', '必填', '说明'])
expect(rowLines(view, '属性')).toEqual([
'属性: 1 个 · 来自 LegalDocPageProps',
expect(rowLines(view, '构造参数')).toEqual([
'构造参数: 1 个 · 来自 LegalDocPageProps',
' doc | "terms" | "privacy" | — | 是 | terms = 用户服务协议; privacy = 隐私政策',
])
const from = row && !('markdown' in row.value) ? row.value.at(-1) : undefined
@@ -98,16 +98,16 @@ describe('react 库规则:属性', () => {
})
it('luffy 的 ShareButton:回调标「回调」、类型写成函数签名;StepLabel 的 children 标「子元素」', async () => {
expect(rowLines(await card(SHARE, 'ShareButton'), '属性')).toEqual([
'属性: 5 个',
expect(rowLines(await card(SHARE, 'ShareButton'), '构造参数')).toEqual([
'构造参数: 5 个',
' open | 布尔 | — | 是 | ',
' onOpenChange ⟦回调|⟧ | (next: 布尔) => 无 | — | 是 | ',
' deployUrl | 字符串 | 空 | — | 是 | 已发布的持久 URL; null = 尚未发布 (点击后由父组件驱动发布)。',
' sessionId | 字符串 | — | 是 | ',
' title | 字符串 | — | 是 | ',
])
expect(rowLines(await card(POSTER, 'StepLabel'), '属性')).toEqual([
'属性: 2 个',
expect(rowLines(await card(POSTER, 'StepLabel'), '构造参数')).toEqual([
'构造参数: 2 个',
' n | 数值 | — | 是',
' children ⟦子元素|⟧ | ReactNode | — | 是',
])
@@ -118,8 +118,8 @@ describe('react 库规则:属性', () => {
'interface Props { size?: number; onPick(v: string): void; label: string }',
'export const A = ({ size = 16, label: text, ...rest }: Props) => <i />;',
].join('\n')
expect(rowLines(await card(source, 'A'), '属性')).toEqual([
'属性: 4 个 · 来自 Props',
expect(rowLines(await card(source, 'A'), '构造参数')).toEqual([
'构造参数: 4 个 · 来自 Props',
' size | 数值 | 16 | 否',
' onPick ⟦回调|⟧ | (v: 字符串) => 无 | — | 是',
' label(组件里叫 text) | 字符串 | — | 是',
@@ -133,8 +133,8 @@ describe('react 库规则:属性', () => {
'export const Card = ({ title, onClose = noop }: CardProps) => <div />;',
'export function Empty() { return <i /> }',
].join('\n')
expect(rowLines(await card(source, 'Card'), '属性')).toEqual([
'属性: 2 个 · 来自 CardProps',
expect(rowLines(await card(source, 'Card'), '构造参数')).toEqual([
'构造参数: 2 个 · 来自 CardProps',
' title | 未标注 | — | —',
' onClose | 未标注 | noop | 否',
])
@@ -143,13 +143,13 @@ describe('react 库规则:属性', () => {
{ name: 'onClose', type: '() => void', optional: true, callback: true },
{ name: 'size', type: 'number', optional: true, callback: false },
])
expect(rowLines(await card(source, 'Card', known({ CardProps: fields })), '属性')).toEqual([
'属性: 3 个 · 来自 CardProps',
expect(rowLines(await card(source, 'Card', known({ CardProps: fields })), '构造参数')).toEqual([
'构造参数: 3 个 · 来自 CardProps',
' title | string | — | 是 | 标题',
' onClose ⟦回调|⟧ | () => void | noop | 否 | ',
' size | number | — | 否 | ',
])
expect(rowLines(await card(source, 'Empty'), '属性')).toEqual(['属性: 无'])
expect(rowLines(await card(source, 'Empty'), '构造参数')).toEqual(['构造参数: 无'])
})
})
@@ -257,11 +257,37 @@ describe('react 库规则:分区', () => {
})
})
describe('单独打开一段源码', () => {
it('读取的数据挂的是这次调用,改它的里 JSX 那一处是整个属性', async () => {
const source = [
'export function Panel() {',
' const pathname =',
' usePathname()',
' const [open, setOpen] = useState(false)',
' return (',
' <Dialog',
' onOpenChange={',
' setOpen',
' }',
' />',
' )',
'}',
].join('\n')
const view = await card(source, 'Panel')
const read = properties(view).find(row => row.label === '读取的数据')?.items?.[0]
expect(read?.edits?.map(edit => edit.snippet.code)).toEqual(['usePathname()'])
const state = properties(view).find(row => row.label === '状态')?.items?.[0]
expect(state?.edits?.map(edit => edit.snippet.code)).toEqual(['onOpenChange={\n setOpen\n}'])
expect(view.code).toContain('function Panel')
expect(read?.edits?.[0].snippet.code).not.toContain('function Panel')
})
})
describe('react 库规则:渲染大纲', () => {
it('luffy 的 DesktopTitlebar:整张卡片讲完了组件,没有留下的子块;渲染大纲每行一个元素,原生标签、组件、样式小标、属性、插值', async () => {
const view = await card(TITLEBAR, 'DesktopTitlebar')
expect(view.children).toEqual([])
expect(properties(view).map(row => row.label)).toEqual(['名称', '说明', '属性', '读取的数据', '派生值', '渲染'])
expect(properties(view).map(row => row.label)).toEqual(['名称', '说明', '构造参数', '读取的数据', '派生值', '渲染'])
expect(rowLines(view, '渲染')).toEqual([
'渲染: 1 处返回',
' div ⟦样式 8 个类|⟧ data-tauri-drag-region="deep"',
@@ -388,7 +414,7 @@ describe('react 库规则:代码差异', () => {
const componentChange = diff.blocks[component.anchor]
expect(componentChange).toMatchObject({ change: 'mod', own: true })
const propsIndex = properties(component).findIndex(row => row.label === '属性')
const propsIndex = properties(component).findIndex(row => row.label === '构造参数')
expect(Object.keys(componentChange.marks?.rows?.changed ?? {})).toEqual([String(propsIndex)])
expect(componentChange.marks?.rows?.changed[propsIndex].items?.changed[1]).toEqual({ added: true })
expect(componentChange.marks?.rows?.removed).toEqual([])
+56 -14
View File
@@ -1,11 +1,11 @@
import type { CodeBlock, Inline, KindBadge, LibraryRule, Node, PropertyItem, PropertyRow, RuleCard, RuleContext, RuleSlot, SegmentGroup, ThemeColor, TokenRole, WorkspaceIndex } from '../contract'
import type { CellEdit, CodeBlock, Inline, KindBadge, LibraryRule, Node, PropertyItem, PropertyRow, RuleCard, RuleContext, RuleSlot, SegmentGroup, ThemeColor, TokenRole, WorkspaceIndex } from '../contract'
import type { BindingFacts, BodyFacts, ClassFacts, ComponentFacts, DerivedFacts, EffectFacts, FieldFacts, FieldText, HandlerFacts, OutlineNode, Place, PropsFacts, ReadFacts } from './reactTree'
import { argumentsOf, attributeName, attributeValue, bodyOf, clientDirective, commentsBefore, commentText, componentAt, componentOf, componentsIn, declaredTypes, enclosingComponent, isComponentTag, isFunction, named, outlineOf, parametersOf, placesOf, propsOf, sameNode, statementsOf, stringContent, unwrap } from './reactTree'
import { hint, joined, name, plain, range } from './segments'
/**
* React 库规则:TSX / JSX 里的 React 函数组件(见 reactTree.ts 的 componentAt)整块换成「React 组件」卡片,不再是普通函数卡片的输入参数 / 输出参数。
* 卡片:名称(后面跟导出方式、客户端组件、记忆化、转发 ref 这些小标签)/ 说明 / 属性(解构的每个属性一行,类型取属性类型里对应的字段;
* 卡片:名称(后面跟导出方式、客户端组件、记忆化、转发 ref 这些小标签)/ 说明 / 构造参数(解构的每个属性一行,类型取属性类型里对应的字段;
* 属性类型是接口、类型别名时写来自哪个类型,导入的类型经工作区索引查它的字段),再按钩子分区,没有就不画:
* 状态(useState / useReducer:名称 / 初始值 / 改它的,渲染时按条件重置状态的 if 也写进改它的)、引用(useRef)、
* 读取的数据(别的钩子:变量 / 来自 / 意思)、派生值(组件体里别的常量、useMemo / useCallback:名称 / 怎么算 / 什么时候算)、
@@ -123,7 +123,7 @@ const ZH: Words = {
labels: {
name: '名称',
doc: '说明',
props: '属性',
props: '构造参数',
state: '状态',
refs: '引用',
reads: '读取的数据',
@@ -254,7 +254,7 @@ function docRows(component: ComponentFacts, { context, words }: Env): PropertyRo
return doc ? [{ label: words.labels.doc, value: doc }] : []
}
// ─── 属性 ─────────────────────────────────────────────────────────────────────
// ─── 构造参数 ─────────────────────────────────────────────────────────────────
/** 工作区里各文件顶层声明的接口、类型别名:名字 → 各字段的文字(JSON,见 FieldText),组件的属性类型是导入的时候查它。 */
const PROP_TYPES_INDEX: WorkspaceIndex = {
@@ -357,7 +357,7 @@ function propDoc(entry: PropEntry): Inline[] {
return text ? [{ text: text.replace(/\s*\n\s*/g, ' '), role: 'comment' }] : []
}
/** 属性:解构的每个属性一行(名称 / 类型 / 默认值 / 必填,有属性带说明时多一列说明);属性类型是一个名字时「属性」后面写来自哪里。 */
/** 构造参数:解构的每个属性一行(名称 / 类型 / 默认值 / 必填,有属性带说明时多一列说明);属性类型是一个名字时「构造参数」后面写来自哪里。 */
function propsRow(component: ComponentFacts, env: Env): PropertyRow {
const { context, words } = env
const props = propsOf(component)
@@ -487,16 +487,54 @@ function commentLine(comments: readonly Node[]): string | undefined {
// ─── 状态、引用、读取的数据、派生值 ──────────────────────────────────────────
/** 状态:名称 / 初始值 / 改它的(改状态的函数,括号里写在哪儿改:副作用、处理函数、渲染时按条件重置……)。 */
/** 这一处改状态的源码:JSX 取包着值的整个属性,处理函数取函数,派生值取那个值,另一处读取取那次调用,重置取条件。纯渲染没有节点。 */
function placeNode(place: Place, body: BodyFacts): Node | undefined {
switch (place.kind) {
case 'jsx':
return place.attribute.parent?.type === 'jsx_attribute' ? place.attribute.parent : undefined
case 'handler':
return body.handlers.find(handler => sameNode(handler.name, place.name))?.fn
case 'derived':
return body.derived.find(item => sameNode(item.name, place.name))?.value
case 'read':
return body.reads.find(read => sameNode(read.target, place.target))?.call
case 'reset':
return place.condition
case 'effect':
return body.effects[place.index]?.statement
default:
return undefined
}
}
/** 「改它的」这一格:函数名,括号里每一处各挂自己的源码。 */
function changesOf(analysis: Analysis, setter: Node, env: Env): { cell: Inline[], edits: CellEdit[] } {
const places = placesOf(setter, analysis.component, analysis.body)
const parts = places.map(place => placeText(place, analysis, env))
const cell = [name(setter, 'function'), ...inParens(parts, env)]
const edits: CellEdit[] = []
let at = 2
parts.forEach((part, index) => {
const node = placeNode(places[index], analysis.body)
if (node)
edits.push({ cell: 2, from: at, to: at + part.length, snippet: env.context.snippet(node) })
at += part.length + (index < parts.length - 1 ? 1 : 0)
})
return { cell, edits }
}
function stateRow(analysis: Analysis, env: Env): PropertyRow {
const { component, body } = analysis
const { body } = analysis
const { context, words } = env
const items = body.states.map((state): PropertyItem => {
const initial = state.initial ? context.translate(state.initial) : [hint(words.nothing)]
const reducer = state.reducer ? [hint(words.parens[0]), ...context.translate(state.reducer), hint(words.parens[1])] : []
const changes = state.setter
? [name(state.setter, 'function'), ...inParens(placesOf(state.setter, component, body).map(place => placeText(place, analysis, env)), env)]
: [hint(words.nothing)]
return { cells: [binding(state.value, 'variable', env), [...initial, ...reducer], changes], defines: range(state.value) }
const changes = state.setter ? changesOf(analysis, state.setter, env) : { cell: [hint(words.nothing)], edits: [] }
return {
cells: [binding(state.value, 'variable', env), [...initial, ...reducer], changes.cell],
...(changes.edits.length > 0 && { edits: changes.edits }),
defines: range(state.value),
}
})
return { label: words.labels.state, value: [hint(words.count(items.length))], items, columns: words.heads.state }
}
@@ -601,10 +639,14 @@ function readMeaning(read: ReadFacts, env: Env): Inline[] {
/** 读取的数据:变量 / 来自(钩子调用照常翻)/ 意思。 */
function readRow(analysis: Analysis, env: Env): PropertyRow {
const { context, words } = env
const items = analysis.body.reads.map((read): PropertyItem => ({
cells: [binding(read.target, 'variable', env), context.translate(read.call), readMeaning(read, env)],
defines: range(read.target),
}))
const items = analysis.body.reads.map((read): PropertyItem => {
const from = context.translate(read.call)
return {
cells: [binding(read.target, 'variable', env), from, readMeaning(read, env)],
edits: [{ cell: 1, from: 0, to: from.length, snippet: context.snippet(read.call) }],
defines: range(read.target),
}
})
return { label: words.labels.reads, value: [hint(words.count(items.length))], items, columns: words.heads.reads }
}
+1 -1
View File
@@ -1,7 +1,7 @@
import type { CodeBlock, Node } from '../contract'
/**
* 读 React 函数组件的语法树(React 库规则用,见 react.ts):认组件,读出它的属性、组件体里的各种钩子、处理函数和渲染的 JSX。
* 读 React 函数组件的语法树(React 库规则用,见 react.ts):认组件,读出它的构造参数、组件体里的各种钩子、处理函数和渲染的 JSX。
* 只读语法树、不翻译,读出来的节点都指向源码;怎么排成卡片、用什么词归 react.ts。
*/