### Install Dependencies with pnpm Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/README.md Installs all project dependencies using the pnpm package manager. Ensure you have pnpm version 9 or 10 installed. ```bash pnpm install ``` -------------------------------- ### Basic useUploadFiles Hook Example Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/packages/react/src/hooks/useUploadFiles/useUploadFiles.mdx Provides a basic example of using the useUploadFiles hook within a React component to display uploaded files and manage their removal. It highlights the integration with component state and UI rendering. ```typescript const MyComponent = () => { const { files, uploadedFiles, removeFile, updateImage, } = useUploadFiles({ handleOnChange: (uploadedFiles) => { console.log('Uploaded files:', uploadedFiles); }, }); return (

Upload Files

{/* Add more UI elements to handle file uploads, removals, and updates */}
); }; ``` -------------------------------- ### Edifice Modal Component Example (React) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt Exemple d'utilisation du composant Modal d'Edifice. Ce composant fournit une boîte de dialogue modale accessible avec gestion du focus et fermeture au clic extérieur. Il utilise un pattern de composants composés pour sa structure. ```tsx import { Modal, Button, useToggle } from '@edifice.io/react'; function ExempleModal() { const [isOpen, toggleModal] = useToggle(false); return ( <> Titre de la modale Sous-titre optionnel

Contenu de la modale avec du texte et des composants.

); } ``` -------------------------------- ### Edifice Alert Component Examples (React) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt Exemples d'utilisation du composant Alert d'Edifice. Ce composant affiche des messages de notification avec différents types et modes, y compris des toasts avec fermeture automatique. Il peut être contrôlé via une référence. ```tsx import { Alert, useRef } from '@edifice.io/react'; // Alerte simple de succès Opération réussie ! // Alerte d'erreur fermable console.log('Fermée')}> Une erreur est survenue lors de l'enregistrement. // Toast avec fermeture automatique Nouvelle notification reçue // Alerte contrôlée via ref function AlerteControlee() { const alertRef = useRef(null); return ( <> console.log('Visible:', visible)} > Message d'avertissement contrôlé ); } ``` -------------------------------- ### Edifice Button Component Examples (React) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt Exemples d'utilisation du composant Button d'Edifice. Ce composant supporte diverses variantes, couleurs, tailles, icônes et états de chargement. Il est conçu pour être accessible et s'intègre dans des formulaires. ```tsx import { Button } from '@edifice.io/react'; import { IconSave, IconTrash } from '@edifice.io/react/icons'; // Bouton primaire simple // Bouton avec icône à gauche // Bouton en état de chargement // Bouton danger avec icône // Bouton submit dans un formulaire ``` -------------------------------- ### Utilize Gap Utilities for Element Spacing (CSS) Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/apps/docs/src/stories/Spacings.mdx Illustrates the usage of gap utilities to control the spacing between elements when using display: grid or display: flex. The example shows various gap values like gap-2, gap-4, up to gap-64. ```html
Prefix Values
gap-
gap-2
gap-4
gap-8
gap-12
gap-16
gap-24
gap-32
gap-48
gap-64
``` -------------------------------- ### HTTP Requests with OdeServices Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The OdeServices HTTP client facilitates making various HTTP requests (GET, POST, PUT, DELETE) to the backend. It supports JSON and file uploads, query parameters, and includes error handling mechanisms. Dependencies include the '@edifice.io/client' package. ```tsx import { odeServices } from '@edifice.io/client'; // Requête GET simple const users = await odeServices.http().get('/directory/users'); // Requête GET avec paramètres const documents = await odeServices.http().get('/workspace/documents', { queryParams: { filter: 'owner', parentId: 'folder-123', includeall: true } }); // Requête POST avec données JSON const newResource = await odeServices.http().postJson( '/blog/post', { title: 'Nouveau post', content: '

Contenu du post

