Skip to content

Truly independent web browser

2.4 KB
Raw Blame
/*
 * Copyright (c) 2025, Sam Atkins <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/HashFunctions.h>
#include <AK/Optional.h>
#include <AK/Traits.h>
#include <AK/Utf16FlyString.h>
#include <LibWeb/CSS/PropertyName.h>
#include <LibWeb/CSS/Serialize.h>

namespace Web::CSS {

class WEB_API PropertyNameAndID {
public:
    static Optional<PropertyNameAndID> from_name(Utf16FlyString name)
    {
        if (is_a_custom_property_name_string(name))
            return PropertyNameAndID(move(name), PropertyID::Custom);

        if (auto property_id = property_id_from_string(name); property_id.has_value())
            return PropertyNameAndID(string_from_property_id(property_id.value()), property_id.value());

        return {};
    }

    static PropertyNameAndID from_id(PropertyID property_id)
    {
        VERIFY(property_id != PropertyID::Custom);
        return PropertyNameAndID({}, property_id);
    }

    PropertyNameAndID(Badge<StyleComputer>, PropertyID property_id, Utf16FlyString name)
        : m_name(move(name))
        , m_property_id(property_id)
    {
    }

    bool is_custom_property() const { return m_property_id == PropertyID::Custom; }
    PropertyID id() const { return m_property_id; }

    Utf16FlyString const& name() const
    {
        if (!m_name.has_value())
            m_name = string_from_property_id(m_property_id);
        return m_name.value();
    }

    String to_string() const
    {
        return serialize_an_identifier(name());
    }

    Utf16String to_utf16_string() const
    {
        return serialize_an_identifier_to_utf16(name());
    }

    bool operator==(PropertyNameAndID const& other) const
    {
        if (m_property_id != other.m_property_id)
            return false;
        return !is_custom_property() || name() == other.name();
    }

    unsigned hash() const
    {
        if (is_custom_property())
            return name().hash();
        return u32_hash(to_underlying(m_property_id));
    }

private:
    PropertyNameAndID(Optional<Utf16FlyString> name, PropertyID id)
        : m_name(move(name))
        , m_property_id(id)
    {
    }

    mutable Optional<Utf16FlyString> m_name;
    PropertyID m_property_id;
};

}

template<>
struct AK::Traits<Web::CSS::PropertyNameAndID> : public DefaultTraits<Web::CSS::PropertyNameAndID> {
    static unsigned hash(Web::CSS::PropertyNameAndID const& property) { return property.hash(); }
};