Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Feat(email): "Sent with Macro" signature for free users (#581)

dev-rb896c424cd0ee
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index ab3dda17a7..d67736c138 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -1,4 +1,7 @@
import { FormatRibbon } from '@block-channel/component/FormatRibbon';
+import { MacroSignatureButton } from '@block-email/component/MacroSignatureButton';
+import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';
+import { useHasPaidAccess } from '@core/auth';
import { useBlockId } from '@core/block';
import { BrightJoins } from '@core/component/BrightJoins';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
@@ -27,7 +30,11 @@ import Plus from '@icon/regular/plus.svg';
import TextAa from '@icon/regular/text-aa.svg';
import Trash from '@icon/regular/trash.svg';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
-import type { DocumentMentionInfo } from '@lexical-core';
+import {
+ $appendWatermarkNodeToLast,
+ $removeAllWatermarkNodes,
+ type DocumentMentionInfo,
+} from '@lexical-core';
import { logger } from '@observability';
import { useSendMessageMutation } from '@queries/email/thread';
import { emailClient } from '@service-email/client';
@@ -236,6 +243,7 @@ export function BaseInput(props: {
const DRAFT_DEBOUNCE_MS = 1000;
function collectDraft(): Omit<MessageToSend, 'link_id'> | null {
+ $removeAllWatermarkNodes(editor());
const prepared = prepareEmailBody(editor());
if (!prepared) {
logger.error(
@@ -377,6 +385,8 @@ export function BaseInput(props: {
});
});
+ const hasPaidAccess = useHasPaidAccess();
+
// Set up hotkey scope for the compose message component
const [attachComposeHotkeys, composeHotkeyScope] =
useHotkeyDOMScope('compose-message');
@@ -420,7 +430,17 @@ export function BaseInput(props: {
linkId = maybeFallbackLinks[1].links[0].id;
}
- const prepared = prepareEmailBody(editor(), {
+ const _editor = editor();
+
+ // We handle cleaning up the signature after we've sent the request because
+ // otherwise the `bodyMacro` signal would update after the clean up call and
+ // not contain the signature in the request data
+ const cleanupWatermark = $appendWatermarkNodeToLast(
+ _editor,
+ !hasPaidAccess() ? MACRO_EMAIL_SIGNATURE : undefined
+ );
+
+ const prepared = prepareEmailBody(_editor, {
replyType: effectiveReplyType(),
replyingTo: props.replyingTo(),
});
@@ -447,6 +467,8 @@ export function BaseInput(props: {
link_id: linkId!,
},
});
+
+ cleanupWatermark();
};
const resetState = () => {
@@ -790,6 +812,7 @@ export function BaseInput(props: {
initialValue={props.preloadedBody}
initialHtml={props.preloadedHtml}
placeholder="Reply — @mention to share or cc people"
+ watermark={!hasPaidAccess() ? <MacroSignatureButton /> : undefined}
onChange={handleChange}
onDocumentMention={(item) => {
makeAttachmentPublic(item.id);
diff --git a/js/app/packages/block-email/component/ComposeEmailInput.tsx b/js/app/packages/block-email/component/ComposeEmailInput.tsx
index 770bed0c24..5d912ab061 100644
--- a/js/app/packages/block-email/component/ComposeEmailInput.tsx
+++ b/js/app/packages/block-email/component/ComposeEmailInput.tsx
@@ -1,11 +1,17 @@
import { useSplitPanel } from '@app/component/split-layout/layoutUtils';
import { FormatRibbon } from '@block-channel/component/FormatRibbon';
+import { MacroSignatureButton } from '@block-email/component/MacroSignatureButton';
+import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';
+import { useHasPaidAccess } from '@core/auth';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
import { IconButton } from '@core/component/IconButton';
import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';
import { fileDrop } from '@core/directive/fileDrop';
import TextAa from '@icon/regular/text-aa.svg';
-import type { DocumentMentionInfo } from '@lexical-core';
+import {
+ $appendWatermarkNodeToLast,
+ type DocumentMentionInfo,
+} from '@lexical-core';
import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
import ArrowFatLineUp from '@phosphor-icons/core/fill/arrow-fat-line-up-fill.svg?component-solid';
import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';
@@ -50,6 +56,8 @@ type ComposeEmailInputProps = {
};
export function ComposeEmailInput(props: ComposeEmailInputProps) {
+ const hasPaidAccess = useHasPaidAccess();
+
const [editor, setEditor] = createSignal<LexicalEditor>();
const [isDragging, setIsDragging] = createSignal<boolean>();
@@ -115,7 +123,17 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
let composeContainerRef: HTMLDivElement | undefined;
async function handleSend() {
- const prepared = prepareEmailBody(editor());
+ const _editor = editor();
+
+ // We handle cleaning up the signature after we've sent the request because
+ // otherwise the `bodyMacro` signal would update after the clean up call and
+ // not contain the signature in the request data
+ const cleanupWatermark = $appendWatermarkNodeToLast(
+ _editor,
+ !hasPaidAccess() ? MACRO_EMAIL_SIGNATURE : undefined
+ );
+
+ const prepared = prepareEmailBody(_editor, undefined);
if (!prepared) return;
const bodyMacro = content();
@@ -127,6 +145,8 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
raw: bodyMacro,
},
});
+
+ cleanupWatermark();
}
onMount(() => {
@@ -197,6 +217,7 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
class="text-sm break-words text-ink"
editable={() => !props.disabled}
placeholder="Use `@` to reference files"
+ watermark={!hasPaidAccess() ? <MacroSignatureButton /> : undefined}
onChange={setContent}
onFocusLeaveStart={(e) => {
e.preventDefault();
diff --git a/js/app/packages/block-email/component/MacroSignatureButton.tsx b/js/app/packages/block-email/component/MacroSignatureButton.tsx
new file mode 100644
index 0000000000..6f8c9b0513
--- /dev/null
+++ b/js/app/packages/block-email/component/MacroSignatureButton.tsx
@@ -0,0 +1,34 @@
+import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';
+import { useHasPaidAccess } from '@core/auth';
+import { Tooltip } from '@core/component/Tooltip';
+import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
+import { Show } from 'solid-js';
+
+interface MacroSignatureButtonProps {
+ signature?: string;
+}
+
+export const MacroSignatureButton = (props: MacroSignatureButtonProps) => {
+ const paywall = usePaywallState();
+ const hasPaidAccess = useHasPaidAccess();
+ return (
+ <Show when={!hasPaidAccess()}>
+ <Tooltip tooltip="Subscribe to remove watermark" class="w-fit">
+ <button
+ type="button"
+ class="hover:bg-hover pointer-events-all"
+ tabindex={-1}
+ // The text area uses non delegated events to capture on click and restore focus
+ // to the editor. We want to capture the click here so we can open the paywall.
+ // That's why we use `on:click` instead of `onClick`
+ on:click={(e) => {
+ e.stopImmediatePropagation();
+ paywall.showPaywall(PaywallKey.REMOVE_SIGNATURE);
+ }}
+ >
+ {props.signature ?? MACRO_EMAIL_SIGNATURE}
+ </button>
+ </Tooltip>
+ </Show>
+ );
+};
diff --git a/js/app/packages/block-email/constants.ts b/js/app/packages/block-email/constants.ts
index aaf168f1c3..30123ad126 100644
--- a/js/app/packages/block-email/constants.ts
+++ b/js/app/packages/block-email/constants.ts
@@ -1,3 +1,5 @@
export const URL_PARAMS = {
messageId: 'email_message_id',
};
+
+export const MACRO_EMAIL_SIGNATURE = '-- Sent with Macro';
diff --git a/js/app/packages/block-email/util/prepareEmailBody.ts b/js/app/packages/block-email/util/prepareEmailBody.ts
index 0fb82c24b3..b1f4ff8959 100644
--- a/js/app/packages/block-email/util/prepareEmailBody.ts
+++ b/js/app/packages/block-email/util/prepareEmailBody.ts
@@ -340,11 +340,9 @@ export function prepareEmailBody(
mentions: DocumentMentionInfo[];
} | null {
if (!editor) return null;
- let generatedHtml = '';
- let bodyHtml = '';
- let bodyText = '';
- editor.read(() => {
- generatedHtml = $generateHtmlFromNodes(editor);
+
+ const generatedHtml = editor.read(() => {
+ return $generateHtmlFromNodes(editor);
});
const parsed = new DOMParser().parseFromString(generatedHtml, 'text/html');
@@ -364,8 +362,8 @@ export function prepareEmailBody(
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/={1,}$/, '');
- bodyHtml = html;
- bodyText = parsed.body.firstChild?.textContent ?? '';
+ const bodyHtml = html;
+ const bodyText = parsed.body.firstChild?.textContent ?? '';
return { bodyHtml, bodyText, mentions };
}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
index 9dea8b3caf..1b592e9381 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
@@ -13,6 +13,7 @@ import {
type Accessor,
createEffect,
createSignal,
+ type JSX,
onCleanup,
onMount,
Show,
@@ -68,6 +69,7 @@ export interface MarkdownTextareaProps {
initialValue?: string;
initialHtml?: string;
placeholder?: string;
+ watermark?: JSX.Element;
type?: EditorType;
onEnter?: (e: KeyboardEvent, value: string) => boolean;
focusOnMount?: boolean;
@@ -281,6 +283,12 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
</p>
</div>
</Show>
+ <Show when={props.watermark}>
+ <div class="text-ink/50 mt-[1lh]" data-watermark>
+ {props.watermark}
+ </div>
+ </Show>
+
<MentionsMenu
editor={editor}
menu={mentionsMenuOperations}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index 8b1a1cdccf..35ff004a2d 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -20,6 +20,7 @@ import {
normalizedLanguage,
SupportedNodeTypes,
type UserMentionNode,
+ type WatermarkNode,
} from '@lexical-core';
import {
$getRoot,
@@ -59,6 +60,7 @@ import { DateMention as DateMentionDecorator } from '../decorator/DateMention';
import { DocumentMention as DocumentMentionDecorator } from '../decorator/DocumentMention';
import { Equation as EquationDecorator } from '../decorator/Equation';
import { UserMention as UserMentionDecorator } from '../decorator/UserMention';
+import { Watermark as WatermarkDecorator } from '../decorator/Watermark';
import { LinkWithPreview } from './LinkWithPreview';
type HeadingTag = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
@@ -215,7 +217,8 @@ function getTextClassName(
| UserMentionNode
| DocumentMentionNode
| ContactMentionNode
- | DateMentionNode,
+ | DateMentionNode
+ | WatermarkNode,
theme: EditorThemeClasses
): string {
const base = theme.text?.base ?? '';
@@ -295,6 +298,20 @@ const DocumentMention: RenderableEntity<DocumentMentionNode> = {
),
};
+const Watermark: RenderableEntity<WatermarkNode> = {
+ guard: (node: LexicalNode): node is WatermarkNode =>
+ node.__type === 'watermark',
+ render: (props) => (
+ <span class={getTextClassName(props.node, props.theme)}>
+ {WatermarkDecorator({
+ ...props.node.exportComponentProps(),
+ key: props.node.getKey(),
+ theme: props.theme,
+ })}
+ </span>
+ ),
+};
+
const ContactMention: RenderableEntity<ContactMentionNode> = {
guard: (node: LexicalNode): node is ContactMentionNode =>
node.__type === 'contact-mention',
@@ -582,6 +599,7 @@ const InlineEntities: Array<RenderableEntity> = [
DateMention,
HorizontalRule,
Equation,
+ Watermark,
] as const;
const Elements: RenderableElement[] = [
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/Watermark.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/Watermark.tsx
new file mode 100644
index 0000000000..2abf8080dc
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/Watermark.tsx
@@ -0,0 +1,14 @@
+import type { Component } from 'solid-js';
+import type { WatermarkDecoratorProps } from '../../../../../lexical-core/nodes/WatermarkNode';
+
+export const Watermark: Component<WatermarkDecoratorProps> = (props) => {
+ return (
+ <span
+ class="select-none macro-watermark-node text-ink/50"
+ inert
+ data-watermark
+ >
+ {props.content}
+ </span>
+ );
+};
diff --git a/js/app/packages/core/component/LexicalMarkdown/init.ts b/js/app/packages/core/component/LexicalMarkdown/init.ts
index 945b24d7b9..bc59920710 100644
--- a/js/app/packages/core/component/LexicalMarkdown/init.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/init.ts
@@ -10,6 +10,7 @@ import {
ImageNode,
UserMentionNode,
VideoNode,
+ WatermarkNode,
} from '@lexical-core';
import { clearDecorators, setDecorator } from '@lexical-core/decoratorRegistry';
import { ContactMention } from './component/decorator/ContactMention';
@@ -23,6 +24,7 @@ import { HtmlRender } from './component/decorator/HtmlRender';
import { MarkdownImage } from './component/decorator/MarkdownImage';
import { MarkdownVideo } from './component/decorator/MarkdownVideo';
import { UserMention } from './component/decorator/UserMention';
+import { Watermark } from './component/decorator/Watermark';
import { registerDiffNodeFactory } from './component/dom-factory/diff-factory';
/**
@@ -41,5 +43,6 @@ export function initializeLexical() {
setDecorator(VideoNode, MarkdownVideo);
setDecorator(EquationNode, Equation);
setDecorator(HtmlRenderNode, HtmlRender);
+ setDecorator(WatermarkNode, Watermark);
registerDiffNodeFactory();
}
diff --git a/js/app/packages/core/component/LexicalMarkdown/utils.ts b/js/app/packages/core/component/LexicalMarkdown/utils.ts
index 8a38f7a567..ff15e66a3f 100644
--- a/js/app/packages/core/component/LexicalMarkdown/utils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/utils.ts
@@ -20,6 +20,7 @@ import {
mergeRegister,
} from '@lexical/utils';
import {
+ $isWatermarkNode,
ALL_TRANSFORMERS,
EXTERNAL_TRANSFORMERS,
INITIALIZE_LOCAL_STATUS,
@@ -392,12 +393,18 @@ export function $isEmpty() {
for (const child of children) {
if (!$isParagraphNode(child)) return false;
if (child.getIndent() !== 0) return false;
+
+ const selfChildren = child.getChildren();
+
+ if (selfChildren.length > 0) {
+ const firstChild = selfChildren[0];
+ if ($isWatermarkNode(firstChild)) continue;
+ if (!$isParagraphNode(firstChild)) {
+ return false;
+ }
+ }
+
if (child.getTextContent() !== '') return false;
- if (
- child.getChildren().length > 0 &&
- !$isParagraphNode(child.getChildren()[0])
- )
- return false;
}
return true;
}
diff --git a/js/app/packages/core/constant/PaywallState.tsx b/js/app/packages/core/constant/PaywallState.tsx
index 24b0f6533e..e3dd320403 100644
--- a/js/app/packages/core/constant/PaywallState.tsx
+++ b/js/app/packages/core/constant/PaywallState.tsx
@@ -14,6 +14,7 @@ export enum PaywallKey {
O1_LIMIT = 'O1_LIMIT',
CANVAS_CLIKED = 'CANVAS_CLIKED',
SAVED_PROMPT = 'SAVED_PROMPT',
+ REMOVE_SIGNATURE = 'REMOVE_SIGNATURE',
}
export const PaywallMessages: Record<PaywallKey, string> = {
@@ -30,6 +31,8 @@ export const PaywallMessages: Record<PaywallKey, string> = {
'Upgrade your plan to have AI generate canvases (diagrams, whiteboards, drawings).',
[PaywallKey.SAVED_PROMPT]:
'Saved prompts are a paid feature. Please upgrade to continue.',
+ [PaywallKey.REMOVE_SIGNATURE]:
+ 'Upgrade your plan to remove the Macro signature.',
};
export const [paywallOpen, setPaywallOpen] = createSignal(false);
diff --git a/js/app/packages/lexical-core/decoratorRegistry.ts b/js/app/packages/lexical-core/decoratorRegistry.ts
index 92369bfb56..146cfb52b0 100644
--- a/js/app/packages/lexical-core/decoratorRegistry.ts
+++ b/js/app/packages/lexical-core/decoratorRegistry.ts
@@ -37,6 +37,10 @@ import type {
UserMentionNode,
} from './nodes/UserMentionNode';
import type { VideoDecoratorProps, VideoNode } from './nodes/VideoNode';
+import type {
+ WatermarkDecoratorProps,
+ WatermarkNode,
+} from './nodes/WatermarkNode';
// Generic component type to be overridden by solid-js on the front end
// and nothing on the backend.
@@ -87,6 +91,10 @@ export interface NodeDecoratorMap {
klass: typeof HtmlRenderNode;
props: HtmlRenderDecoratorProps;
};
+ WatermarkNode: {
+ klass: typeof WatermarkNode;
+ props: WatermarkDecoratorProps;
+ };
}
export type NodeClassToProps<T extends LexicalNode> = T extends InstanceType<
diff --git a/js/app/packages/lexical-core/index.ts b/js/app/packages/lexical-core/index.ts
index d70e49b17d..a1b7694654 100644
--- a/js/app/packages/lexical-core/index.ts
+++ b/js/app/packages/lexical-core/index.ts
@@ -23,6 +23,7 @@ export * from './nodes/MediaNode';
export * from './nodes/UnlinkedTextNode';
export * from './nodes/UserMentionNode';
export * from './nodes/VideoNode';
+export * from './nodes/WatermarkNode';
export * from './plugins/nodeIdPlugin';
export * from './plugins/peerIdPlugin';
diff --git a/js/app/packages/lexical-core/node-list.ts b/js/app/packages/lexical-core/node-list.ts
index b4925f6dfe..158ed24a54 100644
--- a/js/app/packages/lexical-core/node-list.ts
+++ b/js/app/packages/lexical-core/node-list.ts
@@ -33,6 +33,7 @@ import { SearchMatchNode } from './nodes/SearchMatchNode';
import { UnlinkedTextNode } from './nodes/UnlinkedTextNode';
import { UserMentionNode } from './nodes/UserMentionNode';
import { VideoNode } from './nodes/VideoNode';
+import { WatermarkNode } from './nodes/WatermarkNode';
/**
* The pre-specified types of base editor we have configured.
@@ -87,6 +88,7 @@ export const SupportedNodeTypes = [
DiffDeleteNode,
HtmlRenderNode,
ClassedBlockNode,
+ WatermarkNode,
] as const;
export const NodeReplacements: LexicalNodeReplacement[] = [
diff --git a/js/app/packages/lexical-core/nodes/WatermarkNode.ts b/js/app/packages/lexical-core/nodes/WatermarkNode.ts
new file mode 100644
index 0000000000..960916c4e9
--- /dev/null
+++ b/js/app/packages/lexical-core/nodes/WatermarkNode.ts
@@ -0,0 +1,234 @@
+import {
+ $applyNodeReplacement,
+ $getNodeByKey,
+ $getRoot,
+ $hasUpdateTag,
+ DecoratorNode,
+ type DOMConversionMap,
+ type EditorConfig,
+ type EditorThemeClasses,
+ type LexicalEditor,
+ type LexicalNode,
+ type NodeKey,
+ type SerializedLexicalNode,
+ type Spread,
+} from 'lexical';
+import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';
+import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
+
+export type WatermarkInfo = {
+ content: string;
+};
+
+export type SerializedWatermarkNode = Spread<
+ WatermarkInfo,
+ SerializedLexicalNode
+>;
+
+export type WatermarkDecoratorProps = {
+ content: string;
+ key: NodeKey;
+ theme: EditorThemeClasses;
+};
+
+export class WatermarkNode extends DecoratorNode<
+ DecoratorComponent<WatermarkDecoratorProps> | undefined
+> {
+ __content: string;
+
+ static getType() {
+ return 'watermark';
+ }
+
+ isInline(): boolean {
+ return true;
+ }
+
+ isIsolated(): boolean {
+ return true;
+ }
+
+ isKeyboardSelectable(): boolean {
+ return false;
+ }
+
+ static clone(node: WatermarkNode) {
+ return new WatermarkNode(node.__content, node.__key);
+ }
+
+ constructor(content: string, key?: NodeKey) {
+ super(key);
+ this.__content = content;
+ }
+
+ static importJSON(serializedNode: SerializedWatermarkNode) {
+ const node = $createWatermarkNode({
+ content: serializedNode.content,
+ });
+ $applyIdFromSerialized(node, serializedNode);
+ return node;
+ }
+
+ exportJSON(): SerializedWatermarkNode {
+ return {
+ ...super.exportJSON(),
+ content: this.__content,
+ type: WatermarkNode.getType(),
+ version: 1,
+ };
+ }
+
+ exportComponentProps(): WatermarkInfo {
+ return {
+ content: this.__content,
+ };
+ }
+
+ createDOM(_config: EditorConfig): HTMLElement {
+ const container = document.createElement('span');
+ return container;
+ }
+
+ updateDOM(): boolean {
+ return false;
+ }
+
+ getDataAttrs(): Record<string, string | boolean> {
+ return {
+ 'data-watermark': true,
+ 'data-content': this.__content,
+ };
+ }
+
+ static importDOM(): DOMConversionMap<HTMLSpanElement> | null {
+ return {
+ span: (domNode: HTMLSpanElement) => {
+ if (!domNode.hasAttribute('data-watermark')) {
+ return null;
+ }
+ return {
+ conversion: (domNode: HTMLElement) => {
+ const content = domNode.getAttribute('data-content');
+
+ if (content) {
+ const node = $createWatermarkNode({
+ content,
+ });
+ return { node };
+ }
+ return null;
+ },
+ priority: 1,
+ };
+ },
+ };
+ }
+
+ exportDOM() {
+ const element = document.createElement('span');
+ for (const [k, v] of Object.entries(this.getDataAttrs())) {
+ element.setAttribute(k, v.toString());
+ }
+ element.className = 'macro-watermark-node';
+ element.textContent = this.__content;
+ return { element };
+ }
+
+ getTextContent(): string {
+ return this.__content;
+ }
+
+ // To prevent the node from being removed during editing
+ remove(): void {}
+
+ // To manually remove
+ forceRemove(): void {
+ super.remove();
+ }
+
+ getContent() {
+ return this.__content;
+ }
+
+ decorate(_: LexicalEditor, config: EditorConfig) {
+ const decorator = getDecorator<WatermarkNode>(WatermarkNode);
+ if (decorator) {
+ return () =>
+ decorator({
+ ...this.exportComponentProps(),
+ key: this.getKey(),
+ theme: config.theme,
+ });
+ }
+ }
+}
+
+export function $createWatermarkNode(params: { content: string }) {
+ const node = new WatermarkNode(params.content);
+ return $applyNodeReplacement(node);
+}
+
+export function $isWatermarkNode(
+ node: WatermarkNode | LexicalNode | null | undefined
+): node is WatermarkNode {
+ return node instanceof WatermarkNode;
+}
+
+export function $removeAllWatermarkNodes(editor: LexicalEditor | undefined) {
+ editor?.registerMutationListener(
+ WatermarkNode,
+ (mutations) => {
+ editor?.update(
+ () => {
+ if (!$hasUpdateTag('registerMutationListener')) return;
+ for (const [key, mutation] of mutations) {
+ if (mutation !== 'created') continue;
+ const node = $getNodeByKey(key);
+
+ if (node instanceof WatermarkNode) node.forceRemove();
+ }
+ },
+ { discrete: true, skipTransforms: true }
+ );
+ },
+ { skipInitialization: true }
+ );
+}
+
+export function $appendWatermarkNodeToLast(
+ editor: LexicalEditor | undefined,
+ content: string | undefined,
+ sync = true
+) {
+ let nodeKey: string | undefined;
+
+ editor?.update(
+ () => {
+ if (!content) return;
+
+ const node = $createWatermarkNode({ content });
+
+ nodeKey = node.getKey();
+
+ const root = $getRoot();
+
+ root.getLastChild()?.insertAfter(node);
+ },
+ { discrete: sync || undefined }
+ );
+
+ return () => {
+ editor?.update(
+ () => {
+ if (!nodeKey) return;
+
+ const node = $getNodeByKey(nodeKey);
+
+ if (node instanceof WatermarkNode) {
+ node.forceRemove();
+ }
+ },
+ { discrete: true }
+ );
+ };
+}
diff --git a/js/app/packages/lexical-core/transformers/index.ts b/js/app/packages/lexical-core/transformers/index.ts
index 1d9d67e4d0..ae2517aa84 100644
--- a/js/app/packages/lexical-core/transformers/index.ts
+++ b/js/app/packages/lexical-core/transformers/index.ts
@@ -27,6 +27,7 @@ import {
PRESERVE_LINES,
SEARCH_MATCH,
} from './transformers';
+import { E_WATERMARK, I_WATERMARK } from './watermark';
/**
* Internal transformers for converting markdown between Lexical state and markdown.
@@ -46,6 +47,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [
I_DATE_MENTION,
I_TABLE_NODE,
I_EQUATION_NODE,
+ I_WATERMARK,
...CUSTOM_TRANSFORMERS,
];
@@ -67,6 +69,7 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [
E_MULTILINE_BLOCK_EQUATION_NODE,
E_BLOCK_EQUATION_NODE,
E_INLINE_EQUATION_NODE,
+ E_WATERMARK,
...HTML_ENTITY_TRANSFORMERS,
...CUSTOM_TRANSFORMERS,
];
@@ -93,6 +96,8 @@ export const ALL_TRANSFORMERS: Transformer[] = [
I_DATE_MENTION,
E_DATE_MENTION,
I_EQUATION_NODE,
+ I_WATERMARK,
+ E_WATERMARK,
// order matters
E_MULTILINE_BLOCK_EQUATION_NODE,
E_BLOCK_EQUATION_NODE,
diff --git a/js/app/packages/lexical-core/transformers/watermark.ts b/js/app/packages/lexical-core/transformers/watermark.ts
new file mode 100644
index 0000000000..190079b2dd
--- /dev/null
+++ b/js/app/packages/lexical-core/transformers/watermark.ts
@@ -0,0 +1,63 @@
+import type { ElementTransformer } from '@lexical/markdown';
+import type { ElementNode, LexicalNode } from 'lexical';
+import {
+ $createWatermarkNode,
+ $isWatermarkNode,
+ WatermarkNode,
+} from '../nodes/WatermarkNode';
+
+// Internal Watermark
+export const I_WATERMARK: ElementTransformer = {
+ dependencies: [WatermarkNode],
+ type: 'element',
+ regExp: /<m-watermark>(.*?)<\/m-watermark>/,
+ export: (node) => {
+ if (!$isWatermarkNode(node)) return null;
+
+ const data = JSON.stringify({
+ content: node.getContent(),
+ });
+
+ return `<m-watermark>${data}</m-watermark>`;
+ },
+ replace: (parent: ElementNode, _, match: RegExpMatchArray) => {
+ try {
+ const data = JSON.parse(match[1]);
+ for (const field of ['content']) {
+ if (!(field in data)) throw new Error(`Missing field ${field}`);
+ }
+
+ const watermarkNode = $createWatermarkNode({ content: data.content });
+ parent.append(watermarkNode);
+ } catch (e) {
+ console.error(e);
+ }
+ },
+};
+
+// External Watermarks
+export const E_WATERMARK: ElementTransformer = {
+ dependencies: [WatermarkNode],
+ type: 'element',
+ regExp: /$^/,
+ export: (node) => {
+ if (!$isWatermarkNode(node)) return null;
+
+ const content = node.getContent();
+
+ if (!content) {
+ return null;
+ }
+
+ // For external representation, just show the content
+ return content;
+ },
+ replace: (
+ _parentNode: ElementNode,
+ _children: Array<LexicalNode>,
+ _match: Array<string>,
+ _isImport: boolean
+ ) => {
+ return false;
+ },
+};