@airtable/blocks/ui#useWatchable JavaScript Examples

The following examples show how to use @airtable/blocks/ui#useWatchable. 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: 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 #2
Source File: settings.js    From apps-base-schema with MIT License 4 votes vote down vote up
/**
 * Reads values from GlobalConfig and calculates relevant positioning information for the nodes
 * and links.
 *
 * A node represents either a "row" in the visualization - either a table header or a field. A link
 * represents a relationship between two nodes. We persist two types of information in globalConfig:
 * (1) whether a certain link type should be shown; and (2) the x,y position for each table, where
 * position indicates the top-left corner of the table.
 *
 * Positioning calculation takes place as follows:
 * (1) Parse the schema of the base (ie, what tables exist, what fields exist on those tables,
 * and what are the relationships/links between fields & tables).
 * (2) Lookup the persisted position for each table, and check for any recently-created tables that
 * are not accounted for in these persisted settings. Assign positions for any new tables.
 * (3) Using the table & link configurations from step 1 and table coordinates from step 2,
 * calculate the paths (ie, the `d` attribute for SVG element) for the links. Because the row widths
 * & heights are constant, we can infer coordinates by adding offsets to the table coordinates.
 *
 * When dragging a table and updating positions on `mousemove`, it is inefficient to go through this
 * calculation process / rely on React state updates to propagate down to the child components.
 * Instead, we only calculate required changes and directly manipulate the DOM (@see DragWrapper).
 * The new table coordinates are persisted to globalConfig when dragging is finished, but positions
 * and paths for nodes and links are only recalculated from scratch when the base schema changes.
 * Otherwise, we just rely on the current DOM position.
 *
 * @returns {{
 *     enabledLinksByType: { ['multipleRecordLinks' | 'formula' | 'multipleLookupValues' | 'rollup' | 'count']: boolean },
 *     tableCoordsByTableId: { TableId: { x: number, y: number }},
 *     tableConfigsByTableId: { TableId: { tableNode: Node, fieldNodes: Node[] }},
 *     nodesById: { NodeId: Node },
 *     linksById: { LinkId: Link },
 *     linkPathsByLinkId: { LinkId: string },
 *     dependentLinksByNodeId: { NodeId: Link[] }
 * }}
 */
