Browse Source

#19 トップバーと新規作成ちょっとだけ

#23
みてるぞ 1 month ago
parent
commit
5b8a560024
10 changed files with 327 additions and 67 deletions
  1. +0
    -3
      backend/app/controllers/posts_controller.rb
  2. +17
    -7
      backend/app/controllers/wiki_pages_controller.rb
  3. +14
    -11
      backend/app/models/wiki_page.rb
  4. +3
    -2
      backend/config/routes.rb
  5. +15
    -10
      frontend/src/App.tsx
  6. +30
    -8
      frontend/src/components/TopNav.tsx
  7. +31
    -0
      frontend/src/pages/WikiDetailPage.tsx
  8. +214
    -0
      frontend/src/pages/WikiNewPage.tsx
  9. +3
    -0
      frontend/src/pages/WikiPage.tsx
  10. +0
    -26
      frontend/src/pages/WikiShowPage.tsx

+ 0
- 3
backend/app/controllers/posts_controller.rb View File

@@ -36,9 +36,6 @@ class PostsController < ApplicationController


# POST /posts # POST /posts
def create def create
logger.info ">>> thumbnail: #{params[:thumbnail]&.content_type}"
logger.info ">>> filename: #{params[:thumbnail]&.original_filename}"

return head :unauthorized unless current_user return head :unauthorized unless current_user
return head :forbidden unless ['admin', 'member'].include?(current_user.role) return head :forbidden unless ['admin', 'member'].include?(current_user.role)




+ 17
- 7
backend/app/controllers/wiki_pages_controller.rb View File

@@ -1,6 +1,5 @@
class WikiPagesController < ApplicationController class WikiPagesController < ApplicationController
def show def show
p params
wiki_page = WikiPage.find_by(title: params[:title]) wiki_page = WikiPage.find_by(title: params[:title])
if wiki_page if wiki_page
render plain: wiki_page.markdown render plain: wiki_page.markdown
@@ -9,15 +8,26 @@ class WikiPagesController < ApplicationController
end end
end end


def update
def create
return head :unauthorized unless current_user return head :unauthorized unless current_user


title = params[:title]
wiki_page = WikiPage.find_by(title: title)
unless wiki_page
wiki_page = WikiPage.new(title: title, created_user: current_user, updated_user: current_user)
wiki_page = WikiPage.new(title: params[:title], tag_id: params[:tag_id], created_user: current_user, updated_user: current_user)
wiki_page.markdown = params[:markdown], user: current_user
if wiki_page.save
render json: wiki_page, status: :created
else
render json: { errors: wiki_page.errors.full_messages }, status: :unprocessable_entity
end end
wiki_page.markdown = params[:markdown]
end

def update
return head :unauthorized unless current_user

wiki_page = WikiPage.find(params[:id])
return head :not_found unless wiki_pages

wiki_page.updated_user = current_user
wiki_page.markdown = params[:markdown], user: current_user
wiki_page.save! wiki_page.save!
head :ok head :ok
end end


+ 14
- 11
backend/app/models/wiki_page.rb View File

@@ -2,33 +2,36 @@ require 'gollum-lib'




class WikiPage < ApplicationRecord class WikiPage < ApplicationRecord
WIKI_PATH = Rails.root.join('wiki').to_s

belongs_to :tag, optional: true belongs_to :tag, optional: true
belongs_to :created_user, class_name: 'User', foreign_key: 'created_user_id' belongs_to :created_user, class_name: 'User', foreign_key: 'created_user_id'
belongs_to :updated_user, class_name: 'User', foreign_key: 'updated_user_id' belongs_to :updated_user, class_name: 'User', foreign_key: 'updated_user_id'


validates :title, presence: true, length: { maximum: 255 }, uniqueness: true validates :title, presence: true, length: { maximum: 255 }, uniqueness: true


def markdown
wiki = Gollum::Wiki.new(WIKI_PATH)
page = wiki.page(title)
def body
page = wiki.page("#{ id }.md")
page&.raw_data page&.raw_data
end end


def markdown= content
wiki = Gollum::Wiki.new(WIKI_PATH)

