Skip to content

Visualize Your Ideas With Code

feat(2d): code range helpers (#947)

Jacob044c9acd6ee7
diff --git a/packages/2d/src/lib/code/CodeRange.ts b/packages/2d/src/lib/code/CodeRange.ts
index b907cf44..b72cc3a2 100644
--- a/packages/2d/src/lib/code/CodeRange.ts
+++ b/packages/2d/src/lib/code/CodeRange.ts
@@ -163,3 +163,54 @@ export function inverseCodeRange(ranges: CodeRange[]): CodeRange[] {
[lastRange[1], [Infinity, Infinity]],
];
}
+
+/**
+ * Find all code ranges that match the given pattern.
+ *
+ * @param code - The code to search in.
+ * @param pattern - Either a string or a regular expression to search for.
+ * @param limit - An optional limit on the number of ranges to find.
+ */
+export function findAllCodeRanges(
+ code: string,
+ pattern: string | RegExp,
+ limit = Infinity,
+): CodeRange[] {
+ if (typeof pattern === 'string') {
+ pattern = new RegExp(pattern, 'g');
+ }
+
+ const matches = code.matchAll(pattern);
+ const ranges: CodeRange[] = [];
+ let index = 0;
+ let line = 0;
+ let column = 0;
+
+ for (const match of matches) {
+ if (match.index === undefined || ranges.length >= limit) {
+ continue;
+ }
+
+ let from: CodePoint = [line, column];
+ while (index <= code.length) {
+ if (index === match.index) {
+ from = [line, column];
+ }
+
+ if (index === match.index + match[0].length) {
+ ranges.push([from, [line, column]]);
+ break;
+ }
+
+ if (code[index] === '\n') {
+ line++;
+ column = 0;
+ } else {
+ column++;
+ }
+ index++;
+ }
+ }
+
+ return ranges;
+}
\ No newline at end of file
diff --git a/packages/2d/src/lib/components/Code.ts b/packages/2d/src/lib/components/Code.ts
index 3b8efaa6..76fc6d46 100644
--- a/packages/2d/src/lib/components/Code.ts
+++ b/packages/2d/src/lib/components/Code.ts
@@ -20,6 +20,7 @@ import {
codeSignal,
CodeSignalContext,
DefaultHighlightStyle,
+ findAllCodeRanges,
LezerHighlighter,
lines,
parseCodeSelection,
@@ -343,6 +344,33 @@ export class Code extends Shape {
).toSignal();
}
+ /**
+ * Find all code ranges that match the given pattern.
+ *
+ * @param pattern - Either a string or a regular expression to match.
+ */
+ public findAllRanges(pattern: string | RegExp): CodeRange[] {
+ return findAllCodeRanges(this.parsed(), pattern);
+ }
+
+ /**
+ * Find the first code range that matches the given pattern.
+ *
+ * @param pattern - Either a string or a regular expression to match.
+ */
+ public findFirstRange(pattern: string | RegExp): CodeRange {
+ return findAllCodeRanges(this.parsed(), pattern, 1)[0] ?? [[0, 0], [0, 0]];
+ }
+
+ /**
+ * Find the last code range that matches the given pattern.
+ *
+ * @param pattern - Either a string or a regular expression to match.
+ */
+ public findLastRange(pattern: string | RegExp): CodeRange {
+ return findAllCodeRanges(this.parsed(), pattern).at(-1) ?? [[0, 0], [0, 0]];
+ }
+
protected override desiredSize(): SerializedVector2<DesiredLength> {
this.requestFontUpdate();
const context = this.cacheCanvas();