browser.ts 11.6 KB
Newer Older
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/*******************************************************************************
 * 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/>.
 ******************************************************************************/

import "chrome";
import * as $rdf from "rdflib";
import { application, definition, implementation } from "@logilab/libview";
import * as LANGUAGES from "../common/data.iso639.json";
import {
  ResourceData,
  fetchSource,
  selectDataSources,
  RawContent,
  selectPrimaryTopic,
  ObservableContent,
  observeContent,
  ResourceUserCommand,
  DataSource
} from "../common/data";
import {
  getResourceContent,
  getViewRegistry,
  fetchObservableAt
} from "../common/messages";
require("./view-defaults-impl");

/**
 * Gets the user language selected by the browser
 */
function getBrowserLanguage(): application.Language {
  let lang = navigator.language;
  let i = lang.indexOf("-");
  if (i > 0) lang = lang.substring(0, i);
  let result = LANGUAGES.find(
    (language: application.Language) =>
      language.iso639_1 == lang || language.iso639_2 == lang
  );
  if (result != null && result != undefined) return result;
  return application.NO_LANGUAGE;
}

/**
 * The current language of the browser
 */
const BROWSER_LANGUAGE = getBrowserLanguage();

/**
 * Event handler for an LD browser
 */
export interface LDBrowserEventHandler {
  /**
   * When the browser is currently loading data
   * @param description The current loading state
   */
  onLoad(description: string): void;

  /**
   * When the browser must render something
   * @param registry The view registry
   * @param rendering The rendering for a view
   */
  onContent(
    registry: definition.ViewRegistry,
    rendering: application.ViewRendering
  ): void;

  /**
   * When an error occurred
   * @param description The error's description
   */
  onError(description: string): void;
}

/**
 * The interface for an LD browser
 */
export interface LDBrowser {
  /**
   * When an URI has been reached
   * @param uri The URI
   */
  onReachedUri(uri: string): Promise<void>;
  /**
   * Navigates the browser to an URI
   * @param uri The URI to navigate to
   */
  navigateTo(uri: string): void;
  /**
   * Refreshes the current page
   */
  refresh(): void;
  /**
   * Gets the current resource
   */
  getCurrentResource(): ResourceData;
  /**
   * Sets the new user command for the current resouce
   * @param command The new user command
   */
  setCommand(command: ResourceUserCommand): void;
}

/**
 * Creates a new LD browser
 * @param handler The handler for the events
 */
export function newBrowser(handler: LDBrowserEventHandler): LDBrowser {
  return new LDBrowserImpl(handler);
}

/**
 * The data of an LD browser
 */
class LDBrowserImpl implements LDBrowser {
  constructor(handler: LDBrowserEventHandler) {
    this.handler = handler;
    this.renderer = implementation.newRenderer(getResourceContent);
    this.currentResource = null;
    this.cacheResources = {};
    this.cacheStores = {};
    this.onRequestNavigateTo = this.onRequestNavigateTo.bind(this);
    this.onSelectAsPrimaryTopic = this.onSelectAsPrimaryTopic.bind(this);
  }

  /**
   * The handler for the events
   */
  private handler: LDBrowserEventHandler;
  /**
   * The view renderer for the browser
   */
  private renderer: implementation.CachingViewRenderer;
  /**
   * The history of resources
   */
  private currentResource: ResourceData;
  /**
   * The data for each known resource
   */
  private cacheResources: { [url: string]: ResourceData };
  /**
   * The cache of loaded RDF data
   */
  private cacheStores: { [url: string]: $rdf.Formula };

  /**
   * Resolves the data about a resource
   * @param uri The resource's URI
   */
  private resolveResourceData(uri: string): Promise<ResourceData> {
    let self = this;
    return new Promise<ResourceData>(
      (
        resolve: (resource: ResourceData) => void,
        reject: (reason: any) => void
      ) => {
        let resource = self.cacheResources[uri];
        if (resource != null && resource != undefined) return resolve(resource);
        fetchObservableAt(uri)
          .then((observable: ObservableContent) => {
            let observations = observeContent(observable);
            let resource: ResourceData = {
              observations: observations,
180
181
              command: new ResourceUserCommand(),
              supplements: []
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
            };
            self.cacheResources[uri] = resource;
            resolve(resource);
          })
          .catch((reason: any) => {
            reject(reason);
          });
      }
    );
  }

  /**
   * Gets the RDF store for a resource
   * Successively try the sources until one succeed
   * @param resource The resource
   */
  private resolveRdfStore(resource: ResourceData): Promise<$rdf.Formula> {
    let self = this;
    return new Promise(
      (
        resolve: (store: $rdf.Formula) => void,
        reject: (reason: any) => void
      ) => {
        let cached = self.cacheStores[resource.observations.url];
        if (cached != null && cached != undefined) return resolve(cached);
        let sources = selectDataSources(resource);
        let index = 0;
        let reasons: any[] = [];
        let tryNextSource = function() {
          if (index >= sources.length) return reject(reasons.toString());
          self
            .loadRdfStoreFrom(sources[index])
            .then((store: $rdf.Formula) => {
              self.cacheStores[resource.observations.url] = store;
              resolve(store);
            })
            .catch((reason: any) => {
              index++;
              reasons.push(reason);
              tryNextSource();
            });
        };
        tryNextSource();
      }
    );
  }

