Sha256: 9ce75533f68477fd6f63cce5831bc76833ff861b9377738b1a975ed44e38622c

Contents?: true

Size: 1.28 KB

Versions: 1

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

require_relative "constants"
require_relative "transform"
module Plurimath
  class Mathml
    class Parser
      attr_accessor :text

      SUPPORTED_ATTRIBUTES = %w[
        columnlines
        mathvariant
        mathcolor
        notation
        close
        open
      ].freeze

      def initialize(text)
        @text = text
      end

      def parse
        ox_nodes = Ox.load(text, strip_namespace: true).nodes
        nodes = parse_nodes(ox_nodes)
        Math::Formula.new(
          Transform.new.apply(nodes).flatten.compact,
        )
      end

      def parse_nodes(nodes)
        nodes.map do |node|
          next if node.is_a?(Ox::Comment)

          if node.is_a?(String)
            node
          elsif !node.attributes.empty?
            {
              node.name.to_sym => {
                attributes: validate_attributes(node.attributes),
                value: parse_nodes(node.nodes),
              },
            }
          else
            { node.name.to_sym => parse_nodes(node.nodes) }
          end
        end
      end

      def validate_attributes(attributes)
        attributes&.select! { |key, _| SUPPORTED_ATTRIBUTES.include?(key&.to_s) }
        attributes&.transform_keys(&:to_sym) if attributes&.any?
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
plurimath-0.3.6 lib/plurimath/mathml/parser.rb