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

feat: read feature toggles in control property editor #2467

Merged
merged 8 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/clean-jars-remember.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sap-ux/feature-toggle': patch
---

Include feature toggles form environment variable in `getAllFeatureToggles`
7 changes: 7 additions & 0 deletions .changeset/fluffy-oranges-divide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@sap-ux-private/preview-middleware-client': patch
'@sap-ux/control-property-editor': patch
'@sap-ux/preview-middleware': patch
---

Use feature toggles in the control property editor
6 changes: 4 additions & 2 deletions packages/control-property-editor/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import './index.css';
import App from './App';
import { store } from './store';
import { registerAppIcons } from './icons';
import { initializeLivereload, setProjectScenario } from './slice';
import { initializeLivereload, setProjectScenario, setFeatureToggles } from './slice';

export interface StartOptions {
previewUrl: string;
Expand All @@ -23,6 +23,7 @@ export interface StartOptions {
livereloadUrl?: string;
telemetry?: boolean;
scenario: Scenario;
features?: { feature: string; isEnabled: boolean }[];
}

/**
Expand All @@ -31,14 +32,15 @@ export interface StartOptions {
* @param options StartOptions
*/
export function start(options: StartOptions): void {
const { previewUrl, rootElementId, telemetry = false, scenario } = options;
const { previewUrl, rootElementId, telemetry = false, scenario, features = [] } = options;
if (telemetry) {
enableTelemetry();
}
initI18n();
registerAppIcons();
initIcons();

store.dispatch(setFeatureToggles(features));
store.dispatch(setProjectScenario(scenario));
store.dispatch(initializeLivereload({ port: options.livereloadPort, url: options.livereloadUrl }));

Expand Down
7 changes: 5 additions & 2 deletions packages/control-property-editor/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Dispatch } from 'redux';
import type { Middleware, MiddlewareAPI } from '@reduxjs/toolkit';
import type { AnyAction, Middleware, MiddlewareAPI } from '@reduxjs/toolkit';

import type { ExternalAction } from '@sap-ux-private/control-property-editor-common';
import {
Expand All @@ -16,6 +16,7 @@ import {
executeQuickAction
} from '@sap-ux-private/control-property-editor-common';

import type reducer from './slice';
import { changeProperty } from './slice';

type Action = ReturnType<typeof changeProperty>;
Expand All @@ -26,7 +27,9 @@ type Action = ReturnType<typeof changeProperty>;
* @param store - redux store
* @returns Function
*/
export const communicationMiddleware: Middleware<Dispatch<ExternalAction>> = (store: MiddlewareAPI) => {
export const communicationMiddleware: Middleware<Dispatch<ExternalAction>, ReturnType<typeof reducer>> = (
store: MiddlewareAPI<Dispatch<AnyAction>, ReturnType<typeof reducer>>
) => {
const { sendAction } = startPostMessageCommunication<ExternalAction>(
function getTarget(): Window | undefined {
let result;
Expand Down
8 changes: 8 additions & 0 deletions packages/control-property-editor/src/slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export interface SliceState {
scenario: Scenario;
isAdpProject: boolean;
icons: IconDetails[];
features: Record<string, boolean>;
changes: ChangesSlice;
dialogMessage: ShowMessage | undefined;
fileChanges?: string[];
Expand Down Expand Up @@ -119,6 +120,7 @@ export const changePreviewScaleMode = createAction<'fit' | 'fixed'>('app/change-
export const changeDeviceType = createAction<DeviceType>('app/change-device-type');
export const filterNodes = createAction<FilterOptions[]>('app/filter-nodes');
export const fileChanged = createAction<string[]>('app/file-changed');
export const setFeatureToggles = createAction<{ feature: string; isEnabled: boolean }[]>('app/set-feature-toggles');
interface LivereloadOptions {
port: number;

Expand All @@ -137,6 +139,7 @@ export const initialState: SliceState = {
scenario: SCENARIO.UiAdaptation,
isAdpProject: false,
icons: [],
features: {},
changes: {
controls: {},
pending: [],
Expand Down Expand Up @@ -331,6 +334,11 @@ const slice = createSlice<SliceState, SliceCaseReducers<SliceState>, string>({
.addMatcher(setSaveEnablement.match, (state, action: ReturnType<typeof setSaveEnablement>): void => {
state.canSave = action.payload;
})
.addMatcher(setFeatureToggles.match, (state, action: ReturnType<typeof setFeatureToggles>): void => {
for (const { feature, isEnabled } of action.payload) {
state.features[feature] = isEnabled;
}
})
.addMatcher(appLoaded.match, (state): void => {
state.isAppLoading = false;
})
Expand Down
17 changes: 12 additions & 5 deletions packages/control-property-editor/test/unit/appIndex.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as icons from '../../src/icons';
import * as initIcon from '@sap-ux/ui-components/dist/components/Icons'; // bug in TS 4.6 https://github.com/microsoft/TypeScript/issues/43081
import ReactDOM from 'react-dom';
import { store } from '../../src/store';
import { initializeLivereload, setProjectScenario } from '../../src/slice';
import { initializeLivereload, setFeatureToggles, setProjectScenario } from '../../src/slice';

describe('index', () => {
const i18nSpy = jest.spyOn(i18n, 'initI18n');
Expand All @@ -17,13 +17,20 @@ describe('index', () => {
test('start', () => {
const previewUrl = 'URL';
const rootElementId = 'root';
start({ previewUrl, rootElementId, livereloadPort: 8080, scenario: 'APP_VARIANT' });
const features = [
{
feature: 'test.feature',
isEnabled: true
}
];
start({ previewUrl, rootElementId, livereloadPort: 8080, scenario: 'APP_VARIANT', features });
expect(i18nSpy).toHaveBeenCalledTimes(1);
expect(iconsSpy).toHaveBeenCalledTimes(1);
expect(initIconSpy).toHaveBeenCalledTimes(1);
expect(reactSpy).toHaveBeenCalledTimes(1);
expect(dispatchSpy).toHaveBeenCalledTimes(2);
expect(dispatchSpy).nthCalledWith(1, setProjectScenario('APP_VARIANT'));
expect(dispatchSpy).nthCalledWith(2, initializeLivereload({ port: 8080, url: undefined }));
expect(dispatchSpy).toHaveBeenCalledTimes(3);
expect(dispatchSpy).nthCalledWith(1, setFeatureToggles(features));
expect(dispatchSpy).nthCalledWith(2, setProjectScenario('APP_VARIANT'));
expect(dispatchSpy).nthCalledWith(3, initializeLivereload({ port: 8080, url: undefined }));
});
});
24 changes: 23 additions & 1 deletion packages/control-property-editor/test/unit/slice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ import reducer, {
changeDeviceType,
setProjectScenario,
fileChanged,
initialState
initialState,
setFeatureToggles
} from '../../src/slice';
import { DeviceType } from '../../src/devices';
import { features } from 'process';

describe('main redux slice', () => {
describe('property changed', () => {
Expand Down Expand Up @@ -624,4 +626,24 @@ describe('main redux slice', () => {
]
});
});

describe('setFeatureToggles', () => {
test('add feature toggles', () => {
expect(
reducer(
{ features: {} } as any,
setFeatureToggles([
{
feature: 'test.feature',
isEnabled: true
}
])
)
).toStrictEqual({
features: {
'test.feature': true
}
});
});
});
});
11 changes: 11 additions & 0 deletions packages/feature-toggle/src/featureToggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,17 @@ export class FeatureToggleAccess {
});
});
}
// if TOOLSUITE_FEATURES env is set check if the feature is enabled there.
else if (process.env.TOOLSUITE_FEATURES) {
const envFeatures = process.env.TOOLSUITE_FEATURES.split(',');
for (const feature of envFeatures) {
const toggle: FeatureToggle = {
feature,
isEnabled: true
};
definedToggles.push(toggle);
}
}
return definedToggles;
}
}
Expand Down
22 changes: 22 additions & 0 deletions packages/feature-toggle/test/index_no_vscode.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { isFeatureEnabled, isInternalFeaturesSettingEnabled } from '../src';

describe('Feature Toggle Tests - ENV', () => {
const originalEnv = { ...process.env };

beforeEach(() => {
jest.resetModules();
jest.doMock('vscode', () => undefined);
});

afterEach(() => {
process.env = originalEnv;
});

test('Feature Toggle Tests - getFeatureToggle - enabled', () => {
process.env.TOOLSUITE_FEATURES = 'dummy.testToggle,otherToggle';
const featureToggle = isFeatureEnabled(`otherToggle`);
Expand All @@ -21,6 +28,21 @@ describe('Feature Toggle Tests - ENV', () => {
const isInternal = isInternalFeaturesSettingEnabled();
expect(isInternal).toBeTruthy();
});
test('Feature Toggle Tests - getAllFeatureToggles', async () => {
process.env.TOOLSUITE_FEATURES = 'dummy.testToggle,otherToggle';
const { FeatureToggleAccess } = await import('../src');
const featureToggles = FeatureToggleAccess.getAllFeatureToggles();
expect(featureToggles).toStrictEqual([
{
feature: 'dummy.testToggle',
isEnabled: true
},
{
feature: 'otherToggle',
isEnabled: true
}
]);
});
});

describe('Feature Toggle Tests - ENV - Negative', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { FeatureService } from '../../cpe/feature-service';
import type { QuickActionDefinitionRegistry } from '../../cpe/quick-actions/registry';
import type { ApplicationType } from '../../utils/application';

/**
* Loads the appropriate Quick Action registries for the given application type.
*
* @param appType - Application type.
*
* @param appType - Application type.
* @returns Quick Action registries.
*/
export async function loadDefinitions(appType: ApplicationType): Promise<QuickActionDefinitionRegistry<string>[]> {
// eslint-disable-next-line fiori-custom/sap-no-localstorage
if (localStorage.getItem('com.sap.ux.control-property-editor.features.quick-actions') !== 'true') {
if (FeatureService.isFeatureEnabled('cpe.beta.quick-actions') === false) {
return [];
}
if (appType === 'fe-v2') {
Expand Down
25 changes: 25 additions & 0 deletions packages/preview-middleware-client/src/cpe/feature-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export class FeatureService {
private static features: Record<string, boolean> = {};

static {
// eslint-disable-next-line fiori-custom/sap-no-dom-access, fiori-custom/sap-browser-api-warning
const bootstrapConfig = document.getElementById('sap-ui-bootstrap');
const features = bootstrapConfig?.getAttribute('data-open-ux-preview-features');
if (features) {
const featureToggles = JSON.parse(features) as { feature: string; isEnabled: boolean }[];
for (const { feature, isEnabled } of featureToggles) {
this.features[feature] = isEnabled;
}
}
}

/**
* Checks if given feature is enabled.
*
* @param featureId - Id of the feature.
* @returns true if feature is enabled.
*/
public static isFeatureEnabled(featureId: string): boolean {
return this.features[featureId] ?? false;
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { FeatureService } from '../../../../src/cpe/feature-service';
import { loadDefinitions } from '../../../../src/adp/quick-actions/load';
import FEV4QuickActionRegistry from 'open/ux/preview/client/adp/quick-actions/fe-v4/registry';
import FEV2QuickActionRegistry from 'open/ux/preview/client/adp/quick-actions/fe-v2/registry';

describe('quick action dyncmic loading', () => {
describe('quick action dynamic loading', () => {
beforeEach(() => {
jest.spyOn(window.localStorage.__proto__, 'getItem').mockImplementation((key) => {
if (key === 'com.sap.ux.control-property-editor.features.quick-actions') {
return 'true';
jest.spyOn(FeatureService, 'isFeatureEnabled').mockImplementation((key: string) => {
if (key === 'cpe.beta.quick-actions') {
return true;
}
return null;
return false;
});
});
test('fe-v2', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
describe('FeatureService', () => {
afterEach(() => {
jest.resetModules();
});

function setFeatureToggles(featureNames: string[]) {
const features = featureNames.map((feature) => ({
feature,
isEnabled: true
}));
const bootstrap = document.createElement('div');
bootstrap.setAttribute('id', 'sap-ui-bootstrap');
bootstrap.setAttribute('data-open-ux-preview-features', JSON.stringify(features));
document.body.appendChild(bootstrap);
}

test('not enabled feature', async () => {
const { FeatureService } = await import('../../../src/cpe/feature-service');
expect(FeatureService.isFeatureEnabled('test.feature')).toStrictEqual(false);
});

test('enabled feature', async () => {
setFeatureToggles(['test.feature']);
const { FeatureService } = await import('../../../src/cpe/feature-service');
expect(FeatureService.isFeatureEnabled('test.feature')).toStrictEqual(true);
});
});
1 change: 1 addition & 0 deletions packages/preview-middleware/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
],
"dependencies": {
"@sap-ux/logger": "workspace:*",
"@sap-ux/feature-toggle": "workspace:*",
"@sap-ux/btp-utils": "workspace:*",
"@sap-ux/adp-tooling": "workspace:*",
"@sap-ux/control-property-editor-sources": "workspace:@sap-ux/control-property-editor@*",
Expand Down
1 change: 1 addition & 0 deletions packages/preview-middleware/src/base/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export interface TemplateConfig {
developerMode: boolean;
pluginScript?: string;
};
features?: { feature: string; isEnabled: boolean }[];
locateReuseLibsScript?: boolean;
}

Expand Down
7 changes: 6 additions & 1 deletion packages/preview-middleware/src/base/flp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
type OperationType
} from '@sap-ux/adp-tooling';
import { isAppStudio, exposePort } from '@sap-ux/btp-utils';
import { FeatureToggleAccess } from '@sap-ux/feature-toggle';

import { deleteChange, readChanges, writeChange } from './flex';
import { generateImportList, mergeTestConfigDefaults } from './test';
Expand Down Expand Up @@ -167,6 +168,8 @@ export class FlpSandbox {
developerMode: editor.developerMode === true,
pluginScript: editor.pluginScript
};
config.features = FeatureToggleAccess.getAllFeatureToggles();

if (editor.developerMode === true) {
config.ui5.bootstrapOptions = serializeUi5Configuration(DEVELOPER_MODE_CONFIG);
}
Expand All @@ -193,6 +196,7 @@ export class FlpSandbox {
templatePreviewUrl = templatePreviewUrl.replace('?', `?sap-ui-layer=${rta.layer}&`);
}
const template = readFileSync(join(__dirname, '../../templates/flp/editor.html'), 'utf-8');
const features = FeatureToggleAccess.getAllFeatureToggles();
const envPort = process.env.FIORI_TOOLS_LIVERELOAD_PORT;
let livereloadPort: number = envPort ? parseInt(envPort, 10) : DEFAULT_LIVERELOAD_PORT;
livereloadPort = isNaN(livereloadPort) ? DEFAULT_LIVERELOAD_PORT : livereloadPort;
Expand All @@ -203,7 +207,8 @@ export class FlpSandbox {
appName: rta.options?.appName,
scenario,
livereloadPort,
livereloadUrl: envLivereloadUrl
livereloadUrl: envLivereloadUrl,
features: JSON.stringify(features)
});
this.sendResponse(res, 'text/html', 200, html);
});
Expand Down
1 change: 1 addition & 0 deletions packages/preview-middleware/templates/flp/editor.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
scenario: '<%- scenario %>',
livereloadPort: <%- livereloadPort %>,
livereloadUrl: '<%- livereloadUrl %>',
features: <%- features %>
});
</script>
</body>
Expand Down
Loading
Loading