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

BrowserDeviceToolbar.tsx

325 lines10.6 KB

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