@airtable/blocks/ui#useBase JavaScript Examples

The following examples show how to use @airtable/blocks/ui#useBase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From apps-print-records with MIT License 6 votes vote down vote up
function PrintRecordsApp() {
    const base = useBase();
    const globalConfig = useGlobalConfig();

    // We want to render the list of records in this table.
    const table = base.getTableByName('Collections');

    // The view ID is stored in globalConfig using ViewPickerSynced.
    const viewId = globalConfig.get(GlobalConfigKeys.VIEW_ID);

    // The view may have been deleted, so we use getViewByIdIfExists
    // instead of getViewById. getViewByIdIfExists will return null
    // if the view doesn't exist.
    const view = table.getViewByIdIfExists(viewId);

    return (
        <div>
            <Toolbar table={table} />
            <Box margin={3}>
                <Report view={view} />
            </Box>
        </div>
    );
}
Example #2
Source File: UpdateRecordsApp.js    From apps-update-records with MIT License 6 votes vote down vote up
function UpdateRecordsApp() {
    const base = useBase();
    const cursor = useCursor();

    const tableToUpdate = base.getTableByName(TABLE_NAME);

    const numberField = tableToUpdate.getFieldByName(FIELD_NAME);

    // cursor.selectedRecordIds isn't loaded by default, so we need to load it
    // explicitly with the useLoadable hook. The rest of the code in the
    // component will not run until it has loaded.
    useLoadable(cursor);

    // Re-render the app whenever the selected records change.
    useWatchable(cursor, ['selectedRecordIds']);

    if (cursor.activeTableId !== tableToUpdate.id) {
        return (
            <Container>
                <Text>Switch to the “{tableToUpdate.name}” table to use this app.</Text>
            </Container>
        );
    }

    return (
        <Container>
            <UpdateSelectedRecordsButton
                tableToUpdate={tableToUpdate}
                fieldToUpdate={numberField}
                selectedRecordIds={cursor.selectedRecordIds}
            />
        </Container>
    );
}
Example #3
Source File: settings.js    From apps-url-preview with MIT License 6 votes vote down vote up
/**
 * A React hook to validate and access settings configured in SettingsForm.
 * @returns {{settings: *, isValid: boolean, message: string}|{settings: *, isValid: boolean}}
 */
export function useSettings() {
    const base = useBase();
    const globalConfig = useGlobalConfig();
    const settings = getSettings(globalConfig, base);
    return getSettingsValidationResult(settings);
}
Example #4
Source File: settings.js    From neighbor-express with MIT License 6 votes vote down vote up
function FieldSetter({
  label,
  description,
  keyOrPath,
  tableName,
  ...setterProps
}) {
  const globalConfig = useGlobalConfig();
  const base = useBase();
  const table = base.getTableByNameIfExists(tableName);

  function setField(newField) {
    globalConfig.setAsync(keyOrPath, newField.id);
  }
  // If table is null or undefined, the FieldPicker will not render.
  return (
    <FormField label={label} description={description}>
      <FieldPicker
        table={table}
        field={table.getFieldIfExists(globalConfig.get(keyOrPath))}
        onChange={setField}
        disabled={!globalConfig.hasPermissionToSet(keyOrPath)}
        {...setterProps}
      />
    </FormField>
  );
}
Example #5
Source File: settings.js    From apps-flashcard with MIT License 5 votes vote down vote up
/**
 * A React hook to validate and access settings configured in SettingsForm.
 * @returns {{
 *  settings: {
 *      table: Table | null,
 *      view: View | null,
 *      questionField: Field | null,
 *      answerField: Field | null,
 *  },
 *  isValid: boolean,
 *  message?: string}}
 */
