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 12 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
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
7 changes: 6 additions & 1 deletion packages/sdks/react-sdk/src/components/Descope.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ const Descope = React.forwardRef<HTMLElement, DescopeProps>(
restartOnError,
errorTransformer,
styleId,
onScreenUpdate,
children,
},
ref,
) => {
Expand Down Expand Up @@ -179,8 +181,11 @@ const Descope = React.forwardRef<HTMLElement, DescopeProps>(
// props
'errorTransformer.prop': errorTransformer,
'logger.prop': logger,
'onScreenUpdate.prop': onScreenUpdate,
}}
/>
>
{children}
</DescopeWC>
</Suspense>
</form>
);
Expand Down
10 changes: 10 additions & 0 deletions packages/sdks/react-sdk/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,16 @@ export type DescopeProps = {
// use to override client context in flow execution
client?: Record<string, any>;
styleId?: string;
onScreenUpdate?: (
screenName: string,
state: Record<string, any>,
next: (
interactionId: string,
form: Record<string, any>,
) => Promise<unknown>,
ref: HTMLElement,
) => boolean;
children?: React.ReactNode;
};

export type UserManagementProps = WidgetProps;
Expand Down
75 changes: 62 additions & 13 deletions packages/sdks/web-component/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,22 +71,22 @@ NOTE: This package is a part of a monorepo. so if you make changes in a dependen

## Optional Attributes

| Attribute | Available options | Default value |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |
| base-url | Custom Descope base URL | **""** |
| theme | **"light"** - Light theme</br>**"dark"** - Dark theme</br>**"os"** - Auto select a theme based on the OS theme settings | **"light"** |
| debug | **"true"** - Enable debugger</br>**"false"** - Disable debugger | **"false"** |
| preview | **"true"** - Run flow in a preview mode</br>**"false"** - Do run flow in a preview mode | **"false"** |
| auto-focus | **"true"** - Automatically focus on the first input of each screen</br>**"false"** - Do not automatically focus on screen's inputs</br>**"skipFirstScreen"** - Automatically focus on the first input of each screen, except first screen | **"true"** |
| Attribute | Available options | Default value |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| base-url | Custom Descope base URL | **""** |
| theme | **"light"** - Light theme</br>**"dark"** - Dark theme</br>**"os"** - Auto select a theme based on the OS theme settings | **"light"** |
| debug | **"true"** - Enable debugger</br>**"false"** - Disable debugger | **"false"** |
| preview | **"true"** - Run flow in a preview mode</br>**"false"** - Do run flow in a preview mode | **"false"** |
| auto-focus | **"true"** - Automatically focus on the first input of each screen</br>**"false"** - Do not automatically focus on screen's inputs</br>**"skipFirstScreen"** - Automatically focus on the first input of each screen, except first screen | **"true"** |

| validate-on-blur | **"true"** - Triggers the input validation upon blur in addition to the validation on submit</br>**"false"** - Do not triggers validation upon blur</br> | **"false"** |
| validate-on-blur | **"true"** - Triggers the input validation upon blur in addition to the validation on submit</br>**"false"** - Do not triggers validation upon blur</br> | **"false"** |

| restart-on-error | **"true"** - In case of flow version mismatch, will restart the flow if the components version was not changed</br>**"false"** - Do not restart the flow automatically</br> | **"false"** |
| restart-on-error | **"true"** - In case of flow version mismatch, will restart the flow if the components version was not changed</br>**"false"** - Do not restart the flow automatically</br> | **"false"** |

