UNPKG

2.22 kBPlain TextView Raw
1import {
2 TaxonomyNode, CompoundWidget, NodeIdentifier, QuerySegment, TaxonomyPath,
3 PathSegment
4} from '@/types';
5import { DraggableConstructor } from 'gsap/Draggable';
6import * as log from 'loglevel';
7
8function getNodeById(rootNode: TaxonomyNode, wantedId: NodeIdentifier): TaxonomyNode {
9 const result = rootNode.all(function(node: TaxonomyNode): boolean {
10 return node.model.uri === wantedId;
11 });
12 if (result.length === 1) {
13 return result[0];
14 } else {
15 throw new Error("not found: " + wantedId);
16 }
17}
18
19function getVirtualRoot(rootNode: TaxonomyNode, wantedPath: NodeIdentifier[]): TaxonomyNode {
20 log.debug("inside getVirtualRoot");
21 if (wantedPath.length === 0) {
22 log.debug("returning root node");
23 return rootNode;
24 }
25
26 // Find the leaf of the path...
27 const leaf = wantedPath[wantedPath.length - 1]
28 return getNodeById(rootNode, leaf);
29}
30
31function findValidChildren(
32 rootNode: TaxonomyNode, wantedPath: NodeIdentifier[]
33): TaxonomyNode[] {
34 const virtualRoot = getVirtualRoot(rootNode, wantedPath);
35 return virtualRoot.children;
36};
37
38
39function getCollidingElements(d: DraggableConstructor, validElements: Element[]) {
40 return validElements.filter(e => d.hitTest(e, '50%'));
41}
42
43function makeEmptyCompoundWidget(): CompoundWidget {
44 return {
45 taxonomyRef: null,
46 isCurrentlyBeingDragged: false,
47 selectedPath: [],
48 hasTentativeTaxonSelector: false,
49 };
50}
51
52
53// Coerce a compound widget's selected path (which may include undefined ones)
54// to a simple list of path identifiers
55function getFlatPath(selectedPath: PathSegment[]): TaxonomyPath {
56 const result: NodeIdentifier[] = [];
57
58 selectedPath.forEach(segment => {
59 result.push.apply(result, segment.toPathElements());
60 });
61
62 return result;
63}
64
65function getQuerySegment(c: CompoundWidget): QuerySegment {
66 if (c.taxonomyRef === null) throw new Error("null taxonomy");
67
68 return {
69 taxonomyRef: c.taxonomyRef,
70 selectedPath: getFlatPath(c.selectedPath)
71 };
72}
73
74
75export default {
76 findValidChildren, getCollidingElements, makeEmptyCompoundWidget,
77 getNodeById, getQuerySegment, getFlatPath
78};