ai-home-cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +246 -2
- package/dist/api/client.js +212 -0
- package/dist/api/types.js +21 -0
- package/dist/args.js +107 -0
- package/dist/auth.js +150 -0
- package/dist/catalog/live.js +307 -0
- package/dist/catalog/store.js +467 -0
- package/dist/config.js +318 -0
- package/dist/hub/client.js +402 -0
- package/dist/index.js +542 -0
- package/dist/mode.js +91 -0
- package/dist/paths.js +31 -0
- package/dist/protocol/serverMessages.js +400 -0
- package/dist/protocol/storedMessages.js +346 -0
- package/dist/session/controller.js +1669 -0
- package/dist/session/inline-presenter.js +48 -0
- package/dist/session/snapshot.js +10 -0
- package/dist/terminal/commands.js +873 -0
- package/dist/terminal/completion-editor.js +480 -0
- package/dist/terminal/context-line.js +84 -0
- package/dist/terminal/feed-renderer.js +70 -0
- package/dist/terminal/greeting.js +29 -0
- package/dist/terminal/interrupt-chain.js +64 -0
- package/dist/terminal/permissions.js +405 -0
- package/dist/terminal/renderer.js +343 -0
- package/dist/terminal/repl.js +1006 -0
- package/dist/terminal/sanitize.js +19 -0
- package/dist/terminal/text-picker.js +135 -0
- package/dist/tui/actions.js +215 -0
- package/dist/tui/cells.js +128 -0
- package/dist/tui/contracts.js +5 -0
- package/dist/tui/jsvision/app.js +1163 -0
- package/dist/tui/jsvision/catalog-adapter.js +141 -0
- package/dist/tui/jsvision/commands.js +130 -0
- package/dist/tui/jsvision/feed-view.js +138 -0
- package/dist/tui/jsvision/layout.js +49 -0
- package/dist/tui/jsvision/search.js +606 -0
- package/dist/tui/jsvision/theme.js +85 -0
- package/dist/tui/snapshot-binding.js +51 -0
- package/dist/tui/startup.js +25 -0
- package/package.json +35 -4
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
// Поиск по чатам экрана B (CS-6, перенос на JSVision): состояние выдачи, удалённый запрос
|
|
2
|
+
// с epoch/abort и собственный список строк с подсветкой совпадения.
|
|
3
|
+
//
|
|
4
|
+
// Почему состояние и запрос живут здесь, а не в адаптере каталога: адаптер — read-only срез
|
|
5
|
+
// CatalogSource, а поиск ходит в REST с JWT и держит отмену в полёте. Транспорт передан швом
|
|
6
|
+
// (SearchSessionOptions.transport), поэтому сессия не знает ни ApiClient, ни токена — экран
|
|
7
|
+
// передаёт их сам, а тест подставляет очередь ответов.
|
|
8
|
+
//
|
|
9
|
+
// Мгновенный title-fallback из загруженного каталога — первый кадр выдачи: сеть ещё ничего
|
|
10
|
+
// не ответила, и футер честно говорит «по названиям». Удалённый ответ заменяет fallback,
|
|
11
|
+
// только если его epoch ещё свежий; снятие любой из двух защит (epoch и abort) делает выдачу
|
|
12
|
+
// гонкой поздних ответов.
|
|
13
|
+
//
|
|
14
|
+
// Список строк — свой View, а не ListView: ListView рисует getText одной строкой без стилей,
|
|
15
|
+
// а подчёркивание обязано лежать РОВНО на сегменте совпадения. Навигация (↑/↓/PgUp/PgDn)
|
|
16
|
+
// и активация Enter приходят из Dialog'а: фокус остаётся в поле ввода, чтобы набор не рвался.
|
|
17
|
+
import { Attr, Text, View, signal, stringWidth } from '@jsvision/ui';
|
|
18
|
+
import { ApiError, InvalidResponseError } from "../../api/client.js";
|
|
19
|
+
import { relTimeText } from "./catalog-adapter.js";
|
|
20
|
+
const PERSONAL_NAME = 'Личное';
|
|
21
|
+
/** Столько строк просит одна страница выдачи (та же величина, что на вебе). */
|
|
22
|
+
const SEARCH_LIMIT = 20;
|
|
23
|
+
/** Пауза между последней правкой запроса и удалённым запросом. */
|
|
24
|
+
export const SEARCH_DEBOUNCE_MS = 250;
|
|
25
|
+
/** Диапазон совпадения запроса в названии (регистронезависимо); null — не совпало. */
|
|
26
|
+
export function matchRange(name, query) {
|
|
27
|
+
const needle = query.trim().toLowerCase();
|
|
28
|
+
if (needle.length === 0)
|
|
29
|
+
return null;
|
|
30
|
+
const at = name.toLowerCase().indexOf(needle);
|
|
31
|
+
return at < 0 ? null : { start: at, end: at + needle.length };
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Части серверного фрагмента в сегменты кадра: разметки нет по построению — только текст и
|
|
35
|
+
* флаг совпадения. Пробельные символы нормализуются в пробел (кадр строковый), соседние
|
|
36
|
+
* части одного флага склеиваются, края обрезаются.
|
|
37
|
+
*/
|
|
38
|
+
export function snippetSegments(parts) {
|
|
39
|
+
const merged = [];
|
|
40
|
+
for (const part of parts) {
|
|
41
|
+
const text = String(part.text ?? '').replace(/\s+/g, ' ');
|
|
42
|
+
if (text.length === 0)
|
|
43
|
+
continue;
|
|
44
|
+
const previous = merged[merged.length - 1];
|
|
45
|
+
if (previous !== undefined && previous.match === (part.match === true))
|
|
46
|
+
previous.text += text;
|
|
47
|
+
else
|
|
48
|
+
merged.push({ text, match: part.match === true });
|
|
49
|
+
}
|
|
50
|
+
if (merged.length === 0)
|
|
51
|
+
return merged;
|
|
52
|
+
merged[0].text = merged[0].text.replace(/^ +/, '');
|
|
53
|
+
merged[merged.length - 1].text = merged[merged.length - 1].text.replace(/ +$/, '');
|
|
54
|
+
return merged.filter((segment) => segment.text.length > 0);
|
|
55
|
+
}
|
|
56
|
+
/** Текст отказа: выдача остаётся title-fallback, поэтому отказ не называется потерей. */
|
|
57
|
+
export function searchFailureText(err) {
|
|
58
|
+
if (err instanceof ApiError) {
|
|
59
|
+
if (err instanceof InvalidResponseError)
|
|
60
|
+
return 'Некорректный ответ поиска — показаны совпадения по названиям.';
|
|
61
|
+
if (err.status === 429)
|
|
62
|
+
return 'Слишком часто — показаны совпадения по названиям.';
|
|
63
|
+
if (err.status === 503)
|
|
64
|
+
return 'Поиск временно недоступен — показаны совпадения по названиям.';
|
|
65
|
+
if (err.status === 0)
|
|
66
|
+
return 'Нет связи — показаны совпадения по названиям.';
|
|
67
|
+
return err.message;
|
|
68
|
+
}
|
|
69
|
+
return err instanceof Error ? err.message : 'Поиск недоступен — показаны совпадения по названиям.';
|
|
70
|
+
}
|
|
71
|
+
/** Русское склонение счётчика строк выдачи (1 чат, 2 чата, 5 чатов). */
|
|
72
|
+
function pluralChats(count) {
|
|
73
|
+
const mod10 = count % 10;
|
|
74
|
+
const mod100 = count % 100;
|
|
75
|
+
const word = mod10 === 1 && mod100 !== 11
|
|
76
|
+
? 'чат'
|
|
77
|
+
: mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)
|
|
78
|
+
? 'чата'
|
|
79
|
+
: 'чатов';
|
|
80
|
+
return `${count} ${word}`;
|
|
81
|
+
}
|
|
82
|
+
function clampIndex(value, range) {
|
|
83
|
+
if (range <= 0)
|
|
84
|
+
return 0;
|
|
85
|
+
return Math.max(0, Math.min(range - 1, value));
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Состояние поиска одного открытого диалога. Сигналы — то, что читает UI; сеть и epoch —
|
|
89
|
+
* внутри. Идемпотентный dispose: после него поздние ответы не трогают сигналы.
|
|
90
|
+
*/
|
|
91
|
+
export class SearchSession {
|
|
92
|
+
rows;
|
|
93
|
+
focused;
|
|
94
|
+
footer;
|
|
95
|
+
title;
|
|
96
|
+
catalog;
|
|
97
|
+
context;
|
|
98
|
+
transport;
|
|
99
|
+
debounceMs;
|
|
100
|
+
now;
|
|
101
|
+
query = '';
|
|
102
|
+
scopeMode;
|
|
103
|
+
epoch = 0;
|
|
104
|
+
abort = null;
|
|
105
|
+
timer = null;
|
|
106
|
+
cursor = null;
|
|
107
|
+
complete = true;
|
|
108
|
+
contentSearched = false;
|
|
109
|
+
loading = false;
|
|
110
|
+
notice = null;
|
|
111
|
+
usedFallback = false;
|
|
112
|
+
scopesLoaded = 0;
|
|
113
|
+
scopesTotal = 0;
|
|
114
|
+
rowsState = [];
|
|
115
|
+
disposed = false;
|
|
116
|
+
constructor(options) {
|
|
117
|
+
this.catalog = options.catalog;
|
|
118
|
+
this.context = options.context;
|
|
119
|
+
this.transport = options.transport;
|
|
120
|
+
this.debounceMs = options.debounceMs ?? SEARCH_DEBOUNCE_MS;
|
|
121
|
+
this.now = options.now ?? (() => new Date());
|
|
122
|
+
this.scopeMode = options.scope ?? 'current';
|
|
123
|
+
this.rows = signal([]);
|
|
124
|
+
this.focused = signal(0);
|
|
125
|
+
this.footer = signal(this.footerText());
|
|
126
|
+
this.title = signal(this.titleText());
|
|
127
|
+
}
|
|
128
|
+
/** Текущий охват: его сохраняет экран после закрытия диалога. */
|
|
129
|
+
get scope() {
|
|
130
|
+
return this.scopeMode;
|
|
131
|
+
}
|
|
132
|
+
/** Новый запрос: новый epoch, отмена прежнего и пауза до удалённого вызова. */
|
|
133
|
+
setQuery(query) {
|
|
134
|
+
if (query === this.query)
|
|
135
|
+
return;
|
|
136
|
+
this.query = query;
|
|
137
|
+
this.beginSearch();
|
|
138
|
+
}
|
|
139
|
+
/** Ctrl+G: охват текущий ↔ все проекты; открытая выдача перезапрашивается. */
|
|
140
|
+
toggleScope() {
|
|
141
|
+
this.scopeMode = this.scopeMode === 'current' ? 'global' : 'current';
|
|
142
|
+
this.beginSearch();
|
|
143
|
+
}
|
|
144
|
+
/** PgDn на последней загруженной строке и наличии cursor — догрузка следующей страницы. */
|
|
145
|
+
requestMore() {
|
|
146
|
+
if (this.disposed || this.usedFallback || this.loading || this.cursor === null)
|
|
147
|
+
return;
|
|
148
|
+
if (this.focused.peek() >= this.rowsState.length - 1)
|
|
149
|
+
void this.runRemote(this.epoch, this.cursor, true);
|
|
150
|
+
}
|
|
151
|
+
dispose() {
|
|
152
|
+
if (this.disposed)
|
|
153
|
+
return;
|
|
154
|
+
this.disposed = true;
|
|
155
|
+
this.cancelRequest();
|
|
156
|
+
}
|
|
157
|
+
beginSearch() {
|
|
158
|
+
this.epoch += 1;
|
|
159
|
+
this.cancelRequest();
|
|
160
|
+
this.cursor = null;
|
|
161
|
+
this.complete = true;
|
|
162
|
+
this.contentSearched = false;
|
|
163
|
+
this.loading = false;
|
|
164
|
+
this.notice = null;
|
|
165
|
+
this.applyFallback();
|
|
166
|
+
this.publish();
|
|
167
|
+
const query = this.query.trim();
|
|
168
|
+
if (query.length === 0)
|
|
169
|
+
return;
|
|
170
|
+
const epoch = this.epoch;
|
|
171
|
+
this.timer = setTimeout(() => {
|
|
172
|
+
this.timer = null;
|
|
173
|
+
void this.runRemote(epoch, null, false);
|
|
174
|
+
}, this.debounceMs);
|
|
175
|
+
// CLI живёт без таймеров: отложенный запрос не должен держать процесс.
|
|
176
|
+
this.timer.unref?.();
|
|
177
|
+
}
|
|
178
|
+
/** Мгновенный ответ без сети: совпадения по названию и проекту из загруженного каталога. */
|
|
179
|
+
applyFallback() {
|
|
180
|
+
const query = this.query.trim();
|
|
181
|
+
this.usedFallback = true;
|
|
182
|
+
if (query.length === 0) {
|
|
183
|
+
this.rowsState = [];
|
|
184
|
+
this.scopesLoaded = 0;
|
|
185
|
+
this.scopesTotal = 0;
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const outcome = this.catalog.searchChats(query);
|
|
189
|
+
const currentProject = this.context().projectId;
|
|
190
|
+
const ids = this.scopeMode === 'current'
|
|
191
|
+
? outcome.chatIds.filter((id) => (this.catalog.chat(id)?.projectId ?? null) === currentProject)
|
|
192
|
+
: outcome.chatIds;
|
|
193
|
+
this.rowsState = ids.map((id) => this.rowFromCatalog(id, query));
|
|
194
|
+
this.complete = outcome.complete;
|
|
195
|
+
this.scopesLoaded = outcome.scopesLoaded;
|
|
196
|
+
this.scopesTotal = outcome.scopesTotal;
|
|
197
|
+
}
|
|
198
|
+
rowFromCatalog(chatId, query) {
|
|
199
|
+
const chat = this.catalog.chat(chatId);
|
|
200
|
+
return {
|
|
201
|
+
chatId,
|
|
202
|
+
name: chat?.name ?? 'Без названия',
|
|
203
|
+
scopeName: chat?.projectId
|
|
204
|
+
? this.catalog.project(chat.projectId)?.name ?? chat.projectId
|
|
205
|
+
: PERSONAL_NAME,
|
|
206
|
+
dateText: relTimeText(chat?.updatedAt ?? null, this.now()),
|
|
207
|
+
nameMatch: matchRange(chat?.name ?? '', query),
|
|
208
|
+
snippet: null,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
rowFromItem(item, query) {
|
|
212
|
+
const chat = item.chat;
|
|
213
|
+
if (chat === null || typeof chat.id !== 'string' || chat.id.length === 0)
|
|
214
|
+
return null;
|
|
215
|
+
const name = typeof chat.name === 'string' && chat.name.length > 0 ? chat.name : 'Без названия';
|
|
216
|
+
const match = item.match ?? null;
|
|
217
|
+
return {
|
|
218
|
+
chatId: chat.id,
|
|
219
|
+
name,
|
|
220
|
+
scopeName: typeof item.projectName === 'string' && item.projectName.length > 0
|
|
221
|
+
? item.projectName
|
|
222
|
+
: chat.projectId
|
|
223
|
+
? this.catalog.project(chat.projectId)?.name ?? chat.projectId
|
|
224
|
+
: PERSONAL_NAME,
|
|
225
|
+
dateText: relTimeText(typeof chat.updatedAt === 'string' ? chat.updatedAt : null, this.now()),
|
|
226
|
+
nameMatch: matchRange(name, query),
|
|
227
|
+
snippet: match === null || match.parts === undefined ? null : snippetSegments(match.parts),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/** Параметры запроса по охвату: проект, «Личное» (без projectId) или все проекты. */
|
|
231
|
+
params(query, cursor) {
|
|
232
|
+
if (this.scopeMode === 'global')
|
|
233
|
+
return { q: query, global: true, limit: SEARCH_LIMIT, cursor };
|
|
234
|
+
const projectId = this.context().projectId;
|
|
235
|
+
if (projectId === null)
|
|
236
|
+
return { q: query, limit: SEARCH_LIMIT, cursor };
|
|
237
|
+
return { q: query, projectId, limit: SEARCH_LIMIT, cursor };
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Удалённый запрос. Ключ — epoch: ответ (и ошибка) применяется, только если epoch всё ещё
|
|
241
|
+
* текущий. Abort уходит в сеть, но поздний ответ, успевший прийти, тоже отбрасывается:
|
|
242
|
+
* снятие любой из двух защит делает выдачу гонкой.
|
|
243
|
+
*/
|
|
244
|
+
async runRemote(epoch, cursor, append) {
|
|
245
|
+
if (this.disposed || epoch !== this.epoch)
|
|
246
|
+
return;
|
|
247
|
+
const query = this.query.trim();
|
|
248
|
+
if (query.length === 0)
|
|
249
|
+
return;
|
|
250
|
+
this.abortRequest();
|
|
251
|
+
const controller = new AbortController();
|
|
252
|
+
this.abort = controller;
|
|
253
|
+
this.loading = true;
|
|
254
|
+
this.notice = null;
|
|
255
|
+
this.publish();
|
|
256
|
+
try {
|
|
257
|
+
const response = await this.transport(query, this.params(query, cursor), controller.signal);
|
|
258
|
+
if (epoch !== this.epoch || this.disposed)
|
|
259
|
+
return; // поздний ответ свежую выдачу не трогает
|
|
260
|
+
this.applyResponse(response, append);
|
|
261
|
+
}
|
|
262
|
+
catch (err) {
|
|
263
|
+
if (epoch !== this.epoch || controller.signal.aborted || this.disposed)
|
|
264
|
+
return; // поздняя ошибка — тихо
|
|
265
|
+
this.loading = false;
|
|
266
|
+
this.notice = searchFailureText(err);
|
|
267
|
+
this.publish();
|
|
268
|
+
}
|
|
269
|
+
finally {
|
|
270
|
+
if (this.abort === controller)
|
|
271
|
+
this.abort = null;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
applyResponse(response, append) {
|
|
275
|
+
const query = this.query.trim();
|
|
276
|
+
const incoming = response.items
|
|
277
|
+
.map((item) => this.rowFromItem(item, query))
|
|
278
|
+
.filter((row) => row !== null);
|
|
279
|
+
if (append) {
|
|
280
|
+
const before = this.rowsState.length;
|
|
281
|
+
const known = new Set(this.rowsState.map((row) => row.chatId));
|
|
282
|
+
this.rowsState = [...this.rowsState, ...incoming.filter((row) => !known.has(row.chatId))];
|
|
283
|
+
// Догрузка пришла с PgDn на последней строке: выбор переходит на первую новую, иначе
|
|
284
|
+
// она осталась бы за нижним краем окна, а Enter открывал бы прежнюю строку.
|
|
285
|
+
if (before > 0 && this.focused.peek() >= before - 1 && this.rowsState.length > before) {
|
|
286
|
+
this.focused.set(before);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
this.rowsState = incoming;
|
|
291
|
+
}
|
|
292
|
+
this.cursor = typeof response.nextCursor === 'string' && response.nextCursor.length > 0 ? response.nextCursor : null;
|
|
293
|
+
this.complete = response.complete === true;
|
|
294
|
+
this.contentSearched = response.contentSearched === true;
|
|
295
|
+
this.loading = false;
|
|
296
|
+
this.notice = null;
|
|
297
|
+
this.usedFallback = false;
|
|
298
|
+
this.publish();
|
|
299
|
+
}
|
|
300
|
+
abortRequest() {
|
|
301
|
+
if (this.abort !== null) {
|
|
302
|
+
this.abort.abort();
|
|
303
|
+
this.abort = null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
cancelRequest() {
|
|
307
|
+
this.abortRequest();
|
|
308
|
+
if (this.timer !== null) {
|
|
309
|
+
clearTimeout(this.timer);
|
|
310
|
+
this.timer = null;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
publish() {
|
|
314
|
+
if (this.disposed)
|
|
315
|
+
return;
|
|
316
|
+
this.rows.set([...this.rowsState]);
|
|
317
|
+
this.focused.set(clampIndex(this.focused.peek(), this.rowsState.length));
|
|
318
|
+
this.footer.set(this.footerText());
|
|
319
|
+
this.title.set(this.titleText());
|
|
320
|
+
}
|
|
321
|
+
titleText() {
|
|
322
|
+
const scopeTitle = this.scopeMode === 'global'
|
|
323
|
+
? 'все проекты'
|
|
324
|
+
: this.context().projectId === null
|
|
325
|
+
? PERSONAL_NAME
|
|
326
|
+
: this.context().projectName !== ''
|
|
327
|
+
? this.context().projectName
|
|
328
|
+
: PERSONAL_NAME;
|
|
329
|
+
return `Поиск чатов · ${scopeTitle}`;
|
|
330
|
+
}
|
|
331
|
+
/** Футер: счётчик, честная неполнота и отказ — без «больше нет» и без обещаний content-поиска. */
|
|
332
|
+
footerText() {
|
|
333
|
+
if (this.notice !== null)
|
|
334
|
+
return `! ${this.notice}`;
|
|
335
|
+
if (this.loading)
|
|
336
|
+
return 'Ищу по названиям и сообщениям…';
|
|
337
|
+
if (this.rowsState.length === 0) {
|
|
338
|
+
if (this.query.trim().length === 0)
|
|
339
|
+
return 'Введите название или фразу — поиск по названиям и сообщениям.';
|
|
340
|
+
return `По «${this.query.trim()}» ничего не найдено. Ctrl+G расширяет охват.`;
|
|
341
|
+
}
|
|
342
|
+
if (!this.complete) {
|
|
343
|
+
if (this.usedFallback && this.scopeMode === 'global') {
|
|
344
|
+
return `проверено ${this.scopesLoaded} из ${this.scopesTotal} проектов · результаты неполные`;
|
|
345
|
+
}
|
|
346
|
+
return `${pluralChats(this.rowsState.length)} · результаты неполные`;
|
|
347
|
+
}
|
|
348
|
+
if (!this.contentSearched)
|
|
349
|
+
return `${pluralChats(this.rowsState.length)} · по названиям`;
|
|
350
|
+
return `${pluralChats(this.rowsState.length)} · названия и сообщения`;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/** Обрезка сегментов по ширине кадра без разрыва широких символов. */
|
|
354
|
+
function fitRuns(runs, maxWidth) {
|
|
355
|
+
const out = [];
|
|
356
|
+
let used = 0;
|
|
357
|
+
for (const run of runs) {
|
|
358
|
+
if (used >= maxWidth)
|
|
359
|
+
break;
|
|
360
|
+
let text = '';
|
|
361
|
+
for (const ch of run.text) {
|
|
362
|
+
const width = stringWidth(ch);
|
|
363
|
+
if (used + width > maxWidth)
|
|
364
|
+
break;
|
|
365
|
+
text += ch;
|
|
366
|
+
used += width;
|
|
367
|
+
}
|
|
368
|
+
if (text.length > 0)
|
|
369
|
+
out.push({ ...run, text });
|
|
370
|
+
if (used >= maxWidth)
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
return out;
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Список выдачи: строка чата занимает первую линию (имя слева, проект и дата справа),
|
|
377
|
+
* фрагмент найденного сообщения — вторую линию под ней. Мета не прячется за фрагментом:
|
|
378
|
+
* в глобальной выдаче по ней различаются одноимённые проекты. Подчёркивание — только на
|
|
379
|
+
* совпавшем сегменте. Фокус остаётся в поле ввода (focusable=false, grabsFocus=false):
|
|
380
|
+
* клавиши навигации приходят из Dialog'а, и набор запроса не прерывается. ↑/↓, PgUp/PgDn,
|
|
381
|
+
* Enter, мышь.
|
|
382
|
+
*/
|
|
383
|
+
export class SearchRows extends View {
|
|
384
|
+
items;
|
|
385
|
+
focusedSignal;
|
|
386
|
+
selectedSignal;
|
|
387
|
+
onActivate;
|
|
388
|
+
onPageEnd;
|
|
389
|
+
top = 0;
|
|
390
|
+
constructor(opts) {
|
|
391
|
+
super();
|
|
392
|
+
this.items = opts.items;
|
|
393
|
+
this.focusedSignal = opts.focused;
|
|
394
|
+
this.selectedSignal = signal(-1);
|
|
395
|
+
this.onActivate = opts.onActivate;
|
|
396
|
+
this.onPageEnd = opts.onPageEnd;
|
|
397
|
+
this.focusable = false;
|
|
398
|
+
this.grabsFocus = false;
|
|
399
|
+
// onMount — регистрация хука, не переопределяемый метод: bind живёт в scope вида.
|
|
400
|
+
this.onMount(() => {
|
|
401
|
+
this.bind(() => {
|
|
402
|
+
this.items();
|
|
403
|
+
this.focusedSignal();
|
|
404
|
+
this.selectedSignal();
|
|
405
|
+
});
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
/** Переместить выбор на delta строк. */
|
|
409
|
+
move(delta) {
|
|
410
|
+
const range = this.items().length;
|
|
411
|
+
if (range === 0)
|
|
412
|
+
return;
|
|
413
|
+
this.focusedSignal.set(clampIndex(this.focusedSignal() + delta, range));
|
|
414
|
+
this.invalidate();
|
|
415
|
+
}
|
|
416
|
+
pageUp() {
|
|
417
|
+
this.move(-this.pageSize());
|
|
418
|
+
}
|
|
419
|
+
/** PgDn: страница вперёд; на последней загруженной строке — догрузка по cursor. */
|
|
420
|
+
pageDown() {
|
|
421
|
+
const range = this.items().length;
|
|
422
|
+
if (range === 0)
|
|
423
|
+
return;
|
|
424
|
+
const current = clampIndex(this.focusedSignal(), range);
|
|
425
|
+
if (current >= range - 1) {
|
|
426
|
+
this.onPageEnd();
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
this.focusedSignal.set(clampIndex(current + this.pageSize(), range));
|
|
430
|
+
this.invalidate();
|
|
431
|
+
}
|
|
432
|
+
/** Enter: открыть выбранную строку. */
|
|
433
|
+
activate() {
|
|
434
|
+
const rows = this.items();
|
|
435
|
+
const row = rows[clampIndex(this.focusedSignal(), rows.length)];
|
|
436
|
+
if (row !== undefined)
|
|
437
|
+
this.onActivate(row);
|
|
438
|
+
}
|
|
439
|
+
onEvent(ev) {
|
|
440
|
+
const inner = ev.event;
|
|
441
|
+
if (inner.type === 'wheel') {
|
|
442
|
+
this.move(inner.dir === 'up' ? -1 : 1);
|
|
443
|
+
ev.handled = true;
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (inner.type === 'mouse' && inner.kind === 'down' && ev.local !== undefined) {
|
|
447
|
+
const index = this.itemAtLine(this.top + ev.local.y);
|
|
448
|
+
if (index !== null) {
|
|
449
|
+
this.focusedSignal.set(index);
|
|
450
|
+
this.selectedSignal.set(index);
|
|
451
|
+
if (ev.clickCount === 2)
|
|
452
|
+
this.activate();
|
|
453
|
+
ev.handled = true;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
draw(ctx) {
|
|
458
|
+
const rows = this.items();
|
|
459
|
+
const range = rows.length;
|
|
460
|
+
const height = ctx.size.height;
|
|
461
|
+
const width = ctx.size.width;
|
|
462
|
+
const normal = ctx.color('listNormal');
|
|
463
|
+
if (range === 0 || height <= 0 || width <= 0) {
|
|
464
|
+
ctx.fill(' ', normal);
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
const lines = this.buildLines(rows);
|
|
468
|
+
const focused = clampIndex(this.focusedSignal(), range);
|
|
469
|
+
// Линии выбранного чата: имя видно всегда, фрагмент — если хватает высоты окна.
|
|
470
|
+
let focusStart = -1;
|
|
471
|
+
let focusEnd = -1;
|
|
472
|
+
for (let at = 0; at < lines.length; at += 1) {
|
|
473
|
+
if (lines[at].index !== focused)
|
|
474
|
+
continue;
|
|
475
|
+
if (focusStart < 0)
|
|
476
|
+
focusStart = at;
|
|
477
|
+
focusEnd = at;
|
|
478
|
+
}
|
|
479
|
+
if (focusStart < this.top)
|
|
480
|
+
this.top = focusStart;
|
|
481
|
+
else if (focusEnd >= this.top + height)
|
|
482
|
+
this.top = Math.min(focusStart, focusEnd - height + 1);
|
|
483
|
+
this.top = Math.max(0, Math.min(this.top, Math.max(0, lines.length - height)));
|
|
484
|
+
const selected = this.selectedSignal();
|
|
485
|
+
for (let offset = 0; offset < height; offset += 1) {
|
|
486
|
+
const at = this.top + offset;
|
|
487
|
+
const line = at < lines.length ? lines[at] : null;
|
|
488
|
+
const role = line !== null && (line.index === focused || line.index === selected) ? 'listSelected' : 'listNormal';
|
|
489
|
+
const base = ctx.color(role);
|
|
490
|
+
ctx.fillRect(0, offset, width, 1, ' ', base);
|
|
491
|
+
if (line === null)
|
|
492
|
+
continue;
|
|
493
|
+
const isFocused = line.index === focused;
|
|
494
|
+
const textX = isFocused ? 2 : 1;
|
|
495
|
+
if (isFocused && !line.snippet)
|
|
496
|
+
ctx.text(0, offset, '>', base);
|
|
497
|
+
if (line.snippet)
|
|
498
|
+
this.drawSnippet(ctx, line.row, textX, offset, width, base);
|
|
499
|
+
else
|
|
500
|
+
this.drawName(ctx, line.row, textX, offset, width, base);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
/** Строки кадра: у чата с фрагментом их две — имя с метой и сам фрагмент. */
|
|
504
|
+
buildLines(rows) {
|
|
505
|
+
const lines = [];
|
|
506
|
+
rows.forEach((row, index) => {
|
|
507
|
+
lines.push({ row, index, snippet: false });
|
|
508
|
+
if (hasSnippet(row))
|
|
509
|
+
lines.push({ row, index, snippet: true });
|
|
510
|
+
});
|
|
511
|
+
return lines;
|
|
512
|
+
}
|
|
513
|
+
/** Номер чата по линии кадра: фрагмент кликается как та же строка. */
|
|
514
|
+
itemAtLine(line) {
|
|
515
|
+
if (line < 0)
|
|
516
|
+
return null;
|
|
517
|
+
const rows = this.items();
|
|
518
|
+
let at = 0;
|
|
519
|
+
for (let index = 0; index < rows.length; index += 1) {
|
|
520
|
+
at += hasSnippet(rows[index]) ? 2 : 1;
|
|
521
|
+
if (line < at)
|
|
522
|
+
return index;
|
|
523
|
+
}
|
|
524
|
+
return null;
|
|
525
|
+
}
|
|
526
|
+
/** Сколько строк целиком помещается в окно: фрагмент занимает отдельную линию. */
|
|
527
|
+
pageSize() {
|
|
528
|
+
const height = this.bounds.height || 1;
|
|
529
|
+
let used = 0;
|
|
530
|
+
let count = 0;
|
|
531
|
+
for (const row of this.items()) {
|
|
532
|
+
const span = hasSnippet(row) ? 2 : 1;
|
|
533
|
+
if (used + span > height)
|
|
534
|
+
break;
|
|
535
|
+
used += span;
|
|
536
|
+
count += 1;
|
|
537
|
+
}
|
|
538
|
+
return Math.max(1, count);
|
|
539
|
+
}
|
|
540
|
+
/** Первая линия чата: имя слева, проект и дата — приглушённо у правого края. */
|
|
541
|
+
drawName(ctx, row, textX, line, width, base) {
|
|
542
|
+
const avail = width - textX;
|
|
543
|
+
if (avail <= 0)
|
|
544
|
+
return;
|
|
545
|
+
const meta = this.metaRuns(row, avail);
|
|
546
|
+
const metaWidth = meta.reduce((sum, run) => sum + stringWidth(run.text), 0);
|
|
547
|
+
// Место под мету резервируется до обрезки имени: проект и дату не прячет длинное имя.
|
|
548
|
+
const bodyMax = Math.max(0, avail - (metaWidth > 0 ? metaWidth + 1 : 0));
|
|
549
|
+
let x = textX;
|
|
550
|
+
for (const run of fitRuns(this.nameRuns(row), bodyMax)) {
|
|
551
|
+
ctx.text(x, line, run.text, this.runStyle(ctx, base, run));
|
|
552
|
+
x += stringWidth(run.text);
|
|
553
|
+
}
|
|
554
|
+
let metaX = textX + Math.max(0, avail - metaWidth);
|
|
555
|
+
for (const run of meta) {
|
|
556
|
+
ctx.text(metaX, line, run.text, this.runStyle(ctx, base, run));
|
|
557
|
+
metaX += stringWidth(run.text);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/** Вторая линия чата: фрагмент найденного сообщения, совпадение — подчёркнуто. */
|
|
561
|
+
drawSnippet(ctx, row, textX, line, width, base) {
|
|
562
|
+
let x = textX;
|
|
563
|
+
for (const run of fitRuns(this.snippetRuns(row), width - textX)) {
|
|
564
|
+
ctx.text(x, line, run.text, this.runStyle(ctx, base, run));
|
|
565
|
+
x += stringWidth(run.text);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
runStyle(ctx, base, run) {
|
|
569
|
+
if (run.match)
|
|
570
|
+
return { ...base, attrs: (base.attrs ?? 0) | Attr.underline };
|
|
571
|
+
return run.muted === true ? ctx.color('listDivider') : base;
|
|
572
|
+
}
|
|
573
|
+
/** Имя с подсветкой совпадения запроса. */
|
|
574
|
+
nameRuns(row) {
|
|
575
|
+
const runs = [];
|
|
576
|
+
const range = row.nameMatch;
|
|
577
|
+
if (range === null) {
|
|
578
|
+
runs.push({ text: row.name, match: false });
|
|
579
|
+
}
|
|
580
|
+
else {
|
|
581
|
+
if (range.start > 0)
|
|
582
|
+
runs.push({ text: row.name.slice(0, range.start), match: false });
|
|
583
|
+
runs.push({ text: row.name.slice(range.start, range.end), match: true });
|
|
584
|
+
if (range.end < row.name.length)
|
|
585
|
+
runs.push({ text: row.name.slice(range.end), match: false });
|
|
586
|
+
}
|
|
587
|
+
return runs;
|
|
588
|
+
}
|
|
589
|
+
/** Фрагмент сообщения (null не встречается: вызывается только при наличии). */
|
|
590
|
+
snippetRuns(row) {
|
|
591
|
+
return (row.snippet ?? []).map((segment) => ({ text: segment.text, match: segment.match }));
|
|
592
|
+
}
|
|
593
|
+
/** Мета справа: проект и дата; на тесной ширине обрезается, но не исчезает целиком. */
|
|
594
|
+
metaRuns(row, maxWidth) {
|
|
595
|
+
const text = row.dateText.length > 0 ? `${row.scopeName} · ${row.dateText}` : row.scopeName;
|
|
596
|
+
return fitRuns([{ text, match: false, muted: true }], maxWidth);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
/** Есть ли у строки фрагмент: у такого чата в кадре две линии. */
|
|
600
|
+
function hasSnippet(row) {
|
|
601
|
+
return row.snippet !== null && row.snippet.length > 0;
|
|
602
|
+
}
|
|
603
|
+
/** Живая строка футера: Text с getter'ом, чтобы перерисовываться на сигналах сессии. */
|
|
604
|
+
export function searchFooterText(session) {
|
|
605
|
+
return new Text(() => session.footer());
|
|
606
|
+
}
|