devnonla-ui 0.6.0 → 0.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "devnonla-ui",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "type": "module",
5
5
  "description": "NonlaUI — React controls for Nonla Agents",
6
6
  "author": "devlangla <devlangla0x01@gmail.com>",
package/src/index.ts CHANGED
@@ -4,6 +4,8 @@ export type { ButtonColor, ButtonGroupProps, ButtonProps, ButtonSize, ButtonType
4
4
  export { Button } from "./button/Button";
5
5
  export type { ButtonCopyProps } from "./button/ButtonCopy";
6
6
  export { ButtonCopy } from "./button/ButtonCopy";
7
+ export type { EditableInputProps, EditableKeyProps } from "./input/EditableInput";
8
+ export { EditableInput } from "./input/EditableInput";
7
9
  export type { InputNumberProps, InputProps, InputSize, PasswordProps, TextAreaProps, TextAreaRef } from "./input/Input";
8
10
  export { Input, InputNumber, TextArea } from "./input/Input";
9
11
  export type { SearchInputProps } from "./input/SearchInput";
@@ -0,0 +1,408 @@
1
+ import { Pencil } from "lucide-react";
2
+ import { type CSSProperties, cloneElement, isValidElement, type KeyboardEvent, type ReactElement, type ReactNode, type Ref, useEffect, useLayoutEffect, useRef, useState } from "react";
3
+ import { createPortal } from "react-dom";
4
+ import { usePopupContainer } from "../app/context";
5
+ import { Button } from "../button/Button";
6
+ import { cn } from "../lib/cn";
7
+ import { type CanonicalSize, type ControlSize, controlHeightVar, controlRadiusVar, getSizeTokens, useControlSize } from "../lib/sizes";
8
+ import { message } from "../message/message";
9
+
10
+ const POPUP_PAD: Record<CanonicalSize, number> = { small: 12, default: 16, large: 20 };
11
+ const FIELD_INSET: Record<CanonicalSize, string> = { small: "-4px", default: "-6px", large: "-8px" };
12
+ const MULTILINE_MIN: Record<CanonicalSize, number> = { small: 56, default: 72, large: 96 };
13
+ const GLASS_BORDER = 1;
14
+
15
+ const fieldClass = (saving: boolean) => cn("relative z-1 m-0 w-full border-0 bg-transparent text-foreground placeholder:text-muted-foreground/50 focus:outline-none", saving && "opacity-60");
16
+
17
+ type Lock = {
18
+ top: number;
19
+ left: number;
20
+ width: number;
21
+ height: number;
22
+ padTop: number;
23
+ padBottom: number;
24
+ font: string;
25
+ letterSpacing: string;
26
+ color: string;
27
+ };
28
+
29
+ function glyphEl(el: HTMLElement): HTMLElement {
30
+ let node = el;
31
+ while (node.childElementCount === 1 && node.firstElementChild instanceof HTMLElement) {
32
+ node = node.firstElementChild;
33
+ }
34
+ return node;
35
+ }
36
+
37
+ function containingOffset(container: HTMLElement) {
38
+ const cs = getComputedStyle(container);
39
+ const fixedContaining = cs.transform !== "none" || cs.perspective !== "none" || cs.filter !== "none" || cs.backdropFilter !== "none" || cs.willChange.includes("transform");
40
+ if (!fixedContaining) return { top: 0, left: 0 };
41
+ const r = container.getBoundingClientRect();
42
+ return { top: r.top, left: r.left };
43
+ }
44
+
45
+ function readLock(textEl: HTMLElement, rowEl: HTMLElement, minWidth: number | undefined): Lock {
46
+ const glyph = glyphEl(textEl);
47
+ const g = glyph.getBoundingClientRect();
48
+ const row = rowEl.getBoundingClientRect();
49
+ const cs = getComputedStyle(glyph);
50
+ const width = Math.max(g.width, row.right - g.left, minWidth ?? 0);
51
+ return {
52
+ top: row.top,
53
+ left: g.left,
54
+ width,
55
+ height: row.height,
56
+ padTop: g.top - row.top,
57
+ padBottom: row.bottom - g.bottom,
58
+ font: cs.font,
59
+ letterSpacing: cs.letterSpacing,
60
+ color: cs.color,
61
+ };
62
+ }
63
+
64
+ function EditorPopover({
65
+ textRef,
66
+ rowRef,
67
+ inputRef,
68
+ size,
69
+ multiline,
70
+ minWidth,
71
+ saving,
72
+ saveDisabled,
73
+ selectOnFocus,
74
+ onSave,
75
+ onCancel,
76
+ children,
77
+ }: {
78
+ textRef: Ref<HTMLDivElement>;
79
+ rowRef: Ref<HTMLDivElement>;
80
+ inputRef: { current: HTMLInputElement | HTMLTextAreaElement | null };
81
+ size: CanonicalSize;
82
+ multiline: boolean;
83
+ minWidth?: number;
84
+ saving: boolean;
85
+ saveDisabled?: boolean;
86
+ selectOnFocus?: boolean;
87
+ onSave: () => void;
88
+ onCancel: () => void;
89
+ children: ReactElement<{ className?: string; style?: CSSProperties; ref?: Ref<HTMLInputElement | HTMLTextAreaElement> }>;
90
+ }) {
91
+ const getContainer = usePopupContainer();
92
+ const [lock, setLock] = useState<Lock | null>(null);
93
+ const [correction, setCorrection] = useState({ x: 0, y: 0 });
94
+ const attempts = useRef(0);
95
+
96
+ useLayoutEffect(() => {
97
+ const text = typeof textRef === "object" && textRef ? textRef.current : null;
98
+ const row = typeof rowRef === "object" && rowRef ? rowRef.current : null;
99
+ if (!text || !row) return;
100
+ const sync = () => setLock((prev) => {
101
+ const next = readLock(text, row, minWidth);
102
+ if (
103
+ prev &&
104
+ Math.abs(prev.top - next.top) < 0.25 &&
105
+ Math.abs(prev.left - next.left) < 0.25 &&
106
+ Math.abs(prev.width - next.width) < 0.25 &&
107
+ Math.abs(prev.height - next.height) < 0.25 &&
108
+ Math.abs(prev.padTop - next.padTop) < 0.25 &&
109
+ Math.abs(prev.padBottom - next.padBottom) < 0.25 &&
110
+ prev.font === next.font &&
111
+ prev.letterSpacing === next.letterSpacing &&
112
+ prev.color === next.color
113
+ ) {
114
+ return prev;
115
+ }
116
+ return next;
117
+ });
118
+ sync();
119
+ const ro = new ResizeObserver(sync);
120
+ ro.observe(text);
121
+ ro.observe(row);
122
+ window.addEventListener("scroll", sync, true);
123
+ window.addEventListener("resize", sync);
124
+ return () => {
125
+ ro.disconnect();
126
+ window.removeEventListener("scroll", sync, true);
127
+ window.removeEventListener("resize", sync);
128
+ };
129
+ }, [textRef, rowRef, minWidth]);
130
+
131
+ useLayoutEffect(() => {
132
+ attempts.current = 0;
133
+ }, [lock?.top, lock?.left, lock?.padTop]);
134
+
135
+ useLayoutEffect(() => {
136
+ const text = typeof textRef === "object" && textRef ? textRef.current : null;
137
+ const input = inputRef.current;
138
+ if (!lock || !text || !input) return;
139
+ const g = glyphEl(text).getBoundingClientRect();
140
+ const box = input.getBoundingClientRect();
141
+ const cs = getComputedStyle(input);
142
+ const dx = g.left - (box.left + parseFloat(cs.paddingLeft));
143
+ const dy = g.top - (box.top + parseFloat(cs.paddingTop));
144
+ if (Math.abs(dx) < 0.25 && Math.abs(dy) < 0.25) {
145
+ attempts.current = 0;
146
+ return;
147
+ }
148
+ if (attempts.current >= 3) return;
149
+ attempts.current += 1;
150
+ setCorrection((current) => ({ x: current.x + dx, y: current.y + dy }));
151
+ }, [lock, textRef, inputRef, correction]);
152
+
153
+ useEffect(() => {
154
+ if (!lock) return;
155
+ const timer = setTimeout(() => {
156
+ const el = inputRef.current;
157
+ el?.focus();
158
+ if (selectOnFocus && el instanceof HTMLInputElement) el.select();
159
+ }, 0);
160
+ return () => clearTimeout(timer);
161
+ }, [lock != null, selectOnFocus, inputRef]);
162
+
163
+ if (!lock || !isValidElement(children)) return null;
164
+
165
+ const pad = POPUP_PAD[size];
166
+ const container = getContainer();
167
+ const origin = containingOffset(container);
168
+ const field = cloneElement(children, {
169
+ ref: inputRef,
170
+ style: {
171
+ ...children.props.style,
172
+ boxSizing: "border-box",
173
+ width: "100%",
174
+ height: multiline ? undefined : lock.height,
175
+ minHeight: multiline ? Math.max(MULTILINE_MIN[size], lock.height) : undefined,
176
+ margin: 0,
177
+ border: 0,
178
+ paddingTop: lock.padTop,
179
+ paddingRight: 0,
180
+ paddingBottom: multiline ? 8 : lock.padBottom,
181
+ paddingLeft: 0,
182
+ font: lock.font,
183
+ letterSpacing: lock.letterSpacing,
184
+ color: lock.color,
185
+ },
186
+ });
187
+
188
+ return createPortal(
189
+ <div
190
+ className="nonla-popup-layer nonla-glass outline-none"
191
+ style={{
192
+ position: "fixed",
193
+ zIndex: "var(--nonla-z-popup, 1050)",
194
+ borderRadius: 10,
195
+ top: lock.top - origin.top - pad - GLASS_BORDER + correction.y,
196
+ left: lock.left - origin.left - pad - GLASS_BORDER + correction.x,
197
+ width: lock.width + (pad + GLASS_BORDER) * 2,
198
+ padding: pad,
199
+ }}
200
+ >
201
+ <div className="relative">
202
+ <span aria-hidden className="pointer-events-none absolute top-0 bottom-0" style={{ left: FIELD_INSET[size], right: FIELD_INSET[size], borderRadius: controlRadiusVar(size), background: "color-mix(in srgb, var(--foreground) 6%, transparent)" }} />
203
+ {field}
204
+ </div>
205
+ <div className="mt-3 flex items-center gap-2">
206
+ <Button type="primary" size="small" loading={saving} disabled={saveDisabled} onClick={onSave}>
207
+ Save
208
+ </Button>
209
+ <Button type="text" size="small" disabled={saving} onClick={onCancel}>
210
+ Cancel
211
+ </Button>
212
+ </div>
213
+ </div>,
214
+ container,
215
+ );
216
+ }
217
+
218
+ function EditButton({ label, size, onClick }: { label: string; size: CanonicalSize; onClick: () => void }) {
219
+ const tok = getSizeTokens(size);
220
+ const box = tok.icon + 8;
221
+ return (
222
+ <button
223
+ type="button"
224
+ aria-label={label}
225
+ title={label}
226
+ onClick={onClick}
227
+ className="inline-flex shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/edit:opacity-100 focus-visible:opacity-100"
228
+ style={{ width: box, height: box }}
229
+ >
230
+ <Pencil size={tok.icon} />
231
+ </button>
232
+ );
233
+ }
234
+
235
+ export type EditableInputProps = {
236
+ display: ReactNode;
237
+ editing: boolean;
238
+ onStartEdit: () => void;
239
+ onCancelEdit: () => void;
240
+ initialValue: string;
241
+ placeholder?: string;
242
+ type?: "text" | "password" | "textarea";
243
+ editLabel?: string;
244
+ minWidth?: number;
245
+ size?: ControlSize;
246
+ /** Datatable cells may be cleared. KV/secrets stay required. */
247
+ allowEmpty?: boolean;
248
+ onSave: (value: string) => Promise<void>;
249
+ };
250
+
251
+ const KEY_RE = /^[A-Z][A-Z0-9_]*$/;
252
+
253
+ export type EditableKeyProps = {
254
+ value: string;
255
+ editing: boolean;
256
+ onStartEdit: () => void;
257
+ onCancelEdit: () => void;
258
+ onSave: (key: string) => Promise<void>;
259
+ placeholder?: string;
260
+ editLabel?: string;
261
+ size?: ControlSize;
262
+ };
263
+
264
+ function EditableKey({ value, editing, onStartEdit, onCancelEdit, onSave, placeholder = "VARIABLE_NAME", editLabel = "Edit key", size }: EditableKeyProps) {
265
+ const resolved = useControlSize(size);
266
+ const tok = getSizeTokens(resolved);
267
+ const [draft, setDraft] = useState(value);
268
+ const [saving, setSaving] = useState(false);
269
+ const textRef = useRef<HTMLDivElement>(null);
270
+ const rowRef = useRef<HTMLDivElement>(null);
271
+ const inputRef = useRef<HTMLInputElement>(null);
272
+
273
+ useEffect(() => {
274
+ if (!editing) return;
275
+ setDraft(value);
276
+ }, [editing, value]);
277
+
278
+ const handleCancel = () => {
279
+ setDraft(value);
280
+ onCancelEdit();
281
+ };
282
+
283
+ const handleSave = async () => {
284
+ const next = draft.trim().toUpperCase();
285
+ if (!next) {
286
+ message.error("Key is required");
287
+ return;
288
+ }
289
+ if (!KEY_RE.test(next)) {
290
+ message.error("Key must match [A-Z][A-Z0-9_]* (e.g. API_TOKEN)");
291
+ return;
292
+ }
293
+ if (next === value) {
294
+ onCancelEdit();
295
+ return;
296
+ }
297
+ setSaving(true);
298
+ try {
299
+ await onSave(next);
300
+ onCancelEdit();
301
+ } catch {
302
+ // Caller shows the error; keep the draft open.
303
+ } finally {
304
+ setSaving(false);
305
+ }
306
+ };
307
+
308
+ const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
309
+ if (e.key === "Enter") {
310
+ e.preventDefault();
311
+ void handleSave();
312
+ } else if (e.key === "Escape") {
313
+ e.preventDefault();
314
+ handleCancel();
315
+ }
316
+ };
317
+
318
+ return (
319
+ <div ref={rowRef} className="flex w-full min-w-0 items-center" style={{ minHeight: controlHeightVar(resolved) }}>
320
+ <div className="group/edit inline-flex max-w-full items-center gap-1">
321
+ <div ref={textRef} className={cn("min-w-0", editing && "invisible")} style={{ fontSize: tok.fontSize, lineHeight: `${tok.lineHeight}px`, minHeight: tok.lineHeight }}>
322
+ <code className="select-text font-mono font-semibold tracking-wide text-foreground">{value}</code>
323
+ </div>
324
+ {editing ? null : <EditButton label={editLabel} size={resolved} onClick={onStartEdit} />}
325
+ </div>
326
+ {editing ? (
327
+ <EditorPopover textRef={textRef} rowRef={rowRef} inputRef={inputRef} size={resolved} multiline={false} saving={saving} selectOnFocus onSave={() => void handleSave()} onCancel={handleCancel}>
328
+ <input type="text" value={draft} onChange={(e) => setDraft(e.target.value.toUpperCase())} onKeyDown={handleKeyDown} placeholder={placeholder} disabled={saving} className={fieldClass(saving)} />
329
+ </EditorPopover>
330
+ ) : null}
331
+ </div>
332
+ );
333
+ }
334
+
335
+ function EditableInputRoot({ display, editing, onStartEdit, onCancelEdit, initialValue, placeholder, type = "text", editLabel = "Edit value", minWidth, size, allowEmpty = false, onSave }: EditableInputProps) {
336
+ const resolved = useControlSize(size);
337
+ const tok = getSizeTokens(resolved);
338
+ const [draft, setDraft] = useState(initialValue);
339
+ const [saving, setSaving] = useState(false);
340
+ const textRef = useRef<HTMLDivElement>(null);
341
+ const rowRef = useRef<HTMLDivElement>(null);
342
+ const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement>(null);
343
+ const multiline = type === "textarea";
344
+
345
+ useEffect(() => {
346
+ if (!editing) return;
347
+ setDraft(initialValue);
348
+ }, [editing, initialValue]);
349
+
350
+ const handleCancel = () => {
351
+ setDraft(initialValue);
352
+ onCancelEdit();
353
+ };
354
+
355
+ const handleSave = async () => {
356
+ if (!allowEmpty && !draft) {
357
+ message.error("Value is required");
358
+ return;
359
+ }
360
+ if (draft === initialValue) {
361
+ onCancelEdit();
362
+ return;
363
+ }
364
+ setSaving(true);
365
+ try {
366
+ await onSave(draft);
367
+ onCancelEdit();
368
+ } catch {
369
+ // Caller shows the error; keep the draft open.
370
+ } finally {
371
+ setSaving(false);
372
+ }
373
+ };
374
+
375
+ const handleKeyDown = (e: KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {
376
+ if (e.key === "Escape") {
377
+ e.preventDefault();
378
+ handleCancel();
379
+ return;
380
+ }
381
+ if (e.key === "Enter" && (!multiline || e.metaKey || e.ctrlKey)) {
382
+ e.preventDefault();
383
+ void handleSave();
384
+ }
385
+ };
386
+
387
+ const field = multiline ? (
388
+ <textarea value={draft} rows={3} onChange={(e) => setDraft(e.target.value)} onKeyDown={handleKeyDown} placeholder={placeholder} disabled={saving} className={fieldClass(saving)} />
389
+ ) : (
390
+ <input type={type} value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={handleKeyDown} placeholder={placeholder} disabled={saving} className={fieldClass(saving)} />
391
+ );
392
+
393
+ return (
394
+ <div ref={rowRef} className="group/edit flex w-full min-w-0 items-center" style={{ minHeight: controlHeightVar(resolved) }}>
395
+ <div ref={textRef} className={cn("min-w-0 truncate", editing && "invisible")} style={{ fontSize: tok.fontSize, lineHeight: `${tok.lineHeight}px`, minHeight: tok.lineHeight }}>
396
+ {display}
397
+ </div>
398
+ {editing ? null : <EditButton label={editLabel} size={resolved} onClick={onStartEdit} />}
399
+ {editing ? (
400
+ <EditorPopover textRef={textRef} rowRef={rowRef} inputRef={inputRef} size={resolved} multiline={multiline} minWidth={minWidth} saving={saving} saveDisabled={!allowEmpty && !draft} onSave={() => void handleSave()} onCancel={handleCancel}>
401
+ {field}
402
+ </EditorPopover>
403
+ ) : null}
404
+ </div>
405
+ );
406
+ }
407
+
408
+ export const EditableInput = Object.assign(EditableInputRoot, { Key: EditableKey });
package/src/lib/sizes.ts CHANGED
@@ -93,9 +93,12 @@ export function controlStatusClass(status?: "error" | "warning"): string {
93
93
  /** Focus surface fade — Input / Select / DatePicker / TimePicker. */
94
94
  export const controlFieldTransition = "transition-[background-color,border-color] duration-[var(--nonla-dur-fast,150ms)] ease-[var(--nonla-ease-out,cubic-bezier(0.16,1,0.3,1))] motion-reduce:transition-none";
95
95
 
96
- /** Outlined field fill — meadow glass, same language as DesktopWindow. */
96
+ /**
97
+ * Outlined field. Border is `--input` (ink on page bg), not glass.
98
+ * Glass border is white frost — it disappears on white.
99
+ */
97
100
  export const controlFieldSurface =
98
- "border border-solid border-glass-border bg-glass-bar text-foreground shadow-[inset_0_1px_0_var(--glass-highlight)] backdrop-blur-xl";
101
+ "border border-solid border-input bg-glass-bar text-foreground shadow-[inset_0_1px_0_var(--glass-highlight)] backdrop-blur-xl";
99
102
 
100
103
  /** Focus / open border — brand (Button primary), keep fields outlined. */
101
104
  export const controlFieldFocusBorder = "focus:border-brand focus-within:border-brand data-[state=open]:border-brand aria-expanded:border-brand";
@@ -1,4 +1,4 @@
1
- import { type ReactNode, type PointerEvent as ReactPointerEvent, type Ref, type UIEventHandler, useCallback, useLayoutEffect, useRef, useState } from "react";
1
+ import { type CSSProperties, type ReactNode, type PointerEvent as ReactPointerEvent, type Ref, type UIEventHandler, useCallback, useLayoutEffect, useRef, useState } from "react";
2
2
  import { cn } from "../lib/cn";
3
3
 
4
4
  export type OverlayScrollVisibility = "hover" | "always";
@@ -12,10 +12,13 @@ export type OverlayScrollProps = {
12
12
  /** Size to content (honors max-height on `className`) instead of filling the parent. */
13
13
  autoHeight?: boolean;
14
14
  className?: string;
15
+ style?: CSSProperties;
15
16
  innerClassName?: string;
16
17
  children?: ReactNode;
17
18
  onScroll?: UIEventHandler<HTMLDivElement>;
18
19
  scrollRef?: Ref<HTMLDivElement>;
20
+ /** Keep the vertical thumb below this many pixels (sticky table header). */
21
+ insetTop?: number;
19
22
  };
20
23
 
21
24
  type Thumb = { offset: number; size: number; shown: boolean };
@@ -29,11 +32,12 @@ function assignRef(ref: Ref<HTMLDivElement> | undefined, node: HTMLDivElement |
29
32
  else ref.current = node;
30
33
  }
31
34
 
32
- function measure(scroll: number, scrollSize: number, client: number): Thumb {
35
+ function measure(scroll: number, scrollSize: number, client: number, inset = 0): Thumb {
36
+ const track = Math.max(0, client - inset);
33
37
  const overflow = scrollSize - client;
34
- if (overflow <= 1) return HIDDEN;
35
- const size = Math.max(MIN_THUMB, (client / scrollSize) * client);
36
- const offset = (scroll / overflow) * (client - size);
38
+ if (overflow <= 1 || track <= 1) return HIDDEN;
39
+ const size = Math.min(track, Math.max(MIN_THUMB, (track / scrollSize) * track));
40
+ const offset = (scroll / overflow) * Math.max(0, track - size);
37
41
  return { offset, size, shown: true };
38
42
  }
39
43
 
@@ -42,7 +46,7 @@ function canScrollX(el: HTMLDivElement) {
42
46
  return overflow === "auto" || overflow === "scroll";
43
47
  }
44
48
 
45
- export function OverlayScroll({ visibility = "hover", autoHeight = false, className, innerClassName, children, onScroll, scrollRef }: OverlayScrollProps) {
49
+ export function OverlayScroll({ visibility = "hover", autoHeight = false, className, style, innerClassName, children, onScroll, scrollRef, insetTop = 0 }: OverlayScrollProps) {
46
50
  const elRef = useRef<HTMLDivElement | null>(null);
47
51
  const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
48
52
  const vThumbRef = useRef<Thumb>(HIDDEN);
@@ -54,10 +58,13 @@ export function OverlayScroll({ visibility = "hover", autoHeight = false, classN
54
58
  vThumbRef.current = vThumb;
55
59
  hThumbRef.current = hThumb;
56
60
 
61
+ const insetTopRef = useRef(insetTop);
62
+ insetTopRef.current = insetTop;
63
+
57
64
  const updateThumb = useCallback(() => {
58
65
  const el = elRef.current;
59
66
  if (!el) return;
60
- setVThumb(measure(el.scrollTop, el.scrollHeight, el.clientHeight));
67
+ setVThumb(measure(el.scrollTop, el.scrollHeight, el.clientHeight, insetTopRef.current));
61
68
  setHThumb(canScrollX(el) ? measure(el.scrollLeft, el.scrollWidth, el.clientWidth) : HIDDEN);
62
69
  }, []);
63
70
 
@@ -79,7 +86,7 @@ export function OverlayScroll({ visibility = "hover", autoHeight = false, classN
79
86
  const child = el.firstElementChild;
80
87
  if (child) ro.observe(child);
81
88
  return () => ro.disconnect();
82
- }, [updateThumb, innerClassName, autoHeight]);
89
+ }, [updateThumb, innerClassName, autoHeight, insetTop]);
83
90
 
84
91
  useLayoutEffect(() => {
85
92
  return () => {
@@ -104,8 +111,9 @@ export function OverlayScroll({ visibility = "hover", autoHeight = false, classN
104
111
  e.preventDefault();
105
112
  e.stopPropagation();
106
113
 
114
+ const inset = axis === "y" ? insetTopRef.current : 0;
107
115
  const overflow = axis === "y" ? el.scrollHeight - el.clientHeight : el.scrollWidth - el.clientWidth;
108
- const track = (axis === "y" ? el.clientHeight : el.clientWidth) - current.size;
116
+ const track = (axis === "y" ? el.clientHeight - inset : el.clientWidth) - current.size;
109
117
  if (overflow <= 0 || track <= 0) return;
110
118
 
111
119
  const start = axis === "y" ? e.clientY : e.clientX;
@@ -145,7 +153,7 @@ export function OverlayScroll({ visibility = "hover", autoHeight = false, classN
145
153
  );
146
154
 
147
155
  return (
148
- <div className={cn("group/scroll relative min-h-0 min-w-0 w-full overflow-hidden", className)} data-scrolling={thumbVisible ? "true" : undefined}>
156
+ <div className={cn("group/scroll relative min-h-0 min-w-0 w-full overflow-hidden", className)} style={style} data-scrolling={thumbVisible ? "true" : undefined}>
149
157
  <div
150
158
  ref={setNode}
151
159
  onScroll={handleScroll}
@@ -154,10 +162,10 @@ export function OverlayScroll({ visibility = "hover", autoHeight = false, classN
154
162
  {children}
155
163
  </div>
156
164
  {vThumb.shown ? (
157
- <div aria-hidden onPointerDown={onThumbPointerDown("y")} className={thumbClass} style={{ right: 2, width: "var(--nonla-scrollbar-size)", height: vThumb.size, transform: `translateY(${vThumb.offset}px)` }} />
165
+ <div aria-hidden onPointerDown={onThumbPointerDown("y")} className={thumbClass} style={{ top: insetTop, right: 2, width: "var(--nonla-scrollbar-size)", height: vThumb.size, transform: `translateY(${vThumb.offset}px)` }} />
158
166
  ) : null}
159
167
  {hThumb.shown ? (
160
- <div aria-hidden onPointerDown={onThumbPointerDown("x")} className={thumbClass} style={{ bottom: 2, height: "var(--nonla-scrollbar-size)", width: hThumb.size, transform: `translateX(${hThumb.offset}px)` }} />
168
+ <div aria-hidden onPointerDown={onThumbPointerDown("x")} className={thumbClass} style={{ left: 0, bottom: 2, height: "var(--nonla-scrollbar-size)", width: hThumb.size, transform: `translateX(${hThumb.offset}px)` }} />
161
169
  ) : null}
162
170
  </div>
163
171
  );
@@ -1,9 +1,10 @@
1
- import { type CSSProperties, type Key, type ReactNode, useMemo, useState } from "react";
1
+ import { type CSSProperties, type Key, type ReactNode, type Ref, useLayoutEffect, useMemo, useRef, useState } from "react";
2
2
  import { Checkbox } from "../checkbox/Checkbox";
3
3
  import { Empty } from "../empty/Empty";
4
4
  import { cn } from "../lib/cn";
5
5
  import { type CanonicalSize, type ControlSize, useControlSize } from "../lib/sizes";
6
6
  import { Pagination, type PaginationProps } from "../pagination/Pagination";
7
+ import { OverlayScroll } from "../scroll/OverlayScroll";
7
8
  import { Spin } from "../spin/Spin";
8
9
 
9
10
  export type SortOrder = "ascend" | "descend" | null;
@@ -18,6 +19,11 @@ export type ColumnType<T> = {
18
19
  /** Custom cell — `(value, record, index) => ReactNode`. */
19
20
  render?: (value: any, record: T, index: number) => ReactNode;
20
21
  className?: string;
22
+ /**
23
+ * Take leftover container width (measured). `true` shares equally with other flex columns.
24
+ * Text wraps inside that width so the table does not scroll horizontally.
25
+ */
26
+ flex?: boolean | number;
21
27
  ellipsis?: boolean;
22
28
  fixed?: "left" | "right";
23
29
  /** `true` = default compare on `dataIndex`; or pass a compare fn. */
@@ -142,6 +148,32 @@ function SortIcon({ order }: { order: SortOrder | undefined }) {
142
148
  );
143
149
  }
144
150
 
151
+ type FlexLayout = { selection?: number; cols: Record<string, number> };
152
+
153
+ function flexWeight<T>(col: ColumnType<T>): number {
154
+ if (col.width != null) return 0;
155
+ if (col.flex === true) return 1;
156
+ if (typeof col.flex === "number" && col.flex > 0) return col.flex;
157
+ return 0;
158
+ }
159
+
160
+ function layoutsClose(prev: FlexLayout | null, next: FlexLayout): boolean {
161
+ if (!prev) return false;
162
+ if (Math.abs((prev.selection ?? 0) - (next.selection ?? 0)) > 0.5) return false;
163
+ const keys = Object.keys(next.cols);
164
+ if (keys.length !== Object.keys(prev.cols).length) return false;
165
+ return keys.every((key) => Math.abs((prev.cols[key] ?? -1) - next.cols[key]) <= 0.5);
166
+ }
167
+
168
+ function TableBodyScroll({ x, y, scrollRef, insetTop = 0, children }: { x?: number | string; y?: number | string; scrollRef: Ref<HTMLDivElement>; insetTop?: number; children: ReactNode }) {
169
+ if (y == null) return <div ref={scrollRef}>{children}</div>;
170
+ return (
171
+ <OverlayScroll autoHeight visibility="hover" scrollRef={scrollRef} insetTop={insetTop} style={{ maxHeight: y }} innerClassName={x != null ? "overflow-x-auto" : undefined}>
172
+ {children}
173
+ </OverlayScroll>
174
+ );
175
+ }
176
+
145
177
  function sizeClasses(s: CanonicalSize) {
146
178
  if (s === "small") {
147
179
  return {
@@ -152,15 +184,15 @@ function sizeClasses(s: CanonicalSize) {
152
184
  }
153
185
  if (s === "large") {
154
186
  return {
155
- head: "h-12 px-3 text-sm",
156
- cell: "px-3 py-3 text-sm",
187
+ head: "h-12 px-3 text-base",
188
+ cell: "px-3 py-3 text-base",
157
189
  check: "w-12 px-3",
158
190
  };
159
191
  }
160
- // default — matches shadcn TableHead h-10 / TableCell p-2 / text-sm
192
+ // default — text-base is 14px (`--text-sm` in this theme is 13px)
161
193
  return {
162
- head: "h-10 px-2 text-sm",
163
- cell: "p-2 text-sm",
194
+ head: "h-10 px-2 text-base",
195
+ cell: "p-2 text-base",
164
196
  check: "w-10 px-2",
165
197
  };
166
198
  }
@@ -264,19 +296,119 @@ export function Table<T extends object = Record<string, unknown>>({ columns = []
264
296
 
265
297
  const alignClass = (align?: "left" | "center" | "right") => (align === "center" ? "text-center" : align === "right" ? "text-right" : "text-left");
266
298
 
299
+ const containerRef = useRef<HTMLDivElement>(null);
300
+ const scrollBodyRef = useRef<HTMLDivElement>(null);
301
+ const columnsRef = useRef(columns);
302
+ columnsRef.current = columns;
303
+ const [flexLayout, setFlexLayout] = useState<FlexLayout | null>(null);
304
+ const flexSig = `${scroll?.x ?? ""}|${scroll?.y ?? ""}|${rowSelection ? 1 : 0}|${showHeader ? 1 : 0}|${dataSource.length}|${columns.map((col, i) => `${getColumnKey(col, i)}:${col.flex ?? ""}:${col.width ?? ""}`).join(",")}`;
305
+ const flexSigRef = useRef(flexSig);
306
+ if (flexSigRef.current !== flexSig) {
307
+ flexSigRef.current = flexSig;
308
+ if (flexLayout) setFlexLayout(null);
309
+ }
310
+
311
+ useLayoutEffect(() => {
312
+ const container = containerRef.current;
313
+ const cols = columnsRef.current;
314
+ const wantsFlex = scroll?.x == null && cols.some((col) => flexWeight(col) > 0);
315
+ if (!container || !wantsFlex) {
316
+ setFlexLayout((prev) => (prev ? null : prev));
317
+ return;
318
+ }
319
+
320
+ let locked: { selection?: number; fixed: Record<string, number>; weights: { key: string; weight: number }[] } | null = null;
321
+
322
+ const apply = () => {
323
+ const scroller = scrollBodyRef.current;
324
+ const scrollbar = scroller && scroller.scrollHeight > scroller.clientHeight + 1 ? scroller.offsetWidth - scroller.clientWidth : 0;
325
+ const client = container.clientWidth - Math.max(0, scrollbar);
326
+ if (client <= 0) return;
327
+ if (!locked) {
328
+ const table = container.querySelector("table");
329
+ const row = table?.querySelector("thead > tr") ?? table?.querySelector("tbody > tr");
330
+ if (!row) return;
331
+ const cells = [...row.children] as HTMLElement[];
332
+ const start = rowSelection ? 1 : 0;
333
+ const fixed: Record<string, number> = {};
334
+ const weights: { key: string; weight: number }[] = [];
335
+ cols.forEach((col, i) => {
336
+ const key = getColumnKey(col, i);
337
+ const weight = flexWeight(col);
338
+ if (weight > 0) weights.push({ key, weight });
339
+ else fixed[key] = cells[start + i]?.getBoundingClientRect().width ?? 0;
340
+ });
341
+ if (!weights.length) return;
342
+ locked = {
343
+ selection: rowSelection ? cells[0]?.getBoundingClientRect().width : undefined,
344
+ fixed,
345
+ weights,
346
+ };
347
+ }
348
+ const used = (locked.selection ?? 0) + Object.values(locked.fixed).reduce((sum, n) => sum + n, 0);
349
+ if (used > client + 1) {
350
+ setFlexLayout((prev) => (prev ? null : prev));
351
+ return;
352
+ }
353
+ const leftover = Math.max(0, client - used);
354
+ const weightSum = locked.weights.reduce((sum, item) => sum + item.weight, 0);
355
+ const colsWidth = { ...locked.fixed };
356
+ for (const item of locked.weights) colsWidth[item.key] = (leftover * item.weight) / weightSum;
357
+ const next: FlexLayout = { selection: locked.selection, cols: colsWidth };
358
+ setFlexLayout((prev) => (layoutsClose(prev, next) ? prev : next));
359
+ };
360
+
361
+ apply();
362
+ const observer = new ResizeObserver(apply);
363
+ observer.observe(container);
364
+ if (scrollBodyRef.current) observer.observe(scrollBodyRef.current);
365
+ return () => observer.disconnect();
366
+ }, [flexSig, rowSelection, scroll?.x, scroll?.y, showHeader]);
367
+
368
+ const wantsFlex = scroll?.x == null && columns.some((col) => flexWeight(col) > 0);
369
+
370
+ const headSticky = scroll?.y != null;
371
+ const [thumbInset, setThumbInset] = useState(0);
372
+ useLayoutEffect(() => {
373
+ if (!headSticky || !showHeader) {
374
+ setThumbInset(0);
375
+ return;
376
+ }
377
+ const head = scrollBodyRef.current?.querySelector("thead");
378
+ const next = head ? Math.ceil(head.getBoundingClientRect().height) + 4 : 0;
379
+ setThumbInset((prev) => (prev === next ? prev : next));
380
+ }, [headSticky, showHeader, size, flexLayout]);
381
+ /** Opaque fill. `bg-foreground/4` is 4% alpha, so body text shows through a sticky header. */
382
+ const headBg: CSSProperties | undefined = headSticky ? { backgroundColor: "var(--nonla-bg)" } : undefined;
383
+
384
+ const colStyle = (col: ColumnType<T>, key: string): CSSProperties => {
385
+ const measured = flexLayout?.cols[key];
386
+ if (measured != null) return { width: measured, maxWidth: measured, minWidth: 0 };
387
+ return { width: col.width, minWidth: col.minWidth };
388
+ };
389
+
267
390
  return (
268
391
  <div className={cn("relative w-full", className)}>
269
392
  {titleNode != null ? <div className="mb-3 text-sm font-medium text-foreground">{titleNode}</div> : null}
270
393
 
271
394
  <Spin spinning={Boolean(loading)}>
272
- <div data-slot="table-container" className={cn("relative w-full overflow-x-auto", bordered && "rounded-md border border-border")} style={scroll?.x != null ? { overflowX: "auto" } : undefined}>
273
- <div style={scroll?.y != null ? { maxHeight: scroll.y, overflow: "auto" } : undefined}>
274
- <table data-slot="table" className="w-full caption-bottom border-collapse text-sm">
395
+ <div ref={containerRef} data-slot="table-container" className={cn("relative w-full", flexLayout ? "overflow-x-hidden" : "overflow-x-auto", bordered && "rounded-md border border-border")} style={scroll?.x != null ? { overflowX: "auto" } : undefined}>
396
+ <TableBodyScroll y={scroll?.y} x={scroll?.x} scrollRef={scrollBodyRef} insetTop={thumbInset}>
397
+ <table data-slot="table" className={cn("caption-bottom text-base", headSticky ? "border-separate border-spacing-0" : "border-collapse", flexLayout ? "w-full table-fixed" : wantsFlex ? "w-max" : "w-full")}>
398
+ {flexLayout ? (
399
+ <colgroup>
400
+ {rowSelection ? <col style={{ width: flexLayout.selection }} /> : null}
401
+ {columns.map((col, i) => {
402
+ const key = getColumnKey(col, i);
403
+ return <col key={key} style={{ width: flexLayout.cols[key] }} />;
404
+ })}
405
+ </colgroup>
406
+ ) : null}
275
407
  {showHeader ? (
276
- <thead data-slot="table-header" className="[&_tr]:border-b [&_tr]:border-border">
408
+ <thead data-slot="table-header" className={cn("[&_tr]:border-b [&_tr]:border-border", headSticky && "relative z-20")}>
277
409
  <tr data-slot="table-row" className="border-b border-border transition-colors hover:bg-transparent">
278
410
  {rowSelection ? (
279
- <th data-slot="table-head" className={cn(sz.head, sz.check, "align-middle font-medium text-foreground", scroll?.y && "sticky top-0 z-10 bg-background", bordered && "border-b border-border")} style={selectionColWidth != null ? { width: selectionColWidth } : undefined}>
411
+ <th data-slot="table-head" className={cn(sz.head, sz.check, "align-middle font-medium text-foreground", headSticky ? "sticky top-0 z-10 border-b border-border" : "bg-foreground/4", bordered && "border-b border-border")} style={{ ...(selectionColWidth != null ? { width: selectionColWidth } : undefined), ...headBg }}>
280
412
  <div className="flex items-center justify-center">
281
413
  {rowSelection.type === "radio" ? null : (
282
414
  <Checkbox
@@ -301,10 +433,10 @@ export function Table<T extends object = Record<string, unknown>>({ columns = []
301
433
  <th
302
434
  key={key}
303
435
  data-slot="table-head"
304
- className={cn(sz.head, "align-middle font-medium whitespace-nowrap text-foreground", alignClass(col.align), scroll?.y && "sticky top-0 z-10 bg-background", bordered && "border-b border-border", sortable && "cursor-pointer select-none", col.className, headerExtra?.className)}
436
+ className={cn(sz.head, "align-middle font-medium text-foreground", headSticky ? "sticky top-0 z-10 border-b border-border" : "bg-foreground/4", flexLayout && flexWeight(col) > 0 ? "min-w-0" : "whitespace-nowrap", alignClass(col.align), bordered && "border-b border-border", sortable && "cursor-pointer select-none", col.className, headerExtra?.className)}
305
437
  style={{
306
- width: col.width,
307
- minWidth: col.minWidth,
438
+ ...colStyle(col, key),
439
+ ...headBg,
308
440
  ...headerExtra?.style,
309
441
  }}
310
442
  onClick={sortable ? () => toggleSort(col, i) : undefined}
@@ -320,7 +452,7 @@ export function Table<T extends object = Record<string, unknown>>({ columns = []
320
452
  </thead>
321
453
  ) : null}
322
454
 
323
- <tbody data-slot="table-body" className="[&_tr:last-child]:border-0">
455
+ <tbody data-slot="table-body" className={cn("[&_tr:last-child]:border-0", headSticky && "relative z-0")}>
324
456
  {pageData.length === 0 ? (
325
457
  <tr data-slot="table-row" className="border-b border-border">
326
458
  <td data-slot="table-cell" colSpan={colCount} className={cn(sz.cell, "text-center align-middle")}>
@@ -334,10 +466,31 @@ export function Table<T extends object = Record<string, unknown>>({ columns = []
334
466
  const rowProps = onRow?.(record, absoluteIndex);
335
467
  const extraClass = typeof rowClassName === "function" ? rowClassName(record, absoluteIndex) : rowClassName;
336
468
  const selected = selectedKeys.includes(key);
469
+ const inSelectionMode = Boolean(rowSelection) && selectedKeys.length > 0;
470
+ const rowDisabled = Boolean(rowSelection?.getCheckboxProps?.(record)?.disabled);
337
471
  return (
338
- <tr key={key} data-slot="table-row" data-state={selected ? "selected" : undefined} className={cn("border-b border-border transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", rowProps?.className, extraClass)} style={rowProps?.style} onClick={rowProps?.onClick}>
472
+ <tr
473
+ key={key}
474
+ data-slot="table-row"
475
+ data-state={selected ? "selected" : undefined}
476
+ className={cn("border-b border-border transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", inSelectionMode && !rowDisabled && "cursor-pointer", rowProps?.className, extraClass)}
477
+ style={rowProps?.style}
478
+ onClick={inSelectionMode ? undefined : rowProps?.onClick}
479
+ onClickCapture={
480
+ inSelectionMode && !rowDisabled
481
+ ? (e) => {
482
+ if (e.target instanceof Element && e.target.closest("[data-row-select]")) return;
483
+ e.preventDefault();
484
+ e.stopPropagation();
485
+ if (rowSelection?.type === "radio") emitSelection([key]);
486
+ else if (selected) emitSelection(selectedKeys.filter((k) => k !== key));
487
+ else emitSelection([...selectedKeys, key]);
488
+ }
489
+ : undefined
490
+ }
491
+ >
339
492
  {rowSelection ? (
340
- <td data-slot="table-cell" className={cn(sz.cell, sz.check, "align-middle")} style={selectionColWidth != null ? { width: selectionColWidth } : undefined} onClick={(e) => e.stopPropagation()}>
493
+ <td data-row-select data-slot="table-cell" className={cn(sz.cell, sz.check, "align-middle", headSticky && "border-b border-border")} style={selectionColWidth != null ? { width: selectionColWidth } : undefined} onClick={(e) => e.stopPropagation()}>
341
494
  <div className="flex items-center justify-center">
342
495
  {rowSelection.type === "radio" ? (
343
496
  <input type="radio" name="nonla-table-row-select" checked={selected} disabled={rowSelection.getCheckboxProps?.(record)?.disabled} aria-label="Select row" className="size-3.5 accent-foreground" onChange={() => emitSelection([key])} />
@@ -362,8 +515,8 @@ export function Table<T extends object = Record<string, unknown>>({ columns = []
362
515
  <td
363
516
  key={getColumnKey(col, i)}
364
517
  data-slot="table-cell"
365
- className={cn(sz.cell, "align-middle", alignClass(col.align), col.ellipsis ? "max-w-0 truncate" : "whitespace-nowrap", col.className)}
366
- style={{ width: col.width, minWidth: col.minWidth }}
518
+ className={cn(sz.cell, "align-middle", headSticky && "border-b border-border", alignClass(col.align), flexLayout && flexWeight(col) > 0 ? (col.ellipsis ? "max-w-0 truncate" : "min-w-0 whitespace-normal wrap-break-word") : col.ellipsis ? "max-w-0 truncate" : "whitespace-nowrap", col.className)}
519
+ style={colStyle(col, getColumnKey(col, i))}
367
520
  title={col.ellipsis && (typeof content === "string" || typeof content === "number") ? String(content) : undefined}
368
521
  >
369
522
  {content}
@@ -386,7 +539,7 @@ export function Table<T extends object = Record<string, unknown>>({ columns = []
386
539
  </tfoot>
387
540
  ) : null}
388
541
  </table>
389
- </div>
542
+ </TableBodyScroll>
390
543
  </div>
391
544
  </Spin>
392
545