page = wiki.page(title)
def body= content, user:
page = wiki.page("#{ id }.md")


commit_info = { message: "Update #{ title }", commit_info = { message: "Update #{ title }",
name: current_user.id,
name: user.id,
email: 'dummy@example.com' } email: 'dummy@example.com' }


if page if page
page.update(content, commit: commit_info) page.update(content, commit: commit_info)
else else
wiki.write_page(title, :markdown, content, commit_info)
wiki.write_page("#{ id }.md", :markdown, content, commit_info)
end end
end end

private

WIKI_PATH = Rails.root.join('wiki').to_s

def wiki
@wiki ||= Gollum::Wiki.new(WIKI_PATH)
end
end end

+ 3
- 2
backend/config/routes.rb View File

@@ -20,8 +20,9 @@ Rails.application.routes.draw do
delete 'posts/:id/viewed', to: 'posts#unviewed' delete 'posts/:id/viewed', to: 'posts#unviewed'
get 'preview/title', to: 'preview#title' get 'preview/title', to: 'preview#title'
get 'preview/thumbnail', to: 'preview#thumbnail' get 'preview/thumbnail', to: 'preview#thumbnail'
get 'wiki/*title', to: 'wiki_pages#show', format: false
post 'wiki/*title', to: 'wiki_pages#save', format: false
get 'wiki/:title', to: 'wiki_pages#show'
post 'wiki', to: 'wiki_pages#create'
put 'wiki/:id', to: 'wiki_pages#update'


# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html




+ 15
- 10
frontend/src/App.tsx View File

