@lukstei/util-review-ui 0.0.0-stage → 0.2.2-rc.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,184 @@
1
+ export interface DiffHunkLine {
2
+ type: " " | "-" | "+";
3
+ line: string;
4
+ }
5
+
6
+ export function createUnifiedDiff(
7
+ path: string,
8
+ before: string | null,
9
+ after: string | null,
10
+ ): string {
11
+ if (before === null && after === null) return "";
12
+ if (before === null) {
13
+ const lines = (after ?? "").split("\n");
14
+ return [
15
+ `--- /dev/null`,
16
+ `+++ b/${path}`,
17
+ `@@ -0,0 +1,${lines.length} @@`,
18
+ ...lines.map((l) => `+${l}`),
19
+ ].join("\n");
20
+ }
21
+ if (after === null) {
22
+ const lines = (before ?? "").split("\n");
23
+ return [
24
+ `--- a/${path}`,
25
+ `+++ /dev/null`,
26
+ `@@ -1,${lines.length} +0,0 @@`,
27
+ ...lines.map((l) => `-${l}`),
28
+ ].join("\n");
29
+ }
30
+
31
+ const a = before.split("\n");
32
+ const b = after.split("\n");
33
+
34
+ if (before === after) return "";
35
+
36
+ // Trim common prefix
37
+ let prefix = 0;
38
+ while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) {
39
+ prefix++;
40
+ }
41
+
42
+ // Trim common suffix
43
+ let aEnd = a.length - 1;
44
+ let bEnd = b.length - 1;
45
+ while (aEnd >= prefix && bEnd >= prefix && a[aEnd] === b[bEnd]) {
46
+ aEnd--;
47
+ bEnd--;
48
+ }
49
+
50
+ const aMid = a.slice(prefix, aEnd + 1);
51
+ const bMid = b.slice(prefix, bEnd + 1);
52
+
53
+ let ops: { type: " " | "-" | "+"; line: string }[];
54
+
55
+ if (aMid.length * bMid.length > 500000) {
56
+ // Large replacement fallback
57
+ ops = [
58
+ ...a.slice(0, prefix).map((l) => ({ type: " " as const, line: l })),
59
+ ...aMid.map((l) => ({ type: "-" as const, line: l })),
60
+ ...bMid.map((l) => ({ type: "+" as const, line: l })),
61
+ ...a.slice(aEnd + 1).map((l) => ({ type: " " as const, line: l })),
62
+ ];
63
+ } else {
64
+ const m = aMid.length;
65
+ const n = bMid.length;
66
+ const dp = Array.from({ length: m + 1 }, () => new Int32Array(n + 1));
67
+ for (let i = 0; i < m; i++) {
68
+ for (let j = 0; j < n; j++) {
69
+ dp[i + 1][j + 1] =
70
+ aMid[i] === bMid[j]
71
+ ? dp[i][j] + 1
72
+ : Math.max(dp[i + 1][j], dp[i][j + 1]);
73
+ }
74
+ }
75
+
76
+ let i = m;
77
+ let j = n;
78
+ const midOps: { type: " " | "-" | "+"; line: string }[] = [];
79
+ while (i > 0 || j > 0) {
80
+ if (i > 0 && j > 0 && aMid[i - 1] === bMid[j - 1]) {
81
+ midOps.push({ type: " ", line: aMid[i - 1] });
82
+ i--;
83
+ j--;
84
+ } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
85
+ midOps.push({ type: "+", line: bMid[j - 1] });
86
+ j--;
87
+ } else {
88
+ midOps.push({ type: "-", line: aMid[i - 1] });
89
+ i--;
90
+ }
91
+ }
92
+ midOps.reverse();
93
+
94
+ ops = [
95
+ ...a.slice(0, prefix).map((l) => ({ type: " " as const, line: l })),
96
+ ...midOps,
97
+ ...a.slice(aEnd + 1).map((l) => ({ type: " " as const, line: l })),
98
+ ];
99
+ }
100
+
101
+ const context = 3;
102
+ // Find hunks (regions containing changes with up to 3 lines of context)
103
+ const changeIndices: number[] = [];
104
+ for (let idx = 0; idx < ops.length; idx++) {
105
+ if (ops[idx].type !== " ") changeIndices.push(idx);
106
+ }
107
+
108
+ if (changeIndices.length === 0) return "";
109
+
110
+ interface HunkRange {
111
+ start: number;
112
+ end: number;
113
+ }
114
+
115
+ const ranges: HunkRange[] = [];
116
+ let currentRange: HunkRange = {
117
+ start: Math.max(0, changeIndices[0] - context),
118
+ end: Math.min(ops.length - 1, changeIndices[0] + context),
119
+ };
120
+
121
+ for (let k = 1; k < changeIndices.length; k++) {
122
+ const nextChange = changeIndices[k];
123
+ const nextStart = Math.max(0, nextChange - context);
124
+ const nextEnd = Math.min(ops.length - 1, nextChange + context);
125
+
126
+ if (nextStart <= currentRange.end + 1) {
127
+ currentRange.end = nextEnd;
128
+ } else {
129
+ ranges.push(currentRange);
130
+ currentRange = { start: nextStart, end: nextEnd };
131
+ }
132
+ }
133
+ ranges.push(currentRange);
134
+
135
+ const result: string[] = [`--- a/${path}`, `+++ b/${path}`];
136
+
137
+ let oldLineNum = 1;
138
+ let newLineNum = 1;
139
+ let opIdx = 0;
140
+
141
+ for (const range of ranges) {
142
+ // Advance line numbers to range.start
143
+ while (opIdx < range.start) {
144
+ if (ops[opIdx].type === "-") oldLineNum++;
145
+ else if (ops[opIdx].type === "+") newLineNum++;
146
+ else {
147
+ oldLineNum++;
148
+ newLineNum++;
149
+ }
150
+ opIdx++;
151
+ }
152
+
153
+ const hunkOldStart = oldLineNum;
154
+ const hunkNewStart = newLineNum;
155
+ let hunkOldCount = 0;
156
+ let hunkNewCount = 0;
157
+ const hunkLines: string[] = [];
158
+
159
+ while (opIdx <= range.end) {
160
+ const op = ops[opIdx];
161
+ hunkLines.push(`${op.type}${op.line}`);
162
+ if (op.type === "-") {
163
+ oldLineNum++;
164
+ hunkOldCount++;
165
+ } else if (op.type === "+") {
166
+ newLineNum++;
167
+ hunkNewCount++;
168
+ } else {
169
+ oldLineNum++;
170
+ newLineNum++;
171
+ hunkOldCount++;
172
+ hunkNewCount++;
173
+ }
174
+ opIdx++;
175
+ }
176
+
177
+ result.push(
178
+ `@@ -${hunkOldStart},${hunkOldCount} +${hunkNewStart},${hunkNewCount} @@`,
179
+ );
180
+ result.push(...hunkLines);
181
+ }
182
+
183
+ return result.join("\n");
184
+ }
@@ -0,0 +1,74 @@
1
+ import type { InputActions } from "@deepseek-ai/dsh-client-ui-conversation/client";
2
+ import { writeClipboard } from "@deepseek-ai/dsh-client-ui-primitives";
3
+ import type { CodeQuotePayload } from "./CodeFileView.tsx";
4
+
5
+ export interface FormattedQuote {
6
+ chipText: string;
7
+ markdownText: string;
8
+ }
9
+
10
+ /**
11
+ * Formats a code quote payload ensuring file name, line numbers, and quoted text
12
+ * are consistently present.
13
+ */
14
+ export function formatQuoteContent(quote: CodeQuotePayload): FormattedQuote {
15
+ const header = quote.lines
16
+ ? `**${quote.path}:${quote.lines}**`
17
+ : `**${quote.path}**`;
18
+ const normalized = quote.text.replace(/\r?\n$/, "");
19
+ const chipText = `${header}\n${quote.text}`;
20
+ const markdownText = `> ${header}\n${normalized
21
+ .split("\n")
22
+ .map((l) => `> ${l}`)
23
+ .join("\n")}\n\n`;
24
+
25
+ return { chipText, markdownText };
26
+ }
27
+
28
+ /**
29
+ * Inserts a formatted quote into the conversation composer or falls back to
30
+ * clipboard copy.
31
+ */
32
+ export function quoteToComposer(
33
+ quote: CodeQuotePayload,
34
+ inputActions?: Pick<
35
+ InputActions,
36
+ "insertQuote" | "insertText" | "captureInsertion" | "persistDraft"
37
+ >,
38
+ ): void {
39
+ const { chipText, markdownText } = formatQuoteContent(quote);
40
+
41
+ let inserted = false;
42
+ if (inputActions) {
43
+ try {
44
+ inserted = Boolean(inputActions.insertQuote(chipText));
45
+ if (inserted) {
46
+ inputActions.persistDraft();
47
+ }
48
+ } catch {
49
+ inserted = false;
50
+ }
51
+
52
+ if (!inserted) {
53
+ try {
54
+ const span = inputActions.captureInsertion();
55
+ const ok = Boolean(
56
+ inputActions.insertText(markdownText, {
57
+ ...span,
58
+ start: span.end,
59
+ }),
60
+ );
61
+ if (ok) {
62
+ inputActions.persistDraft();
63
+ inserted = true;
64
+ }
65
+ } catch {
66
+ inserted = false;
67
+ }
68
+ }
69
+ }
70
+
71
+ if (!inserted) {
72
+ void writeClipboard(markdownText);
73
+ }
74
+ }
@@ -0,0 +1,20 @@
1
+ import { relativeTime } from "@deepseek-ai/dsh-client-ui-primitives";
2
+
3
+ const relativeFormat = new Intl.RelativeTimeFormat("en", {
4
+ style: "short",
5
+ numeric: "always",
6
+ });
7
+
8
+ export function formatRelativeTime(timestamp: number): string {
9
+ const age = relativeTime(timestamp, Date.now());
10
+ const units = {
11
+ minutes: "minute",
12
+ hours: "hour",
13
+ days: "day",
14
+ months: "month",
15
+ years: "year",
16
+ } as const;
17
+ return age.unit === "now"
18
+ ? "just now"
19
+ : relativeFormat.format(-age.n, units[age.unit]);
20
+ }
@@ -0,0 +1,68 @@
1
+ import type { RemoteResult } from "@deepseek-ai/dsh-typert-protocol";
2
+ import { useEffect, useRef, useState } from "react";
3
+
4
+ export type LazyFileResult<T> =
5
+ | { status: "idle"; value: null }
6
+ | { status: "loading"; value: T | null }
7
+ | { status: "failed"; value: T | null; message: string }
8
+ | { status: "ready"; value: T };
9
+
10
+ export function useLazyFile<T>(
11
+ load: (signal: AbortSignal) => Promise<RemoteResult<T>>,
12
+ expanded: boolean,
13
+ ) {
14
+ const [attempt, setAttempt] = useState(0);
15
+ const [result, setResult] = useState<LazyFileResult<T>>({
16
+ status: "idle",
17
+ value: null,
18
+ });
19
+ const request = useRef<{
20
+ load: typeof load;
21
+ attempt: number;
22
+ controller: AbortController;
23
+ } | null>(null);
24
+ useEffect(() => {
25
+ if (request.current !== null && request.current.load !== load)
26
+ request.current.controller.abort();
27
+ if (!expanded) return;
28
+ if (
29
+ request.current !== null &&
30
+ request.current.load === load &&
31
+ request.current.attempt === attempt &&
32
+ !request.current.controller.signal.aborted
33
+ )
34
+ return;
35
+ if (request.current !== null) request.current.controller.abort();
36
+ const controller = new AbortController();
37
+ request.current = { load, attempt, controller };
38
+ setResult((previous) => ({ status: "loading", value: previous.value }));
39
+ load(controller.signal).then(
40
+ (result) => {
41
+ if (controller.signal.aborted) return;
42
+ if (result.ok) setResult({ status: "ready", value: result.value });
43
+ else
44
+ setResult((previous) => ({
45
+ status: "failed",
46
+ value: previous.value,
47
+ message: result.error.message,
48
+ }));
49
+ },
50
+ (error: unknown) => {
51
+ if (!controller.signal.aborted)
52
+ setResult((previous) => ({
53
+ status: "failed",
54
+ value: previous.value,
55
+ message: error instanceof Error ? error.message : String(error),
56
+ }));
57
+ },
58
+ );
59
+ }, [expanded, load, attempt]);
60
+ useEffect(
61
+ () => () => {
62
+ if (request.current !== null) request.current.controller.abort();
63
+ },
64
+ [],
65
+ );
66
+ const retry = () => setAttempt((value) => value + 1);
67
+ return { result, retry };
68
+ }
@@ -0,0 +1,136 @@
1
+ import { type RefObject, useEffect, useState } from "react";
2
+
3
+ export interface FloatingQuoteState {
4
+ text: string;
5
+ lines?: string;
6
+ top: number;
7
+ left: number;
8
+ }
9
+
10
+ /**
11
+ * Computes 1-based start and end line indices from .line elements intersecting the range.
12
+ * @internal
13
+ */
14
+ export function getSelectedLineSpan(
15
+ container: HTMLElement,
16
+ range: Range,
17
+ ): { min: number; max: number } | null {
18
+ const lineElements = container.querySelectorAll<HTMLElement>(".line");
19
+ if (lineElements.length === 0) return null;
20
+
21
+ let min = -1;
22
+ let max = -1;
23
+ const doc = container.ownerDocument;
24
+ const part = doc.createRange();
25
+
26
+ for (let i = 0; i < lineElements.length; i++) {
27
+ const line = lineElements[i];
28
+ if (!range.intersectsNode(line)) {
29
+ if (min !== -1) break; // .line elements are sequential DOM siblings
30
+ continue;
31
+ }
32
+
33
+ const isStart = line.contains(range.startContainer);
34
+ const isEnd = line.contains(range.endContainer);
35
+
36
+ if (!isStart && !isEnd) {
37
+ // Intermediate line strictly spanned by selection
38
+ if (min === -1) min = i;
39
+ max = i;
40
+ continue;
41
+ }
42
+
43
+ part.selectNodeContents(line);
44
+ if (isStart) {
45
+ part.setStart(range.startContainer, range.startOffset);
46
+ }
47
+ if (isEnd) {
48
+ part.setEnd(range.endContainer, range.endOffset);
49
+ }
50
+
51
+ if (!part.collapsed && part.toString() !== "") {
52
+ if (min === -1) min = i;
53
+ max = i;
54
+ }
55
+ }
56
+
57
+ return min === -1 ? null : { min: min + 1, max: max + 1 };
58
+ }
59
+
60
+ export function useSelectionQuote({
61
+ containerRef,
62
+ enabled,
63
+ }: {
64
+ containerRef: RefObject<HTMLElement | null>;
65
+ enabled: boolean;
66
+ }): {
67
+ floatingQuote: FloatingQuoteState | null;
68
+ clearFloatingQuote: () => void;
69
+ } {
70
+ const [floatingQuote, setFloatingQuote] = useState<FloatingQuoteState | null>(
71
+ null,
72
+ );
73
+
74
+ useEffect(() => {
75
+ if (!enabled) {
76
+ setFloatingQuote(null);
77
+ return;
78
+ }
79
+
80
+ const update = () => {
81
+ const container = containerRef.current;
82
+ if (!container) {
83
+ setFloatingQuote(null);
84
+ return;
85
+ }
86
+ const sel = window.getSelection();
87
+ if (!sel || sel.isCollapsed || sel.rangeCount === 0) {
88
+ setFloatingQuote(null);
89
+ return;
90
+ }
91
+ const range = sel.getRangeAt(0);
92
+ if (!container.contains(range.commonAncestorContainer)) {
93
+ setFloatingQuote(null);
94
+ return;
95
+ }
96
+ const text = sel.toString().trim();
97
+ if (!text) {
98
+ setFloatingQuote(null);
99
+ return;
100
+ }
101
+
102
+ const rect = range.getBoundingClientRect();
103
+ const containerRect = container.getBoundingClientRect();
104
+
105
+ let lines: string | undefined;
106
+ const span = getSelectedLineSpan(container, range);
107
+ if (span !== null) {
108
+ lines =
109
+ span.min === span.max ? String(span.min) : `${span.min}–${span.max}`;
110
+ }
111
+
112
+ const top = Math.max(0, rect.top - containerRect.top - 32);
113
+ const left = Math.max(
114
+ 8,
115
+ Math.min(
116
+ containerRect.width - 70,
117
+ rect.left - containerRect.left + rect.width / 2 - 30,
118
+ ),
119
+ );
120
+ setFloatingQuote({ text, lines, top, left });
121
+ };
122
+
123
+ document.addEventListener("selectionchange", update);
124
+ return () => {
125
+ document.removeEventListener("selectionchange", update);
126
+ setFloatingQuote(null);
127
+ };
128
+ }, [enabled, containerRef]);
129
+
130
+ const clearFloatingQuote = () => {
131
+ setFloatingQuote(null);
132
+ window.getSelection()?.removeAllRanges();
133
+ };
134
+
135
+ return { floatingQuote, clearFloatingQuote };
136
+ }
package/src/review.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { z } from "zod";
2
+ import type { BranchReviewScope, GitReviewComment } from "./types.ts";
3
+
4
+ const commit = z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/);
5
+ const commitRecord = z.object({
6
+ sha: commit,
7
+ subject: z.string(),
8
+ author: z.string(),
9
+ date: z.string(),
10
+ });
11
+ export const reviewTargetSchema = z.object({
12
+ repository: z.string().default(""),
13
+ branch: z.string().min(1),
14
+ commit: z.string().min(1).optional(),
15
+ });
16
+
17
+ /** Wire name of the presentation tool whose calls publish a review card. */
18
+ export const GIT_REVIEW_TOOL = "git_review_present";
19
+
20
+ /** Durable shape the presentation tool publishes on its successful result. */
21
+ export const branchReviewScopeSchema = z.object({
22
+ kind: z.literal("branch"),
23
+ repository: z.string().min(1),
24
+ ref: z.string().min(1),
25
+ base: z.discriminatedUnion("kind", [
26
+ z.object({ kind: z.literal("automatic") }),
27
+ z.object({ kind: z.literal("manual"), ref: z.string().min(1) }),
28
+ ]),
29
+ revision: z.discriminatedUnion("kind", [
30
+ z.object({ kind: z.literal("all-commits") }),
31
+ z.object({ kind: z.literal("commit"), commit: commitRecord }),
32
+ ]),
33
+ }) satisfies z.ZodType<BranchReviewScope>;
34
+
35
+ export function branchLabel(ref: string): string {
36
+ return ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref;
37
+ }
38
+
39
+ export function shortSha(sha: string): string {
40
+ return sha.slice(0, 7);
41
+ }
42
+
43
+ export const snapshotSchema = z.object({
44
+ kind: z.enum(["revision", "staged", "unstaged"]),
45
+ repository: z.string().min(1),
46
+ before: commit.nullable(),
47
+ after: commit,
48
+ });
49
+ export function commentLines(comment: GitReviewComment): string {
50
+ const { range } = comment;
51
+ const side = range.side === "deletions" ? "before" : "after";
52
+ const endSide = range.endSide === "deletions" ? "before" : "after";
53
+ if (side !== endSide)
54
+ return `${side}:${range.start} → ${endSide}:${range.end}`;
55
+ return range.start === range.end
56
+ ? String(range.start)
57
+ : `${Math.min(range.start, range.end)}–${Math.max(range.start, range.end)}`;
58
+ }
package/src/types.ts ADDED
@@ -0,0 +1,123 @@
1
+ /**
2
+ * PURPOSE: Shared data contracts for host Git reads and sidebar rendering.
3
+ */
4
+
5
+ export interface SelectedLineRange {
6
+ start: number;
7
+ end: number;
8
+ side: "deletions" | "additions";
9
+ endSide: "deletions" | "additions";
10
+ }
11
+
12
+ export const COMMIT_PAGE_SIZE = 50;
13
+ export const MAX_BRANCH_AGE_MS = 7 * 24 * 60 * 60 * 1000;
14
+
15
+ export type GitCommit = {
16
+ sha: string;
17
+ subject: string;
18
+ author: string;
19
+ date: string;
20
+ };
21
+
22
+ export type ReviewScope =
23
+ | {
24
+ kind: "branch";
25
+ repository: string;
26
+ ref: string;
27
+ base: { kind: "automatic" } | { kind: "manual"; ref: string };
28
+ revision: { kind: "all-commits" } | { kind: "commit"; commit: GitCommit };
29
+ }
30
+ | { kind: "uncommitted"; repository: string; stage: "staged" | "unstaged" };
31
+
32
+ export type BranchReviewScope = Extract<ReviewScope, { kind: "branch" }>;
33
+
34
+ /** A branch scope whose baseline is already resolved to a concrete ref. */
35
+ export type ResolvedReviewScope = Omit<BranchReviewScope, "base"> & {
36
+ base: { kind: "manual"; ref: string };
37
+ };
38
+
39
+ export type ReviewSelection =
40
+ | (Omit<BranchReviewScope, "base"> & {
41
+ base: string;
42
+ })
43
+ | Extract<ReviewScope, { kind: "uncommitted" }>;
44
+
45
+ export interface ReviewTarget {
46
+ repository: string;
47
+ branch: string;
48
+ commit?: string;
49
+ }
50
+
51
+ export type ReviewCatalog =
52
+ | { kind: "git"; repository: GitRepository; repositories: GitRepository[] }
53
+ | { kind: "unavailable"; cwd: string; message: string };
54
+
55
+ export type ReviewView = { kind: "diff"; view: GitDiffView };
56
+
57
+ export interface GitFileDiff {
58
+ path: string;
59
+ status: "added" | "deleted" | "modified";
60
+ addedLines: number;
61
+ deletedLines: number;
62
+ }
63
+
64
+ export interface GitDiffSummary {
65
+ files: number;
66
+ added: number;
67
+ deleted: number;
68
+ }
69
+
70
+ export interface GitRepository {
71
+ cwd: string;
72
+ target: string | null;
73
+ baselines: { ref: string; label: string }[];
74
+ gitbutlerError: string | null;
75
+ branches: {
76
+ ref: string;
77
+ label: string;
78
+ /** Branch tip committer time, in milliseconds since the Unix epoch. */
79
+ modifiedAt: number;
80
+ base: string | null;
81
+ kind: "git" | "gitbutler";
82
+ }[];
83
+ }
84
+
85
+ export interface GitCommitPage {
86
+ commits: GitCommit[];
87
+ hasMore: boolean;
88
+ }
89
+
90
+ export type GitComparison =
91
+ | { kind: "branch"; branch: string; base: string }
92
+ | { kind: "commit"; branch: string; commit: string }
93
+ | { kind: "staged" }
94
+ | { kind: "unstaged" };
95
+
96
+ export interface GitDiffView {
97
+ target: string;
98
+ snapshot: GitSnapshot;
99
+ diffs: GitFileDiff[];
100
+ summary: GitDiffSummary;
101
+ }
102
+
103
+ export interface GitSnapshot {
104
+ kind: "revision" | "staged" | "unstaged";
105
+ repository: string;
106
+ before: string | null;
107
+ after: string;
108
+ }
109
+
110
+ export type GitFileContents =
111
+ | { kind: "text"; before: string | null; after: string | null }
112
+ | { kind: "unavailable"; message: string };
113
+
114
+ export interface GitReviewComment {
115
+ id: string;
116
+ snapshot: GitSnapshot;
117
+ path: string;
118
+ side: "before" | "after";
119
+ line: number;
120
+ // edge case: annotation placement differs from the direction-preserving selected range.
121
+ range: Required<SelectedLineRange>;
122
+ text: string;
123
+ }