@g9tm/lynxcontrols-code 0.0.0-stage → 2.9.0

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.
@@ -0,0 +1,69 @@
1
+ import { type ReactNode } from '@lynx-js/react';
2
+ import { type G9LogEntry, type G9LogLevel, type G9LogStore } from './model.js';
3
+ import './log-view.css';
4
+ /** What the log view says (English defaults). */
5
+ export interface G9LogViewLabels {
6
+ readonly search?: string;
7
+ /** The chip while paused; `{0}`: the lines that arrived since. Default `'Jump to latest ({0})'` / `'Jump to latest'`. */
8
+ readonly jump?: string;
9
+ /** A level chip's text. Default the level in capitals. */
10
+ readonly levels?: Partial<Record<G9LogLevel, string>>;
11
+ /** Shown when no line passes the filter. */
12
+ readonly empty?: string;
13
+ }
14
+ /** Driving the log view from code (`handleRef`). */
15
+ export interface G9LogViewHandle {
16
+ /** Scrolls to the newest line and follows again. */
17
+ jumpToLatest(): void;
18
+ /** True while the reader scrolled away from the end. */
19
+ readonly paused: boolean;
20
+ /** The selected lines, oldest first. */
21
+ getSelected(): G9LogEntry[];
22
+ /** The lines the filter shows now, oldest first (an export of what the reader sees). */
23
+ getRows(): G9LogEntry[];
24
+ clearSelection(): void;
25
+ /** Copies the selection through `onCopy` (as Ctrl+C); false when nothing is selected or there is no `onCopy`. */
26
+ copySelection(): boolean;
27
+ }
28
+ /** Props of {@link G9LogView}. */
29
+ export interface G9LogViewProps {
30
+ readonly id?: string;
31
+ readonly store: G9LogStore;
32
+ /** The levels shown (controlled) or their start (default all). */
33
+ readonly levels?: readonly G9LogLevel[];
34
+ readonly defaultLevels?: readonly G9LogLevel[];
35
+ readonly onLevelsChange?: (levels: G9LogLevel[]) => void;
36
+ /** The search (controlled) or its start. */
37
+ readonly query?: string;
38
+ readonly defaultQuery?: string;
39
+ readonly onQueryChange?: (query: string) => void;
40
+ /** The level chips and the search above the rows. Default true. */
41
+ readonly toolbar?: boolean;
42
+ /** Ctrl+C (and `copySelection`) hands the selected lines here, one per line. */
43
+ readonly onCopy?: (text: string) => void;
44
+ readonly onSelectionChange?: (entries: G9LogEntry[]) => void;
45
+ /** A double tap / click on a line. */
46
+ readonly onActivate?: (entry: G9LogEntry) => void;
47
+ /** Times in UTC. */
48
+ readonly utc?: boolean;
49
+ /** The date before the time. */
50
+ readonly showDate?: boolean;
51
+ /** The category column. Default true. */
52
+ readonly showCategory?: boolean;
53
+ /** Each level's colour (default: the theme's). */
54
+ readonly levelColors?: Partial<Record<G9LogLevel, string>>;
55
+ /** Follow the end while the reader is there. Default true. */
56
+ readonly follow?: boolean;
57
+ /** How often appended lines are shown (ms). Default 100. */
58
+ readonly batchMs?: number;
59
+ /** A row's height (px). Default 22. */
60
+ readonly rowHeight?: number;
61
+ readonly labels?: G9LogViewLabels;
62
+ readonly handleRef?: {
63
+ current: G9LogViewHandle | null;
64
+ };
65
+ readonly className?: string;
66
+ }
67
+ /** A live, virtualised log: follows the end, pauses on scroll-up, filters by level and search, copies selected rows. */
68
+ export declare function G9LogView(props: G9LogViewProps): ReactNode;
69
+ //# sourceMappingURL=log-view.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-view.d.ts","sourceRoot":"","sources":["../../src/log/log-view.tsx"],"names":[],"mappings":"AASA,OAAO,EAAQ,KAAK,SAAS,EAAwC,MAAM,gBAAgB,CAAC;AAC5F,OAAO,EAGL,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,UAAU,EAKhB,MAAM,SAAS,CAAC;AACjB,OAAO,gBAAgB,CAAC;AAExB,iDAAiD;AACjD,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,yHAAyH;IACzH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,0DAA0D;IAC1D,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;IACtD,4CAA4C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,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,CAAC;IAClD,oBAAoB;IACpB,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC;IACvB,gCAAgC;IAChC,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;IAC5B,yCAAyC;IACzC,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;IAChC,kDAAkD;IAClD,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;IAC3D,8DAA8D;IAC9D,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,4DAA4D;IAC5D,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,uCAAuC;IACvC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,CAAC,EAAE,eAAe,CAAC;IAClC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAAE,OAAO,EAAE,eAAe,GAAG,IAAI,CAAA;KAAE,CAAC;IACzD,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AA4DD,wHAAwH;AACxH,wBAAgB,SAAS,CAAC,KAAK,EAAE,cAAc,GAAG,SAAS,CAmR1D"}
@@ -0,0 +1,285 @@
1
+ import { g9SafeId, startTimer, stopTimer } from "@g9tm/lynxcontrols/base";
2
+ import { g9HeldModifiers, useG9Keys } from "@g9tm/lynxcontrols/commands";
3
+ import { G9VirtualList } from "@g9tm/lynxcontrols/list";
4
+ import { useG9Theme } from "@g9tm/lynxcontrols/provider";
5
+ import { memo, useEffect, useMemo, useRef, useState } from "@lynx-js/react";
6
+ import { formatLogEntries, formatLogTime, g9LogLevels, logFilterTest, logRuns, nextLogSelection } from "./model.jsx";
7
+ import "./log-view.css";
8
+ const LogRow = memo(function(p) {
9
+ const e = p.entry;
10
+ return <view className={`g9-log__row g9-log__row--${e.level}${p.selected ? ' g9-log__row--selected' : ''}`} style={{
11
+ height: `${p.height}px`
12
+ }} data-seq={String(e.seq)} bindtap={()=>p.onPress(e.seq)} accessibility-element={true} accessibility-label={`${p.time} ${e.level} ${e.category} ${e.message}`}>
13
+ <text className="g9-log__time">{p.time}</text>
14
+ <text className="g9-log__level" style={{
15
+ color: p.color
16
+ }}>
17
+ {e.level.toUpperCase()}
18
+ </text>
19
+ {p.showCategory ? <text className="g9-log__category" text-maxline="1">
20
+ {e.category}
21
+ </text> : null}
22
+ <text className="g9-log__message" text-maxline="1">
23
+ {logRuns(e.message, p.query).map((r, i)=>r.hit ? <text key={i} className="g9-log__hit">
24
+ {r.text}
25
+ </text> : r.text)}
26
+ </text>
27
+ </view>;
28
+ }, (a, b)=>a.entry === b.entry && a.query === b.query && a.selected === b.selected && a.color === b.color && a.time === b.time && a.showCategory === b.showCategory && a.height === b.height);
29
+ let seq = 0;
30
+ function G9LogView(props) {
31
+ var _props_rowHeight, _props_labels, _props_defaultLevels, _props_levels, _props_defaultQuery, _props_query, _labels_jump, _labels_jump1, _labels_search;
32
+ const { store } = props;
33
+ const theme = useG9Theme();
34
+ const uid = useMemo(()=>{
35
+ var _props_id;
36
+ return g9SafeId(null != (_props_id = props.id) ? _props_id : `g9log${++seq}`);
37
+ }, [
38
+ props.id
39
+ ]);
40
+ const latest = useRef(props);
41
+ latest.current = props;
42
+ const rowH = null != (_props_rowHeight = props.rowHeight) ? _props_rowHeight : 22;
43
+ const labels = null != (_props_labels = props.labels) ? _props_labels : {};
44
+ const [ownLevels, setOwnLevels] = useState(null != (_props_defaultLevels = props.defaultLevels) ? _props_defaultLevels : g9LogLevels);
45
+ const levels = null != (_props_levels = props.levels) ? _props_levels : ownLevels;
46
+ const [ownQuery, setOwnQuery] = useState(null != (_props_defaultQuery = props.defaultQuery) ? _props_defaultQuery : '');
47
+ const query = null != (_props_query = props.query) ? _props_query : ownQuery;
48
+ const levelKey = levels.join(',');
49
+ const test = useMemo(()=>logFilterTest({
50
+ levels,
51
+ query
52
+ }), [
53
+ levelKey,
54
+ query
55
+ ]);
56
+ const testRef = useRef(test);
57
+ testRef.current = test;
58
+ const toggleLevel = (l)=>{
59
+ var _props_onLevelsChange;
60
+ const next = levels.includes(l) ? levels.filter((x)=>x !== l) : g9LogLevels.filter((x)=>x === l || levels.includes(x));
61
+ if (void 0 === props.levels) setOwnLevels(next);
62
+ null == (_props_onLevelsChange = props.onLevelsChange) || _props_onLevelsChange.call(props, next);
63
+ };
64
+ const setQuery = (q)=>{
65
+ var _props_onQueryChange;
66
+ if (void 0 === props.query) setOwnQuery(q);
67
+ null == (_props_onQueryChange = props.onQueryChange) || _props_onQueryChange.call(props, q);
68
+ };
69
+ const [rows, setRowsState] = useState(()=>store.entries().filter(test));
70
+ const rowsRef = useRef(rows);
71
+ const setRows = (next)=>{
72
+ rowsRef.current = next;
73
+ setRowsState(next);
74
+ };
75
+ const pending = useRef({
76
+ added: [],
77
+ reset: false
78
+ });
79
+ const timer = useRef(null);
80
+ const [paused, setPausedState] = useState(false);
81
+ const pausedRef = useRef(false);
82
+ const [missed, setMissed] = useState(0);
83
+ const setPaused = (v)=>{
84
+ pausedRef.current = v;
85
+ setPausedState(v);
86
+ if (!v) setMissed(0);
87
+ };
88
+ const flush = ()=>{
89
+ var _ref;
90
+ var _store_at;
91
+ timer.current = null;
92
+ const p = pending.current;
93
+ pending.current = {
94
+ added: [],
95
+ reset: false
96
+ };
97
+ if (p.reset) return void setRows(store.entries().filter(testRef.current));
98
+ const oldest = null != (_ref = null == (_store_at = store.at(0)) ? void 0 : _store_at.seq) ? _ref : 1 / 0;
99
+ let next = rowsRef.current;
100
+ if (next.length > 0 && next[0].seq < oldest) next = next.filter((e)=>e.seq >= oldest);
101
+ const fresh = p.added.filter((e)=>e.seq >= oldest && testRef.current(e));
102
+ if (fresh.length > 0) next = next.concat(fresh);
103
+ if (next !== rowsRef.current) setRows(next);
104
+ if (fresh.length > 0 && pausedRef.current) setMissed((m)=>m + fresh.length);
105
+ };
106
+ useEffect(()=>{
107
+ const off = store.subscribe((change)=>{
108
+ var _latest_current_batchMs;
109
+ if (change.cleared) {
110
+ pending.current = {
111
+ added: [],
112
+ reset: true
113
+ };
114
+ setSelected([]);
115
+ } else for (const e of change.added)pending.current.added.push(e);
116
+ if (null === timer.current) timer.current = startTimer(flush, null != (_latest_current_batchMs = latest.current.batchMs) ? _latest_current_batchMs : 100);
117
+ });
118
+ const now = store.entries().filter(testRef.current);
119
+ const had = rowsRef.current;
120
+ if (now.length !== had.length || now[now.length - 1] !== had[had.length - 1] || now[0] !== had[0]) setRows(now);
121
+ return ()=>{
122
+ off();
123
+ stopTimer(timer.current);
124
+ timer.current = null;
125
+ };
126
+ }, [
127
+ store
128
+ ]);
129
+ const firstFilter = useRef(true);
130
+ useEffect(()=>{
131
+ if (firstFilter.current) {
132
+ firstFilter.current = false;
133
+ return;
134
+ }
135
+ setRows(store.entries().filter(test));
136
+ }, [
137
+ test
138
+ ]);
139
+ const [selected, setSelectedState] = useState([]);
140
+ const selectedRef = useRef(selected);
141
+ const anchor = useRef(null);
142
+ const setSelected = (next)=>{
143
+ var _latest_current_onSelectionChange, _latest_current;
144
+ selectedRef.current = next;
145
+ setSelectedState(next);
146
+ const set = new Set(next);
147
+ null == (_latest_current_onSelectionChange = (_latest_current = latest.current).onSelectionChange) || _latest_current_onSelectionChange.call(_latest_current, rowsRef.current.filter((e)=>set.has(e.seq)));
148
+ };
149
+ const selectedEntries = ()=>{
150
+ const set = new Set(selectedRef.current);
151
+ return store.entries().filter((e)=>set.has(e.seq));
152
+ };
153
+ const copySelection = ()=>{
154
+ const onCopy = latest.current.onCopy;
155
+ const list = selectedEntries();
156
+ if (!onCopy || 0 === list.length) return false;
157
+ onCopy(formatLogEntries(list, {
158
+ utc: latest.current.utc,
159
+ date: latest.current.showDate
160
+ }));
161
+ return true;
162
+ };
163
+ const [active, setActive] = useState(false);
164
+ const lastPress = useRef({
165
+ seq: -1,
166
+ at: 0
167
+ });
168
+ const onPress = (s)=>{
169
+ setActive(true);
170
+ const now = Date.now();
171
+ const double = lastPress.current.seq === s && now - lastPress.current.at < 400;
172
+ lastPress.current = {
173
+ seq: s,
174
+ at: now
175
+ };
176
+ const m = g9HeldModifiers();
177
+ const mode = m.shift ? 'range' : m.ctrl || m.meta ? 'toggle' : 'single';
178
+ setSelected(nextLogSelection(selectedRef.current, rowsRef.current, s, mode, anchor.current));
179
+ if ('range' !== mode) anchor.current = s;
180
+ if (double) {
181
+ var _latest_current_onActivate, _latest_current;
182
+ const e = rowsRef.current.find((x)=>x.seq === s);
183
+ if (e) null == (_latest_current_onActivate = (_latest_current = latest.current).onActivate) || _latest_current_onActivate.call(_latest_current, e);
184
+ }
185
+ };
186
+ useG9Keys((e)=>{
187
+ const mod = e.ctrl || e.meta;
188
+ const k = 1 === e.key.length ? e.key.toLowerCase() : e.key;
189
+ if (mod && 'c' === k) return copySelection() || selectedRef.current.length > 0;
190
+ if (mod && 'a' === k) {
191
+ setSelected(rowsRef.current.map((x)=>x.seq));
192
+ return true;
193
+ }
194
+ if ('Escape' === k && selectedRef.current.length > 0) {
195
+ setSelected([]);
196
+ return true;
197
+ }
198
+ if ('End' === k && mod) {
199
+ jumpToLatest();
200
+ return true;
201
+ }
202
+ return false;
203
+ }, {
204
+ enabled: active
205
+ });
206
+ const list = useRef(null);
207
+ const follow = false !== props.follow;
208
+ const jumpToLatest = ()=>{
209
+ var _list_current;
210
+ setPaused(false);
211
+ null == (_list_current = list.current) || _list_current.scrollToEnd({
212
+ smooth: false
213
+ });
214
+ };
215
+ const onVisible = (info)=>{
216
+ if (!follow) return;
217
+ const away = info.distanceToEnd > 1.5 * rowH;
218
+ if (away !== pausedRef.current) setPaused(away);
219
+ };
220
+ if (props.handleRef) props.handleRef.current = {
221
+ jumpToLatest,
222
+ get paused () {
223
+ return pausedRef.current;
224
+ },
225
+ getSelected: selectedEntries,
226
+ getRows: ()=>rowsRef.current.slice(),
227
+ clearSelection: ()=>setSelected([]),
228
+ copySelection
229
+ };
230
+ const p = theme.palette;
231
+ const colors = useMemo(()=>{
232
+ var _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
233
+ var _props_levelColors, _props_levelColors1, _props_levelColors2, _props_levelColors3, _props_levelColors4, _props_levelColors5;
234
+ return {
235
+ trace: null != (_ref = null == (_props_levelColors = props.levelColors) ? void 0 : _props_levelColors.trace) ? _ref : p.Outline,
236
+ debug: null != (_ref1 = null == (_props_levelColors1 = props.levelColors) ? void 0 : _props_levelColors1.debug) ? _ref1 : p.OnSurfaceVariant,
237
+ info: null != (_ref2 = null == (_props_levelColors2 = props.levelColors) ? void 0 : _props_levelColors2.info) ? _ref2 : p.Primary,
238
+ warn: null != (_ref3 = null == (_props_levelColors3 = props.levelColors) ? void 0 : _props_levelColors3.warn) ? _ref3 : p.Warning,
239
+ error: null != (_ref4 = null == (_props_levelColors4 = props.levelColors) ? void 0 : _props_levelColors4.error) ? _ref4 : p.Error,
240
+ fatal: null != (_ref5 = null == (_props_levelColors5 = props.levelColors) ? void 0 : _props_levelColors5.fatal) ? _ref5 : p.Error
241
+ };
242
+ }, [
243
+ p,
244
+ props.levelColors
245
+ ]);
246
+ const selSet = useMemo(()=>new Set(selected), [
247
+ selected
248
+ ]);
249
+ const showCategory = false !== props.showCategory;
250
+ const jumpText = missed > 0 ? (null != (_labels_jump = labels.jump) ? _labels_jump : 'Jump to latest ({0})').replace('{0}', String(missed)) : (null != (_labels_jump1 = labels.jump) ? _labels_jump1 : 'Jump to latest').replace(/\s*\(?\{0\}\)?/, '');
251
+ return <view id={uid} className={`g9-log${props.className ? ` ${props.className}` : ''}`} style={{
252
+ direction: 'ltr'
253
+ }}>
254
+ {false === props.toolbar ? null : <view className="g9-log__toolbar">
255
+ {g9LogLevels.map((l)=>{
256
+ var _ref, _ref1;
257
+ var _labels_levels, _labels_levels1;
258
+ const on = levels.includes(l);
259
+ return <view key={l} id={`${uid}__level_${l}`} className={`g9-log__chip${on ? ' g9-log__chip--on' : ''}`} style={on ? {
260
+ borderColor: colors[l]
261
+ } : {}} bindtap={()=>toggleLevel(l)} accessibility-element={true} accessibility-label={null != (_ref = null == (_labels_levels = labels.levels) ? void 0 : _labels_levels[l]) ? _ref : l.toUpperCase()} accessibility-traits="button">
262
+ <view className="g9-log__chip-dot" style={{
263
+ backgroundColor: colors[l]
264
+ }}/>
265
+ <text className="g9-log__chip-text">{null != (_ref1 = null == (_labels_levels1 = labels.levels) ? void 0 : _labels_levels1[l]) ? _ref1 : l.toUpperCase()}</text>
266
+ </view>;
267
+ })}
268
+ <input id={`${uid}__search`} className="g9-log__search" {...{
269
+ value: query
270
+ }} placeholder={null != (_labels_search = labels.search) ? _labels_search : 'Search'} confirm-type="search" bindinput={(e)=>setQuery(e.detail.value)}/>
271
+ </view>}
272
+ <view className="g9-log__body">
273
+ <G9VirtualList id={`${uid}__list`} className="g9-log__list" items={rows} getKey={(e)=>String(e.seq)} estimatedSize={rowH} startAtEnd={follow} followEnd={follow} settle={false} handleRef={list} onVisibleChange={onVisible} empty={labels.empty ? <view className="g9-log__empty">
274
+ <text className="g9-log__empty-text">{labels.empty}</text>
275
+ </view> : void 0} renderItem={(e)=><LogRow entry={e} query={query} selected={selSet.has(e.seq)} color={colors[e.level]} time={formatLogTime(e.time, {
276
+ utc: props.utc,
277
+ date: props.showDate
278
+ })} showCategory={showCategory} height={rowH} onPress={onPress}/>}/>
279
+ {follow && paused ? <view id={`${uid}__jump`} className="g9-log__jump" bindtap={jumpToLatest} accessibility-element={true} accessibility-label={jumpText} accessibility-traits="button">
280
+ <text className="g9-log__jump-text">{jumpText}</text>
281
+ </view> : null}
282
+ </view>
283
+ </view>;
284
+ }
285
+ export { G9LogView };
@@ -0,0 +1,91 @@
1
+ /** The six levels, least to most severe. */
2
+ export type G9LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
3
+ /** Every level in order. */
4
+ export declare const g9LogLevels: readonly G9LogLevel[];
5
+ /** A line the app appends. `time`: ms since the epoch (a `Date` works too). */
6
+ export interface G9LogInput {
7
+ readonly time: number | Date;
8
+ readonly level: G9LogLevel;
9
+ readonly category?: string;
10
+ readonly message: string;
11
+ }
12
+ /** A stored line: the input with its sequence number (unique and rising for the store's life; the row's key). */
13
+ export interface G9LogEntry {
14
+ readonly seq: number;
15
+ readonly time: number;
16
+ readonly level: G9LogLevel;
17
+ readonly category: string;
18
+ readonly message: string;
19
+ }
20
+ /**
21
+ * What a store change was: the lines added at the end that it keeps, how many older lines the cap dropped from the
22
+ * start, or a clear.
23
+ */
24
+ export interface G9LogChange {
25
+ readonly added: readonly G9LogEntry[];
26
+ readonly dropped: number;
27
+ readonly cleared: boolean;
28
+ }
29
+ /** The severity rank of a level (trace 0 … fatal 5); an unknown level counts as info. */
30
+ export declare function logLevelRank(level: string): number;
31
+ /**
32
+ * A bounded, append-only log: the newest `capacity` lines (default 50 000), the oldest dropped. `append` costs only
33
+ * the new lines; listeners hear each change at once (a view coalesces them).
34
+ */
35
+ export declare class G9LogStore {
36
+ private items;
37
+ private start;
38
+ private nextSeq;
39
+ private readonly listeners;
40
+ readonly capacity: number;
41
+ constructor(options?: {
42
+ readonly capacity?: number;
43
+ });
44
+ /** How many lines it holds. */
45
+ get size(): number;
46
+ /** The line at an index (0: the oldest kept). */
47
+ at(index: number): G9LogEntry | undefined;
48
+ /** The kept lines, oldest first (a copy). */
49
+ entries(): G9LogEntry[];
50
+ /** Adds one line or many at the end; answers the stored lines. */
51
+ append(input: G9LogInput | readonly G9LogInput[]): G9LogEntry[];
52
+ /** Removes every line (sequence numbers keep rising). */
53
+ clear(): void;
54
+ /** Hears every change; answers the unsubscribe. */
55
+ subscribe(listener: (change: G9LogChange) => void): () => void;
56
+ private emit;
57
+ }
58
+ /** What a view shows: the levels on (all when omitted) and a search (case-insensitive, in category and message). */
59
+ export interface G9LogFilter {
60
+ readonly levels?: ReadonlySet<G9LogLevel> | readonly G9LogLevel[];
61
+ readonly query?: string;
62
+ }
63
+ /** A filter as one fast test. */
64
+ export declare function logFilterTest(filter: G9LogFilter): (entry: G9LogEntry) => boolean;
65
+ /** The lines a filter keeps, oldest first. */
66
+ export declare function filterLog(entries: readonly G9LogEntry[], filter: G9LogFilter): G9LogEntry[];
67
+ /** Where a search hits a text (case-insensitive, not overlapping): [start, end) pairs. */
68
+ export declare function logHighlights(text: string, query: string): Array<readonly [number, number]>;
69
+ /** A text cut into plain and hit runs by {@link logHighlights}. */
70
+ export declare function logRuns(text: string, query: string): Array<{
71
+ readonly text: string;
72
+ readonly hit: boolean;
73
+ }>;
74
+ /** Options of {@link formatLogTime}. */
75
+ export interface G9LogTimeOptions {
76
+ /** UTC instead of local time. */
77
+ readonly utc?: boolean | undefined;
78
+ /** `.mmm` after the seconds. Default true. */
79
+ readonly millis?: boolean | undefined;
80
+ /** `YYYY-MM-DD ` in front. */
81
+ readonly date?: boolean | undefined;
82
+ }
83
+ /** A time as `HH:MM:SS.mmm` (24 h, ASCII digits — a log is read and pasted as code). */
84
+ export declare function formatLogTime(time: number, options?: G9LogTimeOptions): string;
85
+ /** One line as copied: `time LEVEL [category] message`. */
86
+ export declare function formatLogEntry(entry: G9LogEntry, options?: Omit<G9LogTimeOptions, 'millis'>): string;
87
+ /** Lines as copied, one per line, oldest first. */
88
+ export declare function formatLogEntries(entries: readonly G9LogEntry[], options?: Omit<G9LogTimeOptions, 'millis'>): string;
89
+ /** The selection after a click on a line: alone, added / removed (`toggle`, Ctrl), or the range from `anchor` (Shift). */
90
+ export declare function nextLogSelection(selected: readonly number[], visible: readonly G9LogEntry[], seq: number, mode: 'single' | 'toggle' | 'range', anchor: number | null): number[];
91
+ //# sourceMappingURL=model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/log/model.ts"],"names":[],"mappings":"AAIA,4CAA4C;AAC5C,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG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CAAC;IACnC,8CAA8C;IAC9C,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACtC,8BAA8B;IAC9B,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;CACrC;AAED,wFAAwF;AACxF,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAgBlF;AAED,2DAA2D;AAC3D,wBAAgB,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,GAAE,IAAI,CAAC,gBAAgB,EAAE,QAAQ,CAAM,GAAG,MAAM,CAGxG;AAED,mDAAmD;AACnD,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,SAAS,UAAU,EAAE,EAC9B,OAAO,GAAE,IAAI,CAAC,gBAAgB,EAAE,QAAQ,CAAM,GAC7C,MAAM,CAKR;AAED,0HAA0H;AAC1H,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,SAAS,MAAM,EAAE,EAC3B,OAAO,EAAE,SAAS,UAAU,EAAE,EAC9B,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,OAAO,EACnC,MAAM,EAAE,MAAM,GAAG,IAAI,GACpB,MAAM,EAAE,CAQV"}
@@ -0,0 +1,196 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) Object.defineProperty(obj, key, {
3
+ value: value,
4
+ enumerable: true,
5
+ configurable: true,
6
+ writable: true
7
+ });
8
+ else obj[key] = value;
9
+ return obj;
10
+ }
11
+ const g9LogLevels = [
12
+ 'trace',
13
+ 'debug',
14
+ 'info',
15
+ 'warn',
16
+ 'error',
17
+ 'fatal'
18
+ ];
19
+ function logLevelRank(level) {
20
+ const i = g9LogLevels.indexOf(level);
21
+ return i < 0 ? 2 : i;
22
+ }
23
+ class G9LogStore {
24
+ get size() {
25
+ return this.items.length - this.start;
26
+ }
27
+ at(index) {
28
+ return index < 0 || index >= this.size ? void 0 : this.items[this.start + index];
29
+ }
30
+ entries() {
31
+ return this.items.slice(this.start);
32
+ }
33
+ append(input) {
34
+ const list = Array.isArray(input) ? input : [
35
+ input
36
+ ];
37
+ if (0 === list.length) return [];
38
+ const added = list.map((l)=>{
39
+ var _l_category;
40
+ return {
41
+ seq: this.nextSeq++,
42
+ time: l.time instanceof Date ? l.time.getTime() : l.time,
43
+ level: l.level,
44
+ category: null != (_l_category = l.category) ? _l_category : '',
45
+ message: l.message
46
+ };
47
+ });
48
+ const before = this.size;
49
+ for (const e of added)this.items.push(e);
50
+ const over = this.size - this.capacity;
51
+ if (over > 0) {
52
+ this.start += over;
53
+ if (this.start >= this.capacity) {
54
+ this.items = this.items.slice(this.start);
55
+ this.start = 0;
56
+ }
57
+ }
58
+ const kept = over > 0 ? added.slice(Math.max(0, added.length - this.capacity)) : added;
59
+ const dropped = over > 0 ? Math.min(before, over) : 0;
60
+ this.emit({
61
+ added: kept,
62
+ dropped,
63
+ cleared: false
64
+ });
65
+ return added;
66
+ }
67
+ clear() {
68
+ this.items = [];
69
+ this.start = 0;
70
+ this.emit({
71
+ added: [],
72
+ dropped: 0,
73
+ cleared: true
74
+ });
75
+ }
76
+ subscribe(listener) {
77
+ this.listeners.add(listener);
78
+ return ()=>{
79
+ this.listeners.delete(listener);
80
+ };
81
+ }
82
+ emit(change) {
83
+ for (const l of [
84
+ ...this.listeners
85
+ ])l(change);
86
+ }
87
+ constructor(options = {}){
88
+ var _options_capacity;
89
+ _define_property(this, "items", []);
90
+ _define_property(this, "start", 0);
91
+ _define_property(this, "nextSeq", 1);
92
+ _define_property(this, "listeners", new Set());
93
+ _define_property(this, "capacity", void 0);
94
+ this.capacity = Math.max(1, Math.floor(null != (_options_capacity = options.capacity) ? _options_capacity : 50000));
95
+ }
96
+ }
97
+ function logFilterTest(filter) {
98
+ var _filter_query;
99
+ const lv = filter.levels;
100
+ const levels = void 0 === lv ? null : lv instanceof Set ? lv : new Set(lv);
101
+ const q = (null != (_filter_query = filter.query) ? _filter_query : '').trim().toLowerCase();
102
+ if (!levels && !q) return ()=>true;
103
+ return (e)=>(!levels || levels.has(e.level)) && (!q || e.message.toLowerCase().includes(q) || e.category.toLowerCase().includes(q));
104
+ }
105
+ function filterLog(entries, filter) {
106
+ return entries.filter(logFilterTest(filter));
107
+ }
108
+ function logHighlights(text, query) {
109
+ const q = query.trim().toLowerCase();
110
+ if (!q) return [];
111
+ const t = text.toLowerCase();
112
+ const out = [];
113
+ let i = t.indexOf(q);
114
+ while(i >= 0){
115
+ out.push([
116
+ i,
117
+ i + q.length
118
+ ]);
119
+ i = t.indexOf(q, i + q.length);
120
+ }
121
+ return out;
122
+ }
123
+ function logRuns(text, query) {
124
+ const hits = logHighlights(text, query);
125
+ if (0 === hits.length) return [
126
+ {
127
+ text,
128
+ hit: false
129
+ }
130
+ ];
131
+ const out = [];
132
+ let at = 0;
133
+ for (const [a, b] of hits){
134
+ if (a > at) out.push({
135
+ text: text.slice(at, a),
136
+ hit: false
137
+ });
138
+ out.push({
139
+ text: text.slice(a, b),
140
+ hit: true
141
+ });
142
+ at = b;
143
+ }
144
+ if (at < text.length) out.push({
145
+ text: text.slice(at),
146
+ hit: false
147
+ });
148
+ return out;
149
+ }
150
+ const pad = (v, n = 2)=>String(v).padStart(n, '0');
151
+ function formatLogTime(time, options = {}) {
152
+ const d = new Date(time);
153
+ if (Number.isNaN(d.getTime())) return '--:--:--';
154
+ const u = true === options.utc;
155
+ const h = u ? d.getUTCHours() : d.getHours();
156
+ const m = u ? d.getUTCMinutes() : d.getMinutes();
157
+ const s = u ? d.getUTCSeconds() : d.getSeconds();
158
+ let out = `${pad(h)}:${pad(m)}:${pad(s)}`;
159
+ if (false !== options.millis) out += `.${pad(u ? d.getUTCMilliseconds() : d.getMilliseconds(), 3)}`;
160
+ if (options.date) {
161
+ const y = u ? d.getUTCFullYear() : d.getFullYear();
162
+ const mo = (u ? d.getUTCMonth() : d.getMonth()) + 1;
163
+ const da = u ? d.getUTCDate() : d.getDate();
164
+ out = `${y}-${pad(mo)}-${pad(da)} ${out}`;
165
+ }
166
+ return out;
167
+ }
168
+ function formatLogEntry(entry, options = {}) {
169
+ const cat = entry.category ? ` [${entry.category}]` : '';
170
+ return `${formatLogTime(entry.time, {
171
+ ...options,
172
+ millis: true
173
+ })} ${entry.level.toUpperCase().padEnd(5)}${cat} ${entry.message}`;
174
+ }
175
+ function formatLogEntries(entries, options = {}) {
176
+ return [
177
+ ...entries
178
+ ].sort((a, b)=>a.seq - b.seq).map((e)=>formatLogEntry(e, options)).join('\n');
179
+ }
180
+ function nextLogSelection(selected, visible, seq, mode, anchor) {
181
+ if ('toggle' === mode) return selected.includes(seq) ? selected.filter((s)=>s !== seq) : [
182
+ ...selected,
183
+ seq
184
+ ];
185
+ if ('range' === mode && null !== anchor) {
186
+ const a = visible.findIndex((e)=>e.seq === anchor);
187
+ const b = visible.findIndex((e)=>e.seq === seq);
188
+ if (a >= 0 && b >= 0) return visible.slice(Math.min(a, b), Math.max(a, b) + 1).map((e)=>e.seq);
189
+ }
190
+ return [
191
+ seq
192
+ ];
193
+ }
194
+ export { G9LogStore, filterLog, formatLogEntries, formatLogEntry, formatLogTime, g9LogLevels, logFilterTest, logHighlights, logLevelRank, logRuns, nextLogSelection };
195
+
196
+ //# sourceMappingURL=model.js.map