|
1 | 1 | import { IPickerTerm } from './../propertyFields/termPicker/IPropertyFieldTermPicker'; |
| 2 | +import { findIndex } from '@microsoft/sp-lodash-subset'; |
2 | 3 |
|
3 | 4 | /** |
4 | 5 | * Interfaces for Term store, groups and term sets |
@@ -159,12 +160,56 @@ export class TermStorePickerServiceHelper { |
159 | 160 | return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(strGuid); |
160 | 161 | } |
161 | 162 |
|
162 | | - /** |
| 163 | + /** |
| 164 | + * Sorting terms based on their path and depth |
| 165 | + * |
| 166 | + * @param terms |
| 167 | + */ |
| 168 | + public static sortTerms(terms: ITerm[]) { |
| 169 | + // Start sorting by depth |
| 170 | + let newTermsOrder: ITerm[] = []; |
| 171 | + let itemsToSort = true; |
| 172 | + let pathLevel = 1; |
| 173 | + while (itemsToSort) { |
| 174 | + // Get terms for the current level |
| 175 | + let crntTerms = terms.filter(term => term.PathDepth === pathLevel); |
| 176 | + if (crntTerms && crntTerms.length > 0) { |
| 177 | + crntTerms = crntTerms.sort(this.sortTermByPath); |
| 178 | + |
| 179 | + if (pathLevel !== 1) { |
| 180 | + crntTerms = crntTerms.reverse(); |
| 181 | + for (const crntTerm of crntTerms) { |
| 182 | + const pathElms = crntTerm.PathOfTerm.split(";"); |
| 183 | + // Last item is not needed for parent path |
| 184 | + pathElms.pop(); |
| 185 | + // Find the parent item and add the new item |
| 186 | + const idx = findIndex(newTermsOrder, term => term.PathOfTerm === pathElms.join(";")); |
| 187 | + if (idx !== -1) { |
| 188 | + newTermsOrder.splice(idx + 1, 0, crntTerm); |
| 189 | + } else { |
| 190 | + // Push the item at the end if the parent couldn't be found |
| 191 | + newTermsOrder.push(crntTerm); |
| 192 | + } |
| 193 | + } |
| 194 | + } else { |
| 195 | + newTermsOrder = crntTerms; |
| 196 | + } |
| 197 | + |
| 198 | + ++pathLevel; |
| 199 | + } else { |
| 200 | + itemsToSort = false; |
| 201 | + } |
| 202 | + } |
| 203 | + return newTermsOrder; |
| 204 | + } |
| 205 | + |
| 206 | + /** |
163 | 207 | * Sort the terms by their path |
| 208 | + * |
164 | 209 | * @param a term 2 |
165 | 210 | * @param b term 2 |
166 | 211 | */ |
167 | | - public static sortTerms(a: ITerm, b: ITerm) { |
| 212 | + private static sortTermByPath(a: ITerm, b: ITerm) { |
168 | 213 | if (a.PathOfTerm < b.PathOfTerm) { |
169 | 214 | return -1; |
170 | 215 | } |
|
0 commit comments