ReplaceNodeWithSpanCommand.cpp [plain text]
#include "config.h"
#include "ReplaceNodeWithSpanCommand.h"
#include "htmlediting.h"
#include "HTMLElement.h"
#include "HTMLNames.h"
#include <wtf/Assertions.h>
namespace WebCore {
using namespace HTMLNames;
ReplaceNodeWithSpanCommand::ReplaceNodeWithSpanCommand(PassRefPtr<HTMLElement> element)
: SimpleEditCommand(element->document())
, m_elementToReplace(element)
{
ASSERT(m_elementToReplace);
}
static void swapInNodePreservingAttributesAndChildren(HTMLElement* newNode, HTMLElement* nodeToReplace)
{
ASSERT(nodeToReplace->inDocument());
ExceptionCode ec = 0;
RefPtr<ContainerNode> parentNode = nodeToReplace->parentNode();
parentNode->insertBefore(newNode, nodeToReplace, ec);
ASSERT(!ec);
RefPtr<Node> nextChild;
for (Node* child = nodeToReplace->firstChild(); child; child = nextChild.get()) {
nextChild = child->nextSibling();
newNode->appendChild(child, ec);
ASSERT(!ec);
}
newNode->setAttributesFromElement(*nodeToReplace);
parentNode->removeChild(nodeToReplace, ec);
ASSERT(!ec);
}
void ReplaceNodeWithSpanCommand::doApply()
{
if (!m_elementToReplace->inDocument())
return;
if (!m_spanElement)
m_spanElement = createHTMLElement(m_elementToReplace->document(), spanTag);
swapInNodePreservingAttributesAndChildren(m_spanElement.get(), m_elementToReplace.get());
}
void ReplaceNodeWithSpanCommand::doUnapply()
{
if (!m_spanElement->inDocument())
return;
swapInNodePreservingAttributesAndChildren(m_elementToReplace.get(), m_spanElement.get());
}
#ifndef NDEBUG
void ReplaceNodeWithSpanCommand::getNodesInCommand(HashSet<Node*>& nodes)
{
addNodeAndDescendants(m_elementToReplace.get(), nodes);
addNodeAndDescendants(m_spanElement.get(), nodes);
}
#endif
}