aboutsummaryrefslogtreecommitdiff
path: root/packages/aml-backoffice-ui/src/route.ts
blob: 9176ab5e4f731e4d220c3eef88fb26e75fbfdccf (plain)
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
181
182
import { TranslatedString } from "@gnu-taler/taler-util";
import { createHashHistory } from "history";
import { h as create, VNode } from "preact";
import { useEffect, useState } from "preact/hooks";
const history = createHashHistory();

type PageDefinition<DynamicPart extends Record<string, string>> = {
  pattern: string;
  (params: DynamicPart): string;
};

function replaceAll(
  pattern: string,
  vars: Record<string, string>,
  values: Record<string, string>,
): string {
  let result = pattern;
  for (const v in vars) {
    result = result.replace(vars[v], !values[v] ? "" : values[v]);
  }
  return result;
}

export function pageDefinition<T extends Record<string, string>>(
  pattern: string,
): PageDefinition<T> {
  const patternParams = pattern.match(/(:[\w?]*)/g);
  if (!patternParams)
    throw Error(
      `page definition pattern ${pattern} doesn't have any parameter`,
    );

  const vars = patternParams.reduce((prev, cur) => {
    const pName = cur.match(/(\w+)/g);

    //skip things like :? in the path pattern
    if (!pName || !pName[0]) return prev;
    const name = pName[0];
    return { ...prev, [name]: cur };
  }, {} as Record<string, string>);

  const f = (values: T): string => replaceAll(pattern, vars, values);
  f.pattern = pattern;
  return f;
}

export type PageEntry<T = unknown> = T extends Record<string, string>
  ? {
    url: PageDefinition<T>;
    view: (props: T) => VNode;
    name: TranslatedString,
    Icon?: () => VNode,
  }
  : T extends unknown
  ? {
    url: string;
    view: (props: {}) => VNode;
    name: TranslatedString,
    Icon?: () => VNode,
  }
  : never;

export function Router({
  pageList,
  onNotFound,
}: {
  pageList: Array<PageEntry<any>>;
  onNotFound: () => VNode;
}): VNode {
  const current = useCurrentLocation(pageList);
  if (current !== undefined) {
    return create(current.page.view, current.values);
  }
  return onNotFound();
}

type Location = {
  page: PageEntry<any>;
  path: string;
  values: Record<string, string>;
};
export function useCurrentLocation(pageList: Array<PageEntry<any>>) {
  const [currentLocation, setCurrentLocation] = useState<Location>();
  /**
   * Search path in the pageList
   * get the values from the path found
   * add params from searchParams
   *
   * @param path
   * @param params
   */
  function doSync(path: string, params: URLSearchParams) {
    let result: typeof currentLocation;
    for (let idx = 0; idx < pageList.length; idx++) {
      const page = pageList[idx];
      if (typeof page.url === "string") {
        if (page.url === path) {
          const values: Record<string, string> = {};
          params.forEach((v, k) => {
            values[k] = v;
          });
          result = { page, values, path };
          break;
        }
      } else {
        const values = doestUrlMatchToRoute(path, page.url.pattern);
        if (values !== undefined) {
          params.forEach((v, k) => {
            values[k] = v;
          });
          result = { page, values, path };
          break;
        }
      }
    }
    setCurrentLocation(result);
  }
  useEffect(() => {
    doSync(window.location.hash, new URLSearchParams(window.location.search));
    return history.listen(() => {
      doSync(window.location.hash, new URLSearchParams(window.location.search));
    });
  }, []);
  return currentLocation;
}

export function useChangeLocation() {
  const [location, setLocation] = useState(window.location.hash)
  useEffect(() => {
    return history.listen(() => {
      setLocation(window.location.hash)
    });
  }, []);
  return location;
}

function doestUrlMatchToRoute(
  url: string,
  route: string,
): undefined | Record<string, string> {
  const paramsPattern = /(?:\?([^#]*))?$/;
  // const paramsPattern = /(?:\?([^#]*))?(#.*)?$/;
  const params = url.match(paramsPattern);
  const urlWithoutParams = url.replace(paramsPattern, "");

  const result: Record<string, string> = {};
  if (params && params[1]) {
    const paramList = params[1].split("&");
    for (let i = 0; i < paramList.length; i++) {
      const idx = paramList[i].indexOf("=");
      const name = paramList[i].substring(0, idx);
      const value = paramList[i].substring(idx + 1);
      result[decodeURIComponent(name)] = decodeURIComponent(value);
    }
  }
  const urlSeg = urlWithoutParams.split("/");
  const routeSeg = route.split("/");
  let max = Math.max(urlSeg.length, routeSeg.length);
  for (let i = 0; i < max; i++) {
    if (routeSeg[i] && routeSeg[i].charAt(0) === ":") {
      const param = routeSeg[i].replace(/(^:|[+*?]+$)/g, "");

      const flags = (routeSeg[i].match(/[+*?]+$/) || EMPTY)[0] || "";
      const plus = ~flags.indexOf("+");
      const star = ~flags.indexOf("*");
      const val = urlSeg[i] || "";

      if (!val && !star && (flags.indexOf("?") < 0 || plus)) {
        return undefined;
      }
      result[param] = decodeURIComponent(val);
      if (plus || star) {
        result[param] = urlSeg.slice(i).map(decodeURIComponent).join("/");
        break;
      }
    } else if (routeSeg[i] !== urlSeg[i]) {
      return undefined;
    }
  }
  return result;
}
const EMPTY: Record<string, string> = {};