  /**
   * Loads a RDF store from a data source
   * @param resource The resource
   */
  private loadRdfStoreFrom(source: DataSource): Promise<$rdf.Formula> {
    return new Promise(
      (
        resolve: (store: $rdf.Formula) => void,
        reject: (reason: any) => void
      ) => {
        fetchSource(source)
          .then((value: RawContent) => {
            let store = $rdf.graph();
            try {
              $rdf.parse(
                value.content,
                store,
                source.url,
                source.contentType,
                undefined
              );
              resolve(store);
            } catch (err) {
              reject(err);
            }
          })
          .catch(reason => {
            reject(reason);
          });
      }
    );
  }

  /**
   * Creates a new rendering context
   * @param resource The resource
   * @param store The RDF store
   */
  private newRenderingContext(
    resource: ResourceData,
    store: $rdf.Formula
  ): application.RenderingContext {
    let topic = selectPrimaryTopic(resource);
    let context: application.RenderingContext = {
      event: {
        onRequestNavigateTo: this.onRequestNavigateTo,
        onSelectAsPrimaryTopic: this.onSelectAsPrimaryTopic
      },
      root: topic,
      store: store,
      options: {},
      browserLanguage: BROWSER_LANGUAGE
    };
    context.options[topic] = {
      view: resource.command.isAutomatic ? null : resource.command.selectedView,
      language: resource.command.isAutomatic
        ? null
        : resource.command.selectedLanguage
    };
    return context;
  }

  /**
   * Executes the user request of navigating to a new resource
   * @param uri The URI of the resource
   */
  private onRequestNavigateTo(uri: string) {
    this.navigateTo(uri);
  }

  /**
   * Reacts to a user selecting a resource as the primary topic
   * @param uri The uri of the resource
   */
  private onSelectAsPrimaryTopic(uri: string): void {
    if (this.currentResource == null) return;
    this.currentResource.command.isAutomatic = false;
    this.currentResource.command.selectedTopic = uri;
    this.refresh();
  }

310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
  /**
   * When supplementary resources has been suggested for the current one
   * @param resource The current resource
   * @param uris The URIs of the suggested supplementary ones
   */
  private async onSuggestedResources(
    resource: ResourceData,
    uris: string[]
  ): Promise<any> {
    uris = uris.filter((uri: string) => resource.supplements.indexOf(uri) < 0);
    if (uris.length == 0) return;
    let parentStore = await this.resolveRdfStore(resource);
    let self = this;
    let count = 0;
    let onFinishedPart = function() {
      count++;
      if (count >= uris.length) self.refresh();
    };
    uris.forEach(async (uri: string) => {
      let childResource = await self.resolveResourceData(uri);
      let childStore = await self.resolveRdfStore(childResource);
331
332
333
334
335
336
337
338
339
340
341
342
343
344
      childStore.statements.forEach((statement: $rdf.Statement) => {
        parentStore.add(
          statement.subject.termType == "NamedNode"
            ? parentStore.sym(statement.subject.value)
            : statement.subject,
          statement.predicate.termType == "NamedNode"
            ? parentStore.sym(statement.predicate.value)
            : statement.predicate,
          statement.object.termType == "NamedNode"
            ? parentStore.sym(statement.object.value)
            : statement.object,
          statement.graph
        );
      });
345
346
347
348
349
      resource.supplements.push(uri);
      onFinishedPart();
    });
  }

350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
  /**
   * When an URI has been reached
   * @param uri The URI
   */
  public async onReachedUri(uri: string): Promise<void> {
    this.handler.onLoad("Loading data");
    let resource = await this.resolveResourceData(uri);
    this.currentResource = resource;
    let store = await this.resolveRdfStore(resource);
    let context = this.newRenderingContext(resource, store);
    this.handler.onLoad("Loading view registry");
    let registry = await getViewRegistry();
    this.handler.onLoad("Fetching views");
    let renderer = await this.renderer.refresh(registry);
    this.handler.onLoad("Rendering");
    let rendering = renderer.render(context, context.root);
    if (rendering != null) {
      this.handler.onContent(registry, rendering);
368
      this.onSuggestedResources(resource, rendering.suggestedResources);
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
    } else {
      this.handler.onError("Rendering failed!");
    }
  }

  /**
   * Navigates the browser to an URI
   * @param uri The URI to navigate to
   */
  public navigateTo(uri: string): void {
    history.pushState(
      { uri: uri },
      uri,
      chrome.extension.getURL("ldbrowser/index.html?target=") +
        encodeURIComponent(uri)
    );
    this.onReachedUri(uri);
  }

  /**
   * Refreshes the current page
   */
  public refresh(): void {
    if (this.currentResource == null) return;
    this.onReachedUri(this.currentResource.observations.url);
  }

  /**
   * Gets the current resource
   */
  public getCurrentResource(): ResourceData {
    return this.currentResource;
  }

  /**
   * Sets the new user command for the current resouce
   * @param command The new user command
   */
  public setCommand(command: ResourceUserCommand): void {
    if (this.currentResource == null) return;
    this.currentResource.command = command;
  }
}