Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .ai/rules/entities.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@ Entity templates belong to one campaign and one entity type, carry only a name a

## A journal is the one entity a player creates, and player_user_id is its author
`EntityType::Journal` is the only type `isPlayerWritable()`. `EntityPolicy::create()` takes the type as a third argument; pass it everywhere (`[Entity::class, $campaign, $type]`), because a create check without one stays a GM's. The author is `player_user_id`, set at birth from the actor and never moved: the form strips the DM card's `player_user_id`/`is_pc` on a journal so a GM's edit cannot wipe it. No new gate: `Entity::visibleTo()` already shows a row to its player, so Dm means "me and the GM" and Players means "the party". The author sets that one switch through its own rule set (`Rule::enum(Visibility)->only([Dm, Players])`), outside `updateDmFields()`, in the form and in `EntityController::rules()`. Selected stays a DM-card decision. The author may delete their own; other DM fields from a non-DM are never read, as on a PC's form.

## The family tree is one query through the relations scope and a walk in memory
entity_relations.kinship (Kinship: parent, child, sibling, spouse) is read from the source's side, and Kinship::reverse() is the target's word. Relations::family() loads every kinship row the viewer may see in the campaign through EntityRelation::visibleTo(), both ends eager-loaded, and walks two generations up and down in memory. That is the whole leak design: a row the scope refused is not in the graph, so a GM-only grandmother is never reached through a revealed mother. Do not walk hop by hop with per-hop queries, and do not infer siblings from shared parents. The "hidden" mark is for a GM and means the party would not see the row or the relative. The labels fill in from the kinship when blank and a GM's own words win; a plain relationship still requires a label (required_without:kinship).
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ Slice 24 adds **the player screen**, for the television at the end of the table.

Slice 25 adds **downtime**, what each character did between sessions. A row is what they did, how many days it cost, an optional note in Markdown, the session it happened around, and, when the campaign has a calendar, the day in the world it began, from which the page prints the range it covered. A player writes their own PC's rows and a GM writes anyone's; whoever may see the character reads them, and there is no second switch. The same log sits on the character's page, on the session's page, and at `/downtime`, where the days are summed per character on every read. It travels in the export and lands on the character's page in the vault.

Slice 26 adds **family trees**. A relationship may carry a kinship, parent, child, sibling, or spouse, read from the side it was written on, and the labels fill in from it when the GM leaves them blank. A character's page draws a "Family" card from the typed rows, two generations up and two down, walked through the relations card's own gate at both ends: a hidden row or a GM-only relative never reaches the party's tree, and the GM reads a mark on each. The kinship travels in the export and on both relation lists of the API.

Your creatures travel in your export with the prose you wrote. A shipped creature never does — it is named in the file and nothing more, exactly as before. The CC BY notice follows the words rather than the table: a creature you wrote carries none, and a copy of a shipped one keeps the source and licence it came from, so the credit travels with the text.

## Local setup
Expand Down
1 change: 1 addition & 0 deletions app/Actions/Campaigns/ExportCampaign.php
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ private function entities(Campaign $campaign): iterable
'target_entity_id' => $relation->target_entity_id,
'label' => $relation->label,
'reverse_label' => $relation->reverse_label,
'kinship' => $relation->kinship?->value,
'player_visible' => $relation->player_visible,
'position' => $relation->position,
])->values()->all(),
Expand Down
1 change: 1 addition & 0 deletions app/Actions/Campaigns/ImportCampaign.php
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ private function children(array $document, IdMap $ids): void
'target_entity_id' => $ids->newFor($relation['target_entity_id']),
'label' => $relation['label'],
'reverse_label' => $relation['reverse_label'],
'kinship' => $relation['kinship'] ?? null,
'player_visible' => $relation['player_visible'],
'position' => $relation['position'],
]);
Expand Down
3 changes: 3 additions & 0 deletions app/Actions/Campaigns/ReadCampaignFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use App\Actions\Maps\Coordinate;
use App\Enums\EncounterStatus;
use App\Enums\EntityType;
use App\Enums\Kinship;
use App\Enums\LedgerKind;
use App\Enums\PrepRole;
use App\Enums\QuestStatus;
Expand Down Expand Up @@ -534,6 +535,8 @@ private function relations(array $row): array
'target_entity_id' => $this->reference($relation, 'target_entity_id'),
'label' => $this->text($relation, 'label', EntityRelation::MAX_LABEL_LENGTH) ?? 'related to',
'reverse_label' => $this->text($relation, 'reverse_label', EntityRelation::MAX_LABEL_LENGTH),
// Absent from a file older than slice 26, and null is what that means.
'kinship' => isset($relation['kinship']) ? $this->enum(Kinship::class, $relation, 'kinship', 'a relationship') : null,
'player_visible' => (bool) ($relation['player_visible'] ?? false),
'position' => $this->integer($relation, 'position') ?? $index,
];
Expand Down
4 changes: 3 additions & 1 deletion app/Actions/Entities/RelateEntities.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Actions\Entities;

