Skip to content
Myr

line-hash.ts

This file

Path

apps/web/src/features/code/line-hash.ts

77 lines · 1.9 KiB · TypeScript

Last changed by

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

History of this file

Take it

Give the web its W9 dependencies, components, project nav, line and revision helpers, and a stub for every new pageoscabrielbefore adoption254268a

lines 1–27why, one step back
1import { Option } from "effect";
23export interface LineRange {4 readonly end: number;5 readonly start: number;6}78const ANCHOR = /^#?L(?<first>[1-9]\d*)(?:-L(?<second>[1-9]\d*))?$/u;910export const parseLineHash = (hash: string): Option.Option<LineRange> => {11 const groups = ANCHOR.exec(hash)?.groups;1213 if (groups?.first === undefined) {14 return Option.none();15 }1617 const first = Number(groups.first);18 const second = groups.second === undefined ? first : Number(groups.second);1920 return Option.some({21 end: Math.max(first, second),22 start: Math.min(first, second),23 });24};2526export const lineHash = ({ end, start }: LineRange): string =>27 start === end ? `#L${start}` : `#L${start}-L${end}`;

Merge build/1211-code-browseroscabrielbefore adoptiona6808d3

lines 28–77why, one step back
28
29export interface DiffLines extends LineRange {30 readonly path: string;31 readonly side: "additions" | "deletions";32}3334const DIFF_ANCHOR =35 /^#?diff-(?<path>[^:]+)(?::(?<lines>[DL]\d+(?:-[DL]\d+)?))?$/u;3637const decodePath = Option.liftThrowable(decodeURIComponent);3839export const parseDiffHash = (40 hash: string41): Option.Option<{42 readonly path: string;43 readonly lines: Option.Option<DiffLines>;44}> => {45 const groups = DIFF_ANCHOR.exec(hash)?.groups;4647 return Option.flatMap(Option.fromUndefinedOr(groups?.path), (encoded) =>48 Option.map(decodePath(encoded), (path) => ({49 lines: Option.map(50 Option.flatMap(Option.fromUndefinedOr(groups?.lines), (lines) =>51 parseLineHash(lines.replaceAll("D", "L"))52 ),53 (range): DiffLines => ({54 ...range,55 path,56 side:57 groups?.lines?.startsWith("D") === true ? "deletions" : "additions",58 })59 ),60 path,61 }))62 );63};6465export const diffLinesHash = ({66 end,67 path,68 side,69 start,70}: DiffLines): string => {71 const mark = side === "deletions" ? "D" : "L";7273 const lines =74 start === end ? `${mark}${start}` : `${mark}${start}-${mark}${end}`;7576 return `diff-${encodeURIComponent(path)}:${lines}`;77};