Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(ui): stabilize community rows and native keyboard spacing (#1101)
Generdcbb061c6667
diff --git a/scripts/ci/native-shell-theme-colors.test.ts b/scripts/ci/native-shell-theme-colors.test.tsindex 186a5c4fa..0556c9cf1 100644--- a/scripts/ci/native-shell-theme-colors.test.ts+++ b/scripts/ci/native-shell-theme-colors.test.ts@@ -99,6 +99,46 @@ function driveIosThemeObserver(initial: Array<"light" | "dark"> = []) {}describe("native shell theme color contract", () => {+ it("separates full native framing from the current root's keyboard overlap", () => {+ const layout = iosRuntime.split("- (void)alook_viewDidLayoutSubviews {")[1]?.split("\n}\n")[0] ?? ""+ const install = iosRuntime.split("static void alookInstallKeyboardLayout(")[1]?.split("\n}\n")[0] ?? ""+ expect(layout.indexOf("alookInstallKeyboardLayout(self)")).toBeGreaterThanOrEqual(0)+ expect(layout.indexOf("alookInstallKeyboardLayout(self)")).toBeLessThan(layout.indexOf("alookPublishKeyboardSnapshots(self)"))+ expect(install).toContain("previous.superview == host")+ expect(install).toContain("removeFromSuperview")+ expect(install).toContain("host.keyboardLayoutGuide.topAnchor")+ expect(install).toContain("translatesAutoresizingMaskIntoConstraints = NO")+ expect(layout).not.toContain("contentFrame = guide.layoutFrame")+ expect(layout).toContain("webView.frame = contentFrame")+ expect(layout.indexOf("webView.frame = contentFrame")).toBeLessThan(layout.indexOf("alookPublishKeyboardSnapshots(self)"))+ })++ it("measures snapshot requests live and publishes after the guide-constrained native view lays out", () => {+ const measure = iosRuntime.split("static NSDictionary *alookMeasureKeyboardSnapshot(")[1]?.split("\n}\n")[0] ?? ""+ const observer = iosRuntime.split("@implementation AlookKeyboardLayoutView")[1]?.split("@end")[0] ?? ""+ const handler = iosRuntime.split("@implementation AlookKeyboardHandler")[1]?.split("@end")[0] ?? ""+ const publish = iosRuntime.split("static void alookPublishKeyboardSnapshots(")[1]?.split("\n}\n")[0] ?? ""+ expect(measure).toContain("convertRect:host.keyboardLayoutGuide.layoutFrame fromView:host")+ expect(measure).toContain("CGRectIntersectsRect(bounds, keyboardFrame)")+ expect(measure).toContain("@\"bottomInset\"")+ expect(measure).toContain("@\"viewportWidth\"")+ expect(observer).toContain("[super layoutSubviews]")+ expect(observer).toContain("alookPublishKeyboardSnapshots(controller)")+ expect(observer.indexOf("[super layoutSubviews]")).toBeLessThan(observer.indexOf("alookPublishKeyboardSnapshots(controller)"))+ expect(handler).toContain("replyHandler(alookMeasureKeyboardSnapshot(controller, webView), nil)")+ expect(handler).toContain("webView.superview != controller.view")+ expect(handler).not.toContain("objc_getAssociatedObject")+ expect(publish).toContain("alookMeasureKeyboardSnapshot(controller, webView)")+ expect(publish).toContain("isEqualToDictionary:published")+ expect(publish).toContain("alook:keyboard-change")+ })+ it("disables the iOS input accessory in all effective main-window definitions", () => {+ for (const file of ["tauri.conf.json", "tauri.dev.conf.json", "tauri.ios.release.conf.json"]) {+ const config = JSON.parse(readFileSync(resolve(desktopRoot, file), "utf8"))+ expect(config.app.windows).toHaveLength(1)+ expect(config.app.windows[0]).toMatchObject({ label: "main", disableInputAccessoryView: true })+ }+ })it("uses white light chrome and preserves dark chrome on macOS", () => {expect(macosRuntime).toContain("(0.063f64, 0.051f64, 0.039f64)")expect(macosRuntime).toContain("(1.0f64, 1.0f64, 1.0f64)")diff --git a/src/desktop/src-tauri/gen/apple/Sources/alook-desktop/main.mm b/src/desktop/src-tauri/gen/apple/Sources/alook-desktop/main.mmindex f8567a8e0..ecaaa95de 100644--- a/src/desktop/src-tauri/gen/apple/Sources/alook-desktop/main.mm+++ b/src/desktop/src-tauri/gen/apple/Sources/alook-desktop/main.mm@@ -14,6 +14,8 @@ static UIColor *alookDarkColor(void) {static const void *kAlookResolvedDarkThemeKey = &kAlookResolvedDarkThemeKey;static const void *kAlookWebDarkThemeKey = &kAlookWebDarkThemeKey;static const void *kAlookSafeAreaTopKey = &kAlookSafeAreaTopKey;+static const void *kAlookKeyboardLayoutViewKey = &kAlookKeyboardLayoutViewKey;+static const void *kAlookPublishedKeyboardSnapshotKey = &kAlookPublishedKeyboardSnapshotKey;static const void *kAlookStartupOverlayKey = &kAlookStartupOverlayKey;static const void *kAlookStartupCompletedKey = &kAlookStartupCompletedKey;static const NSInteger kAlookStartupLogoTag = 8738;@@ -27,6 +29,75 @@ static BOOL alookIsTauriRootController(UIViewController *viewController) {return taoViewController != Nil && [viewController isKindOfClass:taoViewController];}+static NSDictionary *alookMeasureKeyboardSnapshot(UIViewController *controller, WKWebView *webView) {+ UIView *host = controller.view;+ CGRect keyboardFrame = [webView convertRect:host.keyboardLayoutGuide.layoutFrame fromView:host];+ CGRect bounds = webView.bounds;+ CGFloat bottomInset = CGRectIntersectsRect(bounds, keyboardFrame)+ ? MIN(bounds.size.height, MAX(0, CGRectGetMaxY(bounds) - CGRectGetMinY(keyboardFrame)))+ : 0;+ return @{+ @"bottomInset": @(bottomInset),+ @"viewportWidth": @(bounds.size.width)+ };+}++static void alookPublishKeyboardSnapshots(UIViewController *controller) {+ if (!alookIsTauriRootController(controller) || !controller.isViewLoaded) return;+ for (UIView *subview in controller.view.subviews) {+ if (![subview isKindOfClass:[WKWebView class]]) continue;+ WKWebView *webView = (WKWebView *)subview;+ NSDictionary *snapshot = alookMeasureKeyboardSnapshot(controller, webView);+ NSDictionary *published = objc_getAssociatedObject(webView, kAlookPublishedKeyboardSnapshotKey);+ if (![snapshot isEqualToDictionary:published]) {+ objc_setAssociatedObject(webView, kAlookPublishedKeyboardSnapshotKey, snapshot, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ [webView evaluateJavaScript:@"window.dispatchEvent(new Event('alook:keyboard-change'))" completionHandler:nil];+ }+ }+}++@interface AlookKeyboardLayoutView : UIView+@property (nonatomic, weak) UIViewController *viewController;+@end++@implementation AlookKeyboardLayoutView++- (void)layoutSubviews {+ [super layoutSubviews];+ UIViewController *controller = self.viewController;+ if (controller != nil && self.superview == controller.view) alookPublishKeyboardSnapshots(controller);+}++@end++static void alookInstallKeyboardLayout(UIViewController *controller) {+ if (!alookIsTauriRootController(controller)) return;+ UIView *host = controller.view;+ AlookKeyboardLayoutView *previous = objc_getAssociatedObject(controller, kAlookKeyboardLayoutViewKey);+ if (previous.superview == host) return;+ [previous removeFromSuperview];+ AlookKeyboardLayoutView *content = [[AlookKeyboardLayoutView alloc] init];+ content.viewController = controller;+ content.accessibilityIdentifier = @"alook.keyboard-layout";+ content.accessibilityElementsHidden = YES;+ content.userInteractionEnabled = NO;+ content.opaque = NO;+ content.backgroundColor = UIColor.clearColor;+ content.translatesAutoresizingMaskIntoConstraints = NO;+ [host insertSubview:content atIndex:0];+ NSLayoutConstraint *bottom = [content.bottomAnchor constraintEqualToAnchor:host.keyboardLayoutGuide.topAnchor];+ bottom.priority = UILayoutPriorityRequired - 1;+ [NSLayoutConstraint activateConstraints:@[+ [content.topAnchor constraintEqualToAnchor:host.safeAreaLayoutGuide.topAnchor],+ [content.leadingAnchor constraintEqualToAnchor:host.safeAreaLayoutGuide.leadingAnchor],+ [content.trailingAnchor constraintEqualToAnchor:host.safeAreaLayoutGuide.trailingAnchor],+ [content.heightAnchor constraintGreaterThanOrEqualToConstant:0],+ bottom+ ]];+ objc_setAssociatedObject(controller, kAlookKeyboardLayoutViewKey, content, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ [host setNeedsLayout];+}+static UIView *alookStartupHostView(UIViewController *viewController) {if ([gAlookStartupOverlay.superview isKindOfClass:[UIWindow class]]) {return gAlookStartupOverlay.superview;@@ -212,6 +283,34 @@ static NSString *const kThemeObserverScript =@end+@interface AlookKeyboardHandler : NSObject <WKScriptMessageHandlerWithReply>+@property (nonatomic, weak) WKWebView *webView;+@property (nonatomic, weak) UIViewController *viewController;+@end++@implementation AlookKeyboardHandler++- (void)userContentController:(WKUserContentController *)userContentController+ didReceiveScriptMessage:(WKScriptMessage *)message+ replyHandler:(void (^)(id, NSString *))replyHandler {+ WKWebView *webView = self.webView;+ UIViewController *controller = self.viewController;+ if (webView == nil || controller == nil || webView.superview != controller.view ||+ message.webView != webView || ![message.frameInfo isMainFrame]) {+ replyHandler(nil, @"Keyboard view unavailable");+ return;+ }+ if ([message.body isEqual:@"dismiss"]) {+ [webView endEditing:YES];+ } else if (![message.body isEqual:@"snapshot"]) {+ replyHandler(nil, @"Invalid keyboard command");+ return;+ }+ replyHandler(alookMeasureKeyboardSnapshot(controller, webView), nil);+}++@end+@implementation UIViewController (AlookSafeArea)+ (BOOL)alook_finishStartupOverlayForController:(UIViewController *)controller@@ -289,12 +388,15 @@ static NSString *const kThemeObserverScript =- (void)alook_viewDidLayoutSubviews {[self alook_viewDidLayoutSubviews];BOOL isTauriRoot = alookIsTauriRootController(self);- if (isTauriRoot) alookPrepareStartupOverlay(self);+ if (isTauriRoot) {+ alookInstallKeyboardLayout(self);+ alookPrepareStartupOverlay(self);+ }UIEdgeInsets insets = self.view.safeAreaInsets;for (UIView *subview in self.view.subviews) {if ([subview isKindOfClass:[WKWebView class]]) {CGRect bounds = self.view.bounds;- subview.frame = CGRectMake(+ CGRect contentFrame = CGRectMake(insets.left,insets.top,bounds.size.width - insets.left - insets.right,@@ -311,12 +413,20 @@ static NSString *const kThemeObserverScript =addScriptMessageHandlerWithReply:handlercontentWorld:WKContentWorld.pageWorldname:@"alookSafeArea"];+ AlookKeyboardHandler *keyboard = [[AlookKeyboardHandler alloc] init];+ keyboard.webView = webView;+ keyboard.viewController = self;+ [webView.configuration.userContentController+ addScriptMessageHandlerWithReply:keyboard+ contentWorld:WKContentWorld.pageWorld+ name:@"alookKeyboard"];}if (previousTop == nil || previousTop.doubleValue != insets.top) {objc_setAssociatedObject(webView, kAlookSafeAreaTopKey, @(insets.top), OBJC_ASSOCIATION_RETAIN_NONATOMIC);[webView evaluateJavaScript:@"window.dispatchEvent(new Event('alook:safe-area-change'))" completionHandler:nil];}}+ if (!CGRectEqualToRect(webView.frame, contentFrame)) webView.frame = contentFrame;static dispatch_once_t scriptToken;dispatch_once(&scriptToken, ^{AlookThemeHandler *handler = [[AlookThemeHandler alloc] init];@@ -333,7 +443,7 @@ static NSString *const kThemeObserverScript =alookApplyTheme(self, alookEffectiveDarkTheme(self));}}-+ if (isTauriRoot) alookPublishKeyboardSnapshots(self);}@enddiff --git a/src/desktop/src-tauri/tauri.conf.json b/src/desktop/src-tauri/tauri.conf.jsonindex c28fc3a67..496a6180e 100644--- a/src/desktop/src-tauri/tauri.conf.json+++ b/src/desktop/src-tauri/tauri.conf.json@@ -37,6 +37,7 @@"visible": false,"titleBarStyle": "Overlay","hiddenTitle": true,+ "disableInputAccessoryView": true,"trafficLightPosition": {"x": 16,"y": 21diff --git a/src/desktop/src-tauri/tauri.dev.conf.json b/src/desktop/src-tauri/tauri.dev.conf.jsonindex bd282cc85..7f1cb03e6 100644--- a/src/desktop/src-tauri/tauri.dev.conf.json+++ b/src/desktop/src-tauri/tauri.dev.conf.json@@ -129,6 +129,7 @@"minHeight": 600,"center": true,"visible": false,+ "disableInputAccessoryView": true,"titleBarStyle": "Overlay","hiddenTitle": true,"trafficLightPosition": {diff --git a/src/desktop/src-tauri/tauri.ios.release.conf.json b/src/desktop/src-tauri/tauri.ios.release.conf.jsonindex 39a05db9f..491be7ac9 100644--- a/src/desktop/src-tauri/tauri.ios.release.conf.json+++ b/src/desktop/src-tauri/tauri.ios.release.conf.json@@ -14,6 +14,7 @@"visible": false,"titleBarStyle": "Overlay","hiddenTitle": true,+ "disableInputAccessoryView": true,"trafficLightPosition": {"x": 16,"y": 21diff --git a/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx b/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsxindex a68c16fb1..4be25d252 100644--- a/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx+++ b/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx@@ -1,6 +1,6 @@import { createElement } from "react"import { afterEach, beforeEach, expect, it, vi } from "vitest"-import { act, mockElementGeometry, render } from "@/test/react-dom-harness"+import { act, fireEvent, mockElementGeometry, render } from "@/test/react-dom-harness"import type { ForumThread } from "@/lib/community/models/message"import { tid } from "@/lib/community/testids"import { ForumView } from "./forum-view"@@ -41,6 +41,43 @@ beforeEach(() => {afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() })+it.each([{ kind: "short", name: "Short title" }, { kind: "long", name: "Long title ".repeat(40).trim() }])("preserves $kind title and action ownership while capabilities change", ({ name }) => {+ const open = vi.fn()+ const edit = vi.fn()+ const remove = vi.fn()+ const post = { ...posts[0], name, parentSeq: 42 }+ const props = {+ forumChannelId: "forum-actions", members: [], posts: [post], tag: "All",+ onTagChange: () => {}, onOpenPost: open, onEditPostTags: edit, onDeletePost: remove,+ onScrollRoot: (node: HTMLDivElement | null) => {+ if (node) mockElementGeometry(node, { clientHeight: 751, clientWidth: 390 })+ },+ }+ const view = render(createElement(ForumView, { ...props, canEditPostTags: () => false, canDeletePost: () => false }))+ const card = view.getByTestId(tid.forumThreadCard(post.id))+ const title = view.getByTestId(tid.forumThreadTitle(post.id))+ const text = view.getByTestId(tid.forumThreadTitleText(post.id))+ for (const actions of [1, 2, 3, 0]) {+ view.rerender(createElement(ForumView, {+ ...props, canEditPostTags: () => actions >= 2, canDeletePost: () => actions === 1 || actions === 3,+ }))+ expect(view.getByTestId(tid.forumThreadCard(post.id))).toBe(card)+ expect(view.getByTestId(tid.forumThreadTitle(post.id))).toBe(title)+ expect(view.getByTestId(tid.forumThreadTitleText(post.id))).toBe(text)+ expect(title).toHaveAccessibleName(`${name} #42`)+ expect(card.querySelectorAll("button")).toHaveLength(actions)+ if (actions >= 2) {+ fireEvent.click(view.getByTestId(tid.forumThreadArchiveBtn(post.id)))+ expect(edit).toHaveBeenLastCalledWith(post.id, ["archived"])+ expect(open).not.toHaveBeenCalled()+ }+ }+ fireEvent.click(text)+ fireEvent.keyDown(card, { key: "Enter" })+ expect(open.mock.calls).toEqual([[post.id], [post.id]])+ expect(remove).not.toHaveBeenCalled()+})+it("keeps native forum rows positioned without individual transforms across scrolling and append", () => {const onLoadMore = vi.fn()const onScrollRoot = (node: HTMLDivElement | null) => {diff --git a/src/web/src/components/community/channels/forum-view.test.ts b/src/web/src/components/community/channels/forum-view.test.tsindex 1589ae7ba..60b588a4f 100644--- a/src/web/src/components/community/channels/forum-view.test.ts+++ b/src/web/src/components/community/channels/forum-view.test.ts@@ -297,8 +297,10 @@ describe("ForumView responsive post actions", () => {expect(archiveButton).toContain('aria-pressed="false"')expect(archiveButton).toContain("disabled:opacity-50")expect(deleteButton).toContain("disabled:opacity-50")- expect(html).toContain("min-h-8 pr-28")- expect(html).toContain("w-full min-w-0 max-w-full text-[15px] font-semibold leading-tight")+ expect(html).toContain("grid-cols-[minmax(0,1fr)_auto]")+ expect(html).toContain("row-span-2")+ expect(html).not.toContain("min-h-8")+ expect(html).toContain("w-full min-w-0 max-w-full self-start text-[15px] font-semibold leading-tight")expect(html).toContain(tid.forumThreadTitle("p1"))expect(html).toContain(tid.forumThreadTitleText("p1"))expect(html).toContain(tid.forumThreadSeq("p1"))@@ -330,7 +332,8 @@ describe("ForumView responsive post actions", () => {expect(html).not.toContain(tid.forumThreadArchiveBtn("p1"))expect(html).not.toContain(tid.forumThreadDeleteBtn("p1"))expect(html).not.toContain("min-h-8")- expect(html).toContain("pr-0")+ expect(html).toContain("grid-cols-1")+ expect(html).not.toContain("grid-cols-[minmax(0,1fr)_auto]")})it("does not expose the archive action when the user may only delete", () => {@@ -339,7 +342,8 @@ describe("ForumView responsive post actions", () => {expect(html).not.toContain(tid.forumThreadTagBtn("p1"))expect(html).not.toContain(tid.forumThreadArchiveBtn("p1"))expect(html).toContain(tid.forumThreadDeleteBtn("p1"))- expect(html).toContain("min-h-8 pr-12")+ expect(html).toContain("grid-cols-[minmax(0,1fr)_auto]")+ expect(html).not.toContain("min-h-8")})})diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsxindex 2c72d167e..af52ecd60 100644--- a/src/web/src/components/community/channels/forum-view.tsx+++ b/src/web/src/components/community/channels/forum-view.tsx@@ -100,7 +100,7 @@ const ForumPostTitle = memo(function ForumPostTitle({ name, postId, seq }: { namdata-testid={tid.forumThreadTitle(postId)}aria-label={`${name}${seq === undefined ? "" : ` #${seq}`}`}title={name}- className="w-full min-w-0 max-w-full text-[15px] font-semibold leading-tight"+ className="w-full min-w-0 max-w-full self-start text-[15px] font-semibold leading-tight"><LineClamptext={name}@@ -322,76 +322,71 @@ export function ForumView({index === posts.length - 1 && "border-b-0",)}>- {(canEdit || canDelete) && (- <div- className="absolute right-3 top-3 z-10 flex items-center gap-1"- onClick={(event) => event.stopPropagation()}- onKeyDown={(event) => event.stopPropagation()}- >- {canEdit && (- <PostTagDialog- trigger={(- <button- type="button"- data-testid={tid.forumThreadTagBtn(p.id)}- onClick={(event) => event.stopPropagation()}- className={cn(POST_ACTION_CLASS, "hover:bg-accent hover:text-foreground")}- aria-label="Edit tags"- >- <Tag className="size-4" />- </button>- )}- postName={p.name}- current={p.tags}- allTags={availableTags}- saving={savingTagsFor === p.id}- onSave={(tags) => onEditPostTags?.(p.id, tags)}- />- )}- {canEdit && (- <button- type="button"- data-testid={tid.forumThreadArchiveBtn(p.id)}- disabled={savingTags}- onClick={(event) => {- event.stopPropagation()- void Promise.resolve(- onEditPostTags?.(p.id, toggleForumArchivedStatus(p.tags)),- ).catch(() => undefined)- }}- className={cn(POST_ACTION_CLASS, "hover:bg-accent hover:text-foreground")}- aria-label={archived ? "Unarchive post" : "Archive post"}- aria-pressed={archived}- >- {archived- ? <ArchiveRestore aria-hidden="true" className="size-4" />- : <Archive aria-hidden="true" className="size-4" />}- </button>- )}- {canDelete && (- <button- type="button"- data-testid={tid.forumThreadDeleteBtn(p.id)}- disabled={deletingPost === p.id}- onClick={(e) => { e.stopPropagation(); setDeletingFor(p) }}- className={cn(POST_ACTION_CLASS, "hover:bg-accent hover:text-destructive")}- aria-label="Delete post"+ <div className={cn("grid grid-rows-[max-content_auto] gap-x-2", actionCount > 0 ? "grid-cols-[minmax(0,1fr)_auto]" : "grid-cols-1")}>+ <ForumPostTitle name={p.name} postId={p.id} seq={p.parentSeq} />+ {(canEdit || canDelete) && (+ <div+ className="col-start-2 row-span-2 row-start-1 z-10 flex items-start gap-1"+ onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => event.stopPropagation()}>- <Trash2 className="size-4" />- </button>- )}- </div>- )}+ {canEdit && (+ <PostTagDialog+ trigger={(+ <button+ type="button"+ data-testid={tid.forumThreadTagBtn(p.id)}+ onClick={(event) => event.stopPropagation()}+ className={cn(POST_ACTION_CLASS, "hover:bg-accent hover:text-foreground")}+ aria-label="Edit tags"+ >+ <Tag className="size-4" />+ </button>+ )}+ postName={p.name}+ current={p.tags}+ allTags={availableTags}+ saving={savingTagsFor === p.id}+ onSave={(tags) => onEditPostTags?.(p.id, tags)}+ />+ )}+ {canEdit && (+ <button+ type="button"+ data-testid={tid.forumThreadArchiveBtn(p.id)}+ disabled={savingTags}+ onClick={(event) => {+ event.stopPropagation()+ void Promise.resolve(+ onEditPostTags?.(p.id, toggleForumArchivedStatus(p.tags)),+ ).catch(() => undefined)+ }}+ className={cn(POST_ACTION_CLASS, "hover:bg-accent hover:text-foreground")}+ aria-label={archived ? "Unarchive post" : "Archive post"}+ aria-pressed={archived}+ >+ {archived+ ? <ArchiveRestore aria-hidden="true" className="size-4" />+ : <Archive aria-hidden="true" className="size-4" />}+ </button>+ )}+ {canDelete && (+ <button+ type="button"+ data-testid={tid.forumThreadDeleteBtn(p.id)}+ disabled={deletingPost === p.id}+ onClick={(e) => { e.stopPropagation(); setDeletingFor(p) }}+ className={cn(POST_ACTION_CLASS, "hover:bg-accent hover:text-destructive")}+ aria-label="Delete post"+ >+ <Trash2 className="size-4" />+ </button>+ )}+ </div>+ )}- <div className={cn(- actionCount === 3 && "min-h-8 pr-28",- actionCount === 2 && "min-h-8 pr-20",- actionCount === 1 && "min-h-8 pr-12",- actionCount === 0 && "pr-0",- )}>- <ForumPostTitle name={p.name} postId={p.id} seq={p.parentSeq} />+ <p data-slot="community-forum-post-preview" className="mb-2.25 mt-0.75 line-clamp-2 text-[13.5px] text-muted-foreground">{p.preview}</p></div>- <p className="mb-2.25 mt-0.75 line-clamp-2 text-[13.5px] text-muted-foreground">{p.preview}</p><div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5 text-xs text-muted-foreground"><Avatar label={author.avatar} seed={p.authorId} size={20} /><span className="shrink-0 font-medium text-foreground" suppressHydrationWarning>{author.name}</span>diff --git a/src/web/src/components/community/channels/sortable-category.presentation.dom.test.tsx b/src/web/src/components/community/channels/sortable-category.presentation.dom.test.tsxnew file mode 100644index 000000000..ea6ed04df--- /dev/null+++ b/src/web/src/components/community/channels/sortable-category.presentation.dom.test.tsx@@ -0,0 +1,60 @@+import { describe, expect, it, vi } from "vitest"+import { fireEvent, mockElementGeometry, render } from "@/test/react-dom-harness"+import { tid } from "@/lib/community/testids"+import { CommunityDndProvider } from "../community-dnd"+import { SortableCategory } from "./sortable-category"++describe.each([false, true])("category presentation (private=%s)", isPrivate => {+ it.each([0, 1, 2])("preserves category identity with %i optional actions", actionCount => {+ const toggle = vi.fn()+ const settings = vi.fn()+ const create = vi.fn()+ const view = render(<CommunityDndProvider>+ <SortableCategory id="category" name="Projects" open onToggle={toggle} isPrivate={isPrivate}+ hasChannels canReorder={false} onSettings={actionCount > 0 ? settings : undefined}+ onAddChannel={actionCount > 1 ? create : undefined}>+ <span>Category content</span>+ </SortableCategory>+ </CommunityDndProvider>)+ const header = view.getByTestId(tid.categoryHeader("category"))+ mockElementGeometry(header, { width: 240, height: 24 })+ expect(header).toHaveAccessibleName("Projects")+ expect(header).toHaveAttribute("aria-description", isPrivate ? "Private category" : "Public category")+ expect(header).toHaveAttribute("aria-expanded", "true")+ expect(header.querySelector(isPrivate ? ".lucide-message-square-lock" : ".lucide-messages-square")).not.toBeNull()+ expect(header.querySelector(isPrivate ? ".lucide-messages-square" : ".lucide-message-square-lock")).toBeNull()+ const glyphs = [...header.querySelectorAll("svg")]+ expect(glyphs).toHaveLength(2 + actionCount)+ for (const glyph of glyphs) expect(glyph).toHaveClass("size-3")+ fireEvent.click(header)+ fireEvent.keyDown(header, { key: "Enter" })+ expect(toggle).toHaveBeenCalledTimes(2)+ toggle.mockClear()+ if (actionCount > 0) {+ const button = view.getByRole("button", { name: "Category settings for Projects" })+ fireEvent.click(button)+ fireEvent.keyDown(button, { key: "Enter" })+ expect(settings).toHaveBeenCalledOnce()+ }+ if (actionCount > 1) {+ fireEvent.click(view.getByRole("button", { name: "Create channel in Projects" }))+ expect(create).toHaveBeenCalledOnce()+ }+ expect(toggle).not.toHaveBeenCalled()+ })++ it("keeps an empty category's identity without a disclosure action", () => {+ const toggle = vi.fn()+ const view = render(<CommunityDndProvider>+ <SortableCategory id="empty" name="Empty" open onToggle={toggle} isPrivate={isPrivate}+ hasChannels={false} canReorder={false}>{null}</SortableCategory>+ </CommunityDndProvider>)+ const header = view.getByTestId(tid.categoryHeader("empty"))+ mockElementGeometry(header, { width: 240, height: 24 })+ expect(header).not.toHaveAttribute("aria-expanded")+ expect(header.querySelectorAll("svg")).toHaveLength(1)+ fireEvent.click(header)+ fireEvent.keyDown(header, { key: "Enter" })+ expect(toggle).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/components/community/channels/sortable-category.tsx b/src/web/src/components/community/channels/sortable-category.tsxindex b6cc1e597..eb648d099 100644--- a/src/web/src/components/community/channels/sortable-category.tsx+++ b/src/web/src/components/community/channels/sortable-category.tsx@@ -3,7 +3,7 @@import { useAtom, useCreateAtom } from "@tanstack/react-store";import type React from "react"-import { ChevronDown, Plus, Settings, Folder, Lock, Trash2 } from "lucide-react"+import { ChevronDown, Plus, Settings, MessagesSquare, MessageSquareLock, Trash2 } from "lucide-react"import { useChannelDndItem } from "./channel-dnd"import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, isKeyboardContextMenu } from "@/components/ui/context-menu"import { ConfirmDialog } from "@/components/ui/confirm-dialog"@@ -54,7 +54,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan}const headerInner = (<>- {isPrivate ? <Lock className="pointer-events-none size-3 shrink-0" aria-hidden="true" /> : <Folder className="pointer-events-none size-3 shrink-0" aria-hidden="true" />}+ {isPrivate ? <MessageSquareLock className="pointer-events-none size-3 shrink-0" aria-hidden="true" /> : <MessagesSquare className="pointer-events-none size-3 shrink-0" aria-hidden="true" />}<span className="pointer-events-none flex-1 truncate text-left">{name}</span>{onSettings && (<button@@ -65,7 +65,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChanclassName="grid size-4 place-items-center rounded opacity-0 hover:bg-accent group-hover:opacity-100"aria-label={`Category settings for ${name}`}>- <Settings className="size-3.5" />+ <Settings className="size-3" /></button>)}{onAddChannel && (@@ -77,7 +77,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChanclassName="grid size-4 place-items-center rounded opacity-0 hover:bg-accent group-hover:opacity-100"aria-label={`Create channel in ${name}`}>- <Plus className="size-3.5" />+ <Plus className="size-3" /></button>)}{hasChannels && <ChevronDown className={`pointer-events-none size-3 shrink-0 transition-transform ${open ? "" : "-rotate-90"}`} />}diff --git a/src/web/src/components/community/messages/composer-view.dom.test.ts b/src/web/src/components/community/messages/composer-view.dom.test.tsindex a70656995..01244ff98 100644--- a/src/web/src/components/community/messages/composer-view.dom.test.ts+++ b/src/web/src/components/community/messages/composer-view.dom.test.ts@@ -2,7 +2,7 @@ import { createElement, type ReactNode } from "react"import { readFileSync } from "node:fs"import { resolve } from "node:path"import { describe, expect, it, vi } from "vitest"-import { fireEvent, render } from "@/test/react-dom-harness"+import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"const mocks = vi.hoisted(() => ({mentionProps: vi.fn(),@@ -18,6 +18,7 @@ vi.mock("lucide-react", () => ({FileIcon: (props: Record<string, unknown>) => createElement("span", { ...props, "data-file-icon": "" }),ImageIcon: (props: Record<string, unknown>) =>createElement("span", { ...props, "data-image-icon": "" }),+ Keyboard: (props: Record<string, unknown>) => createElement("span", { ...props, "data-keyboard-icon": "" }),PlusCircle: (props: Record<string, unknown>) =>createElement("span", { ...props, "data-plus-icon": "" }),Smile: (props: Record<string, unknown>) => createElement("span", { ...props, "data-smile-icon": "" }),@@ -85,6 +86,49 @@ function baseProps(}describe("ComposerView", () => {+ it("dismisses the native keyboard without replacing draft, reply, attachments or send ownership", async () => {+ const descriptor = Object.getOwnPropertyDescriptor(window, "webkit")+ const tauriDescriptor = Object.getOwnPropertyDescriptor(window, "__TAURI__")+ Object.defineProperty(window, "__TAURI__", { configurable: true, value: {} })+ let visible = false+ const postMessage = vi.fn(async () => ({ bottomInset: visible ? 300 : 0, viewportWidth: window.innerWidth }))+ Object.defineProperty(window, "webkit", { configurable: true, value: { messageHandlers: { alookKeyboard: { postMessage } } } })+ try {+ const props = baseProps({+ showSend: true, sendDisabled: false, onCancelReply: vi.fn(), replyingTo: { authorName: "Alice", text: "Original reply" },+ pendingFiles: [{ file: new File(["image"], "draft.png", { type: "image/png" }), thumbnailUrl: null, thumbnailBlob: null }],+ editorContent: createElement("div", { contentEditable: true, suppressContentEditableWarning: true }, "Unsent draft"),+ })+ const view = render(createElement(ComposerView, props))+ const input = view.getByTestId(tid.composerInput)+ const editor = input.firstElementChild+ const send = view.getByTestId(tid.composerSend)+ expect(view.queryByRole("button", { name: "Hide keyboard" })).toBeNull()+ visible = true+ act(() => window.dispatchEvent(new Event("alook:keyboard-change")))+ await waitFor(() => expect(view.getByRole("button", { name: "Hide keyboard" })).toBeVisible())+ fireEvent.click(view.getByRole("button", { name: "Hide keyboard" }))+ expect(postMessage).toHaveBeenLastCalledWith("dismiss")+ expect(props.onSend).not.toHaveBeenCalled()+ expect(props.onCancelReply).not.toHaveBeenCalled()+ expect(props.removePendingFile).not.toHaveBeenCalled()+ visible = false+ act(() => window.dispatchEvent(new Event("alook:keyboard-change")))+ await waitFor(() => expect(view.queryByRole("button", { name: "Hide keyboard" })).toBeNull())+ expect(view.getByTestId(tid.composerInput)).toBe(input)+ expect(input.firstElementChild).toBe(editor)+ expect(input.textContent).toBe("Unsent draft")+ expect(view.getByText("draft.png")).toBeVisible()+ expect(view.getByTestId(tid.composerSend)).toBe(send)+ fireEvent.click(send)+ expect(props.onSend).toHaveBeenCalledOnce()+ } finally {+ if (descriptor) Object.defineProperty(window, "webkit", descriptor)+ else Reflect.deleteProperty(window, "webkit")+ if (tauriDescriptor) Object.defineProperty(window, "__TAURI__", tauriDescriptor)+ else Reflect.deleteProperty(window, "__TAURI__")+ }+ })it("replaces only editor content for a preview and restores the native editor by default", () => {const onSend = vi.fn()const props = baseProps({ showSend: true, sendDisabled: false, onSend })diff --git a/src/web/src/components/community/messages/composer-view.tsx b/src/web/src/components/community/messages/composer-view.tsxindex 2d808e4bc..696726f3a 100644--- a/src/web/src/components/community/messages/composer-view.tsx+++ b/src/web/src/components/community/messages/composer-view.tsx@@ -8,6 +8,7 @@ import { EditorContent, type Editor } from "@tiptap/react"import {FileIcon,ImageIcon,+ Keyboard,PlusCircle,Smile,X,@@ -32,6 +33,7 @@ import {import type { ComposerReplyTarget, MentionCandidateSource } from "./composer-types"import { SendStrokeRoundedIcon } from "./send-stroke-rounded-icon"import { useHydratedClient } from "@/components/community/shell/use-hydrated-client"+import { useNativeKeyboard } from "@/hooks/use-native-keyboard"const COMPOSER_OUTER_CLASS ="relative pl-[var(--community-composer-inline-start)] pr-[var(--community-composer-inline-end)] pb-[calc(0.75rem+var(--app-safe-area-bottom))] pt-0 sm:pb-3"@@ -94,6 +96,8 @@ export function ComposerView({onEmojiPick,}: ComposerViewProps) {const nativeMobile = useHydratedClient() && isMobile()+ const keyboard = useNativeKeyboard()+ const trailingControl = showSend || !hideEmojiconst replyPreview = replyingTo? stripInlineMarkup(replyingTo.text).replace(/\s+/g, " ").trim(): null@@ -207,7 +211,9 @@ export function ComposerView({/><divclassName={`chat-composer relative py-3 ${- isForumThreadBody+ keyboard.visible+ ? `${isForumThreadBody ? "pl-2" : "pl-12"} ${trailingControl ? "pr-24" : "pr-12"}`+ : isForumThreadBody? "px-2": showSend ? "pl-12 pr-16 sm:px-12" : "px-12"}`}@@ -239,6 +245,17 @@ export function ComposerView({</button></EmojiPickerPopover>)}+ {keyboard.visible && (+ <button+ type="button"+ aria-label="Hide keyboard"+ className={`absolute bottom-0.5 grid size-11 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${trailingControl ? "right-11" : "right-0.5"}`}+ onPointerDown={(event) => event.preventDefault()}+ onClick={keyboard.dismiss}+ >+ <Keyboard className="size-5" />+ </button>+ )}{showSend && (<buttontype="button"diff --git a/src/web/src/components/community/messages/conversation-footer-shell.dom.test.tsx b/src/web/src/components/community/messages/conversation-footer-shell.dom.test.tsxindex 2babf06d0..ce7e25664 100644--- a/src/web/src/components/community/messages/conversation-footer-shell.dom.test.tsx+++ b/src/web/src/components/community/messages/conversation-footer-shell.dom.test.tsx@@ -1,14 +1,78 @@import React from "react"import { createPortal } from "react-dom"-import { fireEvent, render } from "@/test/react-dom-harness"-import { describe, expect, it } from "vitest"+import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"+import { afterEach, describe, expect, it } from "vitest"+import { ConversationPresentationContext } from "@/contexts/community/conversation-activity"import {ConversationFooterShell,ConversationFooterSlotProvider,useConversationFooterSlot,} from "./conversation-footer-shell"+const originalWebkit = Object.getOwnPropertyDescriptor(window, "webkit")+const originalTauri = Object.getOwnPropertyDescriptor(window, "__TAURI__")+afterEach(() => {+ if (originalWebkit) Object.defineProperty(window, "webkit", originalWebkit)+ else Reflect.deleteProperty(window, "webkit")+ if (originalTauri) Object.defineProperty(window, "__TAURI__", originalTauri)+ else Reflect.deleteProperty(window, "__TAURI__")+})+describe("ConversationFooterShell", () => {+ it("reserves native occlusion only in the conversation footer and restores the existing style and draft", async () => {+ Object.defineProperty(window, "__TAURI__", { configurable: true, value: {} })+ let bottomInset = 0+ Object.defineProperty(window, "webkit", { configurable: true, value: { messageHandlers: {+ alookKeyboard: { postMessage: async () => ({ bottomInset, viewportWidth: window.innerWidth }) },+ } } })+ const renderer = render(<div data-testid="shell" style={{ height: 600, display: "flex" }}>+ <aside data-testid="rail" style={{ width: 56 }}>Rail</aside>+ <aside data-testid="sidebar" style={{ width: 260 }}>Sidebar</aside>+ <section data-testid="conversation" style={{ display: "flex", flexDirection: "column", flex: 1 }}>+ <header data-testid="header">Channel</header>+ <div data-testid="messages" style={{ flex: 1 }}>Messages</div>+ <ConversationFooterShell data-testid="footer" style={{ marginBottom: 6, borderRadius: 8 }}>+ <input aria-label="Native draft" defaultValue="Unsent draft" />+ </ConversationFooterShell>+ </section>+ </div>)+ const footer = renderer.getByTestId("footer")+ const draft = renderer.getByRole("textbox", { name: "Native draft" })+ const stable = ["shell", "rail", "sidebar", "conversation", "header", "messages"]+ .map(id => ({ node: renderer.getByTestId(id), style: renderer.getByTestId(id).getAttribute("style") }))+ bottomInset = 300+ act(() => window.dispatchEvent(new Event("alook:keyboard-change")))+ await waitFor(() => expect(footer).toHaveStyle({ marginBottom: "300px", borderRadius: "8px" }))+ for (const entry of stable) expect(entry.node.getAttribute("style")).toBe(entry.style)+ expect(renderer.getByRole("textbox", { name: "Native draft" })).toBe(draft)+ expect(draft).toHaveValue("Unsent draft")+ bottomInset = 0+ act(() => window.dispatchEvent(new Event("alook:keyboard-change")))+ await waitFor(() => expect(footer).toHaveStyle({ marginBottom: "6px", borderRadius: "8px" }))+ expect(renderer.getByRole("textbox", { name: "Native draft" })).toBe(draft)+ })++ it("keeps retained inactive conversations out of native layout consumption", async () => {+ Object.defineProperty(window, "__TAURI__", { configurable: true, value: {} })+ Object.defineProperty(window, "webkit", { configurable: true, value: { messageHandlers: {+ alookKeyboard: { postMessage: async () => ({ bottomInset: 200, viewportWidth: window.innerWidth }) },+ } } })+ function Page({ presented }: { presented: boolean }) {+ return <ConversationPresentationContext value={presented}>+ <ConversationFooterShell data-testid="footer"><input aria-label="Retained draft" defaultValue="Keep" /></ConversationFooterShell>+ </ConversationPresentationContext>+ }+ const renderer = render(<Page presented={false} />)+ const draft = renderer.getByRole("textbox", { name: "Retained draft" })+ await act(async () => {})+ expect(renderer.getByTestId("footer").style.marginBottom).toBe("")+ renderer.rerender(<Page presented />)+ await waitFor(() => expect(renderer.getByTestId("footer")).toHaveStyle({ marginBottom: "200px" }))+ renderer.rerender(<Page presented={false} />)+ expect(renderer.getByTestId("footer").style.marginBottom).toBe("")+ expect(renderer.getByRole("textbox", { name: "Retained draft" })).toBe(draft)+ })+it("keeps ordinary composer content in normal flow", () => {const renderer = render(<ConversationFooterShell data-testid="footer">diff --git a/src/web/src/components/community/messages/conversation-footer-shell.tsx b/src/web/src/components/community/messages/conversation-footer-shell.tsxindex e7990a83b..d2b1898c7 100644--- a/src/web/src/components/community/messages/conversation-footer-shell.tsx+++ b/src/web/src/components/community/messages/conversation-footer-shell.tsx@@ -3,6 +3,8 @@import { useAtom, useCreateAtom, type Atom } from "@tanstack/react-store";import { createContext, useCallback, useContext, useMemo, type HTMLAttributes, type ReactNode } from "react"import { CONVERSATION_TAIL_SPACE_PX } from "@/lib/community/conversation-layout"+import { useNativeKeyboard } from "@/hooks/use-native-keyboard"+import { useConversationPresentation } from "@/contexts/community/conversation-activity"type ConversationFooterSlot = {target: HTMLDivElement | null@@ -50,10 +52,13 @@ export function useConversationFooterSlot(): ConversationFooterSlot | null {export function ConversationFooterShell({children,className,+ style,...props}: Omit<HTMLAttributes<HTMLDivElement>, "children"> & {children: ReactNode}) {+ const keyboard = useNativeKeyboard()+ const presented = useConversationPresentation()const footerSlot = useConversationFooterSlot()const setFooterTarget = footerSlot?.setTargetconst setAccessoryTarget = footerSlot?.setAccessoryTarget@@ -71,6 +76,7 @@ export function ConversationFooterShell({data-slot="community-conversation-footer"data-selection-active={selectionActive ? "true" : "false"}className={`relative shrink-0${className ? ` ${className}` : ""}`}+ style={presented && keyboard.bottomInset > 0 ? { ...style, marginBottom: keyboard.bottomInset } : style}><divref={bindAccessoryTarget}diff --git a/src/web/src/components/community/shell/server-rail.pending.dom.test.ts b/src/web/src/components/community/shell/server-rail.pending.dom.test.tsindex 03e073325..e1d5e84c9 100644--- a/src/web/src/components/community/shell/server-rail.pending.dom.test.ts+++ b/src/web/src/components/community/shell/server-rail.pending.dom.test.ts@@ -572,13 +572,17 @@ describe("ServerRail one-in-flight structural guard", () => {it("has no Ungroup callback and keeps the same folder backdrop across toggle", async () => {const view = renderRail()expect(latestFolderProps().onUngroup).toBeUndefined()+ const surface = view.container.querySelector('[data-slot="community-rail-folder-surface"]')const background = view.container.querySelector('[data-slot="community-rail-folder-backdrop"]')- expect(background).toHaveClass("size-10", "rounded-[18px]", "group-hover/folder:rounded-xl")+ expect(surface).not.toHaveClass("py-1")+ expect(background).toHaveClass("top-0", "size-10", "rounded-[18px]", "group-hover/folder:rounded-xl")await act(async () => (latestFolderProps().onToggle as () => void)())+ expect(surface).toHaveClass("py-1")expect(view.container.querySelector('[data-slot="community-rail-folder-backdrop"]')).toBe(background)expect(background).toHaveClass("inset-x-1", "inset-y-0", "rounded-[12px]")expect(background).not.toHaveClass("size-10")await act(async () => (latestFolderProps().onToggle as () => void)())+ expect(surface).not.toHaveClass("py-1")view.rerender(railElement([{ ...folders[0]!, servers: [{ id: "a", name: "A", initial: "A" }] }]))expect(latestFolderProps().active).toBe(true)expect(background).toHaveClass("size-10", "rounded-xl")diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsxindex 90a36c6c4..5bdba5e91 100644--- a/src/web/src/components/community/shell/server-rail.tsx+++ b/src/web/src/components/community/shell/server-rail.tsx@@ -390,10 +390,10 @@ function ServerRailContent({return (<div key={`folder:${folderId}`} data-slot="community-rail-folder-surface" data-folder-id={folderId}data-rail-preview={operation || undefined}- className="group/folder relative w-full py-1">+ className={`group/folder relative w-full ${open ? "py-1" : ""}`}><RailFolderGapDropTarget dnd={dnd} folderId={folderId} operation="reorder-before" testId={tid.serverRailFolderBefore(folderId)} />{index < entries.length - 1 && <RailFolderGapDropTarget dnd={dnd} folderId={folderId} operation="reorder-after" testId={tid.serverRailFolderAfter(folderId)} />}- <div data-slot="community-rail-folder-backdrop" className={`pointer-events-none absolute bg-accent/50 dark:bg-accent ${open ? "inset-x-1 inset-y-0 rounded-[12px]" : `left-1/2 top-1 size-10 -translate-x-1/2 transition-[border-radius] duration-150 ${active ? "rounded-xl" : "rounded-[18px] group-hover/folder:rounded-xl"}`} ${operation === "combine" ? "ring-2 ring-primary" : ""}`} />+ <div data-slot="community-rail-folder-backdrop" className={`pointer-events-none absolute bg-accent/50 dark:bg-accent ${open ? "inset-x-1 inset-y-0 rounded-[12px]" : `left-1/2 top-0 size-10 -translate-x-1/2 transition-[border-radius] duration-150 ${active ? "rounded-xl" : "rounded-[18px] group-hover/folder:rounded-xl"}`} ${operation === "combine" ? "ring-2 ring-primary" : ""}`} />{operation && operation !== "combine" && <span data-slot="community-server-rail-insert" className={`pointer-events-none absolute inset-x-2 z-10 h-0.5 rounded-full bg-primary ${operation === "reorder-before" ? "-top-1 -translate-y-1/2" : "-bottom-1 translate-y-1/2"}`} />}<RailFolder folderId={folderId} name={folderNames.get(folderId) ?? "Group"} open={open}active={!open && active}diff --git a/src/web/src/hooks/use-native-keyboard.dom.test.tsx b/src/web/src/hooks/use-native-keyboard.dom.test.tsxnew file mode 100644index 000000000..3c573f200--- /dev/null+++ b/src/web/src/hooks/use-native-keyboard.dom.test.tsx@@ -0,0 +1,171 @@+import { afterEach, expect, it, vi } from "vitest"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import { useNativeKeyboard } from "./use-native-keyboard"++const original = Object.getOwnPropertyDescriptor(window, "webkit")+const originalTauri = Object.getOwnPropertyDescriptor(window, "__TAURI__")+afterEach(() => {+ if (original) Object.defineProperty(window, "webkit", original)+ else Reflect.deleteProperty(window, "webkit")+ if (originalTauri) Object.defineProperty(window, "__TAURI__", originalTauri)+ else Reflect.deleteProperty(window, "__TAURI__")+})++function snapshot(bottomInset = 0, viewportWidth = window.innerWidth) { return { bottomInset, viewportWidth } }++function install(postMessage: (command: "snapshot" | "dismiss") => Promise<unknown>) {+ Object.defineProperty(window, "__TAURI__", { configurable: true, value: {} })+ Object.defineProperty(window, "webkit", {+ configurable: true, value: { messageHandlers: { alookKeyboard: { postMessage } } },+ })+}++it("keeps ordinary Web and Android without a native keyboard capability unchanged", () => {+ Reflect.deleteProperty(window, "webkit")+ const view = renderHook(useNativeKeyboard)+ expect(view.result.current.visible).toBe(false)+ act(() => view.result.current.dismiss())+ act(() => window.dispatchEvent(new Event("alook:keyboard-change")))+ expect(view.result.current.visible).toBe(false)+})++it("does not enable native layout in a browser with a WebKit-shaped object", async () => {+ const post = vi.fn(async () => snapshot(300))+ install(post)+ Reflect.deleteProperty(window, "__TAURI__")+ const view = renderHook(useNativeKeyboard)+ await act(async () => {})+ expect(view.result.current.bottomInset).toBe(0)+ expect(view.result.current.visible).toBe(false)+ expect(post).not.toHaveBeenCalled()+})++it("reads current visibility and waits for native layout confirmation after explicit dismissal", async () => {+ let visible = true+ const post = vi.fn(async () => snapshot(visible ? 300 : 0))+ install(post)+ const view = renderHook(useNativeKeyboard)+ await waitFor(() => expect(view.result.current.visible).toBe(true))+ act(() => view.result.current.dismiss())+ expect(post).toHaveBeenLastCalledWith("dismiss")+ expect(view.result.current.visible).toBe(true)+ visible = false+ act(() => window.dispatchEvent(new Event("alook:keyboard-change")))+ await waitFor(() => expect(view.result.current.visible).toBe(false))+})++it("does not let an older native snapshot revive a later closed state", async () => {+ let release!: (value: ReturnType<typeof snapshot>) => void+ const post = vi.fn().mockImplementationOnce(() => new Promise<ReturnType<typeof snapshot>>(resolve => { release = resolve }))+ .mockResolvedValue(snapshot())+ install(post)+ const view = renderHook(useNativeKeyboard)+ act(() => window.dispatchEvent(new Event("alook:keyboard-change")))+ await act(async () => release(snapshot(300)))+ expect(view.result.current.visible).toBe(false)+ expect(post).toHaveBeenCalledTimes(2)+})++it("retires pending snapshots and callbacks when a component leaves", async () => {+ let release!: (value: ReturnType<typeof snapshot>) => void+ const oldPost = vi.fn(() => new Promise<ReturnType<typeof snapshot>>(resolve => { release = resolve }))+ install(oldPost)+ const old = renderHook(useNativeKeyboard)+ const dismiss = old.result.current.dismiss+ old.unmount()+ const nextPost = vi.fn(async () => snapshot())+ install(nextPost)+ const next = renderHook(useNativeKeyboard)+ await act(async () => release(snapshot(300)))+ act(() => dismiss())+ expect(oldPost).toHaveBeenCalledTimes(1)+ expect(nextPost).toHaveBeenCalledExactlyOnceWith("snapshot")+ expect(next.result.current.visible).toBe(false)+})++it("retires on pagehide and resumes only the preserved document on BFCache return", async () => {+ const post = vi.fn(async () => snapshot(300))+ install(post)+ const view = renderHook(useNativeKeyboard)+ await waitFor(() => expect(view.result.current.visible).toBe(true))+ act(() => window.dispatchEvent(new PageTransitionEvent("pagehide")))+ const calls = post.mock.calls.length+ act(() => {+ view.result.current.dismiss()+ window.dispatchEvent(new Event("alook:keyboard-change"))+ window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: false }))+ })+ expect(post).toHaveBeenCalledTimes(calls)+ expect(view.result.current.visible).toBe(false)+ act(() => window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true })))+ await waitFor(() => expect(view.result.current.visible).toBe(true))+})++it("keeps failed capability reads closed and accepts a later native state change", async () => {+ const post = vi.fn().mockRejectedValueOnce(new Error("unavailable")).mockResolvedValue(snapshot(300))+ install(post)+ const view = renderHook(useNativeKeyboard)+ await act(async () => {})+ expect(view.result.current.visible).toBe(false)+ act(() => window.dispatchEvent(new Event("alook:keyboard-change")))+ await waitFor(() => expect(view.result.current.visible).toBe(true))+})++it("reports a current dismissal failure while preserving the available retry control", async () => {+ const error = vi.spyOn(console, "error").mockImplementation(() => {})+ const post = vi.fn((command: "snapshot" | "dismiss") => command === "snapshot"+ ? Promise.resolve(snapshot(300)) : Promise.reject(new Error("rejected")))+ install(post)+ const view = renderHook(useNativeKeyboard)+ try {+ await waitFor(() => expect(view.result.current.visible).toBe(true))+ await act(async () => view.result.current.dismiss())+ expect(error).toHaveBeenCalledExactlyOnceWith("Native keyboard dismissal failed")+ expect(view.result.current.visible).toBe(true)+ } finally { error.mockRestore() }+})++it("does not report an old dismissal failure after the component retires", async () => {+ const error = vi.spyOn(console, "error").mockImplementation(() => {})+ let reject!: (error: Error) => void+ install(command => command === "snapshot" ? Promise.resolve(snapshot(300))+ : new Promise<ReturnType<typeof snapshot>>((_resolve, fail) => { reject = fail }))+ const view = renderHook(useNativeKeyboard)+ try {+ await waitFor(() => expect(view.result.current.visible).toBe(true))+ act(() => view.result.current.dismiss())+ view.unmount()+ await act(async () => reject(new Error("retired")))+ expect(error).not.toHaveBeenCalled()+ } finally { error.mockRestore() }+})+++it("converts native overlap points to the current CSS width and resamples on resize", async () => {+ const originalWidth = Object.getOwnPropertyDescriptor(window, "innerWidth")+ Object.defineProperty(window, "innerWidth", { configurable: true, value: 900 })+ const post = vi.fn(async () => snapshot(150, 450))+ install(post)+ const view = renderHook(useNativeKeyboard)+ try {+ await waitFor(() => expect(view.result.current.bottomInset).toBe(300))+ Object.defineProperty(window, "innerWidth", { configurable: true, value: 450 })+ act(() => window.dispatchEvent(new Event("resize")))+ await waitFor(() => expect(view.result.current.bottomInset).toBe(150))+ expect(post).toHaveBeenCalledTimes(2)+ } finally {+ view.unmount()+ if (originalWidth) Object.defineProperty(window, "innerWidth", originalWidth)+ }+})++it.each([true, false, { bottomInset: -10, viewportWidth: 390 }, { bottomInset: 100, viewportWidth: 0 },+ { bottomInset: Number.NaN, viewportWidth: 390 }, { bottomInset: 100, viewportWidth: Number.POSITIVE_INFINITY }])(+ "does not use malformed or retired-format native geometry: %j", async (value) => {+ install(async () => value)+ const view = renderHook(useNativeKeyboard)+ await act(async () => {})+ expect(view.result.current.bottomInset).toBe(0)+ expect(view.result.current.visible).toBe(false)+ },+)diff --git a/src/web/src/hooks/use-native-keyboard.ts b/src/web/src/hooks/use-native-keyboard.tsnew file mode 100644index 000000000..3e95df764--- /dev/null+++ b/src/web/src/hooks/use-native-keyboard.ts@@ -0,0 +1,70 @@+"use client"++import { useCallback, useEffect, useRef, useState } from "react"+import { isTauri } from "@alook/shared"++type KeyboardSnapshot = { bottomInset: number; viewportWidth: number }+type KeyboardBridge = {+ postMessage: (command: "snapshot" | "dismiss") => Promise<KeyboardSnapshot>+}+type KeyboardWindow = Window & {+ webkit?: { messageHandlers?: { alookKeyboard?: KeyboardBridge } }+}++function keyboardBridge() {+ if (!isTauri()) return+ return (window as KeyboardWindow).webkit?.messageHandlers?.alookKeyboard+}++export function useNativeKeyboard() {+ const [bottomInset, setBottomInset] = useState(0)+ const current = useRef<{ bridge: KeyboardBridge; active: boolean } | null>(null)+ useEffect(() => {+ const bridge = keyboardBridge()+ if (!bridge) return+ const owner = { bridge, active: true }+ current.current = owner+ let revision = 0+ const sync = async () => {+ if (!owner.active) return+ const request = ++revision+ try {+ const next = await bridge.postMessage("snapshot")+ if (owner.active && request === revision) {+ const valid = next && Number.isFinite(next.bottomInset) && next.bottomInset >= 0+ && Number.isFinite(next.viewportWidth) && next.viewportWidth > 0+ setBottomInset(valid ? next.bottomInset * window.innerWidth / next.viewportWidth : 0)+ }+ } catch {+ if (owner.active && request === revision) setBottomInset(0)+ }+ }+ const hide = () => { owner.active = false; revision++; setBottomInset(0) }+ const show = (event: PageTransitionEvent) => {+ if (!event.persisted) return+ owner.active = true+ void sync()+ }+ window.addEventListener("alook:keyboard-change", sync)+ window.addEventListener("resize", sync)+ window.addEventListener("pagehide", hide)+ window.addEventListener("pageshow", show)+ void sync()+ return () => {+ owner.active = false+ if (current.current === owner) current.current = null+ revision+++ window.removeEventListener("alook:keyboard-change", sync)+ window.removeEventListener("resize", sync)+ window.removeEventListener("pagehide", hide)+ window.removeEventListener("pageshow", show)+ }+ }, [])+ const dismiss = useCallback(() => {+ const owner = current.current+ if (owner?.active) void owner.bridge.postMessage("dismiss").catch(() => {+ if (owner.active) console.error("Native keyboard dismissal failed")+ })+ }, [])+ return { visible: bottomInset > 0, bottomInset, dismiss }+}diff --git a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.tsindex bbd7de942..29f3644da 100644--- a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts+++ b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts@@ -79,7 +79,7 @@ async function postActionGeometry(card: Locator, postId: string) {return {card: readRect(element),title: readRect(element.querySelector(`[data-testid="${titleId}"]`)),- preview: readRect(element.querySelector(":scope > p")),+ preview: readRect(element.querySelector('[data-slot="community-forum-post-preview"]')),row: readRect(row),virtualHeight: readRect(row?.parentElement ?? null).height,}