@@ -1,14 +1,16 @@
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom' import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom'
import HomePage from './pages/HomePage'
import TagPage from './pages/TagPage'
import TopNav from './components/TopNav'
import TagSidebar from './components/TagSidebar'
import PostPage from './pages/PostPage'
import PostNewPage from './pages/PostNewPage'
import PostDetailPage from './pages/PostDetailPage'
import WikiShowPage from './pages/WikiShowPage'
import { API_BASE_URL } from './config'
import HomePage from '@/pages/HomePage'
import TagPage from '@/pages/TagPage'
import TopNav from '@/components/TopNav'
import TagSidebar from '@/components/TagSidebar'
import PostPage from '@/pages/PostPage'
import PostNewPage from '@/pages/PostNewPage'
import PostDetailPage from '@/pages/PostDetailPage'
import WikiPage from '@/pages/WikiPage'
import WikiNewPage from '@/pages/WikiNewPage'
import WikiDetailPage from '@/pages/WikiDetailPage'
import { API_BASE_URL } from '@/config'
import axios from 'axios' import axios from 'axios'
import { Toaster } from '@/components/ui/toaster' import { Toaster } from '@/components/ui/toaster'
import { camelizeKeys } from 'humps' import { camelizeKeys } from 'humps'
@@ -81,7 +83,10 @@ const App = () => {
<Route path="/posts/new" element={<PostNewPage />} /> <Route path="/posts/new" element={<PostNewPage />} />
<Route path="/posts/:id" element={<PostDetailPage posts={posts} setPosts={setPosts} />} /> <Route path="/posts/:id" element={<PostDetailPage posts={posts} setPosts={setPosts} />} />
<Route path="/tags/:tag" element={<TagPage />} /> <Route path="/tags/:tag" element={<TagPage />} />
<Route path="/wiki/:name" element={<WikiShowPage />} />
<Route path="/wiki" element={<WikiPage />} />
<Route path="/wiki/:name" element={<WikiDetailPage />} />
<Route path="/wiki/new" element={<WikiNewPage />} />
{/* <Route path="/wiki/:id/edit" element={<WikiEditPage />} /> */}
</Routes> </Routes>
</main> </main>
</div> </div>


+ 30
- 8
frontend/src/components/TopNav.tsx View File

@@ -1,5 +1,5 @@
import React, { useState, useEffect } from "react"
import { Link, useLocation } from 'react-router-dom'
import React, { useState, useEffect } from 'react'
import { Link, useLocation, useParams } from 'react-router-dom'
import SettingsDialogue from './SettingsDialogue' import SettingsDialogue from './SettingsDialogue'
import { Button } from './ui/button' import { Button } from './ui/button'
import clsx from 'clsx' import clsx from 'clsx'
@@ -25,9 +25,12 @@ const TopNav: React.FC = ({ user, setUser }: Props) => {
const [settingsVisible, setSettingsVisible] = useState (false) const [settingsVisible, setSettingsVisible] = useState (false)
const [selectedMenu, setSelectedMenu] = useState<Menu> (Menu.None) const [selectedMenu, setSelectedMenu] = useState<Menu> (Menu.None)


const MyLink = ({ to, title, menu }: { to: string; title: string; menu?: Menu }) => (
const MyLink = ({ to, title, menu, base }: { to: string
title: string
menu?: Menu
base?: string }) => (
<Link to={to} className={clsx ('hover:text-orange-500 h-full flex items-center', <Link to={to} className={clsx ('hover:text-orange-500 h-full flex items-center',
(location.pathname.startsWith (to)
(location.pathname.startsWith (base ?? to)
? 'bg-gray-700 px-4 font-bold' ? 'bg-gray-700 px-4 font-bold'
: 'px-2'))}> : 'px-2'))}>
{title} {title}
@@ -50,11 +53,11 @@ const TopNav: React.FC = ({ user, setUser }: Props) => {
<> <>
<nav className="bg-gray-800 text-white px-3 flex justify-between items-center w-full min-h-[48px]"> <nav className="bg-gray-800 text-white px-3 flex justify-between items-center w-full min-h-[48px]">
<div className="flex items-center gap-2 h-full"> <div className="flex items-center gap-2 h-full">
<Link to="/posts" className="mr-4 text-xl font-bold text-orange-500">ぼざクリ タグ広場</Link>
<Link to="/posts" className="mx-4 text-xl font-bold text-orange-500">ぼざクリ タグ広場</Link>
<MyLink to="/posts" title="広場" /> <MyLink to="/posts" title="広場" />
<MyLink to="/deerjikists" title="ニジラー" /> <MyLink to="/deerjikists" title="ニジラー" />
<MyLink to="/tags" title="タグ" /> <MyLink to="/tags" title="タグ" />
<MyLink to="/wiki" title="Wiki" />
<MyLink to="/wiki/ヘルプ:ホーム" base="/wiki" title="Wiki" />
</div> </div>
<div className="ml-auto pr-4"> <div className="ml-auto pr-4">
<Button onClick={() => setSettingsVisible (true)}>{user?.name || '名もなきニジラー'}</Button> <Button onClick={() => setSettingsVisible (true)}>{user?.name || '名もなきニジラー'}</Button>
@@ -66,14 +69,33 @@ const TopNav: React.FC = ({ user, setUser }: Props) => {
</nav> </nav>
{(() => { {(() => {
const className = 'bg-gray-700 text-white px-3 flex items-center w-full min-h-[40px]' const className = 'bg-gray-700 text-white px-3 flex items-center w-full min-h-[40px]'
const subClass = 'hover:text-orange-500 h-full flex items-center px-4'
const subClass = 'hover:text-orange-500 h-full flex items-center px-3'
const inputBox = 'flex items-center px-3 mx-2'
const Separator = () => <span className="flex items-center px-2">|</span>
switch (selectedMenu) switch (selectedMenu)
{ {
case Menu.Post: case Menu.Post:
return ( return (
<div className={className}> <div className={className}>
<Link to="/posts" className={subClass}>一覧</Link> <Link to="/posts" className={subClass}>一覧</Link>
<Link to="/posts/new" className={subClass}>投稿</Link>
<Link to="/posts/new" className={subClass}>投稿追加</Link>
</div>)
case Menu.Wiki:
return (
<div className={className}>
<input className={inputBox}
placeholder="Wiki 検索" />
<Link to="/wiki" className={subClass}>検索</Link>
<Link to="/wiki/new" className={subClass}>新規</Link>
<Link to="/wiki/changes" className={subClass}>全体履歴</Link>
<Link to="/wiki/ヘルプ:Wiki" className={subClass}>ヘルプ</Link>
{/^\/wiki\/(?!new|changes)[^\/]+/.test (location.pathname) &&
<>
<Separator />
<Link to={`/posts?tags=${ location.pathname.split ('/')[2] }`} className={subClass}>投稿</Link>
<Link to={`/wiki/${ location.pathname.split ('/')[2] }/history`} className={subClass}>履歴</Link>
<Link to={`/wiki/${ location.pathname.split ('/')[2] }/edit`} className={subClass}>編輯</Link>
</>}
</div>) </div>)
} }
}) ()} }) ()}


+ 31
- 0
frontend/src/pages/WikiDetailPage.tsx View File

@@ -0,0 +1,31 @@
import { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import ReactMarkdown from 'react-markdown'
import axios from 'axios'
import { API_BASE_URL } from '@/config'


const WikiDetailPage = () => {
const { name } = useParams ()

const [markdown, setMarkdown] = useState<string | null> (null)

useEffect (() => {
void (axios.get (`${ API_BASE_URL }/wiki/${ encodeURIComponent (name) }`)
.then (res => setMarkdown (res.data))
.catch (() => setMarkdown (null)))
}, [name])

return (
<div className="prose mx-auto p-4">
<ReactMarkdown components={{ a: (
({ href, children }) => (href?.startsWith ('/')
? <Link to={href!}>{children}</Link>
: <a href={href} target="_blank" rel="noopener noreferrer">{children}</a>)) }}>
{markdown || `このページは存在しません。[新規作成してください](/wiki/new?title=${ name })。`}
</ReactMarkdown>
</div>)
}


export default WikiDetailPage

+ 214
- 0
frontend/src/pages/WikiNewPage.tsx View File

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

type Tag = { id: number
name: string
category: string }

type Post = { id: number
url: string
title: string
thumbnail: string
tags: Tag[]
viewed: boolean }


const WikiNewPage = () => {
const location = useLocation ()
const navigate = useNavigate ()

const [title, setTitle] = useState ('')
const [titleAutoFlg, setTitleAutoFlg] = useState (true)
const [titleLoading, setTitleLoading] = useState (false)
const [url, setURL] = useState ('')
const [thumbnailFile, setThumbnailFile] = useState<File | null> (null)
const [thumbnailPreview, setThumbnailPreview] = useState<string> ('')
const [thumbnailAutoFlg, setThumbnailAutoFlg] = useState (true)
const [thumbnailLoading, setThumbnailLoading] = useState (false)
const [tags, setTags] = useState<Tag[]> ([])
const [tagIds, setTagIds] = useState<number[]> ([])
const previousURLRef = useRef ('')

const handleSubmit = () => {
const formData = new FormData ()
formData.append ('title', title)
formData.append ('url', url)
formData.append ('tags', JSON.stringify (tagIds))
formData.append ('thumbnail', thumbnailFile)

void (axios.post (`${ API_BASE_URL }/posts`, formData, { headers: {
'Content-Type': 'multipart/form-data',
'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
.then (() => {
toast ({ title: '投稿成功!' })
navigate ('/posts')
})
.catch (e => toast ({ title: '投稿失敗',
description: '入力を確認してください。' })))
}

useEffect (() => {
document.title = `新規 Wiki ページ | ${ SITE_TITLE }`
void (axios.get ('/api/tags')
.then (res => setTags (res.data))
.catch (() => toast ({ title: 'タグ一覧の取得失敗' })))
}, [])

useEffect (() => {
if (titleAutoFlg && url)
fetchTitle ()
}, [titleAutoFlg])

useEffect (() => {
if (thumbnailAutoFlg && url)
fetchThumbnail ()
}, [thumbnailAutoFlg])

const handleURLBlur = () => {
if (!(url) || url === previousURLRef.current)
return

if (titleAutoFlg)
fetchTitle ()
if (thumbnailAutoFlg)
fetchThumbnail ()
previousURLRef.current = url
}

const fetchTitle = () => {
setTitle ('')
setTitleLoading (true)
void (axios.get (`${ API_BASE_URL }/preview/title`, {
params: { url },
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
.then (res => {
setTitle (res.data.title || '')
setTitleLoading (false)
})
.finally (() => setTitleLoading (false)))
}

const fetchThumbnail = () => {
setThumbnailPreview ('')
setThumbnailFile (null)
setThumbnailLoading (true)
if (thumbnailPreview)
URL.revokeObjectURL (thumbnailPreview)
void (axios.get (`${ API_BASE_URL }/preview/thumbnail`, {
params: { url },
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' },
responseType: 'blob' })
.then (res => {
const imageURL = URL.createObjectURL (res.data)
setThumbnailPreview (imageURL)
setThumbnailFile (new File ([res.data],
'thumbnail.png',
{ type: res.data.type || 'image/png' }))
setThumbnailLoading (false)
})
.finally (() => setThumbnailLoading (false)))
}

return (
<div className="max-w-xl mx-auto p-4 space-y-4">
<h1 className="text-2xl font-bold mb-2">新規 Wiki ページ</h1>

{/* URL */}
<div>
<label className="block font-semibold mb-1">URL</label>
<input type="text"
placeholder="例:https://www.nicovideo.jp/watch/..."
value={url}
onChange={e => setURL (e.target.value)}
className="w-full border p-2 rounded"
onBlur={handleURLBlur} />
</div>

{/* タイトル */}
<div>
<div className="flex gap-2 mb-1">
<label className="flex-1 block font-semibold">タイトル</label>
<label className="flex items-center block gap-1">
<input type="checkbox"
checked={titleAutoFlg}
onChange={e => setTitleAutoFlg (e.target.checked)} />
自動
</label>
</div>
<input type="text"
className="w-full border rounded p-2"
value={title}
placeholder={titleLoading ? 'Loading...' : ''}
onChange={e => setTitle (e.target.value)}
disabled={titleAutoFlg} />
</div>

{/* サムネール */}
<div>
<div className="flex gap-2 mb-1">
<label className="block font-semibold flex-1">サムネール</label>
<label className="flex items-center gap-1">
<input type="checkbox"
checked={thumbnailAutoFlg}
onChange={e => setThumbnailAutoFlg (e.target.checked)} />
自動
</label>
</div>
{thumbnailAutoFlg
? (thumbnailLoading
? <p className="text-gray-500 text-sm">Loading...</p>
: !(thumbnailPreview) && (
<p className="text-gray-500 text-sm">
URL から自動取得されます。
</p>))
: (
<input type="file"
accept="image/*"
onChange={e => {
const file = e.target.files?.[0]
if (file)
{
setThumbnailFile (file)
setThumbnailPreview (URL.createObjectURL (file))
}
}} />)}
{thumbnailPreview && (
<img src={thumbnailPreview}
alt="preview"
className="mt-2 max-h-48 rounded border" />)}
</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"
disabled={titleLoading || thumbnailLoading}>
追加
</button>
</div>)
}


export default WikiNewPage

+ 3
- 0
frontend/src/pages/WikiPage.tsx View File

@@ -20,3 +20,6 @@ const WikiPage = () => {


return <WikiEditor value={text} onChange={setText} onSave={save} /> return <WikiEditor value={text} onChange={setText} onSave={save} />
} }


export default WikiPage

+ 0
- 26
frontend/src/pages/WikiShowPage.tsx View File

@@ -1,26 +0,0 @@
import { useParams } from 'react-router-dom'
import ReactMarkdown from 'react-markdown'
import { useEffect, useState } from 'react'
import axios from 'axios'
import { API_BASE_URL } from '@/config'


const WikiShowPage = () => {
const { name } = useParams ()

const [markdown, setMarkdown] = useState ('')

useEffect (() => {
void (axios.get (`${ API_BASE_URL }/wiki/${ encodeURIComponent (name) }`)
.then (res => setMarkdown (res.data))
.catch (() => setMarkdown ('# ページが存在しません')))
}, [name])

return (
<div className="prose mx-auto p-4">
<ReactMarkdown>{markdown}</ReactMarkdown>
</div>)
}


export default WikiShowPage

Loading…
Cancel
Save