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

BrowserDeviceToolbar.tsx

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