Browse Source

#43 完了

#23
みてるぞ 1 month ago
parent
commit
729bb5e4ca
6 changed files with 114 additions and 30 deletions
  1. +10
    -18
      backend/app/controllers/posts_controller.rb
  2. +1
    -1
      frontend/src/App.tsx
  3. +72
    -0
      frontend/src/components/PostEditForm.tsx
  4. +1
    -1
      frontend/src/components/TagDetailSidebar.tsx
  5. +28
    -7
      frontend/src/pages/PostDetailPage.tsx
  6. +2
    -3
      frontend/src/pages/PostNewPage.tsx

+ 10
- 18
backend/app/controllers/posts_controller.rb View File

@@ -3,8 +3,6 @@ require 'nokogiri'




class PostsController < ApplicationController class PostsController < ApplicationController
before_action :set_post, only: %i[ show update destroy ]

# GET /posts # GET /posts
def index def index
if params[:tags].present? if params[:tags].present?
@@ -71,27 +69,21 @@ class PostsController < ApplicationController


# PATCH/PUT /posts/1 # PATCH/PUT /posts/1
def update def update
if @post.update(post_params)
render json: @post
return head :unauthorized unless current_user
return head :forbidden unless ['admin', 'member'].include?(current_user.role)

post = Post.find(params[:id])
tag_ids = JSON.parse(params[:tags])
if post.update(title: params[:title], tags: Tag.where(id: tag_ids))
render({ json: (post
.as_json(include: { tags: { only: [:id, :name, :category] } })),
status: :created })
else else
render json: @post.errors, status: :unprocessable_entity
render json: post.errors, status: :unprocessable_entity
end end
end end


# DELETE /posts/1 # DELETE /posts/1
def destroy def destroy
@post.destroy!
end

private

# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params.expect(:id))
end

# Only allow a list of trusted parameters through.
def post_params
params.expect(post: [ :title, :body ])
end end
end end

+ 1
- 1
frontend/src/App.tsx View File

