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
4 changes: 4 additions & 0 deletions src/Autocomplete/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@

## 2.8.0


- The autocomplete will now update if any of the `option` elements inside of
it change, including the empty / placeholder element. Additionally, if the
`select` or `input` element's `disabled` attribute changes, the autocomplete
instance will update accordingly. This makes Autocomplete work perfectly inside
of a LiveComponent.

- Added support for using [OptionGroups](https://tom-select.js.org/examples/optgroups/).


## 2.7.0

- Add `assets/src` to `.gitattributes` to exclude them from the installation
Expand Down
5 changes: 3 additions & 2 deletions src/Autocomplete/assets/dist/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,13 +266,14 @@ _default_1_instances = new WeakSet(), _default_1_getCommonConfig = function _def
.then((response) => response.json())
.then((json) => {
this.setNextUrl(query, json.next_page);
callback(json.results);
callback(json.results.options || json.results, json.results.optgroups || []);
})
.catch(() => callback());
.catch(() => callback([], []));
},
shouldLoad: function (query) {
return query.length >= minCharacterLength;
},
optgroupField: 'group_by',
score: function (search) {
return function (item) {
return 1;
Expand Down
9 changes: 5 additions & 4 deletions src/Autocomplete/assets/src/controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Controller } from '@hotwired/stimulus';
import TomSelect from 'tom-select';
import { TPluginHash } from 'tom-select/dist/types/contrib/microplugin';
import { RecursivePartial, TomSettings, TomTemplates } from 'tom-select/dist/types/types';
import { RecursivePartial, TomSettings, TomTemplates, TomLoadCallback } from 'tom-select/dist/types/types';

export interface AutocompletePreConnectOptions {
options: any;
Expand Down Expand Up @@ -147,20 +147,21 @@ export default class extends Controller {
// VERY IMPORTANT: use 'function (query, callback) { ... }' instead of the
// '(query, callback) => { ... }' syntax because, otherwise,
// the 'this.XXX' calls inside this method fail
load: function (query: string, callback: (results?: any) => void) {
load: function (query: string, callback: TomLoadCallback) {
const url = this.getUrl(query);
fetch(url)
.then((response) => response.json())
// important: next_url must be set before invoking callback()
.then((json) => {
this.setNextUrl(query, json.next_page);
callback(json.results);
callback(json.results.options || json.results, json.results.optgroups || []);
})
.catch(() => callback());
.catch(() => callback([], []));
},
shouldLoad: function (query: string) {
return query.length >= minCharacterLength;
},
optgroupField: 'group_by',
// avoid extra filtering after results are returned
score: function (search: string) {
return function (item: any) {
Expand Down
104 changes: 101 additions & 3 deletions src/Autocomplete/assets/test/controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ describe('AutocompleteController', () => {
value: 3,
text: 'salad'
},
],
]
}),
);

Expand All @@ -111,8 +111,8 @@ describe('AutocompleteController', () => {
{
value: 2,
text: 'popcorn'
},
],
}
]
}),
);

Expand Down Expand Up @@ -499,4 +499,102 @@ describe('AutocompleteController', () => {
await shortDelay(10);
expect(tomSelect.control_input.placeholder).toBe('Select a kangaroo');
});

it('group related options', async () => {
const { container, tomSelect } = await startAutocompleteTest(`
<label for="the-select">Items</label>
<select
id="the-select"
data-testid="main-element"
data-controller="check autocomplete"
data-autocomplete-url-value="/path/to/autocomplete"
></select>
`);

// initial Ajax request on focus with group_by options
fetchMock.mock(
'/path/to/autocomplete?query=',
JSON.stringify({
results: {
options: [
{
group_by: ['Meat'],
value: 1,
text: 'Beef'
},
{
group_by: ['Meat'],
value: 2,
text: 'Mutton'
},
{
group_by: ['starchy'],
value: 3,
text: 'Potatoes'
},
{
group_by: ['starchy', 'Meat'],
value: 4,
text: 'chili con carne'
},
],
optgroups: [
{
value: 'Meat',
label: 'Meat'
},
{
value: 'starchy',
label: 'starchy'
},
]
},
}),
);

fetchMock.mock(
'/path/to/autocomplete?query=foo',
JSON.stringify({
results: {
options: [
{
group_by: ['Meat'],
value: 1,
text: 'Beef'
},
{
group_by: ['Meat'],
value: 2,
text: 'Mutton'
},
],
optgroups: [
{
value: 'Meat',
label: 'Meat'
},
]
}
}),
);

const controlInput = tomSelect.control_input;

// wait for the initial Ajax request to finish
userEvent.click(controlInput);
await waitFor(() => {
expect(container.querySelectorAll('.option[data-selectable]')).toHaveLength(5);
expect(container.querySelectorAll('.optgroup-header')).toHaveLength(2);
});

// typing was not properly triggering, for some reason
//userEvent.type(controlInput, 'foo');
controlInput.value = 'foo';
controlInput.dispatchEvent(new Event('input'));

await waitFor(() => {
expect(container.querySelectorAll('.option[data-selectable]')).toHaveLength(2);
expect(container.querySelectorAll('.optgroup-header')).toHaveLength(1);
});
});
});
1 change: 1 addition & 0 deletions src/Autocomplete/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/http-foundation": "^5.4|^6.0",
"symfony/http-kernel": "^5.4|^6.0",
"symfony/property-access": "^5.4|^6.0",
"symfony/string": "^5.4|^6.0"
},
"require-dev": {
Expand Down
15 changes: 15 additions & 0 deletions src/Autocomplete/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,20 @@ a :ref:`custom autocompleter <custom-autocompleter>`:
]
}

