terms.ts
92 lines
| 1 | /** |
| 2 | * WordPress dependencies |
| 3 | */ |
| 4 | import { decodeEntities } from '@wordpress/html-entities'; |
| 5 | |
| 6 | /** |
| 7 | * Returns terms in a tree form. |
| 8 | * |
| 9 | * @since 3.16.0 |
| 10 | * |
| 11 | * @param {Array} flatTerms Array of terms in flat format. |
| 12 | * |
| 13 | * @return {Array} Array of terms in tree format. |
| 14 | */ |
| 15 | export function buildTermsTree( flatTerms ) { |
| 16 | const flatTermsWithParentAndChildren = flatTerms.map( ( term ) => { |
| 17 | return { |
| 18 | children: [], |
| 19 | parent: null, |
| 20 | ...term, |
| 21 | }; |
| 22 | } ); |
| 23 | |
| 24 | // All terms should have a `parent` because we're about to index them by it. |
| 25 | if ( |
| 26 | flatTermsWithParentAndChildren.some( ( { parent } ) => parent === null ) |
| 27 | ) { |
| 28 | return flatTermsWithParentAndChildren; |
| 29 | } |
| 30 | |
| 31 | const termsByParent = flatTermsWithParentAndChildren.reduce( |
| 32 | ( acc, term ) => { |
| 33 | const { parent } = term; |
| 34 | if ( ! acc[ parent ] ) { |
| 35 | acc[ parent ] = []; |
| 36 | } |
| 37 | acc[ parent ].push( term ); |
| 38 | return acc; |
| 39 | }, |
| 40 | {} |
| 41 | ); |
| 42 | |
| 43 | const fillWithChildren = ( terms ) => { |
| 44 | return terms.map( ( term ) => { |
| 45 | const children = termsByParent[ term.id ]; |
| 46 | return { |
| 47 | ...term, |
| 48 | children: |
| 49 | children && children.length |
| 50 | ? fillWithChildren( children ) |
| 51 | : [], |
| 52 | }; |
| 53 | } ); |
| 54 | }; |
| 55 | |
| 56 | return fillWithChildren( termsByParent[ '0' ] || [] ); |
| 57 | } |
| 58 | |
| 59 | export const unescapeString = ( arg ) => { |
| 60 | return decodeEntities( arg ); |
| 61 | }; |
| 62 | |
| 63 | /** |
| 64 | * Returns a term object with name unescaped. |
| 65 | * |
| 66 | * @since 3.16.0 |
| 67 | * |
| 68 | * @param {Object} term The term object to unescape. |
| 69 | * |
| 70 | * @return {Object} Term object with name property unescaped. |
| 71 | */ |
| 72 | export const unescapeTerm = ( term ) => { |
| 73 | return { |
| 74 | ...term, |
| 75 | name: unescapeString( term.name ), |
| 76 | }; |
| 77 | }; |
| 78 | |
| 79 | /** |
| 80 | * Returns an array of term objects with names unescaped. |
| 81 | * The unescape of each term is performed using the unescapeTerm function. |
| 82 | * |
| 83 | * @since 3.16.0 |
| 84 | * |
| 85 | * @param {Object[]} terms Array of term objects to unescape. |
| 86 | * |
| 87 | * @return {Object[]} Array of term objects unescaped. |
| 88 | */ |
| 89 | export const unescapeTerms = ( terms ) => { |
| 90 | return ( terms ?? [] ).map( unescapeTerm ); |
| 91 | }; |
| 92 |