Home > Back-end >  Finding the hovered asset id from a VS Code extension
Finding the hovered asset id from a VS Code extension

Time:11-26

I'm trying to display a thumbnail when an asset id is being hovered from a VS Code extension.

let disposable = vscode.languages.registerHoverProvider(['lua', 'luau'], {
        async provideHover(document, position, token) {
            const range = document.getWordRangeAtPosition(position, /rbxassetid:\/\/\d /);
            const word = document.getText(range);

            const id = /rbxassetid:\/\/(\d )/.exec(word)?.[1];
            
            console.log(`Found ${id}, fetching thumbnail info...`);
            const response = await fetch(`<roblox-thumbnail-api>`);
            const data = await response.json() as RobloxThumbnailResponse;
            const image = data.data?.[0]?.imageUrl;
            console.log(image);

            const mdString = new vscode.MarkdownString(`Asset: ${id}\n<img src="${image}" height="150px">`);
            mdString.supportHtml = true;
            return new vscode.Hover(mdString);
        }
    });

This is working mostly, but hovering over something that doesn't match something like rbxassetid://1818 will still display a thumbnail.

I'm using this little luautest.luau script to test my extension.

-- some random stuff that isn't using asset ids
for i=1, 10 do
    print(i)
end
print("rbxassetid://1818") -- an asset id
-- some more stuff that isn't using asset ids
for i=10, 1, -1 do
    print(i)
end
print("rbxassetid://7200003285") -- another asset id
-- some more random stuff that isn't using asset ids
for i=1, 10 do
    print(i)
end

Hovering over rbxassetid://1818 works as expected. hovering over the first asset hovering the string on line 5

Hovering over the other asset id also works as expected. hovering over the second asset hovering the string on line 10

The issue is that hovering over anything else will always display asset 1818. hovering over something that isn't an asset hovering print on line 8

I'm not sure how to fix this RegEx so that hovering over something that isn't an asset id doesn't match the first asset id in the file.

CodePudding user response:

Apparently document.getWordRangeAtPosition() can return undefined, which seems to cause document.getText() to match the entire document. I was able resolve this issue by adding this after the call to document.getWordRangeAtPosition.

if (!range) {
    return;
}
  • Related