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
8 changes: 8 additions & 0 deletions docs/content/2.essentials/6.swimlanes.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ The header `+` from `createCardAction()` creates a card without knowing the lane
- Without `moveUsing()`, the lanes are read-only. Cards move between columns inside their lane, the browser blocks a drop into another lane, and the server refuses it with a message.
- The server checks that the card sits in the lane it left, and refuses the move when the board has changed underneath the user.

## Card order

Cells order their cards by the board query's own `orderBy()` calls first, then by position, the same as columns. A bare column name resolves against the model's own table.

Lanes fall back to position order for the whole query when an order cannot be placed in the ranking: a bare name that is not a column of the model's table (a selected alias such as a `withCount` column) or that a selected alias shadows, an `inOrderOf()` order, or a raw or expression order that uses a selected alias by name. A raw order that only calls a function with an alias's name, such as `count(*)`, is honoured. A board query with `distinct()` honours only plain `orderBy()` columns of the model's own table that its select list includes, and falls back for any other order.

While the board query carries an order, a card dragged within a cell is written a position between neighbours that are not in position order. Refuse or ignore reorders inside a cell while the board sorts, the same as for flat columns.

## Limits and collapsed columns

- A column limit counts the whole column across every lane, and the header is shared.
Expand Down
130 changes: 127 additions & 3 deletions src/Concerns/HasBoardGroupings.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Relaticle\Flowforge\Grouping;
Expand Down Expand Up @@ -96,7 +97,11 @@ protected function getLaneRecordsQuery(Lane $lane, int $perCellLimit): ?Builder
return null;
}

$scoped = $lane->applyQuery($boardQuery)->applyScopes();
$laneQuery = $lane->applyQuery($boardQuery);
$boardOrders = $laneQuery->getQuery()->orders ?? [];
$boardOrderBindings = $laneQuery->getQuery()->getRawBindings()['order'];

$scoped = $laneQuery->applyScopes();
$model = $scoped->getModel();
$inner = $scoped->getQuery();

Expand All @@ -112,21 +117,26 @@ protected function getLaneRecordsQuery(Lane $lane, int $perCellLimit): ?Builder
}
}

[$boardOrder, $boardOrderBindings] = $this->compileBoardOrders($inner, $model, $boardOrders, $boardOrderBindings);

if ($inner->distinct) {
$inner = $model->newModelQuery()->fromSub($inner, $model->getTable())->getQuery();
}

$grammar = $inner->getGrammar();
$partition = $grammar->wrap($this->getColumnIdentifierAttribute());
$order = collect([$this->getPositionIdentifierAttribute(), $model->getKeyName()])
$order = collect([$boardOrder])
->merge(collect([$this->getPositionIdentifierAttribute(), $model->getKeyName()])
->filter()
->map(fn (string $column): string => $grammar->wrap($model->qualifyColumn($column))))
->filter()
->map(fn (string $column): string => $grammar->wrap($model->qualifyColumn($column)))
->implode(', ');

if ($inner->columns === null) {
$inner->select($model->qualifyColumn('*'));
}

