terminalLinks.test.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { describe, expect, it } from "vitest";
  2. import type { IBuffer, IBufferCell, IBufferLine } from "@xterm/xterm";
  3. import {
  4. findHttpLinksInTerminalText,
  5. getHttpLinksForTerminalBufferLine,
  6. } from "@/terminal/terminalLinks.js";
  7. function createCell(chars: string): IBufferCell {
  8. return {
  9. getChars: () => chars,
  10. getWidth: () => 1,
  11. } as IBufferCell;
  12. }
  13. function createLine(text: string, cols: number, isWrapped = false): IBufferLine {
  14. return {
  15. isWrapped,
  16. getCell: (index: number) => {
  17. if (index < 0 || index >= cols) {
  18. return undefined;
  19. }
  20. return createCell(text[index] ?? "");
  21. },
  22. } as IBufferLine;
  23. }
  24. function createBuffer(lines: Array<{ text: string; isWrapped?: boolean }>, cols: number): IBuffer {
  25. const bufferLines = lines.map((line) => createLine(line.text, cols, line.isWrapped));
  26. return {
  27. length: bufferLines.length,
  28. getLine: (index: number) => bufferLines[index],
  29. } as IBuffer;
  30. }
  31. describe("terminalLinks", () => {
  32. it("detects http links and trims surrounding sentence punctuation", () => {
  33. expect(
  34. findHttpLinksInTerminalText(
  35. "Open (https://example.com/path_(ok)), then http://localhost:3000.",
  36. ),
  37. ).toEqual([
  38. {
  39. text: "https://example.com/path_(ok)",
  40. startIndex: 6,
  41. endIndex: 34,
  42. },
  43. {
  44. text: "http://localhost:3000",
  45. startIndex: 43,
  46. endIndex: 63,
  47. },
  48. ]);
  49. });
  50. it("maps a plain http link to xterm buffer coordinates", () => {
  51. const buffer = createBuffer([{ text: "see https://z.ai" }], 18);
  52. expect(getHttpLinksForTerminalBufferLine(buffer, 1, 18)).toEqual([
  53. {
  54. text: "https://z.ai",
  55. range: {
  56. start: { x: 5, y: 1 },
  57. end: { x: 16, y: 1 },
  58. },
  59. decorations: {
  60. underline: true,
  61. pointerCursor: true,
  62. },
  63. },
  64. ]);
  65. });
  66. it("keeps wrapped http links clickable from continuation lines", () => {
  67. const buffer = createBuffer(
  68. [
  69. { text: "run http:/" },
  70. { text: "/example.c", isWrapped: true },
  71. { text: "om done", isWrapped: true },
  72. ],
  73. 10,
  74. );
  75. expect(getHttpLinksForTerminalBufferLine(buffer, 2, 10)).toEqual([
  76. {
  77. text: "http://example.com",
  78. range: {
  79. start: { x: 5, y: 1 },
  80. end: { x: 2, y: 3 },
  81. },
  82. decorations: {
  83. underline: true,
  84. pointerCursor: true,
  85. },
  86. },
  87. ]);
  88. });
  89. });