view-impl.ts 13.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*******************************************************************************
 * 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/>.
 ******************************************************************************/

21
import * as $rdf from 'rdflib';
22
import {
23
24
25
26
27
28
29
    ViewRenderer,
    RenderingResult,
    RenderingContext,
    Language,
    Resource,
    RenderingEvaluation,
} from './application';
30
import {
31
32
33
34
35
    ViewDescriptor,
    ViewRegistry,
    ViewResourceContentResolver,
    ViewDescriptors,
} from './view-def';
36

37
38
39
40
41
/**
 * Priority for a view that is not appropriate (must not be selected)
 */
export const VIEW_PRIORITY_INAPPROPRIATE = -1;

42
43
44
45
/**
 * The rendering of a specific view implementation
 */
export interface ViewRendering {
46
47
48
49
50
51
52
53
    /**
     * The DOM elements representing the rendering
     */
    dom: Element;
    /**
     * The URI of resources that could be of interest to the view that produced this rendering
     */
    suggestedResources?: Resource[];
54
55
}

56
57
58
59
60
61
62
63
64
65
66
67
68
69
export type DataFetcher = {
    /**
     * The fetchDataFromURI is the method to fetch data for a dedicated URI
     */
    fetchDataFromURI: (
        /**
         * The uri for which we want fetch data for
         */
        uri: string,
        /**
         * The respFormat object is a way to configure how to format data when fetched.
         * This allow to define how to result will be formated to avoid manipulate triples.
         * The keys in the respFormat will be used for the object returned. The values are
         * the predicate to use to discover a specific relation. The result object will
70
         * have the string representations for all the objects of the specified predicate.
71
72
73
74
75
76
77
         * For exemple :
         * respFormat(
         *    "http://fr.dbpedia.org/resource/Victor_Hugo", {
         *      label: "http://www.w3.org/2000/01/rdf-schema#label",
         *      sameAs: "http://www.w3.org/2002/07/owl#sameAs",
         *    });
         * returns a promise for the result :
78
79
80
81
82
83
84
85
86
87
88
89
         * {label: ["Victor Hugo"], sameAs: ["http://rdf.freebase.com/ns/m.01vh096"]}
         * Note that the results contains only one result because we assumed for this
         * example that dbpedia:Victor_Hugo contains only one label and one sameAs.
         * Actually it contains several labels and several sameAs. In that case the
         * result would be :
         * {label: ["Victor Hugo", "Виктор Юго", "ヴィクトル・ユーゴー", ...],
         *  sameAs: [
         *      "http://rdf.freebase.com/ns/m.01vh096",
         *      "http://www.viaf.org/viaf/9847974",
         *      ...
         *  ]
         * }
90
91
         */
        respFormat?: {[key: string]: string}
92
    ) => Promise<{[key: string]: string[]}>;
93
};
94

95
96
97
98
/**
 * The implementation of a view
 */
export interface ViewImplementation {
99
100
101
102
    /**
     * The descriptor for ths implementation
     */
    descriptor: ViewDescriptor;
103

104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    /**
     * Gets the view's priority
     * - 0 to Number.MAX_SAFE_INTEGER for valid view with increasing priority
     * - -1 for inappropriate views (must not be selected)
     * @param store The RDF store holding the data to be rendered
     * @param target The target resource to be rendered
     */
    priorityFor(store: $rdf.Formula, target: Resource): number;
    /**
     * Renders a resource belonging to an RDF store
     * @param renderer The parent renderer
     * @param context The current rendering context
     * @param target The target resource for this view
     */
    render(
        renderer: ViewRenderer,
        context: RenderingContext,
        target: Resource
    ): ViewRendering;
123

124
    simpleRender?: (
125
126
127
128
129
130
131
        /**
         * The node id in which the view must be rendered
         */
        nodeId: string,
        /**
         * The triples in which the target is subject or object
         */
132
        context: $rdf.Formula,
133
134
135
        /**
         * The target URI. The target is the element we want to show with the view
         */
136
        target: string,
137
138
139
140
        /**
         * The (optional) data fetcher is an utility to ease fetching data for a specific URI
         */
        dataFetcher?: DataFetcher
141
    ) => void;
142
143
144
145
146
147
}

