hezarfen_frontend
Clone
https://git.tahinli.com/Hezarfen/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | import { For, createSignal, onCleanup, onMount, type JSX } from "solid-js"; |
| 2 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 3 | import { |
| 4 | IconArrowRedo, |
| 5 | IconArrowUndo, |
| 6 | IconBold, |
| 7 | IconCodeBlock, |
| 8 | IconHeading2, |
| 9 | IconHeading3, |
| 10 | IconItalic, |
| 11 | IconLink, |
| 12 | IconListBullets, |
| 13 | IconListNumbers, |
| 14 | IconParagraph, |
| 15 | IconQuote, |
| 16 | IconStrikethrough, |
| 17 | IconUnderline, |
| 18 | } from "@/components/ui/icons"; |
| 19 | import { cn } from "@/lib/cn"; |
| 20 | import { isRichTextEmpty, sanitizeRichText, toRichTextHtml } from "@/lib/rich-text"; |
| 21 | import { useT } from "@/stores/preferences-context"; |
| 22 | |
| 23 | type Block = "p" | "h2" | "h3" | "blockquote" | "pre"; |
| 24 | type InlineState = { bold: boolean; italic: boolean; underline: boolean; strikeThrough: boolean; ul: boolean; ol: boolean; block: Block }; |
| 25 | |
| 26 | const IDLE: InlineState = { bold: false, italic: false, underline: false, strikeThrough: false, ul: false, ol: false, block: "p" }; |
| 27 | |
| 28 | /** |
| 29 | * Document-style note editor: a sticky formatting bar over a contentEditable |
| 30 | * body that grows with its text (the page scrolls, not a small box). The body |
| 31 | * is HTML — the format notes are stored in — and every paste and every value |
| 32 | * loaded from the server is sanitized before it reaches the DOM. |
| 33 | */ |
| 34 | export function NoteRichEditor(props: { |
| 35 | value: string; |
| 36 | onChange: (html: string) => void; |
| 37 | placeholder?: string; |
| 38 | /** Sticky offset for the formatting bar, e.g. below the app header. */ |
| 39 | toolbarClass?: string; |
| 40 | class?: string; |
| 41 | /** Right side of the formatting bar — the page's save control lives here. */ |
| 42 | actions?: JSX.Element; |
| 43 | /** Minimum body height; a full page wants most of the viewport, a side panel less. */ |
| 44 | bodyClass?: string; |
| 45 | }) { |
| 46 | const t = useT(); |
| 47 | let body: HTMLDivElement | undefined; |
| 48 | let savedRange: Range | null = null; |
| 49 | const [state, setState] = createSignal<InlineState>(IDLE); |
| 50 | const [empty, setEmpty] = createSignal(isRichTextEmpty(props.value)); |
| 51 | const [linkOpen, setLinkOpen] = createSignal(false); |
| 52 | const [linkInitial, setLinkInitial] = createSignal("https://"); |
| 53 | const [linkText, setLinkText] = createSignal(""); |
| 54 | |
| 55 | const emit = () => { |
| 56 | if (!body) return; |
| 57 | const blank = isRichTextEmpty(body.innerHTML); |
| 58 | setEmpty(blank); |
| 59 | // A first line typed into an empty body is a bare text node. Store it as a |
| 60 | // paragraph, so the value is recognisably HTML and its entities (`<`) |
| 61 | // are never mistaken for plain text and escaped twice on the next load. |
| 62 | const html = body.firstElementChild ? body.innerHTML : `<p>${body.innerHTML}</p>`; |
| 63 | props.onChange(blank ? "" : html); |
| 64 | }; |
| 65 | |
| 66 | const selectionInside = () => { |
| 67 | const selection = window.getSelection(); |
| 68 | return !!(body && selection && selection.rangeCount > 0 && body.contains(selection.anchorNode)); |
| 69 | }; |
| 70 | |
| 71 | const refreshState = () => { |
| 72 | if (!selectionInside()) return; |
| 73 | const block = String(document.queryCommandValue("formatBlock") || "p").toLowerCase().replace(/[<>]/g, ""); |
| 74 | setState({ |
| 75 | bold: document.queryCommandState("bold"), |
| 76 | italic: document.queryCommandState("italic"), |
| 77 | underline: document.queryCommandState("underline"), |
| 78 | strikeThrough: document.queryCommandState("strikeThrough"), |
| 79 | ul: document.queryCommandState("insertUnorderedList"), |
| 80 | ol: document.queryCommandState("insertOrderedList"), |
| 81 | block: (["h2", "h3", "blockquote", "pre"].includes(block) ? block : "p") as Block, |
| 82 | }); |
| 83 | }; |
| 84 | |
| 85 | const run = (command: string, value?: string) => { |
| 86 | body?.focus(); |
| 87 | document.execCommand(command, false, value); |
| 88 | emit(); |
| 89 | refreshState(); |
| 90 | }; |
| 91 | |
| 92 | // Clicking the active block style again returns the line to a paragraph. |
| 93 | const toggleBlock = (block: Block) => run("formatBlock", `<${state().block === block ? "p" : block}>`); |
| 94 | |
| 95 | onMount(() => { |
| 96 | if (!body) return; |
| 97 | body.innerHTML = toRichTextHtml(props.value); |
| 98 | const onSelection = () => refreshState(); |
| 99 | document.addEventListener("selectionchange", onSelection); |
| 100 | onCleanup(() => document.removeEventListener("selectionchange", onSelection)); |
| 101 | }); |
| 102 | |
| 103 | const openLink = () => { |
| 104 | const selection = window.getSelection(); |
| 105 | savedRange = selectionInside() && selection ? selection.getRangeAt(0).cloneRange() : null; |
| 106 | const anchor = selection?.anchorNode?.parentElement?.closest("a"); |
| 107 | setLinkInitial(anchor?.getAttribute("href") ?? "https://"); |
| 108 | setLinkText(savedRange?.toString().trim() || anchor?.textContent?.trim() || "—"); |
| 109 | setLinkOpen(true); |
| 110 | }; |
| 111 | |
| 112 | const applyLink = (raw: string | undefined) => { |
| 113 | body?.focus(); |
| 114 | const selection = window.getSelection(); |
| 115 | if (savedRange && selection) { |
| 116 | selection.removeAllRanges(); |
| 117 | selection.addRange(savedRange); |
| 118 | } |
| 119 | const value = raw?.trim() ?? ""; |
| 120 | if (!value || value === "https://") return run("unlink"); |
| 121 | const href = /^(https?:|mailto:)/i.test(value) ? value : `https://${value}`; |
| 122 | if (selection?.isCollapsed) { |
| 123 | const link = document.createElement("a"); |
| 124 | link.href = href; |
| 125 | link.textContent = value; |
| 126 | run("insertHTML", sanitizeRichText(link.outerHTML)); |
| 127 | } else { |
| 128 | run("createLink", href); |
| 129 | } |
| 130 | }; |
| 131 | |
| 132 | const onKeyDown = (event: KeyboardEvent) => { |
| 133 | const mod = event.metaKey || event.ctrlKey; |
| 134 | if (mod && !event.shiftKey && event.key.toLowerCase() === "k") { |
| 135 | // Inside the body ⌘K means "link"; stop it before the window-level |
| 136 | // command palette listener opens on top of the link dialog. |
| 137 | event.preventDefault(); |
| 138 | event.stopPropagation(); |
| 139 | openLink(); |
| 140 | } else if (event.key === "Tab" && (state().ul || state().ol)) { |
| 141 | event.preventDefault(); |
| 142 | run(event.shiftKey ? "outdent" : "indent"); |
| 143 | } |
| 144 | }; |
| 145 | |
| 146 | const onPaste = (event: ClipboardEvent) => { |
| 147 | const data = event.clipboardData; |
| 148 | if (!data) return; |
| 149 | event.preventDefault(); |
| 150 | const html = data.getData("text/html"); |
| 151 | if (html) run("insertHTML", sanitizeRichText(html)); |
| 152 | else run("insertText", data.getData("text/plain")); |
| 153 | }; |
| 154 | |
| 155 | type Tool = { label: () => string; icon: (p: { class?: string }) => JSX.Element; active?: () => boolean; onClick: () => void }; |
| 156 | const groups: Tool[][] = [ |
| 157 | [ |
| 158 | { label: () => t("editor.undo"), icon: IconArrowUndo, onClick: () => run("undo") }, |
| 159 | { label: () => t("editor.redo"), icon: IconArrowRedo, onClick: () => run("redo") }, |
| 160 | ], |
| 161 | [ |
| 162 | { label: () => t("editor.paragraph"), icon: IconParagraph, active: () => state().block === "p" && !state().ul && !state().ol, onClick: () => run("formatBlock", "<p>") }, |
| 163 | { label: () => t("editor.heading2"), icon: IconHeading2, active: () => state().block === "h2", onClick: () => toggleBlock("h2") }, |
| 164 | { label: () => t("editor.heading3"), icon: IconHeading3, active: () => state().block === "h3", onClick: () => toggleBlock("h3") }, |
| 165 | ], |
| 166 | [ |
| 167 | { label: () => t("editor.bold"), icon: IconBold, active: () => state().bold, onClick: () => run("bold") }, |
| 168 | { label: () => t("editor.italic"), icon: IconItalic, active: () => state().italic, onClick: () => run("italic") }, |
| 169 | { label: () => t("editor.underline"), icon: IconUnderline, active: () => state().underline, onClick: () => run("underline") }, |
| 170 | { label: () => t("editor.strike"), icon: IconStrikethrough, active: () => state().strikeThrough, onClick: () => run("strikeThrough") }, |
| 171 | { label: () => t("editor.link"), icon: IconLink, onClick: openLink }, |
| 172 | ], |
| 173 | [ |
| 174 | { label: () => t("editor.bulletList"), icon: IconListBullets, active: () => state().ul, onClick: () => run("insertUnorderedList") }, |
| 175 | { label: () => t("editor.numberedList"), icon: IconListNumbers, active: () => state().ol, onClick: () => run("insertOrderedList") }, |
| 176 | { label: () => t("editor.quote"), icon: IconQuote, active: () => state().block === "blockquote", onClick: () => toggleBlock("blockquote") }, |
| 177 | { label: () => t("editor.codeBlock"), icon: IconCodeBlock, active: () => state().block === "pre", onClick: () => toggleBlock("pre") }, |
| 178 | ], |
| 179 | ]; |
| 180 | |
| 181 | return ( |
| 182 | <div class={cn("rounded-xl border border-border bg-card shadow-xs", props.class)}> |
| 183 | <div class={cn("sticky z-20 flex items-center gap-2 rounded-t-xl border-b border-border bg-card/95 px-2 py-1.5 backdrop-blur", props.toolbarClass)}> |
| 184 | {/* One row at every width: the tools scroll sideways on a phone so the |
| 185 | save control on the right never wraps out of reach. */} |
| 186 | <div class="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto"> |
| 187 | <For each={groups}> |
| 188 | {(group, index) => ( |
| 189 | <> |
| 190 | <div class={cn("h-5 w-px shrink-0 bg-border", index() === 0 && "hidden")} /> |
| 191 | <div class="flex items-center gap-0.5"> |
| 192 | <For each={group}> |
| 193 | {(tool) => ( |
| 194 | <button |
| 195 | type="button" |
| 196 | class={cn( |
| 197 | "flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring", |
| 198 | tool.active?.() && "bg-primary/10 text-primary-text hover:bg-primary/15 hover:text-primary-text", |
| 199 | )} |
| 200 | title={tool.label()} |
| 201 | aria-label={tool.label()} |
| 202 | aria-pressed={tool.active ? tool.active() : undefined} |
| 203 | // Keep the caret in the body: a focused button would drop the selection. |
| 204 | onMouseDown={(event) => event.preventDefault()} |
| 205 | onClick={tool.onClick} |
| 206 | > |
| 207 | {tool.icon({ class: "h-4 w-4" })} |
| 208 | </button> |
| 209 | )} |
| 210 | </For> |
| 211 | </div> |
| 212 | </> |
| 213 | )} |
| 214 | </For> |
| 215 | </div> |
| 216 | <div class="flex shrink-0 items-center gap-2">{props.actions}</div> |
| 217 | </div> |
| 218 | <div class="relative px-5 py-5 sm:px-8 sm:py-7"> |
| 219 | <div |
| 220 | ref={body} |
| 221 | role="textbox" |
| 222 | aria-multiline="true" |
| 223 | aria-label={props.placeholder} |
| 224 | contentEditable |
| 225 | class={cn("note-prose outline-hidden", props.bodyClass ?? "min-h-[max(55vh,320px)]")} |
| 226 | data-empty={empty() ? "true" : "false"} |
| 227 | data-placeholder={props.placeholder ?? ""} |
| 228 | onFocus={() => document.execCommand("defaultParagraphSeparator", false, "p")} |
| 229 | onInput={emit} |
| 230 | onKeyDown={onKeyDown} |
| 231 | onPaste={onPaste} |
| 232 | onKeyUp={refreshState} |
| 233 | onMouseUp={refreshState} |
| 234 | /> |
| 235 | </div> |
| 236 | |
| 237 | <ConfirmDialog |
| 238 | open={linkOpen()} |
| 239 | onOpenChange={setLinkOpen} |
| 240 | title={t("editor.linkTitle")} |
| 241 | description={t("editor.linkHint")} |
| 242 | summary={linkText()} |
| 243 | confirmLabel={t("common.save")} |
| 244 | icon={<IconLink class="h-4 w-4" />} |
| 245 | prompt={{ label: t("editor.linkUrl"), initialValue: linkInitial(), singleLine: true, maxLength: 2000 }} |
| 246 | onConfirm={applyLink} |
| 247 | /> |
| 248 | </div> |
| 249 | ); |
| 250 | } |