| storage-prefix | **String** - A prefix to add to the key of the local storage when persisting tokens | **""** |
| store-last-authenticated-user | **"true"** - Stores last-authenticated user details in local storage when flow is completed</br>**"false"** - Do not store last-auth user details. Disabling this flag may cause last-authenticated user features to not function properly | **"true"** |
| keep-last-authenticated-user-after-logout | **"true"** - Do not clear the last authenticated user details from the browser storage after logout</br>**"false"** - Clear the last authenticated user details from the browser storage after logout | **"false"** |
| style-id | **"String"** - Set a specific style to load rather then the default style | **""** |
| storage-prefix | **String** - A prefix to add to the key of the local storage when persisting tokens | **""** |
| store-last-authenticated-user | **"true"** - Stores last-authenticated user details in local storage when flow is completed</br>**"false"** - Do not store last-auth user details. Disabling this flag may cause last-authenticated user features to not function properly | **"true"** |
| keep-last-authenticated-user-after-logout | **"true"** - Do not clear the last authenticated user details from the browser storage after logout</br>**"false"** - Clear the last authenticated user details from the browser storage after logout | **"false"** |
| style-id | **"String"** - Set a specific style to load rather then the default style | **""** |

## Optional Properties

Expand Down Expand Up @@ -131,6 +131,55 @@ const descopeWcEle = document.getElementsByTagName('descope-wc')[0];
descopeWcEle.logger = logger;
```

### `onScreenUpdate`

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

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

The function 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

Usage example:

```javascript
function onScreenUpdate(screenName, state, next, ref) {
if (screenName === 'My Custom Screen') {
ref.innerHTML = `
<form>
<input type="text" name="email" placeholder="Email" />
<button type="submit">Submit</button>
</form>
`;

ref.closest('form').addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const data = Object.fromEntries(formData.entries());

// replace with the button interaction id
next('interactionId', data);
});

return true;
}

return false;
}

const descopeWcEle = document.querySelector('descope-wc');

descopeWcEle.onScreenUpdate = onScreenUpdate;
```

## Events

### `error` - Fired when an error occurs. The event detail contains the error object.
Expand Down
2 changes: 2 additions & 0 deletions packages/sdks/web-component/rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,13 @@ export default [
dir: 'dist/esm',
format: 'esm',
preserveModules: true,
sourcemap: true,
},
{
dir: 'dist/cjs',
format: 'cjs',
preserveModules: true,
sourcemap: true,
},
],
plugins: [
Expand Down
29 changes: 28 additions & 1 deletion packages/sdks/web-component/src/app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
};
return translationMap[error.type] || error.text;
}
const descopeWcEle = document.getElementsByTagName('descope-wc')[0];
const descopeWcEle = document.querySelector('descope-wc');

descopeWcEle.errorTransformer = translateError;
descopeWcEle.addEventListener('error', (e) =>
Expand All @@ -72,6 +72,33 @@
// Alternatively, it can be hidden. For example:
// document.querySelector('.loading')?.style.display = 'none';
});
descopeWcEle.addEventListener('screen-updated', (e) => {
console.log('screen-updated', e.detail);
});
</script>
<script>
const descopeEle = document.querySelector('descope-wc');

descopeEle.onScreenUpdate = async (screenName, state, next, ref) => {
console.log('onScreenUpdate', screenName, state);

// ref.innerHTML = `
// <form>
// <input type="text" name="email" placeholder="Email" />
// <button type="submit">Submit</button>
// </form>
// `;

// ref.closest('form').addEventListener('submit', (e) => {
// e.preventDefault();
// const formData = new FormData(e.target);
// const data = Object.fromEntries(formData.entries());

// next('Ppb_65tyyn', data);
// });

return false;
};
</script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const EXCLUDED_STATE_KEYS = [
'cssVars',
'componentsConfig',
'inputs',
'errorText',
'errorType',
'clientScripts',
];
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ class BaseDescopeWc extends BaseClass {
nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });

rootElement: HTMLDivElement;
contentRootElement: HTMLDivElement;
slotElement: HTMLSlotElement;

#debuggerEle: HTMLElement & {
updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;
Expand All @@ -133,8 +135,9 @@ class BaseDescopeWc extends BaseClass {

#initShadowDom() {
this.shadowRoot.appendChild(initTemplate.content.cloneNode(true));

this.rootElement = this.shadowRoot.querySelector<HTMLDivElement>('#root');
this.slotElement = document.createElement('slot');
this.slotElement.classList.add('hidden');
this.rootElement.appendChild(this.slotElement);
}

get flowId() {
Expand Down
Loading
Loading