1717
1818/**
1919 * @typedef {Object } GScan
20+ * @property {Array<TreeNode> } tree
21+ * @property {Lookup } lookup
2022 */
2123
2224/**
2325 * @typedef {Object<String, TreeNode> } Lookup
2426 */
2527
26- /**
27- * @typedef {Object<String, TreeNode> } Tree
28- */
28+ import { sortedIndexBy } from '@/components/cylc/common/sort'
29+ import { sortWorkflowNamePartNodeOrWorkflowNode } from '@/components/cylc/gscan/sort'
2930
3031/**
31- * @param {WorkflowGraphQLData } workflow
32+ * @param {TreeNode } workflow
3233 * @param {GScan } gscan
3334 * @param {* } options
3435 */
3536function addWorkflow ( workflow , gscan , options ) {
37+ const hierarchical = options . hierarchical || true
38+ if ( hierarchical ) {
39+ addHierarchicalWorkflow ( workflow , gscan . lookup , gscan . tree , options )
40+ } else {
41+ gscan . lookup [ workflow . id ] = workflow
42+ gscan . tree . push ( workflow )
43+ }
44+ }
3645
46+ /**
47+ * @param workflow
48+ * @param {Lookup } lookup
49+ * @param {Array<TreeNode> } tree
50+ * @param {* } options
51+ */
52+ function addHierarchicalWorkflow ( workflow , lookup , tree , options ) {
53+ if ( ! lookup [ workflow . id ] ) {
54+ // a new node, let's add this node and its descendants to the lookup
55+ lookup [ workflow . id ] = workflow
56+ if ( workflow . children ) {
57+ const stack = [ ...workflow . children ]
58+ while ( stack . length ) {
59+ const currentNode = stack . shift ( )
60+ lookup [ currentNode . id ] = currentNode
61+ if ( currentNode . children ) {
62+ stack . push ( ...currentNode . children )
63+ }
64+ }
65+ }
66+ // and now add the top-level node to the tree
67+ // Here we calculate what is the index for this element. If we decide to have ASC and DESC,
68+ // then we just need to invert the location of the element, something like
69+ // `sortedIndex = (array.length - sortedIndex)`.
70+ const sortedIndex = sortedIndexBy (
71+ tree ,
72+ workflow ,
73+ ( n ) => n . name ,
74+ sortWorkflowNamePartNodeOrWorkflowNode
75+ )
76+ tree . splice ( sortedIndex , 0 , workflow )
77+ } else {
78+ // we will have to merge the hierarchies
79+ const existingNode = lookup [ workflow . id ]
80+ // TODO: combine states summaries?
81+ // Copy array since we will iterate it, and modify existingNode.children
82+ if ( existingNode . children ) {
83+ const children = [ ...workflow . children ]
84+ for ( const child of children ) {
85+ // Recursion
86+ addHierarchicalWorkflow ( child , lookup , existingNode . children , options )
87+ }
88+ }
89+ }
3790}
3891
3992/**
40- * @param {WorkflowGraphQLData } workflow
93+ * @param {TreeNode } workflow
4194 * @param {GScan } gscan
4295 * @param {* } options
4396 */
@@ -46,7 +99,7 @@ function updateWorkflow (workflow, gscan, options) {
4699}
47100
48101/**
49- * @param {WorkflowGraphQLData } workflow
102+ * @param {TreeNode } workflow
50103 * @param {GScan } gscan
51104 * @param {* } options
52105 */
0 commit comments