实用工具
Code Hike 提供了一套实用工具,帮助您实现常见模式并使从以前版本迁移变得更容易。
选择
Code Hike 的一个常见用例是根据用户与内容的交互来切换 UI 的一部分。一些例子包括滚动编码布局或聚光灯布局。
my-layout.tsx
import {SelectionProvider,Selectable,Selection,} from "codehike/utils/selection"function MyLayout({steps,}: {steps: {left: React.ReactNoderight: React.ReactNode}[]}) {return (<SelectionProvider className="flex gap-4"><div>{steps.map((step, index) => (<Selectablekey={index}index={index}selectOn={["click", "hover", "scroll"]}className="border border-zinc-700 data-[selected=true]:border-blue-400">{step.left}</Selectable>))}</div><Selectionfrom={steps.map((step) => (<div>{step.right}</div>))}/></SelectionProvider>)}
为了更好地控制选择,您可以使用 useSelectedIndex 钩子。
my-layout.tsx
import { useSelectedIndex } from "codehike/utils/selection"function MyLayout(...) {const [ selectedIndex, setSelectedIndex ] = useSelectedIndex()...}
标记过渡
当您想要为两个代码片段之间的变化添加动画效果时。
import {getStartingSnapshot,calculateTransitions,} from "codehike/utils/token-transitions"const preElement = document.querySelector("pre")// 在更改之前拍摄 pre 元素的快照const startingSnapshot = getStartingSnapshot(preElement)// 然后在代码更改后,计算过渡const transitions = calculateTransitions(preElement, startingSnapshot)// 这样您就可以为更改添加动画const MAX_TRANSITION_DURATION = 900 // millisecondstransitions.forEach(({ element, keyframes, options }) => {const { translateX, translateY, ...kf } = keyframesif (translateX && translateY) {kf.translate = [`${translateX[0]}px ${translateY[0]}px`,`${translateX[1]}px ${translateY[1]}px`,]}element.animate(kf, {duration: options.duration * MAX_TRANSITION_DURATION,delay: options.delay * MAX_TRANSITION_DURATION,easing: options.easing,fill: "both",})})
请参阅标记过渡示例了解使用此实用工具的 React 组件。