locate-the-news / frontend / src / utils / countryHighlight.js
countryHighlight.js
Raw
import { SENTIMENT_COLORS } from './sentimentColors';

export const getCountrySentiments = (events) => {
    const countrySentiments = {};

    events.forEach(event => {
        const country = event.location?.entity_name;
        if (country) {
            if (!countrySentiments[country]) {
                countrySentiments[country] = {
                    positive: 0,
                    neutral: 0,
                    negative: 0,
                    total: 0
                };
            }

            const sentiment = event.sentiment_label || 'neutral';
            countrySentiments[country][sentiment]++;
            countrySentiments[country].total++;
        }
    });

    return countrySentiments;
};

const sentimentToCountryColor = (sentiment) => {
    const { positive, neutral, negative, total } = sentiment;
    const negativeRatio = negative / total;

    if (negativeRatio > 0.5) return 'rgba(255, 51, 102, 0.3)';
    if (negativeRatio < 0.3) return 'rgba(0, 255, 136, 0.2)';
    return 'rgba(0, 217, 255, 0.2)';
};

export const createCountryFillExpression = (countrySentiments) => {
    if (!countrySentiments || Object.keys(countrySentiments).length === 0) {
        return 'rgba(0, 0, 0, 0)';
    }

    const expression = ['match', ['get', 'name']];

    Object.entries(countrySentiments).forEach(([country, sentiment]) => {
        expression.push(country);
        expression.push(sentimentToCountryColor(sentiment));
    });

    expression.push('rgba(0, 0, 0, 0)');

    return expression;
};