Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add jquery.tokeninput to use tokens as search entities #170

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
130 changes: 130 additions & 0 deletions Classes/Ajax/Autocomplete.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<?php

namespace Subugoe\Find\Ajax;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Http\JsonResponse;
use TYPO3\CMS\Core\Http\Response;

class Autocomplete implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
if (!isset($request->getQueryParams()['q']) &&
(!isset($request->getQueryParams()['autocomplete']) || !isset($request->getQueryParams()['entity']))
) {
return $response;
}

include_once __DIR__.'/EidSettings.php';

// Configuration options
$solrSuggestUrl = $HOST.$CORE.'/suggest';

// Autocomplete dictionary
$solrAutocompleteDictionary = 'autocompleteSuggester';

// Entity dictionary
$solrEntityDictionary = 'entitySuggester';

// Entity replacement
// $entityReplacement = '(entity_ids:%s OR entity_ids_from:%s OR entity_ids_to:%s)';
if (isset($request->getQueryParams()['replacement'])) {
$entityReplacement = $request->getQueryParams()['replacement'];
} else {
$entityReplacement = 'id:%s';
}

// Array of suggestions
$suggests = [];

// Get query string
$query = $request->getQueryParams()['q'];
$entity = $request->getQueryParams()['entity'];
$autocomplete = $request->getQueryParams()['autocomplete'];

$dictionaryUrlParams = '';

if ($entity) {
$dictionaryUrlParams .= '&suggest.dictionary='.$solrEntityDictionary;
}

if ($autocomplete) {
$dictionaryUrlParams .= '&suggest.dictionary='.$solrAutocompleteDictionary;
}

if (!$entity && !$autocomplete) {
return $response;
}

// Get Solr suggestions
$response = file_get_contents(
$solrSuggestUrl.'?suggest=true'.$dictionaryUrlParams.'&suggest.q='.urlencode($query),
false,
stream_context_create([
'http' => [
'method' => 'GET',
'follow_location' => 0,
'timeout' => 1.0,
],
])
);

// Parse JSON response
if (false !== $response) {
$json = json_decode($response, true);

if ($autocomplete) {
// get autocomplete
foreach ($json['suggest'][$solrAutocompleteDictionary][$query]['suggestions'] as $suggestion) {
list($id, $normalized) = explode('␝', $suggestion['payload']);
$suggests[] = [
'id' => htmlspecialchars($suggestion['term']),
'term' => htmlspecialchars($suggestion['term']),
'normalized' => htmlspecialchars($suggestion['term']),
'autocomplete' => '1',
];
}
}

if ($entity && $autocomplete) {
// Add break between autocomplete and entity list
$suggests[] = [
'id' => 'br',
];
}

if ($entity) {
$idDeduping = [];

// get entities
foreach ($json['suggest'][$solrEntityDictionary][$query]['suggestions'] as $suggestion) {
list($id, $normalized) = explode('␝', $suggestion['payload']);
if (!in_array($id, $idDeduping)) {
if (empty($normalized)) {
$normalized = $suggestion['term'];
}

$suggests[] = [
'id' => str_replace('%s', $id, $entityReplacement),
'term' => htmlspecialchars($suggestion['term']),
'normalized' => htmlspecialchars($normalized),
'autocomplete' => '0',
];
$idDeduping[] = $id;
}
}
}
}

// Return results
if (!empty($suggests)) {
// Return result
return new JsonResponse($suggests);
}
}
}
6 changes: 6 additions & 0 deletions Classes/Ajax/EidSettings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php

namespace Subugoe\Find\Ajax;

$HOST = 'http://solr:8983/solr/';
$CORE = 'core';
54 changes: 54 additions & 0 deletions Classes/Ajax/GetEntity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

namespace Subugoe\Find\Ajax;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Http\JsonResponse;
use TYPO3\CMS\Core\Http\Response;

class GetEntity implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
if (!isset($request->getQueryParams()['q'], $request->getQueryParams()['getEntity'])) {
return $response;
}

include_once __DIR__.'/EidSettings.php';

// Configuration options
$solr_select_url = $HOST.$CORE.'/select';

// Array of entity facts
$entity = [];

// Get query string
$query = $request->getQueryParams()['q'];

// Get Solr record
$response = file_get_contents(
$solr_select_url.'?q='.urlencode('id:('.$query.')').'&rows=1',
false,
stream_context_create([
'http' => [
'method' => 'GET',
'follow_location' => 0,
'timeout' => 1.0,
],
])
);

// Parse JSON response
if (false !== $response) {
$json = json_decode($response, true);
$entity = $json['response']['docs'][0];
}

