File size: 7,212 Bytes
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/**
 * Data Application resolution for the Table grid: the addressed Application read, its template
 * surface and the paged read a Catalog or Routing App supplies. CustomerGrid reads one value.
 */
import { useCallback, useEffect, useRef, useState } from "react";
import { API_V1, CREDENTIALS } from "../apiContract";
import { readDataPath } from "./dataPath";
import type { DataPath } from "./dataPath";
import type { GridHostCapabilities } from "./seam";
import type { ApplicationType, Field, Row } from "./types";
import { applicationTemplateSurface } from "./viewModes";

export type SavedApplication = {
  id: string;
  type: ApplicationType;
  name: string;
  revision?: number;
  config?: { schemaVersion?: number; display?: Record<string, unknown> };
  starred?: boolean;
  semanticRoleBindings?: Record<string, unknown>;
  capabilities?: Record<string, boolean>;
  compatibleDatabases?: string[];
  openTarget?: { database?: string };
  templateKind?: unknown;
  fieldMap?: unknown;
};

export interface ApplicationHostInput {
  /** A foreground grid: neither embedded nor a Query preview. */
  foreground: boolean;
  dataPath: DataPath | undefined;
  /** The database the registry is asked about. */
  applicationDatabase: string;
  /** The View's referenced Application, and whether it matches the View's reference. */
  resolvedApplication: SavedApplication | null;
  resolvedApplicationMatches: boolean;
  /** The View's Application reference key, "" without one. */
  applicationRefKey: string;
}

export interface ApplicationHost {
  /** `<database>::<application>` on an addressed surface, "" otherwise. */
  key: string;
  /** The key whose registry read settled. */
  settledKey: string;
  /** The addressed Application. Null before the read settles, or when missing or incompatible. */
  definition: SavedApplication | null;
  catalog: boolean;
  routing: boolean;
  /** A Catalog or Routing App: its rows come from its own paged read. */
  paged: boolean;
  /** An App with its own screen. It reads its own routes, never the source rows. */
  templateView: boolean;
  /** The ordinary row reader may run. */
  rowsEnabled: boolean;
  /** The paged App's current read. Null until it lands for this App. */
  pagedRead: { key: string; fields: Field[]; rows: Row[] } | null;
  acceptPagedRead: (fields: Field[], rows: Row[]) => void;
  /** Replace the addressed definition with a newer copy of the same Application. */
  adopt: (application: SavedApplication) => void;
  /** What the grid gives up to this host. An addressed Application takes all three. */
  capabilities: GridHostCapabilities;
}

export function useApplicationHost({
  foreground, dataPath, applicationDatabase, resolvedApplication, resolvedApplicationMatches,
  applicationRefKey,
}: ApplicationHostInput): ApplicationHost {
  // An addressed Application surface: `dataPath.application` on a foreground grid.
  const isApplicationSurface = foreground && !!dataPath?.application;
  const addressedApplicationKey = isApplicationSurface && dataPath?.database
    ? `${dataPath.database}::${dataPath.application}` : "";
  const [addressedApplication, setAddressedApplication] = useState<{
    key: string; application: SavedApplication | null;
  }>({ key: "", application: null });
  const applicationOpenSeq = useRef(0);
  useEffect(() => {
    if (!addressedApplicationKey || !dataPath?.database) return;
    const mine = ++applicationOpenSeq.current;
    const controller = new AbortController();
    const requestedDatabase = dataPath.database;
    const requestedId = dataPath.application;
    void fetch(`${API_V1}/applications?database=${encodeURIComponent(applicationDatabase)}`, {
      credentials: CREDENTIALS, signal: controller.signal,
    }).then(async (response) => response.ok ? response.json() : null).then((body) => {
      if (controller.signal.aborted || mine !== applicationOpenSeq.current) return;
      const livePath = readDataPath();
      if (livePath?.database !== requestedDatabase || livePath.application !== requestedId) return;
      const listed: SavedApplication[] = Array.isArray(body?.applications) ? body.applications : [];
      const application = listed.find((candidate) => candidate.id === requestedId) ?? null;
      const compatible = application?.openTarget?.database === requestedDatabase ||
        application?.compatibleDatabases?.includes(requestedDatabase) === true;
      setAddressedApplication({ key: addressedApplicationKey, application: compatible ? application : null });
    }).catch(() => {
      if (controller.signal.aborted || mine !== applicationOpenSeq.current) return;
      const livePath = readDataPath();
      if (livePath?.database !== requestedDatabase || livePath.application !== requestedId) return;
      setAddressedApplication({ key: addressedApplicationKey, application: null });
    });
    return () => controller.abort();
  }, [addressedApplicationKey, applicationDatabase, dataPath?.database, dataPath?.application]);
  const addressedDefinition = addressedApplication.key === addressedApplicationKey
    ? addressedApplication.application : null;
  const isCatalogApplication = applicationTemplateSurface(addressedDefinition) === "catalog" ||
    (resolvedApplicationMatches && applicationTemplateSurface(resolvedApplication) === "catalog");
  const isRoutingApplication = applicationTemplateSurface(addressedDefinition) === "route" ||
    (resolvedApplicationMatches && applicationTemplateSurface(resolvedApplication) === "route");
  const isPagedOdooApplication = isCatalogApplication || isRoutingApplication;
  // C2: an App with its own screen (Competitor watch and every C1 view) reads its own routes,
  // never the source database rows.
  const isTemplateViewApplication = applicationTemplateSurface(addressedDefinition) === "app";
  // Resolve the registry before allowing an App to use an ordinary row reader.
  const legacyRowsEnabled = !isPagedOdooApplication && (!isApplicationSurface || !!addressedDefinition) &&
    !isTemplateViewApplication;
  const catalogReadKey = addressedApplicationKey || applicationRefKey;
  const [catalogRead, setCatalogRead] = useState<{ key: string; fields: Field[]; rows: Row[] }>(
    { key: "", fields: [], rows: [] });
  const catalogData = isPagedOdooApplication && catalogRead.key === catalogReadKey ? catalogRead : null;
  const acceptPagedRead = useCallback((fields: Field[], rows: Row[]) => {
    setCatalogRead({ key: catalogReadKey, fields, rows });
  }, [catalogReadKey]);
  const adopt = useCallback((application: SavedApplication) => {
    setAddressedApplication((prev) => prev.key && prev.application?.id === application.id
      ? { key: prev.key, application } : prev);
  }, []);
  return {
    key: addressedApplicationKey,
    settledKey: addressedApplication.key,
    definition: addressedDefinition,
    catalog: isCatalogApplication,
    routing: isRoutingApplication,
    paged: isPagedOdooApplication,
    templateView: isTemplateViewApplication,
    rowsEnabled: legacyRowsEnabled,
    pagedRead: catalogData,
    acceptPagedRead,
    adopt,
    capabilities: { ownsLayout: isApplicationSurface, hidesViews: isApplicationSurface,
      ownsDisplay: isApplicationSurface },
  };
}