#include "converter.h"
#include "parser.h"
#include "macrodown.h"
#include <iostream>
namespace macrodown
{
std::vector<std::unique_ptr<Node>> Converter::convert(
const Block* root,
const std::vector<PrefixMarkup>& prefix_markups,
const std::vector<DelimitedMarkup>& delimited_markups)
{
std::vector<std::unique_ptr<Node>> nodes;
if(root->type == BlockType::Document)
{
for(const auto& child : root->children)
{
auto node = convert_block(child.get(), prefix_markups, delimited_markups);
if(node)
{
nodes.push_back(std::move(node));
}
}
}
else
{
// Should not happen if root is Document, but handle single block
auto node = convert_block(root, prefix_markups, delimited_markups);
if(node) nodes.push_back(std::move(node));
}
return nodes;
}
std::unique_ptr<Node> Converter::convert_block(
const Block* block,
const std::vector<PrefixMarkup>& prefix_markups,
const std::vector<DelimitedMarkup>& delimited_markups)
{
if(!block) return nullptr;
std::string macro_name;
switch(block->type)
{
case BlockType::Paragraph:
macro_name = "p";
break;
case BlockType::Heading:
macro_name = "h" + std::to_string(block->level);
break;
case BlockType::Quote:
macro_name = "quote";
break;
default:
return nullptr; // Ignore unknown blocks for now
}
Macro macro;
macro.name = macro_name;
// Handle Content
if(block->children.empty())
{
// Leaf block: Parse literal content
Group group;
auto inline_nodes = Parser::parse(block->literal_content, prefix_markups, delimited_markups);
for(auto& n : inline_nodes)
{
group.addChild(std::move(n));
}
macro.arguments.push_back(std::make_unique<Node>(std::move(group)));
}
else
{
// Container block: Recursively convert children
Group group;
for(const auto& child : block->children)
{
auto child_node = convert_block(child.get(), prefix_markups, delimited_markups);
if(child_node)
{
group.addChild(std::move(child_node));
}
}
macro.arguments.push_back(std::make_unique<Node>(std::move(group)));
}
return std::make_unique<Node>(std::move(macro));
}
} // namespace macrodown