formSearch.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import {Field, JsonFormObject} from 'sentry/components/forms/types';
  2. import FormSearchStore, {FormSearchField} from 'sentry/stores/formSearchStore';
  3. type Params = {
  4. fields: Record<string, Field>;
  5. formGroups: JsonFormObject[];
  6. route: string;
  7. };
  8. /**
  9. * Creates a list of objects to be injected by a search source
  10. *
  11. * @param route The route a form field belongs on
  12. * @param formGroups An array of `FormGroup: {title: string, fields: [Field]}`
  13. * @param fields An object whose key is field name and value is a `Field`
  14. */
  15. const createSearchMap = ({
  16. route,
  17. formGroups,
  18. fields,
  19. ...other
  20. }: Params): FormSearchField[] => {
  21. // There are currently two ways to define forms (TODO(billy): Turn this into one):
  22. // If `formGroups` is defined, then return a flattened list of fields in all formGroups
  23. // Otherwise `fields` is a map of fieldName -> fieldObject -- create a list of fields
  24. const listOfFields = formGroups
  25. ? formGroups.flatMap(formGroup => formGroup.fields)
  26. : Object.keys(fields).map(fieldName => fields[fieldName]);
  27. return listOfFields.map(field => ({
  28. ...other,
  29. route,
  30. title: typeof field !== 'function' ? field.label : undefined,
  31. description: typeof field !== 'function' ? field.help : undefined,
  32. field,
  33. }));
  34. };
  35. export function loadSearchMap() {
  36. // Load all form configuration files via webpack that export a named `route`
  37. // as well as either `fields` or `formGroups`
  38. const context = require.context('../data/forms', true, /\.tsx?$/);
  39. // Get a list of all form fields defined in `../data/forms`
  40. const allFormFields: FormSearchField[] = context.keys().flatMap(key => {
  41. const mod = context(key);
  42. // Since we're dynamically importing an entire directly, there could be malformed modules defined?
  43. // Only look for module that have `route` exported
  44. if (!mod?.route) {
  45. return [];
  46. }
  47. const searchMap = createSearchMap({
  48. // `formGroups` can be a default export or a named export :<
  49. formGroups: mod.default || mod.formGroups,
  50. fields: mod.fields,
  51. route: mod.route,
  52. });
  53. if (searchMap !== null) {
  54. return searchMap;
  55. }
  56. return [];
  57. });
  58. FormSearchStore.loadSearchMap(allFormFields);
  59. }