Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Adding a comment with mentinos

Matt Robertsc174271c05fb
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index 4406917e2..49ccd6359 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -201,6 +201,7 @@ func routes(r *web.Engine) *web.Engine {
membersApi.Post("/api/v1/posts/:number/comments", apiv1.PostComment())
membersApi.Put("/api/v1/posts/:number/comments/:id", apiv1.UpdateComment())
membersApi.Delete("/api/v1/posts/:number/comments/:id", apiv1.DeleteComment())
+ membersApi.Get("/api/v1/taggable-users", apiv1.ListTaggableUsers())
membersApi.Post("/api/v1/posts/:number/votes", apiv1.AddVote())
membersApi.Delete("/api/v1/posts/:number/votes", apiv1.RemoveVote())
membersApi.Post("/api/v1/posts/:number/subscription", apiv1.Subscribe())
diff --git a/app/handlers/apiv1/user.go b/app/handlers/apiv1/user.go
index b75ed64b0..655d201aa 100644
--- a/app/handlers/apiv1/user.go
+++ b/app/handlers/apiv1/user.go
@@ -23,6 +23,16 @@ func ListUsers() web.HandlerFunc {
}
}
+func ListTaggableUsers() web.HandlerFunc {
+ return func(c *web.Context) error {
+ allUsers := &query.GetAllUsersNames{}
+ if err := bus.Dispatch(c, allUsers); err != nil {
+ return c.Failure(err)
+ }
+ return c.Ok(allUsers.Result)
+ }
+}
+
// CreateUser is used to create new users
func CreateUser() web.HandlerFunc {
return func(c *web.Context) error {
diff --git a/app/models/dto/user.go b/app/models/dto/user.go
new file mode 100644
index 000000000..78515e402
--- /dev/null
+++ b/app/models/dto/user.go
@@ -0,0 +1,6 @@
+package dto
+
+type UserNames struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+}
diff --git a/app/models/query/user.go b/app/models/query/user.go
index c44304bba..dc2c7f1e0 100644
--- a/app/models/query/user.go
+++ b/app/models/query/user.go
@@ -1,6 +1,9 @@
package query
-import "github.com/getfider/fider/app/models/entity"
+import (
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
+)
type CountUsers struct {
Result int
@@ -44,3 +47,7 @@ type GetUserByProvider struct {
type GetAllUsers struct {
Result []*entity.User
}
+
+type GetAllUsersNames struct {
+ Result []*dto.UserNames
+}
diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.go
index 8d0f3103a..37e77cb20 100644
--- a/app/services/sqlstore/postgres/postgres.go
+++ b/app/services/sqlstore/postgres/postgres.go
@@ -99,6 +99,7 @@ func (s Service) Init() {
bus.AddHandler(getUserByID)
bus.AddHandler(getUserByProvider)
bus.AddHandler(getAllUsers)
+ bus.AddHandler(getAllUsersNames)
bus.AddHandler(createTenant)
bus.AddHandler(getFirstTenant)
diff --git a/app/services/sqlstore/postgres/user.go b/app/services/sqlstore/postgres/user.go
index 348368042..9cf5f1cf9 100644
--- a/app/services/sqlstore/postgres/user.go
+++ b/app/services/sqlstore/postgres/user.go
@@ -9,6 +9,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
@@ -387,6 +388,30 @@ func getAllUsers(ctx context.Context, q *query.GetAllUsers) error {
})
}
+func getAllUsersNames(ctx context.Context, q *query.GetAllUsersNames) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ var users []*dbUser
+ err := trx.Select(&users, `
+ SELECT id, name
+ FROM users
+ WHERE tenant_id = $1
+ AND status != $2
+ ORDER BY id`, tenant.ID, enum.UserDeleted)
+ if err != nil {
+ return errors.Wrap(err, "failed to get all users")
+ }
+
+ q.Result = make([]*dto.UserNames, len(users))
+ for i, user := range users {
+ q.Result[i] = &dto.UserNames{
+ ID: int(user.ID.Int64),
+ Name: user.Name.String,
+ }
+ }
+ return nil
+ })
+}
+
func queryUser(ctx context.Context, trx *dbx.Trx, filter string, args ...any) (*entity.User, error) {
user := dbUser{}
sql := fmt.Sprintf("SELECT id, name, email, tenant_id, role, status, avatar_type, avatar_bkey FROM users WHERE status != %d AND ", enum.UserDeleted)
diff --git a/public/components/common/form/SlateEditor2.tsx b/public/components/common/form/SlateEditor2.tsx
index d4c59d1a3..88858f5e4 100644
--- a/public/components/common/form/SlateEditor2.tsx
+++ b/public/components/common/form/SlateEditor2.tsx
@@ -1,5 +1,5 @@
import React, { useMemo, useCallback, useRef, useEffect, useState, Fragment, ReactNode } from "react"
-import { Editor, Transforms, Range, createEditor, Descendant, BaseEditor, BaseRange } from "slate"
+import { Element, Editor, Transforms, Range, createEditor, Descendant, BaseEditor, BaseRange, Node } from "slate"
import { HistoryEditor, withHistory } from "slate-history"
import { Slate, Editable, ReactEditor, withReact, useSelected, useFocused } from "slate-react"
@@ -11,19 +11,7 @@ import { actions } from "@fider/services"
import "./SlateEditor.scss"
-// export type Paragraph = { type: "paragraph"; children: Text[] }
-export type Text = { text: string }
-
-// type CustomText = {
-// bold?: boolean
-// italic?: boolean
-// code?: boolean
-// text: string
-// }
-
-// type EmptyText = {
-// text: string
-// }
+export type TextType = { text: string }
interface RenderElementProps {
attributes: React.HTMLAttributes<HTMLElement>
@@ -34,10 +22,10 @@ interface RenderElementProps {
type MentionElement = {
type: "mention"
character: string
- children: Text[]
+ children: TextType[]
}
-type ParagraphElement = {
+export type ParagraphElement = {
type: "paragraph"
children: Descendant[]
}
@@ -61,7 +49,7 @@ declare module "slate" {
interface CustomTypes {
Editor: CustomEditor
Element: CustomElement
- Text: Text
+ Text: TextType
Range: BaseRange & {
[key: string]: unknown
}
@@ -72,7 +60,16 @@ const Portal = ({ children }: { children?: ReactNode }) => {
return typeof document === "object" ? ReactDOM.createPortal(children, document.body) : null
}
-export const MentionExample = () => {
+interface CommentEditorProps {
+ initialValue?: string
+ disabled?: boolean
+ placeholder?: string
+ onChange?: (value: string) => void
+ onFocus?: React.FocusEventHandler<HTMLDivElement>
+ className?: string
+}
+
+export const CommentEditor: React.FunctionComponent<CommentEditorProps> = (props) => {
const [users, setUsers] = useState<UserNames[]>([])
const ref = useRef<HTMLDivElement | null>(null)
const [target, setTarget] = useState<Range | undefined>()
@@ -90,8 +87,7 @@ export const MentionExample = () => {
loadUsers()
}, [])
- const renderElement = useCallback((props: RenderElementProps) => <Element {...props} />, [])
- // const renderLeaf = useCallback((props: { attributes: any; leaf: any; children: any }) => <Leaf {...props} />, [])
+ const renderElement = useCallback((props: RenderElementProps) => <SlateElement {...props} />, [])
const editor = useMemo(() => withMentions(withReact(withHistory(createEditor()))), [])
const filteredUsers = users.filter((user) => user.name.toLowerCase().startsWith(search.toLowerCase())).slice(0, 10)
@@ -116,7 +112,7 @@ export const MentionExample = () => {
case "Enter":
event.preventDefault()
Transforms.select(editor, target)
- insertMention(editor, filteredUsers[index].name)
+ insertMention(editor, filteredUsers[index])
setTarget(undefined)
break
case "Escape":
@@ -140,11 +136,15 @@ export const MentionExample = () => {
}
}, [filteredUsers.length, editor, index, search, target])
+ const initialValue = props.initialValue ? deserialize(props.initialValue) : emptyValue
+
+ console.log(JSON.stringify(initialValue))
+
return (
<Slate
editor={editor}
- initialValue={emptyValue}
- onChange={() => {
+ initialValue={initialValue}
+ onChange={(descendant) => {
const { selection } = editor
if (selection && Range.isCollapsed(selection)) {
@@ -165,21 +165,25 @@ export const MentionExample = () => {
setIndex(0)
return
}
+
+ console.log(JSON.stringify(descendant))
+
+ props.onChange && props.onChange(serialize(descendant))
}
setTarget(undefined)
}}
>
- <Editable className="slate-editor" renderElement={renderElement} onKeyDown={onKeyDown} placeholder="Enter some text..." />
+ <Editable readOnly={props.disabled} className="slate-editor" renderElement={renderElement} onKeyDown={onKeyDown} placeholder={props.placeholder} />
{target && filteredUsers.length > 0 && (
<Portal>
<div ref={ref} className="slate-editor--mentions" data-cy="mentions-portal">
- {filteredUsers.map((char, i) => (
+ {filteredUsers.map((user, i) => (
<div
- key={char.name}
+ key={user.id}
onClick={() => {
Transforms.select(editor, target)
- insertMention(editor, char.name)
+ insertMention(editor, user)
setTarget(undefined)
}}
style={{
@@ -189,7 +193,7 @@ export const MentionExample = () => {
background: i === index ? "#B4D5FF" : "transparent",
}}
>
- {char.name}
+ {user.name}
</div>
))}
</div>
@@ -198,6 +202,7 @@ export const MentionExample = () => {
</Slate>
)
}
+
const withMentions = (editor: CustomEditor) => {
const { isInline, isVoid, markableVoid } = editor
@@ -216,17 +221,17 @@ const withMentions = (editor: CustomEditor) => {
return editor
}
-const insertMention = (editor: Editor, character: string) => {
+const insertMention = (editor: Editor, user: UserNames) => {
const mention: MentionElement = {
type: "mention",
- character,
- children: [{ text: "" }],
+ character: user.name,
+ children: [{ text: "@" + JSON.stringify(user) }],
}
Transforms.insertNodes(editor, mention)
Transforms.move(editor)
}
-const Element = (props: RenderElementProps) => {
+const SlateElement = (props: RenderElementProps) => {
const { attributes, children, element } = props
switch (element.type) {
case "mention":
@@ -273,14 +278,49 @@ const Mention = ({
)
}
-// export const Serialize = (nodes: Descendant[]): string => {
-// return nodes.map((n) => Node.string(n)).join("\n")
-// }
-
-// export const Deserialize = (value: string): Descendant[] => {
-// return value.split("\n").map((line) => {
-// return {
-// children: [{ text: line }],
-// } as Descendant
-// })
-// }
+const serialize = (nodes: Descendant[]): string => {
+ return nodes.map((n) => Node.string(n)).join("\n")
+}
+
+const deserialize = (markdown: string): Descendant[] => {
+ return markdown.split("\n").map((line) => {
+ const children: Descendant[] = []
+ const regex = /@{\\?"id":\\?\d+,\\?"name":\\?"[^"]+\\?"}/g
+ let lastIndex = 0
+
+ let match
+ while ((match = regex.exec(line)) !== null) {
+ // Add text before the mention
+ if (match.index > lastIndex) {
+ children.push({ text: line.slice(lastIndex, match.index) })
+ }
+
+ // Handle mention
+ try {
+ const jsonStr = match[0].replace(/\\/g, "").slice(1)
+ const mentionData = JSON.parse(jsonStr)
+ children.push({
+ type: "mention",
+ character: mentionData.name,
+ children: [{ text: match[0] }],
+ })
+ } catch (err) {
+ console.error("Error parsing mention:", err)
+ // Just add the text as a normal paragraph
+ children.push({ text: line })
+ }
+
+ lastIndex = match.index + match[0].length
+ }
+
+ // Add remaining text after last mention
+ if (lastIndex <= line.length) {
+ children.push({ text: line.slice(lastIndex) })
+ }
+
+ return {
+ type: "paragraph",
+ children,
+ }
+ })
+}
diff --git a/public/models/identity.ts b/public/models/identity.ts
index 47755d91e..d63dd2a5d 100644
--- a/public/models/identity.ts
+++ b/public/models/identity.ts
@@ -28,6 +28,11 @@ export interface User {
avatarURL: string
}
+export interface UserNames {
+ id: number
+ name: string
+}
+
export enum UserAvatarType {
Letter = "letter",
Gravatar = "gravatar",
diff --git a/public/pages/ShowPost/components/CommentInput.tsx b/public/pages/ShowPost/components/CommentInput.tsx
index 8b83a7281..aea6c2593 100644
--- a/public/pages/ShowPost/components/CommentInput.tsx
+++ b/public/pages/ShowPost/components/CommentInput.tsx
@@ -6,9 +6,10 @@ import { SignInModal } from "@fider/components"
import { cache, actions, Failure, Fider } from "@fider/services"
import { HStack } from "@fider/components/layout"
-import { Trans } from "@lingui/macro"
+import { Trans, t } from "@lingui/macro"
-import { MentionExample } from "@fider/components"
+import { CommentEditor } from "@fider/components"
+import { useFider } from "@fider/hooks"
interface CommentInputProps {
post: Post
@@ -19,8 +20,13 @@ const CACHE_TITLE_KEY = "CommentInput-Comment-"
export const CommentInput = (props: CommentInputProps) => {
const getCacheKey = () => `${CACHE_TITLE_KEY}${props.post.id}`
+ const getContentFromCache = () => {
+ return cache.session.get(getCacheKey())
+ }
+ const fider = useFider()
// const inputRef = useRef<HTMLTextAreaElement>()
+ const [content, setContent] = useState<string>((fider.session.isAuthenticated && getContentFromCache()) || "")
const [isSignInModalOpen, setIsSignInModalOpen] = useState(false)
const [attachments, setAttachments] = useState<ImageUpload[]>([])
const [error, setError] = useState<Failure | undefined>(undefined)
@@ -31,8 +37,7 @@ export const CommentInput = (props: CommentInputProps) => {
const submit = async () => {
clearError()
- const editorText = "Hello"
- const result = await actions.createComment(props.post.number, editorText, attachments)
+ const result = await actions.createComment(props.post.number, content, attachments)
if (result.ok) {
cache.session.remove(getCacheKey())
location.reload()
@@ -41,7 +46,19 @@ export const CommentInput = (props: CommentInputProps) => {
}
}
- const hasContent = true
+ const editorFocused = () => {
+ if (!fider.session.isAuthenticated) {
+ setIsSignInModalOpen(true)
+ }
+ }
+
+ const commentChanged = (newContent: string) => {
+ console.log("content changed", newContent)
+ setContent(newContent)
+ cache.session.set(getCacheKey(), newContent)
+ }
+
+ const hasContent = content?.length > 0
return (
<>
@@ -55,7 +72,13 @@ export const CommentInput = (props: CommentInputProps) => {
<UserName user={Fider.session.user} />
</div>
)}
- <MentionExample />
+ <CommentEditor
+ initialValue={content}
+ onChange={commentChanged}
+ onFocus={editorFocused}
+ disabled={!Fider.session.isAuthenticated}
+ placeholder={t({ id: "showpost.commentinput.placeholder", message: "Leave a comment" })}
+ />
{hasContent && (
<>
<MultiImageUploader field="attachments" maxUploads={2} onChange={setAttachments} />
diff --git a/public/services/actions/post.ts b/public/services/actions/post.ts
index 39b382565..f2aa7a189 100644
--- a/public/services/actions/post.ts
+++ b/public/services/actions/post.ts
@@ -1,5 +1,5 @@
import { http, Result, querystring } from "@fider/services"
-import { Post, Vote, ImageUpload } from "@fider/models"
+import { Post, Vote, ImageUpload, UserNames } from "@fider/models"
export const getAllPosts = async (): Promise<Result<Post[]>> => {
return await http.get<Post[]>("/api/v1/posts")
@@ -51,6 +51,10 @@ export const listVotes = async (postNumber: number): Promise<Result<Vote[]>> =>
return http.get<Vote[]>(`/api/v1/posts/${postNumber}/votes`)
}
+export const getTaggableUsers = async (userFilter: string): Promise<Result<UserNames[]>> => {
+ return http.get<UserNames[]>(`/api/v1/taggable-users${querystring.stringify({ query: userFilter })}`)
+}
+
export const createComment = async (postNumber: number, content: string, attachments: ImageUpload[]): Promise<Result> => {
return http.post(`/api/v1/posts/${postNumber}/comments`, { content, attachments }).then(http.event("comment", "create"))
}
diff --git a/public/services/markdown.ts b/public/services/markdown.ts
index aab88c209..496175118 100644
--- a/public/services/markdown.ts
+++ b/public/services/markdown.ts
@@ -26,6 +26,18 @@ const link = (href: string, title: string, text: string) => {
const fullRenderer = new marked.Renderer()
fullRenderer.image = () => ""
fullRenderer.link = link
+fullRenderer.text = (text: string) => {
+ console.log(JSON.stringify(/@{([^}]+)}/g.exec(text)))
+ return text.replace(/@{([^}]+)}/g, (match) => {
+ try {
+ const json = match.substring(1).replace(/&quot;/g, '"')
+ const mention = JSON.parse(json)
+ return `<a href="/users/${mention.id}" class="text-link">@${mention.name}</a>`
+ } catch {
+ return match
+ }
+ })
+}
const plainTextRenderer = new marked.Renderer()
plainTextRenderer.link = (_href, _title, text) => text