for using `Tom Select Option Group`_ the format is as follows

.. code-block:: json

{
"results": {
"options": [
{ "value": "1", "text": "Pizza", "group_by": ["food"] },
{ "value": "2", "text": "Banana", "group_by": ["food"] }
],
"optgroups": [{ "value": "food", "label": "food" }]
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is not valid anymore, right?

And we need docs for the new option :)

}

Once you have this, generate the URL to your controller and
pass it to the ``url`` value of the ``stimulus_controller()`` Twig
function, or to the ``autocomplete_url`` option of your form field.
Expand Down Expand Up @@ -557,3 +571,4 @@ the Symfony framework: https://symfony.com/doc/current/contributing/code/bc.html
.. _`Tom Select Options`: https://tom-select.js.org/docs/#general-configuration
.. _`controller.ts`: https://github.com/symfony/ux/blob/2.x/src/Autocomplete/assets/src/controller.ts
.. _`Tom Select Render Templates`: https://tom-select.js.org/docs/#render-templates
.. _`Tom Select Option Group`: https://tom-select.js.org/examples/optgroups/
1 change: 1 addition & 0 deletions src/Autocomplete/src/AutocompleteResults.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ final class AutocompleteResults
public function __construct(
public array $results,
public bool $hasNextPage,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can't break BC here, even though it's unlikely to cause problems. So:

A) Rename $options back to $results
B) Move $optgroups to the final argument and make it optional

Then, let's move the getResults() logic into the controller. That'll keep this class dead-simple - just a carrier of data.

public array $optgroups = [],
) {
}
}
69 changes: 66 additions & 3 deletions src/Autocomplete/src/AutocompleteResultsExecutor.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
namespace Symfony\UX\Autocomplete;

