Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ automatisch mit [git-cliff](https://git-cliff.org) aus den Commit-Messages gener
- **icons**: Hochgeladene SVG-Symbole nehmen die Textfarbe an
- **calendar**: Schichtzeiten immer mit Minuten
- **weather**: Temperaturdiagramm so scharf wie der übrige Text
- **bring**: Kacheln schneiden Symbole und Namen nicht mehr ab

## [0.9.1] - 2026-11-14

Expand Down
60 changes: 60 additions & 0 deletions web/src/features/modules/bring/FitName.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { cleanup, render } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { FitName } from './FitName.tsx'

const clientWidth = 100
const charWidthPerPx = 0.5 // widest word of n chars at s px is n * s * 0.5 wide

beforeEach(() => {
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(clientWidth)
vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(function (this: HTMLElement) {
const size = parseFloat(this.style.fontSize) || 16
const longest = Math.max(...(this.textContent ?? '').split(' ').map((w) => w.length))
return longest * size * charWidthPerPx
})
vi.spyOn(window, 'getComputedStyle').mockReturnValue({ fontSize: '16px', lineHeight: '19.2px' } as CSSStyleDeclaration)
})

afterEach(() => {
cleanup()
vi.restoreAllMocks()
})

describe('FitName', () => {
it('sets no inline style when the name fits', () => {
const { container } = render(<FitName name="Milch" />)
const el = container.querySelector('.mirror-bring__name') as HTMLElement
expect(el.style.fontSize).toBe('')
expect(el.style.lineHeight).toBe('')
expect(el.classList.contains('mirror-bring__name--break')).toBe(false)
})

it('shrinks a too wide word until it fits and keeps the base line height', () => {
// 15 chars: 120px at 16px, needs <= 13.33px
const { container } = render(<FitName name="Fünfzehnzeichen" />)
const el = container.querySelector('.mirror-bring__name') as HTMLElement
const size = parseFloat(el.style.fontSize)
expect(size).toBeLessThan(16)
expect(size).toBeGreaterThanOrEqual(16 * 0.7)
expect(15 * size * charWidthPerPx).toBeLessThanOrEqual(clientWidth)
expect(15 * (size + 0.5) * charWidthPerPx).toBeGreaterThan(clientWidth)
expect(el.style.lineHeight).toBe('19.2px')
expect(el.classList.contains('mirror-bring__name--break')).toBe(false)
})

it('stops at 70 percent and allows breaking inside the word', () => {
const { container } = render(<FitName name="Donaudampfschifffahrtsgesellschaft" />)
const el = container.querySelector('.mirror-bring__name') as HTMLElement
expect(parseFloat(el.style.fontSize)).toBeCloseTo(16 * 0.7, 5)
expect(el.classList.contains('mirror-bring__name--break')).toBe(true)
})

it('removes the inline style again when the name changes to a short one', () => {
const { container, rerender } = render(<FitName name="Fünfzehnzeichen" />)
const el = container.querySelector('.mirror-bring__name') as HTMLElement
expect(el.style.fontSize).not.toBe('')
rerender(<FitName name="Ei" />)
expect(el.style.fontSize).toBe('')
expect(el.style.lineHeight).toBe('')
})
})
68 changes: 68 additions & 0 deletions web/src/features/modules/bring/FitName.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { useLayoutEffect, useRef } from 'react'

/** The smallest the name may get, as a share of its normal size. */
const minScale = 0.7
const step = 0.5

/**
* Shrinks `el` until its widest word fits, in steps of half a pixel. The line height stays that of the normal
* size (set in px) so a shrunk name keeps the line of its neighbours. When even the smallest size does not fit,
* the word may break inside itself - text is never clipped.
*/
function fit(el: HTMLElement) {
el.style.fontSize = ''
el.style.lineHeight = ''
el.classList.remove('mirror-bring__name--break')
if (el.scrollWidth <= el.clientWidth) return
const computed = getComputedStyle(el)
const base = parseFloat(computed.fontSize)
if (!Number.isFinite(base)) return
const lineHeight = parseFloat(computed.lineHeight)
const linePx = Number.isFinite(lineHeight) ? lineHeight : base * 1.2
const floor = base * minScale
el.style.lineHeight = `${linePx}px`
let size = base
while (size - step >= floor - 1e-9) {
size -= step
el.style.fontSize = `${size}px`
if (el.scrollWidth <= el.clientWidth) return
}
el.style.fontSize = `${floor}px`
el.classList.add('mirror-bring__name--break')
}

/** An item name that wraps at spaces and shrinks, instead of being cut off, when a single word is too wide. */
export function FitName({ name }: { name: string }) {
const ref = useRef<HTMLSpanElement>(null)
useLayoutEffect(() => {
const el = ref.current
if (!el) return
let active = true
const run = () => {
if (active) fit(el)
}
run()
let observer: ResizeObserver | undefined
if (typeof ResizeObserver !== 'undefined') {
let lastWidth = el.clientWidth
// Fitting changes the element's own height, not its width; comparing widths avoids a feedback loop.
observer = new ResizeObserver(() => {
if (el.clientWidth === lastWidth) return
lastWidth = el.clientWidth
run()
})
observer.observe(el)
}
// The font loads late via @font-face and changes every measurement.
if (typeof document !== 'undefined' && document.fonts?.ready) void document.fonts.ready.then(run)
return () => {
active = false
observer?.disconnect()
}
}, [name])
return (
<span ref={ref} className="mirror-bring__name">
{name}
</span>
)
}
64 changes: 64 additions & 0 deletions web/src/features/modules/bring/Widget.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,70 @@ describe('bring widget', () => {
expect(container.querySelectorAll('.mirror-bring__fallback')).toHaveLength(1)
})

it('shows an emoji-only name once, as the symbol, without a name below', async () => {
setup(state([{ name: '🥛', iconUrl: '' }]))
const { container } = renderWithProviders('/')
await waitFor(() => expect(container.querySelector('.mirror-bring__emoji')).not.toBeNull())
expect(container.querySelectorAll('.mirror-bring__item')).toHaveLength(1)
expect(screen.getAllByText('🥛')).toHaveLength(1)
expect(container.querySelector('.mirror-bring__name')).toBeNull()
})

it('keeps the specification of an emoji-only name', async () => {
setup(state([{ name: '🥛', iconUrl: '', specification: '2 Liter' }]))
const { container } = renderWithProviders('/')
await screen.findByText('2 Liter')
expect(container.querySelector('.mirror-bring__name')).toBeNull()
})

it('shows the emoji as the symbol, without a name, when its picture fails to load', async () => {
setup(state([{ name: '🥛', iconUrl: 'https://example.test/milk.png' }]))
const { container } = renderWithProviders('/')
const img = await waitFor(() => {
const found = container.querySelector('img')
expect(found).not.toBeNull()
return found!
})
fireEvent.error(img)
await waitFor(() => expect(container.querySelector('.mirror-bring__emoji')).toHaveTextContent('🥛'))
expect(screen.getAllByText('🥛')).toHaveLength(1)
expect(container.querySelector('.mirror-bring__name')).toBeNull()
})

it('shows picture plus the emoji as name when the picture loads', async () => {
setup(state([{ name: '🥛', iconUrl: 'https://example.test/milk.png' }]))
const { container } = renderWithProviders('/')
await waitFor(() => expect(container.querySelector('img')).not.toBeNull())
expect(container.querySelector('.mirror-bring__name')).toHaveTextContent('🥛')
expect(container.querySelector('.mirror-bring__emoji')).toBeNull()
})

it('fits a name whose word is wider than the tile and leaves a short one alone', async () => {
const realComputed = window.getComputedStyle.bind(window)
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(100)
vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(function (this: HTMLElement) {
if (!this.classList.contains('mirror-bring__name')) return 0
const size = parseFloat(this.style.fontSize) || 16
return Math.max(...(this.textContent ?? '').split(' ').map((w) => w.length)) * size * 0.5
})
// Only the name gets the stub; everything else keeps the real computed style.
vi.spyOn(window, 'getComputedStyle').mockImplementation((el, pseudo) =>
el instanceof HTMLElement && el.classList.contains('mirror-bring__name')
? ({ fontSize: '16px', lineHeight: '19.2px' } as CSSStyleDeclaration)
: realComputed(el, pseudo),
)
try {
setup(state([item('Fünfzehnzeichen'), item('Ei')]))
renderWithProviders('/')
const long = await screen.findByText('Fünfzehnzeichen')
const short = await screen.findByText('Ei')
expect(parseFloat(long.style.fontSize)).toBeLessThan(16)
expect(short.style.fontSize).toBe('')
} finally {
vi.restoreAllMocks()
}
})

it('renders nothing when not configured', async () => {
const api = setup({ configured: false, stale: false, items: [] })
renderWithProviders('/')
Expand Down
36 changes: 20 additions & 16 deletions web/src/features/modules/bring/Widget.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useState } from 'react'
import { useState, type ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import type { BringItem } from './api.ts'
import { dashboardBringQueryKey, fetchDashboardBring } from './api.ts'
import { FitName } from './FitName.tsx'
import './bring.css'

export const columns = 6
Expand All @@ -13,14 +14,25 @@ function isEmojiOnly(value: string) {
return /^\p{Extended_Pictographic}️?$/u.test(value.trim())
}

function BringIcon({ item }: { item: BringItem }) {
/** One tile. The emoji is shown as the symbol when no picture is, and then needs no second appearance as the name. */
function BringTile({ item }: { item: BringItem }) {
const [failed, setFailed] = useState(false)
if (item.iconUrl && !failed) {
return <img className="mirror-bring__icon" src={item.iconUrl} alt="" onError={() => setFailed(true)} />
}
const name = item.name.trim()
if (isEmojiOnly(name)) return <span className="mirror-bring__emoji">{name}</span>
return <span className="mirror-bring__fallback">{Array.from(name)[0]?.toLocaleUpperCase('de-DE')}</span>
const hasPicture = Boolean(item.iconUrl) && !failed
const emojiSymbol = !hasPicture && isEmojiOnly(name)
let icon: ReactNode
if (hasPicture) icon = <img className="mirror-bring__icon" src={item.iconUrl} alt="" onError={() => setFailed(true)} />
else if (emojiSymbol) icon = <span className="mirror-bring__emoji">{name}</span>
else icon = <span className="mirror-bring__fallback">{Array.from(name)[0]?.toLocaleUpperCase('de-DE')}</span>
return (
<li className="mirror-bring__item">
<div className="mirror-bring__icon-slot">{icon}</div>
<div className="mirror-bring__label">
{!emojiSymbol && <FitName name={item.name} />}
{item.specification && <span className="mirror-bring__specification">{item.specification}</span>}
</div>
</li>
)
}

export function BringWidget() {
Expand Down Expand Up @@ -55,15 +67,7 @@ export function BringWidget() {
{rows.map((row, rowIndex) => (
<ul className="mirror-bring__list" key={rowIndex}>
{row.map((item) => (
<li key={`${item.name}\u001f${item.specification ?? ''}`} className="mirror-bring__item">
<div className="mirror-bring__icon-slot">
<BringIcon item={item} />
</div>
<div className="mirror-bring__label">
<span className="mirror-bring__name">{item.name}</span>
{item.specification && <span className="mirror-bring__specification">{item.specification}</span>}
</div>
</li>
<BringTile key={`${item.name}\u001f${item.specification ?? ''}`} item={item} />
))}
</ul>
))}
Expand Down
33 changes: 17 additions & 16 deletions web/src/features/modules/bring/bring.css
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/* Port of SmartMirror2's shopping list; the region already anchors it to the bottom left. */
/* Port of SmartMirror2's shopping list; the region already anchors it to the bottom left. Only the 140px wifi code
shares the bottom edge, so the list may take most of the width. */
.mirror-bring {
background: transparent;
box-sizing: border-box;
max-width: min(720px, 60vw);
max-width: 100%;
padding: clamp(.7rem, 1.7vw, 1rem);
pointer-events: none;
width: min(720px, 60vw);
width: min(880px, 62vw);
}
/* column-reverse: the first row of items sits at the bottom edge. */
.mirror-bring__rows { display: flex; flex-direction: column-reverse; gap: clamp(.55rem, .8vw, .65rem); width: 100%; }
Expand All @@ -14,6 +15,7 @@
font-size: clamp(.9rem, 1.05vw, 1.05rem);
gap: clamp(.55rem, .8vw, .65rem);
grid-template-columns: repeat(6, minmax(0, 1fr));
align-items: start;
letter-spacing: .06rem;
list-style: none;
margin: 0;
Expand All @@ -22,37 +24,32 @@
}
.mirror-bring__item {
align-items: center;
aspect-ratio: 1;
border-radius: 6px;
box-sizing: border-box;
display: flex;
flex-direction: column;
font-weight: 700;
gap: .35rem;
justify-content: space-between;
justify-content: flex-start;
min-width: 0;
overflow: hidden;
padding: .6rem .5rem;
text-align: center;
width: 100%;
word-break: break-word;
}
.mirror-bring__icon-slot { align-items: center; display: flex; height: clamp(64px, 5vw, 76px); justify-content: center; text-align: center; width: 100%; }
.mirror-bring__icon-slot { align-items: center; display: flex; height: 80px; justify-content: center; text-align: center; width: 100%; }
/* Bring!'s pictures are coloured; the mirror wants them white. */
.mirror-bring__icon {
display: block;
filter: brightness(0) invert(1);
height: clamp(48px, 4.6vw, 64px);
height: 80px;
object-fit: contain;
transform: scale(1.4);
transform-origin: center;
width: clamp(48px, 4.6vw, 64px);
width: 80px;
}
.mirror-bring__emoji { display: block; font-size: clamp(2rem, 3vw, 2.5rem); line-height: 1; transform: scale(1.4); transform-origin: center; }
.mirror-bring__emoji { display: block; font-size: 4.4rem; line-height: 1; }
.mirror-bring__fallback {
align-items: center;
display: flex;
font-size: clamp(2.4rem, 4vw, 3.6rem);
font-size: 3.6rem;
font-weight: 700;
height: 100%;
justify-content: center;
Expand All @@ -61,5 +58,9 @@
width: 100%;
}
.mirror-bring__label { align-items: center; display: flex; flex-direction: column; gap: .15rem; line-height: 1.2; min-width: 0; text-align: center; width: 100%; }
.mirror-bring__name, .mirror-bring__specification { max-width: 100%; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.mirror-bring__specification { color: var(--mirror-muted); font-size: clamp(.78rem, .95vw, .9rem); font-weight: 600; }
/* Nothing is clipped: text wraps at spaces; FitName shrinks a word wider than the tile and, as a last resort, adds --break. */
.mirror-bring__name, .mirror-bring__specification { max-width: 100%; min-width: 0; white-space: normal; }
/* Explicit, so nothing inherited can split a word before FitName has measured it. */
.mirror-bring__name { overflow-wrap: normal; word-break: normal; }
.mirror-bring__name--break { overflow-wrap: anywhere; }
.mirror-bring__specification { color: var(--mirror-muted); font-size: clamp(.78rem, .95vw, .9rem); font-weight: 600; overflow-wrap: anywhere; }
26 changes: 26 additions & 0 deletions web/src/features/modules/bring/bringCss.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,30 @@ describe('bring.css', () => {
expect(match).not.toBeNull()
expect(Number(match![1])).toBe(columns)
})

it('never clips a tile, its icon or its texts', () => {
const item = declarations('.mirror-bring__item')
expect(item).not.toMatch(/aspect-ratio/)
expect(item).not.toMatch(/overflow:\s*hidden/)
expect(declarations('.mirror-bring__icon')).not.toMatch(/transform:/)
expect(declarations('.mirror-bring__emoji')).not.toMatch(/transform:/)
for (const selector of ['.mirror-bring__name, .mirror-bring__specification', '.mirror-bring__specification']) {
const rule = declarations(selector)
expect(rule).not.toMatch(/nowrap|text-overflow/)
}
expect(css).not.toMatch(/nowrap|text-overflow|aspect-ratio|(?<![-\w])transform:/)
})

it('is 880px wide at most', () => {
expect(declarations('.mirror-bring')).toMatch(/width:\s*min\(880px,\s*62vw\)/)
})

it('breaks inside a word only for the last-resort name class and the specification', () => {
for (const selector of ['.mirror-bring__item', '.mirror-bring__label', '.mirror-bring__list', '.mirror-bring__name']) {
expect(declarations(selector), selector).not.toMatch(/break-word|anywhere|break-all/)
}
expect(declarations('.mirror-bring__name')).toMatch(/overflow-wrap:\s*normal/)
expect(declarations('.mirror-bring__name')).toMatch(/word-break:\s*normal/)
expect(declarations('.mirror-bring__name--break')).toMatch(/overflow-wrap:\s*anywhere/)
})
})
Loading