|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +import { useEffect } from "react"; |
| 4 | +import { useSearchParams } from "react-router-dom"; |
| 5 | + |
| 6 | +import { applyDensity, applyMode, Density, disableMotion, Mode } from "@cloudscape-design/global-styles"; |
| 7 | + |
| 8 | +export interface AppUrlParams { |
| 9 | + mode: Mode; |
| 10 | + density: Density; |
| 11 | + direction: "ltr" | "rtl"; |
| 12 | + motionDisabled: boolean; |
| 13 | +} |
| 14 | + |
| 15 | +export const defaults: AppUrlParams = { |
| 16 | + mode: Mode.Light, |
| 17 | + density: Density.Comfortable, |
| 18 | + direction: "ltr", |
| 19 | + motionDisabled: false, |
| 20 | +}; |
| 21 | + |
| 22 | +function castToBoolean(s: string) { |
| 23 | + if (s === "true" || s === "false") { |
| 24 | + return s === "true"; |
| 25 | + } |
| 26 | + return s; |
| 27 | +} |
| 28 | + |
| 29 | +export function parseQuery(urlParams: URLSearchParams) { |
| 30 | + const queryParams: Record<string, any> = { ...defaults }; |
| 31 | + urlParams.forEach((value, key) => (queryParams[key] = castToBoolean(value))); |
| 32 | + return queryParams as AppUrlParams; |
| 33 | +} |
| 34 | + |
| 35 | +export function formatQuery(params: AppUrlParams) { |
| 36 | + const query: Record<string, string> = {}; |
| 37 | + for (const [key, value] of Object.entries(params)) { |
| 38 | + if (value === defaults[key as keyof AppUrlParams]) { |
| 39 | + continue; |
| 40 | + } |
| 41 | + query[key] = String(value); |
| 42 | + } |
| 43 | + return query; |
| 44 | +} |
| 45 | + |
| 46 | +export default function useModes() { |
| 47 | + const [searchParams, setSearchParams] = useSearchParams(); |
| 48 | + const urlParams = parseQuery(searchParams); |
| 49 | + const { density, direction, mode, motionDisabled } = urlParams; |
| 50 | + |
| 51 | + function setParams(newParams: Partial<AppUrlParams>) { |
| 52 | + setSearchParams(formatQuery({ ...urlParams, ...newParams })); |
| 53 | + } |
| 54 | + |
| 55 | + useEffect(() => { |
| 56 | + applyMode(mode); |
| 57 | + }, [mode]); |
| 58 | + |
| 59 | + useEffect(() => { |
| 60 | + applyDensity(density); |
| 61 | + }, [density]); |
| 62 | + |
| 63 | + useEffect(() => { |
| 64 | + disableMotion(motionDisabled); |
| 65 | + }, [motionDisabled]); |
| 66 | + |
| 67 | + useEffect(() => { |
| 68 | + document.documentElement.setAttribute("dir", direction); |
| 69 | + }, [direction]); |
| 70 | + |
| 71 | + return { density, direction, mode, motionDisabled, setParams }; |
| 72 | +} |
0 commit comments