use Doctrine\ORM\Tools\Pagination\Paginator;
use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\PropertyAccess\PropertyPathInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
use Symfony\UX\Autocomplete\Doctrine\DoctrineRegistryWrapper;
Expand All @@ -21,10 +26,22 @@
*/
final class AutocompleteResultsExecutor
{
private PropertyAccessorInterface $propertyAccessor;
private ?Security $security;

public function __construct(
private DoctrineRegistryWrapper $managerRegistry,
private ?Security $security = null
$propertyAccessor,
/* Security $security = null */
) {
if ($propertyAccessor instanceof Security) {
trigger_deprecation('symfony/ux-autocomplete', '2.8.0', 'Passing a "%s" instance as the second argument of "%s()" is deprecated, pass a "%s" instance instead.', Security::class, __METHOD__, PropertyAccessorInterface::class);
$this->security = $propertyAccessor;
$this->propertyAccessor = new PropertyAccessor();
} else {
$this->propertyAccessor = $propertyAccessor;
$this->security = \func_num_args() >= 3 ? func_get_arg(2) : null;
}
}

public function fetchResults(EntityAutocompleterInterface $autocompleter, string $query, int $page): AutocompleteResults
Expand All @@ -50,15 +67,61 @@ public function fetchResults(EntityAutocompleterInterface $autocompleter, string
$paginator = new Paginator($queryBuilder);

$nbPages = (int) ceil($paginator->count() / $queryBuilder->getMaxResults());
$hasNextPage = $page < $nbPages;

$results = [];

if (null === $groupBy = $autocompleter->getGroupBy()) {
foreach ($paginator as $entity) {
$results[] = [
'value' => $autocompleter->getValue($entity),
'text' => $autocompleter->getLabel($entity),
];
}

return new AutocompleteResults($results, $hasNextPage);
}

if (\is_string($groupBy)) {
$groupBy = new PropertyPath($groupBy);
}

if ($groupBy instanceof PropertyPathInterface) {
$accessor = $this->propertyAccessor;
$groupBy = function ($choice) use ($accessor, $groupBy) {
try {
return $accessor->getValue($choice, $groupBy);
} catch (UnexpectedTypeException) {
return null;
}
};
}

if (!\is_callable($groupBy)) {
throw new \InvalidArgumentException(sprintf('Option "group_by" must be callable, "%s" given.', get_debug_type($groupBy)));
}

$optgroupLabels = [];

foreach ($paginator as $entity) {
$results[] = [
$result = [
'value' => $autocompleter->getValue($entity),
'text' => $autocompleter->getLabel($entity),
];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor, but I think we should "exit early" first if there is no group by. Basically:

if (null === $groupBy = $autocompleter->getGroupBy()) {
    // use the old logic
    $results = [];
    foreach ($paginator as $entity) {
        $results[] = [
            'value' => $autocompleter->getValue($entity),
            'text' => $autocompleter->getLabel($entity),
        ];
    }

    return $results;
}

Then the code that handles $groupBy can continue without needing to be in an else statement (no else will be needed at all).


$groupLabels = $groupBy($entity, $result['value'], $result['text']);

if (null !== $groupLabels) {
$groupLabels = \is_array($groupLabels) ? array_map('strval', $groupLabels) : [(string) $groupLabels];
$result['group_by'] = $groupLabels;
$optgroupLabels = array_merge($optgroupLabels, $groupLabels);
}

$results[] = $result;
}

return new AutocompleteResults($results, $page < $nbPages);
$optgroups = array_map(fn (string $label) => ['value' => $label, 'label' => $label], array_unique($optgroupLabels));

return new AutocompleteResults($results, $hasNextPage, $optgroups);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function __invoke(string $alias, Request $request): Response
}

return new JsonResponse([
'results' => $data->results,
'results' => ($data->optgroups) ? ['options' => $data->results, 'optgroups' => $data->optgroups] : $data->results,
'next_page' => $nextPage,
]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ private function registerBasicServices(ContainerBuilder $container): void
->register('ux.autocomplete.results_executor', AutocompleteResultsExecutor::class)
->setArguments([
new Reference('ux.autocomplete.doctrine_registry_wrapper'),
new Reference('property_accessor'),
new Reference('security.helper', ContainerInterface::NULL_ON_INVALID_REFERENCE),
])
;
Expand Down
5 changes: 5 additions & 0 deletions src/Autocomplete/src/EntityAutocompleterInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,9 @@ public function getValue(object $entity): mixed;
* Note: if SecurityBundle is not installed, this will not be called.
*/
public function isGranted(Security $security): bool;

/**
* Return group_by option.
*/
public function getGroupBy(): mixed;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of physically adding this method, which would break BC, add some documentation to the top for it: https://github.com/SymfonyCasts/reset-password-bundle/blob/6601f15fce7a4934bc9570f76feaf1b93536b1a7/src/ResetPasswordHelperInterface.php#L19 - that will allow people to be aware of it, and then we will add the actual method whenever we release a new major version.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also is the return value really mixed? Or is it ?string?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes i think, It can be string, callable or null

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, so it is: https://github.com/symfony/symfony/blob/7ed43d1a749d95ae3f3d8ffa9b72858cac3e39fd/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php#L370

That is QUITE the long list of things :). I think we could probably just use null|string|callable. Then, if someone passes a PropertyPath or GroupBy in a form, inside of WrappedEntityTypeAutocompleter, we could "normalize" those into a string|callable.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm struggling to see how to normalize this, how do you see the implementation of this normalization

}
5 changes: 5 additions & 0 deletions src/Autocomplete/src/Form/WrappedEntityTypeAutocompleter.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ public function isGranted(Security $security): bool
throw new \InvalidArgumentException('Invalid passed to the "security" option: it must be the boolean true, a string role or a callable.');
}

public function getGroupBy(): mixed
{
return $this->getFormOption('group_by');
}

private function getFormOption(string $name): mixed
{
$form = $this->getForm();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Symfony\UX\Autocomplete\Tests\Fixtures\Autocompleter;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Security;
use Symfony\UX\Autocomplete\Doctrine\EntitySearchUtil;
use Symfony\UX\Autocomplete\EntityAutocompleterInterface;
use Symfony\UX\Autocomplete\Tests\Fixtures\Entity\Product;

class CustomGroupByProductAutocompleter extends CustomProductAutocompleter
{
public function getGroupBy(): mixed
{
return 'category.name';
}
}
Loading