How can I sort color swatches by best selling on the product page?

Hi. Could you please help me? We want to sort color swatches on the product page from best selling down, except if they are out of stock then put them at the end.

Do we have the ability to do this?

Thanks

You can do these steps:

Determine the best-selling colors

Retrieve the availability status of colors

Sort the color swatches:

I understand it)

For me, the main issue is how we can determine the best-selling colors.
Everything else is easy to implement, but I don’t know how exactly to catch which colors are the best sellers.

I use the Dawn theme.