File size: 4,930 Bytes
cf86710
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import { useHistory, useLocation } from "@docusaurus/router";
import { useEffect, useMemo, useState } from "react";
import type { DayPickerProps } from "react-day-picker";
import * as locales from "react-day-picker/locale";

const qsProps = [
  "animate",
  "broadcastCalendar",
  "captionLayout",
  "defaultMonth",
  "dir",
  "disabled",
  "disableNavigation",
  "calendar",
  "firstDayOfWeek",
  "firstWeekContainsDate",
  "fixedWeeks",
  "fromMonth",
  "hideNavigation",
  "hideWeekdays",
  "ISOWeek",
  "locale",
  "max",
  "min",
  "mode",
  "navLayout",
  "numberOfMonths",
  "numerals",
  "noonSafe",
  "pagedNavigation",
  "required",
  "reverseMonths",
  "reverseYears",
  "selected",
  "showOutsideDays",
  "showWeekNumber",
  "startMonth",
  "endMonth",
  "month",
  "timeZone",
  "toMonth",
  "weeksStartOn",
  "weekStartsOn",
];

export type DayPickerPropsWithCalendar = DayPickerProps & {
  calendar?: "gregorian" | "persian" | "ethiopic" | "buddhist" | "hebrew";
};

export function useQueryStringSync(basePath: string = "/playground") {
  const history = useHistory();
  const location = useLocation();

  const parseQueryString = (search: string): DayPickerPropsWithCalendar => {
    const params = new URLSearchParams(search);
    const parsedProps: DayPickerPropsWithCalendar = {};
    const typeMap: Record<
      string,
      "boolean" | "number" | "string" | "locale" | "date"
    > = {
      animate: "boolean",
      broadcastCalendar: "boolean",
      calendar: "string",
      captionLayout: "string",
      defaultMonth: "date",
      dir: "string",
      disabled: "string",
      disableNavigation: "boolean",
      endMonth: "date",
      firstDayOfWeek: "number",
      firstWeekContainsDate: "number",
      fixedWeeks: "boolean",
      fromMonth: "date",
      hideNavigation: "boolean",
      hideWeekdays: "boolean",
      ISOWeek: "boolean",
      locale: "locale",
      max: "number",
      min: "number",
      mode: "string",
      month: "date",
      navLayout: "string",
      numberOfMonths: "number",
      numerals: "string",
      noonSafe: "boolean",
      pagedNavigation: "boolean",
      required: "boolean",
      reverseMonths: "boolean",
      reverseYears: "boolean",
      selected: "string",
      showOutsideDays: "boolean",
      showWeekNumber: "boolean",
      startMonth: "date",
      timeZone: "string",
      toMonth: "date",
      weeksStartOn: "number",
      weekStartsOn: "number",
    };

    qsProps.forEach((key) => {
      if (!params.has(key)) {
        return;
      }
      const value = params.get(key);
      try {
        switch (typeMap[key]) {
          case "boolean":
            parsedProps[key as keyof DayPickerPropsWithCalendar] = true;
            break;
          case "number":
            if (value !== null) {
              parsedProps[key as keyof DayPickerPropsWithCalendar] =
                Number(value);
            }
            break;
          case "string":
            parsedProps[key as keyof DayPickerPropsWithCalendar] = value ?? "";
            break;
          case "locale":
            if (!value) break;
            parsedProps.locale = Object.values(locales).find(
              (locale) => locale.code === value,
            );
            break;
          case "date": {
            if (!value) break;
            const timestamp = Number(value);
            const parsedDate = new Date(
              Number.isNaN(timestamp) ? value : timestamp,
            );
            if (!Number.isNaN(parsedDate.getTime())) {
              parsedProps[key as keyof DayPickerPropsWithCalendar] = parsedDate;
            }
            break;
          }
          default:
            break;
        }
      } catch (error) {
        console.error(`Error parsing query string key "${key}":`, error);
      }
    });
    return parsedProps;
  };

  const initialProps: DayPickerProps = parseQueryString(location.search);

  const [props, setProps] = useState<DayPickerPropsWithCalendar>(initialProps);

  const updateQueryString = useMemo(
    () => (updatedProps: DayPickerProps) => {
      const qs: string[] = [];
      Object.entries(updatedProps)
        .filter(([key, value]) => !!value && qsProps.includes(key))
        .forEach(([key, value]) => {
          if (key === "locale") {
            if (!value) return;
            qs.push(`locale=${value.code}`);
          } else if (value instanceof Date) {
            qs.push(`${key}=${value.getTime()}`);
          } else {
            qs.push(`${key}${value === true ? "" : `=${value}`}`);
          }
        });

      const newQueryString = qs.length === 0 ? "" : `?${qs.join("&")}`;
      if (location.search !== newQueryString) {
        history.replace(basePath + newQueryString);
      }
    },
    [history, location.search, basePath],
  );

  useEffect(() => {
    updateQueryString(props);
  }, [props, updateQueryString]);

  return { props, setProps };
}