Richer dashboards and infographics, full screen with rotation

- 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 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-12 13:17:57 +03:00
parent 3ba7837d05
commit 1dde9568b3
6 changed files with 1160 additions and 11 deletions

View File

@ -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<string, Page> = {
'stakeholders-infographic': { kind: 'infographic', name: 'STAKEHOLDERS_INFOGRAPH' },
};
type CustomProps = { data: unknown; lab: (k: string) => string; rtl: boolean; nat: string };
const CUSTOM: Record<string, (p: CustomProps) => 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<string, { en: string; ar: string }> = {
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 <Alert severity="info">{ui('noResults')}</Alert>;
const title = meta ? (isRtl(lang) ? meta.ar : meta.en) : slug;
const estates = locations.data?.INDUSTRIALESTATESARRAY ?? [];
return (
<>
<PageHeader title={title} />
{rotating && (
<Box
key={slug}
sx={{ position: 'fixed', top: 0, insetInlineStart: 0, height: 3, bgcolor: 'primary.main', zIndex: 2000, animation: `rotate-progress ${ROTATE_MS}ms linear forwards`, '@keyframes rotate-progress': { from: { width: '0%' }, to: { width: '100%' } } }}
/>
)}
<PageHeader
title={title}
actions={
<>
{fullscreen.active && slugs.length > 1 && (
<Button variant="outlined" startIcon={paused ? <PlayArrowOutlined /> : <PauseOutlined />} onClick={() => setPaused((p) => !p)}>
{paused ? ui('resumeRotation') : ui('pauseRotation')}
</Button>
)}
<Button variant={fullscreen.active ? 'contained' : 'outlined'} startIcon={fullscreen.active ? <FullscreenExitOutlined /> : <FullscreenOutlined />} onClick={fullscreen.active ? fullscreen.exit : fullscreen.enter}>
{fullscreen.active ? ui('exitFullscreen') : ui('fullscreen')}
</Button>
</>
}
/>
{page.locations && estates.length > 0 && (
<Stack
direction="row"
@ -390,7 +447,9 @@ export function DashboardPage() {
{[0, 1, 2, 3].map((i) => <Skeleton key={i} variant="rounded" height={160} />)}
</Box>
)}
{!data.isPending && (() => {
{/* every dashboard and infographic has its own richer layout; the generic blocks below remain as the fallback */}
{!data.isPending && !data.error && Custom && <Custom data={data.data} lab={lab} rtl={isRtl(lang)} nat={nat} />}
{!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');

View File

@ -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<string, Tint> = {
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<string, number> }[]; lab: Label; title: string; tx: (k: TextKey) => string }) {
const statuses = STATUS_ORDER.filter((s) => items.some((i) => (i.values[s] ?? 0) > 0));
return (
<Panel icon={FactCheckOutlined} color="#5fb87a" title={title}>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell />
{statuses.map((s) => {
const Icon = STATUS_TINT[s].icon;
return (
<TableCell key={s} align="center" sx={{ color: STATUS_TINT[s].color }}>
<Stack sx={{ alignItems: 'center' }}>
<Icon fontSize="small" />
<Typography variant="caption" sx={{ fontWeight: 700, lineHeight: 1.2 }}>{lab(s)}</Typography>
</Stack>
</TableCell>
);
})}
<TableCell align="center"><Typography variant="caption" sx={{ fontWeight: 700 }}>{tx('total')}</Typography></TableCell>
</TableRow>
</TableHead>
<TableBody>
{items.map((i) => {
const total = sum(Object.values(i.values));
const Icon = i.tint.icon;
return (
<TableRow key={i.code}>
<TableCell>
<Stack direction="row" spacing={0.75} sx={{ alignItems: 'center', color: i.tint.color }}>
<Icon fontSize="small" />
<Typography variant="body2" sx={{ fontWeight: 700 }}>{i.label}</Typography>
</Stack>
</TableCell>
{statuses.map((s) => {
const v = i.values[s] ?? 0;
const share = total ? v / total : 0;
return (
<TableCell key={s} align="center" sx={{ bgcolor: v ? alpha(STATUS_TINT[s].color, 0.07 + share * 0.45) : undefined, fontWeight: 700 }}>
{fmt(v)}
</TableCell>
);
})}
<TableCell align="center" sx={{ fontWeight: 800 }}>{fmt(total)}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Box>
<Stack direction="row" useFlexGap sx={{ justifyContent: 'space-around', flexWrap: 'wrap', gap: 2, mt: 2 }}>
{items.map((i) => (
<Ring
key={i.code}
total={sum(Object.values(i.values))}
part={{ key: i.code, label: `${i.label} · ${tx('registeredRate')}`, value: i.values.REGISTERED ?? 0, tint: { icon: i.tint.icon, color: i.tint.color } }}
/>
))}
</Stack>
</Panel>
);
}
/** 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 (
<Panel icon={LocationCityOutlined} color="#7c6fd1" title={title}>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell />
{keys.map((k, i) => {
const t = tintOf(k, i);
const Icon = t.icon;
return (
<TableCell key={k} align="center" sx={{ color: t.color }}>
<Stack sx={{ alignItems: 'center' }}>
<Icon fontSize="small" />
<Typography variant="caption" sx={{ fontWeight: 700, lineHeight: 1.2 }}>{nameOf(k)}</Typography>
</Stack>
</TableCell>
);
})}
<TableCell align="center"><Typography variant="caption" sx={{ fontWeight: 700 }}>{tx('total')}</Typography></TableCell>
</TableRow>
</TableHead>
<TableBody>
{cities.map((c) => (
<TableRow key={c.name}>
<TableCell>
<Stack direction="row" spacing={0.75} sx={{ alignItems: 'center' }}>
<MapOutlined fontSize="small" sx={{ color: '#7c6fd1' }} />
<Typography variant="body2" sx={{ fontWeight: 700 }}>{c.name}</Typography>
</Stack>
</TableCell>
{c.values.map((v, i) => {
const t = tintOf(keys[i], i);
const max = Math.max(1, ...cities.map((x) => x.values[i]));
return <TableCell key={keys[i]} align="center" sx={{ bgcolor: v ? alpha(t.color, 0.06 + (v / max) * 0.45) : undefined, fontWeight: 700 }}>{fmt(v)}</TableCell>;
})}
<TableCell align="center" sx={{ fontWeight: 800 }}>{fmt(sum(c.values))}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</Panel>
);
}
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<string, number> };
});
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 (
<Stack spacing={1.5}>
<Hero icon={GroupsOutlined} label={tx('registeredStakeholders')} value={grand} parts={counted.map((c) => ({ key: c.code, label: c.label, value: c.value, tint: c.tint }))} />
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(5, 1fr)' } }}>
{counted.map((c) => (
<StatCard key={c.code} tint={c.tint} value={c.value} label={c.label} share={pct(c.value, grand)} sub={tx('ofTotal')} />
))}
</Box>
{statusItems.length > 0 && <StatusPanel items={statusItems} lab={lab} title={tx('statuses')} tx={tx} />}
{cols.length > 0 && (
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', lg: '2fr 3fr' } }}>
<Panel icon={MapOutlined} color="#5fb87a" title={tx('byCity')}><Columns parts={cols} /></Panel>
<CityTable
rows={cityRows}
keys={cityKeys}
lab={lab}
nameOf={(k) => lab(k)}
tintOf={(k, i) => itemTint(k, i)}
title={tx('cityTable')}
tx={tx}
/>
</Box>
)}
</Stack>
);
}
// ------------------------------------------------------------------------------------------------ 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 (
<Stack spacing={1.5}>
<Hero icon={GroupsOutlined} label={tx('stakeholdersTotal')} value={grand} parts={main.map((m) => ({ key: m.code, label: m.label, value: m.value, tint: m.tint }))} />
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(5, 1fr)' } }}>
{main.map((m) => <StatCard key={m.code} tint={m.tint} value={m.value} label={m.label} share={pct(m.value, grand)} sub={tx('ofTotal')} />)}
</Box>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', lg: 'repeat(2, 1fr)' } }}>
{omani + others > 0 && (
<Panel icon={BadgeOutlined} color="#a5894f" title={tx('drivers')}>
<Gauge
a={{ key: 'OMN', label: tx('omaniDrivers'), value: omani, tint: NATION.OMN }}
b={{ key: 'OTH', label: tx('otherDrivers'), value: others, tint: NATION.OTHERS }}
/>
</Panel>
)}
{cities.length > 0 && (
<Panel icon={LocationCityOutlined} color="#5fb87a" title={tx('investorsByCity')}>
<Columns parts={cities} />
</Panel>
)}
</Box>
</Stack>
);
}
// ------------------------------------------------------------------------------------------------ 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<string, number> };
});
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 (
<Stack spacing={1.5}>
<Hero icon={LocalShippingOutlined} label={tx('totalFleet')} value={grand} parts={totals.map((t) => ({ key: t.code, label: lab(t.code), value: t.value, tint: FLEET[t.code] ?? itemTint(t.code, 0) }))} />
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(5, 1fr)' } }}>
{totals.map((t) => <StatCard key={t.code} tint={FLEET[t.code] ?? itemTint(t.code, 0)} value={t.value} label={lab(t.code)} share={pct(t.value, grand)} sub={tx('ofTotal')} />)}
</Box>
{statusItems.length > 0 && <StatusPanel items={statusItems} lab={lab} title={tx('fleetStatus')} tx={tx} />}
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(3, 1fr)' } }}>
{gauges.map((g) => {
const parts = typeParts(g.entity);
if (!parts.length) return null;
return (
<Panel key={g.entity} icon={g.icon} color={g.color} title={`${tx('classes')} — ${g.title}`}>
{parts.length >= 2 ? <Gauge a={parts[0]} b={parts[1]} /> : <IconBars parts={parts} />}
</Panel>
);
})}
</Box>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', lg: 'repeat(2, 1fr)' } }}>
{cargo.length > 0 && <Panel icon={Inventory2Outlined} color="#cbb67d" title={tx('cargo')}><IconBars parts={cargo} /></Panel>}
{tankers.length > 0 && <Panel icon={LocalGasStationOutlined} color="#d16475" title={tx('tankers')}><IconBars parts={tankers} /></Panel>}
</Box>
{cols.length > 0 && (
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', lg: '2fr 3fr' } }}>
<Panel icon={MapOutlined} color="#5fb87a" title={tx('byCity')}><Columns parts={cols} /></Panel>
<CityTable rows={cityRows} keys={fleetKeys} lab={lab} nameOf={(k) => lab(k)} tintOf={(k) => FLEET[k]} title={tx('fleetByCity')} tx={tx} />
</Box>
)}
</Stack>
);
}
// ------------------------------------------------------------------------------------------------ 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<string, unknown[]> | 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 (
<Stack spacing={1.5}>
<Hero
icon={PeopleAltOutlined}
label={tx('workers')}
value={total}
parts={[
{ key: 'OMN', label: tx('omani'), value: omani, tint: NATION.OMN },
{ key: 'OTH', label: tx('nonOmani'), value: others, tint: NATION.IND },
]}
/>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(4, 1fr)' } }}>
<StatCard tint={NATION.OMN} value={omani} label={tx('omani')} share={pct(omani, total)} sub={tx('ofTotal')} />
<StatCard tint={NATION.IND} value={others} label={tx('nonOmani')} share={pct(others, total)} sub={tx('ofTotal')} />
<StatCard tint={STATUS_TINT.REGISTERED} value={registered} label={tx('complete')} share={pct(registered, registered + incomplete)} sub={tx('ofTotal')} />
<StatCard tint={STATUS_TINT.INCOMPLETE} value={incomplete} label={tx('incomplete')} share={pct(incomplete, registered + incomplete)} sub={tx('ofTotal')} />
</Box>
<Panel icon={HowToRegOutlined} color="#5fb87a" title={tx('dataQuality')}>
<Stack direction="row" useFlexGap sx={{ justifyContent: 'space-around', flexWrap: 'wrap', gap: 2 }}>
<Ring total={registered + incomplete} part={{ key: 'c', label: tx('complete'), value: registered, tint: STATUS_TINT.REGISTERED }} />
<Ring total={subscribed + notSub} part={{ key: 's', label: tx('subscribed'), value: subscribed, tint: { icon: CardMembershipOutlined, color: '#2c98d4' } }} />
<Ring total={yes + no} part={{ key: 'r', label: tx('hasRelatives'), value: yes, tint: { icon: FamilyRestroomOutlined, color: '#d16475' } }} />
<Ring total={total} part={{ key: 'o', label: tx('omani'), value: omani, tint: NATION.OMN }} />
</Stack>
</Panel>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', lg: 'repeat(2, 1fr)' } }}>
{nations.length > 0 && <Panel icon={PublicOutlined} color="#2c98d4" title={tx('topNationalities')}><Columns parts={nations} /></Panel>}
{edu.length > 0 && <Panel icon={SchoolOutlined} color="#7c6fd1" title={tx('education')}><Columns parts={edu} /></Panel>}
</Box>
{jobs.length > 0 && (
<Panel icon={WorkOutline} color="#d1a233" title={tx('employment')}>
<IconBars parts={jobs} columns />
<Box sx={{ mt: 2 }}><ProportionBar parts={jobs} /></Box>
</Panel>
)}
</Stack>
);
}

View File

@ -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<string, unknown>;
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<string, Tint> = {
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<string, Tint> = {
'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<string, string> = { '7': 'INVESTORS', '10': 'OWNERS', '11': 'COMPANIES', '12': 'OTHER_STAKEHOLDERS' };
export const OWNER_ORDER = ['7', '11', '10', '12'];
export const KIND: Record<string, Tint> = {
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<string, Tint> = {
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<string, Tint> = {
MANAGERIAL: { icon: ManageAccountsOutlined, color: '#7c6fd1' },
SUPERVISORY: { icon: SupervisorAccountOutlined, color: '#2c98d4' },
SKILLED: { icon: EngineeringOutlined, color: '#5fb87a' },
UNSKILLED: { icon: HandymanOutlined, color: '#e2a93b' },
};
export const NATION: Record<string, Tint> = {
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 (
<Paper variant="outlined" sx={{ p: 2, height: '100%', ...sx }}>
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', mb: 1.5 }}>
<Avatar sx={{ bgcolor: alpha(color, 0.15), color, width: 28, height: 28 }}>
<Icon sx={{ fontSize: 16 }} />
</Avatar>
<Typography component="h2" sx={{ fontWeight: 700, fontSize: 14.5 }}>{title}</Typography>
</Stack>
{children}
</Paper>
);
}
/** 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 (
<Paper
variant="outlined"
sx={{ p: 1.75, position: 'relative', overflow: 'hidden', borderInlineStart: 3, borderInlineStartColor: tint.color }}
>
<Box sx={{ position: 'absolute', insetInlineEnd: -10, top: -10, opacity: 0.08, color: tint.color }}>
<Icon sx={{ fontSize: 84 }} />
</Box>
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', position: 'relative' }}>
<Avatar sx={{ bgcolor: alpha(tint.color, 0.15), color: tint.color, width: 44, height: 44 }}>
<Icon />
</Avatar>
<Box sx={{ minWidth: 0 }}>
<Typography variant="h5" sx={{ fontWeight: 800, color: tint.color, lineHeight: 1.1 }}>{fmt(value)}</Typography>
<Typography variant="body2" noWrap sx={{ color: 'text.secondary', unicodeBidi: 'plaintext', textAlign: 'start' }}>{label}</Typography>
</Box>
</Stack>
{share !== undefined && (
<Box sx={{ mt: 1.25, position: 'relative' }}>
<Box sx={{ height: 6, borderRadius: 3, bgcolor: alpha(tint.color, 0.15), overflow: 'hidden' }}>
<Box sx={{ width: `${share}%`, height: '100%', bgcolor: tint.color, borderRadius: 3, minWidth: share > 0 ? 3 : 0 }} />
</Box>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>{share}% {sub}</Typography>
</Box>
)}
</Paper>
);
}
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 (
<Box>
<Box sx={{ display: 'flex', height: 16, borderRadius: 8, overflow: 'hidden', bgcolor: light ? alpha('#fff', 0.25) : 'action.hover' }}>
{parts.filter((p) => p.value > 0).map((p) => (
<Box key={p.key} title={`${p.label}: ${fmt(p.value)}`} sx={{ width: `${(p.value / Math.max(1, total)) * 100}%`, bgcolor: p.tint.color, borderInlineEnd: '2px solid', borderColor: light ? 'rgba(255,255,255,.35)' : 'background.paper' }} />
))}
</Box>
<Stack direction="row" spacing={2} useFlexGap sx={{ flexWrap: 'wrap', mt: 1.25 }}>
{parts.map((p) => {
const Icon = p.tint.icon;
return (
<Stack key={p.key} direction="row" spacing={0.5} sx={{ alignItems: 'center', color: light ? '#fff' : 'text.primary' }}>
<Icon sx={{ fontSize: 16, color: light ? '#fff' : p.tint.color }} />
<Typography variant="caption" sx={{ fontWeight: 600 }}>{p.label}</Typography>
<Typography variant="caption" sx={{ opacity: 0.8 }}>{pct(p.value, total)}%</Typography>
</Stack>
);
})}
</Stack>
</Box>
);
}
/** 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 (
<Box>
<Box sx={{ position: 'relative', width: 200, maxWidth: '100%', mx: 'auto' }}>
<svg viewBox="0 0 120 70" width="100%" role="img" aria-label={`${a.label} ${pct(a.value, total)}%`}>
<path d={arc} fill="none" stroke={b.tint.color} strokeWidth="11" strokeLinecap="round" opacity={total ? 1 : 0.2} />
<path d={arc} fill="none" stroke={a.tint.color} strokeWidth="11" strokeLinecap="round" strokeDasharray={`${L * share} ${L}`} />
<path d={arc} fill="none" stroke={theme.palette.background.paper} strokeWidth="1" strokeDasharray="1.5 6" opacity=".6" />
</svg>
<Box sx={{ position: 'absolute', left: 0, right: 0, bottom: 2, textAlign: 'center' }}>
<Typography sx={{ fontWeight: 800, fontSize: 24, lineHeight: 1 }}>{pct(a.value, total)}%</Typography>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>{a.label}</Typography>
</Box>
</Box>
<Stack direction="row" sx={{ justifyContent: 'space-around', mt: 1 }}>
{[a, b].map((p) => {
const Icon = p.tint.icon;
return (
<Stack key={p.key} sx={{ alignItems: 'center' }}>
<Icon sx={{ color: p.tint.color }} />
<Typography sx={{ fontWeight: 800, color: p.tint.color }}>{fmt(p.value)}</Typography>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>{p.label}</Typography>
</Stack>
);
})}
</Stack>
</Box>
);
}
/** 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 (
<Stack sx={{ alignItems: 'center', minWidth: 110 }}>
<Box sx={{ position: 'relative', width: 96, height: 96 }}>
<svg viewBox="0 0 80 80" width="96" height="96" style={{ transform: 'rotate(-90deg)' }}>
<circle cx="40" cy="40" r="34" fill="none" stroke={alpha(part.tint.color, 0.15)} strokeWidth="8" />
<circle cx="40" cy="40" r="34" fill="none" stroke={part.tint.color} strokeWidth="8" strokeLinecap="round" strokeDasharray={`${C * share} ${C}`} />
</svg>
<Box sx={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', color: part.tint.color }}>
<Stack sx={{ alignItems: 'center' }}>
<Icon sx={{ fontSize: 22 }} />
<Typography variant="caption" sx={{ fontWeight: 800, lineHeight: 1 }}>{Math.round(share * 100)}%</Typography>
</Stack>
</Box>
</Box>
<Typography sx={{ fontWeight: 800, color: part.tint.color, mt: 0.5 }}>{fmt(part.value)}</Typography>
<Typography variant="caption" sx={{ color: 'text.secondary', textAlign: 'center' }}>{part.label}</Typography>
</Stack>
);
}
/** 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 (
<Box sx={{ display: 'flex', alignItems: 'flex-end', gap: { xs: 0.75, sm: 1.5 }, height: 230, pt: 1 }}>
{parts.map((p) => {
const Icon = p.tint.icon;
const h = Math.max(4, (p.value / max) * 130);
return (
<Stack key={p.key} sx={{ flex: 1, minWidth: 0, alignItems: 'center', justifyContent: 'flex-end', height: '100%' }}>
<Typography variant="body2" sx={{ fontWeight: 800, color: p.tint.color }}>{fmt(p.value)}</Typography>
<Box
title={`${p.label}: ${fmt(p.value)}`}
sx={{ width: '100%', maxWidth: 64, height: h, borderRadius: '10px 10px 4px 4px', background: `linear-gradient(180deg, ${p.tint.color}, ${alpha(p.tint.color, 0.45)})`, my: 0.75 }}
/>
<Avatar sx={{ bgcolor: alpha(p.tint.color, 0.15), color: p.tint.color, width: 30, height: 30 }}>
<Icon sx={{ fontSize: 18 }} />
</Avatar>
<Typography variant="caption" sx={{ color: 'text.secondary', textAlign: 'center', lineHeight: 1.2, mt: 0.5, height: 28, overflow: 'hidden', unicodeBidi: 'plaintext' }}>{p.label}</Typography>
</Stack>
);
})}
</Box>
);
}
/** 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 (
<Box sx={{ display: 'grid', gap: 1.4, gridTemplateColumns: columns ? { xs: '1fr', md: 'repeat(2, 1fr)' } : '1fr', columnGap: columns ? 4 : undefined }}>
{parts.map((p) => {
const Icon = p.tint.icon;
return (
<Stack key={p.key} direction="row" spacing={1.25} sx={{ alignItems: 'center' }}>
<Avatar sx={{ bgcolor: alpha(p.tint.color, 0.15), color: p.tint.color, width: 32, height: 32 }}>
<Icon sx={{ fontSize: 18 }} />
</Avatar>
<Box sx={{ flex: 1, minWidth: 0 }}>
<Stack direction="row" sx={{ justifyContent: 'space-between', mb: 0.25 }}>
<Typography variant="body2" noWrap sx={{ unicodeBidi: 'plaintext' }}>{p.label}</Typography>
<Typography variant="body2" sx={{ fontWeight: 700 }}>
{fmt(p.value)} <Typography component="span" variant="caption" sx={{ color: 'text.secondary' }}>· {pct(p.value, total)}%</Typography>
</Typography>
</Stack>
<Box sx={{ height: 8, borderRadius: 4, bgcolor: alpha(p.tint.color, 0.12), overflow: 'hidden' }}>
<Box sx={{ width: `${(p.value / max) * 100}%`, height: '100%', borderRadius: 4, background: `linear-gradient(90deg, ${alpha(p.tint.color, 0.6)}, ${p.tint.color})`, minWidth: p.value ? 3 : 0 }} />
</Box>
</Box>
</Stack>
);
})}
</Box>
);
}
/** 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 (
<Box>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(10, 1fr)', gap: 0.25, direction: 'ltr' }}>
{Array.from({ length: 20 }, (_, i) => {
const first = i < countA;
const Icon = first ? IconA : IconB;
return <Icon key={i} sx={{ fontSize: { xs: 24, sm: 34 }, color: first ? a.tint.color : b.tint.color, justifySelf: 'center' }} />;
})}
</Box>
<Stack direction="row" sx={{ justifyContent: 'space-around', mt: 1.5 }}>
{[a, b].map((p) => (
<Stack key={p.key} sx={{ alignItems: 'center' }}>
<Typography variant="h5" sx={{ fontWeight: 800, color: p.tint.color, lineHeight: 1.1 }}>{pct(p.value, total)}%</Typography>
<Typography variant="body2" sx={{ fontWeight: 700 }}>{fmt(p.value)}</Typography>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>{p.label}</Typography>
</Stack>
))}
</Stack>
</Box>
);
}
/** 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 (
<Paper
sx={{ p: 2.5, color: '#fff', background: 'linear-gradient(135deg, #0b6ea8 0%, #1b8fc9 55%, #2c98d4 100%)', position: 'relative', overflow: 'hidden' }}
>
<Icon sx={{ position: 'absolute', insetInlineEnd: 16, top: -6, fontSize: 130, opacity: 0.12 }} />
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', mb: 1.5, position: 'relative' }}>
<Avatar sx={{ bgcolor: 'rgba(255,255,255,.2)', color: '#fff', width: 52, height: 52 }}><Icon fontSize="large" /></Avatar>
<Box>
<Typography sx={{ fontSize: 13.5, opacity: 0.9 }}>{label}</Typography>
<Typography sx={{ fontWeight: 800, fontSize: 38, lineHeight: 1 }}>{fmt(value)}</Typography>
</Box>
</Stack>
<Box sx={{ position: 'relative' }}>
<ProportionBar light parts={parts} />
</Box>
</Paper>
);
}
// ------------------------------------------------------------------------------------------------ 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 ? <Gauge a={list[0]} b={list[1]} /> : <IconBars parts={list} />);
return (
<Stack spacing={1.5}>
{/* the headline: the whole fleet and how it divides between the five kinds */}
<Paper
sx={{
p: 2.5,
color: '#fff',
background: 'linear-gradient(135deg, #0b6ea8 0%, #1b8fc9 55%, #2c98d4 100%)',
position: 'relative',
overflow: 'hidden',
}}
>
<LocalShippingOutlined sx={{ position: 'absolute', insetInlineEnd: 16, top: -6, fontSize: 130, opacity: 0.12 }} />
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', mb: 1.5, position: 'relative' }}>
<Avatar sx={{ bgcolor: 'rgba(255,255,255,.2)', color: '#fff', width: 52, height: 52 }}><LocalShippingOutlined fontSize="large" /></Avatar>
<Box>
<Typography sx={{ fontSize: 13.5, opacity: 0.9 }}>{tx('totalFleet')}</Typography>
<Typography sx={{ fontWeight: 800, fontSize: 38, lineHeight: 1 }}>{fmt(grand)}</Typography>
</Box>
</Stack>
<Box sx={{ position: 'relative' }}>
<ProportionBar light parts={totals.map((t) => ({ key: t.e, label: lab(t.e), value: t.v, tint: FLEET[t.e] }))} />
</Box>
</Paper>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(5, 1fr)' } }}>
{totals.map((t) => (
<StatCard key={t.e} tint={FLEET[t.e]} value={t.v} label={lab(t.e)} share={pct(t.v, grand)} sub={tx('ofFleet')} />
))}
</Box>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', lg: '3fr 2fr' } }}>
<Panel icon={GridViewOutlined} color="#7c6fd1" title={tx('ownership')}>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell />
{OWNER_ORDER.map((o) => {
const Icon = OWNER[o].icon;
return (
<TableCell key={o} align="center" sx={{ color: OWNER[o].color }}>
<Stack sx={{ alignItems: 'center' }}>
<Icon fontSize="small" />
<Typography variant="caption" sx={{ fontWeight: 700, lineHeight: 1.2 }}>{lab(OWNER_NAME[o])}</Typography>
</Stack>
</TableCell>
);
})}
<TableCell align="center"><Typography variant="caption" sx={{ fontWeight: 700 }}>{tx('total')}</Typography></TableCell>
</TableRow>
</TableHead>
<TableBody>
{entities.map((e) => {
const Icon = FLEET[e].icon;
const rowTotal = count(e);
return (
<TableRow key={e}>
<TableCell>
<Stack direction="row" spacing={0.75} sx={{ alignItems: 'center', color: FLEET[e].color }}>
<Icon fontSize="small" />
<Typography variant="body2" sx={{ fontWeight: 700 }}>{lab(e)}</Typography>
</Stack>
</TableCell>
{OWNER_ORDER.map((o) => {
const v = count(e, o);
const share = rowTotal ? v / rowTotal : 0;
return (
<TableCell key={o} align="center" sx={{ bgcolor: alpha(OWNER[o].color, 0.06 + share * 0.5), fontWeight: 700 }}>
{fmt(v)}
<Typography component="div" variant="caption" sx={{ color: 'text.secondary', fontWeight: 400 }}>{pct(v, rowTotal)}%</Typography>
</TableCell>
);
})}
<TableCell align="center" sx={{ fontWeight: 800 }}>{fmt(rowTotal)}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Box>
</Panel>
<Panel icon={BarChartOutlined} color="#2c98d4" title={tx('ownerTotals')}>
<Columns parts={byOwner} />
</Panel>
</Box>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(3, 1fr)' } }}>
{truck.length > 0 && <Panel icon={SpeedOutlined} color="#2c98d4" title={tx('trucks')}>{gauge(truck)}</Panel>}
{equip.length > 0 && <Panel icon={SpeedOutlined} color="#5fb87a" title={tx('equipment')}>{gauge(equip)}</Panel>}
{bus.length > 0 && <Panel icon={PieChartOutlined} color="#d16475" title={tx('buses')}>{gauge(bus)}</Panel>}
</Box>
{trailers.length > 0 && (
<Panel icon={StackedBarChartOutlined} color="#cbb67d" title={tx('trailers')}>
<IconBars parts={trailers} columns />
</Panel>
)}
</Stack>
);
}
// ------------------------------------------------------------------------------------------------ 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 (
<Stack spacing={1.5}>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(4, 1fr)' } }}>
<StatCard tint={{ icon: PeopleAltOutlined, color: '#2c98d4' }} value={shown} label={tx('totalWorkers')} />
<StatCard tint={NATION.OMN} value={omani} label={tx('omani')} share={pct(omani, everyone)} sub={tx('share')} />
<StatCard tint={MALE_TINT} value={male} label={tx('male')} share={pct(male, male + female)} sub={tx('share')} />
<StatCard tint={FEMALE_TINT} value={female} label={tx('female')} share={pct(female, male + female)} sub={tx('share')} />
</Box>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', lg: 'repeat(2, 1fr)' } }}>
<Panel icon={PublicOutlined} color="#2c98d4" title={tx('nationality')}>
<Stack direction="row" useFlexGap sx={{ justifyContent: 'space-around', flexWrap: 'wrap', gap: 2 }}>
{[
{ 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) => <Ring key={p.key} total={everyone} part={{ key: p.key, label: p.label, value: p.value, tint: NATION[p.key] }} />)}
</Stack>
</Panel>
<Panel icon={PeopleAltOutlined} color="#d16475" title={tx('gender')}>
<Pictogram
icons={[ManOutlined, WomanOutlined]}
a={{ key: 'MALE', label: tx('male'), value: male, tint: MALE_TINT }}
b={{ key: 'FEMALE', label: tx('female'), value: female, tint: FEMALE_TINT }}
/>
</Panel>
</Box>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', lg: '3fr 2fr' } }}>
{edu.length > 0 && (
<Panel icon={SchoolOutlined} color="#7c6fd1" title={tx('education')}>
<Columns parts={edu} />
</Panel>
)}
{jobs.length > 0 && (
<Panel icon={WorkOutline} color="#d1a233" title={tx('employment')}>
<IconBars parts={jobs} />
<Box sx={{ mt: 2 }}>
<ProportionBar parts={jobs} />
</Box>
</Panel>
)}
</Box>
</Stack>
);
}
export const MALE_TINT: Tint = { icon: ManOutlined, color: MALE };
export const FEMALE_TINT: Tint = { icon: WomanOutlined, color: FEMALE };

View File

@ -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: 'إغلاق' },

View File

@ -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<HTMLElement | null>(null);
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
@ -146,7 +149,7 @@ function Shell() {
<Box sx={{ display: 'flex', minHeight: '100vh' }}>
<GlobalStyles styles={{ '[dir=rtl] .flip-rtl': { transform: 'scaleX(-1)' } }} />
{wide ? (
{bare ? null : wide ? (
<Drawer variant="permanent" sx={{ width, flexShrink: 0, '& .MuiDrawer-paper': { width, boxSizing: 'border-box', borderInlineEnd: 1, borderColor: 'divider', transition: 'width .2s', overflowX: 'hidden' } }}>
<Sidebar collapsed={collapsed} onToggle={toggleCollapsed} />
</Drawer>
@ -157,7 +160,7 @@ function Shell() {
)}
<Box sx={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
<AppBar position="sticky" color="inherit" elevation={0} sx={{ borderBottom: 1, borderColor: 'divider', bgcolor: 'background.paper' }}>
{!bare && <AppBar position="sticky" color="inherit" elevation={0} sx={{ borderBottom: 1, borderColor: 'divider', bgcolor: 'background.paper' }}>
<Toolbar variant="dense" sx={{ gap: 1.25, minHeight: 52 }}>
{!wide && <IconButton edge="start" aria-label={ui('openMenu')} onClick={() => setDrawer(true)}><MenuIcon /></IconButton>}
<Box sx={{ flex: 1, minWidth: 0 }}><Crumbs /></Box>
@ -184,7 +187,7 @@ function Shell() {
</Avatar>
</IconButton>
</Toolbar>
</AppBar>
</AppBar>}
<Menu anchorEl={menuEl} open={!!menuEl} onClose={() => setMenuEl(null)} slotProps={{ paper: { sx: { minWidth: 220 } } }}>
<Box sx={{ px: 2, py: 1 }}>
@ -231,7 +234,7 @@ function Shell() {
</Menu>
<ChangePasswordDialog open={changePasswordOpen} onClose={() => setChangePasswordOpen(false)} />
<Box component="main" sx={{ flex: 1, p: { xs: 1.5, md: 2.5 }, width: '100%', maxWidth: 1560, mx: 'auto' }}>
<Box component="main" sx={{ flex: 1, p: { xs: 1.5, md: 2.5 }, width: '100%', maxWidth: bare ? 'none' : 1560, mx: 'auto', ...(bare && { bgcolor: 'background.default' }) }}>
<Outlet />
</Box>
</Box>
@ -256,7 +259,9 @@ function LogoutItem({ onDone }: { onDone: () => void }) {
export function AppShell() {
return (
<NavProvider>
<Shell />
<FullscreenProvider>
<Shell />
</FullscreenProvider>
</NavProvider>
);
}

View File

@ -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<FullscreenState>({ 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 <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}