Skip to content

Commit

Permalink
добавление функционала по поиску
Browse files Browse the repository at this point in the history
  • Loading branch information
agoalofalife committed Mar 19, 2024
1 parent ba29924 commit c94d00d
Show file tree
Hide file tree
Showing 13 changed files with 194 additions and 21 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,5 @@ QUIZ_STATUS=false
TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=
TELEGRAM_CHANNEL_ID=

SCOUT_DRIVER=
26 changes: 16 additions & 10 deletions app/Docs.php
Original file line number Diff line number Diff line change
Expand Up @@ -361,20 +361,25 @@ public function update()
/**
* Разбивает markdown файл на разделы по заголовкам.
*
* @return Массив разделов с заголовками и содержимым
* @return Collection разделов с заголовками и содержимым
*/
public function getSections()
public function getSections(): Collection
{

// Разбиваем HTML содержимое на разделы по заголовкам
preg_match_all('/<h(\d)>(.+)<\/h\d>(.*)/sU', $this->content(), $matches, PREG_SET_ORDER);

// Массив для хранения разделов
$sections = collect();
$prevEnd = 0;

$titlePage = null;
foreach ($matches as $index => $match) {
$sectionTitle = $match[2];

if ($match[1] == '1') {
$titlePage = $sectionTitle;
}
// Получаем начальную и конечную позицию текущего заголовка в тексте
$startPos = strpos($this->content(), $match[0], $prevEnd);

Expand All @@ -388,12 +393,13 @@ public function getSections()
}

$sections->push([
'title' => $sectionTitle,
'slug' => Str::of($sectionTitle)->slug()->toString(),
'content' => $sectionContent,
'file' => $this->file,
'version' => $this->version,
'id' => Str::uuid(),
'title_page' => $titlePage,
'title' => $sectionTitle,
'slug' => Str::of($sectionTitle)->slug()->toString(),
'content' => $sectionContent,
'file' => $this->file,
'version' => $this->version,
'id' => Str::uuid(),
]);
}

Expand All @@ -402,7 +408,7 @@ public function getSections()

public function updateSections()
{
// DocumentationSection::where('file', $this->file)->where('version', $this->version)->delete();
// DocumentationSection::insert($this->getSections()->toArray());
DocumentationSection::where('file', $this->file)->where('version', $this->version)->delete();
DocumentationSection::insert($this->getSections()->toArray());
}
}
17 changes: 17 additions & 0 deletions app/Http/Controllers/DocsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use App\Docs;
use App\Models\Document;
use App\Models\DocumentationSection;
use Illuminate\Http\Request;

class DocsController extends Controller
{
Expand Down Expand Up @@ -58,4 +60,19 @@ public function status(string $version = Docs::DEFAULT_VERSION)
'documents' => $documents,
]);
}

public function search(string $versionOfDocs, Request $request)
{

if (empty($request->text)) {
return turbo_stream()->replace('found_candidates', view('docs._search_lines', [
'searchOffer' => [],
]));
}
$searchOffers = DocumentationSection::search($request->text)->where('version', $versionOfDocs)->get();

return turbo_stream()->replace('found_candidates', view('docs._search_lines', [
'searchOffer' => $searchOffers,
]));
}
}
59 changes: 59 additions & 0 deletions app/Models/DocumentationSection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Laravel\Scout\Searchable;

class DocumentationSection extends Model
{
use HasFactory;
use HasUuids;
use Searchable;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id',
'title',
'slug',
'version',
'file',
'content',
];

protected function shortContent(): Attribute
{

return Attribute::make(
get: fn (mixed $value, array $attributes) =>

Str::limit(
nl2br(strip_tags($attributes['content'])),
90
),
);
}

protected function fileForUrl(): Attribute
{
return Attribute::make(
get: fn (mixed $value, array $attributes) => str_replace('.md', '', $attributes['file']),
);
}