// Return result
return new JsonResponse($entity);
}
}
6 changes: 2 additions & 4 deletions Classes/Service/SolrServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -415,10 +415,8 @@ protected function addHighlighting(array $arguments): void
if ($fieldID && $queryParameters[$fieldID]) {
$queryArguments = $queryParameters[$fieldID];
$queryTerms = null;
if (is_array($queryArguments) && array_key_exists(
'alternate',
$queryArguments
) && array_key_exists('queryAlternate', $fieldInfo)
if (is_array($queryArguments) && array_key_exists('alternate',
$queryArguments) && array_key_exists('queryAlternate', $fieldInfo)
) {
if (array_key_exists('term', $queryArguments)) {
$queryTerms = $queryArguments['term'];
Expand Down
18 changes: 18 additions & 0 deletions Configuration/RequestMiddlewares.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

return [
'frontend' => [
'Subugoe/Find/ajax/getentity' => [
'target' => \Subugoe\Find\Ajax\GetEntity::class,
'after' => [
'typo3/cms-frontend/prepare-tsfe-rendering',
],
],
'Subugoe/Find/ajax/autocomplete' => [
'target' => \Subugoe\Find\Ajax\Autocomplete::class,
'after' => [
'typo3/cms-frontend/prepare-tsfe-rendering',
],
],
],
];
13 changes: 13 additions & 0 deletions Configuration/TypoScript/setup.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ plugin.tx_find {
type = Text
# autocomplete = 1
# autocompleteDictionary =
# The following configuration is for a new autocomplete/entity function
# noescape = 2
# replaceAfterEscape {
# 1 {
# id\: = id:
# }
# }
# entityAutocomplete = 1
# entity = 1
# entityReplacement = id:%s
}

#10 {
Expand Down Expand Up @@ -225,7 +235,10 @@ plugin.tx_find {

CSSPaths.10 = {$plugin.tx_find.settings.CSSPath}
CSSPaths.20 = EXT:find/Resources/Public/CSS/fontello/css/fontello.css
CSSPaths.30 = EXT:find/Resources/Public/CSS/token-input.css
JSPaths.10 = {$plugin.tx_find.settings.JSPath}
JSPaths.20 = EXT:find/Resources/Public/JavaScript/jquery.tokeninput.js
JSPaths.30 = EXT:find/Resources/Public/JavaScript/autocomplete.js

languageRootPath = {$plugin.tx_find.settings.languageRootPath}
}
Expand Down
18 changes: 14 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,18 +259,21 @@ The Text field can be the simplest field available. It also allows
advanced behaviour by adding autocomplete or a checkbox to select an
alternate query style.

- `queryAlternate`: an array of alternative queries that can be
- `queryAlternate`: an array of alternative queries that can be
configured for the Text type; it creates a checkbox next to the
input field which toggles between the provided `query` and the first
`queryAlternate`
- `autocomplete` \[0\]: if true, a field of Text type will be hooked
- `autocomplete` \[0\]: if true, a field of Text type will be hooked
up for autocompletion using Solr suggest query
- `autocompleteDictionary`: name of the dictionary the Solr suggest
- `autocompleteDictionary`: name of the dictionary the Solr suggest
query should use
- `default`: default values to use in the query if no value is
- `default`: default values to use in the query if no value is
provided by the user (yet); may be a single value string (e.g. for
the default state of checkboxes) or an array (especially useful for
range queries)
- `entityAutocomplete`[0]: if true, activates the autocomplete (solr dictionary: autocompleteSuggester)
- `entity`[0]: if true, activates the entity search (solr dictionary: entitySuggester)
- `entityReplacement`: the string that should be replaced for an entity (e.g. id:%s)

Examples:

Expand All @@ -293,6 +296,13 @@ plugin.tx_find.settings.queryFields {
autocomplete = 1
autocompleteDictionary = name
}
13 {
id = entity
type = Text
entityAutocomplete = 1
entity = 1
entityReplacement = id:%s
}
}
```

Expand Down
5 changes: 3 additions & 2 deletions Resources/Private/Partials/Form/Fields/Text.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
</label>
<span class="inputContainer">
<f:form.textfield
id="c{config.uid}-field-{fieldInfo.id}"
id="c{config.uid}-field-{fieldInfo.id} {f:if(condition: '{fieldInfo.entity} || {fieldInfo.entityAutocomplete}', then: 'entity-input-{fieldInfo.id}')}"
class="inputType-text"
name="q[{fieldInfo.id}]{f:if(
condition:hasAlternate,
Expand All @@ -23,6 +23,7 @@
then:queryParameter.term,
else:queryParameter
)}"
data="{entityreplacement:\"{fieldInfo.entityReplacement}\", entity:\"{fieldInfo.entity}\", entityautocomplete:\"{fieldInfo.entityAutocomplete}\"}"
placeholder="{f:translate(key:'LLL:{settings.languageRootPath}locallang-form.xml:input.{fieldInfo.id}.placeholder')}"
additionalAttributes="<f:if condition='{fieldInfo.autocomplete}==1'><f:then>{autocompleteURL:\"{f:uri.action(
arguments:{dictionary:fieldInfo.autocompleteDictionary, q:'%%%%'},
Expand All @@ -47,4 +48,4 @@
</span>
</f:if>
</span>
</f:alias>
</f:alias>
4 changes: 2 additions & 2 deletions Resources/Private/Partials/Page/JavaScript.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
Adds the JavaScript files configured in the CSSPaths settings to the page’s head.
</f:comment>

<f:for each="{settings.JSPaths}" as="JSPath">
<s:page.script name="findJs{idx}" file="{JSPath}"/>
<f:for each="{settings.JSPaths}" as="JSPath" iteration="idx">
<s:page.script name="findJs{idx.index}" file="{JSPath}"/>
</f:for>
4 changes: 4 additions & 0 deletions Resources/Public/CSS/find.css
Original file line number Diff line number Diff line change
Expand Up @@ -352,3 +352,7 @@
position: absolute;
background: #fff;
}

.token-input-dropdown li:hover {
background-color: #b9b9b9;
}
Loading