', state: 'PUBLISHED' } ); // Upload de fichier const formData = new FormData(); formData.append('file', file, file.name); const uploaded = await odeServices.http().postFile( '/workspace/document?protected=true', formData ); // Vérifier les erreurs if (odeServices.http().isResponseError()) { console.error('Erreur:', odeServices.http().latestResponse.statusText); } // Requête PUT pour mise à jour await odeServices.http().putJson('/blog/post/123', { title: 'Titre modifié', content: '

Nouveau contenu

' }); // Requête DELETE await odeServices.http().delete('/blog/post/123'); ``` -------------------------------- ### Session Management Service (TS) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The Session service handles user authentication and retrieves connected user information. It provides methods to get user details, descriptions, and check authentication status. ```typescript import { odeServices } from '@edifice.io/client'; // Obtenir les informations de l'utilisateur courant const user = await odeServices.session().getUser(); console.log('Utilisateur:', user?.userId, user?.username); // Obtenir la description complète de l'utilisateur const description = await odeServices.session().getUserDescription(); console.log('Profil:', description?.firstName, description?.lastName); // Vérifier si l'utilisateur est connecté const isAuthenticated = await odeServices.session().isAuthenticated(); // Exemple d'utilisation dans un composant function SessionInfo() { const [sessionData, setSessionData] = useState(null); useEffect(() => { async function loadSession() { const user = await odeServices.session().getUser(); const description = await odeServices.session().getUserDescription(); setSessionData({ user, description }); } loadSession(); }, []); if (!sessionData) return ; return (

Connecté en tant que: {sessionData.user.username}

Établissement: {sessionData.description.structureNames?.join(', ')}

); } ``` -------------------------------- ### Apply Responsive Spacing Utilities (CSS) Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/apps/docs/src/stories/Spacings.mdx Explains how to reassign spacing utilities using breakpoints such as sm, md, lg, xl, and xxl. The format for responsive spacing is provided as `*-{direction}-{breakpoint}-{value}`. ```css /* Example of responsive spacing */ .padding-left-sm-16 { padding-left: 16px; /* applied on small screens and up */ } .margin-top-md-32 { margin-top: 32px; /* applied on medium screens and up */ } ``` -------------------------------- ### Build Project with pnpm Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/README.md Compiles and bundles the project assets for production using the pnpm build script. This command is essential for preparing the application for deployment. ```bash pnpm run build ``` -------------------------------- ### Initialize application context with EdificeClientProvider Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The EdificeClientProvider initializes the application context with user session data, configuration, and translations. It is typically wrapped at the root of the application. ```tsx import { EdificeClientProvider, EdificeThemeProvider, useEdificeClient } from '@edifice.io/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; const queryClient = new QueryClient(); function App() { return ( ); } function MonComposant() { const { appCode, currentApp, user, currentLanguage, init } = useEdificeClient(); if (!init) { return ; } return (

Application: {currentApp?.displayName}

Utilisateur: {user?.username}

