SmarMaker - Documentation
Docs» 15_training:module10-fonctionnalites-avancees:autres

Chapitre 3 : Autres fonctionnalités

Géolocalisation

Obtenir la position

snippet.javascript
import { useState } from 'react';
import { Button, Block } from '@cap-rel/smartcommon';
 
function LocationButton({ onLocation }) {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
 
    const getLocation = () => {
        if (!navigator.geolocation) {
            setError('Géolocalisation non supportée');
            return;
        }
 
        setLoading(true);
        setError(null);
 
        navigator.geolocation.getCurrentPosition(
            (position) => {
                setLoading(false);
                onLocation({
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                    accuracy: position.coords.accuracy
                });
            },
            (err) => {
                setLoading(false);
                setError(err.message);
            },
            {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 0
            }
        );
    };
 
    return (
        <Block>
            <Button onClick={getLocation} loading={loading}>
                Obtenir ma position
            </Button>
            {error && <p className="text-red-500 mt-2">{error}</p>}
        </Block>
    );
}

Composant Gps de SmartCommon

snippet.javascript
import { Gps } from '@cap-rel/smartcommon';
 
<Gps
    name="location"
    label="Position de l'intervention"
    onChange={(coords) => console.log(coords)}
/>

Upload de fichiers

PhotosUploader

snippet.javascript
import { PhotosUploader } from '@cap-rel/smartcommon';
 
<PhotosUploader
    name="photos"
    label="Photos"
    maxFiles={5}
    maxSize={5 * 1024 * 1024}  // 5 Mo
    onChange={(files) => console.log(files)}
/>

FilesUploader

snippet.javascript
import { FilesUploader } from '@cap-rel/smartcommon';
 
<FilesUploader
    name="documents"
    label="Documents"
    accept=".pdf,.doc,.docx"
    multiple
    maxFiles={10}
/>

Redimensionner une image

snippet.javascript
import { useFile } from '@cap-rel/smartcommon';
 
function ImageUploader() {
    const { resizeImage } = useFile();
 
    const handleFile = async (e) => {
        const file = e.target.files[0];
 
        const base64 = await resizeImage(file, {
            maxWidth: 1200,
            maxHeight: 1200,
            quality: 80
        });
 
        // Envoyer au serveur
        await api.private.post('files', {
            json: {
                filename: file.name,
                content: base64
            }
        });
    };
 
    return <input type="file" accept="image/*" onChange={handleFile} />;
}

Thème sombre

Configuration globale

snippet.javascript
// appConfig.js
export const config = {
    globalState: {
        reducers: {
            settings: {
                theme: 'light'  // 'light' ou 'dark'
            }
        }
    }
};

Appliquer le thème

snippet.javascript
import { useEffect } from 'react';
import { useGlobalStates } from '@cap-rel/smartcommon';
 
function ThemeProvider({ children }) {
    const [settings] = useGlobalStates('settings');
 
    useEffect(() => {
        document.documentElement.classList.toggle(
            'dark',
            settings.theme === 'dark'
        );
    }, [settings.theme]);
 
    return children;
}

Toggle de thème

snippet.javascript
import { useGlobalStates } from '@cap-rel/smartcommon';
import { Boolean } from '@cap-rel/smartcommon';
 
function ThemeToggle() {
    const [settings, setSettings] = useGlobalStates('settings');
 
    const toggleTheme = () => {
        setSettings({
            ...settings,
            theme: settings.theme === 'light' ? 'dark' : 'light'
        });
    };
 
    return (
        <Boolean
            value={settings.theme === 'dark'}
            onChange={toggleTheme}
            label="Mode sombre"
        />
    );
}

Signature manuscrite

snippet.javascript
import { SignaturePad } from '@cap-rel/smartcommon';
 
<SignaturePad
    name="signature"
    label="Signature du client"
    width={400}
    height={200}
/>

Scan de code-barres

Utiliser une bibliothèque comme @zxing/browser :

snippet.bash
npm install @zxing/browser @zxing/library
snippet.javascript
import { useState, useRef, useEffect } from 'react';
import { BrowserMultiFormatReader } from '@zxing/browser';
 
function BarcodeScanner({ onScan }) {
    const videoRef = useRef(null);
    const [scanning, setScanning] = useState(false);
 
    useEffect(() => {
        let reader;
 
        if (scanning) {
            reader = new BrowserMultiFormatReader();
            reader.decodeFromVideoDevice(
                undefined,
                videoRef.current,
                (result, error) => {
                    if (result) {
                        onScan(result.getText());
                        setScanning(false);
                    }
                }
            );
        }
 
        return () => {
            if (reader) {
                reader.reset();
            }
        };
    }, [scanning]);
 
    return (
        <div>
            {scanning ? (
                <video ref={videoRef} className="w-full" />
            ) : (
                <button onClick={() => setScanning(true)}>
                    Scanner un code
                </button>
            )}
        </div>
    );
}