$inner->addBinding($boardOrderBindings, 'select');
$inner->addSelect([
DB::raw("row_number() over (partition by {$partition} order by {$order}) as flowforge_cell_row"),
DB::raw("count(*) over (partition by {$partition}) as flowforge_cell_total"),
Expand All @@ -140,6 +150,120 @@ protected function getLaneRecordsQuery(Lane $lane, int $perCellLimit): ?Builder
return $outer->setEagerLoads($scoped->getEagerLoads());
}

/**
* @param array<int, array<string, mixed>> $orders
* @param array<int, mixed> $bindings
* @return array{string, array<int, mixed>}
*/
protected function compileBoardOrders(QueryBuilder $inner, Model $model, array $orders, array $bindings): array
{
$grammar = $inner->getGrammar();
$table = $model->getTable();
$columns = array_filter(array_map($grammar->getValue(...), $inner->columns ?? []), is_string(...));
$selectsOwnColumns = array_intersect(['*', "{$table}.*"], $columns) !== [];
$compiled = [];

foreach ($orders as $order) {
$column = $order['column'] ?? null;

if (($order['type'] ?? null) === 'InOrderOf') {
return ['', []];
}

if ($inner->distinct) {
$name = is_string($column) && ! isset($order['sql']) ? Str::after($column, "{$table}.") : '';

if ($name === '' || str_contains($name, '.') || ! ($selectsOwnColumns || array_intersect([$name, "{$table}.{$name}"], $columns) !== [])) {
return ['', []];
}

$compiled[] = $grammar->wrap($model->qualifyColumn($name)) . ' ' . $order['direction'];

continue;
}

if (is_string($column) && ! isset($order['sql'])) {
$isBare = ! str_contains($column, '.');

if ($isBare && (! $this->modelHasColumn($model, $column) || in_array($column, $this->selectAliases($inner), true))) {
return ['', []];
}

$compiled[] = $grammar->wrap($isBare ? $model->qualifyColumn($column) : $column) . ' ' . $order['direction'];

continue;
}

$sql = isset($order['sql'])
? $grammar->getValue($order['sql'])
: $grammar->wrap($column) . ' ' . $order['direction'];

if ($this->mentionsAlias($sql, $this->selectAliases($inner))) {
return ['', []];
}

$compiled[] = $sql;
}

return [implode(', ', $compiled), $bindings];
}

/**
* @return array<int, string>
*/
protected function selectAliases(QueryBuilder $query): array
{
$aliases = [];

foreach ($query->columns ?? [] as $column) {
$items = [''];
$depth = 0;
$quote = null;

foreach (str_split((string) $query->getGrammar()->getValue($column)) as $char) {
if ($quote !== null) {
$quote = $char === $quote ? null : $quote;
} elseif (in_array($char, ["'", '"', '`'], true)) {
$quote = $char;
} elseif ($char === '(' || $char === ')') {
$depth += $char === '(' ? 1 : -1;
} elseif ($char === ',' && $depth === 0) {
$items[] = '';

continue;
}

$items[array_key_last($items)] .= $char;
}

foreach ($items as $item) {
if (preg_match('/\sas\s+(?:"((?:[^"]|"")+)"|`([^`]+)`|\[([^\]]+)\]|([\w$]+))\s*$|\)\s+([\w$]+)\s*$/i', $item, $match)) {
$aliases[] = array_values(array_filter(array_slice($match, 1), fn (string $part): bool => $part !== ''))[0];
}
}
}

return $aliases;
}

/**
* @param array<int, string> $aliases
*/
protected function mentionsAlias(string $sql, array $aliases): bool
{
$code = preg_replace("/'(?:[^']|'')*'/", "''", $sql) ?? $sql;

foreach ($aliases as $alias) {
$name = preg_quote($alias, '/');

if (preg_match('/(?<![\w$."`\[])' . $name . '(?![\w$"`\](])/i', $code) || preg_match('/(?<!\.)["`\[]' . $name . '["`\]]/i', $code)) {
return true;
}
}

return false;
}

protected function identifierBelongsToModel(Model $model): bool
{
$identifier = (string) $this->getColumnIdentifierAttribute();
Expand Down
9 changes: 8 additions & 1 deletion tests/Fixtures/Modern/TestCastGroupedBoard.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class TestCastGroupedBoard extends BoardPage

public bool $distinctJoin = false;

public string $orderShape = 'none';

public function getEloquentQuery(): Builder
{
$query = CastTask::query();
Expand All @@ -28,7 +30,12 @@ public function getEloquentQuery(): Builder
$query->join('task_user', 'task_user.task_id', '=', 'tasks.id')->select('tasks.*')->distinct();
}

return $query;
return match ($this->orderShape) {
'title_desc' => $query->orderBy('tasks.title', 'desc'),
'unselected' => $query->orderBy('task_user.user_id', 'desc'),
'raw' => $query->orderByRaw('lower(tasks.title) desc'),
default => $query,
};
}

public function board(Board $board): Board
Expand Down
45 changes: 44 additions & 1 deletion tests/Fixtures/Modern/TestGroupedBoard.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ class TestGroupedBoard extends BoardPage

public bool $boundHaving = false;

public string $orderShape = 'none';

public int $subqueryUserId = 0;

public array $authorizedLanes = [];

public function getEloquentQuery(): Builder
Expand All @@ -43,7 +47,46 @@ public function getEloquentQuery(): Builder
$query->groupByRaw('tasks.id, ?', [1])->havingRaw('count(*) > ?', [0]);
}

return $query;
return match ($this->orderShape) {
'title_desc' => $query->orderBy('title', 'desc'),
'hours_title' => $query->orderBy('estimated_hours', 'desc')->orderBy('title'),
'bound_raw' => $query
->select('tasks.*')
->selectRaw('? as picked', ['picked'])
->where('tasks.title', '<>', 'Excluded')
->orderByRaw('case when tasks.title = ? then 0 else 1 end', ['Gamma']),
'bound_subquery' => $query
->select('tasks.*')
->selectRaw('? as picked', ['picked'])
->where('tasks.title', '<>', 'Excluded')
->orderBy(
DB::table('task_user')
->selectRaw('count(*)')
->whereColumn('task_user.task_id', 'tasks.id')
->where('task_user.user_id', '<>', $this->subqueryUserId),
'desc',
),
'expression' => $query->orderBy(DB::raw('length(tasks.title)'), 'desc'),
'alias' => $query->withCount('assignees')->orderBy('assignees_count', 'desc'),
'joined_latest' => $query->join('users', 'users.id', '=', 'tasks.created_by')->select('tasks.*')->latest(),
'joined_same_name' => $query->join('task_labels', 'task_labels.task_id', '=', 'tasks.id')->select('tasks.*')->orderBy('id', 'desc'),
'multi_alias' => $query->select('tasks.*')->selectRaw('length(tasks.title) as cnt, 1 as total')->orderBy('cnt', 'desc'),
'multi_alias_raw' => $query->select('tasks.*')->selectRaw('length(tasks.title) as cnt, 1 as total')->orderByRaw('cnt desc'),
'shadowed_alias' => $query->select('tasks.id', 'tasks.status', 'tasks.priority', 'tasks.order_position')->selectRaw('lower(tasks.title) as title')->orderBy('title', 'desc'),
'quoted_alias' => $query->select('tasks.*')->selectRaw('length(tasks.title) as "Total Hours"')->orderByRaw('"Total Hours" desc'),
'function_named_like_alias' => $query
->select('tasks.*')
->selectRaw('(select count(*) from task_user where task_user.task_id = tasks.id) as count')
->orderByRaw('(select count(*) from task_user where task_user.task_id = tasks.id) desc'),
'literal_named_like_alias' => $query
->select('tasks.*')
->selectRaw('1 as picked')
->orderByRaw("case when tasks.title = 'picked' then 0 else 1 end, tasks.title desc"),
'from_sub' => $query
->fromSub(Task::query()->select('tasks.*')->selectRaw('? as picked', ['picked']), 'tasks')
->orderByRaw('case when tasks.title = ? then 0 else 1 end', ['Gamma']),
default => $query,
};
}

public function board(Board $board): Board
Expand Down
Loading
Loading