use App\Enums\Kinship;
use App\Models\Entity;
use App\Models\EntityRelation;

Expand All @@ -11,7 +12,7 @@ class RelateEntities
* Writes one row from $source's side. The caller has already checked that the
* target is in the same campaign and is not the source itself.
*/
public function handle(Entity $source, Entity $target, string $label, ?string $reverseLabel, bool $playerVisible = false): EntityRelation
public function handle(Entity $source, Entity $target, string $label, ?string $reverseLabel, bool $playerVisible = false, ?Kinship $kinship = null): EntityRelation
{
$position = $source->relations()->exists() ? (int) $source->relations()->max('position') + 1 : 0;

Expand All @@ -20,6 +21,7 @@ public function handle(Entity $source, Entity $target, string $label, ?string $r
'target_entity_id' => $target->id,
'label' => $label,
'reverse_label' => $reverseLabel,
'kinship' => $kinship,
'player_visible' => $playerVisible,
'position' => $position,
]);
Expand Down
51 changes: 51 additions & 0 deletions app/Enums/Kinship.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace App\Enums;

/**
* What a relationship means when it is family, read from the source's side: the
* source is a parent of the target, a child of it, a sibling, or a spouse.
*
* Four cases, because four is what a tree needs. A cousin is a sibling's child, an
* in-law is a spouse's parent, and both are walked rather than typed.
*/
enum Kinship: string
{
case Parent = 'parent';
case Child = 'child';
case Sibling = 'sibling';
case Spouse = 'spouse';

/**
* The word from the source's side: "parent of".
*/
public function label(): string
{
return $this->value.' of';
}

/**
* The same row read from the target's side.
*/
public function reverse(): self
{
return match ($this) {
self::Parent => self::Child,
self::Child => self::Parent,
self::Sibling, self::Spouse => $this,
};
}

/**
* The heading a generation gets on the tree.
*/
public function plural(): string
{
return match ($this) {
self::Parent => 'Parents',
self::Child => 'Children',
self::Sibling => 'Siblings',
self::Spouse => 'Spouses',
};
}
}
3 changes: 3 additions & 0 deletions app/Http/Resources/Api/V1/EntityResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,15 @@ public function toArray(Request $request): array
'id' => $relation->id,
'label' => $relation->label,
'reverse_label' => $relation->reverse_label,
'kinship' => $relation->kinship?->value,
'target' => self::link($relation->target),
])->values()->all());
$data['incoming_relations'] = $this->whenLoaded('incomingRelations', fn () => $this->incomingRelations
->map(fn (EntityRelation $relation) => [
'id' => $relation->id,
'label' => $relation->readsFromTargetAs(),
// From this page's side, like the label above it.
'kinship' => $relation->kinship?->reverse()->value,
'source' => self::link($relation->source),
])->values()->all());

