import { describe, expect, test } from 'bun:test' import { readFileSync } from 'node:fs' import { resolve } from 'node:path' /** * Where the dashboard switch's thumb sits in its track. * * The track is a flex box that never centred its thumb, so the thumb sat flush * against the top edge (0px above, 4px below) on every size. And the thumb * stopped 2px from the left when off but 4px from the right when on. Every * yes-or-no field on a model's edit page showed it. * * The thumb is now the same distance from every edge it rests against: centred * top to bottom, and as far from the right when on as from the left when off. */ const source = readFileSync(resolve('storage/framework/defaults/resources/components/Dashboard/UI/Toggle.stx'), 'utf8') /** A spacing-scale step in pixels: `9` is 36px, `0.5` is 2px. */ function px(step: string): number { return Number(step) * 4 } function table(name: string): Record { const body = source.match(new RegExp(`const ${name}: Record = \\{([^}]*)\\}`))![1]! return Object.fromEntries([...body.matchAll(/(\w+): '([^']*)'/g)].map(match => [match[1]!, match[2]!])) } const tracks = table('trackSizes') const thumbs = table('thumbSizes') const onShifts = table('checkedTranslations') const offShift = px(source.match(/: '(translate-x-[\d.]+)',\n\]\.join/)![1]!.replace('translate-x-', '')) const trackClasses = source.match(/const trackClass = derived\(\(\) => \[([\s\S]*?)\]\.join/)![1]! function size(classes: string): { width: number, height: number } { return { width: px(classes.match(/\bw-([\d.]+)/)![1]!), height: px(classes.match(/\bh-([\d.]+)/)![1]!), } } describe('the switch thumb', () => { test('the track centres the thumb top to bottom', () => { expect(trackClasses).toMatch(/\binline-flex\b/) expect(trackClasses).toMatch(/\bitems-center\b/) }) test.each(['sm', 'md', 'lg'])('%s: the thumb rests as far from each edge as from the left when off', (key) => { const track = size(tracks[key]!) const thumb = size(thumbs[key]!) const onShift = px(onShifts[key]!.replace('translate-x-', '')) // Centred, the gap above and below is what the thumb leaves of the height. expect((track.height - thumb.height) / 2).toBe(offShift) // On, the gap to the right edge matches the gap to the left edge when off. expect(track.width - thumb.width - onShift).toBe(offShift) }) })