Implement ID-based routing and folder auto-generation from titles

Major features:
- Switch from slug-based to ID-based routing (/documents/123)
- Enable title editing with automatic slug/path regeneration
- Auto-generate folder structure from title slashes (e.g., Laravel/Livewire/Components)
- Persist sidebar folder open/close state using localStorage
- Remove slug unique constraint (ID routing makes it unnecessary)
- Implement recursive tree view with multi-level folder support

Architecture changes:
- DocumentService: Add generatePathAndSlug() for title-based path generation
- Routes: Change from {document:slug} to {document} for ID binding
- SidebarTree: Extract recursive rendering to partials/tree-item.blade.php
- Database: Remove unique constraint from documents.slug column

UI improvements:
- Display only last path component in sidebar (Components vs Laravel/Livewire/Components)
- Folder state persists across page navigation via localStorage
- Title field accepts slashes for folder organization

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-29 09:41:38 +09:00
commit 6e7f8566ef
140 changed files with 40590 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
<?php
namespace App\Console\Commands;
use App\Services\DocumentService;
use App\Models\Document;
use Illuminate\Console\Command;
class DocumentsInitCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'docs:init
{--force : Force initialization even if documents exist}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Initialize knowledge base with default documents';
/**
* Execute the console command.
*/
public function handle(DocumentService $documentService): int
{
// 既存ドキュメントがある場合は確認
if (Document::count() > 0 && !$this->option('force')) {
if (!$this->confirm('Documents already exist. Do you want to continue?', false)) {
$this->info('Initialization cancelled.');
return self::SUCCESS;
}
}
$this->info('Initializing knowledge base...');
try {
$documentService->createInitialDocuments();
$this->newLine();
$this->info('✓ Initial documents created successfully!');
$this->newLine();
$this->table(
['Document', 'Path'],
[
['Home', 'Home.md'],
['Getting Started', 'Getting Started.md'],
]
);
$this->newLine();
$this->info('You can now access your knowledge base at /documents');
return self::SUCCESS;
} catch (\Exception $e) {
$this->error('Failed to initialize documents: ' . $e->getMessage());
return self::FAILURE;
}
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Helpers;
use Cocur\Slugify\Slugify;
use Illuminate\Support\Str;
class SlugHelper
{
/**
* Generate a slug from a title, supporting Japanese and other non-ASCII characters
*
* @param string $title
* @param string|null $fallback Optional fallback if slug is empty
* @return string
*/
public static function generate(string $title, ?string $fallback = null): string
{
$slugify = new Slugify(['lowercase' => true]);
// Try to generate slug with cocur/slugify
$slug = $slugify->slugify($title);
// If slug is empty (happens with pure Japanese/Chinese characters),
// use fallback or generate a unique identifier
if (empty($slug)) {
if ($fallback) {
$slug = $fallback;
} else {
// Use timestamp + random string for unique slug
$slug = date('YmdHis') . '-' . Str::random(8);
}
}
return $slug;
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*/
public function create(): View
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*/
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(route('dashboard', absolute: false));
}
/**
* Destroy an authenticated session.
*/
public function destroy(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class ConfirmablePasswordController extends Controller
{
/**
* Show the confirm password view.
*/
public function show(): View
{
return view('auth.confirm-password');
}
/**
* Confirm the user's password.
*/
public function store(Request $request): RedirectResponse
{
if (! Auth::guard('web')->validate([
'email' => $request->user()->email,
'password' => $request->password,
])) {
throw ValidationException::withMessages([
'password' => __('auth.password'),
]);
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended(route('dashboard', absolute: false));
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class EmailVerificationNotificationController extends Controller
{
/**
* Send a new email verification notification.
*/
public function store(Request $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false));
}
$request->user()->sendEmailVerificationNotification();
return back()->with('status', 'verification-link-sent');
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class EmailVerificationPromptController extends Controller
{
/**
* Display the email verification prompt.
*/
public function __invoke(Request $request): RedirectResponse|View
{
return $request->user()->hasVerifiedEmail()
? redirect()->intended(route('dashboard', absolute: false))
: view('auth.verify-email');
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
class NewPasswordController extends Controller
{
/**
* Display the password reset view.
*/
public function create(Request $request): View
{
return view('auth.reset-password', ['request' => $request]);
}
/**
* Handle an incoming new password request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'token' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function (User $user) use ($request) {
$user->forceFill([
'password' => Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $status == Password::PASSWORD_RESET
? redirect()->route('login')->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
class PasswordController extends Controller
{
/**
* Update the user's password.
*/
public function update(Request $request): RedirectResponse
{
$validated = $request->validateWithBag('updatePassword', [
'current_password' => ['required', 'current_password'],
'password' => ['required', Password::defaults(), 'confirmed'],
]);
$request->user()->update([
'password' => Hash::make($validated['password']),
]);
return back()->with('status', 'password-updated');
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\View\View;
class PasswordResetLinkController extends Controller
{
/**
* Display the password reset link request view.
*/
public function create(): View
{
return view('auth.forgot-password');
}
/**
* Handle an incoming password reset link request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'email' => ['required', 'email'],
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*/
public function create(): View
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(route('dashboard', absolute: false));
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;
class VerifyEmailController extends Controller
{
/**
* Mark the authenticated user's email address as verified.
*/
public function __invoke(EmailVerificationRequest $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;
class ProfileController extends Controller
{
/**
* Display the user's profile form.
*/
public function edit(Request $request): View
{
return view('profile.edit', [
'user' => $request->user(),
]);
}
/**
* Update the user's profile information.
*/
public function update(ProfileUpdateRequest $request): RedirectResponse
{
$request->user()->fill($request->validated());
if ($request->user()->isDirty('email')) {
$request->user()->email_verified_at = null;
}
$request->user()->save();
return Redirect::route('profile.edit')->with('status', 'profile-updated');
}
/**
* Delete the user's account.
*/
public function destroy(Request $request): RedirectResponse
{
$request->validateWithBag('userDeletion', [
'password' => ['required', 'current_password'],
]);
$user = $request->user();
Auth::logout();
$user->delete();
$request->session()->invalidate();
$request->session()->regenerateToken();
return Redirect::to('/');
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string'],
];
}
/**
* Attempt to authenticate the request's credentials.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited(): void
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*/
public function throttleKey(): string
{
return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ProfileUpdateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'lowercase',
'email',
'max:255',
Rule::unique(User::class)->ignore($this->user()->id),
],
];
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace App\Livewire;
use App\Models\Document;
use App\Services\DocumentService;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
class DocumentEditor extends Component
{
public ?Document $document = null;
public $title = '';
public $content = '';
public $directory = '';
public $isEditMode = false;
public function mount(?Document $document = null)
{
if ($document) {
$this->document = $document;
$this->title = $document->title;
$this->content = $document->content;
$this->directory = $document->directory;
$this->isEditMode = true;
} else {
$titleParam = request()->query('title');
if ($titleParam) {
$this->title = $titleParam;
}
}
}
public function save(DocumentService $documentService)
{
$this->validate([
'title' => 'required|string|max:255',
'content' => 'required|string',
]);
try {
if ($this->isEditMode && $this->document) {
$this->document = $documentService->updateDocument(
$this->document,
$this->title,
$this->content,
Auth::id()
);
session()->flash('message', 'Document updated successfully!');
return $this->redirect(route('documents.show', $this->document));
} else {
$this->document = $documentService->createDocument(
$this->title,
$this->content,
Auth::id(),
$this->directory ?: null
);
session()->flash('message', 'Document created successfully!');
return $this->redirect(route('documents.show', $this->document));
}
} catch (\Exception $e) {
session()->flash('error', 'Error saving document: ' . $e->getMessage());
}
}
public function delete(DocumentService $documentService)
{
if (!$this->isEditMode || !$this->document) {
return;
}
try {
$documentService->deleteDocument($this->document);
session()->flash('message', 'Document deleted successfully!');
// Try to redirect to home document, or root if not found
$homeDocument = Document::where('slug', 'home')->first();
if ($homeDocument) {
return redirect()->route('documents.show', $homeDocument);
}
return redirect('/');
} catch (\Exception $e) {
session()->flash('error', 'Error deleting document: ' . $e->getMessage());
}
}
public function render()
{
return view('livewire.document-editor')
->layout('layouts.knowledge-base', [
'title' => $this->isEditMode ? 'Edit: ' . $this->title : 'New Document'
]);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Livewire;
use App\Models\Document;
use App\Services\DocumentService;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
class DocumentViewer extends Component
{
public Document $document;
public $backlinks = [];
public $renderedContent = '';
public function mount(Document $document, DocumentService $documentService)
{
$this->document = $document;
$this->renderedContent = $this->document->processLinks();
$this->backlinks = $documentService->getBacklinks($this->document);
if (Auth::check()) {
$documentService->recordDocumentAccess($this->document, Auth::id());
}
}
public function render()
{
return view('livewire.document-viewer')
->layout('layouts.knowledge-base', ['title' => $this->document->title]);
}
}

View File

@@ -0,0 +1,107 @@
<?php
namespace App\Livewire;
use App\Models\Document;
use App\Services\DocumentService;
use Livewire\Component;
use Livewire\Attributes\Computed;
class QuickSwitcher extends Component
{
public $search = '';
public $selectedIndex = 0;
#[Computed]
public function results()
{
if (empty($this->search)) {
return Document::select('id', 'title', 'slug', 'path', 'updated_at')
->orderBy('updated_at', 'desc')
->limit(10)
->get()
->map(fn($doc) => [
'id' => $doc->id,
'title' => $doc->title,
'slug' => $doc->slug,
'directory' => dirname($doc->path),
])
->toArray();
}
// FULLTEXT検索を使用日本語対応
$results = Document::select('id', 'title', 'slug', 'path', 'updated_at')
->whereRaw('MATCH(title, content) AGAINST(? IN BOOLEAN MODE)', [$this->search])
->orderBy('updated_at', 'desc')
->limit(10)
->get()
->map(fn($doc) => [
'id' => $doc->id,
'title' => $doc->title,
'slug' => $doc->slug,
'directory' => dirname($doc->path),
])
->toArray();
// FULLTEXT検索で結果がない場合は LIKE 検索にフォールバック
if (empty($results)) {
$results = Document::select('id', 'title', 'slug', 'path', 'updated_at')
->where(function($query) {
$query->where('title', 'like', '%' . $this->search . '%')
->orWhere('content', 'like', '%' . $this->search . '%');
})
->orderBy('updated_at', 'desc')
->limit(10)
->get()
->map(fn($doc) => [
'id' => $doc->id,
'title' => $doc->title,
'slug' => $doc->slug,
'directory' => dirname($doc->path),
])
->toArray();
}
return $results;
}
public function updated($propertyName)
{
if ($propertyName === 'search') {
$this->selectedIndex = 0;
}
}
public function selectNext()
{
$results = $this->results;
if ($this->selectedIndex < count($results) - 1) {
$this->selectedIndex++;
}
}
public function selectPrevious()
{
if ($this->selectedIndex > 0) {
$this->selectedIndex--;
}
}
public function selectDocument()
{
$results = $this->results;
if (isset($results[$this->selectedIndex])) {
$document = $results[$this->selectedIndex];
// id が存在することを確認
if (!empty($document['id'])) {
return $this->redirect(route('documents.show', $document['id']));
}
}
}
public function render()
{
return view('livewire.quick-switcher');
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Livewire;
use App\Models\Document;
use App\Services\DocumentService;
use Livewire\Component;
class SidebarTree extends Component
{
public $tree = [];
public function mount(DocumentService $documentService)
{
$this->tree = $documentService->getDirectoryTree();
}
public function render()
{
return view('livewire.sidebar-tree');
}
}

295
src/app/Models/Document.php Normal file
View File

@@ -0,0 +1,295 @@
<?php
namespace App\Models;
use App\Helpers\SlugHelper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use League\CommonMark\CommonMarkConverter;
use League\CommonMark\Extension\CommonMark\Node\Inline\Link;
use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
class Document extends Model
{
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'path',
'title',
'slug',
'content',
'rendered_html',
'frontmatter',
'file_size',
'file_hash',
'file_modified_at',
'created_by',
'updated_by',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'frontmatter' => 'array',
'file_modified_at' => 'datetime',
];
}
/**
* Frontmatterをパース互換性のため残す
*
* @param string $content
* @return array{frontmatter: array, content: string}
*/
protected static function parseFrontmatter(string $content): array
{
$frontmatter = [];
$bodyContent = $content;
// Frontmatterの検出--- で囲まれた部分)
if (preg_match('/^---\s*\n(.*?)\n---\s*\n(.*)/s', $content, $matches)) {
$frontmatterText = $matches[1];
$bodyContent = $matches[2];
// 簡易的なYAMLパースkey: value形式のみ
$lines = explode("\n", $frontmatterText);
foreach ($lines as $line) {
if (preg_match('/^([^:]+):\s*(.*)$/', $line, $lineMatches)) {
$frontmatter[trim($lineMatches[1])] = trim($lineMatches[2]);
}
}
}
return [
'frontmatter' => $frontmatter,
'content' => trim($bodyContent),
];
}
/**
* Markdownをレンダリング
*
* @param string $markdown
* @return string
*/
public static function renderMarkdown(string $markdown): string
{
$converter = new CommonMarkConverter([
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
$converter->getEnvironment()->addExtension(new GithubFlavoredMarkdownExtension());
return $converter->convert($markdown)->getContent();
}
/**
* [[wiki-link]]を抽出してリンクテーブルに同期
*
* @return void
*/
public function syncLinks(): void
{
// 既存のリンクを削除
$this->outgoingLinks()->delete();
// [[wiki-link]]を抽出
preg_match_all('/\[\[([^\]]+)\]\]/', $this->content, $matches);
if (empty($matches[1])) {
return;
}
$position = 0;
foreach ($matches[1] as $linkTitle) {
$linkTitle = trim($linkTitle);
// リンク先のドキュメントを検索
$targetDocument = static::where('title', $linkTitle)
->orWhere('slug', SlugHelper::generate($linkTitle))
->first();
DocumentLink::create([
'source_document_id' => $this->id,
'target_document_id' => $targetDocument?->id,
'target_title' => $linkTitle,
'position' => $position++,
]);
}
}
/**
* [[wiki-link]]をHTMLリンクに変換
*
* @return string
*/
public function processLinks(): string
{
return preg_replace_callback(
'/\[\[([^\]]+)\]\]/',
function ($matches) {
$linkTitle = trim($matches[1]);
$slug = SlugHelper::generate($linkTitle);
// リンク先のドキュメントを検索
$targetDocument = static::where('title', $linkTitle)
->orWhere('slug', $slug)
->first();
if ($targetDocument) {
return '<a href="/documents/' . $targetDocument->slug . '" class="wiki-link">' . e($linkTitle) . '</a>';
} else {
return '<a href="/documents/create?title=' . urlencode($linkTitle) . '" class="wiki-link wiki-link-new">' . e($linkTitle) . '</a>';
}
},
$this->rendered_html
);
}
/**
* 全文検索スコープ
*
* @param Builder $query
* @param string $searchTerm
* @return Builder
*/
public function scopeSearch(Builder $query, string $searchTerm): Builder
{
return $query->whereRaw(
'MATCH(title, content) AGAINST(? IN BOOLEAN MODE)',
[$searchTerm]
);
}
/**
* ディレクトリ内検索スコープ
*
* @param Builder $query
* @param string $directory
* @return Builder
*/
public function scopeInDirectory(Builder $query, string $directory): Builder
{
$directory = rtrim($directory, '/') . '/';
return $query->where('path', 'like', $directory . '%');
}
/**
* 作成者リレーション
*
* @return BelongsTo
*/
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
/**
* 更新者リレーション
*
* @return BelongsTo
*/
public function updater(): BelongsTo
{
return $this->belongsTo(User::class, 'updated_by');
}
/**
* 発リンク(このドキュメントから他へのリンク)
*
* @return HasMany
*/
public function outgoingLinks(): HasMany
{
return $this->hasMany(DocumentLink::class, 'source_document_id');
}
/**
* 被リンク(他のドキュメントからこのドキュメントへのリンク)
*
* @return HasMany
*/
public function incomingLinks(): HasMany
{
return $this->hasMany(DocumentLink::class, 'target_document_id');
}
/**
* このドキュメントを最近閲覧したユーザー
*
* @return HasManyThrough
*/
public function recentByUsers(): HasManyThrough
{
return $this->hasManyThrough(
User::class,
RecentDocument::class,
'document_id',
'id',
'id',
'user_id'
);
}
/**
* ディレクトリパスを取得
*
* @return string
*/
public function getDirectoryAttribute(): string
{
return dirname($this->path);
}
/**
* ファイル名を取得
*
* @return string
*/
public function getFilenameAttribute(): string
{
return basename($this->path);
}
/**
* 絶対パスを取得
*
* @return string
*/
public function getAbsolutePathAttribute(): string
{
return Storage::disk('markdown')->path($this->path);
}
/**
* タイトルセット時にslugも自動生成
*
* @param string $value
* @return void
*/
public function setTitleAttribute(string $value): void
{
$this->attributes['title'] = $value;
if (empty($this->attributes['slug'])) {
$this->attributes['slug'] = SlugHelper::generate($value);
}
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class DocumentLink extends Model
{
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'source_document_id',
'target_document_id',
'target_title',
'position',
];
/**
* ソース(リンク元)ドキュメント
*
* @return BelongsTo
*/
public function sourceDocument(): BelongsTo
{
return $this->belongsTo(Document::class, 'source_document_id');
}
/**
* ターゲット(リンク先)ドキュメント
*
* @return BelongsTo
*/
public function targetDocument(): BelongsTo
{
return $this->belongsTo(Document::class, 'target_document_id');
}
/**
* リンク先が未作成かどうかを判定
*
* @return bool
*/
public function isBroken(): bool
{
return is_null($this->target_document_id);
}
/**
* リンク先ドキュメントのURLを取得
*
* @return string
*/
public function getUrlAttribute(): string
{
if ($this->isBroken()) {
return '/documents/create?title=' . urlencode($this->target_title);
}
return '/documents/' . $this->targetDocument->slug;
}
}

View File

@@ -0,0 +1,95 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class RecentDocument extends Model
{
/**
* テーブルにはtimestampsがないため無効化
*
* @var bool
*/
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'user_id',
'document_id',
'accessed_at',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'accessed_at' => 'datetime',
];
}
/**
* ユーザーリレーション
*
* @return BelongsTo
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* ドキュメントリレーション
*
* @return BelongsTo
*/
public function document(): BelongsTo
{
return $this->belongsTo(Document::class);
}
/**
* ドキュメントアクセスを記録
*
* @param int $userId
* @param int $documentId
* @return void
*/
public static function recordAccess(int $userId, int $documentId): void
{
static::updateOrCreate(
[
'user_id' => $userId,
'document_id' => $documentId,
],
[
'accessed_at' => now(),
]
);
}
/**
* ユーザーの最近閲覧したドキュメントを取得
*
* @param int $userId
* @param int $limit
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getRecentForUser(int $userId, int $limit = 10)
{
return static::where('user_id', $userId)
->with('document')
->orderBy('accessed_at', 'desc')
->limit($limit)
->get();
}
}

48
src/app/Models/User.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}

View File

@@ -0,0 +1,306 @@
<?php
namespace App\Services;
use App\Models\Document;
use App\Models\RecentDocument;
use App\Helpers\SlugHelper;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class DocumentService
{
/**
* 新しいドキュメントを作成
*
* @param string $title
* @param string $content
* @param int|null $userId
* @param string|null $directory (deprecated - path is now auto-generated from title)
* @return Document
*/
public function createDocument(
string $title,
string $content,
?int $userId = null,
?string $directory = null
): Document {
// タイトルからパスとスラッグを自動生成
// 例: "Laravel/Livewire/Components" → path="Laravel/Livewire/Components.md", slug="components"
[$path, $slug] = $this->generatePathAndSlug($title);
// ドキュメントをDBに作成
$document = Document::create([
'path' => $path,
'title' => $title,
'slug' => $slug,
'content' => $content,
'rendered_html' => Document::renderMarkdown($content),
'created_by' => $userId,
'updated_by' => $userId,
]);
// リンクを同期
$document->syncLinks();
return $document;
}
/**
* ドキュメントを更新
*
* @param Document $document
* @param string $title
* @param string $content
* @param int|null $userId
* @return Document
*/
public function updateDocument(
Document $document,
string $title,
string $content,
?int $userId = null
): Document {
// タイトルが変更された場合はパスとスラッグを再生成
if ($document->title !== $title) {
[$path, $slug] = $this->generatePathAndSlug($title, $document->id);
$document->path = $path;
$document->slug = $slug;
}
$document->title = $title;
$document->content = $content;
$document->rendered_html = Document::renderMarkdown($content);
$document->updated_by = $userId;
// DBに保存
$document->save();
// リンクを再同期
$document->syncLinks();
return $document;
}
/**
* ドキュメントを削除
*
* @param Document $document
* @return bool
*/
public function deleteDocument(Document $document): bool
{
// DBから削除ソフトデリート
return $document->delete();
}
/**
* 全文検索
*
* @param string $query
* @param int $limit
* @return \Illuminate\Database\Eloquent\Collection
*/
public function search(string $query, int $limit = 20)
{
return Document::search($query)
->limit($limit)
->get();
}
/**
* ディレクトリツリーを生成
*
* @return array
*/
public function getDirectoryTree(): array
{
$documents = Document::orderBy('path')->get();
$tree = [];
foreach ($documents as $document) {
$parts = explode('/', $document->path);
$current = &$tree;
foreach ($parts as $index => $part) {
$isFile = ($index === count($parts) - 1);
if ($isFile) {
// ファイル
if (!isset($current['_files'])) {
$current['_files'] = [];
}
$current['_files'][] = [
'name' => $part,
'document' => $document,
];
} else {
// ディレクトリ
if (!isset($current[$part])) {
$current[$part] = [];
}
$current = &$current[$part];
}
}
}
return $tree;
}
/**
* ユーザーの最近閲覧したドキュメントを取得
*
* @param int $userId
* @param int $limit
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getRecentDocuments(int $userId, int $limit = 10)
{
return RecentDocument::getRecentForUser($userId, $limit);
}
/**
* ドキュメント閲覧を記録
*
* @param Document $document
* @param int $userId
* @return void
*/
public function recordDocumentAccess(Document $document, int $userId): void
{
RecentDocument::recordAccess($userId, $document->id);
}
/**
* 指定タイトルのドキュメントを検索
*
* @param string $title
* @return Document|null
*/
public function findByTitle(string $title): ?Document
{
return Document::where('title', $title)
->orWhere('slug', SlugHelper::generate($title))
->first();
}
/**
* 被リンク(バックリンク)を取得
*
* @param Document $document
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getBacklinks(Document $document)
{
return $document->incomingLinks()
->with('sourceDocument')
->get()
->pluck('sourceDocument')
->filter();
}
/**
* 壊れたリンク(未作成ページへのリンク)を取得
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getBrokenLinks()
{
return DB::table('document_links')
->whereNull('target_document_id')
->select('target_title', DB::raw('COUNT(*) as count'))
->groupBy('target_title')
->orderByDesc('count')
->get();
}
/**
* タイトルからパスとスラッグを生成
* タイトルに含まれる / をディレクトリ区切りとして扱う
*
* : "Laravel/Livewire/Components"
* path = "Laravel/Livewire/Components.md"
* slug = "components" (最後のコンポーネントから生成)
*
* @param string $title
* @param int|null $excludeDocumentId 更新時に除外するドキュメントID
* @return array [path, slug]
*/
private function generatePathAndSlug(string $title, ?int $excludeDocumentId = null): array
{
// タイトルをそのままパスとして使用(.md拡張子を追加
$basePath = $title . '.md';
// 最後のパスコンポーネント(スラッシュで区切られた最後の部分)からスラッグを生成
$lastComponent = basename($title);
$baseSlug = SlugHelper::generate($lastComponent);
// ユニークなパスとスラッグを生成
return $this->ensureUniquePath($basePath, $baseSlug, $excludeDocumentId);
}
/**
* パスとスラッグがユニークになるように調整
*
* @param string $basePath
* @param string $baseSlug
* @param int|null $excludeDocumentId
* @return array [path, slug]
*/
private function ensureUniquePath(string $basePath, string $baseSlug, ?int $excludeDocumentId = null): array
{
$path = $basePath;
$slug = $baseSlug;
$counter = 1;
while (true) {
$query = Document::withTrashed()
->where(function ($q) use ($path, $slug) {
$q->where('path', $path)->orWhere('slug', $slug);
});
if ($excludeDocumentId) {
$query->where('id', '!=', $excludeDocumentId);
}
if (!$query->exists()) {
break;
}
$counter++;
// パス: "title.md" → "title-2.md"
$path = preg_replace('/\.md$/', "-{$counter}.md", $basePath);
// スラッグ: "title" → "title-2"
$slug = $baseSlug . '-' . $counter;
}
return [$path, $slug];
}
/**
* 初期ドキュメントを作成
*
* @return void
*/
public function createInitialDocuments(): void
{
// ホームページ
$this->createDocument(
'Home',
"# Welcome to Knowledge Base\n\nThis is your personal knowledge base powered by Markdown.\n\n## Getting Started\n\n- Create new documents using [[wiki-links]]\n- Use Ctrl+K for quick switching\n- Full-text search is available\n\n## Example Links\n\n- [[Getting Started]]\n- [[Documentation]]\n- [[Notes]]",
null,
null
);
// Getting Startedページ
$this->createDocument(
'Getting Started',
"# Getting Started\n\nLearn how to use this knowledge base.\n\n## Creating Documents\n\nClick on any [[wiki-link]] to create a new document.\n\n## Editing\n\nClick the edit button to modify content.\n\nBack to [[Home]]",
null,
null
);
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class AppLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.app');
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class GuestLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.guest');
}
}