Expand Down
113 changes: 109 additions & 4 deletions app/Livewire/Entities/Relations.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,18 @@
use App\Actions\Entities\RelateEntities;
use App\Actions\Entities\RemoveRelation;
use App\Actions\Entities\SetRelationVisibility;
use App\Enums\CampaignRole;
use App\Enums\Kinship;
use App\Enums\Visibility;
use App\Livewire\Concerns\InteractsWithCampaign;
use App\Models\Campaign;
use App\Models\Entity;
use App\Models\EntityRelation;
use App\Models\User;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Collection as SupportCollection;
use Illuminate\Validation\Rule;
use Livewire\Component;

/**
Expand All @@ -31,6 +36,9 @@ class Relations extends Component

public string $reverseLabel = '';

/** A Kinship value, or '' for a relationship that is not family. */
public string $kinship = '';

public bool $showParty = false;

public function mount(Campaign $campaign, Entity $entity): void
Expand All @@ -45,15 +53,21 @@ public function relate(RelateEntities $relateEntities): void
{
$this->authorize('manageRelations', $this->entity);

// The labels fill in from the kinship when the GM leaves them blank, so a
// kinship row needs no words; a plain relationship still does.
$validated = $this->validate([
'targetId' => ['required', 'string', 'different:entity.id'],
'label' => ['required', 'string', 'max:'.EntityRelation::MAX_LABEL_LENGTH],
'kinship' => ['nullable', Rule::enum(Kinship::class)],
'label' => ['required_without:kinship', 'nullable', 'string', 'max:'.EntityRelation::MAX_LABEL_LENGTH],
'reverseLabel' => ['nullable', 'string', 'max:'.EntityRelation::MAX_LABEL_LENGTH],
'showParty' => ['boolean'],
], [
'targetId.different' => 'A page cannot be related to itself.',
'label.required_without' => 'Say what this page is to the other, or pick a kinship.',
]);

$kinship = filled($validated['kinship'] ?? null) ? Kinship::from($validated['kinship']) : null;

if ($validated['targetId'] === $this->entity->id) {
$this->addError('targetId', 'A page cannot be related to itself.');

Expand All @@ -73,12 +87,13 @@ public function relate(RelateEntities $relateEntities): void
$relateEntities->handle(
$this->entity,
$target,
trim($validated['label']),
filled($validated['reverseLabel']) ? trim($validated['reverseLabel']) : null,
filled($validated['label']) ? trim((string) $validated['label']) : (string) $kinship?->label(),
filled($validated['reverseLabel']) ? trim((string) $validated['reverseLabel']) : $kinship?->reverse()->label(),
(bool) $validated['showParty'],
$kinship,
);

$this->reset('targetId', 'label', 'reverseLabel', 'showParty');
$this->reset('targetId', 'label', 'reverseLabel', 'kinship', 'showParty');
}

public function remove(string $relationId, RemoveRelation $removeRelation): void
Expand Down Expand Up @@ -107,9 +122,99 @@ public function render(): View
'incoming' => $this->entity->incomingRelations()->visibleTo($user, $role)->with('source')->orderBy('created_at')->get(),
'canManage' => $canManage,
'targetOptions' => $canManage ? $this->targetOptions() : collect(),
'kinships' => Kinship::cases(),
'family' => $this->family($user, $role),
]);
}

