i18n - docs translations (#18546)
Created by Github action --------- Co-authored-by: github-actions <github-actions@twenty.com>
This commit is contained in:
committed by
GitHub
parent
0fe7e9d5fe
commit
f855dacec9
@@ -837,20 +837,20 @@ export default defineFrontComponent({
|
||||
* **مُنشأ بالقالب**: شغّل `yarn twenty entity:add` واختر خيار إضافة مكوّن أمامي جديد.
|
||||
* **يدوي**: أنشئ ملفًا جديدًا `.tsx` واستخدم `defineFrontComponent()` مع اتباع النمط نفسه.
|
||||
|
||||
#### Where front components can be used
|
||||
#### أين يمكن استخدام مكوّنات الواجهة الأمامية
|
||||
|
||||
Front components can render in two locations within Twenty:
|
||||
يمكن عرض مكوّنات الواجهة الأمامية في موقعين داخل Twenty:
|
||||
|
||||
* **Side panel** — Non-headless front components open in the right-hand side panel. This is the default behavior when a front component is triggered from the command menu.
|
||||
* **Widgets (dashboards and record pages)** — Front components can be embedded as widgets inside page layouts. When configuring a dashboard or a record page layout, users can add a front component widget.
|
||||
* **اللوحة الجانبية** — المكوّنات غير عديمة الرأس تفتح في اللوحة الجانبية اليمنى. هذا هو السلوك الافتراضي عندما يتم تشغيل مكوّن واجهة أمامية من قائمة الأوامر.
|
||||
* **الويدجت (لوحات المعلومات وصفحات السجلات)** — يمكن تضمين مكوّنات الواجهة الأمامية كويدجت داخل تخطيطات الصفحات. عند تكوين لوحة معلومات أو تخطيط صفحة سجل، يمكن للمستخدمين إضافة ويدجت لمكوّن واجهة أمامية.
|
||||
|
||||
#### Headless vs non-headless
|
||||
#### عديم الرأس مقابل غير عديم الرأس
|
||||
|
||||
Front components come in two rendering modes controlled by the `isHeadless` option:
|
||||
تأتي مكوّنات الواجهة الأمامية بوضعَي عرض يتحكّم بهما الخيار `isHeadless`:
|
||||
|
||||
**Non-headless (default)** — The component renders a visible UI. When triggered from the command menu it opens in the side panel. This is the default behavior when `isHeadless` is `false` or omitted.
|
||||
**غير عديم الرأس (افتراضي)** — يعرض المكوّن واجهة مستخدم مرئية. عند تشغيله من قائمة الأوامر يفتح في اللوحة الجانبية. هذا هو السلوك الافتراضي عندما تكون `isHeadless` تساوي `false` أو يتم تجاهلها.
|
||||
|
||||
**Headless** — The component mounts invisibly in the background. It does not open the side panel. Headless components are designed for actions that execute logic and then unmount themselves — for example, running an async task, navigating to a page, or showing a confirmation modal. They pair naturally with the SDK Command components described below.
|
||||
**عديم الرأس** — يتم تركيب المكوّن بشكل غير مرئي في الخلفية. لا يفتح اللوحة الجانبية. تم تصميم المكوّنات عديمة الرأس لإجراءات تنفّذ منطقًا ثم تُزيل تركيبها ذاتيًا — على سبيل المثال، تشغيل مهمة غير متزامنة، أو الانتقال إلى صفحة، أو إظهار نافذة تأكيد منبثقة. تتوافق بشكل طبيعي مع مكوّنات Command في SDK الموصوفة أدناه.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
@@ -866,22 +866,22 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Adding command menu items
|
||||
#### إضافة عناصر قائمة الأوامر
|
||||
|
||||
To make a front component appear as an item in Twenty's command menu, add the `command` property to `defineFrontComponent()`. When users open the command menu (Cmd+K / Ctrl+K), the item shows up and triggers the front component on click.
|
||||
لجعل مكوّن واجهة أمامية يظهر كعنصر في قائمة الأوامر في Twenty، أضف الخاصية `command` إلى `defineFrontComponent()`. عند فتح المستخدمين لقائمة الأوامر (Cmd+K / Ctrl+K)، يظهر العنصر ويشغّل مكوّن الواجهة الأمامية عند النقر.
|
||||
|
||||
The `command` object accepts the following fields:
|
||||
يقبل كائن `command` الحقول التالية:
|
||||
|
||||
| الحقل | النوع | الوصف |
|
||||
| --------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `universalIdentifier` | `string` (required) | Unique ID for the command menu item |
|
||||
| `التسمية` | `string` (required) | Display label shown in the command menu |
|
||||
| `أيقونة` | `string` (optional) | Icon name (e.g., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (optional) | Whether the command is pinned at the top of the menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` shows the command everywhere; `RECORD_SELECTION` shows it only in record contexts |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Restrict the command to a specific object type (e.g., Person) |
|
||||
| الحقل | النوع | الوصف |
|
||||
| --------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------- |
|
||||
| `universalIdentifier` | `string` (إلزامي) | معرّف فريد لعنصر قائمة الأوامر |
|
||||
| `التسمية` | `string` (إلزامي) | التسمية المعروضة في قائمة الأوامر |
|
||||
| `أيقونة` | `string` (اختياري) | اسم الأيقونة (مثال: `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (اختياري) | ما إذا كان الأمر مثبتًا أعلى القائمة |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (اختياري) | `GLOBAL` يعرض الأمر في كل مكان؛ `RECORD_SELECTION` يعرضه فقط في سياقات السجلّات |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (اختياري) | تقييد الأمر بنوع كائن محدّد (مثال: Person) |
|
||||
|
||||
Here is an example from the call-recording app that adds a command scoped to Person records:
|
||||
إليك مثالًا من تطبيق تسجيل المكالمات يضيف أمرًا محصورًا بسجلات Person:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
@@ -903,20 +903,20 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
When the command is synced, it appears in the command menu. If the front component is non-headless the side panel opens with the component rendered inside. If it is headless the component mounts in the background and executes its logic.
|
||||
عند مزامنة الأمر، يظهر في قائمة الأوامر. إذا كان مكوّن الواجهة الأمامية غير عديم الرأس، تُفتح اللوحة الجانبية مع عرض المكوّن بداخلها. إذا كان عديم الرأس، فسيتم تركيب المكوّن في الخلفية وتنفيذ منطقه.
|
||||
|
||||
#### SDK Command components
|
||||
#### مكوّنات Command في SDK
|
||||
|
||||
The `twenty-sdk` package provides four Command helper components designed for headless front components. Each component executes an action on mount, handles errors by showing a snackbar notification, and automatically unmounts the front component when done.
|
||||
توفر حزمة `twenty-sdk` أربعة مكوّنات مساعدة من نوع Command مصممة للمكوّنات عديمة الرأس في الواجهة الأمامية. كل مكوّن ينفّذ إجراءً عند التركيب، ويتعامل مع الأخطاء بعرض إشعار Snackbar، ويزيل تركيب مكوّن الواجهة الأمامية تلقائيًا عند الانتهاء.
|
||||
|
||||
Import them from `twenty-sdk/command`:
|
||||
استوردها من `twenty-sdk/command`:
|
||||
|
||||
* **`Command`** — Runs an async callback via the `execute` prop.
|
||||
* **`CommandLink`** — Navigates to an app path. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Opens a confirmation modal. If the user confirms, executes the `execute` callback. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Opens a specific side panel page. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
* **`Command`** — يشغّل رد نداء غير متزامن عبر الخاصية `execute`.
|
||||
* **`CommandLink`** — ينتقل إلى مسار في التطبيق. الخصائص: `to`، `params`، `queryParams`، `options`.
|
||||
* **`CommandModal`** — يفتح نافذة تأكيد منبثقة. إذا أكّد المستخدم، ينفّذ رد النداء `execute`. الخصائص: `title`، `subtitle`، `execute`، `confirmButtonText`، `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — يفتح صفحة محدّدة في اللوحة الجانبية. الخصائص: `page`، `pageTitle`، `pageIcon`.
|
||||
|
||||
Here is a full example of a headless front component using `Command` to run an action from the command menu:
|
||||
فيما يلي مثال كامل لمكوّن واجهة أمامية عديم الرأس يستخدم `Command` لتشغيل إجراء من قائمة الأوامر:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
@@ -953,7 +953,7 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
And an example using `CommandModal` to ask for confirmation before executing:
|
||||
ومثال يستخدم `CommandModal` لطلب التأكيد قبل التنفيذ:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
@@ -990,15 +990,15 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Execution context
|
||||
#### سياق التنفيذ
|
||||
|
||||
Every front component receives an execution context that provides information about where and how it is running. Access context values using hooks from `twenty-sdk`:
|
||||
يتلقّى كل مكوّن واجهة أمامية سياق تنفيذ يوفّر معلومات حول مكان وكيفية تشغيله. يمكنك الوصول إلى قيم السياق باستخدام الخطافات من `twenty-sdk`:
|
||||
|
||||
| Hook | Return type | الوصف |
|
||||
| ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | The unique ID of the current front component instance |
|
||||
| `useRecordId()` | `string \| null` | The ID of the current record, when the component runs in a record context (e.g., a record page widget or a command scoped to a record). Returns `null` otherwise. |
|
||||
| `useUserId()` | `string \| null` | The ID of the current user |
|
||||
| الخطّاف | نوع القيمة المرجعة | الوصف |
|
||||
| ----------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | المعرّف الفريد لمثيل مكوّن الواجهة الأمامية الحالي |
|
||||
| `useRecordId()` | `string \| null` | معرّف السجل الحالي، عندما يعمل المكوّن في سياق سجل (مثال: ويدجت صفحة سجل أو أمر محصور بسجل). يُرجع `null` خلاف ذلك. |
|
||||
| `useUserId()` | `string \| null` | معرّف المستخدم الحالي |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
@@ -1016,11 +1016,11 @@ const MyWidget = () => {
|
||||
};
|
||||
```
|
||||
|
||||
The context is reactive — if the surrounding record changes, hooks automatically return the updated values.
|
||||
السياق تفاعلي — إذا تغيّر السجل المحيط، فستُرجع الخطافات القيم المحدّثة تلقائيًا.
|
||||
|
||||
#### Host API functions
|
||||
#### دوال واجهة برمجة تطبيقات المضيف
|
||||
|
||||
Front components run in an isolated sandbox but can interact with Twenty's UI through a set of functions provided by the host. Import them directly from `twenty-sdk`:
|
||||
تعمل مكوّنات الواجهة الأمامية في بيئة معزولة، لكنها تستطيع التفاعل مع واجهة مستخدم Twenty عبر مجموعة من الدوال التي يوفّرها المضيف. استوردها مباشرةً من `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
@@ -1033,16 +1033,16 @@ import {
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| دالة | Signature | الوصف |
|
||||
| ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `التنقل` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigate to a typed app path within Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Close the side panel |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Show a snackbar notification. Params: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Unmount the current front component (used by headless components to clean up after execution) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Open a page in the side panel. Params: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Show a confirmation modal and wait for the user's response. Params: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
| دالة | التوقيع | الوصف |
|
||||
| ------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `التنقل` | `(to, params?, queryParams?, options?) => Promise<void>` | الانتقال إلى مسار تطبيق محدّد النوع داخل Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | إغلاق اللوحة الجانبية |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | عرض إشعار Snackbar. المعاملات: `message`، `variant` (`'error'`، `'success'`، `'info'`، `'warning'`)، `duration` اختياري، `detailedMessage`، `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | إلغاء تركيب مكوّن الواجهة الأمامية الحالي (تستخدمه المكوّنات عديمة الرأس للتنظيف بعد التنفيذ) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | فتح صفحة في اللوحة الجانبية. المعاملات: `page`، `pageTitle`، `pageIcon`، `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | عرض نافذة تأكيد منبثقة والانتظار لرد المستخدم. المعاملات: `title`، `subtitle`، `confirmButtonText`، `confirmButtonAccent` (`'default'`، `'blue'`، `'danger'`) |
|
||||
|
||||
Here is an example that uses the host API to show a snackbar and close the side panel after an action completes:
|
||||
فيما يلي مثال يستخدم واجهة برمجة تطبيقات المضيف لعرض Snackbar وإغلاق اللوحة الجانبية بعد اكتمال الإجراء:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
|
||||
@@ -837,20 +837,20 @@ Sie können neue Frontend-Komponenten auf zwei Arten erstellen:
|
||||
* **Generiert**: Führen Sie `yarn twenty entity:add` aus und wählen Sie die Option zum Hinzufügen einer neuen Frontend-Komponente.
|
||||
* **Manuell**: Erstellen Sie eine neue `.tsx`-Datei und verwenden Sie `defineFrontComponent()` nach demselben Muster.
|
||||
|
||||
#### Where front components can be used
|
||||
#### Wo Front-Komponenten verwendet werden können
|
||||
|
||||
Front components can render in two locations within Twenty:
|
||||
Front-Komponenten können an zwei Stellen innerhalb von Twenty gerendert werden:
|
||||
|
||||
* **Side panel** — Non-headless front components open in the right-hand side panel. This is the default behavior when a front component is triggered from the command menu.
|
||||
* **Widgets (dashboards and record pages)** — Front components can be embedded as widgets inside page layouts. When configuring a dashboard or a record page layout, users can add a front component widget.
|
||||
* **Seitenpanel** — Nicht-Headless-Front-Komponenten werden im rechten Seitenpanel geöffnet. Dies ist das Standardverhalten, wenn eine Front-Komponente über das Befehlsmenü ausgelöst wird.
|
||||
* **Widgets (Dashboards und Datensatzseiten)** — Front-Komponenten können als Widgets in Seitenlayouts eingebettet werden. Beim Konfigurieren eines Dashboards oder eines Datensatzseiten-Layouts können Benutzer ein Front-Komponenten-Widget hinzufügen.
|
||||
|
||||
#### Headless vs non-headless
|
||||
#### Headless vs. Nicht-Headless
|
||||
|
||||
Front components come in two rendering modes controlled by the `isHeadless` option:
|
||||
Front-Komponenten gibt es in zwei Rendering-Modi, die durch die Option `isHeadless` gesteuert werden:
|
||||
|
||||
**Non-headless (default)** — The component renders a visible UI. When triggered from the command menu it opens in the side panel. This is the default behavior when `isHeadless` is `false` or omitted.
|
||||
**Nicht-Headless (Standard)** — Die Komponente rendert eine sichtbare UI. Wird sie über das Befehlsmenü ausgelöst, öffnet sie sich im Seitenpanel. Dies ist das Standardverhalten, wenn `isHeadless` `false` ist oder weggelassen wird.
|
||||
|
||||
**Headless** — The component mounts invisibly in the background. It does not open the side panel. Headless components are designed for actions that execute logic and then unmount themselves — for example, running an async task, navigating to a page, or showing a confirmation modal. They pair naturally with the SDK Command components described below.
|
||||
**Headless** — Die Komponente wird unsichtbar im Hintergrund gemountet. Sie öffnet das Seitenpanel nicht. Headless-Komponenten sind für Aktionen konzipiert, die Logik ausführen und sich anschließend selbst unmounten — zum Beispiel das Ausführen einer asynchronen Aufgabe, das Navigieren zu einer Seite oder das Anzeigen eines Bestätigungsdialogs. Sie lassen sich gut mit den unten beschriebenen SDK-Command-Komponenten kombinieren.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
@@ -866,22 +866,22 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Adding command menu items
|
||||
#### Befehlsmenü-Einträge hinzufügen
|
||||
|
||||
To make a front component appear as an item in Twenty's command menu, add the `command` property to `defineFrontComponent()`. When users open the command menu (Cmd+K / Ctrl+K), the item shows up and triggers the front component on click.
|
||||
Damit eine Front-Komponente als Eintrag im Befehlsmenü von Twenty erscheint, fügen Sie die Eigenschaft `command` zu `defineFrontComponent()` hinzu. Wenn Benutzer das Befehlsmenü öffnen (Cmd+K / Ctrl+K), erscheint der Eintrag und löst beim Klicken die Front-Komponente aus.
|
||||
|
||||
The `command` object accepts the following fields:
|
||||
Das Objekt `command` akzeptiert die folgenden Felder:
|
||||
|
||||
| Feld | Typ | Beschreibung |
|
||||
| --------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `universalIdentifier` | `string` (required) | Unique ID for the command menu item |
|
||||
| `beschriftung` | `string` (required) | Display label shown in the command menu |
|
||||
| `symbol` | `string` (optional) | Icon name (e.g., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (optional) | Whether the command is pinned at the top of the menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` shows the command everywhere; `RECORD_SELECTION` shows it only in record contexts |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Restrict the command to a specific object type (e.g., Person) |
|
||||
| Feld | Typ | Beschreibung |
|
||||
| --------------------------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------------- |
|
||||
| `universalIdentifier` | `string` (erforderlich) | Eindeutige ID für den Befehlsmenü-Eintrag |
|
||||
| `beschriftung` | `string` (erforderlich) | Angezeigtes Label im Befehlsmenü |
|
||||
| `symbol` | `string` (optional) | Iconname (z. B. 'IconSparkles') |
|
||||
| `isPinned` | `boolean` (optional) | Ob der Befehl oben im Menü angeheftet ist |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` zeigt den Befehl überall an; `RECORD_SELECTION` zeigt ihn nur in Datensatzkontexten an |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Beschränkt den Befehl auf einen bestimmten Objekttyp (z. B. Person) |
|
||||
|
||||
Here is an example from the call-recording app that adds a command scoped to Person records:
|
||||
Hier ist ein Beispiel aus der Call-Recording-App, das einen auf Person-Datensätze beschränkten Befehl hinzufügt:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
@@ -903,20 +903,20 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
When the command is synced, it appears in the command menu. If the front component is non-headless the side panel opens with the component rendered inside. If it is headless the component mounts in the background and executes its logic.
|
||||
Wenn der Befehl synchronisiert wird, erscheint er im Befehlsmenü. Wenn die Front-Komponente Nicht-Headless ist, öffnet sich das Seitenpanel und die Komponente wird darin gerendert. Wenn sie Headless ist, wird die Komponente im Hintergrund gemountet und führt ihre Logik aus.
|
||||
|
||||
#### SDK Command components
|
||||
#### SDK-Command-Komponenten
|
||||
|
||||
The `twenty-sdk` package provides four Command helper components designed for headless front components. Each component executes an action on mount, handles errors by showing a snackbar notification, and automatically unmounts the front component when done.
|
||||
Das Paket `twenty-sdk` stellt vier Command-Hilfskomponenten bereit, die für Headless-Front-Komponenten ausgelegt sind. Jede Komponente führt beim Mounten eine Aktion aus, behandelt Fehler durch Anzeige einer Snackbar-Benachrichtigung und unmountet die Front-Komponente nach Abschluss automatisch.
|
||||
|
||||
Import them from `twenty-sdk/command`:
|
||||
Importieren Sie sie aus `twenty-sdk/command`:
|
||||
|
||||
* **`Command`** — Runs an async callback via the `execute` prop.
|
||||
* **`CommandLink`** — Navigates to an app path. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Opens a confirmation modal. If the user confirms, executes the `execute` callback. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Opens a specific side panel page. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
* **`Command`** — Führt einen asynchronen Callback über das Prop `execute` aus.
|
||||
* **`CommandLink`** — Navigiert zu einem App-Pfad. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Öffnet einen Bestätigungsdialog. Bestätigt der Benutzer, wird der Callback `execute` ausgeführt. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Öffnet eine bestimmte Seite im Seitenpanel. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
|
||||
Here is a full example of a headless front component using `Command` to run an action from the command menu:
|
||||
Hier ist ein vollständiges Beispiel einer Headless-Front-Komponente, die `Command` verwendet, um eine Aktion aus dem Befehlsmenü auszuführen:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
@@ -953,7 +953,7 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
And an example using `CommandModal` to ask for confirmation before executing:
|
||||
Und ein Beispiel, das `CommandModal` verwendet, um vor der Ausführung um Bestätigung zu bitten:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
@@ -990,15 +990,15 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Execution context
|
||||
#### Ausführungskontext
|
||||
|
||||
Every front component receives an execution context that provides information about where and how it is running. Access context values using hooks from `twenty-sdk`:
|
||||
Jede Front-Komponente erhält einen Ausführungskontext, der Informationen darüber liefert, wo und wie sie ausgeführt wird. Greifen Sie mit Hooks aus `twenty-sdk` auf Kontextwerte zu:
|
||||
|
||||
| Hook | Return type | Beschreibung |
|
||||
| ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | The unique ID of the current front component instance |
|
||||
| `useRecordId()` | `string \| null` | The ID of the current record, when the component runs in a record context (e.g., a record page widget or a command scoped to a record). Returns `null` otherwise. |
|
||||
| `useUserId()` | `string \| null` | The ID of the current user |
|
||||
| Hook | Rückgabetyp | Beschreibung |
|
||||
| ----------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `useFrontComponentId()` | `string` | Die eindeutige ID der aktuellen Front-Komponenteninstanz |
|
||||
| `useRecordId()` | `string \| null` | Die ID des aktuellen Datensatzes, wenn die Komponente in einem Datensatzkontext ausgeführt wird (z. B. ein Widget auf einer Datensatzseite oder ein auf einen Datensatz beschränkter Befehl). Andernfalls wird `null` zurückgegeben. |
|
||||
| `useUserId()` | `string \| null` | Die ID des aktuellen Benutzers |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
@@ -1016,11 +1016,11 @@ const MyWidget = () => {
|
||||
};
|
||||
```
|
||||
|
||||
The context is reactive — if the surrounding record changes, hooks automatically return the updated values.
|
||||
Der Kontext ist reaktiv — ändert sich der umgebende Datensatz, liefern die Hooks automatisch die aktualisierten Werte.
|
||||
|
||||
#### Host API functions
|
||||
#### Host-API-Funktionen
|
||||
|
||||
Front components run in an isolated sandbox but can interact with Twenty's UI through a set of functions provided by the host. Import them directly from `twenty-sdk`:
|
||||
Front-Komponenten laufen in einer isolierten Sandbox, können jedoch über eine Reihe vom Host bereitgestellter Funktionen mit der UI von Twenty interagieren. Importieren Sie sie direkt aus `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
@@ -1033,16 +1033,16 @@ import {
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| Funktion | Signature | Beschreibung |
|
||||
| ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `navigieren` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigate to a typed app path within Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Close the side panel |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Show a snackbar notification. Params: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Unmount the current front component (used by headless components to clean up after execution) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Open a page in the side panel. Params: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Show a confirmation modal and wait for the user's response. Params: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
| Funktion | Signatur | Beschreibung |
|
||||
| ------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `navigieren` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigieren Sie zu einem typisierten App-Pfad innerhalb von Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Seitenpanel schließen |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Eine Snackbar-Benachrichtigung anzeigen. Parameter: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Die aktuelle Front-Komponente unmounten (wird von Headless-Komponenten verwendet, um nach der Ausführung aufzuräumen) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Eine Seite im Seitenpanel öffnen. Parameter: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Einen Bestätigungsdialog anzeigen und auf die Antwort des Benutzers warten. Parameter: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
|
||||
Here is an example that uses the host API to show a snackbar and close the side panel after an action completes:
|
||||
Hier ist ein Beispiel, das die Host-API verwendet, um nach Abschluss einer Aktion eine Snackbar anzuzeigen und das Seitenpanel zu schließen:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
|
||||
@@ -837,20 +837,20 @@ Puoi creare nuovi componenti front-end in due modi:
|
||||
* **Generata dallo scaffolder**: Esegui `yarn twenty entity:add` e scegli l'opzione per aggiungere un nuovo componente front-end.
|
||||
* **Manuale**: Crea un nuovo file `.tsx` e usa `defineFrontComponent()`, seguendo lo stesso schema.
|
||||
|
||||
#### Where front components can be used
|
||||
#### Dove possono essere utilizzati i componenti front.
|
||||
|
||||
Front components can render in two locations within Twenty:
|
||||
I componenti front possono essere renderizzati in due posizioni all'interno di Twenty:
|
||||
|
||||
* **Side panel** — Non-headless front components open in the right-hand side panel. This is the default behavior when a front component is triggered from the command menu.
|
||||
* **Widgets (dashboards and record pages)** — Front components can be embedded as widgets inside page layouts. When configuring a dashboard or a record page layout, users can add a front component widget.
|
||||
* **Pannello laterale** — I componenti front non headless si aprono nel pannello laterale destro. Questo è il comportamento predefinito quando un componente front viene avviato dal menu comandi.
|
||||
* **Widget (dashboard e pagine dei record)** — I componenti front possono essere incorporati come widget all'interno dei layout di pagina. Quando si configura una dashboard o il layout di una pagina record, gli utenti possono aggiungere un widget del componente front.
|
||||
|
||||
#### Headless vs non-headless
|
||||
#### Headless vs non headless
|
||||
|
||||
Front components come in two rendering modes controlled by the `isHeadless` option:
|
||||
I componenti front prevedono due modalità di rendering controllate dall'opzione `isHeadless`:
|
||||
|
||||
**Non-headless (default)** — The component renders a visible UI. When triggered from the command menu it opens in the side panel. This is the default behavior when `isHeadless` is `false` or omitted.
|
||||
**Non headless (predefinito)** — Il componente renderizza un'interfaccia utente visibile. Quando viene avviato dal menu comandi, si apre nel pannello laterale. Questo è il comportamento predefinito quando `isHeadless` è `false` o omesso.
|
||||
|
||||
**Headless** — The component mounts invisibly in the background. It does not open the side panel. Headless components are designed for actions that execute logic and then unmount themselves — for example, running an async task, navigating to a page, or showing a confirmation modal. They pair naturally with the SDK Command components described below.
|
||||
**Headless** — Il componente viene montato in modo invisibile in background. Non apre il pannello laterale. I componenti headless sono pensati per azioni che eseguono una logica e poi si smontano — ad esempio, eseguire un'attività asincrona, navigare a una pagina o mostrare una finestra modale di conferma. Si abbinano naturalmente ai componenti Command dell'SDK descritti di seguito.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
@@ -866,22 +866,22 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Adding command menu items
|
||||
#### Aggiungere voci al menu comandi
|
||||
|
||||
To make a front component appear as an item in Twenty's command menu, add the `command` property to `defineFrontComponent()`. When users open the command menu (Cmd+K / Ctrl+K), the item shows up and triggers the front component on click.
|
||||
Per far comparire un componente front come voce nel menu comandi di Twenty, aggiungi la proprietà `command` a `defineFrontComponent()`. Quando gli utenti aprono il menu comandi (Cmd+K / Ctrl+K), la voce viene mostrata e al clic attiva il componente front.
|
||||
|
||||
The `command` object accepts the following fields:
|
||||
L'oggetto `command` accetta i seguenti campi:
|
||||
|
||||
| Campo | Tipo | Descrizione |
|
||||
| --------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `universalIdentifier` | `string` (required) | Unique ID for the command menu item |
|
||||
| `etichetta` | `string` (required) | Display label shown in the command menu |
|
||||
| `icona` | `string` (optional) | Icon name (e.g., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (optional) | Whether the command is pinned at the top of the menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` shows the command everywhere; `RECORD_SELECTION` shows it only in record contexts |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Restrict the command to a specific object type (e.g., Person) |
|
||||
| Campo | Tipo | Descrizione |
|
||||
| --------------------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------- |
|
||||
| `universalIdentifier` | `string` (obbligatorio) | ID univoco per la voce del menu comandi |
|
||||
| `etichetta` | `string` (obbligatorio) | Etichetta visualizzata nel menu comandi |
|
||||
| `icona` | `string` (facoltativo) | Nome dell'icona (ad es., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (facoltativo) | Indica se il comando è fissato in alto nel menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (facoltativo) | `GLOBAL` mostra il comando ovunque; `RECORD_SELECTION` lo mostra solo nei contesti dei record |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (facoltativo) | Limita il comando a uno specifico tipo di oggetto (ad es., Person) |
|
||||
|
||||
Here is an example from the call-recording app that adds a command scoped to Person records:
|
||||
Ecco un esempio dall'app di registrazione delle chiamate che aggiunge un comando limitato ai record Person:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
@@ -903,20 +903,20 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
When the command is synced, it appears in the command menu. If the front component is non-headless the side panel opens with the component rendered inside. If it is headless the component mounts in the background and executes its logic.
|
||||
Quando il comando viene sincronizzato, appare nel menu comandi. Se il componente front è non headless, si apre il pannello laterale con il componente renderizzato al suo interno. Se è headless, il componente viene montato in background ed esegue la propria logica.
|
||||
|
||||
#### SDK Command components
|
||||
#### Componenti Command dell'SDK
|
||||
|
||||
The `twenty-sdk` package provides four Command helper components designed for headless front components. Each component executes an action on mount, handles errors by showing a snackbar notification, and automatically unmounts the front component when done.
|
||||
Il pacchetto `twenty-sdk` fornisce quattro componenti di supporto Command progettati per i componenti front headless. Ogni componente esegue un'azione al montaggio, gestisce gli errori mostrando una notifica snackbar e smonta automaticamente il componente front al termine.
|
||||
|
||||
Import them from `twenty-sdk/command`:
|
||||
Importali da `twenty-sdk/command`:
|
||||
|
||||
* **`Command`** — Runs an async callback via the `execute` prop.
|
||||
* **`CommandLink`** — Navigates to an app path. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Opens a confirmation modal. If the user confirms, executes the `execute` callback. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Opens a specific side panel page. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
* **`Command`** — Esegue una callback asincrona tramite la prop `execute`.
|
||||
* **`CommandLink`** — Naviga verso un percorso dell'app. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Apre una finestra modale di conferma. Se l'utente conferma, esegue la callback `execute`. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Apre una specifica pagina del pannello laterale. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
|
||||
Here is a full example of a headless front component using `Command` to run an action from the command menu:
|
||||
Ecco un esempio completo di componente front headless che usa `Command` per eseguire un'azione dal menu comandi:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
@@ -953,7 +953,7 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
And an example using `CommandModal` to ask for confirmation before executing:
|
||||
E un esempio che usa `CommandModal` per chiedere conferma prima di eseguire:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
@@ -990,15 +990,15 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Execution context
|
||||
#### Contesto di esecuzione
|
||||
|
||||
Every front component receives an execution context that provides information about where and how it is running. Access context values using hooks from `twenty-sdk`:
|
||||
Ogni componente front riceve un contesto di esecuzione che fornisce informazioni su dove e come sta funzionando. Accedi ai valori del contesto usando gli hook di `twenty-sdk`:
|
||||
|
||||
| Hook | Return type | Descrizione |
|
||||
| ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | The unique ID of the current front component instance |
|
||||
| `useRecordId()` | `string \| null` | The ID of the current record, when the component runs in a record context (e.g., a record page widget or a command scoped to a record). Returns `null` otherwise. |
|
||||
| `useUserId()` | `string \| null` | The ID of the current user |
|
||||
| Hook | Tipo restituito | Descrizione |
|
||||
| ----------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | L'ID univoco dell'istanza corrente del componente front |
|
||||
| `useRecordId()` | `string \| null` | L'ID del record corrente, quando il componente viene eseguito in un contesto di record (ad es., un widget di pagina record o un comando con ambito a un record). In caso contrario, restituisce `null`. |
|
||||
| `useUserId()` | `string \| null` | L'ID dell'utente corrente |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
@@ -1016,11 +1016,11 @@ const MyWidget = () => {
|
||||
};
|
||||
```
|
||||
|
||||
The context is reactive — if the surrounding record changes, hooks automatically return the updated values.
|
||||
Il contesto è reattivo — se il record circostante cambia, gli hook restituiscono automaticamente i valori aggiornati.
|
||||
|
||||
#### Host API functions
|
||||
#### Funzioni dell'API host
|
||||
|
||||
Front components run in an isolated sandbox but can interact with Twenty's UI through a set of functions provided by the host. Import them directly from `twenty-sdk`:
|
||||
I componenti front vengono eseguiti in una sandbox isolata ma possono interagire con l'interfaccia di Twenty tramite un insieme di funzioni fornite dall'host. Importale direttamente da `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
@@ -1033,16 +1033,16 @@ import {
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| Funzione | Signature | Descrizione |
|
||||
| ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `naviga` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigate to a typed app path within Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Close the side panel |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Show a snackbar notification. Params: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Unmount the current front component (used by headless components to clean up after execution) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Open a page in the side panel. Params: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Show a confirmation modal and wait for the user's response. Params: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
| Funzione | Firma | Descrizione |
|
||||
| ------------------------------ | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `naviga` | `(to, params?, queryParams?, options?) => Promise<void>` | Naviga verso un percorso tipizzato dell'app all'interno di Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Chiudi il pannello laterale |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Mostra una notifica snackbar. Parametri: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), `duration` opzionale, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Smonta il componente front corrente (usato dai componenti headless per pulire dopo l'esecuzione) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Apri una pagina nel pannello laterale. Parametri: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Mostra una finestra modale di conferma e attende la risposta dell'utente. Parametri: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
|
||||
Here is an example that uses the host API to show a snackbar and close the side panel after an action completes:
|
||||
Ecco un esempio che usa l'API host per mostrare una snackbar e chiudere il pannello laterale dopo il completamento di un'azione:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
|
||||
@@ -838,20 +838,20 @@ Você pode criar novos componentes de front-end de duas formas:
|
||||
* **Gerado automaticamente**: Execute `yarn twenty entity:add` e escolha a opção para adicionar um novo componente de front-end.
|
||||
* **Manual**: Crie um novo ficheiro `.tsx` e use `defineFrontComponent()`, seguindo o mesmo padrão.
|
||||
|
||||
#### Where front components can be used
|
||||
#### Onde os componentes de front-end podem ser usados
|
||||
|
||||
Front components can render in two locations within Twenty:
|
||||
Os componentes de front-end podem ser renderizados em dois locais dentro do Twenty:
|
||||
|
||||
* **Side panel** — Non-headless front components open in the right-hand side panel. This is the default behavior when a front component is triggered from the command menu.
|
||||
* **Widgets (dashboards and record pages)** — Front components can be embedded as widgets inside page layouts. When configuring a dashboard or a record page layout, users can add a front component widget.
|
||||
* **Painel lateral** — Componentes de front-end não headless abrem no painel lateral direito. Este é o comportamento padrão quando um componente de front-end é acionado pelo menu de comandos.
|
||||
* **Widgets (painéis e páginas de registro)** — Componentes de front-end podem ser incorporados como widgets nos layouts de página. Ao configurar um painel ou o layout de uma página de registro, os usuários podem adicionar um widget de componente de front-end.
|
||||
|
||||
#### Headless vs non-headless
|
||||
#### Headless vs não headless
|
||||
|
||||
Front components come in two rendering modes controlled by the `isHeadless` option:
|
||||
Os componentes de front-end têm dois modos de renderização controlados pela opção `isHeadless`:
|
||||
|
||||
**Non-headless (default)** — The component renders a visible UI. When triggered from the command menu it opens in the side panel. This is the default behavior when `isHeadless` is `false` or omitted.
|
||||
**Não headless (padrão)** — O componente renderiza uma interface visível. Quando acionado pelo menu de comandos, ele é aberto no painel lateral. Este é o comportamento padrão quando `isHeadless` é `false` ou omitido.
|
||||
|
||||
**Headless** — The component mounts invisibly in the background. It does not open the side panel. Headless components are designed for actions that execute logic and then unmount themselves — for example, running an async task, navigating to a page, or showing a confirmation modal. They pair naturally with the SDK Command components described below.
|
||||
**Headless** — O componente é montado de forma invisível em segundo plano. Ele não abre o painel lateral. Componentes headless são projetados para ações que executam lógica e, em seguida, se desmontam — por exemplo, executar uma tarefa assíncrona, navegar para uma página ou exibir um modal de confirmação. Eles se combinam naturalmente com os componentes Command do SDK descritos abaixo.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
@@ -867,22 +867,22 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Adding command menu items
|
||||
#### Adicionando itens ao menu de comandos
|
||||
|
||||
To make a front component appear as an item in Twenty's command menu, add the `command` property to `defineFrontComponent()`. When users open the command menu (Cmd+K / Ctrl+K), the item shows up and triggers the front component on click.
|
||||
Para que um componente de front-end apareça como um item no menu de comandos do Twenty, adicione a propriedade `command` a `defineFrontComponent()`. Quando os usuários abrem o menu de comandos (Cmd+K / Ctrl+K), o item aparece e aciona o componente de front-end ao clicar.
|
||||
|
||||
The `command` object accepts the following fields:
|
||||
O objeto `command` aceita os seguintes campos:
|
||||
|
||||
| Campo | Tipo | Descrição |
|
||||
| --------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `universalIdentifier` | `string` (required) | Unique ID for the command menu item |
|
||||
| `etiqueta` | `string` (required) | Display label shown in the command menu |
|
||||
| `ícone` | `string` (optional) | Icon name (e.g., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (optional) | Whether the command is pinned at the top of the menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` shows the command everywhere; `RECORD_SELECTION` shows it only in record contexts |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Restrict the command to a specific object type (e.g., Person) |
|
||||
| Campo | Tipo | Descrição |
|
||||
| --------------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
||||
| `universalIdentifier` | `string` (obrigatório) | ID exclusivo para o item do menu de comandos |
|
||||
| `etiqueta` | `string` (obrigatório) | Rótulo exibido no menu de comandos |
|
||||
| `ícone` | `string` (opcional) | Nome do ícone (por exemplo, `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (opcional) | Se o comando fica fixado no topo do menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (opcional) | `GLOBAL` mostra o comando em todos os lugares; `RECORD_SELECTION` o mostra apenas em contextos de registro |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (opcional) | Restringe o comando a um tipo específico de objeto (por exemplo, Person) |
|
||||
|
||||
Here is an example from the call-recording app that adds a command scoped to Person records:
|
||||
Aqui está um exemplo do app de gravação de chamadas que adiciona um comando com escopo para registros de Person:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
@@ -904,20 +904,20 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
When the command is synced, it appears in the command menu. If the front component is non-headless the side panel opens with the component rendered inside. If it is headless the component mounts in the background and executes its logic.
|
||||
Quando o comando é sincronizado, ele aparece no menu de comandos. Se o componente de front-end não for headless, o painel lateral é aberto com o componente renderizado dentro. Se for headless, o componente é montado em segundo plano e executa sua lógica.
|
||||
|
||||
#### SDK Command components
|
||||
#### Componentes Command do SDK
|
||||
|
||||
The `twenty-sdk` package provides four Command helper components designed for headless front components. Each component executes an action on mount, handles errors by showing a snackbar notification, and automatically unmounts the front component when done.
|
||||
O pacote `twenty-sdk` fornece quatro componentes auxiliares Command projetados para componentes de front-end headless. Cada componente executa uma ação ao montar, trata erros exibindo uma notificação de snackbar e desmonta automaticamente o componente de front-end ao concluir.
|
||||
|
||||
Import them from `twenty-sdk/command`:
|
||||
Importe-os de `twenty-sdk/command`:
|
||||
|
||||
* **`Command`** — Runs an async callback via the `execute` prop.
|
||||
* **`CommandLink`** — Navigates to an app path. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Opens a confirmation modal. If the user confirms, executes the `execute` callback. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Opens a specific side panel page. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
* **`Command`** — Executa um callback assíncrono via a prop `execute`.
|
||||
* **`CommandLink`** — Navega para um caminho do app. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Abre um modal de confirmação. Se o usuário confirmar, executa o callback `execute`. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Abre uma página específica do painel lateral. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
|
||||
Here is a full example of a headless front component using `Command` to run an action from the command menu:
|
||||
Aqui está um exemplo completo de um componente de front-end headless usando `Command` para executar uma ação a partir do menu de comandos:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
@@ -954,7 +954,7 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
And an example using `CommandModal` to ask for confirmation before executing:
|
||||
E um exemplo usando `CommandModal` para solicitar confirmação antes de executar:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
@@ -991,15 +991,15 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Execution context
|
||||
#### Contexto de execução
|
||||
|
||||
Every front component receives an execution context that provides information about where and how it is running. Access context values using hooks from `twenty-sdk`:
|
||||
Todo componente de front-end recebe um contexto de execução que fornece informações sobre onde e como está sendo executado. Acesse os valores do contexto usando hooks do `twenty-sdk`:
|
||||
|
||||
| Hook | Return type | Descrição |
|
||||
| ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | The unique ID of the current front component instance |
|
||||
| `useRecordId()` | `string \| null` | The ID of the current record, when the component runs in a record context (e.g., a record page widget or a command scoped to a record). Returns `null` otherwise. |
|
||||
| `useUserId()` | `string \| null` | The ID of the current user |
|
||||
| Hook | Tipo de retorno | Descrição |
|
||||
| ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | O ID exclusivo da instância atual do componente de front-end |
|
||||
| `useRecordId()` | `string \| null` | O ID do registro atual, quando o componente é executado em um contexto de registro (por exemplo, um widget de página de registro ou um comando com escopo para um registro). Retorna `null` caso contrário. |
|
||||
| `useUserId()` | `string \| null` | O ID do usuário atual |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
@@ -1017,11 +1017,11 @@ const MyWidget = () => {
|
||||
};
|
||||
```
|
||||
|
||||
The context is reactive — if the surrounding record changes, hooks automatically return the updated values.
|
||||
O contexto é reativo — se o registro de contexto mudar, os hooks retornam automaticamente os valores atualizados.
|
||||
|
||||
#### Host API functions
|
||||
#### Funções da API do host
|
||||
|
||||
Front components run in an isolated sandbox but can interact with Twenty's UI through a set of functions provided by the host. Import them directly from `twenty-sdk`:
|
||||
Os componentes de front-end são executados em um sandbox isolado, mas podem interagir com a UI do Twenty por meio de um conjunto de funções fornecidas pelo host. Importe-as diretamente de `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
@@ -1034,16 +1034,16 @@ import {
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| Função | Signature | Descrição |
|
||||
| ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `navegar` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigate to a typed app path within Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Close the side panel |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Show a snackbar notification. Params: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Unmount the current front component (used by headless components to clean up after execution) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Open a page in the side panel. Params: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Show a confirmation modal and wait for the user's response. Params: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
| Função | Assinatura | Descrição |
|
||||
| ------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `navegar` | `(to, params?, queryParams?, options?) => Promise<void>` | Navega para um caminho tipado do app dentro do Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Fecha o painel lateral |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Exibe uma notificação de snackbar. Parâmetros: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), `duration` opcional, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Desmonta o componente de front-end atual (usado por componentes headless para limpar após a execução) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Abre uma página no painel lateral. Parâmetros: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Exibe um modal de confirmação e aguarda a resposta do usuário. Parâmetros: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
|
||||
Here is an example that uses the host API to show a snackbar and close the side panel after an action completes:
|
||||
Aqui está um exemplo que usa a API do host para exibir um snackbar e fechar o painel lateral após a conclusão de uma ação:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
|
||||
@@ -837,20 +837,20 @@ export default defineFrontComponent({
|
||||
* **Сгенерировано**: Запустите `yarn twenty entity:add` и выберите опцию добавления нового фронтенд-компонента.
|
||||
* **Вручную**: Создайте новый файл `.tsx` и используйте `defineFrontComponent()`, следуя тому же шаблону.
|
||||
|
||||
#### Where front components can be used
|
||||
#### Где можно использовать фронт-компоненты
|
||||
|
||||
Front components can render in two locations within Twenty:
|
||||
Фронт-компоненты могут отображаться в двух местах внутри Twenty:
|
||||
|
||||
* **Side panel** — Non-headless front components open in the right-hand side panel. This is the default behavior when a front component is triggered from the command menu.
|
||||
* **Widgets (dashboards and record pages)** — Front components can be embedded as widgets inside page layouts. When configuring a dashboard or a record page layout, users can add a front component widget.
|
||||
* **Боковая панель** — фронт-компоненты с интерфейсом открываются в правой боковой панели. Это поведение по умолчанию, когда фронт-компонент запускается из меню команд.
|
||||
* **Виджеты (дашборды и страницы записей)** — фронт-компоненты можно встраивать как виджеты в макеты страниц. При настройке дашборда или макета страницы записи пользователи могут добавить виджет фронт-компонента.
|
||||
|
||||
#### Headless vs non-headless
|
||||
#### Headless и non-headless
|
||||
|
||||
Front components come in two rendering modes controlled by the `isHeadless` option:
|
||||
Фронт-компоненты поддерживают два режима отображения, управляемых опцией `isHeadless`:
|
||||
|
||||
**Non-headless (default)** — The component renders a visible UI. When triggered from the command menu it opens in the side panel. This is the default behavior when `isHeadless` is `false` or omitted.
|
||||
**Non-headless (по умолчанию)** — компонент отображает видимый интерфейс. При запуске из меню команд он открывается в боковой панели. Это поведение по умолчанию, когда `isHeadless` имеет значение `false` или опущен.
|
||||
|
||||
**Headless** — The component mounts invisibly in the background. It does not open the side panel. Headless components are designed for actions that execute logic and then unmount themselves — for example, running an async task, navigating to a page, or showing a confirmation modal. They pair naturally with the SDK Command components described below.
|
||||
**Headless** — компонент монтируется невидимо в фоновом режиме. Он не открывает боковую панель. Компоненты headless предназначены для действий, которые выполняют логику и затем размонтируются — например, запуск асинхронной задачи, переход на страницу или показ модального окна подтверждения. Они естественно сочетаются с компонентами SDK Command, описанными ниже.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
@@ -866,22 +866,22 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Adding command menu items
|
||||
#### Добавление элементов меню команд
|
||||
|
||||
To make a front component appear as an item in Twenty's command menu, add the `command` property to `defineFrontComponent()`. When users open the command menu (Cmd+K / Ctrl+K), the item shows up and triggers the front component on click.
|
||||
Чтобы фронт-компонент отображался как элемент в меню команд Twenty, добавьте свойство `command` в `defineFrontComponent()`. Когда пользователи открывают меню команд (Cmd+K / Ctrl+K), элемент появляется и при клике запускает фронт-компонент.
|
||||
|
||||
The `command` object accepts the following fields:
|
||||
Объект `command` принимает следующие поля:
|
||||
|
||||
| Поле | Тип | Описание |
|
||||
| --------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `universalIdentifier` | `string` (required) | Unique ID for the command menu item |
|
||||
| `метка` | `string` (required) | Display label shown in the command menu |
|
||||
| `иконка` | `string` (optional) | Icon name (e.g., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (optional) | Whether the command is pinned at the top of the menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` shows the command everywhere; `RECORD_SELECTION` shows it only in record contexts |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Restrict the command to a specific object type (e.g., Person) |
|
||||
| Поле | Тип | Описание |
|
||||
| --------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------- |
|
||||
| `universalIdentifier` | `string` (обязательно) | Уникальный ID для элемента меню команд |
|
||||
| `метка` | `string` (обязательно) | Отображаемая метка в меню команд |
|
||||
| `иконка` | `string` (необязательно) | Имя иконки (например, `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (необязательно) | Закреплена ли команда в верхней части меню |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (необязательно) | `GLOBAL` показывает команду везде; `RECORD_SELECTION` показывает её только в контексте записи |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (необязательно) | Ограничивает команду конкретным типом объекта (например, Person) |
|
||||
|
||||
Here is an example from the call-recording app that adds a command scoped to Person records:
|
||||
Вот пример из приложения записи звонков, которое добавляет команду, ограниченную записями Person:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
@@ -903,20 +903,20 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
When the command is synced, it appears in the command menu. If the front component is non-headless the side panel opens with the component rendered inside. If it is headless the component mounts in the background and executes its logic.
|
||||
Когда команда синхронизируется, она появляется в меню команд. Если фронт-компонент с интерфейсом, открывается боковая панель с отображаемым внутри компонентом. Если он headless, компонент монтируется в фоновом режиме и выполняет свою логику.
|
||||
|
||||
#### SDK Command components
|
||||
#### Компоненты SDK Command
|
||||
|
||||
The `twenty-sdk` package provides four Command helper components designed for headless front components. Each component executes an action on mount, handles errors by showing a snackbar notification, and automatically unmounts the front component when done.
|
||||
Пакет `twenty-sdk` предоставляет четыре вспомогательных компонента Command, предназначенных для headless фронт-компонентов. Каждый компонент выполняет действие при монтировании, обрабатывает ошибки, показывая уведомление snackbar, и автоматически размонтирует фронт-компонент по завершении.
|
||||
|
||||
Import them from `twenty-sdk/command`:
|
||||
Импортируйте их из `twenty-sdk/command`:
|
||||
|
||||
* **`Command`** — Runs an async callback via the `execute` prop.
|
||||
* **`CommandLink`** — Navigates to an app path. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Opens a confirmation modal. If the user confirms, executes the `execute` callback. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Opens a specific side panel page. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
* **`Command`** — запускает асинхронный колбэк через проп `execute`.
|
||||
* **`CommandLink`** — переходит по пути внутри приложения. Пропы: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — открывает модальное окно подтверждения. Если пользователь подтвердит, выполняет колбэк `execute`. Пропы: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — открывает конкретную страницу боковой панели. Пропы: `page`, `pageTitle`, `pageIcon`.
|
||||
|
||||
Here is a full example of a headless front component using `Command` to run an action from the command menu:
|
||||
Полный пример headless фронт-компонента, использующего `Command` для запуска действия из меню команд:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
@@ -953,7 +953,7 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
And an example using `CommandModal` to ask for confirmation before executing:
|
||||
А также пример с использованием `CommandModal` для запроса подтверждения перед выполнением:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
@@ -990,15 +990,15 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Execution context
|
||||
#### Контекст выполнения
|
||||
|
||||
Every front component receives an execution context that provides information about where and how it is running. Access context values using hooks from `twenty-sdk`:
|
||||
Каждый фронт-компонент получает контекст выполнения, который предоставляет информацию о том, где и как он запущен. Получайте значения контекста с помощью хуков из `twenty-sdk`:
|
||||
|
||||
| Hook | Return type | Описание |
|
||||
| ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `строка` | The unique ID of the current front component instance |
|
||||
| `useRecordId()` | `string \| null` | The ID of the current record, when the component runs in a record context (e.g., a record page widget or a command scoped to a record). Returns `null` otherwise. |
|
||||
| `useUserId()` | `string \| null` | The ID of the current user |
|
||||
| Хук | Тип возвращаемого значения | Описание |
|
||||
| ----------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `строка` | Уникальный ID текущего экземпляра фронт-компонента |
|
||||
| `useRecordId()` | `string \| null` | ID текущей записи, когда компонент запускается в контексте записи (например, виджет на странице записи или команда с областью действия записи). В противном случае возвращает `null`. |
|
||||
| `useUserId()` | `string \| null` | ID текущего пользователя |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
@@ -1016,11 +1016,11 @@ const MyWidget = () => {
|
||||
};
|
||||
```
|
||||
|
||||
The context is reactive — if the surrounding record changes, hooks automatically return the updated values.
|
||||
Контекст реактивный: если окружающая запись изменяется, хуки автоматически возвращают обновлённые значения.
|
||||
|
||||
#### Host API functions
|
||||
#### Функции API хоста
|
||||
|
||||
Front components run in an isolated sandbox but can interact with Twenty's UI through a set of functions provided by the host. Import them directly from `twenty-sdk`:
|
||||
Фронт-компоненты выполняются в изолированной песочнице, но могут взаимодействовать с интерфейсом Twenty через набор функций, предоставляемых хостом. Импортируйте их напрямую из `twenty-sdk`:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
@@ -1033,16 +1033,16 @@ import {
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| Функция | Signature | Описание |
|
||||
| ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `навигация` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigate to a typed app path within Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Close the side panel |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Show a snackbar notification. Params: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Unmount the current front component (used by headless components to clean up after execution) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Open a page in the side panel. Params: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Show a confirmation modal and wait for the user's response. Params: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
| Функция | Сигнатура | Описание |
|
||||
| ------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `навигация` | `(to, params?, queryParams?, options?) => Promise<void>` | Переход по типизированному пути приложения внутри Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Закрыть боковую панель |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Показать уведомление snackbar. Параметры: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), необязательно `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Размонтировать текущий фронт-компонент (используется headless-компонентами для очистки после выполнения) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Открыть страницу в боковой панели. Параметры: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Показать модальное окно подтверждения и дождаться ответа пользователя. Параметры: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
|
||||
Here is an example that uses the host API to show a snackbar and close the side panel after an action completes:
|
||||
Пример, который использует API хоста для показа snackbar и закрытия боковой панели после завершения действия:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
|
||||
@@ -837,20 +837,20 @@ Yeni ön uç bileşenlerini iki şekilde oluşturabilirsiniz:
|
||||
* **Şablondan**: `yarn twenty entity:add` çalıştırın ve yeni bir ön uç bileşeni ekleme seçeneğini seçin.
|
||||
* **Manuel**: Aynı deseni izleyerek yeni bir `.tsx` dosyası oluşturun ve `defineFrontComponent()` kullanın.
|
||||
|
||||
#### Where front components can be used
|
||||
#### Ön bileşenlerin kullanılabileceği yerler
|
||||
|
||||
Front components can render in two locations within Twenty:
|
||||
Ön bileşenler, Twenty içinde iki konumda işlenebilir:
|
||||
|
||||
* **Side panel** — Non-headless front components open in the right-hand side panel. This is the default behavior when a front component is triggered from the command menu.
|
||||
* **Widgets (dashboards and record pages)** — Front components can be embedded as widgets inside page layouts. When configuring a dashboard or a record page layout, users can add a front component widget.
|
||||
* **Yan panel** — Headless olmayan ön bileşenler, sağ taraftaki yan panelde açılır. Bir ön bileşen komut menüsünden tetiklendiğinde varsayılan davranış budur.
|
||||
* **Widget'lar (panolar ve kayıt sayfaları)** — Ön bileşenler, sayfa düzenlerine widget olarak gömülebilir. Bir pano veya kayıt sayfası düzeni yapılandırılırken kullanıcılar bir ön bileşen widget'ı ekleyebilir.
|
||||
|
||||
#### Headless vs non-headless
|
||||
#### Headless ve headless olmayan
|
||||
|
||||
Front components come in two rendering modes controlled by the `isHeadless` option:
|
||||
Ön bileşenler, `isHeadless` seçeneğiyle kontrol edilen iki işleme kipiyle gelir:
|
||||
|
||||
**Non-headless (default)** — The component renders a visible UI. When triggered from the command menu it opens in the side panel. This is the default behavior when `isHeadless` is `false` or omitted.
|
||||
**Headless olmayan (varsayılan)** — Bileşen görünür bir kullanıcı arayüzü (UI) oluşturur. Komut menüsünden tetiklendiğinde yan panelde açılır. `isHeadless` `false` olduğunda veya belirtilmediğinde bu varsayılan davranıştır.
|
||||
|
||||
**Headless** — The component mounts invisibly in the background. It does not open the side panel. Headless components are designed for actions that execute logic and then unmount themselves — for example, running an async task, navigating to a page, or showing a confirmation modal. They pair naturally with the SDK Command components described below.
|
||||
**Headless** — Bileşen arka planda görünmez şekilde bağlanır. Yan paneli açmaz. Headless bileşenler, mantığı çalıştırıp ardından kendilerini kaldıran eylemler için tasarlanmıştır — örneğin, bir async görevi çalıştırma, bir sayfaya gitme veya bir onay modalı gösterme. Aşağıda açıklanan SDK Command bileşenleriyle doğal olarak eşleşirler.
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
@@ -866,22 +866,22 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Adding command menu items
|
||||
#### Komut menüsüne öğe ekleme
|
||||
|
||||
To make a front component appear as an item in Twenty's command menu, add the `command` property to `defineFrontComponent()`. When users open the command menu (Cmd+K / Ctrl+K), the item shows up and triggers the front component on click.
|
||||
Bir ön bileşenin Twenty'nin komut menüsünde bir öğe olarak görünmesi için `defineFrontComponent()` içine `command` özelliğini ekleyin. Kullanıcılar komut menüsünü (Cmd+K / Ctrl+K) açtığında, öğe görüntülenir ve tıklandığında ön bileşeni tetikler.
|
||||
|
||||
The `command` object accepts the following fields:
|
||||
`command` nesnesi aşağıdaki alanları kabul eder:
|
||||
|
||||
| Alan | Tür | Açıklama |
|
||||
| --------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `universalIdentifier` | `string` (required) | Unique ID for the command menu item |
|
||||
| `etiket` | `string` (required) | Display label shown in the command menu |
|
||||
| `simge` | `string` (optional) | Icon name (e.g., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (optional) | Whether the command is pinned at the top of the menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` shows the command everywhere; `RECORD_SELECTION` shows it only in record contexts |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Restrict the command to a specific object type (e.g., Person) |
|
||||
| Alan | Tür | Açıklama |
|
||||
| --------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------ |
|
||||
| `universalIdentifier` | `string` (zorunlu) | Komut menüsü öğesi için benzersiz kimlik |
|
||||
| `etiket` | `string` (zorunlu) | Komut menüsünde gösterilen etiket |
|
||||
| `simge` | `string` (isteğe bağlı) | Simge adı (ör. `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (isteğe bağlı) | Komutun menünün en üstüne sabitlenip sabitlenmediği |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (isteğe bağlı) | `GLOBAL` komutu her yerde gösterir; `RECORD_SELECTION` ise yalnızca kayıt bağlamlarında gösterir |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (isteğe bağlı) | Komutu belirli bir nesne türüyle sınırlandırın (ör. Person) |
|
||||
|
||||
Here is an example from the call-recording app that adds a command scoped to Person records:
|
||||
Person kayıtlarına özel bir komut ekleyen çağrı kaydı uygulamasından bir örnek:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
@@ -903,20 +903,20 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
When the command is synced, it appears in the command menu. If the front component is non-headless the side panel opens with the component rendered inside. If it is headless the component mounts in the background and executes its logic.
|
||||
Komut senkronize edildiğinde komut menüsünde görünür. Ön bileşen headless değilse, yan panel bileşen içeride işlenmiş halde açılır. Headless ise bileşen arka planda bağlanır ve mantığını yürütür.
|
||||
|
||||
#### SDK Command components
|
||||
#### SDK Command bileşenleri
|
||||
|
||||
The `twenty-sdk` package provides four Command helper components designed for headless front components. Each component executes an action on mount, handles errors by showing a snackbar notification, and automatically unmounts the front component when done.
|
||||
`twenty-sdk` paketi, headless ön bileşenler için tasarlanmış dört Command yardımcı bileşeni sağlar. Her bileşen bağlandığında bir eylem yürütür, hataları bir snackbar bildirimi göstererek ele alır ve tamamlandığında ön bileşeni otomatik olarak kaldırır.
|
||||
|
||||
Import them from `twenty-sdk/command`:
|
||||
Bunları `twenty-sdk/command` içinden içe aktarın:
|
||||
|
||||
* **`Command`** — Runs an async callback via the `execute` prop.
|
||||
* **`CommandLink`** — Navigates to an app path. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Opens a confirmation modal. If the user confirms, executes the `execute` callback. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Opens a specific side panel page. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
* **`Command`** — `execute` prop'u aracılığıyla async bir geri çağrıyı çalıştırır.
|
||||
* **`CommandLink`** — Bir uygulama yoluna gider. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Bir onay modalı açar. Kullanıcı onaylarsa `execute` geri çağrısını yürütür. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Belirli bir yan panel sayfasını açar. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
|
||||
Here is a full example of a headless front component using `Command` to run an action from the command menu:
|
||||
`Command` kullanarak komut menüsünden bir eylem çalıştıran headless bir ön bileşenin tam örneği:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
@@ -953,7 +953,7 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
And an example using `CommandModal` to ask for confirmation before executing:
|
||||
Ve yürütmeden önce onay istemek için `CommandModal` kullanan bir örnek:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
@@ -990,15 +990,15 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Execution context
|
||||
#### Yürütme bağlamı
|
||||
|
||||
Every front component receives an execution context that provides information about where and how it is running. Access context values using hooks from `twenty-sdk`:
|
||||
Her ön bileşen, nerede ve nasıl çalıştığına dair bilgi sağlayan bir yürütme bağlamı alır. Bağlam değerlerine `twenty-sdk` içindeki hook'ları kullanarak erişin:
|
||||
|
||||
| Hook | Return type | Açıklama |
|
||||
| ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | The unique ID of the current front component instance |
|
||||
| `useRecordId()` | `string \| null` | The ID of the current record, when the component runs in a record context (e.g., a record page widget or a command scoped to a record). Returns `null` otherwise. |
|
||||
| `useUserId()` | `string \| null` | The ID of the current user |
|
||||
| Hook | Dönüş türü | Açıklama |
|
||||
| ----------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | Geçerli ön bileşen örneğinin benzersiz kimliği |
|
||||
| `useRecordId()` | `string \| null` | Bileşen bir kayıt bağlamında çalıştığında (ör. bir kayıt sayfası widget'ı veya bir kayda özel bir komut) geçerli kaydın kimliği. Aksi halde `null` döner. |
|
||||
| `useUserId()` | `string \| null` | Geçerli kullanıcının kimliği |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
@@ -1016,11 +1016,11 @@ const MyWidget = () => {
|
||||
};
|
||||
```
|
||||
|
||||
The context is reactive — if the surrounding record changes, hooks automatically return the updated values.
|
||||
Bağlam tepkiseldir — çevredeki kayıt değişirse, hook'lar güncellenmiş değerleri otomatik olarak döndürür.
|
||||
|
||||
#### Host API functions
|
||||
#### Host API işlevleri
|
||||
|
||||
Front components run in an isolated sandbox but can interact with Twenty's UI through a set of functions provided by the host. Import them directly from `twenty-sdk`:
|
||||
Ön bileşenler yalıtılmış bir korumalı alanda çalışır ancak host tarafından sağlanan bir dizi işleve aracılığıyla Twenty'nin arayüzüyle etkileşime girebilir. Bunları doğrudan `twenty-sdk` içinden içe aktarın:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
@@ -1033,16 +1033,16 @@ import {
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| Fonksiyon | Signature | Açıklama |
|
||||
| ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `gezin` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigate to a typed app path within Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Close the side panel |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Show a snackbar notification. Params: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Unmount the current front component (used by headless components to clean up after execution) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Open a page in the side panel. Params: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Show a confirmation modal and wait for the user's response. Params: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
| Fonksiyon | İmza | Açıklama |
|
||||
| ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `gezin` | `(to, params?, queryParams?, options?) => Promise<void>` | Twenty içinde tiplendirilmiş bir uygulama yoluna gidin |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Yan paneli kapat |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Bir snackbar bildirimi gösterin. Parametreler: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), isteğe bağlı `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Geçerli ön bileşeni kaldırın (yürütmeden sonra temizlemek için headless bileşenler tarafından kullanılır) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Yan panelde bir sayfa açın. Parametreler: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Bir onay modalı gösterin ve kullanıcının yanıtını bekleyin. Parametreler: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
|
||||
Here is an example that uses the host API to show a snackbar and close the side panel after an action completes:
|
||||
Bir eylem tamamlandıktan sonra bir snackbar göstermek ve yan paneli kapatmak için host API'sini kullanan bir örnek:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
|
||||
@@ -837,20 +837,20 @@ export default defineFrontComponent({
|
||||
* **脚手架生成**:运行 `yarn twenty entity:add` 并选择添加新前端组件的选项。
|
||||
* **手动**:创建一个新的 `.tsx` 文件,并使用 `defineFrontComponent()`,遵循相同的模式。
|
||||
|
||||
#### Where front components can be used
|
||||
#### 前端组件可用位置
|
||||
|
||||
Front components can render in two locations within Twenty:
|
||||
在 Twenty 中,前端组件可在两个位置进行渲染:
|
||||
|
||||
* **Side panel** — Non-headless front components open in the right-hand side panel. This is the default behavior when a front component is triggered from the command menu.
|
||||
* **Widgets (dashboards and record pages)** — Front components can be embedded as widgets inside page layouts. When configuring a dashboard or a record page layout, users can add a front component widget.
|
||||
* **侧边栏** — 非无头的前端组件会在右侧侧边栏中打开。 当前端组件从命令菜单触发时,这是默认行为。
|
||||
* **小部件(仪表盘和记录页面)** — 前端组件可以作为小部件嵌入页面布局中。 在配置仪表盘或记录页面布局时,用户可以添加前端组件小部件。
|
||||
|
||||
#### Headless vs non-headless
|
||||
#### 无头与非无头
|
||||
|
||||
Front components come in two rendering modes controlled by the `isHeadless` option:
|
||||
前端组件有两种由 `isHeadless` 选项控制的渲染模式:
|
||||
|
||||
**Non-headless (default)** — The component renders a visible UI. When triggered from the command menu it opens in the side panel. This is the default behavior when `isHeadless` is `false` or omitted.
|
||||
**非无头(默认)** — 该组件会渲染可见的 UI。 从命令菜单触发时,它会在侧边栏中打开。 当 `isHeadless` 为 `false` 或被省略时,这是默认行为。
|
||||
|
||||
**Headless** — The component mounts invisibly in the background. It does not open the side panel. Headless components are designed for actions that execute logic and then unmount themselves — for example, running an async task, navigating to a page, or showing a confirmation modal. They pair naturally with the SDK Command components described below.
|
||||
**无头** — 该组件会在后台以不可见的方式挂载。 它不会打开侧边栏。 无头组件旨在用于执行逻辑后自行卸载的操作——例如运行异步任务、导航到某个页面或显示确认模态框。 它们与下文介绍的 SDK Command 组件天然契合。
|
||||
|
||||
```typescript
|
||||
export default defineFrontComponent({
|
||||
@@ -866,22 +866,22 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Adding command menu items
|
||||
#### 添加命令菜单项
|
||||
|
||||
To make a front component appear as an item in Twenty's command menu, add the `command` property to `defineFrontComponent()`. When users open the command menu (Cmd+K / Ctrl+K), the item shows up and triggers the front component on click.
|
||||
要让前端组件作为一项出现在 Twenty 的命令菜单中,请在 `defineFrontComponent()` 中添加 `command` 属性。 当用户打开命令菜单(Cmd+K / Ctrl+K)时,该项会显示,并在点击时触发该前端组件。
|
||||
|
||||
The `command` object accepts the following fields:
|
||||
`command` 对象接受以下字段:
|
||||
|
||||
| 字段 | 类型 | 描述 |
|
||||
| --------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `universalIdentifier` | `string` (required) | Unique ID for the command menu item |
|
||||
| `标签` | `string` (required) | Display label shown in the command menu |
|
||||
| `图标` | `string` (optional) | Icon name (e.g., `'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (optional) | Whether the command is pinned at the top of the menu |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (optional) | `GLOBAL` shows the command everywhere; `RECORD_SELECTION` shows it only in record contexts |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (optional) | Restrict the command to a specific object type (e.g., Person) |
|
||||
| 字段 | 类型 | 描述 |
|
||||
| --------------------------------------- | ------------------------------------- | -------------------------------------------------- |
|
||||
| `universalIdentifier` | `string` (必填) | 命令菜单项的唯一 ID |
|
||||
| `标签` | `string` (必填) | 在命令菜单中显示的标签 |
|
||||
| `图标` | `string` (可选) | 图标名称(例如,`'IconSparkles'`) |
|
||||
| `isPinned` | `boolean` (可选) | 该命令是否固定在菜单顶部 |
|
||||
| `availabilityType` | `'GLOBAL' \| 'RECORD_SELECTION'` (可选) | `GLOBAL` 会在任意位置显示该命令;`RECORD_SELECTION` 仅在记录上下文中显示 |
|
||||
| `availabilityObjectUniversalIdentifier` | `string` (可选) | 将该命令限制为特定对象类型(例如,Person) |
|
||||
|
||||
Here is an example from the call-recording app that adds a command scoped to Person records:
|
||||
以下是来自通话录音应用的示例,它添加了一个作用域为 Person 记录的命令:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent } from 'twenty-sdk';
|
||||
@@ -903,20 +903,20 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
When the command is synced, it appears in the command menu. If the front component is non-headless the side panel opens with the component rendered inside. If it is headless the component mounts in the background and executes its logic.
|
||||
当该命令同步后,它会出现在命令菜单中。 如果前端组件为非无头,侧边栏将打开并在其中渲染该组件。 如果为无头,该组件会在后台挂载并执行其逻辑。
|
||||
|
||||
#### SDK Command components
|
||||
#### SDK Command 组件
|
||||
|
||||
The `twenty-sdk` package provides four Command helper components designed for headless front components. Each component executes an action on mount, handles errors by showing a snackbar notification, and automatically unmounts the front component when done.
|
||||
`twenty-sdk` 包提供了四个为无头前端组件设计的 Command 辅助组件。 每个组件都会在挂载时执行一个操作,通过显示 snackbar 通知来处理错误,并在完成后自动卸载该前端组件。
|
||||
|
||||
Import them from `twenty-sdk/command`:
|
||||
从 `twenty-sdk/command` 导入它们:
|
||||
|
||||
* **`Command`** — Runs an async callback via the `execute` prop.
|
||||
* **`CommandLink`** — Navigates to an app path. Props: `to`, `params`, `queryParams`, `options`.
|
||||
* **`CommandModal`** — Opens a confirmation modal. If the user confirms, executes the `execute` callback. Props: `title`, `subtitle`, `execute`, `confirmButtonText`, `confirmButtonAccent`.
|
||||
* **`CommandOpenSidePanelPage`** — Opens a specific side panel page. Props: `page`, `pageTitle`, `pageIcon`.
|
||||
* **`Command`** — 通过 `execute` 属性运行异步回调。
|
||||
* **`CommandLink`** — 导航到某个应用路径。 属性:`to`、`params`、`queryParams`、`options`。
|
||||
* **`CommandModal`** — 打开一个确认模态框。 如果用户确认,则执行 `execute` 回调。 属性:`title`、`subtitle`、`execute`、`confirmButtonText`、`confirmButtonAccent`。
|
||||
* **`CommandOpenSidePanelPage`** — 打开特定的侧边栏页面。 属性:`page`、`pageTitle`、`pageIcon`。
|
||||
|
||||
Here is a full example of a headless front component using `Command` to run an action from the command menu:
|
||||
下面是一个完整示例:无头前端组件使用 `Command` 从命令菜单运行一个操作:
|
||||
|
||||
```typescript
|
||||
// src/front-components/run-action.tsx
|
||||
@@ -953,7 +953,7 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
And an example using `CommandModal` to ask for confirmation before executing:
|
||||
另一个示例:使用 `CommandModal` 在执行前请求确认:
|
||||
|
||||
```typescript
|
||||
// src/front-components/delete-draft.tsx
|
||||
@@ -990,15 +990,15 @@ export default defineFrontComponent({
|
||||
});
|
||||
```
|
||||
|
||||
#### Execution context
|
||||
#### 执行上下文
|
||||
|
||||
Every front component receives an execution context that provides information about where and how it is running. Access context values using hooks from `twenty-sdk`:
|
||||
每个前端组件都会接收一个执行上下文,提供其运行位置与方式的信息。 使用来自 `twenty-sdk` 的钩子来访问上下文值:
|
||||
|
||||
| Hook | Return type | 描述 |
|
||||
| ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | The unique ID of the current front component instance |
|
||||
| `useRecordId()` | `string \| null` | The ID of the current record, when the component runs in a record context (e.g., a record page widget or a command scoped to a record). Returns `null` otherwise. |
|
||||
| `useUserId()` | `string \| null` | The ID of the current user |
|
||||
| 钩子 | 返回类型 | 描述 |
|
||||
| ----------------------- | ---------------- | ------------------------------------------------------------- |
|
||||
| `useFrontComponentId()` | `string` | 当前前端组件实例的唯一 ID |
|
||||
| `useRecordId()` | `string \| null` | 当组件在记录上下文中运行时(例如记录页面小部件或作用域限定于某条记录的命令),当前记录的 ID。 否则返回 `null`。 |
|
||||
| `useUserId()` | `string \| null` | 当前用户的 ID |
|
||||
|
||||
```typescript
|
||||
import { useRecordId, useUserId } from 'twenty-sdk';
|
||||
@@ -1016,11 +1016,11 @@ const MyWidget = () => {
|
||||
};
|
||||
```
|
||||
|
||||
The context is reactive — if the surrounding record changes, hooks automatically return the updated values.
|
||||
该上下文是响应式的——如果周围的记录发生变化,钩子会自动返回更新后的值。
|
||||
|
||||
#### Host API functions
|
||||
#### 宿主 API 函数
|
||||
|
||||
Front components run in an isolated sandbox but can interact with Twenty's UI through a set of functions provided by the host. Import them directly from `twenty-sdk`:
|
||||
前端组件在隔离的沙箱中运行,但可以通过宿主提供的一组函数与 Twenty 的 UI 进行交互。 直接从 `twenty-sdk` 导入它们:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
@@ -1033,16 +1033,16 @@ import {
|
||||
} from 'twenty-sdk';
|
||||
```
|
||||
|
||||
| 函数 | Signature | 描述 |
|
||||
| ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `导航` | `(to, params?, queryParams?, options?) => Promise<void>` | Navigate to a typed app path within Twenty |
|
||||
| `closeSidePanel` | `() => Promise<void>` | Close the side panel |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | Show a snackbar notification. Params: `message`, `variant` (`'error'`, `'success'`, `'info'`, `'warning'`), optional `duration`, `detailedMessage`, `dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | Unmount the current front component (used by headless components to clean up after execution) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | Open a page in the side panel. Params: `page`, `pageTitle`, `pageIcon`, `shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | Show a confirmation modal and wait for the user's response. Params: `title`, `subtitle`, `confirmButtonText`, `confirmButtonAccent` (`'default'`, `'blue'`, `'danger'`) |
|
||||
| 函数 | 签名 | 描述 |
|
||||
| ------------------------------ | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `导航` | `(to, params?, queryParams?, options?) => Promise<void>` | 在 Twenty 内导航到一个类型化的应用路径 |
|
||||
| `closeSidePanel` | `() => Promise<void>` | 关闭侧边栏 |
|
||||
| `enqueueSnackbar` | `(params) => Promise<void>` | 显示一条 snackbar 通知。 参数:`message`、`variant`(`'error'`、`'success'`、`'info'`、`'warning'`),可选的 `duration`、`detailedMessage`、`dedupeKey` |
|
||||
| `unmountFrontComponent` | `() => Promise<void>` | 卸载当前前端组件(供无头组件在执行后进行清理) |
|
||||
| `openSidePanelPage` | `(params) => Promise<void>` | 在侧边栏中打开一个页面。 参数:`page`、`pageTitle`、`pageIcon`、`shouldResetSearchState` |
|
||||
| `openCommandConfirmationModal` | `(params) => Promise<'confirm' \| 'cancel'>` | 显示一个确认模态框并等待用户的响应。 参数:`title`、`subtitle`、`confirmButtonText`、`confirmButtonAccent`(`'default'`、`'blue'`、`'danger'`) |
|
||||
|
||||
Here is an example that uses the host API to show a snackbar and close the side panel after an action completes:
|
||||
下面是一个示例,使用宿主 API 在操作完成后显示一条 snackbar 并关闭侧边栏:
|
||||
|
||||
```typescript
|
||||
import { defineFrontComponent, useRecordId } from 'twenty-sdk';
|
||||
|
||||
Reference in New Issue
Block a user