export function useSettings() {
    const base = useBase();
    const globalConfig = useGlobalConfig();

    const table = base.getTableByIdIfExists(globalConfig.get(ConfigKeys.TABLE_ID));
    const view = table ? table.getViewByIdIfExists(globalConfig.get(ConfigKeys.VIEW_ID)) : null;
    const questionField = table
        ? table.getFieldByIdIfExists(globalConfig.get(ConfigKeys.QUESTION_FIELD_ID))
        : null;
    const answerField = table
        ? table.getFieldByIdIfExists(globalConfig.get(ConfigKeys.ANSWER_FIELD_ID))
        : null;
    const settings = {
        table,
        view,
        questionField,
        answerField,
    };

    if (!table || !view || !questionField) {
        return {
            isValid: false,
            message: 'Pick a table, view, and question field',
            settings,
        };
    }
    return {
        isValid: true,
        settings,
    };
}
Example #6
Source File: index.js    From apps-simple-chart with MIT License 5 votes vote down vote up
function SimpleChartApp() {
    const base = useBase();
    const globalConfig = useGlobalConfig();

    const tableId = globalConfig.get(GlobalConfigKeys.TABLE_ID);
    const table = base.getTableByIdIfExists(tableId);

    const viewId = globalConfig.get(GlobalConfigKeys.VIEW_ID);
    const view = table ? table.getViewByIdIfExists(viewId) : null;

    const xFieldId = globalConfig.get(GlobalConfigKeys.X_FIELD_ID);
    const xField = table ? table.getFieldByIdIfExists(xFieldId) : null;

    const records = useRecords(view);

    const data = records && xField ? getChartData({records, xField}) : null;

    return (
        <Box
            position="absolute"
            top={0}
            left={0}
            right={0}
            bottom={0}
            display="flex"
            flexDirection="column"
        >
            <Settings table={table} />
            {data && (
                <Box position="relative" flex="auto" padding={3}>
                    <Bar
                        data={data}
                        options={{
                            maintainAspectRatio: false,
                            scales: {
                                yAxes: [
                                    {
                                        ticks: {
                                            beginAtZero: true,
                                        },
                                    },
                                ],
                            },
                            legend: {
                                display: false,
                            },
                        }}
                    />
                </Box>
            )}
        </Box>
    );
}
Example #7
Source File: todo-app.js    From apps-todo-list with MIT License 5 votes vote down vote up
export default function TodoApp() {
    const base = useBase();

    // Read the user's choice for which table and view to use from globalConfig.
    const globalConfig = useGlobalConfig();
    const tableId = globalConfig.get('selectedTableId');
    const viewId = globalConfig.get('selectedViewId');
    const doneFieldId = globalConfig.get('selectedDoneFieldId');

    const table = base.getTableByIdIfExists(tableId);
    const view = table ? table.getViewByIdIfExists(viewId) : null;
    const doneField = table ? table.getFieldByIdIfExists(doneFieldId) : null;

    // Don't need to fetch records if doneField doesn't exist (the field or it's parent table may
    // have been deleted, or may not have been selected yet.)
    const records = useRecords(doneField ? view : null, {
        fields: doneField ? [table.primaryField, doneField] : [],
    });

    const tasks = records
        ? records.map(record => {
              return <Task key={record.id} record={record} table={table} doneField={doneField} />;
          })
        : null;

    return (
        <div>
            <Box padding={3} borderBottom="thick">
                <FormField label="Table">
                    <TablePickerSynced globalConfigKey="selectedTableId" />
                </FormField>
                <FormField label="View">
                    <ViewPickerSynced table={table} globalConfigKey="selectedViewId" />
                </FormField>
                <FormField label="Field" marginBottom={0}>
                    <FieldPickerSynced
                        table={table}
                        globalConfigKey="selectedDoneFieldId"
                        placeholder="Pick a 'done' field..."
                        allowedTypes={[FieldType.CHECKBOX]}
                    />
                </FormField>
            </Box>
            {tasks}
            {table && doneField && <AddTaskForm table={table} />}
        </div>
    );
}
Example #8
Source File: index.js    From apps-wikipedia-enrichment with MIT License 5 votes vote down vote up
function WikipediaEnrichmentApp() {
    const base = useBase();

    const table = base.getTableByName(TABLE_NAME);
    const titleField = table.getFieldByName(TITLE_FIELD_NAME);

    // load the records ready to be updated
    // we only need to load the word field - the others don't get read, only written to.
    const records = useRecords(table, {fields: [titleField]});

    // keep track of whether we have up update currently in progress - if there is, we want to hide
    // the update button so you can't have two updates running at once.
    const [isUpdateInProgress, setIsUpdateInProgress] = useState(false);

    // check whether we have permission to update our records or not. Any time we do a permissions
    // check like this, we can pass in undefined for values we don't yet know. Here, as we want to
    // make sure we can update the summary and image fields, we make sure to include them even
    // though we don't know the values we want to use for them yet.
    const permissionCheck = table.checkPermissionsForUpdateRecord(undefined, {
        [EXTRACT_FIELD_NAME]: undefined,
        [IMAGE_FIELD_NAME]: undefined,
    });

    async function onButtonClick() {
        setIsUpdateInProgress(true);
        const recordUpdates = await getExtractAndImageUpdatesAsync(table, titleField, records);
        await updateRecordsInBatchesAsync(table, recordUpdates);
        setIsUpdateInProgress(false);
    }

    return (
        <Box
            // center the button/loading spinner horizontally and vertically.
            position="absolute"
            top="0"
            bottom="0"
            left="0"
            right="0"
            display="flex"
            flexDirection="column"
            justifyContent="center"
            alignItems="center"
        >
            {isUpdateInProgress ? (
                <Loader />
            ) : (
                <Fragment>
                    <Button
                        variant="primary"
                        onClick={onButtonClick}
                        disabled={!permissionCheck.hasPermission}
                        marginBottom={3}
                    >
                        Update summaries and images
                    </Button>
                    {!permissionCheck.hasPermission &&
                        // when we don't have permission to perform the update, we want to tell the
                        // user why. `reasonDisplayString` is a human-readable string that will
                        // explain why the button is disabled.
                        permissionCheck.reasonDisplayString}
                </Fragment>
            )}
        </Box>
    );
}
Example #9
Source File: settings.js    From neighbor-express with MIT License 5 votes vote down vote up
function EmailTypeSettings({ emailType }) {
  const globalConfig = useGlobalConfig();

  const audienceOptions = [
    { value: "volunteer", label: "Volunteer" },
    { value: "recipient", label: "Delivery Recipient" },
  ];

  const deliveriesTable = useBase().getTableByNameIfExists("Deliveries");
  const triggerField = deliveriesTable.getFieldIfExists(
    globalConfig.get("trigger_column")
  );

  const stageOptions = triggerField?.options.choices.map((choice) => {
    return {
      value: choice.id,
      label: choice.name,
    };
  });

  function deleteMe() {
    globalConfig.setAsync(["email_types", emailType], undefined);
  }

  return (
    <Box padding={3}>
      <TextButton onClick={deleteMe} icon="trash" style={{ float: "right" }}>
        Delete
      </TextButton>
      <Accordion title={emailType}>
        <InputSetter
          label="Sendgrid Template ID"
          description="Find this in the Sendgrid UI. Looks like d-ea13bf1f408947829fa19779eade8250"
          keyOrPath={["email_types", emailType, "sendgrid_template"]}
        />
        <FormField
          label="Send to..."
          description="Who should this email be sent to?"
        >
          <SelectButtonsSynced
            globalConfigKey={["email_types", emailType, "audience"]}
            options={audienceOptions}
            width="320px"
          />
        </FormField>
        <FormField
          label="Send when..."
          description={`Email will be sent when ${triggerField.name} column is...`}
        >
          <SelectSynced
            globalConfigKey={["email_types", emailType, "stage"]}
            options={stageOptions}
            width="320px"
          />
        </FormField>
      </Accordion>
    </Box>
  );
}
Example #10
Source File: settings.js    From neighbor-express with MIT License 5 votes vote down vote up
function TableTemplateVariables({ tableName }) {
  const globalConfig = useGlobalConfig();
  if (globalConfig.get(["template_variables", tableName]) === undefined) {
    globalConfig.setAsync(["template_variables", tableName], {});
  }
  const base = useBase();
  const table = base.getTableByNameIfExists(tableName);

  const tableNameToSendgrid = {
    Deliveries: "delivery",
    Volunteers: "volunteer",
  };

  return (
    <Box padding={3}>
      <Text>
        {" "}
        You can use these fields from the {table.name} table in sendgrid{" "}
      </Text>
      <ul>
        {Object.keys(globalConfig.get(["template_variables", table.name])).map(
          (f_id) => {
            const field = table.getFieldIfExists(f_id);
            // this should be deletable
            const sendgridValue = globalConfig.get([
              "template_variables",
              table.name,
              f_id,
            ]);
            const sendgridFormat = `{{${tableNameToSendgrid[tableName]}.${sendgridValue}}}`;
            const removeLink = (
              <TextButton
                onClick={() => {
                  globalConfig.setAsync(
                    ["template_variables", table.name, f_id],
                    undefined
                  );
                }}
              >
                (remove)
              </TextButton>
            );
            return (
              <li key={f_id}>
                {" "}
                {field.name} -> {sendgridFormat} {removeLink}
              </li>
            );
          }
        )}
      </ul>
      <AddTemplateVariableDialog table={table} />
    </Box>
  );
}
Example #11
Source File: sync-data.js    From neighbor-express with MIT License 5 votes vote down vote up
export function SyncData() {
  const messagesTable = useBase().getTable(DESTINATION_TABLE);
  const records = useRecords(messagesTable);
  const [completed, setCompleted] = useState(false);
  const [syncing, setSyncing] = useState(false);

  const [succesfulCount, setSuccesfulCount] = useState(0);
  const [syncError, setSyncError] = useState(null);

  async function syncData() {
    setCompleted(false);
    setSyncing(true);

    const { total, err } = await SyncVolunteerData(messagesTable, records);
    setSuccesfulCount(total);
    setSyncError(err);

    setSyncing(false);
    setCompleted(true);
  }

  return (
    <Box>
      <h2> Sync Galaxy Digital Data </h2>
      {syncing && !completed && <Loader />}
      {!syncing && (
        <>
          {completed && !syncError && (
            <p>Successfully updated all volunteer data</p>
          )}
          {completed && syncError && (
            <p>
              `Sync completed for ${succesfulCount} with error ${syncError}`
            </p>
          )}
          <Box
            margin={2}
            display="flex"
            flexDirection="row"
            justifyContent="flex-start"
            alignItems="center"
          >
            <Button
              marginX={2}
              variant="primary"
              onClick={syncData}
              disabled={syncing}
            >
              Sync
            </Button>
          </Box>
        </>
      )}
    </Box>
  );
}
Example #12
Source File: index.js    From apps-print-records with MIT License 4 votes vote down vote up
// Renders a single record from the Collections table with each
// of its linked Artists records.
function Record({record}) {
    const base = useBase();

    // Each record in the "Collections" table is linked to records
    // in the "Artists" table. We want to show the Artists for
    // each collection.
    const linkedTable = base.getTableByName('Artists');
    const linkedRecords = useRecords(
        record.selectLinkedRecordsFromCell('Artists', {
            // Keep the linked records sorted by their primary field.
            sorts: [{field: linkedTable.primaryField, direction: 'asc'}],
        }),
    );

    return (
        <Box marginY={3}>
            <Heading>{record.name}</Heading>
            <table style={{borderCollapse: 'collapse', width: '100%'}}>
                <thead>
                    <tr>
                        <td
                            style={{
                                whiteSpace: 'nowrap',
                                verticalAlign: 'bottom',
                            }}
                        >
                            <Heading variant="caps" size="xsmall" marginRight={3} marginBottom={0}>
                                On display?
                            </Heading>
                        </td>
                        <td style={{width: '50%', verticalAlign: 'bottom'}}>
                            <Heading variant="caps" size="xsmall" marginRight={3} marginBottom={0}>
                                Artist name
                            </Heading>
                        </td>
                        <td style={{width: '50%', verticalAlign: 'bottom'}}>
                            <Heading variant="caps" size="xsmall" marginBottom={0}>
                                Artworks
                            </Heading>
                        </td>
                    </tr>
                </thead>
                <tbody>
                    {linkedRecords.map(linkedRecord => {
                        // Render a check or an x depending on if the artist is on display or not.
                        const isArtistOnDisplay = linkedRecord.getCellValue('On Display?');
                        return (
                            <tr key={linkedRecord.id} style={{borderTop: '2px solid #ddd'}}>
                                <td style={{textAlign: 'center', whiteSpace: 'nowrap'}}>
                                    <Box
                                        display="inline-flex"
                                        alignItems="center"
                                        justifyContent="center"
                                        width="16px"
                                        height="16px"
                                        marginRight={3}
                                        borderRadius="100%"
                                        backgroundColor={isArtistOnDisplay ? 'green' : 'red'}
                                        textColor="white"
                                    >
                                        <Icon name={isArtistOnDisplay ? 'check' : 'x'} size={12} />
                                    </Box>
                                </td>
                                <td style={{width: '50%'}}>
                                    <Text marginRight={3}>{linkedRecord.name}</Text>
                                </td>
                                <td style={{width: '50%'}}>
                                    <CellRenderer
                                        record={linkedRecord}
                                        field={linkedTable.getFieldByName('Attachments')}
                                    />
                                </td>
                            </tr>
                        );
                    })}
                </tbody>
            </table>
        </Box>
    );
}
Example #13
Source File: index.js    From apps-url-preview with MIT License 4 votes vote down vote up
// How this app chooses a preview to show:
//
// Without a specified Table & Field:
//
//  - When the user selects a cell in grid view and the field's content is
//    a supported preview URL, the app uses this URL to construct an embed
//    URL and inserts this URL into an iframe.
//
// To Specify a Table & Field:
//
//  - The user may use "Settings" to toggle a specified table and specified
//    field constraint. If the constraint switch is set to "Yes",he user must
//    set a specified table and specified field for URL previews.
//
// With a specified table & specified field:
//
//  - When the user selects a cell in grid view and the active table matches
//    the specified table or when the user opens a record from a button field
//    in the specified table:
//    The app looks in the selected record for the
//    specified field containing a supported URL (e.g. https://www.youtube.com/watch?v=KYz2wyBy3kc),
//    and uses this URL to construct an embed URL and inserts this URL into
//    an iframe.
//
function UrlPreviewApp() {
    const [isSettingsOpen, setIsSettingsOpen] = useState(false);
    useSettingsButton(() => setIsSettingsOpen(!isSettingsOpen));

    const {
        isValid,
        settings: {isEnforced, urlTable},
    } = useSettings();

    // Caches the currently selected record and field in state. If the user
    // selects a record and a preview appears, and then the user de-selects the
    // record (but does not select another), the preview will remain. This is
    // useful when, for example, the user resizes the apps pane.
    const [selectedRecordId, setSelectedRecordId] = useState(null);
    const [selectedFieldId, setSelectedFieldId] = useState(null);

    const [recordActionErrorMessage, setRecordActionErrorMessage] = useState('');

    // cursor.selectedRecordIds and selectedFieldIds aren't loaded by default,
    // so we need to load them explicitly with the useLoadable hook. The rest of
    // the code in the component will not run until they are loaded.
    useLoadable(cursor);

    // Update the selectedRecordId and selectedFieldId state when the selected
    // record or field change.
    useWatchable(cursor, ['selectedRecordIds', 'selectedFieldIds'], () => {
        // If the update was triggered by a record being de-selected,
        // the current selectedRecordId will be retained.  This is
        // what enables the caching described above.
        if (cursor.selectedRecordIds.length > 0) {
            // There might be multiple selected records. We'll use the first
            // one.
            setSelectedRecordId(cursor.selectedRecordIds[0]);
        }
        if (cursor.selectedFieldIds.length > 0) {
            // There might be multiple selected fields. We'll use the first
            // one.
            setSelectedFieldId(cursor.selectedFieldIds[0]);
        }
    });

    // Close the record action error dialog whenever settings are opened or the selected record
    // is updated. (This means you don't have to close the modal to see the settings, or when
    // you've opened a different record.)
    useEffect(() => {
        setRecordActionErrorMessage('');
    }, [isSettingsOpen, selectedRecordId]);

    // Register a callback to be called whenever a record action occurs (via button field)
    // useCallback is used to memoize the callback, to avoid having to register/unregister
    // it unnecessarily.
    const onRecordAction = useCallback(
        data => {
            // Ignore the event if settings are already open.
            // This means we can assume settings are valid (since we force settings to be open if
            // they are invalid).
            if (!isSettingsOpen) {
                if (isEnforced) {
                    if (data.tableId === urlTable.id) {
                        setSelectedRecordId(data.recordId);
                    } else {
                        // Record is from a mismatching table.
                        setRecordActionErrorMessage(
                            `This app is set up to preview URLs using records from the "${urlTable.name}" table, but was opened from a different table.`,
                        );
                    }
                } else {
                    // Preview is not supported in this case, as we wouldn't know what field to preview.
                    // Show a dialog to the user instead.
                    setRecordActionErrorMessage(
                        'You must enable "Use a specific field for previews" to preview URLs with a button field.',
                    );
                }
            }
        },
        [isSettingsOpen, isEnforced, urlTable],
    );
    useEffect(() => {
        // Return the unsubscribe function to ensure we clean up the handler.
        return registerRecordActionDataCallback(onRecordAction);
    }, [onRecordAction]);

    // This watch deletes the cached selectedRecordId and selectedFieldId when
    // the user moves to a new table or view. This prevents the following
    // scenario: User selects a record that contains a preview url. The preview appears.
    // User switches to a different table. The preview disappears. The user
    // switches back to the original table. Weirdly, the previously viewed preview
    // reappears, even though no record is selected.
    useWatchable(cursor, ['activeTableId', 'activeViewId'], () => {
        setSelectedRecordId(null);
        setSelectedFieldId(null);
    });

    const base = useBase();
    const activeTable = base.getTableByIdIfExists(cursor.activeTableId);

    useEffect(() => {
        // Display the settings form if the settings aren't valid.
        if (!isValid && !isSettingsOpen) {
            setIsSettingsOpen(true);
        }
    }, [isValid, isSettingsOpen]);

    // activeTable is briefly null when switching to a newly created table.
    if (!activeTable) {
        return null;
    }

    return (
        <Box>
            {isSettingsOpen ? (
                <SettingsForm setIsSettingsOpen={setIsSettingsOpen} />
            ) : (
                <RecordPreviewWithDialog
                    activeTable={activeTable}
                    selectedRecordId={selectedRecordId}
                    selectedFieldId={selectedFieldId}
                    setIsSettingsOpen={setIsSettingsOpen}
                />
            )}
            {recordActionErrorMessage && (
                <Dialog onClose={() => setRecordActionErrorMessage('')} maxWidth={400}>
                    <Dialog.CloseButton />
                    <Heading size="small">Can&apos;t preview URL</Heading>
                    <Text variant="paragraph" marginBottom={0}>
                        {recordActionErrorMessage}
                    </Text>
                </Dialog>
            )}
        </Box>
    );
}
Example #14
Source File: index.js    From blocks-usa-map with MIT License 4 votes vote down vote up
function USAMapBlock() {
    const [isShowingSettings, setIsShowingSettings] = useState(false);
    const [selectedState, setSelectedState] = useState(null);

    useSettingsButton(function() {
        setIsShowingSettings(!isShowingSettings);
    });

    const viewport = useViewport();

    const base = useBase();
    const globalConfig = useGlobalConfig();
    const tableId = globalConfig.get('selectedTableId');
    const stateFieldId = globalConfig.get('selectedStateFieldId');
    const colorFieldId = globalConfig.get('selectedColorFieldId');

    const table = base.getTableByIdIfExists(tableId);
    const stateField = table ? table.getFieldByIdIfExists(stateFieldId) : null;
    const colorField = table ? table.getFieldByIdIfExists(colorFieldId) : null;

    // if (table == null || stateField == null || colorField == null) {
    //     setIsShowingSettings(true);
    // }

    const records = useRecords(stateField ? table : null);

    let mapData = null;
    if (stateField !== null && colorField !== null) {
        mapData = getMapData(records, stateField, colorField);
    }

    const mapHandler = (event) => {
        setSelectedState(event.target.dataset.name);
    };

    // If settings is showing, draw settings only
    if (isShowingSettings) {
        return (
            <Box padding={3} display="flex">
                <FormField
                    label="Table"
                    description="Choose the table you want to your State data to come from."
                    padding={1}
                    marginBottom={0}
                >
                    <TablePickerSynced globalConfigKey="selectedTableId" />
                </FormField>
                <FormField
                    label="State Field"
                    description='The State field will select a state by either abbreviation ("NJ") or name ("New Jersey")'
                    marginBottom={0}
                    padding={1}
                >
                    <FieldPickerSynced
                        table={table}
                        globalConfigKey="selectedStateFieldId"
                        placeholder="Pick a 'state' field..."
                        allowedTypes={[FieldType.SINGLE_LINE_TEXT, FieldType.SINGLE_SELECT, FieldType.MULTIPLE_RECORD_LINKS, FieldType.MULTIPLE_LOOKUP_VALUES]}
                    />
                </FormField>
                <FormField
                    label="Color Field"
                    marginBottom={0}
                    description="Choose the state color using either a text field which describes the color name, or a single select."
                    padding={1}
                >
                    <FieldPickerSynced
                        table={table}
                        globalConfigKey="selectedColorFieldId"
                        placeholder="Pick a 'color' field..."
                        allowedTypes={[FieldType.SINGLE_LINE_TEXT, FieldType.SINGLE_SELECT, FieldType.MULTIPLE_LOOKUP_VALUES, FieldType.NUMBER]}
                    />

                {colorField != null && colorField.type === FieldType.NUMBER &&
                    <text>You have selected a numeric type; state colors will be normalized to the maximum value in your field.</text>
                }
                </FormField>
            </Box>
        )
    }
    // otherwise draw the map.
    return (
        <div>
            <Box border="default"
                 backgroundColor="lightGray1"
                //  padding={}
                 >
                {/* TODO Allow selected state to show a column of data. */}
                {/* {selectedState
                    ? <SelectedState selected={selectedState}/>
                    : <div>Click to select a state</div>
                } */}
                <USAMap
                    title="USA USA USA"
                    width={viewport.size.width}
                    height={viewport.size.height - 5}
                    customize={mapData}
                    onClick={mapHandler}
                />
            </Box>
        </div>
    )
}
Example #15
Source File: send-messages.js    From neighbor-express with MIT License 4 votes vote down vote up
export function SendMessagesStep({ previousStep }) {
  const [completed, setCompleted] = useState(false);
  const [sending, setSending] = useState(false);
  const [progress, setProgress] = useState(0);

  const messagesTable = useBase().getTable("Messages");
  const statusField = messagesTable.getFieldByName("Status");
  const queuedOption = statusField.options.choices.find(
    (c) => c.name == "Queued"
  );

  const messagesToSend = useRecords(messagesTable).filter(
    (m) => m.getCellValue("Status").name === "Queued"
  );

  async function sendMessages() {
    setCompleted(false);
    setSending(true);
    const total = messagesToSend.length;
    let i = 0;
    for (const messageToSend of messagesToSend) {
      const response = await sendMessage(messageToSend);

      if (response.status === 202) {
        messagesTable.updateRecordAsync(messageToSend.id, {
          Status: { name: "Sent" },
          "Sent Time": new Date(),
        });
      } else {
        messagesTable.updateRecordAsync(messageToSend.id, {
          Status: { name: "Errored" },
        });
      }
      i += 1;
      setProgress(i / total);
    }
    setSending(false);
    setCompleted(true);
  }

  async function goBack() {
    // Clear any non-persistent data before leaving
    setCompleted(false);
    setSending(false);
    setProgress(0);
    previousStep();
  }

  return (
    <Box>
      <h2> Step 2: Send emails </h2>
      {(sending || completed) && <ProgressBar progress={progress} />}
      {completed && <p> Successfully sent all messages </p>}
      {messagesToSend.length === 0 ? (
        <p>
          {" "}
          There are no messages with status{" "}
          <ChoiceToken choice={queuedOption} marginRight={1} />{" "}
        </p>
      ) : (
        <>
          <Box
            margin={2}
            display="flex"
            flexDirection="row"
            justifyContent="flex-start"
            alignItems="center"
          >
            <Text>
              {" "}
              The following {messagesToSend.length} messages will be sent:
            </Text>
            <Button
              marginX={2}
              variant="primary"
              onClick={sendMessages}
              disabled={sending}
            >
              Send All Messages
            </Button>
          </Box>
          <Box height="300px" border="thick" backgroundColor="lightGray1">
            <RecordCardList
              records={messagesToSend}
              fields={["Email type", "Recipient", "Delivery"].map((f) =>
                messagesTable.getFieldByName(f)
              )}
            />
          </Box>
        </>
      )}
      <Button onClick={goBack}> Go Back </Button>
    </Box>
  );
}