/**
* The family, walked from this character two generations up and two down.
*
* One query for every kinship row this viewer may see in the campaign, through
* the relations scope, and then a walk in memory. That is what makes the second
* hop as safe as the first: a row the scope refused is not in the graph, so a
* GM-only grandmother is never reached through a revealed mother. A campaign's
* kinship rows are a handful, and one query for all of them is cheaper than a
* query per hop.
*
* A row is read from either end: the source is its kinship of the target, and
* the target is the reverse of the source. The "hidden" mark is for a GM, who
* reads every row, and says the party would not: the row is unrevealed or the
* relative is not a page the party may see.
*
* @return array<string, SupportCollection<int, array{entity: Entity, hidden: bool}>>|null
*/
private function family(User $user, CampaignRole $role): ?array
{
if (! $this->entity->isCharacter()) {
return null;
}

$rows = EntityRelation::query()
->visibleTo($user, $role)
->whereNotNull('kinship')
->with(['source', 'target'])
->get();

if ($rows->isEmpty()) {
return null;
}

/** @var array<string, list<array{kinship: Kinship, entity: Entity, hidden: bool}>> $edges */
$edges = [];

foreach ($rows as $row) {
if ($row->kinship === null) {
continue;
}

$edges[$row->target_entity_id][] = ['kinship' => $row->kinship, 'entity' => $row->source, 'hidden' => ! $row->player_visible || $row->source->visibility !== Visibility::Players];
$edges[$row->entity_id][] = ['kinship' => $row->kinship->reverse(), 'entity' => $row->target, 'hidden' => ! $row->player_visible || $row->target->visibility !== Visibility::Players];
}

$me = $this->entity->id;

if (! isset($edges[$me])) {
return null;
}

/** @return SupportCollection<int, array{entity: Entity, hidden: bool}> */
$of = function (string $id, Kinship $kinship, bool $throughHidden = false) use ($edges): SupportCollection {
return collect($edges[$id] ?? [])
->filter(fn (array $edge) => $edge['kinship'] === $kinship)
->map(fn (array $edge) => ['entity' => $edge['entity'], 'hidden' => $edge['hidden'] || $throughHidden])
->values();
};

$parents = $of($me, Kinship::Parent);
$children = $of($me, Kinship::Child);

$generations = [
'Grandparents' => $parents->flatMap(fn (array $parent) => $of($parent['entity']->id, Kinship::Parent, $parent['hidden'])),
'Parents' => $parents,
'Siblings' => $of($me, Kinship::Sibling),
'Spouses' => $of($me, Kinship::Spouse),
'Children' => $children,
'Grandchildren' => $children->flatMap(fn (array $child) => $of($child['entity']->id, Kinship::Child, $child['hidden'])),
];

$family = [];

foreach ($generations as $heading => $people) {
$people = $people
->reject(fn (array $person) => $person['entity']->id === $me)
->unique(fn (array $person) => $person['entity']->id)
->sortBy(fn (array $person) => $person['entity']->name)
->values();

if ($people->isNotEmpty()) {
$family[$heading] = $people;
}
}

return $family === [] ? null : $family;
}

/**
* What a relationship may point at: anything in the campaign the viewer may see,
* this page excluded.
Expand Down
7 changes: 5 additions & 2 deletions app/Models/EntityRelation.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Models;

use App\Enums\CampaignRole;
use App\Enums\Kinship;
use App\Models\Concerns\BelongsToCampaign;
use Database\Factories\EntityRelationFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
Expand All @@ -21,7 +22,8 @@
* It adds one gate the pin does not need, on the source, because the incoming list
* on the target's page is built from rows whose source is somebody else.
*
* @property string $id
* @property string|null $reverse_label
* @property Kinship|null $kinship What the row means when it is family, from the source's side.
* @property string $campaign_id
* @property string $entity_id
* @property string $target_entity_id
Expand All @@ -36,7 +38,7 @@
* @property-read Entity $target
*/
#[Fillable([
'campaign_id', 'entity_id', 'target_entity_id', 'label', 'reverse_label', 'player_visible', 'position',
'campaign_id', 'entity_id', 'target_entity_id', 'label', 'reverse_label', 'kinship', 'player_visible', 'position',
])]
class EntityRelation extends Model
{
Expand All @@ -50,6 +52,7 @@ class EntityRelation extends Model
protected function casts(): array
{
return [
'kinship' => Kinship::class,
'player_visible' => 'boolean',
'position' => 'integer',
];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
* What a relationship means when it is family. One nullable column, because a
* kinship is one fact about the row and most rows have none: "employer of" is a
* relationship and not a branch. The tree is drawn from the rows that carry one.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('entity_relations', function (Blueprint $table) {
$table->string('kinship', 8)->nullable()->after('reverse_label');
});
}

public function down(): void
{
Schema::table('entity_relations', function (Blueprint $table) {
$table->dropColumn('kinship');
});
}
};
Loading
Loading