@proef/common-ui 2.6.14 → 2.6.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +11 -4
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/legacy/components/molecules/PhotoAvatar/PhotoAvatar.js +15 -7
- package/dist/esm/legacy/components/molecules/PhotoAvatar/PhotoAvatar.js.map +1 -1
- package/dist/esm/v1/capabilities/documents/QRScanning/scanQRCodes.js.map +1 -1
- package/dist/esm/v1/capabilities/onepoint-rn/bridge.js.map +1 -0
- package/dist/esm/v1/capabilities/onepoint-rn/dentroDaApp.js.map +1 -0
- package/dist/esm/v1/capabilities/onepoint-rn/onepoint.js.map +1 -0
- package/dist/esm/v1/capabilities/onepoint-rn/useOrientacaoNaApp.js.map +1 -0
- package/dist/esm/v1/components/data/DayTimeline/DayTimeline.js +152 -0
- package/dist/esm/v1/components/data/DayTimeline/DayTimeline.js.map +1 -0
- package/dist/esm/v1/components/data/MonthCalendar/MonthCalendar.js +63 -30
- package/dist/esm/v1/components/data/MonthCalendar/MonthCalendar.js.map +1 -1
- package/dist/esm/v1/components/documents/DocumentDropzone/DocumentDropzone.js.map +1 -1
- package/dist/esm/v1/components/layout/SideNav/SideNav.js +1 -1
- package/dist/esm/v1/components/layout/SideNav/SideNav.js.map +1 -1
- package/dist/esm/v1/components/overlays/Dialog/Dialog.js +10 -5
- package/dist/esm/v1/components/overlays/Dialog/Dialog.js.map +1 -1
- package/dist/esm/v1/primitives/documents/PdfPreview/PdfPreview.js.map +1 -1
- package/dist/esm/v1/primitives/documents/PdfPreview/pdfjs.js.map +1 -1
- package/dist/style.components.css +1 -1
- package/dist/style.css +1 -1
- package/dist/style.layered.css +1 -1
- package/dist/theme.css +5 -0
- package/dist/tokens.css +5 -0
- package/dist/types/v1/components/data/DayTimeline/DayTimeline.d.ts +72 -0
- package/dist/types/v1/components/data/MonthCalendar/MonthCalendar.d.ts +11 -2
- package/dist/types/v1/components/overlays/Dialog/Dialog.d.ts +11 -2
- package/dist/types/v1/index.d.ts +6 -4
- package/package.json +1 -1
- package/dist/esm/v1/capabilities/onepoint/bridge.js.map +0 -1
- package/dist/esm/v1/capabilities/onepoint/dentroDaApp.js.map +0 -1
- package/dist/esm/v1/capabilities/onepoint/onepoint.js.map +0 -1
- package/dist/esm/v1/capabilities/onepoint/useOrientacaoNaApp.js.map +0 -1
- /package/dist/esm/v1/capabilities/{onepoint → onepoint-rn}/bridge.js +0 -0
- /package/dist/esm/v1/capabilities/{onepoint → onepoint-rn}/dentroDaApp.js +0 -0
- /package/dist/esm/v1/capabilities/{onepoint → onepoint-rn}/onepoint.js +0 -0
- /package/dist/esm/v1/capabilities/{onepoint → onepoint-rn}/useOrientacaoNaApp.js +0 -0
- /package/dist/types/v1/capabilities/{onepoint → onepoint-rn}/bridge.d.ts +0 -0
- /package/dist/types/v1/capabilities/{onepoint → onepoint-rn}/dentroDaApp.d.ts +0 -0
- /package/dist/types/v1/capabilities/{onepoint → onepoint-rn}/onepoint.d.ts +0 -0
- /package/dist/types/v1/capabilities/{onepoint → onepoint-rn}/useOrientacaoNaApp.d.ts +0 -0
|
@@ -14,6 +14,9 @@ function MonthCalendar({
|
|
|
14
14
|
locale = "pt-PT",
|
|
15
15
|
weekStartsOn = 1,
|
|
16
16
|
today,
|
|
17
|
+
dimPast = true,
|
|
18
|
+
highlightCurrent = true,
|
|
19
|
+
summary,
|
|
17
20
|
className = "",
|
|
18
21
|
...props
|
|
19
22
|
}) {
|
|
@@ -45,37 +48,67 @@ function MonthCalendar({
|
|
|
45
48
|
const inicio = (new Date(Date.UTC(year, month - 1, 1)).getUTCDay() - weekStartsOn + 7) % 7;
|
|
46
49
|
const diaHoje = today === void 0 ? hoje() : today;
|
|
47
50
|
const cabecalho = title === void 0 ? nomes.mes : title;
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
51
|
+
const mesAtual = highlightCurrent && !!diaHoje && diaHoje.startsWith(prefixo);
|
|
52
|
+
const eFimDeSemana = (coluna) => weekStartsOn === 1 ? coluna >= 5 : coluna === 0 || coluna === 6;
|
|
53
|
+
const FDS = "bg-slate-100 dark:bg-slate-800/55";
|
|
54
|
+
const fimVazio = (7 - (inicio + total) % 7) % 7;
|
|
55
|
+
return /* @__PURE__ */ jsxs(
|
|
56
|
+
"section",
|
|
57
|
+
{
|
|
58
|
+
...props,
|
|
59
|
+
"aria-label": `${nomes.mes} ${year}`,
|
|
60
|
+
"data-current": mesAtual || void 0,
|
|
61
|
+
className: `min-w-[16rem] overflow-hidden rounded-lg border border-border bg-card ${className}`,
|
|
62
|
+
children: [
|
|
63
|
+
(cabecalho !== null || summary) && // Faixa navy (a dos cabeçalhos das janelas); no mês de hoje, uma linha turquesa por baixo.
|
|
64
|
+
/* @__PURE__ */ jsxs(
|
|
65
|
+
"div",
|
|
62
66
|
{
|
|
63
|
-
"
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
},
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
67
|
+
className: "flex items-baseline justify-between gap-2 bg-primary px-3.5 py-2.5 text-primary-foreground dark:bg-slate-900 dark:text-slate-50 " + (mesAtual ? "shadow-[inset_0_-3px_0_var(--color-proef-turquoise)]" : ""),
|
|
68
|
+
children: [
|
|
69
|
+
cabecalho !== null && /* @__PURE__ */ jsx("h3", { className: "m-0 text-[15px] font-bold capitalize", children: cabecalho }),
|
|
70
|
+
summary && /* @__PURE__ */ jsx("span", { className: "ml-auto text-[11px] font-semibold opacity-75", children: summary })
|
|
71
|
+
]
|
|
72
|
+
}
|
|
73
|
+
),
|
|
74
|
+
/* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[repeat(7,minmax(2rem,1fr))] gap-0.5 p-3 text-center text-[13px] tabular-nums", children: [
|
|
75
|
+
nomes.semana.map((s, i) => /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: `rounded-t-md pb-1 text-xs font-medium uppercase text-muted-foreground ${eFimDeSemana(i) ? FDS : ""}`, children: s }, i)),
|
|
76
|
+
Array.from({ length: inicio }, (_, i) => /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: eFimDeSemana(i) ? `rounded-lg ${FDS}` : void 0 }, `v${i}`)),
|
|
77
|
+
Array.from({ length: total }, (_, i) => {
|
|
78
|
+
const dia = i + 1;
|
|
79
|
+
const data = `${prefixo}${pad(dia)}`;
|
|
80
|
+
const fimDeSemana = eFimDeSemana((inicio + i) % 7);
|
|
81
|
+
const marca = marcados.get(data);
|
|
82
|
+
const texto = marca?.labels.join(" · ");
|
|
83
|
+
const eHoje = data === diaHoje;
|
|
84
|
+
const passado = dimPast && !!diaHoje && data < diaHoje;
|
|
85
|
+
return /* @__PURE__ */ jsx(
|
|
86
|
+
"span",
|
|
87
|
+
{
|
|
88
|
+
"data-date": data,
|
|
89
|
+
"data-today": eHoje || void 0,
|
|
90
|
+
"data-tip": texto || void 0,
|
|
91
|
+
"aria-label": texto ? `${nomes.longo.format(new Date(Date.UTC(year, month - 1, dia)))}: ${texto}` : void 0,
|
|
92
|
+
"aria-current": eHoje ? "date" : void 0,
|
|
93
|
+
className: [
|
|
94
|
+
"flex h-[34px] items-center justify-center rounded-lg transition-colors",
|
|
95
|
+
marca ? `${BADGE_TONE_CLASSES[marca.tone]} font-semibold` : [
|
|
96
|
+
fimDeSemana ? FDS : "",
|
|
97
|
+
passado ? "text-slate-400 dark:text-slate-500" : fimDeSemana ? "text-muted-foreground" : "text-foreground",
|
|
98
|
+
"hover:bg-slate-200 dark:hover:bg-slate-800"
|
|
99
|
+
].join(" "),
|
|
100
|
+
texto ? "cursor-help" : ""
|
|
101
|
+
].join(" "),
|
|
102
|
+
children: eHoje ? /* @__PURE__ */ jsx("span", { className: "flex h-7 w-7 items-center justify-center rounded-full bg-primary font-bold text-primary-foreground dark:bg-proef-turquoise dark:text-proef-navy", children: dia }) : dia
|
|
103
|
+
},
|
|
104
|
+
data
|
|
105
|
+
);
|
|
106
|
+
}),
|
|
107
|
+
Array.from({ length: fimVazio }, (_, i) => /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: eFimDeSemana((inicio + total + i) % 7) ? `rounded-lg ${FDS}` : void 0 }, `f${i}`))
|
|
108
|
+
] })
|
|
109
|
+
]
|
|
110
|
+
}
|
|
111
|
+
);
|
|
79
112
|
}
|
|
80
113
|
export {
|
|
81
114
|
MonthCalendar
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MonthCalendar.js","sources":["../../../../../../src/v1/components/data/MonthCalendar/MonthCalendar.tsx"],"sourcesContent":["import React from 'react'\r\nimport { BADGE_TONE_CLASSES, type BadgeTone } from '../../../primitives/display/Badge/Badge'\r\n\r\n/** Os mesmos tons do `Badge`: estados (`ok`, `risco`, `incumprido`, `neutral`, `accent`) e classificações. */\r\nexport type MonthCalendarTone = BadgeTone\r\n\r\nexport interface MonthCalendarDay {\r\n /** `YYYY-MM-DD`. Os dias de outros meses são ignorados, por isso pode passar-se a lista do ano inteiro. */\r\n date: string\r\n tone: MonthCalendarTone\r\n /** O que o dia tem (ex: \"Férias · Autorizado\"); vai para o `data-tip` e para os leitores de ecrã. */\r\n label?: string\r\n}\r\n\r\nexport interface MonthCalendarProps extends Omit<React.HTMLAttributes<HTMLElement>, 'children' | 'title'> {\r\n year: number\r\n /** 1 = janeiro … 12 = dezembro. */\r\n month: number\r\n /** Dias marcados. Vários na mesma data: fica a cor do primeiro e juntam-se as etiquetas. */\r\n days?: MonthCalendarDay[]\r\n /** Título por cima dos dias. Por omissão o nome do mês; `null` para nenhum. */\r\n title?: React.ReactNode | null\r\n /** Nomes do mês e dos dias da semana. */\r\n locale?: string\r\n /** 1 = segunda (Portugal), 0 = domingo. */\r\n weekStartsOn?: 0 | 1\r\n /** Dia com contorno. Por omissão o de hoje; `null` para nenhum. */\r\n today?: string | null\r\n}\r\n\r\nconst pad = (n: number) => String(n).padStart(2, '0')\r\nconst hoje = () => {\r\n const d = new Date()\r\n return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`\r\n}\r\n\r\n/**\r\n * Um mês, com os dias pintados por tom (ex: férias, feriados, ausências).\r\n * Para o ano inteiro, um por mês numa grelha (ver a story \"Ano inteiro\").\r\n *\r\n * Genérico: não sabe o que são férias. A app decide a cor e a etiqueta de cada\r\n * dia; o calendário só desenha. A legenda faz-se com `Badge`, nos mesmos tons.\r\n *\r\n * **Aceita os atributos HTML do `<section>`** (ex: `id`, `className`).\r\n */\r\nexport default function MonthCalendar({\r\n year,\r\n month,\r\n days = [],\r\n title,\r\n locale = 'pt-PT',\r\n weekStartsOn = 1,\r\n today,\r\n className = '',\r\n ...props\r\n}: MonthCalendarProps) {\r\n const prefixo = `${year}-${pad(month)}-`\r\n\r\n const marcados = React.useMemo(() => {\r\n const m = new Map<string, { tone: MonthCalendarTone; labels: string[] }>()\r\n for (const d of days) {\r\n if (!d.date.startsWith(prefixo)) continue\r\n const atual = m.get(d.date)\r\n if (atual) {\r\n if (d.label) atual.labels.push(d.label)\r\n } else {\r\n m.set(d.date, { tone: d.tone, labels: d.label ? [d.label] : [] })\r\n }\r\n }\r\n return m\r\n }, [days, prefixo])\r\n\r\n const nomes = React.useMemo(() => {\r\n const utc = { timeZone: 'UTC' } as const\r\n // 05/01/2026 é segunda; 04/01/2026 domingo.\r\n const primeiro = weekStartsOn === 1 ? 5 : 4\r\n const semana = new Intl.DateTimeFormat(locale, { ...utc, weekday: 'narrow' })\r\n return {\r\n mes: new Intl.DateTimeFormat(locale, { ...utc, month: 'long' }).format(new Date(Date.UTC(year, month - 1, 1))),\r\n semana: Array.from({ length: 7 }, (_, i) => semana.format(new Date(Date.UTC(2026, 0, primeiro + i)))),\r\n longo: new Intl.DateTimeFormat(locale, { ...utc, day: 'numeric', month: 'long' }),\r\n }\r\n }, [locale, weekStartsOn, year, month])\r\n\r\n const total = new Date(Date.UTC(year, month, 0)).getUTCDate()\r\n const inicio = (new Date(Date.UTC(year, month - 1, 1)).getUTCDay() - weekStartsOn + 7) % 7\r\n const diaHoje = today === undefined ? hoje() : today\r\n const cabecalho = title === undefined ? nomes.mes : title\r\n\r\n // Mínimo de 7 dias × 2rem: num sítio estreito o mês não encolhe ao ponto de os números se sobreporem.\r\n return (\r\n <section {...props} aria-label={`${nomes.mes} ${year}`} className={`min-w-[16rem] rounded-lg border border-border bg-card p-3 ${className}`}>\r\n {cabecalho !== null && (\r\n <h3 className=\"mb-2 text-center text-sm font-semibold capitalize text-foreground\">{cabecalho}</h3>\r\n )}\r\n <div className=\"grid grid-cols-[repeat(7,minmax(2rem,1fr))] gap-0.5 text-center text-xs tabular-nums\">\r\n {nomes.semana.map((s, i) => (\r\n <span key={i} aria-hidden className=\"pb-1 font-medium uppercase text-muted-foreground\">{s}</span>\r\n ))}\r\n {Array.from({ length: inicio }, (_, i) => <span key={`v${i}`} aria-hidden />)}\r\n {Array.from({ length: total }, (_, i) => {\r\n const dia = i + 1\r\n const data = `${prefixo}${pad(dia)}`\r\n const coluna = (inicio + i) % 7\r\n const fimDeSemana = weekStartsOn === 1 ? coluna >= 5 : coluna === 0 || coluna === 6\r\n const marca = marcados.get(data)\r\n const texto = marca?.labels.join(' · ')\r\n return (\r\n <span\r\n key={data}\r\n data-date={data}\r\n data-tip={texto || undefined}\r\n aria-label={texto ? `${nomes.longo.format(new Date(Date.UTC(year, month - 1, dia)))}: ${texto}` : undefined}\r\n className={[\r\n 'flex h-7 items-center justify-center rounded-md',\r\n marca ? `${BADGE_TONE_CLASSES[marca.tone]} font-semibold` : fimDeSemana ? 'text-muted-foreground' : 'text-foreground',\r\n data === diaHoje ? 'ring-1 ring-primary dark:ring-sky-300' : '',\r\n texto ? 'cursor-help' : '',\r\n ].join(' ')}\r\n >\r\n {dia}\r\n </span>\r\n )\r\n })}\r\n </div>\r\n </section>\r\n )\r\n}\r\n\r\nexport { MonthCalendar }\r\n"],"names":[],"mappings":";;;AA8BA,MAAM,MAAM,CAAC,MAAc,OAAO,CAAC,EAAE,SAAS,GAAG,GAAG;AACpD,MAAM,OAAO,MAAM;AACjB,QAAM,wBAAQ,KAAA;AACd,SAAO,GAAG,EAAE,YAAA,CAAa,IAAI,IAAI,EAAE,SAAA,IAAa,CAAC,CAAC,IAAI,IAAI,EAAE,QAAA,CAAS,CAAC;AACxE;AAWA,SAAwB,cAAc;AAAA,EACpC;AAAA,EACA;AAAA,EACA,OAAO,CAAA;AAAA,EACP;AAAA,EACA,SAAS;AAAA,EACT,eAAe;AAAA,EACf;AAAA,EACA,YAAY;AAAA,EACZ,GAAG;AACL,GAAuB;AACrB,QAAM,UAAU,GAAG,IAAI,IAAI,IAAI,KAAK,CAAC;AAErC,QAAM,WAAW,MAAM,QAAQ,MAAM;AACnC,UAAM,wBAAQ,IAAA;AACd,eAAW,KAAK,MAAM;AACpB,UAAI,CAAC,EAAE,KAAK,WAAW,OAAO,EAAG;AACjC,YAAM,QAAQ,EAAE,IAAI,EAAE,IAAI;AAC1B,UAAI,OAAO;AACT,YAAI,EAAE,MAAO,OAAM,OAAO,KAAK,EAAE,KAAK;AAAA,MACxC,OAAO;AACL,UAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,EAAE,QAAQ,CAAC,EAAE,KAAK,IAAI,CAAA,GAAI;AAAA,MAClE;AAAA,IACF;AACA,WAAO;AAAA,EACT,GAAG,CAAC,MAAM,OAAO,CAAC;AAElB,QAAM,QAAQ,MAAM,QAAQ,MAAM;AAChC,UAAM,MAAM,EAAE,UAAU,MAAA;AAExB,UAAM,WAAW,iBAAiB,IAAI,IAAI;AAC1C,UAAM,SAAS,IAAI,KAAK,eAAe,Q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,KAAA,GAApB,IAAI,CAAC,EAAgB,CAAE;AAAA,MAC3E,MAAM,KAAK,EAAE,QAAQ,SAAS,CAAC,GAAG,MAAM;AACvC,cAAM,MAAM,IAAI;AAChB,cAAM,OAAO,GAAG,OAAO,GAAG,IAAI,GAAG,CAAC;AAClC,cAAM,UAAU,SAAS,KAAK;AAC9B,cAAM,cAAc,iBAAiB,IAAI,UAAU,IAAI,WAAW,KAAK,WAAW;AAClF,cAAM,QAAQ,SAAS,IAAI,IAAI;AAC/B,cAAM,QAAQ,OAAO,OAAO,KAAK,KAAK;AACtC,eACE;AAAA,UAAC;AAAA,UAAA;AAAA,YAEC,aAAW;AAAA,YACX,YAAU,SAAS;AAAA,YACnB,cAAY,QAAQ,GAAG,MAAM,MAAM,OAAO,IAAI,KAAK,KAAK,IAAI,MAAM,QAAQ,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,KAAK,KAAK;AAAA,YAClG,WAAW;AAAA,cACT;AAAA,cACA,QAAQ,GAAG,mBAAmB,MAAM,IAAI,CAAC,mBAAmB,cAAc,0BAA0B;AAAA,cACpG,SAAS,UAAU,0CAA0C;AAAA,cAC7D,QAAQ,gBAAgB;AAAA,YAAA,EACxB,KAAK,GAAG;AAAA,YAET,UAAA;AAAA,UAAA;AAAA,UAXI;AAAA,QAAA;AAAA,MAcX,CAAC;AAAA,IAAA,EAAA,CACH;AAAA,EAAA,GACF;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"MonthCalendar.js","sources":["../../../../../../src/v1/components/data/MonthCalendar/MonthCalendar.tsx"],"sourcesContent":["import React from 'react'\r\nimport { BADGE_TONE_CLASSES, type BadgeTone } from '../../../primitives/display/Badge/Badge'\r\n\r\n/** Os mesmos tons do `Badge`: estados (`ok`, `risco`, `incumprido`, `neutral`, `accent`) e classificações. */\r\nexport type MonthCalendarTone = BadgeTone\r\n\r\nexport interface MonthCalendarDay {\r\n /** `YYYY-MM-DD`. Os dias de outros meses são ignorados, por isso pode passar-se a lista do ano inteiro. */\r\n date: string\r\n tone: MonthCalendarTone\r\n /** O que o dia tem (ex: \"Férias · Autorizado\"); vai para o `data-tip` e para os leitores de ecrã. */\r\n label?: string\r\n}\r\n\r\nexport interface MonthCalendarProps extends Omit<React.HTMLAttributes<HTMLElement>, 'children' | 'title'> {\r\n year: number\r\n /** 1 = janeiro … 12 = dezembro. */\r\n month: number\r\n /** Dias marcados. Vários na mesma data: fica a cor do primeiro e juntam-se as etiquetas. */\r\n days?: MonthCalendarDay[]\r\n /** Título por cima dos dias. Por omissão o nome do mês; `null` para nenhum. */\r\n title?: React.ReactNode | null\r\n /** Nomes do mês e dos dias da semana. */\r\n locale?: string\r\n /** 1 = segunda (Portugal), 0 = domingo. */\r\n weekStartsOn?: 0 | 1\r\n /**\r\n * O dia de hoje, num círculo cheio. Por omissão o de hoje; `null` para nenhum.\r\n * Também decide os dias que já passaram (`dimPast`) e o mês atual (`highlightCurrent`).\r\n */\r\n today?: string | null\r\n /** Os dias antes de hoje ficam mais apagados (os marcados mantêm a cor). Por omissão sim. */\r\n dimPast?: boolean\r\n /** O mês que contém hoje fica com uma linha turquesa por baixo do cabeçalho. Por omissão sim. */\r\n highlightCurrent?: boolean\r\n /** Texto curto à direita do nome do mês (ex: \"4 dias de férias\"). */\r\n summary?: React.ReactNode\r\n}\r\n\r\nconst pad = (n: number) => String(n).padStart(2, '0')\r\nconst hoje = () => {\r\n const d = new Date()\r\n return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`\r\n}\r\n\r\n/**\r\n * Um mês, com os dias pintados por tom (ex: férias, feriados, ausências).\r\n * Para o ano inteiro, um por mês numa grelha (ver a story \"Ano inteiro\").\r\n *\r\n * Genérico: não sabe o que são férias. A app decide a cor e a etiqueta de cada\r\n * dia; o calendário só desenha. A legenda faz-se com `Badge`, nos mesmos tons.\r\n *\r\n * **Aceita os atributos HTML do `<section>`** (ex: `id`, `className`).\r\n */\r\nexport default function MonthCalendar({\r\n year,\r\n month,\r\n days = [],\r\n title,\r\n locale = 'pt-PT',\r\n weekStartsOn = 1,\r\n today,\r\n dimPast = true,\r\n highlightCurrent = true,\r\n summary,\r\n className = '',\r\n ...props\r\n}: MonthCalendarProps) {\r\n const prefixo = `${year}-${pad(month)}-`\r\n\r\n const marcados = React.useMemo(() => {\r\n const m = new Map<string, { tone: MonthCalendarTone; labels: string[] }>()\r\n for (const d of days) {\r\n if (!d.date.startsWith(prefixo)) continue\r\n const atual = m.get(d.date)\r\n if (atual) {\r\n if (d.label) atual.labels.push(d.label)\r\n } else {\r\n m.set(d.date, { tone: d.tone, labels: d.label ? [d.label] : [] })\r\n }\r\n }\r\n return m\r\n }, [days, prefixo])\r\n\r\n const nomes = React.useMemo(() => {\r\n const utc = { timeZone: 'UTC' } as const\r\n // 05/01/2026 é segunda; 04/01/2026 domingo.\r\n const primeiro = weekStartsOn === 1 ? 5 : 4\r\n const semana = new Intl.DateTimeFormat(locale, { ...utc, weekday: 'narrow' })\r\n return {\r\n mes: new Intl.DateTimeFormat(locale, { ...utc, month: 'long' }).format(new Date(Date.UTC(year, month - 1, 1))),\r\n semana: Array.from({ length: 7 }, (_, i) => semana.format(new Date(Date.UTC(2026, 0, primeiro + i)))),\r\n longo: new Intl.DateTimeFormat(locale, { ...utc, day: 'numeric', month: 'long' }),\r\n }\r\n }, [locale, weekStartsOn, year, month])\r\n\r\n const total = new Date(Date.UTC(year, month, 0)).getUTCDate()\r\n const inicio = (new Date(Date.UTC(year, month - 1, 1)).getUTCDay() - weekStartsOn + 7) % 7\r\n const diaHoje = today === undefined ? hoje() : today\r\n const cabecalho = title === undefined ? nomes.mes : title\r\n const mesAtual = highlightCurrent && !!diaHoje && diaHoje.startsWith(prefixo)\r\n const eFimDeSemana = (coluna: number) => (weekStartsOn === 1 ? coluna >= 5 : coluna === 0 || coluna === 6)\r\n // Fundo das colunas de sábado e domingo: dá o ritmo das semanas sem competir com as marcações.\r\n const FDS = 'bg-slate-100 dark:bg-slate-800/55'\r\n // Completa a última semana, para a faixa do fim de semana chegar ao fundo.\r\n const fimVazio = (7 - ((inicio + total) % 7)) % 7\r\n\r\n // Mínimo de 7 dias × 2rem: num sítio estreito o mês não encolhe ao ponto de os números se sobreporem.\r\n return (\r\n <section\r\n {...props}\r\n aria-label={`${nomes.mes} ${year}`}\r\n data-current={mesAtual || undefined}\r\n className={`min-w-[16rem] overflow-hidden rounded-lg border border-border bg-card ${className}`}\r\n >\r\n {(cabecalho !== null || summary) && (\r\n // Faixa navy (a dos cabeçalhos das janelas); no mês de hoje, uma linha turquesa por baixo.\r\n <div\r\n className={\r\n 'flex items-baseline justify-between gap-2 bg-primary px-3.5 py-2.5 text-primary-foreground dark:bg-slate-900 dark:text-slate-50 ' +\r\n (mesAtual ? 'shadow-[inset_0_-3px_0_var(--color-proef-turquoise)]' : '')\r\n }\r\n >\r\n {cabecalho !== null && <h3 className=\"m-0 text-[15px] font-bold capitalize\">{cabecalho}</h3>}\r\n {summary && <span className=\"ml-auto text-[11px] font-semibold opacity-75\">{summary}</span>}\r\n </div>\r\n )}\r\n <div className=\"grid grid-cols-[repeat(7,minmax(2rem,1fr))] gap-0.5 p-3 text-center text-[13px] tabular-nums\">\r\n {nomes.semana.map((s, i) => (\r\n <span key={i} aria-hidden className={`rounded-t-md pb-1 text-xs font-medium uppercase text-muted-foreground ${eFimDeSemana(i) ? FDS : ''}`}>{s}</span>\r\n ))}\r\n {Array.from({ length: inicio }, (_, i) => <span key={`v${i}`} aria-hidden className={eFimDeSemana(i) ? `rounded-lg ${FDS}` : undefined} />)}\r\n {Array.from({ length: total }, (_, i) => {\r\n const dia = i + 1\r\n const data = `${prefixo}${pad(dia)}`\r\n const fimDeSemana = eFimDeSemana((inicio + i) % 7)\r\n const marca = marcados.get(data)\r\n const texto = marca?.labels.join(' · ')\r\n const eHoje = data === diaHoje\r\n const passado = dimPast && !!diaHoje && data < diaHoje\r\n return (\r\n <span\r\n key={data}\r\n data-date={data}\r\n data-today={eHoje || undefined}\r\n data-tip={texto || undefined}\r\n aria-label={texto ? `${nomes.longo.format(new Date(Date.UTC(year, month - 1, dia)))}: ${texto}` : undefined}\r\n aria-current={eHoje ? 'date' : undefined}\r\n className={[\r\n 'flex h-[34px] items-center justify-center rounded-lg transition-colors',\r\n marca\r\n ? `${BADGE_TONE_CLASSES[marca.tone]} font-semibold`\r\n : [\r\n fimDeSemana ? FDS : '',\r\n passado ? 'text-slate-400 dark:text-slate-500' : fimDeSemana ? 'text-muted-foreground' : 'text-foreground',\r\n 'hover:bg-slate-200 dark:hover:bg-slate-800',\r\n ].join(' '),\r\n texto ? 'cursor-help' : '',\r\n ].join(' ')}\r\n >\r\n {eHoje ? (\r\n <span className=\"flex h-7 w-7 items-center justify-center rounded-full bg-primary font-bold text-primary-foreground dark:bg-proef-turquoise dark:text-proef-navy\">{dia}</span>\r\n ) : (\r\n dia\r\n )}\r\n </span>\r\n )\r\n })}\r\n {Array.from({ length: fimVazio }, (_, i) => (\r\n <span key={`f${i}`} aria-hidden className={eFimDeSemana((inicio + total + i) % 7) ? `rounded-lg ${FDS}` : undefined} />\r\n ))}\r\n </div>\r\n </section>\r\n )\r\n}\r\n\r\nexport { MonthCalendar }\r\n"],"names":[],"mappings":";;;AAuCA,MAAM,MAAM,CAAC,MAAc,OAAO,CAAC,EAAE,SAAS,GAAG,GAAG;AACpD,MAAM,OAAO,MAAM;AACjB,QAAM,wBAAQ,KAAA;AACd,SAAO,GAAG,EAAE,YAAA,CAAa,IAAI,IAAI,EAAE,SAAA,IAAa,CAAC,CAAC,IAAI,IAAI,EAAE,QAAA,CAAS,CAAC;AACxE;AAWA,SAAwB,cAAc;AAAA,EACpC;AAAA,EACA;AAAA,EACA,OAAO,CAAA;AAAA,EACP;AAAA,EACA,SAAS;AAAA,EACT,eAAe;AAAA,EACf;AAAA,EACA,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB;AAAA,EACA,YAAY;AAAA,EACZ,GAAG;AACL,GAAuB;AACrB,QAAM,UAAU,GAAG,IAA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A,MAAA;AAAA,IAAA;AAAA,EAAA;AAGN;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DocumentDropzone.js","sources":["../../../../../../src/v1/components/documents/DocumentDropzone/DocumentDropzone.tsx"],"sourcesContent":["import React, { useEffect, useRef, useState } from 'react'\nimport PdfPreview from '../../../primitives/documents/PdfPreview/PdfPreview'\n\nexport interface DocumentDropzoneLabels {\n title: string\n hint?: string\n change: string\n remove: string\n /** Texto enquanto procura QR codes (só com `onQRCodes`), ex: \"A procurar QR codes…\". */\n scanningQR?: string\n /**\n * Mensagem quando um ficheiro não é permitido pelo `accept`, ex: \"Formato não\n * permitido. Aceita PDF, JPG ou PNG.\" Aparece logo ao arrastar e depois de largar.\n */\n rejected: string\n}\n\nexport interface DocumentDropzoneProps {\n file: File | null\n onFileChange: (file: File | null) => void\n /**\n * Tipos permitidos: extensões e/ou tipos MIME, separados por vírgulas, ex:\n * \".pdf,.jpg,.jpeg,.png\". Os restantes são recusados (ver `labels.rejected` e\n * `onReject`). Sem `accept`, aceita qualquer ficheiro.\n *\n * - `image/*` inclui SVG (que pode conter código) e HEIC (sem pré-visualização\n * na maioria dos browsers). Para documentos, prefira uma lista explícita.\n * - Só se verificam o nome e o tipo declarado, não o conteúdo: um ficheiro\n * renomeado passa. O servidor deve validar o que recebe.\n */\n accept?: string\n disabled?: boolean\n labels: DocumentDropzoneLabels\n /** Pré-visualização própria. Se devolver null/undefined, usa a de omissão (imagem, PDF ou ícone). */\n renderPreview?: (file: File, url: string) => React.ReactNode\n /**\n * Procura QR codes em cada ficheiro escolhido (imagem ou 1.ª página do PDF) e\n * entrega o texto de todos os encontrados (vazio se nenhum). Sem esta prop não\n * se procura nada. Usa a capacidade [QR Scanning](?path=/docs/v1-capabilities-documents-qr-scanning--docs).\n */\n onQRCodes?: (codes: string[], file: File) => void\n /** Chamado com os ficheiros recusados pelo `accept` (quando nenhum dos largados/escolhidos serve). */\n onReject?: (files: File[]) => void\n /** Continuar a procurar até um QR code satisfazer isto (ex: ser o QR de uma fatura). Por omissão, pára no primeiro. */\n qrCodeWanted?: (code: string) => boolean\n className?: string\n}\n\n// Tipos MIME das extensões mais comuns. Ao arrastar, o browser só revela o tipo\n// do ficheiro (não o nome), por isso as regras \".ext\" são traduzidas por aqui.\nconst EXT_TYPES: Record<string, string[]> = {\n '.pdf': ['application/pdf'],\n '.jpg': ['image/jpeg'],\n '.jpeg': ['image/jpeg'],\n '.png': ['image/png'],\n '.webp': ['image/webp'],\n '.gif': ['image/gif'],\n '.heic': ['image/heic'],\n '.svg': ['image/svg+xml'],\n '.doc': ['application/msword'],\n '.docx': ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],\n '.xls': ['application/vnd.ms-excel'],\n '.xlsx': ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],\n '.csv': ['text/csv', 'application/vnd.ms-excel'],\n '.txt': ['text/plain'],\n '.zip': ['application/zip', 'application/x-zip-compressed'],\n}\n\n/**\n * Se um ficheiro deste tipo é permitido, sabendo só o tipo (durante o arrastar).\n * `null` quando não dá para saber (tipo desconhecido, ou extensão fora da tabela).\n */\nexport function acceptsType(type: string, accept?: string): boolean | null {\n const rules = (accept ?? '')\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter(Boolean)\n if (rules.length === 0) return true\n const t = type.toLowerCase()\n if (!t) return null\n let unknown = false\n for (const rule of rules) {\n if (rule.startsWith('.')) {\n const types = EXT_TYPES[rule]\n if (!types) unknown = true\n else if (types.includes(t)) return true\n } else if (rule.endsWith('/*')) {\n if (t.startsWith(rule.slice(0, -1))) return true\n } else if (t === rule) return true\n }\n return unknown ? null : false\n}\n\nexport function accepts(file: File, accept?: string): boolean {\n if (!accept) return true\n const name = file.name.toLowerCase()\n const type = file.type.toLowerCase()\n // Regras vazias (ex: vírgula a mais em \".pdf,\") são ignoradas: senão aceitavam\n // qualquer ficheiro cujo tipo o browser não conhece (type === '').\n const rules = accept\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter(Boolean)\n if (rules.length === 0) return true\n return rules.some((rule) => {\n if (rule.startsWith('.')) return name.endsWith(rule)\n if (rule.endsWith('/*')) return type.startsWith(rule.slice(0, -1))\n return type === rule\n })\n}\n\nfunction UploadIcon() {\n return (\n <svg width=\"36\" height=\"36\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.9\" aria-hidden>\n <path d=\"M12 15V4M7.5 8.5L12 4l4.5 4.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n <path d=\"M4.5 14v3.5a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V14\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n )\n}\n\nfunction DocumentIcon({ size }: { size: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" aria-hidden>\n <path d=\"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n <path d=\"M14 2v5h5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n )\n}\n\nfunction ImageIcon() {\n return (\n <svg width=\"17\" height=\"17\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" aria-hidden>\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" />\n <circle cx=\"8.5\" cy=\"8.5\" r=\"1.5\" />\n <path d=\"M21 15l-5-5L4 20\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n )\n}\n\n// Documento com etiqueta do formato (PDF, XLS, CSV). As letras são recortadas\n// da etiqueta (máscara), para lerem bem sobre qualquer fundo, claro ou escuro.\nfunction FileTypeIcon({ label, size = 20 }: { label: string; size?: number }) {\n const id = React.useId()\n return (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" aria-hidden>\n <mask id={`${id}-doc`} stroke=\"none\">\n <rect width=\"24\" height=\"24\" fill=\"#fff\" />\n <rect x=\"1\" y=\"11\" width=\"17\" height=\"9.5\" rx=\"2\" fill=\"#000\" />\n </mask>\n <mask id={`${id}-label`} stroke=\"none\">\n <rect x=\"2\" y=\"12\" width=\"15\" height=\"7.5\" rx=\"1.6\" fill=\"#fff\" />\n <text x=\"9.5\" y=\"17.9\" textAnchor=\"middle\" fontFamily=\"Arial, Helvetica, sans-serif\" fontWeight=\"700\" fontSize=\"6\" fill=\"#000\">\n {label}\n </text>\n </mask>\n <g mask={`url(#${id}-doc)`}>\n <path d=\"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z\" strokeLinejoin=\"round\" />\n <path d=\"M14 2v5h5\" strokeLinejoin=\"round\" />\n </g>\n <rect x=\"2\" y=\"12\" width=\"15\" height=\"7.5\" rx=\"1.6\" fill=\"currentColor\" stroke=\"none\" mask={`url(#${id}-label)`} />\n </svg>\n )\n}\n\nconst spreadsheetLabel = (file: File) => (/.csv$/i.test(file.name) || file.type.toLowerCase() === 'text/csv' ? 'CSV' : 'XLS')\n\nconst isPdf = (file: File) => file.type === 'application/pdf'\n\nconst SPREADSHEET_TYPES = [\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'application/vnd.ms-excel.sheet.macroenabled.12',\n 'application/vnd.ms-excel',\n 'text/csv',\n]\n/** Folhas de cálculo (Excel, CSV): pela extensão ou pelo tipo, que o browser às vezes não conhece. */\nexport const isSpreadsheet = (file: File) => /\\.(xlsx|xlsm|xls|csv)$/i.test(file.name) || SPREADSHEET_TYPES.includes(file.type.toLowerCase())\n\nfunction DefaultPreview({ file, url }: { file: File; url: string }) {\n if (file.type.startsWith('image/')) {\n return <img src={url} alt={file.name} className=\"block max-h-full max-w-full object-contain p-3\" />\n }\n if (isPdf(file)) {\n return <PdfPreview file={file} label={file.name} />\n }\n return (\n <div className=\"flex h-24 w-24 items-center justify-center rounded-3xl bg-primary text-primary-foreground shadow-tile\">\n {isSpreadsheet(file) ? <FileTypeIcon label={spreadsheetLabel(file)} size={42} /> : <DocumentIcon size={42} />}\n </div>\n )\n}\n\n/**\n * Caixa para anexar um ficheiro a um formulário: arrastar ou clicar para\n * escolher. Mostra o nome, o tamanho e uma pré-visualização do ficheiro.\n *\n * **Usa:** [PdfPreview](?path=/docs/v1-primitives-documents-pdfpreview--docs) para mostrar PDFs; imagens com `<img>`.\n * Com `onQRCodes`, a capacidade [QR Scanning](?path=/docs/v1-capabilities-documents-qr-scanning--docs).\n */\nexport default function DocumentDropzone({\n file,\n onFileChange,\n accept,\n disabled = false,\n labels,\n renderPreview,\n onQRCodes,\n qrCodeWanted,\n onReject,\n className = '',\n}: DocumentDropzoneProps) {\n const input = useRef<HTMLInputElement>(null)\n // Durante o arrastar: 'ok' se o ficheiro serve (ou não dá para saber), 'rejected' se não.\n const [drag, setDrag] = useState<'none' | 'ok' | 'rejected'>('none')\n const [url, setUrl] = useState('')\n const [scanning, setScanning] = useState(false)\n const [rejected, setRejected] = useState(false)\n\n // A mensagem de recusa desaparece sozinha passado uns segundos.\n useEffect(() => {\n if (!rejected) return\n const t = window.setTimeout(() => setRejected(false), 5000)\n return () => window.clearTimeout(t)\n }, [rejected])\n\n // Sempre a versão mais recente das funções da app, sem recomeçar a leitura\n // quando a app passa uma função nova em cada render.\n const onQRCodesRef = useRef(onQRCodes)\n const qrCodeWantedRef = useRef(qrCodeWanted)\n onQRCodesRef.current = onQRCodes\n qrCodeWantedRef.current = qrCodeWanted\n const scanQR = Boolean(onQRCodes)\n\n useEffect(() => {\n if (!file || !scanQR) {\n setScanning(false)\n return\n }\n let alive = true\n setScanning(true)\n import('../../../capabilities/documents/QRScanning/scanQRCodes')\n .then(({ scanQRCodes }) => scanQRCodes(file, { until: (code) => qrCodeWantedRef.current?.(code) ?? true }))\n .catch(() => [] as string[])\n .then((codes) => {\n // Um resultado de um ficheiro que entretanto mudou é descartado.\n if (!alive) return\n setScanning(false)\n onQRCodesRef.current?.(codes, file)\n })\n return () => {\n alive = false\n }\n }, [file, scanQR])\n\n useEffect(() => {\n if (!file) {\n setUrl('')\n return\n }\n const created = URL.createObjectURL(file)\n setUrl(created)\n return () => URL.revokeObjectURL(created)\n }, [file])\n\n const pick = () => {\n if (!disabled) input.current?.click()\n }\n\n const receive = (list: FileList | null) => {\n if (disabled || !list || list.length === 0) return\n const files = Array.from(list)\n const first = files.find((f) => accepts(f, accept))\n if (first) {\n setRejected(false)\n onFileChange(first)\n return\n }\n setRejected(true)\n onReject?.(files)\n }\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n if (e.key !== 'Enter' && e.key !== ' ') return\n e.preventDefault()\n pick()\n }\n\n let frame = 'border-2 border-dashed border-primary/30 bg-card shadow-card hover:border-primary hover:bg-muted hover:shadow-card-hover'\n if (file) frame = 'border border-border bg-card shadow-card'\n if (drag === 'ok') frame = 'border-2 border-dashed border-primary bg-primary/5 shadow-card-active'\n if (drag === 'rejected') frame = 'border-2 border-dashed border-destructive bg-destructive/5 shadow-card'\n if (disabled) frame += ' cursor-not-allowed opacity-60'\n\n const sizeMb = file ? (file.size / 1024 / 1024).toFixed(2) : ''\n const custom = file && url && renderPreview ? renderPreview(file, url) : null\n const preview = file && url ? custom ?? <DefaultPreview file={file} url={url} /> : null\n\n return (\n <div\n onDragOver={(e) => {\n e.preventDefault()\n if (disabled) {\n e.dataTransfer.dropEffect = 'none'\n return\n }\n const types = Array.from(e.dataTransfer.items ?? [])\n .filter((item) => item.kind === 'file')\n .map((item) => item.type)\n const verdict = types.length && types.every((t) => acceptsType(t, accept) === false) ? 'rejected' : 'ok'\n e.dataTransfer.dropEffect = verdict === 'rejected' ? 'none' : 'copy'\n setDrag(verdict)\n }}\n onDragLeave={(e) => {\n // Passar por cima do ícone ou do texto da caixa não é sair dela.\n if (e.currentTarget.contains(e.relatedTarget as Node | null)) return\n // Ficheiro não permitido: a mensagem fica uns segundos depois de largar/sair.\n if (drag === 'rejected') setRejected(true)\n setDrag('none')\n }}\n onDrop={(e) => {\n e.preventDefault()\n setDrag('none')\n receive(e.dataTransfer.files)\n }}\n className={`group relative flex overflow-hidden rounded-2xl transition-[border-color,background-color,box-shadow] duration-200 ${frame} ${className}`}\n >\n {!file && (\n <div\n role=\"button\"\n tabIndex={disabled ? -1 : 0}\n aria-disabled={disabled}\n onClick={pick}\n onKeyDown={onKeyDown}\n className=\"flex h-full w-full cursor-pointer flex-col items-center justify-center gap-[18px] px-6 py-7 text-center outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <div className=\"flex h-[78px] w-[78px] items-center justify-center rounded-[22px] bg-primary/5 text-primary transition-transform duration-200 group-hover:-translate-y-0.5\">\n <UploadIcon />\n </div>\n <div>\n <div className=\"mb-1.5 text-title font-semibold text-foreground\">{labels.title}</div>\n {labels.hint && <div className=\"text-control text-muted-foreground\">{labels.hint}</div>}\n </div>\n </div>\n )}\n\n {file && (\n <div className=\"flex h-full min-h-0 w-full flex-col\">\n <div className=\"flex flex-none items-center gap-[11px] border-b border-border bg-card py-2.5 pr-3 pl-3.5\">\n <span className=\"flex h-[30px] w-[30px] flex-none items-center justify-center rounded-lg bg-primary/5 text-primary\">\n {isPdf(file) ? (\n <FileTypeIcon label=\"PDF\" />\n ) : isSpreadsheet(file) ? (\n <FileTypeIcon label={spreadsheetLabel(file)} />\n ) : file.type.startsWith('image/') ? (\n <ImageIcon />\n ) : (\n <DocumentIcon size={17} />\n )}\n </span>\n <div className=\"min-w-0 flex-1 text-left\">\n <div className=\"truncate text-control font-semibold text-primary\">{file.name}</div>\n <div className=\"mt-px flex items-center gap-1.5 text-caption text-muted-foreground\">\n <span>{sizeMb} MB</span>\n {scanning && (\n <span role=\"status\" className=\"inline-flex items-center gap-1.5\">\n <span aria-hidden className=\"inline-block h-2.5 w-2.5 animate-spin rounded-full border-[1.5px] border-primary/20 border-t-primary\" />\n {labels.scanningQR}\n </span>\n )}\n </div>\n </div>\n <button\n type=\"button\"\n disabled={disabled}\n onClick={pick}\n className=\"inline-flex flex-none cursor-pointer items-center gap-1.5 rounded-lg border border-border bg-card px-[11px] py-1.5 text-caption font-bold tracking-[0.02em] text-primary transition-colors duration-150 hover:border-primary/30 hover:bg-primary/5 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none\"\n >\n <svg width=\"13\" height=\"13\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.2\" aria-hidden>\n <path d=\"M21 12a9 9 0 1 1-2.64-6.36\" strokeLinecap=\"round\" />\n <path d=\"M21 3v5h-5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n {labels.change}\n </button>\n <button\n type=\"button\"\n title={labels.remove}\n aria-label={labels.remove}\n disabled={disabled}\n onClick={() => onFileChange(null)}\n className=\"inline-flex h-8 w-8 flex-none cursor-pointer items-center justify-center rounded-lg border border-border bg-card p-0 text-muted-foreground transition-colors duration-150 hover:border-destructive/30 hover:bg-destructive/10 hover:text-destructive\"\n >\n <svg width=\"15\" height=\"15\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.9\" aria-hidden>\n <path d=\"M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-13\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n </button>\n </div>\n <div className=\"flex min-h-0 flex-1 basis-0 items-center justify-center overflow-hidden bg-card\">\n {preview}\n </div>\n </div>\n )}\n\n {(rejected || drag === 'rejected') && (\n <div\n role=\"alert\"\n className=\"absolute inset-x-3 bottom-3 rounded-lg border border-destructive/30 bg-card px-3 py-2 text-center text-xs font-medium text-destructive shadow-popover\"\n >\n {labels.rejected}\n </div>\n )}\n\n <input\n ref={input}\n type=\"file\"\n accept={accept}\n className=\"hidden\"\n onChange={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,QAAA,CACH;AAAA,QAAA,GACF;AAAA,SAGA,YAAY,SAAS,eACrB;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,MAAK;AAAA,YACL,WAAU;AAAA,YAET,UAAA,OAAO;AAAA,UAAA;AAAA,QAAA;AAAA,QAIZ;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,KAAK;AAAA,YACL,MAAK;AAAA,YACL;AAAA,YACA,WAAU;AAAA,YACV,UAAU,CAAC,MAAM;AACf,sBAAQ,EAAE,OAAO,KAAK;AACtB,gBAAE,OAAO,QAAQ;AAAA,YACnB;AAAA,UAAA;AAAA,QAAA;AAAA,MACF;AAAA,IAAA;AAAA,EAAA;AAGN;"}
|
|
1
|
+
{"version":3,"file":"DocumentDropzone.js","sources":["../../../../../../src/v1/components/documents/DocumentDropzone/DocumentDropzone.tsx"],"sourcesContent":["import React, { useEffect, useRef, useState } from 'react'\r\nimport PdfPreview from '../../../primitives/documents/PdfPreview/PdfPreview'\r\n\r\nexport interface DocumentDropzoneLabels {\r\n title: string\r\n hint?: string\r\n change: string\r\n remove: string\r\n /** Texto enquanto procura QR codes (só com `onQRCodes`), ex: \"A procurar QR codes…\". */\r\n scanningQR?: string\r\n /**\r\n * Mensagem quando um ficheiro não é permitido pelo `accept`, ex: \"Formato não\r\n * permitido. Aceita PDF, JPG ou PNG.\" Aparece logo ao arrastar e depois de largar.\r\n */\r\n rejected: string\r\n}\r\n\r\nexport interface DocumentDropzoneProps {\r\n file: File | null\r\n onFileChange: (file: File | null) => void\r\n /**\r\n * Tipos permitidos: extensões e/ou tipos MIME, separados por vírgulas, ex:\r\n * \".pdf,.jpg,.jpeg,.png\". Os restantes são recusados (ver `labels.rejected` e\r\n * `onReject`). Sem `accept`, aceita qualquer ficheiro.\r\n *\r\n * - `image/*` inclui SVG (que pode conter código) e HEIC (sem pré-visualização\r\n * na maioria dos browsers). Para documentos, prefira uma lista explícita.\r\n * - Só se verificam o nome e o tipo declarado, não o conteúdo: um ficheiro\r\n * renomeado passa. O servidor deve validar o que recebe.\r\n */\r\n accept?: string\r\n disabled?: boolean\r\n labels: DocumentDropzoneLabels\r\n /** Pré-visualização própria. Se devolver null/undefined, usa a de omissão (imagem, PDF ou ícone). */\r\n renderPreview?: (file: File, url: string) => React.ReactNode\r\n /**\r\n * Procura QR codes em cada ficheiro escolhido (imagem ou 1.ª página do PDF) e\r\n * entrega o texto de todos os encontrados (vazio se nenhum). Sem esta prop não\r\n * se procura nada. Usa a capacidade [QR Scanning](?path=/docs/v1-capabilities-documents-qr-scanning--docs).\r\n */\r\n onQRCodes?: (codes: string[], file: File) => void\r\n /** Chamado com os ficheiros recusados pelo `accept` (quando nenhum dos largados/escolhidos serve). */\r\n onReject?: (files: File[]) => void\r\n /** Continuar a procurar até um QR code satisfazer isto (ex: ser o QR de uma fatura). Por omissão, pára no primeiro. */\r\n qrCodeWanted?: (code: string) => boolean\r\n className?: string\r\n}\r\n\r\n// Tipos MIME das extensões mais comuns. Ao arrastar, o browser só revela o tipo\r\n// do ficheiro (não o nome), por isso as regras \".ext\" são traduzidas por aqui.\r\nconst EXT_TYPES: Record<string, string[]> = {\r\n '.pdf': ['application/pdf'],\r\n '.jpg': ['image/jpeg'],\r\n '.jpeg': ['image/jpeg'],\r\n '.png': ['image/png'],\r\n '.webp': ['image/webp'],\r\n '.gif': ['image/gif'],\r\n '.heic': ['image/heic'],\r\n '.svg': ['image/svg+xml'],\r\n '.doc': ['application/msword'],\r\n '.docx': ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],\r\n '.xls': ['application/vnd.ms-excel'],\r\n '.xlsx': ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],\r\n '.csv': ['text/csv', 'application/vnd.ms-excel'],\r\n '.txt': ['text/plain'],\r\n '.zip': ['application/zip', 'application/x-zip-compressed'],\r\n}\r\n\r\n/**\r\n * Se um ficheiro deste tipo é permitido, sabendo só o tipo (durante o arrastar).\r\n * `null` quando não dá para saber (tipo desconhecido, ou extensão fora da tabela).\r\n */\r\nexport function acceptsType(type: string, accept?: string): boolean | null {\r\n const rules = (accept ?? '')\r\n .split(',')\r\n .map((s) => s.trim().toLowerCase())\r\n .filter(Boolean)\r\n if (rules.length === 0) return true\r\n const t = type.toLowerCase()\r\n if (!t) return null\r\n let unknown = false\r\n for (const rule of rules) {\r\n if (rule.startsWith('.')) {\r\n const types = EXT_TYPES[rule]\r\n if (!types) unknown = true\r\n else if (types.includes(t)) return true\r\n } else if (rule.endsWith('/*')) {\r\n if (t.startsWith(rule.slice(0, -1))) return true\r\n } else if (t === rule) return true\r\n }\r\n return unknown ? null : false\r\n}\r\n\r\nexport function accepts(file: File, accept?: string): boolean {\r\n if (!accept) return true\r\n const name = file.name.toLowerCase()\r\n const type = file.type.toLowerCase()\r\n // Regras vazias (ex: vírgula a mais em \".pdf,\") são ignoradas: senão aceitavam\r\n // qualquer ficheiro cujo tipo o browser não conhece (type === '').\r\n const rules = accept\r\n .split(',')\r\n .map((s) => s.trim().toLowerCase())\r\n .filter(Boolean)\r\n if (rules.length === 0) return true\r\n return rules.some((rule) => {\r\n if (rule.startsWith('.')) return name.endsWith(rule)\r\n if (rule.endsWith('/*')) return type.startsWith(rule.slice(0, -1))\r\n return type === rule\r\n })\r\n}\r\n\r\nfunction UploadIcon() {\r\n return (\r\n <svg width=\"36\" height=\"36\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.9\" aria-hidden>\r\n <path d=\"M12 15V4M7.5 8.5L12 4l4.5 4.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\r\n <path d=\"M4.5 14v3.5a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V14\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\r\n </svg>\r\n )\r\n}\r\n\r\nfunction DocumentIcon({ size }: { size: number }) {\r\n return (\r\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" aria-hidden>\r\n <path d=\"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\r\n <path d=\"M14 2v5h5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\r\n </svg>\r\n )\r\n}\r\n\r\nfunction ImageIcon() {\r\n return (\r\n <svg width=\"17\" height=\"17\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" aria-hidden>\r\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" />\r\n <circle cx=\"8.5\" cy=\"8.5\" r=\"1.5\" />\r\n <path d=\"M21 15l-5-5L4 20\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\r\n </svg>\r\n )\r\n}\r\n\r\n// Documento com etiqueta do formato (PDF, XLS, CSV). As letras são recortadas\r\n// da etiqueta (máscara), para lerem bem sobre qualquer fundo, claro ou escuro.\r\nfunction FileTypeIcon({ label, size = 20 }: { label: string; size?: number }) {\r\n const id = React.useId()\r\n return (\r\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" aria-hidden>\r\n <mask id={`${id}-doc`} stroke=\"none\">\r\n <rect width=\"24\" height=\"24\" fill=\"#fff\" />\r\n <rect x=\"1\" y=\"11\" width=\"17\" height=\"9.5\" rx=\"2\" fill=\"#000\" />\r\n </mask>\r\n <mask id={`${id}-label`} stroke=\"none\">\r\n <rect x=\"2\" y=\"12\" width=\"15\" height=\"7.5\" rx=\"1.6\" fill=\"#fff\" />\r\n <text x=\"9.5\" y=\"17.9\" textAnchor=\"middle\" fontFamily=\"Arial, Helvetica, sans-serif\" fontWeight=\"700\" fontSize=\"6\" fill=\"#000\">\r\n {label}\r\n </text>\r\n </mask>\r\n <g mask={`url(#${id}-doc)`}>\r\n <path d=\"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z\" strokeLinejoin=\"round\" />\r\n <path d=\"M14 2v5h5\" strokeLinejoin=\"round\" />\r\n </g>\r\n <rect x=\"2\" y=\"12\" width=\"15\" height=\"7.5\" rx=\"1.6\" fill=\"currentColor\" stroke=\"none\" mask={`url(#${id}-label)`} />\r\n </svg>\r\n )\r\n}\r\n\r\nconst spreadsheetLabel = (file: File) => (/.csv$/i.test(file.name) || file.type.toLowerCase() === 'text/csv' ? 'CSV' : 'XLS')\r\n\r\nconst isPdf = (file: File) => file.type === 'application/pdf'\r\n\r\nconst SPREADSHEET_TYPES = [\r\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\r\n 'application/vnd.ms-excel.sheet.macroenabled.12',\r\n 'application/vnd.ms-excel',\r\n 'text/csv',\r\n]\r\n/** Folhas de cálculo (Excel, CSV): pela extensão ou pelo tipo, que o browser às vezes não conhece. */\r\nexport const isSpreadsheet = (file: File) => /\\.(xlsx|xlsm|xls|csv)$/i.test(file.name) || SPREADSHEET_TYPES.includes(file.type.toLowerCase())\r\n\r\nfunction DefaultPreview({ file, url }: { file: File; url: string }) {\r\n if (file.type.startsWith('image/')) {\r\n return <img src={url} alt={file.name} className=\"block max-h-full max-w-full object-contain p-3\" />\r\n }\r\n if (isPdf(file)) {\r\n return <PdfPreview file={file} label={file.name} />\r\n }\r\n return (\r\n <div className=\"flex h-24 w-24 items-center justify-center rounded-3xl bg-primary text-primary-foreground shadow-tile\">\r\n {isSpreadsheet(file) ? <FileTypeIcon label={spreadsheetLabel(file)} size={42} /> : <DocumentIcon size={42} />}\r\n </div>\r\n )\r\n}\r\n\r\n/**\r\n * Caixa para anexar um ficheiro a um formulário: arrastar ou clicar para\r\n * escolher. Mostra o nome, o tamanho e uma pré-visualização do ficheiro.\r\n *\r\n * **Usa:** [PdfPreview](?path=/docs/v1-primitives-documents-pdfpreview--docs) para mostrar PDFs; imagens com `<img>`.\r\n * Com `onQRCodes`, a capacidade [QR Scanning](?path=/docs/v1-capabilities-documents-qr-scanning--docs).\r\n */\r\nexport default function DocumentDropzone({\r\n file,\r\n onFileChange,\r\n accept,\r\n disabled = false,\r\n labels,\r\n renderPreview,\r\n onQRCodes,\r\n qrCodeWanted,\r\n onReject,\r\n className = '',\r\n}: DocumentDropzoneProps) {\r\n const input = useRef<HTMLInputElement>(null)\r\n // Durante o arrastar: 'ok' se o ficheiro serve (ou não dá para saber), 'rejected' se não.\r\n const [drag, setDrag] = useState<'none' | 'ok' | 'rejected'>('none')\r\n const [url, setUrl] = useState('')\r\n const [scanning, setScanning] = useState(false)\r\n const [rejected, setRejected] = useState(false)\r\n\r\n // A mensagem de recusa desaparece sozinha passado uns segundos.\r\n useEffect(() => {\r\n if (!rejected) return\r\n const t = window.setTimeout(() => setRejected(false), 5000)\r\n return () => window.clearTimeout(t)\r\n }, [rejected])\r\n\r\n // Sempre a versão mais recente das funções da app, sem recomeçar a leitura\r\n // quando a app passa uma função nova em cada render.\r\n const onQRCodesRef = useRef(onQRCodes)\r\n const qrCodeWantedRef = useRef(qrCodeWanted)\r\n onQRCodesRef.current = onQRCodes\r\n qrCodeWantedRef.current = qrCodeWanted\r\n const scanQR = Boolean(onQRCodes)\r\n\r\n useEffect(() => {\r\n if (!file || !scanQR) {\r\n setScanning(false)\r\n return\r\n }\r\n let alive = true\r\n setScanning(true)\r\n import('../../../capabilities/documents/QRScanning/scanQRCodes')\r\n .then(({ scanQRCodes }) => scanQRCodes(file, { until: (code) => qrCodeWantedRef.current?.(code) ?? true }))\r\n .catch(() => [] as string[])\r\n .then((codes) => {\r\n // Um resultado de um ficheiro que entretanto mudou é descartado.\r\n if (!alive) return\r\n setScanning(false)\r\n onQRCodesRef.current?.(codes, file)\r\n })\r\n return () => {\r\n alive = false\r\n }\r\n }, [file, scanQR])\r\n\r\n useEffect(() => {\r\n if (!file) {\r\n setUrl('')\r\n return\r\n }\r\n const created = URL.createObjectURL(file)\r\n setUrl(created)\r\n return () => URL.revokeObjectURL(created)\r\n }, [file])\r\n\r\n const pick = () => {\r\n if (!disabled) input.current?.click()\r\n }\r\n\r\n const receive = (list: FileList | null) => {\r\n if (disabled || !list || list.length === 0) return\r\n const files = Array.from(list)\r\n const first = files.find((f) => accepts(f, accept))\r\n if (first) {\r\n setRejected(false)\r\n onFileChange(first)\r\n return\r\n }\r\n setRejected(true)\r\n onReject?.(files)\r\n }\r\n\r\n const onKeyDown = (e: React.KeyboardEvent) => {\r\n if (e.key !== 'Enter' && e.key !== ' ') return\r\n e.preventDefault()\r\n pick()\r\n }\r\n\r\n let frame = 'border-2 border-dashed border-primary/30 bg-card shadow-card hover:border-primary hover:bg-muted hover:shadow-card-hover'\r\n if (file) frame = 'border border-border bg-card shadow-card'\r\n if (drag === 'ok') frame = 'border-2 border-dashed border-primary bg-primary/5 shadow-card-active'\r\n if (drag === 'rejected') frame = 'border-2 border-dashed border-destructive bg-destructive/5 shadow-card'\r\n if (disabled) frame += ' cursor-not-allowed opacity-60'\r\n\r\n const sizeMb = file ? (file.size / 1024 / 1024).toFixed(2) : ''\r\n const custom = file && url && renderPreview ? renderPreview(file, url) : null\r\n const preview = file && url ? custom ?? <DefaultPreview file={file} url={url} /> : null\r\n\r\n return (\r\n <div\r\n onDragOver={(e) => {\r\n e.preventDefault()\r\n if (disabled) {\r\n e.dataTransfer.dropEffect = 'none'\r\n return\r\n }\r\n const types = Array.from(e.dataTransfer.items ?? [])\r\n .filter((item) => item.kind === 'file')\r\n .map((item) => item.type)\r\n const verdict = types.length && types.every((t) => acceptsType(t, accept) === false) ? 'rejected' : 'ok'\r\n e.dataTransfer.dropEffect = verdict === 'rejected' ? 'none' : 'copy'\r\n setDrag(verdict)\r\n }}\r\n onDragLeave={(e) => {\r\n // Passar por cima do ícone ou do texto da caixa não é sair dela.\r\n if (e.currentTarget.contains(e.relatedTarget as Node | null)) return\r\n // Ficheiro não permitido: a mensagem fica uns segundos depois de largar/sair.\r\n if (drag === 'rejected') setRejected(true)\r\n setDrag('none')\r\n }}\r\n onDrop={(e) => {\r\n e.preventDefault()\r\n setDrag('none')\r\n receive(e.dataTransfer.files)\r\n }}\r\n className={`group relative flex overflow-hidden rounded-2xl transition-[border-color,background-color,box-shadow] duration-200 ${frame} ${className}`}\r\n >\r\n {!file && (\r\n <div\r\n role=\"button\"\r\n tabIndex={disabled ? -1 : 0}\r\n aria-disabled={disabled}\r\n onClick={pick}\r\n onKeyDown={onKeyDown}\r\n className=\"flex h-full w-full cursor-pointer flex-col items-center justify-center gap-[18px] px-6 py-7 text-center outline-none focus-visible:ring-2 focus-visible:ring-ring\"\r\n >\r\n <div className=\"flex h-[78px] w-[78px] items-center justify-center rounded-[22px] bg-primary/5 text-primary transition-transform duration-200 group-hover:-translate-y-0.5\">\r\n <UploadIcon />\r\n </div>\r\n <div>\r\n <div className=\"mb-1.5 text-title font-semibold text-foreground\">{labels.title}</div>\r\n {labels.hint && <div className=\"text-control text-muted-foreground\">{labels.hint}</div>}\r\n </div>\r\n </div>\r\n )}\r\n\r\n {file && (\r\n <div className=\"flex h-full min-h-0 w-full flex-col\">\r\n <div className=\"flex flex-none items-center gap-[11px] border-b border-border bg-card py-2.5 pr-3 pl-3.5\">\r\n <span className=\"flex h-[30px] w-[30px] flex-none items-center justify-center rounded-lg bg-primary/5 text-primary\">\r\n {isPdf(file) ? (\r\n <FileTypeIcon label=\"PDF\" />\r\n ) : isSpreadsheet(file) ? (\r\n <FileTypeIcon label={spreadsheetLabel(file)} />\r\n ) : file.type.startsWith('image/') ? (\r\n <ImageIcon />\r\n ) : (\r\n <DocumentIcon size={17} />\r\n )}\r\n </span>\r\n <div className=\"min-w-0 flex-1 text-left\">\r\n <div className=\"truncate text-control font-semibold text-primary\">{file.name}</div>\r\n <div className=\"mt-px flex items-center gap-1.5 text-caption text-muted-foreground\">\r\n <span>{sizeMb} MB</span>\r\n {scanning && (\r\n <span role=\"status\" className=\"inline-flex items-center gap-1.5\">\r\n <span aria-hidden className=\"inline-block h-2.5 w-2.5 animate-spin rounded-full border-[1.5px] border-primary/20 border-t-primary\" />\r\n {labels.scanningQR}\r\n </span>\r\n )}\r\n </div>\r\n </div>\r\n <button\r\n type=\"button\"\r\n disabled={disabled}\r\n onClick={pick}\r\n className=\"inline-flex flex-none cursor-pointer items-center gap-1.5 rounded-lg border border-border bg-card px-[11px] py-1.5 text-caption font-bold tracking-[0.02em] text-primary transition-colors duration-150 hover:border-primary/30 hover:bg-primary/5 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none\"\r\n >\r\n <svg width=\"13\" height=\"13\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.2\" aria-hidden>\r\n <path d=\"M21 12a9 9 0 1 1-2.64-6.36\" strokeLinecap=\"round\" />\r\n <path d=\"M21 3v5h-5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\r\n </svg>\r\n {labels.change}\r\n </button>\r\n <button\r\n type=\"button\"\r\n title={labels.remove}\r\n aria-label={labels.remove}\r\n disabled={disabled}\r\n onClick={() => onFileChange(null)}\r\n className=\"inline-flex h-8 w-8 flex-none cursor-pointer items-center justify-center rounded-lg border border-border bg-card p-0 text-muted-foreground transition-colors duration-150 hover:border-destructive/30 hover:bg-destructive/10 hover:text-destructive\"\r\n >\r\n <svg width=\"15\" height=\"15\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.9\" aria-hidden>\r\n <path d=\"M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-13\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\r\n </svg>\r\n </button>\r\n </div>\r\n <div className=\"flex min-h-0 flex-1 basis-0 items-center justify-center overflow-hidden bg-card\">\r\n {preview}\r\n </div>\r\n </div>\r\n )}\r\n\r\n {(rejected || drag === 'rejected') && (\r\n <div\r\n role=\"alert\"\r\n className=\"absolute inset-x-3 bottom-3 rounded-lg border border-destructive/30 bg-card px-3 py-2 text-center text-xs font-medium text-destructive shadow-popover\"\r\n >\r\n {labels.rejected}\r\n </div>\r\n )}\r\n\r\n <input\r\n ref={input}\r\n type=\"file\"\r\n accept={accept}\r\n className=\"hidden\"\r\n onChange={(e) => {\r\n receive(e.target.files)\r\n e.target.value = ''\r\n }}\r\n />\r\n </div>\r\n )\r\n}\r\n"],"names":[],"mappings":";;;AAkDA,MAAM,YAAsC;AAAA,EAC1C,QAAQ,CAAC,iBAAiB;AAAA,EAC1B,QAAQ,CAAC,YAAY;AAAA,EACrB,SAAS,CAAC,YAAY;AAAA,EACtB,QAAQ,CAAC,WAAW;AAAA,EACpB,SAAS,CAAC,YAAY;AAAA,EACtB,QAAQ,CAAC,WAAW;AAAA,EACpB,SAAS,CAAC,YAAY;AAAA,EACtB,QAAQ,CAAC,eAAe;AAAA,EACxB,QAAQ,CAAC,oBAAoB;AAAA,EAC7B,SAAS,CAAC,yEAAyE;AAAA,EACnF,QAAQ,CAAC,0BAA0B;AAAA,EACnC,SAAS,CAAC,mEAAmE;AAAA,EAC7E,QAAQ,CAAC,YAAY,0BAA0B;AAAA,EAC/C,QAAQ,CAAC,YAAY;AAAA,EACrB,QAAQ,CAAC,mBAAmB,8BAA8B;AAC5D;AAMO,SAAS,YAAY,MAAc,QAAiC;AACzE,QAAM,SAAS,UAAU,IACtB,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,OAAO,YAAA,CAAa,EACjC,OAAO,OAAO;AACjB,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,IAAI,KAAK,YAAA;AACf,MAAI,CAAC,EAAG,QAAO;AACf,MAAI,UAAU;AACd,aAAW,QAAQ,OAAO;AACxB,QAAI,KAAK,WAAW,GAAG,GAAG;AACxB,YAAM,QAAQ,UAAU,IAAI;AAC5B,UAAI,CAAC,MAAO,WAAU;AAAA,eACb,MAAM,SAAS,CAAC,EAAG,QAAO;AAAA,IACrC,WAAW,KAAK,SAAS,IAAI,GAAG;AAC9B,UAAI,EAAE,WA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K,GAAE,6FAA4F,eAAc,SAAQ,gBAAe,QAAA,CAAQ,EAAA,CACnJ;AAAA,cAAA;AAAA,YAAA;AAAA,UACF,GACF;AAAA,UACA,oBAAC,OAAA,EAAI,WAAU,mFACZ,UAAA,QAAA,CACH;AAAA,QAAA,GACF;AAAA,SAGA,YAAY,SAAS,eACrB;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,MAAK;AAAA,YACL,WAAU;AAAA,YAET,UAAA,OAAO;AAAA,UAAA;AAAA,QAAA;AAAA,QAIZ;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,KAAK;AAAA,YACL,MAAK;AAAA,YACL;AAAA,YACA,WAAU;AAAA,YACV,UAAU,CAAC,MAAM;AACf,sBAAQ,EAAE,OAAO,KAAK;AACtB,gBAAE,OAAO,QAAQ;AAAA,YACnB;AAAA,UAAA;AAAA,QAAA;AAAA,MACF;AAAA,IAAA;AAAA,EAAA;AAGN;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { jsxs, jsx, Fragment } from "react/jsx-runtime";
|
|
2
2
|
import React, { useState, useEffect } from "react";
|
|
3
3
|
import { useLocation, NavLink } from "react-router-dom";
|
|
4
|
-
import { dentroDaApp } from "../../../capabilities/onepoint/dentroDaApp.js";
|
|
4
|
+
import { dentroDaApp } from "../../../capabilities/onepoint-rn/dentroDaApp.js";
|
|
5
5
|
import { SunIcon, MoonIcon, MonitorIcon, CloseIcon, ChevronLeftIcon, ChevronRightIcon, PanelOpenIcon, ChevronDownIcon, GlobeIcon, LogOutIcon, ExternalLinkIcon } from "../../../foundations/icons/icons.js";
|
|
6
6
|
const SIDENAV_LABELS = {
|
|
7
7
|
closeMenu: "Fechar menu",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SideNav.js","sources":["../../../../../../src/v1/components/layout/SideNav/SideNav.tsx"],"sourcesContent":["import React, { useEffect, useState } from 'react'\r\nimport { NavLink, useLocation } from 'react-router-dom'\r\nimport { dentroDaApp } from '../../../capabilities/onepoint/dentroDaApp'\r\nimport {\r\n ChevronDownIcon,\r\n ChevronLeftIcon,\r\n ChevronRightIcon,\r\n CloseIcon,\r\n ExternalLinkIcon,\r\n GlobeIcon,\r\n LogOutIcon,\r\n MonitorIcon,\r\n MoonIcon,\r\n PanelOpenIcon,\r\n SunIcon,\r\n type IconProps,\r\n} from '../../../foundations/icons/icons'\r\n\r\nexport type SideNavTheme = 'light' | 'dark' | 'system'\r\n\r\nexport interface SideNavBadge {\r\n count: number\r\n /** `attention` (amarelo, por omissão): coisas à espera da pessoa. `alert` (laranja): à espera de outro circuito (ex: CAB). */\r\n tone?: 'attention' | 'alert'\r\n /** O que o número conta, para o tooltip e leitores de ecrã (ex: \"Aprovações pendentes\"). */\r\n label?: string\r\n}\r\n\r\nexport interface SideNavItem {\r\n /** Rota da app, ou URL completo com `external`. */\r\n to: string\r\n label: string\r\n /** Componente de ícone que aceita `size` e `className` (ex: um ícone do lucide-react). */\r\n icon: React.ComponentType<{ size?: number; className?: string }>\r\n /** Chave do grupo. Os itens do mesmo grupo aparecem juntos, por baixo do título do grupo. */\r\n group?: string\r\n /** Só fica ativo na rota exata (como o `end` do NavLink). */\r\n end?: boolean\r\n /** Abre num separador novo, fora da app. */\r\n external?: boolean\r\n /** Contadores ao lado do texto. Os que têm `count` 0 não aparecem. */\r\n badges?: SideNavBadge[]\r\n /**\r\n * Se esta entrada aparece dentro do WebView da app OnePoint.\r\n *\r\n * A maioria dos menus foi desenhada para secretária: catálogos, logs,\r\n * gestão de utilizadores, listas de referência. Num telemóvel só ocupam\r\n * espaço a quem nunca lhes toca.\r\n *\r\n * Sem valor, segue o `naAppPorOmissao` do `SideNav` (que por omissão\r\n * mostra tudo, para nada mudar em quem já usa isto). Um portal com muitas\r\n * entradas de secretária põe esse valor a `false` e marca aqui `true` as\r\n * poucas que servem de pé — é menos trabalho do que o contrário.\r\n */\r\n naApp?: boolean\r\n}\r\n\r\nexport interface SideNavLabels {\r\n closeMenu: string\r\n expandMenu: string\r\n collapseMenu: string\r\n /** Antes do nome do grupo, no botão que o abre/fecha (ex: \"Abrir Recursos\"). */\r\n openGroup: string\r\n closeGroup: string\r\n theme: string\r\n light: string\r\n dark: string\r\n system: string\r\n language: string\r\n logout: string\r\n deployedAt: string\r\n}\r\n\r\nexport const SIDENAV_LABELS: SideNavLabels = {\r\n closeMenu: 'Fechar menu',\r\n expandMenu: 'Expandir menu',\r\n collapseMenu: 'Recolher menu',\r\n openGroup: 'Abrir',\r\n closeGroup: 'Fechar',\r\n theme: 'Tema',\r\n light: 'Claro',\r\n dark: 'Escuro',\r\n system: 'Sistema',\r\n language: 'Idioma',\r\n logout: 'Terminar sessão',\r\n deployedAt: 'Último deploy',\r\n}\r\n\r\nexport interface SideNavProps {\r\n menu: SideNavItem[]\r\n /** Título de cada grupo do menu, pela chave (`group`). Sem título, aparece a chave. */\r\n groupLabels?: Record<string, string>\r\n /** Por baixo do logótipo (ex: \"IT Portal\"). */\r\n appTitle?: string\r\n /** Foto ou iniciais da pessoa, no topo do menu. */\r\n avatar?: React.ReactNode\r\n /** Sem isto, não há botão de terminar sessão. */\r\n onLogout?: () => void\r\n /** Escolha de idioma no rodapé. Só aparece com `languages` e `onLanguageChange`. */\r\n languages?: { code: string; label: string }[]\r\n currentLanguage?: string\r\n onLanguageChange?: (code: string) => void\r\n /**\r\n * Escolha de tema no rodapé. Só aparece com `onThemeChange`. O menu só\r\n * mostra a escolha: pôr a classe `.dark` no `<html>` é da app.\r\n */\r\n theme?: SideNavTheme\r\n onThemeChange?: (theme: SideNavTheme) => void\r\n /** Quando foi feito o build, no fundo do menu. A app decide a quem o mostra (ex: só administradores). */\r\n deployedAt?: string | number | Date\r\n /** Conteúdo extra no rodapé, por cima do tema (ex: um filtro global). Recebe se o menu está expandido. */\r\n footer?: (expanded: boolean) => React.ReactNode\r\n labels?: Partial<SideNavLabels>\r\n /**\r\n * O que fazer, dentro da app OnePoint, às entradas sem `naApp` definido.\r\n *\r\n * Por omissão `true`: o menu aparece inteiro, como sempre apareceu. Um\r\n * portal com dezenas de entradas de secretária põe isto a `false` e marca\r\n * `naApp: true` só nas que servem em telemóvel.\r\n *\r\n * Não tem efeito no browser.\r\n */\r\n naAppPorOmissao?: boolean\r\n /** Aberto (256px) ou fechado (só ícones; em ecrãs pequenos, escondido). A app guarda este estado. */\r\n open: boolean\r\n onOpenChange: (open: boolean) => void\r\n}\r\n\r\n/** Abaixo desta largura o menu é uma gaveta por cima da página; acima ocupa espaço (aberto ou só ícones). */\r\nexport const DRAWER_MAX = 1024\r\n\r\nexport const isDrawer = () => typeof window !== 'undefined' && window.innerWidth < DRAWER_MAX\r\n\r\n/** `DD/MM/AAAA, HH:MM` na hora local: um carimbo que não muda com o idioma escolhido. */\r\nfunction formatDeploy(value: string | number | Date): string {\r\n const d = value instanceof Date ? value : new Date(value)\r\n if (Number.isNaN(d.getTime())) return ''\r\n const two = (n: number) => String(n).padStart(2, '0')\r\n return `${two(d.getDate())}/${two(d.getMonth() + 1)}/${d.getFullYear()}, ${two(d.getHours())}:${two(d.getMinutes())}`\r\n}\r\n\r\nconst BADGE_TONES = {\r\n attention: 'bg-amber-400 text-proef-navy',\r\n alert: 'bg-orange-500 text-white',\r\n}\r\n\r\n/**\r\n * Menu lateral navy da app, fixo à esquerda. Normalmente usa-se através do\r\n * `AppShell`, que também trata da página ao lado.\r\n *\r\n * - **Ecrãs grandes** (≥ 1024px): aberto ocupa 256px; fechado fica só com os\r\n * ícones (80px) e abre por cima da página ao passar o rato.\r\n * - **Ecrãs pequenos**: escondido quando fechado; aberto fica por cima da\r\n * página e fecha ao escolher uma página.\r\n * - **Grupos**: abertos por omissão, fecham com um clique no título. Só com os\r\n * ícones, fica aberto apenas o grupo da página atual.\r\n *\r\n * Precisa de estar dentro de um Router do react-router.\r\n */\r\nexport default function SideNav({\r\n menu: menuProp,\r\n groupLabels = {},\r\n appTitle,\r\n avatar,\r\n onLogout,\r\n languages,\r\n currentLanguage,\r\n onLanguageChange,\r\n theme,\r\n onThemeChange,\r\n deployedAt,\r\n footer,\r\n labels: labelsProp,\r\n naAppPorOmissao = true,\r\n open,\r\n onOpenChange,\r\n}: SideNavProps) {\r\n /*\r\n Dentro da app OnePoint o menu é filtrado e o \"Terminar sessão\" não\r\n aparece.\r\n\r\n O menu: a maioria das entradas foi desenhada para secretária. Cada\r\n entrada decide por si com `naApp`; as que não decidem seguem o\r\n `naAppPorOmissao`.\r\n\r\n O logout: a sessão é da aplicação, não do portal. O que o botão faria\r\n aqui — um `logoutRedirect` do MSAL — é um redirect de topo, que a tranca\r\n de origem do ecrã nativo recusa: não fazia nada, ou saía para o browser e\r\n perdia a sessão. Quem termina sessão é a app.\r\n */\r\n const naApp = dentroDaApp()\r\n const menu = React.useMemo(\r\n () => (naApp ? menuProp.filter((i) => i.naApp ?? naAppPorOmissao) : menuProp),\r\n [menuProp, naApp, naAppPorOmissao],\r\n )\r\n const mostrarLogout = onLogout && !naApp\r\n const labels = { ...SIDENAV_LABELS, ...labelsProp }\r\n const location = useLocation()\r\n const [hovered, setHovered] = useState(false)\r\n const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})\r\n const expanded = open || hovered\r\n\r\n // O hover fica \"colado\" quando a janela perde o foco.\r\n useEffect(() => {\r\n const reset = () => setHovered(false)\r\n window.addEventListener('blur', reset)\r\n document.addEventListener('visibilitychange', reset)\r\n return () => {\r\n window.removeEventListener('blur', reset)\r\n document.removeEventListener('visibilitychange', reset)\r\n }\r\n }, [])\r\n\r\n const ungrouped = menu.filter((item) => !item.group)\r\n const groups = Array.from(new Set(menu.map((item) => item.group).filter(Boolean))) as string[]\r\n // Só com os ícones não há títulos para clicar: fica aberto só o grupo da página atual.\r\n const activeGroup = menu.find((item) => item.group && !item.external && location.pathname.startsWith(item.to))?.group\r\n\r\n const closeIfDrawer = () => {\r\n if (isDrawer()) onOpenChange(false)\r\n }\r\n\r\n const themeOptions: { value: SideNavTheme; Icon: React.ComponentType<IconProps>; label: string }[] = [\r\n { value: 'light', Icon: SunIcon, label: labels.light },\r\n { value: 'dark', Icon: MoonIcon, label: labels.dark },\r\n { value: 'system', Icon: MonitorIcon, label: labels.system },\r\n ]\r\n const currentTheme = themeOptions.find((o) => o.value === (theme ?? 'system')) ?? themeOptions[2]\r\n const cycle = <T,>(list: T[], current: T) => list[(list.indexOf(current) + 1) % list.length]\r\n\r\n const footerIconButton =\r\n 'flex cursor-pointer items-center justify-center rounded-lg border-0 bg-transparent p-2 text-white/30 transition-colors hover:bg-white/5 hover:text-proef-turquoise focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none'\r\n\r\n const renderItem = (item: SideNavItem) => {\r\n const badges = (item.badges ?? []).filter((b) => b.count > 0)\r\n const rowClass = (active: boolean) =>\r\n `mx-2 flex items-center gap-4 rounded-lg no-underline transition-colors duration-200 focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none ${\r\n expanded ? 'px-6 py-3 lg:py-2.5' : 'justify-center px-0 py-3 lg:py-2.5'\r\n } ${active ? 'bg-proef-turquoise/15 font-semibold text-proef-turquoise' : 'text-white/50 hover:bg-white/5 hover:text-white'}`\r\n\r\n const content = (active: boolean) => (\r\n <>\r\n <span className=\"relative flex-none\">\r\n <item.icon size={20} className={active ? 'drop-shadow-[0_0_6px_rgba(0,230,200,0.6)]' : ''} />\r\n {badges.length > 0 && !expanded && <span className=\"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-amber-400\" />}\r\n </span>\r\n {expanded && (\r\n <span className=\"flex min-w-0 flex-1 items-center gap-1.5\">\r\n <span className=\"truncate text-sm font-semibold\">{item.label}</span>\r\n {item.external && <ExternalLinkIcon size={12} className=\"ml-auto flex-none text-white/30\" />}\r\n {badges.map((b, i) => (\r\n <span\r\n key={i}\r\n data-tip={b.label}\r\n aria-label={b.label ? `${b.label}: ${b.count}` : undefined}\r\n className={`${i === 0 ? 'ml-auto' : ''} min-w-[18px] flex-none rounded-full px-1.5 py-0.5 text-center text-[10px] leading-none font-black tabular-nums ${BADGE_TONES[b.tone ?? 'attention']}`}\r\n >\r\n {b.count}\r\n </span>\r\n ))}\r\n </span>\r\n )}\r\n </>\r\n )\r\n\r\n const tip = expanded ? undefined : item.label\r\n if (item.external) {\r\n return (\r\n <a\r\n key={item.to}\r\n href={item.to}\r\n target=\"_blank\"\r\n rel=\"noreferrer\"\r\n data-tip={tip}\r\n aria-label={expanded ? undefined : item.label}\r\n onClick={closeIfDrawer}\r\n className={rowClass(false)}\r\n >\r\n {content(false)}\r\n </a>\r\n )\r\n }\r\n return (\r\n <NavLink\r\n key={item.to}\r\n to={item.to}\r\n end={item.end}\r\n data-tip={tip}\r\n aria-label={expanded ? undefined : item.label}\r\n onClick={closeIfDrawer}\r\n className={({ isActive }) => rowClass(isActive)}\r\n >\r\n {({ isActive }) => content(isActive)}\r\n </NavLink>\r\n )\r\n }\r\n\r\n return (\r\n <aside\r\n // Abrir por hover só com rato: em ecrãs táteis o hover fica \"colado\".\r\n onPointerEnter={(e) => {\r\n if (e.pointerType === 'mouse' && !open) setHovered(true)\r\n }}\r\n onPointerLeave={() => setHovered(false)}\r\n // As barras do topo do AppShell (se houver) empurram o menu para baixo.\r\n style={{ top: 'var(--app-shell-top, 0px)', height: 'calc(100dvh - var(--app-shell-top, 0px))' }}\r\n className={\r\n 'fixed left-0 z-40 flex w-64 flex-col overflow-hidden border-r border-white/10 bg-proef-navy text-white transition-all duration-300 ' +\r\n `${open ? 'translate-x-0' : '-translate-x-full'} lg:translate-x-0 ${expanded ? 'lg:w-64' : 'lg:w-20'}`\r\n }\r\n >\r\n <div className={`flex h-16 flex-none items-center px-4 ${expanded ? 'justify-between' : 'justify-center'}`}>\r\n {expanded && (\r\n <div className=\"flex flex-col pl-2\">\r\n <div className=\"flex items-center gap-2\">\r\n <span className=\"text-3xl font-black tracking-tighter text-white\">proef</span>\r\n <span className=\"mt-3 h-2 w-2 rounded-full bg-proef-turquoise motion-safe:animate-pulse\" />\r\n </div>\r\n {appTitle && <span className=\"mt-1 pl-1 text-[10px] font-black tracking-[0.3em] text-white/50 uppercase\">{appTitle}</span>}\r\n </div>\r\n )}\r\n <div className=\"flex items-center gap-2\">\r\n {avatar && <div className=\"flex-none\">{avatar}</div>}\r\n {open && expanded && (\r\n <button\r\n type=\"button\"\r\n onClick={() => onOpenChange(false)}\r\n aria-label={isDrawer() ? labels.closeMenu : labels.collapseMenu}\r\n className=\"flex cursor-pointer items-center justify-center rounded-lg border-0 bg-white/5 p-2.5 text-white/40 transition-colors hover:bg-white/10 hover:text-white focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none lg:p-1.5\"\r\n >\r\n <CloseIcon size={18} className=\"lg:hidden\" />\r\n <ChevronLeftIcon size={16} className=\"hidden lg:block\" />\r\n </button>\r\n )}\r\n {/* Aberto só por o rato estar em cima (não fixo): sem este botão não havia como fixar o menu\r\n a partir do cabeçalho, e o de recolher só aparece com o menu fixo. Faz o mesmo que o botão\r\n de expandir do menu só com ícones: `onOpenChange(true)`. Só com rato, por isso só em desktop. */}\r\n {!open && expanded && (\r\n <button\r\n type=\"button\"\r\n onClick={() => onOpenChange(true)}\r\n aria-label={labels.expandMenu}\r\n className=\"hidden cursor-pointer items-center justify-center rounded-lg border-0 bg-white/5 p-1.5 text-white/40 transition-colors hover:bg-white/10 hover:text-white focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none lg:flex\"\r\n >\r\n <ChevronRightIcon size={16} />\r\n </button>\r\n )}\r\n </div>\r\n </div>\r\n\r\n <nav className=\"flex-1 overflow-x-hidden overflow-y-auto pt-2\">\r\n {/* Só ícones: botão para abrir (em ecrãs táteis não há hover). */}\r\n {!expanded && (\r\n <button\r\n type=\"button\"\r\n onClick={() => onOpenChange(true)}\r\n data-tip={labels.expandMenu}\r\n aria-label={labels.expandMenu}\r\n className=\"mb-1 flex w-full cursor-pointer items-center justify-center border-0 bg-transparent py-3 text-white/40 transition-colors hover:bg-white/5 hover:text-white focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none\"\r\n >\r\n <PanelOpenIcon size={20} />\r\n </button>\r\n )}\r\n {ungrouped.map(renderItem)}\r\n {groups.map((g) => {\r\n const isOpen = expanded ? !collapsed[g] : g === activeGroup\r\n const name = groupLabels[g] ?? g\r\n return (\r\n <div key={g}>\r\n {expanded ? (\r\n <button\r\n type=\"button\"\r\n onClick={() => setCollapsed((prev) => ({ ...prev, [g]: !prev[g] }))}\r\n aria-expanded={isOpen}\r\n aria-label={`${isOpen ? labels.closeGroup : labels.openGroup} ${name}`}\r\n className=\"group/grp w-full cursor-pointer border-0 bg-transparent px-6 pt-5 pb-3 text-left focus-visible:outline-none lg:pb-1.5\"\r\n >\r\n <span className=\"flex items-center justify-between\">\r\n <span className=\"text-[9px] font-black tracking-[0.25em] text-white/30 uppercase transition-colors group-hover/grp:text-white/50 group-focus-visible/grp:text-white\">\r\n {name}\r\n </span>\r\n <ChevronDownIcon size={10} className={`text-white/30 transition-transform group-hover/grp:text-white/50 ${isOpen ? '' : '-rotate-90'}`} />\r\n </span>\r\n <span className=\"mt-1 block h-px bg-white/10\" />\r\n </button>\r\n ) : (\r\n isOpen && <div className=\"mx-auto my-3 h-px w-8 bg-white/15\" />\r\n )}\r\n {isOpen && menu.filter((item) => item.group === g).map(renderItem)}\r\n </div>\r\n )\r\n })}\r\n </nav>\r\n\r\n <div className={`mt-auto flex flex-none flex-col border-t border-white/10 px-2 py-3 ${expanded ? 'gap-2' : 'items-center gap-3'}`}>\r\n {footer && <div className={expanded ? '' : 'flex w-full justify-center'}>{footer(expanded)}</div>}\r\n\r\n {onThemeChange &&\r\n (expanded ? (\r\n <div>\r\n <p className=\"m-0 px-1 pb-1 text-[8px] font-black tracking-[0.25em] text-white/30 uppercase\">{labels.theme}</p>\r\n <div role=\"group\" aria-label={labels.theme} className=\"grid grid-cols-3 gap-1 rounded-lg border border-white/5 bg-white/5 p-1\">\r\n {themeOptions.map(({ value, Icon, label }) => (\r\n <button\r\n key={value}\r\n type=\"button\"\r\n onClick={() => onThemeChange(value)}\r\n aria-pressed={currentTheme.value === value}\r\n className={`flex cursor-pointer flex-col items-center gap-1 rounded-md border-0 py-1.5 text-[8px] font-black tracking-wider uppercase transition-colors focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none ${\r\n currentTheme.value === value ? 'bg-proef-turquoise/15 text-proef-turquoise' : 'bg-transparent text-white/40 hover:bg-white/5 hover:text-white/70'\r\n }`}\r\n >\r\n <Icon size={14} />\r\n {label}\r\n </button>\r\n ))}\r\n </div>\r\n </div>\r\n ) : (\r\n <button\r\n type=\"button\"\r\n onClick={() => onThemeChange(cycle(themeOptions, currentTheme).value)}\r\n aria-label={`${labels.theme}: ${currentTheme.label}`}\r\n data-tip={`${labels.theme}: ${currentTheme.label}`}\r\n className={footerIconButton}\r\n >\r\n <currentTheme.Icon size={18} />\r\n </button>\r\n ))}\r\n\r\n {languages &&\r\n languages.length > 0 &&\r\n onLanguageChange &&\r\n (expanded ? (\r\n <div role=\"group\" aria-label={labels.language} className=\"flex gap-1\">\r\n {languages.map((l) => (\r\n <button\r\n key={l.code}\r\n type=\"button\"\r\n onClick={() => onLanguageChange(l.code)}\r\n aria-pressed={currentLanguage === l.code}\r\n className={`flex-1 cursor-pointer rounded-md border bg-transparent py-1.5 text-[10px] font-black tracking-widest uppercase transition-colors focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none ${\r\n currentLanguage === l.code ? 'border-proef-turquoise/40 text-proef-turquoise' : 'border-white/5 text-white/40 hover:border-white/20 hover:text-white'\r\n }`}\r\n >\r\n {l.label}\r\n </button>\r\n ))}\r\n </div>\r\n ) : (\r\n <button\r\n type=\"button\"\r\n onClick={() => {\r\n const codes = languages.map((l) => l.code)\r\n onLanguageChange(cycle(codes, currentLanguage ?? codes[0]))\r\n }}\r\n aria-label={`${labels.language}: ${currentLanguage?.toUpperCase() ?? ''}`}\r\n data-tip={`${labels.language}: ${currentLanguage?.toUpperCase() ?? ''}`}\r\n className={footerIconButton}\r\n >\r\n <GlobeIcon size={18} />\r\n </button>\r\n ))}\r\n\r\n {mostrarLogout &&\r\n (expanded ? (\r\n <button\r\n type=\"button\"\r\n onClick={onLogout}\r\n className=\"w-full cursor-pointer rounded-lg border border-white/5 bg-transparent py-2.5 text-center text-[10px] font-black tracking-widest text-white/40 uppercase transition-colors hover:border-proef-turquoise/30 hover:text-proef-turquoise focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none\"\r\n >\r\n {labels.logout}\r\n </button>\r\n ) : (\r\n <button type=\"button\" onClick={onLogout} aria-label={labels.logout} data-tip={labels.logout} className={footerIconButton}>\r\n <LogOutIcon size={18} />\r\n </button>\r\n ))}\r\n\r\n {/* Só com o menu aberto: só com ícones ficava ilegível, e é para consulta. */}\r\n {deployedAt != null && expanded && (\r\n <p data-tip={labels.deployedAt} className=\"m-0 text-center text-[9px] tracking-wider text-white/25 tabular-nums select-text\">\r\n {formatDeploy(deployedAt)}\r\n </p>\r\n )}\r\n </div>\r\n </aside>\r\n )\r\n}\r\n"],"names":[],"mappings":";;;;;AAyEO,MAAM,iBAAgC;AAAA,EAC3C,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AACd;AA2CO,MAAM,aAAa;AAEnB,MAAM,WAAW,MAAM,OAAO,WAAW,eAAe,OAAO,aAAa;AAGnF,SAAS,aAAa,OAAuC;AAC3D,QAAM,IAAI,iBAAiB,OAAO,QAAQ,IAAI,KAAK,KAAK;AACxD,MAAI,OAAO,MAAM,EAAE,QAAA,CAAS,EAAG,QAAO;AACtC,QAAM,MAAM,CAAC,MAAc,OAAO,CAAC,EAAE,SAAS,GAAG,GAAG;AACp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AAA,EAAA;AAGN;"}
|
|
1
|
+
{"version":3,"file":"SideNav.js","sources":["../../../../../../src/v1/components/layout/SideNav/SideNav.tsx"],"sourcesContent":["import React, { useEffect, useState } from 'react'\r\nimport { NavLink, useLocation } from 'react-router-dom'\r\nimport { dentroDaApp } from '../../../capabilities/onepoint-rn/dentroDaApp'\r\nimport {\r\n ChevronDownIcon,\r\n ChevronLeftIcon,\r\n ChevronRightIcon,\r\n CloseIcon,\r\n ExternalLinkIcon,\r\n GlobeIcon,\r\n LogOutIcon,\r\n MonitorIcon,\r\n MoonIcon,\r\n PanelOpenIcon,\r\n SunIcon,\r\n type IconProps,\r\n} from '../../../foundations/icons/icons'\r\n\r\nexport type SideNavTheme = 'light' | 'dark' | 'system'\r\n\r\nexport interface SideNavBadge {\r\n count: number\r\n /** `attention` (amarelo, por omissão): coisas à espera da pessoa. `alert` (laranja): à espera de outro circuito (ex: CAB). */\r\n tone?: 'attention' | 'alert'\r\n /** O que o número conta, para o tooltip e leitores de ecrã (ex: \"Aprovações pendentes\"). */\r\n label?: string\r\n}\r\n\r\nexport interface SideNavItem {\r\n /** Rota da app, ou URL completo com `external`. */\r\n to: string\r\n label: string\r\n /** Componente de ícone que aceita `size` e `className` (ex: um ícone do lucide-react). */\r\n icon: React.ComponentType<{ size?: number; className?: string }>\r\n /** Chave do grupo. Os itens do mesmo grupo aparecem juntos, por baixo do título do grupo. */\r\n group?: string\r\n /** Só fica ativo na rota exata (como o `end` do NavLink). */\r\n end?: boolean\r\n /** Abre num separador novo, fora da app. */\r\n external?: boolean\r\n /** Contadores ao lado do texto. Os que têm `count` 0 não aparecem. */\r\n badges?: SideNavBadge[]\r\n /**\r\n * Se esta entrada aparece dentro do WebView da app OnePoint.\r\n *\r\n * A maioria dos menus foi desenhada para secretária: catálogos, logs,\r\n * gestão de utilizadores, listas de referência. Num telemóvel só ocupam\r\n * espaço a quem nunca lhes toca.\r\n *\r\n * Sem valor, segue o `naAppPorOmissao` do `SideNav` (que por omissão\r\n * mostra tudo, para nada mudar em quem já usa isto). Um portal com muitas\r\n * entradas de secretária põe esse valor a `false` e marca aqui `true` as\r\n * poucas que servem de pé — é menos trabalho do que o contrário.\r\n */\r\n naApp?: boolean\r\n}\r\n\r\nexport interface SideNavLabels {\r\n closeMenu: string\r\n expandMenu: string\r\n collapseMenu: string\r\n /** Antes do nome do grupo, no botão que o abre/fecha (ex: \"Abrir Recursos\"). */\r\n openGroup: string\r\n closeGroup: string\r\n theme: string\r\n light: string\r\n dark: string\r\n system: string\r\n language: string\r\n logout: string\r\n deployedAt: string\r\n}\r\n\r\nexport const SIDENAV_LABELS: SideNavLabels = {\r\n closeMenu: 'Fechar menu',\r\n expandMenu: 'Expandir menu',\r\n collapseMenu: 'Recolher menu',\r\n openGroup: 'Abrir',\r\n closeGroup: 'Fechar',\r\n theme: 'Tema',\r\n light: 'Claro',\r\n dark: 'Escuro',\r\n system: 'Sistema',\r\n language: 'Idioma',\r\n logout: 'Terminar sessão',\r\n deployedAt: 'Último deploy',\r\n}\r\n\r\nexport interface SideNavProps {\r\n menu: SideNavItem[]\r\n /** Título de cada grupo do menu, pela chave (`group`). Sem título, aparece a chave. */\r\n groupLabels?: Record<string, string>\r\n /** Por baixo do logótipo (ex: \"IT Portal\"). */\r\n appTitle?: string\r\n /** Foto ou iniciais da pessoa, no topo do menu. */\r\n avatar?: React.ReactNode\r\n /** Sem isto, não há botão de terminar sessão. */\r\n onLogout?: () => void\r\n /** Escolha de idioma no rodapé. Só aparece com `languages` e `onLanguageChange`. */\r\n languages?: { code: string; label: string }[]\r\n currentLanguage?: string\r\n onLanguageChange?: (code: string) => void\r\n /**\r\n * Escolha de tema no rodapé. Só aparece com `onThemeChange`. O menu só\r\n * mostra a escolha: pôr a classe `.dark` no `<html>` é da app.\r\n */\r\n theme?: SideNavTheme\r\n onThemeChange?: (theme: SideNavTheme) => void\r\n /** Quando foi feito o build, no fundo do menu. A app decide a quem o mostra (ex: só administradores). */\r\n deployedAt?: string | number | Date\r\n /** Conteúdo extra no rodapé, por cima do tema (ex: um filtro global). Recebe se o menu está expandido. */\r\n footer?: (expanded: boolean) => React.ReactNode\r\n labels?: Partial<SideNavLabels>\r\n /**\r\n * O que fazer, dentro da app OnePoint, às entradas sem `naApp` definido.\r\n *\r\n * Por omissão `true`: o menu aparece inteiro, como sempre apareceu. Um\r\n * portal com dezenas de entradas de secretária põe isto a `false` e marca\r\n * `naApp: true` só nas que servem em telemóvel.\r\n *\r\n * Não tem efeito no browser.\r\n */\r\n naAppPorOmissao?: boolean\r\n /** Aberto (256px) ou fechado (só ícones; em ecrãs pequenos, escondido). A app guarda este estado. */\r\n open: boolean\r\n onOpenChange: (open: boolean) => void\r\n}\r\n\r\n/** Abaixo desta largura o menu é uma gaveta por cima da página; acima ocupa espaço (aberto ou só ícones). */\r\nexport const DRAWER_MAX = 1024\r\n\r\nexport const isDrawer = () => typeof window !== 'undefined' && window.innerWidth < DRAWER_MAX\r\n\r\n/** `DD/MM/AAAA, HH:MM` na hora local: um carimbo que não muda com o idioma escolhido. */\r\nfunction formatDeploy(value: string | number | Date): string {\r\n const d = value instanceof Date ? value : new Date(value)\r\n if (Number.isNaN(d.getTime())) return ''\r\n const two = (n: number) => String(n).padStart(2, '0')\r\n return `${two(d.getDate())}/${two(d.getMonth() + 1)}/${d.getFullYear()}, ${two(d.getHours())}:${two(d.getMinutes())}`\r\n}\r\n\r\nconst BADGE_TONES = {\r\n attention: 'bg-amber-400 text-proef-navy',\r\n alert: 'bg-orange-500 text-white',\r\n}\r\n\r\n/**\r\n * Menu lateral navy da app, fixo à esquerda. Normalmente usa-se através do\r\n * `AppShell`, que também trata da página ao lado.\r\n *\r\n * - **Ecrãs grandes** (≥ 1024px): aberto ocupa 256px; fechado fica só com os\r\n * ícones (80px) e abre por cima da página ao passar o rato.\r\n * - **Ecrãs pequenos**: escondido quando fechado; aberto fica por cima da\r\n * página e fecha ao escolher uma página.\r\n * - **Grupos**: abertos por omissão, fecham com um clique no título. Só com os\r\n * ícones, fica aberto apenas o grupo da página atual.\r\n *\r\n * Precisa de estar dentro de um Router do react-router.\r\n */\r\nexport default function SideNav({\r\n menu: menuProp,\r\n groupLabels = {},\r\n appTitle,\r\n avatar,\r\n onLogout,\r\n languages,\r\n currentLanguage,\r\n onLanguageChange,\r\n theme,\r\n onThemeChange,\r\n deployedAt,\r\n footer,\r\n labels: labelsProp,\r\n naAppPorOmissao = true,\r\n open,\r\n onOpenChange,\r\n}: SideNavProps) {\r\n /*\r\n Dentro da app OnePoint o menu é filtrado e o \"Terminar sessão\" não\r\n aparece.\r\n\r\n O menu: a maioria das entradas foi desenhada para secretária. Cada\r\n entrada decide por si com `naApp`; as que não decidem seguem o\r\n `naAppPorOmissao`.\r\n\r\n O logout: a sessão é da aplicação, não do portal. O que o botão faria\r\n aqui — um `logoutRedirect` do MSAL — é um redirect de topo, que a tranca\r\n de origem do ecrã nativo recusa: não fazia nada, ou saía para o browser e\r\n perdia a sessão. Quem termina sessão é a app.\r\n */\r\n const naApp = dentroDaApp()\r\n const menu = React.useMemo(\r\n () => (naApp ? menuProp.filter((i) => i.naApp ?? naAppPorOmissao) : menuProp),\r\n [menuProp, naApp, naAppPorOmissao],\r\n )\r\n const mostrarLogout = onLogout && !naApp\r\n const labels = { ...SIDENAV_LABELS, ...labelsProp }\r\n const location = useLocation()\r\n const [hovered, setHovered] = useState(false)\r\n const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})\r\n const expanded = open || hovered\r\n\r\n // O hover fica \"colado\" quando a janela perde o foco.\r\n useEffect(() => {\r\n const reset = () => setHovered(false)\r\n window.addEventListener('blur', reset)\r\n document.addEventListener('visibilitychange', reset)\r\n return () => {\r\n window.removeEventListener('blur', reset)\r\n document.removeEventListener('visibilitychange', reset)\r\n }\r\n }, [])\r\n\r\n const ungrouped = menu.filter((item) => !item.group)\r\n const groups = Array.from(new Set(menu.map((item) => item.group).filter(Boolean))) as string[]\r\n // Só com os ícones não há títulos para clicar: fica aberto só o grupo da página atual.\r\n const activeGroup = menu.find((item) => item.group && !item.external && location.pathname.startsWith(item.to))?.group\r\n\r\n const closeIfDrawer = () => {\r\n if (isDrawer()) onOpenChange(false)\r\n }\r\n\r\n const themeOptions: { value: SideNavTheme; Icon: React.ComponentType<IconProps>; label: string }[] = [\r\n { value: 'light', Icon: SunIcon, label: labels.light },\r\n { value: 'dark', Icon: MoonIcon, label: labels.dark },\r\n { value: 'system', Icon: MonitorIcon, label: labels.system },\r\n ]\r\n const currentTheme = themeOptions.find((o) => o.value === (theme ?? 'system')) ?? themeOptions[2]\r\n const cycle = <T,>(list: T[], current: T) => list[(list.indexOf(current) + 1) % list.length]\r\n\r\n const footerIconButton =\r\n 'flex cursor-pointer items-center justify-center rounded-lg border-0 bg-transparent p-2 text-white/30 transition-colors hover:bg-white/5 hover:text-proef-turquoise focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none'\r\n\r\n const renderItem = (item: SideNavItem) => {\r\n const badges = (item.badges ?? []).filter((b) => b.count > 0)\r\n const rowClass = (active: boolean) =>\r\n `mx-2 flex items-center gap-4 rounded-lg no-underline transition-colors duration-200 focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none ${\r\n expanded ? 'px-6 py-3 lg:py-2.5' : 'justify-center px-0 py-3 lg:py-2.5'\r\n } ${active ? 'bg-proef-turquoise/15 font-semibold text-proef-turquoise' : 'text-white/50 hover:bg-white/5 hover:text-white'}`\r\n\r\n const content = (active: boolean) => (\r\n <>\r\n <span className=\"relative flex-none\">\r\n <item.icon size={20} className={active ? 'drop-shadow-[0_0_6px_rgba(0,230,200,0.6)]' : ''} />\r\n {badges.length > 0 && !expanded && <span className=\"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-amber-400\" />}\r\n </span>\r\n {expanded && (\r\n <span className=\"flex min-w-0 flex-1 items-center gap-1.5\">\r\n <span className=\"truncate text-sm font-semibold\">{item.label}</span>\r\n {item.external && <ExternalLinkIcon size={12} className=\"ml-auto flex-none text-white/30\" />}\r\n {badges.map((b, i) => (\r\n <span\r\n key={i}\r\n data-tip={b.label}\r\n aria-label={b.label ? `${b.label}: ${b.count}` : undefined}\r\n className={`${i === 0 ? 'ml-auto' : ''} min-w-[18px] flex-none rounded-full px-1.5 py-0.5 text-center text-[10px] leading-none font-black tabular-nums ${BADGE_TONES[b.tone ?? 'attention']}`}\r\n >\r\n {b.count}\r\n </span>\r\n ))}\r\n </span>\r\n )}\r\n </>\r\n )\r\n\r\n const tip = expanded ? undefined : item.label\r\n if (item.external) {\r\n return (\r\n <a\r\n key={item.to}\r\n href={item.to}\r\n target=\"_blank\"\r\n rel=\"noreferrer\"\r\n data-tip={tip}\r\n aria-label={expanded ? undefined : item.label}\r\n onClick={closeIfDrawer}\r\n className={rowClass(false)}\r\n >\r\n {content(false)}\r\n </a>\r\n )\r\n }\r\n return (\r\n <NavLink\r\n key={item.to}\r\n to={item.to}\r\n end={item.end}\r\n data-tip={tip}\r\n aria-label={expanded ? undefined : item.label}\r\n onClick={closeIfDrawer}\r\n className={({ isActive }) => rowClass(isActive)}\r\n >\r\n {({ isActive }) => content(isActive)}\r\n </NavLink>\r\n )\r\n }\r\n\r\n return (\r\n <aside\r\n // Abrir por hover só com rato: em ecrãs táteis o hover fica \"colado\".\r\n onPointerEnter={(e) => {\r\n if (e.pointerType === 'mouse' && !open) setHovered(true)\r\n }}\r\n onPointerLeave={() => setHovered(false)}\r\n // As barras do topo do AppShell (se houver) empurram o menu para baixo.\r\n style={{ top: 'var(--app-shell-top, 0px)', height: 'calc(100dvh - var(--app-shell-top, 0px))' }}\r\n className={\r\n 'fixed left-0 z-40 flex w-64 flex-col overflow-hidden border-r border-white/10 bg-proef-navy text-white transition-all duration-300 ' +\r\n `${open ? 'translate-x-0' : '-translate-x-full'} lg:translate-x-0 ${expanded ? 'lg:w-64' : 'lg:w-20'}`\r\n }\r\n >\r\n <div className={`flex h-16 flex-none items-center px-4 ${expanded ? 'justify-between' : 'justify-center'}`}>\r\n {expanded && (\r\n <div className=\"flex flex-col pl-2\">\r\n <div className=\"flex items-center gap-2\">\r\n <span className=\"text-3xl font-black tracking-tighter text-white\">proef</span>\r\n <span className=\"mt-3 h-2 w-2 rounded-full bg-proef-turquoise motion-safe:animate-pulse\" />\r\n </div>\r\n {appTitle && <span className=\"mt-1 pl-1 text-[10px] font-black tracking-[0.3em] text-white/50 uppercase\">{appTitle}</span>}\r\n </div>\r\n )}\r\n <div className=\"flex items-center gap-2\">\r\n {avatar && <div className=\"flex-none\">{avatar}</div>}\r\n {open && expanded && (\r\n <button\r\n type=\"button\"\r\n onClick={() => onOpenChange(false)}\r\n aria-label={isDrawer() ? labels.closeMenu : labels.collapseMenu}\r\n className=\"flex cursor-pointer items-center justify-center rounded-lg border-0 bg-white/5 p-2.5 text-white/40 transition-colors hover:bg-white/10 hover:text-white focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none lg:p-1.5\"\r\n >\r\n <CloseIcon size={18} className=\"lg:hidden\" />\r\n <ChevronLeftIcon size={16} className=\"hidden lg:block\" />\r\n </button>\r\n )}\r\n {/* Aberto só por o rato estar em cima (não fixo): sem este botão não havia como fixar o menu\r\n a partir do cabeçalho, e o de recolher só aparece com o menu fixo. Faz o mesmo que o botão\r\n de expandir do menu só com ícones: `onOpenChange(true)`. Só com rato, por isso só em desktop. */}\r\n {!open && expanded && (\r\n <button\r\n type=\"button\"\r\n onClick={() => onOpenChange(true)}\r\n aria-label={labels.expandMenu}\r\n className=\"hidden cursor-pointer items-center justify-center rounded-lg border-0 bg-white/5 p-1.5 text-white/40 transition-colors hover:bg-white/10 hover:text-white focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none lg:flex\"\r\n >\r\n <ChevronRightIcon size={16} />\r\n </button>\r\n )}\r\n </div>\r\n </div>\r\n\r\n <nav className=\"flex-1 overflow-x-hidden overflow-y-auto pt-2\">\r\n {/* Só ícones: botão para abrir (em ecrãs táteis não há hover). */}\r\n {!expanded && (\r\n <button\r\n type=\"button\"\r\n onClick={() => onOpenChange(true)}\r\n data-tip={labels.expandMenu}\r\n aria-label={labels.expandMenu}\r\n className=\"mb-1 flex w-full cursor-pointer items-center justify-center border-0 bg-transparent py-3 text-white/40 transition-colors hover:bg-white/5 hover:text-white focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none\"\r\n >\r\n <PanelOpenIcon size={20} />\r\n </button>\r\n )}\r\n {ungrouped.map(renderItem)}\r\n {groups.map((g) => {\r\n const isOpen = expanded ? !collapsed[g] : g === activeGroup\r\n const name = groupLabels[g] ?? g\r\n return (\r\n <div key={g}>\r\n {expanded ? (\r\n <button\r\n type=\"button\"\r\n onClick={() => setCollapsed((prev) => ({ ...prev, [g]: !prev[g] }))}\r\n aria-expanded={isOpen}\r\n aria-label={`${isOpen ? labels.closeGroup : labels.openGroup} ${name}`}\r\n className=\"group/grp w-full cursor-pointer border-0 bg-transparent px-6 pt-5 pb-3 text-left focus-visible:outline-none lg:pb-1.5\"\r\n >\r\n <span className=\"flex items-center justify-between\">\r\n <span className=\"text-[9px] font-black tracking-[0.25em] text-white/30 uppercase transition-colors group-hover/grp:text-white/50 group-focus-visible/grp:text-white\">\r\n {name}\r\n </span>\r\n <ChevronDownIcon size={10} className={`text-white/30 transition-transform group-hover/grp:text-white/50 ${isOpen ? '' : '-rotate-90'}`} />\r\n </span>\r\n <span className=\"mt-1 block h-px bg-white/10\" />\r\n </button>\r\n ) : (\r\n isOpen && <div className=\"mx-auto my-3 h-px w-8 bg-white/15\" />\r\n )}\r\n {isOpen && menu.filter((item) => item.group === g).map(renderItem)}\r\n </div>\r\n )\r\n })}\r\n </nav>\r\n\r\n <div className={`mt-auto flex flex-none flex-col border-t border-white/10 px-2 py-3 ${expanded ? 'gap-2' : 'items-center gap-3'}`}>\r\n {footer && <div className={expanded ? '' : 'flex w-full justify-center'}>{footer(expanded)}</div>}\r\n\r\n {onThemeChange &&\r\n (expanded ? (\r\n <div>\r\n <p className=\"m-0 px-1 pb-1 text-[8px] font-black tracking-[0.25em] text-white/30 uppercase\">{labels.theme}</p>\r\n <div role=\"group\" aria-label={labels.theme} className=\"grid grid-cols-3 gap-1 rounded-lg border border-white/5 bg-white/5 p-1\">\r\n {themeOptions.map(({ value, Icon, label }) => (\r\n <button\r\n key={value}\r\n type=\"button\"\r\n onClick={() => onThemeChange(value)}\r\n aria-pressed={currentTheme.value === value}\r\n className={`flex cursor-pointer flex-col items-center gap-1 rounded-md border-0 py-1.5 text-[8px] font-black tracking-wider uppercase transition-colors focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none ${\r\n currentTheme.value === value ? 'bg-proef-turquoise/15 text-proef-turquoise' : 'bg-transparent text-white/40 hover:bg-white/5 hover:text-white/70'\r\n }`}\r\n >\r\n <Icon size={14} />\r\n {label}\r\n </button>\r\n ))}\r\n </div>\r\n </div>\r\n ) : (\r\n <button\r\n type=\"button\"\r\n onClick={() => onThemeChange(cycle(themeOptions, currentTheme).value)}\r\n aria-label={`${labels.theme}: ${currentTheme.label}`}\r\n data-tip={`${labels.theme}: ${currentTheme.label}`}\r\n className={footerIconButton}\r\n >\r\n <currentTheme.Icon size={18} />\r\n </button>\r\n ))}\r\n\r\n {languages &&\r\n languages.length > 0 &&\r\n onLanguageChange &&\r\n (expanded ? (\r\n <div role=\"group\" aria-label={labels.language} className=\"flex gap-1\">\r\n {languages.map((l) => (\r\n <button\r\n key={l.code}\r\n type=\"button\"\r\n onClick={() => onLanguageChange(l.code)}\r\n aria-pressed={currentLanguage === l.code}\r\n className={`flex-1 cursor-pointer rounded-md border bg-transparent py-1.5 text-[10px] font-black tracking-widest uppercase transition-colors focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none ${\r\n currentLanguage === l.code ? 'border-proef-turquoise/40 text-proef-turquoise' : 'border-white/5 text-white/40 hover:border-white/20 hover:text-white'\r\n }`}\r\n >\r\n {l.label}\r\n </button>\r\n ))}\r\n </div>\r\n ) : (\r\n <button\r\n type=\"button\"\r\n onClick={() => {\r\n const codes = languages.map((l) => l.code)\r\n onLanguageChange(cycle(codes, currentLanguage ?? codes[0]))\r\n }}\r\n aria-label={`${labels.language}: ${currentLanguage?.toUpperCase() ?? ''}`}\r\n data-tip={`${labels.language}: ${currentLanguage?.toUpperCase() ?? ''}`}\r\n className={footerIconButton}\r\n >\r\n <GlobeIcon size={18} />\r\n </button>\r\n ))}\r\n\r\n {mostrarLogout &&\r\n (expanded ? (\r\n <button\r\n type=\"button\"\r\n onClick={onLogout}\r\n className=\"w-full cursor-pointer rounded-lg border border-white/5 bg-transparent py-2.5 text-center text-[10px] font-black tracking-widest text-white/40 uppercase transition-colors hover:border-proef-turquoise/30 hover:text-proef-turquoise focus-visible:ring-2 focus-visible:ring-proef-turquoise/50 focus-visible:outline-none\"\r\n >\r\n {labels.logout}\r\n </button>\r\n ) : (\r\n <button type=\"button\" onClick={onLogout} aria-label={labels.logout} data-tip={labels.logout} className={footerIconButton}>\r\n <LogOutIcon size={18} />\r\n </button>\r\n ))}\r\n\r\n {/* Só com o menu aberto: só com ícones ficava ilegível, e é para consulta. */}\r\n {deployedAt != null && expanded && (\r\n <p data-tip={labels.deployedAt} className=\"m-0 text-center text-[9px] tracking-wider text-white/25 tabular-nums select-text\">\r\n {formatDeploy(deployedAt)}\r\n </p>\r\n )}\r\n </div>\r\n </aside>\r\n )\r\n}\r\n"],"names":[],"mappings":";;;;;AAyEO,MAAM,iBAAgC;AAAA,EAC3C,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AACd;AA2CO,MAAM,aAAa;AAEnB,MAAM,WAAW,MAAM,OAAO,WAAW,eAAe,OAAO,aAAa;AAGnF,SAAS,aAAa,OAAuC;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,IAAI,EAAA,CACxB;AAAA,UAIH,cAAc,QAAQ,YACrB,oBAAC,KAAA,EAAE,YAAU,OAAO,YAAY,WAAU,oFACvC,UAAA,aAAa,UAAU,EAAA,CAC1B;AAAA,QAAA,EAAA,CAEJ;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAGN;"}
|
|
@@ -48,6 +48,7 @@ function Dialog({
|
|
|
48
48
|
footer,
|
|
49
49
|
size = "md",
|
|
50
50
|
height = "auto",
|
|
51
|
+
placement = "center",
|
|
51
52
|
closeOnBackdrop = true,
|
|
52
53
|
closeLabel = "Fechar",
|
|
53
54
|
flush = false,
|
|
@@ -91,6 +92,12 @@ function Dialog({
|
|
|
91
92
|
return libertarScroll;
|
|
92
93
|
}, [open]);
|
|
93
94
|
const noFundo = (e) => e.target === fundo.current || e.target === e.currentTarget;
|
|
95
|
+
const lateral = placement === "right";
|
|
96
|
+
const classesRaiz = lateral ? "fixed inset-0 z-[200] items-stretch justify-end" : `fixed inset-0 z-[200] items-center justify-center p-dialog-margin ${height === "full" ? "max-sm:p-0" : ""}`;
|
|
97
|
+
const classesJanela = lateral ? `relative flex h-full w-full ${WIDTHS[size]} max-sm:max-w-none flex-col overflow-hidden bg-card text-foreground shadow-modal outline-none dark:border-l dark:border-slate-700 motion-safe:animate-panel-in` : (
|
|
98
|
+
// No escuro a sombra não se vê: a linha (a mesma dos menus) separa a janela do fundo.
|
|
99
|
+
`relative flex max-h-full w-full ${WIDTHS[size]} flex-col overflow-hidden rounded-2xl bg-card text-foreground shadow-modal outline-none dark:border dark:border-slate-700 motion-safe:animate-dialog-in ${height === "full" ? "h-full max-sm:rounded-none max-sm:border-0" : ""}`
|
|
100
|
+
);
|
|
94
101
|
return createPortal(
|
|
95
102
|
/* @__PURE__ */ jsxs(
|
|
96
103
|
"div",
|
|
@@ -103,7 +110,8 @@ function Dialog({
|
|
|
103
110
|
onClick: (e) => {
|
|
104
111
|
if (closeOnBackdrop && pressedBackdrop.current && noFundo(e)) onClose();
|
|
105
112
|
},
|
|
106
|
-
className:
|
|
113
|
+
className: `${classesRaiz} ${open ? "flex" : "hidden"}`,
|
|
114
|
+
"data-placement": placement,
|
|
107
115
|
children: [
|
|
108
116
|
/* @__PURE__ */ jsx("div", { ref: fundo, className: "absolute inset-0 bg-black/40 motion-safe:animate-backdrop-in" }),
|
|
109
117
|
/* @__PURE__ */ jsxs(
|
|
@@ -114,10 +122,7 @@ function Dialog({
|
|
|
114
122
|
"aria-modal": "true",
|
|
115
123
|
"aria-labelledby": titleId,
|
|
116
124
|
tabIndex: -1,
|
|
117
|
-
className:
|
|
118
|
-
// No escuro a sombra não se vê: a linha (a mesma dos menus) separa a janela do fundo.
|
|
119
|
-
`relative flex max-h-full w-full ${WIDTHS[size]} flex-col overflow-hidden rounded-2xl bg-card text-foreground shadow-modal outline-none dark:border dark:border-slate-700 motion-safe:animate-dialog-in ${height === "full" ? "h-full max-sm:rounded-none max-sm:border-0" : ""}`
|
|
120
|
-
),
|
|
125
|
+
className: classesJanela,
|
|
121
126
|
children: [
|
|
122
127
|
/* @__PURE__ */ jsxs("header", { className: "flex flex-none items-center justify-between gap-3 bg-gradient-to-br from-primary to-primary-strong px-5 py-3.5", children: [
|
|
123
128
|
/* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Dialog.js","sources":["../../../../../../src/v1/components/overlays/Dialog/Dialog.tsx"],"sourcesContent":["import React, { createContext, useContext, useEffect, useId, useRef, useState } from 'react'\r\nimport { createPortal } from 'react-dom'\r\n\r\nconst DialogContainerContext = createContext<HTMLElement | null>(null)\r\nconst DialogDepthContext = createContext(0)\r\n\r\n/**\r\n * O elemento da janela, para usar como destino de `createPortal` (ex: avisos,\r\n * confirmações, sobreposições) quando o conteúdo deve ficar junto dela. Um\r\n * portal para `document.body` também funciona, desde que fique por cima\r\n * (`z-index` acima de 200). Fora de um Dialog devolve `null`.\r\n *\r\n * `createPortal(conteudo, useDialogContainer() ?? document.body)`\r\n */\r\nexport const useDialogContainer = () => useContext(DialogContainerContext)\r\n\r\nexport interface DialogProps {\r\n /** Aberta ou fechada. A app guarda este estado. */\r\n open: boolean\r\n /** Pedido para fechar (×, Esc ou clique fora): a app põe `open` a `false`. */\r\n onClose: () => void\r\n /** Normalmente texto; aceita JSX (ex: um nome em negrito). */\r\n title: React.ReactNode\r\n /** Linha por baixo do título (ex: nome · departamento). */\r\n subtitle?: React.ReactNode\r\n /** Botões no rodapé, sempre visíveis (ex: Confirmar, Fechar). */\r\n footer?: React.ReactNode\r\n /**\r\n * Largura máxima: `sm` 480px, `md` 720px, `lg` 1000px, `xl` até 1600px (95% do ecrã, para janelas com\r\n * mapa e tabela lado a lado). Nunca passa o ecrã.\r\n */\r\n size?: 'sm' | 'md' | 'lg' | 'xl'\r\n /**\r\n * Altura: `auto` (por omissão) cresce com o conteúdo; `full` ocupa sempre a\r\n * altura disponível (útil quando o conteúdo muda de tamanho e a janela não\r\n * deve saltar). Em ambos, se o conteúdo não couber, o corpo faz scroll.\r\n */\r\n height?: 'auto' | 'full'\r\n /** Fechar ao clicar fora da janela. Por omissão sim; num formulário longo pode valer a pena desligar. */\r\n closeOnBackdrop?: boolean\r\n /** Nome do botão ×, para leitores de ecrã. Por omissão: \"Fechar\". */\r\n closeLabel?: string\r\n /**\r\n * Corpo sem margens e sem scroll: o conteúdo ocupa-o todo e gere o seu próprio\r\n * scroll (ex: passos que deslizam, rodapé próprio de cada passo).\r\n */\r\n flush?: boolean\r\n children: React.ReactNode\r\n}\r\n\r\n// O `xl` é 95% do ecrã: no telemóvel deixava uma faixa do fundo escurecido de cada lado,\r\n// mesmo em `height=\"full\"` (que aí ocupa o ecrã todo). Abaixo de `sm` a margem da janela\r\n// já limita a largura, como nos outros tamanhos.\r\nconst WIDTHS = { sm: 'max-w-dialog-sm', md: 'max-w-dialog-md', lg: 'max-w-dialog-lg', xl: 'max-w-dialog-xl max-sm:max-w-none' }\r\n\r\ninterface Aberta {\r\n root: HTMLElement\r\n janela: HTMLElement | null\r\n depth: number\r\n}\r\n\r\nconst abertas: Aberta[] = []\r\nconst silenciados = new Set<Element>()\r\n\r\nconst doTopo = () => abertas[abertas.length - 1]\r\n\r\n// Scroll da página bloqueado enquanto houver pelo menos uma janela aberta. Um contador\r\n// partilhado, e não o \"antes\" de cada janela: com duas abertas que fecham fora de ordem\r\n// (ex: a de baixo desmonta primeiro), a última a fechar repunha o `hidden` e a página\r\n// ficava sem scroll até recarregar.\r\nlet bloqueios = 0\r\nlet overflowAntes = ''\r\n\r\nfunction bloquearScroll() {\r\n const html = document.documentElement\r\n if (bloqueios++ === 0) {\r\n overflowAntes = html.style.overflow\r\n html.style.overflow = 'hidden'\r\n }\r\n}\r\n\r\nfunction libertarScroll() {\r\n if (bloqueios === 0) return\r\n if (--bloqueios === 0) document.documentElement.style.overflow = overflowAntes\r\n}\r\n\r\nfunction silenciar() {\r\n for (const el of silenciados) el.removeAttribute('inert')\r\n silenciados.clear()\r\n // A ordem no ecrã segue a pilha, não a posição no `body`: a confirmação do\r\n // ConfirmProvider entra no `body` quando a app arranca, antes de qualquer\r\n // janela, e com o mesmo z-index ficava escondida por baixo da que a pediu.\r\n abertas.forEach((a, i) => {\r\n a.root.style.zIndex = String(200 + i)\r\n })\r\n const topo = doTopo()\r\n if (!topo) return\r\n for (const el of Array.from(document.body.children)) {\r\n if (el === topo.root || el.hasAttribute('inert')) continue\r\n el.setAttribute('inert', '')\r\n silenciados.add(el)\r\n }\r\n}\r\n\r\n// Uma janela aberta dentro de outra fica sempre por cima dela, mesmo que abram juntas.\r\nfunction empilhar(aberta: Aberta) {\r\n const acima = abertas.findIndex((a) => a.depth > aberta.depth)\r\n if (acima === -1) abertas.push(aberta)\r\n else abertas.splice(acima, 0, aberta)\r\n}\r\n\r\n/**\r\n * Janela por cima da página: cabeçalho navy com título, corpo que faz scroll e\r\n * rodapé com os botões ([Button](?path=/docs/v1-primitives-buttons-button--docs)).\r\n *\r\n * É a janela modal da V1 (substitui o `Modal` legacy).\r\n *\r\n * Fundo escurecido, Esc para fechar e, ao fechar, o foco volta ao sítio onde\r\n * estava. Enquanto está aberta, o resto da página fica\r\n * [inert](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/inert):\r\n * nem rato, nem teclado, nem leitores de ecrã lhe chegam. Os portais abertos\r\n * depois dela (seletores, confirmações) continuam a responder.\r\n *\r\n * O conteúdo fica montado mesmo com a janela fechada, para poder carregar antes\r\n * de ela abrir.\r\n *\r\n * O tamanho adapta-se ao ecrã só com CSS: nunca passa a largura nem a altura\r\n * da janela do browser (com uma margem), e acompanha-a quando é\r\n * redimensionada. O que não couber faz scroll no corpo; o cabeçalho e o\r\n * rodapé ficam sempre visíveis.\r\n *\r\n * **Exemplo completo:** [Formulário em modal](?path=/docs/v1-patterns-forms-formulário-em-modal--docs).\r\n */\r\nexport default function Dialog({\r\n open,\r\n onClose,\r\n title,\r\n subtitle,\r\n footer,\r\n size = 'md',\r\n height = 'auto',\r\n closeOnBackdrop = true,\r\n closeLabel = 'Fechar',\r\n flush = false,\r\n children,\r\n}: DialogProps) {\r\n const [root, setRoot] = useState<HTMLDivElement | null>(null)\r\n const janela = useRef<HTMLDivElement>(null)\r\n const fundo = useRef<HTMLDivElement>(null)\r\n const titleId = useId()\r\n const depth = useContext(DialogDepthContext)\r\n const fechar = useRef(onClose)\r\n fechar.current = onClose\r\n // Clique fora: só conta se começou e acabou no fundo (arrastar a partir de um\r\n // campo para fora não fecha a janela).\r\n const pressedBackdrop = useRef(false)\r\n\r\n useEffect(() => {\r\n if (!open || !root) return\r\n const anterior = document.activeElement as HTMLElement | null\r\n const aberta = { root, janela: janela.current, depth }\r\n empilhar(aberta)\r\n silenciar()\r\n const topo = doTopo()\r\n const dentro = topo.janela?.contains(document.activeElement)\r\n if (!dentro) topo.janela?.focus()\r\n\r\n const onKeyDown = (e: KeyboardEvent) => {\r\n if (e.key !== 'Escape' || e.defaultPrevented) return\r\n if (doTopo() !== aberta) return\r\n fechar.current()\r\n }\r\n document.addEventListener('keydown', onKeyDown)\r\n\r\n return () => {\r\n document.removeEventListener('keydown', onKeyDown)\r\n abertas.splice(abertas.indexOf(aberta), 1)\r\n silenciar()\r\n const voltar = anterior && !anterior.closest('[inert]')\r\n if (voltar) anterior.focus()\r\n else doTopo()?.janela?.focus()\r\n }\r\n }, [open, root, depth])\r\n\r\n // A página por trás não faz scroll enquanto a janela está aberta.\r\n useEffect(() => {\r\n if (!open) return\r\n bloquearScroll()\r\n return libertarScroll\r\n }, [open])\r\n\r\n const noFundo = (e: React.SyntheticEvent) => e.target === fundo.current || e.target === e.currentTarget\r\n\r\n return createPortal(\r\n <div\r\n ref={setRoot}\r\n hidden={!open}\r\n onPointerDown={(e) => {\r\n pressedBackdrop.current = noFundo(e)\r\n }}\r\n onClick={(e) => {\r\n if (closeOnBackdrop && pressedBackdrop.current && noFundo(e)) onClose()\r\n }}\r\n // No telemóvel, a janela de altura total ocupa o ecrã todo (sem margem nem cantos): o cabeçalho, com o ×, fica sempre à vista.\r\n className={`fixed inset-0 z-[200] items-center justify-center p-dialog-margin ${height === 'full' ? 'max-sm:p-0' : ''} ${open ? 'flex' : 'hidden'}`}\r\n >\r\n <div ref={fundo} className=\"absolute inset-0 bg-black/40 motion-safe:animate-backdrop-in\" />\r\n <div\r\n ref={janela}\r\n role=\"dialog\"\r\n aria-modal=\"true\"\r\n aria-labelledby={titleId}\r\n tabIndex={-1}\r\n className={\r\n // No escuro a sombra não se vê: a linha (a mesma dos menus) separa a janela do fundo.\r\n `relative flex max-h-full w-full ${WIDTHS[size]} flex-col overflow-hidden rounded-2xl bg-card text-foreground shadow-modal outline-none dark:border dark:border-slate-700 ` +\r\n `motion-safe:animate-dialog-in ${height === 'full' ? 'h-full max-sm:rounded-none max-sm:border-0' : ''}`\r\n }\r\n >\r\n <header className=\"flex flex-none items-center justify-between gap-3 bg-gradient-to-br from-primary to-primary-strong px-5 py-3.5\">\r\n <div className=\"min-w-0\">\r\n <h2 id={titleId} className=\"m-0 truncate text-title font-bold text-primary-foreground\">\r\n {title}\r\n </h2>\r\n {subtitle && <p className=\"m-0 mt-0.5 truncate text-caption text-primary-foreground/75\">{subtitle}</p>}\r\n </div>\r\n <button\r\n type=\"button\"\r\n aria-label={closeLabel}\r\n title={closeLabel}\r\n onClick={onClose}\r\n className=\"flex h-7 w-7 flex-none cursor-pointer items-center justify-center rounded-md border border-primary-foreground/25 bg-primary-foreground/15 text-base leading-none text-primary-foreground transition-colors hover:bg-primary-foreground/25 focus-visible:ring-2 focus-visible:ring-primary-foreground/60 focus-visible:outline-none\"\r\n >\r\n ×\r\n </button>\r\n </header>\r\n\r\n <DialogContainerContext.Provider value={root}>\r\n <DialogDepthContext.Provider value={depth + 1}>\r\n <div className={flush ? 'flex min-h-0 flex-1 flex-col overflow-hidden bg-canvas' : 'min-h-0 flex-1 overflow-y-auto bg-canvas px-5 py-4'}>{children}</div>\r\n\r\n {footer && <footer className=\"flex flex-none flex-wrap justify-end gap-2 border-t border-border bg-muted/40 px-5 py-[18px]\">{footer}</footer>}\r\n </DialogDepthContext.Provider>\r\n </DialogContainerContext.Provider>\r\n </div>\r\n </div>,\r\n document.body,\r\n )\r\n}\r\n"],"names":[],"mappings":";;;AAGA,MAAM,yBAAyB,cAAkC,IAAI;AACrE,MAAM,qBAAqB,cAAc,CAAC;AAUnC,MAAM,qBAAqB,MAAM,WAAW,sBAAsB;AAuCzE,MAAM,SAAS,EAAE,IAAI,mBAAmB,IAAI,mBAAmB,IAAI,mBAAmB,IAAI,oCAAA;AAQ1F,MAAM,UAAoB,CAAA;AAC1B,MAAM,kCAAkB,IAAA;AAExB,MAAM,SAAS,MAAM,QAAQ,QAAQ,SAAS,CAAC;AAM/C,IAAI,YAAY;AAChB,IAAI,gBAAgB;AAEpB,SAAS,iBAAiB;AACxB,QAAM,OAAO,SAAS;AACtB,MAAI,gBAAgB,GAAG;AACrB,oBAAgB,KAAK,MAAM;AAC3B,SAAK,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import React, { createContext, useContext, useEffect, useId, useRef, useState } from 'react'\r\nimport { createPortal } from 'react-dom'\r\n\r\nconst DialogContainerContext = createContext<HTMLElement | null>(null)\r\nconst DialogDepthContext = createContext(0)\r\n\r\n/**\r\n * O elemento da janela, para usar como destino de `createPortal` (ex: avisos,\r\n * confirmações, sobreposições) quando o conteúdo deve ficar junto dela. Um\r\n * portal para `document.body` também funciona, desde que fique por cima\r\n * (`z-index` acima de 200). Fora de um Dialog devolve `null`.\r\n *\r\n * `createPortal(conteudo, useDialogContainer() ?? document.body)`\r\n */\r\nexport const useDialogContainer = () => useContext(DialogContainerContext)\r\n\r\nexport interface DialogProps {\r\n /** Aberta ou fechada. A app guarda este estado. */\r\n open: boolean\r\n /** Pedido para fechar (×, Esc ou clique fora): a app põe `open` a `false`. */\r\n onClose: () => void\r\n /** Normalmente texto; aceita JSX (ex: um nome em negrito). */\r\n title: React.ReactNode\r\n /** Linha por baixo do título (ex: nome · departamento). */\r\n subtitle?: React.ReactNode\r\n /** Botões no rodapé, sempre visíveis (ex: Confirmar, Fechar). */\r\n footer?: React.ReactNode\r\n /**\r\n * Largura máxima: `sm` 480px, `md` 720px, `lg` 1000px, `xl` até 1600px (95% do ecrã, para janelas com\r\n * mapa e tabela lado a lado). Nunca passa o ecrã.\r\n */\r\n size?: 'sm' | 'md' | 'lg' | 'xl'\r\n /**\r\n * Altura: `auto` (por omissão) cresce com o conteúdo; `full` ocupa sempre a\r\n * altura disponível (útil quando o conteúdo muda de tamanho e a janela não\r\n * deve saltar). Em ambos, se o conteúdo não couber, o corpo faz scroll.\r\n * Ignorada com `placement=\"right\"`, que ocupa sempre a altura toda.\r\n */\r\n height?: 'auto' | 'full'\r\n /**\r\n * Onde abre: `center` (por omissão) é a janela ao centro; `right` é um painel\r\n * encostado à direita, com a altura toda do ecrã, para trabalhar sem perder a\r\n * página de vista (ex: justificar um dia ao lado da tabela). A largura vem de\r\n * `size`, como na janela; no telemóvel ocupa o ecrã todo.\r\n */\r\n placement?: 'center' | 'right'\r\n /** Fechar ao clicar fora da janela. Por omissão sim; num formulário longo pode valer a pena desligar. */\r\n closeOnBackdrop?: boolean\r\n /** Nome do botão ×, para leitores de ecrã. Por omissão: \"Fechar\". */\r\n closeLabel?: string\r\n /**\r\n * Corpo sem margens e sem scroll: o conteúdo ocupa-o todo e gere o seu próprio\r\n * scroll (ex: passos que deslizam, rodapé próprio de cada passo).\r\n */\r\n flush?: boolean\r\n children: React.ReactNode\r\n}\r\n\r\n// O `xl` é 95% do ecrã: no telemóvel deixava uma faixa do fundo escurecido de cada lado,\r\n// mesmo em `height=\"full\"` (que aí ocupa o ecrã todo). Abaixo de `sm` a margem da janela\r\n// já limita a largura, como nos outros tamanhos.\r\nconst WIDTHS = { sm: 'max-w-dialog-sm', md: 'max-w-dialog-md', lg: 'max-w-dialog-lg', xl: 'max-w-dialog-xl max-sm:max-w-none' }\r\n\r\ninterface Aberta {\r\n root: HTMLElement\r\n janela: HTMLElement | null\r\n depth: number\r\n}\r\n\r\nconst abertas: Aberta[] = []\r\nconst silenciados = new Set<Element>()\r\n\r\nconst doTopo = () => abertas[abertas.length - 1]\r\n\r\n// Scroll da página bloqueado enquanto houver pelo menos uma janela aberta. Um contador\r\n// partilhado, e não o \"antes\" de cada janela: com duas abertas que fecham fora de ordem\r\n// (ex: a de baixo desmonta primeiro), a última a fechar repunha o `hidden` e a página\r\n// ficava sem scroll até recarregar.\r\nlet bloqueios = 0\r\nlet overflowAntes = ''\r\n\r\nfunction bloquearScroll() {\r\n const html = document.documentElement\r\n if (bloqueios++ === 0) {\r\n overflowAntes = html.style.overflow\r\n html.style.overflow = 'hidden'\r\n }\r\n}\r\n\r\nfunction libertarScroll() {\r\n if (bloqueios === 0) return\r\n if (--bloqueios === 0) document.documentElement.style.overflow = overflowAntes\r\n}\r\n\r\nfunction silenciar() {\r\n for (const el of silenciados) el.removeAttribute('inert')\r\n silenciados.clear()\r\n // A ordem no ecrã segue a pilha, não a posição no `body`: a confirmação do\r\n // ConfirmProvider entra no `body` quando a app arranca, antes de qualquer\r\n // janela, e com o mesmo z-index ficava escondida por baixo da que a pediu.\r\n abertas.forEach((a, i) => {\r\n a.root.style.zIndex = String(200 + i)\r\n })\r\n const topo = doTopo()\r\n if (!topo) return\r\n for (const el of Array.from(document.body.children)) {\r\n if (el === topo.root || el.hasAttribute('inert')) continue\r\n el.setAttribute('inert', '')\r\n silenciados.add(el)\r\n }\r\n}\r\n\r\n// Uma janela aberta dentro de outra fica sempre por cima dela, mesmo que abram juntas.\r\nfunction empilhar(aberta: Aberta) {\r\n const acima = abertas.findIndex((a) => a.depth > aberta.depth)\r\n if (acima === -1) abertas.push(aberta)\r\n else abertas.splice(acima, 0, aberta)\r\n}\r\n\r\n/**\r\n * Janela por cima da página: cabeçalho navy com título, corpo que faz scroll e\r\n * rodapé com os botões ([Button](?path=/docs/v1-primitives-buttons-button--docs)).\r\n *\r\n * É a janela modal da V1 (substitui o `Modal` legacy). Com `placement=\"right\"`\r\n * abre como painel lateral, encostado à direita e com a altura toda.\r\n *\r\n * Fundo escurecido, Esc para fechar e, ao fechar, o foco volta ao sítio onde\r\n * estava. Enquanto está aberta, o resto da página fica\r\n * [inert](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/inert):\r\n * nem rato, nem teclado, nem leitores de ecrã lhe chegam. Os portais abertos\r\n * depois dela (seletores, confirmações) continuam a responder.\r\n *\r\n * O conteúdo fica montado mesmo com a janela fechada, para poder carregar antes\r\n * de ela abrir.\r\n *\r\n * O tamanho adapta-se ao ecrã só com CSS: nunca passa a largura nem a altura\r\n * da janela do browser (com uma margem), e acompanha-a quando é\r\n * redimensionada. O que não couber faz scroll no corpo; o cabeçalho e o\r\n * rodapé ficam sempre visíveis.\r\n *\r\n * **Exemplo completo:** [Formulário em modal](?path=/docs/v1-patterns-forms-formulário-em-modal--docs).\r\n */\r\nexport default function Dialog({\r\n open,\r\n onClose,\r\n title,\r\n subtitle,\r\n footer,\r\n size = 'md',\r\n height = 'auto',\r\n placement = 'center',\r\n closeOnBackdrop = true,\r\n closeLabel = 'Fechar',\r\n flush = false,\r\n children,\r\n}: DialogProps) {\r\n const [root, setRoot] = useState<HTMLDivElement | null>(null)\r\n const janela = useRef<HTMLDivElement>(null)\r\n const fundo = useRef<HTMLDivElement>(null)\r\n const titleId = useId()\r\n const depth = useContext(DialogDepthContext)\r\n const fechar = useRef(onClose)\r\n fechar.current = onClose\r\n // Clique fora: só conta se começou e acabou no fundo (arrastar a partir de um\r\n // campo para fora não fecha a janela).\r\n const pressedBackdrop = useRef(false)\r\n\r\n useEffect(() => {\r\n if (!open || !root) return\r\n const anterior = document.activeElement as HTMLElement | null\r\n const aberta = { root, janela: janela.current, depth }\r\n empilhar(aberta)\r\n silenciar()\r\n const topo = doTopo()\r\n const dentro = topo.janela?.contains(document.activeElement)\r\n if (!dentro) topo.janela?.focus()\r\n\r\n const onKeyDown = (e: KeyboardEvent) => {\r\n if (e.key !== 'Escape' || e.defaultPrevented) return\r\n if (doTopo() !== aberta) return\r\n fechar.current()\r\n }\r\n document.addEventListener('keydown', onKeyDown)\r\n\r\n return () => {\r\n document.removeEventListener('keydown', onKeyDown)\r\n abertas.splice(abertas.indexOf(aberta), 1)\r\n silenciar()\r\n const voltar = anterior && !anterior.closest('[inert]')\r\n if (voltar) anterior.focus()\r\n else doTopo()?.janela?.focus()\r\n }\r\n }, [open, root, depth])\r\n\r\n // A página por trás não faz scroll enquanto a janela está aberta.\r\n useEffect(() => {\r\n if (!open) return\r\n bloquearScroll()\r\n return libertarScroll\r\n }, [open])\r\n\r\n const noFundo = (e: React.SyntheticEvent) => e.target === fundo.current || e.target === e.currentTarget\r\n const lateral = placement === 'right'\r\n\r\n // Janela ao centro (com margem e cantos) ou painel encostado à direita (altura toda, sem cantos).\r\n const classesRaiz = lateral\r\n ? 'fixed inset-0 z-[200] items-stretch justify-end'\r\n : `fixed inset-0 z-[200] items-center justify-center p-dialog-margin ${height === 'full' ? 'max-sm:p-0' : ''}`\r\n const classesJanela = lateral\r\n ? `relative flex h-full w-full ${WIDTHS[size]} max-sm:max-w-none flex-col overflow-hidden bg-card text-foreground shadow-modal outline-none dark:border-l dark:border-slate-700 motion-safe:animate-panel-in`\r\n : // No escuro a sombra não se vê: a linha (a mesma dos menus) separa a janela do fundo.\r\n `relative flex max-h-full w-full ${WIDTHS[size]} flex-col overflow-hidden rounded-2xl bg-card text-foreground shadow-modal outline-none dark:border dark:border-slate-700 ` +\r\n `motion-safe:animate-dialog-in ${height === 'full' ? 'h-full max-sm:rounded-none max-sm:border-0' : ''}`\r\n\r\n return createPortal(\r\n <div\r\n ref={setRoot}\r\n hidden={!open}\r\n onPointerDown={(e) => {\r\n pressedBackdrop.current = noFundo(e)\r\n }}\r\n onClick={(e) => {\r\n if (closeOnBackdrop && pressedBackdrop.current && noFundo(e)) onClose()\r\n }}\r\n // No telemóvel, a janela de altura total ocupa o ecrã todo (sem margem nem cantos): o cabeçalho, com o ×, fica sempre à vista.\r\n className={`${classesRaiz} ${open ? 'flex' : 'hidden'}`}\r\n data-placement={placement}\r\n >\r\n <div ref={fundo} className=\"absolute inset-0 bg-black/40 motion-safe:animate-backdrop-in\" />\r\n <div\r\n ref={janela}\r\n role=\"dialog\"\r\n aria-modal=\"true\"\r\n aria-labelledby={titleId}\r\n tabIndex={-1}\r\n className={classesJanela}\r\n >\r\n <header className=\"flex flex-none items-center justify-between gap-3 bg-gradient-to-br from-primary to-primary-strong px-5 py-3.5\">\r\n <div className=\"min-w-0\">\r\n <h2 id={titleId} className=\"m-0 truncate text-title font-bold text-primary-foreground\">\r\n {title}\r\n </h2>\r\n {subtitle && <p className=\"m-0 mt-0.5 truncate text-caption text-primary-foreground/75\">{subtitle}</p>}\r\n </div>\r\n <button\r\n type=\"button\"\r\n aria-label={closeLabel}\r\n title={closeLabel}\r\n onClick={onClose}\r\n className=\"flex h-7 w-7 flex-none cursor-pointer items-center justify-center rounded-md border border-primary-foreground/25 bg-primary-foreground/15 text-base leading-none text-primary-foreground transition-colors hover:bg-primary-foreground/25 focus-visible:ring-2 focus-visible:ring-primary-foreground/60 focus-visible:outline-none\"\r\n >\r\n ×\r\n </button>\r\n </header>\r\n\r\n <DialogContainerContext.Provider value={root}>\r\n <DialogDepthContext.Provider value={depth + 1}>\r\n <div className={flush ? 'flex min-h-0 flex-1 flex-col overflow-hidden bg-canvas' : 'min-h-0 flex-1 overflow-y-auto bg-canvas px-5 py-4'}>{children}</div>\r\n\r\n {footer && <footer className=\"flex flex-none flex-wrap justify-end gap-2 border-t border-border bg-muted/40 px-5 py-[18px]\">{footer}</footer>}\r\n </DialogDepthContext.Provider>\r\n </DialogContainerContext.Provider>\r\n </div>\r\n </div>,\r\n document.body,\r\n )\r\n}\r\n"],"names":[],"mappings":";;;AAGA,MAAM,yBAAyB,cAAkC,IAAI;AACrE,MAAM,qBAAqB,cAAc,CAAC;AAUnC,MAAM,qBAAqB,MAAM,WAAW,sBAAsB;AA+CzE,MAAM,SAAS,EAAE,IAAI,mBAAmB,IAAI,mBAAmB,IAAI,mBAAmB,IAAI,oCAAA;AAQ1F,MAAM,UAAoB,CAAA;AAC1B,MAAM,kCAAkB,IAAA;AAExB,MAAM,SAAS,MAAM,QAAQ,QAAQ,SAAS,CAAC;AAM/C,IAAI,YAAY;AAChB,IAAI,gBAAgB;AAEpB,SAAS,iBAAiB;AACxB,QAAM,OAAO,SAAS;AACtB,MAAI,gBAAgB,GAAG;AACrB,oBAAgB,KAAK,MAAM;AAC3B,SAAK,MAAM,WAAW;AAAA,EACxB;AACF;AAEA,SAAS,iBAAiB;AACxB,MAAI,cAAc,EAAG;AACrB,MAAI,EAAE,cAAc,EAAG,UAAS,gBAAgB,MAAM,WAAW;AACnE;AAEA,SAAS,YAAY;AACnB,aAAW,MAAM,YAAa,IAAG,gBAAgB,OAAO;AACxD,cAAY,MAAA;AAIZ,UAAQ,QAAQ,CAAC,GAAG,MAAM;AACxB,MAAE,KAAK,MAAM,SAAS,OAAO,MAAM,CAAC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