Skip to content

Commit

Permalink
feat: sort the simple key value list (#22335)
Browse files Browse the repository at this point in the history
Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
  • Loading branch information
pauldambra and github-actions[bot] authored May 19, 2024
1 parent 946a7e3 commit c41995f
Showing 1 changed file with 29 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,16 +1,43 @@
// A React component that renders a list of key-value pairs in a simple way.

import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { useEffect, useState } from 'react'

export interface SimpleKeyValueListProps {
item: Record<string, any>
emptyMessage?: string | JSX.Element | null
/**
* SimpleKeyValueList will render these keys first.
* keys are otherwise rendered in alphabetical order.
*/
promotedKeys?: string[]
}

export function SimpleKeyValueList({ item, emptyMessage }: SimpleKeyValueListProps): JSX.Element {
export function SimpleKeyValueList({ item, emptyMessage, promotedKeys }: SimpleKeyValueListProps): JSX.Element {
const [sortedItemsPromotedFirst, setSortedItemsPromotedFirst] = useState<[string, any][]>([])

useEffect(() => {
const sortedItems = Object.entries(item).sort((a, b) => {
if (a[0] < b[0]) {
return -1
}
if (a[0] > b[0]) {
return 1
}
return 0
})

const promotedItems = promotedKeys?.length ? sortedItems.filter(([key]) => promotedKeys.includes(key)) : []
const nonPromotedItems = promotedKeys?.length
? sortedItems.filter(([key]) => !promotedKeys.includes(key))
: sortedItems

setSortedItemsPromotedFirst([...promotedItems, ...nonPromotedItems])
}, [item, promotedKeys])

return (
<div className="text-xs space-y-1 max-w-full">
{Object.entries(item).map(([key, value]) => (
{sortedItemsPromotedFirst.map(([key, value]) => (
<div key={key} className="flex gap-4 items-start justify-between overflow-hidden">
<span className="font-semibold">
<PropertyKeyInfo value={key} />
Expand Down

0 comments on commit c41995f

Please sign in to comment.