Skip to content

Commit

Permalink
Ensure govuk-font-size() handles string keys
Browse files Browse the repository at this point in the history
This lets us treat 14, “14”, “_14” and named “x-large” size keys equally
  • Loading branch information
colinrotherham committed Feb 2, 2024
1 parent eb3c18d commit 1ed26b0
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 3 deletions.
17 changes: 14 additions & 3 deletions packages/govuk-frontend/src/govuk/helpers/_typography.scss
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,22 @@
/// @access public

@mixin govuk-font-size($size, $line-height: false, $important: false) {
@if not map-has-key($govuk-typography-scale, $size) {
@error "Unknown font size `#{$size}` - expected a point from the type scale.";
// Check for a font map exactly matching the given size
$font-map: map-get($govuk-typography-scale, $size);

// No match? Try with string type (e.g. $size: "16" not 16)
@if not $font-map {
@each $font-size in map-keys($govuk-typography-scale) {
@if not $font-map and #{$font-size} == #{$size} {
$font-map: map-get($govuk-typography-scale, $font-size);
}
}
}

$font-map: map-get($govuk-typography-scale, $size);
// Still no match? Throw error
@if not $font-map {
@error "Unknown font size `#{$size}` - expected a point from the type scale.";
}

// Check for a deprecation within the type scale
$deprecation: map-get($font-map, "deprecation");
Expand Down
67 changes: 67 additions & 0 deletions packages/govuk-frontend/src/govuk/helpers/typography.unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,73 @@ describe('@mixin govuk-font-size', () => {
})
})

it('outputs CSS when passing size as a string', async () => {
const sass = `
${sassBootstrap}
.foo {
@include govuk-font-size($size: "14")
}
`

await expect(compileSassString(sass)).resolves.toMatchObject({
css: outdent`
.foo {
font-size: 0.75rem;
line-height: 1.25;
}
@media (min-width: 30em) {
.foo {
font-size: 0.875rem;
line-height: 1.4285714286;
}
}
`
})
})

it('outputs CSS using points as strings', async () => {
const sass = `
$govuk-breakpoints: (
desktop: 30em
);
$govuk-typography-scale: (
"small": (
null: (
font-size: 12px,
line-height: 15px
),
print: (
font-size: 14pt,
line-height: 1.5
)
)
);
@import "base";
.foo {
@include govuk-font-size($size: "small")
}
`

await expect(compileSassString(sass)).resolves.toMatchObject({
css: outdent`
.foo {
font-size: 0.75rem;
line-height: 1.25;
}
@media print {
.foo {
font-size: 14pt;
line-height: 1.5;
}
}
`
})
})

it('throws an exception when passed a size that is not in the scale', async () => {
const sass = `
${sassBootstrap}
Expand Down

0 comments on commit 1ed26b0

Please sign in to comment.