标注

在代码块内添加标注。

content.md
```js
const lorem = ipsum(dolor, sit)
// !callout[/amet/] This is a callout
const [amet, consectetur] = [0, 0]
lorem.adipiscing((sed, elit) => {
if (sed) {
amet += elit
}
})
```
const lorem = ipsum(dolor, sit)
const [amet, consectetur] = [0, 0]
This is a callout
lorem.adipiscing((sed, elit) => {
if (sed) {
amet += elit
}
})

Implementation

code.tsx
1
import { InlineAnnotation, AnnotationHandler } from "codehike/code"
2
3
const callout: AnnotationHandler = {
4
name: "callout",
5
transform: (annotation: InlineAnnotation) => {

我们需要将注释从 InlineAnnotation 转换为 BlockAnnotation

6
const { name, query, lineNumber, fromColumn, toColumn, data } = annotation
7
return {
8
name,
9
query,
10
fromLineNumber: lineNumber,
11
toLineNumber: lineNumber,
12
data: { ...data, column: (fromColumn + toColumn) / 2 },

这将是标注中箭头的位置

13
}
14
},
15
Block: ({ annotation, children }) => {
16
const { column } = annotation.data
17
return (
18
<>
19
{children}
20
<div
21
style={{ minWidth: `${column + 4}ch` }}
22
className=""
23
>
24
<div
25
style={{ left: `${column}ch` }}
26
className=""
27
/>
28
{annotation.query}
29
</div>
30
</>
31
)
32
},
33
}

然后将 callout 处理器传递给 Pre 组件:

code.tsx
async function Code({ codeblock }: { codeblock: RawCode }) {
const highlighted = await highlight(codeblock, "github-dark")
return <Pre code={highlighted} handlers={[callout]} />
}

改进建议

改进标注注释的一些方法:

  • 添加不同样式的注释(如警告、错误、信息等)
  • 添加在行前或行后显示标注的选项
  • 在标注内放置 markdown(参见工具提示示例