CritasWang commented on code in PR #134: URL: https://github.com/apache/iotdb-extras/pull/134#discussion_r4236078515
########## connectors/grafana-plugin/src/componments/TablePicker.tsx: ########## @@ -0,0 +1,176 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +import React, { useEffect, useState } from 'react'; +import { SelectableValue } from '@grafana/data'; +import { Button, Select } from '@grafana/ui'; +import { DataSource } from '../datasource'; +import { starterTableQuery } from '../tableQuery'; +import { TableColumn } from '../types'; +import { QueryInlineField } from './Form'; + +interface Props { + datasource: DataSource; + database: string; + table: string; + onDatabaseChange: (database: string) => void; + onTableChange: (table: string) => void; + onSqlChange: (sql: string) => void; +} + +interface Loaded<T> { + value?: T; + loading: boolean; + error?: string; +} + +const categories = ['TAG', 'FIELD', 'ATTRIBUTE']; + +function toOptions(names: string[] | undefined): Array<SelectableValue<string>> { + return (names ?? []).map((name) => ({ label: name, value: name })); +} + +function toValue(name: string): SelectableValue<string> | null { + return name ? { label: name, value: name } : null; +} + +function errorMessage(err: unknown): string { + const e = err as { data?: { message?: string }; message?: string }; + return e?.data?.message ?? e?.message ?? String(err); +} + +// useLoaded runs one metadata lookup whenever its key changes. State is only +// written when a lookup settles, and a result is only used while its key is +// current. A failed lookup keeps its message; the pickers still accept a typed +// name, so the editor stays usable when metadata cannot be read. +function useLoaded<T>(key: string, load: (() => Promise<T>) | undefined): Loaded<T> { + const [result, setResult] = useState<{ key: string; value?: T; error?: string }>(); + useEffect(() => { + if (!load) { + return; + } + let cancelled = false; + load().then( + (value) => { + if (!cancelled) { + setResult({ key, value }); + } + }, + (err) => { + if (!cancelled) { + setResult({ key, error: errorMessage(err) }); + } + } + ); + return () => { + cancelled = true; + }; + // The key identifies the lookup; `load` is a fresh closure on every render. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + if (!load) { + return { loading: false }; + } + if (result?.key !== key) { + return { loading: true }; + } + return { value: result.value, error: result.error, loading: false }; +} + +// TablePicker lists the databases, tables and columns of the connected server +// for the table-model editor, and can fill in a starter query for the chosen +// table. +export function TablePicker({ datasource, database, table, onDatabaseChange, onTableChange, onSqlChange }: Props) { + const databases = useLoaded('databases', () => datasource.getTableDatabases()); + const tables = useLoaded(`tables|${database}`, database ? () => datasource.getTableTables(database) : undefined); + const columns = useLoaded<TableColumn[]>( + `columns|${database}|${table}`, + database && table ? () => datasource.getTableColumns(database, table) : undefined + ); + const error = databases.error ?? tables.error ?? columns.error; + + return ( + <> + <div className="gf-form"> + <QueryInlineField label={'DATABASE'}> + {/* Select rather than Combobox: with Combobox, picking information_schema + crashed Explore on Grafana 12.3 with React error 185 raised from the + popover's floating-ui reference; Select does not. */} + <Select + inputId="iotdb-table-database" + width={30} + options={toOptions(databases.value)} + value={toValue(database)} Review Comment: Thanks, the TABLE picker keeps its value now. The DATABASE picker still loses it, though, because of the refresh-on-open in the same commit. Opening the menu re-runs SHOW DATABASES. The response is a new array, so `useMemo` builds new option objects, and react-select recomputes the focused option by identity (`getNextFocusedOption` in `getDerivedStateFromProps`). It doesn't find the old one and moves focus to the first option. So opening DATABASE and pressing Tab or Enter after the refresh comes back still switches to the first database (`information_schema`) and clears the table. The e2e test presses Tab only on TABLE, which doesn't refresh on open. <details> <summary>A Jest test that reproduces it on 3694fe8 (the same steps pass when the lookup returns the same array every time)</summary> ```tsx it('keeps the database on Tab after the refresh-on-open settles', async () => { const ds = { resolveTemplate: (value: string) => value, // Like a real lookup, every response is a new array. getTableDatabases: jest.fn(() => Promise.resolve(['information_schema', 'db1', 'db2'])), getTableTables: jest.fn().mockResolvedValue([]), getTableColumns: jest.fn().mockResolvedValue([]), }; const onDatabaseChange = jest.fn(); render( <TablePicker datasource={ds as unknown as DataSource} refId="A" database="db2" table="" onDatabaseChange={onDatabaseChange} onTableChange={jest.fn()} onSqlChange={jest.fn()} /> ); await waitFor(() => expect(ds.getTableDatabases).toHaveBeenCalledTimes(1)); await act(async () => {}); const input = document.getElementById('iotdb-table-database-A') as HTMLInputElement; await act(async () => { fireEvent.focus(input); fireEvent.keyDown(input, { key: 'ArrowDown' }); }); await waitFor(() => expect(ds.getTableDatabases).toHaveBeenCalledTimes(2)); await act(async () => {}); await act(async () => { fireEvent.keyDown(input, { key: 'Tab' }); }); expect(onDatabaseChange).not.toHaveBeenCalledWith('information_schema'); }); ``` </details> Handing out one option object per name keeps the focused option across refreshes. With the change below, that test passes, and so do the existing 36 tests, `tsc` and `eslint` (only the two `Select` deprecation warnings remain). <details> <summary>Suggested change to TablePicker.tsx</summary> ```diff -import React, { useEffect, useMemo, useRef, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; @@ -function pickerOptions(names: string[] | undefined, current: string): Array<SelectableValue<string>> { - const options = (names ?? []).map((name) => ({ label: name, value: name })); - return current && !options.some((o) => o.value === current) - ? [...options, { label: current, value: current }] - : options; +function pickerOptions( + names: string[] | undefined, + current: string, + optionFor: (name: string) => SelectableValue<string> +): Array<SelectableValue<string>> { + const options = (names ?? []).map(optionFor); + return current && !options.some((o) => o.value === current) ? [...options, optionFor(current)] : options; } +// useOptionCache hands out one option object per name for the picker's +// lifetime, so a refreshed list still contains the option that has focus. +function useOptionCache(): (name: string) => SelectableValue<string> { + const cache = useRef(new Map<string, SelectableValue<string>>()); + return useCallback((name: string) => { + let option = cache.current.get(name); + if (!option) { + option = { label: name, value: name }; + cache.current.set(name, option); + } + return option; + }, []); +} @@ - const databaseOptions = useMemo(() => pickerOptions(databases.value, database), [databases.value, database]); - const tableOptions = useMemo(() => pickerOptions(tables.value, table), [tables.value, table]); + const databaseOption = useOptionCache(); + const tableOption = useOptionCache(); + const databaseOptions = useMemo( + () => pickerOptions(databases.value, database, databaseOption), + [databases.value, database, databaseOption] + ); + const tableOptions = useMemo(() => pickerOptions(tables.value, table, tableOption), [tables.value, table, tableOption]); ``` </details> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
