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

BrowserDeviceToolbar.tsx

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