summaryrefslogtreecommitdiff
path: root/packages/web-util/src/forms/forms.ts
blob: 4c50508309c5a5448a47ac26d222176f0dadff61 (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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import { h as create, Fragment, VNode } from "preact";
import { Caption } from "./Caption.js";
import { Group } from "./Group.js";
import { InputAbsoluteTime } from "./InputAbsoluteTime.js";
import { InputAmount } from "./InputAmount.js";
import { InputArray } from "./InputArray.js";
import { InputChoiceHorizontal } from "./InputChoiceHorizontal.js";
import { InputChoiceStacked } from "./InputChoiceStacked.js";
import { InputFile } from "./InputFile.js";
import { InputInteger } from "./InputInteger.js";
import { InputSelectMultiple } from "./InputSelectMultiple.js";
import { InputSelectOne } from "./InputSelectOne.js";
import { InputText } from "./InputText.js";
import { InputTextArea } from "./InputTextArea.js";
import { InputToggle } from "./InputToggle.js";
import { Addon, StringConverter, UIFieldHandler } from "./FormProvider.js";
import { InternationalizationAPI, UIFieldElementDescription } from "../index.browser.js";
import { assertUnreachable, TranslatedString } from "@gnu-taler/taler-util";
import {UIFormFieldBaseConfig, UIFormElementConfig} from "./ui-form.js";
/**
 * Constrain the type with the ui props
 */
type FieldType<T extends object = any, K extends keyof T = any> = {
  group: Parameters<typeof Group>[0];
  caption: Parameters<typeof Caption>[0];
  array: Parameters<typeof InputArray<T, K>>[0];
  file: Parameters<typeof InputFile<T, K>>[0];
  selectOne: Parameters<typeof InputSelectOne<T, K>>[0];
  selectMultiple: Parameters<typeof InputSelectMultiple<T, K>>[0];
  text: Parameters<typeof InputText<T, K>>[0];
  textArea: Parameters<typeof InputTextArea<T, K>>[0];
  choiceStacked: Parameters<typeof InputChoiceStacked<T, K>>[0];
  choiceHorizontal: Parameters<typeof InputChoiceHorizontal<T, K>>[0];
  absoluteTimeText: Parameters<typeof InputAbsoluteTime<T, K>>[0];
  integer: Parameters<typeof InputInteger<T, K>>[0];
  toggle: Parameters<typeof InputToggle<T, K>>[0];
  amount: Parameters<typeof InputAmount<T, K>>[0];
};

/**
 * List all the form fields so typescript can type-check the form instance
 */
export type UIFormField =
  | { type: "group"; properties: FieldType["group"] }
  | { type: "caption"; properties: FieldType["caption"] }
  | { type: "array"; properties: FieldType["array"] }
  | { type: "file"; properties: FieldType["file"] }
  | { type: "amount"; properties: FieldType["amount"] }
  | { type: "selectOne"; properties: FieldType["selectOne"] }
  | {
      type: "selectMultiple";
      properties: FieldType["selectMultiple"];
    }
  | { type: "text"; properties: FieldType["text"] }
  | { type: "textArea"; properties: FieldType["textArea"] }
  | {
      type: "choiceStacked";
      properties: FieldType["choiceStacked"];
    }
  | {
      type: "choiceHorizontal";
      properties: FieldType["choiceHorizontal"];
    }
  | { type: "integer"; properties: FieldType["integer"] }
  | { type: "toggle"; properties: FieldType["toggle"] }
  | {
      type: "absoluteTimeText";
      properties: FieldType["absoluteTimeText"];
    };

type FieldComponentFunction<key extends keyof FieldType> = (
  props: FieldType[key],
) => VNode;

type UIFormFieldMap = {
  [key in keyof FieldType]: FieldComponentFunction<key>;
};

/**
 * Maps input type with component implementation
 */
const UIFormConfiguration: UIFormFieldMap = {
  group: Group,
  caption: Caption,
  //@ts-ignore
  array: InputArray,
  text: InputText,
  //@ts-ignore
  file: InputFile,
  textArea: InputTextArea,
  //@ts-ignore
  absoluteTimeText: InputAbsoluteTime,
  //@ts-ignore
  choiceStacked: InputChoiceStacked,
  //@ts-ignore
  choiceHorizontal: InputChoiceHorizontal,
  integer: InputInteger,
  //@ts-ignore
  selectOne: InputSelectOne,
  //@ts-ignore
  selectMultiple: InputSelectMultiple,
  //@ts-ignore
  toggle: InputToggle,
  //@ts-ignore
  amount: InputAmount,
};

export function RenderAllFieldsByUiConfig({
  fields,
}: {
  fields: UIFormField[];
}): VNode {
  return create(
    Fragment,
    {},
    fields.map((field, i) => {
      const Component = UIFormConfiguration[
        field.type
      ] as FieldComponentFunction<any>;
      return Component(field.properties);
    }),
  );
}

// type FormSet<T extends object> = {
//   Provider: typeof FormProvider<T>;
//   InputLine: <K extends keyof T>() => typeof InputLine<T, K>;
//   InputChoiceHorizontal: <K extends keyof T>() => typeof InputChoiceHorizontal<T, K>;
// };

/**
 * Helper function that created a typed object.
 *
 * @returns
 */
// export function createNewForm<T extends object>() {
//   const res: FormSet<T> = {
//     Provider: FormProvider,
//     InputLine: () => InputLine,
//     InputChoiceHorizontal: () => InputChoiceHorizontal,
//   };
//   return {
//     Provider: res.Provider,
//     InputLine: res.InputLine(),
//     InputChoiceHorizontal: res.InputChoiceHorizontal(),
//   };
// }

/**
 * convert field configuration to render function
 * 
 * @param i18n_ 
 * @param fieldConfig 
 * @param form 
 * @returns 
 */
export function convertUiField(
  i18n_: InternationalizationAPI,
  fieldConfig: UIFormElementConfig[],
  form: object,
  getConverterById: GetConverterById,
): UIFormField[] {
  return fieldConfig.map((config) => {
    // NON input fields
    switch (config.type) {
      case "caption": {
        const resp: UIFormField = {
          type: config.type,
          properties: converBaseFieldsProps(i18n_, config),
        };
        return resp;
      }
      case "group": {
        const resp: UIFormField = {
          type: config.type,
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            fields: convertUiField(i18n_, config.fields, form, getConverterById),
          },
        };
        return resp;
      }
    }
    // Input Fields
    switch (config.type) {
      case "array": {
        return {
          type: "array",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
            labelField: config.labelFieldId,
            fields: convertUiField(i18n_, config.fields, form, getConverterById),
          },
        } as UIFormField;
      }
      case "absoluteTimeText": {
        return {
          type: "absoluteTimeText",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
          },
        } as UIFormField;
      }
      case "amount": {
        return {
          type: "amount",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),      
            currency: config.currency,      
          },
        } as UIFormField;
      }
      case "choiceHorizontal": {
        return {
          type: "choiceHorizontal",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
            choices: config.choices,
          },
        } as UIFormField;
      }
      case "choiceStacked": {
        return {
          type: "choiceStacked",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
            choices: config.choices,
            
          },
        }as UIFormField;
      }
      case "file":{
        return {
          type: "file",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
            accept: config.accept,
            maxBites: config.maxBytes,
          },
        } as UIFormField;
      }
      case "integer":{
        return {
          type: "integer",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
          },
        } as UIFormField;
      }
      case "selectMultiple":{
        return {
          type: "selectMultiple",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
            choices: config.choices,
          },
        } as UIFormField;
      }
      case "selectOne": {
        return {
          type: "selectOne",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
            choices: config.choices,
          },
        } as UIFormField;
      }
      case "text": {
        return {
          type: "text",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
          },
        } as UIFormField;
      }
      case "textArea": {
        return {
          type: "text",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
          },
        } as UIFormField;
      }
      case "toggle": {
        return {
          type: "toggle",
          properties: {
            ...converBaseFieldsProps(i18n_, config),
            ...converInputFieldsProps(form, config, getConverterById),
          },
        } as UIFormField;
      }
      default: {
        assertUnreachable(config);
      }
    }
  });
}



