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

feat: Editor option to customize placeholders #503

Merged
merged 7 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 3 additions & 31 deletions packages/core/src/editor/Block.css
Original file line number Diff line number Diff line change
Expand Up @@ -301,45 +301,17 @@ NESTED BLOCKS
}

/* PLACEHOLDERS*/

.bn-is-empty .bn-inline-content:before,
.bn-is-filter .bn-inline-content:before {
/* TODO: Move to extension? */
.bn-inline-content:has(> .ProseMirror-trailingBreak):before {
/*float: left; */
content: "";
pointer-events: none;
height: 0;
/* width: 0; */
position: absolute;
font-style: italic;
}

/* TODO: would be nicer if defined from code */

.bn-block-content.bn-is-empty.bn-has-anchor .bn-inline-content:before {
content: "Enter text or type '/' for commands";
}

.bn-block-content.bn-is-filter.bn-has-anchor .bn-inline-content:before {
content: "Type to filter";
}

.bn-block-content[data-content-type="heading"].bn-is-empty
.bn-inline-content:before {
content: "Heading";
}

.bn-block-content[data-content-type="bulletListItem"].bn-is-empty
.bn-inline-content:before,
.bn-block-content[data-content-type="numberedListItem"].bn-is-empty
.bn-inline-content:before {
content: "List";
}

.bn-is-empty
.bn-block-content[data-content-type="captionedImage"]
.bn-inline-content:before {
content: "Caption";
}
/* TODO: should this be here? */

/* TEXT COLORS */
[data-text-color="gray"] {
Expand Down
11 changes: 11 additions & 0 deletions packages/core/src/editor/BlockNoteEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ export type BlockNoteEditorOptions<
> = {
// TODO: Figure out if enableBlockNoteExtensions/disableHistoryExtension are needed and document them.
enableBlockNoteExtensions: boolean;

placeholder: Record<
string | "default" | "addBlock",
| string
| {
placeholder: string;
mustBeFocused: boolean;
}
>;

/**
*
* (couldn't fix any type, see https://github.com/TypeCellOS/BlockNote/pull/191#discussion_r1210708771)
Expand Down Expand Up @@ -301,6 +311,7 @@ export class BlockNoteEditor<

const extensions = getBlockNoteExtensions({
editor: this,
placeholder: newOptions.placeholder,
domAttributes: newOptions.domAttributes || {},
blockSchema: this.blockSchema,
blockSpecs: newOptions.blockSpecs,
Expand Down
14 changes: 12 additions & 2 deletions packages/core/src/editor/BlockNoteExtensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ export const getBlockNoteExtensions = <
S extends StyleSchema
>(opts: {
editor: BlockNoteEditor<BSchema, I, S>;
placeholder?: Record<
string | "default" | "addBlock",
| string
| {
placeholder: string;
mustBeFocused: boolean;
}
>;
domAttributes: Partial<BlockNoteDOMAttributes>;
blockSchema: BSchema;
blockSpecs: BlockSpecs;
Expand Down Expand Up @@ -66,8 +74,10 @@ export const getBlockNoteExtensions = <

// DropCursor,
Placeholder.configure({
includeChildren: true,
showOnlyCurrent: false,
// TODO: This shorthand is kind of ugly
...(opts.placeholder !== undefined
? { placeholder: opts.placeholder }
: {}),
}),
UniqueID.configure({
types: ["blockContainer"],
Expand Down
196 changes: 110 additions & 86 deletions packages/core/src/extensions/Placeholder/PlaceholderExtension.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Editor, Extension } from "@tiptap/core";
import { Node as ProsemirrorNode } from "prosemirror-model";
import { Extension } from "@tiptap/core";
import { Plugin, PluginKey } from "prosemirror-state";
import { Decoration, DecorationSet } from "prosemirror-view";
import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin";
Expand All @@ -14,115 +13,140 @@ const PLUGIN_KEY = new PluginKey(`blocknote-placeholder`);
*
*/
export interface PlaceholderOptions {
emptyEditorClass: string;
emptyNodeClass: string;
isFilterClass: string;
hasAnchorClass: string;
placeholder:
| ((PlaceholderProps: {
editor: Editor;
node: ProsemirrorNode;
pos: number;
hasAnchor: boolean;
}) => string)
| string;
showOnlyWhenEditable: boolean;
showOnlyCurrent: boolean;
includeChildren: boolean;
placeholder: Record<
string | "default" | "addBlock",
| string
| {
placeholder: string;
mustBeFocused: boolean;
}
>;
}

export const Placeholder = Extension.create<PlaceholderOptions>({
name: "placeholder",

addOptions() {
return {
emptyEditorClass: "bn-is-editor-empty",
emptyNodeClass: "bn-is-empty",
isFilterClass: "bn-is-filter",
hasAnchorClass: "bn-has-anchor",
placeholder: "Write something …",
showOnlyWhenEditable: true,
showOnlyCurrent: true,
includeChildren: false,
placeholder: {
default: "Enter text or type '/' for commands",
addBlock: "Type to filter",
heading: {
placeholder: "Heading",
mustBeFocused: false,
matthewlipski marked this conversation as resolved.
Show resolved Hide resolved
},
bulletListItem: {
placeholder: "List",
mustBeFocused: false,
},
numberedListItem: {
placeholder: "List",
mustBeFocused: false,
},
},
matthewlipski marked this conversation as resolved.
Show resolved Hide resolved
};
},

addProseMirrorPlugins() {
const styleEl = document.createElement("style");
matthewlipski marked this conversation as resolved.
Show resolved Hide resolved

// Append <style> element to <head>
document.head.appendChild(styleEl);

// Grab style element's sheet
const styleSheet = styleEl.sheet!;

const getBaseSelector = (additionalSelectors = "") =>
`.bn-block-content${additionalSelectors} .bn-inline-content:has(> .ProseMirror-trailingBreak):before`;

const getSelector = (
blockType: string | "default" | "addBlock",
mustBeFocused = true
) => {
const mustBeFocusedSelector = mustBeFocused
? `[data-is-empty-and-focused]`
: ``;

if (blockType === "default") {
return getBaseSelector(mustBeFocusedSelector);
}

if (blockType === "addBlock") {
const addBlockSelector = "[data-is-filter]";
return getBaseSelector(addBlockSelector);
}

const blockTypeSelector = `[data-content-type="${blockType}"]`;
return getBaseSelector(mustBeFocusedSelector + blockTypeSelector);
};

for (const [blockType, placeholderRule] of Object.entries(
this.options.placeholder
)) {
const placeholder =
typeof placeholderRule === "string"
? placeholderRule
: placeholderRule.placeholder;
const mustBeFocused =
typeof placeholderRule === "string"
? true
: placeholderRule.mustBeFocused;

styleSheet.insertRule(
`${getSelector(blockType, mustBeFocused)}{ content: "${placeholder}"; }`
);

// For some reason, the placeholders which show when the block is focused
// take priority over ones which show depending on block type, so we need
// to make sure the block specific ones are also used when the block is
// focused.
if (!mustBeFocused) {
styleSheet.insertRule(
`${getSelector(blockType, true)}{ content: "${placeholder}"; }`
);
}
}

return [
new Plugin({
key: PLUGIN_KEY,
props: {
// TODO: maybe also add placeholder for empty document ("e.g.: start writing..")
decorations: (state) => {
const { doc, selection } = state;
// Get state of slash menu

// TODO: fix slash menu ("type to filter")
const menuState = slashMenuPluginKey.getState(state);
const active =
this.editor.isEditable || !this.options.showOnlyWhenEditable;
const { anchor } = selection;
const decorations: Decoration[] = [];
const isFilter =
matthewlipski marked this conversation as resolved.
Show resolved Hide resolved
menuState?.triggerCharacter === "" && menuState?.active;

const active = this.editor.isEditable;

if (!active) {
return;
}

doc.descendants((node, pos) => {
const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize;
const isEmpty = !node.isLeaf && !node.childCount;

if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {
const classes = [this.options.emptyNodeClass];

// TODO: Doesn't work?
if (this.editor.isEmpty) {
classes.push(this.options.emptyEditorClass);
}

if (hasAnchor) {
classes.push(this.options.hasAnchorClass);
}

// If slash menu is of drag type and active, show the filter placeholder
if (menuState?.triggerCharacter === "" && menuState?.active) {
classes.push(this.options.isFilterClass);
}
// using widget, didn't work (caret position bug)
// const decoration = Decoration.widget(
// pos + 1,
// () => {
// const el = document.createElement("span");
// el.innerText = "hello";
// return el;
// },
// { side: 0 }

// Code that sets variables / classes
// const ph =
// typeof this.options.placeholder === "function"
// ? this.options.placeholder({
// editor: this.editor,
// node,
// pos,
// hasAnchor,
// })
// : this.options.placeholder;
// const decoration = Decoration.node(pos, pos + node.nodeSize, {
// class: classes.join(" "),
// style: `--placeholder:'${ph.replaceAll("'", "\\'")}';`,
// "data-placeholder": ph,
// });

// Latest version, only set isEmpty and hasAnchor, rest is done via CSS

const decoration = Decoration.node(pos, pos + node.nodeSize, {
class: classes.join(" "),
});
decorations.push(decoration);
}

return this.options.includeChildren;
if (!selection.empty) {
return;
}

const $pos = selection.$anchor;
const node = $pos.parent;

if (node.content.size > 0) {
return null;
}

const before = $pos.before();

const attr = isFilter
? "data-is-filter"
matthewlipski marked this conversation as resolved.
Show resolved Hide resolved
: "data-is-empty-and-focused";
const dec = Decoration.node(before, before + node.nodeSize, {
[attr]: "true",
});

return DecorationSet.create(doc, decorations);
return DecorationSet.create(doc, [dec]);
},
},
}),
Expand Down
Loading