Source code

Revision control

Other Tools

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef mozilla_HTMLEditor_h
#define mozilla_HTMLEditor_h
#include "mozilla/Attributes.h"
#include "mozilla/ComposerCommandsUpdater.h"
#include "mozilla/CSSEditUtils.h"
#include "mozilla/EditorBase.h"
#include "mozilla/EditorUtils.h"
#include "mozilla/ManualNAC.h"
#include "mozilla/Result.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/dom/BlobImpl.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/File.h"
#include "nsAttrName.h"
#include "nsCOMPtr.h"
#include "nsIDocumentObserver.h"
#include "nsIDOMEventListener.h"
#include "nsIEditorMailSupport.h"
#include "nsIHTMLAbsPosEditor.h"
#include "nsIHTMLEditor.h"
#include "nsIHTMLInlineTableEditor.h"
#include "nsIHTMLObjectResizer.h"
#include "nsITableEditor.h"
#include "nsPoint.h"
#include "nsStubMutationObserver.h"
#include "nsTArray.h"
class nsDocumentFragment;
class nsFrameSelection;
class nsHTMLDocument;
class nsITransferable;
class nsIClipboard;
class nsRange;
class nsStaticAtom;
class nsStyledElement;
class nsTableWrapperFrame;
namespace mozilla {
class AlignStateAtSelection;
class AutoSelectionSetterAfterTableEdit;
class AutoSetTemporaryAncestorLimiter;
class EditActionResult;
class EditResult;
class EmptyEditableFunctor;
class JoinNodeTransaction;
class ListElementSelectionState;
class ListItemElementSelectionState;
class MoveNodeResult;
class ParagraphStateAtSelection;
class ResizerSelectionListener;
class Runnable;
class SplitNodeTransaction;
class SplitRangeOffFromNodeResult;
class SplitRangeOffResult;
class WhiteSpaceVisibilityKeeper;
class WSRunScanner;
class WSScanResult;
enum class EditSubAction : int32_t;
enum class SpecifiedStyle : uint8_t;
struct PropItem;
template <class T>
class OwningNonNull;
namespace dom {
class AbstractRange;
class Blob;
class DocumentFragment;
class Event;
class MouseEvent;
class StaticRange;
} // namespace dom
namespace widget {
struct IMEState;
} // namespace widget
enum class ParagraphSeparator { div, p, br };
/**
* The HTML editor implementation.<br>
* Use to edit HTML document represented as a DOM tree.
*/
class HTMLEditor final : public EditorBase,
public nsIHTMLEditor,
public nsIHTMLObjectResizer,
public nsIHTMLAbsPosEditor,
public nsITableEditor,
public nsIHTMLInlineTableEditor,
public nsStubMutationObserver,
public nsIEditorMailSupport {
public:
/****************************************************************************
* NOTE: DO NOT MAKE YOUR NEW METHODS PUBLIC IF they are called by other
* classes under libeditor except EditorEventListener and
* HTMLEditorEventListener because each public method which may fire
* eEditorInput event will need to instantiate new stack class for
* managing input type value of eEditorInput and cache some objects
* for smarter handling. In other words, when you add new root
* method to edit the DOM tree, you can make your new method public.
****************************************************************************/
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(HTMLEditor, EditorBase)
// nsStubMutationObserver overrides
NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED
NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED
NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED
// nsIHTMLEditor methods
NS_DECL_NSIHTMLEDITOR
// nsIHTMLObjectResizer methods (implemented in HTMLObjectResizer.cpp)
NS_DECL_NSIHTMLOBJECTRESIZER
// nsIHTMLAbsPosEditor methods (implemented in HTMLAbsPositionEditor.cpp)
NS_DECL_NSIHTMLABSPOSEDITOR
// nsIHTMLInlineTableEditor methods (implemented in HTMLInlineTableEditor.cpp)
NS_DECL_NSIHTMLINLINETABLEEDITOR
// nsIEditorMailSupport methods
NS_DECL_NSIEDITORMAILSUPPORT
// nsITableEditor methods
NS_DECL_NSITABLEEDITOR
// nsISelectionListener overrides
NS_DECL_NSISELECTIONLISTENER
HTMLEditor();
/**
* @param aDocument The document whose content will be editable.
* @param aFlags Some of nsIEditor::eEditor*Mask flags.
*/
MOZ_CAN_RUN_SCRIPT nsresult Init(Document& aDocument, uint32_t aFlags);
/**
* PostCreate() should be called after Init, and is the time that the editor
* tells its documentStateObservers that the document has been created.
*/
MOZ_CAN_RUN_SCRIPT nsresult PostCreate();
/**
* PreDestroy() is called before the editor goes away, and gives the editor a
* chance to tell its documentStateObservers that the document is going away.
*/
MOZ_CAN_RUN_SCRIPT void PreDestroy();
static HTMLEditor* GetFrom(nsIEditor* aEditor) {
return aEditor ? aEditor->GetAsHTMLEditor() : nullptr;
}
static const HTMLEditor* GetFrom(const nsIEditor* aEditor) {
return aEditor ? aEditor->GetAsHTMLEditor() : nullptr;
}
/**
* Adds or removes transaction listener to or from the transaction manager.
* Note that TransactionManager does not check if the listener is in the
* array. So, caller of AddTransactionListener() needs to manage if it's
* already been registered to the transaction manager.
*/
bool AddTransactionListener(nsITransactionListener& aListener) {
if (!mTransactionManager) {
return false;
}
return mTransactionManager->AddTransactionListener(aListener);
}
bool RemoveTransactionListener(nsITransactionListener& aListener) {
if (!mTransactionManager) {
return false;
}
return mTransactionManager->RemoveTransactionListener(aListener);
}
bool GetReturnInParagraphCreatesNewParagraph();
// EditorBase overrides
MOZ_CAN_RUN_SCRIPT NS_IMETHOD BeginningOfDocument() final;
NS_IMETHOD GetDocumentCharacterSet(nsACString& aCharacterSet) final;
MOZ_CAN_RUN_SCRIPT NS_IMETHOD
SetDocumentCharacterSet(const nsACString& aCharacterSet) final;
bool IsEmpty() const final;
bool CanPaste(int32_t aClipboardType) const final;
using EditorBase::CanPaste;
MOZ_CAN_RUN_SCRIPT nsresult PasteTransferableAsAction(
nsITransferable* aTransferable, nsIPrincipal* aPrincipal = nullptr) final;
MOZ_CAN_RUN_SCRIPT NS_IMETHOD DeleteNode(nsINode* aNode) final;
MOZ_CAN_RUN_SCRIPT NS_IMETHOD InsertLineBreak() final;
/**
* PreHandleMouseDown() and PreHandleMouseUp() are called before
* HTMLEditorEventListener handles them. The coming event may be
* non-acceptable event.
*/
void PreHandleMouseDown(const dom::MouseEvent& aMouseDownEvent);
void PreHandleMouseUp(const dom::MouseEvent& aMouseUpEvent);
/**
* PreHandleSelectionChangeCommand() and PostHandleSelectionChangeCommand()
* are called before or after handling a command which may change selection
* and/or scroll position.
*/
void PreHandleSelectionChangeCommand(Command aCommand);
void PostHandleSelectionChangeCommand(Command aCommand);
MOZ_CAN_RUN_SCRIPT nsresult
HandleKeyPressEvent(WidgetKeyboardEvent* aKeyboardEvent) final;
nsIContent* GetFocusedContent() const final;
nsIContent* GetFocusedContentForIME() const final;
bool IsActiveInDOMWindow() const final;
dom::EventTarget* GetDOMEventTarget() const final;
Element* FindSelectionRoot(nsINode* aNode) const final;
bool IsAcceptableInputEvent(WidgetGUIEvent* aGUIEvent) const final;
nsresult GetPreferredIMEState(widget::IMEState* aState) final;
/**
* GetBackgroundColorState() returns what the background color of the
* selection.
*
* @param aMixed true if there is more than one font color
* @param aOutColor Color string. "" is returned for none.
*/
MOZ_CAN_RUN_SCRIPT nsresult GetBackgroundColorState(bool* aMixed,
nsAString& aOutColor);
MOZ_CAN_RUN_SCRIPT NS_IMETHOD Paste(int32_t aClipboardType) final {
const nsresult rv = HTMLEditor::PasteAsAction(aClipboardType, true);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::PasteAsAction() failed");
return rv;
}
MOZ_CAN_RUN_SCRIPT nsresult
PasteAsAction(int32_t aClipboardType, bool aDispatchPasteEvent,
nsIPrincipal* aPrincipal = nullptr) final;
/**
* PasteNoFormattingAsAction() pastes content in clipboard without any style
* information.
*
* @param aSelectionType nsIClipboard::kGlobalClipboard or
* nsIClipboard::kSelectionClipboard.
* @param aPrincipal Set subject principal if it may be called by
* JS. If set to nullptr, will be treated as
* called by system.
*/
MOZ_CAN_RUN_SCRIPT nsresult PasteNoFormattingAsAction(
int32_t aSelectionType, nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult
PasteAsQuotationAsAction(int32_t aClipboardType, bool aDispatchPasteEvent,
nsIPrincipal* aPrincipal = nullptr) final;
bool CanPasteTransferable(nsITransferable* aTransferable) final;
MOZ_CAN_RUN_SCRIPT nsresult
InsertLineBreakAsAction(nsIPrincipal* aPrincipal = nullptr) final;
/**
* InsertParagraphSeparatorAsAction() is called when user tries to separate
* current paragraph with Enter key press in HTMLEditor or something.
*
* @param aPrincipal Set subject principal if it may be called by
* JS. If set to nullptr, will be treated as
* called by system.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
InsertParagraphSeparatorAsAction(nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult
InsertElementAtSelectionAsAction(Element* aElement, bool aDeleteSelection,
nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult InsertLinkAroundSelectionAsAction(
Element* aAnchorElement, nsIPrincipal* aPrincipal = nullptr);
/**
* CreateElementWithDefaults() creates new element whose name is
* aTagName with some default attributes are set. Note that this is a
* public utility method. I.e., just creates element, not insert it
* into the DOM tree.
* NOTE: This is available for internal use too since this does not change
* the DOM tree nor undo transactions, and does not refer Selection,
* etc.
*
* @param aTagName The new element's tag name. If the name is
* one of "href", "anchor" or "namedanchor",
* this creates an <a> element.
* @return Newly created element.
*/
MOZ_CAN_RUN_SCRIPT already_AddRefed<Element> CreateElementWithDefaults(
const nsAtom& aTagName);
/**
* Indent or outdent content around Selection.
*
* @param aPrincipal Set subject principal if it may be called by
* JS. If set to nullptr, will be treated as
* called by system.
*/
MOZ_CAN_RUN_SCRIPT nsresult
IndentAsAction(nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult
OutdentAsAction(nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult SetParagraphFormatAsAction(
const nsAString& aParagraphFormat, nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult AlignAsAction(const nsAString& aAlignType,
nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult RemoveListAsAction(
const nsAString& aListType, nsIPrincipal* aPrincipal = nullptr);
/**
* MakeOrChangeListAsAction() makes selected hard lines list element(s).
*
* @param aListElementTagName The new list element tag name. Must be
* nsGkAtoms::ul, nsGkAtoms::ol or
* nsGkAtoms::dl.
* @param aBulletType If this is not empty string, it's set
* to `type` attribute of new list item
* elements. Otherwise, existing `type`
* attributes will be removed.
* @param aSelectAllOfCurrentList Yes if this should treat all of
* ancestor list element at selection.
*/
enum class SelectAllOfCurrentList { Yes, No };
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult MakeOrChangeListAsAction(
nsAtom& aListElementTagName, const nsAString& aBulletType,
SelectAllOfCurrentList aSelectAllOfCurrentList,
nsIPrincipal* aPrincipal = nullptr);
/**
* If aTargetElement is a resizer, start to drag the resizer. Otherwise, if
* aTargetElement is the grabber, start to handle drag gester on it.
*
* @param aMouseDownEvent A `mousedown` event fired on aTargetElement.
* @param aEventTargetElement The target element being pressed. This must
* be same as explicit original event target of
* aMouseDownEvent.
*/
MOZ_CAN_RUN_SCRIPT nsresult StartToDragResizerOrHandleDragGestureOnGrabber(
dom::MouseEvent& aMouseDownEvent, Element& aEventTargetElement);
/**
* If the editor is handling dragging a resizer, handling drag gesture on
* the grabber or dragging the grabber, this finalize it. Otherwise,
* does nothing.
*
* @param aClientPoint The final point of the drag.
*/
MOZ_CAN_RUN_SCRIPT nsresult
StopDraggingResizerOrGrabberAt(const CSSIntPoint& aClientPoint);
/**
* If the editor is handling dragging a resizer, handling drag gesture to
* start dragging the grabber or dragging the grabber, this method updates
* it's position.
*
* @param aClientPoint The new point of the drag.
*/
MOZ_CAN_RUN_SCRIPT nsresult
UpdateResizerOrGrabberPositionTo(const CSSIntPoint& aClientPoint);
/**
* IsCSSEnabled() returns true if this editor treats styles with style
* attribute of HTML elements. Otherwise, if this editor treats all styles
* with "font style elements" like <b>, <i>, etc, and <blockquote> to indent,
* align attribute to align contents, returns false.
*/
bool IsCSSEnabled() const {
return !IsMailEditor() && mCSSEditUtils &&
mCSSEditUtils->IsCSSPrefChecked();
}
/**
* Enable/disable object resizers for <img> elements, <table> elements,
* absolute positioned elements (required absolute position editor enabled).
*/
MOZ_CAN_RUN_SCRIPT void EnableObjectResizer(bool aEnable) {
if (mIsObjectResizingEnabled == aEnable) {
return;
}
AutoEditActionDataSetter editActionData(
*this, EditAction::eEnableOrDisableResizer);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return;
}
mIsObjectResizingEnabled = aEnable;
RefreshEditingUI();
}
bool IsObjectResizerEnabled() const { return mIsObjectResizingEnabled; }
Element* GetResizerTarget() const { return mResizedObject; }
/**
* Enable/disable inline table editor, e.g., adding new row or column,
* removing existing row or column.
*/
MOZ_CAN_RUN_SCRIPT void EnableInlineTableEditor(bool aEnable) {
if (mIsInlineTableEditingEnabled == aEnable) {
return;
}
AutoEditActionDataSetter editActionData(
*this, EditAction::eEnableOrDisableInlineTableEditingUI);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return;
}
mIsInlineTableEditingEnabled = aEnable;
RefreshEditingUI();
}
bool IsInlineTableEditorEnabled() const {
return mIsInlineTableEditingEnabled;
}
/**
* Enable/disable absolute position editor, resizing absolute positioned
* elements (required object resizers enabled) or positioning them with
* dragging grabber.
*/
MOZ_CAN_RUN_SCRIPT void EnableAbsolutePositionEditor(bool aEnable) {
if (mIsAbsolutelyPositioningEnabled == aEnable) {
return;
}
AutoEditActionDataSetter editActionData(
*this, EditAction::eEnableOrDisableAbsolutePositionEditor);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return;
}
mIsAbsolutelyPositioningEnabled = aEnable;
RefreshEditingUI();
}
bool IsAbsolutePositionEditorEnabled() const {
return mIsAbsolutelyPositioningEnabled;
}
/**
* returns the deepest absolutely positioned container of the selection
* if it exists or null.
*/
MOZ_CAN_RUN_SCRIPT already_AddRefed<Element>
GetAbsolutelyPositionedSelectionContainer() const;
Element* GetPositionedElement() const { return mAbsolutelyPositionedObject; }
/**
* extracts the selection from the normal flow of the document and
* positions it.
*
* @param aEnabled [IN] true to absolutely position the selection,
* false to put it back in the normal flow
* @param aPrincipal Set subject principal if it may be called by
* JS. If set to nullptr, will be treated as
* called by system.
*/
MOZ_CAN_RUN_SCRIPT nsresult SetSelectionToAbsoluteOrStaticAsAction(
bool aEnabled, nsIPrincipal* aPrincipal = nullptr);
/**
* returns the absolute z-index of a positioned element. Never returns 'auto'
* @return the z-index of the element
* @param aElement [IN] the element.
*/
MOZ_CAN_RUN_SCRIPT int32_t GetZIndex(Element& aElement);
/**
* adds aChange to the z-index of the currently positioned element.
*
* @param aChange [IN] relative change to apply to current z-index
* @param aPrincipal Set subject principal if it may be called by
* JS. If set to nullptr, will be treated as
* called by system.
*/
MOZ_CAN_RUN_SCRIPT nsresult
AddZIndexAsAction(int32_t aChange, nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult SetBackgroundColorAsAction(
const nsAString& aColor, nsIPrincipal* aPrincipal = nullptr);
/**
* SetInlinePropertyAsAction() sets a property which changes inline style of
* text. E.g., bold, italic, super and sub.
* This automatically removes exclusive style, however, treats all changes
* as a transaction.
*
* @param aPrincipal Set subject principal if it may be called by
* JS. If set to nullptr, will be treated as
* called by system.
*/
MOZ_CAN_RUN_SCRIPT nsresult SetInlinePropertyAsAction(
nsAtom& aProperty, nsAtom* aAttribute, const nsAString& aValue,
nsIPrincipal* aPrincipal = nullptr);
/**
* GetInlineProperty() gets aggregate properties of the current selection.
* All object in the current selection are scanned and their attributes are
* represented in a list of Property object.
* TODO: Make this return Result<Something> instead of bool out arguments.
*
* @param aHTMLProperty the property to get on the selection
* @param aAttribute the attribute of the property, if applicable.
* May be null.
* Example: aHTMLProperty=nsGkAtoms::font,
* aAttribute=nsGkAtoms::color
* @param aValue if aAttribute is not null, the value of the
* attribute. May be null.
* Example: aHTMLProperty=nsGkAtoms::font,
* aAttribute=nsGkAtoms::color,
* aValue="0x00FFFF"
* @param aFirst [OUT] true if the first text node in the
* selection has the property
* @param aAny [OUT] true if any of the text nodes in the
* selection have the property
* @param aAll [OUT] true if all of the text nodes in the
* selection have the property
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult GetInlineProperty(
nsAtom* aHTMLProperty, nsAtom* aAttribute, const nsAString& aValue,
bool* aFirst, bool* aAny, bool* aAll) const;
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult GetInlinePropertyWithAttrValue(
nsAtom* aHTMLProperty, nsAtom* aAttribute, const nsAString& aValue,
bool* aFirst, bool* aAny, bool* aAll, nsAString& outValue);
/**
* RemoveInlinePropertyAsAction() removes a property which changes inline
* style of text. E.g., bold, italic, super and sub.
*
* @param aHTMLProperty Tag name whcih represents the inline style you want
* to remove. E.g., nsGkAtoms::strong, nsGkAtoms::b,
* etc. If nsGkAtoms::href, <a> element which has
* href attribute will be removed.
* If nsGkAtoms::name, <a> element which has non-empty
* name attribute will be removed.
* @param aAttribute If aHTMLProperty is nsGkAtoms::font, aAttribute should
* be nsGkAtoms::fase, nsGkAtoms::size, nsGkAtoms::color
* or nsGkAtoms::bgcolor. Otherwise, set nullptr.
* Must not use nsGkAtoms::_empty here.
* @param aPrincipal Set subject principal if it may be called by JS. If
* set to nullptr, will be treated as called by system.
*/
MOZ_CAN_RUN_SCRIPT nsresult RemoveInlinePropertyAsAction(
nsStaticAtom& aHTMLProperty, nsStaticAtom* aAttribute,
nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult
RemoveAllInlinePropertiesAsAction(nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult
IncreaseFontSizeAsAction(nsIPrincipal* aPrincipal = nullptr);
MOZ_CAN_RUN_SCRIPT nsresult
DecreaseFontSizeAsAction(nsIPrincipal* aPrincipal = nullptr);
/**
* GetFontColorState() returns foreground color information in first
* range of Selection.
* If first range of Selection is collapsed and there is a cache of style for
* new text, aIsMixed is set to false and aColor is set to the cached color.
* If first range of Selection is collapsed and there is no cached color,
* this returns the color of the node, aIsMixed is set to false and aColor is
* set to the color.
* If first range of Selection is not collapsed, this collects colors of
* each node in the range. If there are two or more colors, aIsMixed is set
* to true and aColor is truncated. If only one color is set to all of the
* range, aIsMixed is set to false and aColor is set to the color.
* If there is no Selection ranges, aIsMixed is set to false and aColor is
* truncated.
*
* @param aIsMixed Must not be nullptr. This is set to true
* if there is two or more colors in first
* range of Selection.
* @param aColor Returns the color if only one color is set to
* all of first range in Selection. Otherwise,
* returns empty string.
* @return Returns error only when illegal cases, e.g.,
* Selection instance has gone, first range
* Selection is broken.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
GetFontColorState(bool* aIsMixed, nsAString& aColor);
/**
* SetComposerCommandsUpdater() sets or unsets mComposerCommandsUpdater.
* This will crash in debug build if the editor already has an instance
* but called with another instance.
*/
void SetComposerCommandsUpdater(
ComposerCommandsUpdater* aComposerCommandsUpdater) {
MOZ_ASSERT(!aComposerCommandsUpdater || !mComposerCommandsUpdater ||
aComposerCommandsUpdater == mComposerCommandsUpdater);
mComposerCommandsUpdater = aComposerCommandsUpdater;
}
nsStaticAtom& DefaultParagraphSeparatorTagName() const {
return HTMLEditor::ToParagraphSeparatorTagName(mDefaultParagraphSeparator);
}
ParagraphSeparator GetDefaultParagraphSeparator() const {
return mDefaultParagraphSeparator;
}
void SetDefaultParagraphSeparator(ParagraphSeparator aSep) {
mDefaultParagraphSeparator = aSep;
}
static nsStaticAtom& ToParagraphSeparatorTagName(
ParagraphSeparator aSeparator) {
switch (aSeparator) {
case ParagraphSeparator::div:
return *nsGkAtoms::div;
case ParagraphSeparator::p:
return *nsGkAtoms::p;
case ParagraphSeparator::br:
return *nsGkAtoms::br;
default:
MOZ_ASSERT_UNREACHABLE("New paragraph separator isn't handled here");
return *nsGkAtoms::div;
}
}
/**
* Modifies the table containing the selection according to the
* activation of an inline table editing UI element
* @param aUIAnonymousElement [IN] the inline table editing UI element
*/
MOZ_CAN_RUN_SCRIPT nsresult
DoInlineTableEditingAction(const Element& aUIAnonymousElement);
/**
* GetInclusiveAncestorByTagName() looks for an element node whose name
* matches aTagName from aNode or anchor node of Selection to <body> element.
*
* @param aTagName The tag name which you want to look for.
* Must not be nsGkAtoms::_empty.
* If nsGkAtoms::list, the result may be <ul>, <ol> or
* <dl> element.
* If nsGkAtoms::td, the result may be <td> or <th>.
* If nsGkAtoms::href, the result may be <a> element
* which has "href" attribute with non-empty value.
* If nsGkAtoms::anchor, the result may be <a> which
* has "name" attribute with non-empty value.
* @param aContent Start node to look for the result.
* @return If an element which matches aTagName, returns
* an Element. Otherwise, nullptr.
*/
Element* GetInclusiveAncestorByTagName(const nsStaticAtom& aTagName,
nsIContent& aContent) const;
/**
* Get an active editor's editing host in DOM window. If this editor isn't
* active in the DOM window, this returns NULL.
*/
enum class LimitInBodyElement { No, Yes };
Element* GetActiveEditingHost(
LimitInBodyElement aLimitInBodyElement = LimitInBodyElement::Yes) const;
/**
* Retruns true if we're in designMode.
*/
bool IsInDesignMode() const {
Document* document = GetDocument();
return document && document->HasFlag(NODE_IS_EDITABLE);
}
/**
* Basically, this always returns true if we're for `contenteditable` or
* `designMode` editor in web apps. However, e.g., Composer of SeaMonkey
* can make the editor not tabbable.
*/
bool IsTabbable() const { return IsInteractionAllowed(); }
/**
* NotifyEditingHostMaybeChanged() is called when new element becomes
* contenteditable when the document already had contenteditable elements.
*/
void NotifyEditingHostMaybeChanged();
/** Insert a string as quoted text
* (whose representation is dependant on the editor type),
* replacing the selected text (if any).
*
* @param aQuotedText The actual text to be quoted
* @parem aNodeInserted Return the node which was inserted.
*/
MOZ_CAN_RUN_SCRIPT // USED_BY_COMM_CENTRAL
nsresult
InsertAsQuotation(const nsAString& aQuotedText, nsINode** aNodeInserted);
/**
* Inserts a plaintext string at the current location,
* with special processing for lines beginning with ">",
* which will be treated as mail quotes and inserted
* as plaintext quoted blocks.
* If the selection is not collapsed, the selection is deleted
* and the insertion takes place at the resulting collapsed selection.
*
* @param aString the string to be inserted
*/
MOZ_CAN_RUN_SCRIPT nsresult
InsertTextWithQuotations(const nsAString& aStringToInsert);
MOZ_CAN_RUN_SCRIPT nsresult InsertHTMLAsAction(
const nsAString& aInString, nsIPrincipal* aPrincipal = nullptr);
/**
* Refresh positions of resizers. If you change size of target of resizers,
* you need to refresh position of resizers with calling this.
*/
MOZ_CAN_RUN_SCRIPT nsresult RefreshResizers();
protected: // May be called by friends.
/****************************************************************************
* Some friend classes are allowed to call the following protected methods.
* However, those methods won't prepare caches of some objects which are
* necessary for them. So, if you call them from friend classes, you need
* to make sure that AutoEditActionDataSetter is created.
****************************************************************************/
/**
* InsertBRElementWithTransaction() creates a <br> element and inserts it
* before aPointToInsert. Then, tries to collapse selection at or after the
* new <br> node if aSelect is not eNone.
*
* @param aPointToInsert The DOM point where should be <br> node inserted
* before.
* @param aSelect If eNone, this won't change selection.
* If eNext, selection will be collapsed after
* the <br> element.
* If ePrevious, selection will be collapsed at
* the <br> element.
* @return The new <br> node. If failed to create new
* <br> node, returns error.
*/
MOZ_CAN_RUN_SCRIPT Result<RefPtr<Element>, nsresult>
InsertBRElementWithTransaction(const EditorDOMPoint& aPointToInsert,
EDirection aSelect = eNone);
/**
* DeleteNodeWithTransaction() removes aContent from the DOM tree if it's
* modifiable.
*
* @param aContent The node to be removed from the DOM tree.
*/
MOZ_CAN_RUN_SCRIPT nsresult
DeleteNodeWithTransaction(nsIContent& aContent) final;
/**
* DeleteTextWithTransaction() removes text in the range from aTextNode if
* it's modifiable. Note that this not an override of same method of
* EditorBase.
*
* @param aTextNode The text node which should be modified.
* @param aOffset Start offset of removing text in aTextNode.
* @param aLength Length of removing text.
*/
MOZ_CAN_RUN_SCRIPT nsresult DeleteTextWithTransaction(dom::Text& aTextNode,
uint32_t aOffset,
uint32_t aLength);
/**
* ReplaceTextWithTransaction() replaces text in the range with
* aStringToInsert.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult ReplaceTextWithTransaction(
dom::Text& aTextNode, uint32_t aOffset, uint32_t aLength,
const nsAString& aStringToInsert);
/**
* InsertTextWithTransaction() inserts aStringToInsert at aPointToInsert.
*/
MOZ_CAN_RUN_SCRIPT nsresult InsertTextWithTransaction(
Document& aDocument, const nsAString& aStringToInsert,
const EditorRawDOMPoint& aPointToInsert,
EditorRawDOMPoint* aPointAfterInsertedString = nullptr) final;
/**
* CopyLastEditableChildStyles() clones inline container elements into
* aPreviousBlock to aNewBlock to keep using same style in it.
*
* @param aPreviousBlock The previous block element. All inline
* elements which are last sibling of each level
* are cloned to aNewBlock.
* @param aNewBlock New block container element.
* @param aNewBRElement If this method creates a new <br> element for
* placeholder, this is set to the new <br>
* element.
*/
MOZ_CAN_RUN_SCRIPT nsresult CopyLastEditableChildStylesWithTransaction(
Element& aPreviousBlock, Element& aNewBlock,
RefPtr<Element>* aNewBRElement);
/**
* RemoveBlockContainerWithTransaction() removes aElement from the DOM tree
* but moves its all children to its parent node and if its parent needs <br>
* element to have at least one line-height, this inserts <br> element
* automatically.
*
* @param aElement Block element to be removed.
*/
MOZ_CAN_RUN_SCRIPT nsresult
RemoveBlockContainerWithTransaction(Element& aElement);
Element* GetEditorRoot() const final;
MOZ_CAN_RUN_SCRIPT nsresult RemoveAttributeOrEquivalent(
Element* aElement, nsAtom* aAttribute, bool aSuppressTransaction) final;
MOZ_CAN_RUN_SCRIPT nsresult SetAttributeOrEquivalent(
Element* aElement, nsAtom* aAttribute, const nsAString& aValue,
bool aSuppressTransaction) final;
using EditorBase::RemoveAttributeOrEquivalent;
using EditorBase::SetAttributeOrEquivalent;
/**
* Returns container element of ranges in Selection. If Selection is
* collapsed, returns focus container node (or its parent element).
* If Selection selects only one element node, returns the element node.
* If Selection is only one range, returns common ancestor of the range.
* XXX If there are two or more Selection ranges, this returns parent node
* of start container of a range which starts with different node from
* start container of the first range.
*/
Element* GetSelectionContainerElement() const;
/**
* DeleteTableCellContentsWithTransaction() removes any contents in cell
* elements. If two or more cell elements are selected, this removes
* all selected cells' contents. Otherwise, this removes contents of
* a cell which contains first selection range. This does not return
* error even if selection is not in cell element, just does nothing.
*/
MOZ_CAN_RUN_SCRIPT nsresult DeleteTableCellContentsWithTransaction();
/**
* extracts an element from the normal flow of the document and
* positions it, and puts it back in the normal flow.
* @param aElement [IN] the element
* @param aEnabled [IN] true to absolutely position the element,
* false to put it back in the normal flow
*/
MOZ_CAN_RUN_SCRIPT nsresult SetPositionToAbsoluteOrStatic(Element& aElement,
bool aEnabled);
/**
* adds aChange to the z-index of an arbitrary element.
* @param aElement [IN] the element
* @param aChange [IN] relative change to apply to current z-index of
* the element
* @return The new z-index of the element
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT Result<int32_t, nsresult>
AddZIndexWithTransaction(nsStyledElement& aStyledElement, int32_t aChange);
/**
* Join together any adjacent editable text nodes in the range.
*/
MOZ_CAN_RUN_SCRIPT nsresult CollapseAdjacentTextNodes(nsRange& aRange);
static bool HasAttributes(Element* aElement) {
MOZ_ASSERT(aElement);
uint32_t attrCount = aElement->GetAttrCount();
return attrCount > 1 ||
(1 == attrCount &&
!aElement->GetAttrNameAt(0)->Equals(nsGkAtoms::mozdirty));
}
static dom::Element* GetLinkElement(nsINode* aNode);
/**
* Helper routines for font size changing.
*/
enum class FontSize { incr, decr };
MOZ_CAN_RUN_SCRIPT nsresult
RelativeFontChangeOnTextNode(FontSize aDir, Text& aTextNode,
uint32_t aStartOffset, uint32_t aEndOffset);
MOZ_CAN_RUN_SCRIPT nsresult SetInlinePropertyOnNode(nsIContent& aNode,
nsAtom& aProperty,
nsAtom* aAttribute,
const nsAString& aValue);
/**
* SplitAncestorStyledInlineElementsAtRangeEdges() splits all ancestor inline
* elements in the block at both aStartPoint and aEndPoint if given style
* matches with some of them.
*
* @param aStartPoint Start of range to split ancestor inline elements.
* @param aEndPoint End of range to split ancestor inline elements.
* @param aProperty The style tag name which you want to split. Set
* nullptr if you want to split any styled elements.
* @param aAttribute Attribute name if aProperty has some styles like
* nsGkAtoms::font.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT SplitRangeOffResult
SplitAncestorStyledInlineElementsAtRangeEdges(
const EditorDOMPoint& aStartPoint, const EditorDOMPoint& aEndPoint,
nsAtom* aProperty, nsAtom* aAttribute);
/**
* SplitAncestorStyledInlineElementsAt() splits ancestor inline elements at
* aPointToSplit if specified style matches with them.
*
* @param aPointToSplit The point to split style at.
* @param aProperty The style tag name which you want to split.
* Set nullptr if you want to split any styled
* elements.
* @param aAttribute Attribute name if aProperty has some styles
* like nsGkAtoms::font.
* @return The result of SplitNodeDeepWithTransaction()
* with topmost split element. If this didn't
* find inline elements to be split, Handled()
* returns false.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT SplitNodeResult
SplitAncestorStyledInlineElementsAt(const EditorDOMPoint& aPointToSplit,
nsAtom* aProperty, nsAtom* aAttribute);
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult GetInlinePropertyBase(
nsAtom& aHTMLProperty, nsAtom* aAttribute, const nsAString* aValue,
bool* aFirst, bool* aAny, bool* aAll, nsAString* outValue) const;
/**
* ClearStyleAt() splits parent elements to remove the specified style.
* If this splits some parent elements at near their start or end, such
* empty elements will be removed. Then, remove the specified style
* from the point and returns DOM point to put caret.
*
* @param aPoint The point to clear style at.
* @param aProperty An HTML tag name which represents a style.
* Set nullptr if you want to clear all styles.
* @param aAttribute Attribute name if aProperty has some styles like
* nsGkAtoms::font.
* @param aSpecifiedStyle Whether the class and style attributes should
* be preserved or discareded.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT EditResult
ClearStyleAt(const EditorDOMPoint& aPoint, nsAtom* aProperty,
nsAtom* aAttribute, SpecifiedStyle aSpecifiedStyle);
MOZ_CAN_RUN_SCRIPT nsresult SetPositionToAbsolute(Element& aElement);
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
SetPositionToStatic(Element& aElement);
/**
* OnModifyDocument() is called when the editor is changed. This should
* be called only by runnable in HTMLEditor::OnDocumentModified() to call
* HTMLEditor::OnModifyDocument() with AutoEditActionDataSetter instance.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult OnModifyDocument();
/**
* DoSplitNode() creates a new node (left node) identical to an existing
* node (right node), and split the contents between the same point in both
* nodes.
*
* @param aStartOfRightNode The point to split. Its container will be
* the right node, i.e., become the new node's
* next sibling. And the point will be start
* of the right node.
* @param aNewLeftNode The new node called as left node, so, this
* becomes the container of aPointToSplit's
* previous sibling.
* @param aError Must have not already failed.
* If succeed to insert aLeftNode before the
* right node and remove unnecessary contents
* (and collapse selection at end of the left
* node if necessary), returns no error.
* Otherwise, an error.
*/
MOZ_CAN_RUN_SCRIPT void DoSplitNode(const EditorDOMPoint& aStartOfRightNode,
nsIContent& aNewLeftNode,
ErrorResult& aError);
/**
* DoJoinNodes() merges contents in aContentToJoin to aContentToKeep and
* remove aContentToJoin from the DOM tree. aContentToJoin and aContentToKeep
* must have same parent, aParent. Additionally, if one of aContentToJoin or
* aContentToKeep is a text node, the other must be a text node.
*
* @param aContentToKeep The node that will remain after the join.
* @param aContentToJoin The node that will be joined with aContentToKeep.
* There is no requirement that the two nodes be of the
* same type.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
DoJoinNodes(nsIContent& aContentToKeep, nsIContent& aContentToJoin);
/**
* Routines for managing the preservation of selection across
* various editor actions.
*/
bool ArePreservingSelection() const;
void PreserveSelectionAcrossActions();
MOZ_CAN_RUN_SCRIPT nsresult RestorePreservedSelection();
void StopPreservingSelection();
protected: // edit sub-action handler
/**
* CanHandleHTMLEditSubAction() checks whether there is at least one
* selection range or not, and whether the first range is editable.
* If it's not editable, `Canceled()` of the result returns true.
* If `Selection` is in odd situation, returns an error.
*
* XXX I think that `IsSelectionEditable()` is better name, but it's already
* in `EditorBase`...
*/
EditActionResult CanHandleHTMLEditSubAction() const;
/**
* EnsureCaretNotAfterInvisibleBRElement() makes sure that caret is NOT after
* padding `<br>` element for preventing insertion after padding `<br>`
* element at empty last line.
* NOTE: This method should be called only when `Selection` is collapsed
* because `Selection` is a pain to work with when not collapsed.
* (no good way to extend start or end of selection), so we need to
* ignore those types of selections.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
EnsureCaretNotAfterInvisibleBRElement();
/**
* MaybeCreatePaddingBRElementForEmptyEditor() creates padding <br> element
* for empty editor if there is no children.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
MaybeCreatePaddingBRElementForEmptyEditor();
/**
* EnsureNoPaddingBRElementForEmptyEditor() removes padding <br> element
* for empty editor if there is.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
EnsureNoPaddingBRElementForEmptyEditor();
/**
* ReflectPaddingBRElementForEmptyEditor() scans the tree from the root
* element and sets mPaddingBRElementForEmptyEditor if exists, or otherwise
* nullptr. Can be used to manage undo/redo.
*/
[[nodiscard]] nsresult ReflectPaddingBRElementForEmptyEditor();
/**
* PrepareInlineStylesForCaret() consider inline styles from top level edit
* sub-action and setting it to `mTypeInState` and clear inline style cache
* if necessary.
* NOTE: This method should be called only when `Selection` is collapsed.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult PrepareInlineStylesForCaret();
[[nodiscard]] MOZ_CAN_RUN_SCRIPT EditActionResult HandleInsertText(
EditSubAction aEditSubAction, const nsAString& aInsertionString,
SelectionHandling aSelectionHandling) final;
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult InsertDroppedDataTransferAsAction(
AutoEditActionDataSetter& aEditActionData,
dom::DataTransfer& aDataTransfer, const EditorDOMPoint& aDroppedAt,
nsIPrincipal* aSourcePrincipal) final;
/**
* GetInlineStyles() retrieves the style of aNode and modifies each item of
* aStyleCacheArray. This might cause flushing layout at retrieving computed
* values of CSS properties.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
GetInlineStyles(nsIContent& aContent, AutoStyleCacheArray& aStyleCacheArray);
/**
* CacheInlineStyles() caches style of aContent into mCachedInlineStyles of
* TopLevelEditSubAction. This may cause flushing layout at retrieving
* computed value of CSS properties.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
CacheInlineStyles(nsIContent& aContent);
/**
* ReapplyCachedStyles() restores some styles which are disappeared during
* handling edit action and it should be restored. This may cause flushing
* layout at retrieving computed value of CSS properties.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult ReapplyCachedStyles();
/**
* CreateStyleForInsertText() sets CSS properties which are stored in
* TypeInState to proper element node.
* XXX This modifies Selection, but should return insertion point instead.
*
* @param aAbstractRange Set current selection range where new text
* should be inserted.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
CreateStyleForInsertText(const dom::AbstractRange& aAbstractRange);
/**
* GetMostAncestorMailCiteElement() returns most-ancestor mail cite element.
* "mail cite element" is <pre> element when it's in plaintext editor mode
* or an element with which calling HTMLEditUtils::IsMailCite() returns true.
*
* @param aNode The start node to look for parent mail cite elements.
*/
Element* GetMostAncestorMailCiteElement(nsINode& aNode) const;
/**
* SplitMailCiteElements() splits mail-cite elements at start of Selection if
* Selection starts from inside a mail-cite element. Of course, if it's
* necessary, this inserts <br> node to new left nodes or existing right
* nodes.
* XXX This modifies Selection, but should return SplitNodeResult() instead.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT EditActionResult
SplitMailCiteElements(const EditorDOMPoint& aPointToSplit);
/**
* HandleInsertBRElement() inserts a <br> element into aInsertToBreak.
* This may split container elements at the point and/or may move following
* <br> element to immediately after the new <br> element if necessary.
* XXX This modifies Selection, but should return CreateElementResult instead.
*
* @param aInsertToBreak The point where new <br> element will be
* inserted before.
* @param aEditingHost Current active editing host.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult HandleInsertBRElement(
const EditorDOMPoint& aInsertToBreak, Element& aEditingHost);
/**
* HandleInsertLinefeed() inserts a linefeed character into aInsertToBreak.
*
* @param aInsertToBreak The point where new linefeed character will be
* inserted before.
* @param aEditingHost Current active editing host.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult HandleInsertLinefeed(
const EditorDOMPoint& aInsertToBreak, Element& aEditingHost);
/**
* SplitParentInlineElementsAtRangeEdges() splits parent inline nodes at both
* start and end of aRangeItem. If this splits at every point, this modifies
* aRangeItem to point each split point (typically, right node).
*
* @param aRangeItem [in/out] One or two DOM points where should be
* split. Will be modified to split point if
* they're split.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
SplitParentInlineElementsAtRangeEdges(RangeItem& aRangeItem);
/**
* SplitParentInlineElementsAtRangeEdges(nsTArray<RefPtr<nsRange>>&) calls
* SplitParentInlineElementsAtRangeEdges(RangeItem&) for each range. Then,
* updates given range to keep edit target ranges as expected.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
SplitParentInlineElementsAtRangeEdges(
nsTArray<RefPtr<nsRange>>& aArrayOfRanges);
/**
* SplitElementsAtEveryBRElement() splits before all <br> elements in
* aMostAncestorToBeSplit. All <br> nodes will be moved before right node
* at splitting its parent. Finally, this returns left node, first <br>
* element, next left node, second <br> element... and right-most node.
*
* @param aMostAncestorToBeSplit Most-ancestor element which should
* be split.
* @param aOutArrayOfNodes First left node, first <br> element,
* Second left node, second <br> element,
* ...right-most node. So, all nodes
* in this list should be siblings (may be
* broken the relation by mutation event
* listener though). If first <br> element
* is first leaf node of
* aMostAncestorToBeSplit, starting from
* the first <br> element.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult SplitElementsAtEveryBRElement(
nsIContent& aMostAncestorToBeSplit,
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents);
/**
* MaybeSplitElementsAtEveryBRElement() calls SplitElementsAtEveryBRElement()
* for each given node when this needs to do that for aEditSubAction.
* If split a node, it in aArrayOfContents is replaced with split nodes and
* <br> elements.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult MaybeSplitElementsAtEveryBRElement(
nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents,
EditSubAction aEditSubAction);
/**
* CollectEditableChildren() collects child nodes of aNode (starting from
* first editable child, but may return non-editable children after it).
*
* @param aNode Parent node of retrieving children.
* @param aOutArrayOfContents [out] This method will inserts found children
* into this array.
* @param aIndexToInsertChildren Starting from this index, found
* children will be inserted to the array.
* @param aCollectListChildren If Yes, will collect children of list
* and list-item elements recursively.
* @param aCollectTableChildren If Yes, will collect children of table
* related elements recursively.
* @param aCollectNonEditableNodes If Yes, will collect found children
* even if they are not editable.
* @return Number of found children.
*/
enum class CollectListChildren { No, Yes };
enum class CollectTableChildren { No, Yes };
enum class CollectNonEditableNodes { No, Yes };
size_t CollectChildren(
nsINode& aNode, nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents,
size_t aIndexToInsertChildren, CollectListChildren aCollectListChildren,
CollectTableChildren aCollectTableChildren,
CollectNonEditableNodes aCollectNonEditableNodes) const;
/**
* SplitInlinessAndCollectEditTargetNodes() splits text nodes and inline
* elements around aArrayOfRanges. Then, collects edit target nodes to
* aOutArrayOfNodes. Finally, each edit target nodes is split at every
* <br> element in it.
* FYI: You can use SplitInlinesAndCollectEditTargetNodesInOneHardLine()
* or SplitInlinesAndCollectEditTargetNodesInExtendedSelectionRanges()
* instead if you want to call this with a hard line including
* specific DOM point or extended selection ranges.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
SplitInlinesAndCollectEditTargetNodes(
nsTArray<RefPtr<nsRange>>& aArrayOfRanges,
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents,
EditSubAction aEditSubAction,
CollectNonEditableNodes aCollectNonEditableNodes);
/**
* SplitTextNodesAtRangeEnd() splits text nodes if each range end is in
* middle of a text node.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
SplitTextNodesAtRangeEnd(nsTArray<RefPtr<nsRange>>& aArrayOfRanges);
/**
* CollectEditTargetNodes() collects edit target nodes in aArrayOfRanges.
* First, this collects all nodes in given ranges, then, modifies the
* result for specific edit sub-actions.
* FYI: You can use CollectEditTargetNodesInExtendedSelectionRanges() instead
* if you want to call this with extended selection ranges.
*/
nsresult CollectEditTargetNodes(
nsTArray<RefPtr<nsRange>>& aArrayOfRanges,
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents,
EditSubAction aEditSubAction,
CollectNonEditableNodes aCollectNonEditableNodes);
/**
* GetCurrentHardLineStartPoint() returns start point of hard line
* including aPoint. If the line starts after a `<br>` element, returns
* next sibling of the `<br>` element. If the line is first line of a block,
* returns point of the block.
* NOTE: The result may be point of editing host. I.e., the container may
* be outside of editing host.
*/
template <typename PT, typename RT>
EditorDOMPoint GetCurrentHardLineStartPoint(
const RangeBoundaryBase<PT, RT>& aPoint,
EditSubAction aEditSubAction) const;
/**
* GetCurrentHardLineEndPoint() returns end point of hard line including
* aPoint. If the line ends with a visible `<br>` element, returns the point
* after the `<br>` element. If the line ends with a preformatted linefeed,
* returns the point after the linefeed unless it's an invisible linebreak
* immediately before a block boundary. If the line ends with a block
* boundary, returns the block.
*/
template <typename PT, typename RT>
EditorDOMPoint GetCurrentHardLineEndPoint(
const RangeBoundaryBase<PT, RT>& aPoint) const;
/**
* CreateRangeIncludingAdjuscentWhiteSpaces() creates an nsRange instance
* which may be expanded from the given range to include adjuscent
* white-spaces. If this fails handling something, returns nullptr.
*/
already_AddRefed<nsRange> CreateRangeIncludingAdjuscentWhiteSpaces(
const dom::AbstractRange& aAbstractRange);
template <typename SPT, typename SRT, typename EPT, typename ERT>
already_AddRefed<nsRange> CreateRangeIncludingAdjuscentWhiteSpaces(
const RangeBoundaryBase<SPT, SRT>& aStartRef,
const RangeBoundaryBase<EPT, ERT>& aEndRef);
/**
* GetSelectionRangesExtendedToIncludeAdjuscentWhiteSpaces() collects
* selection ranges with extending to include adjuscent white-spaces
* of each range start and end.
*
* @param aOutArrayOfRanges [out] Always appended same number of ranges
* as Selection::RangeCount(). Must be empty
* when you call this.
*/
void GetSelectionRangesExtendedToIncludeAdjuscentWhiteSpaces(
nsTArray<RefPtr<nsRange>>& aOutArrayOfRanges);
/**
* CreateRangeExtendedToHardLineStartAndEnd() creates an nsRange instance
* which may be expanded to start/end of hard line at both edges of the given
* range. If this fails handling something, returns nullptr.
*/
already_AddRefed<nsRange> CreateRangeExtendedToHardLineStartAndEnd(
const dom::AbstractRange& aAbstractRange,
EditSubAction aEditSubAction) const;
template <typename SPT, typename SRT, typename EPT, typename ERT>
already_AddRefed<nsRange> CreateRangeExtendedToHardLineStartAndEnd(
const RangeBoundaryBase<SPT, SRT>& aStartRef,
const RangeBoundaryBase<EPT, ERT>& aEndRef,
EditSubAction aEditSubAction) const;
/**
* GetSelectionRangesExtendedToHardLineStartAndEnd() collects selection ranges
* with extending to start/end of hard line from each range start and end.
* XXX This means that same range may be included in the result.
*
* @param aOutArrayOfRanges [out] Always appended same number of ranges
* as Selection::RangeCount(). Must be empty
* when you call this.
*/
void GetSelectionRangesExtendedToHardLineStartAndEnd(
nsTArray<RefPtr<nsRange>>& aOutArrayOfRanges,
EditSubAction aEditSubAction);
/**
* SplitInlinesAndCollectEditTargetNodesInExtendedSelectionRanges() calls
* SplitInlinesAndCollectEditTargetNodes() with result of
* GetSelectionRangesExtendedToHardLineStartAndEnd(). See comments for these
* methods for the detail.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
SplitInlinesAndCollectEditTargetNodesInExtendedSelectionRanges(
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents,
EditSubAction aEditSubAction,
CollectNonEditableNodes aCollectNonEditableNodes) {
AutoTArray<RefPtr<nsRange>, 4> extendedSelectionRanges;
GetSelectionRangesExtendedToHardLineStartAndEnd(extendedSelectionRanges,
aEditSubAction);
nsresult rv = SplitInlinesAndCollectEditTargetNodes(
extendedSelectionRanges, aOutArrayOfContents, aEditSubAction,
aCollectNonEditableNodes);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"SplitInlinesAndCollectEditTargetNodes() failed");
return rv;
}
/**
* SplitInlinesAndCollectEditTargetNodesInOneHardLine() just calls
* SplitInlinesAndCollectEditTargetNodes() with result of calling
* CreateRangeExtendedToHardLineStartAndEnd() with aPointInOneHardLine.
* In other words, returns nodes in the hard line including
* `aPointInOneHardLine`. See the comments for these methods for the
* detail.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
SplitInlinesAndCollectEditTargetNodesInOneHardLine(
const EditorDOMPoint& aPointInOneHardLine,
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents,
EditSubAction aEditSubAction,
CollectNonEditableNodes aCollectNonEditableNodes) {
if (NS_WARN_IF(!aPointInOneHardLine.IsSet())) {
return NS_ERROR_INVALID_ARG;
}
RefPtr<nsRange> oneLineRange = CreateRangeExtendedToHardLineStartAndEnd(
aPointInOneHardLine.ToRawRangeBoundary(),
aPointInOneHardLine.ToRawRangeBoundary(), aEditSubAction);
if (!oneLineRange) {
// XXX It seems odd to create collapsed range for one line range...
ErrorResult error;
oneLineRange =
nsRange::Create(aPointInOneHardLine.ToRawRangeBoundary(),
aPointInOneHardLine.ToRawRangeBoundary(), error);
if (NS_WARN_IF(error.Failed())) {
return error.StealNSResult();
}
}
AutoTArray<RefPtr<nsRange>, 1> arrayOfLineRanges;
arrayOfLineRanges.AppendElement(oneLineRange);
nsresult rv = SplitInlinesAndCollectEditTargetNodes(
arrayOfLineRanges, aOutArrayOfContents, aEditSubAction,
aCollectNonEditableNodes);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"SplitInlinesAndCollectEditTargetNodes() failed");
return rv;
}
/**
* CollectEditTargetNodesInExtendedSelectionRanges() calls
* CollectEditTargetNodes() with result of
* GetSelectionRangesExtendedToHardLineStartAndEnd(). See comments for these
* methods for the detail.
*/
nsresult CollectEditTargetNodesInExtendedSelectionRanges(
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents,
EditSubAction aEditSubAction,
CollectNonEditableNodes aCollectNonEditableNodes) {
AutoTArray<RefPtr<nsRange>, 4> extendedSelectionRanges;
GetSelectionRangesExtendedToHardLineStartAndEnd(extendedSelectionRanges,
aEditSubAction);
nsresult rv =
CollectEditTargetNodes(extendedSelectionRanges, aOutArrayOfContents,
aEditSubAction, aCollectNonEditableNodes);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "CollectEditTargetNodes() failed");
return rv;
}
/**
* SelectBRElementIfCollapsedInEmptyBlock() helper method for
* CreateRangeIncludingAdjuscentWhiteSpaces() and
* CreateRangeExtendedToLineStartAndEnd(). If the given range is collapsed
* in a block and the block has only one `<br>` element, this makes
* aStartRef and aEndRef select the `<br>` element.
*/
template <typename SPT, typename SRT, typename EPT, typename ERT>
void SelectBRElementIfCollapsedInEmptyBlock(
RangeBoundaryBase<SPT, SRT>& aStartRef,
RangeBoundaryBase<EPT, ERT>& aEndRef) const;
/**
* GetChildNodesOf() returns all child nodes of aParent with an array.
*/
static void GetChildNodesOf(
nsINode& aParentNode,
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents) {
MOZ_ASSERT(aOutArrayOfContents.IsEmpty());
aOutArrayOfContents.SetCapacity(aParentNode.GetChildCount());
for (nsIContent* childContent = aParentNode.GetFirstChild(); childContent;
childContent = childContent->GetNextSibling()) {
aOutArrayOfContents.AppendElement(*childContent);
}
}
/**
* Try to get parent list element at `Selection`. This returns first find
* parent list element of common ancestor of ranges (looking for it from
* first range to last range).
*/
Element* GetParentListElementAtSelection() const;
/**
* MaybeExtendSelectionToHardLineEdgesForBlockEditAction() adjust Selection if
* there is only one range. If range start and/or end point is <br> node or
* something non-editable point, they should be moved to nearest text node or
* something where the other methods easier to handle edit action.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
MaybeExtendSelectionToHardLineEdgesForBlockEditAction();
/**
* MaybeSplitAncestorsForInsertWithTransaction() does nothing if container of
* aStartOfDeepestRightNode can have an element whose tag name is aTag.
* Otherwise, looks for an ancestor node which is or is in active editing
* host and can have an element whose name is aTag. If there is such
* ancestor, its descendants are split.
*
* Note that this may create empty elements while splitting ancestors.
*
* @param aTag The name of element to be inserted
* after calling this method.
* @param aStartOfDeepestRightNode The start point of deepest right node.
* This point must be descendant of
* active editing host.
* @return When succeeded, SplitPoint() returns
* the point to insert the element.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT SplitNodeResult
MaybeSplitAncestorsForInsertWithTransaction(
nsAtom& aTag, const EditorDOMPoint& aStartOfDeepestRightNode);
/**
* SplitRangeOffFromBlock() splits aBlockElement at two points, before
* aStartOfMiddleElement and after aEndOfMiddleElement. If they are very
* start or very end of aBlcok, this won't create empty block.
*
* @param aBlockElement A block element which will be split.
* @param aStartOfMiddleElement Start node of middle block element.
* @param aEndOfMiddleElement End node of middle block element.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT SplitRangeOffFromNodeResult
SplitRangeOffFromBlock(Element& aBlockElement,
nsIContent& aStartOfMiddleElement,
nsIContent& aEndOfMiddleElement);
/**
* SplitRangeOffFromBlockAndRemoveMiddleContainer() splits the nodes
* between aStartOfRange and aEndOfRange, then, removes the middle element
* and moves its content to where the middle element was.
*
* @param aBlockElement The node which will be split.
* @param aStartOfRange The first node which will be unwrapped
* from aBlockElement.
* @param aEndOfRange The last node which will be unwrapped from
* aBlockElement.
* @return The left content is new created left
* element of aBlockElement.
* The right content is split element,
* i.e., must be aBlockElement.
* The middle content is nullptr since
* removing it is the job of this method.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT SplitRangeOffFromNodeResult
SplitRangeOffFromBlockAndRemoveMiddleContainer(Element& aBlockElement,
nsIContent& aStartOfRange,
nsIContent& aEndOfRange);
/**
* MoveNodesIntoNewBlockquoteElement() inserts at least one <blockquote>
* element and moves nodes in aArrayOfContents into new <blockquote>
* elements.
* If aArrayOfContents includes a table related element except <table>,
* this calls itself recursively to insert <blockquote> into the cell.
*
* @param aArrayOfContents Nodes which will be moved into created
* <blockquote> elements.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult MoveNodesIntoNewBlockquoteElement(
nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents);
/**
* RemoveBlockContainerElements() removes all format blocks, table related
* element, etc in aArrayOfContents from the DOM tree.
* If aArrayOfContents has a format node, it will be removed and its contents
* will be moved to where it was.
* If aArrayOfContents has a table related element, <li>, <blockquote> or
* <div>, it will be removed and its contents will be moved to where it was.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult RemoveBlockContainerElements(
nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents);
/**
* CreateOrChangeBlockContainerElement() formats all nodes in aArrayOfContents
* with block elements whose name is aBlockTag.
* If aArrayOfContents has an inline element, a block element is created and
* the inline element and following inline elements are moved into the new
* block element.
* If aArrayOfContents has <br> elements, they'll be removed from the DOM
* tree and new block element will be created when there are some remaining
* inline elements.
* If aArrayOfContents has a block element, this calls itself with children
* of the block element. Then, new block element will be created when there
* are some remaining inline elements.
*
* @param aArrayOfContents Must be descendants of a node.
* @param aBlockTag The element name of new block elements.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult CreateOrChangeBlockContainerElement(
nsTArray<OwningNonNull<nsIContent>>& aArrayOfContents, nsAtom& aBlockTag);
/**
* FormatBlockContainerWithTransaction() is implementation of "formatBlock"
* command of `Document.execCommand()`. This applies block style or removes
* it.
* NOTE: This creates AutoSelectionRestorer. Therefore, even when this
* return NS_OK, editor may have been destroyed.
*
* @param aBlockType New block tag name.
* If nsGkAtoms::normal or nsGkAtoms::_empty,
* RemoveBlockContainerElements() will be called.
* If nsGkAtoms::blockquote,
* MoveNodesIntoNewBlockquoteElement() will be
* called. Otherwise,
* CreateOrChangeBlockContainerElement() will be
* called.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
FormatBlockContainerWithTransaction(nsAtom& aBlockType);
/**
* InsertBRElementIfHardLineIsEmptyAndEndsWithBlockBoundary() determines if
* aPointToInsert is start of a hard line and end of the line (i.e, the
* line is empty) and the line ends with block boundary, inserts a `<br>`
* element.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
InsertBRElementIfHardLineIsEmptyAndEndsWithBlockBoundary(
const EditorDOMPoint& aPointToInsert);
/**
* Insert a `<br>` element if aElement is a block element and empty.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
InsertBRElementIfEmptyBlockElement(Element& aElement);
/**
* Insert padding `<br>` element for empty last line into aElement if
* aElement is a block element and empty.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
InsertPaddingBRElementForEmptyLastLineIfNeeded(Element& aElement);
/**
* This method inserts a padding `<br>` element for empty last line if
* selection is collapsed and container of the range needs it.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
MaybeInsertPaddingBRElementForEmptyLastLineAtSelection();
/**
* SplitParagraph() splits the parent block, aParentDivOrP, at
* aStartOfRightNode.
*
* @param aParentDivOrP The parent block to be split. This must be <p>
* or <div> element.
* @param aStartOfRightNode The point to be start of right node after
* split. This must be descendant of
* aParentDivOrP.
* @param aNextBRNode Next <br> node if there is. Otherwise, nullptr.
* If this is not nullptr, the <br> node may be
* removed.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult
SplitParagraph(Element& aParentDivOrP,
const EditorDOMPoint& aStartOfRightNode, nsIContent* aBRNode);
/**
* HandleInsertParagraphInParagraph() does the right thing for Enter key
* press or 'insertParagraph' command in aParentDivOrP. aParentDivOrP will
* be split at start of first selection range.
*
* @param aParentDivOrP The parent block. This must be <p> or <div>
* element.
* @return Returns with NS_OK if this doesn't meat any
* unexpected situation. If this method tries to
* split the paragraph, marked as handled.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT EditActionResult
HandleInsertParagraphInParagraph(Element& aParentDivOrP);