/**
 * A repository of view implementations
 */
export interface ViewImplementations {
148
    [id: string]: ViewImplementation;
149
150
151
152
153
154
155
156
157
158
159
160
}

/**
 * The global reposistory of embedded view implementations
 */
export const IMPL_EMBEDDED: ViewImplementations = {};

/**
 * Registers an embedded view implementation
 * @param implementation A view implementation
 */
export function registerImplementation(implementation: ViewImplementation) {
161
    IMPL_EMBEDDED[implementation.descriptor.identifier] = implementation;
162
163
164
165
166
}

/**
 * Fetches the implementation corresponding to a descriptor
 * @param descriptor The descriptor
167
 * @param resolver The content resolver to use
168
169
 */
function fetchImplementation(
170
171
    descriptor: ViewDescriptor,
    resolver: ViewResourceContentResolver
172
): Promise<ViewImplementation> {
173
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
207
208
209
210
211
212
213
214
215
216
    return new Promise(
        (
            resolve: (impl: ViewImplementation) => any,
            reject: (reason: string) => void
        ) => {
            resolver(descriptor.resourceMain)
                .then((content: string) => {
                    // tslint:disable-next-line:no-unused-variable
                    let EMBEDDED = IMPL_EMBEDDED;
                    try {
                        let result = eval(content);
                        if (result === null || result === undefined) {
                            reject(
                                'Failed to load definition of ' +
                                    descriptor.name +
                                    ': Cannot find entrypoint'
                            );
                            return;
                        }
                        if (descriptor.entrypoint.length > 0) {
                            result = result[descriptor.entrypoint];
                        }
                        if (result === null || result === undefined) {
                            reject(
                                'Failed to load definition of ' +
                                    descriptor.name +
                                    ': Cannot find entrypoint'
                            );
                        } else {
                            resolve(result);
                        }
                    } catch (e) {
                        reject(e);
                    }
                })
                .catch((reason: string) => {
                    reject(
                        'Failed to fetch definition of ' +
                            descriptor.name +
                            ': Cannot find entrypoint'
                    );
                });
        }
    );
217
218
219
}

/**
220
 * Evaluates all view implementation against an RDF datastore and a resource in it
221
222
223
224
 * @param implementations The view implementations to use
 * @param store The RDF store holding the data to be rendered
 * @param target The target RDF resource to render
 */
225
function evaluateViewsFor(
226
227
228
    implementations: ViewImplementations,
    store: $rdf.Formula,
    target: Resource
229
): RenderingEvaluation[] {
230
231
232
233
234
235
236
237
238
239
240
    return Object.keys(implementations)
        .map((id: string) => {
            return {
                viewId: id,
                priority: implementations[id].priorityFor(store, target),
            };
        })
        .sort(
            (x: RenderingEvaluation, y: RenderingEvaluation) =>
                y.priority - x.priority
        );
241
242
}

243
244
245
246
/**
 * A view renderer that caches the view implementations
 */
export interface CachingViewRenderer extends ViewRenderer {
247
248
249
250
251
    /**
     * Refreshes this view renderer
     * @param registry The current view registry
     */
    refresh(registry: ViewRegistry): Promise<CachingViewRenderer>;
252
253
}

254
255
256
/**
 * A renderer for an application
 */
