Skip to content

Safari/Chrome Desktop: Caret movement with up/down arrow keys breaks when DOM is constructed programmatically #513

@michael

Description

@michael

When the following markup is constructed programmatically...

<div class="editable" contenteditable="true">
	<h3 class="centered field empty" placeholder="Hello"></h3>
	<!---->
	<h3 class="centered field empty" placeholder="Hello"></h3>
	<!---->
	<h3 class="centered field empty" placeholder="Hello"></h3>
	<!---->
	<h3 class="centered field empty" placeholder="Hello"></h3>
	<!---->
</div>

with this code...

function create_text(value = "") {
	return document.createTextNode(value);
}
function comment() {
	var frag = document.createDocumentFragment();
	var start = document.createComment("");
	var anchor = create_text();
	frag.append(start, anchor);
	return frag;
}
function first_child(fragment) {
	return Object.getOwnPropertyDescriptor(
		Node.prototype,
		"firstChild",
	)?.get?.call(fragment);
}
function element(node, tag, render) {
	const el = document.createElement(tag);
	el.append(create_text());
	render(el);
	node.before(el);
}
function render(root) {
	for (let i = 0; i < 4; i++) {
		const f = comment();
		const n = first_child(f);
		element(n, "h3", (el) => {
			el.className = "centered field empty";
			el.setAttribute("placeholder", "Hello");
		});
		root.append(f);
	}
}
render(document.getElementById("root"));

... caret movement breaks.

See Repro: https://w3c.github.io/editing/repros/512.html

Also see this issue in Svelte for context: sveltejs/svelte#17164

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions