差异

显示插入和删除的行。

content.md
```js
function lorem(ipsum, dolor = 1) {
const sit = ipsum == null ? 0 : ipsum.sit
// !diff -
dolor = ipsum - sit
// !diff +
dolor = sit - amet(dolor)
return sit ? consectetur(ipsum) : []
}
```
function lorem(ipsum, dolor = 1) {
const sit = ipsum == null ? 0 : ipsum.sit
-
dolor = ipsum - sit
+
dolor = sit - amet(dolor)
return sit ? consectetur(ipsum) : []
}

Implementation

有两个部分:

  • 对于 +- 图标,我们自定义 Line 并在前面添加 annotation.query
  • 对于边框和颜色,我们使用 transform 函数添加 mark 注释,并使用来自标记示例AnnotationHandler
diff.tsx
import { AnnotationHandler, InnerLine, BlockAnnotation } from "codehike/code"
export const diff: AnnotationHandler = {
name: "diff",
onlyIfAnnotated: true,
transform: (annotation: BlockAnnotation) => {
const color = annotation.query == "-" ? "#f85149" : "#3fb950"
return [annotation, { ...annotation, name: "mark", query: color }]
},
Line: ({ annotation, ...props }) => (
<>
<div className="">
{annotation?.query}
</div>
<InnerLine merge={props} />
</>
),
}

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

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