@@ -59,7 +59,7 @@ export default () => {
<Route path="/" element={<Navigate to="/posts" replace />} /> <Route path="/" element={<Navigate to="/posts" replace />} />
<Route path="/posts" element={<PostPage />} /> <Route path="/posts" element={<PostPage />} />
<Route path="/posts/new" element={<PostNewPage />} /> <Route path="/posts/new" element={<PostNewPage />} />
<Route path="/posts/:id" element={<PostDetailPage />} />
<Route path="/posts/:id" element={<PostDetailPage user={user} />} />
<Route path="/tags/:tag" element={<TagPage />} /> <Route path="/tags/:tag" element={<TagPage />} />
<Route path="/wiki/:name" element={<WikiDetailPage />} /> <Route path="/wiki/:name" element={<WikiDetailPage />} />
<Route path="/wiki/new" element={<WikiNewPage />} /> <Route path="/wiki/new" element={<WikiNewPage />} />


+ 72
- 0
frontend/src/components/PostEditForm.tsx View File

@@ -0,0 +1,72 @@
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { API_BASE_URL } from '@/config'

import type { Post, Tag } from '@/types'

type Props = { post: Post
onSave: (newPost: Post) => void }


export default ({ post, onSave }: Props) => {
const [title, setTitle] = useState (post.title)
const [tags, setTags] = useState<Tag[]> ([])
const [tagIds, setTagIds] = useState<number[]> (post.tags.map (t => t.id))

const handleSubmit = () => {
void (axios.put (`${ API_BASE_URL }/posts/${ post.id }`,
{ title,
tags: JSON.stringify (tagIds) },
{ headers: { 'Content-Type': 'multipart/form-data',
'X-Transfer-Code': localStorage.getItem ('user_code') || '' } } )
.then (res => {
const newPost: Post = res.data
onSave ({ ...post,
title: newPost.title,
tags: newPost.tags } as Post)
}))
}

useEffect (() => {
void (axios.get ('/api/tags')
.then (res => setTags (res.data))
.catch (() => toast ({ title: 'タグ一覧の取得失敗' })))
}, [])

return (
<div className="max-w-xl p-4 space-y-4">
{/* タイトル */}
<div>
<div className="flex gap-2 mb-1">
<label className="flex-1 block font-semibold">タイトル</label>
</div>
<input type="text"
className="w-full border rounded p-2"
value={title}
onChange={e => setTitle (e.target.value)} />
</div>

{/* タグ */}
<div>
<label className="block font-semibold">タグ</label>
<select multiple
value={tagIds.map (String)}
onChange={e => {
const values = Array.from (e.target.selectedOptions).map (o => Number (o.value))
setTagIds (values)
}}
className="w-full p-2 border rounded h-32">
{tags.map ((tag: Tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>))}
</select>
</div>

{/* 送信 */}
<button onClick={handleSubmit}
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400">
更新
</button>
</div>)
}

+ 1
- 1
frontend/src/components/TagDetailSidebar.tsx View File

@@ -24,7 +24,7 @@ export default ({ post }: Props) => {
if (!(post)) if (!(post))
return return


const fetchTags = async () => {
const fetchTags = () => {
const tagsTmp: TagByCategory = { } const tagsTmp: TagByCategory = { }
for (const tag of post.tags) for (const tag of post.tags)
{ {


+ 28
- 7
frontend/src/pages/PostDetailPage.tsx View File

@@ -8,17 +8,21 @@ import { toast } from '@/components/ui/use-toast'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import MainArea from '@/components/layout/MainArea' import MainArea from '@/components/layout/MainArea'
import TagDetailSidebar from '@/components/TagDetailSidebar' import TagDetailSidebar from '@/components/TagDetailSidebar'
import PostEditForm from '@/components/PostEditForm'


import type { Post, Tag } from '@/types'
import type { Post, Tag, User } from '@/types'


type Props = { user: User }


const PostDetailPage = () => {
const { id } = useParams ()


const [post, setPost] = useState<Post | null> (null)
export default ({ user }: Props) => {
const { id } = useParams ()


const location = useLocation () const location = useLocation ()


const [post, setPost] = useState<Post | null> (null)
const [editing, setEditing] = useState (true)

const changeViewedFlg = () => { const changeViewedFlg = () => {
if (post?.viewed) if (post?.viewed)
{ {
@@ -56,6 +60,15 @@ const PostDetailPage = () => {
.catch (err => console.error ('うんち!', err))) .catch (err => console.error ('うんち!', err)))
}, [id]) }, [id])


useEffect (() => {
setEditing (false)
}, [post])

useEffect (() => {
if (!(editing))
setEditing (true)
}, [editing])

if (!(post)) if (!(post))
return ( return (
<> <>
@@ -93,11 +106,19 @@ const PostDetailPage = () => {
post.viewed ? 'bg-blue-600 hover:bg-blue-700' : 'bg-gray-500 hover:bg-gray-600')}> post.viewed ? 'bg-blue-600 hover:bg-blue-700' : 'bg-gray-500 hover:bg-gray-600')}>
{post.viewed ? '閲覧済' : '未閲覧'} {post.viewed ? '閲覧済' : '未閲覧'}
</Button> </Button>
{(['admin', 'member'].includes (user.role) && editing) &&
<div className="mt-4">
<span className="text-blue-400 hover:underline cursor-pointer">
編輯
</span>
<PostEditForm post={post}
onSave={newPost => {
setPost (newPost)
toast ({ description: '更新しました.' })
}} />
</div>}
</div>) </div>)
: 'Loading...'} : 'Loading...'}
</MainArea> </MainArea>
</>) </>)
} }


export default PostDetailPage

+ 2
- 3
frontend/src/pages/PostNewPage.tsx View File

@@ -1,8 +1,8 @@
import React, { useEffect, useState, useRef } from 'react' import React, { useEffect, useState, useRef } from 'react'
import { Link, useLocation, useParams, useNavigate } from 'react-router-dom' import { Link, useLocation, useParams, useNavigate } from 'react-router-dom'
import axios from 'axios' import axios from 'axios'
import { API_BASE_URL, SITE_TITLE } from '../config'
import NicoViewer from '../components/NicoViewer'
import { API_BASE_URL, SITE_TITLE } from '@/config'
import NicoViewer from '@/components/NicoViewer'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/use-toast' import { toast } from '@/components/ui/use-toast'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
@@ -10,7 +10,6 @@ import MainArea from '@/components/layout/MainArea'


import type { Post, Tag } from '@/types' import type { Post, Tag } from '@/types'



type Props = { posts: Post[] type Props = { posts: Post[]
setPosts: (posts: Post[]) => void } setPosts: (posts: Post[]) => void }




Loading…
Cancel
Save