Skip to content

Commit 2980d43

Browse files
Improved handling of empty ranges
1 parent f9b04d4 commit 2980d43

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

packages/cursorless-org-docs/src/docs/components/flattenHighlights.ts

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
import type { BorderRadius, Highlight, Style } from "./types";
99

1010
export function flattenHighlights(highlights: Highlight[]): Highlight[] {
11-
const positions = getPositions(highlights);
11+
const positions = getUniquePositions(highlights);
1212
const results: Highlight[] = [];
1313
for (let i = 0; i < positions.length - 1; i++) {
1414
const range = new Range(positions[i], positions[i + 1]);
@@ -30,23 +30,48 @@ export function flattenHighlights(highlights: Highlight[]): Highlight[] {
3030
results.push({ range, style });
3131
}
3232

33+
const emptyHighlights = highlights.filter((h) => h.range.isEmpty);
34+
35+
if (emptyHighlights.length > 0) {
36+
for (const emptyHighlight of emptyHighlights) {
37+
if (!results.some((h) => h.range.isRangeEqual(emptyHighlight.range))) {
38+
results.push(emptyHighlight);
39+
}
40+
}
41+
42+
sortHighlights(results);
43+
}
44+
3345
return results;
3446
}
3547

36-
function getPositions(highlights: Highlight[]): Position[] {
48+
function sortHighlights(highlights: Highlight[]) {
49+
highlights.sort((a, b) => {
50+
if (a.range.start.isBefore(b.range.start)) {
51+
return -1;
52+
}
53+
if (a.range.start.isAfter(b.range.start)) {
54+
return 1;
55+
}
56+
if (a.range.end.isBefore(b.range.end)) {
57+
return -1;
58+
}
59+
if (a.range.end.isAfter(b.range.end)) {
60+
return 1;
61+
}
62+
return 0;
63+
});
64+
}
65+
66+
function getUniquePositions(highlights: Highlight[]): Position[] {
3767
const result: Position[] = [];
38-
const emptyHighlights = highlights.filter((h) => h.range.isEmpty);
3968
const positions = highlights
4069
.flatMap((h) => [h.range.start, h.range.end])
4170
.sort((a, b) =>
4271
a.line === b.line ? a.character - b.character : a.line - b.line,
4372
);
4473
for (let i = 0; i < positions.length; i++) {
45-
if (
46-
i === 0 ||
47-
!positions[i].isEqual(positions[i - 1]) ||
48-
emptyHighlights.some((h) => h.range.start.isEqual(positions[i]))
49-
) {
74+
if (i === 0 || !positions[i].isEqual(positions[i - 1])) {
5075
result.push(positions[i]);
5176
}
5277
}

0 commit comments

Comments
 (0)