Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BrowserDeviceToolbar.tsx

334 lines11.3 KB

1"use client";
2​
3import {
4 PREVIEW_VIEWPORT_MAX_AREA,
5 PREVIEW_VIEWPORT_MAX_DIMENSION,
6 PREVIEW_VIEWPORT_MIN_DIMENSION,
7 type PreviewViewportSetting,
8} from "@t3tools/contracts";
9import { PREVIEW_VIEWPORT_PRESETS, resolvePreviewViewport } from "@t3tools/shared/previewViewport";
10import { Link2, Unlink2, X } from "lucide-react";
11import { useState } from "react";
12​
13import { Button } from "~/components/ui/button";
14import { Input } from "~/components/ui/input";
15import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
16import {
17 Select,
18 SelectGroup,
19 SelectGroupLabel,
20 SelectItem,
21 SelectPopup,
22 SelectTrigger,
23 SelectValue,
24} from "~/components/ui/select";
25import { cn } from "~/lib/utils";
26​
27import { BROWSER_DEVICE_TOOLBAR_HEIGHT, resizeFreeformViewport } from "./browserViewportLayout";
28import { commitViewportAndAspectRatio } from "./browserDeviceToolbarState";
29import { ScreenRotationIcon } from "./ScreenRotationIcon";
30​
31const RESPONSIVE_VALUE = "responsive";
32const SELECT_ITEMS = [
33 { value: RESPONSIVE_VALUE, label: "Responsive" },
34 ...PREVIEW_VIEWPORT_PRESETS.map((preset) => ({ value: preset.id, label: preset.label })),
35];
36​
37interface Props {
38 readonly setting: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>;
39 readonly width: number;
40 readonly aspectRatio: number | null;
41 readonly onAspectRatioChange: (aspectRatio: number | null) => void;
42 readonly onChange: (setting: PreviewViewportSetting) => Promise<void>;
44​
45export function BrowserDeviceToolbar({
46 setting,
47 width,
48 aspectRatio,
49 onAspectRatioChange,
50 onChange,
51}: Props) {
52 const [pending, setPending] = useState(false);
53 const [customSize, setCustomSize] = useState<{
54 readonly width: string;
55 readonly height: string;
56 } | null>(null);
57 const presentedSize = customSize ?? {
58 width: String(setting.width),
59 height: String(setting.height),
60 };
61 const selectedValue =
62 setting._tag === "preset" &&
63 PREVIEW_VIEWPORT_PRESETS.some((preset) => preset.id === setting.presetId)
64 ? setting.presetId
65 : RESPONSIVE_VALUE;
66 const customWidth = Number(presentedSize.width);
67 const customHeight = Number(presentedSize.height);
68 const customValid =
69 Number.isInteger(customWidth) &&
70 Number.isInteger(customHeight) &&
71 customWidth >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
72 customWidth <= PREVIEW_VIEWPORT_MAX_DIMENSION &&
73 customHeight >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
74 customHeight <= PREVIEW_VIEWPORT_MAX_DIMENSION &&
75 customWidth * customHeight <= PREVIEW_VIEWPORT_MAX_AREA;
76​
77 const apply = (next: PreviewViewportSetting, nextAspectRatio = aspectRatio) => {
78 setPending(true);
79 void commitViewportAndAspectRatio(next, nextAspectRatio, onChange, onAspectRatioChange).then(
80 () => {
81 setPending(false);
82 setCustomSize(null);
83 },
84 () => setPending(false),
85 );
86 };
87​
88 const applyCustomSize = () => {
89 if (!customValid || (customWidth === setting.width && customHeight === setting.height)) {
90 setCustomSize(null);
91 return;
92 }
93 apply({ _tag: "freeform", width: customWidth, height: customHeight });
94 };
95​
96 const updateCustomDimension = (axis: "width" | "height", value: string) => {
97 setCustomSize((current) => {
98 const next = {
99 width: axis === "width" ? value : (current?.width ?? String(setting.width)),
100 height: axis === "height" ? value : (current?.height ?? String(setting.height)),
101 };
102 const numeric = Number(value);
103 if (
104 aspectRatio === null ||
105 !Number.isInteger(numeric) ||
106 numeric < PREVIEW_VIEWPORT_MIN_DIMENSION ||
107 numeric > PREVIEW_VIEWPORT_MAX_DIMENSION
108 ) {
109 return next;
110 }
111 const resized = resizeFreeformViewport(
112 setting,
113 axis === "width"
114 ? { x: numeric - setting.width, y: 0 }
115 : { x: 0, y: numeric - setting.height },
116 1,
117 axis === "width" ? "east" : "south",
118 aspectRatio,
119 );
120 return { width: String(resized.width), height: String(resized.height) };
121 });
122 };
123​
124 const selectViewport = (value: string | null) => {
125 if (!value) return;
126 if (value === RESPONSIVE_VALUE) {
127 if (setting._tag === "freeform") return;
128 apply({ _tag: "freeform", width: setting.width, height: setting.height });
129 return;
130 }
131 const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.id === value);
132 if (!preset) return;
133 apply(
134 resolvePreviewViewport({ mode: "preset", preset: preset.id }),
135 aspectRatio === null ? null : preset.width / preset.height,
136 );
137 };
138​
139 const rotate = () => {
140 const hasCustomSize =
141 customValid && (customWidth !== setting.width || customHeight !== setting.height);
142 const source = hasCustomSize
143 ? ({ _tag: "freeform", width: customWidth, height: customHeight } as const)
144 : setting;
145 apply(
146 { ...source, width: source.height, height: source.width },
147 aspectRatio === null ? null : 1 / aspectRatio,
148 );
149 };
150​
151 const toggleAspectRatio = () => {
152 onAspectRatioChange(aspectRatio === null ? customWidth / customHeight : null);
153 };
154​
155 return (
156 <div
157 className="sticky left-0 top-0 z-50 flex items-center gap-0.5 overflow-x-auto border-b border-border/70 bg-background/95 px-1.5 shadow-xs backdrop-blur-md [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
158 style={{ width, height: BROWSER_DEVICE_TOOLBAR_HEIGHT }}
159 role="toolbar"
160 aria-label="Browser device toolbar"
161 data-browser-device-toolbar
162 onBlur={(event) => {
163 const nextTarget = event.relatedTarget;
164 if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
165 const eventTarget = event.target;
166 if (
167 (nextTarget instanceof HTMLElement &&
168 nextTarget.closest('[data-slot="select-positioner"]')) ||
169 (eventTarget instanceof HTMLElement &&
170 eventTarget.closest('[data-slot="select-positioner"]'))
171 ) {
172 return;
173 }
174 applyCustomSize();
175 }}
176 >
177 {width >= 560 ? (
178 <span className="mr-0.5 shrink-0 text-[11px] font-medium text-muted-foreground">
179 Dimensions
180 </span>
181 ) : null}
182 <Select
183 modal={false}
184 value={selectedValue}
185 onValueChange={selectViewport}
186 items={SELECT_ITEMS}
187 disabled={pending}
188 >
189 <SelectTrigger
190 variant="ghost"
191 size="xs"
192 className={cn(
193 "shrink-0 justify-between px-1.5 font-medium",
194 width >= 440 ? "w-36" : "w-24",
195 )}
196 aria-label="Browser device preset"
197 >
198 <SelectValue />
199 </SelectTrigger>
200 <SelectPopup align="start" alignItemWithTrigger={false} className="min-w-64">
201 <SelectItem value={RESPONSIVE_VALUE}>Responsive</SelectItem>
202 <SelectGroup>
203 <SelectGroupLabel>Standard</SelectGroupLabel>
204 {PREVIEW_VIEWPORT_PRESETS.map((preset) => (
205 <SelectItem key={preset.id} value={preset.id}>
206 <span className="flex w-full items-center justify-between gap-5">
207 <span>{preset.label}</span>
208 <span className="text-xs tabular-nums text-muted-foreground">
209 {preset.detail}
210 </span>
211 </span>
212 </SelectItem>
213 ))}
214 </SelectGroup>
215 </SelectPopup>
216 </Select>
217​
218 <form
219 className="m-0 flex min-w-0 shrink-0 items-center gap-0.5 border-0 p-0"
220 aria-label="Viewport dimensions"
221 onSubmit={(event) => {
222 event.preventDefault();
223 applyCustomSize();
224 }}
225 >
226 <Input
227 nativeInput
228 type="number"
229 inputMode="numeric"
230 size="sm"
231 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
232 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
233 value={presentedSize.width}
234 disabled={pending}
235 onFocus={() =>
236 setCustomSize(
237 (current) =>
238 current ?? {
239 width: String(setting.width),
240 height: String(setting.height),
241 },
242 )
243 }
244 onChange={(event) => updateCustomDimension("width", event.target.value)}
245 aria-label="Viewport width"
246 aria-invalid={!customValid}
247 className={cn(
248 "h-6 rounded-md text-center tabular-nums [&_[data-slot=input]]:h-full [&_[data-slot=input]]:px-1 [&_[data-slot=input]]:text-xs [&_[data-slot=input]]:leading-none [&_[data-slot=input]::-webkit-inner-spin-button]:appearance-none [&_[data-slot=input]]:[appearance:textfield]",
249 width >= 360 ? "w-14" : "w-11",
250 )}
251 />
252 <span className="text-xs text-muted-foreground">×</span>
253 <Input
254 nativeInput
255 type="number"
256 inputMode="numeric"
257 size="sm"
258 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
259 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
260 value={presentedSize.height}
261 disabled={pending}
262 onFocus={() =>
263 setCustomSize(
264 (current) =>
265 current ?? {
266 width: String(setting.width),
267 height: String(setting.height),
268 },
269 )
270 }
271 onChange={(event) => updateCustomDimension("height", event.target.value)}
272 aria-label="Viewport height"
273 aria-invalid={!customValid}
274 className={cn(
275 "h-6 rounded-md text-center tabular-nums [&_[data-slot=input]]:h-full [&_[data-slot=input]]:px-1 [&_[data-slot=input]]:text-xs [&_[data-slot=input]]:leading-none [&_[data-slot=input]::-webkit-inner-spin-button]:appearance-none [&_[data-slot=input]]:[appearance:textfield]",
276 width >= 360 ? "w-14" : "w-11",
277 )}
278 />
279 </form>
280​
281 <Tooltip>
282 <TooltipTrigger
283 render={
284 <Button
285 variant="ghost"
286 size="icon-xs"
287 type="button"
288 aria-label={
289 aspectRatio === null ? "Lock viewport aspect ratio" : "Unlock viewport aspect ratio"
290 }
291 aria-pressed={aspectRatio !== null}
292 className={cn(aspectRatio !== null && "bg-accent text-foreground")}
293 disabled={pending || !customValid}
294 onPointerDown={(event) => event.preventDefault()}
295 onClick={toggleAspectRatio}
296 />
297 }
298 >
299 {aspectRatio === null ? (
300 <Unlink2 className={cn(aspectRatio !== null && "text-foreground")} />
301 ) : (
302 <Link2 className={cn(aspectRatio !== null && "text-foreground")} />
303 )}
304 </TooltipTrigger>
305 <TooltipPopup side="top">
306 {aspectRatio === null ? "Lock aspect ratio" : "Unlock aspect ratio"}
307 </TooltipPopup>
308 </Tooltip>
309 <Button
310 variant="ghost"
311 size="icon-xs"
312 type="button"
313 aria-label="Rotate viewport"
314 disabled={pending}
315 onClick={rotate}
316 >
317 <ScreenRotationIcon />
318 </Button>
319 <Button
320 variant="ghost"
321 size="icon-xs"
322 type="button"
323 aria-label="Close device toolbar"
324 className="sticky right-0 ml-auto bg-background/95"
325 disabled={pending}
326 onClick={() => {
327 apply({ _tag: "fill" }, null);
328 }}
329 >
330 <X />
331 </Button>
332 </div>
333 );