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: Custom screens support RELEASE #1012

Merged
merged 25 commits into from
Feb 11, 2025
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"preversion:ci": "sh ./tools/scripts/latestTag.sh",
"version:ci": "pnpm affected:ci --target version --noVerify=true --parallel 1",
"postversion:ci": "pnpm run build:ci",
"print-affected:ci": "nx print-affected --base=$(sh ./tools/scripts/latestTag.sh) --select=projects",
"print-affected:ci": "nx show projects --affected --base=$(sh ./tools/scripts/latestTag.sh) --select=projects",
"format": "nx format:write",
"format:ci": "nx format:check",
"postinstall": "pnpm update @descope/web-components-ui"
Expand Down
8 changes: 4 additions & 4 deletions packages/libs/sdk-helpers/src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ export class State<T extends StateObject> {

#token = 0;

#updateOnlyOnChange = false;
#forceUpdate = true;

constructor(init: T = {} as T, { updateOnlyOnChange = true } = {}) {
constructor(init: T = {} as T, { forceUpdate = false } = {}) {
this.#state = init;
this.#updateOnlyOnChange = updateOnlyOnChange;
this.#forceUpdate = forceUpdate;
}

get current() {
Expand All @@ -73,7 +73,7 @@ export class State<T extends StateObject> {
typeof newState === 'function' ? newState(this.#state) : newState;

const nextState = { ...this.#state, ...internalNewState };
if (!this.#updateOnlyOnChange || !compareObjects(this.#state, nextState)) {
if (this.#forceUpdate || !compareObjects(this.#state, nextState)) {
const prevState = this.#state;
this.#state = nextState;
Object.freeze(this.#state);
Expand Down
2 changes: 2 additions & 0 deletions packages/libs/sdk-mixins/src/mixins/configMixin/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,13 @@ export type ClientCondition = {

export type ClientConditionResult = {
screenId: string;
screenName: string;
interactionId: string;
};

export type FlowConfig = {
startScreenId?: string;
startScreenName?: string;
version: number;
targetLocales?: string[];
conditions?: ClientCondition[];
Expand Down
31 changes: 31 additions & 0 deletions packages/sdks/angular-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,37 @@ export class AppComponent {
></descope>
```

### `onScreenUpdate`

A function that is called whenever there is a new screen state and after every next call. It receives the following parameters:

- `screenName`: The name of the screen that is about to be rendered
- `context`: An object containing the upcoming screen context
- `next`: A function that, when called, continues the flow execution
- `ref`: A reference to the descope-wc node

The function can be sync or async, and should return a boolean indicating whether a custom screen should be rendered:

- `true`: Render a custom screen
- `false`: Render the default flow screen

This function allows rendering custom screens instead of the default flow screens.
It can be useful for highly customized UIs or specific logic not covered by the default screens

To render a custom screen, its elements should be appended as children of the `descope` component

Usage example:

```javascript
function onScreenUpdate(screenName, context, next, ref) {
if (screenName === 'My Custom Screen') {
return true;
}

return false;
}
```

#### Standalone Mode

All components in the sdk are standalone, so you can use them by directly importing them to your components.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ describe('DescopeComponent', () => {
debug: jest.fn()
};
component.errorTransformer = jest.fn();
component.onScreenUpdate = jest.fn();
component.client = {};
component.form = {};
component.storeLastAuthenticatedUser = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ export class DescopeComponent implements OnInit, OnChanges {

@Input() debug: boolean;
@Input() errorTransformer: (error: { text: string; type: string }) => string;
@Input() onScreenUpdate: (
screenName: string,
context: Record<string, any>,
next: (
interactionId: string,
form: Record<string, any>
) => Promise<unknown>,
ref: HTMLElement
) => boolean | Promise<boolean>;
@Input() client: Record<string, any>;
@Input() form: Record<string, any>;
@Input() logger: ILogger;
Expand Down Expand Up @@ -155,6 +164,10 @@ export class DescopeComponent implements OnInit, OnChanges {
this.webComponent.errorTransformer = this.errorTransformer;
}

if (this.onScreenUpdate) {
this.webComponent.onScreenUpdate = this.onScreenUpdate;
}

if (this.client) {
this.webComponent.setAttribute('client', JSON.stringify(this.client));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
[restartOnError]="restartOnError"
[debug]="debug"
[errorTransformer]="errorTransformer"
[onScreenUpdate]="onScreenUpdate"
[client]="client"
[form]="form"
[logger]="logger"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,18 @@ export class SignInFlowComponent {
@Input() autoFocus: true | false | 'skipFirstScreen';
@Input() validateOnBlur: boolean;
@Input() restartOnError: boolean;

@Input() debug: boolean;
@Input() errorTransformer: (error: { text: string; type: string }) => string;
@Input() onScreenUpdate: (
screenName: string,
context: Record<string, any>,
next: (
interactionId: string,
form: Record<string, any>
) => Promise<unknown>,
ref: HTMLElement
) => boolean | Promise<boolean>;
@Input() client: Record<string, any>;
@Input() form: Record<string, any>;
@Input() logger: ILogger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
[restartOnError]="restartOnError"
[debug]="debug"
[errorTransformer]="errorTransformer"
[onScreenUpdate]="onScreenUpdate"
[client]="client"
[form]="form"
[logger]="logger"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,18 @@ export class SignUpFlowComponent {
@Input() autoFocus: true | false | 'skipFirstScreen';
@Input() validateOnBlur: boolean;
@Input() restartOnError: boolean;

@Input() debug: boolean;
@Input() errorTransformer: (error: { text: string; type: string }) => string;
@Input() onScreenUpdate: (
screenName: string,
context: Record<string, any>,
next: (
interactionId: string,
form: Record<string, any>
) => Promise<unknown>,
ref: HTMLElement
) => boolean | Promise<boolean>;
@Input() client: Record<string, any>;
@Input() form: Record<string, any>;
@Input() logger: ILogger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
[restartOnError]="restartOnError"
[debug]="debug"
[errorTransformer]="errorTransformer"
[onScreenUpdate]="onScreenUpdate"
[client]="client"
[form]="form"
[logger]="logger"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,18 @@ export class SignUpOrInFlowComponent {
@Input() autoFocus: true | false | 'skipFirstScreen';
@Input() validateOnBlur: boolean;
@Input() restartOnError: boolean;

@Input() debug: boolean;
@Input() errorTransformer: (error: { text: string; type: string }) => string;
@Input() onScreenUpdate: (
screenName: string,
context: Record<string, any>,
next: (
interactionId: string,
form: Record<string, any>
) => Promise<unknown>,
ref: HTMLElement
) => boolean | Promise<boolean>;
@Input() client: Record<string, any>;
@Input() form: Record<string, any>;
@Input() logger: ILogger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ describe('AppComponent', () => {
providers: [
DescopeAuthConfig,
{ provide: DescopeAuthConfig, useValue: { projectId: 'test' } }
],
]
}).compileComponents();
});

Expand Down
76 changes: 38 additions & 38 deletions packages/sdks/core-js-sdk/src/createSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,48 +24,48 @@ const withSdkConfigValidations = withValidations([
/** Add the ability to pass multiple hooks instead of one when creating an SDK instance */
const withMultipleHooks =
<T extends object>(createSdk: (config: SdkConfig) => T) =>
(
config: Omit<SdkConfig, 'hooks'> & {
hooks?: {
beforeRequest?: BeforeRequest | BeforeRequest[];
afterRequest?: AfterRequest | AfterRequest[];
transformResponse?: Hooks['transformResponse'];
};
},
) => {
const beforeRequest: BeforeRequest = (conf) => {
// get the before hooks from the config while function is running
// because the hooks might change after sdk creation
const beforeRequestHooks = [].concat(config.hooks?.beforeRequest || []);
return beforeRequestHooks?.reduce((acc, fn) => fn(acc), conf);
};

const afterRequest: AfterRequest = async (req, res) => {
// get the after hooks from the config while function is running
// because the hooks might change after sdk creation
const afterRequestHooks = [].concat(config.hooks?.afterRequest || []);
// do not remove this check - on old versions of react-native it is required
if (afterRequestHooks.length == 0) return;
const results = await Promise.allSettled(
afterRequestHooks?.map((fn) => fn(req, res?.clone())),
);
// eslint-disable-next-line no-console
results.forEach(
(result) =>
result.status === 'rejected' && config.logger?.error(result.reason),
);
(
config: Omit<SdkConfig, 'hooks'> & {
hooks?: {
beforeRequest?: BeforeRequest | BeforeRequest[];
afterRequest?: AfterRequest | AfterRequest[];
transformResponse?: Hooks['transformResponse'];
};
},
) => {
const beforeRequest: BeforeRequest = (conf) => {
// get the before hooks from the config while function is running
// because the hooks might change after sdk creation
const beforeRequestHooks = [].concat(config.hooks?.beforeRequest || []);
return beforeRequestHooks?.reduce((acc, fn) => fn(acc), conf);
};

return createSdk({
...config,
hooks: {
beforeRequest,
afterRequest,
transformResponse: config.hooks?.transformResponse,
},
});
const afterRequest: AfterRequest = async (req, res) => {
// get the after hooks from the config while function is running
// because the hooks might change after sdk creation
const afterRequestHooks = [].concat(config.hooks?.afterRequest || []);
// do not remove this check - on old versions of react-native it is required
if (afterRequestHooks.length == 0) return;
const results = await Promise.allSettled(
afterRequestHooks?.map((fn) => fn(req, res?.clone())),
);
// eslint-disable-next-line no-console
results.forEach(
(result) =>
result.status === 'rejected' && config.logger?.error(result.reason),
);
};

return createSdk({
...config,
hooks: {
beforeRequest,
afterRequest,
transformResponse: config.hooks?.transformResponse,
},
});
};

/** Descope SDK client */
export default withSdkConfigValidations(
withMultipleHooks(
Expand Down
34 changes: 17 additions & 17 deletions packages/sdks/nextjs-sdk/rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const commonPlugins = (outputDir) => [
}),
typescript({
tsconfig: './tsconfig.json',
declaration: false,
declaration: false
}),
// swcPreserveDirectives(),
preserveDirectives({ supressPreserveModulesWarning: true }),
Expand Down Expand Up @@ -89,20 +89,20 @@ const configurations = ['server', 'client', ''].flatMap((entry) => {
});

export default [
...configurations,
{
input: 'src/index.ts',
output: [{ dir: './dist', format: 'esm' }],
plugins: [
typescript({
tsconfig: './tsconfig.json',
compilerOptions: {
rootDir: './src',
declaration: true,
declarationDir: './dist/types',
},
}),
noEmit({ match: (file) => file.endsWith('.js') }),
],
},
...configurations,
{
input: 'src/index.ts',
output: [{ dir: './dist', format: 'esm' }],
plugins: [
typescript({
tsconfig: './tsconfig.json',
compilerOptions: {
rootDir: './src',
declaration: true,
declarationDir: './dist/types'
}
}),
noEmit({ match: (file) => file.endsWith('.js') })
]
}
];
Loading