Skip to content

Commit

Permalink
feat: add when functionality for setting properties (#4159)
Browse files Browse the repository at this point in the history
### What does this PR do?

Adds the ability to use "when" statements for setting properties.

For example, if you want to only show certain settings for certain
operating systems by using `"when": "isLinux"`.

### Screenshot/screencast of this PR

### What issues does this PR fix or reference?

Closes #4141

### How to test this PR?

Edit `extensions/podman/package.json` configuration for binary path to:

```json
        "podman.binary.path": {
          "type": "string",
          "format": "file",
          "default": "",
          "description": "Custom path to Podman binary (Default is blank)",
          "when": "isLinux"
        },
```

When you check your preferences, it will now only show the binary path
if you are running Linux.

Signed-off-by: Charlie Drage <charlie@charliedrage.com>
  • Loading branch information
cdrage committed Oct 3, 2023
1 parent 5ebbd2e commit 5e67b9b
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 12 deletions.
Expand Up @@ -3,7 +3,7 @@ import type { IConfigurationPropertyRecordedSchema } from '../../../../main/src/
import type { ProviderInfo } from '../../../../main/src/plugin/api/provider-info';
import PreferencesRenderingItemFormat from './PreferencesRenderingItemFormat.svelte';
import TerminalWindow from '../ui/TerminalWindow.svelte';
import { getNormalizedDefaultNumberValue, writeToTerminal } from './Util';
import { getNormalizedDefaultNumberValue, writeToTerminal, isPropertyValidInContext } from './Util';
import ErrorMessage from '../ui/ErrorMessage.svelte';
import {
clearCreateTask,
Expand Down Expand Up @@ -31,7 +31,6 @@ import EmptyScreen from '../ui/EmptyScreen.svelte';
import { faCubes } from '@fortawesome/free-solid-svg-icons';
import Button from '../ui/Button.svelte';
import type { ContextUI } from '/@/lib/context/context';
import { ContextKeyExpr } from '/@/lib/context/contextKey';
import { context } from '/@/stores/context';
export let properties: IConfigurationPropertyRecordedSchema[] = [];
Expand Down Expand Up @@ -94,11 +93,6 @@ $: if (logsTerminal && loggerHandlerKey) {
}
}
function isPropertyValidInContext(when: string, context: ContextUI) {
const expr = ContextKeyExpr.deserialize(when);
return expr?.evaluate(context);
}
onMount(async () => {
osMemory = await window.getOsMemory();
osCpu = await window.getOsCpu();
Expand All @@ -107,7 +101,7 @@ onMount(async () => {
configurationKeys = properties
.filter(property => property.scope === propertyScope)
.filter(property => property.id?.startsWith(providerInfo.id))
.filter(property => !property.when || isPropertyValidInContext(property.when, globalContext))
.filter(property => isPropertyValidInContext(property.when, globalContext))
.map(property => {
switch (property.maximum) {
case 'HOST_TOTAL_DISKSIZE': {
Expand Down
58 changes: 58 additions & 0 deletions packages/renderer/src/lib/preferences/PreferencesRendering.spec.ts
Expand Up @@ -26,6 +26,16 @@ import { render, screen } from '@testing-library/svelte';
import type { IConfigurationPropertyRecordedSchema } from '../../../../main/src/plugin/configuration-registry';
import PreferencesRendering from './PreferencesRendering.svelte';
import { CONFIGURATION_DEFAULT_SCOPE } from '../../../../main/src/plugin/configuration-registry-constants';
import { ContextUI } from '../context/context';
import { context } from '/@/stores/context';

async function waitRender(customProperties: any): Promise<void> {
const result = render(PreferencesRendering, { ...customProperties });
// wait that result.component.$$.ctx[0] is set
while (result.component.$$.ctx[0] === undefined) {
await new Promise(resolve => setTimeout(resolve, 100));
}
}

beforeAll(() => {
(window as any).getConfigurationValue = vi.fn().mockResolvedValue(true);
Expand Down Expand Up @@ -77,3 +87,51 @@ test('Expect extension title used a section name', async () => {
const sectionName = screen.getAllByText('my boolean property');
expect(sectionName.length > 0).toBe(true);
});

test('Expect example when property to be missing if when statement is not satisfied from context', async () => {
const contextConfig = new ContextUI();
context.set(contextConfig);
contextConfig.setValue('config.test', true);
expect(contextConfig.getValue('config.test')).toBe(true);

const whenProperty: IConfigurationPropertyRecordedSchema = {
title: 'example when property',
id: 'foobar',
parentId: 'key',
type: 'boolean',
default: true,
when: '!config.test',
markdownDescription: 'foobar',
scope: CONFIGURATION_DEFAULT_SCOPE,
};

waitRender({ properties: [whenProperty], key: 'key' });

// Expect "example when property" to NOT be found when running getByLabelText
const exampleWhenProperty = screen.queryByLabelText('example when property');
expect(exampleWhenProperty).not.toBeInTheDocument();
});

test('Expect example when property to show if when statement is satisfied from context', async () => {
const contextConfig = new ContextUI();
context.set(contextConfig);
contextConfig.setValue('config.test', true);
expect(contextConfig.getValue('config.test')).toBe(true);

const whenProperty: IConfigurationPropertyRecordedSchema = {
title: 'example when property',
id: 'foobar',
parentId: 'key',
type: 'boolean',
default: true,
when: 'config.test', // If config.test is false, this will be shown in the render
markdownDescription: 'foobar',
scope: CONFIGURATION_DEFAULT_SCOPE,
};

waitRender({ properties: [whenProperty], key: 'key' });

// Expect "example when property" to be found when running getByLabelText
const exampleWhenProperty = screen.queryByLabelText('example when property');
expect(exampleWhenProperty).not.toBeInTheDocument();
});
26 changes: 23 additions & 3 deletions packages/renderer/src/lib/preferences/PreferencesRendering.svelte
Expand Up @@ -4,19 +4,27 @@ import type { IConfigurationPropertyRecordedSchema } from '../../../../main/src/
import PreferencesRenderingItem from './PreferencesRenderingItem.svelte';
import SettingsPage from './SettingsPage.svelte';
import Route from '../../Route.svelte';
import { isDefaultScope } from './Util';
import { isDefaultScope, isPropertyValidInContext } from './Util';
import type { ContextUI } from '../context/context';
import { context } from '/@/stores/context';
import { onDestroy, onMount } from 'svelte';
import { type Unsubscriber } from 'svelte/store';
export let properties: IConfigurationPropertyRecordedSchema[] = [];
export let key: string;
let updateSearchValueTimeout: NodeJS.Timeout;
// Context variables
let contextsUnsubscribe: Unsubscriber;
let globalContext: ContextUI;
// Search and matching records
let updateSearchValueTimeout: NodeJS.Timeout;
let matchingRecords: Map<string, IConfigurationPropertyRecordedSchema[]>;
export let searchValue = '';
$: searchValue;
$: matchingRecords = properties
.filter(property => property.parentId.startsWith(key) && isDefaultScope(property.scope) && !property.hidden)
.filter(property => isPropertyValidInContext(property.when, globalContext))
.filter(
property =>
!searchValue ||
Expand All @@ -32,6 +40,18 @@ $: matchingRecords = properties
return map;
}, new Map<string, IConfigurationPropertyRecordedSchema[]>());
onMount(async () => {
contextsUnsubscribe = context.subscribe(value => {
globalContext = value;
});
});
onDestroy(() => {
if (contextsUnsubscribe) {
contextsUnsubscribe();
}
});
function matchValue(text: string, searchValue: string): boolean {
if (!text) {
return false;
Expand Down
28 changes: 27 additions & 1 deletion packages/renderer/src/lib/preferences/Util.spec.ts
Expand Up @@ -17,8 +17,9 @@
***********************************************************************/

import { test, expect, vi, afterEach } from 'vitest';
import { getNormalizedDefaultNumberValue, isTargetScope, writeToTerminal } from './Util';
import { getNormalizedDefaultNumberValue, isPropertyValidInContext, isTargetScope, writeToTerminal } from './Util';
import type { IConfigurationPropertyRecordedSchema } from '../../../../main/src/plugin/configuration-registry';
import { ContextUI } from '../context/context';

const xtermMock = {
write: vi.fn(),
Expand Down Expand Up @@ -147,3 +148,28 @@ test('return true if scope is a string and it is equal to targetScope', () => {
const result = isTargetScope('DEFAULT', 'DEFAULT');
expect(result).toBe(true);
});

test('test isPropertyValidInContext returns true if when is undefined', () => {
const contextMock = new ContextUI();
const result = isPropertyValidInContext(undefined, contextMock);
expect(result).toBe(true);
});

test('test isPropertyValidInContext returns false if when is defined but context is empty / undefined', () => {
const result = isPropertyValidInContext('config.test', new ContextUI());
expect(result).toBe(false);
});

test('test isPropertyValidInContext with valid when statements', () => {
const contextMock = new ContextUI();
contextMock.setValue('config.test', false);

// Test with single when statements
expect(isPropertyValidInContext('config.test', contextMock)).toBe(false);
expect(isPropertyValidInContext('!config.test', contextMock)).toBe(true);

// Test with multiple when statements
contextMock.setValue('config.test2', true);
expect(isPropertyValidInContext('config.test && config.test2', contextMock)).toBe(false);
expect(isPropertyValidInContext('config.test && !config.test2', contextMock)).toBe(false);
});
15 changes: 15 additions & 0 deletions packages/renderer/src/lib/preferences/Util.ts
Expand Up @@ -24,6 +24,8 @@ import type {
} from '../../../../main/src/plugin/api/provider-info';
import type { IConfigurationPropertyRecordedSchema } from '../../../../main/src/plugin/configuration-registry';
import { CONFIGURATION_DEFAULT_SCOPE } from '../../../../main/src/plugin/configuration-registry-constants';
import { ContextKeyExpr } from '../context/contextKey';
import type { ContextUI } from '../context/context';

export interface IProviderConnectionConfigurationPropertyRecorded extends IConfigurationPropertyRecordedSchema {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -107,3 +109,16 @@ export function isTargetScope(
}
return scope === targetScope;
}

export function isPropertyValidInContext(when: string | undefined, context: ContextUI): boolean {
if (!when) {
return true;
}
const expr = ContextKeyExpr.deserialize(when);

// Only evaluate if context is not undefined
if (expr && context !== undefined) {
return expr.evaluate(context);
}
return false;
}

0 comments on commit 5e67b9b

Please sign in to comment.