Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

377 focus out of bound #407

Open
wants to merge 2 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions packages/mdx/src/utils/focus.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, it, expect, test } from "vitest"

import {
getFocusIndexes,
mapFocusToLineNumbers,
relativeToAbsolute,
} from "./focus"
Expand Down Expand Up @@ -33,3 +34,31 @@ describe("relative to absolute", () => {
)
})
})

describe("get focus indexes", () => {
it("return correct focus indexes", () => {
expect(getFocusIndexes("3:4", fixtureCode)).toEqual([2, 3])
expect(getFocusIndexes("1:8", fixtureCode)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
})
it("return all lines when focus string is empty", () => {
expect(getFocusIndexes(null, fixtureCode)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
expect(getFocusIndexes("", fixtureCode)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
})
it("throws error if one or many indexes are larger than lines count", () => {
expect(() => getFocusIndexes("13:14", fixtureCode)).toThrowError("Out of bound focus line number(s)")
expect(() => getFocusIndexes("7:9", fixtureCode)).toThrowError("Out of bound focus line number(s)")
expect(() => getFocusIndexes("1:3,7:9", fixtureCode)).toThrowError("Out of bound focus line number(s)")
})
})

const fixtureCode = [
"function doStuffToFoo(foo: any) {",
"",
" const bar = doStuff(foo)",
" if(!bar)",
" return null",
"",
" return bar",
"}",
]

22 changes: 13 additions & 9 deletions packages/mdx/src/utils/focus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,15 +124,19 @@ export function getFocusIndexes(
focus: FocusString,
lines: any[]
): number[] {
if (!focus) {
return [...lines.keys()]
} else {
const parsed = parseFocus(focus)
const focusedIndexes = Object.keys(parsed).map(i =>
parseInt(i, 10)
)
return focusedIndexes
}
if (!focus)
return [...lines.keys()]

const parsed = parseFocus(focus)
const focusedIndexes = Object.keys(parsed).map(i =>
parseInt(i, 10)
)

const hasOutOfRangeIndex = focusedIndexes.some(i => i + 1 > lines.length)
if(hasOutOfRangeIndex)
throw new Error("Out of bound focus line number(s)")

return focusedIndexes
}

function getFocusByKey(focus: FocusString, keys: number[]) {
Expand Down