257
class ViewRendererImpl implements CachingViewRenderer {
258
259
260
261
262
263
264
265
266
    /**
     * Initializes a renderer
     * @param resolver The content resolver to use
     */
    constructor(resolver: ViewResourceContentResolver) {
        this.descriptors = {};
        this.implementations = {};
        this.resolver = resolver;
    }
267

268
269
270
271
272
273
274
275
276
277
278
279
    /**
     * The registry of descriptors
     */
    descriptors: ViewDescriptors;
    /**
     * The view implementations
     */
    implementations: ViewImplementations;
    /**
     * The content resolver to use
     */
    resolver: ViewResourceContentResolver;
280

281
282
283
284
285
286
287
288
289
290
291
292
293
    /**
     * Selects the language to use for a target resource
     * @param context The current rendering context
     * @param target The target resource for this view
     */
    getLanguagesFor(context: RenderingContext, target: Resource): Language[] {
        let options = context.options[target.uri];
        let result = [];
        if (options && options.language) {
            result.push(options.language);
        }
        result.push(context.browserLanguage);
        return result;
294
    }
Laurent Wouters's avatar
Laurent Wouters committed
295

296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    /**
     * Renders a resource belonging to an RDF store
     * @param context The context for the rendering
     * @param target The target resource for this view
     */
    render(context: RenderingContext, target: Resource): RenderingResult {
        let view: ViewImplementation | null = null;
        let evaluations: RenderingEvaluation[] = evaluateViewsFor(
            this.implementations,
            context.store,
            target
        );
        let options = context.options[target.uri];
        if (options && options.view !== undefined) {
            // try to use the forced view
            view = this.implementations[options.view];
        }
        if (view === null) {
            // try to resolve a view
            if (evaluations.length > 0) {
                view = this.implementations[evaluations[0].viewId];
            }
        }
        if (view === null) {
            // cannot resolve a view ...
            return {
                dom: null,
                viewId: '',
                evaluations: evaluations,
                suggestedResources: [],
                languages: [],
            };
        }
        let result = view.render(this, context, target);
        return {
            dom: result.dom,
            viewId: view.descriptor.identifier,
            evaluations: evaluations,
            suggestedResources: result.suggestedResources
                ? result.suggestedResources
                : [],
            languages: this.getLanguagesFor(context, target),
        };
339
    }
340

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
    /**
     * Refreshes this view renderer
     * @param registry The current view registry
     */
    refresh(registry: ViewRegistry): Promise<CachingViewRenderer> {
        let self = this;
        return new Promise<CachingViewRenderer>(
            (
                resolve: (renderer: CachingViewRenderer) => void,
                reject: (reason: any) => void
            ) => {
                let toAdd: ViewDescriptor[] = [];
                Object.keys(registry.descriptors).forEach((id: string) => {
                    let candidate = self.descriptors[id];
                    let newDescriptor = registry.descriptors[id];
                    if (
                        candidate === undefined &&
                        newDescriptor !== undefined
                    ) {
                        toAdd.push(newDescriptor);
                    }
                });
                Object.keys(self.descriptors).forEach((id: string) => {
                    let current = self.descriptors[id];
                    let newDescriptor = registry.descriptors[id];
                    if (current !== undefined && newDescriptor === undefined) {
                        // has been deleted
                        delete self.descriptors[id];
                        delete self.implementations[id];
                    }
                });
                if (toAdd.length === 0) {
                    resolve(self);
                    return;
                }
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
                let finished = 0;
                function onPartFinished() {
                    finished += 1;
                    if (finished >= toAdd.length) resolve(self);
                }
                toAdd.forEach((descriptor: ViewDescriptor) => {
                    fetchImplementation(descriptor, self.resolver)
                        .then((implementation: ViewImplementation) => {
                            self.descriptors[
                                descriptor.identifier
                            ] = descriptor;
                            self.implementations[
                                descriptor.identifier
                            ] = implementation;
                            onPartFinished();
                        })
                        .catch((reason: string) => {
                            console.log(
                                'Failed to fetch implementation for view ' +
                                    descriptor.name +
                                    ': ' +
                                    reason
                            );
                            onPartFinished();
                        });
                });
            }
        );
    }
406
407
408
409
}

/**
 * Creates a new view renderer
410
 * @param resolver The content resolver to use
411
412
 */
export function newRenderer(
413
    resolver: ViewResourceContentResolver
414
): CachingViewRenderer {
415
    return new ViewRendererImpl(resolver);
416
}