Open platform to collect and prioritize feedback
feature: image attachments on Posts (#719)
Guilherme Oenning5ff7250b667b
diff --git a/app/actions/post.go b/app/actions/post.goindex 1bd01d084..8a89538b3 100644--- a/app/actions/post.go+++ b/app/actions/post.go@@ -46,6 +46,16 @@ func (input *CreateNewPost) Validate(user *models.User, services *app.Services)result.AddFieldFailure("title", "This has already been posted before.")}+ messages, err := validate.MultiImageUpload(nil, input.Model.Attachments, validate.MultiImageUploadOpts{+ MaxUploads: 3,+ MaxKilobytes: 5120,+ ExactRatio: false,+ })+ if err != nil {+ return validate.Error(err)+ }+ result.AddFieldFailure("attachments", messages...)+return result}@@ -92,6 +102,21 @@ func (input *UpdatePost) Validate(user *models.User, services *app.Services) *varesult.AddFieldFailure("title", "This has already been posted before.")}+ attachments, err := services.Posts.GetAttachments(post, nil)+ if err != nil {+ return validate.Error(err)+ }++ messages, err := validate.MultiImageUpload(attachments, input.Model.Attachments, validate.MultiImageUploadOpts{+ MaxUploads: 3,+ MaxKilobytes: 5120,+ ExactRatio: false,+ })+ if err != nil {+ return validate.Error(err)+ }+ result.AddFieldFailure("attachments", messages...)+input.Post = postreturn resultdiff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.goindex b9ff99ca6..923a419e9 100644--- a/app/handlers/apiv1/post.go+++ b/app/handlers/apiv1/post.go@@ -4,6 +4,7 @@ import ("github.com/getfider/fider/app/actions""github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/web"+ webutil "github.com/getfider/fider/app/pkg/web/util""github.com/getfider/fider/app/tasks")@@ -32,11 +33,22 @@ func CreatePost() web.HandlerFunc {}posts := c.Services().Posts++ err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")+ if err != nil {+ return c.Failure(err)+ }+post, err := posts.Add(input.Model.Title, input.Model.Description)if err != nil {return c.Failure(err)}+ err = c.Services().Posts.SetAttachments(post, nil, input.Model.Attachments)+ if err != nil {+ return c.Failure(err)+ }+if err := posts.AddVote(post, c.User()); err != nil {return c.Failure(err)}@@ -77,7 +89,17 @@ func UpdatePost() web.HandlerFunc {return c.HandleValidation(result)}- _, err := c.Services().Posts.Update(input.Post, input.Model.Title, input.Model.Description)+ err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")+ if err != nil {+ return c.Failure(err)+ }++ _, err = c.Services().Posts.Update(input.Post, input.Model.Title, input.Model.Description)+ if err != nil {+ return c.Failure(err)+ }++ err = c.Services().Posts.SetAttachments(input.Post, nil, input.Model.Attachments)if err != nil {return c.Failure(err)}diff --git a/app/handlers/post.go b/app/handlers/post.goindex 169a4490d..b81ef092e 100644--- a/app/handlers/post.go+++ b/app/handlers/post.go@@ -84,16 +84,22 @@ func PostDetails() web.HandlerFunc {return c.Failure(err)}+ attachments, err := c.Services().Posts.GetAttachments(post, nil)+ if err != nil {+ return c.Failure(err)+ }+return c.Page(web.Props{Title: post.Title,Description: markdown.PlainText(post.Description),ChunkName: "ShowPost.page",Data: web.Map{- "comments": comments,- "subscribed": subscribed,- "post": post,- "tags": tags,- "votes": votes,+ "comments": comments,+ "subscribed": subscribed,+ "post": post,+ "tags": tags,+ "votes": votes,+ "attachments": attachments,},})}diff --git a/app/models/feedback.go b/app/models/feedback.goindex acd040fbd..7c840c844 100644--- a/app/models/feedback.go+++ b/app/models/feedback.go@@ -43,15 +43,17 @@ func (i *Post) CanBeVoted() bool {// NewPost represents a new posttype NewPost struct {- Title string `json:"title"`- Description string `json:"description"`+ Title string `json:"title"`+ Description string `json:"description"`+ Attachments []*ImageUpload `json:"attachments"`}// UpdatePost represents a request to edit an existing posttype UpdatePost struct {- Number int `route:"number"`- Title string `json:"title"`- Description string `json:"description"`+ Number int `route:"number"`+ Title string `json:"title"`+ Description string `json:"description"`+ Attachments []*ImageUpload `json:"attachments"`}// DeletePost represents a request to delete an existing postdiff --git a/app/pkg/validate/upload.go b/app/pkg/validate/upload.goindex a279226d7..35af3a2ea 100644--- a/app/pkg/validate/upload.go+++ b/app/pkg/validate/upload.go@@ -7,6 +7,19 @@ import ("github.com/getfider/fider/app/pkg/img")+// MaxDimensionSize is the max width/height of an image. If image is bigger than this, it'll be resized.+const MaxDimensionSize = 1500++// MultiImageUploadOpts arguments to validate mulitple image upload process+type MultiImageUploadOpts struct {+ MaxUploads int+ IsRequired bool+ MinWidth int+ MinHeight int+ ExactRatio bool+ MaxKilobytes int+}+// ImageUploadOpts arguments to validate given uploadtype ImageUploadOpts struct {IsRequired bool@@ -16,6 +29,47 @@ type ImageUploadOpts struct {MaxKilobytes int}+//MultiImageUpload validates multiple image uploads+func MultiImageUpload(currentAttachments []string, uploads []*models.ImageUpload, opts MultiImageUploadOpts) ([]string, error) {+ if currentAttachments == nil {+ currentAttachments = []string{}+ }++ totalCount := len(currentAttachments)++ for _, upload := range uploads {+ if upload.Remove {+ for _, attachment := range currentAttachments {+ if attachment == upload.BlobKey {+ totalCount--+ }+ }+ } else if upload.Upload != nil {+ totalCount+++ }++ messages, err := ImageUpload(upload, ImageUploadOpts{+ IsRequired: opts.IsRequired,+ MinWidth: opts.MinWidth,+ MinHeight: opts.MinHeight,+ ExactRatio: opts.ExactRatio,+ MaxKilobytes: opts.MaxKilobytes,+ })+ if err != nil {+ return nil, err+ }+ if len(messages) > 0 {+ return messages, nil+ }+ }++ if totalCount > opts.MaxUploads {+ return []string{fmt.Sprintf("A maximum of %d attachments are allowed per post.", opts.MaxUploads)}, nil+ }++ return []string{}, nil+}+//ImageUpload validates given image uploadfunc ImageUpload(upload *models.ImageUpload, opts ImageUploadOpts) ([]string, error) {messages := []string{}@@ -35,6 +89,7 @@ func ImageUpload(upload *models.ImageUpload, opts ImageUploadOpts) ([]string, erreturn nil, err}} else {+if logo.Width < opts.MinWidth || logo.Height < opts.MinHeight {messages = append(messages, fmt.Sprintf("The image must have minimum dimensions of %dx%d pixels.", opts.MinWidth, opts.MinHeight))}@@ -46,6 +101,14 @@ func ImageUpload(upload *models.ImageUpload, opts ImageUploadOpts) ([]string, erif logo.Size > (opts.MaxKilobytes * 1024) {messages = append(messages, fmt.Sprintf("The image size must be smaller than %dKB.", opts.MaxKilobytes))}++ if logo.Height > MaxDimensionSize && logo.Width > MaxDimensionSize {+ newImageBytes, err := img.Apply(upload.Upload.Content, img.Resize(MaxDimensionSize))+ if err != nil {+ return nil, err+ }+ upload.Upload.Content = newImageBytes+ }}}diff --git a/app/pkg/validate/upload_test.go b/app/pkg/validate/upload_test.goindex bbe08256b..5e43ae1b4 100644--- a/app/pkg/validate/upload_test.go+++ b/app/pkg/validate/upload_test.go@@ -121,3 +121,69 @@ func TestValidateImageUpload_Required(t *testing.T) {Expect(err).IsNil()}}++func TestValidateMultiImageUpload(t *testing.T) {+ RegisterT(t)++ img, _ := ioutil.ReadFile(env.Path("/app/pkg/img/testdata/logo3-200w.gif"))++ uploads := []*models.ImageUpload{+ &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: img,+ },+ },+ &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: img,+ },+ },+ &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: img,+ },+ },+ }++ messages, err := validate.MultiImageUpload(nil, uploads, validate.MultiImageUploadOpts{+ MaxUploads: 2,+ MaxKilobytes: 500,+ })+ Expect(messages).HasLen(1)+ Expect(err).IsNil()+}++func TestValidateMultiImageUpload_Existing(t *testing.T) {+ RegisterT(t)++ img, _ := ioutil.ReadFile(env.Path("/app/pkg/img/testdata/logo3-200w.gif"))++ uploads := []*models.ImageUpload{+ &models.ImageUpload{+ BlobKey: "attachments/file1.png",+ Remove: true,+ },+ &models.ImageUpload{+ BlobKey: "attachments/file2.png",+ Remove: true,+ },+ &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: img,+ },+ },+ &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: img,+ },+ },+ }++ currentAttachments := []string{"attachments/file1.png", "attachments/file2.png"}+ messages, err := validate.MultiImageUpload(currentAttachments, uploads, validate.MultiImageUploadOpts{+ MaxUploads: 2,+ MaxKilobytes: 500,+ })+ Expect(messages).HasLen(0)+ Expect(err).IsNil()+}diff --git a/app/pkg/web/util/webutil.go b/app/pkg/web/util/webutil.goindex 9efeae7df..b50bfa4f4 100644--- a/app/pkg/web/util/webutil.go+++ b/app/pkg/web/util/webutil.go@@ -91,6 +91,17 @@ func GetOAuthBaseURL(ctx web.Context) string {return oauthBaseURL}+// ProcessMultiImageUpload uploads multiple image to blob (if it's a new one)+func ProcessMultiImageUpload(c web.Context, imgs []*models.ImageUpload, preffix string) error {+ for _, img := range imgs {+ err := ProcessImageUpload(c, img, preffix)+ if err != nil {+ return err+ }+ }+ return nil+}+// ProcessImageUpload uploads image to blob (if it's a new one)func ProcessImageUpload(c web.Context, img *models.ImageUpload, preffix string) error {if img.Upload != nil && len(img.Upload.Content) > 0 {diff --git a/app/pkg/web/util/webutil_test.go b/app/pkg/web/util/webutil_test.goindex 64b1d435f..81f748f73 100644--- a/app/pkg/web/util/webutil_test.go+++ b/app/pkg/web/util/webutil_test.go@@ -1,9 +1,14 @@package webutil_testimport (+ "io/ioutil""net/url""testing"+ "github.com/getfider/fider/app"+ "github.com/getfider/fider/app/pkg/di"++ "github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/env"webutil "github.com/getfider/fider/app/pkg/web/util"@@ -44,3 +49,58 @@ func TestGetOAuthBaseURL_WithPort(t *testing.T) {env.Config.HostMode = "single"Expect(webutil.GetOAuthBaseURL(ctx)).Equals("http://demo.test.fider.io:3000")}++func TestProcessImageUpload(t *testing.T) {+ RegisterT(t)++ img, _ := ioutil.ReadFile(env.Path("/app/pkg/img/testdata/logo3-200w.gif"))+ services := &app.Services{+ Blobs: di.NewBlobStorage(nil),+ }+ ctx := newContext("http://demo.test.fider.io:3000/hello-world")+ ctx.SetServices(services)++ upload := &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: img,+ ContentType: "image/gif",+ },+ }+ err := webutil.ProcessImageUpload(ctx, upload, "attachments")+ Expect(err).IsNil()+ Expect(upload.BlobKey).ContainsSubstring("attachments/")++ blob, err := services.Blobs.Get(upload.BlobKey)+ Expect(err).IsNil()+ Expect(blob.ContentType).Equals("image/gif")+ Expect(blob.Object).Equals(img)+ Expect(int(blob.Size)).Equals(len(img))+}++func TestMultiProcessImageUpload(t *testing.T) {+ RegisterT(t)++ img, _ := ioutil.ReadFile(env.Path("/app/pkg/img/testdata/logo3-200w.gif"))+ services := &app.Services{+ Blobs: di.NewBlobStorage(nil),+ }+ ctx := newContext("http://demo.test.fider.io:3000/hello-world")+ ctx.SetServices(services)++ upload1 := &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: img,+ ContentType: "image/gif",+ },+ }+ upload2 := &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: img,+ ContentType: "image/gif",+ },+ }+ err := webutil.ProcessMultiImageUpload(ctx, []*models.ImageUpload{upload1, upload2}, "attachments")+ Expect(err).IsNil()+ Expect(upload1.BlobKey).ContainsSubstring("attachments/")+ Expect(upload2.BlobKey).ContainsSubstring("attachments/")+}diff --git a/app/storage/inmemory/post.go b/app/storage/inmemory/post.goindex c685bec15..bbcde7050 100644--- a/app/storage/inmemory/post.go+++ b/app/storage/inmemory/post.go@@ -279,3 +279,13 @@ func (s *PostStorage) GetActiveSubscribers(number int, channel models.Notificati}return make([]*models.User, 0), nil}++// GetAttachments for given post or comment+func (s *PostStorage) GetAttachments(post *models.Post, comment *models.Comment) ([]string, error) {+ return make([]string, 0), nil+}++// SetAttachments on given post or comment+func (s *PostStorage) SetAttachments(post *models.Post, comment *models.Comment, attachments []*models.ImageUpload) error {+ return nil+}diff --git a/app/storage/postgres/post.go b/app/storage/postgres/post.goindex 6a31dd0eb..4d65ea47c 100644--- a/app/storage/postgres/post.go+++ b/app/storage/postgres/post.go@@ -796,3 +796,61 @@ func (s *PostStorage) ListVotes(post *models.Post, limit int) ([]*models.Vote, e}return result, nil}++// GetAttachments for given post or comment+func (s *PostStorage) GetAttachments(post *models.Post, comment *models.Comment) ([]string, error) {+ postID := post.ID+ var commentID sql.NullInt64+ if comment != nil {+ commentID.Scan(comment.ID)+ }++ type entry struct {+ BlobKey string `db:"attachment_bkey"`+ }++ entries := []*entry{}+ err := s.trx.Select(&entries, `+ SELECT attachment_bkey+ FROM attachments+ WHERE tenant_id = $1 AND post_id = $2 AND (comment_id = $3 OR ($3 IS NULL AND comment_id IS NULL))+ `, s.tenant.ID, postID, commentID)+ if err != nil {+ return nil, errors.Wrap(err, "failed to get attachments")+ }++ var result = make([]string, len(entries))+ for i, entry := range entries {+ result[i] = entry.BlobKey+ }+ return result, nil+}++// SetAttachments on given post or comment+func (s *PostStorage) SetAttachments(post *models.Post, comment *models.Comment, attachments []*models.ImageUpload) error {+ postID := post.ID+ var commentID sql.NullInt64+ if comment != nil {+ commentID.Scan(comment.ID)+ }++ for _, attachment := range attachments {+ if attachment.Remove {+ if _, err := s.trx.Execute(+ "DELETE FROM attachments WHERE tenant_id = $1 AND post_id = $2 AND (comment_id = $3 OR ($3 IS NULL AND comment_id IS NULL)) AND attachment_bkey = $4",+ s.tenant.ID, postID, commentID, attachment.BlobKey,+ ); err != nil {+ return errors.Wrap(err, "failed to delete attachment")+ }+ } else {+ if _, err := s.trx.Execute(+ "INSERT INTO attachments (tenant_id, post_id, comment_id, user_id, attachment_bkey) VALUES ($1, $2, $3, $4, $5)",+ s.tenant.ID, postID, commentID, s.user.ID, attachment.BlobKey,+ ); err != nil {+ return errors.Wrap(err, "failed to insert attachment")+ }+ }+ }++ return nil+}diff --git a/app/storage/postgres/post_test.go b/app/storage/postgres/post_test.goindex 354b26ba6..36fae140f 100644--- a/app/storage/postgres/post_test.go+++ b/app/storage/postgres/post_test.go@@ -1,12 +1,14 @@package postgres_testimport (+ "io/ioutil""testing""time""github.com/getfider/fider/app""github.com/getfider/fider/app/models". "github.com/getfider/fider/app/pkg/assert"+ "github.com/getfider/fider/app/pkg/env""github.com/getfider/fider/app/pkg/errors")@@ -549,3 +551,88 @@ func TestPostStorage_ListVotesOfPost(t *testing.T) {Expect(users[1].User.Name).Equals("Arya Stark")Expect(users[1].User.Email).Equals("[email protected]")}++func TestPostStorage_Attachments(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ posts.SetCurrentTenant(demoTenant)+ posts.SetCurrentUser(jonSnow)+ post1, _ := posts.Add("My new post", "with this description")+ post2, _ := posts.Add("My other post", "with another description")++ attachments, err := posts.GetAttachments(post1, nil)+ Expect(err).IsNil()+ Expect(attachments).HasLen(0)++ bytes, err := ioutil.ReadFile(env.Path("favicon.png"))+ Expect(err).IsNil()++ err = posts.SetAttachments(post1, nil, []*models.ImageUpload{+ &models.ImageUpload{+ BlobKey: "12345-test.png",+ Upload: &models.ImageUploadData{+ FileName: "test.png",+ ContentType: "image/png",+ Content: bytes,+ },+ },+ })+ Expect(err).IsNil()++ attachments, err = posts.GetAttachments(post1, nil)+ Expect(err).IsNil()+ Expect(attachments).HasLen(1)+ Expect(attachments[0]).Equals("12345-test.png")++ attachments, err = posts.GetAttachments(post2, nil)+ Expect(err).IsNil()+ Expect(attachments).HasLen(0)++ err = posts.SetAttachments(post2, nil, []*models.ImageUpload{+ &models.ImageUpload{+ BlobKey: "12345-test.png",+ Remove: true,+ },+ &models.ImageUpload{+ BlobKey: "67890-test2.png",+ Upload: &models.ImageUploadData{+ FileName: "test2.png",+ ContentType: "image/png",+ Content: bytes,+ },+ },+ &models.ImageUpload{+ BlobKey: "67890-test6.png",+ Upload: &models.ImageUploadData{+ FileName: "test6.png",+ ContentType: "image/png",+ Content: bytes,+ },+ },+ })+ Expect(err).IsNil()++ attachments, err = posts.GetAttachments(post1, nil)+ Expect(err).IsNil()+ Expect(attachments).HasLen(1)+ Expect(attachments[0]).Equals("12345-test.png")++ attachments, err = posts.GetAttachments(post2, nil)+ Expect(err).IsNil()+ Expect(attachments).HasLen(2)+ Expect(attachments[0]).Equals("67890-test2.png")+ Expect(attachments[1]).Equals("67890-test6.png")++ err = posts.SetAttachments(post1, nil, []*models.ImageUpload{+ &models.ImageUpload{+ BlobKey: "12345-test.png",+ Remove: true,+ },+ })+ Expect(err).IsNil()++ attachments, err = posts.GetAttachments(post1, nil)+ Expect(err).IsNil()+ Expect(attachments).HasLen(0)+}diff --git a/app/storage/storage.go b/app/storage/storage.goindex f0547b9d6..ba61f2a8e 100644--- a/app/storage/storage.go+++ b/app/storage/storage.go@@ -43,6 +43,8 @@ type Post interface {IsReferenced(post *models.Post) (bool, error)VotedBy() ([]int, error)ListVotes(post *models.Post, limit int) ([]*models.Vote, error)+ GetAttachments(post *models.Post, comment *models.Comment) ([]string, error)+ SetAttachments(post *models.Post, comment *models.Comment, attachments []*models.ImageUpload) error}// User is used for user operationsdiff --git a/migrations/201901130830_attachments.sql b/migrations/201901130830_attachments.sqlnew file mode 100644index 000000000..a48cdef7d--- /dev/null+++ b/migrations/201901130830_attachments.sql@@ -0,0 +1,13 @@+create table if not exists attachments (+ id serial not null,+ tenant_id int not null,+ post_id int not null,+ comment_id int null,+ user_id int not null,+ attachment_bkey varchar(512) not null,+ primary key (id),+ foreign key (tenant_id) references tenants(id),+ foreign key (post_id) references posts(id),+ foreign key (user_id) references users(id),+ foreign key (comment_id) references comments(id)+);\ No newline at end of filediff --git a/public/components/common/form/ImageUploader.tsx b/public/components/common/form/ImageUploader.tsxindex 07c5904ef..d5467ab68 100644--- a/public/components/common/form/ImageUploader.tsx+++ b/public/components/common/form/ImageUploader.tsx@@ -8,6 +8,8 @@ import { Button, ButtonClickEvent, Modal } from "@fider/components";import { FaRegImage } from "react-icons/fa";import { ImageUpload } from "@fider/models";+const hardFileSizeLimit = 5 * 1024 * 1024;+interface ImageUploaderProps {instanceID?: string;field: string;@@ -39,6 +41,11 @@ export class ImageUploader extends React.Component<ImageUploaderProps, ImageUplopublic fileChanged = async (e: React.ChangeEvent<HTMLInputElement>) => {if (e.target.files && e.target.files[0]) {const file = e.target.files[0];+ if (file.size > hardFileSizeLimit) {+ alert("The image size must be smaller than 5MB.");+ return;+ }+const base64 = await fileToBase64(file);this.setState({@@ -101,9 +108,9 @@ export class ImageUploader extends React.Component<ImageUploaderProps, ImageUploprivate modal() {return (- <Modal.Window isOpen={this.state.showModal} center={false} size="fluid">+ <Modal.Window className="c-image-viewer-modal" isOpen={this.state.showModal} center={false} size="fluid"><Modal.Content>- <img src={this.state.previewURL} />+ {this.props.bkey ? <img src={uploadedImageURL(this.props.bkey)} /> : <img src={this.state.previewURL} />}</Modal.Content><Modal.Footer>@@ -147,7 +154,7 @@ export class ImageUploader extends React.Component<ImageUploaderProps, ImageUplo</div>)}- <input ref={e => (this.fileSelector = e)} type="file" onChange={this.fileChanged} />+ <input ref={e => (this.fileSelector = e)} type="file" onChange={this.fileChanged} accept="image/*" /><DisplayError fields={[this.props.field]} error={ctx.error} />{!hasFile && (<div className="c-form-field-wrapper">diff --git a/public/components/common/form/ImageViewer.scss b/public/components/common/form/ImageViewer.scssindex 5910ea605..f0ae25574 100644--- a/public/components/common/form/ImageViewer.scss+++ b/public/components/common/form/ImageViewer.scss@@ -11,6 +11,7 @@margin-left: 10px;}}+.c-image-viewer-modal {img {max-width: 90vw;diff --git a/public/components/common/form/MultiImageUploader.tsx b/public/components/common/form/MultiImageUploader.tsxindex f1d611287..8dc736a77 100644--- a/public/components/common/form/MultiImageUploader.tsx+++ b/public/components/common/form/MultiImageUploader.tsx@@ -62,8 +62,7 @@ export class MultiImageUploader extends React.Component<MultiImageUploaderProps,}} else {instances[instanceID].upload = upload;- count++;- if (count <= this.props.maxUploads) {+ if (count++ <= this.props.maxUploads) {this.addNewElement(instances);}}diff --git a/public/pages/Home/components/PostInput.tsx b/public/pages/Home/components/PostInput.tsxindex 71a37c322..07b795dca 100644--- a/public/pages/Home/components/PostInput.tsx+++ b/public/pages/Home/components/PostInput.tsx@@ -1,7 +1,8 @@import React from "react";-import { Button, ButtonClickEvent, Input, Form, TextArea } from "@fider/components";+import { Button, ButtonClickEvent, Input, Form, TextArea, MultiImageUploader } from "@fider/components";import { SignInModal } from "@fider/components";import { cache, actions, Failure, Fider } from "@fider/services";+import { ImageUpload } from "@fider/models";interface PostInputProps {placeholder: string;@@ -11,6 +12,7 @@ interface PostInputProps {interface PostInputState {title: string;description: string;+ attachments: ImageUpload[];focused: boolean;showSignIn: boolean;error?: Failure;@@ -28,7 +30,8 @@ export class PostInput extends React.Component<PostInputProps, PostInputState> {title: (Fider.session.isAuthenticated && cache.session.get(CACHE_TITLE_KEY)) || "",description: (Fider.session.isAuthenticated && cache.session.get(CACHE_DESCRIPTION_KEY)) || "",focused: false,- showSignIn: false+ showSignIn: false,+ attachments: []};if (this.state.title) {@@ -54,9 +57,13 @@ export class PostInput extends React.Component<PostInputProps, PostInputState> {this.setState({ description });};+ private setAttachments = (attachments: ImageUpload[]) => {+ this.setState({ attachments });+ };+private submit = async (event: ButtonClickEvent) => {if (this.state.title) {- const result = await actions.createPost(this.state.title, this.state.description);+ const result = await actions.createPost(this.state.title, this.state.description, this.state.attachments);if (result.ok) {this.setState({ error: undefined });cache.session.remove(CACHE_TITLE_KEY, CACHE_DESCRIPTION_KEY);@@ -82,6 +89,7 @@ export class PostInput extends React.Component<PostInputProps, PostInputState> {minRows={5}placeholder="Describe your suggestion (optional)"/>+ <MultiImageUploader field="attachments" maxUploads={3} previewMaxWidth={100} onChange={this.setAttachments} /><Button color="positive" onClick={this.submit}>Submit</Button>diff --git a/public/pages/ShowPost/ShowPost.page.tsx b/public/pages/ShowPost/ShowPost.page.tsxindex 4c8835125..2ee3aae9f 100644--- a/public/pages/ShowPost/ShowPost.page.tsx+++ b/public/pages/ShowPost/ShowPost.page.tsx@@ -2,7 +2,7 @@ import "./ShowPost.page.scss";import React from "react";-import { Comment, Post, Tag, Vote } from "@fider/models";+import { Comment, Post, Tag, Vote, ImageUpload } from "@fider/models";import { actions, Failure, Fider } from "@fider/services";import {@@ -17,7 +17,9 @@ import {ListItem,Input,Form,- TextArea+ TextArea,+ MultiImageUploader,+ ImageViewer} from "@fider/components";import { FaSave, FaTimes, FaEdit } from "react-icons/fa";import { ResponseForm } from "./components/ResponseForm";@@ -33,11 +35,13 @@ interface ShowPostPageProps {comments: Comment[];tags: Tag[];votes: Vote[];+ attachments: string[];}interface ShowPostPageState {editMode: boolean;newTitle: string;+ attachments: ImageUpload[];newDescription: string;error?: Failure;}@@ -49,20 +53,20 @@ export default class ShowPostPage extends React.Component<ShowPostPageProps, Shothis.state = {editMode: false,newTitle: this.props.post.title,- newDescription: this.props.post.description+ newDescription: this.props.post.description,+ attachments: []};}private saveChanges = async () => {- const result = await actions.updatePost(this.props.post.number, this.state.newTitle, this.state.newDescription);+ const result = await actions.updatePost(+ this.props.post.number,+ this.state.newTitle,+ this.state.newDescription,+ this.state.attachments+ );if (result.ok) {- this.setState({- error: undefined,- editMode: false- });- this.props.post.title = this.state.newTitle;- this.props.post.description = this.state.newDescription;- this.forceUpdate();+ location.reload();} else {this.setState({error: result.error@@ -78,6 +82,10 @@ export default class ShowPostPage extends React.Component<ShowPostPageProps, Shothis.setState({ newDescription });};+ private setAttachments = (attachments: ImageUpload[]) => {+ this.setState({ attachments });+ };+private cancelEdit = async () => {this.setState({ error: undefined, editMode: false });};@@ -115,11 +123,22 @@ export default class ShowPostPage extends React.Component<ShowPostPageProps, Sho{this.state.editMode ? (<Form error={this.state.error}><TextArea field="description" value={this.state.newDescription} onChange={this.setNewDescription} />+ <MultiImageUploader+ field="attachments"+ bkeys={this.props.attachments}+ maxUploads={3}+ previewMaxWidth={100}+ onChange={this.setAttachments}+ /></Form>) : (- <MultiLineText className="description" text={this.props.post.description} style="simple" />+ <>+ <MultiLineText className="description" text={this.props.post.description} style="simple" />+ {this.props.attachments.map(x => (+ <ImageViewer key={x} bkey={x} />+ ))}+ </>)}-<ShowPostResponse showUser={true} status={this.props.post.status} response={this.props.post.response} /></div>diff --git a/public/services/actions/post.ts b/public/services/actions/post.tsindex 6cb68692b..3fa986a08 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 } from "@fider/models";+import { Post, Vote, ImageUpload } from "@fider/models";export const getAllPosts = async (): Promise<Result<Post[]>> => {return await http.get<Post[]>("/api/v1/posts");@@ -88,10 +88,23 @@ interface CreatePostResponse {slug: string;}-export const createPost = async (title: string, description: string): Promise<Result<CreatePostResponse>> => {- return http.post<CreatePostResponse>(`/api/v1/posts`, { title, description }).then(http.event("post", "create"));+export const createPost = async (+ title: string,+ description: string,+ attachments: ImageUpload[]+): Promise<Result<CreatePostResponse>> => {+ return http+ .post<CreatePostResponse>(`/api/v1/posts`, { title, description, attachments })+ .then(http.event("post", "create"));};-export const updatePost = async (postNumber: number, title: string, description: string): Promise<Result> => {- return http.put(`/api/v1/posts/${postNumber}`, { title, description }).then(http.event("post", "update"));+export const updatePost = async (+ postNumber: number,+ title: string,+ description: string,+ attachments: ImageUpload[]+): Promise<Result> => {+ return http+ .put(`/api/v1/posts/${postNumber}`, { title, description, attachments })+ .then(http.event("post", "update"));};diff --git a/public/services/http.ts b/public/services/http.tsindex 93853f190..0c5929f15 100644--- a/public/services/http.ts+++ b/public/services/http.ts@@ -1,4 +1,4 @@-import { analytics, notify } from "@fider/services";+import { analytics, notify, truncate } from "@fider/services";export interface ErrorItem {field?: string;@@ -52,7 +52,8 @@ async function request<T>(url: string, method: "GET" | "POST" | "PUT" | "DELETE"});return await toResult<T>(response);} catch (err) {- throw new Error(`Failed to ${method} ${url} with body '${body ? JSON.stringify(body) : "<empty>"}'`);+ const truncatedBody = truncate(body ? JSON.stringify(body) : "<empty>", 1000);+ throw new Error(`Failed to ${method} ${url} with body '${truncatedBody}'`);}}diff --git a/public/services/utils.ts b/public/services/utils.tsindex abc178cf4..6ba57d8d4 100644--- a/public/services/utils.ts+++ b/public/services/utils.ts@@ -134,9 +134,19 @@ export const isCookieEnabled = (): boolean => {}};-export const uploadedImageURL = (bkey: string | undefined, size: number): string | undefined => {+export const uploadedImageURL = (bkey: string | undefined, size?: number): string | undefined => {if (bkey) {- return `${Fider.settings.tenantAssetsURL}/images/${bkey}?size=${size}`;+ if (size) {+ return `${Fider.settings.tenantAssetsURL}/images/${bkey}?size=${size}`;+ }+ return `${Fider.settings.tenantAssetsURL}/images/${bkey}`;}return undefined;};++export const truncate = (input: string, maxLength: number): string => {+ if (input && input.length > 1000) {+ return `${input.substr(0, maxLength)}...`;+ }+ return input;+};