Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Insert HTML from text #2732

Closed
Alex-Brines opened this issue Jun 27, 2024 · 2 comments
Closed

Insert HTML from text #2732

Alex-Brines opened this issue Jun 27, 2024 · 2 comments

Comments

@Alex-Brines
Copy link

Hello, I am implementing a functionality which, from a text in HTML format, inserts said text into the editor, where the cursor is. Based on previous Issues I have created the following code:

export function insertHTML(editor: IEditor, html: string): void {
    editor.focus();
    editor.formatContentModel(model => {
        const selections = getSelectedSegmentsAndParagraphs(model, false);

        if (selections.length == 1 && selections[0][0].segmentType == 'SelectionMarker' && selections[0][1]) {
            mutateSegment(selections[0][1], selections[0][0], (_, para, index) => {

                const element = getVirtualElement(html);
                const general = createGeneralSegment(element);

                para.segments.splice(index, 0, general)
            });

            return true;
        } else {
            return false;
        }
    });
}
function getVirtualElement(html: string):HTMLElement {
    const span = document.createElement("span");
    span.innerHTML = html;

    if (span.children.length == 1 && span.children[0].nodeType === 1) {
        return <HTMLElement>span.children[0];
    } else {
        return span;
    }
}

The problem is that it doesn't work as I expect:
1.- If it is just text, do not insert it
2.- If it is an HTML code of the following form <a href="#">Hello</a> it does not insert the internal text (Hello).

@BryanValverdeU
Copy link
Contributor

Hello Alex,

I believe a possible fix for this is to transform the html to model and then call the mergeModel API.
Something like:

import { createModelFromHtml } from 'roosterjs-content-model-core';
import { mergeModel } from 'roosterjs-content-model-dom';

        editor.focus();
        const modelToInsert = createModelFromHtml(editor.getTrustedHTMLHandler()(html));
        editor.formatContentModel(model => {
            mergeModel(model, modelToInsert);
            return true;
        });

@Alex-Brines
Copy link
Author

Thank you!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants