Tracker cards

This commit is contained in:
loucass003 committed 2026-10-25 22:08:44 +01:00
1 parent a902ffa15f
commit 262fbd72ef
21 files changed
+1100 -3

No files matched your search

@@ -0,0 +1,209 @@
import { BoardType, BodyPart } from 'solarxr-protocol';
import { type Component, type JSX, Show } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import HeadMountedDeviceRoundedIcon from '~icons/material-symbols/head-mounted-device-rounded';
import AnkleIcon from '~icons/slime/ankle';
import ButterflyIcon from '~icons/slime/butterfly';
import ChestIcon from '~icons/slime/chest';
import ControllerIcon from '~icons/slime/controller';
import FingersIcon from '~icons/slime/fingers';
import FootIcon from '~icons/slime/foot';
import HipIcon from '~icons/slime/hip';
import LowerArmIcon from '~icons/slime/lower-arm';
import NeckIcon from '~icons/slime/neck';
import PawIcon from '~icons/slime/paw';
import ShoulderIcon from '~icons/slime/shoulder';
import SlimeExtensionIcon from '~icons/slime/slime-extension';
import SlimeNormalIcon from '~icons/slime/slime-normal';
import SlimevrIcon from '~icons/slime/slimevr';
import UpperArmIcon from '~icons/slime/upper-arm';
import UpperChestIcon from '~icons/slime/upper-chest';
import UpperLegIcon from '~icons/slime/upper-leg';
import WaistIcon from '~icons/slime/waist';
import { cx } from '@/lib/cx';
import { locale } from '@/lib/l10n';
import {
trackerByKey,
trackerDevice,
trackerKeys,
type TrackerKey,
} from './store';
type Icon = Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
interface PartGlyph {
icon: Icon;
// Icons are drawn for the left side
mirror?: boolean;
// Paw in the owo locale
foot?: boolean;
}
const FINGERS: PartGlyph = { icon: FingersIcon };
const LEFT_FOOT: PartGlyph = { icon: FootIcon, foot: true };
const RIGHT_FOOT: PartGlyph = { icon: FootIcon, mirror: true, foot: true };
const PART_GLYPHS = {
[BodyPart.NONE]: { icon: SlimevrIcon },
[BodyPart.HEAD]: { icon: HeadMountedDeviceRoundedIcon },
[BodyPart.NECK]: { icon: NeckIcon },
[BodyPart.UPPER_CHEST]: { icon: UpperChestIcon },
[BodyPart.LOWER_CHEST]: { icon: ChestIcon },
[BodyPart.UPPER_WAIST]: { icon: WaistIcon },
[BodyPart.LOWER_WAIST]: { icon: WaistIcon },
[BodyPart.HIP]: { icon: HipIcon },
[BodyPart.LEFT_UPPER_LEG]: { icon: UpperLegIcon },
[BodyPart.RIGHT_UPPER_LEG]: { icon: UpperLegIcon, mirror: true },
[BodyPart.LEFT_LOWER_LEG]: { icon: AnkleIcon },
[BodyPart.RIGHT_LOWER_LEG]: { icon: AnkleIcon, mirror: true },
[BodyPart.LEFT_FOOT]: LEFT_FOOT,
[BodyPart.RIGHT_FOOT]: RIGHT_FOOT,
[BodyPart.LEFT_UPPER_ARM]: { icon: UpperArmIcon },
[BodyPart.RIGHT_UPPER_ARM]: { icon: UpperArmIcon, mirror: true },
[BodyPart.LEFT_LOWER_ARM]: { icon: LowerArmIcon },
[BodyPart.RIGHT_LOWER_ARM]: { icon: LowerArmIcon, mirror: true },
[BodyPart.LEFT_HAND]: { icon: ControllerIcon },
[BodyPart.RIGHT_HAND]: { icon: ControllerIcon, mirror: true },
// Old icons never mirrored the right shoulder
[BodyPart.LEFT_SHOULDER]: { icon: ShoulderIcon },
[BodyPart.RIGHT_SHOULDER]: { icon: ShoulderIcon },
[BodyPart.LEFT_THUMB_METACARPAL]: FINGERS,
[BodyPart.LEFT_THUMB_PROXIMAL]: FINGERS,
[BodyPart.LEFT_THUMB_DISTAL]: FINGERS,
[BodyPart.LEFT_INDEX_PROXIMAL]: FINGERS,
[BodyPart.LEFT_INDEX_INTERMEDIATE]: FINGERS,
[BodyPart.LEFT_INDEX_DISTAL]: FINGERS,
[BodyPart.LEFT_MIDDLE_PROXIMAL]: FINGERS,
[BodyPart.LEFT_MIDDLE_INTERMEDIATE]: FINGERS,
[BodyPart.LEFT_MIDDLE_DISTAL]: FINGERS,
[BodyPart.LEFT_RING_PROXIMAL]: FINGERS,
[BodyPart.LEFT_RING_INTERMEDIATE]: FINGERS,
[BodyPart.LEFT_RING_DISTAL]: FINGERS,
[BodyPart.LEFT_LITTLE_PROXIMAL]: FINGERS,
[BodyPart.LEFT_LITTLE_INTERMEDIATE]: FINGERS,
[BodyPart.LEFT_LITTLE_DISTAL]: FINGERS,
[BodyPart.RIGHT_THUMB_METACARPAL]: FINGERS,
[BodyPart.RIGHT_THUMB_PROXIMAL]: FINGERS,
[BodyPart.RIGHT_THUMB_DISTAL]: FINGERS,
[BodyPart.RIGHT_INDEX_PROXIMAL]: FINGERS,
[BodyPart.RIGHT_INDEX_INTERMEDIATE]: FINGERS,
[BodyPart.RIGHT_INDEX_DISTAL]: FINGERS,
[BodyPart.RIGHT_MIDDLE_PROXIMAL]: FINGERS,
[BodyPart.RIGHT_MIDDLE_INTERMEDIATE]: FINGERS,
[BodyPart.RIGHT_MIDDLE_DISTAL]: FINGERS,
[BodyPart.RIGHT_RING_PROXIMAL]: FINGERS,
[BodyPart.RIGHT_RING_INTERMEDIATE]: FINGERS,
[BodyPart.RIGHT_RING_DISTAL]: FINGERS,
[BodyPart.RIGHT_LITTLE_PROXIMAL]: FINGERS,
[BodyPart.RIGHT_LITTLE_INTERMEDIATE]: FINGERS,
[BodyPart.RIGHT_LITTLE_DISTAL]: FINGERS,
[BodyPart.LEFT_BIG_TOE]: LEFT_FOOT,
[BodyPart.LEFT_INDEX_TOE]: LEFT_FOOT,
[BodyPart.LEFT_MIDDLE_TOE]: LEFT_FOOT,
[BodyPart.LEFT_RING_TOE]: LEFT_FOOT,
[BodyPart.LEFT_LITTLE_TOE]: LEFT_FOOT,
[BodyPart.RIGHT_BIG_TOE]: RIGHT_FOOT,
[BodyPart.RIGHT_INDEX_TOE]: RIGHT_FOOT,
[BodyPart.RIGHT_MIDDLE_TOE]: RIGHT_FOOT,
[BodyPart.RIGHT_RING_TOE]: RIGHT_FOOT,
[BodyPart.RIGHT_LITTLE_TOE]: RIGHT_FOOT,
} satisfies Record<BodyPart, PartGlyph>;
const BUTTERFLY_BOARDS = new Set([
BoardType.SLIMEVR_BUTTERFLY,
BoardType.SLIMEVR_BUTTERFLY_DEV,
]);
const SLIME_BOARDS = new Set([
BoardType.SLIMEVR,
BoardType.SLIMEVR_V1_2,
BoardType.SLIMEVR_DEV,
BoardType.SLIMEVR_LEGACY,
]);
const OWO_LOCALE = 'en-x-owo';
function partGlyph(part: BodyPart): PartGlyph {
const glyph: PartGlyph = PART_GLYPHS[part];
if (glyph.foot && locale() === OWO_LOCALE) return { icon: PawIcon };
return glyph;
}
// Unassigned trackers show their hardware: butterfly, slime (main or extension
// IMU) or the SlimeVR glyph
function UnassignedGlyph(props: { trackerKey: TrackerKey }) {
const board = () =>
trackerDevice(props.trackerKey)?.hardwareInfo?.officialBoardType;
const extension = () => {
const deviceId = trackerByKey(props.trackerKey)?.deviceId;
const first = trackerKeys().find(
(key) => trackerByKey(key)?.deviceId === deviceId
);
return first !== props.trackerKey;
};
const icon = (): { icon: Icon; small?: boolean } => {
const type = board();
if (type != null && BUTTERFLY_BOARDS.has(type)) {
return { icon: ButterflyIcon };
}
if (type != null && SLIME_BOARDS.has(type)) {
return {
icon: extension() ? SlimeExtensionIcon : SlimeNormalIcon,
small: true,
};
}
return { icon: SlimevrIcon };
};
return (
<span class={cx('flex', icon().small && 'scale-70')}>
<Dynamic component={icon().icon} />
</span>
);
}
export interface BodyPartIconProps {
// Reads the part and hardware from the tracker
trackerKey?: TrackerKey;
// Overrides the tracker's part
part?: BodyPart;
}
// Rounded square sized by the container's `--icon-size` (`icon-xl` etc).
// Decorative, the name shows beside it.
export function BodyPartIcon(props: BodyPartIconProps) {
const part = () =>
props.part ??
(props.trackerKey
? trackerByKey(props.trackerKey)?.info?.bodyPart
: undefined) ??
BodyPart.NONE;
const unassignedKey = () =>
part() === BodyPart.NONE &&
props.trackerKey &&
trackerDevice(props.trackerKey)
? props.trackerKey
: undefined;
const glyph = () => partGlyph(part());
return (
<span
aria-hidden="true"
class={cx(
'flex size-(--icon-size) shrink-0 items-center justify-center rounded-xs text-fg',
unassignedKey() ? 'bg-accent' : 'bg-accent-muted'
)}
>
<Show
when={unassignedKey()}
fallback={
<span class={cx('flex', glyph().mirror && '-scale-x-100')}>
<Dynamic component={glyph().icon} />
</span>
}
>
{(key) => <UnassignedGlyph trackerKey={key()} />}
</Show>
</span>
);
}
@@ -0,0 +1,15 @@
import * as v from 'valibot';
import { definePref } from '@/lib/storage';
const trackerDisplaySchema = v.looseObject({
showBatteryVoltage: v.optional(v.boolean(), false),
showNumericSignal: v.optional(v.boolean(), false),
});
export type TrackerDisplay = v.InferOutput<typeof trackerDisplaySchema>;
// Old config key `trackerDisplay`, edited on the Home layout settings
export const trackerDisplayPref = definePref('trackerDisplay', trackerDisplaySchema, {
showBatteryVoltage: false,
showNumericSignal: false,
});
@@ -1,4 +1,6 @@
export { BodyPartIcon, type BodyPartIconProps } from './body-part-icon';
export { bodyPartLabels } from './body-parts';
export { trackerDisplayPref, type TrackerDisplay } from './display-prefs';
export { toEulerDegrees, trackerName } from './display';
export {
assignedTrackerKeys,
@@ -24,3 +26,8 @@ export {
type TrackerInfo,
type TrackerKey,
} from './store';
export { TrackerBattery } from './tracker-battery';
export { TrackerCard, type TrackerCardProps } from './tracker-card';
export { TrackerRow } from './tracker-row';
export { TrackerStatusLabel, trackerStatusLabels } from './tracker-status';
export { TrackerWifi, type TrackerWifiProps } from './tracker-wifi';
@@ -0,0 +1,94 @@
import { TrackerStatus } from 'solarxr-protocol';
import { createUniqueId, Show } from 'solid-js';
import { debugPref } from '@/domain/developer';
import { fmt, formats } from '@/lib/format';
import { t } from '@/lib/l10n';
import { BatteryIcon } from '@/ui/battery-icon';
import { Tooltip } from '@/ui/tooltip';
import { trackerDisplayPref } from './display-prefs';
import { trackerByKey, trackerDevice, type TrackerKey } from './store';
// Above this voltage the tracker is on a charger
const CHARGING_VOLTS = 4.3;
const MICROS_PER_HOUR = 3_600_000_000n;
const MICROS_PER_MINUTE = 60_000_000n;
function runtimeText(micros: bigint): string {
return t('tracker-battery-runtime', {
hours: Number(micros / MICROS_PER_HOUR),
minutes: Number((micros % MICROS_PER_HOUR) / MICROS_PER_MINUTE),
});
}
// Battery icon + runtime or percent (+ voltage when enabled). Nothing when the
// device reports no battery.
export function TrackerBattery(props: { trackerKey: TrackerKey }) {
const tipId = createUniqueId();
let el: HTMLDivElement | undefined;
const hw = () => trackerDevice(props.trackerKey)?.hardwareStatus;
const disconnected = () =>
trackerByKey(props.trackerKey)?.status === TrackerStatus.DISCONNECTED;
return (
<Show when={hw()?.batteryPctEstimate != null && hw()}>
{(status) => {
// 0..1 with the over and underflow encodings BatteryIcon understands
const value = () => status().batteryPctEstimate! / 100;
const percent = () =>
value() > 2 ? 0 : Math.min(Math.max(value(), 0), 1);
const voltage = () => status().batteryVoltage;
const runtime = () => {
const micros = status().batteryRuntimeEstimate;
return micros != null && micros > 0n ? micros : null;
};
const charging = () => (voltage() ?? 0) > CHARGING_VOLTS;
const showVoltage = () =>
!!voltage() && trackerDisplayPref().showBatteryVoltage;
const showPercent = () =>
!charging() && (runtime() == null || debugPref());
// Runtime replaces the percent, which moves to the tooltip
const percentTip = () =>
!charging() && runtime() != null && !debugPref();
return (
<>
<div
ref={el}
aria-describedby={percentTip() ? tipId : undefined}
class="flex items-center gap-sm"
>
<BatteryIcon
value={value()}
charging={charging()}
disabled={disconnected()}
/>
<Show
when={!charging() || showVoltage()}
fallback={
<span class="flex w-15 items-center">
<span class="h-1 w-5 rounded-full bg-fg-disabled" />
</span>
}
>
<span class="flex w-15 flex-col whitespace-nowrap">
<Show when={!charging() && runtime()}>
{(micros) => <span>{runtimeText(micros())}</span>}
</Show>
<Show when={showPercent()}>
<span>{fmt(formats.percent, percent())}</span>
</Show>
<Show when={showVoltage()}>
<span>{fmt(formats.volts, voltage())}</span>
</Show>
</span>
</Show>
</div>
<Tooltip id={tipId} anchor={() => el} placement="left">
{percentTip() ? fmt(formats.percent, percent()) : undefined}
</Tooltip>
</>
);
}}
</Show>
);
}
@@ -0,0 +1,112 @@
import { TrackerStatus } from 'solarxr-protocol';
import { createUniqueId, Show } from 'solid-js';
import ExclamationTriangleIcon from '~icons/heroicons/exclamation-triangle-20-solid';
import { cx } from '@/lib/cx';
import { t, type MessageId } from '@/lib/l10n';
import { Tooltip } from '@/ui/tooltip';
import { BodyPartIcon } from './body-part-icon';
import { trackerName } from './display';
import { trackerByKey, trackerMovement, type TrackerKey } from './store';
import { TrackerBattery } from './tracker-battery';
import { TrackerStatusLabel } from './tracker-status';
import { TrackerWifi } from './tracker-wifi';
export interface TrackerCardProps {
trackerKey: TrackerKey;
// small: one line (Home grid). large: centered column (tracker page).
size?: 'small' | 'large';
warning?: MessageId;
// Glow with the tracker's movement
glow?: boolean;
}
function SmallCard(props: { trackerKey: TrackerKey; warning?: MessageId }) {
const tracker = () => trackerByKey(props.trackerKey);
return (
<div class="flex h-17.5 w-full items-center gap-lg px-md py-1.5">
<div class="relative flex">
<span
class={cx(
'flex overflow-clip rounded-md border-3 icon-xl',
props.warning ? 'border-warning/80' : 'border-transparent'
)}
>
<BodyPartIcon trackerKey={props.trackerKey} />
</span>
<Show when={props.warning}>
<span class="absolute -right-2 -bottom-3 flex text-warning icon-md">
<ExclamationTriangleIcon />
</span>
</Show>
</div>
<div class="flex min-w-0 grow flex-col justify-center gap-0.5">
<span class="truncate text-section">
{trackerName(tracker()?.info)}
</span>
<TrackerStatusLabel status={tracker()?.status ?? TrackerStatus.NONE} />
</div>
<TrackerBattery trackerKey={props.trackerKey} />
<TrackerWifi trackerKey={props.trackerKey} />
</div>
);
}
function LargeCard(props: { trackerKey: TrackerKey }) {
const tracker = () => trackerByKey(props.trackerKey);
return (
<div class="flex w-full flex-col items-center justify-center gap-sm px-lg py-2xl">
<span class="flex icon-lg">
<BodyPartIcon trackerKey={props.trackerKey} />
</span>
<span class="max-w-full truncate font-bold">
{trackerName(tracker()?.info)}
</span>
<TrackerStatusLabel status={tracker()?.status ?? TrackerStatus.NONE} />
<div class="flex min-h-9 flex-wrap items-center justify-center gap-5">
<TrackerBattery trackerKey={props.trackerKey} />
<TrackerWifi trackerKey={props.trackerKey} numeric />
</div>
</div>
);
}
// Tracker summary on a card surface. Make it pressable by wrapping it in
// Pressable or a link with `group/press`, the card then shows hover.
export function TrackerCard(props: TrackerCardProps) {
const tipId = createUniqueId();
let el: HTMLDivElement | undefined;
const movement = () =>
props.glow === false ? 0 : trackerMovement(props.trackerKey);
return (
<>
<div
ref={el}
class="
surface-card movement-glow overflow-hidden rounded-lg group-hover/press:bg-surface-control
"
style={{ '--movement': movement() }}
>
<Show
when={props.size === 'small'}
fallback={<LargeCard trackerKey={props.trackerKey} />}
>
<SmallCard trackerKey={props.trackerKey} warning={props.warning} />
<Show when={props.warning}>
{(warning) => <span class="sr-only">{t(warning())}</span>}
</Show>
</Show>
</div>
<Tooltip id={tipId} anchor={() => el} placement="top">
{props.size === 'small' && props.warning ? (
<span class="flex items-center gap-xs text-warning icon-md">
<ExclamationTriangleIcon />
{t(props.warning)}
</span>
) : undefined}
</Tooltip>
</>
);
}
@@ -0,0 +1,154 @@
import { cleanup, render, screen } from '@solidjs/testing-library';
import {
DataFeedUpdateT,
DeviceDataT,
HardwareStatusT,
TrackerDataT,
TrackerInfoT,
TrackerStatus,
} from 'solarxr-protocol';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { debugPref } from '@/domain/developer';
import { createBundle, setL10nBundles, t } from '@/lib/l10n';
import { setPlatform } from '@/lib/platform';
import { fakePlatform } from '@/lib/platform-fake';
import {
ingestTrackers,
resetTrackers,
TrackerBattery,
trackerDisplayPref,
trackerKey,
TrackerStatusLabel,
TrackerWifi,
} from '.';
const KEY = trackerKey(1, 0);
function feed(
hw: Partial<HardwareStatusT>,
status: TrackerStatus = TrackerStatus.OK
) {
const tracker = new TrackerDataT();
tracker.deviceId = 1;
tracker.trackerId = 0;
tracker.info = new TrackerInfoT();
tracker.status = status;
const device = new DeviceDataT();
device.id = 1;
device.hardwareStatus = Object.assign(new HardwareStatusT(), hw);
device.trackers = [tracker];
const update = new DataFeedUpdateT();
update.devices = [device];
ingestTrackers(update, 0);
}
beforeEach(() => {
setPlatform(fakePlatform());
resetTrackers();
debugPref.set(false);
trackerDisplayPref.set({
showBatteryVoltage: false,
showNumericSignal: false,
});
setL10nBundles([
createBundle(
'en',
[
'tracker-status-ok = OK',
'tracker-battery-runtime = { $hours }h { $minutes }min',
'tracker-infos-packet_loss = Packet Loss',
].join('\n')
),
]);
});
afterEach(cleanup);
describe('TrackerBattery', () => {
it('renders nothing without a battery estimate', () => {
feed({ batteryPctEstimate: null });
const { container } = render(() => <TrackerBattery trackerKey={KEY} />);
expect(container).toBeEmptyDOMElement();
});
it('shows the percent when there is no runtime', () => {
feed({ batteryPctEstimate: 55, batteryVoltage: 3.9 });
render(() => <TrackerBattery trackerKey={KEY} />);
expect(screen.getByText('55%')).toBeInTheDocument();
});
it('shows the runtime, the percent moves to the tooltip', () => {
feed({
batteryPctEstimate: 55,
batteryVoltage: 3.9,
batteryRuntimeEstimate: 2n * 3_600_000_000n + 5n * 60_000_000n,
});
render(() => <TrackerBattery trackerKey={KEY} />);
expect(
screen.getByText(t('tracker-battery-runtime', { hours: 2, minutes: 5 }))
).toBeInTheDocument();
expect(screen.getByText('55%')).toHaveAttribute('role', 'tooltip');
});
it('debug shows both runtime and percent', () => {
debugPref.set(true);
feed({ batteryPctEstimate: 55, batteryRuntimeEstimate: 3_600_000_000n });
render(() => <TrackerBattery trackerKey={KEY} />);
expect(
screen.getByText(t('tracker-battery-runtime', { hours: 1, minutes: 0 }))
).toBeInTheDocument();
expect(screen.getByText('55%')).not.toHaveAttribute('role', 'tooltip');
});
it('hides the numbers while charging, unless the voltage pref is on', () => {
feed({ batteryPctEstimate: 80, batteryVoltage: 4.4 });
render(() => <TrackerBattery trackerKey={KEY} />);
expect(screen.queryByText('80%')).not.toBeInTheDocument();
expect(screen.queryByText('4.40 V')).not.toBeInTheDocument();
trackerDisplayPref.set({
showBatteryVoltage: true,
showNumericSignal: false,
});
expect(screen.getByText('4.40 V')).toBeInTheDocument();
});
});
describe('TrackerWifi', () => {
it('shows ping, and dBm only when numeric', () => {
feed({ rssi: -60, ping: 12 });
render(() => <TrackerWifi trackerKey={KEY} />);
expect(screen.getByText('12 ms')).toBeInTheDocument();
expect(screen.queryByText('-60 dBm')).not.toBeInTheDocument();
trackerDisplayPref.set({
showBatteryVoltage: false,
showNumericSignal: true,
});
expect(screen.getByText('-60 dBm')).toBeInTheDocument();
});
it('hides the text while disconnected', () => {
feed({ rssi: -60, ping: 12 }, TrackerStatus.DISCONNECTED);
render(() => <TrackerWifi trackerKey={KEY} numeric />);
expect(screen.queryByText('12 ms')).not.toBeInTheDocument();
expect(screen.queryByText('-60 dBm')).not.toBeInTheDocument();
});
it('shows packet loss with counts', () => {
feed({ ping: 12, packetLoss: 0.25, packetsLost: 5, packetsReceived: 20 });
render(() => <TrackerWifi trackerKey={KEY} packetLoss />);
expect(screen.getByText('25% (5 / 20)')).toBeInTheDocument();
});
it('shows -- for unknown packet loss', () => {
feed({ ping: 12, packetLoss: null });
render(() => <TrackerWifi trackerKey={KEY} packetLoss />);
expect(screen.getByText('--')).toBeInTheDocument();
});
});
describe('TrackerStatusLabel', () => {
it('shows the status name', () => {
render(() => <TrackerStatusLabel status={TrackerStatus.OK} />);
expect(screen.getByText('OK')).toBeInTheDocument();
});
});
@@ -0,0 +1,38 @@
import { TrackerStatus } from 'solarxr-protocol';
import { Show } from 'solid-js';
import { BodyPartIcon } from './body-part-icon';
import { trackerName } from './display';
import { trackerByKey, trackerMovement, type TrackerKey } from './store';
import { TrackerStatusLabel } from './tracker-status';
// One-line tracker: icon, name (+ display name under a custom name), status.
// Paints the parent's control colour. Wrap in Pressable for selection.
export function TrackerRow(props: { trackerKey: TrackerKey }) {
const tracker = () => trackerByKey(props.trackerKey);
const info = () => tracker()?.info;
const renamed = () =>
!!info()?.customName && info()?.displayName !== info()?.customName;
return (
<div
class="
movement-glow flex h-12 items-center gap-sm rounded-lg bg-surface-control p-sm
group-hover/press:bg-surface-hover
"
style={{ '--movement': trackerMovement(props.trackerKey) }}
>
<span class="flex icon-xl">
<BodyPartIcon trackerKey={props.trackerKey} />
</span>
<div class="flex min-w-0 grow flex-col">
<span class="truncate font-bold">{trackerName(info())}</span>
<Show when={renamed()}>
<span class="truncate">{info()?.displayName}</span>
</Show>
</div>
<span class="shrink-0">
<TrackerStatusLabel status={tracker()?.status ?? TrackerStatus.NONE} />
</span>
</div>
);
}
@@ -0,0 +1,34 @@
import { TrackerStatus } from 'solarxr-protocol';
import { cx } from '@/lib/cx';
import { t, type MessageId } from '@/lib/l10n';
export const trackerStatusLabels = {
[TrackerStatus.NONE]: 'tracker-status-none',
[TrackerStatus.BUSY]: 'tracker-status-busy',
[TrackerStatus.ERROR]: 'tracker-status-error',
[TrackerStatus.DISCONNECTED]: 'tracker-status-disconnected',
[TrackerStatus.OCCLUDED]: 'tracker-status-occluded',
[TrackerStatus.OK]: 'tracker-status-ok',
[TrackerStatus.TIMED_OUT]: 'tracker-status-timed_out',
[TrackerStatus.SLEEPING]: 'tracker-status-sleeping',
} satisfies Record<TrackerStatus, MessageId>;
const DOT = {
[TrackerStatus.NONE]: 'bg-fg-disabled',
[TrackerStatus.BUSY]: 'bg-warning',
[TrackerStatus.ERROR]: 'bg-critical',
[TrackerStatus.DISCONNECTED]: 'bg-fg-disabled',
[TrackerStatus.OCCLUDED]: 'bg-warning',
[TrackerStatus.OK]: 'bg-success',
[TrackerStatus.TIMED_OUT]: 'bg-warning',
[TrackerStatus.SLEEPING]: 'bg-info',
} satisfies Record<TrackerStatus, string>;
export function TrackerStatusLabel(props: { status: TrackerStatus }) {
return (
<span class="flex items-center gap-sm whitespace-nowrap">
<span class={cx('size-2 shrink-0 rounded-full', DOT[props.status])} />
{t(trackerStatusLabels[props.status])}
</span>
);
}
@@ -0,0 +1,84 @@
import { TrackerStatus } from 'solarxr-protocol';
import { createUniqueId, Show } from 'solid-js';
import { fmt, formats } from '@/lib/format';
import { TextTooltip } from '@/ui/tooltip';
import { WifiSignalIcon } from '@/ui/wifi-signal-icon';
import { trackerDisplayPref } from './display-prefs';
import { trackerByKey, trackerDevice, type TrackerKey } from './store';
export interface TrackerWifiProps {
trackerKey: TrackerKey;
// Show the dBm value. Default: the `showNumericSignal` display pref.
numeric?: boolean;
packetLoss?: boolean;
}
function PacketLoss(props: {
loss: number | null | undefined;
lost: number | null | undefined;
received: number | null | undefined;
}) {
const tipId = createUniqueId();
let el: HTMLSpanElement | undefined;
const counts = () =>
props.lost != null && props.received != null
? ` (${props.lost} / ${props.received})`
: '';
return (
<>
<span ref={el} aria-describedby={tipId}>
{fmt(formats.percent, props.loss)}
{props.loss == null ? '' : counts()}
</span>
<TextTooltip
id={tipId}
anchor={() => el}
placement="top"
text="tracker-infos-packet_loss"
/>
</>
);
}
// Signal icon + ping, dBm and packet loss. Nothing when the device reports
// neither ping nor signal.
export function TrackerWifi(props: TrackerWifiProps) {
const hw = () => trackerDevice(props.trackerKey)?.hardwareStatus;
const disconnected = () =>
trackerByKey(props.trackerKey)?.status === TrackerStatus.DISCONNECTED;
const numeric = () => props.numeric ?? trackerDisplayPref().showNumericSignal;
return (
<Show when={(hw()?.rssi != null || hw()?.ping != null) && hw()}>
{(status) => {
const showText = () =>
!disconnected() &&
(status().ping != null || (numeric() && status().rssi != null));
return (
<div class="flex items-center gap-sm">
<WifiSignalIcon rssi={status().rssi} disabled={disconnected()} />
<Show when={showText()}>
<span class="flex w-12 flex-col whitespace-nowrap">
<Show when={status().ping != null}>
<span>{fmt(formats.milliseconds, status().ping)}</span>
</Show>
<Show when={numeric() && status().rssi != null}>
<span>{fmt(formats.dbm, status().rssi)}</span>
</Show>
<Show when={props.packetLoss}>
<PacketLoss
loss={status().packetLoss}
lost={status().packetsLost}
received={status().packetsReceived}
/>
</Show>
</span>
</Show>
</div>
);
}}
</Show>
);
}
+1
View File
@@ -28,6 +28,7 @@ export const formats = {
},
volts: { suffix: 'V', minimumFractionDigits: 2, maximumFractionDigits: 2 },
dbm: { suffix: 'dBm', maximumFractionDigits: 0 },
milliseconds: { suffix: 'ms', maximumFractionDigits: 0 },
offset: { signDisplay: 'exceptZero', maximumFractionDigits: 2 },
} satisfies Record<string, NumberSpec>;
@@ -1,5 +1,5 @@
import { BodyPart, ResetAvailability, TrackerStatus } from 'solarxr-protocol';
import { For, Index, Show } from 'solid-js';
import { createSignal, For, Index, Show } from 'solid-js';
import { bones, serverGuards } from '@/domain/datafeed';
import {
assignedTrackerKeys,
@@ -7,16 +7,21 @@ import {
dongleById,
dongleIds,
toEulerDegrees,
TrackerCard,
trackerByKey,
trackerDevice,
trackerKeys,
trackerMovement,
trackerName,
TrackerRow,
type TrackerKey,
} from '@/domain/trackers';
import { fmt, formats } from '@/lib/format';
import { Pressable } from '@/ui/pressable';
function TrackerRow(props: { trackerKey: TrackerKey }) {
//placholder
function TrackerTableRow(props: { trackerKey: TrackerKey }) {
const tracker = () => trackerByKey(props.trackerKey);
const device = () => trackerDevice(props.trackerKey);
const euler = () => toEulerDegrees(tracker()?.rotation);
@@ -58,6 +63,54 @@ function availability(value: ResetAvailability | undefined) {
return value === undefined ? '--' : ResetAvailability[value];
}
function TrackerWidgets() {
const [selected, setSelected] = createSignal<TrackerKey>();
function toggle(key: TrackerKey) {
setSelected(selected() === key ? undefined : key);
}
return (
<>
<span class="text-section">Tracker cards</span>
<div class="grid gap-lg @3xl:grid-cols-2">
<For each={trackerKeys()}>
{(key, i) => (
<Pressable onClick={() => toggle(key)} class="rounded-lg">
<TrackerCard
trackerKey={key}
size="small"
warning={i() === 0 ? 'tracker-status-error' : undefined}
/>
</Pressable>
)}
</For>
</div>
<Show when={trackerKeys()[0]}>
{(key) => (
<div class="w-full max-w-xs">
<TrackerCard trackerKey={key()} glow={false} />
</div>
)}
</Show>
<span class="text-section">Tracker rows (press to select)</span>
<div class="flex max-w-md flex-col gap-sm">
<For each={trackerKeys()}>
{(key) => (
<Pressable
onClick={() => toggle(key)}
pressed={selected() === key}
class="rounded-lg aria-pressed:ring-2 aria-pressed:ring-accent"
>
<TrackerRow trackerKey={key} />
</Pressable>
)}
</For>
</div>
</>
);
}
// Dev check of the datafeed ingest and the trackers store
export function DatafeedDemo() {
return (
@@ -106,12 +159,14 @@ export function DatafeedDemo() {
</thead>
<tbody>
<For each={trackerKeys()}>
{(key) => <TrackerRow trackerKey={key} />}
{(key) => <TrackerTableRow trackerKey={key} />}
</For>
</tbody>
</table>
</div>
<TrackerWidgets />
<span class="text-section">Dongles</span>
<Show
when={dongleIds().length > 0}
+9
View File
@@ -19,6 +19,7 @@
--palette-warning: #ffe135;
--palette-critical: #df6d8c;
--palette-special: #a44fed;
--palette-info: #06b6d4;
--palette-window-icon: #c0a1d8;
--palette-assign-left: #2b83e8;
--palette-assign-right: #f956b8;
@@ -463,6 +464,7 @@
--color-warning: var(--palette-warning);
--color-critical: var(--palette-critical);
--color-special: var(--palette-special);
--color-info: var(--palette-info);
--color-window-icon: var(--palette-window-icon);
--color-assign-left: var(--palette-assign-left);
--color-assign-right: var(--palette-assign-right);
@@ -635,6 +637,13 @@
image-rendering: crisp-edges;
}
/* Tracker movement glow, `--movement` 0..1 set inline from trackerMovement */
@utility movement-glow {
--glow: calc(var(--movement, 0) * 8px);
box-shadow: 0 0 var(--glow) var(--glow) var(--palette-accent-30);
transition: box-shadow 200ms linear;
}
/* Sprite sheet player, see ui/sprite. One integer frame counter steps through
the grid left to right, top to bottom, so a partial last row never shows. */
@property --sprite-frame {
@@ -0,0 +1,95 @@
import { createUniqueId, Match, Switch } from 'solid-js';
import { cx } from '@/lib/cx';
const BODY =
'M11.0833 0H1.31203C0.995003 0.00131561 0.691347 0.121213 0.467167 0.333594C0.242986 0.545976 0.116428 0.83365 0.115039 1.134V7.383C0.114754 7.68458 0.240506 7.97399 0.464808 8.18799C0.689109 8.40198 0.993714 8.52315 1.31203 8.525H11.0833V0Z';
const CAP =
'M15.0005 8.525C15.3175 8.52368 15.6212 8.40379 15.8454 8.19141C16.0696 7.97902 16.1961 7.69135 16.1975 7.391V5.968H17.9972V2.558H16.1975V1.134C16.1961 0.83365 16.0696 0.545976 15.8454 0.333594C15.6212 0.121213 15.3175 0.00131561 15.0005 0H10.9672V8.525H15.0005Z';
const BOLT =
'M 7.7638355,8.4189633 8.0112251,4.9834646 5.7712838,4.9834645 8.5644084,0.07977871 8.3170195,3.5152773 H 10.55696 Z';
const CHECK =
'M 5.5342464,4.6225095 C 6.1777799,5.0106205 6.6131537,5.2516456 7.5253371,6.545223 8.4340868,4.4016445 8.7809738,3.661475 10.605195,1.5520288';
export function levelColor(level: number): string {
if (level > 0.4) return 'text-success';
if (level > 0.2) return 'text-warning';
if (level > 0) return 'text-critical';
return 'text-fg';
}
export interface BatteryIconProps {
value: number;
charging?: boolean;
disabled?: boolean;
}
export function BatteryIcon(props: BatteryIconProps) {
const shapeId = createUniqueId();
const holeId = createUniqueId();
const level = () =>
props.value > 2 ? 0 : Math.min(Math.max(props.value, 0), 1);
const full = () => props.value > 1 && props.value <= 2;
const color = () => {
if (props.disabled) return 'text-fg-disabled';
if (props.charging) return 'text-success';
return levelColor(level());
};
return (
<svg
width="19"
height="11"
viewBox="0 0 19 9"
aria-hidden="true"
class="shrink-0"
>
<defs>
<mask
id={shapeId}
maskUnits="userSpaceOnUse"
x="0"
y="0"
width="18"
height="9"
style={{ 'mask-type': 'alpha' }}
>
<path d={BODY} />
<path d={CAP} />
</mask>
<mask
id={holeId}
maskUnits="userSpaceOnUse"
x="0"
y="0"
width="19"
height="9"
>
<rect width="19" height="9" fill="white" />
<Switch>
<Match when={props.charging && full()}>
<path
d={CHECK}
fill="none"
stroke="black"
stroke-width="1.5"
stroke-linecap="square"
/>
</Match>
<Match when={props.charging}>
<path d={BOLT} fill="black" />
</Match>
</Switch>
</mask>
</defs>
<g mask={`url(#${holeId})`}>
<g class="fill-fg-disabled">
<path d={BODY} />
<path d={CAP} />
</g>
<g mask={`url(#${shapeId})`} class={cx('fill-current', color())}>
<rect width={props.charging ? 18 : level() * 18} height="9" />
</g>
</g>
</svg>
);
}
@@ -0,0 +1 @@
export * from './battery-icon';
+1
View File
@@ -0,0 +1 @@
export * from './pressable';
@@ -0,0 +1,47 @@
import { cleanup, render, screen } from '@solidjs/testing-library';
import userEvent from '@testing-library/user-event';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Pressable } from '@/ui/pressable';
describe('Pressable', () => {
afterEach(cleanup);
it('is a button named by its content and fires onClick', async () => {
const onClick = vi.fn();
render(() => (
<Pressable onClick={onClick}>
<span>Left foot</span>
</Pressable>
));
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Left foot' }));
expect(onClick).toHaveBeenCalledOnce();
});
it('reflects pressed as aria-pressed', () => {
render(() => (
<Pressable onClick={() => {}} pressed label="Tracker">
<span />
</Pressable>
));
expect(screen.getByRole('button', { name: 'Tracker' })).toHaveAttribute(
'aria-pressed',
'true'
);
});
it('disabled stays focusable and ignores presses', async () => {
const onClick = vi.fn();
render(() => (
<Pressable onClick={onClick} disabled label="Tracker">
<span />
</Pressable>
));
const button = screen.getByRole('button', { name: 'Tracker' });
await userEvent.setup().click(button);
expect(onClick).not.toHaveBeenCalled();
expect(button).toHaveAttribute('aria-disabled', 'true');
expect(button).not.toBeDisabled();
});
});
@@ -0,0 +1,49 @@
import type { JSX } from 'solid-js';
import { cx } from '@/lib/cx';
import { useMotionItem } from '@/ui/motion';
export interface PressableProps {
onClick: (e: MouseEvent) => void;
// Toggle state, sets aria-pressed
pressed?: boolean;
disabled?: boolean;
// Accessible name when the content has no text
label?: string;
// Layout and the pressed look (`rounded-lg aria-pressed:ring-2`)
class?: string;
ref?: (el: HTMLButtonElement) => void;
children: JSX.Element;
}
export function Pressable(props: PressableProps) {
let el!: HTMLButtonElement;
useMotionItem(() => el);
function setRef(node: HTMLButtonElement) {
el = node;
props.ref?.(node);
}
function onClick(e: MouseEvent) {
if (props.disabled) return;
props.onClick(e);
}
return (
<button
ref={(node) => setRef(node)}
type="button"
aria-label={props.label}
aria-pressed={props.pressed}
aria-disabled={props.disabled ? 'true' : undefined}
class={cx(
'group/press block w-full text-left',
'aria-disabled:cursor-not-allowed aria-disabled:opacity-50',
props.class
)}
onClick={onClick}
>
{props.children}
</button>
);
}
@@ -0,0 +1 @@
export * from './wifi-signal-icon';
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest';
import { levelColor } from '@/ui/battery-icon';
import { signalLevel } from '@/ui/wifi-signal-icon';
describe('signalLevel', () => {
it('maps -95..-40 dBm to 0..1, clamped', () => {
expect(signalLevel(-95)).toBe(0);
expect(signalLevel(-40)).toBe(1);
expect(signalLevel(-67.5)).toBeCloseTo(0.5);
expect(signalLevel(-120)).toBe(0);
expect(signalLevel(-10)).toBe(1);
});
it('reads unknown as empty', () => {
expect(signalLevel(null)).toBe(0);
expect(signalLevel(undefined)).toBe(0);
});
});
describe('levelColor', () => {
it('uses the old thresholds', () => {
expect(levelColor(0.5)).toBe('text-success');
expect(levelColor(0.4)).toBe('text-warning');
expect(levelColor(0.2)).toBe('text-critical');
expect(levelColor(0)).toBe('text-fg');
});
});
@@ -0,0 +1,61 @@
import { createUniqueId } from 'solid-js';
import { cx } from '@/lib/cx';
import { levelColor } from '@/ui/battery-icon';
const BACK =
'M7.799 12.378L15.585 2.67801C13.3492 0.95947 10.6129 0.01903 7.793 1.00136e-05C4.9725 0.0172 2.23528 0.95782 0 2.67801L7.786 12.378L7.793 12.385L7.799 12.378Z';
const WEDGE =
'M0 2.712L7.782 12.392V12.407L7.795 12.396L15.577 2.716C13.3449 0.980306 10.6044 0.026036 7.777 0C4.95656 0.021826 2.22242 0.975276 0 2.712Z';
// -95 dBm reads empty, -40 dBm full
const RSSI_EMPTY = -95;
const RSSI_FULL = -40;
export function signalLevel(rssi: number | null | undefined): number {
if (rssi == null) return 0;
const level = (rssi - RSSI_EMPTY) / (RSSI_FULL - RSSI_EMPTY);
return Math.min(Math.max(level, 0), 1);
}
export interface WifiSignalIconProps {
// dBm, null when unknown (drawn empty)
rssi: number | null | undefined;
disabled?: boolean;
}
export function WifiSignalIcon(props: WifiSignalIconProps) {
const maskId = createUniqueId();
const level = () => signalLevel(props.rssi);
const color = () =>
props.disabled ? 'text-fg-disabled' : levelColor(level());
return (
<svg
width="16"
height="16"
viewBox="0 0 16 13"
aria-hidden="true"
class="shrink-0"
>
<defs>
<mask
id={maskId}
maskUnits="userSpaceOnUse"
x="0"
width="16"
height="13"
style={{ 'mask-type': 'alpha' }}
>
<path d={WEDGE} />
</mask>
</defs>
<path d={BACK} class="fill-fg-disabled" />
<g mask={`url(#${maskId})`} class={cx('fill-current', color())}>
<path
d={WEDGE}
style={{ transform: `translateY(${(1 - level()) * 13}px)` }}
/>
</g>
</svg>
);
}
+3
View File
@@ -312,6 +312,9 @@ tracker-status-ok = OK
tracker-status-timed_out = Timed out
tracker-status-sleeping = Sleeping
# $hours (Number), $minutes (Number) - Estimated battery runtime left
tracker-battery-runtime = { $hours }h { $minutes }min
## Tracker status columns
tracker-table-column-name = Name
tracker-table-column-type = Type