devnonla-ui 0.5.1 → 0.6.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.
package/README.md CHANGED
@@ -115,7 +115,31 @@ import { DesktopStage, DesktopHeader, MeadowDesktop, DesktopWindow, MeadowShell,
115
115
  </DesktopStage>
116
116
  ```
117
117
 
118
- `MeadowShell` is the login/setup backdrop. `DesktopWindow` chrome is inline: traffic lights, `left`, a flex middle (title — double-click to expand), then `right`. A child can fill the same slots with `WindowHeader`. `Menu` is the glass picker (trigger + items + hover action) used by AgentsMenu. Wallpaper defaults to the bundled meadow; pass `src` on `MeadowWallpaper` to swap.
118
+ `MeadowShell` is the login/setup backdrop. `DesktopWindow` chrome is inline: traffic lights, `left`, a flex middle (title — double-click to expand), then `right`. A child can fill the same slots with `WindowHeader`. Last collapsed position and size are restored on reopen (`persistKey`, or `false` to disable). Resize handles stay when expanded; dragging an edge leaves expand and keeps the new size. `Menu` is the glass picker (trigger + items + hover action) used by AgentsMenu. Wallpaper defaults to the bundled meadow; pass `src` on `MeadowWallpaper` to swap.
119
+
120
+ # Sidebar
121
+
122
+ Grouped side nav. Pass JSON groups + items; the app owns routing.
123
+
124
+ ```tsx
125
+ import { Sidebar, type SidebarItemType } from "devnonla-ui";
126
+
127
+ const items: SidebarItemType[] = [
128
+ {
129
+ type: "group",
130
+ key: "chat",
131
+ label: "Chat",
132
+ children: [
133
+ { key: "inbox", label: "Inbox", icon: "chat-24" },
134
+ { key: "archive", label: "Archive", icon: "library-24" },
135
+ ],
136
+ },
137
+ ];
138
+
139
+ <Sidebar items={items} selectedKey={active} searchable onSelect={({ key }) => setActive(key)} />
140
+ ```
141
+
142
+ `icon` may be a Fluent name string (JSON-friendly) or a node. Set `href` to render `<a>`; left-click still goes through `onSelect` so a SPA can `navigate`. Cmd/Ctrl-click keeps the native new-tab. Parent sets width; `Sidebar` fills height.
119
143
 
120
144
  # Chat
121
145
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "devnonla-ui",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "NonlaUI — React controls for Nonla Agents",
6
6
  "author": "devlangla <devlangla0x01@gmail.com>",
@@ -139,6 +139,69 @@ function offsetFromRect(view: Size, rect: Rect): Point {
139
139
  };
140
140
  }
141
141
 
142
+ type Geometry = Point & Size;
143
+
144
+ const GEOMETRY_PREFIX = "nonla-desktop-window:";
145
+ const geometryMemory = new Map<string, Geometry>();
146
+
147
+ function isGeometry(value: unknown): value is Geometry {
148
+ if (!value || typeof value !== "object") return false;
149
+ const { x, y, w, h } = value as Record<string, unknown>;
150
+ return [x, y, w, h].every((n) => typeof n === "number" && Number.isFinite(n));
151
+ }
152
+
153
+ function geometryStorageKey(persistKey: string) {
154
+ return `${GEOMETRY_PREFIX}${persistKey}`;
155
+ }
156
+
157
+ function readGeometry(persistKey: string | false): Geometry | null {
158
+ if (!persistKey) return null;
159
+ const cached = geometryMemory.get(persistKey);
160
+ if (cached) return cached;
161
+ try {
162
+ const raw = localStorage.getItem(geometryStorageKey(persistKey));
163
+ if (!raw) return null;
164
+ const parsed: unknown = JSON.parse(raw);
165
+ if (!isGeometry(parsed)) return null;
166
+ geometryMemory.set(persistKey, parsed);
167
+ return parsed;
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
173
+ function writeGeometry(persistKey: string | false, geometry: Geometry) {
174
+ if (!persistKey) return;
175
+ geometryMemory.set(persistKey, geometry);
176
+ try {
177
+ localStorage.setItem(geometryStorageKey(persistKey), JSON.stringify(geometry));
178
+ } catch {
179
+ /* private mode / quota */
180
+ }
181
+ }
182
+
183
+ function initialView(): Size {
184
+ return { w: window.innerWidth, h: Math.max(0, window.innerHeight - 42) };
185
+ }
186
+
187
+ function restoreGeometry(persistKey: string | false, view: Size): { offset: Point; size: Size | null } {
188
+ const stored = readGeometry(persistKey);
189
+ if (!stored) return { offset: { x: 0, y: 0 }, size: null };
190
+ const size = clampSize(view, stored);
191
+ return { offset: clampOffset(view, size, stored), size };
192
+ }
193
+
194
+ function persistGeometry(persistKey: string | false, view: Size, offset: Point, size: Size | null) {
195
+ const compact = windowSize(view, size);
196
+ const clamped = clampOffset(view, compact, offset);
197
+ writeGeometry(persistKey, {
198
+ x: Math.round(clamped.x),
199
+ y: Math.round(clamped.y),
200
+ w: Math.round(compact.w),
201
+ h: Math.round(compact.h),
202
+ });
203
+ }
204
+
142
205
  function lockResizeCursor(cursor: string | null) {
143
206
  document.body.style.cursor = cursor ?? "";
144
207
  document.body.style.userSelect = cursor ? "none" : "";
@@ -227,6 +290,8 @@ export type DesktopWindowProps = {
227
290
  /** Overlay auto-hide scrollbar on the body. Pass `false` when children manage their own scroll (split panes, AgentPanel). */
228
291
  scroll?: boolean;
229
292
  scrollbar?: OverlayScrollVisibility;
293
+ /** Last collapsed position and size. Default `"default"`. Pass a unique key per window, or `false` to disable. */
294
+ persistKey?: string | false;
230
295
  children: ReactNode;
231
296
  };
232
297
 
@@ -239,6 +304,7 @@ export function DesktopWindow({
239
304
  onToggleExpand,
240
305
  scroll = true,
241
306
  scrollbar = "hover",
307
+ persistKey = "default",
242
308
  children,
243
309
  }: DesktopWindowProps) {
244
310
  const overlayRef = useRef<HTMLDivElement>(null);
@@ -260,15 +326,12 @@ export function DesktopWindow({
260
326
  orig: Rect;
261
327
  } | null>(null);
262
328
  const [phase, setPhase] = useState<Phase>("open");
263
- const [offset, setOffset] = useState({ x: 0, y: 0 });
264
- const [size, setSize] = useState<Size | null>(null);
329
+ const [view, setView] = useState<Size>(initialView);
330
+ const [offset, setOffset] = useState(() => restoreGeometry(persistKey, initialView()).offset);
331
+ const [size, setSize] = useState<Size | null>(() => restoreGeometry(persistKey, initialView()).size);
265
332
  const [dragging, setDragging] = useState(false);
266
333
  const [resizing, setResizing] = useState(false);
267
334
  const sizeRef = useRef<Size | null>(null);
268
- const [view, setView] = useState<Size>(() => ({
269
- w: window.innerWidth,
270
- h: Math.max(0, window.innerHeight - 42),
271
- }));
272
335
  const [leftSlot, setLeftSlot] = useState<HTMLDivElement | null>(null);
273
336
  const [rightSlot, setRightSlot] = useState<HTMLDivElement | null>(null);
274
337
  const headerChrome = useMemo(() => ({ left: leftSlot, right: rightSlot }), [leftSlot, rightSlot]);
@@ -339,6 +402,17 @@ export function DesktopWindow({
339
402
  return () => observer.disconnect();
340
403
  }, []);
341
404
 
405
+ useEffect(() => {
406
+ if (dragging || resizing) return;
407
+ persistGeometry(persistKey, view, offset, size);
408
+ }, [dragging, resizing, offset, size, view, persistKey]);
409
+
410
+ useEffect(() => {
411
+ return () => {
412
+ persistGeometry(persistKey, viewRef.current, offsetRef.current, sizeRef.current);
413
+ };
414
+ }, [persistKey]);
415
+
342
416
  useEffect(() => {
343
417
  const onKey = (e: KeyboardEvent) => {
344
418
  if (e.key !== "Escape" || e.defaultPrevented || isEditableTarget(e.target) || hasOpenDialog()) return;
@@ -423,16 +497,31 @@ export function DesktopWindow({
423
497
  };
424
498
 
425
499
  const startResize = (edge: Edge, e: ReactPointerEvent<HTMLElement>) => {
426
- if (e.button !== 0 || expanded || phase === "leaving") return;
500
+ if (e.button !== 0 || phase === "leaving") return;
427
501
  e.stopPropagation();
428
502
  e.preventDefault();
429
503
 
504
+ const nextView = viewRef.current;
505
+ const orig = expandedRef.current
506
+ ? { x: 0, y: 0, w: nextView.w, h: nextView.h }
507
+ : collapsedRect(nextView, offsetRef.current, sizeRef.current);
508
+
509
+ if (expandedRef.current) {
510
+ const nextSize = { w: orig.w, h: orig.h };
511
+ const nextOffset = offsetFromRect(nextView, orig);
512
+ sizeRef.current = nextSize;
513
+ offsetRef.current = nextOffset;
514
+ setSize(nextSize);
515
+ setOffset(nextOffset);
516
+ onToggleExpand();
517
+ }
518
+
430
519
  resizeRef.current = {
431
520
  pointerId: e.pointerId,
432
521
  edge,
433
522
  startX: e.clientX,
434
523
  startY: e.clientY,
435
- orig: collapsedRect(viewRef.current, offsetRef.current, sizeRef.current),
524
+ orig,
436
525
  };
437
526
  setResizing(true);
438
527
  lockResizeCursor(HANDLES.find((handle) => handle.edge === edge)?.cursor ?? "nwse-resize");
@@ -530,7 +619,7 @@ export function DesktopWindow({
530
619
  </div>
531
620
  </div>
532
621
 
533
- {!expanded && !leaving
622
+ {!leaving
534
623
  ? HANDLES.map((handle) => (
535
624
  <div key={handle.edge} aria-hidden onPointerDown={(e) => startResize(handle.edge, e)} className={cn("absolute z-10 touch-none", handle.className)} />
536
625
  ))
package/src/index.ts CHANGED
@@ -174,6 +174,8 @@ export type { SelectOptionConfig, SelectProps, SelectValue } from "./select/Sele
174
174
  export { Select, SelectOption } from "./select/Select";
175
175
  export type { ShimmerProps } from "./shimmer/Shimmer";
176
176
  export { Shimmer } from "./shimmer/Shimmer";
177
+ export type { SidebarItemType, SidebarProps, SidebarSelectInfo } from "./sidebar/Sidebar";
178
+ export { Sidebar } from "./sidebar/Sidebar";
177
179
  export type { SkeletonProps } from "./skeleton/Skeleton";
178
180
  export { Skeleton } from "./skeleton/Skeleton";
179
181
  export type { SpinProps, SpinVariant } from "./spin/Spin";
@@ -0,0 +1,198 @@
1
+ import { type MouseEvent, type ReactNode, useMemo, useState } from "react";
2
+ import { FluentIcon } from "../icon/FluentIcon";
3
+ import { SearchInput } from "../input/SearchInput";
4
+ import { cn } from "../lib/cn";
5
+ import { OverlayScroll } from "../scroll/OverlayScroll";
6
+
7
+ export type SidebarItemType = {
8
+ key?: string;
9
+ label?: ReactNode;
10
+ /** Fluent icon name, or a node. */
11
+ icon?: ReactNode;
12
+ disabled?: boolean;
13
+ type?: "item" | "group" | "divider";
14
+ children?: SidebarItemType[];
15
+ href?: string;
16
+ extra?: ReactNode;
17
+ className?: string;
18
+ };
19
+
20
+ export type SidebarSelectInfo = {
21
+ key: string;
22
+ item: SidebarItemType;
23
+ };
24
+
25
+ export type SidebarProps = {
26
+ items?: SidebarItemType[];
27
+ selectedKey?: string;
28
+ defaultSelectedKey?: string;
29
+ onSelect?: (info: SidebarSelectInfo) => void;
30
+ searchable?: boolean;
31
+ searchPlaceholder?: string;
32
+ header?: ReactNode;
33
+ footer?: ReactNode;
34
+ emptyText?: ReactNode;
35
+ className?: string;
36
+ "aria-label"?: string;
37
+ };
38
+
39
+ function itemKey(item: SidebarItemType, i: number) {
40
+ return item.key ?? (item.type === "divider" ? `divider-${i}` : isGroup(item) ? `group-${i}` : `item-${i}`);
41
+ }
42
+
43
+ function isGroup(item: SidebarItemType) {
44
+ return item.type === "group" || (item.type !== "item" && item.type !== "divider" && Boolean(item.children?.length));
45
+ }
46
+
47
+ function labelText(label: ReactNode) {
48
+ if (typeof label === "string" || typeof label === "number") return String(label);
49
+ return "";
50
+ }
51
+
52
+ function matchesQuery(item: SidebarItemType, q: string) {
53
+ if (!q) return true;
54
+ return labelText(item.label).toLowerCase().includes(q);
55
+ }
56
+
57
+ function filterItems(items: SidebarItemType[], q: string): SidebarItemType[] {
58
+ if (!q) return items;
59
+ const out: SidebarItemType[] = [];
60
+ for (const item of items) {
61
+ if (item.type === "divider") {
62
+ if (out.length && out[out.length - 1]?.type !== "divider") out.push(item);
63
+ continue;
64
+ }
65
+ if (isGroup(item)) {
66
+ const children = filterItems(item.children ?? [], q);
67
+ if (children.length || matchesQuery(item, q)) out.push({ ...item, children });
68
+ continue;
69
+ }
70
+ if (matchesQuery(item, q)) out.push(item);
71
+ }
72
+ while (out[out.length - 1]?.type === "divider") out.pop();
73
+ return out;
74
+ }
75
+
76
+ function ItemIcon({ icon }: { icon?: ReactNode }) {
77
+ if (icon == null || icon === false) return null;
78
+ if (typeof icon === "string") return <FluentIcon name={icon} size={16} />;
79
+ return <span className="inline-flex size-4 shrink-0 items-center justify-center [&_img]:size-4 [&_svg]:size-4">{icon}</span>;
80
+ }
81
+
82
+ function SidebarList({
83
+ items,
84
+ selected,
85
+ onSelect,
86
+ }: {
87
+ items: SidebarItemType[];
88
+ selected?: string;
89
+ onSelect?: SidebarProps["onSelect"];
90
+ }) {
91
+ return (
92
+ <>
93
+ {items.map((item, i) => {
94
+ const key = itemKey(item, i);
95
+ if (item.type === "divider") {
96
+ return <div key={key} className="mx-2 my-1 h-px bg-ink-line" />;
97
+ }
98
+ if (isGroup(item)) {
99
+ return (
100
+ <div key={key} className="mb-4">
101
+ {item.label != null && item.label !== "" ? (
102
+ <div className={cn("px-2 pb-1.5 pt-2 text-[11px] font-medium uppercase tracking-wider text-quaternary-foreground", item.className)}>
103
+ {item.label}
104
+ </div>
105
+ ) : null}
106
+ <div className="flex flex-col gap-0.5">
107
+ <SidebarList items={item.children ?? []} selected={selected} onSelect={onSelect} />
108
+ </div>
109
+ </div>
110
+ );
111
+ }
112
+
113
+ const active = selected != null && key === selected;
114
+ const className = cn(
115
+ "flex w-full items-center gap-2 rounded-md border-0 px-2 py-1.5 text-left text-sm no-underline",
116
+ item.disabled ? "pointer-events-none cursor-not-allowed opacity-40" : "cursor-pointer",
117
+ active ? "bg-ink-active font-medium text-foreground" : "bg-transparent text-foreground/80 hover:bg-ink-hover hover:text-foreground",
118
+ item.className,
119
+ );
120
+
121
+ const body = (
122
+ <>
123
+ <ItemIcon icon={item.icon} />
124
+ <span className="min-w-0 flex-1 truncate">{item.label}</span>
125
+ {item.extra != null ? <span className="shrink-0 text-xs tabular-nums text-muted-foreground">{item.extra}</span> : null}
126
+ </>
127
+ );
128
+
129
+ const activate = (e: MouseEvent<HTMLElement>) => {
130
+ if (item.disabled) {
131
+ e.preventDefault();
132
+ return;
133
+ }
134
+ if (item.href && (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0)) return;
135
+ if (item.href && onSelect) e.preventDefault();
136
+ onSelect?.({ key, item });
137
+ };
138
+
139
+ if (item.href) {
140
+ return (
141
+ <a key={key} href={item.href} aria-current={active ? "page" : undefined} aria-disabled={item.disabled || undefined} className={className} onClick={activate}>
142
+ {body}
143
+ </a>
144
+ );
145
+ }
146
+
147
+ return (
148
+ <button key={key} type="button" aria-current={active ? "true" : undefined} disabled={item.disabled} className={className} onClick={activate}>
149
+ {body}
150
+ </button>
151
+ );
152
+ })}
153
+ </>
154
+ );
155
+ }
156
+
157
+ /** Grouped side nav — pass JSON groups + items. Router stays in the app (`onSelect` / `href`). */
158
+ export function Sidebar({
159
+ items = [],
160
+ selectedKey,
161
+ defaultSelectedKey,
162
+ onSelect,
163
+ searchable = false,
164
+ searchPlaceholder = "Search…",
165
+ header,
166
+ footer,
167
+ emptyText = "No matches.",
168
+ className,
169
+ "aria-label": ariaLabel = "Sidebar",
170
+ }: SidebarProps) {
171
+ const [query, setQuery] = useState("");
172
+ const [uncontrolled, setUncontrolled] = useState(defaultSelectedKey);
173
+ const selected = selectedKey ?? uncontrolled;
174
+
175
+ const visible = useMemo(() => filterItems(items, query.trim().toLowerCase()), [items, query]);
176
+
177
+ const handleSelect = (info: SidebarSelectInfo) => {
178
+ if (selectedKey === undefined) setUncontrolled(info.key);
179
+ onSelect?.(info);
180
+ };
181
+
182
+ return (
183
+ <div className={cn("flex h-full min-h-0 flex-col", className)}>
184
+ {header}
185
+ {searchable ? (
186
+ <div className={cn("shrink-0 px-3 pb-2", header ? "pt-1" : "pt-3")}>
187
+ <SearchInput size="small" wait={0} placeholder={searchPlaceholder} onChange={setQuery} />
188
+ </div>
189
+ ) : null}
190
+ <OverlayScroll className="min-h-0 flex-1" innerClassName={cn("px-2 pb-6", !searchable && !header && "pt-2")}>
191
+ <nav aria-label={ariaLabel}>
192
+ {visible.length === 0 ? <p className="px-2 py-4 text-sm text-muted-foreground">{emptyText}</p> : <SidebarList items={visible} selected={selected} onSelect={handleSelect} />}
193
+ </nav>
194
+ </OverlayScroll>
195
+ {footer}
196
+ </div>
197
+ );
198
+ }