Small fixes/performance improvements

This commit is contained in:
Jon Staab
2025-01-02 10:04:28 -08:00
parent 8dfbc99a34
commit 23ae530cd4
28 changed files with 407 additions and 1189 deletions
+1 -2
View File
@@ -4,10 +4,9 @@
import {type Instance} from "tippy.js"
import {identity} from "@welshman/lib"
import {createSearch} from "@welshman/app"
import {Suggestions, SuggestionString} from "@welshman/editor"
import Icon from "@lib/components/Icon.svelte"
import Tippy from "@lib/components/Tippy.svelte"
import Suggestions from "@lib/editor/Suggestions.svelte"
import SuggestionString from "@lib/editor/SuggestionString.svelte"
export let value: string
export let options: string[]
-20
View File
@@ -1,20 +0,0 @@
<script lang="ts">
import cx from "classnames"
import type {NodeViewProps} from "@tiptap/core"
import {NodeViewWrapper} from "svelte-tiptap"
import Icon from "@lib/components/Icon.svelte"
import Button from "@lib/components/Button.svelte"
import {clip} from "@app/toast"
export let node: NodeViewProps["node"]
export let selected: NodeViewProps["selected"]
const copy = () => clip(node.attrs.lnbc)
</script>
<NodeViewWrapper class="inline">
<Button on:click={copy} class={cx("link-content", {"link-content-selected": selected})}>
<Icon icon="bolt" size={3} class="inline-block translate-y-px" />
{node.attrs.lnbc.slice(0, 16)}...
</Button>
</NodeViewWrapper>
-42
View File
@@ -1,42 +0,0 @@
<script lang="ts">
import cx from "classnames"
import type {NodeViewProps} from "@tiptap/core"
import {NodeViewWrapper} from "svelte-tiptap"
import {always, nthEq} from "@welshman/lib"
import {parse, renderAsText, ParsedType} from "@welshman/content"
import {type TrustedEvent, fromNostrURI, Address} from "@welshman/util"
import Link from "@lib/components/Link.svelte"
import {deriveEvent, entityLink} from "@app/state"
export let node: NodeViewProps["node"]
export let selected: NodeViewProps["selected"]
const renderLink = (href: string, display: string) => display
const displayEvent = (e: TrustedEvent) => {
const content = e?.tags.find(nthEq(0, "alt"))?.[1] || e?.content || ""
if (content.length < 1) {
return fromNostrURI(nevent || naddr).slice(0, 16) + "..."
}
const parsed = parse({...e, content})
// Try stripping entities, but if we get nothing back go ahead and show them
const renderEntity = always(parsed.find(p => p.type === ParsedType.Text) ? "" : "[quote]")
return renderAsText(parsed, {renderLink, renderEntity})
}
$: ({identifier, pubkey, kind, id, relays = [], nevent, naddr} = node.attrs)
$: event = deriveEvent(id || new Address(kind, pubkey, identifier).toString(), relays)
</script>
<NodeViewWrapper class="inline">
<Link
external
href={entityLink(node.attrs.nevent)}
class={cx("link-content", {"link-content-selected": selected})}>
{displayEvent($event)}
</Link>
</NodeViewWrapper>
-18
View File
@@ -1,18 +0,0 @@
<script lang="ts">
import cx from "classnames"
import type {NodeViewProps} from "@tiptap/core"
import {NodeViewWrapper} from "svelte-tiptap"
import Icon from "@lib/components/Icon.svelte"
export let node: NodeViewProps["node"]
export let selected: NodeViewProps["selected"]
</script>
<NodeViewWrapper class={cx("link-content inline", {"link-content-selected": selected})}>
{#if node.attrs.uploading}
<span class="loading loading-spinner loading-xs translate-y-[2px] scale-75" />
{:else}
<Icon icon="paperclip" size={3} class="inline-block translate-y-px" />
{/if}
{node.attrs.file.name}
</NodeViewWrapper>
-23
View File
@@ -1,23 +0,0 @@
<script lang="ts">
import cx from "classnames"
import type {NodeViewProps} from "@tiptap/core"
import {NodeViewWrapper} from "svelte-tiptap"
import {displayProfile} from "@welshman/util"
import {deriveProfile} from "@welshman/app"
import Link from "@lib/components/Link.svelte"
import {pubkeyLink} from "@app/state"
export let node: NodeViewProps["node"]
export let selected: NodeViewProps["selected"]
$: profile = deriveProfile(node.attrs.pubkey, node.attrs.relays)
</script>
<NodeViewWrapper class="inline">
<Link
external
href={pubkeyLink(node.attrs.pubkey, node.attrs.relays)}
class={cx("link-content", {"link-content-selected": selected})}>
@{displayProfile($profile)}
</Link>
</NodeViewWrapper>
-16
View File
@@ -1,16 +0,0 @@
<script lang="ts">
import type {NodeViewProps} from "@tiptap/core"
import {NodeViewWrapper} from "svelte-tiptap"
import Icon from "@lib/components/Icon.svelte"
export let node: NodeViewProps["node"]
</script>
<NodeViewWrapper class="link-content inline">
{#if node.attrs.uploading}
<span class="loading loading-spinner loading-xs translate-y-[2px] scale-75" />
{:else}
<Icon icon="paperclip" size={3} class="inline-block translate-y-px" />
{/if}
{node.attrs.file.name}
</NodeViewWrapper>
-395
View File
@@ -1,395 +0,0 @@
import type {CommandProps, Editor} from "@tiptap/core"
import {Extension} from "@tiptap/core"
import {now} from "@welshman/lib"
import type {StampedEvent, SignedEvent} from "@welshman/util"
import type {ImageAttributes, VideoAttributes} from "nostr-editor"
import {readServerConfig, uploadFile} from "nostr-tools/nip96"
import {getToken} from "nostr-tools/nip98"
import type {Node} from "prosemirror-model"
import {Plugin, PluginKey} from "prosemirror-state"
import {writable} from "svelte/store"
declare module "@tiptap/core" {
interface Commands<ReturnType> {
uploadFile: {
selectFiles: () => ReturnType
uploadFiles: () => ReturnType
getMetaTags: () => string[][]
}
}
}
export interface FileUploadOptions {
allowedMimeTypes: string[]
expiration: number
immediateUpload: boolean
hash: (file: File) => Promise<string>
sign?: (event: StampedEvent) => Promise<SignedEvent | undefined>
onDrop: (currentEditor: Editor, file: File, pos: number) => void
onComplete: (currentEditor: Editor) => void
}
interface UploadTask {
url?: string
sha256?: string
error?: string
}
function bufferToHex(buffer: ArrayBuffer) {
return Array.from(new Uint8Array(buffer))
.map(b => b.toString(16).padStart(2, "0"))
.join("")
}
export const FileUploadExtension = Extension.create<FileUploadOptions>({
name: "fileUpload",
addStorage() {
return {
loading: writable(false),
tags: [] as string[][],
}
},
addOptions() {
return {
allowedMimeTypes: [
"image/jpeg",
"image/png",
"image/gif",
"video/mp4",
"video/mpeg",
"video/webm",
],
immediateUpload: true,
expiration: 60000,
async hash(file: File) {
return bufferToHex(await crypto.subtle.digest("SHA-256", await file.arrayBuffer()))
},
onDrop() {},
onComplete() {},
}
},
addCommands() {
return {
selectFiles: () => props => {
props.tr.setMeta("selectFiles", true)
return true
},
uploadFiles: () => (props: CommandProps) => {
props.tr.setMeta("uploadFiles", true)
return true
},
getMetaTags: () =>
((props: CommandProps) => {
const tags: string[][] = []
// make sure the file uploaded is still in the editor content
props.editor.state.doc.descendants(node => {
if (!(node.type.name === "image" || node.type.name === "video")) {
return
}
const tag = props.editor.storage.fileUpload.tags.find((t: string[]) =>
t[1].includes(node.attrs.src),
)
if (tag) {
tags.push(tag)
}
})
return tags
}) as any,
}
},
addProseMirrorPlugins() {
const uploader = new Uploader(this.editor, this.options)
return [
new Plugin({
key: new PluginKey("fileUploadPlugin"),
state: {
init() {
return {}
},
apply(tr) {
setTimeout(() => {
if (tr.getMeta("selectFiles")) {
uploader.selectFiles()
tr.setMeta("selectFiles", null)
} else if (tr.getMeta("uploadFiles")) {
uploader.uploadFiles()
tr.setMeta("uploadFiles", null)
}
})
return {}
},
},
props: {
handleDrop: (_, event) => {
return uploader.handleDrop(event)
},
},
}),
]
},
})
class Uploader {
constructor(
public editor: Editor,
private options: FileUploadOptions,
) {}
get view() {
return this.editor.view
}
addFile(file: File, pos: number) {
if (
!this.options.allowedMimeTypes.some(amt => amt.split("*").every(s => file.type.includes(s)))
) {
return false
}
const {tr} = this.view.state
const [mimetype] = file.type.split("/")
const node = this.view.state.schema.nodes[mimetype].create({
file,
src: URL.createObjectURL(file),
alt: "",
uploading: false,
uploadError: null,
})
tr.insert(pos, node)
this.view.dispatch(tr)
if (this.options.immediateUpload) {
this.editor.storage.fileUpload.loading.set(true)
this.upload(node).then(() => this.editor.storage.fileUpload.loading.set(false))
}
this.options.onDrop(this.editor, file, pos)
return true
}
findNodePosition(node: Node) {
let pos = -1
this.view.state.doc.descendants((n, p) => {
if (n === node) {
pos = p
return false
}
})
return pos
}
findNodes(uploading: boolean) {
const nodes = [] as [Node, number][]
this.view.state.doc.descendants((node, pos) => {
if (!(node.type.name === "image" || node.type.name === "video")) {
return
}
if (node.attrs.sha256) {
return
}
if ((node.attrs.uploading || false) !== uploading) {
return
}
nodes.push([node, pos])
})
return nodes
}
updateNodeAttributes(nodeRef: Node, attrs: Record<string, unknown>) {
const {tr} = this.editor.view.state
const pos = this.findNodePosition(nodeRef)
if (pos === -1) return
Object.entries(attrs).forEach(
([key, value]) => value !== undefined && tr.setNodeAttribute(pos, key, value),
)
this.view.dispatch(tr)
}
onUploadDone(nodeRef: Node, response: UploadTask) {
this.findNodes(true).forEach(([node, pos]) => {
if (node.attrs.src === nodeRef.attrs.src) {
this.updateNodeAttributes(node, {
uploading: false,
src: response.url,
sha256: response.sha256,
uploadError: response.error,
})
}
})
}
async upload(node: Node) {
const {sign, hash, expiration} = this.options
const {
file,
alt,
uploadType,
uploadUrl: serverUrl,
} = node.attrs as ImageAttributes | VideoAttributes
this.updateNodeAttributes(node, {uploading: true, uploadError: null})
try {
if (uploadType === "nip96") {
const res = (await uploadNIP96({file, alt, sign: sign!, serverUrl}))!
// add the tags as received from nip-96 to the storage
this.editor.storage.fileUpload.tags.push(["imeta", ...res.tags!])
this.onUploadDone(node, res)
} else {
const res = await uploadBlossom({file, serverUrl, hash, sign, expiration})
this.editor.storage.fileUpload.tags.push([
"imeta",
`url ${res.url}`,
`size ${res.size}`,
`m ${res.type}`,
`x ${res.sha256}`,
])
this.onUploadDone(node, res)
}
} catch (error) {
const msg = error as string
this.onUploadDone(node, {error: msg})
throw new Error(msg as string)
}
}
async uploadFiles() {
const tasks = this.findNodes(false).map(([node]) => {
return this.upload(node)
})
try {
this.editor.storage.fileUpload.loading.set(true)
await Promise.all(tasks)
this.options.onComplete(this.editor)
} finally {
this.editor.storage.fileUpload.loading.set(false)
}
}
selectFiles() {
const input = document.createElement("input")
input.type = "file"
input.multiple = true
input.accept = this.options.allowedMimeTypes.join(",")
input.onchange = event => {
const files = (event.target as HTMLInputElement).files
if (files) {
Array.from(files).forEach(file => {
if (file) {
const pos = this.view.state.selection.from + 1
this.addFile(file, pos)
}
})
}
}
input.click()
}
handleDrop(event: DragEvent) {
event.preventDefault()
const pos = this.view.posAtCoords({left: event.clientX, top: event.clientY})?.pos
if (pos === undefined) return false
const file = event.dataTransfer?.files?.[0]
if (file) {
this.addFile(file, pos)
}
}
}
export interface NIP96Options {
file: File
alt?: string
serverUrl: string
expiration?: number
sign: (event: StampedEvent) => Promise<SignedEvent | undefined>
}
export async function uploadNIP96(options: NIP96Options) {
try {
const server = await readServerConfig(options.serverUrl)
const authorization = await getToken(server.api_url, "POST", options.sign as any, true)
const res = await uploadFile(options.file, server.api_url, authorization, {
alt: options.alt || "",
expiration: options.expiration?.toString() || "",
content_type: options.file.type,
})
if (res.status === "error") {
throw new Error(res.message)
}
const url = res.nip94_event?.tags.find(x => x[0] === "url")?.[1] || ""
const sha256 = res.nip94_event?.tags.find(x => x[0] === "x")?.[1] || ""
return {
url,
sha256,
tags: res.nip94_event?.tags.flatMap(item => item.join(" ")),
}
} catch (error) {
console.warn(error)
}
}
export interface BlossomOptions {
file: File
serverUrl: string
expiration?: number
hash?: (file: File) => Promise<string>
sign?: (event: StampedEvent) => Promise<SignedEvent | undefined>
}
export interface BlossomResponse {
sha256: string
size: number
type: string
uploaded: number
url: string
}
export interface BlossomResponseError {
message: string
}
export async function uploadBlossom(options: BlossomOptions) {
if (!options.hash) {
throw new Error("No hash function provided")
}
if (!options.sign) {
throw new Error("No signer provided")
}
const created_at = now()
const hash = await options.hash(options.file)
const event = await options.sign({
kind: 24242,
content: `Upload ${options.file.name}`,
created_at,
tags: [
["t", "upload"],
["x", hash],
["size", options.file.size.toString()],
["expiration", (created_at + (options.expiration || 60000)).toString()],
],
})
const data = JSON.stringify(event)
const base64 = btoa(data)
const authorization = `Nostr ${base64}`
const res = await fetch(options.serverUrl + "/upload", {
method: "PUT",
body: options.file,
headers: {
authorization,
},
})
const json = await res.json()
if (res.status === 200) {
return json as BlossomResponse
}
throw new Error((json as BlossomResponseError).message)
}
-40
View File
@@ -1,40 +0,0 @@
<script lang="ts">
import {displayPubkey, getPubkeyTagValues, getListTags} from "@welshman/util"
import {
userFollows,
deriveUserWotScore,
deriveProfile,
deriveHandleForPubkey,
displayHandle,
deriveProfileDisplay,
} from "@welshman/app"
import Avatar from "@lib/components/Avatar.svelte"
import WotScore from "@lib/components/WotScore.svelte"
export let value
const pubkey = value
const profile = deriveProfile(pubkey)
const profileDisplay = deriveProfileDisplay(pubkey)
const handle = deriveHandleForPubkey(pubkey)
const score = deriveUserWotScore(pubkey)
$: following = getPubkeyTagValues(getListTags($userFollows)).includes(pubkey)
</script>
<div class="flex max-w-full gap-3">
<div class="py-1">
<Avatar src={$profile?.picture} size={10} />
</div>
<div class="flex min-w-0 flex-col">
<div class="flex items-center gap-2">
<div class="text-bold overflow-hidden text-ellipsis">
{$profileDisplay}
</div>
<WotScore score={$score} active={following} />
</div>
<div class="overflow-hidden text-ellipsis text-sm opacity-75">
{$handle ? displayHandle($handle) : displayPubkey(pubkey)}
</div>
</div>
</div>
-5
View File
@@ -1,5 +0,0 @@
<script lang="ts">
export let value
</script>
{value}
-99
View File
@@ -1,99 +0,0 @@
<svelte:options accessors />
<script lang="ts">
import {fly, slide} from "svelte/transition"
import {clamp, throttle} from "@welshman/lib"
import Icon from "@lib/components/Icon.svelte"
import {theme} from "@app/theme"
export let term
export let search
export let select
export let component
export let loading = false
export let allowCreate = false
let index = 0
let element: Element
let items: string[] = []
$: populateItems(term)
const populateItems = throttle(300, term => {
items = $search.searchValues(term).slice(0, 5)
})
const setIndex = (newIndex: number, block: any) => {
index = clamp([0, items.length - 1], newIndex)
}
export const onKeyDown = (e: any) => {
if (["Enter", "Tab"].includes(e.code)) {
const value = items[index]
if (value) {
select(value)
return true
} else if (term && allowCreate) {
select(term)
return true
}
}
if (e.code === "Space" && term && allowCreate) {
select(term)
return true
}
if (e.code === "ArrowUp") {
setIndex(index - 1, "start")
return true
}
if (e.code === "ArrowDown") {
setIndex(index + 1, "start")
return true
}
}
</script>
{#if term}
<div
data-theme={$theme}
bind:this={element}
transition:fly|local={{duration: 200}}
class="mt-2 max-h-[350px] overflow-y-auto overflow-x-hidden shadow-xl {$$props.class} bg-alt"
style={$$props.style}>
{#if term && allowCreate && !items.includes(term)}
<button
class="white-space-nowrap block w-full min-w-0 cursor-pointer overflow-x-hidden text-ellipsis px-4 py-2 text-left transition-all hover:brightness-150"
on:mousedown|preventDefault
on:click|preventDefault={() => select(term)}>
Use "<svelte:component this={component} value={term} />"
</button>
{/if}
{#each items as value, i (value)}
<button
class="white-space-nowrap block flex w-full min-w-0 cursor-pointer items-center overflow-x-hidden text-ellipsis px-4 py-2 text-left transition-all hover:brightness-150"
on:mousedown|preventDefault
on:click|preventDefault={() => select(value)}>
{#if index === i}
<div transition:slide|local={{axis: "x"}} class="flex items-center pr-2">
<Icon icon="alt-arrow-right" />
</div>
{/if}
<svelte:component this={component} {value} />
</button>
{/each}
</div>
{#if loading}
<div transition:slide|local class="flex gap-2 px-4 py-2">
<div>
<i class="fa fa-circle-notch fa-spin" />
</div>
Loading more options...
</div>
{/if}
{/if}
-104
View File
@@ -1,104 +0,0 @@
import type {SvelteComponent, ComponentType} from "svelte"
import type {Readable} from "svelte/store"
import tippy, {type Instance} from "tippy.js"
import type {Editor} from "@tiptap/core"
import {PluginKey} from "@tiptap/pm/state"
import Suggestion from "@tiptap/suggestion"
import type {Search} from "@welshman/app"
export type SuggestionsOptions = {
char: string
name: string
editor: Editor
search: Readable<Search<any, any>>
select: (value: any, props: any) => void
allowCreate?: boolean
suggestionComponent: ComponentType
suggestionsComponent: ComponentType
}
export const createSuggestions = (options: SuggestionsOptions) =>
Suggestion({
char: options.char,
editor: options.editor,
pluginKey: new PluginKey(`suggest-${options.name}`),
command: ({editor, range, props}) => {
// increase range.to by one when the next node is of type "text"
// and starts with a space character
const nodeAfter = editor.view.state.selection.$to.nodeAfter
const overrideSpace = nodeAfter?.text?.startsWith(" ")
if (overrideSpace) {
range.to += 1
}
editor
.chain()
.focus()
.insertContentAt(range, [
{type: options.name, attrs: props},
{type: "text", text: " "},
])
.run()
window.getSelection()?.collapseToEnd()
},
allow: ({state, range}) => {
const $from = state.doc.resolve(range.from)
const type = state.schema.nodes[options.name]
return !!$from.parent.type.contentMatch.matchType(type)
},
render: () => {
let popover: Instance[]
let suggestions: SvelteComponent
const mapProps = (props: any) => ({
term: props.query,
search: options.search,
allowCreate: options.allowCreate,
component: options.suggestionComponent,
select: (value: string) => options.select(value, props),
})
return {
onStart: props => {
const target = document.createElement("div")
popover = tippy("body", {
getReferenceClientRect: props.clientRect as any,
appendTo: document.querySelector("dialog[open]") || document.body,
content: target,
showOnCreate: true,
interactive: true,
trigger: "manual",
placement: "bottom-start",
})
suggestions = new options.suggestionsComponent({target, props: mapProps(props)})
},
onUpdate: props => {
suggestions.$set(mapProps(props))
if (props.clientRect) {
popover[0].setProps({
getReferenceClientRect: props.clientRect as any,
})
}
},
onKeyDown: props => {
if (props.event.key === "Escape") {
popover[0].hide()
return true
}
return Boolean(suggestions.onKeyDown?.(props.event))
},
onExit: () => {
popover[0].destroy()
suggestions.$destroy()
},
}
},
})
-155
View File
@@ -1,155 +0,0 @@
import {nprofileEncode} from "nostr-tools/nip19"
import {SvelteNodeViewRenderer} from "svelte-tiptap"
import Placeholder from "@tiptap/extension-placeholder"
import Code from "@tiptap/extension-code"
import CodeBlock from "@tiptap/extension-code-block"
import Document from "@tiptap/extension-document"
import Dropcursor from "@tiptap/extension-dropcursor"
import Gapcursor from "@tiptap/extension-gapcursor"
import History from "@tiptap/extension-history"
import Paragraph from "@tiptap/extension-paragraph"
import Text from "@tiptap/extension-text"
import HardBreakExtension from "@tiptap/extension-hard-break"
import {
Bolt11Extension,
NProfileExtension,
NEventExtension,
NAddrExtension,
ImageExtension,
VideoExtension,
TagExtension,
} from "nostr-editor"
import type {StampedEvent} from "@welshman/util"
import {toNostrURI} from "@welshman/util"
import {signer, profileSearch} from "@welshman/app"
import {FileUploadExtension} from "./FileUpload"
import {createSuggestions} from "./Suggestions"
import EditMention from "./EditMention.svelte"
import EditEvent from "./EditEvent.svelte"
import EditImage from "./EditImage.svelte"
import EditBolt11 from "./EditBolt11.svelte"
import EditVideo from "./EditVideo.svelte"
import Suggestions from "./Suggestions.svelte"
import SuggestionProfile from "./SuggestionProfile.svelte"
import {asInline} from "./util"
import {getSetting} from "@app/state"
export {
createSuggestions,
EditMention,
EditEvent,
EditImage,
EditBolt11,
EditVideo,
Suggestions,
SuggestionProfile,
}
export * from "./util"
type UploadType = "nip96" | "blossom"
type EditorOptions = {
submit: () => void
getPubkeyHints: (pubkey: string) => string[]
submitOnEnter?: boolean
placeholder?: string
autofocus?: boolean
uploadType?: UploadType
defaultUploadUrl?: string
}
export const getEditorOptions = ({
submit,
getPubkeyHints,
submitOnEnter,
placeholder = "",
autofocus = false,
uploadType = getSetting("upload_type") as UploadType,
defaultUploadUrl = getSetting("upload_type") == "nip96"
? (getSetting("nip96_urls") as string[])[0] || "https://nostr.build"
: (getSetting("blossom_urls") as string[])[0] || "https://cdn.satellite.earth",
}: EditorOptions) => ({
autofocus,
content: "",
extensions: [
Code,
CodeBlock,
Document,
Dropcursor,
Gapcursor,
History,
Paragraph,
Text,
TagExtension,
Placeholder.configure({placeholder}),
HardBreakExtension.extend({
addKeyboardShortcuts() {
return {
"Shift-Enter": () => this.editor.commands.setHardBreak(),
"Mod-Enter": () => {
if (this.editor.getText().trim()) {
submit()
return true
}
return this.editor.commands.setHardBreak()
},
Enter: () => {
if (submitOnEnter && this.editor.getText().trim()) {
submit()
return true
}
return this.editor.commands.setHardBreak()
},
}
},
}),
Bolt11Extension.extend(asInline({addNodeView: () => SvelteNodeViewRenderer(EditBolt11)})),
NProfileExtension.extend({
addNodeView: () => SvelteNodeViewRenderer(EditMention),
renderText: props => toNostrURI(props.node.attrs.nprofile),
addProseMirrorPlugins() {
return [
createSuggestions({
char: "@",
name: "nprofile",
editor: this.editor,
search: profileSearch,
select: (pubkey: string, props: any) => {
const relays = getPubkeyHints(pubkey)
const nprofile = nprofileEncode({pubkey, relays})
return props.command({pubkey, nprofile, relays})
},
suggestionComponent: SuggestionProfile,
suggestionsComponent: Suggestions,
}),
]
},
}),
NEventExtension.extend(
asInline({
addNodeView: () => SvelteNodeViewRenderer(EditEvent),
renderText: (props: any) => toNostrURI(props.node.attrs.nevent),
}),
),
NAddrExtension.extend(
asInline({
addNodeView: () => SvelteNodeViewRenderer(EditEvent),
renderText: (props: any) => toNostrURI(props.node.attrs.nevent),
}),
),
ImageExtension.extend(
asInline({addNodeView: () => SvelteNodeViewRenderer(EditImage)}),
).configure({defaultUploadUrl, defaultUploadType: uploadType}),
VideoExtension.extend(
asInline({addNodeView: () => SvelteNodeViewRenderer(EditVideo)}),
).configure({defaultUploadUrl, defaultUploadType: uploadType}),
FileUploadExtension.configure({
immediateUpload: true,
allowedMimeTypes: ["image/*", "video/*"],
sign: (event: StampedEvent) => signer.get()!.sign(event),
}),
],
})
-96
View File
@@ -1,96 +0,0 @@
import type {JSONContent, PasteRuleMatch, InputRuleMatch} from "@tiptap/core"
import {Editor} from "@tiptap/core"
import {ctx} from "@welshman/lib"
import {Address} from "@welshman/util"
import {repository} from "@welshman/app"
export const asInline = (extend: Record<string, any>) => ({
inline: true,
group: "inline",
...extend,
})
export const createInputRuleMatch = <T extends Record<string, unknown>>(
match: RegExpMatchArray,
data: T,
): InputRuleMatch => ({index: match.index!, text: match[0], match, data})
export const createPasteRuleMatch = <T extends Record<string, unknown>>(
match: RegExpMatchArray,
data: T,
): PasteRuleMatch => ({index: match.index!, text: match[0], match, data})
export const findNodes = (type: string, json: JSONContent) => {
const results: JSONContent[] = []
for (const node of json.content || []) {
if (node.type === type) {
results.push(node)
}
for (const result of findNodes(type, node)) {
results.push(result)
}
}
return results
}
export const findMarks = (type: string, json: JSONContent) => {
const results: JSONContent[] = []
for (const node of json.content || []) {
for (const mark of node.marks || []) {
if (mark.type === type) {
results.push(mark)
}
}
for (const result of findMarks(type, node)) {
results.push(result)
}
}
return results
}
export const getEditorTags = (editor: Editor) => {
const json = editor.getJSON()
const topicTags = findMarks("tag", json).map(({attrs}: any) => [
"t",
attrs.tag.replace(/^#/, "").toLowerCase(),
])
const naddrTags = findNodes("naddr", json).map(
({attrs: {kind, pubkey, identifier, relays = []}}: any) => {
const address = new Address(kind, pubkey, identifier).toString()
return ["q", address, ctx.app.router.FromRelays(relays).getUrl(), pubkey]
},
)
const neventTags = findNodes("nevent", json).map(({attrs: {id, author, relays = []}}: any) => {
const event = repository.getEvent(id)
const pubkey = author || repository.getEvent(id)?.pubkey || ""
const scenario = event ? ctx.app.router.Event(event) : ctx.app.router.FromPubkeys([pubkey])
return ["q", id, scenario.getUrl(), pubkey]
})
const mentionTags = findNodes("nprofile", json).map(({attrs: {pubkey, relays = []}}: any) => [
"p",
pubkey,
ctx.app.router.FromRelays(relays).getUrl(),
"",
])
const imetaTags = findNodes("image", json).map(({attrs: {src, sha256}}: any) => [
"imeta",
`url ${src}`,
`x ${sha256}`,
`ox ${sha256}`,
])
return [...topicTags, ...naddrTags, ...neventTags, ...mentionTags, ...imetaTags]
}