function getAddonById(_id: string | undefined): Addon {
  return undefined!;
}


type GetConverterById = (
  id: string | undefined,
  config: unknown,
) => StringConverter<unknown>;


function converInputFieldsProps(
  form: object,
  p: UIFormFieldBaseConfig,
  getConverterById: GetConverterById,
) {
  return {
    converter: getConverterById(p.converterId, p),
    handler: getValueDeeper2(form, p.id.split(".")),
    name: p.name,
    required: p.required,
    disabled: p.disabled,
    help: p.help,
    placeholder: p.placeholder,
    tooltip: p.tooltip,
    label: p.label as TranslatedString,
  };
}

function converBaseFieldsProps(
  i18n_: InternationalizationAPI,
  p: UIFieldElementDescription,
) {
  return {
    after: getAddonById(p.addonAfterId),
    before: getAddonById(p.addonBeforeId),
    hidden: p.hidden,
    name: p.name,
    help: i18n_.str`${p.help}`,
    label: i18n_.str`${p.label}`,
    tooltip: i18n_.str`${p.tooltip}`,
  };
}

export function getValueDeeper2(
  object: Record<string, any>,
  names: string[],
): UIFieldHandler {
  if (names.length === 0) return object as UIFieldHandler;
  const [head, ...rest] = names;
  if (!head) {
    return getValueDeeper2(object, rest);
  }
  if (object === undefined) {
    throw Error("handler not found");
  }
  return getValueDeeper2(object[head], rest);
}