diff --git a/docs/figma/Checkbox.md b/docs/figma/Checkbox.md index a185f6c1..747165ef 100644 --- a/docs/figma/Checkbox.md +++ b/docs/figma/Checkbox.md @@ -26,8 +26,8 @@ - Keyboard focus draws a 2px `color/focus-ring` ring 2px outside the box (like Button); in Figma it is a `focus ring` rectangle inside `input`, absolutely positioned. -- Disabled and readOnly use one neutral look: `color/surface/disabled`, `color/border/disabled`, mark and label - `color/text/disabled`. +- Disabled and readOnly use one neutral look: `color/surface/disabled`, `color/border/disabled`, mark + `color/text/disabled-soft`, label `color/text/disabled`. - The error border stays on a checked box. - The partial mark is a rectangle (the code's SVG line); the check mark is `Icon/check` with its fill overridden. - ListView's selectable rows use this Checkbox. diff --git a/docs/figma/Drawer.md b/docs/figma/Drawer.md new file mode 100644 index 00000000..8c45b47c --- /dev/null +++ b/docs/figma/Drawer.md @@ -0,0 +1,26 @@ +# Drawer: Figma notes (maintained by AI, do not edit by hand) + +## Nodes + +| What | ID | +| ---------------------------------------------- | ------------------------------- | +| Page | `595:286` | +| Component set `Drawer` (12 variants) | `595:412` | +| Doc frame / Playground frame | `596:224` / `596:280` | +| Sections: Documentation, Playground, Component | `595:287`, `595:288`, `595:289` | + +## Properties + +- Variants: `position` (left, right, top, bottom) × `size` (md first; sm, lg). Width `sizing/320 · 480 · 760` for + left and right (shown 360 high), height `sizing/256 · 400 · 600` for top and bottom (shown 760 wide): the code + takes the screen's other dimension, at most 85% of it. +- Each variant is a clipped box with 40 of shadow room on the inner side only; the `drawer` frame inside carries the + size tokens and the shadow, so the outer edges show none (they sit at the screen edge in code). +- As Modal: `color/surface/raised`, effect `elevation/4`, radius `sizing/radius/lg` on the inner edges only, no border, + no line under the header. +- Header: `headerTitle` (text style heading-h5, `color/text/strong`) and `closeButton` (IconButton neutral, close, + `sizing/icon/lg`), padding and gap 16. Content: padding 16 (includePadding), a `children` placeholder in body-md. +- Properties: text `title`; booleans `showTitle`, `closable`, `header` (code: shown when there is a title or a close + button). includePadding=false is an override of the content padding (Scenarios). +- Scenarios: backdrop (`color/backdrop`) vs removeBackdrop on a page; header and padding combinations. +- Dark: every color follows its token. diff --git a/docs/figma/Radio.md b/docs/figma/Radio.md index 868e1fd3..03f45352 100644 --- a/docs/figma/Radio.md +++ b/docs/figma/Radio.md @@ -14,6 +14,6 @@ - Variants: `size` (md default, xs, sm, lg) × `checked` × `error` / `success` / `disabled` (one at a time, like Checkbox). `label` (text) and `showLabel` (boolean). - Checked is a filled disc (user, 2026-11-23: no dot). success colors the empty disc's border `color/success/border` - (and Checkbox's empty box, same PR). Checked disabled disc `color/text/disabled`. + (and Checkbox's empty box, same PR). Checked disabled disc `color/text/disabled-soft`. - Keyboard focus is not a variant: a hidden `focus ring` ellipse in `radio`, turned on in the Color spec. - Table: column `size`; rows off / on × default, error, success, disabled. diff --git a/docs/figma/Slider.md b/docs/figma/Slider.md new file mode 100644 index 00000000..28b5d896 --- /dev/null +++ b/docs/figma/Slider.md @@ -0,0 +1,28 @@ +# Slider: Figma notes (maintained by AI, do not edit by hand) + +## Nodes + +| What | ID | +| -------------------------------------------------------- | -------------------------------------- | +| Page | `590:22` | +| Component set `Slider` (38 variants) | `590:188` | +| Part `_Slider/Thumb` (4 variants) | `590:31` | +| Part `_Slider/Tooltip` | `590:32` | +| Doc frame / Playground frame | `592:140` / `592:196` | +| Sections: Documentation, Playground, Component, Internal | `590:23`, `590:24`, `590:25`, `590:26` | + +## Properties + +- Variants: `size` (md first) × `variant` (VariantV2: neutral, primary, secondary, accent, info, success, warning, + danger) at fill=left; `disabled=true` at primary for every size; `fill` right and none at md primary. +- 240 wide (the code takes its container's width), as high as the hovered thumb (16 · 20 · 22 · 28). Track and fill + `sizing/2 · 4 · 6 · 8`, radius round; the thumb sits at 40%. +- `_Slider/Thumb`: `sizing/12 · 16 · 18 · 24`, `color/surface/raised`, a `sizing/2 · 2 · 3 · 4` inside ring + (`color/primary/solid`, overridden per variant), effect `elevation/1`. +- `_Slider/Tooltip`: `color/surface/contrast` bubble, `color/text/on-contrast` label-md stronger (text-sm 600), padding + 4 / 8, radius md, a 12 × 6 pointer; text property `value`. +- Colors: track `color/neutral/soft`, fill and ring `{variant}/solid`. Disabled (and readOnly, the same look): track + `color/surface/disabled`, fill and ring `color/text/disabled-soft`. +- Spec: Size spec, Color spec · thumb (default, hover grown to the hover size, focus 2px `color/focus-ring` 2px + outside). Scenarios: value tooltip on hover, disabled and readOnly. +- Dark: every color follows its token. diff --git a/docs/figma/SliderRange.md b/docs/figma/SliderRange.md new file mode 100644 index 00000000..018780a1 --- /dev/null +++ b/docs/figma/SliderRange.md @@ -0,0 +1,16 @@ +# SliderRange: Figma notes (maintained by AI, do not edit by hand) + +## Nodes + +| What | ID | +| ---------------------------------------------- | ---------------------------- | +| Page | `593:22` | +| Component set `SliderRange` (36 variants) | `593:206` | +| Doc frame / Playground frame | `593:276` / `593:332` | +| Sections: Documentation, Playground, Component | `593:23`, `593:24`, `593:25` | + +## Properties + +- Variants: `size` (md first) × `variant` (VariantV2) and `disabled=true` at primary for every size. +- Same geometry and colors as Slider (two `_Slider/Thumb` at 20% and 70%, the fill between them); the code stacks two + Sliders. The value tooltip is `_Slider/Tooltip` (Scenarios). diff --git a/docs/figma/Switch.md b/docs/figma/Switch.md index 35cd650b..227b5a79 100644 --- a/docs/figma/Switch.md +++ b/docs/figma/Switch.md @@ -23,7 +23,8 @@ ## Decisions (user, 2026-11-19) - The off track is `color/neutral/solid` (darker than today's light gray, for contrast); the off thumb is - `color/surface/default` (dark in dark mode); checked: `color/primary/solid` with a `color/on-primary` thumb. + `color/surface/default` (dark in dark mode); checked: `color/primary/solid` with a `color/on-primary` thumb. Disabled: track `color/surface/disabled`, thumb + `color/text/disabled-soft`, label `color/text/disabled`. - Disabled and readOnly: track `color/surface/disabled`, thumb and label `color/text/disabled`. - The switch is keyboard accessible (role switch, Space toggles) with a 2px `color/focus-ring` ring 2px outside the track; the input is visually hidden and not drawn in Figma. diff --git a/docs/figma/Table.md b/docs/figma/Table.md new file mode 100644 index 00000000..8ffc8333 --- /dev/null +++ b/docs/figma/Table.md @@ -0,0 +1,42 @@ +# Table: Figma notes (maintained by AI, do not edit by hand) + +## Nodes + +| What | ID | +| -------------------------------------------------------- | ------------------------------------------ | +| Page | `597:286` | +| Component set `Table` (9 variants) | `597:956` | +| Part `_Table/HeaderCell` (9 variants) | `597:365` | +| Part `_Table/Cell` (33 variants) | `597:432` | +| Part `_Table/FooterCell` (9 variants) | `597:451` | +| Scenarios (group) | `599:907` | +| Doc frame / Playground frame | `601:763` / `601:819` | +| Sections: Documentation, Playground, Component, Internal | `597:287`, `597:288`, `597:289`, `597:290` | + +## Properties + +- Variants: `border` (cellBorders default, rowBorders, none) × `headerColsBackground` (solid default, transparent, + opposite; the footer takes the same). Three columns of 160 (the code sizes them by content or evenly), three rows, + the footer row (the first two cells absorbed) and the total records line. +- Parts, padding 12 / 8 (`sizing/space`), lines `color/border/soft` 1px included in layout (cell: right and bottom, + row: bottom, none): + - `_Table/HeaderCell`: `background` × `border`; label-md strongest `color/text/strong` (opposite: + `color/surface/contrast` + `color/text/on-contrast`); text `label`, boolean `sorting` (IconButton neutral, sm, expand_all). + - `_Table/Cell`: `state` (default, striped `color/surface/subtle`, selected `color/primary/soft`, a VariantV2 row color + `{variant}/soft`) × `border`; body-sm `color/text/default`; text `value`. + - `_Table/FooterCell`: as the header cell, text to the right. +- cellBorders: the table is clipped by a 1px `color/border/soft` outline with radius md; rowBorders: a top line. +- Hover (hoverable) is a Scenarios override: the row's own tone one step darker (`color/neutral/soft-hover` for plain + and striped rows, `color/primary/soft-hover` selected, `{variant}/soft-hover` row colors), never on a rowSpan cell + (drawn with a rowSpan table). +- cellBorders: the outline draws the outer edges, so the last column has no right line and the last row no bottom line + (instance overrides); no doubled 2px edge. +- opposite + cellBorders: the head and foot rows draw the outer edges in `color/surface/contrast` (as the code), the + body rows `color/border/soft`. +- Scenarios: title and subtitle, striped, selectable (Checkbox md without label, partial in the header), row colors, + hover with rowSpan, filterableTable, column filters and both (InputText sm), footer line (default, hideTotalRecords, pagination left / + center / right), pagination (footer 60 high, 8 under the table), loading + (Skeleton, three bars), + no data. +- The code's SCSS keeps its structure (deep th/td selectors, out of the strict stylelint list for now). +- Dark: every color follows its token. diff --git a/docs/review/design-tokens.md b/docs/review/design-tokens.md index bc3d1150..cdd34fdc 100644 --- a/docs/review/design-tokens.md +++ b/docs/review/design-tokens.md @@ -88,7 +88,7 @@ Where the text comes from depends on whether the component has a size prop: - Text: `text-stronger, text-strong, text-default, text-soft, text-softer`, `text-disabled`. On a solid intent fill use `on-{intent}`; on images use `text-on-media`. - Surfaces: `surface-canvas` (page), `surface-default` (card, panel), `surface-raised` (popover, dropdown, modal), - `surface-sunken`, `surface-subtle`, `surface-disabled`, `surface-opposite` (tooltip). + `surface-sunken`, `surface-subtle`, `surface-disabled`, `surface-contrast` (tooltip, with `text-on-contrast`), `surface-opposite`. - Intent tokens, by job: - `{intent}-solid`, `-solid-hover`, `-solid-active`: filled backgrounds; - `{intent}-soft`, `-soft-hover`: tinted backgrounds, ghost/outline hover; @@ -104,6 +104,9 @@ Where the text comes from depends on whether the component has a size prop: `border-field`, `border-field-hover`, `border-field-focus`. Validation uses the intent borders directly (`danger-border`, `success-border`); disabled uses the global disabled tokens. Flag a field-like component that uses the generic text or border tokens instead of the field ones. +- Disabled controls: areas `surface-disabled`, lines `border-disabled`, labels `text-disabled`, and the fills and marks + inside (Checkbox check, Radio disc, Switch knob, Slider fill and thumb ring) `text-disabled-soft`, so a disabled fill does + not read as the neutral variant. Flag a disabled fill or mark on `text-disabled`. - Dark mode is handled by the tokens (`light-dark()`). Flag component-level dark overrides: `@media (prefers-color-scheme)`, `[data-mtf-mode]` selectors, or separate dark variables inside a component. diff --git a/src/lib/components/Checkbox/Checkbox.module.scss b/src/lib/components/Checkbox/Checkbox.module.scss index 19bf056b..838e72d4 100644 --- a/src/lib/components/Checkbox/Checkbox.module.scss +++ b/src/lib/components/Checkbox/Checkbox.module.scss @@ -73,7 +73,7 @@ $sizes: (("xs", 18, 6, 4, 16, "0 0 23 23"), ("sm", 20, 8, 6, 18, "0 0 23 23"), ( background-color: var(--mtf-color-surface-disabled); &::before { - background-color: var(--mtf-color-text-disabled); + background-color: var(--mtf-color-text-disabled-soft); } } } diff --git a/src/lib/components/Drawer/Drawer.module.scss b/src/lib/components/Drawer/Drawer.module.scss index 3d422237..4726355e 100644 --- a/src/lib/components/Drawer/Drawer.module.scss +++ b/src/lib/components/Drawer/Drawer.module.scss @@ -1,17 +1,14 @@ @use "@styles" as *; -$sizes: ( - //sizeName, width, height - ("sm", "320x", "256x"), - ("md", "480x", "400x"), - ("lg", "760x", "600x") -); +// size, width (left and right), height (top and bottom) +$sizes: (("sm", 320, 256), ("md", 480, 400), ("lg", 760, 600)); +// The panel, as Modal's: a raised surface, rounded only on its inner edges .Root { position: fixed; inset: 0; - background-color: var(--base-colors-black-black-overlay50); z-index: z-layer("modal"); + background-color: var(--mtf-color-backdrop); @include fade-default; &.show { @@ -24,69 +21,70 @@ $sizes: ( } .drawer { + position: fixed; display: flex; flex-direction: column; - position: fixed; - background: var(--theme-color-surface-base-global-light); - border: solid var(--base-sizing-1x) var(--theme-color-border-light-default); max-width: 100%; max-height: 100%; overflow: hidden; - @include shadow(4); + color: var(--mtf-color-text-default); + background-color: var(--mtf-color-surface-raised); + box-shadow: var(--mtf-elevation-4); +} - .left & { - @include slide-default("left"); - inset: 0 auto 0 0; - border-radius: 0 var(--theme-sizing-radius-default) var(--theme-sizing-radius-default) 0; - } +.left .drawer { + @include slide-default("left"); + inset: 0 auto 0 0; + border-radius: 0 var(--mtf-sizing-radius-lg) var(--mtf-sizing-radius-lg) 0; +} - .right & { - @include slide-default("right"); - inset: 0 0 0 auto; - border-radius: var(--theme-sizing-radius-default) 0 0 var(--theme-sizing-radius-default); - } +.right .drawer { + @include slide-default("right"); + inset: 0 0 0 auto; + border-radius: var(--mtf-sizing-radius-lg) 0 0 var(--mtf-sizing-radius-lg); +} - .top & { - @include slide-default("top"); - inset: 0 0 auto; - border-radius: 0 0 var(--theme-sizing-radius-default) var(--theme-sizing-radius-default); - } +.top .drawer { + @include slide-default("top"); + inset: 0 0 auto; + border-radius: 0 0 var(--mtf-sizing-radius-lg) var(--mtf-sizing-radius-lg); +} - .bottom & { - @include slide-default("bottom"); - inset: auto 0 0; - border-radius: var(--theme-sizing-radius-default) var(--theme-sizing-radius-default) 0 0; - } +.bottom .drawer { + @include slide-default("bottom"); + inset: auto 0 0; + border-radius: var(--mtf-sizing-radius-lg) var(--mtf-sizing-radius-lg) 0 0; +} - .show & { - @include slide-in; - } +// After the positions: same specificity, so the open state wins by order +.show .drawer { + @include slide-in; +} - @each $size, $width, $height in $sizes { - .left.#{$size} &, - .right.#{$size} & { - width: min(var(--base-sizing-#{$width}), 85vw); - } +@each $size, $width, $height in $sizes { + .left.#{$size} .drawer, + .right.#{$size} .drawer { + width: min(var(--mtf-sizing-#{$width}), 85vw); + } - .top.#{$size} &, - .bottom.#{$size} & { - height: min(var(--base-sizing-#{$height}), 85vh); - } + .top.#{$size} .drawer, + .bottom.#{$size} .drawer { + height: min(var(--mtf-sizing-#{$height}), 85vh); } } .header { display: flex; align-items: flex-start; - gap: var(--base-sizing-16x); - padding: var(--base-sizing-16x); + gap: var(--mtf-sizing-space-16); + padding: var(--mtf-sizing-space-16); } .headerTitle { flex: 1; - color: var(--theme-color-text-base-title); overflow-wrap: break-word; - @include font("base", "lg", "700"); + color: var(--mtf-color-text-strong); + @include typography("heading-h5"); } .closeButton { @@ -97,8 +95,9 @@ $sizes: ( flex: 1 1 auto; min-height: 0; overflow-y: auto; -} + scrollbar-color: var(--mtf-color-border-strong) transparent; -.includePadding .content { - padding: var(--base-sizing-16x); + .includePadding & { + padding: var(--mtf-sizing-space-16); + } } diff --git a/src/lib/components/Radio/Radio.module.scss b/src/lib/components/Radio/Radio.module.scss index 60f7f455..706d708f 100644 --- a/src/lib/components/Radio/Radio.module.scss +++ b/src/lib/components/Radio/Radio.module.scss @@ -46,9 +46,9 @@ $sizes: (("xs", 16, 6), ("sm", 20, 8), ("md", 24, 10), ("lg", 28, 12)); border-color: var(--mtf-color-border-disabled); background-color: var(--mtf-color-surface-disabled); - // A checked disabled disc stays a darker gray, so it still reads as selected + // A checked disabled disc stays a step darker than the disabled surface, so it still reads as selected &:checked { - background-color: var(--mtf-color-text-disabled); + background-color: var(--mtf-color-text-disabled-soft); } } } diff --git a/src/lib/components/Slider/Slider.module.scss b/src/lib/components/Slider/Slider.module.scss index 19bfa4e9..dba6b618 100644 --- a/src/lib/components/Slider/Slider.module.scss +++ b/src/lib/components/Slider/Slider.module.scss @@ -1,117 +1,55 @@ +@use "sass:math"; @use "@styles" as *; @use "./sliderValues" as *; -// variant, color, border color, disabled, border disabled -$color-types: ( - ("secondary", var(--theme-color-surface-base-base7), var(--theme-color-surface-base-base7), var(--theme-color-surface-base-base6), var(--theme-color-surface-base-base6)), - ("warning", var(--theme-color-surface-warning-default), var(--theme-color-surface-warning-default), var(--theme-color-surface-warning-inverse), var(--theme-color-border-warning-disabled)), - ("success", var(--theme-color-surface-success-default), var(--theme-color-surface-success-default), var(--theme-color-surface-success-inverse), var(--theme-color-border-success-disabled)), - ("danger", var(--theme-color-surface-danger-default), var(--theme-color-surface-danger-default), var(--theme-color-surface-danger-inverse), var(--theme-color-border-danger-disabled)), - ("primary", var(--theme-color-surface-primary-default), var(--theme-color-surface-primary-default), var(--theme-color-surface-primary-inverse), var(--theme-color-border-primary-disabled)), - ("info", var(--theme-color-surface-info-default), var(--theme-color-surface-info-default), var(--theme-color-surface-info-inverse), var(--theme-color-border-info-disabled)) -); - -@mixin slider-style-thumb { - border-radius: var(--theme-sizing-radius-round); - background: var(--theme-color-surface-base-bg-light); - box-shadow: 0 var(--base-sizing-1x) var(--base-sizing-2x) var(--base-sizing-1x) var(--base-colors-black-black-overlay15); +$variants: "neutral", "primary", "secondary", "accent", "info", "success", "warning", "danger"; + +@mixin thumb { + box-sizing: border-box; + border-style: solid; + border-radius: var(--mtf-sizing-radius-round); + background-color: var(--mtf-color-surface-raised); + box-shadow: var(--mtf-elevation-1); cursor: pointer; - @include transition(transform); pointer-events: auto; - box-sizing: border-box; -} -@mixin slider-size-thumb($thumbSize, $thumbBorderSize, $thumbHoverSize) { - height: var(--base-sizing-#{$thumbSize}); - width: var(--base-sizing-#{$thumbSize}); - border: var(--base-sizing-#{$thumbBorderSize}) solid; - &:hover { - transform: scale(calc(var(--base-sizing-#{$thumbHoverSize}) / var(--base-sizing-#{$thumbSize}))); - } -} -@mixin slider-color-thumb-disabled($borderDisabledColor) { - cursor: not-allowed; - border-color: $borderDisabledColor; + @include transition(transform); } -@each $size, $progressHeight, $thumb, $thumbHover, $thumbBorder, $marginTop, $horizontalPadding in $sizes-positions { - .#{$size} { - &.Root { - min-height: var(--base-sizing-#{$thumbHover}); - - &.inFormField { - margin: var(--base-sizing-#{$marginTop}) var(--base-sizing-#{$horizontalPadding}) 0; - } - } - .tooltip { - bottom: calc(var(--base-sizing-#{$thumb}) - var(--base-sizing-20x)); - } - .fill, - .track, - .mRangeContainer::after { - height: var(--base-sizing-#{$progressHeight}); - } - .mRange { - &::-webkit-slider-thumb { - @include slider-size-thumb($thumb, $thumbBorder, $thumbHover); - } - &::-moz-range-thumb { - @include slider-size-thumb($thumb, $thumbBorder, $thumbHover); - } - } - } -} +@mixin thumb-size($thumb, $thumbHover, $thumbBorder) { + width: var(--mtf-sizing-#{$thumb}); + height: var(--mtf-sizing-#{$thumb}); + border-width: var(--mtf-sizing-#{$thumbBorder}); -@each $variant, $color, $borderColor, $disabledColor, $borderDisabledColor in $color-types { - .#{$variant} { - .fill { - background: $color; - } - .mRange { - &::-webkit-slider-thumb { - border-color: $borderColor; - } - &::-moz-range-thumb { - border-color: $borderColor; - } - } - &.disabled { - cursor: not-allowed; - .fill { - background: $disabledColor; - } - .mRange { - &::-webkit-slider-thumb { - @include slider-color-thumb-disabled($borderDisabledColor); - } - &::-moz-range-thumb { - @include slider-color-thumb-disabled($borderDisabledColor); - } - } - } + &:hover { + transform: scale(math.div($thumbHover, $thumb)); } } .Root { position: relative; display: flex; - cursor: pointer; align-items: center; + cursor: pointer; + + &.disabled { + cursor: not-allowed; + } } .mRangeContainer { + position: absolute; top: 0; bottom: 0; - position: absolute; } .mRange { position: absolute; inset: 0; + z-index: 1; + margin: 0; appearance: none; background: transparent; - z-index: 1; pointer-events: none; - margin: 0; &:hover + .tooltip { @include pop-in; @@ -119,46 +57,133 @@ $color-types: ( &::-webkit-slider-thumb { appearance: none; - @include slider-style-thumb; + @include thumb; } + &::-moz-range-thumb { - @include slider-style-thumb; + @include thumb; + } + + &:focus-visible { + outline: none; + + &::-webkit-slider-thumb { + outline: var(--mtf-sizing-2) solid var(--mtf-color-focus-ring); + outline-offset: var(--mtf-sizing-2); + } + + &::-moz-range-thumb { + outline: var(--mtf-sizing-2) solid var(--mtf-color-focus-ring); + outline-offset: var(--mtf-sizing-2); + } } } +// The value above the thumb, as Tooltip .tooltip { @include pop-default; - transform-origin: center left; - bottom: auto; position: absolute; - transform: translateX(-50%) translateY(-100%); - background: var(--theme-color-text-secondary-active); - padding: var(--base-sizing-4x) var(--base-sizing-8x); - border-radius: var(--theme-sizing-radius-default); - color: var(--theme-color-text-base-text-light); z-index: 1; + padding: var(--mtf-sizing-space-4) var(--mtf-sizing-space-8); + border-radius: var(--mtf-sizing-radius-md); + color: var(--mtf-color-text-on-contrast); + background-color: var(--mtf-color-surface-contrast); + transform: translateX(-50%) translateY(-100%); + transform-origin: center left; + @include typography("text-sm", "stronger"); &::after { content: " "; position: absolute; top: 100%; left: 50%; - transform: translateX(-50%) translateY(-1px); - border-width: var(--base-sizing-6x); - border-style: solid; - border-color: var(--theme-color-text-secondary-active) transparent transparent; + border: var(--mtf-sizing-6) solid transparent; + border-top-color: var(--mtf-color-surface-contrast); + transform: translateX(-50%) translateY(calc(-1 * var(--mtf-sizing-1))); } } +.track, .fill { position: absolute; - border-radius: var(--theme-sizing-radius-round); + border-radius: var(--mtf-sizing-radius-round); } .track { - position: absolute; left: 0; right: 0; - background: var(--theme-color-surface-base-base4); - border-radius: var(--theme-sizing-radius-round); + background-color: var(--mtf-color-neutral-soft); +} + +@each $size, $track, $thumb, $thumbHover, $thumbBorder, $marginTop, $marginSides in $sizes-positions { + .#{$size} { + min-height: var(--mtf-sizing-#{$thumbHover}); + + &.inFormField { + margin: var(--mtf-sizing-space-#{$marginTop}) var(--mtf-sizing-space-#{$marginSides}) 0; + } + + // A position offset (so the spacing scale): with the fixed thumb size it puts the pointer on the thumb's top edge + .tooltip { + bottom: calc(var(--mtf-sizing-#{$thumb}) - var(--mtf-sizing-space-20)); + } + + .fill, + .track, + .mRangeContainer::after { + height: var(--mtf-sizing-#{$track}); + } + + .mRange { + &::-webkit-slider-thumb { + @include thumb-size($thumb, $thumbHover, $thumbBorder); + } + + &::-moz-range-thumb { + @include thumb-size($thumb, $thumbHover, $thumbBorder); + } + } + } +} + +@each $variant in $variants { + .#{$variant} { + .fill { + background-color: var(--mtf-color-#{$variant}-solid); + } + + .mRange { + &::-webkit-slider-thumb { + border-color: var(--mtf-color-#{$variant}-solid); + } + + &::-moz-range-thumb { + border-color: var(--mtf-color-#{$variant}-solid); + } + } + } +} + +// After the variants: same specificity, so disabled wins by order +.disabled { + .track { + background-color: var(--mtf-color-surface-disabled); + } + + // Disabled fills and marks take text-disabled-soft, as Checkbox, Radio and Switch + .fill { + background-color: var(--mtf-color-text-disabled-soft); + } + + .mRange { + &::-webkit-slider-thumb { + border-color: var(--mtf-color-text-disabled-soft); + cursor: not-allowed; + } + + &::-moz-range-thumb { + border-color: var(--mtf-color-text-disabled-soft); + cursor: not-allowed; + } + } } diff --git a/src/lib/components/Slider/Slider.test.tsx b/src/lib/components/Slider/Slider.test.tsx index 46d15e7f..53584dbf 100644 --- a/src/lib/components/Slider/Slider.test.tsx +++ b/src/lib/components/Slider/Slider.test.tsx @@ -3,7 +3,7 @@ import { userEvent } from "@testing-library/user-event"; import Slider from "@/components/Slider/Slider"; import { InputSize } from "../Form/types"; import { runSnapshotDefaultsAndStandardPropsTest } from "../../../utils/testUtils"; -import { StandardPropsWithRef, Variant } from "../../../lib/types"; +import { StandardPropsWithRef, VariantV2 } from "../../../lib/types"; describe("Slider", () => { // eslint-disable-next-line @typescript-eslint/unbound-method const originalGetBoundingClientRect = Element.prototype.getBoundingClientRect; @@ -50,7 +50,7 @@ describe("Slider", () => { }); it("should be rendered with different colors considering the given variant prop", () => { - const variants: Variant[] = ["primary", "secondary", "success", "warning", "danger", "info"]; + const variants: VariantV2[] = ["neutral", "primary", "secondary", "accent", "info", "success", "warning", "danger"]; variants.forEach(variant => { const { container, unmount } = render(); expect(container.firstChild).toHaveClass(variant); diff --git a/src/lib/components/Slider/sliderValues.scss b/src/lib/components/Slider/sliderValues.scss index 33c98433..6b86e10c 100644 --- a/src/lib/components/Slider/sliderValues.scss +++ b/src/lib/components/Slider/sliderValues.scss @@ -1,7 +1,2 @@ -// size, progressHeight, thumb, thumbHover, thumbBorder, marginTop, horizontalPadding -$sizes-positions: ( - ("xs", "2x", "12x", "16x", "2x", "4x", "8x"), - ("sm", "4x", "16x", "20x", "2x", "6x", "10x"), - ("md", "6x", "18x", "22x", "3x", "8x", "10x"), - ("lg", "8x", "24x", "28x", "4x", "10x", "10x") -); +// size, track height, thumb, thumb on hover, thumb border, form field margin top, form field margin sides +$sizes-positions: (("xs", 2, 12, 16, 2, 4, 8), ("sm", 4, 16, 20, 2, 6, 10), ("md", 6, 18, 22, 3, 8, 10), ("lg", 8, 24, 28, 4, 10, 10)); diff --git a/src/lib/components/Slider/types.ts b/src/lib/components/Slider/types.ts index d29a8bca..9b628915 100644 --- a/src/lib/components/Slider/types.ts +++ b/src/lib/components/Slider/types.ts @@ -1,5 +1,5 @@ import { InputCommonProps } from "../Form/types"; -import { Size4SM, Variant } from "../../types"; +import { Size4SM, VariantV2 } from "../../types"; export type SliderBaseProps = { start?: number; @@ -14,7 +14,7 @@ export type SliderBaseProps = { export type SliderProps = Omit; export type SliderDefaultableProps = { - variant?: Variant; + variant?: VariantV2; fill?: "left" | "right" | "none"; hideTooltip?: boolean; size?: Size4SM; diff --git a/src/lib/components/SliderRange/SliderRange.module.scss b/src/lib/components/SliderRange/SliderRange.module.scss index db8ee808..fda338a6 100644 --- a/src/lib/components/SliderRange/SliderRange.module.scss +++ b/src/lib/components/SliderRange/SliderRange.module.scss @@ -11,10 +11,10 @@ } } -@each $size, $progressHeight, $thumb, $thumbHover, $thumbBorder, $marginTop, $horizontalPadding in $sizes-positions { +@each $size, $track, $thumb, $thumbHover, $thumbBorder, $marginTop, $marginSides in $sizes-positions { .#{$size} { &.inFormField { - margin: var(--base-sizing-#{$marginTop}) var(--base-sizing-#{$horizontalPadding}) 0; + margin: var(--mtf-sizing-space-#{$marginTop}) var(--mtf-sizing-space-#{$marginSides}) 0; } } } diff --git a/src/lib/components/SliderRange/SliderRange.test.tsx b/src/lib/components/SliderRange/SliderRange.test.tsx index 37b3ec10..f89e570f 100644 --- a/src/lib/components/SliderRange/SliderRange.test.tsx +++ b/src/lib/components/SliderRange/SliderRange.test.tsx @@ -3,7 +3,7 @@ import { userEvent } from "@testing-library/user-event"; import SliderRange from "@/components/SliderRange/SliderRange"; import Slider from "@/components/Slider/Slider"; import { runSnapshotDefaultsAndStandardPropsTest } from "../../../utils/testUtils"; -import { StandardPropsWithRef, Variant } from "../../../lib/types"; +import { StandardPropsWithRef, VariantV2 } from "../../../lib/types"; describe("SliderRange", () => { // eslint-disable-next-line @typescript-eslint/unbound-method const originalGetBoundingClientRect = Element.prototype.getBoundingClientRect; @@ -62,7 +62,7 @@ describe("SliderRange", () => { }); it("should be rendered with different colors considering the given variant prop", () => { - const variants: Variant[] = ["primary", "secondary", "success", "warning", "danger", "info"]; + const variants: VariantV2[] = ["neutral", "primary", "secondary", "accent", "info", "success", "warning", "danger"]; variants.forEach(variant => { const { getAllByTestId, unmount } = render(); const [slider1, slider2] = getAllByTestId("slider"); diff --git a/src/lib/components/SliderRange/types.ts b/src/lib/components/SliderRange/types.ts index 03260b22..cfd89048 100644 --- a/src/lib/components/SliderRange/types.ts +++ b/src/lib/components/SliderRange/types.ts @@ -1,5 +1,5 @@ import { InputCommonProps } from "../Form/types"; -import { Size4SM, Variant } from "../../types"; +import { Size4SM, VariantV2 } from "../../types"; export type SliderRangeProps = { start?: number; @@ -11,7 +11,7 @@ export type SliderRangeProps = { export type SliderRangeDefaultableProps = { step?: number; - variant?: Variant; + variant?: VariantV2; hideTooltip?: boolean; size?: Size4SM; }; diff --git a/src/lib/components/Switch/Switch.module.scss b/src/lib/components/Switch/Switch.module.scss index 8f6f0bcf..21975abc 100644 --- a/src/lib/components/Switch/Switch.module.scss +++ b/src/lib/components/Switch/Switch.module.scss @@ -52,7 +52,7 @@ $sizes: (("xs", 12, 16, 6, 4), ("sm", 16, 18, 8, 6), ("md", 20, 20, 10, 8), ("lg background-color: var(--mtf-color-surface-disabled); &::before { - background-color: var(--mtf-color-text-disabled); + background-color: var(--mtf-color-text-disabled-soft); } } diff --git a/src/lib/components/Table/Table.mdx b/src/lib/components/Table/Table.mdx index 0bc4fbd6..67c6196f 100644 --- a/src/lib/components/Table/Table.mdx +++ b/src/lib/components/Table/Table.mdx @@ -234,8 +234,8 @@ possible to change the title, add sorting or filtering, etc. ## Row Coloring Each row may be colored with a user defined coloring rule. `rowColorCallback` prop is used to provide a function which -will be called for each row. This function should return a string which is the color variant defined in **RowColor** -type. +will be called for each row. This function should return one of the **RowColor** values, the same as `VariantV2`: `neutral`, `primary`, +`secondary`, `accent`, `info`, `success`, `warning` or `danger`. diff --git a/src/lib/components/Table/Table.module.scss b/src/lib/components/Table/Table.module.scss index 4c79616d..35e4933d 100644 --- a/src/lib/components/Table/Table.module.scss +++ b/src/lib/components/Table/Table.module.scss @@ -1,6 +1,6 @@ @use "@styles" as *; -$row-color-variants: "primary", "secondary", "light", "success", "danger", "warning", "info"; +$row-colors: "neutral", "primary", "secondary", "accent", "info", "success", "warning", "danger"; .Root { display: table; @@ -25,14 +25,14 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn background-color: transparent; } &.solid { - background-color: var(--theme-color-surface-light-default); + background-color: var(--mtf-color-surface-subtle); } &.opposite { - background-color: var(--theme-color-surface-secondary-default); + background-color: var(--mtf-color-surface-contrast); th { - color: var(--theme-color-text-base-global-light); + color: var(--mtf-color-text-on-contrast); .thContent .sortButton { - color: var(--theme-color-text-base-global-light); + color: var(--mtf-color-text-on-contrast); } } } @@ -40,7 +40,7 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn thead { tr.trColumnFilters th { - padding: var(--base-sizing-8x); + padding: var(--mtf-sizing-space-8); .thFilterContent { display: flex; flex-direction: column; @@ -48,16 +48,16 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn } th { - color: var(--theme-color-text-base-title); - @include font("base", "sm", "700"); + color: var(--mtf-color-text-strong); + @include typography("label-md", "strongest"); overflow: hidden; .thContent { display: inline-flex; - gap: var(--base-sizing-8x); + gap: var(--mtf-sizing-space-8); .sortButton { - color: var(--theme-color-text-base-title); + color: var(--mtf-color-text-strong); } } } @@ -65,26 +65,26 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn tbody { td { - color: var(--theme-color-text-base-title); - @include font("body", "sm"); + color: var(--mtf-color-text-default); + @include typography("body-sm"); overflow-wrap: break-word; word-break: break-all; hyphens: auto; } &.striped { :where(tr.stripedRow) { - background-color: var(--theme-color-surface-base-base2); + background-color: var(--mtf-color-surface-subtle); } } tr { &.selected { @include transition(background-color); - background-color: var(--theme-color-surface-primary-negative); + background-color: var(--mtf-color-primary-soft); } - @each $variant in $row-color-variants { - &.#{$variant} { - background-color: var(--theme-color-surface-#{$variant}-negative); + @each $rowColor in $row-colors { + &.#{$rowColor} { + background-color: var(--mtf-color-#{$rowColor}-soft); } } } @@ -102,18 +102,18 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn td, th { - padding: var(--base-sizing-12x) var(--base-sizing-8x); + padding: var(--mtf-sizing-space-12) var(--mtf-sizing-space-8); &.selectable { text-align: center; - width: var(--base-sizing-32x); + width: var(--mtf-sizing-32); } } tfoot { th { - color: var(--theme-color-text-base-title); - @include font("base", "sm", "700"); + color: var(--mtf-color-text-strong); + @include typography("label-md", "strongest"); overflow: hidden; &.customFooter { @@ -125,9 +125,19 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn } } } + + // A hovered row takes its own tone's hover step, so striped, neutral and colored rows still change &.hoverable tbody { tr:hover td:not([rowspan]) { - background-color: var(--theme-color-surface-light-default); + background-color: var(--mtf-color-neutral-soft-hover); + } + tr.selected:hover td:not([rowspan]) { + background-color: var(--mtf-color-primary-soft-hover); + } + @each $rowColor in $row-colors { + tr.#{$rowColor}:hover td:not([rowspan]) { + background-color: var(--mtf-color-#{$rowColor}-soft-hover); + } } } } @@ -139,36 +149,36 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn } td, th { - border-color: var(--theme-color-border-light-default); + border-color: var(--mtf-color-border-soft); border-style: solid; - border-width: 0 var(--base-sizing-1x) var(--base-sizing-1x) 0; + border-width: 0 var(--mtf-sizing-1) var(--mtf-sizing-1) 0; &:first-child { - border-left-width: var(--base-sizing-1x); + border-left-width: var(--mtf-sizing-1); } } tbody tr:first-child td { - border-top-left-radius: var(--theme-sizing-radius-default); - border-top-right-radius: var(--theme-sizing-radius-default); - border-top-width: var(--base-sizing-1x); + border-top-left-radius: var(--mtf-sizing-radius-md); + border-top-right-radius: var(--mtf-sizing-radius-md); + border-top-width: var(--mtf-sizing-1); } thead tr:first-child th { - border-top-width: var(--base-sizing-1x); + border-top-width: var(--mtf-sizing-1); &:first-child { - border-top-left-radius: var(--theme-sizing-radius-default); + border-top-left-radius: var(--mtf-sizing-radius-md); } &:last-child { - border-top-right-radius: var(--theme-sizing-radius-default); + border-top-right-radius: var(--mtf-sizing-radius-md); } } tbody:not(:has(+ tfoot)) tr:last-child td, tfoot tr:last-child th { &:first-child { - border-bottom-left-radius: var(--theme-sizing-radius-default); + border-bottom-left-radius: var(--mtf-sizing-radius-md); } &:last-child { - border-bottom-right-radius: var(--theme-sizing-radius-default); + border-bottom-right-radius: var(--mtf-sizing-radius-md); } } @@ -194,12 +204,12 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn tfoot { &.opposite { th { - border-top-color: var(--theme-color-surface-secondary-default); + border-top-color: var(--mtf-color-surface-contrast); &:first-child { - border-left-color: var(--theme-color-surface-secondary-default); + border-left-color: var(--mtf-color-surface-contrast); } &:last-child { - border-right-color: var(--theme-color-surface-secondary-default); + border-right-color: var(--mtf-color-surface-contrast); } } } @@ -211,51 +221,52 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn border-collapse: collapse; } tr { - border-bottom: var(--base-sizing-1x) solid var(--theme-color-border-light-default); + border-bottom: var(--mtf-sizing-1) solid var(--mtf-color-border-soft); &:first-child { - border-top: var(--base-sizing-1x) solid var(--theme-color-border-light-default); + border-top: var(--mtf-sizing-1) solid var(--mtf-color-border-soft); } } } } .titleSection { - margin-bottom: var(--base-sizing-8x); + margin-bottom: var(--mtf-sizing-space-8); span { display: block; - padding: var(--base-sizing-4x) var(--base-sizing-8x); + padding: var(--mtf-sizing-space-4) var(--mtf-sizing-space-8); } } .title { - color: var(--theme-color-text-base-title); - @include font("base", "lg", "600"); + color: var(--mtf-color-text-strong); + @include typography("label-xl", "stronger"); } .subtitle { - color: var(--theme-color-text-base-subtitle); - @include font("base", "md", "500"); + color: var(--mtf-color-text-soft); + @include typography("label-lg"); } .headerRowContent { display: flex; - gap: var(--base-sizing-8x); + gap: var(--mtf-sizing-space-8); align-items: center; } .header { flex: 1; - padding: var(--base-sizing-10x) var(--base-sizing-8x); - @include font("base", "lg", "600"); + padding: var(--mtf-sizing-space-10) var(--mtf-sizing-space-8); + color: var(--mtf-color-text-strong); + @include typography("label-xl", "stronger"); } .filterInput { flex-shrink: 0; - margin: var(--base-sizing-8x) var(--base-sizing-8x) var(--base-sizing-8x) auto; + margin: var(--mtf-sizing-space-8) var(--mtf-sizing-space-8) var(--mtf-sizing-space-8) auto; } .footerForNumbers { - padding: var(--base-sizing-8x) var(--base-sizing-12x); + padding: var(--mtf-sizing-space-8) var(--mtf-sizing-space-12); align-items: center; display: flex; @@ -282,8 +293,8 @@ $row-color-variants: "primary", "secondary", "light", "success", "danger", "warn } .totalRecordsLabel { - color: var(--theme-color-text-base-title); - @include font("body", "sm"); + color: var(--mtf-color-text-default); + @include typography("body-sm"); } } diff --git a/src/lib/components/Table/Table.test.tsx b/src/lib/components/Table/Table.test.tsx index bceafc6c..e827b783 100644 --- a/src/lib/components/Table/Table.test.tsx +++ b/src/lib/components/Table/Table.test.tsx @@ -249,7 +249,7 @@ describe("Table", () => { }); it("should render correct row class for each RowColor variant", () => { - const rowColors: RowColor[] = ["primary", "secondary", "light", "success", "danger", "warning", "info"]; + const rowColors: RowColor[] = ["neutral", "primary", "secondary", "accent", "info", "success", "warning", "danger"]; const { getTableBody, rerender } = renderExt( "primary"} />, ); diff --git a/src/lib/components/Table/types.ts b/src/lib/components/Table/types.ts index b8cabe33..2ab2bea5 100644 --- a/src/lib/components/Table/types.ts +++ b/src/lib/components/Table/types.ts @@ -1,4 +1,5 @@ import { Dispatch, ReactNode, SetStateAction } from "react"; +import { VariantV2 } from "../../types"; export type ResolvedCellSpan = { colSpan: number; @@ -188,5 +189,5 @@ export const TableContextDefaultValues: TableContextType = { // Other // -export type RowColor = "primary" | "secondary" | "light" | "success" | "danger" | "warning" | "info"; +export type RowColor = VariantV2; export type SortDirection = "asc" | "desc"; diff --git a/src/lib/styles/tokens/compare/Drawer.compare-stories.tsx b/src/lib/styles/tokens/compare/Drawer.compare-stories.tsx new file mode 100644 index 00000000..bc7324e2 --- /dev/null +++ b/src/lib/styles/tokens/compare/Drawer.compare-stories.tsx @@ -0,0 +1,67 @@ +import type { Meta, StoryObj } from "@storybook/nextjs"; +import nextStyles from "@/components/Drawer/Drawer.module.scss"; +import { DrawerProps } from "@/components/Drawer/types"; +import { MotifIconButton } from "@/components/Motif/Icon"; +import currentStyles from "./baseline/Batch13/Drawer/DrawerBaseline.module.scss"; +import { sanitizeModuleRootClasses } from "../../../../utils/cssUtils"; +import { CompareSection, TokenCompare } from "./TokenCompare"; + +type Row = Omit & { text?: string }; + +// Drawer portals into document.body with position: fixed, so the preview draws the same markup in place with each +// version's own classes +const preview = + (styles: Readonly>) => + ({ position = "left", size = "sm", title, closable, includePadding, text }: Row) => ( +
+ +
+ ); + +const TEXT = "Filters apply to every list on the page. Clear them to see all the records again."; +const base: Row = { title: "Filters", closable: true, includePadding: true, text: TEXT }; + +const sections: CompareSection[] = [ + { + title: "Content", + rows: [ + { label: "default", props: base }, + { label: "title only", props: { ...base, closable: false } }, + { label: "no header", props: { ...base, title: undefined, closable: false } }, + { label: "no padding", props: { ...base, includePadding: false } }, + ], + }, + { + title: "position", + note: "Only the inner edges are rounded; the box keeps its own height here.", + rows: (["left", "right"] as const).map(position => ({ label: position, props: { ...base, position } })), + }, + { + title: "Scrolling content", + rows: [{ label: "long text", props: { ...base, text: Array(10).fill(TEXT).join(" ") } }], + }, +]; + +const meta: Meta = { + title: "Token Compare/Drawer", + component: TokenCompare, + parameters: { layout: "padded" }, +}; + +export default meta; + +export const Drawer_: StoryObj = { + name: "Drawer", + render: () => , +}; diff --git a/src/lib/styles/tokens/compare/Slider.compare-stories.tsx b/src/lib/styles/tokens/compare/Slider.compare-stories.tsx new file mode 100644 index 00000000..36c0cd17 --- /dev/null +++ b/src/lib/styles/tokens/compare/Slider.compare-stories.tsx @@ -0,0 +1,58 @@ +import type { Meta, StoryObj } from "@storybook/nextjs"; +import { ComponentType } from "react"; +import Slider from "@/components/Slider"; +import SliderRange from "@/components/SliderRange"; +import SliderBaseline from "./baseline/Batch13/Slider"; +import SliderRangeBaseline from "./baseline/Batch13/SliderRange"; +import { CompareSection, TokenCompare } from "./TokenCompare"; + +type Props = Record; +type AnySlider = ComponentType; + +const SIZES = ["xs", "sm", "md", "lg"] as const; +// The baseline still takes the old variants; secondary is gray there and the brand color in the new one +const VARIANTS = ["neutral", "primary", "secondary", "accent", "info", "success", "warning", "danger"] as const; + +const sections = (value: unknown): CompareSection[] => [ + { title: "Sizes", rows: SIZES.map(size => ({ label: size, props: { size, value } })) }, + { + title: "variant", + note: "Old secondary was gray: that is neutral now, and secondary is the brand color. neutral and accent are new.", + rows: VARIANTS.map(variant => ({ label: variant, props: { variant, value } })), + }, + { + title: "States", + rows: [ + { label: "disabled", props: { disabled: true, value } }, + { label: "readOnly", props: { readOnly: true, value } }, + { label: "fill=right", props: { fill: "right", value } }, + ], + }, +]; + +const meta: Meta = { + title: "Token Compare/Slider", + component: TokenCompare, + parameters: { layout: "padded" }, +}; + +export default meta; + +type Story = StoryObj; + +export const Slider_: Story = { + name: "Slider", + render: () => , +}; + +export const SliderRange_: Story = { + name: "SliderRange", + render: () => ( + + ), +}; diff --git a/src/lib/styles/tokens/compare/Table.compare-stories.tsx b/src/lib/styles/tokens/compare/Table.compare-stories.tsx new file mode 100644 index 00000000..5b06c4a3 --- /dev/null +++ b/src/lib/styles/tokens/compare/Table.compare-stories.tsx @@ -0,0 +1,85 @@ +import type { Meta, StoryObj } from "@storybook/nextjs"; +import { ComponentType } from "react"; +import Table from "@/components/Table"; +import TableBaseline from "./baseline/Batch13/Table"; +import { CompareSection, TokenCompare } from "./TokenCompare"; + +type Props = Record; +type AnyTable = ComponentType; +type RowData = { name: string; city: string; age: number; color?: string }; + +const columns = [ + { title: "Name", dataKey: "name", sorting: true }, + { title: "City", dataKey: "city" }, + { title: "Age", dataKey: "age", footer: { render: () => "Total 3" } }, +]; +const data: RowData[] = [ + { name: "Ada", city: "Ankara", age: 34, color: "primary" }, + { name: "Can", city: "İzmir", age: 28, color: "secondary" }, + { name: "Ece", city: "Bursa", age: 41, color: "success" }, +]; +const base: Props = { columns, data, fluid: true }; +const ROW_COLORS = ["neutral", "primary", "secondary", "accent", "info", "success", "warning", "danger"]; + +const sections: CompareSection[] = [ + { + title: "Content", + rows: [ + { label: "default", props: base }, + { label: "title · subtitle", props: { ...base, title: "Team", subtitle: "3 people" } }, + { label: "striped", props: { ...base, striped: true } }, + { label: "selectable", props: { ...base, selectable: true, selectionKey: "name", defaultSelectedIds: ["Can"] } }, + ], + }, + { + title: "Filters and pages", + rows: [ + { + label: "filterableTable · column filters", + props: { ...base, filterableTable: true, columns: columns.map(column => ({ ...column, filter: true })) }, + }, + { label: "pagination", props: { ...base, data: [...data, ...data, ...data], pagination: { rowsPerPage: 3 } } }, + ], + }, + { + title: "Header background", + rows: (["transparent", "solid", "opposite"] as const).map(bg => ({ + label: bg, + props: { ...base, headerColsBackground: bg, footerColsBackground: bg }, + })), + }, + { + title: "border", + rows: (["cellBorders", "rowBorders"] as const).flatMap(border => [ + { label: border, props: { ...base, border } }, + { label: `${border} · opposite`, props: { ...base, border, headerColsBackground: "opposite", footerColsBackground: "opposite" } }, + ]), + }, + { + title: "Row colors", + note: "RowColor is VariantV2: light became neutral, accent is new, secondary is the brand color (it was gray). Today has no neutral or accent, so those rows are white there.", + rows: [ + { + label: "rowColorCallback", + props: { + ...base, + data: ROW_COLORS.map((color, i) => ({ name: color, city: "—", age: 20 + i, color })), + rowColorCallback: (row: RowData) => row.color, + }, + }, + ], + }, +]; + +const meta: Meta = { + title: "Token Compare/Table", + component: TokenCompare, + parameters: { layout: "padded" }, +}; + +export default meta; + +export const Table_: StoryObj = { + name: "Table", + render: () => , +}; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/Drawer.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/Drawer.tsx new file mode 100644 index 00000000..9adece74 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/Drawer.tsx @@ -0,0 +1,67 @@ +"use client"; + +import styles from "./DrawerBaseline.module.scss"; +import { createPortal } from "react-dom"; +import useModalOverlay from "src/lib/hooks/useModalOverlay"; +import { PropsWithRefAndChildren } from "src/lib/types"; +import { DrawerProps } from "./types"; +import { sanitizeModuleRootClasses } from "src/utils/cssUtils"; +import usePropsWithThemeDefaults from "src/lib/motif/hooks/usePropsWithThemeDefaults"; +import { MotifIconButton } from "@/components/Motif/Icon"; + +const Drawer = (props: PropsWithRefAndChildren) => { + const { + title, + open, + onClose, + onAfterClose, + children, + position = "left", + size = "md", + closable, + removeBackdrop, + includePadding, + ref, + style, + className, + } = usePropsWithThemeDefaults("Drawer", props); + + const { attached, visible, hide, rootRef, dialogRef, insideProps } = useModalOverlay({ + open: !!open, + rootRef: ref, + onClose, + onAfterClose, + duration: 300, + closeOnOutsideClick: closable, + closeOnEscape: closable, + }); + + const classNames = sanitizeModuleRootClasses(styles, className, [ + visible && "show", + position, + size, + removeBackdrop && "removeBackdrop", + includePadding && "includePadding", + ]); + + return ( + attached && + createPortal( +
+ +
, + document.body, + ) + ); +}; + +Drawer.displayName = "Drawer"; +export default Drawer; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/DrawerBaseline.module.scss b/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/DrawerBaseline.module.scss new file mode 100644 index 00000000..3d422237 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/DrawerBaseline.module.scss @@ -0,0 +1,104 @@ +@use "@styles" as *; + +$sizes: ( + //sizeName, width, height + ("sm", "320x", "256x"), + ("md", "480x", "400x"), + ("lg", "760x", "600x") +); + +.Root { + position: fixed; + inset: 0; + background-color: var(--base-colors-black-black-overlay50); + z-index: z-layer("modal"); + @include fade-default; + + &.show { + @include fade-in; + } + + &.removeBackdrop { + background-color: transparent; + } +} + +.drawer { + display: flex; + flex-direction: column; + position: fixed; + background: var(--theme-color-surface-base-global-light); + border: solid var(--base-sizing-1x) var(--theme-color-border-light-default); + max-width: 100%; + max-height: 100%; + overflow: hidden; + @include shadow(4); + + .left & { + @include slide-default("left"); + inset: 0 auto 0 0; + border-radius: 0 var(--theme-sizing-radius-default) var(--theme-sizing-radius-default) 0; + } + + .right & { + @include slide-default("right"); + inset: 0 0 0 auto; + border-radius: var(--theme-sizing-radius-default) 0 0 var(--theme-sizing-radius-default); + } + + .top & { + @include slide-default("top"); + inset: 0 0 auto; + border-radius: 0 0 var(--theme-sizing-radius-default) var(--theme-sizing-radius-default); + } + + .bottom & { + @include slide-default("bottom"); + inset: auto 0 0; + border-radius: var(--theme-sizing-radius-default) var(--theme-sizing-radius-default) 0 0; + } + + .show & { + @include slide-in; + } + + @each $size, $width, $height in $sizes { + .left.#{$size} &, + .right.#{$size} & { + width: min(var(--base-sizing-#{$width}), 85vw); + } + + .top.#{$size} &, + .bottom.#{$size} & { + height: min(var(--base-sizing-#{$height}), 85vh); + } + } +} + +.header { + display: flex; + align-items: flex-start; + gap: var(--base-sizing-16x); + padding: var(--base-sizing-16x); +} + +.headerTitle { + flex: 1; + color: var(--theme-color-text-base-title); + overflow-wrap: break-word; + @include font("base", "lg", "700"); +} + +.closeButton { + margin-left: auto; +} + +.content { + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; +} + +.includePadding .content { + padding: var(--base-sizing-16x); +} diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/index.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/index.ts new file mode 100644 index 00000000..e20a1869 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/index.ts @@ -0,0 +1 @@ +export { default } from "./Drawer"; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/types.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/types.ts new file mode 100644 index 00000000..5ef88181 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Drawer/types.ts @@ -0,0 +1,18 @@ +import { OverlayCloseReason, Size3 } from "src/lib/types"; + +export type DrawerPosition = "top" | "bottom" | "left" | "right"; + +export type DrawerProps = { + title?: string; + open?: boolean; + onClose?: (reason: OverlayCloseReason) => void; + onAfterClose?: () => void; + includePadding?: boolean; +} & DrawerDefaultableProps; + +export type DrawerDefaultableProps = { + position?: DrawerPosition; + size?: Size3; + closable?: boolean; + removeBackdrop?: boolean; +}; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Slider/Slider.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/Slider.tsx new file mode 100644 index 00000000..f1edf77c --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/Slider.tsx @@ -0,0 +1,157 @@ +"use client"; + +import styles from "./SliderBaseline.module.scss"; +import type { MouseEvent } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { calculateRealClickedValue, normalizeValueByStep } from "./helper"; +import { useRegisterFormField } from "@/components/Form/context/useRegisterFormField"; +import { PropsWithRef } from "src/lib/types"; +import { SliderBaseProps, SliderProps } from "./types"; +import { sanitizeModuleRootClasses } from "src/utils/cssUtils"; +import usePropsWithThemeDefaults from "src/lib/motif/hooks/usePropsWithThemeDefaults"; +import { isNotAvailable } from "src/utils/utils"; + +export const SliderComponent = (p: PropsWithRef) => { + const props = usePropsWithThemeDefaults("Slider", p); + const { + start = 0, + end = 100, + step = 1, + min = start, + max = end, + fill = "left", + style, + className, + variant = "primary", + hideTooltip, + onChange, + ref, + inRangeSelector, + } = props; + const avgThumbWidth = 20; + const maxSelectableValue = useMemo(() => normalizeValueByStep(max, step, min, "floor"), [max, min, step]); + + const getCorrectValue = useCallback( + (val?: number) => + !isNotAvailable(val) + ? Number(Math.max(min, Math.min(normalizeValueByStep(val as number, step, min), maxSelectableValue)).toFixed(1)) + : min, + [maxSelectableValue, min, step], + ); + const value = useMemo(() => getCorrectValue(props.value as number), [getCorrectValue, props.value]); + + if (start > end || min > max || min < start || max > end) { + throw new Error("Range error! Invalid range value. min-max values should be in the range of start-end."); + } + + const calculateTooltipPosition = useCallback( + (val: number) => { + const correctValue = getCorrectValue(val); + const thumbPosition = ((correctValue - min) / (max - min || 1)) * 100; + const offset = avgThumbWidth / 2 - thumbPosition * 0.2; + return `calc(${thumbPosition}% + ${offset}px)`; + }, + [getCorrectValue, min, max], + ); + + const [rangeValue, setRangeValue] = useState(value); + const { size, disabled, readOnly, onFormFieldValueUpdate, name, inFormField } = useRegisterFormField({ + props: { ...props, value }, + defaultValue: min, + valueStateSetter: setRangeValue, + dontRegister: inRangeSelector, + }); + + useEffect(() => { + setRangeValue(getCorrectValue(value)); + onFormFieldValueUpdate?.(getCorrectValue(value)); + }, [getCorrectValue, onFormFieldValueUpdate, value]); + + const handleValueChange = useCallback( + (valueRetrieved: number) => { + if (readOnly) return; + const correctValue = getCorrectValue(valueRetrieved); + if (correctValue !== rangeValue) { + setRangeValue(correctValue); + onChange?.(correctValue); + onFormFieldValueUpdate?.(correctValue); + } + }, + [getCorrectValue, onChange, onFormFieldValueUpdate, rangeValue, readOnly], + ); + + const onClick = useCallback( + (e: MouseEvent) => { + e.stopPropagation(); + if (e.target instanceof HTMLInputElement) return; + + const clickedValue = calculateRealClickedValue(start, end, e); + handleValueChange(clickedValue); + }, + [handleValueChange, end, start], + ); + + const fillStyle = useMemo(() => { + const rate = 100 / (end - start); + if (fill === "left") { + return { left: `${(min - start) * rate}%`, width: `${(rangeValue - min) * rate}%` }; + } else if (fill === "right") { + return { left: `${(rangeValue - start) * rate}%`, width: `${(max - rangeValue) * rate}%` }; + } else { + return { display: "none" }; + } + }, [end, fill, max, min, rangeValue, start]); + + const rangeContainerStyle = useMemo(() => { + const widthPerc = ((max - min) / (end - start)) * 100; + const leftPerc = ((min - start) / (end - start)) * 100; + return { + width: "calc(" + widthPerc.toFixed(2) + "%" + " + " + avgThumbWidth + "px)", + left: "calc(" + leftPerc.toFixed(2) + "%" + " - " + avgThumbWidth / 2 + "px)", + }; + }, [end, max, min, start]); + + const classNames = sanitizeModuleRootClasses(styles, className, [ + variant, + size, + (disabled || readOnly) && "disabled", + inFormField && "inFormField", + ]); + + return ( +
+
+
+
+ handleValueChange(Number(e.target.value))} + value={rangeValue} + disabled={disabled} + readOnly={readOnly} + aria-readonly={readOnly} + /> + {!hideTooltip && ( +
+ {rangeValue} +
+ )} +
+
+ ); +}; + +const Slider = (props: PropsWithRef) => ; +Object.assign(Slider, { displayName: "Slider" }); +export default Slider; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Slider/SliderBaseline.module.scss b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/SliderBaseline.module.scss new file mode 100644 index 00000000..19bfa4e9 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/SliderBaseline.module.scss @@ -0,0 +1,164 @@ +@use "@styles" as *; +@use "./sliderValues" as *; + +// variant, color, border color, disabled, border disabled +$color-types: ( + ("secondary", var(--theme-color-surface-base-base7), var(--theme-color-surface-base-base7), var(--theme-color-surface-base-base6), var(--theme-color-surface-base-base6)), + ("warning", var(--theme-color-surface-warning-default), var(--theme-color-surface-warning-default), var(--theme-color-surface-warning-inverse), var(--theme-color-border-warning-disabled)), + ("success", var(--theme-color-surface-success-default), var(--theme-color-surface-success-default), var(--theme-color-surface-success-inverse), var(--theme-color-border-success-disabled)), + ("danger", var(--theme-color-surface-danger-default), var(--theme-color-surface-danger-default), var(--theme-color-surface-danger-inverse), var(--theme-color-border-danger-disabled)), + ("primary", var(--theme-color-surface-primary-default), var(--theme-color-surface-primary-default), var(--theme-color-surface-primary-inverse), var(--theme-color-border-primary-disabled)), + ("info", var(--theme-color-surface-info-default), var(--theme-color-surface-info-default), var(--theme-color-surface-info-inverse), var(--theme-color-border-info-disabled)) +); + +@mixin slider-style-thumb { + border-radius: var(--theme-sizing-radius-round); + background: var(--theme-color-surface-base-bg-light); + box-shadow: 0 var(--base-sizing-1x) var(--base-sizing-2x) var(--base-sizing-1x) var(--base-colors-black-black-overlay15); + cursor: pointer; + @include transition(transform); + pointer-events: auto; + box-sizing: border-box; +} +@mixin slider-size-thumb($thumbSize, $thumbBorderSize, $thumbHoverSize) { + height: var(--base-sizing-#{$thumbSize}); + width: var(--base-sizing-#{$thumbSize}); + border: var(--base-sizing-#{$thumbBorderSize}) solid; + &:hover { + transform: scale(calc(var(--base-sizing-#{$thumbHoverSize}) / var(--base-sizing-#{$thumbSize}))); + } +} +@mixin slider-color-thumb-disabled($borderDisabledColor) { + cursor: not-allowed; + border-color: $borderDisabledColor; +} + +@each $size, $progressHeight, $thumb, $thumbHover, $thumbBorder, $marginTop, $horizontalPadding in $sizes-positions { + .#{$size} { + &.Root { + min-height: var(--base-sizing-#{$thumbHover}); + + &.inFormField { + margin: var(--base-sizing-#{$marginTop}) var(--base-sizing-#{$horizontalPadding}) 0; + } + } + .tooltip { + bottom: calc(var(--base-sizing-#{$thumb}) - var(--base-sizing-20x)); + } + .fill, + .track, + .mRangeContainer::after { + height: var(--base-sizing-#{$progressHeight}); + } + .mRange { + &::-webkit-slider-thumb { + @include slider-size-thumb($thumb, $thumbBorder, $thumbHover); + } + &::-moz-range-thumb { + @include slider-size-thumb($thumb, $thumbBorder, $thumbHover); + } + } + } +} + +@each $variant, $color, $borderColor, $disabledColor, $borderDisabledColor in $color-types { + .#{$variant} { + .fill { + background: $color; + } + .mRange { + &::-webkit-slider-thumb { + border-color: $borderColor; + } + &::-moz-range-thumb { + border-color: $borderColor; + } + } + &.disabled { + cursor: not-allowed; + .fill { + background: $disabledColor; + } + .mRange { + &::-webkit-slider-thumb { + @include slider-color-thumb-disabled($borderDisabledColor); + } + &::-moz-range-thumb { + @include slider-color-thumb-disabled($borderDisabledColor); + } + } + } + } +} + +.Root { + position: relative; + display: flex; + cursor: pointer; + align-items: center; +} + +.mRangeContainer { + top: 0; + bottom: 0; + position: absolute; +} + +.mRange { + position: absolute; + inset: 0; + appearance: none; + background: transparent; + z-index: 1; + pointer-events: none; + margin: 0; + + &:hover + .tooltip { + @include pop-in; + } + + &::-webkit-slider-thumb { + appearance: none; + @include slider-style-thumb; + } + &::-moz-range-thumb { + @include slider-style-thumb; + } +} + +.tooltip { + @include pop-default; + transform-origin: center left; + bottom: auto; + position: absolute; + transform: translateX(-50%) translateY(-100%); + background: var(--theme-color-text-secondary-active); + padding: var(--base-sizing-4x) var(--base-sizing-8x); + border-radius: var(--theme-sizing-radius-default); + color: var(--theme-color-text-base-text-light); + z-index: 1; + + &::after { + content: " "; + position: absolute; + top: 100%; + left: 50%; + transform: translateX(-50%) translateY(-1px); + border-width: var(--base-sizing-6x); + border-style: solid; + border-color: var(--theme-color-text-secondary-active) transparent transparent; + } +} + +.fill { + position: absolute; + border-radius: var(--theme-sizing-radius-round); +} + +.track { + position: absolute; + left: 0; + right: 0; + background: var(--theme-color-surface-base-base4); + border-radius: var(--theme-sizing-radius-round); +} diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Slider/helper.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/helper.ts new file mode 100644 index 00000000..eefa00d3 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/helper.ts @@ -0,0 +1,10 @@ +import type { MouseEvent } from "react"; + +export const normalizeValueByStep = (value: number, step: number, min: number, func?: "floor" | "round") => { + return Math[func ?? "round"]((value - min) / step) * step + min; +}; +export const calculateRealClickedValue = (min: number, max: number, e: MouseEvent) => { + const rect = e.currentTarget.getBoundingClientRect(); + const rate = (e.clientX - rect.left) / rect.width; + return Math.round(min + (max - min) * rate); +}; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Slider/index.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/index.ts new file mode 100644 index 00000000..8e109100 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/index.ts @@ -0,0 +1 @@ +export { default } from "./Slider"; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Slider/sliderValues.scss b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/sliderValues.scss new file mode 100644 index 00000000..33c98433 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/sliderValues.scss @@ -0,0 +1,7 @@ +// size, progressHeight, thumb, thumbHover, thumbBorder, marginTop, horizontalPadding +$sizes-positions: ( + ("xs", "2x", "12x", "16x", "2x", "4x", "8x"), + ("sm", "4x", "16x", "20x", "2x", "6x", "10x"), + ("md", "6x", "18x", "22x", "3x", "8x", "10x"), + ("lg", "8x", "24x", "28x", "4x", "10x", "10x") +); diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Slider/types.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/types.ts new file mode 100644 index 00000000..465ca562 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Slider/types.ts @@ -0,0 +1,21 @@ +import { InputCommonProps } from "@/components/Form/types"; +import { Size4SM, Variant } from "src/lib/types"; + +export type SliderBaseProps = { + start?: number; + end?: number; + min?: number; + max?: number; + step?: number; + inRangeSelector?: boolean; +} & Omit & + SliderDefaultableProps; + +export type SliderProps = Omit; + +export type SliderDefaultableProps = { + variant?: Variant; + fill?: "left" | "right" | "none"; + hideTooltip?: boolean; + size?: Size4SM; +}; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/SliderRange.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/SliderRange.tsx new file mode 100644 index 00000000..5eee2940 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/SliderRange.tsx @@ -0,0 +1,144 @@ +"use client"; + +import styles from "./SliderRangeBaseline.module.scss"; + +import { SliderComponent } from "../Slider/Slider"; +import type { MouseEvent } from "react"; +import { useCallback, useMemo, useState } from "react"; +import { calculateRealClickedValue, normalizeValueByStep } from "../Slider/helper"; +import { useRegisterFormField } from "@/components/Form/context/useRegisterFormField"; +import useDeepCompareEffect from "use-deep-compare-effect"; +import { PropsWithRef } from "src/lib/types"; +import { SliderRangeProps } from "./types"; +import usePropsWithThemeDefaults from "src/lib/motif/hooks/usePropsWithThemeDefaults"; +import { sanitizeModuleRootClasses } from "src/utils/cssUtils"; +import { isNotAvailable } from "src/utils/utils"; + +const SliderRange = (p: PropsWithRef) => { + const props = usePropsWithThemeDefaults("SliderRange", p); + const { + start = 0, + end = 100, + step = 1, + min = start, + max = end, + hideTooltip, + variant = "primary", + onChange, + ref, + style, + className, + } = props; + + const maxSelectableValue = useMemo(() => normalizeValueByStep(max, step, min, "floor"), [max, min, step]); + + const getCorrectValue = useCallback( + (sliderIndex: 0 | 1, val?: number) => + !isNotAvailable(val) + ? Math.max(min, Math.min(normalizeValueByStep(val as number, step, min), maxSelectableValue)) + : sliderIndex === 0 + ? min + : maxSelectableValue, + [maxSelectableValue, min, step], + ); + const value = useMemo(() => { + const arr = Array.isArray(props.value) ? (props.value as (number | undefined)[]) : []; + return [getCorrectValue(0, arr[0]), getCorrectValue(1, arr[1])]; + }, [getCorrectValue, props.value]); + + const [rangeValue, setRangeValue] = useState(value); + const { size, disabled, readOnly, onFormFieldValueUpdate, inFormField } = useRegisterFormField({ + props, + defaultValue: [min, maxSelectableValue], + valueStateSetter: setRangeValue, + }); + + const applyValueUpdates = useCallback( + (newRangeValue: number[], maybeTriggerOnChange: boolean) => { + setRangeValue(newRangeValue); + onFormFieldValueUpdate?.(newRangeValue); + maybeTriggerOnChange && onChange?.(newRangeValue); + }, + [onChange, onFormFieldValueUpdate], + ); + + const onClick = useCallback( + (e: MouseEvent) => { + e.stopPropagation(); + if (e.target instanceof HTMLInputElement) return; + + const clickedValue = calculateRealClickedValue(start, end, e); + if (clickedValue > rangeValue[1]) { + const correctValue = getCorrectValue(1, clickedValue); + if (correctValue !== rangeValue[1]) { + applyValueUpdates([rangeValue[0], correctValue], true); + } + } else { + const correctValue = getCorrectValue(0, clickedValue); + if (correctValue !== rangeValue[0]) { + applyValueUpdates([correctValue, rangeValue[1]], true); + } + } + }, + [applyValueUpdates, getCorrectValue, end, start, rangeValue], + ); + + const changeHandler = useCallback( + (val: number, firstSlider?: boolean) => { + if (firstSlider) { + applyValueUpdates([val, rangeValue[1]], true); + } else { + applyValueUpdates([rangeValue[0], val], true); + } + }, + [applyValueUpdates, rangeValue], + ); + + useDeepCompareEffect(() => { + const firstVal = getCorrectValue(0, value[0]); + const secondVal = getCorrectValue(1, value[1]); + applyValueUpdates([firstVal, secondVal], false); + }, [applyValueUpdates, getCorrectValue, max, min, value]); + + const classes = sanitizeModuleRootClasses(styles, className, [size, inFormField && "inFormField"]); + + return ( +
+ changeHandler(val as number, true)} + fill="none" + value={rangeValue[0]} + {...(rangeValue[1] === min && { style: { visibility: "hidden" } })} + hideTooltip={hideTooltip} + variant={variant} + size={size} + disabled={disabled} + readOnly={readOnly} + step={step} + /> + changeHandler(val as number)} + value={rangeValue[1]} + hideTooltip={hideTooltip} + variant={variant} + size={size} + disabled={disabled} + readOnly={readOnly} + step={step} + style={{ ...(rangeValue[0] === rangeValue[1] && rangeValue[1] !== min && { visibility: "hidden" }) }} + /> +
+ ); +}; + +export default SliderRange; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/SliderRangeBaseline.module.scss b/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/SliderRangeBaseline.module.scss new file mode 100644 index 00000000..db8ee808 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/SliderRangeBaseline.module.scss @@ -0,0 +1,20 @@ +@use "../Slider/sliderValues" as *; + +.Root { + position: relative; + + > :last-child { + position: absolute; + top: 0; + left: 0; + right: 0; + } +} + +@each $size, $progressHeight, $thumb, $thumbHover, $thumbBorder, $marginTop, $horizontalPadding in $sizes-positions { + .#{$size} { + &.inFormField { + margin: var(--base-sizing-#{$marginTop}) var(--base-sizing-#{$horizontalPadding}) 0; + } + } +} diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/index.ts b/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/index.ts new file mode 100644 index 00000000..208c72e3 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/index.ts @@ -0,0 +1 @@ +export { default } from "./SliderRange"; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/types.ts b/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/types.ts new file mode 100644 index 00000000..af906fa8 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/SliderRange/types.ts @@ -0,0 +1,17 @@ +import { InputCommonProps } from "@/components/Form/types"; +import { Size4SM, Variant } from "src/lib/types"; + +export type SliderRangeProps = { + start?: number; + end?: number; + min?: number; + max?: number; +} & Omit & + SliderRangeDefaultableProps; + +export type SliderRangeDefaultableProps = { + step?: number; + variant?: Variant; + hideTooltip?: boolean; + size?: Size4SM; +}; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/Table.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/Table.tsx new file mode 100644 index 00000000..71bf2eba --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/Table.tsx @@ -0,0 +1,58 @@ +import { RowColor, TableProps } from "./types"; +import { TableProvider } from "./TableContext"; +import TableContainer from "./components/TableContainer"; +import { PropsWithRef } from "src/lib/types"; +import usePropsWithThemeDefaults from "src/lib/motif/hooks/usePropsWithThemeDefaults"; + +const Table = (props: PropsWithRef, HTMLDivElement>) => { + const { + columns, + data, + totalRecords, + onSortChange, + onFilterChange, + onColumnFilterChange, + onPageChange, + showFixedRowNumbers, + pagination, + selectable, + selectionKey, + defaultSelectedIds, + onSelectionChange, + filterableTable, + filterPlaceholder, + disableFilterOnKeyPress, + reflectDataChanges, + rowColorCallback, + ref, + ...rest + } = usePropsWithThemeDefaults("Table", props); + + return ( + RowColor | undefined} + > + + + ); +}; + +Table.displayName = "Table"; +export default Table; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/TableBaseline.module.scss b/src/lib/styles/tokens/compare/baseline/Batch13/Table/TableBaseline.module.scss new file mode 100644 index 00000000..4c79616d --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/TableBaseline.module.scss @@ -0,0 +1,292 @@ +@use "@styles" as *; + +$row-color-variants: "primary", "secondary", "light", "success", "danger", "warning", "info"; + +.Root { + display: table; + &.distributeColsEvenly table { + table-layout: fixed; + } + &.fluid { + &, + table { + width: 100%; + } + } + + table { + text-align: left; + border-spacing: 0; + } + + thead, + tfoot { + &.transparent { + background-color: transparent; + } + &.solid { + background-color: var(--theme-color-surface-light-default); + } + &.opposite { + background-color: var(--theme-color-surface-secondary-default); + th { + color: var(--theme-color-text-base-global-light); + .thContent .sortButton { + color: var(--theme-color-text-base-global-light); + } + } + } + } + + thead { + tr.trColumnFilters th { + padding: var(--base-sizing-8x); + .thFilterContent { + display: flex; + flex-direction: column; + } + } + + th { + color: var(--theme-color-text-base-title); + @include font("base", "sm", "700"); + overflow: hidden; + + .thContent { + display: inline-flex; + gap: var(--base-sizing-8x); + + .sortButton { + color: var(--theme-color-text-base-title); + } + } + } + } + + tbody { + td { + color: var(--theme-color-text-base-title); + @include font("body", "sm"); + overflow-wrap: break-word; + word-break: break-all; + hyphens: auto; + } + &.striped { + :where(tr.stripedRow) { + background-color: var(--theme-color-surface-base-base2); + } + } + + tr { + &.selected { + @include transition(background-color); + background-color: var(--theme-color-surface-primary-negative); + } + @each $variant in $row-color-variants { + &.#{$variant} { + background-color: var(--theme-color-surface-#{$variant}-negative); + } + } + } + } + + tr { + &.loading, + &.emptyData { + pointer-events: none; + } + &.headerRow th { + padding: 0; + } + } + + td, + th { + padding: var(--base-sizing-12x) var(--base-sizing-8x); + + &.selectable { + text-align: center; + width: var(--base-sizing-32x); + } + } + + tfoot { + th { + color: var(--theme-color-text-base-title); + @include font("base", "sm", "700"); + overflow: hidden; + + &.customFooter { + padding: 0; + } + + &[colspan] { + text-align: right; + } + } + } + &.hoverable tbody { + tr:hover td:not([rowspan]) { + background-color: var(--theme-color-surface-light-default); + } + } +} + +.bordered { + &.cellBorders { + table:has(thead [colspan], thead [rowspan], tbody [colspan], tbody [rowspan]) { + border-collapse: collapse; + } + td, + th { + border-color: var(--theme-color-border-light-default); + border-style: solid; + border-width: 0 var(--base-sizing-1x) var(--base-sizing-1x) 0; + &:first-child { + border-left-width: var(--base-sizing-1x); + } + } + + tbody tr:first-child td { + border-top-left-radius: var(--theme-sizing-radius-default); + border-top-right-radius: var(--theme-sizing-radius-default); + border-top-width: var(--base-sizing-1x); + } + thead tr:first-child th { + border-top-width: var(--base-sizing-1x); + &:first-child { + border-top-left-radius: var(--theme-sizing-radius-default); + } + &:last-child { + border-top-right-radius: var(--theme-sizing-radius-default); + } + } + + tbody:not(:has(+ tfoot)) tr:last-child td, + tfoot tr:last-child th { + &:first-child { + border-bottom-left-radius: var(--theme-sizing-radius-default); + } + &:last-child { + border-bottom-right-radius: var(--theme-sizing-radius-default); + } + } + + // custom footer + tfoot tr:nth-child(2) th { + padding: 0; + } + + thead + tbody tr:first-child td { + border-top-left-radius: 0; + border-top-right-radius: 0; + border-top-width: 0; + } + + // Body with footer + tbody:has(+ tfoot) { + tr:last-child td { + border-radius: 0; + } + } + + thead, + tfoot { + &.opposite { + th { + border-top-color: var(--theme-color-surface-secondary-default); + &:first-child { + border-left-color: var(--theme-color-surface-secondary-default); + } + &:last-child { + border-right-color: var(--theme-color-surface-secondary-default); + } + } + } + } + } + + &.rowBorders { + table { + border-collapse: collapse; + } + tr { + border-bottom: var(--base-sizing-1x) solid var(--theme-color-border-light-default); + &:first-child { + border-top: var(--base-sizing-1x) solid var(--theme-color-border-light-default); + } + } + } +} + +.titleSection { + margin-bottom: var(--base-sizing-8x); + span { + display: block; + padding: var(--base-sizing-4x) var(--base-sizing-8x); + } +} + +.title { + color: var(--theme-color-text-base-title); + @include font("base", "lg", "600"); +} + +.subtitle { + color: var(--theme-color-text-base-subtitle); + @include font("base", "md", "500"); +} + +.headerRowContent { + display: flex; + gap: var(--base-sizing-8x); + align-items: center; +} + +.header { + flex: 1; + padding: var(--base-sizing-10x) var(--base-sizing-8x); + @include font("base", "lg", "600"); +} + +.filterInput { + flex-shrink: 0; + margin: var(--base-sizing-8x) var(--base-sizing-8x) var(--base-sizing-8x) auto; +} + +.footerForNumbers { + padding: var(--base-sizing-8x) var(--base-sizing-12x); + align-items: center; + display: flex; + + &.hasPagination-center { + justify-content: center; + } + &.hasPagination-right { + justify-content: flex-end; + } + + &.hasNumbers { + &.hasPagination-left { + flex-direction: row-reverse; + justify-content: space-between; + } + &.hasPagination-center { + .totalRecordsLabel { + flex: 1; + } + } + &.hasPagination-right { + justify-content: space-between; + } + } + + .totalRecordsLabel { + color: var(--theme-color-text-base-title); + @include font("body", "sm"); + } +} + +.pagination { + display: flex; +} diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/TableContext.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/TableContext.tsx new file mode 100644 index 00000000..90e08ca2 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/TableContext.tsx @@ -0,0 +1,257 @@ +"use client"; + +import { createContext, PropsWithChildren, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { foldNormalize, getNextItemInArray, getTextFromNode, getValueByChainedKey } from "src/utils/utils"; +import { sortByType, SORT_DIRECTIONS, getSpannedCellsMap } from "./helper"; +import { ColumnState, RowDetail, TableContextDefaultValues, TableContextProps, TableContextType, TableRowId } from "./types"; +import { useMotifContext } from "src/lib/motif/context/MotifProvider"; + +export const TableContext = createContext(TableContextDefaultValues); + +export const TableProvider = (props: PropsWithChildren) => { + const { + dataRaw, + columns, + totalRecords, + onSortChange, + onFilterChange, + onColumnFilterChange, + onPageChange, + showFixedRowNumbers, + pagination, + selectable, + selectionKey, + defaultSelectedIds, + onSelectionChange, + filterableTable, + filterPlaceholder, + disableFilterOnKeyPress, + reflectDataChanges, + rowColorCallback, + } = props; + if (selectable && !selectionKey) throw new Error("selectionKey is required when selectable is true"); + + const { locale } = useMotifContext(); + const [currentPage, setCurrentPage] = useState(1); + const [appliedMainFilterQuery, setAppliedMainFilterQuery] = useState(""); + const [mainFilterInputValue, setMainFilterInputValueState] = useState(""); + const mainFilterInputValueRef = useRef(mainFilterInputValue); + const pendingDefaultIdsRef = useRef(new Set(defaultSelectedIds)); + const [selectedIds, setSelectedIds] = useState>(() => { + const initial = new Set(); + if (selectionKey) { + dataRaw?.forEach(row => { + const rowUniqueId = (row as Record)[selectionKey] as TableRowId; + pendingDefaultIdsRef.current.has(rowUniqueId) && initial.add(rowUniqueId); + }); + } + return initial; + }); + + const setMainFilterInputValue = useCallback((value: string) => { + mainFilterInputValueRef.current = value; + setMainFilterInputValueState(value); + }, []); + + const mapDataToMotifTableRow: (row: object, index: number) => RowDetail = useCallback( + (row: object, index: number) => ({ + rowId: (selectionKey ? (row as Record)[selectionKey] : index) as TableRowId, + data: { "#": index + 1, ...row }, + }), + [selectionKey], + ); + + useEffect(() => { + if (!selectionKey || !pendingDefaultIdsRef.current.size || !dataRaw) return; + setSelectedIds(prev => { + const next = new Set(prev); + dataRaw.forEach(row => { + const rowUniqueId = (row as Record)[selectionKey] as TableRowId; + pendingDefaultIdsRef.current.delete(rowUniqueId) && next.add(rowUniqueId); + }); + return next.size === prev.size ? prev : next; + }); + }, [dataRaw, selectionKey]); + + // Original data user provided. We only add some necessary internal props to it. It doesn't change at all, + // unless reflectDataChanges is set — synced in-render (not via useEffect) so a dataRaw change is never + // painted a frame late, which would otherwise flash the previous page's rows (and their selection state). + const [originalRows, setOriginalRows] = useState(() => dataRaw?.map(mapDataToMotifTableRow)); + const [prevDataRaw, setPrevDataRaw] = useState(dataRaw); + if (dataRaw !== prevDataRaw) { + setPrevDataRaw(dataRaw); + ((dataRaw?.length && !originalRows?.length) || reflectDataChanges) && setOriginalRows(dataRaw?.map(mapDataToMotifTableRow)); + } + const [columnStates, setColumnStates] = useState(columns.map(() => ({}))); + + // Data that is used in the table. It can be sorted, filtered, paginated etc. (derived from originalRows) + const usableRows = useMemo(() => { + if (!originalRows) return undefined; + + const normalize = (s: string) => foldNormalize(s, locale); + const normalizedMainQuery = appliedMainFilterQuery && normalize(appliedMainFilterQuery); + const normalizedColumnQueries = columnStates.map(s => s.filterQuery && normalize(s.filterQuery)); + + const filteredRows = originalRows.filter(row => { + const columnMatches = + !!onColumnFilterChange || + !columns.some((column, index) => { + const data = getValueByChainedKey(row.data, column.dataKey); + const contentToBeSearched = !column.render ? data : getTextFromNode(column.render(data)); + const columnQuery = normalizedColumnQueries[index]; + return !!columnQuery && !normalize(contentToBeSearched).includes(columnQuery); + }); + + const mainFilterMatches = + normalizedMainQuery && !onFilterChange + ? columns.some(column => { + const data = getValueByChainedKey(row.data, column.dataKey); + const contentToBeSearched = !column.render ? data : getTextFromNode(column.render(data)); + return normalize(contentToBeSearched).includes(normalizedMainQuery); + }) + : true; + + return columnMatches && mainFilterMatches; + }); + + // Sort + return columns.reduce((acc, column, index) => { + const sortDirection = columnStates[index]?.lastSortDirection; + return sortDirection && !onSortChange + ? acc.sort((a, b) => { + const data1 = getValueByChainedKey(sortDirection === "asc" ? a.data : b.data, column.dataKey); + const data2 = getValueByChainedKey(sortDirection === "asc" ? b.data : a.data, column.dataKey); + return column.sorting?.customSort?.(data1, data2) ?? sortByType(data1, data2, typeof data1); + }) + : acc; + }, filteredRows); + }, [originalRows, columnStates, columns, appliedMainFilterQuery, locale, onSortChange, onFilterChange, onColumnFilterChange]); + + // Data that is visible in the table. It can be less than usableRows if pagination is enabled. + // isSelected is derived here, fresh, from selectedIds — never stored on originalRows itself. + const visibleRows = useMemo(() => { + const sliced = + pagination && totalRecords === undefined + ? usableRows?.slice((currentPage - 1) * pagination.rowsPerPage, currentPage * pagination.rowsPerPage) + : usableRows; + return sliced?.map(row => ({ ...row, isSelected: selectedIds.has(row.rowId) })); + }, [currentPage, usableRows, pagination, totalRecords, selectedIds]); + + const spannedCellsMap = useMemo(() => getSpannedCellsMap(columns, visibleRows), [columns, visibleRows]); + + const selectHandler = useCallback( + ({ row, all }: { row?: RowDetail; all?: "select" | "deselect" }) => { + const next = new Set(selectedIds); + + if (all === "select") { + const changedIds = (visibleRows ?? []).map(r => r.rowId); + changedIds.forEach(id => next.add(id)); + setSelectedIds(next); + onSelectionChange?.(changedIds, true, Array.from(next)); + } else if (all === "deselect") { + const changedIds = (visibleRows ?? []).map(r => r.rowId); + changedIds.forEach(id => next.delete(id)); + setSelectedIds(next); + onSelectionChange?.(changedIds, false, Array.from(next)); + } else if (row) { + const selected = !selectedIds.has(row.rowId); + selected ? next.add(row.rowId) : next.delete(row.rowId); + setSelectedIds(next); + onSelectionChange?.([row.rowId], selected, Array.from(next)); + } + }, + [selectedIds, visibleRows, onSelectionChange], + ); + + const updateSortState = useCallback( + (columnIndex: number) => { + if (usableRows?.length || onSortChange) { + const sortDirection = getNextItemInArray(SORT_DIRECTIONS, columnStates[columnIndex]?.lastSortDirection); + setColumnStates(prev => prev.map((c, index) => ({ ...c, lastSortDirection: index === columnIndex ? sortDirection : undefined }))); + setCurrentPage(1); + onSortChange?.({ dataKey: columns[columnIndex]?.dataKey, direction: sortDirection }); + } + }, + [usableRows?.length, columnStates, columns, onSortChange], + ); + + const updateFilterState = useCallback( + (query: string, columnIndex?: number) => { + if (columnIndex !== undefined) { + setColumnStates(prev => prev.map((c, index) => (index === columnIndex ? { ...c, filterQuery: query } : c))); + setCurrentPage(1); + onColumnFilterChange?.({ dataKey: columns[columnIndex]?.dataKey, query }); + } + }, + [columns, onColumnFilterChange], + ); + + const applyFilter = useCallback( + (forceImmediate?: boolean) => { + if (mainFilterInputValueRef.current === appliedMainFilterQuery) return; + setAppliedMainFilterQuery(mainFilterInputValueRef.current); + setCurrentPage(1); + onFilterChange?.(mainFilterInputValueRef.current, forceImmediate ?? disableFilterOnKeyPress); + }, + [appliedMainFilterQuery, onFilterChange, disableFilterOnKeyPress], + ); + + const contextValue = useMemo( + () => ({ + originalRows, + usableRows, + updateSortState, + visibleRows, + columns, + spannedCellsMap, + columnStates, + showFixedRowNumbers, + setCurrentPage, + currentPage, + onPageChange, + pagination, + selectable, + selectedIds, + selectHandler, + filterableTable, + filterPlaceholder, + disableFilterOnKeyPress, + filterableColumns: columns.some(c => c.filter), + updateFilterState, + totalRecords: totalRecords ?? originalRows?.length ?? 0, + explicitTotalRecords: totalRecords, + mainFilterInputValue, + setMainFilterInputValue, + applyFilter, + numberOfVisibleColumns: columns.length + (selectable ? 1 : 0) + (showFixedRowNumbers ? 1 : 0), + rowColorCallback, + }), + [ + originalRows, + usableRows, + updateSortState, + visibleRows, + columns, + spannedCellsMap, + columnStates, + showFixedRowNumbers, + currentPage, + onPageChange, + pagination, + selectable, + selectedIds, + selectHandler, + filterableTable, + filterPlaceholder, + disableFilterOnKeyPress, + updateFilterState, + mainFilterInputValue, + setMainFilterInputValue, + applyFilter, + rowColorCallback, + totalRecords, + ], + ); + + return {props.children}; +}; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Body/DataCell.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Body/DataCell.tsx new file mode 100644 index 00000000..3161cc3b --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Body/DataCell.tsx @@ -0,0 +1,19 @@ +import { getSpanProps } from "../../helper"; +import { Column, ResolvedCellSpan } from "../../types"; +import { getValueByChainedKey } from "src/utils/utils"; + +type Props = { + column: Column; + rowData: object; + span: ResolvedCellSpan; +}; + +const DataCell = (props: Props) => { + const { column, rowData, span } = props; + const data = getValueByChainedKey(rowData, column.dataKey); + const content = column.render?.(data) ?? (data as string); + + return
; +}; + +export default DataCell; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Body/DataRow.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Body/DataRow.tsx new file mode 100644 index 00000000..9668fbd2 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Body/DataRow.tsx @@ -0,0 +1,38 @@ +import styles from "../../TableBaseline.module.scss"; +import Checkbox from "@/components/Checkbox"; +import DataCell from "./DataCell"; +import { useContext } from "react"; +import { TableContext } from "../../TableContext"; +import { RowDetail } from "../../types"; +import { sanitizeModuleClasses } from "src/utils/cssUtils"; + +type Props = { + rowNumberStatic: number; + row: RowDetail; + rowIndex: number; + isStripe?: boolean; +}; + +const DataRow = (props: Props) => { + const { rowNumberStatic, row, rowIndex, isStripe } = props; + const { columns, showFixedRowNumbers, selectable, selectHandler, rowColorCallback, spannedCellsMap } = useContext(TableContext); + + const className = sanitizeModuleClasses(styles, isStripe && "stripedRow", row.isSelected && "selected", rowColorCallback?.(row.data)); + + return ( + + {selectable && ( + + )} + {showFixedRowNumbers ? : null} + {columns.map((column, cIndex) => { + const span = spannedCellsMap.get(`${rowIndex}-${cIndex}`); + return span && ; + })} + + ); +}; + +export default DataRow; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Body/TableBody.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Body/TableBody.tsx new file mode 100644 index 00000000..81466a0b --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Body/TableBody.tsx @@ -0,0 +1,54 @@ +import { memo, ReactNode, useContext, useMemo } from "react"; +import { TableContext } from "../../TableContext"; +import styles from "../../TableBaseline.module.scss"; +import Skeleton from "@/components/Skeleton"; +import DataRow from "./DataRow"; +import { getRowStripeGroups } from "../../helper"; +import { sanitizeModuleClasses } from "src/utils/cssUtils"; + +type Props = { + loading?: boolean; + emptyMessage?: ReactNode; + striped?: boolean; +}; + +const TableBody = memo((props: Props) => { + const { loading, emptyMessage, striped } = props; + const { visibleRows, numberOfVisibleColumns, spannedCellsMap } = useContext(TableContext); + + const stripeGroups = useMemo( + () => striped && getRowStripeGroups(spannedCellsMap, visibleRows?.length ?? 0), + [striped, spannedCellsMap, visibleRows?.length], + ); + + const className = sanitizeModuleClasses(styles, striped && "striped"); + return ( + + {loading ? ( + + + + ) : !visibleRows?.length ? ( + + + + ) : ( + visibleRows.map((row, index) => ( + + )) + )} + + ); +}); + +export default TableBody; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Foot/ColumnFootArea.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Foot/ColumnFootArea.tsx new file mode 100644 index 00000000..436ca75d --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Foot/ColumnFootArea.tsx @@ -0,0 +1,88 @@ +import { ReactNode, useContext, useMemo } from "react"; +import { TableContext } from "../../TableContext"; +import { Column, RowBackground } from "../../types"; +import { getRenderableHeaderColumns, getSpanProps, getFooterValue } from "../../helper"; +import styles from "../../TableBaseline.module.scss"; + +type Props = { + background: RowBackground; + customFooter?: () => ReactNode; +}; + +const ColumnFootArea = ({ background, customFooter }: Props) => { + const { originalRows, columns, showFixedRowNumbers, selectable, numberOfVisibleColumns } = useContext(TableContext); + + const columnsConsideringExtraCols = useMemo( + () => + columns.some(column => column.footer) + ? [...(selectable ? [{ title: "" }] : []), ...(showFixedRowNumbers ? [{ title: "#" }] : []), ...columns] + : undefined, + [columns, showFixedRowNumbers, selectable], + ); + + const buildFooterCells = (renderableColumns: ReturnType, allColumns: Column[]) => { + const { cells, pending } = renderableColumns.reduce<{ cells: ReactNode[]; pending: number }>( + (acc, { column, index, colSpan }) => { + if (column.footer) { + const value = getFooterValue(column, originalRows); + return { + cells: [ + ...acc.cells, + ...(acc.pending + ? [ + , + ] + : []), + , + ], + pending: 0, + }; + } + + const spanCount = colSpan ?? 1; + const absorbedFooterCol = spanCount > 1 ? allColumns.slice(index + 1, index + spanCount).find(c => c.footer) : undefined; + + if (absorbedFooterCol) { + const value = getFooterValue(absorbedFooterCol, originalRows); + return { + cells: [ + ...acc.cells, + ...(acc.pending ? [, + ], + pending: 0, + }; + } + + return { ...acc, pending: acc.pending + spanCount }; + }, + { cells: [], pending: 0 }, + ); + return pending ? [...cells, + {footerCells && {footerCells}} + {customFooter && ( + + + + )} + + ); +}; + +export default ColumnFootArea; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Foot/FooterForNumbers.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Foot/FooterForNumbers.tsx new file mode 100644 index 00000000..8065e282 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Foot/FooterForNumbers.tsx @@ -0,0 +1,49 @@ +import styles from "../../TableBaseline.module.scss"; +import Pagination from "@/components/Pagination"; +import { useContext } from "react"; +import { TableContext } from "../../TableContext"; +import RowNumberMessage from "./RowNumberMessage"; +import { sanitizeModuleClasses } from "src/utils/cssUtils"; + +type Props = { + loading?: boolean; + hideTotalRecordsMessage?: boolean; +}; + +const FooterForNumbers = ({ loading, hideTotalRecordsMessage }: Props) => { + const { originalRows, pagination, usableRows, totalRecords, explicitTotalRecords, currentPage, setCurrentPage, onPageChange } = + useContext(TableContext); + + const paginationPosition = pagination?.position || "center"; + const className = sanitizeModuleClasses( + styles, + "footerForNumbers", + !hideTotalRecordsMessage && "hasNumbers", + pagination && `hasPagination-${paginationPosition}`, + ); + + return ( +
+ {!hideTotalRecordsMessage && totalRecords > 0 && } + {pagination && ( +
+ {!loading && originalRows && ( + { + setCurrentPage?.(page); + onPageChange?.(page); + }} + size="sm" + /> + )} +
+ )} + {pagination && !hideTotalRecordsMessage && paginationPosition === "center" &&
} +
+ ); +}; + +export default FooterForNumbers; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Foot/RowNumberMessage.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Foot/RowNumberMessage.tsx new file mode 100644 index 00000000..d941a182 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Foot/RowNumberMessage.tsx @@ -0,0 +1,17 @@ +import styles from "../../TableBaseline.module.scss"; +import { memo, useContext } from "react"; +import { TableContext } from "../../TableContext"; +import { useMotifContext } from "src/lib/motif/context/MotifProvider"; + +const RowNumberMessage = memo(() => { + const { t } = useMotifContext(); + const { selectedIds, selectable, totalRecords } = useContext(TableContext); + + const message = selectable + ? t("table.selectedRecords", { selected: selectedIds.size, count: totalRecords }) + : t("table.totalRecords", { total: totalRecords }); + + return {message}; +}); + +export default RowNumberMessage; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/FilterCell.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/FilterCell.tsx new file mode 100644 index 00000000..52b80304 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/FilterCell.tsx @@ -0,0 +1,25 @@ +import InputText from "@/components/Motif/InputText/InputText"; +import { getSpanProps } from "../../helper"; +import { TableContext } from "../../TableContext"; +import { useContext } from "react"; +import styles from "../../TableBaseline.module.scss"; + +type Props = { + index: number; + colSpan?: number; + placeholder?: string; +}; + +const FilterCell = ({ index, colSpan, placeholder }: Props) => { + const { updateFilterState } = useContext(TableContext); + + return ( +
+ ); +}; + +export default FilterCell; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/FilterColumnsRow.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/FilterColumnsRow.tsx new file mode 100644 index 00000000..50307e93 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/FilterColumnsRow.tsx @@ -0,0 +1,26 @@ +import styles from "../../TableBaseline.module.scss"; +import FilterCell from "./FilterCell"; +import { useContext } from "react"; +import { TableContext } from "../../TableContext"; +import { getRenderableHeaderColumns, getSpanProps } from "../../helper"; + +const FilterColumnsRow = () => { + const { columns, showFixedRowNumbers, selectable } = useContext(TableContext); + + return ( + + {selectable && + ); +}; + +export default FilterColumnsRow; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/HeaderCell.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/HeaderCell.tsx new file mode 100644 index 00000000..c366ef61 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/HeaderCell.tsx @@ -0,0 +1,33 @@ +import styles from "../../TableBaseline.module.scss"; +import { MotifIconButton } from "@/components/Motif/Icon"; +import { getSpanProps } from "../../helper"; +import { Column } from "../../types"; +import { useContext } from "react"; +import { TableContext } from "../../TableContext"; + +type Props = { + index: number; + column: Column; + colSpan?: number; +}; + +const HeaderCell = (props: Props) => { + const { index, column, colSpan } = props; + const { updateSortState, columnStates } = useContext(TableContext); + + const lastSortDirection = columnStates[index]?.lastSortDirection; + const iconName = lastSortDirection === "asc" ? "keyboard_arrow_up" : lastSortDirection === "desc" ? "keyboard_arrow_down" : "expand_all"; + + return ( + + ); +}; + +export default HeaderCell; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/HeaderRow.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/HeaderRow.tsx new file mode 100644 index 00000000..9637ae53 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/HeaderRow.tsx @@ -0,0 +1,52 @@ +"use client"; + +import styles from "../../TableBaseline.module.scss"; +import InputText from "@/components/Motif/InputText/InputText"; +import MotifIcon from "@/components/Motif/Icon/MotifIcon"; +import { TableContext } from "../../TableContext"; +import { ReactNode, useContext } from "react"; +import { useMotifContext } from "src/lib/motif/context/MotifProvider"; + +type Props = { + colspan: number; + header?: ReactNode; +}; + +const HeaderRow = ({ colspan, header }: Props) => { + const { filterableTable, filterPlaceholder, disableFilterOnKeyPress, mainFilterInputValue, setMainFilterInputValue, applyFilter } = + useContext(TableContext); + const { t } = useMotifContext(); + + return ( + + + + ); +}; + +export default HeaderRow; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/RowSelectionCell.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/RowSelectionCell.tsx new file mode 100644 index 00000000..3fbf7202 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/RowSelectionCell.tsx @@ -0,0 +1,25 @@ +import styles from "../../TableBaseline.module.scss"; +import Checkbox from "@/components/Checkbox"; +import { useContext, useMemo } from "react"; +import { TableContext } from "../../TableContext"; + +const RowSelectionCell = () => { + const { visibleRows, selectHandler } = useContext(TableContext); + + const selectedVisibleRows = useMemo(() => visibleRows?.filter(r => r.isSelected), [visibleRows]); + const checked = !!visibleRows?.length && selectedVisibleRows?.length === visibleRows.length; + const partialCheck = !checked && !!selectedVisibleRows?.length && selectedVisibleRows.length > 0; + + return ( + + ); +}; + +export default RowSelectionCell; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/TableHead.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/TableHead.tsx new file mode 100644 index 00000000..a7a60fa9 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/Head/TableHead.tsx @@ -0,0 +1,34 @@ +import HeaderCell from "./HeaderCell"; +import { ReactNode, useContext } from "react"; +import { TableContext } from "../../TableContext"; +import { RowBackground } from "../../types"; +import styles from "../../TableBaseline.module.scss"; +import HeaderRow from "./HeaderRow"; +import FilterColumnsRow from "./FilterColumnsRow"; +import RowSelectionCell from "./RowSelectionCell"; +import { getRenderableHeaderColumns } from "../../helper"; + +type Props = { + background: RowBackground; + header?: ReactNode; +}; + +const TableHead = ({ background, header }: Props) => { + const { columns, showFixedRowNumbers, selectable, filterableTable, filterableColumns, numberOfVisibleColumns } = useContext(TableContext); + + return ( + + {(filterableTable || header) && } + + {selectable && } + {showFixedRowNumbers && } + {getRenderableHeaderColumns(columns).map(({ column, index, colSpan }) => ( + + ))} + + {filterableColumns && } + + ); +}; + +export default TableHead; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/TableContainer.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/TableContainer.tsx new file mode 100644 index 00000000..14bda436 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/TableContainer.tsx @@ -0,0 +1,66 @@ +import styles from "../TableBaseline.module.scss"; +import TableHead from "./Head/TableHead"; +import TableBody from "./Body/TableBody"; +import ColumnFootArea from "./Foot/ColumnFootArea"; +import { TableProps } from "../types"; +import FooterForNumbers from "./Foot/FooterForNumbers"; +import { PropsWithRef } from "src/lib/types"; +import { sanitizeModuleRootClasses } from "src/utils/cssUtils"; +import TableTitleSection from "./TableTitleSection"; + +type Props = Omit< + TableProps, + | "columns" + | "data" + | "showFixedRowNumbers" + | "pagination" + | "selectable" + | "selectionKey" + | "onSelectionChange" + | "filterableTable" + | "rowColorCallback" + | "reflectDataChanges" +>; + +const TableContainer = (props: PropsWithRef) => { + const { + title, + subtitle, + header, + headerColsBackground = "solid", + footer, + border = "cellBorders", + hoverable, + striped, + loading, + emptyMessage, + footerColsBackground = "solid", + hideTotalRecords, + ref, + distributeColsEvenly, + fluid, + className, + style, + } = props; + + const classNames = sanitizeModuleRootClasses(styles, className, [ + ["bordered", border], + hoverable && "hoverable", + distributeColsEvenly && "distributeColsEvenly", + fluid && "fluid", + ]); + + return ( +
+ +
{typeof content === "boolean" ? String(content) : content}
+ selectHandler?.({ row })} checked={row.isSelected} /> + {rowNumberStatic}
+ +
+ {emptyMessage ?? "No data"} +
+ {column.footer.title} + + {column.footer.render?.(value) ?? value} + ] : []), + + {absorbedFooterCol.footer!.render?.(value) ?? value} + ] : cells; + }; + + const footerCells = columnsConsideringExtraCols + ? buildFooterCells(getRenderableHeaderColumns(columnsConsideringExtraCols), columnsConsideringExtraCols) + : undefined; + + return ( +
+ {customFooter()} +
+
+ updateFilterState(val as string, index)} /> +
+
} + {showFixedRowNumbers && } + {getRenderableHeaderColumns(columns).map(({ column, index, colSpan }) => { + const key = "0-filter" + index; + return column.filter ? ( + + ) : ( + + ); + })} +
+
+ {column.title} + {column.sorting && ( + updateSortState(index)} /> + )} +
+
+ {typeof header === "string" || filterableTable ? ( +
+ {header && (typeof header === "string" ? {header} : header)} + {filterableTable && ( + applyFilter() }, onKeyUp: e => e.key === "Enter" && applyFilter() } + : { iconRight: })} + clearable + className={styles.filterInput} + placeholder={filterPlaceholder ?? t("g.search")} + size="sm" + onChange={val => { + setMainFilterInputValue(val as string); + !disableFilterOnKeyPress && applyFilter(); + }} + onClearClick={() => applyFilter(true)} + /> + )} +
+ ) : ( + header + )} +
+ selectHandler?.({ all: checked ? "deselect" : "select" })} + /> +
#
+ + + +
+ {!loading && } + + ); +}; + +export default TableContainer; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/TableTitleSection.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/TableTitleSection.tsx new file mode 100644 index 00000000..2ecb447d --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/components/TableTitleSection.tsx @@ -0,0 +1,19 @@ +import styles from "../TableBaseline.module.scss"; + +type Props = { + title?: string; + subtitle?: string; +}; + +const TableTitleSection = ({ title, subtitle }: Props) => { + return ( + (title || subtitle) && ( +
+ {title && {title}} + {subtitle && {subtitle}} +
+ ) + ); +}; + +export default TableTitleSection; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/helper.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Table/helper.ts new file mode 100644 index 00000000..588917c1 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/helper.ts @@ -0,0 +1,152 @@ +import { Column, RowDetail, ResolvedCellSpan, RenderableColumn, SpannedCellKey, SpannedCellsMap, SortDirection } from "./types"; +import { getValueByChainedKey } from "src/utils/utils"; + +// Constants +export const SORT_DIRECTIONS: (SortDirection | undefined)[] = ["asc", "desc", undefined] as const; + +// Cell Span Utils +const clampSpanValue = (span: number | undefined, maxSpan?: number): number => { + if (!span || !Number.isFinite(span)) return 1; + const clamped = Math.max(Math.floor(span), 1); + return maxSpan != null ? Math.min(clamped, Math.max(Math.floor(maxSpan), 1)) : clamped; +}; + +const resolveCellSpan = ( + column: Column, + rowData: object, + limits?: { + maxColSpan?: number; + maxRowSpan?: number; + }, +): ResolvedCellSpan => ({ + colSpan: clampSpanValue(typeof column.colSpan === "function" ? column.colSpan(rowData) : column.colSpan, limits?.maxColSpan), + rowSpan: clampSpanValue(typeof column.rowSpan === "function" ? column.rowSpan(rowData) : column.rowSpan, limits?.maxRowSpan), +}); + +export const getColSpan = (column: Column, maxColSpan?: number) => { + if (typeof column.colSpan !== "number") return undefined; + + const colSpan = clampSpanValue(column.colSpan, maxColSpan); + return colSpan > 1 ? colSpan : undefined; +}; + +export const getSpanProps = (colSpan?: number, rowSpan?: number) => ({ + ...(colSpan && colSpan > 1 ? { colSpan } : {}), + ...(rowSpan && rowSpan > 1 ? { rowSpan } : {}), +}); + +export const getRenderableHeaderColumns = (columns: Column[]) => { + const renderableColumns: RenderableColumn[] = []; + + for (let index = 0; index < columns.length; index++) { + if (renderableColumns.length) { + const previousColumn = renderableColumns[renderableColumns.length - 1]; + if (previousColumn.index + (previousColumn.colSpan ?? 1) > index) continue; + } + + renderableColumns.push({ + column: columns[index], + index, + colSpan: getColSpan(columns[index], columns.length - index), + }); + } + + return renderableColumns; +}; + +export const getSpannedCellsMap = (columns: Column[], rows?: RowDetail[]): SpannedCellsMap => { + const map = new Map(); + if (!rows) return map; + + rows.forEach((row, rowIndex) => { + const remainingRowsCount = rows.length - rowIndex; + columns.forEach((column, colIndex) => { + const cellKey: SpannedCellKey = `${rowIndex}-${colIndex}`; + if (map.has(cellKey)) return; + + const span = resolveCellSpan(column, row.data, { + maxColSpan: columns.length - colIndex, + maxRowSpan: remainingRowsCount, + }); + const { colSpan, rowSpan } = span; + map.set(cellKey, span); + + for (let c = 1; c < colSpan; c++) { + map.set(`${rowIndex}-${colIndex + c}`, undefined); + } + + for (let r = 1; r < rowSpan; r++) { + for (let c = 0; c < colSpan; c++) { + map.set(`${rowIndex + r}-${colIndex + c}`, undefined); + } + } + }); + }); + + return map; +}; + +export const getRowStripeGroups = (spannedCellsMap: SpannedCellsMap, rowCount: number) => { + const continuation = Array(rowCount).fill(false); + + for (const [key, span] of spannedCellsMap) { + if (!span || span.rowSpan <= 1) continue; + + const row = Number.parseInt(key, 10); + for (let i = 1; i < span.rowSpan && row + i < rowCount; i++) { + continuation[row + i] = true; + } + } + + return Array.from({ length: rowCount }).reduce((groups, _, row) => { + const isGroupStart = !continuation[row]; + groups[row] = row === 0 ? 0 : groups[row - 1] + Number(isGroupStart); + return groups; + }, []); +}; + +// Sorting Utils +export const sortByType = (a: unknown, b: unknown, type: string) => { + switch (type) { + case "string": + return sortStrings(a as string, b as string); + case "number": + return sortNumbers(a as number, b as number); + case "boolean": + return sortBoolean(a as boolean, b as boolean); + case "object": + return sortObjects(a, b); + default: + return 0; + } +}; + +const sortStrings = (s1: string, s2: string) => s1.localeCompare(s2); + +const sortNumbers = (n1: number, n2: number) => n1 - n2; + +const sortBoolean = (b1: boolean, b2: boolean) => (b1 === b2 ? 0 : b1 ? 1 : -1); + +const sortObjects = (a: unknown, b: unknown) => { + if (!a || !b) { + return a === b ? 0 : !a ? -1 : 1; + } + return 0; +}; + +// Footer Utils +export const getFooterValue = ({ title, dataKey, footer }: Column, originalRows: RowDetail[] | undefined) => { + const { type } = footer || {}; + switch (type) { + case "avg": + return originalRows?.length + ? (originalRows.reduce((acc, row) => acc + getValueByChainedKey(row.data, dataKey), 0) / originalRows.length).toFixed(2) + : undefined; + case "sum": + return originalRows?.reduce((acc, row) => acc + getValueByChainedKey(row.data, dataKey), 0); + case "title": + return title; + default: + return undefined; + } +}; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/hooks/requestReducer.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Table/hooks/requestReducer.ts new file mode 100644 index 00000000..d992505a --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/hooks/requestReducer.ts @@ -0,0 +1,43 @@ +import { Filters, Sort } from "./types"; + +export type RequestState = { + page: number; + sort: Sort; + filters: Filters; + debouncedFilters: Filters; + pageResetPending: boolean; +}; + +export type RequestAction = + | { type: "setPage"; page: number } + | { type: "sort"; sort: Sort } + | { type: "filter"; query: string; immediate?: boolean } + | { type: "columnFilter"; dataKey: string; query: string } + | { type: "debounceElapsed" }; + +export const requestReducer = (state: RequestState, action: RequestAction): RequestState => { + const { filters, debouncedFilters } = state; + + switch (action.type) { + case "setPage": + return { ...state, page: action.page }; + case "sort": + return { ...state, sort: action.sort, page: 1 }; + case "filter": { + const nextFilters = { ...filters, main: action.query }; + return action.immediate + ? { ...state, filters: nextFilters, debouncedFilters: nextFilters, page: 1, pageResetPending: false } + : { ...state, filters: nextFilters, pageResetPending: true }; + } + case "columnFilter": { + const nextFilters = { ...filters, columns: { ...filters.columns, [action.dataKey]: action.query } }; + return { ...state, filters: nextFilters, pageResetPending: true }; + } + case "debounceElapsed": { + const unchanged = + filters.main === debouncedFilters.main && JSON.stringify(filters.columns) === JSON.stringify(debouncedFilters.columns); + if (unchanged && !state.pageResetPending) return state; + return { ...state, debouncedFilters: filters, page: state.pageResetPending ? 1 : state.page, pageResetPending: false }; + } + } +}; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/hooks/types.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Table/hooks/types.ts new file mode 100644 index 00000000..3573cfae --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/hooks/types.ts @@ -0,0 +1,39 @@ +import { SortDirection } from "../types"; + +export type Sort = { dataKey?: string; direction?: SortDirection }; +export type Filters = { main: string; columns: Record }; + +export type FetchState = { page: number; pageSize?: number; sort: Sort; filters: Filters; signal: AbortSignal }; +export type FetchResult = { data: T[]; totalRecords: number }; +export type Fetcher = (state: FetchState) => Promise>; + +/** + * Query string key names for page/sort/filter values. Every field is independently optional and has no + * default — a value (or pair, for `page`/`pageSize` and `sortBy`/`sortOrder`) is only ever sent when its + * key name is actually configured here. + */ +export type QueryStringKeys = { + page?: string; + pageSize?: string; + sortBy?: string; + sortOrder?: string; + query?: string; + columnFilter?: (dataKey: string) => string; +}; + +export type UseServerTableOptions = { + /** Base request URL for the default fetch implementation. Ignored when a `fetcher` is given. */ + url?: string; + /** HTTP method for the default fetch implementation. GET sends the built params as a query string, POST as a JSON body. Defaults to "GET". */ + method?: "GET" | "POST"; + /** Query string key names for page/sort/filter values. Every field is independently optional — nothing is sent unless its key name is configured. */ + queryStringKeys?: QueryStringKeys; + /** Dotted path to the rows array inside the response body, if the body isn't a bare array. */ + itemsKey?: string; + /** Where the total record count comes from — pick one. Neither has a default; without either, total falls back to `data.length`. */ + totalCount?: { bodyKey?: string; headerKey?: string }; + /** The page size to request. Without it, no pagination query string params are sent at all. */ + pageSize?: number; + /** Debounce delay, in milliseconds, before a filter keystroke triggers a request. Defaults to 500. */ + filterKeyPressRequestDelay?: number; +}; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/hooks/useServerTable.tsx b/src/lib/styles/tokens/compare/baseline/Batch13/Table/hooks/useServerTable.tsx new file mode 100644 index 00000000..bc4948a8 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/hooks/useServerTable.tsx @@ -0,0 +1,120 @@ +"use client"; + +import { useCallback, useEffect, useReducer, useRef, useState } from "react"; +import { getValueByChainedKey } from "src/utils/utils"; +import { Fetcher, Sort, UseServerTableOptions } from "./types"; +import { requestReducer } from "./requestReducer"; + +const createUrlFetcher = + ({ url, method = "GET", queryStringKeys = {}, itemsKey, totalCount = {} }: UseServerTableOptions): Fetcher => + async ({ page, pageSize, sort, filters, signal }) => { + const { page: pageKey, pageSize: pageSizeKey, sortBy, sortOrder, query: queryKey, columnFilter } = queryStringKeys; + const { dataKey: sortKey, direction } = sort; + const { main, columns } = filters; + + const params = new URLSearchParams(); + if (pageSize != null && pageKey && pageSizeKey) { + params.set(pageKey, String(page)); + params.set(pageSizeKey, String(pageSize)); + } + if (sortKey && direction && sortBy && sortOrder) { + params.set(sortBy, sortKey); + params.set(sortOrder, direction); + } + main && queryKey && params.set(queryKey, main); + columnFilter && + Object.entries(columns) + .filter(([, value]) => value) + .forEach(([columnKey, value]) => params.set(columnFilter(columnKey), value)); + + const separator = url?.includes("?") ? "&" : "?"; + const response = await fetch(method === "GET" ? `${url}${separator}${params}` : `${url}`, { + method, + ...(method === "POST" && { + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(Object.fromEntries(params.entries())), + }), + signal, + }); + if (!response.ok) throw new Error(`useServerTable: request to ${response.url} failed with status ${response.status}`); + + const body = (await response.json()) as object; + const data = (itemsKey ? getValueByChainedKey(body, itemsKey) : (body as T[])) ?? []; + const { bodyKey, headerKey } = totalCount; + const totalRecords = bodyKey + ? Number(getValueByChainedKey(body, bodyKey)) + : headerKey + ? Number(response.headers.get(headerKey)) + : data.length; + + return { data, totalRecords }; + }; + +const useServerTable = (options: UseServerTableOptions = {}, fetcher?: Fetcher) => { + const { url, pageSize, filterKeyPressRequestDelay = 500 } = options; + if (!fetcher && !url) throw new Error("useServerTable: provide either `options.url` or a `fetcher`."); + + const [{ page, sort, filters, debouncedFilters }, dispatch] = useReducer(requestReducer, { + page: 1, + sort: {}, + filters: { main: "", columns: {} }, + debouncedFilters: { main: "", columns: {} }, + pageResetPending: false, + }); + const debounceTimeoutRef = useRef>(undefined); + + const [data, setData] = useState([]); + const [error, setError] = useState(null); + const [totalRecords, setTotalRecords] = useState(0); + const [loading, setLoading] = useState(true); + + const resolvedFetcher = fetcher ?? createUrlFetcher(options); + const fetcherRef = useRef(resolvedFetcher); + fetcherRef.current = resolvedFetcher; + + useEffect(() => { + debounceTimeoutRef.current = setTimeout(() => dispatch({ type: "debounceElapsed" }), filterKeyPressRequestDelay); + return () => clearTimeout(debounceTimeoutRef.current); + }, [filters, filterKeyPressRequestDelay]); + + useEffect(() => { + const controller = new AbortController(); + const { signal } = controller; + setLoading(true); + setError(null); + + fetcherRef + .current({ page, pageSize, sort, filters: debouncedFilters, signal }) + .then(result => { + if (!signal.aborted) { + setData(result.data); + setTotalRecords(result.totalRecords); + } + }) + .catch((error: unknown) => { + !signal.aborted && error instanceof Error && error.name !== "AbortError" && setError(error); + }) + .finally(() => { + !signal.aborted && setLoading(false); + }); + + return () => controller.abort(); + }, [page, pageSize, sort, debouncedFilters]); + + const onPageChange = useCallback((newPage: number) => dispatch({ type: "setPage", page: newPage }), []); + + const onSortChange = useCallback((newSort: Sort) => dispatch({ type: "sort", sort: newSort }), []); + + const onFilterChange = useCallback((query: string, immediate?: boolean) => { + if (immediate) clearTimeout(debounceTimeoutRef.current); + dispatch({ type: "filter", query, immediate }); + }, []); + + const onColumnFilterChange = useCallback(({ dataKey, query }: { dataKey?: string; query: string }) => { + dataKey && dispatch({ type: "columnFilter", dataKey, query }); + }, []); + + return { data, totalRecords, loading, error, page, onPageChange, onSortChange, onFilterChange, onColumnFilterChange }; +}; + +export default useServerTable; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/index.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Table/index.ts new file mode 100644 index 00000000..a99a46c3 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/index.ts @@ -0,0 +1,4 @@ +export { default } from "./Table"; +export { default as useServerTable } from "./hooks/useServerTable"; +export type { RowColor, Column, Pagination, Sorting, Footer, TableRowId } from "./types"; +export type { UseServerTableOptions, Fetcher, FetchState, FetchResult, QueryStringKeys } from "./hooks/types"; diff --git a/src/lib/styles/tokens/compare/baseline/Batch13/Table/types.ts b/src/lib/styles/tokens/compare/baseline/Batch13/Table/types.ts new file mode 100644 index 00000000..b8cabe33 --- /dev/null +++ b/src/lib/styles/tokens/compare/baseline/Batch13/Table/types.ts @@ -0,0 +1,192 @@ +import { Dispatch, ReactNode, SetStateAction } from "react"; + +export type ResolvedCellSpan = { + colSpan: number; + rowSpan: number; +}; + +export type SpannedCellKey = `${number}-${number}`; +export type SpannedCellsMap = Map; + +export type RenderableColumn = { + column: Column; + index: number; + colSpan?: number; +}; + +export type TableRowId = string | number; + +export type TableProps = { + /** + * ``` + * { + * title: string; + * dataKey?: string; + * sorting?: Sorting; + * render?: (data: never) => ReactNode; + * footer?: Footer; + * width?: string; + * filter?: boolean; + * filterPlaceholder?: string; + * colSpan?: number | ((rowData: object) => number); + * rowSpan?: number | ((rowData: object) => number); + * }[] + * ``` + */ + columns: Column[]; + data?: T[]; + title?: string; + subtitle?: string; + header?: ReactNode; + footer?: () => ReactNode; + loading?: boolean; + totalRecords?: number; + onSortChange?: (sort: { dataKey?: string; direction?: SortDirection }) => void; + onFilterChange?: (query: string, immediate?: boolean) => void; + onColumnFilterChange?: (filter: { dataKey?: string; query: string }) => void; + onPageChange?: (page: number) => void; + selectable?: boolean; + selectionKey?: string; + defaultSelectedIds?: TableRowId[]; + onSelectionChange?: (changedIds: TableRowId[], selected: boolean, selectedIds: TableRowId[]) => void; + reflectDataChanges?: boolean; + rowColorCallback?: (rowData: T) => RowColor | undefined; +} & TableDefaultableProps; + +export type TableDefaultableProps = { + border?: "cellBorders" | "rowBorders"; + hoverable?: boolean; + striped?: boolean; + headerColsBackground?: RowBackground; + footerColsBackground?: RowBackground; + pagination?: Pagination; + showFixedRowNumbers?: boolean; + emptyMessage?: ReactNode; + filterableTable?: boolean; + filterPlaceholder?: string; + disableFilterOnKeyPress?: boolean; + hideTotalRecords?: boolean; + distributeColsEvenly?: boolean; + fluid?: boolean; +}; + +export type Column = { + title: string; + dataKey?: string; + sorting?: Sorting; + render?: (data: never) => ReactNode; + footer?: Footer; + width?: string; + filter?: boolean; + filterPlaceholder?: string; + colSpan?: number | ((rowData: object) => number); + rowSpan?: number | ((rowData: object) => number); +}; + +export type Sorting = { + customSort?: (a: unknown, b: unknown) => number; +}; + +export type Pagination = { + rowsPerPage: number; + position?: "left" | "center" | "right"; +}; + +export type Footer = { + type?: "sum" | "avg" | "title"; + render?: (data: T) => ReactNode; + title?: string; +}; + +export type RowBackground = "transparent" | "solid" | "opposite"; + +// +// +// TableContext related types +// + +export type TableContextProps = { + columns: Column[]; + dataRaw?: object[]; + totalRecords?: number; + onSortChange?: (sort: { dataKey?: string; direction?: SortDirection }) => void; + onFilterChange?: (query: string, immediate?: boolean) => void; + onColumnFilterChange?: (filter: { dataKey?: string; query: string }) => void; + onPageChange?: (page: number) => void; + showFixedRowNumbers?: boolean; + pagination?: Pagination; + selectable?: boolean; + selectionKey?: string; + defaultSelectedIds?: TableRowId[]; + onSelectionChange?: (changedIds: TableRowId[], selected: boolean, selectedIds: TableRowId[]) => void; + filterableTable?: boolean; + filterPlaceholder?: string; + disableFilterOnKeyPress?: boolean; + reflectDataChanges?: boolean; + rowColorCallback?: (rowData: object) => RowColor | undefined; +}; + +export type TableContextType = { + originalRows?: RowDetail[]; + usableRows?: RowDetail[]; + visibleRows?: RowDetail[]; + totalRecords: number; + /** The raw `totalRecords` prop, unmerged with any fallback — undefined unless the consumer explicitly set it. */ + explicitTotalRecords?: number; + columns: Column[]; + spannedCellsMap: SpannedCellsMap; + updateSortState: (columnIndex: number) => void; + columnStates: ColumnState[]; + showFixedRowNumbers?: boolean; + currentPage: number; + setCurrentPage?: Dispatch>; + onPageChange?: (page: number) => void; + pagination?: Pagination; + selectable?: boolean; + selectedIds: Set; + selectHandler?: (selection: { row?: RowDetail; all?: "select" | "deselect" }) => void; + filterableTable?: boolean; + filterPlaceholder?: string; + disableFilterOnKeyPress?: boolean; + filterableColumns?: boolean; + updateFilterState: (query: string, columnIndex?: number) => void; + mainFilterInputValue: string; + setMainFilterInputValue: (value: string) => void; + applyFilter: (forceImmediate?: boolean) => void; + numberOfVisibleColumns: number; + rowColorCallback?: (rowData: object) => RowColor | undefined; +}; + +export type ColumnState = { + lastSortDirection?: SortDirection; + filterQuery?: string; +}; + +export type RowDetail = { + rowId: TableRowId; + isSelected?: boolean; + data: object; +}; + +export const TableContextDefaultValues: TableContextType = { + totalRecords: 0, + selectedIds: new Set(), + updateSortState: () => {}, + updateFilterState: () => {}, + mainFilterInputValue: "", + setMainFilterInputValue: () => {}, + applyFilter: () => {}, + columns: [], + columnStates: [], + currentPage: 1, + numberOfVisibleColumns: 0, + spannedCellsMap: new Map(), +}; + +// +// +// Other +// + +export type RowColor = "primary" | "secondary" | "light" | "success" | "danger" | "warning" | "info"; +export type SortDirection = "asc" | "desc"; diff --git a/src/lib/styles/tokens/generated/basic.figma.json b/src/lib/styles/tokens/generated/basic.figma.json index fea63a4a..6414b1b5 100644 --- a/src/lib/styles/tokens/generated/basic.figma.json +++ b/src/lib/styles/tokens/generated/basic.figma.json @@ -5272,6 +5272,18 @@ "Value": 512 } }, + { + "name": "sizing/600", + "type": "FLOAT", + "scopes": [ + "WIDTH_HEIGHT" + ], + "hiddenFromPublishing": false, + "description": "600px", + "values": { + "Value": 600 + } + }, { "name": "sizing/720", "type": "FLOAT", @@ -5284,6 +5296,18 @@ "Value": 720 } }, + { + "name": "sizing/760", + "type": "FLOAT", + "scopes": [ + "WIDTH_HEIGHT" + ], + "hiddenFromPublishing": false, + "description": "760px", + "values": { + "Value": 760 + } + }, { "name": "sizing/960", "type": "FLOAT", diff --git a/src/lib/styles/tokens/generated/basic.tokens.json b/src/lib/styles/tokens/generated/basic.tokens.json index 86a35140..7cc3487b 100644 --- a/src/lib/styles/tokens/generated/basic.tokens.json +++ b/src/lib/styles/tokens/generated/basic.tokens.json @@ -2627,6 +2627,14 @@ }, "$description": "512px" }, + "600": { + "$type": "dimension", + "$value": { + "value": 37.5, + "unit": "rem" + }, + "$description": "600px" + }, "720": { "$type": "dimension", "$value": { @@ -2635,6 +2643,14 @@ }, "$description": "720px" }, + "760": { + "$type": "dimension", + "$value": { + "value": 47.5, + "unit": "rem" + }, + "$description": "760px" + }, "960": { "$type": "dimension", "$value": { diff --git a/src/lib/styles/tokens/generated/themes/basic.css b/src/lib/styles/tokens/generated/themes/basic.css index d14146d6..69566c4e 100644 --- a/src/lib/styles/tokens/generated/themes/basic.css +++ b/src/lib/styles/tokens/generated/themes/basic.css @@ -403,7 +403,9 @@ --mtf-sizing-418: 26.125rem; --mtf-sizing-480: 30rem; --mtf-sizing-512: 32rem; + --mtf-sizing-600: 37.5rem; --mtf-sizing-720: 45rem; + --mtf-sizing-760: 47.5rem; --mtf-sizing-960: 60rem; --mtf-sizing-radius-sm: 0.125rem; --mtf-sizing-radius-md: 0.25rem; diff --git a/src/lib/styles/tokens/generated/themes/legacy.css b/src/lib/styles/tokens/generated/themes/legacy.css index 374289a0..77c924e1 100644 --- a/src/lib/styles/tokens/generated/themes/legacy.css +++ b/src/lib/styles/tokens/generated/themes/legacy.css @@ -403,7 +403,9 @@ --mtf-sizing-418: 26.125rem; --mtf-sizing-480: 30rem; --mtf-sizing-512: 32rem; + --mtf-sizing-600: 37.5rem; --mtf-sizing-720: 45rem; + --mtf-sizing-760: 47.5rem; --mtf-sizing-960: 60rem; --mtf-sizing-radius-sm: 0.125rem; --mtf-sizing-radius-md: 0.25rem; diff --git a/src/scripts/tokens/buildTokens.ts b/src/scripts/tokens/buildTokens.ts index e9ecd5a5..ba54c9e9 100644 --- a/src/scripts/tokens/buildTokens.ts +++ b/src/scripts/tokens/buildTokens.ts @@ -55,7 +55,7 @@ const TYPE_ROLES: [string, string, string][] = [ ]; const SIZES = [ 0, 1, 2, 3, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 38, 40, 44, 48, 52, 56, 64, 72, 80, 96, 120, 128, 160, 176, 190, 216, - 256, 266, 320, 342, 360, 400, 418, 480, 512, 720, 960, + 256, 266, 320, 342, 360, 400, 418, 480, 512, 600, 720, 760, 960, ]; // Spacing is named by its px at the default space seed, so Figma values read 1:1 (space-8 = 8px); // the value still follows the seed (space-8 = 10px at space 5). Half-unit steps keep today's 2px, 6px and 10px paddings diff --git a/src/scripts/tokens/legacyMap.ts b/src/scripts/tokens/legacyMap.ts index cbebede7..96ed4101 100644 --- a/src/scripts/tokens/legacyMap.ts +++ b/src/scripts/tokens/legacyMap.ts @@ -3,7 +3,7 @@ const SIZES = [ 1, 2, 3, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 38, 40, 44, 48, 52, 56, 64, 72, 80, 96, 120, 128, 160, 176, 190, 216, 256, - 266, 320, 342, 360, 400, 418, 480, 512, 720, 960, + 266, 320, 342, 360, 400, 418, 480, 512, 600, 720, 760, 960, ]; // Old "base" text family is size × weight; the new scale splits it into a role (size + line height) and a weight diff --git a/stylelint.config.mjs b/stylelint.config.mjs index 0b550a54..bbb1ea9b 100644 --- a/stylelint.config.mjs +++ b/stylelint.config.mjs @@ -51,6 +51,7 @@ export default { "src/lib/components/Container/**/*.scss", "src/lib/components/DataView/**/*.scss", "src/lib/components/Divider/**/*.scss", + "src/lib/components/Drawer/**/*.scss", "src/lib/components/Dropdown/**/*.scss", "src/lib/components/Form/**/*.scss", "src/lib/components/Grid/**/*.scss", @@ -74,6 +75,8 @@ export default { "src/lib/components/RadioGroup/**/*.scss", "src/lib/components/Select/**/*.scss", "src/lib/components/Skeleton/**/*.scss", + "src/lib/components/Slider/**/*.scss", + "src/lib/components/SliderRange/**/*.scss", "src/lib/components/Switch/**/*.scss", "src/lib/components/Tab/**/*.scss", "src/lib/components/Text/**/*.scss",