view-def.ts 9.22 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*******************************************************************************
 * Copyright 2003-2018 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 * contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
 *
 * This file is part of CubicWeb.
 *
 * CubicWeb is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * CubicWeb is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

/**
22
 * The kind of location for the resource of a view
23
 */
24
25
26
export enum ViewResourceLocation {
  inline = "inline",
  remote = "remote"
27
28
29
}

/**
30
 * The base interface for the resource of a view
31
 */
32
export interface ViewResource {
33
  /**
34
   * The kind of location of a resource for a view
35
   */
36
  location: ViewResourceLocation;
37
38
39
}

/**
40
 * An inlined resource for a view
41
 */
42
43
44
45
46
47
export interface ViewResourceInline extends ViewResource {
  /**
   * The content for the resource
   */
  content: string;
}
48
49

/**
50
 * A remote resource for a view
51
 */
52
export interface ViewResourceRemote extends ViewResource {
53
  /**
54
   * The URI to the resource's content
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
   */
  uri: string;
}

/**
 * The metadata of a view
 */
export interface ViewDescriptor {
  /**
   * The unique identifier for this view
   */
  identifier: string;
  /**
   * The human readable name
   */
  name: string;
  /**
   * A longer description for the view
   */
  description: string;
  /**
   * The name of the entry point in the view definition
   */
  entrypoint: string;
  /**
80
81
82
83
84
85
86
87
88
   * The CSS resources for this view
   */
  resourceCss: ViewResource[];
  /**
   * The additional javascript resources for this view
   */
  resourceJs: ViewResource[];
  /**
   * The main javascript resource for this view
89
   */
90
  resourceMain: ViewResource;
91
92
93
94
95
96
97
98
99
100
101
102
103
}

/**
 * A repository of view descriptors
 */
export interface ViewDescriptors {
  [id: string]: ViewDescriptor;
}

/**
 * Kinds of sources for view descriptors for a registry
 */
export enum ViewRegistrySourceKind {
104
105
  inline = "inline",
  remote = "remote"
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
143
144
145
146
147
148
}

/**
 * A source of view descriptors for a registry
 */
export interface ViewRegistrySource {
  /**
   * The kind of source
   */
  kind: ViewRegistrySourceKind;
  /**
   * The name of the source
   */
  name: string;
}

/**
 * A source of view descriptors with the descriptors inlined within it
 */
export interface ViewRegistrySourceInline extends ViewRegistrySource {
  /**
   * The inlined descriptors
   */
  descriptors: ViewDescriptor[];
}

/**
 * A remote source of view descriptors
 */
export interface ViewRegistrySourceRemote extends ViewRegistrySource {
  /**
   * The uri to fetch the descriptors at
   */
  uri: string;
}

/**
 * Fetches the descriptors for a source
 * @param source The source to fetch from
 */
function fetchDescriptors(
  source: ViewRegistrySource
): Promise<ViewDescriptor[]> {
149
  if (source.kind === ViewRegistrySourceKind.inline) {
150
151
152
153
154
155
156
157
    return new Promise<ViewDescriptor[]>(
      (
        resolve: (result: ViewDescriptor[] | Promise<ViewDescriptor[]>) => void,
        reject: (reason: string) => void
      ) => {
        resolve((source as ViewRegistrySourceInline).descriptors);
      }
    );
158
  } else if (source.kind === ViewRegistrySourceKind.remote) {
159
160
161
162
163
164
165
    return new Promise<ViewDescriptor[]>(
      (
        resolve: (result: ViewDescriptor[] | Promise<ViewDescriptor[]>) => void,
        reject: (reason: string) => void
      ) => {
        let xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
166
          if (xmlHttp.readyState === 4) {
167
168
            if (xmlHttp.status < 200 || xmlHttp.status >= 300) {
              reject("HTTP error: " + xmlHttp.status);
169
              return;
170
            }
171
            if (xmlHttp.responseText.length === 0) {
172
              reject("Empty result");
173
              return;
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
            }
            resolve(JSON.parse(xmlHttp.responseText));
          }
        };
        xmlHttp.open("GET", (source as ViewRegistrySourceRemote).uri, true);
        xmlHttp.setRequestHeader("Accept", "application/json");
        xmlHttp.send();
      }
    );
  } else {
    return new Promise<ViewDescriptor[]>(
      (
        resolve: (result: ViewDescriptor[] | Promise<ViewDescriptor[]>) => void,
        reject: (reason: string) => void
      ) => {
        reject("Invalid source");
      }
    );
  }
}

/**
 * Loads all descriptors from the registered sources
 * @param sources The sources to load from
 */
