Skip to content

Documentation search #114

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

Merged
merged 9 commits into from
Mar 29, 2024
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
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=
2 changes: 1 addition & 1 deletion app/Console/Commands/CompareDocument.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ protected function updateVersion(string $version): void
{
Docs::every($version)->each(function (Docs $docs) {
try {
$docs->update();
dispatch(fn () => $docs->update());
} catch (\Exception $exception) {
// Log a warning if an error occurs during update
$this->warn("Failed to update document: {$exception->getMessage()} {$exception->getFile()} {$exception->getLine()}");
Expand Down
58 changes: 37 additions & 21 deletions app/Docs.php
Original file line number Diff line number Diff line change
Expand Up @@ -349,14 +349,13 @@ public function isOlderVersion()
*/
public function update()
{

$this->getModel()->fill([
'behind' => $this->fetchBehind(),
'last_commit' => $this->fetchLastCommit(),
'current_commit' => $this->variables('git'),
])->save();

// $this->updateSections();
$this->updateSections();
}

/**
Expand All @@ -366,44 +365,61 @@ public function update()
*/
public function getSections(): Collection
{
$content = Str::of($this->content());

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

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

foreach ($matches as $index => $match) {
$tag = $match[0];
$level = (int) $match[1];
$sectionTitle = $match[2];

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

$sectionContent = $content->after($tag);

// Получаем текст между текущим и предыдущим заголовком
if ($index > 0) {
$prevMatch = $matches[$index - 1];
$prevEnd = strpos($this->content(), $prevMatch[0]) + strlen($prevMatch[0]);
$sectionContent = substr($this->content(), $prevEnd, $startPos - $prevEnd);
} else {
$sectionContent = substr($this->content(), 0, $startPos);
// Если есть следующий заголовок - обрезаем контент до него
if (isset($matches[$index + 1])) {
Copy link
Member

Choose a reason for hiding this comment

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

Как насчет комментария хотя бы? 😀

$sectionContent = $sectionContent->before($matches[$index + 1][0]);
}

$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(),
'level' => $level,
'created_at' => now(),
'updated_at' => now(),
]);
}

return $sections;
}

/**
* @return void
*/
public function updateSections()
{
// DocumentationSection::where('file', $this->file)->where('version', $this->version)->delete();
// DocumentationSection::insert($this->getSections()->toArray());
if ($this->file === 'documentation.md') {
return;
}

DocumentationSection::where('file', $this->file)
->where('version', $this->version)
->delete();

DocumentationSection::insert($this->getSections()->toArray());
}
}
25 changes: 25 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,27 @@ public function status(string $version = Docs::DEFAULT_VERSION)
'documents' => $documents,
]);
}

/**
* @param string $version
* @param \Illuminate\Http\Request $request
*
* @return \HotwiredLaravel\TurboLaravel\Http\MultiplePendingTurboStreamResponse|\HotwiredLaravel\TurboLaravel\Http\PendingTurboStreamResponse
*/
public function search(string $version, Request $request)
{
$searchOffers = [];

if ($request->filled('text')) {
$searchOffers = DocumentationSection::search($request->text)
->where('version', $version)
->orderBy('level')
->get()
->take(6);
}

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

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

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

/**
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function fileForUrl(): Attribute
{
return Attribute::make(
get: fn (mixed $value, array $attributes) => str_replace('.md', '', $attributes['file']),
);
}

/**
* @return array
*/
public function toSearchableArray()
{
return [
'title' => $this->title,
'content' => $this->content,
'level' => $this->level,
];
}
}
2 changes: 1 addition & 1 deletion app/Services/TelegramBot.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public static function notificationToTelegram(\Throwable $exception): void
->line('*💪 Не сдавайтесь!*')
->line('Каждая ошибка - это шанс стать лучше. Давайте использовать этот момент, чтобы улучшить наш код и стать еще сильнее. Удачи!')
->send();
} catch (\Exception|Throwable) {
} catch (\Exception|\Throwable) {
// without recursive
}
}
Expand Down
42 changes: 21 additions & 21 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;

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->integer('level')->nullable()->comment('Уровень заголовка');
$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');
}
};

Large diffs are not rendered by default.

5 changes: 0 additions & 5 deletions public/build/assets/app-C5tVmPJ2.css

This file was deleted.

5 changes: 5 additions & 0 deletions public/build/assets/app-jsXsVF-0.css

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions public/build/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
"src": "public/img/ui/warning.svg"
},
"resources/css/app.scss": {
"file": "assets/app-C5tVmPJ2.css",
"file": "assets/app-jsXsVF-0.css",
"src": "resources/css/app.scss",
"isEntry": true
},
"resources/js/app.js": {
"file": "assets/app-BUWIDZ8f.js",
"file": "assets/app-B-hWsIbj.js",
"src": "resources/js/app.js",
"isEntry": true,
"css": [
Expand Down
2 changes: 2 additions & 0 deletions resources/css/app.scss
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ $input-padding-x: 1rem;

$badge-font-weight: normal;

$modal-backdrop-opacity: 0.675;

$utilities: (
'line-clamp': (
property: -webkit-line-clamp,
Expand Down
Loading