From 1dde9568b3aa75f81e54613e7600f68594aabb1b Mon Sep 17 00:00:00 2001 From: Samer Salameh Date: Thu, 12 Nov 2026 13:17:57 +0300 Subject: [PATCH] Richer dashboards and infographics, full screen with rotation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fleet, Personnel and Stakeholders infographics and the three statistics dashboards get their own layouts: headline totals, stat cards with icons, status heat-maps, gauges, rings, columns, icon bars and a gender pictogram - Full screen button on every dashboard: hides the menu and header (and asks the browser for full screen); in full screen the dashboards the user may open take turns every 5 seconds, with a countdown line and a pause button - Titles: "Fleet by stakeholders"; Arabic labels "شاشة كاملة" / "شاشة مصغرة" Co-Authored-By: Claude Sonnet 5.5 --- src/features/dashboard/DashboardPage.tsx | 71 ++- src/features/dashboard/dashboards.tsx | 433 ++++++++++++++++ src/features/dashboard/infographics.tsx | 605 +++++++++++++++++++++++ src/i18n/ui.ts | 4 + src/layout/AppShell.tsx | 15 +- src/layout/FullscreenContext.tsx | 43 ++ 6 files changed, 1160 insertions(+), 11 deletions(-) create mode 100644 src/features/dashboard/dashboards.tsx create mode 100644 src/features/dashboard/infographics.tsx create mode 100644 src/layout/FullscreenContext.tsx diff --git a/src/features/dashboard/DashboardPage.tsx b/src/features/dashboard/DashboardPage.tsx index 10f9a46..f32ce3e 100644 --- a/src/features/dashboard/DashboardPage.tsx +++ b/src/features/dashboard/DashboardPage.tsx @@ -1,7 +1,7 @@ -import { useMemo, useState } from 'react'; -import { useParams } from 'react-router-dom'; +import { useEffect, useMemo, useState, type ReactElement } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; import { useQuery } from '@tanstack/react-query'; -import { Alert, Avatar, Box, Chip, Paper, Skeleton, Stack, Typography, alpha, useTheme } from '@mui/material'; +import { Alert, Avatar, Box, Button, Chip, Paper, Skeleton, Stack, Typography, alpha, useTheme } from '@mui/material'; import { useAuth } from '../../auth/AuthContext'; import { isRtl, useLabel, useT, useUi } from '../../i18n'; import { PageHeader } from '../../components/PageHeader'; @@ -10,6 +10,14 @@ import type { Option } from '../../api/entity'; import { DASHBOARDS } from '../../layout/nav'; import { buildDashboard, buildInfographic, type Block, type Item } from './model'; import { blockIcon, itemTint } from './icons'; +import FullscreenOutlined from '@mui/icons-material/FullscreenOutlined'; +import FullscreenExitOutlined from '@mui/icons-material/FullscreenExitOutlined'; +import { useFullscreen } from '../../layout/FullscreenContext'; +import { useNav } from '../../layout/NavContext'; +import PauseOutlined from '@mui/icons-material/PauseOutlined'; +import PlayArrowOutlined from '@mui/icons-material/PlayArrowOutlined'; +import { FleetInfographic, PersonnelInfographic } from './infographics'; +import { FleetDashboard, PersonnelDashboard, StakeholderDashboard, StakeholdersInfographic } from './dashboards'; interface Page { kind: 'dashboard' | 'infographic'; @@ -26,6 +34,19 @@ const PAGES: Record = { 'stakeholders-infographic': { kind: 'infographic', name: 'STAKEHOLDERS_INFOGRAPH' }, }; +type CustomProps = { data: unknown; lab: (k: string) => string; rtl: boolean; nat: string }; +const CUSTOM: Record ReactElement> = { + stakeholders: StakeholderDashboard, + fleet: FleetDashboard, + personnel: PersonnelDashboard, + 'stakeholders-infographic': StakeholdersInfographic, + 'fleet-infographic': FleetInfographic, + 'personnel-infographic': PersonnelInfographic, +}; + +/** How long each dashboard stays up in full screen. */ +const ROTATE_MS = 5000; + const fmt = (n: number) => n.toLocaleString(); // titles / categories the system has no caption for (it falls back to a readable version of the code) @@ -43,7 +64,7 @@ const OWN: Record = { USAGE_TYPE_TANK: { en: 'Tankers by type', ar: 'الصهاريج حسب النوع' }, FLEET_LOCATION: { en: 'Fleet by industrial city', ar: 'المركبات حسب المدينة الصناعية' }, OTHER_TRAILERS_TYPE: { en: 'Other trailer types', ar: 'أنواع المقطورات الأخرى' }, - STAKEHOLDER_FLEET: { en: 'Fleet by stakeholder type', ar: 'المركبات حسب نوع صاحب المصلحة' }, + STAKEHOLDER_FLEET: { en: 'Fleet by stakeholders', ar: 'المركبات حسب الجهات' }, TRAILERS_TYPE: { en: 'Trailer types', ar: 'أنواع المقطورات' }, Educational_Level: { en: 'Education level', ar: 'المستوى التعليمي' }, Nationality: { en: 'Nationality', ar: 'الجنسية' }, @@ -318,6 +339,10 @@ export function DashboardPage() { const own = OWN[k] ?? OWN[k.toUpperCase()]; return caption(k) !== k ? caption(k) : own ? (isRtl(lang) ? own.ar : own.en) : humanize(k); }; + const fullscreen = useFullscreen(); + // leaving the page leaves full screen, so the menu is never left hidden on another page + const leave = fullscreen.exit; + useEffect(() => () => leave(), [leave]); const [location, setLocation] = useState(0); const [nat, setNat] = useState('ALL'); const meta = Object.values(DASHBOARDS).find((d) => d.slug === slug); @@ -347,13 +372,45 @@ export function DashboardPage() { return buildInfographic(data.data, lab, nat); }, [page, data.data, lab, nat]); + // in full screen the dashboards take turns: every few seconds the next one the user may open comes up + const nav = useNavigate(); + const { sections } = useNav(); + const slugs = useMemo(() => (sections.find((x) => x.key === 'dashboard')?.items ?? []).map((i) => i.to.replace('/dashboard/', '')), [sections]); + const [paused, setPaused] = useState(false); + const rotating = fullscreen.active && !paused && slugs.length > 1 && !data.isPending; + useEffect(() => { + if (!rotating) return; + const t = setTimeout(() => nav(`/dashboard/${slugs[(Math.max(0, slugs.indexOf(slug)) + 1) % slugs.length]}`), ROTATE_MS); + return () => clearTimeout(t); + }, [rotating, slug, slugs, nav]); + const Custom = CUSTOM[slug]; if (!page) return {ui('noResults')}; const title = meta ? (isRtl(lang) ? meta.ar : meta.en) : slug; const estates = locations.data?.INDUSTRIALESTATESARRAY ?? []; return ( <> - + {rotating && ( + + )} + + {fullscreen.active && slugs.length > 1 && ( + + )} + + + } + /> {page.locations && estates.length > 0 && ( )} )} - {!data.isPending && (() => { + {/* every dashboard and infographic has its own richer layout; the generic blocks below remain as the fallback */} + {!data.isPending && !data.error && Custom && } + {!data.isPending && !Custom && (() => { // the statistics (KPI tiles) always come first, as their own full-width row; the diagrams // that follow sit in a multi-column grid so they line up side by side wherever there is room const stats = model.blocks.filter((b) => b.kind === 'tiles'); diff --git a/src/features/dashboard/dashboards.tsx b/src/features/dashboard/dashboards.tsx new file mode 100644 index 0000000..990b050 --- /dev/null +++ b/src/features/dashboard/dashboards.tsx @@ -0,0 +1,433 @@ +import type { ElementType } from 'react'; +import { alpha, Box, Stack, Table, TableBody, TableCell, TableHead, TableRow, Typography } from '@mui/material'; +import CheckCircleOutline from '@mui/icons-material/CheckCircleOutlineOutlined'; +import ScheduleOutlined from '@mui/icons-material/ScheduleOutlined'; +import AutorenewOutlined from '@mui/icons-material/AutorenewOutlined'; +import ErrorOutlineOutlined from '@mui/icons-material/ErrorOutlineOutlined'; +import UndoOutlined from '@mui/icons-material/UndoOutlined'; +import BlockOutlined from '@mui/icons-material/BlockOutlined'; +import GroupsOutlined from '@mui/icons-material/GroupsOutlined'; +import LocationCityOutlined from '@mui/icons-material/LocationCityOutlined'; +import MapOutlined from '@mui/icons-material/MapOutlined'; +import FactCheckOutlined from '@mui/icons-material/FactCheckOutlined'; +import BadgeOutlined from '@mui/icons-material/BadgeOutlined'; +import PeopleAltOutlined from '@mui/icons-material/PeopleAltOutlined'; +import LocalShippingOutlined from '@mui/icons-material/LocalShippingOutlined'; +import Inventory2Outlined from '@mui/icons-material/Inventory2Outlined'; +import LocalGasStationOutlined from '@mui/icons-material/LocalGasStationOutlined'; +import SpeedOutlined from '@mui/icons-material/SpeedOutlined'; +import PublicOutlined from '@mui/icons-material/PublicOutlined'; +import FlagOutlined from '@mui/icons-material/FlagOutlined'; +import SchoolOutlined from '@mui/icons-material/SchoolOutlined'; +import WorkOutline from '@mui/icons-material/WorkOutlineOutlined'; +import FamilyRestroomOutlined from '@mui/icons-material/FamilyRestroomOutlined'; +import HowToRegOutlined from '@mui/icons-material/HowToRegOutlined'; +import CardMembershipOutlined from '@mui/icons-material/CardMembershipOutlined'; +import { + Columns, EDU, EDU_ORDER, FLEET, Gauge, Hero, IconBars, JOB, NATION, PALETTE, Panel, ProportionBar, Ring, StatCard, fmt, kind, n, pct, + type Label, type Part, type Row, type Tint, +} from './infographics'; +import { itemTint } from './icons'; + +/** The three dashboards (stakeholders, fleet, personnel) and the stakeholders infographic, in the same visual language as the other infographics. */ + +const TEXT = { + total: { en: 'Total', ar: 'الإجمالي' }, + registeredStakeholders: { en: 'Registered stakeholders', ar: 'الجهات المسجلة' }, + statuses: { en: 'Records by status', ar: 'السجلات حسب الحالة' }, + registeredRate: { en: 'Registered', ar: 'مسجّل' }, + byCity: { en: 'By industrial city', ar: 'حسب المدينة الصناعية' }, + cityTable: { en: 'Industrial cities in detail', ar: 'تفاصيل المدن الصناعية' }, + drivers: { en: 'Drivers by nationality', ar: 'السائقون حسب الجنسية' }, + omaniDrivers: { en: 'Omani', ar: 'عماني' }, + otherDrivers: { en: 'Other nationalities', ar: 'جنسيات أخرى' }, + investorsByCity: { en: 'Investors by industrial city', ar: 'المستثمرون حسب المدينة الصناعية' }, + totalFleet: { en: 'Registered fleet', ar: 'المركبات المسجلة' }, + fleetStatus: { en: 'Fleet by status', ar: 'المركبات حسب الحالة' }, + classes: { en: 'Fleet by class', ar: 'المركبات حسب الفئة' }, + cargo: { en: 'Trailers by cargo type', ar: 'المقطورات حسب نوع الحمولة' }, + tankers: { en: 'Tankers by type', ar: 'الصهاريج حسب النوع' }, + fleetByCity: { en: 'Fleet by industrial city', ar: 'المركبات حسب المدينة الصناعية' }, + workers: { en: 'Total workers', ar: 'إجمالي العاملين' }, + omani: { en: 'Omani', ar: 'عماني' }, + nonOmani: { en: 'Non-Omani', ar: 'غير عماني' }, + dataQuality: { en: 'Record quality', ar: 'جودة السجلات' }, + complete: { en: 'Complete records', ar: 'سجلات مكتملة' }, + incomplete: { en: 'Incomplete records', ar: 'سجلات غير مكتملة' }, + subscribed: { en: 'Subscribed', ar: 'مشترك' }, + notSubscribed: { en: 'Not subscribed', ar: 'غير مشترك' }, + hasRelatives: { en: 'Relatives in the country', ar: 'لديهم أقارب' }, + noRelatives: { en: 'No relatives', ar: 'بدون أقارب' }, + topNationalities: { en: 'Top nationalities', ar: 'أعلى الجنسيات' }, + education: { en: 'Education level', ar: 'المستوى التعليمي' }, + employment: { en: 'Employment category', ar: 'فئة التوظيف' }, + stakeholdersTotal: { en: 'Stakeholders', ar: 'الجهات' }, + ofTotal: { en: 'of the total', ar: 'من الإجمالي' }, +} as const; +type TextKey = keyof typeof TEXT; +const useText = (rtl: boolean) => (k: TextKey) => (rtl ? TEXT[k].ar : TEXT[k].en); + +const STATUS_TINT: Record = { + REGISTERED: { icon: CheckCircleOutline, color: '#5fb87a' }, + PENDING: { icon: ScheduleOutlined, color: '#e2a93b' }, + PENDING_UPDATE: { icon: AutorenewOutlined, color: '#2c98d4' }, + INCOMPLETE: { icon: ErrorOutlineOutlined, color: '#d1a233' }, + RETURNED: { icon: UndoOutlined, color: '#7c6fd1' }, + INACTIVE: { icon: BlockOutlined, color: '#8d98a4' }, +}; +const STATUS_ORDER = ['REGISTERED', 'PENDING', 'PENDING_UPDATE', 'INCOMPLETE', 'RETURNED', 'INACTIVE']; + +const META = new Set(['DASHBOARD_ORDER', 'DASHBOARD_SECTION', 'ENTITY_NAME', 'LOCATION_NAME', 'DATA', 'DATALBL']); +const metricsOf = (r: Row) => Object.entries(r).filter(([k, v]) => !META.has(k) && !/^\d+$/.test(k) && typeof v === 'number' && Number.isFinite(v)) as [string, number][]; +const section = (rows: Row[], name: string) => rows.filter((r) => r.DASHBOARD_SECTION === name); +const asRows = (data: unknown) => (Array.isArray(data) ? data : []) as Row[]; +const sum = (xs: number[]) => xs.reduce((a, v) => a + v, 0); + +/** Records by status per kind: a heat-map table and a "registered" ring for each. */ +function StatusPanel({ items, lab, title, tx }: { items: { code: string; label: string; tint: Tint; values: Record }[]; lab: Label; title: string; tx: (k: TextKey) => string }) { + const statuses = STATUS_ORDER.filter((s) => items.some((i) => (i.values[s] ?? 0) > 0)); + return ( + + + + + + + {statuses.map((s) => { + const Icon = STATUS_TINT[s].icon; + return ( + + + + {lab(s)} + + + ); + })} + {tx('total')} + + + + {items.map((i) => { + const total = sum(Object.values(i.values)); + const Icon = i.tint.icon; + return ( + + + + + {i.label} + + + {statuses.map((s) => { + const v = i.values[s] ?? 0; + const share = total ? v / total : 0; + return ( + + {fmt(v)} + + ); + })} + {fmt(total)} + + ); + })} + +
+
+ + {items.map((i) => ( + + ))} + +
+ ); +} + +/** Industrial cities: a heat-map of kinds per city, leaving out the cities with nothing. */ +function CityTable({ rows, keys, lab, nameOf, tintOf, title, tx }: { rows: Row[]; keys: string[]; lab: Label; nameOf: (k: string) => string; tintOf: (k: string, i: number) => Tint; title: string; tx: (k: TextKey) => string }) { + const cities = rows + .map((r) => ({ name: lab(String(r.LOCATION_NAME ?? '')), values: keys.map((k) => Number(r[k] ?? 0) || 0) })) + .filter((c) => sum(c.values) > 0) + .sort((a, b) => sum(b.values) - sum(a.values)); + if (!cities.length) return null; + return ( + + + + + + + {keys.map((k, i) => { + const t = tintOf(k, i); + const Icon = t.icon; + return ( + + + + {nameOf(k)} + + + ); + })} + {tx('total')} + + + + {cities.map((c) => ( + + + + + {c.name} + + + {c.values.map((v, i) => { + const t = tintOf(keys[i], i); + const max = Math.max(1, ...cities.map((x) => x.values[i])); + return {fmt(v)}; + })} + {fmt(sum(c.values))} + + ))} + +
+
+
+ ); +} + +const cityColumns = (rows: Row[], keys: string[], lab: Label): Part[] => + rows + .map((r, i) => ({ key: String(r.LOCATION_NAME), label: lab(String(r.LOCATION_NAME ?? '')), value: sum(keys.map((k) => Number(r[k] ?? 0) || 0)), tint: { icon: LocationCityOutlined, color: PALETTE[i % PALETTE.length] } as Tint })) + .filter((p) => p.value > 0) + .sort((a, b) => b.value - a.value); + +// ------------------------------------------------------------------------------------------------ stakeholders dashboard + +export function StakeholderDashboard({ data, lab, rtl }: { data: unknown; lab: Label; rtl: boolean }) { + const rows = asRows(data); + const tx = useText(rtl); + const counted = section(rows, 'REGISTERED_STAKEHOLDER').map((r, i) => { + const code = String(r.ENTITY_NAME); + return { code, value: n(r.REGISTERED_INCOMPLETE), tint: itemTint(code, i), label: code === 'OWNERS' ? (rtl ? 'المالكون' : 'Owners') : lab(code) }; + }); + const grand = sum(counted.map((c) => c.value)); + const statusItems = section(rows, 'STAKEHOLDER_STATUS_CODES').map((r, i) => { + const code = String(r.ENTITY_NAME); + // the status rows of OWNERS count the driver-owners (about 19,000), so they keep the system's own name for them + return { code, label: lab(code), tint: itemTint(code, i), values: Object.fromEntries(metricsOf(r)) as Record }; + }); + const cityRows = section(rows, 'STAKEHOLDER_LOCATION'); + const cityKeys = ['INVESTORS', 'OTHER_STAKEHOLDERS'].filter((k) => cityRows.some((r) => n(r[k]) > 0)); + const cols = cityColumns(cityRows, cityKeys, lab); + + return ( + + ({ key: c.code, label: c.label, value: c.value, tint: c.tint }))} /> + + {counted.map((c) => ( + + ))} + + {statusItems.length > 0 && } + {cols.length > 0 && ( + + + lab(k)} + tintOf={(k, i) => itemTint(k, i)} + title={tx('cityTable')} + tx={tx} + /> + + )} + + ); +} + +// ------------------------------------------------------------------------------------------------ stakeholders infographic + +export function StakeholdersInfographic({ data, lab, rtl }: { data: unknown; lab: Label; rtl: boolean }) { + const rows = asRows(data); + const tx = useText(rtl); + const cnt = (code: string) => n(rows.find((r) => r.ENTITY_NAME === code)?.CNT); + const main = ['INVESTORS', 'COMPANIES', 'OWNERS', 'OTHER_STAKEHOLDERS', 'FREEZONE_CLEARING_COMPANIES'] + .filter((c) => rows.some((r) => r.ENTITY_NAME === c)) + .map((code, i) => ({ code, value: cnt(code), tint: itemTint(code, i), label: lab(code) })); + const grand = sum(main.map((m) => m.value)); + const omani = cnt('OMN_NAT_DRVR'); + const others = cnt('OTHER_NAT_DRVR'); + const cities = rows + .filter((r) => String(r.ENTITY_NAME).startsWith('INVESTORS_')) + .map((r, i) => ({ key: String(r.ENTITY_NAME), label: lab(String(r.ENTITY_NAME)), value: n(r.CNT), tint: { icon: LocationCityOutlined, color: PALETTE[i % PALETTE.length] } as Tint })) + .sort((a, b) => b.value - a.value); + + return ( + + ({ key: m.code, label: m.label, value: m.value, tint: m.tint }))} /> + + {main.map((m) => )} + + + {omani + others > 0 && ( + + + + )} + {cities.length > 0 && ( + + + + )} + + + ); +} + +// ------------------------------------------------------------------------------------------------ fleet dashboard + +export function FleetDashboard({ data, lab, rtl }: { data: unknown; lab: Label; rtl: boolean }) { + const rows = asRows(data); + const tx = useText(rtl); + const totals = section(rows, 'REGISTERED_FLEET').map((r) => ({ code: String(r.ENTITY_NAME), value: n(r.REGISTERED_INCOMPLETE) })); + const grand = sum(totals.map((t) => t.value)); + const statusItems = section(rows, 'FLEET_DETAILS').map((r) => { + const code = String(r.ENTITY_NAME); + return { code, label: lab(code), tint: FLEET[code] ?? itemTint(code, 0), values: Object.fromEntries(metricsOf(r)) as Record }; + }); + const typeParts = (entity: string): Part[] => + section(rows, 'FLEET_TYPE') + .filter((r) => r.ENTITY_NAME === entity) + .flatMap((r) => metricsOf(r)) + .map(([k, v], i) => ({ key: k, label: lab(k), value: v, tint: kind(k, i) })) + .sort((a, b) => b.value - a.value); + const usage = (name: string): Part[] => + section(rows, name) + .map((r, i) => ({ key: String(r.DATALBL ?? r.ENTITY_NAME), label: lab(String(r.DATALBL ?? r.ENTITY_NAME)), value: n(r.DATA), tint: kind(String(r.DATALBL ?? r.ENTITY_NAME), i) })) + .filter((p) => p.value > 0) + .sort((a, b) => b.value - a.value); + const cargo = usage('USAGE_TYPE_CARGO'); + const tankers = usage('USAGE_TYPE_TANK'); + const cityRows = section(rows, 'FLEET_LOCATION'); + const fleetKeys = Object.keys(FLEET).filter((k) => cityRows.some((r) => n(r[k]) > 0)); + const cols = cityColumns(cityRows, fleetKeys, lab); + const gauges: { entity: string; title: string; icon: ElementType; color: string }[] = [ + { entity: 'TRUCKS', title: lab('TRUCKS'), icon: LocalShippingOutlined, color: '#2c98d4' }, + { entity: 'EQUIPMENTS', title: lab('EQUIPMENTS'), icon: SpeedOutlined, color: '#5fb87a' }, + { entity: 'BUSES', title: lab('BUSES'), icon: SpeedOutlined, color: '#d16475' }, + ]; + + return ( + + ({ key: t.code, label: lab(t.code), value: t.value, tint: FLEET[t.code] ?? itemTint(t.code, 0) }))} /> + + {totals.map((t) => )} + + {statusItems.length > 0 && } + + {gauges.map((g) => { + const parts = typeParts(g.entity); + if (!parts.length) return null; + return ( + + {parts.length >= 2 ? : } + + ); + })} + + + {cargo.length > 0 && } + {tankers.length > 0 && } + + {cols.length > 0 && ( + + + lab(k)} tintOf={(k) => FLEET[k]} title={tx('fleetByCity')} tx={tx} /> + + )} + + ); +} + +// ------------------------------------------------------------------------------------------------ personnel dashboard + +export function PersonnelDashboard({ data, lab, rtl }: { data: unknown; lab: Label; rtl: boolean }) { + const rows = asRows(data); + const tx = useText(rtl); + const one = (name: string) => section(rows, name)[0] ?? {}; + const header = one('PERSONNEL_HEADER'); + const status = one('PERSONNEL_STATUS_CODES'); + const rel = one('PERSONNEL_RELATIVES'); + const omani = n(header.OMN_NAT); + const others = n(header.OTHERS_NAT); + const registered = n(status.REGISTERED); + const incomplete = n(status.INCOMPLETE); + const total = omani + others || registered + incomplete; + const subscribed = n(header.SUBSCRIPED); + const notSub = n(header.NOT_SUBSCRIPED); + const yes = n(rel.YES); + const no = n(rel.NO); + + const eduRow = one('PERSONNEL_EDUCATIONAL_LEVEL'); + const edu: Part[] = [...EDU_ORDER, ...Object.keys(eduRow).filter((k) => !EDU_ORDER.includes(k) && typeof eduRow[k] === 'number' && !META.has(k) && !/^\d+$/.test(k))] + .filter((k) => n(eduRow[k]) > 0) + .map((k, i) => ({ key: k, label: lab(k), value: n(eduRow[k]), tint: EDU[k] ?? kind(k, i) })); + const jobs: Part[] = metricsOf(one('PERSONNEL_EMPLOYMENT_CATEGORY')) + .map(([k, v], i) => ({ key: k, label: lab(k), value: v, tint: JOB[k] ?? kind(k, i) })) + .sort((a, b) => b.value - a.value); + const topRow = rows.find((r) => r.TOP_NATIONALITY && typeof r.TOP_NATIONALITY === 'object')?.TOP_NATIONALITY as Record | undefined; + const nations: Part[] = Object.entries(topRow ?? {}) + .map(([code, v], i) => ({ key: code, label: lab(code), value: n(v?.[0]), tint: { icon: FlagOutlined, color: NATION[code]?.color ?? PALETTE[(i + 3) % PALETTE.length] } as Tint })) + .sort((a, b) => b.value - a.value); + + return ( + + + + + + + + + + + + + + + + + + + + {nations.length > 0 && } + {edu.length > 0 && } + + {jobs.length > 0 && ( + + + + + )} + + ); +} diff --git a/src/features/dashboard/infographics.tsx b/src/features/dashboard/infographics.tsx new file mode 100644 index 0000000..bfbe2d2 --- /dev/null +++ b/src/features/dashboard/infographics.tsx @@ -0,0 +1,605 @@ +import type { ElementType, ReactNode } from 'react'; +import { alpha, Avatar, Box, Paper, Stack, Table, TableBody, TableCell, TableHead, TableRow, Typography, useTheme } from '@mui/material'; +import LocalShippingOutlined from '@mui/icons-material/LocalShippingOutlined'; +import Inventory2Outlined from '@mui/icons-material/Inventory2Outlined'; +import ConstructionOutlined from '@mui/icons-material/ConstructionOutlined'; +import DirectionsBusOutlined from '@mui/icons-material/DirectionsBusOutlined'; +import DirectionsCarOutlined from '@mui/icons-material/DirectionsCarOutlined'; +import AirportShuttleOutlined from '@mui/icons-material/AirportShuttleOutlined'; +import HandymanOutlined from '@mui/icons-material/HandymanOutlined'; +import ScienceOutlined from '@mui/icons-material/ScienceOutlined'; +import TerrainOutlined from '@mui/icons-material/TerrainOutlined'; +import RvHookupOutlined from '@mui/icons-material/RvHookupOutlined'; +import LayersOutlined from '@mui/icons-material/LayersOutlined'; +import AcUnitOutlined from '@mui/icons-material/AcUnitOutlined'; +import ViewInArOutlined from '@mui/icons-material/ViewInArOutlined'; +import LocalGasStationOutlined from '@mui/icons-material/LocalGasStationOutlined'; +import WaterDropOutlined from '@mui/icons-material/WaterDropOutlined'; +import OilBarrelOutlined from '@mui/icons-material/OilBarrelOutlined'; +import MedicalServicesOutlined from '@mui/icons-material/MedicalServicesOutlined'; +import RecyclingOutlined from '@mui/icons-material/RecyclingOutlined'; +import RouteOutlined from '@mui/icons-material/RouteOutlined'; +import FoundationOutlined from '@mui/icons-material/FoundationOutlined'; +import CategoryOutlined from '@mui/icons-material/CategoryOutlined'; +import TrendingUpOutlined from '@mui/icons-material/TrendingUpOutlined'; +import BusinessOutlined from '@mui/icons-material/BusinessOutlined'; +import BadgeOutlined from '@mui/icons-material/BadgeOutlined'; +import GroupsOutlined from '@mui/icons-material/GroupsOutlined'; +import ManOutlined from '@mui/icons-material/ManOutlined'; +import WomanOutlined from '@mui/icons-material/WomanOutlined'; +import FlagOutlined from '@mui/icons-material/FlagOutlined'; +import PublicOutlined from '@mui/icons-material/PublicOutlined'; +import LanguageOutlined from '@mui/icons-material/LanguageOutlined'; +import MenuBookOutlined from '@mui/icons-material/MenuBookOutlined'; +import SchoolOutlined from '@mui/icons-material/SchoolOutlined'; +import WorkspacePremiumOutlined from '@mui/icons-material/WorkspacePremiumOutlined'; +import VerifiedOutlined from '@mui/icons-material/VerifiedOutlined'; +import PsychologyOutlined from '@mui/icons-material/PsychologyOutlined'; +import EmojiEventsOutlined from '@mui/icons-material/EmojiEventsOutlined'; +import ManageAccountsOutlined from '@mui/icons-material/ManageAccountsOutlined'; +import SupervisorAccountOutlined from '@mui/icons-material/SupervisorAccountOutlined'; +import EngineeringOutlined from '@mui/icons-material/EngineeringOutlined'; +import PeopleAltOutlined from '@mui/icons-material/PeopleAltOutlined'; +import PieChartOutlined from '@mui/icons-material/PieChartOutlined'; +import StackedBarChartOutlined from '@mui/icons-material/StackedBarChartOutlined'; +import GridViewOutlined from '@mui/icons-material/GridViewOutlined'; +import BarChartOutlined from '@mui/icons-material/BarChartOutlined'; +import SpeedOutlined from '@mui/icons-material/SpeedOutlined'; +import WorkOutline from '@mui/icons-material/WorkOutlineOutlined'; + +/** The two infographics get their own layouts: big totals, share bars, gauges, rings, columns, a heat-map and a pictogram. */ +export type Row = Record; +export type Label = (key: string) => string; +export interface Tint { icon: ElementType; color: string } + +export const n = (v: unknown) => Number(v ?? 0) || 0; +export const fmt = (v: number) => v.toLocaleString(); +export const pct = (v: number, total: number) => (total > 0 ? Math.round((v / total) * 100) : 0); + +// ------------------------------------------------------------------------------------------------ tints + +export const FLEET: Record = { + TRUCKS: { icon: LocalShippingOutlined, color: '#2c98d4' }, + TRAILERS: { icon: Inventory2Outlined, color: '#cbb67d' }, + EQUIPMENTS: { icon: ConstructionOutlined, color: '#5fb87a' }, + BUSES: { icon: DirectionsBusOutlined, color: '#d16475' }, + CARS: { icon: DirectionsCarOutlined, color: '#7c6fd1' }, +}; +export const OWNER: Record = { + '7': { icon: TrendingUpOutlined, color: '#5fb87a' }, + '11': { icon: BusinessOutlined, color: '#2c98d4' }, + '10': { icon: BadgeOutlined, color: '#cbb67d' }, + '12': { icon: GroupsOutlined, color: '#7c6fd1' }, +}; +export const OWNER_NAME: Record = { '7': 'INVESTORS', '10': 'OWNERS', '11': 'COMPANIES', '12': 'OTHER_STAKEHOLDERS' }; +export const OWNER_ORDER = ['7', '11', '10', '12']; + +export const KIND: Record = { + HEAVY: { icon: LocalShippingOutlined, color: '#2c98d4' }, + MEDIUM: { icon: LocalShippingOutlined, color: '#e2a93b' }, + LARGE: { icon: DirectionsBusOutlined, color: '#d16475' }, + SMALL: { icon: AirportShuttleOutlined, color: '#7c6fd1' }, + HEAVYEQUIPMENT: { icon: ConstructionOutlined, color: '#5fb87a' }, + MEDIUMEQUIPMENT: { icon: HandymanOutlined, color: '#e2a93b' }, + CHEMICAL_TANKER: { icon: ScienceOutlined, color: '#d16475' }, + DUMP_TRUCK: { icon: TerrainOutlined, color: '#a5894f' }, + FLATBED_TRAILER: { icon: RvHookupOutlined, color: '#2c98d4' }, + MULTI_TRAILER: { icon: LayersOutlined, color: '#7c6fd1' }, + REFRIGERATED_TRAILER: { icon: AcUnitOutlined, color: '#1cabe3' }, + SIDE_WALL_GENERAL_CARGO: { icon: ViewInArOutlined, color: '#5fb87a' }, + OTHER: { icon: CategoryOutlined, color: '#8d98a4' }, + CAR_CARRIER_TRAIER: { icon: DirectionsCarOutlined, color: '#7c6fd1' }, + BULK_TRAILER: { icon: TerrainOutlined, color: '#a5894f' }, + LOWBED: { icon: LocalShippingOutlined, color: '#d1a233' }, + FUEL_TANK: { icon: LocalGasStationOutlined, color: '#d16475' }, + WATER_TANKER: { icon: WaterDropOutlined, color: '#1cabe3' }, + OIL_TANK: { icon: OilBarrelOutlined, color: '#a5894f' }, + MEDICAL_OXYGEN_TANK: { icon: MedicalServicesOutlined, color: '#5fb87a' }, + RAW_MATERIAL_TANK: { icon: ScienceOutlined, color: '#7c6fd1' }, + VEGETABLE_OIL_TANK: { icon: WaterDropOutlined, color: '#d1a233' }, + WASTE_OIL_TANKER: { icon: RecyclingOutlined, color: '#8d98a4' }, + ASPHALT_TANKER: { icon: RouteOutlined, color: '#5b6b7d' }, + CEMENT_TANK: { icon: FoundationOutlined, color: '#cbb67d' }, +}; +export const kind = (code: string, i: number): Tint => KIND[code] ?? { icon: CategoryOutlined, color: PALETTE[i % PALETTE.length] }; +export const PALETTE = ['#2c98d4', '#d16475', '#5fb87a', '#e2a93b', '#7c6fd1', '#cbb67d', '#1cabe3', '#a5894f']; + +export const EDU: Record = { + PRIMARY: { icon: MenuBookOutlined, color: '#cbb67d' }, + SECONDARY: { icon: SchoolOutlined, color: '#2c98d4' }, + DIPLOMA: { icon: WorkspacePremiumOutlined, color: '#5fb87a' }, + BA: { icon: VerifiedOutlined, color: '#7c6fd1' }, + MA: { icon: PsychologyOutlined, color: '#d16475' }, + PHD: { icon: EmojiEventsOutlined, color: '#d1a233' }, +}; +export const EDU_ORDER = ['PRIMARY', 'SECONDARY', 'DIPLOMA', 'BA', 'MA', 'PHD']; +export const JOB: Record = { + MANAGERIAL: { icon: ManageAccountsOutlined, color: '#7c6fd1' }, + SUPERVISORY: { icon: SupervisorAccountOutlined, color: '#2c98d4' }, + SKILLED: { icon: EngineeringOutlined, color: '#5fb87a' }, + UNSKILLED: { icon: HandymanOutlined, color: '#e2a93b' }, +}; +export const NATION: Record = { + OMN: { icon: FlagOutlined, color: '#13964c' }, + IND: { icon: PublicOutlined, color: '#e2a93b' }, + OTHERS: { icon: LanguageOutlined, color: '#7c6fd1' }, +}; +const MALE = '#2c98d4'; +const FEMALE = '#d16475'; + +// ------------------------------------------------------------------------------------------------ own texts + +const TEXT = { + totalFleet: { en: 'Total fleet', ar: 'إجمالي المركبات' }, + ofFleet: { en: 'of the fleet', ar: 'من المركبات' }, + mix: { en: 'Fleet composition', ar: 'تركيبة المركبات' }, + ownership: { en: 'Who owns the fleet', ar: 'ملكية المركبات' }, + ownerTotals: { en: 'Fleet by stakeholders', ar: 'المركبات حسب الجهات' }, + trucks: { en: 'Trucks by class', ar: 'الشاحنات حسب الفئة' }, + equipment: { en: 'Equipment by class', ar: 'المعدات حسب الفئة' }, + buses: { en: 'Buses by size', ar: 'الباصات حسب الحجم' }, + trailers: { en: 'Trailer types', ar: 'أنواع المقطورات' }, + total: { en: 'Total', ar: 'الإجمالي' }, + totalWorkers: { en: 'Total workers', ar: 'إجمالي العاملين' }, + omani: { en: 'Omani', ar: 'عماني' }, + nonOmani: { en: 'Non-Omani', ar: 'غير عماني' }, + male: { en: 'Male', ar: 'ذكور' }, + female: { en: 'Female', ar: 'إناث' }, + nationality: { en: 'Nationality', ar: 'الجنسية' }, + gender: { en: 'Gender', ar: 'الجنس' }, + education: { en: 'Education level', ar: 'المستوى التعليمي' }, + employment: { en: 'Employment category', ar: 'فئة التوظيف' }, + share: { en: 'share', ar: 'النسبة' }, +} as const; +type TextKey = keyof typeof TEXT; + +// ------------------------------------------------------------------------------------------------ building blocks + +export function Panel({ icon: Icon, color, title, children, sx }: { icon: ElementType; color: string; title: string; children: ReactNode; sx?: object }) { + return ( + + + + + + {title} + + {children} + + ); +} + +/** A coloured stat card: icon badge, big number, label and a small share bar. */ +export function StatCard({ tint, value, label, share, sub }: { tint: Tint; value: number; label: string; share?: number; sub?: string }) { + const Icon = tint.icon; + return ( + + + + + + + + + + {fmt(value)} + {label} + + + {share !== undefined && ( + + + 0 ? 3 : 0 }} /> + + {share}% {sub} + + )} + + ); +} + +export interface Part { key: string; label: string; value: number; tint: Tint } + +/** One bar split into coloured parts, with an icon legend: how a whole divides. */ +export function ProportionBar({ parts, light }: { parts: Part[]; light?: boolean }) { + const total = parts.reduce((a, p) => a + p.value, 0); + return ( + + + {parts.filter((p) => p.value > 0).map((p) => ( + + ))} + + + {parts.map((p) => { + const Icon = p.tint.icon; + return ( + + + {p.label} + {pct(p.value, total)}% + + ); + })} + + + ); +} + +/** A half-circle meter for a two-way split; the big number is the first part's share. */ +export function Gauge({ a, b }: { a: Part; b: Part }) { + const theme = useTheme(); + const total = a.value + b.value; + const L = Math.PI * 50; + const share = total > 0 ? a.value / total : 0; + const arc = 'M10 60 A50 50 0 0 1 110 60'; + return ( + + + + + + + + + {pct(a.value, total)}% + {a.label} + + + + {[a, b].map((p) => { + const Icon = p.tint.icon; + return ( + + + {fmt(p.value)} + {p.label} + + ); + })} + + + ); +} + +/** A progress ring with an icon in the middle. */ +export function Ring({ part, total }: { part: Part; total: number }) { + const C = 2 * Math.PI * 34; + const Icon = part.tint.icon; + const share = total > 0 ? part.value / total : 0; + return ( + + + + + + + + + + {Math.round(share * 100)}% + + + + {fmt(part.value)} + {part.label} + + ); +} + +/** Vertical columns with an icon under each: a ranking or a ladder (education). */ +export function Columns({ parts }: { parts: Part[] }) { + const max = Math.max(1, ...parts.map((p) => p.value)); + return ( + + {parts.map((p) => { + const Icon = p.tint.icon; + const h = Math.max(4, (p.value / max) * 130); + return ( + + {fmt(p.value)} + + + + + {p.label} + + ); + })} + + ); +} + +/** Horizontal bars with an icon badge in front and the share at the end. */ +export function IconBars({ parts, columns }: { parts: Part[]; columns?: boolean }) { + const max = Math.max(1, ...parts.map((p) => p.value)); + const total = parts.reduce((a, p) => a + p.value, 0); + return ( + + {parts.map((p) => { + const Icon = p.tint.icon; + return ( + + + + + + + {p.label} + + {fmt(p.value)} · {pct(p.value, total)}% + + + + + + + + ); + })} + + ); +} + +/** Twenty little people coloured by the split: a pictogram. */ +export function Pictogram({ a, b, icons: [IconA, IconB] }: { a: Part; b: Part; icons: [ElementType, ElementType] }) { + const total = a.value + b.value; + const countA = total ? Math.round((a.value / total) * 20) : 0; + return ( + + + {Array.from({ length: 20 }, (_, i) => { + const first = i < countA; + const Icon = first ? IconA : IconB; + return ; + })} + + + {[a, b].map((p) => ( + + {pct(p.value, total)}% + {fmt(p.value)} + {p.label} + + ))} + + + ); +} + +/** The big blue headline of a dashboard: one total, with the proportion bar of what it is made of. */ +export function Hero({ icon: Icon, label, value, parts }: { icon: ElementType; label: string; value: number; parts: Part[] }) { + return ( + + + + + + {label} + {fmt(value)} + + + + + + + ); +} + +// ------------------------------------------------------------------------------------------------ fleet + +export function FleetInfographic({ data, lab, rtl }: { data: unknown; lab: Label; rtl: boolean }) { + const rows = (Array.isArray(data) ? data : []) as Row[]; + const tx = (k: TextKey) => (rtl ? TEXT[k].ar : TEXT[k].en); + const owned = rows.filter((r) => r.TYPE === 'STAKEHOLDER_FLEET'); + const entities = Object.keys(FLEET).filter((e) => owned.some((r) => r.ENTITY_NAME === e)); + const count = (entity: string, owner?: string) => + owned.filter((r) => r.ENTITY_NAME === entity && (owner === undefined || String(r.KEY) === owner)).reduce((a, r) => a + n(r.CNT), 0); + const totals = entities.map((e) => ({ e, v: count(e) })); + const grand = totals.reduce((a, t) => a + t.v, 0); + const parts = (type: string, entity: string): Part[] => + rows + .filter((r) => r.TYPE === type && r.ENTITY_NAME === entity) + .map((r, i) => ({ key: String(r.KEY), label: lab(String(r.KEY)), value: n(r.CNT), tint: kind(String(r.KEY), i) })) + .sort((a, b) => b.value - a.value); + + const truck = parts('TRUCK_TYPE', 'TRUCKS'); + const equip = parts('TRUCK_TYPE', 'EQUIPMENTS'); + const bus = parts('TRUCK_TYPE', 'BUSES'); + const trailers = [...parts('TRAILERS_TYPE', 'TRAILERS'), ...parts('OTHER_TRAILERS_TYPE', 'TRAILERS')].sort((a, b) => b.value - a.value); + const byOwner: Part[] = OWNER_ORDER.map((o) => ({ + key: o, + label: lab(OWNER_NAME[o]), + value: entities.reduce((a, e) => a + count(e, o), 0), + tint: OWNER[o], + })).sort((a, b) => b.value - a.value); + const gauge = (list: Part[]) => (list.length >= 2 ? : ); + + return ( + + {/* the headline: the whole fleet and how it divides between the five kinds */} + + + + + + {tx('totalFleet')} + {fmt(grand)} + + + + ({ key: t.e, label: lab(t.e), value: t.v, tint: FLEET[t.e] }))} /> + + + + + {totals.map((t) => ( + + ))} + + + + + + + + + + {OWNER_ORDER.map((o) => { + const Icon = OWNER[o].icon; + return ( + + + + {lab(OWNER_NAME[o])} + + + ); + })} + {tx('total')} + + + + {entities.map((e) => { + const Icon = FLEET[e].icon; + const rowTotal = count(e); + return ( + + + + + {lab(e)} + + + {OWNER_ORDER.map((o) => { + const v = count(e, o); + const share = rowTotal ? v / rowTotal : 0; + return ( + + {fmt(v)} + {pct(v, rowTotal)}% + + ); + })} + {fmt(rowTotal)} + + ); + })} + +
+
+
+ + + +
+ + + {truck.length > 0 && {gauge(truck)}} + {equip.length > 0 && {gauge(equip)}} + {bus.length > 0 && {gauge(bus)}} + + {trailers.length > 0 && ( + + + + )} +
+ ); +} + +// ------------------------------------------------------------------------------------------------ personnel + +export function PersonnelInfographic({ data, lab, rtl, nat }: { data: unknown; lab: Label; rtl: boolean; nat: string }) { + const rows = (Array.isArray(data) ? data : []) as Row[]; + const tx = (k: TextKey) => (rtl ? TEXT[k].ar : TEXT[k].en); + const nats = [...new Set(rows.map((r) => r.NAT).filter((x): x is string => typeof x === 'string'))]; + const filtered = nats.length ? rows.filter((r) => r.NAT === nat) : rows; + const of = (type: string, list = filtered) => list.filter((r) => r.TYPE === type); + const val = (type: string, key: string, list = filtered) => n(of(type, list).find((r) => String(r.KEY) === key)?.CNT); + + // nationality always shows the whole workforce, whichever nationality filter is on + const nation = rows.filter((r) => r.TYPE === 'Nationality'); + const everyone = n(nation.find((r) => r.NAT === 'ALL')?.CNT); + const omani = n(nation.find((r) => r.NAT === 'OMN')?.CNT); + const indian = n(nation.find((r) => r.NAT === 'IND')?.CNT); + const others = n(nation.find((r) => r.NAT === 'OTHERS')?.CNT); + const shown = nat === 'ALL' || !nats.length ? everyone : n(nation.find((r) => r.NAT === nat)?.CNT); + + const male = val('GENDER', 'MALE'); + const female = val('GENDER', 'FEMALE'); + + const edu: Part[] = [ + ...EDU_ORDER.filter((k) => val('Educational_Level', k) > 0), + ...of('Educational_Level').map((r) => String(r.KEY)).filter((k) => !EDU_ORDER.includes(k)), + ].map((k, i) => ({ key: k, label: lab(k), value: val('Educational_Level', k), tint: EDU[k] ?? kind(k, i) })); + const jobs: Part[] = of('CATEGORY_OF_EMPLOYMENT') + .map((r, i) => ({ key: String(r.KEY), label: lab(String(r.KEY)), value: n(r.CNT), tint: JOB[String(r.KEY)] ?? kind(String(r.KEY), i) })) + .sort((a, b) => b.value - a.value); + + return ( + + + + + + + + + + + + {[ + { key: 'OMN', label: lab('OMN_NAT') !== 'OMN_NAT' ? lab('OMN_NAT') : tx('omani'), value: omani }, + { key: 'IND', label: lab('IND'), value: indian }, + { key: 'OTHERS', label: lab('OTHERS_NAT') !== 'OTHERS_NAT' ? lab('OTHERS_NAT') : lab('OTHERS'), value: others }, + ].map((p) => )} + + + + + + + + + {edu.length > 0 && ( + + + + )} + {jobs.length > 0 && ( + + + + + + + )} + + + ); +} + +export const MALE_TINT: Tint = { icon: ManOutlined, color: MALE }; +export const FEMALE_TINT: Tint = { icon: WomanOutlined, color: FEMALE }; + diff --git a/src/i18n/ui.ts b/src/i18n/ui.ts index 7c95f03..291a739 100644 --- a/src/i18n/ui.ts +++ b/src/i18n/ui.ts @@ -37,6 +37,10 @@ export const UI = { exportAll: { en: 'No filters are applied: every record will be exported.', ar: 'لا توجد عوامل تصفية: سيتم تصدير جميع السجلات.' }, exportReady: { en: 'The file is ready and is downloading', ar: 'الملف جاهز ويجري تنزيله' }, saved: { en: 'Saved successfully', ar: 'تم الحفظ بنجاح' }, + fullscreen: { en: 'Full screen', ar: 'شاشة كاملة' }, + pauseRotation: { en: 'Pause', ar: 'إيقاف التبديل' }, + resumeRotation: { en: 'Resume', ar: 'متابعة التبديل' }, + exitFullscreen: { en: 'Exit full screen', ar: 'شاشة مصغرة' }, copy: { en: 'Copy', ar: 'نسخ' }, copied: { en: 'Copied', ar: 'تم النسخ' }, close: { en: 'Close', ar: 'إغلاق' }, diff --git a/src/layout/AppShell.tsx b/src/layout/AppShell.tsx index 4715b0b..a2f3e28 100644 --- a/src/layout/AppShell.tsx +++ b/src/layout/AppShell.tsx @@ -23,6 +23,7 @@ import { roleLabel } from '../i18n/roles'; import { useColorMode } from '../theme'; import { NavProvider, useNav } from './NavContext'; import { RAIL_WIDTH, SIDEBAR_WIDTH, Sidebar } from './Sidebar'; +import { FullscreenProvider, useFullscreen } from './FullscreenContext'; import { CommandPalette } from './CommandPalette'; import { GlobalLoading } from '../components/GlobalLoading'; @@ -102,6 +103,8 @@ function Shell() { const theme = useTheme(); const wide = useMediaQuery(theme.breakpoints.up('md')); const [drawer, setDrawer] = useState(false); + // full screen (dashboards): no menu and no header, the page takes the whole window + const { active: bare } = useFullscreen(); const [palette, setPalette] = useState(false); const [menuEl, setMenuEl] = useState(null); const [changePasswordOpen, setChangePasswordOpen] = useState(false); @@ -146,7 +149,7 @@ function Shell() { - {wide ? ( + {bare ? null : wide ? ( @@ -157,7 +160,7 @@ function Shell() { )} - + {!bare && {!wide && setDrawer(true)}>} @@ -184,7 +187,7 @@ function Shell() { - + } setMenuEl(null)} slotProps={{ paper: { sx: { minWidth: 220 } } }}> @@ -231,7 +234,7 @@ function Shell() { setChangePasswordOpen(false)} /> - + @@ -256,7 +259,9 @@ function LogoutItem({ onDone }: { onDone: () => void }) { export function AppShell() { return ( - + + + ); } diff --git a/src/layout/FullscreenContext.tsx b/src/layout/FullscreenContext.tsx new file mode 100644 index 0000000..1568a52 --- /dev/null +++ b/src/layout/FullscreenContext.tsx @@ -0,0 +1,43 @@ +import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'; + +/** + * Full screen for pages that are meant to be watched (the dashboards): the shell hides its menu and top bar, and the + * browser itself goes full screen when it allows it. Esc leaves both. + */ +interface FullscreenState { + /** the menu and the header are hidden */ + active: boolean; + enter: () => void; + exit: () => void; +} + +const Ctx = createContext({ active: false, enter: () => undefined, exit: () => undefined }); +export const useFullscreen = () => useContext(Ctx); + +export function FullscreenProvider({ children }: { children: ReactNode }) { + const [active, setActive] = useState(false); + const set = setActive; + + const enter = useCallback(() => { + set(true); + // the browser may refuse (no user gesture, embedded frame): the hidden menu and header still give the clean view + void document.documentElement.requestFullscreen?.().catch(() => undefined); + }, [set]); + + const exit = useCallback(() => { + set(false); + if (document.fullscreenElement) void document.exitFullscreen().catch(() => undefined); + }, [set]); + + // Esc (or the browser's own exit) leaves full screen: bring the menu and header back too + useEffect(() => { + const left = () => { + if (!document.fullscreenElement) set(false); + }; + document.addEventListener('fullscreenchange', left); + return () => document.removeEventListener('fullscreenchange', left); + }, [set]); + + const value = useMemo(() => ({ active, enter, exit }), [active, enter, exit]); + return {children}; +}