function loadDescriptors(
  sources: ViewRegistrySource[]
): Promise<ViewDescriptors> {
  return new Promise<ViewDescriptors>(
    (
      resolve: (descriptors: ViewDescriptors) => void,
      reject: (reason: any) => void
    ) => {
207
208
209
      let finished = 0;
      let target = sources.length;
      let descriptors: ViewDescriptors = {};
210
      function onPartFinished() {
211
212
        finished += 1;
        if (finished >= target) resolve(descriptors);
213
      }
Laurent Wouters's avatar
Laurent Wouters committed
214
      sources.forEach((source: ViewRegistrySource) => {
215
216
217
218
219
        fetchDescriptors(source)
          .then((result: ViewDescriptor[]) => {
            result.map((descriptor: ViewDescriptor) => {
              descriptors[descriptor.identifier] = descriptor;
            });
220
            onPartFinished();
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
          })
          .catch((reason: string) => {
            console.log(
              "Failed to fetch descriptor from source " +
                source.name +
                ": " +
                reason
            );
            onPartFinished();
          });
      });
    }
  );
}

/**
 * A registry of views
 */
export class ViewRegistry {
  constructor() {
    this.sources = [];
    this.descriptors = {};
  }
  /**
   * The sources for this registry
   */
  sources: ViewRegistrySource[];
  /**
   * The registry of descriptors
   */
  descriptors: ViewDescriptors;
}

/**
 * Loads the descriptors for this registry
256
 * @param registry The current registry
257
258
259
260
261
262
263
 */
export function loadRegistry(registry: ViewRegistry): Promise<ViewRegistry> {
  return new Promise<ViewRegistry>(
    (
      resolve: (result: ViewRegistry) => void,
      reject: (reason: any) => void
    ) => {
264
      registry.descriptors = {};
265
266
267
268
269
270
271
272
      loadDescriptors(registry.sources)
        .then((descriptors: ViewDescriptors) => {
          registry.descriptors = descriptors;
          resolve(registry);
        })
        .catch((reason: any) => {
          console.log(reason);
        });
273
274
275
    }
  );
}
276

277
278
279
280
281
282
283
/**
 * Represents a cache of content for view resources
 */
export interface ViewResourceCache {
  [uri: string]: string;
}

284
285
/**
 * Gets the content of a resource
286
 * @param cache The cache to use
287
288
 * @param resource The resource
 */
289
290
export function getResourceContent(
  cache: ViewResourceCache,
291
292
293
294
  resource: ViewResource
): Promise<string> {
  return new Promise<string>(
    (resolve: (result: string) => void, reject: (reason: any) => void) => {
295
      if (resource.location === ViewResourceLocation.inline) {
296
        resolve((resource as ViewResourceInline).content);
297
      } else if (resource.location === ViewResourceLocation.remote) {
298
        let uri = (resource as ViewResourceRemote).uri;
299
300
        if (cache.hasOwnProperty(uri)) {
          resolve(cache[uri]);
301
302
303
304
          return;
        }
        let xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
305
306
          if (xmlHttp.readyState === 4) {
            if (xmlHttp.status === 0 && uri.startsWith("http://")) {
307
308
309
310
311
312
313
314
315
316
317
318
319
              // try https
              getResourceContent(cache, {
                location: ViewResourceLocation.remote,
                uri: "https:" + uri.substring("http:".length)
              } as ViewResourceRemote)
                .then((result: string) => {
                  resolve(result);
                })
                .catch((reason: any) => {
                  reject("Failed to fetch: " + reason);
                });
              return;
            }
320
321
322
323
            if (xmlHttp.status < 200 || xmlHttp.status >= 300) {
              reject("HTTP error: " + xmlHttp.status);
              return;
            }
324
            cache[uri] = xmlHttp.responseText;
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
            resolve(xmlHttp.responseText);
          }
        };
        xmlHttp.open("GET", uri, true);
        xmlHttp.setRequestHeader(
          "Accept",
          "text/plain, application/javascript, text/css"
        );
        xmlHttp.send();
      } else {
        reject(
          "Cannot fetch content of resource with location: " + resource.location
        );
      }
    }
  );
}
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358

/**
 * An entity able to resolve the content of a resource
 */
export type ViewResourceContentResolver = (
  resource: ViewResource
) => Promise<string>;

/**
 * Gets a resolver for the content of resources that uses the specified cache
 * @param cache The cache to use
 */
export function newCacheResolver(
  cache: ViewResourceCache
): ViewResourceContentResolver {
  return (resource: ViewResource) => getResourceContent(cache, resource);
}