Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@
[![GitHub Forks](https://img.shields.io/github/forks/usetrmnl/byos_next?style=social)](https://github.com/usetrmnl/byos_next/network/members)

## 🚀 Overview
**BYOS (Build Your Own Server) Next.js** is a Next.js implementation that powers device management, playlist-driven content scheduling, and on-demand BMP generation for e-ink displays.
**BYOS (Build Your Own Server) Next.js** is a Next.js implementation that powers device management, playlist-driven content scheduling, and on-demand device image generation for e-ink displays.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fusetrmnl%2Fbyos_next&env=AUTH_ENABLED&envDefaults=%7B%22AUTH_ENABLED%22%3A%22false%22%7D&envDescription=User%20authentication%20is%20disabled.&envLink=https%3A%2F%2Fgithub.com%2Fusetrmnl%2Fbyos_next%3Ftab%3Dreadme-ov-file&project-name=byos-next&repository-name=byos_next&demo-title=BYOS%20NextJS&demo-description=BYOS%20(Build%20Your%20Own%20Server)%20Next.js%2C%20TRMNL%20server%20with%20local%20recipe%20rendering%20and%20cloud%20proxy%20support.&demo-url=https%3A%2F%2Fbyos-next-demo.vercel.app&demo-image=https%3A%2F%2Fusetrmnl.com%2Fimages%2Fbrand%2Ficons%2Ficon--brand.svg&products=%5B%7B%22type%22%3A%22integration%22%2C%22integrationSlug%22%3A%22neon%22%2C%22productSlug%22%3A%22neon%22%2C%22protocol%22%3A%22storage%22%2C%22group%22%3A%22postgres%22%7D%5D)

### ✨ Features
- Device management UI with MAC/API key registration, status tracking, and refresh scheduling.
- Playlist-based screen rotation with time and weekday rules, custom durations, and per-device assignment.
- On-demand screen rendering to 1-bit BMP via Takumi/Satori with caching and revalidation.
- On-demand screen rendering via Takumi/Satori with model-driven image encoding, palette hard snap, and default image-only dithering.
- Postgres backed persistence for devices, logs, and playlists.
- Recipes gallery to prototype screens and compare direct vs. bitmap rendering before pushing to hardware.
- Tailwind v4 + TypeScript + Next.js 16 + React 19; Biome lint/format baseline.
Expand Down Expand Up @@ -47,7 +47,7 @@
- [License](#license)

## Highlights
- Dynamic BMP generation with Next.js 16, React 19, Tailwind CSS v4, and TypeScript.
- Dynamic device image generation with Next.js 16, React 19, Tailwind CSS v4, and TypeScript.
- Supabase-backed device management, logging, and playlist scheduling.
- No-DB fallback mode for quickly previewing screens without a database.
- Docker Compose support for local PostgreSQL.
Expand Down
180 changes: 23 additions & 157 deletions app/(app)/client-page.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,28 @@
"use client";

import { AlertTriangle, ArrowRight } from "lucide-react";
import Image from "next/image";
import { AlertTriangle } from "lucide-react";
import Link from "next/link";
import { DeviceFrame } from "@/components/common/device-frame";
import { ScreenPreviewImage } from "@/components/common/screen-preview-image";
import { StatusIndicator } from "@/components/common/status-indicator";
import { Badge } from "@/components/ui/badge";
import { RecentSystemLogs } from "@/components/system-logs/recent-system-logs";
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
DEFAULT_IMAGE_HEIGHT,
DEFAULT_IMAGE_WIDTH,
} from "@/lib/recipes/constants";
import { normalizeGrayscale } from "@/lib/trmnl/grayscale";
import { DEFAULT_MODEL_NAME } from "@/lib/trmnl/types";
import { getOrientedDeviceDimensions } from "@/lib/device/dimensions";
import { buildDevicePreviewSrc } from "@/lib/render/preview-image";
import type { Device, SystemLog } from "@/lib/types";
import { cn } from "@/lib/utils";
import { formatDate, getDeviceStatus } from "@/utils/helpers";

interface DashboardClientPageProps {
devices: Device[];
systemLogs: SystemLog[];
firstScreenByPlaylistId: Record<string, string>;
}

export default function DashboardClientPage({
devices,
systemLogs,
firstScreenByPlaylistId,
}: DashboardClientPageProps) {
const processedDevices = devices.map((device) => ({
...device,
Expand All @@ -44,24 +34,26 @@ export default function DashboardClientPage({

const lastUpdatedDevice =
processedDevices.length > 0
? processedDevices.sort(
? [...processedDevices].sort(
(a, b) =>
new Date(b.last_update_time || "").getTime() -
new Date(a.last_update_time || "").getTime(),
)[0]
: null;

const isPortrait = lastUpdatedDevice?.screen_orientation === "portrait";
// Orientation-adjusted device resolution, used for BOTH the rendered image
// and the frame aspect ratio so the preview isn't cropped by object-cover.
const previewWidth = isPortrait
? lastUpdatedDevice?.screen_height || DEFAULT_IMAGE_HEIGHT
: lastUpdatedDevice?.screen_width || DEFAULT_IMAGE_WIDTH;
const previewHeight = isPortrait
? lastUpdatedDevice?.screen_width || DEFAULT_IMAGE_WIDTH
: lastUpdatedDevice?.screen_height || DEFAULT_IMAGE_HEIGHT;
const {
width: previewWidth,
height: previewHeight,
isPortrait,
} = getOrientedDeviceDimensions(lastUpdatedDevice);
const latestScreenSrc = lastUpdatedDevice
? buildLatestScreenSrc(lastUpdatedDevice, previewWidth, previewHeight)
? buildDevicePreviewSrc(lastUpdatedDevice, {
width: previewWidth,
height: previewHeight,
playlistScreen: lastUpdatedDevice.playlist_id
? firstScreenByPlaylistId[lastUpdatedDevice.playlist_id]
: null,
})
: "";

return (
Expand Down Expand Up @@ -104,13 +96,10 @@ export default function DashboardClientPage({
portrait={isPortrait}
screenAspectRatio={`${previewWidth} / ${previewHeight}`}
>
<Image
<ScreenPreviewImage
src={latestScreenSrc}
alt={`${lastUpdatedDevice.name} screen`}
fill
className="absolute inset-0 h-full w-full object-cover"
style={{ imageRendering: "pixelated" }}
unoptimized
className="absolute inset-0"
/>
</DeviceFrame>
</div>
Expand Down Expand Up @@ -164,115 +153,11 @@ export default function DashboardClientPage({
</section>
</div>

{/* System logs */}
<section className="overflow-hidden rounded-2xl border bg-card">
<header className="flex flex-wrap items-center justify-between gap-2 border-b bg-muted/30 px-4 py-2">
<div className="flex items-center gap-2">
<h3 className="text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
Recent system logs
</h3>
<span className="rounded-full border px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground">
{systemLogs.length}
</span>
</div>
<Link
href="/system-logs"
className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
>
See all
<ArrowRight className="h-3.5 w-3.5" />
</Link>
</header>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[80px]">Time</TableHead>
<TableHead className="w-[80px]">Level</TableHead>
<TableHead>Source</TableHead>
<TableHead>Message</TableHead>
<TableHead className="max-w-[220px]">Metadata</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{systemLogs.length > 0 ? (
systemLogs.map((log, index) => {
const prevLog = index > 0 ? systemLogs[index - 1] : null;
const diffSec =
prevLog &&
Math.abs(
new Date(log.created_at || "").getTime() -
new Date(prevLog.created_at || "").getTime(),
) / 1000;
const showTime = index === 0 || (diffSec && diffSec >= 3);
const showLevel =
index === 0 ||
(prevLog && prevLog.level !== log.level) ||
(diffSec && diffSec >= 3);

return (
<TableRow key={log.id}>
<TableCell
className="text-xs tabular-nums text-muted-foreground"
suppressHydrationWarning
>
{showTime ? formatDate(log.created_at) : ""}
</TableCell>
<TableCell>
{showLevel ? <LevelBadge level={log.level} /> : ""}
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{log.source || "—"}
</TableCell>
<TableCell className="text-sm">{log.message}</TableCell>
<TableCell className="max-w-[220px] truncate text-xs text-muted-foreground">
{log.metadata}
</TableCell>
</TableRow>
);
})
) : (
<TableRow>
<TableCell
colSpan={5}
className="h-32 text-center text-sm text-muted-foreground"
>
No system logs to show
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</section>
<RecentSystemLogs systemLogs={systemLogs} />
</div>
);
}

function buildLatestScreenSrc(
device: Device,
width: number,
height: number,
): string {
const params = new URLSearchParams({
width: String(width),
height: String(height),
grayscale: String(normalizeGrayscale(device.grayscale)),
model: device.model?.trim() || DEFAULT_MODEL_NAME,
});
const paletteId = device.palette_id?.trim();
if (paletteId) {
params.set("palette_id", paletteId);
}

if (!device.screen) {
params.set("message", "Device screen is not configured");
return `/api/bitmap/error.png?${params.toString()}`;
}

return `/api/bitmap/${device.screen}.png?${params.toString()}`;
}

function Stat({
label,
value,
Expand Down Expand Up @@ -356,22 +241,3 @@ function DeviceColumn({
</div>
);
}

function LevelBadge({ level }: { level: SystemLog["level"] }) {
const styles: Record<NonNullable<SystemLog["level"]>, string> = {
error: "bg-destructive/10 text-destructive border-destructive/20",
warning:
"bg-amber-500/10 text-amber-700 border-amber-500/20 dark:text-amber-400",
info: "bg-primary/10 text-primary border-primary/20",
debug: "bg-muted text-muted-foreground border-border",
};
if (!level) return null;
return (
<Badge
variant="outline"
className={cn("text-[10px] uppercase tracking-wider", styles[level])}
>
{level}
</Badge>
);
}
58 changes: 22 additions & 36 deletions app/(app)/device/[friendly_id]/client-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@

import { Pencil, RefreshCw, Save, X } from "lucide-react";
import type React from "react";
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { fetchDeviceByFriendlyId, updateDevice } from "@/app/actions/device";
import { PageTemplate } from "@/components/common/page-template";
import { StatusIndicator } from "@/components/common/status-indicator";
import DeviceEditForm from "@/components/device/device-edit-form";
import DeviceView from "@/components/device/device-view";
import DeviceLogsContainer from "@/components/device-logs/device-logs-container";
import { Button } from "@/components/ui/button";
import { UI_REFRESH_FALLBACK_SECONDS } from "@/lib/device/defaults";
import {
getPlaylistScreens,
type PlaylistScreen,
} from "@/lib/playlists/playlist-items";
import {
DEFAULT_IMAGE_HEIGHT,
DEFAULT_IMAGE_WIDTH,
Expand Down Expand Up @@ -57,15 +60,24 @@ export default function DeviceClientPage({
const [editedDevice, setEditedDevice] = useState<
Device & { status?: string; type?: string }
>(JSON.parse(JSON.stringify(initialDevice)));
const [playlistScreens, setPlaylistScreens] = useState<
{ screen: string; duration: number }[]
>([]);
const [playlistScreens, setPlaylistScreens] = useState<PlaylistScreen[]>([]);
const [isSaving, setIsSaving] = useState(false);

// State for validation error messages
const [apiKeyError, setApiKeyError] = useState<string | null>(null);
const [friendlyIdError, setFriendlyIdError] = useState<string | null>(null);

// Adopt fresh server data (e.g. from the dashboard auto-refresh) without
// clobbering in-progress edits. Keyed on `initialDevice` only so toggling
// edit mode off after a save doesn't re-apply a now-stale prop.
const isEditingRef = useRef(isEditing);
isEditingRef.current = isEditing;
useEffect(() => {
if (isEditingRef.current) return;
setDevice(initialDevice);
setEditedDevice(JSON.parse(JSON.stringify(initialDevice)));
}, [initialDevice]);

// State for device size preset
const [deviceSizePreset, setDeviceSizePreset] = useState<DeviceSizePreset>(
() => {
Expand Down Expand Up @@ -176,13 +188,7 @@ export default function DeviceClientPage({
},
});
} else {
// Convert grayscale to number
if (name === "grayscale") {
setEditedDevice({
...editedDevice,
[name]: Number.parseInt(value, 10),
});
} else if (name === "model") {
if (name === "model") {
const model = trmnlModels.find((item) => item.name === value);
const nextPaletteId = model?.palette_ids[0] ?? null;
setEditedDevice({
Expand Down Expand Up @@ -298,7 +304,6 @@ export default function DeviceClientPage({
screen_width: editedDevice.screen_width,
screen_height: editedDevice.screen_height,
screen_orientation: editedDevice.screen_orientation,
grayscale: editedDevice.grayscale,
model: editedDevice.model,
palette_id: editedDevice.palette_id,
temperature_profile: editedDevice.temperature_profile,
Expand Down Expand Up @@ -412,36 +417,16 @@ export default function DeviceClientPage({
};

useEffect(() => {
if (editedDevice.playlist_id) {
const playlistScreens = playlistItems
.filter((item) => item.playlist_id === editedDevice.playlist_id)
.map((item) => ({
screen: item.screen_id,
duration: item.duration,
}));
setPlaylistScreens(playlistScreens);
}
setPlaylistScreens(
getPlaylistScreens(playlistItems, editedDevice.playlist_id),
);
}, [editedDevice.playlist_id, playlistItems]);

return (
<PageTemplate
title={
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<h1 className="text-2xl font-bold tracking-tight">{device.name}</h1>
<span className="inline-flex items-center gap-1.5 rounded-full border bg-muted/40 px-2 py-0.5 text-[11px] font-medium capitalize text-muted-foreground">
<StatusIndicator
status={
device.status === "online" || device.status === "offline"
? device.status
: "offline"
}
size="sm"
/>
{device.status}
</span>
<span className="font-mono text-[11px] text-muted-foreground">
{device.friendly_id}
</span>
</div>
}
left={
Expand Down Expand Up @@ -489,6 +474,7 @@ export default function DeviceClientPage({
editedDevice={editedDevice}
availableScreens={availableScreens}
availablePlaylists={availablePlaylists}
playlistItems={playlistItems}
availableMixups={availableMixups}
trmnlModels={trmnlModels}
trmnlPalettes={trmnlPalettes}
Expand Down
Loading
Loading