Search code examples
visual-studio-codevscode-extensions

How to set a dynamic color for a TreeItem icon in Visual Studio Code?


In my Visual Studio Code extension I want to build a tree that displays a class hierarchy. These classes are usually from different namespaces. As a visual aid I want to assign the icon of the tree item in a color from a dynamically generated palette.

The constructor of the vscode.ThemeColor class appears to only accept color IDs which are statically defined in package.json. Like this:

const c = new vscode.ThemeColor('my.color.id');

I have looked through the Theme Color and File Icon API reference but I cannot see how to achieve goal.

I tried to dynamically generate SVG data but I failed loading the images into the the item.

I also tried to dynamically alter the color palette configuration but I did not succeed.

Can anyone help me?


Solution

  • I found an acceptable solution for my problem. It is possible to dynamically add colors to the workbench configuration like this:

    const workbench = vscode.workspace.getConfiguration("workbench");
    
    const colorCustomizations: any = workbench.get("colorCustomizations");
    
    workbench.update(
        "colorCustomizations",
        {
            ...colorCustomizations,
            "my.color": "#ff0000",
        },
        1,
    );
    

    This does not even require a definition in the extension's package.json file. Now I can use my custom color like any other:

    const c = new vscode.ThemeColor('my.color')