Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
markhuot committed Oct 27, 2023
1 parent f08949d commit 2d05820
Show file tree
Hide file tree
Showing 13 changed files with 108 additions and 55 deletions.
18 changes: 6 additions & 12 deletions src/actions/AddComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,17 @@ public function handle(
string $type
): Component {
// Check if we can be added here
if ($path) {
$parentId = last(explode('/', $path));
if (! empty($parentId)) {
$parent = Component::find()->where([
'id' => $parentId,
'elementId' => $elementId,
'fieldId' => $fieldId,
])->one();
if (! $parent->getType()->getSlotDefinition($slot)->allows($type)) {
throw new \RuntimeException('Not allowed here');
}
}
$parent = (new GetParentFromPath)->handle($elementId, $fieldId, $path);
if ($parent && ! $parent->getType()->getSlotDefinition($slot)->allows($type)) {
throw new \RuntimeException('Not allowed here');
}

// Create the data
$componentData = new ComponentData;
$componentData->type = $type;

Check failure on line 26 in src/actions/AddComponent.php

View workflow job for this annotation

GitHub Actions / Run PHPStan

Access to an undefined property markhuot\keystone\models\ComponentData::$type.
$componentData->save();

// Create the component
$component = new Component;
$component->elementId = $elementId;
$component->fieldId = $fieldId;
Expand All @@ -44,6 +37,7 @@ public function handle(
$component->sortOrder = $sortOrder;

Check failure on line 37 in src/actions/AddComponent.php

View workflow job for this annotation

GitHub Actions / Run PHPStan

Access to an undefined property markhuot\keystone\models\Component::$sortOrder.
$component->save();

// Refresh the instance so we have the correct data reference
$component->refresh();

return $component;
Expand Down
19 changes: 19 additions & 0 deletions src/actions/GetParentFromPath.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace markhuot\keystone\actions;

use markhuot\keystone\models\Component;

class GetParentFromPath
{
public function handle(int $elementId, int $fieldId, ?string $path): ?Component
{
$parentId = last(explode('/', $path));

return $parentId ? Component::findOne([
'elementId' => $elementId,
'fieldId' => $fieldId,
'id' => $parentId,
]) : null;
}
}
15 changes: 15 additions & 0 deletions src/actions/MakeModelFromArray.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,21 @@
use markhuot\keystone\db\ActiveRecord;
use yii\base\ModelEvent;

/**
* Recursively create models from an array.
*
* ```php
* (new MakeModelFromArray)->handle(Component::class, ['id' => 123], errorOnMissing: true, createOnMissing: false)
* ```
*
* That would search for component 123 and error out if it could not be found.
*
* ```php
* (new MakeModelFromArray)->handle(PostData::class, ['foo' => 'bar'], errorOnMissing: false, createOnMissing: true)
* ```
*
* That would instantiate a new PostData class with the `foo` property set to `bar`.
*/
class MakeModelFromArray
{
/**
Expand Down
15 changes: 15 additions & 0 deletions src/actions/MapExpandedAttributeValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@

namespace markhuot\keystone\actions;

/**
* Takes an array of either CSS "shorthand" or "expanded" values and returns a css-ish
* representation of them.
*
* For example, given `->handle(['useExpanded' => false, 'shorthand' => 3], 'margin')` you
* would end up with `['margin' => 3]`.
*
* If you `useExpanded` like this, `->handle(['useExpanded' => true, 'expanded' => ['top' => 3]], 'margin')`
* then you would end up with `['margin-top' => 3]`.
*
* Notice that the `$property` attribute is automatically converted to `{$property}-top` or `{$property}-left`
* for the expanded values. If you need to customize that you can pass in an `$expandedProperty` attribute
* with `&` as a placeholder for the direction. E.g., `->handle([...], 'border', 'border-&-width')` would
* return `['border-top-width' => 3]` if `'top' => 3` was passed.
*/
class MapExpandedAttributeValue
{
public function handle(?array $value, string $property, string $expandedProperty = null)
Expand Down
13 changes: 7 additions & 6 deletions src/actions/MoveComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,19 @@

namespace markhuot\keystone\actions;

use markhuot\keystone\enums\MoveComponentPosition;
use markhuot\keystone\models\Component;
use yii\db\Expression;

class MoveComponent
{
public function handle(Component $source, Component $target, string $position, string $slotName = null)
public function handle(Component $source, Component $target, MoveComponentPosition $position, string $slotName = null)
{
if ($position === 'above' || $position === 'below') {
if ($position === MoveComponentPosition::BEFORE || $position === MoveComponentPosition::AFTER) {
$this->handleAboveOrBelow($source, $target, $position);
}

if ($position === 'beforeend') {
if ($position === MoveComponentPosition::BEFOREEND) {
$this->handleBeforeEnd($source, $target, $slotName);
}
}
Expand All @@ -39,7 +40,7 @@ public function handleAboveOrBelow(Component $source, Component $target, string
$target->refresh();

// make room for the insertion
if ($position === 'above') {
if ($position === MoveComponentPosition::BEFORE) {
Component::updateAll([
'sortOrder' => new Expression('sortOrder + 1'),
], ['and',
Expand All @@ -50,7 +51,7 @@ public function handleAboveOrBelow(Component $source, Component $target, string
['>=', 'sortOrder', $target->sortOrder],
]);
}
if ($position === 'below') {
if ($position === MoveComponentPosition::AFTER) {
Component::updateAll([
'sortOrder' => new Expression('sortOrder + 1'),
], ['and',
Expand All @@ -70,7 +71,7 @@ public function handleAboveOrBelow(Component $source, Component $target, string
// move the source to the target
$source->path = $target->path;
$source->slot = $target->slot;
$source->sortOrder = $position == 'above' ? $target->sortOrder - 1 : $target->sortOrder + 1;
$source->sortOrder = $position == MoveComponentPosition::BEFORE ? $target->sortOrder - 1 : $target->sortOrder + 1;
$source->save();

// move any children of the source
Expand Down
2 changes: 1 addition & 1 deletion src/actions/NormalizeFieldDataForComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function handle(mixed $value, string $handle)

// If the field is editable, return an editable div
if ($field?->getBehavior('inlineEdit')) {
if ($field->isEditableInPreview() && (Craft::$app->getRequest()->isPreview() ?? false)) {
if ($field->isEditableInLivePreview() && Craft::$app->getRequest()->getQueryParam('x-craft-live-preview') !== null) {
return new InlineEditData($this->component, $field, $value);
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/behaviors/InlineEditBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@

class InlineEditBehavior extends Behavior
{
protected bool $editableInPreview = false;
protected bool $editableInLivePreview = false;

public function setEditableInPreview(bool $editable=true)
public function setEditableInLivePreview(bool $editable=true)
{
$this->editableInPreview = $editable;
$this->editableInLivePreview = $editable;
}

public function isEditableInPreview()
public function isEditableInLivePreview()
{
return $this->editableInPreview;
return $this->editableInLivePreview;
}
}
4 changes: 2 additions & 2 deletions src/controllers/ComponentsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use markhuot\keystone\actions\DeleteComponent;
use markhuot\keystone\actions\EditComponentData;
use markhuot\keystone\actions\GetComponentType;
use markhuot\keystone\actions\GetParentFromPath;
use markhuot\keystone\actions\MoveComponent;
use markhuot\keystone\behaviors\BodyParamObjectBehavior;
use markhuot\keystone\models\Component;
Expand All @@ -29,8 +30,7 @@ public function actionAdd()
$path = $this->request->getQueryParam('path');
$slot = $this->request->getQueryParam('slot');
$sortOrder = $this->request->getRequiredQueryParam('sortOrder');
$parentId = last(explode('/', $path));
$parent = $parentId ? Component::findOne(['elementId' => $elementId, 'fieldId' => $fieldId, 'id' => $parentId]) : null;
$parent = (new GetParentFromPath)->handle($elementId, $fieldId, $path);

return $this->asCpScreen()
->title('Add component')
Expand Down
10 changes: 10 additions & 0 deletions src/enums/MoveComponentPosition.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace markhuot\keystone\enums;

enum MoveComponentPosition: string
{
case BEFOREEND = 'beforeEnd';
case BEFORE = 'before';
case AFTER = 'after';
}
3 changes: 2 additions & 1 deletion src/models/http/MoveComponentRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use craft\base\ElementInterface;
use craft\base\FieldInterface;
use craft\base\Model;
use markhuot\keystone\enums\MoveComponentPosition;
use markhuot\keystone\models\Component;

use function markhuot\keystone\helpers\base\app;
Expand All @@ -17,7 +18,7 @@ class MoveComponentRequest extends Model

public Component $target;

public string $position;
public MoveComponentPosition $position;

public ?string $slot = null;

Expand Down
2 changes: 1 addition & 1 deletion src/templates/components/text.twig
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{% export propTypes = {
text: field('plaintext').multiline(true).editableInPreview(true)
text: field('plaintext').multiline(true).editableInLivePreview(true)
} %}
{% export summary = props.text|default('')|slice(0,25) %}
{% export icon %}<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><path d="M206,56V88a6,6,0,0,1-12,0V62H134V194h26a6,6,0,0,1,0,12H96a6,6,0,0,1,0-12h26V62H62V88a6,6,0,0,1-12,0V56a6,6,0,0,1,6-6H200A6,6,0,0,1,206,56Z"></path></svg>{% endexport %}
Expand Down
32 changes: 14 additions & 18 deletions src/templates/inline-edit.twig
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
<div contenteditable data-id='{{ component.getQueryCondition()|json_encode }}'>
{{ value }}
</div>
<span contenteditable data-id='{{ component.getQueryCondition()|merge({handle: field.handle})|json_encode }}'>{{ value }}</span>

{% if craft.app.getRequest().isPreview() %}
{% js %}
document.addEventListener('input', event => {
const params = JSON.parse(event.target.dataset.id);
fetch("{{ actionUrl('keystone/components/update') }}", {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': '{{ craft.app.request.csrfToken }}',
},
body: JSON.stringify({...params, fields: { {{ field.handle }}: event.target.innerHTML}}),
});
{% js %}
document.addEventListener('input', event => {
const params = JSON.parse(event.target.dataset.id);
fetch("{{ actionUrl('keystone/components/update') }}", {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': '{{ craft.app.request.csrfToken }}',
},
body: JSON.stringify({...params, fields: { {{ field.handle }}: event.target.innerHTML}}),
});
{% endjs %}
{% endif %}
});
{% endjs %}
20 changes: 11 additions & 9 deletions tests/MoveComponentsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use markhuot\keystone\actions\MakeModelFromArray;
use markhuot\keystone\actions\MoveComponent;
use markhuot\keystone\enums\MoveComponentPosition;
use markhuot\keystone\models\Component;
use markhuot\keystone\models\http\MoveComponentRequest;

Expand All @@ -17,11 +18,12 @@

it('parses post data', function () {
[$source, $target] = Component::factory()->count(2)->create();
$data = new MoveComponentRequest();
$data->load([
$data = (new MakeModelFromArray())->handle(MoveComponentRequest::class, [
'source' => ['id' => $source->id, 'fieldId' => $source->fieldId, 'elementId' => $source->elementId],
'target' => ['id' => $target->id, 'fieldId' => $target->fieldId, 'elementId' => $target->elementId],
], '');
'position' => 'beforeend'
]);
\markhuot\craftpest\helpers\test\dd($data);

expect($data)
->errors->toBeEmpty()
Expand All @@ -39,7 +41,7 @@
expect($data->errors)
->target->not->toBeNull()
->position->not->toBeNull();
})->only();
});

it('moves components', function () {
$components = collect([
Expand All @@ -48,7 +50,7 @@
Component::factory()->create(['sortOrder' => 2]),
]);

(new MoveComponent())->handle($components[0], $components[2], 'below');
(new MoveComponent())->handle($components[0], $components[2], MoveComponentPosition::BEFORE);
$components->each->refresh();

expect($components[0])->sortOrder->toBe(2);
Expand All @@ -63,7 +65,7 @@
'targetChild' => $targetChild,
] = $this->components;

(new MoveComponent())->handle($sourceParent, $targetChild, 'below');
(new MoveComponent())->handle($sourceParent, $targetChild, MoveComponentPosition::AFTER);
$this->components->each->refresh();

expect($sourceParent)
Expand All @@ -83,7 +85,7 @@
'targetChild' => $targetChild,
] = $this->components;

(new MoveComponent())->handle($sourceGrandParent, $targetChild, 'below');
(new MoveComponent())->handle($sourceGrandParent, $targetChild, MoveComponentPosition::AFTER);
$this->components->each->refresh();

expect($sourceGrandParent)
Expand All @@ -106,7 +108,7 @@
$target = Component::factory()->create(['sortOrder' => 1]),
]);

(new MoveComponent())->handle($parent, $target, 'beforeend');
(new MoveComponent())->handle($parent, $target, MoveComponentPosition::BEFOREEND);
$components->each->refresh();

expect($parent)
Expand All @@ -126,7 +128,7 @@
'targetChild' => $targetChild,
] = $this->components;

(new MoveComponent())->handle($sourceGrandParent, $targetParent, 'beforeend');
(new MoveComponent())->handle($sourceGrandParent, $targetParent, MoveComponentPosition::BEFOREEND);
$this->components->each->refresh();

expect($targetParent)->path->toBe(null)->sortOrder->toBe(0);
Expand Down

0 comments on commit 2d05820

Please sign in to comment.