Langue: {currentLanguage}

); } ``` -------------------------------- ### Implement useResourceSearch Hook Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/packages/react/src/hooks/useResourceSearch/useResourceSearch.mdx Demonstrates how to initialize the useResourceSearch hook with an application code. It returns a list of resource applications and a loadResources function for fetching data. ```typescript import { useResourceSearch } from 'path-to-hook'; const { resourceApplications, loadResources } = useResourceSearch(appCode); // Use resourceApplications and loadResources as needed ``` -------------------------------- ### Initialize useUploadFiles Hook Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/packages/react/src/hooks/useUploadFiles/useUploadFiles.mdx Demonstrates how to initialize the useUploadFiles hook with various options like callbacks, visibility, and application context. It outlines the returned state and functions for managing file uploads. ```typescript import useUploadFiles from './useUploadFiles'; const { files, getUploadStatus, clearUploadStatus, uploadedFiles, editingImage, setEditingImage, getUrl, updateImage, uploadFile, removeFile, } = useUploadFiles({ handleOnChange: (uploadedFiles) => { console.log(uploadedFiles); }, visibility: 'public', application: 'myApp', }); ``` -------------------------------- ### Format Code with Prettier Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/README.md Applies code formatting rules defined by Prettier to the project files. This ensures a consistent and readable code style throughout the codebase. ```bash pnpm run format ``` -------------------------------- ### Lint Code with Eslint Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/README.md Runs the Eslint linter to check for code style and potential errors. This command helps maintain code quality and consistency across the project. ```bash pnpm run lint ``` -------------------------------- ### Import and Initialize useWorkspaceFile Hook Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/packages/react/src/hooks/useWorkspaceFile/useWorkspaceFile.mdx Demonstrates how to import and destructure the necessary functions (createOrUpdate, create, remove) from the useWorkspaceFile hook for managing workspace files. ```typescript import useWorkspaceFile from './useWorkspaceFile'; const { createOrUpdate, create, remove } = useWorkspaceFile(); ``` -------------------------------- ### Apply Padding with Card Component (React) Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/apps/docs/src/stories/Spacings.mdx Demonstrates applying different padding values to Card components using inline styles in a React application. Each Card component showcases a specific padding size, ranging from 2px to 64px. ```jsx
.p-2 .p-4 .p-8 .p-12 .p-16 .p-24 .p-32 .p-48 .p-64
``` -------------------------------- ### OdeServices HTTP Client Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The OdeServices HTTP client provides a centralized way to make HTTP requests to the ENT backend, with built-in error handling, CDN, and caching. ```APIDOC ## OdeServices HTTP Client ### Description Provides a centralized HTTP client with error handling, CDN, and cache for communicating with the ENT backend. ### Method Various (GET, POST, PUT, DELETE) ### Endpoint Various (e.g., /directory/users, /workspace/documents, /blog/post) ### Parameters #### Query Parameters - **queryParams** (object) - Optional - Key-value pairs for query parameters. - **filter** (string) - Optional - Filter criteria for requests. - **parentId** (string) - Optional - ID of the parent folder. - **includeall** (boolean) - Optional - Whether to include all items. #### Request Body - **(POST/PUT)** (object) - JSON payload for the request. - **(POST File)** (FormData) - FormData object for file uploads. ### Request Example (GET with parameters) ```typescript const documents = await odeServices.http().get('/workspace/documents', { queryParams: { filter: 'owner', parentId: 'folder-123', includeall: true } }); ``` ### Request Example (POST JSON) ```typescript const newResource = await odeServices.http().postJson( '/blog/post', { title: 'Nouveau post', content: '

Contenu du post

', state: 'PUBLISHED' } ); ``` ### Request Example (POST File) ```typescript const formData = new FormData(); formData.append('file', file, file.name); const uploaded = await odeServices.http().postFile( '/workspace/document?protected=true', formData ); ``` ### Request Example (PUT JSON) ```typescript await odeServices.http().putJson('/blog/post/123', { title: 'Titre modifié', content: '

Nouveau contenu

