Line data Source code
1 : import * as React from 'react';
2 : import * as dashql from '@ankoh/dashql-core';
3 :
4 : import type { ConnectionState } from './connection_state.js';
5 : import { useConnectionAllocator, useConnectionRegistryStore, type ConnectionAllocator } from './connection_registry.js';
6 : import { createDefaultHyperWasmConnectionState } from './connection_params.js';
7 : import { isHyperWasmConnection } from './connection_label.js';
8 : import { getHyperLinkTabState } from './hyper/hyper_link.js';
9 :
10 : /// The connection to the embedded Hyper of the app, if one is known
11 1 : export function findEmbeddedConnection(connections: Iterable<ConnectionState>): ConnectionState | null {
12 1 : for (const connection of connections) {
13 1 : if (isHyperWasmConnection(connection)) return connection;
14 : }
15 1 : return null;
16 1 : }
17 :
18 : /// The connection to the embedded Hyper, allocated when none is known.
19 : /// The embedded engine is a single database, the app holds a single connection to it.
20 1 : export function embeddedConnection(connections: Iterable<ConnectionState>, allocate: ConnectionAllocator, dql: dashql.DashQL): ConnectionState {
21 1 : return findEmbeddedConnection(connections) ?? allocate({ ...createDefaultHyperWasmConnectionState(dql), active: true });
22 1 : }
23 :
24 : /// The connection that new sessions start on, the connection of the latest Hyper link of the tab or the embedded Hyper
25 1 : export function newSessionConnection(connections: Map<string, ConnectionState>, allocate: ConnectionAllocator, dql: dashql.DashQL, linkConnectionId: string | null = getHyperLinkTabState().current): ConnectionState {
26 1 : const linked = linkConnectionId == null ? null : connections.get(linkConnectionId);
27 1 : return linked ?? embeddedConnection(connections.values(), allocate, dql);
28 1 : }
29 :
30 : /// Resolve the connection that new sessions start on, see `newSessionConnection`
31 1 : export function useNewSessionConnection(): (dql: dashql.DashQL) => ConnectionState {
32 1 : const registryStore = useConnectionRegistryStore();
33 1 : const allocate = useConnectionAllocator();
34 1 : return React.useCallback(
35 0 : (dql: dashql.DashQL) => newSessionConnection(registryStore.current.connections, allocate, dql),
36 1 : [allocate, registryStore],
37 1 : );
38 1 : }
39 :
40 : /// Resolve the connection to the embedded Hyper, see `embeddedConnection`
41 1 : export function useEmbeddedConnection(): (dql: dashql.DashQL) => ConnectionState {
42 1 : const registryStore = useConnectionRegistryStore();
43 1 : const allocate = useConnectionAllocator();
44 1 : return React.useCallback(
45 0 : (dql: dashql.DashQL) => embeddedConnection(registryStore.current.connections.values(), allocate, dql),
46 1 : [allocate, registryStore],
47 1 : );
48 1 : }
|