initial commit. gotta go

This commit is contained in:
2025-09-26 14:30:57 -05:00
parent b342335502
commit eb0b35bb7f
299 changed files with 6902 additions and 6741 deletions

View File

@@ -1,6 +1,6 @@
import { Button } from "@usesend/ui/src/button";
import { CheckIcon } from "lucide-react";
import { useState, useCallback, useMemo } from "react";
import { Button } from '@usesend/ui/src/button';
import { CheckIcon } from 'lucide-react';
import { useState, useCallback, useMemo } from 'react';
export type LinkEditorPanelProps = {
initialUrl?: string;
@@ -11,7 +11,7 @@ export const useLinkEditorState = ({
initialUrl,
onSetLink,
}: LinkEditorPanelProps) => {
const [url, setUrl] = useState(initialUrl || "");
const [url, setUrl] = useState(initialUrl || '');
const onChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setUrl(event.target.value);
@@ -22,7 +22,7 @@ export const useLinkEditorState = ({
e.preventDefault();
onSetLink(url);
},
[url, onSetLink]
[url, onSetLink],
);
return {
@@ -46,11 +46,11 @@ export const LinkEditorPanel = ({
<div className="">
<form
onSubmit={state.handleSubmit}
className="flex items-center gap-2 justify-between"
className="flex items-center justify-between gap-2"
>
<label className="flex items-center gap-2 p-2 rounded-lg cursor-text">
<label className="flex cursor-text items-center gap-2 rounded-lg p-2">
<input
className="flex-1 bg-transparent outline-none min-w-[12rem] text-black text-sm"
className="min-w-[12rem] flex-1 bg-transparent text-sm text-black outline-none"
placeholder="Enter valid url"
value={state.url}
onChange={state.onChange}

View File

@@ -1,5 +1,5 @@
import { Button } from "@usesend/ui/src/button";
import { Edit2Icon, EditIcon, Trash2Icon } from "lucide-react";
import { Button } from '@usesend/ui/src/button';
import { Edit2Icon, EditIcon, Trash2Icon } from 'lucide-react';
export type LinkPreviewPanelProps = {
url: string;
@@ -18,7 +18,7 @@ export const LinkPreviewPanel = ({
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-sm underline w-[12rem] overflow-hidden text-ellipsis"
className="w-[12rem] overflow-hidden text-ellipsis text-sm underline"
>
{url}
</a>
@@ -26,7 +26,7 @@ export const LinkPreviewPanel = ({
<Edit2Icon className="h-4 w-4" />
</Button>
<Button onClick={onClear} variant="silent" size="sm" className="p-1">
<Trash2Icon className="h-4 w-4 text-destructive" />
<Trash2Icon className="text-destructive h-4 w-4" />
</Button>
</div>
);

View File

@@ -1,6 +1,6 @@
import { Button } from "@usesend/ui/src/button";
import { CheckIcon } from "lucide-react";
import { useState, useCallback, useMemo } from "react";
import { Button } from '@usesend/ui/src/button';
import { CheckIcon } from 'lucide-react';
import { useState, useCallback, useMemo } from 'react';
export type TextEditorPanelProps = {
initialText?: string;
@@ -11,7 +11,7 @@ export const useTextEditorState = ({
initialText,
onSetInitialText,
}: TextEditorPanelProps) => {
const [url, setUrl] = useState(initialText || "");
const [url, setUrl] = useState(initialText || '');
const onChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setUrl(event.target.value);
@@ -22,7 +22,7 @@ export const useTextEditorState = ({
e.preventDefault();
onSetInitialText(url);
},
[url, onSetInitialText]
[url, onSetInitialText],
);
return {
@@ -46,11 +46,11 @@ export const TextEditorPanel = ({
<div className="">
<form
onSubmit={state.handleSubmit}
className="flex items-center gap-2 justify-between"
className="flex items-center justify-between gap-2"
>
<label className="flex items-center gap-2 p-2 rounded-lg cursor-text">
<label className="flex cursor-text items-center gap-2 rounded-lg p-2">
<input
className="flex-1 bg-transparent outline-none min-w-[12rem] text-black text-sm"
className="min-w-[12rem] flex-1 bg-transparent text-sm text-black outline-none"
placeholder="Enter valid url"
value={state.url}
onChange={state.onChange}

View File

@@ -1,13 +1,13 @@
"use client";
'use client';
import { Button } from "@usesend/ui/src/button";
import { Button } from '@usesend/ui/src/button';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@usesend/ui/src/popover";
import { ReactNode, useState } from "react";
import { HexAlphaColorPicker, HexColorInput } from "react-colorful";
} from '@usesend/ui/src/popover';
import { ReactNode, useState } from 'react';
import { HexAlphaColorPicker, HexColorInput } from 'react-colorful';
type ColorPickerProps = {
color: string;
@@ -25,7 +25,7 @@ export function ColorPicker(props: ColorPickerProps) {
};
return (
<div className="min-w-[260px] rounded-xl shadow border border-gray-200 bg-white p-4">
<div className="min-w-[260px] rounded-xl border border-gray-200 bg-white p-4 shadow">
<HexAlphaColorPicker
color={color}
onChange={handleColorChange}
@@ -35,7 +35,7 @@ export function ColorPicker(props: ColorPickerProps) {
alpha={true}
color={color}
onChange={handleColorChange}
className="mt-4 bg-transparent text-black w-full min-w-0 rounded-lg border px-2 py-1.5 text-sm uppercase focus-visible:border-gray-400 focus-visible:outline-none"
className="mt-4 w-full min-w-0 rounded-lg border bg-transparent px-2 py-1.5 text-sm uppercase text-black focus-visible:border-gray-400 focus-visible:outline-none"
prefixed
/>
</div>
@@ -43,7 +43,7 @@ export function ColorPicker(props: ColorPickerProps) {
}
export function ColorPickerPopup(
props: ColorPickerProps & { trigger: ReactNode }
props: ColorPickerProps & { trigger: ReactNode },
) {
const { color, onChange } = props;

View File

@@ -1,16 +1,16 @@
import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon } from "lucide-react";
import { AllowedAlignments } from "../../../types";
import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon } from 'lucide-react';
import { AllowedAlignments } from '../../../types';
export const AlignmentIcon = ({
alignment,
}: {
alignment: AllowedAlignments;
}) => {
if (alignment === "left") {
if (alignment === 'left') {
return <AlignLeftIcon className="h-4 w-4" />;
} else if (alignment === "center") {
} else if (alignment === 'center') {
return <AlignCenterIcon className="h-4 w-4" />;
} else if (alignment === "right") {
} else if (alignment === 'right') {
return <AlignRightIcon className="h-4 w-4" />;
}
return null;

View File

@@ -1,6 +1,6 @@
import React from "react";
import React from 'react';
import { SVGProps } from "../../../types";
import { SVGProps } from '../../../types';
export const BorderWidth: React.FC<SVGProps> = (props) => {
return (

View File

@@ -1,4 +1,4 @@
"use client";
'use client';
import {
BubbleMenu,
@@ -6,16 +6,16 @@ import {
EditorProvider,
FloatingMenu,
useEditor,
} from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import React, { useRef } from "react";
import { TextMenu } from "./menus/TextMenu";
import { cn } from "@usesend/ui/lib/utils";
} from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import React, { useRef } from 'react';
import { TextMenu } from './menus/TextMenu';
import { cn } from '@usesend/ui/lib/utils';
import { extensions } from "./extensions";
import LinkMenu from "./menus/LinkMenu";
import { Content, Editor as TipTapEditor } from "@tiptap/core";
import { UploadFn } from "./extensions/ImageExtension";
import { extensions } from './extensions';
import LinkMenu from './menus/LinkMenu';
import { Content, Editor as TipTapEditor } from '@tiptap/core';
import { UploadFn } from './extensions/ImageExtension';
const content = `<h2>Hello World!</h2>
@@ -82,13 +82,13 @@ export const Editor: React.FC<EditorProps> = ({
const editor = useEditor({
editorProps: {
attributes: {
class: cn("unsend-prose w-full"),
class: cn('unsend-prose w-full'),
},
handleDOMEvents: {
keydown: (_view, event) => {
// prevent default event listeners from firing when slash command is active
if (["ArrowUp", "ArrowDown", "Enter"].includes(event.key)) {
const slashCommand = document.querySelector("#slash-command");
if (['ArrowUp', 'ArrowDown', 'Enter'].includes(event.key)) {
const slashCommand = document.querySelector('#slash-command');
if (slashCommand) {
return true;
}
@@ -105,7 +105,7 @@ export const Editor: React.FC<EditorProps> = ({
return (
<div
className="bg-white rounded-md text-black p-8 unsend-editor light"
className="unsend-editor light rounded-md bg-white p-8 text-black"
ref={menuContainerRef}
>
<EditorContent editor={editor} className="min-h-[50vh]" />

View File

@@ -1,11 +1,11 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { AllowedAlignments } from "../types";
import { mergeAttributes, Node } from '@tiptap/core';
import { ReactNodeViewRenderer } from '@tiptap/react';
import { AllowedAlignments } from '../types';
import { ButtonComponent } from "../nodes/button";
import { ButtonComponent } from '../nodes/button';
// import { AllowedLogoAlignment } from '../nodes/logo';
declare module "@tiptap/core" {
declare module '@tiptap/core' {
interface Commands<ReturnType> {
button: {
setButton: () => ReturnType;
@@ -14,39 +14,39 @@ declare module "@tiptap/core" {
}
export const ButtonExtension = Node.create({
name: "button",
group: "block",
name: 'button',
group: 'block',
atom: true,
draggable: true,
addAttributes() {
return {
component: {
default: "button",
default: 'button',
},
text: {
default: "Button",
default: 'Button',
},
url: {
default: "",
default: '',
},
alignment: {
default: "left",
default: 'left',
},
borderRadius: {
default: "4",
default: '4',
},
borderWidth: {
default: "1",
default: '1',
},
buttonColor: {
default: "rgb(0, 0, 0)",
default: 'rgb(0, 0, 0)',
},
borderColor: {
default: "rgb(0, 0, 0)",
default: 'rgb(0, 0, 0)',
},
textColor: {
default: "rgb(255, 255, 255)",
default: 'rgb(255, 255, 255)',
},
};
},
@@ -61,12 +61,12 @@ export const ButtonExtension = Node.create({
renderHTML({ HTMLAttributes }) {
return [
"a",
'a',
mergeAttributes(
{
"data-unsend-component": this.name,
'data-unsend-component': this.name,
},
HTMLAttributes
HTMLAttributes,
),
];
},

View File

@@ -1,10 +1,10 @@
import { ReactNodeViewRenderer } from "@tiptap/react";
import TipTapImage from "@tiptap/extension-image";
import { ResizableImageTemplate } from "../nodes/image-resize";
import { PluginKey, Plugin } from "@tiptap/pm/state";
import { toast } from "@usesend/ui/src/toaster";
import { ReactNodeViewRenderer } from '@tiptap/react';
import TipTapImage from '@tiptap/extension-image';
import { ResizableImageTemplate } from '../nodes/image-resize';
import { PluginKey, Plugin } from '@tiptap/pm/state';
import { toast } from '@usesend/ui/src/toaster';
const uploadKey = new PluginKey("upload-image");
const uploadKey = new PluginKey('upload-image');
export type UploadFn = (image: File) => Promise<string>;
@@ -17,22 +17,22 @@ export const ResizableImageExtension =
addAttributes() {
return {
...this.parent?.(),
width: { renderHTML: ({ width }) => ({ width }), default: "600" },
width: { renderHTML: ({ width }) => ({ width }), default: '600' },
height: { renderHTML: ({ height }) => ({ height }) },
borderRadius: {
default: "0",
default: '0',
},
borderWidth: {
default: "0",
default: '0',
},
borderColor: {
default: "rgb(0, 0, 0)",
default: 'rgb(0, 0, 0)',
},
alignment: {
default: "center",
renderHTML: ({ alignment }) => ({ "data-alignment": alignment }),
default: 'center',
renderHTML: ({ alignment }) => ({ 'data-alignment': alignment }),
parseHTML: (element) =>
element.getAttribute("data-alignment") || "center",
element.getAttribute('data-alignment') || 'center',
},
externalLink: {
default: null,
@@ -41,16 +41,16 @@ export const ResizableImageExtension =
return {};
}
return {
"data-external-link": externalLink,
'data-external-link': externalLink,
};
},
parseHTML: (element) => {
const externalLink = element.getAttribute("data-external-link");
const externalLink = element.getAttribute('data-external-link');
return externalLink ? { externalLink } : null;
},
},
alt: {
default: "image",
default: 'image',
},
isUploading: {
default: false,
@@ -73,16 +73,16 @@ export const ResizableImageExtension =
event.preventDefault();
const image = Array.from(event.dataTransfer.files).find(
(file) => file.type.startsWith("image/")
(file) => file.type.startsWith('image/'),
);
if (!this.options.uploadImage) {
toast.error("Upload image is not supported");
toast.error('Upload image is not supported');
return true;
}
if (!image) {
toast.error("Only image is supported");
toast.error('Only image is supported');
return true;
}
@@ -104,7 +104,7 @@ export const ResizableImageExtension =
});
const transaction = view.state.tr.insert(
coordinates?.pos || 0,
node
node,
);
view.dispatch(transaction);
@@ -117,7 +117,7 @@ export const ResizableImageExtension =
{
src: url,
isUploading: false,
}
},
);
view.dispatch(updateTransaction);
})
@@ -125,11 +125,11 @@ export const ResizableImageExtension =
// Remove the placeholder image node if there's an error
const removeTransaction = view.state.tr.delete(
coordinates?.pos || 0,
(coordinates?.pos || 0) + 1
(coordinates?.pos || 0) + 1,
);
view.dispatch(removeTransaction);
toast.error("Error uploading image:", error.message);
console.error("Error uploading image:", error);
toast.error('Error uploading image:', error.message);
console.error('Error uploading image:', error);
});
return true;

View File

@@ -1,6 +1,6 @@
import { Editor, Extension, Range, ReactRenderer } from "@tiptap/react";
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
import { cn } from "@usesend/ui/lib/utils";
import { Editor, Extension, Range, ReactRenderer } from '@tiptap/react';
import Suggestion, { SuggestionOptions } from '@tiptap/suggestion';
import { cn } from '@usesend/ui/lib/utils';
import {
CodeIcon,
DivideIcon,
@@ -17,7 +17,7 @@ import {
TextQuoteIcon,
UserXIcon,
VariableIcon,
} from "lucide-react";
} from 'lucide-react';
import {
ReactNode,
useCallback,
@@ -25,9 +25,9 @@ import {
useLayoutEffect,
useRef,
useState,
} from "react";
import tippy, { GetReferenceClientRect } from "tippy.js";
import { UploadFn } from "./ImageExtension";
} from 'react';
import tippy, { GetReferenceClientRect } from 'tippy.js';
import { UploadFn } from './ImageExtension';
export interface CommandProps {
editor: Editor;
@@ -49,11 +49,11 @@ export type SlashCommandItem = {
};
export const SlashCommand = Extension.create({
name: "slash-command",
name: 'slash-command',
addOptions() {
return {
suggestion: {
char: "/",
char: '/',
command: ({
editor,
range,
@@ -81,89 +81,89 @@ export const SlashCommand = Extension.create({
const DEFAULT_SLASH_COMMANDS = (uploadImage?: UploadFn): SlashCommandItem[] => [
{
title: "Text",
description: "Just start typing with plain text.",
searchTerms: ["p", "paragraph"],
title: 'Text',
description: 'Just start typing with plain text.',
searchTerms: ['p', 'paragraph'],
icon: <TextIcon className="h-4 w-4" />,
command: ({ editor, range }) => {
editor
.chain()
.focus()
.deleteRange(range)
.toggleNode("paragraph", "paragraph")
.toggleNode('paragraph', 'paragraph')
.run();
},
},
{
title: "Heading 1",
description: "Big section heading.",
searchTerms: ["title", "big", "large"],
title: 'Heading 1',
description: 'Big section heading.',
searchTerms: ['title', 'big', 'large'],
icon: <Heading1Icon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor
.chain()
.focus()
.deleteRange(range)
.setNode("heading", { level: 1 })
.setNode('heading', { level: 1 })
.run();
},
},
{
title: "Heading 2",
description: "Medium section heading.",
searchTerms: ["subtitle", "medium"],
title: 'Heading 2',
description: 'Medium section heading.',
searchTerms: ['subtitle', 'medium'],
icon: <Heading2Icon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor
.chain()
.focus()
.deleteRange(range)
.setNode("heading", { level: 2 })
.setNode('heading', { level: 2 })
.run();
},
},
{
title: "Heading 3",
description: "Small section heading.",
searchTerms: ["subtitle", "small"],
title: 'Heading 3',
description: 'Small section heading.',
searchTerms: ['subtitle', 'small'],
icon: <Heading3Icon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor
.chain()
.focus()
.deleteRange(range)
.setNode("heading", { level: 3 })
.setNode('heading', { level: 3 })
.run();
},
},
{
title: "Bullet List",
description: "Create a simple bullet list.",
searchTerms: ["unordered", "point"],
title: 'Bullet List',
description: 'Create a simple bullet list.',
searchTerms: ['unordered', 'point'],
icon: <ListIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).toggleBulletList().run();
},
},
{
title: "Numbered List",
description: "Create a list with numbering.",
searchTerms: ["ordered"],
title: 'Numbered List',
description: 'Create a list with numbering.',
searchTerms: ['ordered'],
icon: <ListOrderedIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).toggleOrderedList().run();
},
},
{
title: "Image",
description: "Full width image",
searchTerms: ["image"],
title: 'Image',
description: 'Full width image',
searchTerms: ['image'],
icon: <ImageIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
if (uploadImage) {
const input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = async () => {
const file = input.files?.[0];
if (file && uploadImage) {
@@ -173,25 +173,25 @@ const DEFAULT_SLASH_COMMANDS = (uploadImage?: UploadFn): SlashCommandItem[] => [
.chain()
.focus()
.setImage({ src: placeholder })
.updateAttributes("image", { isUploading: true })
.updateAttributes('image', { isUploading: true })
.run();
try {
console.log("before upload");
console.log('before upload');
const url = await uploadImage(file);
editor
.chain()
.focus()
.updateAttributes("image", { src: url, isUploading: false })
.updateAttributes('image', { src: url, isUploading: false })
.run();
} catch (e) {
editor.chain().focus().deleteNode("image").run();
console.error("Failed to upload image:", e);
editor.chain().focus().deleteNode('image').run();
console.error('Failed to upload image:', e);
}
}
};
input.click();
} else {
const imageUrl = prompt("Image URL: ") || "";
const imageUrl = prompt('Image URL: ') || '';
if (!imageUrl) {
return;
@@ -203,72 +203,72 @@ const DEFAULT_SLASH_COMMANDS = (uploadImage?: UploadFn): SlashCommandItem[] => [
},
},
{
title: "Hard Break",
description: "Add a break between lines.",
searchTerms: ["break", "line"],
title: 'Hard Break',
description: 'Add a break between lines.',
searchTerms: ['break', 'line'],
icon: <DivideIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setHardBreak().run();
},
},
{
title: "Blockquote",
description: "Add blockquote.",
searchTerms: ["quote", "blockquote"],
title: 'Blockquote',
description: 'Add blockquote.',
searchTerms: ['quote', 'blockquote'],
icon: <TextQuoteIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).toggleBlockquote().run();
},
},
{
title: "Button",
description: "Add code.",
searchTerms: ["button"],
title: 'Button',
description: 'Add code.',
searchTerms: ['button'],
icon: <RectangleEllipsisIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setButton().run();
},
},
{
title: "Code Block",
description: "Add code.",
searchTerms: ["code"],
title: 'Code Block',
description: 'Add code.',
searchTerms: ['code'],
icon: <CodeIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).toggleCodeBlock().run();
},
},
{
title: "Horizontal Rule",
description: "Add a horizontal rule.",
searchTerms: ["horizontal", "rule"],
title: 'Horizontal Rule',
description: 'Add a horizontal rule.',
searchTerms: ['horizontal', 'rule'],
icon: <SquareSplitVerticalIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setHorizontalRule().run();
},
},
{
title: "Clear Line",
description: "Clear the current line.",
searchTerms: ["clear", "line"],
title: 'Clear Line',
description: 'Clear the current line.',
searchTerms: ['clear', 'line'],
icon: <EraserIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().selectParentNode().deleteSelection().run();
},
},
{
title: "Variable",
description: "Add a variable.",
searchTerms: ["variable"],
title: 'Variable',
description: 'Add a variable.',
searchTerms: ['variable'],
icon: <VariableIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).insertContent("{{").run();
editor.chain().focus().deleteRange(range).insertContent('{{').run();
},
},
{
title: "Unsubscribe Footer",
description: "Add an unsubscribe link.",
searchTerms: ["unsubscribe"],
title: 'Unsubscribe Footer',
description: 'Add an unsubscribe link.',
searchTerms: ['unsubscribe'],
icon: <UserXIcon className="h-4 w-4" />,
command: ({ editor, range }: CommandProps) => {
editor
@@ -277,7 +277,7 @@ const DEFAULT_SLASH_COMMANDS = (uploadImage?: UploadFn): SlashCommandItem[] => [
.deleteRange(range)
.setHorizontalRule()
.insertContent(
`<unsub data-unsend-component='unsubscribe-footer'><p>You are receiving this email because you opted in via our site.<br/><br/><a href="{{usesend_unsubscribe_url}}">Unsubscribe from the list</a></p><br><br><p>Company name,<br/>00 street name<br/>City, State 000000</p></unsub>`
`<unsub data-unsend-component='unsubscribe-footer'><p>You are receiving this email because you opted in via our site.<br/><br/><a href="{{usesend_unsubscribe_url}}">Unsubscribe from the list</a></p><br><br><p>Company name,<br/>00 street name<br/>City, State 000000</p></unsub>`,
)
.run();
},
@@ -318,32 +318,32 @@ const CommandList = ({
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[command, editor, items]
[command, editor, items],
);
useEffect(() => {
const navigationKeys = ["ArrowUp", "ArrowDown", "Enter"];
const navigationKeys = ['ArrowUp', 'ArrowDown', 'Enter'];
const onKeyDown = (e: KeyboardEvent) => {
if (navigationKeys.includes(e.key)) {
e.preventDefault();
if (e.key === "ArrowUp") {
if (e.key === 'ArrowUp') {
setSelectedIndex((selectedIndex + items.length - 1) % items.length);
return true;
}
if (e.key === "ArrowDown") {
if (e.key === 'ArrowDown') {
setSelectedIndex((selectedIndex + 1) % items.length);
return true;
}
if (e.key === "Enter") {
if (e.key === 'Enter') {
selectItem(selectedIndex);
return true;
}
return false;
}
};
document.addEventListener("keydown", onKeyDown);
document.addEventListener('keydown', onKeyDown);
return () => {
document.removeEventListener("keydown", onKeyDown);
document.removeEventListener('keydown', onKeyDown);
};
}, [items, selectedIndex, setSelectedIndex, selectItem]);
@@ -372,10 +372,10 @@ const CommandList = ({
return (
<button
className={cn(
"flex w-full items-center space-x-2 rounded-md px-2 py-1 text-left text-sm text-gray-900 hover:bg-gray-100 hover:text-gray-900",
'flex w-full items-center space-x-2 rounded-md px-2 py-1 text-left text-sm text-gray-900 hover:bg-gray-100 hover:text-gray-900',
index === selectedIndex
? "bg-gray-100 text-gray-900"
: "bg-transparent"
? 'bg-gray-100 text-gray-900'
: 'bg-transparent',
)}
key={index}
onClick={() => selectItem(index)}
@@ -397,13 +397,13 @@ const CommandList = ({
export function getSlashCommandSuggestions(
commands: SlashCommandItem[] = [],
uploadImage?: UploadFn
): Omit<SuggestionOptions, "editor"> {
uploadImage?: UploadFn,
): Omit<SuggestionOptions, 'editor'> {
return {
items: ({ query }) => {
return [...DEFAULT_SLASH_COMMANDS(uploadImage), ...commands].filter(
(item) => {
if (typeof query === "string" && query.length > 0) {
if (typeof query === 'string' && query.length > 0) {
const search = query.toLowerCase();
return (
item.title.toLowerCase().includes(search) ||
@@ -413,7 +413,7 @@ export function getSlashCommandSuggestions(
);
}
return true;
}
},
);
},
render: () => {
@@ -427,13 +427,13 @@ export function getSlashCommandSuggestions(
editor: props.editor,
});
popup = tippy("body", {
popup = tippy('body', {
getReferenceClientRect: props.clientRect as GetReferenceClientRect,
appendTo: () => document.body,
content: component.element,
showOnCreate: true,
interactive: true,
trigger: "manual",
trigger: 'manual',
});
},
onUpdate: (props) => {
@@ -445,7 +445,7 @@ export function getSlashCommandSuggestions(
});
},
onKeyDown: (props) => {
if (props.event.key === "Escape") {
if (props.event.key === 'Escape') {
popup?.[0].hide();
return true;

View File

@@ -1,9 +1,9 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { mergeAttributes, Node } from '@tiptap/core';
import { ReactNodeViewRenderer } from '@tiptap/react';
import { UnsubscribeFooterComponent } from "../nodes/unsubscribe-footer";
import { UnsubscribeFooterComponent } from '../nodes/unsubscribe-footer';
declare module "@tiptap/core" {
declare module '@tiptap/core' {
interface Commands<ReturnType> {
unsubscribeFooter: {
setUnsubscribeFooter: () => ReturnType;
@@ -12,14 +12,14 @@ declare module "@tiptap/core" {
}
export const UnsubscribeFooterExtension = Node.create({
name: "unsubscribeFooter",
group: "block",
content: "inline*",
name: 'unsubscribeFooter',
group: 'block',
content: 'inline*',
addAttributes() {
return {
component: {
default: "unsubscribeFooter",
default: 'unsubscribeFooter',
},
};
},
@@ -34,14 +34,14 @@ export const UnsubscribeFooterExtension = Node.create({
renderHTML({ HTMLAttributes }) {
return [
"unsub",
'unsub',
mergeAttributes(
{
"data-unsend-component": this.name,
class: "footer",
contenteditable: "true",
'data-unsend-component': this.name,
class: 'footer',
contenteditable: 'true',
},
HTMLAttributes
HTMLAttributes,
),
0,
];

View File

@@ -1,22 +1,22 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { PluginKey } from "@tiptap/pm/state";
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
import { VariableComponent, VariableOptions } from "../nodes/variable";
import { mergeAttributes, Node } from '@tiptap/core';
import { ReactNodeViewRenderer } from '@tiptap/react';
import { PluginKey } from '@tiptap/pm/state';
import Suggestion, { SuggestionOptions } from '@tiptap/suggestion';
import { VariableComponent, VariableOptions } from '../nodes/variable';
export interface VariableNodeAttrs extends VariableOptions {}
export type VariableExtensionOptions = {
HTMLAttributes: Record<string, any>;
suggestion: Omit<SuggestionOptions, "editor">;
suggestion: Omit<SuggestionOptions, 'editor'>;
};
export const VariablePluginKey = new PluginKey("variable");
export const VariablePluginKey = new PluginKey('variable');
export const VariableExtension = Node.create<VariableExtensionOptions>({
name: "variable",
name: 'variable',
group: "inline",
group: 'inline',
inline: true,
@@ -30,10 +30,10 @@ export const VariableExtension = Node.create<VariableExtensionOptions>({
HTMLAttributes: {},
deleteTriggerWithBackspace: false,
suggestion: {
char: "{{",
char: '{{',
pluginKey: VariablePluginKey,
command: ({ editor, range, props }) => {
console.log("props: ", props);
console.log('props: ', props);
editor
.chain()
.focus()
@@ -43,8 +43,8 @@ export const VariableExtension = Node.create<VariableExtensionOptions>({
attrs: props,
},
{
type: "text",
text: " ",
type: 'text',
text: ' ',
},
])
.run();
@@ -57,7 +57,7 @@ export const VariableExtension = Node.create<VariableExtensionOptions>({
const allow = type
? !!$from.parent.type.contentMatch.matchType(type)
: false;
console.log("allow: ", allow);
console.log('allow: ', allow);
return allow;
},
@@ -69,42 +69,42 @@ export const VariableExtension = Node.create<VariableExtensionOptions>({
return {
id: {
default: null,
parseHTML: (element) => element.getAttribute("data-id"),
parseHTML: (element) => element.getAttribute('data-id'),
renderHTML: (attributes) => {
if (!attributes.id) {
return {};
}
return {
"data-id": attributes.id,
'data-id': attributes.id,
};
},
},
name: {
default: null,
parseHTML: (element) => element.getAttribute("data-name"),
parseHTML: (element) => element.getAttribute('data-name'),
renderHTML: (attributes) => {
if (!attributes.name) {
return {};
}
return {
"data-name": attributes.name,
'data-name': attributes.name,
};
},
},
fallback: {
default: null,
parseHTML: (element) => element.getAttribute("data-fallback"),
parseHTML: (element) => element.getAttribute('data-fallback'),
renderHTML: (attributes) => {
if (!attributes.fallback) {
return {};
}
return {
"data-fallback": attributes.fallback,
'data-fallback': attributes.fallback,
};
},
},
@@ -121,7 +121,7 @@ export const VariableExtension = Node.create<VariableExtensionOptions>({
renderHTML({ HTMLAttributes }) {
return [
"span",
'span',
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
];
},

View File

@@ -1,13 +1,13 @@
import { Extension } from "@tiptap/core";
import { Extension } from '@tiptap/core';
import {
NodeSelection,
Plugin,
PluginKey,
TextSelection,
} from "@tiptap/pm/state";
import { Fragment, Slice, Node } from "@tiptap/pm/model";
} from '@tiptap/pm/state';
import { Fragment, Slice, Node } from '@tiptap/pm/model';
import { EditorView } from "@tiptap/pm/view";
import { EditorView } from '@tiptap/pm/view';
export interface GlobalDragHandleOptions {
/**
@@ -35,7 +35,7 @@ function absoluteRect(node: Element) {
const data = node.getBoundingClientRect();
const modal = node.closest('[role="dialog"]');
if (modal && window.getComputedStyle(modal).transform !== "none") {
if (modal && window.getComputedStyle(modal).transform !== 'none') {
const modalRect = modal.getBoundingClientRect();
return {
@@ -56,23 +56,23 @@ function nodeDOMAtCoords(coords: { x: number; y: number }) {
.elementsFromPoint(coords.x, coords.y)
.find(
(elem: Element) =>
elem.parentElement?.matches?.(".ProseMirror") ||
elem.parentElement?.matches?.('.ProseMirror') ||
elem.matches(
[
"li",
"p:not(:first-child)",
"pre",
"blockquote",
"h1, h2, h3, h4, h5, h6",
].join(", ")
)
'li',
'p:not(:first-child)',
'pre',
'blockquote',
'h1, h2, h3, h4, h5, h6',
].join(', '),
),
);
}
function nodePosAtDOM(
node: Element,
view: EditorView,
options: GlobalDragHandleOptions
options: GlobalDragHandleOptions,
) {
const boundingRect = node.getBoundingClientRect();
@@ -89,9 +89,9 @@ function calcNodePos(pos: number, view: EditorView) {
}
export function DragHandlePlugin(
options: GlobalDragHandleOptions & { pluginKey: string }
options: GlobalDragHandleOptions & { pluginKey: string },
) {
let listType = "";
let listType = '';
function handleDragStart(event: DragEvent, view: EditorView) {
view.focus();
@@ -117,11 +117,11 @@ export function DragHandlePlugin(
const nodePos = view.state.doc.resolve(fromSelectionPos);
// Check if nodePos points to the top level node
if (nodePos.node().type.name === "doc") differentNodeSelected = true;
if (nodePos.node().type.name === 'doc') differentNodeSelected = true;
else {
const nodeSelection = NodeSelection.create(
view.state.doc,
nodePos.before()
nodePos.before(),
);
// Check if the node where the drag event started is part of the current selection
@@ -140,7 +140,7 @@ export function DragHandlePlugin(
selection = TextSelection.create(
view.state.doc,
draggedNodePos,
endSelection.$to.pos
endSelection.$to.pos,
);
} else {
selection = NodeSelection.create(view.state.doc, draggedNodePos);
@@ -149,7 +149,7 @@ export function DragHandlePlugin(
// if table row is selected, go to the parent node to select the whole node
if (
(selection as NodeSelection).node.type.isInline ||
(selection as NodeSelection).node.type.name === "tableRow"
(selection as NodeSelection).node.type.name === 'tableRow'
) {
let $pos = view.state.doc.resolve(selection.from);
selection = NodeSelection.create(view.state.doc, $pos.before());
@@ -160,7 +160,7 @@ export function DragHandlePlugin(
// If the selected node is a list item, we need to save the type of the wrapping list e.g. OL or UL
if (
view.state.selection instanceof NodeSelection &&
view.state.selection.node.type.name === "listItem"
view.state.selection.node.type.name === 'listItem'
) {
listType = node.parentElement!.tagName;
}
@@ -170,9 +170,9 @@ export function DragHandlePlugin(
const { dom, text } = view.serializeForClipboard(slice);
event.dataTransfer.clearData();
event.dataTransfer.setData("text/html", dom.innerHTML);
event.dataTransfer.setData("text/plain", text);
event.dataTransfer.effectAllowed = "copyMove";
event.dataTransfer.setData('text/html', dom.innerHTML);
event.dataTransfer.setData('text/plain', text);
event.dataTransfer.effectAllowed = 'copyMove';
event.dataTransfer.setDragImage(node, 0, 0);
@@ -183,21 +183,21 @@ export function DragHandlePlugin(
function hideDragHandle() {
if (dragHandleElement) {
dragHandleElement.classList.add("hide");
dragHandleElement.classList.add('hide');
}
}
function showDragHandle() {
if (dragHandleElement) {
dragHandleElement.classList.remove("hide");
dragHandleElement.classList.remove('hide');
}
}
function hideHandleOnEditorOut(event: MouseEvent) {
if (event.target instanceof Element) {
const isInsideEditor = !!event.target.closest(".tiptap.ProseMirror");
const isInsideEditor = !!event.target.closest('.tiptap.ProseMirror');
const isHandle =
!!event.target.attributes.getNamedItem("data-drag-handle");
!!event.target.attributes.getNamedItem('data-drag-handle');
if (isInsideEditor || isHandle) return;
}
hideDragHandle();
@@ -209,28 +209,28 @@ export function DragHandlePlugin(
const handleBySelector = options.dragHandleSelector
? document.querySelector<HTMLElement>(options.dragHandleSelector)
: null;
dragHandleElement = handleBySelector ?? document.createElement("div");
dragHandleElement = handleBySelector ?? document.createElement('div');
dragHandleElement.draggable = true;
dragHandleElement.dataset.dragHandle = "";
dragHandleElement.classList.add("drag-handle");
dragHandleElement.dataset.dragHandle = '';
dragHandleElement.classList.add('drag-handle');
function onDragHandleDragStart(e: DragEvent) {
handleDragStart(e, view);
}
dragHandleElement.addEventListener("dragstart", onDragHandleDragStart);
dragHandleElement.addEventListener('dragstart', onDragHandleDragStart);
function onDragHandleDrag(e: DragEvent) {
hideDragHandle();
let scrollY = window.scrollY;
if (e.clientY < options.scrollTreshold) {
window.scrollTo({ top: scrollY - 30, behavior: "smooth" });
window.scrollTo({ top: scrollY - 30, behavior: 'smooth' });
} else if (window.innerHeight - e.clientY < options.scrollTreshold) {
window.scrollTo({ top: scrollY + 30, behavior: "smooth" });
window.scrollTo({ top: scrollY + 30, behavior: 'smooth' });
}
}
dragHandleElement.addEventListener("drag", onDragHandleDrag);
dragHandleElement.addEventListener('drag', onDragHandleDrag);
hideDragHandle();
@@ -238,8 +238,8 @@ export function DragHandlePlugin(
view?.dom?.parentElement?.appendChild(dragHandleElement);
}
view?.dom?.parentElement?.parentElement?.addEventListener(
"mouseleave",
hideHandleOnEditorOut
'mouseleave',
hideHandleOnEditorOut,
);
return {
@@ -247,15 +247,15 @@ export function DragHandlePlugin(
if (!handleBySelector) {
dragHandleElement?.remove?.();
}
dragHandleElement?.removeEventListener("drag", onDragHandleDrag);
dragHandleElement?.removeEventListener('drag', onDragHandleDrag);
dragHandleElement?.removeEventListener(
"dragstart",
onDragHandleDragStart
'dragstart',
onDragHandleDragStart,
);
dragHandleElement = null;
view?.dom?.parentElement?.parentElement?.removeEventListener(
"mouseleave",
hideHandleOnEditorOut
'mouseleave',
hideHandleOnEditorOut,
);
},
};
@@ -272,10 +272,10 @@ export function DragHandlePlugin(
y: event.clientY,
});
const notDragging = node?.closest(".not-draggable");
const notDragging = node?.closest('.not-draggable');
const excludedTagList = options.excludedTags
.concat(["ol", "ul"])
.join(", ");
.concat(['ol', 'ul'])
.join(', ');
if (
!(node instanceof Element) ||
@@ -298,7 +298,7 @@ export function DragHandlePlugin(
rect.top += (lineHeight - 24) / 2;
rect.top += paddingTop;
// Li markers
if (node.matches("ul:not([data-type=taskList]) li, ol li")) {
if (node.matches('ul:not([data-type=taskList]) li, ol li')) {
rect.left -= options.dragHandleWidth;
}
rect.width = options.dragHandleWidth;
@@ -317,10 +317,10 @@ export function DragHandlePlugin(
},
// dragging class is used for CSS
dragstart: (view) => {
view.dom.classList.add("dragging");
view.dom.classList.add('dragging');
},
drop: (view, event) => {
view.dom.classList.remove("dragging");
view.dom.classList.remove('dragging');
hideDragHandle();
let droppedNode: Node | null = null;
const dropPos = view.posAtCoords({
@@ -338,25 +338,25 @@ export function DragHandlePlugin(
const resolvedPos = view.state.doc.resolve(dropPos.pos);
const isDroppedInsideList =
resolvedPos.parent.type.name === "listItem";
resolvedPos.parent.type.name === 'listItem';
// If the selected node is a list item and is not dropped inside a list, we need to wrap it inside <ol> tag otherwise ol list items will be transformed into ul list item when dropped
if (
view.state.selection instanceof NodeSelection &&
view.state.selection.node.type.name === "listItem" &&
view.state.selection.node.type.name === 'listItem' &&
!isDroppedInsideList &&
listType == "OL"
listType == 'OL'
) {
const newList = view.state.schema.nodes.orderedList?.createAndFill(
null,
droppedNode
droppedNode,
);
const slice = new Slice(Fragment.from(newList), 0, 0);
view.dragging = { slice, move: event.ctrlKey };
}
},
dragend: (view) => {
view.dom.classList.remove("dragging");
view.dom.classList.remove('dragging');
},
},
},
@@ -364,7 +364,7 @@ export function DragHandlePlugin(
}
const GlobalDragHandle = Extension.create({
name: "globalDragHandle",
name: 'globalDragHandle',
addOptions() {
return {
@@ -377,7 +377,7 @@ const GlobalDragHandle = Extension.create({
addProseMirrorPlugins() {
return [
DragHandlePlugin({
pluginKey: "globalDragHandle",
pluginKey: 'globalDragHandle',
dragHandleWidth: this.options.dragHandleWidth,
scrollTreshold: this.options.scrollTreshold,
dragHandleSelector: this.options.dragHandleSelector,

View File

@@ -1,22 +1,22 @@
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
import Link from "@tiptap/extension-link";
import TextAlign from "@tiptap/extension-text-align";
import Paragraph from "@tiptap/extension-paragraph";
import Heading from "@tiptap/extension-heading";
import CodeBlock from "@tiptap/extension-code-block";
import TextStyle from "@tiptap/extension-text-style";
import { Color } from "@tiptap/extension-color";
import TaskItem from "@tiptap/extension-task-item";
import TaskList from "@tiptap/extension-task-list";
import Placeholder from "@tiptap/extension-placeholder";
import GlobalDragHandle from "./dragHandle";
import { ButtonExtension } from "./ButtonExtension";
import { SlashCommand, getSlashCommandSuggestions } from "./SlashCommand";
import { VariableExtension } from "./VariableExtension";
import { getVariableSuggestions } from "../nodes/variable";
import { UnsubscribeFooterExtension } from "./UnsubsubscribeExtension";
import { ResizableImageExtension, UploadFn } from "./ImageExtension";
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import Link from '@tiptap/extension-link';
import TextAlign from '@tiptap/extension-text-align';
import Paragraph from '@tiptap/extension-paragraph';
import Heading from '@tiptap/extension-heading';
import CodeBlock from '@tiptap/extension-code-block';
import TextStyle from '@tiptap/extension-text-style';
import { Color } from '@tiptap/extension-color';
import TaskItem from '@tiptap/extension-task-item';
import TaskList from '@tiptap/extension-task-list';
import Placeholder from '@tiptap/extension-placeholder';
import GlobalDragHandle from './dragHandle';
import { ButtonExtension } from './ButtonExtension';
import { SlashCommand, getSlashCommandSuggestions } from './SlashCommand';
import { VariableExtension } from './VariableExtension';
import { getVariableSuggestions } from '../nodes/variable';
import { UnsubscribeFooterExtension } from './UnsubsubscribeExtension';
import { ResizableImageExtension, UploadFn } from './ImageExtension';
export function extensions({
variables,
@@ -31,25 +31,25 @@ export function extensions({
levels: [1, 2, 3],
},
dropcursor: {
color: "#555",
color: '#555',
width: 3,
},
code: {
HTMLAttributes: {
class:
"p-0.5 px-2 bg-slate-200 text-black text-sm rounded tracking-normal font-normal",
'p-0.5 px-2 bg-slate-200 text-black text-sm rounded tracking-normal font-normal',
},
},
blockquote: {
HTMLAttributes: {
class: "not-prose border-l-4 border-gray-300 pl-4 mt-4 mb-4",
class: 'not-prose border-l-4 border-gray-300 pl-4 mt-4 mb-4',
},
},
}),
Underline,
Link.configure({
HTMLAttributes: {
class: "underline cursor-pointer",
class: 'underline cursor-pointer',
},
openOnClick: false,
}),
@@ -59,7 +59,7 @@ export function extensions({
CodeBlock.configure({
HTMLAttributes: {
class:
"p-4 bg-slate-800 text-gray-100 text-sm rounded-md tracking-normal font-normal",
'p-4 bg-slate-800 text-gray-100 text-sm rounded-md tracking-normal font-normal',
},
}),
Heading.configure({

View File

@@ -1,4 +1,4 @@
import { useCallback, useLayoutEffect, useRef } from "react";
import { useCallback, useLayoutEffect, useRef } from 'react';
export const useEvent = <T extends (...args: any[]) => any>(handler: T): T => {
const handlerRef = useRef<T | null>(null);
@@ -9,7 +9,7 @@ export const useEvent = <T extends (...args: any[]) => any>(handler: T): T => {
return useCallback((...args: Parameters<T>): ReturnType<T> => {
if (handlerRef.current === null) {
throw new Error("Handler is not assigned");
throw new Error('Handler is not assigned');
}
return handlerRef.current(...args);
}, []) as T;

View File

@@ -1,3 +1,3 @@
import "./styles/index.css";
import './styles/index.css';
export * from "./editor";
export * from './editor';

View File

@@ -1,19 +1,19 @@
import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react";
import React, { useCallback, useState } from "react";
import { BubbleMenu as BaseBubbleMenu } from '@tiptap/react';
import React, { useCallback, useState } from 'react';
import { MenuProps } from "../types";
import { LinkPreviewPanel } from "../components/panels/LinkPreviewPanel";
import { LinkEditorPanel } from "../components/panels/LinkEditorPanel";
import { MenuProps } from '../types';
import { LinkPreviewPanel } from '../components/panels/LinkPreviewPanel';
import { LinkEditorPanel } from '../components/panels/LinkEditorPanel';
export const LinkMenu = ({ editor, appendTo }: MenuProps): React.ReactNode => {
const [showEdit, setShowEdit] = useState(false);
const shouldShow = useCallback(() => {
const isActive = editor.isActive("link");
const isActive = editor.isActive('link');
return isActive;
}, [editor]);
const { href: link } = editor.getAttributes("link");
const { href: link } = editor.getAttributes('link');
const handleEdit = useCallback(() => {
setShowEdit(true);
@@ -24,16 +24,16 @@ export const LinkMenu = ({ editor, appendTo }: MenuProps): React.ReactNode => {
editor
.chain()
.focus()
.extendMarkRange("link")
.setLink({ href: url, target: "_blank" })
.extendMarkRange('link')
.setLink({ href: url, target: '_blank' })
.run();
setShowEdit(false);
},
[editor]
[editor],
);
const onUnsetLink = useCallback(() => {
editor.chain().focus().extendMarkRange("link").unsetLink().run();
editor.chain().focus().extendMarkRange('link').unsetLink().run();
setShowEdit(false);
return null;
}, [editor]);
@@ -54,7 +54,7 @@ export const LinkMenu = ({ editor, appendTo }: MenuProps): React.ReactNode => {
updateDelay={0}
tippyOptions={{
popperOptions: {
modifiers: [{ name: "flip", enabled: false }],
modifiers: [{ name: 'flip', enabled: false }],
},
appendTo: () => {
return appendTo?.current;
@@ -63,7 +63,7 @@ export const LinkMenu = ({ editor, appendTo }: MenuProps): React.ReactNode => {
setShowEdit(false);
},
}}
className="flex gap-1 rounded-md border border-gray-200 bg-white p-1 shadow-md items-center mt-4"
className="mt-4 flex items-center gap-1 rounded-md border border-gray-200 bg-white p-1 shadow-md"
>
{showEdit ? (
<LinkEditorPanel initialUrl={link} onSetLink={onSetLink} />

View File

@@ -1,4 +1,4 @@
import { BubbleMenu, BubbleMenuProps, isTextSelection } from "@tiptap/react";
import { BubbleMenu, BubbleMenuProps, isTextSelection } from '@tiptap/react';
import {
AlignCenterIcon,
AlignLeftIcon,
@@ -19,17 +19,17 @@ import {
TextIcon,
TextQuoteIcon,
UnderlineIcon,
} from "lucide-react";
import { TextMenuButton } from "./TextMenuButton";
import { Button } from "@usesend/ui/src/button";
} from 'lucide-react';
import { TextMenuButton } from './TextMenuButton';
import { Button } from '@usesend/ui/src/button';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@usesend/ui/src/popover";
import { Separator } from "@usesend/ui/src/separator";
import { useMemo, useState } from "react";
import { LinkEditorPanel } from "../components/panels/LinkEditorPanel";
} from '@usesend/ui/src/popover';
import { Separator } from '@usesend/ui/src/separator';
import { useMemo, useState } from 'react';
import { LinkEditorPanel } from '../components/panels/LinkEditorPanel';
// import { allowedLogoAlignment } from "../nodes/logo";
export interface TextMenuItem {
@@ -40,12 +40,12 @@ export interface TextMenuItem {
icon?: LucideIcon;
}
export type TextMenuProps = Omit<BubbleMenuProps, "children">;
export type TextMenuProps = Omit<BubbleMenuProps, 'children'>;
export type ContentTypePickerOption = {
label: string;
id: string;
type: "option";
type: 'option';
disabled: () => boolean | undefined;
isActive: () => boolean | undefined;
onClick: () => void;
@@ -54,40 +54,40 @@ export type ContentTypePickerOption = {
const textColors = [
{
name: "default",
value: "#000000",
name: 'default',
value: '#000000',
},
{
name: "red",
value: "#dc2626",
name: 'red',
value: '#dc2626',
},
{
name: "green",
value: "#16a34a",
name: 'green',
value: '#16a34a',
},
{
name: "blue",
value: "#2563eb",
name: 'blue',
value: '#2563eb',
},
{
name: "yellow",
value: "#eab308",
name: 'yellow',
value: '#eab308',
},
{
name: "purple",
value: "#a855f7",
name: 'purple',
value: '#a855f7',
},
{
name: "orange",
value: "#f97316",
name: 'orange',
value: '#f97316',
},
{
name: "pink",
value: "#db2777",
name: 'pink',
value: '#db2777',
},
{
name: "gray",
value: "#6b7280",
name: 'gray',
value: '#6b7280',
},
];
@@ -95,7 +95,7 @@ export function TextMenu(props: TextMenuProps) {
const { editor } = props;
const icons = [AlignLeftIcon, AlignCenterIcon, AlignRightIcon];
const alignmentItems: TextMenuItem[] = ["left", "center", "right"].map(
const alignmentItems: TextMenuItem[] = ['left', 'center', 'right'].map(
(alignment, index) => ({
name: alignment,
isActive: () => editor?.isActive({ textAlign: alignment })!,
@@ -107,44 +107,44 @@ export function TextMenu(props: TextMenuProps) {
}
},
icon: icons[index],
})
}),
);
const items: TextMenuItem[] = useMemo(
() => [
{
name: "bold",
isActive: () => editor?.isActive("bold")!,
name: 'bold',
isActive: () => editor?.isActive('bold')!,
command: () => editor?.chain().focus().toggleBold().run()!,
icon: BoldIcon,
},
{
name: "italic",
isActive: () => editor?.isActive("italic")!,
name: 'italic',
isActive: () => editor?.isActive('italic')!,
command: () => editor?.chain().focus().toggleItalic().run()!,
icon: ItalicIcon,
},
{
name: "underline",
isActive: () => editor?.isActive("underline")!,
name: 'underline',
isActive: () => editor?.isActive('underline')!,
command: () => editor?.chain().focus().toggleUnderline().run()!,
icon: UnderlineIcon,
},
{
name: "strike",
isActive: () => editor?.isActive("strike")!,
name: 'strike',
isActive: () => editor?.isActive('strike')!,
command: () => editor?.chain().focus().toggleStrike().run()!,
icon: StrikethroughIcon,
},
{
name: "code",
isActive: () => editor?.isActive("code")!,
name: 'code',
isActive: () => editor?.isActive('code')!,
command: () => editor?.chain().focus().toggleCode().run()!,
icon: CodeIcon,
},
...alignmentItems,
],
[editor]
[editor],
);
const contentTypePickerOptions: ContentTypePickerOption[] = useMemo(
@@ -163,19 +163,19 @@ export function TextMenu(props: TextMenuProps) {
editor
?.chain()
.focus()
.lift("taskItem")
.liftListItem("listItem")
.lift('taskItem')
.liftListItem('listItem')
.setParagraph()
.run(),
id: "text",
id: 'text',
disabled: () => !editor?.can().setParagraph(),
isActive: () =>
editor?.isActive("paragraph") &&
!editor?.isActive("orderedList") &&
!editor?.isActive("bulletList") &&
!editor?.isActive("taskList"),
label: "Text",
type: "option",
editor?.isActive('paragraph') &&
!editor?.isActive('orderedList') &&
!editor?.isActive('bulletList') &&
!editor?.isActive('taskList'),
label: 'Text',
type: 'option',
},
{
icon: Heading1Icon,
@@ -183,15 +183,15 @@ export function TextMenu(props: TextMenuProps) {
editor
?.chain()
.focus()
.lift("taskItem")
.liftListItem("listItem")
.lift('taskItem')
.liftListItem('listItem')
.setHeading({ level: 1 })
.run(),
id: "heading1",
id: 'heading1',
disabled: () => !editor?.can().setHeading({ level: 1 }),
isActive: () => editor?.isActive("heading", { level: 1 }),
label: "Heading 1",
type: "option",
isActive: () => editor?.isActive('heading', { level: 1 }),
label: 'Heading 1',
type: 'option',
},
{
icon: Heading2Icon,
@@ -199,15 +199,15 @@ export function TextMenu(props: TextMenuProps) {
editor
?.chain()
?.focus()
?.lift("taskItem")
.liftListItem("listItem")
?.lift('taskItem')
.liftListItem('listItem')
.setHeading({ level: 2 })
.run(),
id: "heading2",
id: 'heading2',
disabled: () => !editor?.can().setHeading({ level: 2 }),
isActive: () => editor?.isActive("heading", { level: 2 }),
label: "Heading 2",
type: "option",
isActive: () => editor?.isActive('heading', { level: 2 }),
label: 'Heading 2',
type: 'option',
},
{
icon: Heading3Icon,
@@ -215,36 +215,36 @@ export function TextMenu(props: TextMenuProps) {
editor
?.chain()
?.focus()
?.lift("taskItem")
.liftListItem("listItem")
?.lift('taskItem')
.liftListItem('listItem')
.setHeading({ level: 3 })
.run(),
id: "heading3",
id: 'heading3',
disabled: () => !editor?.can().setHeading({ level: 3 }),
isActive: () => editor?.isActive("heading", { level: 3 }),
label: "Heading 3",
type: "option",
isActive: () => editor?.isActive('heading', { level: 3 }),
label: 'Heading 3',
type: 'option',
},
{
icon: ListIcon,
onClick: () => editor?.chain()?.focus()?.toggleBulletList()?.run(),
id: "bulletList",
id: 'bulletList',
disabled: () => !editor?.can()?.toggleBulletList(),
isActive: () => editor?.isActive("bulletList"),
label: "Bullet list",
type: "option",
isActive: () => editor?.isActive('bulletList'),
label: 'Bullet list',
type: 'option',
},
{
icon: ListOrderedIcon,
onClick: () => editor?.chain()?.focus()?.toggleOrderedList()?.run(),
id: "orderedList",
id: 'orderedList',
disabled: () => !editor?.can()?.toggleOrderedList(),
isActive: () => editor?.isActive("orderedList"),
label: "Numbered list",
type: "option",
isActive: () => editor?.isActive('orderedList'),
label: 'Numbered list',
type: 'option',
},
],
[editor, editor?.state]
[editor, editor?.state],
);
const bubbleMenuProps: TextMenuProps = {
@@ -263,13 +263,13 @@ export function TextMenu(props: TextMenuProps) {
empty ||
isEmptyTextBlock ||
!editor.isEditable ||
editor.isActive("image") ||
editor.isActive("logo") ||
editor.isActive("spacer") ||
editor.isActive("variable") ||
editor.isActive("link") ||
editor.isActive('image') ||
editor.isActive('logo') ||
editor.isActive('spacer') ||
editor.isActive('variable') ||
editor.isActive('link') ||
editor.isActive({
component: "button",
component: 'button',
})
) {
return false;
@@ -278,24 +278,24 @@ export function TextMenu(props: TextMenuProps) {
return true;
},
tippyOptions: {
maxWidth: "100%",
moveTransition: "transform 0.15s ease-out",
maxWidth: '100%',
moveTransition: 'transform 0.15s ease-out',
},
};
const selectedColor = editor?.getAttributes("textStyle")?.color;
const selectedColor = editor?.getAttributes('textStyle')?.color;
const activeItem = useMemo(
() =>
contentTypePickerOptions.find(
(option) => option.type === "option" && option.isActive()
(option) => option.type === 'option' && option.isActive(),
),
[contentTypePickerOptions]
[contentTypePickerOptions],
);
return (
<BubbleMenu
{...bubbleMenuProps}
className="flex gap-1 rounded-md border border-gray-200 bg-white shadow-md items-center"
className="flex items-center gap-1 rounded-md border border-gray-200 bg-white shadow-md"
>
<ContentTypePicker options={contentTypePickerOptions} />
<EditLinkPopover
@@ -303,7 +303,7 @@ export function TextMenu(props: TextMenuProps) {
editor
?.chain()
.focus()
.setLink({ href: url, target: "_blank" })
.setLink({ href: url, target: '_blank' })
.run();
// editor?.commands.blur();
@@ -321,28 +321,28 @@ export function TextMenu(props: TextMenuProps) {
className="hover:bg-slate-100 hover:text-slate-900"
>
<span style={{ color: selectedColor }}>A</span>
<ChevronDown className="h-4 w-4 ml-1.5 text-gray-800" />
<ChevronDown className="ml-1.5 h-4 w-4 text-gray-800" />
</Button>
</PopoverTrigger>
<PopoverContent
side="bottom"
align="start"
className="bg-white text-slate-900 w-52 px-1 border border-gray-200"
className="w-52 border border-gray-200 bg-white px-1 text-slate-900"
sideOffset={16}
>
{textColors.map((color) => (
<button
key={color.value}
onClick={() => editor?.chain().setColor(color.value).run()}
className={`flex gap-2 items-center p-1 px-2 w-full ${
className={`flex w-full items-center gap-2 p-1 px-2 ${
selectedColor === color.value ||
(selectedColor === undefined && color.value === "#000000")
? "bg-gray-200 rounded-md"
: ""
(selectedColor === undefined && color.value === '#000000')
? 'rounded-md bg-gray-200'
: ''
}`}
>
<span style={{ color: color.value }}>A</span>
<span className=" capitalize">{color.name}</span>
<span className="capitalize">{color.name}</span>
</button>
))}
</PopoverContent>
@@ -358,7 +358,7 @@ type ContentTypePickerProps = {
function ContentTypePicker({ options }: ContentTypePickerProps) {
const activeOption = useMemo(
() => options.find((option) => option.isActive()),
[options]
[options],
);
return (
@@ -366,16 +366,16 @@ function ContentTypePicker({ options }: ContentTypePickerProps) {
<PopoverTrigger asChild>
<Button
variant="ghost"
className="hover:bg-slate-100 hover:text-slate-600 text-slate-600 px-2"
className="px-2 text-slate-600 hover:bg-slate-100 hover:text-slate-600"
>
<span>{activeOption?.label || "Text"}</span>
<ChevronDown className="h-4 w-4 ml-1.5 text-gray-800" />
<span>{activeOption?.label || 'Text'}</span>
<ChevronDown className="ml-1.5 h-4 w-4 text-gray-800" />
</Button>
</PopoverTrigger>
<PopoverContent
side="bottom"
align="start"
className="bg-white border-gray-200 text-slate-900 w-52 px-1"
className="w-52 border-gray-200 bg-white px-1 text-slate-900"
sideOffset={16}
>
{options.map((option) => (
@@ -384,12 +384,12 @@ function ContentTypePicker({ options }: ContentTypePickerProps) {
onClick={() => {
option.onClick();
}}
className={`flex gap-2 items-center p-1 px-2 w-full ${
option.isActive() ? "bg-slate-100 rounded-md" : ""
className={`flex w-full items-center gap-2 p-1 px-2 ${
option.isActive() ? 'rounded-md bg-slate-100' : ''
}`}
>
<option.icon className="h-3.5 w-3.5" />
<span className=" capitalize">{option.label}</span>
<span className="capitalize">{option.label}</span>
</button>
))}
</PopoverContent>
@@ -407,16 +407,16 @@ function EditLinkPopover({ onSetLink }: EditLinkPopoverType) {
<PopoverTrigger asChild>
<Button
variant="ghost"
className="hover:bg-slate-100 hover:text-slate-600 text-slate-600 px-2"
className="px-2 text-slate-600 hover:bg-slate-100 hover:text-slate-600"
>
<span>Link</span>
<LinkIcon className="h-3.5 w-3.5 ml-1.5 text-gray-800" />
<LinkIcon className="ml-1.5 h-3.5 w-3.5 text-gray-800" />
</Button>
</PopoverTrigger>
<PopoverContent
side="bottom"
align="start"
className="bg-white text-slate-900 px-1 w-[17rem] py-1 border border-gray-200"
className="w-[17rem] border border-gray-200 bg-white px-1 py-1 text-slate-900"
sideOffset={16}
>
<LinkEditorPanel onSetLink={onSetLink} />

View File

@@ -1,7 +1,7 @@
import { Button } from "@usesend/ui/src/button";
import { cn } from "@usesend/ui/lib/utils";
import { Button } from '@usesend/ui/src/button';
import { cn } from '@usesend/ui/lib/utils';
import { TextMenuItem } from "./TextMenu";
import { TextMenuItem } from './TextMenu';
export function TextMenuButton(item: TextMenuItem) {
return (
@@ -10,16 +10,16 @@ export function TextMenuButton(item: TextMenuItem) {
size="sm"
onClick={item.command}
className={cn(
"px-2.5 hover:bg-slate-100 hover:text-black",
item.isActive() ? "bg-slate-300" : ""
'px-2.5 hover:bg-slate-100 hover:text-black',
item.isActive() ? 'bg-slate-300' : '',
)}
type="button"
>
{item.icon ? (
<item.icon
className={cn(
"h-3.5 w-3.5",
item.isActive() ? "text-black" : "text-slate-700"
'h-3.5 w-3.5',
item.isActive() ? 'text-black' : 'text-slate-700',
)}
/>
) : (

View File

@@ -1,4 +1,4 @@
import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
import { NodeViewProps, NodeViewWrapper } from '@tiptap/react';
import {
AlignCenterIcon,
AlignLeftIcon,
@@ -6,29 +6,29 @@ import {
BoxSelectIcon,
LinkIcon,
ScanIcon,
} from "lucide-react";
} from 'lucide-react';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@usesend/ui/src/popover";
import { cn } from "@usesend/ui/lib/utils";
import { Input } from "@usesend/ui/src/input";
import { Button } from "@usesend/ui/src/button";
import { AllowedAlignments, ButtonOptions } from "../types";
import { Separator } from "@usesend/ui/src/separator";
import { BorderWidth } from "../components/ui/icons/BorderWidth";
import { ColorPickerPopup } from "../components/ui/ColorPicker";
import { LinkEditorPanel } from "../components/panels/LinkEditorPanel";
import { useState } from "react";
} from '@usesend/ui/src/popover';
import { cn } from '@usesend/ui/lib/utils';
import { Input } from '@usesend/ui/src/input';
import { Button } from '@usesend/ui/src/button';
import { AllowedAlignments, ButtonOptions } from '../types';
import { Separator } from '@usesend/ui/src/separator';
import { BorderWidth } from '../components/ui/icons/BorderWidth';
import { ColorPickerPopup } from '../components/ui/ColorPicker';
import { LinkEditorPanel } from '../components/panels/LinkEditorPanel';
import { useState } from 'react';
import {
Tooltip,
TooltipProvider,
TooltipContent,
TooltipTrigger,
} from "@usesend/ui/src/tooltip";
} from '@usesend/ui/src/tooltip';
const alignments: Array<AllowedAlignments> = ["left", "center", "right"];
const alignments: Array<AllowedAlignments> = ['left', 'center', 'right'];
export function ButtonComponent(props: NodeViewProps) {
const {
@@ -50,7 +50,7 @@ export function ButtonComponent(props: NodeViewProps) {
return (
<NodeViewWrapper
className={`react-component ${
props.selected && "ProseMirror-selectednode"
props.selected && 'ProseMirror-selectednode'
}`}
draggable="true"
data-drag-handle=""
@@ -63,17 +63,17 @@ export function ButtonComponent(props: NodeViewProps) {
<div>
<div
className={cn(
"cursor-pointer",
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-white transition-colors disabled:pointer-events-none disabled:opacity-50",
"h-10 px-4 py-2",
"px-[32px] py-[20px] font-semibold no-underline"
'cursor-pointer',
'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-white transition-colors disabled:pointer-events-none disabled:opacity-50',
'h-10 px-4 py-2',
'px-[32px] py-[20px] font-semibold no-underline',
)}
tabIndex={-1}
style={{
backgroundColor: buttonColor,
color: textColor,
borderWidth: Number(borderWidth),
borderStyle: "solid",
borderStyle: 'solid',
borderColor: borderColor,
borderRadius: Number(_radius),
}}
@@ -85,14 +85,14 @@ export function ButtonComponent(props: NodeViewProps) {
>
<div className="relative flex max-w-full items-center">
{props.selected}
<div className="inset-0 flex items-center overflow-hidden ">
<div className="inset-0 flex items-center overflow-hidden">
<span
className={cn(
" cursor-text",
props.selected ? "text-transparent" : ""
'cursor-text',
props.selected ? 'text-transparent' : '',
)}
>
{text === "" ? "Button text" : text}
{text === '' ? 'Button text' : text}
</span>
</div>
{props.selected ? (
@@ -102,11 +102,11 @@ export function ButtonComponent(props: NodeViewProps) {
e.preventDefault();
const endPos = props.getPos() + props.node.nodeSize;
editor.commands.focus("start");
editor.commands.focus('start');
editor
.chain()
.insertContentAt(endPos, { type: "paragraph" })
.insertContentAt(endPos, { type: 'paragraph' })
.focus(endPos)
.run();
}}
@@ -134,7 +134,7 @@ export function ButtonComponent(props: NodeViewProps) {
<PopoverContent
align="start"
side="top"
className="space-y-2 w-[28rem] light border-gray-200 py-1 px-1"
className="light w-[28rem] space-y-2 border-gray-200 px-1 py-1"
sideOffset={10}
onOpenAutoFocus={(e) => e.preventDefault()}
onCloseAutoFocus={(e) => e.preventDefault()}
@@ -162,7 +162,7 @@ export function ButtonComponent(props: NodeViewProps) {
</div> */}
<TooltipProvider>
<div className="flex gap-1 items-center">
<div className="flex items-center gap-1">
<div>
<div className="flex">
{alignments.map((alignment) => (
@@ -190,7 +190,7 @@ export function ButtonComponent(props: NodeViewProps) {
))}
</div>
</div>
<Separator orientation="vertical" className=" h-6 my-auto" />
<Separator orientation="vertical" className="my-auto h-6" />
<div>
<div className="flex">
<Tooltip>
@@ -240,13 +240,13 @@ export function ButtonComponent(props: NodeViewProps) {
</Tooltip>
</div>
</div>
<Separator orientation="vertical" className=" h-6 my-auto" />
<Separator orientation="vertical" className="my-auto h-6" />
<div>
<div className="flex gap-1">
<Tooltip>
<TooltipTrigger>
<div className="flex items-center border border-transparent hover:border-border focus-within:border-border gap-1 px-1 py-0.5 rounded-md">
<ScanIcon className="text-slate-700 h-4 w-4" />
<div className="hover:border-border focus-within:border-border flex items-center gap-1 rounded-md border border-transparent px-1 py-0.5">
<ScanIcon className="h-4 w-4 text-slate-700" />
<Input
value={_radius}
onChange={(e) =>
@@ -254,7 +254,7 @@ export function ButtonComponent(props: NodeViewProps) {
borderRadius: e.target.value,
})
}
className="border-0 focus-visible:ring-0 h-6 p-0 w-5"
className="h-6 w-5 border-0 p-0 focus-visible:ring-0"
/>
</div>
</TooltipTrigger>
@@ -262,8 +262,8 @@ export function ButtonComponent(props: NodeViewProps) {
</Tooltip>
<Tooltip>
<TooltipTrigger>
<div className="flex items-center border border-transparent hover:border-border focus-within:border-border gap-1 px-1 py-0.5 rounded-md">
<BorderWidth className="text-slate-700 h-4 w-4" />
<div className="hover:border-border focus-within:border-border flex items-center gap-1 rounded-md border border-transparent px-1 py-0.5">
<BorderWidth className="h-4 w-4 text-slate-700" />
<Input
value={borderWidth}
onChange={(e) =>
@@ -271,7 +271,7 @@ export function ButtonComponent(props: NodeViewProps) {
borderWidth: e.target.value,
})
}
className="border-0 focus-visible:ring-0 h-6 p-0 w-5"
className="h-6 w-5 border-0 p-0 focus-visible:ring-0"
/>
</div>
</TooltipTrigger>
@@ -299,7 +299,7 @@ export function ButtonComponent(props: NodeViewProps) {
</Tooltip>
</div>
</div>
<Separator orientation="vertical" className=" h-6 my-auto" />
<Separator orientation="vertical" className="my-auto h-6" />
<Popover open={editUrlOpen} onOpenChange={setEditUrlOpen}>
<PopoverTrigger asChild>
<Button
@@ -309,7 +309,7 @@ export function ButtonComponent(props: NodeViewProps) {
type="button"
>
Link
<LinkIcon className="h-4 w-4 ml-2" />
<LinkIcon className="ml-2 h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="light border-gray-200 px-4 py-2">
@@ -333,11 +333,11 @@ export function ButtonComponent(props: NodeViewProps) {
}
const AlignmentIcon = ({ alignment }: { alignment: AllowedAlignments }) => {
if (alignment === "left") {
if (alignment === 'left') {
return <AlignLeftIcon className="h-4 w-4" />;
} else if (alignment === "center") {
} else if (alignment === 'center') {
return <AlignCenterIcon className="h-4 w-4" />;
} else if (alignment === "right") {
} else if (alignment === 'right') {
return <AlignRightIcon className="h-4 w-4" />;
}
return null;

View File

@@ -1,37 +1,37 @@
import { NodeViewProps } from "@tiptap/core";
import { CSSProperties, useRef, useState } from "react";
import { useEvent } from "../hooks/useEvent";
import { NodeViewWrapper } from "@tiptap/react";
import { NodeViewProps } from '@tiptap/core';
import { CSSProperties, useRef, useState } from 'react';
import { useEvent } from '../hooks/useEvent';
import { NodeViewWrapper } from '@tiptap/react';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@usesend/ui/src/popover";
} from '@usesend/ui/src/popover';
import {
ExpandIcon,
ScanIcon,
LinkIcon,
ImageIcon,
TypeIcon,
} from "lucide-react";
import { Input } from "@usesend/ui/src/input";
import { BorderWidth } from "../components/ui/icons/BorderWidth";
import { ColorPickerPopup } from "../components/ui/ColorPicker";
import { AllowedAlignments } from "../types";
import { Button } from "@usesend/ui/src/button";
import { AlignmentIcon } from "../components/ui/icons/AlignmentIcon";
} from 'lucide-react';
import { Input } from '@usesend/ui/src/input';
import { BorderWidth } from '../components/ui/icons/BorderWidth';
import { ColorPickerPopup } from '../components/ui/ColorPicker';
import { AllowedAlignments } from '../types';
import { Button } from '@usesend/ui/src/button';
import { AlignmentIcon } from '../components/ui/icons/AlignmentIcon';
import {
Tooltip,
TooltipProvider,
TooltipContent,
TooltipTrigger,
} from "@usesend/ui/src/tooltip";
import { Separator } from "@usesend/ui/src/separator";
import Spinner from "@usesend/ui/src/spinner";
import { LinkEditorPanel } from "../components/panels/LinkEditorPanel";
import { TextEditorPanel } from "../components/panels/TextEditorPanel";
} from '@usesend/ui/src/tooltip';
import { Separator } from '@usesend/ui/src/separator';
import Spinner from '@usesend/ui/src/spinner';
import { LinkEditorPanel } from '../components/panels/LinkEditorPanel';
import { TextEditorPanel } from '../components/panels/TextEditorPanel';
const alignments: Array<AllowedAlignments> = ["left", "center", "right"];
const alignments: Array<AllowedAlignments> = ['left', 'center', 'right'];
const MIN_WIDTH = 60;
@@ -41,11 +41,11 @@ export function ResizableImageTemplate(props: NodeViewProps) {
const imgRef = useRef<HTMLImageElement>(null);
const [resizingStyle, setResizingStyle] = useState<
Pick<CSSProperties, "width" | "height"> | undefined
Pick<CSSProperties, 'width' | 'height'> | undefined
>();
let {
alignment = "center",
alignment = 'center',
width,
height,
borderRadius,
@@ -62,7 +62,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
const handleMouseDown = useEvent(
(event: React.MouseEvent<HTMLDivElement>) => {
const imageParent = document.querySelector(
".ProseMirror-selectednode"
'.ProseMirror-selectednode',
) as HTMLDivElement;
if (!imgRef.current || !imageParent || !selected) {
@@ -72,17 +72,17 @@ export function ResizableImageTemplate(props: NodeViewProps) {
const imageParentWidth = imageParent.offsetWidth;
event.preventDefault();
const direction = event.currentTarget.dataset.direction || "--";
const direction = event.currentTarget.dataset.direction || '--';
const initialXPosition = event.clientX;
const currentWidth = imgRef.current.width;
const currentHeight = imgRef.current.height;
let newWidth = currentWidth;
let newHeight = currentHeight;
const transform = direction === "left" ? -1 : 1;
const transform = direction === 'left' ? -1 : 1;
const removeListeners = () => {
window.removeEventListener("mousemove", mouseMoveHandler);
window.removeEventListener("mouseup", removeListeners);
window.removeEventListener('mousemove', mouseMoveHandler);
window.removeEventListener('mouseup', removeListeners);
updateAttributes({ width: newWidth, height: newHeight });
setResizingStyle(undefined);
};
@@ -90,7 +90,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
const mouseMoveHandler = (event: MouseEvent) => {
newWidth = Math.max(
currentWidth + transform * (event.clientX - initialXPosition),
MIN_WIDTH
MIN_WIDTH,
);
if (newWidth > imageParentWidth) {
@@ -107,9 +107,9 @@ export function ResizableImageTemplate(props: NodeViewProps) {
}
};
window.addEventListener("mousemove", mouseMoveHandler);
window.addEventListener("mouseup", removeListeners);
}
window.addEventListener('mousemove', mouseMoveHandler);
window.addEventListener('mouseup', removeListeners);
},
);
const updateWidth = (_newWidth: string) => {
@@ -119,7 +119,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
}
const imageParent = document.querySelector(
".ProseMirror-selectednode"
'.ProseMirror-selectednode',
) as HTMLDivElement;
const imageParentWidth = imageParent.offsetWidth;
@@ -143,22 +143,22 @@ export function ResizableImageTemplate(props: NodeViewProps) {
});
};
function dragButton(direction: "left" | "right") {
function dragButton(direction: 'left' | 'right') {
return (
<div
role="button"
tabIndex={0}
onMouseDown={handleMouseDown}
data-direction={direction}
className=" bg-white bg-opacity-40 border rounded-3xl"
className="rounded-3xl border bg-white bg-opacity-40"
style={{
position: "absolute",
height: "60px",
width: "7px",
position: 'absolute',
height: '60px',
width: '7px',
[direction]: 5,
top: "50%",
transform: "translateY(-50%)",
cursor: "ew-resize",
top: '50%',
transform: 'translateY(-50%)',
cursor: 'ew-resize',
}}
/>
);
@@ -185,28 +185,28 @@ export function ResizableImageTemplate(props: NodeViewProps) {
borderWidth: Number(borderWidth),
borderColor,
...resizingStyle,
overflow: "hidden",
position: "relative",
overflow: 'hidden',
position: 'relative',
// Weird! Basically tiptap/prose wraps this in a span and the line height causes an annoying buffer.
lineHeight: "0px",
display: "block",
lineHeight: '0px',
display: 'block',
...({
center: { marginLeft: "auto", marginRight: "auto" },
left: { marginRight: "auto" },
right: { marginLeft: "auto" },
center: { marginLeft: 'auto', marginRight: 'auto' },
left: { marginRight: 'auto' },
right: { marginLeft: 'auto' },
}[alignment as string] || {}),
}}
>
<Popover open={props.selected && !isUploading}>
<PopoverTrigger>
{isUploading ? (
<div className="relative w-full h-full">
<div className="relative h-full w-full">
<img
{...attrs}
className="flex items-center justify-center opacity-70"
/>
<div className="absolute inset-0 flex items-center justify-center">
<Spinner className="w-8 h-8 text-foreground" />
<Spinner className="text-foreground h-8 w-8" />
</div>
</div>
) : (
@@ -215,7 +215,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
ref={imgRef}
style={{
...resizingStyle,
cursor: "default",
cursor: 'default',
marginBottom: 0,
}}
/>
@@ -223,15 +223,15 @@ export function ResizableImageTemplate(props: NodeViewProps) {
{selected && !isUploading && (
<>
{dragButton("left")}
{dragButton("right")}
{dragButton('left')}
{dragButton('right')}
</>
)}
</PopoverTrigger>
<PopoverContent
align="start"
side="top"
className="light border-gray-200 px-2 py-2 w-[32rem]"
className="light w-[32rem] border-gray-200 px-2 py-2"
sideOffset={10}
onOpenAutoFocus={(e) => e.preventDefault()}
onCloseAutoFocus={(e) => e.preventDefault()}
@@ -240,18 +240,18 @@ export function ResizableImageTemplate(props: NodeViewProps) {
<div className="flex items-center gap-1">
<Tooltip>
<TooltipTrigger>
<div className="flex items-center border border-transparent focus-within:border-border gap-2 px-1 py-0.5 rounded-md">
<ExpandIcon className="text-slate-700 h-4 w-4" />
<div className="focus-within:border-border flex items-center gap-2 rounded-md border border-transparent px-1 py-0.5">
<ExpandIcon className="h-4 w-4 text-slate-700" />
<Input
value={widthState}
onChange={(e) => updateWidth(e.target.value)}
className="border-0 focus-visible:ring-0 h-6 p-0 w-8"
className="h-6 w-8 border-0 p-0 focus-visible:ring-0"
/>
</div>
</TooltipTrigger>
<TooltipContent>Width</TooltipContent>
</Tooltip>
<Separator orientation="vertical" className="h-6 my-auto" />
<Separator orientation="vertical" className="my-auto h-6" />
{alignments.map((alignment) => (
<Tooltip key={alignment}>
<TooltipTrigger asChild>
@@ -273,12 +273,12 @@ export function ResizableImageTemplate(props: NodeViewProps) {
<TooltipContent>Align {alignment}</TooltipContent>
</Tooltip>
))}
<Separator orientation="vertical" className="h-6 my-auto" />
<Separator orientation="vertical" className="my-auto h-6" />
<Tooltip>
<TooltipTrigger>
<div className="flex items-center border border-transparent focus-within:border-border gap-2 px-1 py-0.5 rounded-md">
<ScanIcon className="text-slate-700 h-4 w-4" />
<div className="focus-within:border-border flex items-center gap-2 rounded-md border border-transparent px-1 py-0.5">
<ScanIcon className="h-4 w-4 text-slate-700" />
<Input
value={borderRadius}
onChange={(e) =>
@@ -286,7 +286,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
borderRadius: e.target.value,
})
}
className="border-0 focus-visible:ring-0 h-6 p-0 w-5"
className="h-6 w-5 border-0 p-0 focus-visible:ring-0"
/>
</div>
</TooltipTrigger>
@@ -294,8 +294,8 @@ export function ResizableImageTemplate(props: NodeViewProps) {
</Tooltip>
<Tooltip>
<TooltipTrigger>
<div className="flex items-center border border-transparent focus-within:border-border gap-2 px-1 py-0.5 rounded-md">
<BorderWidth className="text-slate-700 h-4 w-4" />
<div className="focus-within:border-border flex items-center gap-2 rounded-md border border-transparent px-1 py-0.5">
<BorderWidth className="h-4 w-4 text-slate-700" />
<Input
value={borderWidth}
onChange={(e) =>
@@ -303,7 +303,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
borderWidth: e.target.value,
})
}
className="border-0 focus-visible:ring-0 h-6 p-0 w-5"
className="h-6 w-5 border-0 p-0 focus-visible:ring-0"
/>
</div>
</TooltipTrigger>
@@ -330,7 +330,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
</TooltipTrigger>
<TooltipContent>Border color</TooltipContent>
</Tooltip>
<Separator orientation="vertical" className="h-6 my-auto" />
<Separator orientation="vertical" className="my-auto h-6" />
<Popover open={openImgSrc} onOpenChange={setOpenImgSrc}>
<PopoverTrigger asChild>
<Button
@@ -342,7 +342,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
>
<Tooltip>
<TooltipTrigger asChild>
<ImageIcon className="h-4 w-4 " />
<ImageIcon className="h-4 w-4" />
</TooltipTrigger>
<TooltipContent>Image source</TooltipContent>
</Tooltip>
@@ -371,7 +371,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
type="button"
onClick={() => setOpenAltText(true)}
>
<TypeIcon className="h-4 w-4 " />
<TypeIcon className="h-4 w-4" />
</Button>
</PopoverTrigger>
</TooltipTrigger>
@@ -400,7 +400,7 @@ export function ResizableImageTemplate(props: NodeViewProps) {
type="button"
onClick={() => setOpenLink(true)}
>
<LinkIcon className="h-4 w-4 " />
<LinkIcon className="h-4 w-4" />
</Button>
</PopoverTrigger>
</TooltipTrigger>

View File

@@ -1,5 +1,5 @@
import { NodeViewProps, NodeViewWrapper, NodeViewContent } from "@tiptap/react";
import { cn } from "@usesend/ui/lib/utils";
import { NodeViewProps, NodeViewWrapper, NodeViewContent } from '@tiptap/react';
import { cn } from '@usesend/ui/lib/utils';
export function UnsubscribeFooterComponent(props: NodeViewProps) {
return (

View File

@@ -1,16 +1,16 @@
import { NodeViewProps, NodeViewWrapper, ReactRenderer } from "@tiptap/react";
import { NodeViewProps, NodeViewWrapper, ReactRenderer } from '@tiptap/react';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@usesend/ui/src/popover";
import { cn } from "@usesend/ui/lib/utils";
import { Input } from "@usesend/ui/src/input";
import { Button } from "@usesend/ui/src/button";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { SuggestionOptions } from "@tiptap/suggestion";
import tippy, { GetReferenceClientRect } from "tippy.js";
import { CheckIcon, TriangleAlert } from "lucide-react";
} from '@usesend/ui/src/popover';
import { cn } from '@usesend/ui/lib/utils';
import { Input } from '@usesend/ui/src/input';
import { Button } from '@usesend/ui/src/button';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { SuggestionOptions } from '@tiptap/suggestion';
import tippy, { GetReferenceClientRect } from 'tippy.js';
import { CheckIcon, TriangleAlert } from 'lucide-react';
export interface VariableOptions {
name: string;
@@ -23,10 +23,10 @@ export const VariableList = forwardRef((props: any, ref) => {
const selectItem = (index: number) => {
const item = props.items[index];
console.log("item: ", item);
console.log('item: ', item);
if (item) {
props.command({ id: item, name: item, fallback: "" });
props.command({ id: item, name: item, fallback: '' });
}
};
@@ -34,19 +34,19 @@ export const VariableList = forwardRef((props: any, ref) => {
useImperativeHandle(ref, () => ({
onKeyDown: ({ event }: { event: KeyboardEvent }) => {
if (event.key === "ArrowUp") {
if (event.key === 'ArrowUp') {
setSelectedIndex(
(selectedIndex + props.items.length - 1) % props.items.length
(selectedIndex + props.items.length - 1) % props.items.length,
);
return true;
}
if (event.key === "ArrowDown") {
if (event.key === 'ArrowDown') {
setSelectedIndex((selectedIndex + 1) % props.items.length);
return true;
}
if (event.key === "Enter") {
if (event.key === 'Enter') {
selectItem(selectedIndex);
return true;
}
@@ -63,8 +63,8 @@ export const VariableList = forwardRef((props: any, ref) => {
key={index}
onClick={() => selectItem(index)}
className={cn(
"flex w-full space-x-2 rounded-md px-2 py-1 text-left text-sm text-gray-900 hover:bg-gray-100",
index === selectedIndex ? "bg-gray-200" : "bg-white"
'flex w-full space-x-2 rounded-md px-2 py-1 text-left text-sm text-gray-900 hover:bg-gray-100',
index === selectedIndex ? 'bg-gray-200' : 'bg-white',
)}
>
{item}
@@ -79,11 +79,11 @@ export const VariableList = forwardRef((props: any, ref) => {
);
});
VariableList.displayName = "VariableList";
VariableList.displayName = 'VariableList';
export function getVariableSuggestions(
variables: Array<string> = []
): Omit<SuggestionOptions, "editor"> {
variables: Array<string> = [],
): Omit<SuggestionOptions, 'editor'> {
return {
items: ({ query }) => {
return variables
@@ -107,14 +107,14 @@ export function getVariableSuggestions(
return;
}
popup = tippy("body", {
popup = tippy('body', {
getReferenceClientRect: props.clientRect as GetReferenceClientRect,
appendTo: () => document.body,
content: component.element,
showOnCreate: true,
interactive: true,
trigger: "manual",
placement: "bottom-start",
trigger: 'manual',
placement: 'bottom-start',
});
},
@@ -131,7 +131,7 @@ export function getVariableSuggestions(
},
onKeyDown(props) {
if (props.event.key === "Escape") {
if (props.event.key === 'Escape') {
popup?.[0].hide();
return true;
@@ -170,7 +170,7 @@ export function VariableComponent(props: NodeViewProps) {
return (
<NodeViewWrapper
className={`react-component inline-block ${
props.selected && "ProseMirror-selectednode"
props.selected && 'ProseMirror-selectednode'
}`}
draggable="false"
data-drag-handle=""
@@ -179,8 +179,8 @@ export function VariableComponent(props: NodeViewProps) {
<PopoverTrigger asChild>
<button
className={cn(
"inline-flex items-center justify-center rounded-md text-sm gap-1 ring-offset-white transition-colors",
"px-2 border border-gray-300 shadow-sm cursor-pointer text-foreground/80"
'inline-flex items-center justify-center gap-1 rounded-md text-sm ring-offset-white transition-colors',
'text-foreground/80 cursor-pointer border border-gray-300 px-2 shadow-sm',
)}
onClick={(e) => {
e.preventDefault();
@@ -190,19 +190,19 @@ export function VariableComponent(props: NodeViewProps) {
>
<span className="">{`{{${name}}}`}</span>
{!fallback ? (
<TriangleAlert className="w-3 h-3 text-orange-400" />
<TriangleAlert className="h-3 w-3 text-orange-400" />
) : null}
</button>
</PopoverTrigger>
<PopoverContent
align="start"
side="top"
className="space-y-2 light border-gray-200"
className="light space-y-2 border-gray-200"
sideOffset={10}
onOpenAutoFocus={(e) => e.preventDefault()}
onCloseAutoFocus={(e) => e.preventDefault()}
>
<form onSubmit={handleSubmit} className="flex gap-2 items-center">
<form onSubmit={handleSubmit} className="flex items-center gap-2">
<Input
placeholder="Fallback value"
value={fallbackValue}
@@ -215,7 +215,7 @@ export function VariableComponent(props: NodeViewProps) {
<CheckIcon className="h-4 w-4" />
</Button>
</form>
<div className="text-sm text-muted-foreground">
<div className="text-muted-foreground text-sm">
Fallback value will be used if the variable value is empty.
</div>
</PopoverContent>

View File

@@ -1,5 +1,5 @@
import { CSSProperties, Fragment } from "react";
import type { JSONContent } from "@tiptap/core";
import { CSSProperties, Fragment } from 'react';
import type { JSONContent } from '@tiptap/core';
import {
Text,
Html,
@@ -17,8 +17,8 @@ import {
Column,
render,
Code,
} from "jsx-email";
import { AllowedAlignments } from "./types";
} from 'jsx-email';
import { AllowedAlignments } from './types';
interface NodeOptions {
parent?: JSONContent;
@@ -83,19 +83,19 @@ export interface RenderConfig {
const DEFAULT_THEME: ThemeOptions = {
colors: {
heading: "rgb(17, 24, 39)",
paragraph: "rgb(55, 65, 81)",
horizontal: "rgb(234, 234, 234)",
footer: "rgb(100, 116, 139)",
blockquoteBorder: "rgb(209, 213, 219)",
codeBackground: "rgb(239, 239, 239)",
codeText: "rgb(17, 24, 39)",
link: "rgb(59, 130, 246)",
heading: 'rgb(17, 24, 39)',
paragraph: 'rgb(55, 65, 81)',
horizontal: 'rgb(234, 234, 234)',
footer: 'rgb(100, 116, 139)',
blockquoteBorder: 'rgb(209, 213, 219)',
codeBackground: 'rgb(239, 239, 239)',
codeText: 'rgb(17, 24, 39)',
link: 'rgb(59, 130, 246)',
},
fontSize: {
paragraph: "15px",
paragraph: '15px',
footer: {
size: ".8rem",
size: '.8rem',
},
},
};
@@ -103,35 +103,35 @@ const DEFAULT_THEME: ThemeOptions = {
const CODE_FONT_FAMILY =
'SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';
const allowedHeadings = ["h1", "h2", "h3"] as const;
const allowedHeadings = ['h1', 'h2', 'h3'] as const;
type AllowedHeadings = (typeof allowedHeadings)[number];
const headings: Record<AllowedHeadings, CSSProperties> = {
h1: {
fontSize: "36px",
lineHeight: "40px",
fontSize: '36px',
lineHeight: '40px',
fontWeight: 800,
},
h2: {
fontSize: "30px",
lineHeight: "36px",
fontSize: '30px',
lineHeight: '36px',
fontWeight: 700,
},
h3: {
fontSize: "24px",
lineHeight: "38px",
fontSize: '24px',
lineHeight: '38px',
fontWeight: 600,
},
};
const allowedSpacers = ["sm", "md", "lg", "xl"] as const;
const allowedSpacers = ['sm', 'md', 'lg', 'xl'] as const;
export type AllowedSpacers = (typeof allowedSpacers)[number];
const spacers: Record<AllowedSpacers, string> = {
sm: "8px",
md: "16px",
lg: "32px",
xl: "64px",
sm: '8px',
md: '16px',
lg: '32px',
xl: '64px',
};
export interface MarkType {
@@ -141,8 +141,8 @@ export interface MarkType {
}
const antialiased: CSSProperties = {
WebkitFontSmoothing: "antialiased",
MozOsxFontSmoothing: "grayscale",
WebkitFontSmoothing: 'antialiased',
MozOsxFontSmoothing: 'grayscale',
};
export function generateKey() {
@@ -154,13 +154,13 @@ export type VariableFormatter = (options: {
fallback?: string;
}) => string;
const allowedLogoSizes = ["sm", "md", "lg"] as const;
const allowedLogoSizes = ['sm', 'md', 'lg'] as const;
type AllowedLogoSizes = (typeof allowedLogoSizes)[number];
const logoSizes: Record<AllowedLogoSizes, string> = {
sm: "40px",
md: "48px",
lg: "64px",
sm: '40px',
md: '48px',
lg: '64px',
};
type EmailRendererOption = {
@@ -178,8 +178,8 @@ export class EmailRenderer {
private linkValues: Record<string, string | null> = {};
constructor(
private readonly email: JSONContent = { type: "doc", content: [] },
options: EmailRendererOption = {}
private readonly email: JSONContent = { type: 'doc', content: [] },
options: EmailRendererOption = {},
) {
this.shouldReplaceVariableValues =
options.shouldReplaceVariableValues || false;
@@ -229,8 +229,8 @@ export class EmailRenderer {
fontStyle="normal"
fontWeight={400}
webFont={{
url: "https://rsms.me/inter/font-files/Inter-Regular.woff2?v=3.19",
format: "woff2",
url: 'https://rsms.me/inter/font-files/Inter-Regular.woff2?v=3.19',
format: 'woff2',
}}
/>
<style
@@ -253,12 +253,12 @@ export class EmailRenderer {
<Body>
<Container
style={{
maxWidth: "600px",
minWidth: "300px",
width: "100%",
marginLeft: "auto",
marginRight: "auto",
padding: "0.5rem",
maxWidth: '600px',
minWidth: '300px',
width: '100%',
marginLeft: 'auto',
marginRight: 'auto',
padding: '0.5rem',
}}
>
{jsxNodes}
@@ -286,13 +286,13 @@ export class EmailRenderer {
throw new Error(`Mark type "${type}" is not supported.`);
},
<>{text}</>
<>{text}</>,
);
}
private getMappedContent(
node: JSONContent,
options?: NodeOptions
options?: NodeOptions,
): React.ReactNode[] {
return node.content
?.map((childNode) => {
@@ -308,9 +308,9 @@ export class EmailRenderer {
private renderNode(
node: JSONContent,
options: NodeOptions = {}
options: NodeOptions = {},
): React.ReactNode | null {
const type = node.type || "";
const type = node.type || '';
if (type in this) {
// @ts-expect-error - `this` is not assignable to type 'never'
@@ -322,14 +322,14 @@ export class EmailRenderer {
private unsubscribeFooter(
node: JSONContent,
options?: NodeOptions
options?: NodeOptions,
): React.ReactNode {
return (
<Container
style={{
fontSize: this.config.theme?.fontSize?.footer?.size,
lineHeight: this.config.theme?.fontSize?.footer?.lineHeight,
maxWidth: "100%",
maxWidth: '100%',
color: this.config.theme?.colors?.footer,
}}
>
@@ -340,18 +340,18 @@ export class EmailRenderer {
private paragraph(node: JSONContent, options?: NodeOptions): React.ReactNode {
const { attrs } = node;
const alignment = attrs?.textAlign || "left";
const alignment = attrs?.textAlign || 'left';
const { parent, next } = options || {};
const isParentListItem = parent?.type === "listItem";
const isNextSpacer = next?.type === "spacer";
const isParentListItem = parent?.type === 'listItem';
const isNextSpacer = next?.type === 'spacer';
return (
<Text
style={{
textAlign: alignment,
marginBottom: isParentListItem || isNextSpacer ? "0px" : "20px",
marginTop: "0px",
marginBottom: isParentListItem || isNextSpacer ? '0px' : '20px',
marginTop: '0px',
fontSize: this.config.theme?.fontSize?.paragraph,
color: this.config.theme?.colors?.paragraph,
...antialiased,
@@ -363,7 +363,7 @@ export class EmailRenderer {
}
private text(node: JSONContent, _?: NodeOptions): React.ReactNode {
const text = node.text || "&nbsp";
const text = node.text || '&nbsp';
if (node.marks) {
return this.renderMark(node);
}
@@ -384,7 +384,7 @@ export class EmailRenderer {
}
private strike(_: MarkType, text: React.ReactNode): React.ReactNode {
return <s style={{ textDecoration: "line-through" }}>{text}</s>;
return <s style={{ textDecoration: 'line-through' }}>{text}</s>;
}
private textStyle(mark: MarkType, text: React.ReactNode): React.ReactNode {
@@ -396,15 +396,15 @@ export class EmailRenderer {
private link(mark: MarkType, text: React.ReactNode): React.ReactNode {
const { attrs } = mark;
let href = attrs?.href || "#";
const target = attrs?.target || "_blank";
const rel = attrs?.rel || "noopener noreferrer nofollow";
let href = attrs?.href || '#';
const target = attrs?.target || '_blank';
const rel = attrs?.rel || 'noopener noreferrer nofollow';
// If the href value is provided, use it to replace the link
// Otherwise, use the original link
if (
typeof this.linkValues === "object" ||
typeof this.variableValues === "object"
typeof this.linkValues === 'object' ||
typeof this.variableValues === 'object'
) {
href = this.linkValues[href] || this.variableValues[href] || href;
}
@@ -415,7 +415,7 @@ export class EmailRenderer {
rel={rel}
style={{
fontWeight: 500,
textDecoration: "underline",
textDecoration: 'underline',
color: this.config.theme?.colors?.link,
}}
target={target}
@@ -430,9 +430,9 @@ export class EmailRenderer {
const { next, prev } = options || {};
const level = `h${Number(attrs?.level) || 1}`;
const alignment = attrs?.textAlign || "left";
const isNextSpacer = next?.type === "spacer";
const isPrevSpacer = prev?.type === "spacer";
const alignment = attrs?.textAlign || 'left';
const isNextSpacer = next?.type === 'spacer';
const isPrevSpacer = prev?.type === 'spacer';
const { fontSize, lineHeight, fontWeight } =
headings[level as AllowedHeadings];
@@ -444,8 +444,8 @@ export class EmailRenderer {
style={{
textAlign: alignment,
color: this.config.theme?.colors?.heading,
marginBottom: isNextSpacer ? "0px" : "12px",
marginTop: isPrevSpacer ? "0px" : "0px",
marginBottom: isNextSpacer ? '0px' : '12px',
marginTop: isPrevSpacer ? '0px' : '0px',
fontSize,
lineHeight,
fontWeight,
@@ -478,9 +478,9 @@ export class EmailRenderer {
return (
<Hr
style={{
marginTop: "32px",
marginBottom: "32px",
borderTopWidth: "2px",
marginTop: '32px',
marginBottom: '32px',
borderTopWidth: '2px',
}}
/>
);
@@ -488,13 +488,13 @@ export class EmailRenderer {
private orderedList(node: JSONContent, _?: NodeOptions): React.ReactNode {
return (
<Container style={{ maxWidth: "100%" }}>
<Container style={{ maxWidth: '100%' }}>
<ol
style={{
marginTop: "0px",
marginBottom: "20px",
paddingLeft: "26px",
listStyleType: "decimal",
marginTop: '0px',
marginBottom: '20px',
paddingLeft: '26px',
listStyleType: 'decimal',
}}
>
{this.getMappedContent(node)}
@@ -507,15 +507,15 @@ export class EmailRenderer {
return (
<Container
style={{
maxWidth: "100%",
maxWidth: '100%',
}}
>
<ul
style={{
marginTop: "0px",
marginBottom: "20px",
paddingLeft: "26px",
listStyleType: "disc",
marginTop: '0px',
marginBottom: '20px',
paddingLeft: '26px',
listStyleType: 'disc',
}}
>
{this.getMappedContent(node)}
@@ -528,13 +528,13 @@ export class EmailRenderer {
return (
<Container
style={{
maxWidth: "100%",
maxWidth: '100%',
}}
>
<li
style={{
marginBottom: "8px",
paddingLeft: "6px",
marginBottom: '8px',
paddingLeft: '6px',
...antialiased,
}}
>
@@ -555,11 +555,11 @@ export class EmailRenderer {
borderColor,
borderWidth,
// @TODO: Update the attribute to `textAlign`
alignment = "left",
alignment = 'left',
} = attrs || {};
const { next } = options || {};
const isNextSpacer = next?.type === "spacer";
const isNextSpacer = next?.type === 'spacer';
const href = this.linkValues[url] || this.variableValues[url] || url;
@@ -567,8 +567,8 @@ export class EmailRenderer {
<Container
style={{
textAlign: alignment,
maxWidth: "100%",
marginBottom: isNextSpacer ? "0px" : "20px",
maxWidth: '100%',
marginBottom: isNextSpacer ? '0px' : '20px',
}}
>
<Button
@@ -577,11 +577,11 @@ export class EmailRenderer {
color: String(textColor),
backgroundColor: buttonColor,
borderColor: borderColor,
padding: "12px 34px",
padding: '12px 34px',
borderWidth,
borderStyle: "solid",
textDecoration: "none",
fontSize: "14px",
borderStyle: 'solid',
textDecoration: 'none',
fontSize: '14px',
fontWeight: 500,
borderRadius: `${borderRadius}px`,
}}
@@ -594,7 +594,7 @@ export class EmailRenderer {
private spacer(node: JSONContent, _?: NodeOptions): React.ReactNode {
const { attrs } = node;
const { height = "auto" } = attrs || {};
const { height = 'auto' } = attrs || {};
return (
<Container
@@ -617,28 +617,28 @@ export class EmailRenderer {
title,
size,
// @TODO: Update the attribute to `textAlign`
alignment = "left",
alignment = 'left',
} = attrs || {};
const { next } = options || {};
const isNextSpacer = next?.type === "spacer";
const isNextSpacer = next?.type === 'spacer';
return (
<Row
style={{
marginTop: "0px",
marginBottom: isNextSpacer ? "0px" : "32px",
marginTop: '0px',
marginBottom: isNextSpacer ? '0px' : '32px',
}}
>
<Column align={alignment}>
<Img
alt={alt || title || "Logo"}
alt={alt || title || 'Logo'}
src={src}
style={{
width: logoSizes[size as AllowedLogoSizes] || size,
height: logoSizes[size as AllowedLogoSizes] || size,
}}
title={title || alt || "Logo"}
title={title || alt || 'Logo'}
/>
</Column>
</Row>
@@ -651,42 +651,42 @@ export class EmailRenderer {
src,
alt,
title,
width = "auto",
height = "auto",
alignment = "center",
externalLink = "",
width = 'auto',
height = 'auto',
alignment = 'center',
externalLink = '',
borderRadius,
borderColor,
borderWidth,
} = attrs || {};
const { next } = options || {};
const isNextSpacer = next?.type === "spacer";
const isNextSpacer = next?.type === 'spacer';
const mainImage = (
<Img
alt={alt || title || "Image"}
alt={alt || title || 'Image'}
src={src}
style={{
height,
width,
maxWidth: "100%",
outline: "none",
textDecoration: "none",
borderStyle: "solid",
maxWidth: '100%',
outline: 'none',
textDecoration: 'none',
borderStyle: 'solid',
borderRadius: `${borderRadius}px`,
borderColor,
borderWidth: `${borderWidth}px`,
}}
title={title || alt || "Image"}
title={title || alt || 'Image'}
/>
);
return (
<Row
style={{
marginTop: "0px",
marginBottom: isNextSpacer ? "0px" : "32px",
marginTop: '0px',
marginBottom: isNextSpacer ? '0px' : '32px',
}}
>
<Column align={alignment}>
@@ -695,9 +695,9 @@ export class EmailRenderer {
href={externalLink}
rel="noopener noreferrer"
style={{
display: "block",
maxWidth: "100%",
textDecoration: "none",
display: 'block',
maxWidth: '100%',
textDecoration: 'none',
}}
target="_blank"
>
@@ -713,23 +713,23 @@ export class EmailRenderer {
private blockquote(
node: JSONContent,
options?: NodeOptions
options?: NodeOptions,
): React.ReactNode {
const { next, prev } = options || {};
const isNextSpacer = next?.type === "spacer";
const isPrevSpacer = prev?.type === "spacer";
const isNextSpacer = next?.type === 'spacer';
const isPrevSpacer = prev?.type === 'spacer';
return (
<blockquote
style={{
borderLeftWidth: "4px",
borderLeftStyle: "solid",
borderLeftWidth: '4px',
borderLeftStyle: 'solid',
borderLeftColor: this.config.theme?.colors?.blockquoteBorder,
paddingLeft: "16px",
marginLeft: "0px",
marginRight: "0px",
marginTop: isPrevSpacer ? "0px" : "20px",
marginBottom: isNextSpacer ? "0px" : "20px",
paddingLeft: '16px',
marginLeft: '0px',
marginRight: '0px',
marginTop: isPrevSpacer ? '0px' : '20px',
marginBottom: isNextSpacer ? '0px' : '20px',
}}
>
{this.getMappedContent(node)}
@@ -743,8 +743,8 @@ export class EmailRenderer {
style={{
backgroundColor: this.config.theme?.colors?.codeBackground,
color: this.config.theme?.colors?.codeText,
padding: "2px 4px",
borderRadius: "6px",
padding: '2px 4px',
borderRadius: '6px',
fontFamily: CODE_FONT_FAMILY,
fontWeight: 400,
letterSpacing: 0,
@@ -767,7 +767,7 @@ export class EmailRenderer {
.map((n) => {
return n.text;
})
.join("")}
.join('')}
</Code>
);
}

View File

@@ -1,4 +1,4 @@
import { Editor } from "@tiptap/react";
import { Editor } from '@tiptap/react';
export interface MenuProps {
editor: Editor;
@@ -6,7 +6,7 @@ export interface MenuProps {
shouldHide?: boolean;
}
export type AllowedAlignments = "left" | "center" | "right";
export type AllowedAlignments = 'left' | 'center' | 'right';
export interface ButtonOptions {
text: string;

View File

@@ -1,7 +1,7 @@
import { type Config } from "tailwindcss";
import sharedConfig from "@usesend/tailwind-config/tailwind.config";
import { type Config } from 'tailwindcss';
import sharedConfig from '@usesend/tailwind-config/tailwind.config';
export default {
...sharedConfig,
content: ["./src/**/*.tsx", "./src/**/*.ts"],
content: ['./src/**/*.tsx', './src/**/*.ts'],
} satisfies Config;

View File

@@ -1,17 +1,17 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { defineConfig, Options } from "tsup";
import { defineConfig, Options } from 'tsup';
// eslint-disable-next-line import/no-default-export
export default defineConfig((options: Options) => ({
entry: ["src/index.ts"],
format: ["esm", "cjs"],
entry: ['src/index.ts'],
format: ['esm', 'cjs'],
banner: {
js: "'use client'",
},
dts: true,
minify: true,
clean: true,
external: ["react", "react-dom"],
external: ['react', 'react-dom'],
injectStyle: true,
...options,
}));