tablo_core/panel/shell/brand.rs
1//! The panel's brand: its name and logos, in the sidebar header and above the sign-in card.
2
3use topcoat::{
4 Result,
5 context::Cx,
6 view::{BoxView, ViewExt, view},
7};
8
9use super::{super::Panel, current};
10
11/// Branding for the panel's shell: the sidebar header, the login card, and the
12/// topbar below `md`, where the sidebar folds into a sheet.
13#[derive(Debug, Clone)]
14pub struct Brand {
15 /// Display name (e.g. `"Acme"`).
16 pub name: String,
17 /// Optional logo URL (e.g. `"/logo.svg"`). Rendered as an `<img>` when present.
18 pub logo: Option<String>,
19 /// Optional logo URL shown in place of [`logo`](Self::logo) while the page renders dark.
20 pub dark_logo: Option<String>,
21 /// Optional favicon URL (e.g. `"/favicon.svg"`), the `<link rel="icon">` of every page the
22 /// panel renders, its sign-in pages included.
23 pub favicon: Option<String>,
24 /// The primary color, light then dark, and the text on it.
25 palette: Palette,
26 radius: Option<Radius>,
27 theme: Theme,
28 sidebar: Option<SidebarFrame>,
29 look: Option<LookFn>,
30}
31
32/// What [`Brand::look`] takes: the [`Look`] a request wears.
33type LookFn = fn(&Cx) -> Look;
34
35/// A [`Brand`]'s colors over its theme's primary tokens.
36#[derive(Debug, Clone, Default)]
37struct Palette {
38 color: Option<String>,
39 dark_color: Option<String>,
40 on_color: Option<String>,
41}
42
43/// One of the looks Tablo ships, which a [`Brand`] picks with [`Brand::theme`]: its palette in both
44/// color schemes, its type, corners and shadows, and the [`SidebarFrame`] it suggests. Every theme
45/// speaks the same grammar (captions over the sidebar's groups and the tables' columns, the
46/// current page notched in the primary color, the title ruled off from the page, ruled head
47/// bands), each in a voice of its own.
48///
49/// A brand's [`color`](Brand::color), [`radius`](Brand::radius) and
50/// [`sidebar`](Brand::sidebar), and the tokens an app's stylesheet redeclares, apply over the
51/// theme.
52#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum Theme {
55 /// Tablo's own, the ruled sheet: a jade primary on cool neutrals, the page a white sheet
56 /// inset in the sidebar's frame.
57 #[default]
58 Jade,
59 /// The workshop: warm stone neutrals and an amber primary, bold titles, ringed cards, the
60 /// current page an amber plate. Close to Filament's default look.
61 Amber,
62 /// The instrument: black and white, barely rounded and flat, captions and figures in the
63 /// monospace and tables gridded, beside a charcoal sidebar in either color scheme.
64 Graphite,
65 /// The studio: a violet primary on tinted grays, pills for buttons, badges and tabs, soft
66 /// violet shadows, the sidebar floating beside the page under a frosted topbar.
67 Iris,
68 /// Tablo's site as a panel: black and red inks on pale green paper, square corners, mono
69 /// capitals over ink rules, set in Schibsted Grotesk and Martian Mono, which the shell loads
70 /// for it.
71 Ledger,
72}
73
74impl Theme {
75 /// The `data-tablo-theme` the stylesheet selects the theme's tokens by; the default theme's
76 /// are the stylesheet's `:root` ones, so it needs none.
77 pub(crate) const fn attribute(self) -> Option<&'static str> {
78 match self {
79 Self::Jade => None,
80 Self::Amber => Some("amber"),
81 Self::Graphite => Some("graphite"),
82 Self::Iris => Some("iris"),
83 Self::Ledger => Some("ledger"),
84 }
85 }
86
87 /// The faces the theme sets its pages in, which the shell loads with it: each family's name,
88 /// its file, and the weights the file spans. Empty for a theme in the app's own font.
89 pub(crate) const fn faces(
90 self,
91 ) -> &'static [(&'static str, topcoat::asset::Asset, &'static str)] {
92 match self {
93 Self::Ledger => &[
94 ("Schibsted Grotesk", tablo_ui::SCHIBSTED_GROTESK, "400 900"),
95 ("Martian Mono", tablo_ui::MARTIAN_MONO, "100 800"),
96 ],
97 Self::Jade | Self::Amber | Self::Graphite | Self::Iris => &[],
98 }
99 }
100
101 /// The theme the request's page wears: its panel's brand's, under the brand's [`Look`], or
102 /// the default for a panel without a brand; `None` outside every panel. A picker reads it to
103 /// mark the theme in use.
104 pub fn current(cx: &Cx) -> Option<Self> {
105 let panel = current(cx)?;
106 Some(
107 panel
108 .brand
109 .as_ref()
110 .map_or_else(Self::default, |brand| brand.current_theme(cx)),
111 )
112 }
113
114 /// The frame the theme was drawn beside, unless the brand picks another.
115 pub(super) const fn sidebar(self) -> SidebarFrame {
116 match self {
117 Self::Jade => SidebarFrame::Inset,
118 Self::Amber | Self::Graphite | Self::Ledger => SidebarFrame::Ruled,
119 Self::Iris => SidebarFrame::Floating,
120 }
121 }
122}
123
124/// How the sidebar sits beside the page, which a [`Brand`] picks with [`Brand::sidebar`] over its
125/// [`Theme`]'s.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127#[non_exhaustive]
128pub enum SidebarFrame {
129 /// Flush with the window's edge, a rule between it and the page: Amber's, Graphite's and
130 /// Ledger's.
131 Ruled,
132 /// The page a sheet inset in the sidebar's color, the sidebar its frame: Jade's.
133 Inset,
134 /// A card floating beside the page, clear of the window's edge: Iris's.
135 Floating,
136}
137
138impl SidebarFrame {
139 /// The frame the request's page wears, as [`Theme::current`] reads the theme; `None` outside
140 /// every panel.
141 pub fn current(cx: &Cx) -> Option<Self> {
142 let panel = current(cx)?;
143 Some(panel.brand.as_ref().map_or_else(
144 || Theme::default().sidebar(),
145 |brand| brand.sidebar_frame(cx),
146 ))
147 }
148
149 pub(crate) const fn variant(self) -> tablo_ui::SidebarVariant {
150 match self {
151 Self::Ruled => tablo_ui::SidebarVariant::Sidebar,
152 Self::Inset => tablo_ui::SidebarVariant::Inset,
153 Self::Floating => tablo_ui::SidebarVariant::Floating,
154 }
155 }
156}
157
158/// The theme and the sidebar frame one request wears over its [`Brand`]'s, which the function
159/// passed to [`Brand::look`] answers for every page the panel renders, sign-in included: a
160/// visitor's own pick, read from a cookie the app writes.
161///
162/// A look that names a theme but no frame keeps the brand's [`sidebar`](Brand::sidebar), else
163/// takes the theme's own.
164///
165/// ```rust
166/// # use tablo_core::{Brand, Look, Theme};
167/// # use topcoat::{context::Cx, cookie::{Cookies, cookies}};
168/// fn visitor_look(cx: &Cx) -> Look {
169/// match cookies(cx)
170/// .get("acme_theme")
171/// .as_ref()
172/// .map(|cookie| cookie.value())
173/// {
174/// Some("iris") => Look::default().theme(Theme::Iris),
175/// _ => Look::default(),
176/// }
177/// }
178///
179/// Brand::new("Acme").look(visitor_look);
180/// ```
181#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
182pub struct Look {
183 theme: Option<Theme>,
184 sidebar: Option<SidebarFrame>,
185}
186
187impl Look {
188 /// Wear `theme` instead of the brand's.
189 #[must_use]
190 pub const fn theme(mut self, theme: Theme) -> Self {
191 self.theme = Some(theme);
192 self
193 }
194
195 /// Frame the page with the sidebar as `frame` says instead of as the brand or the theme does.
196 #[must_use]
197 pub const fn sidebar(mut self, frame: SidebarFrame) -> Self {
198 self.sidebar = Some(frame);
199 self
200 }
201}
202
203/// How round a [`Brand`]'s controls, cards and badges are, over its theme's.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205#[non_exhaustive]
206pub enum Radius {
207 /// Square corners.
208 None,
209 /// `0.25rem`.
210 Small,
211 /// `0.5rem`, Jade's.
212 Medium,
213 /// `0.75rem`.
214 Large,
215 /// `1rem`.
216 ExtraLarge,
217}
218
219impl Radius {
220 const fn css(self) -> &'static str {
221 match self {
222 Self::None => "0rem",
223 Self::Small => "0.25rem",
224 Self::Medium => "0.5rem",
225 Self::Large => "0.75rem",
226 Self::ExtraLarge => "1rem",
227 }
228 }
229}
230
231impl Brand {
232 /// Create a brand with the given name (surrounding whitespace is
233 /// trimmed so `" Acme "` cannot break the `flex h-16` header).
234 pub fn new(name: impl Into<String>) -> Self {
235 Self {
236 name: name.into().trim().to_string(),
237 logo: None,
238 dark_logo: None,
239 favicon: None,
240 palette: Palette::default(),
241 radius: None,
242 theme: Theme::default(),
243 sidebar: None,
244 look: None,
245 }
246 }
247
248 /// Paint the panel's primary color, its buttons, links, focus rings and brand mark, in
249 /// `color`: a hex color or a color function such as `oklch(0.55 0.2 260)`. It paints the dark
250 /// theme too, unless [`dark_color`](Self::dark_color) says otherwise. Mounting the panel
251 /// refuses any other spelling, which the page's stylesheet would carry as it is.
252 pub fn color(mut self, color: impl Into<String>) -> Self {
253 self.palette.color = Some(color.into().trim().to_string());
254 self
255 }
256
257 /// Paint the primary color in `color` while the page renders dark, such as a lighter shade
258 /// of [`color`](Self::color) for a dark background.
259 pub fn dark_color(mut self, color: impl Into<String>) -> Self {
260 self.palette.dark_color = Some(color.into().trim().to_string());
261 self
262 }
263
264 /// Paint the text on the primary color in `color`, over the theme's: a dark
265 /// color for a light [`color`](Self::color), such as yellow.
266 pub fn on_color(mut self, color: impl Into<String>) -> Self {
267 self.palette.on_color = Some(color.into().trim().to_string());
268 self
269 }
270
271 /// Dress the panel in `theme` instead of [`Theme::Jade`]: its pages, sign-in included.
272 pub fn theme(mut self, theme: Theme) -> Self {
273 self.theme = theme;
274 self
275 }
276
277 /// Frame the page with the sidebar as `frame` says instead of as the theme does.
278 pub fn sidebar(mut self, frame: SidebarFrame) -> Self {
279 self.sidebar = Some(frame);
280 self
281 }
282
283 /// Let each request pick its theme and sidebar frame over the brand's, through the [`Look`]
284 /// `look` answers for it.
285 pub fn look(mut self, look: fn(&Cx) -> Look) -> Self {
286 self.look = Some(look);
287 self
288 }
289
290 /// The look `cx` wears: the brand's theme and frame, under the request's [`Look`].
291 fn current_look(&self, cx: &Cx) -> Look {
292 self.look.map(|look| look(cx)).unwrap_or_default()
293 }
294
295 /// The theme `cx` wears: the request's, else the brand's.
296 pub(crate) fn current_theme(&self, cx: &Cx) -> Theme {
297 self.current_look(cx).theme.unwrap_or(self.theme)
298 }
299
300 /// The sidebar's frame `cx` wears: the request's, else the brand's, else its theme's.
301 pub(crate) fn sidebar_frame(&self, cx: &Cx) -> SidebarFrame {
302 let look = self.current_look(cx);
303 look.sidebar
304 .or(self.sidebar)
305 .unwrap_or_else(|| look.theme.unwrap_or(self.theme).sidebar())
306 }
307
308 /// Round the panel's corners to `radius`.
309 pub fn radius(mut self, radius: Radius) -> Self {
310 self.radius = Some(radius);
311 self
312 }
313
314 /// The colors mounting refuses: each that is no CSS color.
315 pub(crate) fn declaration_errors(&self) -> Vec<crate::DeclarationErrorKind> {
316 let Palette {
317 color,
318 dark_color,
319 on_color,
320 } = &self.palette;
321 [color, dark_color, on_color]
322 .into_iter()
323 .flatten()
324 .filter(|value| !crate::column::is_css_color(value))
325 .map(|value| crate::DeclarationErrorKind::BrandColor {
326 value: value.clone(),
327 })
328 .collect()
329 }
330
331 /// The style sheet that lays the brand's colors and radius over its theme; `None`
332 /// when it sets neither, or a color mounting would refuse.
333 pub(crate) fn style(&self) -> Option<String> {
334 if !self.declaration_errors().is_empty() {
335 return None;
336 }
337 let Palette {
338 color,
339 dark_color,
340 on_color,
341 } = &self.palette;
342 let tokens = |primary: Option<&String>| {
343 let mut tokens = String::new();
344 if let Some(primary) = primary {
345 tokens.push_str(&format!("--primary:{primary};--ring:{primary};"));
346 }
347 if let Some(on) = on_color {
348 tokens.push_str(&format!("--primary-foreground:{on};"));
349 }
350 tokens
351 };
352 let mut light = tokens(color.as_ref());
353 if let Some(radius) = self.radius {
354 light.push_str(&format!("--radius:{};", radius.css()));
355 }
356 let dark = tokens(dark_color.as_ref().or(color.as_ref()));
357 let mut style = String::new();
358 if !light.is_empty() {
359 style.push_str(&format!(":root{{{light}}}"));
360 }
361 if !dark.is_empty() {
362 style.push_str(&format!(":root.dark{{{dark}}}"));
363 }
364 (!style.is_empty()).then_some(style)
365 }
366
367 /// Attach a logo URL (blank values are ignored so an empty
368 /// `logo("")` falls back to the name-only render instead of a
369 /// broken-image icon).
370 pub fn logo(mut self, logo: impl Into<String>) -> Self {
371 let logo = logo.into().trim().to_string();
372 if !logo.is_empty() {
373 self.logo = Some(logo);
374 }
375 self
376 }
377
378 /// Attach the logo URL shown in place of [`logo`](Self::logo) while the page renders dark,
379 /// such as a light wordmark for a dark background; a blank value is ignored. Without a
380 /// [`logo`](Self::logo) it is ignored too, and the brand shows its initial in either theme.
381 pub fn dark_logo(mut self, logo: impl Into<String>) -> Self {
382 let logo = logo.into().trim().to_string();
383 if !logo.is_empty() {
384 self.dark_logo = Some(logo);
385 }
386 self
387 }
388
389 /// Attach a favicon URL; a blank value is ignored, leaving the browser's default.
390 pub fn favicon(mut self, favicon: impl Into<String>) -> Self {
391 let favicon = favicon.into().trim().to_string();
392 if !favicon.is_empty() {
393 self.favicon = Some(favicon);
394 }
395 self
396 }
397}
398
399/// A brand's logo URLs: the one it shows, and the one it shows instead while the page renders
400/// dark.
401struct Logos {
402 light: String,
403 dark: Option<String>,
404}
405
406/// Where a brand mark renders, which sets its size.
407#[derive(Clone, Copy)]
408enum BrandSize {
409 /// The sidebar header and the narrow topbar: 28px.
410 Sidebar,
411 /// Above the card of a page outside the shell, such as sign-in: 40px.
412 Page,
413}
414
415impl Panel {
416 /// The panel's brand: its name and its logos, light then dark, or none for its initial on
417 /// the primary color.
418 fn current_brand(cx: &Cx) -> (String, Option<Logos>) {
419 match current(cx).and_then(|panel| panel.brand.as_ref()) {
420 Some(brand) => (
421 brand.name.clone(),
422 brand.logo.clone().map(|light| Logos {
423 light,
424 dark: brand.dark_logo.clone(),
425 }),
426 ),
427 None => ("Tablo".to_string(), None),
428 }
429 }
430
431 /// The request's panel brand name, `Tablo` without one.
432 pub(crate) fn brand_name(cx: &Cx) -> String {
433 Self::current_brand(cx).0
434 }
435
436 /// The brand's mark at `size`: its logo, or without one its initial on the primary token, so
437 /// a header keeps its mark.
438 fn brand_mark<'a>(cx: &'a Cx, name: &str, logo: Option<Logos>, size: BrandSize) -> BoxView<'a> {
439 // A page logo keeps its own width at the page mark's height. Logos show at multiples of
440 // 16px, where one drawn on a 16px grid puts every edge on a whole pixel, and keep their
441 // own corners.
442 let (width, height, logo_class, initial_class) = match size {
443 BrandSize::Sidebar => (
444 Some("32"),
445 "32",
446 "size-8 shrink-0",
447 "flex size-7 shrink-0 items-center justify-center rounded-md bg-primary text-sm \
448 font-semibold text-primary-foreground",
449 ),
450 BrandSize::Page => (
451 None,
452 "48",
453 "h-12 w-auto shrink-0",
454 "flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary text-lg \
455 font-semibold text-primary-foreground",
456 ),
457 };
458 match logo {
459 Some(Logos { light, dark }) => {
460 // A page always shows the name beside its logo, so the logo is decoration there;
461 // the icon rail hides the sidebar's name, so the sidebar logo names the brand.
462 let alt = match size {
463 BrandSize::Sidebar => name.to_string(),
464 BrandSize::Page => String::new(),
465 };
466 // Both images render and the `dark` class picks one, so the theme toggle swaps
467 // the logo without a request.
468 let light_class = match dark {
469 Some(_) => format!("{logo_class} dark:hidden"),
470 None => logo_class.to_string(),
471 };
472 let dark_class = format!("{logo_class} hidden dark:block");
473 view! {
474 <img
475 src=(light)
476 alt=(alt.clone())
477 width=(width)
478 height=(height)
479 class=(light_class)
480 >
481 if let Some(dark_url) = dark {
482 <img
483 src=(dark_url)
484 alt=(alt)
485 width=(width)
486 height=(height)
487 class=(dark_class)
488 >
489 }
490 }
491 .boxed()
492 }
493 None => {
494 let initial = name.chars().next().map(String::from).unwrap_or_default();
495 view! { <span aria-hidden="true" class=(initial_class)>(initial)</span> }.boxed()
496 }
497 }
498 }
499
500 /// The brand as the sidebar header shows it: the mark beside the name.
501 pub(crate) async fn render_brand(cx: &Cx) -> Result<BoxView<'_>> {
502 let (name, logo) = Self::current_brand(cx);
503 let mark = Self::brand_mark(cx, &name, logo, BrandSize::Sidebar);
504 Ok(view! {
505 <div class="flex min-w-0 items-center gap-2 font-semibold text-foreground">
506 (mark)
507 <span
508 class="truncate tracking-[var(--tablo-heading-tracking)] md:group-data-[collapsible=icon]/sidebar:hidden"
509 data-brand-name=""
510 >
511 (name)
512 </span>
513 </div>
514 }
515 .boxed())
516 }
517
518 /// The brand as a page outside the shell shows it, above its card: the mark over the name.
519 pub(crate) fn render_page_brand(cx: &Cx) -> BoxView<'_> {
520 let (name, logo) = Self::current_brand(cx);
521 let mark = Self::brand_mark(cx, &name, logo, BrandSize::Page);
522 view! {
523 <div class="flex flex-col items-center gap-3 text-center" data-brand="">
524 (mark)
525 <span class="tablo-heading text-lg text-foreground" data-brand-name="">
526 (name)
527 </span>
528 </div>
529 }
530 .boxed()
531 }
532}