Notifications locales

snippet.javascript
function requestNotificationPermission() {
    if ('Notification' in window) {
        Notification.requestPermission().then(permission => {
            console.log('Permission:', permission);
        });
    }
}
 
function showNotification(title, body) {
    if (Notification.permission === 'granted') {
        new Notification(title, { body });
    }
}

Points clés à retenir

  1. Géolocalisation avec navigator.geolocation ou composant Gps
  2. Upload avec PhotosUploader, FilesUploader, useFile
  3. Thème sombre via useGlobalStates et classes CSS
  4. Signature avec SignaturePad
  5. Intégrer des bibliothèques tierces selon les besoins

← Chapitre précédent | Retour au module | Module suivant : Bonnes pratiques →

Previous Next

Made with ❤ by CAP-REL · SmartMaker · GNU AGPL v3+
Code source · Faire un don
SmarMaker - Documentation
Traductions de cette page:
  • Français
  • Deutsch
  • English
  • Español
  • Italiano
  • Nederlands

Table of Contents

Table des matières

  • Chapitre 3 : Autres fonctionnalités
    • Géolocalisation
      • Obtenir la position
      • Composant Gps de SmartCommon
    • Upload de fichiers
      • PhotosUploader
      • FilesUploader
      • Redimensionner une image
    • Thème sombre
      • Configuration globale
      • Appliquer le thème
      • Toggle de thème
    • Signature manuscrite
    • Scan de code-barres
    • Notifications locales
    • Points clés à retenir
  • SmartAuth
  • SmartMaker - Back (PHP)
    • Mapping Dolibarr - React
  • SmartMaker - Front (React)
    • Animations de pages
    • Architecture
    • Astuces
    • Calendar
    • Composants et pages
    • Configuration du Provider
    • Debug et Logs
    • Hooks SmartCommon
    • PWA (Progressive Web App)
    • Requêtes API
    • Routage
    • SmartCommon
    • Stockage de données
    • Thèmes
    • Traductions
  • HowTo - Pas à pas - Votre première application
    • Développement PHP (back)
    • Développement React (front)
    • Première étape : Module Builder Dolibarr
    • SmartAuth
    • SmartBoot : Un "squelette" quasiment prêt à l'emploi
  • Formation SmartMaker
    • Module 1 : Fondamentaux JavaScript ES6+
      • Chapitre 1 : Variables et Scope
      • Chapitre 2 : Fonctions
      • Chapitre 3 : Programmation Asynchrone
      • Chapitre 4 : Modules ES6
    • Module 2 : Introduction à React
      • Chapitre 1 : Philosophie React
      • Chapitre 2 : JSX
      • Chapitre 3 : Composants
    • Module 3 : Hooks React Fondamentaux
      • Chapitre 1 : useState
      • Chapitre 2 : useEffect
      • Chapitre 3 : useRef
      • Chapitre 4 : useContext
    • Module 4 : React Avancé
      • Chapitre 1 : useCallback et useMemo
      • Chapitre 2 : Custom Hooks
      • Chapitre 3 : Redux et Redux Toolkit
    • Module 5 : Architecture SmartMaker
      • Chapitre 1 : Structure du projet
      • Chapitre 2 : Configuration
      • Chapitre 3 : Flux de données
    • Module 6 : SmartCommon - Composants
      • Chapitre 1 : Mise en page
      • Chapitre 2 : Navigation
      • Chapitre 3 : Formulaires
      • Chapitre 4 : Affichage
    • Module 7 : SmartCommon - Hooks
      • Chapitre 1 : useApi
      • Chapitre 2 : Gestion d'état
      • Chapitre 3 : Hooks utilitaires
    • Module 8 : Backend API (PHP)
      • Chapitre 1 : Routage
      • Chapitre 2 : Controllers
      • Chapitre 3 : Mappers
      • Extrafields et formulaires dynamiques
    • Module 9 : Intégration complète
      • Chapitre 1 : Backend
      • Chapitre 2 : Frontend
      • Chapitre 3 : Déploiement
    • Module 10 : Fonctionnalités avancées
      • Chapitre 1 : Mode offline
      • Chapitre 2 : Internationalisation (i18n)
      • Chapitre 3 : Autres fonctionnalités
    • Module 11 : Bonnes pratiques
  • Démonstration
  • Start
  • Composants et pages
  • Afficher le texte source
  • Anciennes révisions
  • Liens de retour
  • Haut de page