' }); ``` ### Request Example (DELETE) ```typescript await odeServices.http().delete('/blog/post/123'); ``` ### Error Handling - **isResponseError()** (boolean) - Checks if the last response resulted in an error. - **latestResponse.statusText** (string) - Accesses the status text of the latest response. ### Response #### Success Response (200) - **(Varies)** (type) - The type depends on the endpoint and the generic type provided (e.g., `User[]`, `Document[]`, `Resource`, `WorkspaceElement`). #### Response Example (GET users) ```json [ { "id": "user-1", "name": "John Doe" } ] ``` ``` -------------------------------- ### Workspace File and Folder Management Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The Workspace service enables comprehensive management of files and folders, including uploads, updates, deletions, transfers, and thumbnail generation. It requires the '@edifice.io/client' package and operates on WorkspaceElement objects. ```tsx import { odeServices, WorkspaceElement } from '@edifice.io/client'; // Upload d'un fichier const file = event.target.files[0]; const uploadedFile = await odeServices.workspace().saveFile(file, { parentId: 'folder-id', visibility: 'protected', application: 'blog' }); // Mettre à jour un fichier existant const updatedFile = await odeServices.workspace().updateFile( 'document-id', newFile, { name: 'nouveau-nom.pdf', alt: 'Description alternative' } ); // Lister les documents d'un dossier const documents = await odeServices.workspace().listDocuments('owner', 'parent-folder-id'); // Recherche avancée de documents const results = await odeServices.workspace().searchDocuments({ filter: 'shared', search: 'rapport', limit: 20, includeall: true }); // Lister les dossiers avec hiérarchie const folders = await odeServices.workspace().listOwnerFolders(true); const sharedFolders = await odeServices.workspace().listSharedFolders(true, 'parent-id'); // Créer un nouveau dossier await odeServices.workspace().createFolder('Nouveau dossier', 'parent-folder-id'); // Supprimer des fichiers const filesToDelete: WorkspaceElement[] = [doc1, doc2, doc3]; await odeServices.workspace().deleteFile(filesToDelete); // Transférer des documents vers une visibilité différente const transferredDocs = await odeServices.workspace().transferDocuments( selectedDocuments, 'blog', 'public' ); // Obtenir l'URL d'une miniature const thumbnailUrl = odeServices.workspace().getThumbnailUrl(document, 300, 200); // Ou avec taille par défaut const defaultThumb = odeServices.workspace().getThumbnailUrl(document); ``` -------------------------------- ### Implement useDebounce Hook in React Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/packages/react/src/hooks/useDebounce/useDebounce.mdx Demonstrates how to integrate the useDebounce hook into a functional React component to delay state-dependent logic. It accepts a value and a delay duration, returning a debounced version of the input. ```typescript import useDebounce from './useDebounce'; function Component() { const [value, setValue] = useState(''); const debouncedValue = useDebounce(value, 500); useEffect(() => { // Do something with debouncedValue }, [debouncedValue]); return ( setValue(e.target.value)} /> ); } ``` ```typescript import React, { useState } from 'react'; import useDebounce from './useDebounce'; function SearchInput() { const [query, setQuery] = useState(''); const debouncedQuery = useDebounce(query, 300); useEffect(() => { if (debouncedQuery) { // Fetch data or perform some action with debouncedQuery } }, [debouncedQuery]); return ( setQuery(e.target.value)} placeholder="Search..." /> ); } ``` -------------------------------- ### MediaLibrary Component for Media Selection and Upload (React) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The MediaLibrary component provides a modal interface for users to select, upload, or capture media files (images, audio, video, links). It supports various configurations for media types, visibility, and multiple selections. The component uses a ref for programmatic control and provides callbacks for success and cancellation. ```tsx import { MediaLibrary, MediaLibraryRef, useRef } from '@edifice.io/react'; import { WorkspaceElement } from '@edifice.io/client'; function EditeurAvecMedias() { const mediaLibraryRef = useRef(null); const handleSuccess = (result: WorkspaceElement[] | string) => { if (Array.isArray(result)) { // Fichiers sélectionnés/uploadés result.forEach(file => { insertMedia(file); }); } else { // Lien ou embed insertLink(result); } }; const handleCancel = (uploads?: WorkspaceElement[]) => { // Nettoyer les uploads annulés si nécessaire if (uploads?.length) { odeServices.workspace().deleteFile(uploads); } }; return (
{ console.log('Tab changé:', tab.id); }} />
); } // Ouvrir avec un lien pré-rempli pour édition function EditLien() { const mediaLibraryRef = useRef(null); const editExternalLink = () => { mediaLibraryRef.current?.showLink({ url: 'https://example.com', text: 'Texte du lien', target: '_blank' }); }; const editInternalLink = () => { mediaLibraryRef.current?.showLink({ appPrefix: 'blog', resourceId: 'post-123' }); }; return ( <> ); } ``` -------------------------------- ### Optimize search inputs with useDebounce Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The useDebounce hook delays the update of a value to optimize search operations and prevent excessive API calls. It takes the value and a delay in milliseconds as inputs. ```tsx import { useDebounce } from '@edifice.io/react'; import { useState, useEffect } from 'react'; function RechercheAvecDebounce() { const [searchTerm, setSearchTerm] = useState(''); const debouncedSearch = useDebounce(searchTerm, 500); const [results, setResults] = useState([]); useEffect(() => { if (debouncedSearch) { fetchSearchResults(debouncedSearch).then(setResults); } }, [debouncedSearch]); return (
setSearchTerm(e.target.value)} />
    {results.map((item) => (
  • {item.name}
  • ))}
); } ``` -------------------------------- ### ImageResizer Utility for Client-Side Image Optimization (React) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The ImageResizer utility class allows for client-side resizing and compression of images before they are uploaded. This helps optimize performance by reducing file sizes. It can be used to resize images to specific dimensions and quality levels, and it returns a new File object representing the processed image. ```tsx import { ImageResizer } from '@edifice.io/utilities'; // Redimensionner une image avant upload async function handleImageUpload(event: React.ChangeEvent) { const file = event.target.files?.[0]; if (!file) return; try { // Redimensionner à max 1440x1440 avec qualité 80% const resizedFile = await ImageResizer.resizeImageFile( file, 1440, // maxWidth 1440, // maxHeight 80 // quality (%) ); console.log('Taille originale:', file.size); console.log('Taille après compression:', resizedFile.size); // Upload du fichier redimensionné const uploaded = await odeServices.workspace().saveFile(resizedFile, { visibility: 'protected', application: 'blog' }); return uploaded; } catch (error) { console.error('Erreur de redimensionnement:', error); } } // Redimensionner pour thumbnail async function createThumbnail(file: File) { return ImageResizer.resizeImageFile( file, 300, // maxWidth 300, // maxHeight 70 // quality ); } ``` -------------------------------- ### Workspace Service Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The Workspace service manages files and folders within the workspace, supporting uploads, deletions, transfers, and thumbnail generation. ```APIDOC ## Workspace Service ### Description Manages files and folders in the workspace, including upload, deletion, transfer, and thumbnail generation. ### Method Various (saveFile, updateFile, listDocuments, searchDocuments, listOwnerFolders, listSharedFolders, createFolder, deleteFile, transferDocuments, getThumbnailUrl) ### Endpoint Internal to the Workspace service. ### Parameters #### Path Parameters - **fileId** (string) - Required - The ID of the file to update or delete. #### Query Parameters - **parentId** (string) - Optional - The ID of the parent folder for new files or listed documents. - **visibility** (string) - Optional - Visibility setting for uploaded files (e.g., 'protected'). - **application** (string) - Optional - Associated application for files. - **owner** (string) - Optional - Filter documents by owner. - **search** (string) - Optional - Search query string. - **limit** (number) - Optional - Maximum number of results to return. - **includeall** (boolean) - Optional - Whether to include all items. - **hierarchical** (boolean) - Optional - Whether to return folders in a hierarchical structure. #### Request Body - **file** (File) - Required (for saveFile) - The file object to upload. - **newFile** (File) - Required (for updateFile) - The updated file object. - **metadata** (object) - Optional (for updateFile) - Metadata to update (e.g., `name`, `alt`). - **searchOptions** (object) - Optional (for searchDocuments) - Options for searching documents. - **folderName** (string) - Required (for createFolder) - The name of the new folder. - **parentFolderId** (string) - Optional (for createFolder) - The ID of the parent folder. - **documentsToDelete** (WorkspaceElement[]) - Required (for deleteFile) - An array of WorkspaceElement objects to delete. - **documentsToTransfer** (WorkspaceElement[]) - Required (for transferDocuments) - An array of WorkspaceElement objects to transfer. - **targetApplication** (string) - Required (for transferDocuments) - The target application for the transfer. - **targetVisibility** (string) - Required (for transferDocuments) - The target visibility for the transfer. ### Request Example (Upload File) ```typescript const file = event.target.files[0]; const uploadedFile = await odeServices.workspace().saveFile(file, { parentId: 'folder-id', visibility: 'protected', application: 'blog' }); ``` ### Request Example (Update File) ```typescript const updatedFile = await odeServices.workspace().updateFile( 'document-id', newFile, { name: 'nouveau-nom.pdf', alt: 'Description alternative' } ); ``` ### Request Example (List Documents) ```typescript const documents = await odeServices.workspace().listDocuments('owner', 'parent-folder-id'); ``` ### Request Example (Search Documents) ```typescript const results = await odeServices.workspace().searchDocuments({ filter: 'shared', search: 'rapport', limit: 20, includeall: true }); ``` ### Request Example (List Folders) ```typescript const folders = await odeServices.workspace().listOwnerFolders(true); const sharedFolders = await odeServices.workspace().listSharedFolders(true, 'parent-id'); ``` ### Request Example (Create Folder) ```typescript await odeServices.workspace().createFolder('Nouveau dossier', 'parent-folder-id'); ``` ### Request Example (Delete Files) ```typescript const filesToDelete: WorkspaceElement[] = [doc1, doc2, doc3]; await odeServices.workspace().deleteFile(filesToDelete); ``` ### Request Example (Transfer Documents) ```typescript const transferredDocs = await odeServices.workspace().transferDocuments( selectedDocuments, 'blog', 'public' ); ``` ### Request Example (Get Thumbnail URL) ```typescript const thumbnailUrl = odeServices.workspace().getThumbnailUrl(document, 300, 200); const defaultThumb = odeServices.workspace().getThumbnailUrl(document); ``` ### Response #### Success Response (200) - **(Varies)** (type) - The type depends on the method called (e.g., `WorkspaceElement`, `Document[]`, `Folder[]`, `string` for thumbnail URL). #### Response Example (List Documents) ```json [ { "id": "doc-123", "name": "report.pdf", "type": "file", "size": 102400, "createdAt": "2023-10-27T10:00:00Z" } ] ``` ``` -------------------------------- ### Fix Linting Errors with Eslint Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/README.md Automatically fixes common linting errors detected by Eslint. This command streamlines the process of code correction and improves developer productivity. ```bash pnpm run fix ``` -------------------------------- ### Card Component: Display Structured Content (React) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The Card component displays structured content with header, image, body, and footer. It supports selection and click interactions. It requires the '@edifice.io/react' package. ```tsx import { Card } from '@edifice.io/react'; // Carte basique avec image navigateTo('/detail')}> Titre de la ressource Description courte de la ressource éducative. // Carte sélectionnable avec application setSelectedId(item.id)} > {(appCode) => ( Article du blog Code application: {appCode} )} ``` -------------------------------- ### String Manipulation Utilities (TS) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The StringUtils class provides methods for checking URL types, formatting counters, and generating unique IDs. It's useful for data presentation and validation. ```typescript import { StringUtils } from '@edifice.io/utilities'; // Vérifier si une URL est locale (relative) StringUtils.isLocalURL('/workspace/document/123'); // true StringUtils.isLocalURL('https://example.com'); // false // Vérifier si une URL commence par http/https StringUtils.startWithHttp('https://example.com'); // true StringUtils.startWithHttp('/local/path'); // false // Formater un compteur pour affichage StringUtils.toCounter(500); // "500" StringUtils.toCounter(1500); // "1.5 k" StringUtils.toCounter(12345); // "12.3 k" // Générer un identifiant unique virtuel const virtualId = StringUtils.generateVirtualId(); // Exemple: "a3f2-b1c4-d5e-6f7a" // Utilisation pratique function ResourceCard({ resource }) { const { viewCount, url } = resource; return ( Vues: {StringUtils.toCounter(viewCount)} {StringUtils.isLocalURL(url) ? ( Voir la ressource ) : ( Ouvrir le lien externe )} ); } ``` -------------------------------- ### Rights and Workflow Verification Service (TS) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The Rights service checks user permissions for specific workflows. It allows checking individual or multiple workflow rights and integrating the results into UI components. ```typescript import { odeServices } from '@edifice.io/client'; // Vérifier un droit de workflow unique const canAddDocument = await odeServices.rights().sessionHasWorkflowRight( 'org.entcore.workspace.controllers.WorkspaceController|addDocument' ); // Vérifier plusieurs droits en une fois const rights = await odeServices.rights().sessionHasWorkflowRights([ 'org.entcore.workspace.controllers.WorkspaceController|addDocument', 'org.entcore.workspace.controllers.WorkspaceController|deleteDocument', 'com.opendigitaleducation.video.controllers.VideoController|capture' ]); // Utilisation des résultats if (rights['org.entcore.workspace.controllers.WorkspaceController|addDocument']) { // Afficher le bouton d'ajout } // Dans un composant React function AdminPanel() { const [permissions, setPermissions] = useState({}); useEffect(() => { async function checkPermissions() { const results = await odeServices.rights().sessionHasWorkflowRights([ 'org.entcore.workspace.controllers.WorkspaceController|addDocument', 'org.entcore.blog.controllers.BlogController|create' ]); setPermissions(results); } checkPermissions(); }, []); return (
{permissions['org.entcore.workspace.controllers.WorkspaceController|addDocument'] && ( )} {permissions['org.entcore.blog.controllers.BlogController|create'] && ( )}
); } ``` -------------------------------- ### Retrieve user profile with useUser Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The useUser hook provides access to the authenticated user's information, including avatar and profile details, retrieved from the Edifice application context. ```tsx import { useUser } from '@edifice.io/react'; function ProfilUtilisateur() { const { user, avatar, userDescription } = useUser(); if (!user) { return
Chargement...
; } return (
{user.username}

{user.username}

Prénom: {userDescription?.firstName}

Nom: {userDescription?.lastName}

Email: {userDescription?.email}

Profil: {user.type}

); } ``` -------------------------------- ### Manage boolean state with useToggle Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The useToggle hook provides a boolean state and a memoized toggle function. It is ideal for managing UI elements like modals, menus, and visibility states. ```tsx import { useToggle } from '@edifice.io/react'; function ComponenteAvecToggle() { const [isOpen, toggle] = useToggle(); const [isExpanded, toggleExpanded] = useToggle(true); return (
{isOpen && (
Contenu du panneau
)}
); } ``` -------------------------------- ### Select Component: Customizable Selection Lists (React) Source: https://context7.com/edificeio/edifice-frontend-framework/llms.txt The Select component provides a customizable selection list based on Dropdown, supporting icons, and controlled/uncontrolled modes. It requires '@edifice.io/react' and optionally '@edifice.io/react/icons'. ```tsx import { Select } from '@edifice.io/react'; import { IconFolder, IconFile, IconImage } from '@edifice.io/react/icons'; // Select simple avec options string setResourceType(option)} block /> // Select contrôlé const [selected, setSelected] = useState('option1'); // Input avec compteur de caractères setDescription(e.target.value)} /> // Input dans un FormControl avec validation Veuillez saisir une adresse email valide // Input en lecture seule ``` -------------------------------- ### Check Session Workflow Rights with useHasWorkflow (TypeScript) Source: https://github.com/edificeio/edifice-frontend-framework/blob/develop/packages/react/src/hooks/useHasWorkflow/useHasWorkflow.mdx The useHasWorkflow hook checks if the current session has the specified workflow rights. It takes a workflow name or an array of workflow names as input and returns a boolean or an object indicating the presence of these rights. This hook is useful for conditionally rendering UI elements or controlling access based on user permissions. ```typescript import useHasWorkflow from './useHasWorkflow'; const hasWorkflow = useHasWorkflow('workflowName'); ``` ```typescript import React from 'react'; import useHasWorkflow from './useHasWorkflow'; const MyComponent = () => { const hasWorkflow = useHasWorkflow('exampleWorkflow'); if (hasWorkflow === undefined) { return
Loading...
; } return (
{hasWorkflow ? 'Workflow is available' : 'Workflow is not available'}
); }; export default MyComponent; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.