Working tree is now the canonical repo. Off-chain play-money + trustless on-chain (FPMM AMM + CLOB via UMA settlement), AI market factory, creator/social/distribution, mobile shell + push, one-command demo + deploy-kit. Secrets excluded (see ENV-AND-KEYS.md). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
313 lines
9.6 KiB
TypeScript
313 lines
9.6 KiB
TypeScript
import CharacterCount from '@tiptap/extension-character-count'
|
|
import Placeholder from '@tiptap/extension-placeholder'
|
|
import type { Content, JSONContent } from '@tiptap/react'
|
|
import { Editor, EditorContent, Extensions, useEditor } from '@tiptap/react'
|
|
import StarterKit from '@tiptap/starter-kit'
|
|
import clsx from 'clsx'
|
|
import Iframe from 'common/util/tiptap-iframe'
|
|
import { TiptapSpoiler } from 'common/util/tiptap-spoiler'
|
|
import { debounce, noop } from 'lodash'
|
|
import { ReactNode, useCallback, useEffect, useMemo, useRef } from 'react'
|
|
import { DisplayContractMention } from '../editor/contract-mention/contract-mention-extension'
|
|
import { EmojiExtension } from '../editor/emoji/emoji-extension'
|
|
import { FloatingFormatMenu } from '../editor/floating-format-menu'
|
|
import { BasicImage, DisplayImage, MediumDisplayImage } from '../editor/image'
|
|
import { DisplayLink } from '../editor/link-extension'
|
|
import { nodeViewMiddleware } from '../editor/nodeview-middleware'
|
|
import { DisplaySpoiler } from '../editor/spoiler'
|
|
import { StickyFormatMenu } from '../editor/sticky-format-menu'
|
|
import GridComponent from '../editor/tiptap-grid-cards'
|
|
import { DisplayTweet } from '../editor/tweet'
|
|
import { Upload, useUploadMutation } from '../editor/upload-extension'
|
|
import {
|
|
DisplayMention,
|
|
createDisplayMention,
|
|
} from '../editor/user-mention/mention-extension'
|
|
import { generateReact, insertContent } from '../editor/utils'
|
|
import { Linkify } from './linkify'
|
|
|
|
import { useEvent } from 'client-common/hooks/use-event'
|
|
import { LinkPreviewExtension } from 'web/components/editor/link-preview-extension'
|
|
|
|
import { richTextToString } from 'common/util/parse'
|
|
import {
|
|
findLinksInContent,
|
|
insertLinkPreviews,
|
|
} from 'web/components/editor/link-preview-node-view'
|
|
import { Row } from 'web/components/layout/row'
|
|
import { usePersistentLocalState } from 'web/hooks/use-persistent-local-state'
|
|
import { safeLocalStorage } from 'web/lib/util/local'
|
|
|
|
const editorExtensions = (
|
|
simple = false,
|
|
priorityUserIds?: string[]
|
|
): Extensions =>
|
|
nodeViewMiddleware([
|
|
StarterKit.configure({
|
|
heading: simple ? false : { levels: [1, 2, 3, 4] },
|
|
horizontalRule: simple ? false : {},
|
|
}),
|
|
simple ? DisplayImage : BasicImage,
|
|
EmojiExtension,
|
|
DisplayLink,
|
|
priorityUserIds?.length
|
|
? createDisplayMention(priorityUserIds)
|
|
: DisplayMention,
|
|
DisplayContractMention,
|
|
GridComponent,
|
|
Iframe,
|
|
LinkPreviewExtension,
|
|
DisplayTweet,
|
|
TiptapSpoiler.configure({ class: 'rounded-sm bg-ink-200' }),
|
|
Upload,
|
|
])
|
|
|
|
// also see tailwind.config.js
|
|
const proseClass = (size: 'sm' | 'md' | 'lg') =>
|
|
clsx(
|
|
'prose dark:prose-invert max-w-none leading-relaxed',
|
|
'prose-a:text-primary-700 prose-a:no-underline',
|
|
size === 'sm' ? 'prose-sm' : 'text-md',
|
|
size !== 'lg' && 'prose-p:my-0 prose-ul:my-0 prose-ol:my-0 prose-li:my-0',
|
|
'[&>p]:prose-li:my-0',
|
|
'text-ink-900 prose-blockquote:text-teal-700',
|
|
'break-anywhere'
|
|
)
|
|
|
|
export const getEditorLocalStorageKey = (key: string) => `text ${key}`
|
|
|
|
export function useTextEditor(props: {
|
|
placeholder?: string
|
|
max?: number
|
|
defaultValue?: Content
|
|
size: 'sm' | 'md' | 'lg'
|
|
key?: string // unique key for autosave. If set, plz call `editor.commands.clearContent(true)` on submit to clear autosave
|
|
extensions?: Extensions
|
|
autofocus?: boolean
|
|
className?: string
|
|
priorityUserIds?: string[] // user IDs to prioritize in mention suggestions (e.g., contract creator first, then commenters)
|
|
}) {
|
|
const {
|
|
placeholder,
|
|
className,
|
|
max,
|
|
defaultValue,
|
|
size,
|
|
key,
|
|
autofocus,
|
|
priorityUserIds,
|
|
} = props
|
|
const simple = size === 'sm'
|
|
const [content, setContent] = usePersistentLocalState<
|
|
JSONContent | undefined
|
|
>(undefined, getEditorLocalStorageKey(key ?? ''))
|
|
const fetchingLinks = useRef<boolean>(false)
|
|
|
|
const save = useCallback(
|
|
debounce((newContent: JSONContent) => {
|
|
const oldText = richTextToString(content)
|
|
const newText = richTextToString(newContent)
|
|
if (oldText.length === 0 && newText.length === 0) {
|
|
safeLocalStorage?.removeItem(getEditorLocalStorageKey(key ?? ''))
|
|
} else {
|
|
setContent(newContent)
|
|
}
|
|
}, 500),
|
|
[]
|
|
)
|
|
|
|
const getEditorProps = () => ({
|
|
attributes: {
|
|
class: clsx(
|
|
proseClass(size),
|
|
'outline-none py-[.5em] px-4',
|
|
'prose-img:select-auto',
|
|
'[&_.ProseMirror-selectednode]:outline-dotted [&_*]:outline-primary-300', // selected img, embeds
|
|
'dark:[&_.ProseMirror-gapcursor]:after:border-white', // gap cursor
|
|
className
|
|
),
|
|
style: `min-height: ${1 + 1.625 * (simple ? 2 : 3)}em`, // 1em padding + 1.625 lines per row
|
|
},
|
|
})
|
|
|
|
const editor = useEditor({
|
|
editorProps: getEditorProps(),
|
|
onTransaction: !key
|
|
? noop
|
|
: ({ editor }) => {
|
|
save(editor.getJSON())
|
|
debouncedAddPreviewIfLinkPresent()
|
|
},
|
|
extensions: [
|
|
...editorExtensions(simple, priorityUserIds),
|
|
Placeholder.configure({
|
|
placeholder,
|
|
emptyEditorClass:
|
|
'before:content-[attr(data-placeholder)] before:text-ink-500 before:float-left before:h-0 cursor-text',
|
|
}),
|
|
CharacterCount.configure({ limit: max }),
|
|
...(props.extensions ?? []),
|
|
],
|
|
content: defaultValue ?? (key && content ? content : ''),
|
|
// idk why but `autofocus: undefined` and `autofocus: false` don't work right
|
|
...(autofocus ? { autofocus: true } : {}),
|
|
})
|
|
|
|
useEffect(() => {
|
|
// Using a dep array in the useEditor hook doesn't work, so we have to use a useEffect
|
|
editor?.setOptions({
|
|
editorProps: getEditorProps(),
|
|
})
|
|
}, [className])
|
|
|
|
const debouncedAddPreviewIfLinkPresent = useCallback(
|
|
debounce(() => addPreviewIfLinkPresent(), 500),
|
|
[]
|
|
)
|
|
|
|
const addPreviewIfLinkPresent = useEvent(async () => {
|
|
if (!editor) return
|
|
const links = findLinksInContent(editor.getJSON())
|
|
if (fetchingLinks.current) return
|
|
fetchingLinks.current = true
|
|
await insertLinkPreviews(editor, links, key)
|
|
fetchingLinks.current = false
|
|
})
|
|
|
|
const upload = useUploadMutation(editor)
|
|
if (!editor) return null
|
|
editor.storage.upload.mutation = upload
|
|
|
|
editor.setOptions({
|
|
editorProps: {
|
|
handlePaste(view, event) {
|
|
const imageFiles = getImages(event.clipboardData)
|
|
if (imageFiles.length) {
|
|
event.preventDefault()
|
|
upload.mutate(imageFiles)
|
|
return true // Prevent image in text/html from getting pasted again
|
|
}
|
|
|
|
// If the pasted content is iframe code, directly inject it
|
|
const text = event.clipboardData?.getData('text/plain').trim() ?? ''
|
|
if (isValidIframe(text)) {
|
|
insertContent(editor, text)
|
|
return true // Prevent the code from getting pasted as text
|
|
}
|
|
|
|
// Otherwise, use default paste handler
|
|
},
|
|
handleDrop(_view, event, _slice, moved) {
|
|
// if dragged from outside
|
|
if (!moved) {
|
|
event.preventDefault()
|
|
upload.mutate(getImages(event.dataTransfer))
|
|
}
|
|
},
|
|
},
|
|
})
|
|
|
|
return editor
|
|
}
|
|
|
|
const getImages = (data: DataTransfer | null) =>
|
|
Array.from(data?.files ?? []).filter((file) => file.type.startsWith('image'))
|
|
|
|
function isValidIframe(text: string) {
|
|
return /^<iframe.*<\/iframe>$/.test(text)
|
|
}
|
|
|
|
export function TextEditor(props: {
|
|
editor: Editor | null
|
|
simple?: boolean // show heading in toolbar
|
|
hideToolbar?: boolean // hide toolbar
|
|
children?: ReactNode // additional toolbar buttons
|
|
className?: string
|
|
onBlur?: () => void
|
|
}) {
|
|
const { editor, simple, hideToolbar, children, className, onBlur } = props
|
|
|
|
return (
|
|
// matches input styling
|
|
<div
|
|
className={clsx(
|
|
'border-ink-300 bg-canvas-0 focus-within:border-primary-500 focus-within:ring-primary-500 w-full overflow-hidden rounded-lg border shadow-sm transition-colors focus-within:ring-1',
|
|
className
|
|
)}
|
|
>
|
|
<FloatingFormatMenu editor={editor} advanced={!simple} />
|
|
<div className={clsx('max-h-[69vh] overflow-auto')}>
|
|
<EditorContent editor={editor} onBlur={onBlur} />
|
|
</div>
|
|
{!hideToolbar ? (
|
|
<StickyFormatMenu editor={editor}>{children}</StickyFormatMenu>
|
|
) : (
|
|
<Row className={'justify-end p-1'}>{children}</Row>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function RichContent(props: {
|
|
content: JSONContent
|
|
className?: string
|
|
size: 'sm' | 'md' | 'lg'
|
|
}) {
|
|
const { className, content, size } = props
|
|
|
|
const jsxContent = useMemo(() => {
|
|
try {
|
|
return generateReact(content, [
|
|
StarterKit,
|
|
size === 'sm'
|
|
? DisplayImage
|
|
: size === 'md'
|
|
? MediumDisplayImage
|
|
: BasicImage,
|
|
DisplayLink,
|
|
DisplayMention,
|
|
DisplayContractMention,
|
|
GridComponent,
|
|
Iframe,
|
|
LinkPreviewExtension.configure({ hideCloseButton: true }),
|
|
DisplayTweet,
|
|
DisplaySpoiler,
|
|
])
|
|
} catch (e) {
|
|
console.error('Error generating react', e, 'for content', content)
|
|
return ''
|
|
}
|
|
}, [content, size])
|
|
|
|
return (
|
|
<div
|
|
className={clsx(
|
|
'ProseMirror',
|
|
className,
|
|
proseClass(size),
|
|
String.raw`empty:prose-p:after:content-["\00a0"]` // make empty paragraphs have height
|
|
)}
|
|
>
|
|
{jsxContent}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// backwards compatibility: we used to store content as strings
|
|
export function Content(props: {
|
|
content: JSONContent | string
|
|
/** font/spacing */
|
|
size: 'sm' | 'md' | 'lg'
|
|
className?: string
|
|
}) {
|
|
const { className, size, content } = props
|
|
return typeof content === 'string' ? (
|
|
<Linkify
|
|
className={clsx('whitespace-pre-line', proseClass(size), className)}
|
|
text={content}
|
|
/>
|
|
) : (
|
|
<RichContent {...(props as any)} />
|
|
)
|
|
}
|