public function toSearchableArray()
{
return [
'title' => $this->title,
'content' => $this->content,
];
}
}
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"laravel-notification-channels/webpush": "^7.1",
"laravel/framework": "^10.31",
"laravel/sanctum": "^3.2",
"laravel/scout": "^10.5",
"laravel/scout": "^10.8",
"laravel/socialite": "^5.9",
"laravel/telescope": "^4.17",
"laravel/tinker": "^2.8",
Expand Down
4 changes: 2 additions & 2 deletions composer.lock

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('documentation_sections', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('title_page')->comment('Заголовок всей страницы');
$table->string('title');
$table->string('slug');
$table->string('version');
$table->string('file');
$table->text('content');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('documentation_sections');
}
};
4 changes: 3 additions & 1 deletion 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 public/build/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"isEntry": true
},
"resources/js/app.js": {
"file": "assets/app-BUWIDZ8f.js",
"file": "assets/app-CnjHucs5.js",
"src": "resources/js/app.js",
"isEntry": true,
"css": [
Expand Down
14 changes: 14 additions & 0 deletions resources/js/controllers/search-docs_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
static targets = [ "text", "spinner"]
/**
* Port for laravel.com
*/
connect() {}
search(event) {
this.spinnerTarget.classList.remove('d-none');
event.target.form.requestSubmit();
setTimeout(() => this.spinnerTarget.classList.add('d-none'), 500)
}
}
17 changes: 17 additions & 0 deletions resources/views/docs/_search_lines.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<ul class="list-group" id="found_candidates">
@foreach($searchOffer as $offer)
{{-- <li class="list-group-item fs-6 text fw-bold" style="font-size: 14px !important;">{{ $offer->title_page }}</li>--}}

<a href="{{ route('docs', ['version' => $offer->version, 'page' => "{$offer->file_for_url}#{$offer->slug}" ]) }}" class="list-group-item list-group-item-action" aria-current="true">
<div class="d-flex w-100 justify-content-between">
<p class="mb-1 fw-bold font-monospace">{{ $offer->title_page }}</p>
{{-- <small>3 days ago</small>--}}
</div>
{{-- @dd(Str::of($offer->content)->limit(20)->__toString())--}}
<p class="mb-1">{{ $offer->title }}</p>
<small>{!! $offer->short_content !!}</small>

</a>
@endforeach
</ul>

32 changes: 26 additions & 6 deletions resources/views/docs/docs.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,32 @@
<div class="row gap-2 justify-content-center align-items-start position-relative mb-5">
<div class="col-3 col-xl-2 order-md-first order-last position-sticky top-0 py-md-3 z-1 d-none d-lg-block doc-navigation">

<div class="mb-md-4 ms-md-4 d-flex align-items-stretch flex-column offcanvas-md offcanvas-start" id="docs-menu">
<div class="mb-md-4 ms-md-4 d-flex align-items-stretch flex-column offcanvas-md offcanvas-start" id="docs-menu"
data-controller="search-docs"
>
<div>
<div class="mb-3">
<span data-search-docs-target="spinner" class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
<form action="{{ route('docs.search', ['versionOfDocs' => $docs->version]) }}" method="post" id="search-form">
@csrf
<input class="form-control form-control-md"
data-action="input->search-docs#search"
name="text"
data-search-docs-target="text"
type="text" placeholder="Поиск по документации..." aria-label=".form-control-lg example">
</form>
{{-- <template>--}}
<div class="mt-2" >
@include('docs._search_lines', ['searchOffer' => []])
{{-- <ul class="list-group">--}}
{{-- <li class="list-group-item">Курс по Laravel (Laravel Bootcamp)</li>--}}
{{-- <li class="list-group-item">Значения атрибутов по умолчанию</li>--}}
{{-- </ul>--}}
</div>
{{-- </template>--}}
</div>
</div>

{{--
<input class="form-control form-control-lg" type="text" placeholder="Поиск по документации..."
aria-label=".form-control-lg example">
--}}

<div class="d-flex align-items-center p-4 p-sm-0">
<select class="form-select form-select-sm rounded-3" onchange="Turbo.visit(this.value);">
Expand Down Expand Up @@ -80,7 +100,7 @@ class="{{ active(url($link['href']), 'active', 'link-body-emphasis') }} d-inline
</div>
<div class="px-0 px-md-2 px-xl-3 col-md-10 col-lg-8 col-xl-7 col-xxl-6 order-md-1 order-first">

<main class="bg-body-tertiary p-4 p-xl-5 rounded documentations position-relative" data-controller="prism">
<main class="bg-body-tertiary p-4 p-xl-5 rounded documentations position-relative" §>
<h1 class="display-6 fw-bold text-body-emphasis">{{ $docs->title() }}</h1>
@if ($docs->isOlderVersion())
<blockquote class="docs-blockquote-note position-relative mt-4" role="alert">
Expand Down
2 changes: 2 additions & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -375,8 +375,10 @@
->whereIn('version', Docs::SUPPORT_VERSIONS)
->name('docs');

Route::post('/docs/{versionOfDocs}/search', [DocsController::class, 'search'])->name('docs.search');
Route::get('/docs/{page}', fn (string $page) => redirect()->route('docs', ['version' => Docs::DEFAULT_VERSION, 'page' => $page]));


Route::get('nav/docs/{version?}', [DocsController::class, 'navigation'])
->whereIn('version', Docs::SUPPORT_VERSIONS)
->name('nav.docs');
Expand Down

0 comments on commit c94d00d

Please sign in to comment.