The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Expose host location to front components (#28444)
Raphaël Bosi540c10e07617
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdxindex e9ee9cb538f..b4744514928 100644--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx@@ -500,6 +500,7 @@ Available hooks:| `useFrontComponentId()` | `string` | This component instance's ID || `useTimelineActivityId()` | `string` or `null` | The current timeline activity ID when rendering a custom timeline row || `useColorScheme()` | `'light'` or `'dark'` | The host UI's active color scheme (`System` is already resolved) |+| `useLocation()` | `FrontComponentLocation` or `null` | The host route's pathname, query string, and hash, plus the host app's origin || `useToolCall()` | `FrontComponentToolCall` or `null` | The AI tool call this component is rendering, when it was surfaced from a logic function's `toolTriggerSettings` || `useFrontComponentExecutionContext(selector)` | varies | Access the full execution context with a selector function |@@ -534,6 +535,25 @@ The result contains `id` (the workspace's object-metadata UUID), `nameSingular`,Object metadata can be available even when no records are selected. It belongs to this front component's context, so a side panel can expose a different object from the main page. The hook updates when that context changes and returns `null` when the object cannot be resolved, when no object context is supplied, or when running on an older host that does not provide object metadata.+### Host location++Use `useLocation()` to read the route hosting your front component. It returns a `FrontComponentLocation` object with four required string fields: `pathname`, `search`, `hash`, and `origin`. For example, a page at `https://myworkspace.twenty.com/page/page-layout-id?project=abc#details` provides `/page/page-layout-id`, `?project=abc`, `#details`, and `https://myworkspace.twenty.com` respectively. `hash` includes its leading `#` and is `''` when there is no fragment.++`pathname`, `search`, and `hash` follow the component's React Router context, including a routed side panel's own route. `origin` comes from the host app. The hook updates when the route changes. Older hosts may omit `executionContext.location`, so `useLocation()` returns `null` when location is unavailable.++For query parameters, read `useLocation()?.search ?? ''` and parse the result with `URLSearchParams`. `search` includes its leading `?` and is `''` when the route has no query string. The fallback also provides `''` when the host does not provide location.++```tsx+import { useLocation } from 'twenty-sdk/front-component';++const ProjectDetails = () => {+ const search = useLocation()?.search ?? '';+ const projectId = new URLSearchParams(search).get('project');++ return <p>Project: {projectId ?? 'No project selected'}</p>;+};+```+## Application variablesApplication variables defined in [`defineApplication()`](/developers/extend/apps/config/application) with `isSecret: false` are available inside front components via the `getApplicationVariable` utility:diff --git a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/__tests__/setFrontComponentExecutionContext.test.ts b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/__tests__/setFrontComponentExecutionContext.test.tsindex 61b6114bf45..cd134fa6257 100644--- a/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/__tests__/setFrontComponentExecutionContext.test.ts+++ b/packages/twenty-front-component-renderer/src/remote/worker/environment/utils/__tests__/setFrontComponentExecutionContext.test.ts@@ -18,6 +18,12 @@ const EXECUTION_CONTEXT: FrontComponentExecutionContext = {},timelineActivityId: null,colorScheme: 'light',+ location: {+ pathname: '/page/page-record-id',+ search: '?project=abc',+ hash: '',+ origin: 'https://app.twenty.com',+ },};const cloneExecutionContext = (@@ -56,6 +62,7 @@ describe('setFrontComponentExecutionContext', () => {expect(executionContext.selectedRecordIds).toBe(previousExecutionContext.selectedRecordIds,);+ expect(executionContext.location).toBe(previousExecutionContext.location);});it('should replace fields whose value changed', () => {@@ -75,6 +82,35 @@ describe('setFrontComponentExecutionContext', () => {expect(executionContext.selectedObjectMetadata).toBeNull();});+ it.each([+ { search: '?project=def', hash: '' },+ { search: '?project=abc', hash: '#details' },+ ])(+ 'should replace the location with search $search and hash $hash',+ ({ search, hash }) => {+ setFrontComponentExecutionContext(+ cloneExecutionContext(EXECUTION_CONTEXT),+ );++ const previousExecutionContext = getStoredExecutionContext();+ const location = {+ pathname: '/page/page-record-id',+ search,+ hash,+ origin: 'https://app.twenty.com',+ };++ setFrontComponentExecutionContext(+ cloneExecutionContext({ ...EXECUTION_CONTEXT, location }),+ );++ expect(getStoredExecutionContext().location).toEqual(location);+ expect(getStoredExecutionContext().location).not.toBe(+ previousExecutionContext.location,+ );+ },+ );+it('should notify listeners once the new context is stored', () => {const observedColorSchemes: string[] = [];diff --git a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsxindex 08987d4e7be..9cacfe3107d 100644--- a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx+++ b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx@@ -59,6 +59,19 @@ const mockStorageClear = jest.fn();let mockCurrentUser: { id: string } | null = { id: 'user-123' };let mockIsMobile = false;+let mockLocationSearch = '';+let mockLocationPathname = '/';+let mockLocationHash = '';++jest.mock('react-router-dom', () => ({+ ...jest.requireActual('react-router-dom'),+ useLocation: () => ({+ search: mockLocationSearch,+ pathname: mockLocationPathname,+ hash: mockLocationHash,+ }),+}));+jest.mock('~/hooks/useNavigateApp', () => ({useNavigateApp: () => mockNavigateApp,}));@@ -252,6 +265,9 @@ describe('useFrontComponentExecutionContext', () => {jest.clearAllMocks();mockCurrentUser = { id: 'user-123' };mockIsMobile = false;+ mockLocationSearch = '';+ mockLocationPathname = '/';+ mockLocationHash = '';getDefaultStore().set(parentViewAtom, undefined);getDefaultStore().set(currentWorkspaceMemberState.atom, null);});@@ -273,6 +289,12 @@ describe('useFrontComponentExecutionContext', () => {timelineActivityId: null,colorScheme: 'light',locale: i18n.locale as AppLocale,+ location: {+ pathname: '/',+ search: '',+ hash: '',+ origin: window.location.origin,+ },});});@@ -311,6 +333,62 @@ describe('useFrontComponentExecutionContext', () => {timelineActivityId: null,colorScheme: 'light',locale: i18n.locale as AppLocale,+ location: {+ pathname: '/',+ search: '',+ hash: '',+ origin: window.location.origin,+ },+ });+ });++ it('should expose the URL pathname, query string, hash and the app origin', () => {+ mockLocationSearch = '?project=abc&tab=2';+ mockLocationPathname = '/page/page-record-id';+ mockLocationHash = '#details';++ const { result } = renderUseFrontComponentExecutionContext({+ frontComponentId: FRONT_COMPONENT_ID,+ });++ expect(result.current.executionContext.location).toEqual({+ pathname: '/page/page-record-id',+ search: '?project=abc&tab=2',+ hash: '#details',+ origin: window.location.origin,+ });+ });++ it('should update the location when the host route changes', () => {+ const { result, rerender } = renderUseFrontComponentExecutionContext({+ frontComponentId: FRONT_COMPONENT_ID,+ });++ mockLocationPathname = '/page/page-record-id';+ mockLocationSearch = '?project=abc';+ rerender();++ expect(result.current.executionContext.location).toEqual({+ pathname: '/page/page-record-id',+ search: '?project=abc',+ hash: '',+ origin: window.location.origin,+ });+ });++ it('should update the location when only the hash changes', () => {+ const { result, rerender } = renderUseFrontComponentExecutionContext({+ frontComponentId: FRONT_COMPONENT_ID,+ });++ mockLocationHash = '#details';+ rerender();++ expect(result.current.executionContext.location).toEqual({+ pathname: '/',+ search: '',+ hash: '#details',+ origin: window.location.origin,});});diff --git a/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.tsindex 4f458b97e9d..2464802e778 100644--- a/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts+++ b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts@@ -7,6 +7,7 @@ import { type FrontComponentToolCall } from 'twenty-sdk/front-component';import { useLingui } from '@lingui/react/macro';import { isNonEmptyString } from '@sniptt/guards';import { useRef } from 'react';+import { useLocation } from 'react-router-dom';import {buildFrontComponentStorageNamespace,clearFrontComponentStorage,@@ -148,6 +149,7 @@ export const useFrontComponentExecutionContext = ({} => {const currentUser = useAtomStateValue(currentUserState);const navigateApp = useNavigateApp();+ const location = useLocation();const store = useStore();const { requestApplicationAccessTokenRefresh } =useFrontComponentApplicationTokenPair();@@ -471,6 +473,12 @@ export const useFrontComponentExecutionContext = ({colorScheme,// The host is always configured with APP_LOCALES, so this is a valid AppLocale.locale: i18n.locale as AppLocale,+ location: {+ pathname: location.pathname,+ search: location.search,+ hash: location.hash,+ origin: window.location.origin,+ },};const unmountFrontComponent: FrontComponentHostCommunicationApi['unmountFrontComponent'] =diff --git a/packages/twenty-sdk/src/sdk/front-component/hooks/useLocation.ts b/packages/twenty-sdk/src/sdk/front-component/hooks/useLocation.tsnew file mode 100644index 00000000000..83dd37cfcba--- /dev/null+++ b/packages/twenty-sdk/src/sdk/front-component/hooks/useLocation.ts@@ -0,0 +1,11 @@+import { type FrontComponentExecutionContext } from '../types/FrontComponentExecutionContext';+import { type FrontComponentLocation } from '../types/FrontComponentLocation';+import { useFrontComponentExecutionContext } from './useFrontComponentExecutionContext';++const selectLocation = (+ context: FrontComponentExecutionContext,+): FrontComponentLocation | null => context.location ?? null;++export const useLocation = (): FrontComponentLocation | null => {+ return useFrontComponentExecutionContext(selectLocation);+};diff --git a/packages/twenty-sdk/src/sdk/front-component/index.ts b/packages/twenty-sdk/src/sdk/front-component/index.tsindex 2aeb2ed8aa1..21c34c13894 100644--- a/packages/twenty-sdk/src/sdk/front-component/index.ts+++ b/packages/twenty-sdk/src/sdk/front-component/index.ts@@ -16,6 +16,7 @@ export { useFrontComponentId } from './hooks/useFrontComponentId';export { useTranslate } from './hooks/useTranslate';export type { UseTranslateResult } from './hooks/useTranslate';export { useLocale } from './hooks/useLocale';+export { useLocation } from './hooks/useLocation';export { useRecordId } from './hooks/useRecordId';export { useToolCall } from './hooks/useToolCall';export { useSelectedRecordIds } from './hooks/useSelectedRecordIds';@@ -30,6 +31,7 @@ export type {TranslationValues,} from './translations/message';export type { FrontComponentExecutionContext } from './types/FrontComponentExecutionContext';+export type { FrontComponentLocation } from './types/FrontComponentLocation';export type { FrontComponentSelectedObjectMetadata } from './types/FrontComponentSelectedObjectMetadata';export type { FrontComponentToolCall } from './types/FrontComponentToolCall';export type { FrontComponentToolCallStatus } from './types/FrontComponentToolCallStatus';diff --git a/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentExecutionContext.ts b/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentExecutionContext.tsindex 866bab59dff..00d17c8a390 100644--- a/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentExecutionContext.ts+++ b/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentExecutionContext.ts@@ -1,6 +1,7 @@import { type AppLocale } from 'twenty-shared/translations';import { type RecordGqlOperationFilter } from 'twenty-shared/types';+import { type FrontComponentLocation } from './FrontComponentLocation';import { type FrontComponentSelectedObjectMetadata } from './FrontComponentSelectedObjectMetadata';import { type FrontComponentToolCall } from './FrontComponentToolCall';@@ -23,6 +24,7 @@ export type FrontComponentExecutionContext = {/** Resolved color scheme of the host UI ('System' is already resolved) */colorScheme: 'light' | 'dark';locale?: AppLocale;+ location?: FrontComponentLocation;/** Set when the component renders an AI chat tool call */toolCall?: FrontComponentToolCall;};diff --git a/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentLocation.ts b/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentLocation.tsnew file mode 100644index 00000000000..cd2306188de--- /dev/null+++ b/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentLocation.ts@@ -0,0 +1,6 @@+export type FrontComponentLocation = {+ pathname: string;+ search: string;+ hash: string;+ origin: string;+};