Diff

Show inserted and deleted lines.

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

There are two parts:

  • for the + and - icons, we customize the Line and prepend the annotation.query
  • for the border and color we use the transform function to add mark annotations and use the AnnotationHandler from the mark example
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} />
</>
),
}

Then pass the mark and diff handlers to the Pre component:

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]} />
}