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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ Das Format basiert auf [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
automatisch mit [git-cliff](https://git-cliff.org) aus den Commit-Messages generiert –
**nicht von Hand bearbeiten**.

## [Unreleased]

### Changed

- Tags nur noch für festgehaltene Versionen

### Fixed

- **icons**: Hochgeladene SVG-Symbole nehmen die Textfarbe an

## [0.9.1] - 2026-11-14

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ Pi 5 · Ubuntu 26.04 Server · Host: nur Docker

1. **README.md prüfen und ggf. aktualisieren** – wenn die Phase Struktur, Setup, Architektur, Prüfbefehle, Deployment oder Abhängigkeiten ändert.
2. **Commit mit Conventional Commit** – Autor und Committer jedes Commits ist **`Thazzr <22547926+Thazzr@users.noreply.github.com>`** (Nutzerentscheidung 2026-11-14: kein Klarname, keine private oder Firmen-E-Mail in der Historie; die lokale Git-Konfiguration des Repos ist so gesetzt, in einem frischen Klon vor dem ersten Commit `git config user.name Thazzr` und `git config user.email 22547926+Thazzr@users.noreply.github.com`). Ein per cherry-pick übernommener Commit bekommt danach `git commit --amend --no-edit --reset-author`. Format `type(scope): beschreibung`, Betreff auf Deutsch. Der Betreff wird zur Changelog-Zeile, deshalb **immer einen Body** mit Ursache bzw. Anlass, Lösung und Prüfung. Typ → Sektion: `feat`→Added, `fix`→Fixed, `perf`/`refactor`/`docs`/`test`/`chore`/`build`/`style`→Changed, `revert`→Removed, `fix(sec…)`/`sec…`→Security. `ci` erscheint nicht im Changelog.
3. **Versions-Tag setzen + CHANGELOG.md erzeugen (nie von Hand editieren)** – Bei einer eigenständig abgeschlossenen Phase setzt `node tools/changelog.mjs --tag v0.X.0 --message "<Kurzbeschreibung>"` einen annotierten Tag auf HEAD und erzeugt `CHANGELOG.md` neu. Bei einem Zwischenschritt genügt `node tools/changelog.mjs` ohne Tag. Die neue `CHANGELOG.md` wird als eigener Commit `docs(changelog): update` committet (erscheint selbst nicht im Changelog).
3. **Versions-Tag setzen + CHANGELOG.md erzeugen (nie von Hand editieren)** – Nutzerentscheidung 2026-11-14: Kleine Korrekturen gehen ohne Tag raus (Merge nach `main` reicht, der Spiegel holt `latest`); ein Tag kommt nur, wenn der Nutzer einen Stand als Version festhalten will. Bei einer eigenständig abgeschlossenen Phase setzt `node tools/changelog.mjs --tag v0.X.0 --message "<Kurzbeschreibung>"` einen annotierten Tag auf HEAD und erzeugt `CHANGELOG.md` neu. Bei einem Zwischenschritt genügt `node tools/changelog.mjs` ohne Tag. Die neue `CHANGELOG.md` wird als eigener Commit `docs(changelog): update` committet (erscheint selbst nicht im Changelog).
4. **Pushen** – den Branch und den neuen Tag pushen. Der Cloud-Container ist flüchtig, lokale Tags gingen sonst verloren (bewusste Abweichung von Core). Verweigert die Umgebung den Tag-Push (die Cloud-Sitzung erlaubt nur Pushes auf ihren Arbeits-Branch, ein Tag-Push endet mit HTTP 403), wird das nicht umgangen: Die Hauptsitzung nennt dem Nutzer Tag, Commit und Tag-Nachricht, damit er ihn selbst setzt (`git tag -a vX.Y.Z <commit> -m "<nachricht>"` und `git push origin vX.Y.Z`).
5. **Nächste Schritte vorschlagen.**
6. **Keine offenen Änderungen mitschleifen** – vor Beginn der nächsten Phase ist `git status` sauber.
Expand Down
3 changes: 3 additions & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1640,6 +1640,9 @@ components:
file:
type: string
description: Id of an uploaded icon, for kind `upload`.
contentType:
type: string
description: Set by the server for kind `upload` in responses (for example `image/svg+xml`, `image/png`); ignored on input.
Icon:
type: object
description: An uploaded icon.
Expand Down
3 changes: 3 additions & 0 deletions server/internal/api/api.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 25 additions & 16 deletions server/internal/api/calendar.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,23 @@ import (
"github.com/thazzr/mirrornextgen/server/internal/settings"
)

func iconRefOut(kind, name, file string) IconRef {
// iconRefOut builds the response form of an icon reference. For an upload the
// content type comes from the icon store, so the client can tell an SVG (drawn
// in the text colour) from a PNG; an unknown id leaves it empty.
func (s *Server) iconRefOut(kind, name, file string) IconRef {
if kind == "" {
kind = string(None)
}
return IconRef{Kind: IconRefKind(kind), Name: optional(name), File: optional(file)}
ref := IconRef{Kind: IconRefKind(kind), Name: optional(name), File: optional(file)}
if kind == string(Upload) && file != "" && s.icons != nil {
if ic, ok := s.icons.Get(file); ok {
ref.ContentType = optional(ic.ContentType)
}
}
return ref
}

func toIconRef(r settings.IconRef) IconRef { return iconRefOut(r.Kind, r.Name, r.File) }
func (s *Server) toIconRef(r settings.IconRef) IconRef { return s.iconRefOut(r.Kind, r.Name, r.File) }

func fromIconRef(r IconRef) settings.IconRef {
return settings.IconRef{Kind: string(r.Kind), Name: deref(r.Name), File: deref(r.File)}
Expand All @@ -41,7 +50,7 @@ func fromHighlight(h CalendarHighlight) settings.CalendarHighlight {
}
}

func toCalendarSettings(c settings.CalendarSettings) CalendarSettings {
func (s *Server) toCalendarSettings(c settings.CalendarSettings) CalendarSettings {
out := CalendarSettings{
RefreshMinutes: c.RefreshMinutes,
Calendars: make([]CalendarSource, 0, len(c.Calendars)),
Expand All @@ -51,7 +60,7 @@ func toCalendarSettings(c settings.CalendarSettings) CalendarSettings {
for _, cal := range c.Calendars {
// The address stays on the server; only a shortened hint leaves it.
out.Calendars = append(out.Calendars, CalendarSource{
Id: cal.ID, Name: cal.Name, Icon: toIconRef(cal.Icon),
Id: cal.ID, Name: cal.Name, Icon: s.toIconRef(cal.Icon),
HasUrl: cal.URL != "", UrlHint: settings.URLHint(cal.URL),
})
}
Expand All @@ -65,15 +74,15 @@ func toCalendarSettings(c settings.CalendarSettings) CalendarSettings {
for _, sh := range sec.Shifts {
o.Shifts = append(o.Shifts, CalendarShift{
Id: sh.ID, Match: sh.Match, MatchMode: CalendarShiftMatchMode(sh.MatchMode), Label: sh.Label,
Start: sh.Start, End: sh.End, Icon: toIconRef(sh.Icon),
Start: sh.Start, End: sh.End, Icon: s.toIconRef(sh.Icon),
})
}
out.Sections = append(out.Sections, o)
}
for _, r := range c.Rules {
out.Rules = append(out.Rules, CalendarRule{
Id: r.ID, CalendarIds: r.CalendarIDs, MatchMode: CalendarRuleMatchMode(r.MatchMode), Text: r.Text,
Action: CalendarRuleAction(r.Action), Icon: toIconRef(r.Icon), RenameTo: r.RenameTo,
Action: CalendarRuleAction(r.Action), Icon: s.toIconRef(r.Icon), RenameTo: r.RenameTo,
})
}
return out
Expand Down Expand Up @@ -144,23 +153,23 @@ func calendarConfig(c settings.CalendarSettings) calendar.Config {
return cfg
}

func calIcon(r calendar.IconRef) IconRef { return iconRefOut(r.Kind, r.Name, r.File) }
func (s *Server) calIcon(r calendar.IconRef) IconRef { return s.iconRefOut(r.Kind, r.Name, r.File) }

func toShiftDays(days []calendar.ShiftDay) []ShiftDay {
func (s *Server) toShiftDays(days []calendar.ShiftDay) []ShiftDay {
out := make([]ShiftDay, 0, len(days))
for _, d := range days {
date, err := time.Parse(time.DateOnly, d.Date)
if err != nil {
continue // the engine formats the date itself; cannot happen
}
out = append(out, ShiftDay{Date: openapi_types.Date{Time: date}, DayLabel: d.DayLabel, Title: d.Title, TimeRange: optional(d.TimeRange), Icon: calIcon(d.Icon), Free: d.Free, Ongoing: d.Ongoing, HighlightColor: optional(d.HighlightColor)})
out = append(out, ShiftDay{Date: openapi_types.Date{Time: date}, DayLabel: d.DayLabel, Title: d.Title, TimeRange: optional(d.TimeRange), Icon: s.calIcon(d.Icon), Free: d.Free, Ongoing: d.Ongoing, HighlightColor: optional(d.HighlightColor)})
}
return out
}

// GetCalendarSettings returns the calendar settings without the addresses.
func (s *Server) GetCalendarSettings(_ context.Context, _ GetCalendarSettingsRequestObject) (GetCalendarSettingsResponseObject, error) {
return GetCalendarSettings200JSONResponse(toCalendarSettings(s.settings.Get().Calendar)), nil
return GetCalendarSettings200JSONResponse(s.toCalendarSettings(s.settings.Get().Calendar)), nil
}

// UpdateCalendarSettings stores new calendar settings and drops the cached
Expand All @@ -178,7 +187,7 @@ func (s *Server) UpdateCalendarSettings(_ context.Context, request UpdateCalenda
return UpdateCalendarSettings400ApplicationProblemPlusJSONResponse{BadRequestApplicationProblemPlusJSONResponse(badRequest(errs))}, nil
}
s.calendar.Invalidate()
return UpdateCalendarSettings200JSONResponse(toCalendarSettings(stored)), nil
return UpdateCalendarSettings200JSONResponse(s.toCalendarSettings(stored)), nil
}

// PreviewCalendar evaluates an unsaved draft against the real feeds.
Expand All @@ -199,7 +208,7 @@ func (s *Server) PreviewCalendar(ctx context.Context, request PreviewCalendarReq
o := CalendarPreviewSection{Id: sec.ID, Title: sec.Title, Type: CalendarPreviewSectionType(sec.Type), Error: optional(sec.Error)}
switch {
case sec.Type == calendar.TypeShifts && sec.Days != nil:
days := toShiftDays(sec.Days)
days := s.toShiftDays(sec.Days)
o.Days = &days
case sec.Type == calendar.TypeList:
items := make([]PreviewItem, 0, len(sec.Candidates))
Expand All @@ -210,7 +219,7 @@ func (s *Server) PreviewCalendar(ctx context.Context, request PreviewCalendarReq
}
items = append(items, PreviewItem{
Title: p.Title, OriginalTitle: p.OriginalTitle, Location: optional(p.Location), TimeLabel: p.TimeLabel,
Relative: p.Relative, Icon: calIcon(p.Icon), AllDay: p.AllDay, Ongoing: p.Ongoing, HighlightColor: optional(p.HighlightColor),
Relative: p.Relative, Icon: s.calIcon(p.Icon), AllDay: p.AllDay, Ongoing: p.Ongoing, HighlightColor: optional(p.HighlightColor),
Hidden: p.Hidden, Shown: p.Shown, MatchedRules: rules, CalendarId: p.CalendarID, Start: p.Start,
})
}
Expand All @@ -231,7 +240,7 @@ func (s *Server) GetDashboardCalendarSection(ctx context.Context, request GetDas
out := GetDashboardCalendarSection200JSONResponse{Id: res.ID, Title: res.Title, Type: DashboardCalendarSectionType(res.Type), Error: optional(res.Error)}
if res.Type == calendar.TypeShifts {
if res.Days != nil {
days := toShiftDays(res.Days)
days := s.toShiftDays(res.Days)
out.Days = &days
}
return out, nil
Expand All @@ -240,7 +249,7 @@ func (s *Server) GetDashboardCalendarSection(ctx context.Context, request GetDas
for _, it := range res.Items {
items = append(items, DashboardCalendarItem{
Title: it.Title, Location: optional(it.Location), TimeLabel: it.TimeLabel, Relative: it.Relative,
Icon: calIcon(it.Icon), AllDay: it.AllDay, Ongoing: it.Ongoing, HighlightColor: optional(it.HighlightColor),
Icon: s.calIcon(it.Icon), AllDay: it.AllDay, Ongoing: it.Ongoing, HighlightColor: optional(it.HighlightColor),
})
}
out.Items = &items
Expand Down
89 changes: 89 additions & 0 deletions server/internal/api/calendaricon_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package api

import (
"net/http"
"testing"

"github.com/thazzr/mirrornextgen/server/internal/icons"
)

func uploadPNG(t *testing.T, e *testEnv, c creds) string {
t.Helper()
rec := upload(e, c, goodPNG, "haus.png", nil)
if rec.Code != http.StatusCreated {
t.Fatalf("upload %d: %s", rec.Code, rec.Body)
}
return decode[Icon](t, rec).Id
}

func ctOf(r IconRef) string {
if r.ContentType == nil {
return ""
}
return *r.ContentType
}

func TestUploadedIconsCarryTheirContentTypeInResponses(t *testing.T) {
e := newTestEnv(t)
c := e.setup(t)
svg, png := uploadSVG(t, e, c), uploadPNG(t, e, c)

body := calBody(e)
body.Calendars[0].Icon = IconRef{Kind: Upload, File: sptr(svg)}
body.Sections[1].Shifts[0].Icon = IconRef{Kind: Upload, File: sptr(png)}
body.Rules = []CalendarRule{{Id: "r1", CalendarIds: []string{"familie"}, MatchMode: "contains", Text: "Standup", Action: CalendarRuleActionIcon, Icon: IconRef{Kind: Upload, File: sptr(svg)}}}
putCalendar(t, e, c, body)

// Settings GET: calendar, shift and rule icons.
got := decode[CalendarSettings](t, e.do(http.MethodGet, calSettingsPath, nil, opts{cookie: c.cookie}))
if ctOf(got.Calendars[0].Icon) != "image/svg+xml" || ctOf(got.Sections[1].Shifts[0].Icon) != "image/png" || ctOf(got.Rules[0].Icon) != "image/svg+xml" {
t.Errorf("settings = %+v", got)
}
if got.Calendars[1].Icon.ContentType != nil {
t.Error("an icon of kind none carries no content type")
}

// Dashboard list item (public).
list := decode[DashboardCalendarSection](t, e.do(http.MethodGet, "/api/v1/dashboard/calendar/termine", nil, opts{}))
if len(*list.Items) == 0 || ctOf((*list.Items)[0].Icon) != "image/svg+xml" {
t.Errorf("list item = %+v", *list.Items)
}
// Dashboard shift row.
shifts := decode[DashboardCalendarSection](t, e.do(http.MethodGet, "/api/v1/dashboard/calendar/plan", nil, opts{}))
days := *shifts.Days
if ctOf(days[3].Icon) != "image/png" {
t.Errorf("shift day = %+v", days[3])
}
// Preview.
pv := decode[CalendarPreview](t, e.do(http.MethodPost, calPreviewPath, body, opts{cookie: c.cookie, csrf: c.csrf}))
found := false
for _, sec := range pv.Sections {
if sec.Items != nil {
for _, it := range *sec.Items {
if it.Icon.Kind == Upload {
found = true
if ctOf(it.Icon) != "image/svg+xml" {
t.Errorf("preview item = %+v", it.Icon)
}
}
}
}
}
if !found {
t.Error("preview has no upload icon")
}
}

func TestIconRefOutLeavesUnknownIdsWithoutContentType(t *testing.T) {
store, err := icons.Load(t.TempDir())
if err != nil {
t.Fatal(err)
}
s := &Server{icons: store}
if r := s.iconRefOut("upload", "", "abcdefgh12345678"); r.ContentType != nil {
t.Errorf("unknown id = %+v", r)
}
if r := s.iconRefOut("bootstrap", "house", ""); r.ContentType != nil {
t.Errorf("bootstrap = %+v", r)
}
}
20 changes: 15 additions & 5 deletions web/src/features/admin/components/IconPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useMemo } from 'react'
import { Group, Select, type ComboboxItem, type ComboboxItemGroup } from '@mantine/core'
import { useQuery } from '@tanstack/react-query'
import 'bootstrap-icons/font/bootstrap-icons.css'
import { MaskIcon } from '../../../shared/MaskIcon.tsx'
import { fetchIcons, iconFileUrl, iconsQueryKey, type IconRef } from '../api/icons.ts'
import { BOOTSTRAP_ICONS } from './bootstrapIcons.ts'

Expand All @@ -16,10 +17,13 @@ function decode(value: string): IconRef {
return { kind: 'none' }
}

function Preview({ value }: { value: string }) {
function Preview({ value, svgIds }: { value: string; svgIds: ReadonlySet<string> }) {
if (value.startsWith('bootstrap:')) return <i className={`bi bi-${value.slice('bootstrap:'.length)}`} aria-hidden />
if (value.startsWith('upload:'))
return <img src={iconFileUrl(value.slice('upload:'.length))} alt="" width={18} height={18} style={{ objectFit: 'contain' }} />
if (value.startsWith('upload:')) {
const id = value.slice('upload:'.length)
if (svgIds.has(id)) return <MaskIcon src={iconFileUrl(id)} size={18} />
return <img src={iconFileUrl(id)} alt="" width={18} height={18} style={{ objectFit: 'contain' }} />
}
return null
}

Expand All @@ -34,6 +38,12 @@ type Props = {
export function IconPicker({ label, value, onChange, error }: Props) {
const uploads = useQuery({ queryKey: iconsQueryKey, queryFn: fetchIcons })
const current = encode(value)
// Ids of SVG uploads; the reference itself may carry the type when the list is not loaded yet.
const svgIds = useMemo(() => {
const ids = new Set((uploads.data ?? []).filter((i) => i.contentType === 'image/svg+xml').map((i) => i.id))
if (value.kind === 'upload' && value.file && value.contentType === 'image/svg+xml') ids.add(value.file)
return ids
}, [uploads.data, value])

const data = useMemo<Array<ComboboxItem | ComboboxItemGroup<ComboboxItem>>>(() => {
const own: ComboboxItem[] = (uploads.data ?? []).map((i) => ({ value: `upload:${i.id}`, label: i.name }))
Expand All @@ -60,11 +70,11 @@ export function IconPicker({ label, value, onChange, error }: Props) {
searchable
allowDeselect={false}
nothingFoundMessage="Kein Symbol gefunden"
leftSection={<Preview value={current} />}
leftSection={<Preview value={current} svgIds={svgIds} />}
renderOption={({ option }) => (
<Group gap="xs" wrap="nowrap">
<span style={{ display: 'inline-flex', width: 20, justifyContent: 'center' }}>
<Preview value={option.value} />
<Preview value={option.value} svgIds={svgIds} />
</span>
<span>{option.label}</span>
</Group>
Expand Down
27 changes: 26 additions & 1 deletion web/src/features/admin/icons.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,13 @@ describe('icons page', () => {
const { container } = await openIcons()
expectSinglePageTitle('Symbole')
expect(screen.getByRole('group', { name: 'Stern' })).toBeInTheDocument()
// A PNG stays an image; an SVG is a mask in the text colour, so it shows on the dark page.
const imgs = [...container.querySelectorAll('img')].map((i) => i.getAttribute('src'))
expect(imgs).toEqual(['/api/v1/icons/ic1/file', '/api/v1/icons/ic2/file'])
expect(imgs).toEqual(['/api/v1/icons/ic1/file'])
const masks = [...container.querySelectorAll<HTMLElement>('span[aria-hidden="true"]')].filter((m) => m.style.maskImage)
expect(masks).toHaveLength(1)
expect(masks[0].style.maskImage).toContain('/api/v1/icons/ic2/file')
expect(within(screen.getByRole('group', { name: 'Stern' })).queryByRole('img', { hidden: true })).toBeNull()
})

it('says so when there are no icons', async () => {
Expand Down Expand Up @@ -167,6 +172,26 @@ describe('IconPicker (in the calendar page)', () => {
expect(list.getByRole('option', { name: 'Geburtstag', hidden: true })).toBeInTheDocument()
})

it('previews a selected SVG upload as a mask and a PNG upload as an image', async () => {
const withIcon = (file: string) => ({ ...calendarSettings, calendars: [{ ...calendarSettings.calendars[0], icon: { kind: 'upload', file } }] })
const svg = await openCalendar({ 'GET /api/v1/settings/calendar': () => json(withIcon('ic2')) })
await waitFor(() => expect(svg.card.getByRole('combobox', { name: 'Symbol' })).toHaveValue('Stern'))
const field = svg.card.getByRole('combobox', { name: 'Symbol' }).closest('.mantine-InputWrapper-root') as HTMLElement
const maskOf = () => [...field.querySelectorAll<HTMLElement>('span[aria-hidden="true"]')].filter((m) => m.style.maskImage)
expect(maskOf()[0].style.maskImage).toContain('/api/v1/icons/ic2/file')
expect(field.querySelector('img')).toBeNull()
})

it('previews a selected PNG upload as an image', async () => {
const png = await openCalendar({
'GET /api/v1/settings/calendar': () => json({ ...calendarSettings, calendars: [{ ...calendarSettings.calendars[0], icon: { kind: 'upload', file: 'ic1' } }] }),
})
await waitFor(() => expect(png.card.getByRole('combobox', { name: 'Symbol' })).toHaveValue('Logo'))
const field = png.card.getByRole('combobox', { name: 'Symbol' }).closest('.mantine-InputWrapper-root') as HTMLElement
expect(field.querySelector('img')).toHaveAttribute('src', '/api/v1/icons/ic1/file')
expect([...field.querySelectorAll<HTMLElement>('span')].some((m) => m.style.maskImage)).toBe(false)
})

it('picking an uploaded icon and a standard icon sends the matching references', async () => {
const { api, card } = await openCalendar({
'PUT /api/v1/settings/calendar': (c) => json({ ...calendarSettings, calendars: [{ ...(c.body as { calendars: object[] }).calendars[0], hasUrl: true, urlHint: 'h' }] }),
Expand Down
Loading
Loading