@wordpress/components
Version:
UI components for WordPress.
1 lines • 2.63 kB
Source Map (JSON)
{"version":3,"file":"terms.mjs","names":[],"sources":["../../src/query-controls/terms.ts"],"sourcesContent":["import type {\n\tAuthor,\n\tCategory,\n\tTermWithParentAndChildren,\n\tTermsByParent,\n} from './types';\n\nconst ensureParentsAreDefined = (\n\tterms: TermWithParentAndChildren[]\n): terms is ( TermWithParentAndChildren & { parent: number } )[] => {\n\treturn terms.every( ( term ) => term.parent !== null );\n};\n/**\n * Returns terms in a tree form.\n *\n * @param flatTerms Array of terms in flat format.\n *\n * @return Terms in tree format.\n */\nexport function buildTermsTree( flatTerms: readonly ( Author | Category )[] ) {\n\tconst flatTermsWithParentAndChildren: TermWithParentAndChildren[] =\n\t\tflatTerms.map( ( term ) => ( {\n\t\t\tchildren: [],\n\t\t\tparent: null,\n\t\t\t...term,\n\t\t\tid: String( term.id ),\n\t\t} ) );\n\n\t// We use a custom type guard here to ensure that the parent property is\n\t// defined on all terms. The type of the `parent` property is `number | null`\n\t// and we need to ensure that it is `number`. This is because we use the\n\t// `parent` property as a key in the `termsByParent` object.\n\tif ( ! ensureParentsAreDefined( flatTermsWithParentAndChildren ) ) {\n\t\treturn flatTermsWithParentAndChildren;\n\t}\n\n\tconst termsByParent = flatTermsWithParentAndChildren.reduce(\n\t\t( acc: TermsByParent, term ) => {\n\t\t\tconst { parent } = term;\n\t\t\tif ( ! acc[ parent ] ) {\n\t\t\t\tacc[ parent ] = [];\n\t\t\t}\n\t\t\tacc[ parent ].push( term );\n\t\t\treturn acc;\n\t\t},\n\t\t{}\n\t);\n\n\tconst fillWithChildren = (\n\t\tterms: TermWithParentAndChildren[]\n\t): TermWithParentAndChildren[] => {\n\t\treturn terms.map( ( term ) => {\n\t\t\tconst children = termsByParent[ term.id ];\n\t\t\treturn {\n\t\t\t\t...term,\n\t\t\t\tchildren:\n\t\t\t\t\tchildren && children.length\n\t\t\t\t\t\t? fillWithChildren( children )\n\t\t\t\t\t\t: [],\n\t\t\t};\n\t\t} );\n\t};\n\n\treturn fillWithChildren( termsByParent[ '0' ] || [] );\n}\n"],"mappings":";AAOA,MAAM,2BACL,UACmE;CACnE,OAAO,MAAM,OAAS,SAAU,KAAK,WAAW,IAAK;AACtD;;;;;;;;AAQA,SAAgB,eAAgB,WAA8C;CAC7E,MAAM,iCACL,UAAU,KAAO,UAAY;EAC5B,UAAU,CAAC;EACX,QAAQ;EACR,GAAG;EACH,IAAI,OAAQ,KAAK,EAAG;CACrB,EAAI;CAML,IAAK,CAAE,wBAAyB,8BAA+B,GAC9D,OAAO;CAGR,MAAM,gBAAgB,+BAA+B,QAClD,KAAoB,SAAU;EAC/B,MAAM,EAAE,WAAW;EACnB,IAAK,CAAE,IAAK,SACX,IAAK,UAAW,CAAC;EAElB,IAAK,OAAQ,CAAC,KAAM,IAAK;EACzB,OAAO;CACR,GACA,CAAC,CACF;CAEA,MAAM,oBACL,UACiC;EACjC,OAAO,MAAM,KAAO,SAAU;GAC7B,MAAM,WAAW,cAAe,KAAK;GACrC,OAAO;IACN,GAAG;IACH,UACC,YAAY,SAAS,SAClB,iBAAkB,QAAS,IAC3B,CAAC;GACN;EACD,CAAE;CACH;CAEA,OAAO,iBAAkB,cAAe,QAAS,CAAC,CAAE;AACrD"}