fix(backlinks): keep truncateMiddle within maxLength (#134)
This commit is contained in:
parent
8ca2e0b332
commit
d7cfbec796
33
src/client/features/backlinks/backlinksPageUtils.test.ts
Normal file
33
src/client/features/backlinks/backlinksPageUtils.test.ts
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { truncateMiddle } from "./backlinksPageUtils";
|
||||||
|
|
||||||
|
describe("truncateMiddle", () => {
|
||||||
|
it("returns the value unchanged when it already fits", () => {
|
||||||
|
expect(truncateMiddle("short", 10)).toBe("short");
|
||||||
|
expect(truncateMiddle("exactly-ten", "exactly-ten".length)).toBe(
|
||||||
|
"exactly-ten",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never returns a string longer than maxLength", () => {
|
||||||
|
const value = "/very/long/path/segment/that/keeps/going/here";
|
||||||
|
for (let maxLength = 0; maxLength <= value.length; maxLength++) {
|
||||||
|
expect(truncateMiddle(value, maxLength).length).toBeLessThanOrEqual(
|
||||||
|
maxLength,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps head and tail around a middle ellipsis", () => {
|
||||||
|
expect(truncateMiddle("abcdefghijklmno", 10)).toBe("abc...mno");
|
||||||
|
expect(truncateMiddle("/very/long/path/segment/here", 12)).toBe(
|
||||||
|
"/ver...here",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("head-truncates when there is no room for both sides", () => {
|
||||||
|
expect(truncateMiddle("abcdefgh", 4)).toBe("a...");
|
||||||
|
expect(truncateMiddle("abcdefgh", 3)).toBe("abc");
|
||||||
|
expect(truncateMiddle("abcdefgh", 2)).toBe("ab");
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -114,8 +114,15 @@ export function extractUrlPath(url: string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ELLIPSIS = "...";
|
||||||
|
|
||||||
export function truncateMiddle(value: string, maxLength: number) {
|
export function truncateMiddle(value: string, maxLength: number) {
|
||||||
if (value.length <= maxLength) return value;
|
if (value.length <= maxLength) return value;
|
||||||
const sideLength = Math.floor((maxLength - 1) / 2);
|
if (maxLength <= ELLIPSIS.length)
|
||||||
return `${value.slice(0, sideLength)}...${value.slice(-sideLength)}`;
|
return value.slice(0, Math.max(maxLength, 0));
|
||||||
|
const sideLength = Math.floor((maxLength - ELLIPSIS.length) / 2);
|
||||||
|
if (sideLength <= 0) {
|
||||||
|
return `${value.slice(0, maxLength - ELLIPSIS.length)}${ELLIPSIS}`;
|
||||||
|
}
|
||||||
|
return `${value.slice(0, sideLength)}${ELLIPSIS}${value.slice(-sideLength)}`;
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user