Skip to content

Commit

Permalink
Improve performance (#1191)
Browse files Browse the repository at this point in the history
* fix bootstrap spinner (#1134)

* fix detail entangle when using cache (#1179)

* Fix cache ttl (#1187)

* fx cache ttl

* fx cache ttl

* fix tests

* Add perPage on getCacheKeys (#1189)

* fix (#1170)

* fix

* fix 2

* merge 4.x

* fix wire:key

---------

Co-authored-by: luanfreitasdev <[email protected]>

* fix cacheKeys

* wip

* fix phpstan

* fix cypress tests

---------

Co-authored-by: racerguy <[email protected]>
  • Loading branch information
luanfreitasdev and racerguy authored Oct 2, 2023
1 parent 690433e commit fdc48e9
Show file tree
Hide file tree
Showing 24 changed files with 161 additions and 142 deletions.
2 changes: 1 addition & 1 deletion dist/mix-manifest.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"/powergrid.js": "/powergrid.js?id=fdb4bf85097f08ea205185a7e199ada2",
"/powergrid.js": "/powergrid.js?id=50f814d7565817030b1b2ce4099bb763",
"/tom-select.css": "/tom-select.css?id=7af730d2c4bf937316d4002948b1571d",
"/powergrid.css": "/powergrid.css?id=f2c32aef475db76375ad76fb2f0f7d33"
}
2 changes: 1 addition & 1 deletion dist/powergrid.js

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"devDependencies": {
"autoprefixer": "^10.4.14",
"blade-formatter": "^1.37.1",
"cypress": "^13.2.0",
"cypress": "^13.3.0",
"flatpickr": "^4.6.13",
"postcss": "^8.4.29",
"resolve-url-loader": "^5.0.0",
Expand Down
20 changes: 19 additions & 1 deletion resources/js/components/pg-editable.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export default (params) => ({
hash: null,
hashError: true,
showEditable: false,
editableInput: '',
inputClass: params.inputClass,
saveOnMouseOut: params.saveOnMouseOut,
init() {
if (this.content.length === 0 && this.fallback) {
this.content = this.htmlSpecialChars(this.fallback);
Expand All @@ -32,6 +35,21 @@ export default (params) => ({
showEditable = true
}

this.editableInput = `
<div
x-ref="editable"
x-text="content"
value="${this.content}"
placeholder="adasda"
contenteditable
class="pg-single-line ${this.inputClass}"
${this.saveOnMouseOut ? 'x-on:mousedown.outside="save()"' : ''}
x-on:keydown.enter="save()"
id="${`editable-` + this.dataField + `-` + this.id}"
x-on:keydown.esc="cancel"
>
</div>`;

this.$nextTick(() => setTimeout(() => {
this.showEditable = showEditable
this.focus()
Expand Down Expand Up @@ -70,7 +88,7 @@ export default (params) => ({

this.$nextTick(() => setTimeout(() => {
this.focus()
setTimeout(() =>this.$el.setAttribute('value', ''), 200)
setTimeout(() => this.$el.setAttribute('value', ''), 200)
}, 100))

}, 100)
Expand Down
29 changes: 17 additions & 12 deletions resources/views/components/editable.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,37 @@
$resolveContent = function (string $currentTable, string $field, \Illuminate\Database\Eloquent\Model|\stdClass $row): ?string {
$currentField = $field;
$replace = fn($content) => preg_replace('#<script(.*?)>(.*?)</script>#is', '', $content);
/** @codeCoverageIgnore */
if (str_contains($currentField, '.')) {
$data = \Illuminate\Support\Str::of($field)->explode('.');
$table = $data->get(0);
$field = $data->get(1);
if ($table === $currentTable) {
return $replace($row->{$field});
}
return $replace($row->{$table}->{$field});
}
return $replace($row->{$field});
};
$fallback = html_entity_decode(strval(data_get($editable, 'fallback')), ENT_QUOTES, 'utf-8');
$value = html_entity_decode(strval($resolveContent($currentTable, $field, $row)), ENT_QUOTES, 'utf-8');
$content = !empty($value) || $value == '0' ? $value : $fallback;
$params = [
'theme' => $theme->name,
'tableName' => $tableName,
'id' => data_get($row, $primaryKey),
'dataField' => $field,
'content' => $content,
'fallback' => $fallback,
'inputClass' => $theme->editable->inputClass,
'saveOnMouseOut' => data_get($editable, 'saveOnMouseOut'),
];
@endphp
<div
Expand All @@ -60,14 +62,17 @@
:id="`clickable-` + dataField + '-' + id"
style="cursor: pointer; width: 100%; height: 100%;"
>
<span style="border-bottom: dotted 1px;">{{ $content }}</span>
<span
style="border-bottom: dotted 1px;"
x-text="content"
></span>
</div>
<div
x-show="showEditable && !hashError"
<template
x-if="showEditable && !hashError"
style="margin-bottom: 4px"
>
{{ $input }}
</div>
<div x-html="editableInput"></div>
</template>
@if ($showErrorBag)
@error($field . '.' . $row->{$primaryKey})
<div class="text-sm text-red-800 p-1 transition-all duration-200">
Expand Down
27 changes: 14 additions & 13 deletions resources/views/components/frameworks/tailwind/toggleable.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
if (str_contains($primaryKey, '.')) {
$showDefaultToggle = true;
}
$value = (int) $row->{$column->field};
$trueValue = $column->toggleable['default'][0];
$falseValue = $column->toggleable['default'][1];
$params = [
'id' => data_get($row, $primaryKey),
'isHidden' => !$showToggleable ? 'true' : 'false',
Expand All @@ -22,17 +22,18 @@
<div x-data="pgToggleable(@js($params))">
@if ($column->toggleable['enabled'] && !$showDefaultToggle && $showToggleable === true)
<div class="flex">
<div @class([
'relative rounded-full w-8 h-4 transition duration-200 ease-linear',
'bg-pg-secondary-600 dark:pg-secondary-500' => $value === 1,
'bg-pg-primary-200' => $value === 0,
])>
<div
:class="{
'relative rounded-full w-8 h-4 transition duration-200 ease-linear': true,
'bg-pg-secondary-600 dark:pg-secondary-500': toggle,
'bg-pg-primary-200': !toggle
}">
<label
@class([
'absolute left-0 bg-white border-2 mb-2 w-4 h-4 rounded-full transition transform duration-100 ease-linear cursor-pointer',
'translate-x-full border-pg-secondary-600' => $value === 1,
'translate-x-0 border-pg-primary-200' => $value === 0,
])
:class="{
'absolute left-0 bg-white border-2 mb-2 w-4 h-4 rounded-full transition transform duration-100 ease-linear cursor-pointer': true,
'translate-x-full border-pg-secondary-600': toggle,
'translate-x-0 border-pg-primary-200': !toggle
}"
x-on:click="save"
></label>
<input
Expand Down
1 change: 1 addition & 0 deletions resources/views/components/table-base.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class="{{ $theme->theadClass }}"
<tbody
class="{{ $theme->tbodyClass }}"
style="{{ $theme->tbodyStyle }}"
wire:key="tableBody-{{ uniqid() }}"
>
{{ $body }}
</tbody>
Expand Down
27 changes: 12 additions & 15 deletions resources/views/components/table/detail.blade.php
Original file line number Diff line number Diff line change
@@ -1,29 +1,26 @@
@php
$rulesValues = $actionRulesClass->recoverFromAction($row, 'pg:rows');
@endphp
<template
x-cloak
x-if="detailState"
>
<td colspan="999">
@if (filled($rulesValues['detailView']))
@includeWhen(data_get($setUp, 'detail.state.' . $row->{$primaryKey}),
$rulesValues['detailView'][0]['detailView'],
[
@if (data_get($setUp, 'detail.state.' . $row->{$primaryKey}))
@php
$rulesValues = $actionRulesClass->recoverFromAction($row, 'pg:rows');
@endphp

@if (filled($rulesValues['detailView']))
@include($rulesValues['detailView'][0]['detailView'], [
'id' => data_get($row, $primaryKey),
'options' => array_merge(
data_get($setUp, 'detail.options'),
$rulesValues['detailView']['0']['options']),
]
)
@else
@includeWhen(data_get($setUp, 'detail.state.' . $row->{$primaryKey}),
data_get($setUp, 'detail.view'),
[
])
@else
@include(data_get($setUp, 'detail.view'), [
'id' => data_get($row, $primaryKey),
'options' => data_get($setUp, 'detail.options'),
]
)
])
@endif
@endif
</td>
</template>
2 changes: 1 addition & 1 deletion src/Components/Actions/ActionsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
namespace PowerComponents\LivewirePowerGrid\Components\Actions;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\{Arr, Collection};
use Illuminate\View\ComponentAttributeBag;
use PowerComponents\LivewirePowerGrid\{Button, PowerGridComponent, Traits\UnDot};

Expand Down
4 changes: 2 additions & 2 deletions src/PowerGridComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ protected function getCacheKeys(): array
{
return [
json_encode(['page' => $this->getPage()]),
json_encode(['perPage' => data_get($this->setUp, 'footer.perPage')]),
json_encode(['search' => $this->search]),
json_encode(['sortDirection' => $this->sortDirection]),
json_encode(['sortField' => $this->sortField]),
Expand Down Expand Up @@ -177,7 +178,7 @@ private function getCachedData(): mixed
$prefix = strval(data_get($this->setUp, 'cache.prefix'));
$customTag = strval(data_get($this->setUp, 'cache.tag'));
$forever = boolval(data_get($this->setUp, 'cache.forever', false));
$ttl = boolval(data_get($this->setUp, 'cache.ttl', false));
$ttl = intval(data_get($this->setUp, 'cache.ttl'));

$tag = $prefix . ($customTag ?: 'powergrid-' . $this->datasource()->getModel()->getTable() . '-' . $this->tableName);
$cacheKey = join('-', $this->getCacheKeys());
Expand All @@ -186,7 +187,6 @@ private function getCachedData(): mixed
return $this->readyToLoad ? Cache::tags($tag)->rememberForever($cacheKey, fn () => $this->fillData()) : collect([]);
}

/** @phpstan-ignore-next-line */
return $this->readyToLoad ? Cache::tags($tag)->remember($cacheKey, $ttl, fn () => $this->fillData()) : collect([]);
}

Expand Down
24 changes: 17 additions & 7 deletions src/ProcessDataSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -246,19 +246,29 @@ protected function resolveCollection(array|BaseCollection|EloquentBuilder|QueryB

public function transform(BaseCollection $results): BaseCollection
{
return $results->map(function ($row) {
$addColumns = $this->component->addColumns();
$processedResults = collect();

$results->chunk(3)
->each(function (BaseCollection $collection) use (&$processedResults) {
$processedBatch = $this->processBatch($collection);
$processedResults = $processedResults->concat($processedBatch);
});

$columns = $addColumns->columns;
return $processedResults;
}

$columns = collect($columns);
private function processBatch(BaseCollection $collection): BaseCollection
{
return $collection->map(function ($row) {
$addColumns = $this->component->addColumns();
$columns = $addColumns->columns;
$columns = collect($columns);

/** @phpstan-ignore-next-line */
$data = $columns->mapWithKeys(fn ($column, $columnName) => (object) [$columnName => $column((object) $row)]);

$actions = [];

$prepareRules = collect();
$actions = collect();

if (method_exists($this->component, 'actionRules')) {
$prepareRules = resolve(RulesController::class)
Expand All @@ -267,7 +277,7 @@ public function transform(BaseCollection $results): BaseCollection

if (method_exists($this->component, 'actions')) {
$actions = (new ActionsController($this->component, $prepareRules))
->execute($this->component->actions($row), (object) $row);
->execute($this->component->actions($row), (object)$row);
}

$mergedData = $data->merge([
Expand Down
1 change: 0 additions & 1 deletion tests/DishesEnumTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ public function columns(): array

Column::make('Prato', 'name')
->searchable()
->editOnClick($canEdit)
->placeholder('Prato placeholder')
->sortable(),

Expand Down
5 changes: 1 addition & 4 deletions tests/DishesMakeTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ public function columns(): array

Column::make('Prato', 'name')
->searchable()
->editOnClick()
->placeholder('Prato placeholder')
->sortable(),

Expand All @@ -138,15 +137,13 @@ public function columns(): array

Column::make('Chef', 'chef_name')
->searchable()
->editOnClick()
->placeholder('Chef placeholder')
->sortable(),

Column::make('Category', 'category_name')
->placeholder('Category'),

Column::make('Preço', 'price_BRL')
->editOnClick(true, 'price'),
Column::make('Preço', 'price_BRL'),

Column::make('Preço de Venda', 'sales_price_BRL'),

Expand Down
5 changes: 1 addition & 4 deletions tests/DishesQueryBuilderTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ public function columns(): array
->title('Dish')
->field('name')
->searchable()
->editOnClick()
->placeholder('Prato placeholder')
->sortable(),

Expand All @@ -131,7 +130,6 @@ public function columns(): array
->title('Chef')
->field('chef_name')
->searchable()
->editOnClick()
->placeholder('Chef placeholder')
->sortable(),

Expand All @@ -142,8 +140,7 @@ public function columns(): array

Column::add()
->title('Price')
->field('price_BRL')
->editOnClick(true, 'price'),
->field('price_BRL'),

Column::add()
->title('Sales Price')
Expand Down
1 change: 0 additions & 1 deletion tests/DishesSearchableRawTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ public function columns(): array

Column::make('Prato', 'name')
->searchable()
->editOnClick()
->placeholder('Prato placeholder')
->sortable(),

Expand Down
Loading

0 comments on commit fdc48e9

Please sign in to comment.