Skip to content

Commit

Permalink
Allow a DOM constructor function to be passed to placeholder
Browse files Browse the repository at this point in the history
FEATURE: `placeholder` now allows a function that constructs the placedholder DOM to be passed
in, and uses `cloneNode` when a raw element is passed in, to prevent adding the same element
to multiple editors.

Closes codemirror/dev#1395
  • Loading branch information
marijnh committed Sep 20, 2024
1 parent d6c45ca commit 154c03b
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/placeholder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import {EditorView} from "./editorview"
import {clientRectsFor, flattenRect} from "./dom"

class Placeholder extends WidgetType {
constructor(readonly content: string | HTMLElement) { super() }
constructor(readonly content: string | HTMLElement | ((view: EditorView) => HTMLElement)) { super() }

toDOM() {
toDOM(view: EditorView) {
let wrap = document.createElement("span")
wrap.className = "cm-placeholder"
wrap.style.pointerEvents = "none"
wrap.appendChild(typeof this.content == "string" ? document.createTextNode(this.content) : this.content)
wrap.appendChild(
typeof this.content == "string" ? document.createTextNode(this.content) :
typeof this.content == "function" ? this.content(view) :
this.content.cloneNode(true))
if (typeof this.content == "string")
wrap.setAttribute("aria-label", "placeholder " + this.content)
else
Expand All @@ -35,7 +38,7 @@ class Placeholder extends WidgetType {

/// Extension that enables a placeholder—a piece of example content
/// to show when the editor is empty.
export function placeholder(content: string | HTMLElement): Extension {
export function placeholder(content: string | HTMLElement | ((view: EditorView) => HTMLElement)): Extension {
return ViewPlugin.fromClass(class {
placeholder: DecorationSet

Expand Down

0 comments on commit 154c03b

Please sign in to comment.