export default function useSettings() {
    const [baseSchema, setBaseSchema] = useState(() => parseSchema(base));
    const {nodesById, linksById, tableConfigsByTableId, dependentLinksByNodeId} = baseSchema;
    const globalConfig = useGlobalConfig();
    let tableCoordsByTableId;

    if (!globalConfig.get(ConfigKeys.TABLE_COORDS_BY_TABLE_ID)) {
        // First time run, determine initial table coords
        tableCoordsByTableId = getInitialTableCoords(tableConfigsByTableId);
        globalConfig.setPathsAsync([
            {
                path: [ConfigKeys.TABLE_COORDS_BY_TABLE_ID],
                value: tableCoordsByTableId,
            },
            {
                path: [ConfigKeys.ENABLED_LINKS_BY_TYPE],
                value: {
                    [FieldType.MULTIPLE_RECORD_LINKS]: true,
                    [FieldType.FORMULA]: true,
                    [FieldType.ROLLUP]: true,
                    [FieldType.COUNT]: true,
                    [FieldType.MULTIPLE_LOOKUP_VALUES]: true,
                },
            },
        ]);
    } else {
        // Non-first time run, check for any new tables missing from the old saved coords
        tableCoordsByTableId = globalConfig.get(ConfigKeys.TABLE_COORDS_BY_TABLE_ID);
        if (
            _.difference(Object.keys(tableConfigsByTableId), Object.keys(tableCoordsByTableId))
                .length > 0
        ) {
            tableCoordsByTableId = getUpdatedTableCoords(
                tableConfigsByTableId,
                tableCoordsByTableId,
            );
            if (globalConfig.hasPermissionToSet()) {
                globalConfig.setAsync(ConfigKeys.TABLE_COORDS_BY_TABLE_ID, tableCoordsByTableId);
            }
        }
    }
    const [linkPathsByLinkId, setLinkPathsByLinkId] = useState(() =>
        calculateLinkPaths(linksById, tableConfigsByTableId, tableCoordsByTableId),
    );

    // Only re-perform these potentially expensive calclulations when required, when the base
    // schema changes (ie, table added/removed/renamed, field added/removed/renamed).
    useWatchable(base, ['schema'], () => {
        const newSchema = parseSchema(base);
        const newTableCoords = getUpdatedTableCoords(
            newSchema.tableConfigsByTableId,
            tableCoordsByTableId,
        );
        const newLinkPaths = calculateLinkPaths(
            newSchema.linksById,
            newSchema.tableConfigsByTableId,
            newTableCoords,
        );

        if (globalConfig.hasPermissionToSet()) {
            globalConfig.setAsync(ConfigKeys.TABLE_COORDS_BY_TABLE_ID, newTableCoords);
        }
        setBaseSchema(newSchema);
        setLinkPathsByLinkId(newLinkPaths);
    });

    const enabledLinksByType = {
        [FieldType.MULTIPLE_RECORD_LINKS]: globalConfig.get([
            ConfigKeys.ENABLED_LINKS_BY_TYPE,
            FieldType.MULTIPLE_RECORD_LINKS,
        ]),
        [FieldType.FORMULA]: globalConfig.get([
            ConfigKeys.ENABLED_LINKS_BY_TYPE,
            FieldType.FORMULA,
        ]),
        [FieldType.ROLLUP]: globalConfig.get([ConfigKeys.ENABLED_LINKS_BY_TYPE, FieldType.ROLLUP]),
        [FieldType.MULTIPLE_LOOKUP_VALUES]: globalConfig.get([
            ConfigKeys.ENABLED_LINKS_BY_TYPE,
            FieldType.MULTIPLE_LOOKUP_VALUES,
        ]),
        [FieldType.COUNT]: globalConfig.get([ConfigKeys.ENABLED_LINKS_BY_TYPE, FieldType.COUNT]),
    };

    return {
        enabledLinksByType,
        tableCoordsByTableId,
        tableConfigsByTableId,
        nodesById,
        linksById,
        linkPathsByLinkId,
        dependentLinksByNodeId,
    };
}
Example #3
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 #4
Source File: index.js    From apps-url-preview with MIT License 4 votes vote down vote up
// Shows a preview, or a message about what the user should do to see a preview.
function RecordPreview({
    activeTable,
    selectedRecordId,
    selectedFieldId,
    setIsDialogOpen,
    setIsSettingsOpen,
}) {
    const {
        settings: {isEnforced, urlField, urlTable},
    } = useSettings();

    const table = (isEnforced && urlTable) || activeTable;

    // We use getFieldByIdIfExists because the field might be deleted.
    const selectedField = selectedFieldId ? table.getFieldByIdIfExists(selectedFieldId) : null;
    // When using a specific field for previews is enabled and that field exists,
    // use the selectedField
    const previewField = (isEnforced && urlField) || selectedField;
    // Triggers a re-render if the record changes. Preview URL cell value
    // might have changed, or record might have been deleted.
    const selectedRecord = useRecordById(table, selectedRecordId ? selectedRecordId : '', {
        fields: [previewField],
    });

    // Triggers a re-render if the user switches table or view.
    // RecordPreview may now need to render a preview, or render nothing at all.
    useWatchable(cursor, ['activeTableId', 'activeViewId']);

    // This button is re-used in two states so it's pulled out in a constant here.
    const viewSupportedURLsButton = (
        <TextButton size="small" marginTop={3} onClick={() => setIsDialogOpen(true)}>
            View supported URLs
        </TextButton>
    );

    if (
        // If there is/was a specified table enforced, but the cursor
        // is not presently in the specified table, display a message to the user.
        // Exception: selected record is from the specified table (has been opened
        // via button field or other means while cursor is on a different table.)
        isEnforced &&
        cursor.activeTableId !== table.id &&
        !(selectedRecord && selectedRecord.parentTable.id === table.id)
    ) {
        return (
            <Fragment>
                <Text paddingX={3}>Switch to the “{table.name}” table to see previews.</Text>
                <TextButton size="small" marginTop={3} onClick={() => setIsSettingsOpen(true)}>
                    Settings
                </TextButton>
            </Fragment>
        );
    } else if (
        // activeViewId is briefly null when switching views
        selectedRecord === null &&
        (cursor.activeViewId === null ||
            table.getViewById(cursor.activeViewId).type !== ViewType.GRID)
    ) {
        return <Text>Switch to a grid view to see previews</Text>;
    } else if (
        // selectedRecord will be null on app initialization, after
        // the user switches table or view, or if it was deleted.
        selectedRecord === null ||
        // The preview field may have been deleted.
        previewField === null
    ) {
        return (
            <Fragment>
                <Text>Select a cell to see a preview</Text>
                {viewSupportedURLsButton}
            </Fragment>
        );
    } else {
        // Using getCellValueAsString guarantees we get a string back. If
        // we use getCellValue, we might get back numbers, booleans, or
        // arrays depending on the field type.
        const cellValue = selectedRecord.getCellValueAsString(previewField);

        if (!cellValue) {
            return (
                <Fragment>
                    <Text>The “{previewField.name}” field is empty</Text>
                    {viewSupportedURLsButton}
                </Fragment>
            );
        } else {
            const previewUrl = getPreviewUrlForCellValue(cellValue);

            // In this case, the FIELD_NAME field of the currently selected
            // record either contains no URL, or contains a that cannot be
            // resolved to a supported preview.
            if (!previewUrl) {
                return (
                    <Fragment>
                        <Text>No preview</Text>
                        {viewSupportedURLsButton}
                    </Fragment>
                );
            } else {
                return (
                    <iframe
                        // Using `key=previewUrl` will immediately unmount the
                        // old iframe when we're switching to a new
                        // preview. Otherwise, the old iframe would be reused,
                        // and the old preview would stay onscreen while the new
                        // one was loading, which would be a confusing user
                        // experience.
                        key={previewUrl}
                        style={{flex: 'auto', width: '100%'}}
                        src={previewUrl}
                        frameBorder="0"
                        allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
                        allowFullScreen
                    />
                );
            }
        }
    }
}