-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathVizyField.php
1267 lines (1005 loc) · 47.3 KB
/
VizyField.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace verbb\vizy\fields;
use verbb\vizy\Vizy;
use verbb\vizy\base\PluginInterface;
use verbb\vizy\elements\Block as BlockElement;
use verbb\vizy\events\ModifyVizyConfigEvent;
use verbb\vizy\events\RegisterLinkOptionsEvent;
use verbb\vizy\events\RegisterPluginEvent;
use verbb\vizy\gql\types\NodeCollectionType;
use verbb\vizy\helpers\Plugin;
use verbb\vizy\models\BlockType;
use verbb\vizy\models\NodeCollection;
use verbb\vizy\nodes\VizyBlock;
use verbb\vizy\web\assets\field\VizyAsset;
use Craft;
use craft\base\Element;
use craft\base\ElementInterface;
use craft\base\Field;
use craft\elements\Asset;
use craft\elements\Category;
use craft\elements\Entry;
use craft\elements\MatrixBlock;
use craft\fieldlayoutelements\CustomField;
use craft\helpers\ArrayHelper;
use craft\helpers\FileHelper;
use craft\helpers\Html;
use craft\helpers\Json;
use craft\helpers\StringHelper;
use craft\fields\BaseRelationField;
use craft\fields\conditions\EmptyFieldConditionRule;
use craft\fields\Matrix;
use craft\models\FieldLayout;
use craft\models\Section;
use craft\validators\ArrayValidator;
use craft\web\twig\variables\Cp;
use yii\base\Event;
use yii\base\InvalidConfigException;
use yii\db\Schema;
use Throwable;
use GraphQL\Type\Definition\Type;
use verbb\supertable\elements\SuperTableBlockElement;
use verbb\supertable\fields\SuperTableField as SuperTable;
use benf\neo\elements\Block as NeoBlock;
class VizyField extends Field
{
// Constants
// =========================================================================
public const EVENT_DEFINE_VIZY_CONFIG = 'defineVizyConfig';
public const EVENT_MODIFY_PURIFIER_CONFIG = 'modifyPurifierConfig';
public const EVENT_REGISTER_LINK_OPTIONS = 'registerLinkOptions';
public const EVENT_REGISTER_PLUGINS = 'registerPlugins';
public const PICKER_BEHAVIOUR_CLICK = 'click';
public const PICKER_BEHAVIOUR_HOVER = 'hover';
public const MODE_COMBINED = 'combined';
public const MODE_BLOCKS = 'blocks';
public const MODE_RICH_TEXT = 'richText';
// Static Methods
// =========================================================================
public static function displayName(): string
{
return Craft::t('vizy', 'Vizy');
}
public static function valueType(): string
{
return 'string|null';
}
public static function registerPlugin(string $pluginKey): void
{
if (isset(self::$_registeredPlugins[$pluginKey])) {
return;
}
$event = new RegisterPluginEvent([
'plugins' => [],
]);
Event::trigger(self::class, self::EVENT_REGISTER_PLUGINS, $event);
foreach ($event->plugins as $plugin) {
if (($plugin instanceof PluginInterface) && $pluginKey === $plugin->handle) {
Craft::$app->getView()->registerAssetBundle($plugin->assetBundle);
self::$_registeredPlugins[$pluginKey] = true;
}
}
}
// Properties
// =========================================================================
public array $fieldData = [];
public string $vizyConfig = '';
public string $configSelectionMode = 'choose';
public string $manualConfig = '';
public string|array|null $availableVolumes = '*';
public string|array|null $availableTransforms = '*';
public bool $showUnpermittedVolumes = false;
public bool $showUnpermittedFiles = false;
public string $defaultTransform = '';
public ?string $defaultUploadLocationSource = null;
public bool $trimEmptyParagraphs = true;
public bool $pasteAsPlainText = false;
public int $initialRows = 7;
public ?int $minBlocks = null;
public ?int $maxBlocks = null;
public string $blockTypeBehaviour = self::PICKER_BEHAVIOUR_CLICK;
public string $editorMode = self::MODE_COMBINED;
public string $columnType = Schema::TYPE_TEXT;
private static array $_registeredPlugins = [];
private ?array $_blockTypesById = [];
private ?array $_linkOptions = null;
private ?array $_sectionSources = null;
private ?array $_categorySources = null;
private ?array $_volumeKeys = null;
private ?array $_transforms = null;
private ?int $_recursiveFieldCount = null;
// Public Methods
// =========================================================================
public function __construct($config = [])
{
// Temporarily fix a config issue during beta
if (array_key_exists('vizyConfig', $config)) {
if (is_array($config['vizyConfig'])) {
$config['vizyConfig'] = $config['vizyConfig'][0];
Craft::$app->getDeprecator()->log("vizy:${config['handle']}", "Your Vizy field ${config['handle']} contains out of date settings. Please re-save the field.");
}
}
parent::__construct($config);
}
protected function defineRules(): array
{
$rules = parent::defineRules();
$rules[] = [['initialRows', 'minBlocks', 'maxBlocks'], 'integer', 'min' => 0];
return $rules;
}
public function getContentColumnType(): array|string
{
return $this->columnType;
}
public function isValueEmpty(mixed $value, ElementInterface $element): bool
{
$isValueEmpty = parent::isValueEmpty($value, $element);
// Check for an empty paragraph
if ($value instanceof NodeCollection) {
$isValueEmpty = $isValueEmpty || $value->isEmpty();
}
return $isValueEmpty;
}
public function getSettingsHtml(): ?string
{
$view = Craft::$app->getView();
$fieldData = $this->_getBlockGroupsForSettings();
$settings = [
'fieldId' => $this->id,
'suggestions' => (new Cp())->getTemplateSuggestions(),
];
$inputNamePrefix = $view->getNamespace();
$inputIdPrefix = Html::id($inputNamePrefix);
Plugin::registerAsset('field/src/js/vizy.js');
// Create the Vizy Settings Vue component
$js = 'new Craft.Vizy.Settings(' .
Json::encode($inputNamePrefix, JSON_UNESCAPED_UNICODE) . ', ' .
Json::encode($fieldData, JSON_UNESCAPED_UNICODE) . ', ' .
Json::encode($settings, JSON_UNESCAPED_UNICODE) .
');';
// Wait for Vizy JS to be loaded, either through an event listener, or by a flag.
// This covers if this script is run before, or after the Vizy JS has loaded
$view->registerJs('document.addEventListener("vizy-loaded", function(e) {' . $js . '}); if (Craft.VizyReady) {' . $js . '}');
$volumeOptions = [];
foreach (Craft::$app->getVolumes()->getAllVolumes() as $volume) {
if ($volume->getFs()->hasUrls) {
$volumeOptions[] = [
'label' => Html::encode($volume->name),
'value' => $volume->uid,
];
}
}
$transformOptions = [];
foreach (Craft::$app->getImageTransforms()->getAllTransforms() as $transform) {
$transformOptions[] = [
'label' => Html::encode($transform->name),
'value' => $transform->uid,
];
}
return $view->renderTemplate('vizy/field/settings', [
'field' => $this,
'inputNamePrefix' => $inputNamePrefix,
'inputIdPrefix' => $inputIdPrefix,
'componentData' => [
'id' => $inputIdPrefix,
'fieldData' => $fieldData,
'settings' => $settings,
],
'vizyConfigOptions' => $this->_getCustomConfigOptions('vizy'),
'volumeOptions' => $volumeOptions,
'sourceOptions' => $this->_getSourceOptions(),
'transformOptions' => $transformOptions,
'defaultTransformOptions' => [
...[
[
'label' => Craft::t('vizy', 'No transform'),
'value' => null,
],
], ...$transformOptions,
],
]);
}
public function getInputHtml(mixed $value, ?ElementInterface $element = null): string
{
$view = Craft::$app->getView();
$id = Html::id($this->handle);
$site = ($element ? $element->getSite() : Craft::$app->getSites()->getCurrentSite());
// Cache the placeholder key for the fields' JS. Because we're caching the block type HTML/JS
// we also need to cache the placeholder key to match that cached data.
$placeholderKey = Vizy::$plugin->getCache()->getOrSet($this->getCacheKey('placeholderKey'), function() {
return StringHelper::randomString(10);
});
// Because we can recursively nest Vizy fields, this can turn into an infinite loop if we're not careful. We limit to 10
// nested instances, so ensure we keep a count of how many identical fields we're implementing.
$this->_recursiveFieldCount = Vizy::$plugin->getCache()->get($this->getCacheKey('recursiveFieldCount'));
$this->_recursiveFieldCount += 1;
Vizy::$plugin->getCache()->set($this->getCacheKey('recursiveFieldCount'), $this->_recursiveFieldCount);
$settings = [
// The order of `blocks` and `blockGroups` is important here, to ensure that the blocks
// are rendered with content, where `blockGroups` is just the template for new blocks.
'blocks' => $this->_getBlocksForInput($value, $placeholderKey, $element),
'blockGroups' => $this->_getBlockGroupsForInput($placeholderKey, $element),
'vizyConfig' => $this->_getVizyConfig(),
'elementSiteId' => $site->id,
'showAllUploaders' => $this->showUnpermittedFiles,
'placeholderKey' => $placeholderKey,
'fieldHandle' => $this->handle,
'isRoot' => true,
'initialRows' => $this->initialRows,
'minBlocks' => $this->minBlocks,
'maxBlocks' => $this->maxBlocks,
'pasteAsPlainText' => $this->pasteAsPlainText,
'blockTypeBehaviour' => $this->blockTypeBehaviour,
'editorMode' => $this->editorMode,
];
// Set Asset setting
if (!empty($this->defaultTransform) && $transform = Craft::$app->getImageTransforms()->getTransformByUid($this->defaultTransform)) {
$settings['defaultTransform'] = $transform->handle;
}
$settings['defaultSource'] = $this->defaultUploadLocationSource;
foreach ($this->getBlockTypes() as $blockType) {
if ($blockType->minBlocks) {
$settings['minBlockTypeBlocks'][$blockType->id] = $blockType->minBlocks;
}
if ($blockType->maxBlocks) {
$settings['maxBlockTypeBlocks'][$blockType->id] = $blockType->maxBlocks;
}
}
// Only include some options if we need them - for performance
$buttons = $settings['vizyConfig']['buttons'] ?? [];
if (in_array('link', $buttons) || in_array('image', $buttons)) {
$settings['linkOptions'] = $this->_getLinkOptions($element);
$settings['volumes'] = $this->_getVolumeKeys();
$settings['transforms'] = $this->_getTransforms();
}
// Register the Vizy JS for Vite
Plugin::registerAsset('field/src/js/vizy.js');
// JS logic will handle whether to run this on nested fields or not. For the most part, Vue will
// automatically render any nested fields when run from the root component.
$js = 'new Craft.Vizy.Input(' .
'"' . $view->namespaceInputId($id) . '", ' .
'"' . $view->namespaceInputName($this->handle) . '"' .
');';
// Wait for Vizy JS to be loaded, either through an event listener, or by a flag.
// This covers if this script is run before, or after the Vizy JS has loaded
$view->registerJs('document.addEventListener("vizy-loaded", function(e) {' . $js . '}); if (Craft.VizyReady) {' . $js . '}');
// Let the field know if this is the root field for nested fields
$settings['isRoot'] = $this->_isRootField($element);
// Register any third-party plugins
if (isset($settings['vizyConfig']['plugins'])) {
foreach ($settings['vizyConfig']['plugins'] as $pluginKey) {
static::registerPlugin($pluginKey);
}
}
$rawNodes = $value->getRawNodes();
return $view->renderTemplate('vizy/field/input', [
'id' => $id,
'name' => $this->handle,
'field' => $this,
'value' => Json::encode($rawNodes, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT),
'settings' => Json::encode($settings, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT),
]);
}
public function normalizeValue(mixed $value, ?ElementInterface $element = null): NodeCollection
{
if ($value instanceof NodeCollection) {
return $value;
}
// To avoid collisions with other POST items, we store all serialized Vizy content in `vizyData`
// which is all we care about. Due to how Craft works, we'll get lots of other field content coming
// through which we can discard. For example:
//
// fields[richContent][blocks][vizy-block-X2y6Pysezv][fields][image][]: 6
// fields[richContent][blocks][vizy-block-X2y6Pysezv][fields][text]: Some Text
// fields[richContent]: [{"type":"vizyBlock","attrs": ...}]
//
// We're after just the last item, but its order cannot be guaranteed. It's safer to store that as `fields[richContent][vizyData]`.
if (is_array($value) && isset($value['vizyData'])) {
$value = $value['vizyData'];
}
if (is_string($value) && !empty($value)) {
$value = Json::decodeIfJson($value);
}
if (!is_array($value)) {
$value = [];
}
// Convert serialized data to a collection of nodes.
return new NodeCollection($this, $value, $element);
}
public function serializeValue(mixed $value, ?ElementInterface $element = null): mixed
{
if ($value instanceof NodeCollection) {
return $value->serializeValues($element);
}
return $value;
}
/**
* @inheritdoc
*/
public function getElementConditionRuleType(): array|string|null
{
return EmptyFieldConditionRule::class;
}
public function getStaticHtml(mixed $value, ElementInterface $element): string
{
$view = Craft::$app->getView();
$view->registerAssetBundle(VizyAsset::class);
return Html::tag('div', $value->renderStaticHtml() ?: ' ', [
'class' => 'text vizy-static',
]);
}
public function beforeSave(bool $isNew): bool
{
if (!parent::beforeSave($isNew)) {
return false;
}
$errors = [];
// Prepare the setting data to be saved
$this->fieldData = Json::decodeIfJson($this->fieldData) ?? [];
foreach ($this->fieldData as $groupKey => $group) {
$blockTypes = $group['blockTypes'] ?? [];
foreach ($blockTypes as $blockTypeKey => $blockType) {
// Ensure we catch errors to prevent data loss
try {
// Remove this before populating the model
$layoutConfig = Json::decode(ArrayHelper::remove($blockType, 'layout'));
// Create a model so we can properly validate
$blockType = new BlockType($blockType);
if (!$blockType->validate()) {
foreach ($blockType->getErrors() as $key => $error) {
$errors[$blockType->id . ':' . $key] = $error;
}
continue;
}
// Check if there's any changes to be made
if ($layoutConfig && $fieldLayout = FieldLayout::createFromConfig($layoutConfig)) {
$fieldLayout->type = BlockType::class;
// Set the layout here, saving takes place in PC event handlers, straight after this
$blockType->setFieldLayout($fieldLayout);
}
// Override with our cleaned model data
$this->fieldData[$groupKey]['blockTypes'][$blockTypeKey] = $blockType->serializeArray();
} catch (Throwable $e) {
$this->addErrors([$blockType['id'] . ':general' => $e->getMessage()]);
return false;
}
}
}
if ($errors) {
$this->addErrors($errors);
return false;
}
// Prevent any empty groups.
foreach ($this->fieldData as $groupKey => $group) {
$blocks = $group['blockTypes'] ?? [];
if (!$blocks) {
unset($this->fieldData[$groupKey]);
}
}
// Be sure to reset the array keys, in case empty blocks have been deleted.
// Can cause PC issues with `unpackAssociativeArray`.
$this->fieldData = array_values($this->fieldData);
// Any fields not in the global scope won't trigger a PC change event. Go manual.
if ($this->context !== 'global') {
Vizy::$plugin->getService()->saveField($this->fieldData);
}
return true;
}
public function beforeElementSave(ElementInterface $element, bool $isNew): bool
{
// If we're propagating the element (entry), we need to perform some additional checks in a specific scenario
// If the Vizy field is set to un-translatable but the inner fields are, Craft's `_propagateElement()` will copy
// values across all elements, which we don't want. As such, check each field and remove the duplicated content,
// restoring the content that was there. This is tricky that Vizy fields don't use elements for their content
// unlike Matrix, so we need to do a deep-dive into the content to re-jig it.
//
// We can also skip over this entirely if the Vizy field is translatable - that works as expected.
if ($element->propagating && $this->translationMethod === Field::TRANSLATION_METHOD_NONE) {
$translatableFields = [];
// Before going any further, are there any inner fields in _any_ block type for this field
// that are translatable? No need to go further if there aren't, and saves a lot of time.
foreach ($this->getBlockTypes() as $blockType) {
if (($fieldLayout = $blockType->getFieldLayout()) !== null) {
foreach ($fieldLayout->getCustomFields() as $field) {
if ($field->translationMethod !== Field::TRANSLATION_METHOD_NONE) {
$translatableFields[$blockType->id][] = $field->handle;
}
}
}
}
if ($translatableFields) {
// Fetch the current element, so we can get it's content before saving.
$siteElement = Craft::$app->getElements()->getElementById($element->id, $element::class, $element->siteId);
if ($siteElement) {
$hasUpdatedContent = false;
$newNodes = $element->getFieldValue($this->handle)->getRawNodes();
// Extract the raw content for _just_ the translatable fields
foreach ($siteElement->getFieldValue($this->handle)->getRawNodes() as $rawNode) {
if ($rawNode['type'] === 'vizyBlock') {
$blockId = $rawNode['attrs']['id'] ?? '';
$blockTypeId = $rawNode['attrs']['values']['type'] ?? '';
$fields = $translatableFields[$blockTypeId] ?? [];
foreach ($fields as $fieldHandle) {
// For some fields, they control their own propagation settings.
// Check those, and only proceed with swapping content if not managing per-site.
$field = Craft::$app->getFields()->getFieldByHandle($fieldHandle);
// "Only save blocks to the site they were created in" (none) is selected
if ($field instanceof Matrix && $field->propagationMethod !== Matrix::PROPAGATION_METHOD_NONE) {
continue;
}
// "Only save blocks to the site they were created in" (none) is selected
if (Craft::$app->getPlugins()->isPluginEnabled('super-table')) {
if ($field instanceof SuperTable && $field->propagationMethod !== SuperTable::PROPAGATION_METHOD_NONE) {
continue;
}
}
// "Manage relations on a per-site basis" is disabled
if ($field instanceof BaseRelationField && !$field->localizeRelations) {
continue;
}
// Ensure we find the right block to update
foreach ($newNodes as $key => $newNode) {
$newBlockId = $newNode['attrs']['id'] ?? '';
if ($newBlockId === $blockId) {
$hasUpdatedContent = true;
$newNodes[$key]['attrs']['values']['content']['fields'][$fieldHandle] = $rawNode['attrs']['values']['content']['fields'][$fieldHandle] ?? '';
}
}
}
}
}
if ($hasUpdatedContent) {
// Rebuild the node collection - if it's changed
$nodeCollection = new NodeCollection($this, $newNodes, $element);
$element->setFieldValue($this->handle, $nodeCollection);
}
}
}
}
return parent::beforeElementSave($element, $isNew);
}
public function getBlockTypeById($blockTypeId)
{
if (isset($this->_blockTypesById[$blockTypeId])) {
return $this->_blockTypesById[$blockTypeId];
}
foreach ($this->fieldData as $group) {
foreach ($group['blockTypes'] as $block) {
if ($block['id'] === $blockTypeId) {
return $this->_blockTypesById[$blockTypeId] = new BlockType($block);
}
}
}
return null;
}
public function getBlockTypes(): array
{
$blockTypes = [];
foreach ($this->fieldData as $group) {
$blocks = $group['blockTypes'] ?? [];
foreach ($blocks as $blockTypeData) {
// Remove this before populating the model
ArrayHelper::remove($blockTypeData, 'layout');
$blockType = new BlockType($blockTypeData);
$blockType->fieldId = $this->id;
$blockTypes[] = $blockType;
}
}
return $blockTypes;
}
public function getContentGqlType(): Type|array
{
return NodeCollectionType::getType($this);
}
public function getElementValidationRules(): array
{
return [
[
'validateBlocks',
'on' => [Element::SCENARIO_ESSENTIALS, Element::SCENARIO_DEFAULT, Element::SCENARIO_LIVE],
'skipOnEmpty' => false,
],
];
}
public function validateBlocks(ElementInterface $element): void
{
$scenario = $element->getScenario();
if ($scenario !== Element::SCENARIO_LIVE) {
return;
}
$value = $element->getFieldValue($this->handle);
$blocks = $value->query()->where(['type' => 'vizyBlock'])->all();
foreach ($blocks as $i => $block) {
$blockElement = $block->getBlockElement($element);
$blockElement->setScenario($scenario);
if (!$blockElement->validate()) {
$element->addModelErrors($blockElement, "{$this->handle}[{$i}]");
}
}
if ($this->minBlocks || $this->maxBlocks) {
$arrayValidator = new ArrayValidator([
'min' => $this->minBlocks ?: null,
'max' => $this->maxBlocks ?: null,
'tooFew' => $this->minBlocks ? Craft::t('app', '{attribute} should contain at least {min, number} {min, plural, one{block} other{blocks}}.', [
'attribute' => Craft::t('site', $this->name),
'min' => $this->minBlocks, // Need to pass this in now
]) : null,
'tooMany' => $this->maxBlocks ? Craft::t('app', '{attribute} should contain at most {max, number} {max, plural, one{block} other{blocks}}.', [
'attribute' => Craft::t('site', $this->name),
'max' => $this->maxBlocks, // Need to pass this in now
]) : null,
'skipOnEmpty' => false,
]);
if (!$arrayValidator->validate($blocks, $error)) {
$element->addError($this->handle, $error);
}
}
// Validate block types
$blockTypesCount = [];
$blockTypesById = [];
foreach ($this->getBlockTypes() as $blockType) {
$blockTypesCount[$blockType->id] = 0;
$blockTypesById[$blockType->id] = $blockType;
}
foreach ($blocks as $block) {
if ($block->enabled) {
$blockTypesCount[$block->blockType->id] += 1;
}
}
foreach ($blockTypesCount as $blockTypeId => $blockTypeCount) {
$blockType = $blockTypesById[$blockTypeId];
if ($blockType->minBlocks > 0 && $blockTypeCount < $blockType->minBlocks) {
$element->addError($this->handle, Craft::t('vizy', '{attribute} should contain at least {minBlockTypeBlocks, number} {minBlockTypeBlocks, plural, one{block} other{blocks}} of type {blockType}.', [
'attribute' => Craft::t('site', $this->name),
'minBlockTypeBlocks' => $blockType->minBlocks,
'blockType' => $blockType->name,
])
);
}
if ($blockType->maxBlocks > 0 && $blockTypeCount > $blockType->maxBlocks) {
$element->addError($this->handle, Craft::t('vizy', '{attribute} should contain at most {maxBlockTypeBlocks, number} {maxBlockTypeBlocks, plural, one{block} other{blocks}} of type {blockType}.', [
'attribute' => Craft::t('site', $this->name),
'maxBlockTypeBlocks' => $blockType->maxBlocks,
'blockType' => $blockType->name,
])
);
}
}
}
protected function searchKeywords(mixed $value, ElementInterface $element): string
{
$keywords = parent::searchKeywords($value, $element);
if ($value instanceof NodeCollection) {
$nodes = $value->getRawNodes();
// Any actual editor text
$keywords = $this->_getNestedValues($nodes, 'text');
// Fields are different, and we need to check on their searchability
foreach ($value->getNodes() as $block) {
if ($block instanceof VizyBlock) {
if ($fieldLayout = $block->getFieldLayout()) {
foreach ($fieldLayout->getCustomFields() as $field) {
if (!$field->searchable) {
continue;
}
$fieldData = $block->getFieldValue($field->handle);
$keywords[] = $field->searchKeywords($fieldData, $element);
}
}
}
}
}
if (is_array($keywords)) {
$keywords = trim(implode(' ', array_unique($keywords)));
}
return $keywords;
}
// Private Methods
// =========================================================================
private function getCacheKey($key): string
{
return $this->id . '-' . $this->handle . '-' . $key;
}
private function _isRootField(?ElementInterface $element = null): bool
{
if ($element instanceof BlockElement) {
return false;
}
if ($element instanceof MatrixBlock) {
return $this->_isRootField($element->getOwner());
}
if (Plugin::isPluginInstalledAndEnabled('super-table')) {
if ($element instanceof SuperTableBlockElement) {
return $this->_isRootField($element->getOwner());
}
}
if (Plugin::isPluginInstalledAndEnabled('neo')) {
if ($element instanceof NeoBlock) {
return $this->_isRootField($element->getOwner());
}
}
return true;
}
private function _getNestedValues($value, $key, &$items = []): array
{
foreach ($value as $k => $v) {
if ((string)$k === $key) {
$items[] = $v;
}
if (is_array($v)) {
$this->_getNestedValues($v, $key, $items);
}
}
return $items;
}
private function _getBlockGroupsForSettings(): array
{
$data = $this->fieldData;
foreach ($data as $groupKey => $group) {
$blocks = $group['blockTypes'] ?? [];
foreach ($blocks as $blockTypeKey => $blockTypeData) {
// Remove this before populating the model
$layout = ArrayHelper::remove($blockTypeData, 'layout');
$blockType = new BlockType($blockTypeData);
$blockTypeArray = $blockType->toArray();
// Watch for Vue's reactivity with arrays/objects. Easier to just implement here.
// Never actually stored in the DB, but needed for field layout designer
$blockTypeArray['layout'] = $layout;
// Override with prepped data for Vue
$data[$groupKey]['blockTypes'][$blockTypeKey] = $blockTypeArray;
}
}
return $data;
}
private function _getBlockGroupsForInput($placeholderKey, ElementInterface $element = null): array
{
/** @var Settings $settings */
$settings = Vizy::$plugin->getSettings();
// Get from the cache, if we've already prepped this field's block groups.
// The blocks HTML/JS is unique to this fields' ID and handle. Even if used multiple
// times in an element, or nested, we only need to generate this once.
return Vizy::$plugin->getCache()->getOrSet($this->getCacheKey('blockGroups'), function() use ($placeholderKey, $element, $settings) {
$view = Craft::$app->getView();
$data = $this->fieldData;
// As we can nested the same field recursively, we'll hit infinite loop errors at some point, so stop loading blocks at 10 levels.
if ($this->_recursiveFieldCount > $settings->recursiveFieldCount) {
return [];
}
foreach ($data as $groupKey => $group) {
$blocks = $group['blockTypes'] ?? [];
foreach ($blocks as $blockTypeKey => $blockTypeData) {
// Skip any disabled blocktypes
$enabled = $blockTypeData['enabled'] ?? true;
if (!$enabled) {
continue;
}
$blockType = new BlockType($blockTypeData);
$fieldLayout = $blockType->getFieldLayout();
if (!$fieldLayout) {
// Discard the blocktype
unset($data[$groupKey]['blockTypes'][$blockTypeKey]);
continue;
}
$blockTypeArray = $blockType->toArray();
$view->startJsBuffer();
// Create a fake element with the same fieldtype as our block
$blockElement = new BlockElement();
$blockElement->setFieldLayout($fieldLayout);
$blockElement->setOwner($element);
$blockElement->setType($blockType);
$blockElement->setField($this);
$originalNamespace = $view->getNamespace();
// Ensure that all fields in the block are marked as fresh for new blocks
if ($fieldLayout = $blockElement->getFieldLayout()) {
foreach ($fieldLayout->getCustomFields() as $field) {
$field->setIsFresh(true);
}
}
// Because Vizy Vue components serialize the input into JSON (including nested fields), we
// actually don't want the rendered block fields to use the same `fields` namespace as other
// fields do. It's not required for the field, and only used to serialize into JSON.
// We don't have control over the output of fields to remove `name` attributes, so changing
// the namespace is the way to go. This also prevents Craft's JS detecting field changes.
$newNamespace = ($originalNamespace === 'fields') ? 'vizyBlockFields' : $originalNamespace;
$namespace = $view->namespaceInputName($this->handle . "[blocks][__VIZY_BLOCK_{$placeholderKey}__]", $newNamespace);
$view->setNamespace($namespace);
$form = $fieldLayout->createForm($blockElement);
$blockTypeArray['tabs'] = $form->getTabMenu();
$fieldsHtml = $view->namespaceInputs($form->render());
$fieldsHtml = $this->_parseFieldHtml($fieldsHtml);
$blockTypeArray['fieldsHtml'] = $fieldsHtml;
$footHtml = $view->clearJsBuffer(false);
$view->setNamespace($originalNamespace);
if ($footHtml) {
$footHtml = '<script id="script-__VIZY_BLOCK_' . $placeholderKey . '__">' . $footHtml . '</script>';
}
// Reset $_isFresh's
if ($fieldLayout = $blockElement->getFieldLayout()) {
foreach ($fieldLayout->getCustomFields() as $field) {
$field->setIsFresh(null);
}
}
$blockTypeArray['footHtml'] = $footHtml;
$data[$groupKey]['blockTypes'][$blockTypeKey] = $blockTypeArray;
}
// Ensure we reset array indexes to play nicely with JS
$data[$groupKey]['blockTypes'] = array_values($data[$groupKey]['blockTypes']);
}
return $data;
});
}
private function _getBlocksForInput($value, $placeholderKey, ElementInterface $element = null): array
{
$view = Craft::$app->getView();
$blocks = [];
if ($value instanceof NodeCollection) {
foreach ($value->getNodes() as $block) {
if ($block instanceof VizyBlock) {
$tabErrors = [];
$blockId = $block->attrs['id'];
$fieldLayout = $block->getFieldLayout();
if (!$fieldLayout) {
continue;
}
$view->startJsBuffer();
// Create a fake element with the same fieldtype as our block
$blockElement = $block->getBlockElement($element);
$blockElement->setType($block->getBlockType());
$blockElement->setField($this);
$blockElement->setIsFresh(false);
// Bit of a hack here to trick `Element::getIsFresh()` that this _isn't_ a fresh block. Using `setIsFresh()` won't work.
$blockElement->contentId = 99999;
$originalNamespace = $view->getNamespace();
if ($fieldLayout = $blockElement->getFieldLayout()) {
foreach ($fieldLayout->getTabs() as $tab) {
foreach ($tab->getElements() as $layoutElement) {
if ($layoutElement instanceof CustomField) {
$layoutElement->getField()->setIsFresh(false);
// Record any tabs with field errors so we can reflect it via the UI
if (isset($blockElement->getErrors()[$layoutElement->getField()->handle])) {
$tabErrors[] = 'tab-' . $tab->getHtmlId();
}
}
}
}
}
// Because Vizy Vue components serialize the input into JSON (including nested fields), we
// actually don't want the rendered block fields to use the same `fields` namespace as other
// fields do. It's not required for the field, and only used to serialize into JSON.
// We don't have control over the output of fields to remove `name` attributes, so changing
// the namespace is the way to go. This also prevents Craft's JS detecting field changes.
$newNamespace = ($originalNamespace === 'fields') ? 'vizyBlockFields' : $originalNamespace;
$namespace = $view->namespaceInputName($this->handle . "[blocks][__VIZY_BLOCK_{$placeholderKey}__]", $newNamespace);
$view->setNamespace($namespace);
$fieldsHtml = $view->namespaceInputs($fieldLayout->createForm($blockElement)->render());
$fieldsHtml = $this->_parseFieldHtml($fieldsHtml);
$footHtml = $view->clearJsBuffer(false);
// Just in case some JS slips through (see dismissable UI element tips)
preg_match_all('#<script>(.*?)<\/script>#is', $fieldsHtml, $extraJs);
if (isset($extraJs[1])) {
$footHtml = $footHtml . implode('', $extraJs[1]);
}
$fieldsHtml = preg_replace('#<script>(.*?)<\/script>#is', '', $fieldsHtml);
$view->setNamespace($originalNamespace);
if ($footHtml) {
$footHtml = '<script id="script-__VIZY_BLOCK_' . $placeholderKey . '__">' . $footHtml . '</script>';
}
$blocks[] = [
'id' => $blockId,
'fieldsHtml' => $fieldsHtml,
'footHtml' => $footHtml,
'tabErrors' => $tabErrors,
];
}
}
}