*/ use HasFactory; public const COLORS = [ 'zinc', 'red', 'orange', 'amber', 'green', 'emerald', 'sky', 'blue', 'indigo', 'violet', 'fuchsia', 'pink', ]; /** @return BelongsTo */ public function user(): BelongsTo { return $this->belongsTo(User::class); } /** @return BelongsTo */ public function parent(): BelongsTo { return $this->belongsTo(Folder::class, 'parent_id'); } /** @return HasMany */ public function children(): HasMany { return $this->hasMany(Folder::class, 'parent_id'); } /** @return HasMany */ public function todos(): HasMany { return $this->hasMany(Todo::class); } /** * Scope the query to folders owned by the given user. * * @param Builder $query * @return Builder */ public function scopeForUser(Builder $query, User|int $user): Builder { return $query->where('user_id', $user instanceof User ? $user->id : $user); } /** * Scope the query to top-level folders (no parent). * * @param Builder $query * @return Builder */ public function scopeToplevel(Builder $query): Builder { return $query->whereNull('parent_id'); } /** * Build a flattened, depth-aware tree of the user's folders * ordered top-down, with the full path (e.g. "Work / Acme Corp"). * * @return Collection */ public static function treeForUser(User|int $user): Collection { $folders = Folder::query() ->forUser($user) ->orderBy('name') ->get() ->keyBy('id'); $tree = collect(); $visit = function (Folder $folder, int $depth, string $prefix) use (&$visit, &$tree, $folders): void { $path = $prefix === '' ? $folder->name : $prefix.' / '.$folder->name; $tree->push([ 'folder' => $folder, 'depth' => $depth, 'path' => $path, ]); foreach ($folders->where('parent_id', $folder->id)->values() as $child) { $visit($child, $depth + 1, $path); } }; foreach ($folders->whereNull('parent_id')->values() as $topLevel) { $visit($topLevel, 0, ''); } return $tree; } }