Новые изменения в компоенты

This commit is contained in:
Web-serfer 2026-04-28 22:28:13 +05:00
parent 1cea684a89
commit ce93982f11
8 changed files with 598 additions and 6 deletions

View file

@ -1,3 +1,124 @@
## v0.37.4
- Added backups list scroll container ([#7655](https://github.com/pocketbase/pocketbase/issues/7655)).
- Optimized record upsert and preview modals data loading to minimize layout jumps.
- Fixed SMTP IPv6 network address format ([#7659](https://github.com/pocketbase/pocketbase/issues/7659)).
- Fixed autocomplete selection not properly updating the underlying input value ([#7664](https://github.com/pocketbase/pocketbase/issues/7664)).
- Added `ghupdate.BaseURL` config option ([#7665](https://github.com/pocketbase/pocketbase/issues/7665)).
- Added dummy bcrypt password check for the failure auth path to minimize enumeration timing attacks when registrations are disabled.
- Adjusted Bitbucket, GitHub, GitLab and Gitea/Forgejo OAuth2 providers to better reflect recent API updates and doc references.
_In case the userinfo data is not sufficient, some of the providers now send a separate list emails request in order to minimize eventual linking security issues caused by custom onpremise setups (e.g. Gitea/Forgejo allows skipping the email verification if an ENV variable is configured)._
- ⚠️ Fixed a pre-hijacking OAuth2 linking vulnerability ([#7662](https://github.com/pocketbase/pocketbase/discussions/7662); thanks @Alardiians for reporting it privately).
- Bumped Go and npm dependencies.
## v0.37.3
- Fixed total count load on page back/forward navigation.
- Fixed `editor` floating dialogs position when scrolling ([#7653](https://github.com/pocketbase/pocketbase/issues/7653)).
- Enabled text wrapping for the API rule fields.
- Added view query sample loading indicator.
- Other minor light UI contrast and styles improvements.
## v0.37.2
- Fixed autoexpandable input in Firefox ([#7648](https://github.com/pocketbase/pocketbase/discussions/7648)).
- Slightly adjusted the dark theme colors for better readability ([#7648](https://github.com/pocketbase/pocketbase/discussions/7648)).
- Removed unnecessary tags stripping from the displayed log attributes ([#7649](https://github.com/pocketbase/pocketbase/issues/7649)).
- Workarounded Safari freeze caused by a buggy CSS popover property ([#7650](https://github.com/pocketbase/pocketbase/issues/7650)).
## v0.37.1
- Minor UI bugfixes:
- Fixed `number` field input values normalization ([#7646](https://github.com/pocketbase/pocketbase/issues/7646)).
- Allow opening collections in new tab with middle click.
- Show collection name in the page title on initial load.
## v0.37.0
- New UI rewritten from scratch and with support for external customization in mind.
> Note that as explained in [#7612](https://github.com/pocketbase/pocketbase/discussions/7612) the new UI kit and extensions APIs will intentionally remain undocumented until "Stage 2 completion" _(there no ETAs)_.
The new UI also introduced several other small improvements:
- ~2MB smaller bundle size.
- Dark mode and theming support.
- Basic responsive/mobile support _(it is far from perfect but certainly more usable than before)_.
- Help text option for the collection fields.
- Lifted the max nested level restriction of presentable relations _(children are lazy loaded)_.
- Lighter rules autocomplete.
- Live view query preview.
- Insert of an audio/video embed tag in the richtext editor from a collection file.
- Option to bulk export records as JSON.
- Local search history for all searchbars.
- API rules overview across all collections.
- Very basic ERD-like visualization for the collections structure and relations.
- New stepped logs chart visualization with panning support.
- `listAuthMethods()` (aka. `/api/collection/{col}/auth-methods`) now returns the OAuth2 provider logo for each provider as inlined SVG string in its response data.
_⚠ Note that if your app for whatever reason rely on the dashboard OAuth2 logos available under `/_/images/oauth2/*` they are still available for now but will be removed in future versions and it is recommended to use the new inline SVGs!_
- Added optional `no_ui` build tag to exclude the UI from bundling with the executable ([#7548](https://github.com/pocketbase/pocketbase/issues/7548)).
```sh
go build -tags no_ui
```
- Exported the internal JSVM bind functions ([#7600](https://github.com/pocketbase/pocketbase/discussions/7600)).
```go
jsvm.BindCore(vm)
jsvm.BindDbx(vm)
jsvm.BindSecurity(vm)
jsvm.BindOS(vm)
jsvm.BindFilepath(vm)
jsvm.BindHTTP(vm)
jsvm.BindFilesystem(vm)
jsvm.BindForms(vm)
jsvm.BindMails(vm)
jsvm.BindApis(vm)
```
- Updated `modernc.org/sqlite` to v1.49.1 (SQLite 3.53.0).
## v0.36.9
- Updated the Discord `AuthUser.Name` field to use `global_name` ([#7603](https://github.com/pocketbase/pocketbase/pull/7603); thanks @HansHans135).
- Fixed settings SMTP password clear persistence.
- Added extra OAuth2 checks when downloading the avatar URL to prevent internal network probing requests in case of a malicious/vulnerable vendor.
- Updated `modernc.org/sqlite` to v1.48.2 _(vfs and other error path related fixes)_.
- Updated min Go GitHub action version to 1.26.2 because it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.2).
- Other small improvements _(updated `$apis.static` JSVM documentation, fixed comment typos, added missing file close on seek error, etc.)_.
## v0.36.8
- Fixed OAuth2 client secret reset when serializing a cached collection model.
- Bumped all Go and npm deps.
_This should also silence recent spam reports and security scanners regarding `golang.org/x/image` [CVE-2026-33809](https://www.cve.org/CVERecord?id=CVE-2026-33809) (it is not an issue in PocketBase because we don't support TIFF thumbs)._
## v0.36.7
- Fixed high memory usage with large file uploads ([#7572](https://github.com/pocketbase/pocketbase/discussions/7572)).
@ -663,7 +784,7 @@ and the minor performance boost that you may get when used on large records is n
- Eagerly interrupt waiting for the email alert send in case it takes longer than 15s.
- Normalized the hidden fields filter checks and allow targetting hidden fields in the List API rule.
- Normalized the hidden fields filter checks and allow targeting hidden fields in the List API rule.
- Fixed "Unique identify fields" input not refreshing on unique indexes change ([#6184](https://github.com/pocketbase/pocketbase/issues/6184)).
@ -755,7 +876,7 @@ and the minor performance boost that you may get when used on large records is n
- Added support for passing more than one id in the `Hook.Unbind` method for consistency with the router.
- Added collection rules change list in the confirmation popup
(_to avoid getting anoying during development, the rules confirmation currently is enabled only when using https_).
(_to avoid getting annoying during development, the rules confirmation currently is enabled only when using https_).
## v0.23.1
@ -798,7 +919,7 @@ There are a lot of changes but to highlight some of the most notable ones:
- Option to specify custom `DBConnect` function as part of the app configuration to allow different `database/sql` SQLite drivers (_turso/libsql, sqlcipher, etc._) and custom builds.
_Note that we no longer loads the `mattn/go-sqlite3` driver by default when building with `CGO_ENABLED=1` to avoid `multiple definition` linker errors in case different CGO SQLite drivers or builds are used. You can find an example how to enable it back if you want to in the [new documentation](https://pocketbase.io/docs/go-overview/#github-commattngo-sqlite3)._
- New hooks allowing better control over the execution chain and error handling (_including wrapping an entire hook chain in a single DB transaction_).
- Various `Record` model improvements (_support for get/set modifiers, simplfied file upload by treating the file(s) as regular field value like `record.Set("document", file)`, etc._).
- Various `Record` model improvements (_support for get/set modifiers, simplified file upload by treating the file(s) as regular field value like `record.Set("document", file)`, etc._).
- Dedicated fields structs with safer defaults to make it easier creating/updating collections programmatically.
- Option to mark field as "Hidden", disallowing regular users to read or modify it (_there is also a dedicated Record hook to hide/unhide Record fields programmatically from a single place_).
- Option to customize the default system collection fields (`id`, `email`, `password`, etc.).

View file

@ -0,0 +1,42 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_1125843985")
// update field
collection.fields.addAt(9, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text1864383797",
"max": 0,
"min": 0,
"name": "readTime",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_1125843985")
// update field
collection.fields.addAt(9, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text1864383797",
"max": 0,
"min": 0,
"name": "readmeTime",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
return app.save(collection)
})

Binary file not shown.

View file

@ -54,7 +54,7 @@ const imageUrl = image || '/images/blog/default.avif';
<circle cx="12" cy="12" r="10"></circle>
<polyline points="12 6 12 12 16 14"></polyline>
</svg>
{readmeTime || readTime} мин.
{readTime || readmeTime} мин.
</span>
</div>
</div>

View file

@ -64,7 +64,7 @@ const filteredPosts = currentSlug
<circle cx="12" cy="12" r="10"></circle>
<polyline points="12 6 12 12 16 14"></polyline>
</svg>
{post.readmeTime || post.readTime} мин.
{post.readTime || post.readmeTime} мин.
</span>
</div>
</div>

View file

@ -105,7 +105,7 @@ const {
</span>
<span class="meta-item">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="meta-icon"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
{readmeTime} мин.
{readTime} мин.
</span>
<span class="meta-item">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="meta-icon"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"></path><circle cx="12" cy="12" r="3"></circle></svg>

View file

@ -0,0 +1,271 @@
import PocketBase from 'pocketbase';
import fs from 'fs';
import path from 'path';
import https from 'https';
import http from 'http';
const SERVER_URL = 'https://avt-back.ru/';
const LOCAL_URL = 'http://127.0.0.1:8090';
const LOCAL_STORAGE_PATH = 'D:/Verstka/production/astro_avtourist/backend/pb_data/storage/pbc_1125843985';
const ADMIN_EMAIL = 'redibedi2019@gmail.com';
const ADMIN_PASSWORD = 'Stalin4444';
const localPb = new PocketBase(LOCAL_URL);
interface Post {
id: string;
title: string;
slug: string;
description: string;
content: string;
author: string;
category: string;
categoryColor: string;
date: string;
readmeTime: string;
image: string;
draft: boolean;
views: number;
}
const COLLECTION_ID = 'pbc_1125843985';
const TEMP_DIR = path.join(process.cwd(), 'temp_images');
function ensureDir(dir: string) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
function copyFileSync(src: string, dest: string): boolean {
try {
if (!fs.existsSync(src)) {
return false;
}
ensureDir(path.dirname(dest));
fs.copyFileSync(src, dest);
return true;
} catch (e) {
return false;
}
}
async function downloadFile(url: string, destPath: string, token?: string): Promise<boolean> {
return new Promise((resolve) => {
const protocol = url.startsWith('https') ? https : http;
const options: https.RequestOptions = {};
if (token) {
options.headers = { 'Authorization': `Bearer ${token}` };
}
console.log(` Headers:`, JSON.stringify(options.headers));
const file = fs.createWriteStream(destPath);
protocol.get(url, (response) => {
if (response.statusCode === 404) {
fs.unlinkSync(destPath);
resolve(false);
return;
}
response.pipe(file);
file.on('finish', () => {
file.close();
resolve(true);
});
}).on('error', (err) => {
fs.unlinkSync(destPath);
resolve(false);
});
});
}
async function uploadImage(localPb: PocketBase, filePath: string): Promise<string | null> {
try {
const formData = new FormData();
const fileBuffer = fs.readFileSync(filePath);
const fileName = path.basename(filePath);
const blob = new Blob([fileBuffer]);
const file = new File([blob], fileName);
formData.append('image', file);
const record = await localPb.collection('posts').create(formData);
return record.image;
} catch (e) {
console.error('Ошибка загрузки изображения:', e);
return null;
}
}
async function syncPosts() {
console.log('🔄 Синхронизация постов с сервера на локальную БД...\n');
ensureDir(TEMP_DIR);
const adminData = await localPb.admins.authWithPassword(ADMIN_EMAIL, ADMIN_PASSWORD);
console.log('✅ Подключено к локальной БД\n');
const serverPb = new PocketBase(SERVER_URL);
const authData = await serverPb.admins.authWithPassword(ADMIN_EMAIL, ADMIN_PASSWORD);
console.log('✅ Подключено к серверу');
const token = authData.token;
console.log('📥 Получение постов с сервера...');
const response = await fetch(`${SERVER_URL}api/collections/posts/records?perPage=500`, {
headers: { 'Authorization': `Bearer ${token}` }
});
const data = await response.json();
const serverPosts = data.items as Post[];
// Дебаг: смотрю структуру image
if (serverPosts.length > 0) {
console.log('\n📋 Дебаг - структура поста:');
console.log(' id:', serverPosts[0].id);
console.log(' image field:', serverPosts[0].image);
console.log(' slug:', serverPosts[0].slug);
console.log('');
}
console.log(`📊 На сервере: ${serverPosts.length} постов\n`);
console.log('📥 Получение локальных постов...');
const localPosts = await localPb.collection('posts').getFullList<Post>();
const localSlugs = new Set(localPosts.map(p => p.slug));
const localPostsMap = new Map(localPosts.map(p => [p.slug, p]));
console.log(`📊 Локально: ${localPosts.length} постов\n`);
// Создаем карту slug -> localId для маппинга файлов
const slugToLocalId = new Map(localPosts.map(p => [p.slug, p.id]));
let added = 0;
let skipped = 0;
let imagesDownloaded = 0;
for (const post of serverPosts) {
if (localSlugs.has(post.slug)) {
// Пост уже есть - проверяем, есть ли картинка
const localPost = localPostsMap.get(post.slug);
if (!localPost?.image && post.image) {
console.log(`📷 Загружаю изображение для: ${post.slug}`);
// Маппим server record ID -> local record ID через slug
const localRecordId = slugToLocalId.get(post.slug);
if (!localRecordId) {
console.log(`Не найден local ID для slug: ${post.slug}\n`);
continue;
}
const filename = post.image;
// Копируем файл из server storage в local storage
// Путь: D:\...\backend\pb_data\storage\pbc_1125843985\{record_id}\{filename}
// Но у нас нет доступа к server storage напрямую!
// Однако - мы можем скопировать из ЛОКАЛЬНОГО storage, если там есть эти файлы
// Они были загружены при создании постов в локальной БД
// Проверим, есть ли файл в локальном storage
console.log(` Server record ID: ${post.id}`);
console.log(` Local record ID: ${localRecordId}`);
console.log(` Image filename: ${filename}`);
// Так как файлы на сервере недоступны, попробуем скачать через другой метод
// Проверим есть ли они в локальном storage
const localStorageDir = path.join(LOCAL_STORAGE_PATH, localRecordId);
if (fs.existsSync(localStorageDir)) {
const files = fs.readdirSync(localStorageDir);
console.log(` Файлы в local storage: ${files.join(', ')}`);
}
}
skipped++;
continue;
}
try {
// Загружаем изображение если есть
let localImage = '';
if (post.image) {
const filename = post.image;
const tempPath = path.join(TEMP_DIR, filename);
const fileUrl = `${SERVER_URL}api/files/collections/posts/${post.id}/${filename}`;
console.log(`📷 Скачиваю изображение для ${post.slug}...`);
console.log(` URL: ${fileUrl}`);
const downloaded = await downloadFile(fileUrl, tempPath, token);
if (downloaded && fs.existsSync(tempPath)) {
try {
// Создаем запись с изображением через FormData
const formData = new FormData();
const fileBuffer = fs.readFileSync(tempPath);
const blob = new Blob([fileBuffer]);
const file = new File([blob], filename);
formData.append('image', file);
formData.append('title', post.title);
formData.append('slug', post.slug);
formData.append('description', post.description || '');
formData.append('content', post.content || '');
formData.append('author', post.author || '');
formData.append('category', post.category || '');
formData.append('categoryColor', post.categoryColor || '');
formData.append('date', post.date || '');
formData.append('readTime', post.readmeTime || '');
formData.append('draft', String(post.draft ?? false));
formData.append('views', String(post.views ?? 0));
const newRecord = await localPb.collection('posts').create(formData);
localImage = newRecord.image;
fs.unlinkSync(tempPath);
console.log(` ✅ Создан с изображением\n`);
} catch (e: any) {
console.error(` ❌ Ошибка загрузки изображения:`, e.message);
// Создаем без изображения
}
} else {
console.log(` ⚠️ Не удалось скачать изображение, создаю без него\n`);
}
}
// Если изображение не загружено, создаем запись без него
if (!localImage) {
const postData = {
title: post.title,
slug: post.slug,
description: post.description,
content: post.content,
author: post.author,
category: post.category,
categoryColor: post.categoryColor,
date: post.date,
readTime: post.readmeTime || '',
image: '',
draft: post.draft ?? false,
views: post.views ?? 0,
};
await localPb.collection('posts').create(postData);
}
console.log(`✅ Добавлен: ${post.slug}`);
added++;
} catch (e: any) {
console.error(`❌ Ошибка добавления ${post.slug}:`, e.response?.data || e.message);
}
}
// Очистка temps
if (fs.existsSync(TEMP_DIR)) {
fs.rmSync(TEMP_DIR, { recursive: true, force: true });
}
console.log(`\n📊 Готово! Добавлено: ${added}, пропущено: ${skipped}, изображений загружено: ${imagesDownloaded}`);
}
syncPosts().catch(console.error);

158
scripts/sync-posts.ts Normal file
View file

@ -0,0 +1,158 @@
import PocketBase from 'pocketbase';
import fs from 'fs';
import path from 'path';
const LOCAL_URL = 'http://127.0.0.1:8090';
const SERVER_URL = 'https://avt-back.ru/';
const ADMIN_EMAIL = 'redibedi2019@gmail.com';
const ADMIN_PASSWORD = 'Stalin4444';
const LOCAL_STORAGE_DIR = 'D:/Verstka/production/astro_avtourist/backend/pb_data/storage/pbc_1125843985';
interface Post {
id: string;
title: string;
slug: string;
description: string;
content: string;
author: string;
category: string;
categoryColor: string;
date: string;
readTime: string;
readmeTime: string;
image: string;
draft: boolean;
views: number;
created: string;
updated: string;
}
async function main() {
console.log('🔄 Синхронизация постов: Локальный → Публичный сервер\n');
// Подключение к локальному PocketBase
const localPb = new PocketBase(LOCAL_URL);
await localPb.admins.authWithPassword(ADMIN_EMAIL, ADMIN_PASSWORD);
console.log('✅ Подключено к локальной БД');
// Подключение к публичному серверу
const serverPb = new PocketBase(SERVER_URL);
await serverPb.admins.authWithPassword(ADMIN_EMAIL, ADMIN_PASSWORD);
console.log('✅ Подключено к публичному серверу\n');
// Получение постов с локальной БД
console.log('📥 Получение постов с локальной БД...');
const localPosts = await localPb.collection('posts').getFullList<Post>({
filter: 'slug != "" && title != ""',
});
// Фильтруем только неп черновые посты
const publishedPosts = localPosts.filter(p => !p.draft && p.slug);
console.log(`📊 Локально: ${publishedPosts.length} опубликованных постов\n`);
// Получение постов с публичного сервера
console.log('📥 Получение постов с публичного сервера...');
const serverPosts = await serverPb.collection('posts').getFullList<Post>();
const serverSlugs = new Set(serverPosts.map(p => p.slug));
console.log(`📊 На сервере: ${serverPosts.length} постов\n`);
// Синхронизация постов
let created = 0;
let skipped = 0;
let imagesUploaded = 0;
for (const post of publishedPosts) {
// Проверяем, существует ли пост на сервере
if (serverSlugs.has(post.slug)) {
console.log(`⏭️ Пропущен (уже есть): ${post.slug}`);
skipped++;
continue;
}
console.log(`📝 Создаю пост: ${post.slug}`);
try {
// Если есть картинка - загружаем через FormData
if (post.image) {
const imagePath = path.join(LOCAL_STORAGE_DIR, post.id, post.image);
if (fs.existsSync(imagePath)) {
console.log(` 📷 Загружаю изображение: ${post.image}`);
const formData = new FormData();
const fileBuffer = fs.readFileSync(imagePath);
const blob = new Blob([fileBuffer]);
const file = new File([blob], post.image);
formData.append('image', file);
formData.append('title', post.title);
formData.append('slug', post.slug);
formData.append('description', post.description || '');
formData.append('content', post.content || '');
formData.append('author', post.author || '');
formData.append('category', post.category || '');
formData.append('categoryColor', post.categoryColor || '');
formData.append('date', post.date || '');
formData.append('readTime', post.readTime || '');
formData.append('readmeTime', post.readTime || post.readmeTime || '');
formData.append('draft', String(post.draft ?? false));
formData.append('views', String(post.views ?? 0));
await serverPb.collection('posts').create(formData);
console.log(` ✅ Создан с картинкой`);
imagesUploaded++;
} else {
// Файла нет - создаем без картинки
console.log(` ⚠️ Картинка не найдена: ${imagePath}`);
await serverPb.collection('posts').create({
title: post.title,
slug: post.slug,
description: post.description || '',
content: post.content || '',
author: post.author || '',
category: post.category || '',
categoryColor: post.categoryColor || '',
date: post.date || '',
readTime: post.readTime || '',
readmeTime: post.readTime || post.readmeTime || '',
image: '',
draft: post.draft ?? false,
views: post.views ?? 0,
});
console.log(` ✅ Создан без картинки`);
}
} else {
// Нет картинки - создаем без неё
await serverPb.collection('posts').create({
title: post.title,
slug: post.slug,
description: post.description || '',
content: post.content || '',
author: post.author || '',
category: post.category || '',
categoryColor: post.categoryColor || '',
date: post.date || '',
readTime: post.readTime || post.readmeTime || '',
image: '',
draft: post.draft ?? false,
views: post.views ?? 0,
});
console.log(` ✅ Создан без картинки`);
}
created++;
} catch (e: any) {
console.error(` ❌ Ошибка:`, e.response?.data || e.message);
}
}
console.log('\n📊 Итоги:');
console.log(` ✅ Создано: ${created}`);
console.log(` ⏭️ Пропущено: ${skipped}`);
console.log(` 🖼️ Картинок загружено: ${imagesUploaded}`);
}
main().catch(console.error);